diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 60fa57bfb8..f3148c46b2 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -265,7 +265,7 @@ public class AwsQueryController { private static final Set CLOUDFORMATION_ACTIONS = Set.of( "CreateStack", "DeleteStack", "UpdateStack", "DescribeStacks", - "ListStacks", "GetTemplate", "ValidateTemplate", + "ListStacks", "ListExports", "GetTemplate", "ValidateTemplate", "CreateChangeSet", "DeleteChangeSet", "DescribeChangeSet", "ExecuteChangeSet", "ListChangeSets", "DescribeStackEvents", "DescribeStackResources", "ListStackResources", "DescribeStackResource", "SetStackPolicy", "GetStackPolicy", "ListStackSets", "DescribeStackSet", "CreateStackSet" diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java index 20659c0a7f..bbfeddb58e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java @@ -55,6 +55,7 @@ public class CloudFormationQueryHandler { case "GetTemplate" -> getTemplate(params, region); case "ValidateTemplate" -> validateTemplate(params); case "ListStacks" -> listStacks(params, region); + case "ListExports" -> listExports(params, region); case "SetStackPolicy" -> Response.ok(emptyResult("SetStackPolicyResponse")).build(); case "GetStackPolicy" -> Response.ok(emptyResult("GetStackPolicyResponse")).build(); case "DescribeStackResource" -> describeStackResource(params, region); @@ -428,6 +429,27 @@ public class CloudFormationQueryHandler { return Response.ok(xml.build()).type("text/xml").build(); } + // ── ListExports ───────────────────────────────────────────────────────── + + private Response listExports(MultivaluedMap params, String region) { + var exportEntries = cfnService.listExports(region); + XmlBuilder xml = new XmlBuilder() + .start("ListExportsResponse", CF_NS) + .start("ListExportsResult") + .start("Exports"); + for (var entry : exportEntries.values()) { + xml.start("member") + .elem("ExportingStackId", entry.exportingStackId()) + .elem("Name", entry.name()) + .elem("Value", entry.value()) + .end("member"); + } + xml.end("Exports").end("ListExportsResult") + .raw(AwsQueryResponse.responseMetadata()) + .end("ListExportsResponse"); + return Response.ok(xml.build()).type("text/xml").build(); + } + // ── Helpers ─────────────────────────────────────────────────────────────── private String stackToXml(Stack s) { @@ -448,11 +470,16 @@ public class CloudFormationQueryHandler { } xml.end("Capabilities"); xml.start("Outputs"); - s.getOutputs().forEach((k, v) -> - xml.start("member") - .elem("OutputKey", k) - .elem("OutputValue", v) - .end("member")); + s.getOutputs().forEach((k, v) -> { + xml.start("member") + .elem("OutputKey", k) + .elem("OutputValue", v); + String exportName = s.getOutputExportNames().get(k); + if (exportName != null) { + xml.elem("ExportName", exportName); + } + xml.end("member"); + }); xml.end("Outputs"); xml.start("Tags"); s.getTags().forEach((k, v) -> diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index e48dbfee09..d7f82e666b 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 @@ -32,6 +32,8 @@ public class CloudFormationService { private static final Logger LOG = Logger.getLogger(CloudFormationService.class); private final ConcurrentHashMap stacks = new ConcurrentHashMap<>(); + // Global exports registry: region:exportName -> exportValue + private final ConcurrentHashMap exports = new ConcurrentHashMap<>(); private final ExecutorService executor = Executors.newCachedThreadPool(); private final CloudFormationResourceProvisioner provisioner; @@ -191,8 +193,63 @@ public class CloudFormationService { .toList(); } + // ── ListExports ───────────────────────────────────────────────────────── + + public Map listExports(String region) { + Map result = new LinkedHashMap<>(); + for (Stack stack : stacks.values()) { + if (!region.equals(stack.getRegion())) { + continue; + } + for (var entry : stack.getExports().entrySet()) { + result.put(entry.getKey(), new ExportEntry(entry.getKey(), entry.getValue(), stack.getStackId())); + } + } + return result; + } + + public record ExportEntry(String name, String value, String exportingStackId) {} + // ── Private ─────────────────────────────────────────────────────────────── + private void removeStackExports(Stack stack, String region) { + for (String exportName : stack.getExports().keySet()) { + exports.remove(exportKey(region, exportName)); + } + } + + private String exportKey(String region, String exportName) { + return region + ":" + exportName; + } + + private void validateExportNameAvailable(String region, String exportName, + Map oldExports, + Map newExports) { + if (newExports.containsKey(exportName)) { + throw new AwsException("ValidationError", + "Export with name " + exportName + " is already defined by this stack", 400); + } + if (!oldExports.containsKey(exportName) && exports.containsKey(exportKey(region, exportName))) { + throw new AwsException("ValidationError", + "Export with name " + exportName + " is already exported by another stack", 400); + } + } + + private Map resolveDefaultParameters(JsonNode template, Map callerParams) { + Map resolved = new HashMap<>(callerParams != null ? callerParams : Map.of()); + JsonNode paramDefs = template.path("Parameters"); + if (paramDefs.isObject()) { + paramDefs.fields().forEachRemaining(e -> { + String paramName = e.getKey(); + JsonNode paramDef = e.getValue(); + if (!resolved.containsKey(paramName) && paramDef.has("Default")) { + resolved.put(paramName, paramDef.path("Default").asText()); + } + }); + } + return resolved; + } + private void executeTemplate(Stack stack, String templateBody, Map params, boolean isCreate, String region) { try { @@ -232,7 +289,8 @@ public class CloudFormationService { CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine( config.defaultAccountId(), region, stack.getStackName(), - stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper); + stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper, + name -> exports.get(exportKey(region, name))); StackResource resource = stack.getResources().get(logicalId); if (resource == null) { @@ -255,21 +313,48 @@ public class CloudFormationService { } } - // Resolve outputs - stack.getOutputs().clear(); CloudFormationTemplateEngine finalEngine = new CloudFormationTemplateEngine( config.defaultAccountId(), region, stack.getStackName(), - stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper); + stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper, + name -> exports.get(exportKey(region, name))); + // Resolve outputs before mutating stack/global export state, so failed updates do not + // leave stale or partially registered exports behind. + Map oldExports = new LinkedHashMap<>(stack.getExports()); + Map newOutputs = new LinkedHashMap<>(); + Map newExports = new LinkedHashMap<>(); + Map 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")); - stack.getOutputs().put(e.getKey(), 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); + } }); } + removeStackExports(stack, region); + stack.getOutputs().clear(); + stack.getOutputs().putAll(newOutputs); + stack.getExports().clear(); + stack.getExports().putAll(newExports); + stack.getOutputExportNames().clear(); + stack.getOutputExportNames().putAll(newOutputExportNames); + newExports.forEach((exportName, value) -> { + exports.put(exportKey(region, exportName), value); + LOG.infov("Registered export {0} = {1} from stack {2}", + exportName, value, stack.getStackName()); + }); + String completeStatus = isCreate ? "CREATE_COMPLETE" : "UPDATE_COMPLETE"; stack.setStatus(completeStatus); stack.setLastUpdatedTime(Instant.now()); @@ -306,6 +391,7 @@ public class CloudFormationService { stack.setStatus("DELETE_COMPLETE"); addEvent(stack, stack.getStackName(), stack.getStackId(), "AWS::CloudFormation::Stack", "DELETE_COMPLETE", null); + removeStackExports(stack, region); stacks.remove(key(stack.getStackName(), region)); LOG.infov("Stack {0} deleted", stack.getStackName()); @@ -316,21 +402,6 @@ public class CloudFormationService { } } - private Map resolveDefaultParameters(JsonNode template, Map callerParams) { - Map resolved = new HashMap<>(callerParams != null ? callerParams : Map.of()); - JsonNode paramDefs = template.path("Parameters"); - if (paramDefs.isObject()) { - paramDefs.fields().forEachRemaining(e -> { - String paramName = e.getKey(); - JsonNode paramDef = e.getValue(); - if (!resolved.containsKey(paramName) && paramDef.has("Default")) { - resolved.put(paramName, paramDef.path("Default").asText()); - } - }); - } - return resolved; - } - private Map resolveConditions(JsonNode template, Map params, Stack stack, String region) { Map conditions = new HashMap<>(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java index 1afaf447be..ff10440788 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 @@ -3,12 +3,14 @@ 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.jboss.logging.Logger; import java.util.Base64; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.function.Function; /** * Resolves CloudFormation intrinsic functions and pseudo-parameters in template nodes. @@ -29,6 +31,7 @@ public class CloudFormationTemplateEngine { private final Map conditions; private final Map mappings; private final ObjectMapper objectMapper; + private final Function importValueResolver; CloudFormationTemplateEngine(String accountId, String region, String stackName, String stackId, Map parameters, @@ -36,7 +39,8 @@ public class CloudFormationTemplateEngine { Map> resourceAttributes, Map conditions, Map mappings, - ObjectMapper objectMapper) { + ObjectMapper objectMapper, + Function importValueResolver) { this.accountId = accountId; this.region = region; this.stackName = stackName; @@ -47,6 +51,7 @@ public class CloudFormationTemplateEngine { this.conditions = conditions; this.mappings = mappings; this.objectMapper = objectMapper; + this.importValueResolver = importValueResolver; } public String resolve(JsonNode node) { @@ -88,7 +93,7 @@ public class CloudFormationTemplateEngine { return resolveGetAtt(node.get("Fn::GetAtt")); } if (node.has("Fn::ImportValue")) { - return resolve(node.get("Fn::ImportValue")); + return resolveImportValue(node.get("Fn::ImportValue")); } if (node.has("Fn::FindInMap")) { return resolveFindInMap(node.get("Fn::FindInMap")); @@ -271,4 +276,16 @@ public class CloudFormationTemplateEngine { } return ""; } + + private String resolveImportValue(JsonNode node) { + String exportName = resolve(node); + if (importValueResolver != null) { + String value = importValueResolver.apply(exportName); + if (value != null) { + return value; + } + } + LOG.warnv("Unresolved Fn::ImportValue: {0}", exportName); + throw new AwsException("ValidationError", "No export named " + exportName + " found", 400); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java index 6a4c356728..4c20d2e5fa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java @@ -15,6 +15,9 @@ public class Stack { private List capabilities = new ArrayList<>(); private Map parameters = new LinkedHashMap<>(); private Map outputs = new LinkedHashMap<>(); + private Map exports = new LinkedHashMap<>(); + // Maps output key to its export name (when Export.Name is defined on an output) + private Map outputExportNames = new LinkedHashMap<>(); private Map resources = new LinkedHashMap<>(); private List events = new ArrayList<>(); private Map changeSets = new LinkedHashMap<>(); @@ -42,6 +45,10 @@ public class Stack { public void setParameters(Map parameters) { this.parameters = parameters; } public Map getOutputs() { return outputs; } public void setOutputs(Map outputs) { this.outputs = outputs; } + public Map getExports() { return exports; } + public void setExports(Map exports) { this.exports = exports; } + public Map getOutputExportNames() { return outputExportNames; } + public void setOutputExportNames(Map outputExportNames) { this.outputExportNames = outputExportNames; } public Map getResources() { return resources; } public void setResources(Map resources) { this.resources = resources; } public List getEvents() { return events; } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java index eb5decea6e..4fa1a2482c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java @@ -2512,4 +2512,410 @@ class CloudFormationIntegrationTest { .statusCode(404); } + @Test + void crossStackReference_fnImportValue() { + // Stack A exports a bucket name + String templateA = """ + { + "Resources": { + "SharedBucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "cross-stack-shared-bucket" + } + } + }, + "Outputs": { + "BucketNameOutput": { + "Value": { "Ref": "SharedBucket" }, + "Export": { + "Name": "SharedBucketName" + } + } + } + } + """; + + // Create Stack A + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "exporter-stack") + .formParam("TemplateBody", templateA) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + // Verify Stack A is complete and has export in output + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "exporter-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .body(containsString("BucketNameOutput")) + .body(containsString("cross-stack-shared-bucket")) + .body(containsString("SharedBucketName")); + + // Verify ListExports returns the export + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListExports") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("SharedBucketName")) + .body(containsString("cross-stack-shared-bucket")); + + // Stack B imports the bucket name from Stack A + String templateB = """ + { + "Resources": { + "ImporterQueue": { + "Type": "AWS::SQS::Queue", + "Properties": { + "QueueName": { + "Fn::Join": ["-", [ + { "Fn::ImportValue": "SharedBucketName" }, + "queue" + ]] + } + } + } + }, + "Outputs": { + "QueueNameOutput": { + "Value": { "Ref": "ImporterQueue" } + } + } + } + """; + + // Create Stack B (imports from Stack A) + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "importer-stack") + .formParam("TemplateBody", templateB) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + // Verify Stack B is complete and resolved the import correctly + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "importer-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .body(containsString("cross-stack-shared-bucket-queue")); + + // Verify the SQS queue was actually created with the resolved name + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetQueueUrl") + .formParam("QueueName", "cross-stack-shared-bucket-queue") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("cross-stack-shared-bucket-queue")); + } + + @Test + void crossStackReference_fnImportValueWithSub() { + // Stack that exports with a Fn::Sub-based export name + String templateExporter = """ + { + "Resources": { + "MyTable": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "TableName": "cross-stack-table", + "AttributeDefinitions": [ + { "AttributeName": "pk", "AttributeType": "S" } + ], + "KeySchema": [ + { "AttributeName": "pk", "KeyType": "HASH" } + ], + "BillingMode": "PAY_PER_REQUEST" + } + } + }, + "Outputs": { + "TableNameOut": { + "Value": { "Ref": "MyTable" }, + "Export": { + "Name": { "Fn::Sub": "${AWS::StackName}-TableName" } + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "sub-exporter-stack") + .formParam("TemplateBody", templateExporter) + .when() + .post("/") + .then() + .statusCode(200); + + // Verify the dynamic export name resolved correctly + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListExports") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("sub-exporter-stack-TableName")) + .body(containsString("cross-stack-table")); + + // Stack that imports using the dynamic export name + String templateImporter = """ + { + "Resources": { + "ConsumerQueue": { + "Type": "AWS::SQS::Queue", + "Properties": { + "QueueName": { + "Fn::Join": ["-", [ + { "Fn::ImportValue": "sub-exporter-stack-TableName" }, + "consumer" + ]] + } + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "sub-importer-stack") + .formParam("TemplateBody", templateImporter) + .when() + .post("/") + .then() + .statusCode(200); + + // Verify the queue was created with the correctly resolved imported value + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "sub-importer-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetQueueUrl") + .formParam("QueueName", "cross-stack-table-consumer") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("cross-stack-table-consumer")); + } + + @Test + void crossStackReference_updateRemovesOldExportName() { + String oldTemplate = """ + { + "Outputs": { + "SharedValue": { + "Value": "old-value", + "Export": { "Name": "OldExportName" } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "export-rename-stack") + .formParam("TemplateBody", oldTemplate) + .when() + .post("/") + .then() + .statusCode(200); + + String newTemplate = """ + { + "Outputs": { + "SharedValue": { + "Value": "new-value", + "Export": { "Name": "NewExportName" } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStack") + .formParam("StackName", "export-rename-stack") + .formParam("TemplateBody", newTemplate) + .when() + .post("/") + .then() + .statusCode(200); + + String exportsXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListExports") + .when() + .post("/") + .then() + .statusCode(200) + .extract().body().asString(); + + assertThat(exportsXml, containsString("NewExportName")); + assertThat(exportsXml, containsString("new-value")); + assertThat(exportsXml, not(containsString("OldExportName"))); + } + + @Test + void crossStackReference_duplicateExportNameFailsSecondStack() { + String firstTemplate = """ + { + "Outputs": { + "SharedValue": { + "Value": "first-value", + "Export": { "Name": "DuplicateExportName" } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "duplicate-export-stack-a") + .formParam("TemplateBody", firstTemplate) + .when() + .post("/") + .then() + .statusCode(200); + + String secondTemplate = """ + { + "Outputs": { + "SharedValue": { + "Value": "second-value", + "Export": { "Name": "DuplicateExportName" } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "duplicate-export-stack-b") + .formParam("TemplateBody", secondTemplate) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "duplicate-export-stack-b") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_FAILED")) + .body(containsString("DuplicateExportName")); + + String exportsXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListExports") + .when() + .post("/") + .then() + .statusCode(200) + .extract().body().asString(); + + assertThat(exportsXml, containsString("DuplicateExportName")); + assertThat(exportsXml, containsString("first-value")); + assertThat(exportsXml, not(containsString("second-value"))); + } + + @Test + void crossStackReference_missingImportValueFailsResource() { + String template = """ + { + "Resources": { + "ImporterQueue": { + "Type": "AWS::SQS::Queue", + "Properties": { + "QueueName": { "Fn::ImportValue": "MissingExportName" } + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "missing-import-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", "missing-import-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_FAILED")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackEvents") + .formParam("StackName", "missing-import-stack") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("MissingExportName")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetQueueUrl") + .formParam("QueueName", "MissingExportName") + .when() + .post("/") + .then() + .statusCode(400); + } + }