From f1204d9d4ba1479556fddef0858ef623e53d8a56 Mon Sep 17 00:00:00 2001 From: Vishal Goyal Date: Sat, 20 Jun 2026 17:06:44 +0200 Subject: [PATCH] feat(cloudformation): generate implicit API Gateway from SAM Api events (#1438) * feat(cloudformation): generate implicit API Gateway from SAM Api events Synthesize an implicit AWS::ApiGateway RestApi (RestApi / Resource / Method / AWS_PROXY Integration / Deployment / Stage) from SAM function Api events, matching SAM/CloudFormation behavior so a template that relies on the implicit API can be deployed and served. Routes are deduped by (path, method); a route whose RestApiId is explicitly set (non-null) is left untouched; the generated RestApi uses a collision-safe logical id. * fix(cloudformation): harden implicit API route generation - skip Api routes whose Path is a non-literal intrinsic (Ref/Fn::Sub) instead of registering them as the API root - default Method to ANY when given as a non-literal value - make the Deployment and Stage logical ids collision-safe via uniqueId --- .../cloudformation/SamTransformProcessor.java | 217 ++++++++++++++++++ .../SamTransformProcessorTest.java | 130 +++++++++++ 2 files changed, 347 insertions(+) diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java index 0661c8df41..99f2d3a2f5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java @@ -64,6 +64,9 @@ class SamTransformProcessor { } }); + // Collect implicit-API routes from function Api events before the functions are expanded. + List apiRoutes = collectApiRoutes(samLogicalIds, resources); + for (String logicalId : samLogicalIds) { JsonNode resDef = resources.get(logicalId); String type = resDef.path("Type").asText(); @@ -80,9 +83,223 @@ class SamTransformProcessor { } } + // Synthesize the implicit REST API (RestApi + resources + methods + AWS_PROXY integrations + + // deployment + stage + lambda permissions) for functions that declare Api events without an + // explicit RestApiId — matching SAM's implicit-API behavior so the deployed service is reachable. + if (!apiRoutes.isEmpty()) { + generateImplicitApi(apiRoutes, globals(template), expandedResources); + } + return expanded; } + private JsonNode globals(JsonNode template) { + return template.path("Globals"); + } + + private record ApiRoute(String functionLogicalId, String path, String httpMethod) {} + + private List collectApiRoutes(List samLogicalIds, JsonNode resources) { + List routes = new ArrayList<>(); + for (String logicalId : samLogicalIds) { + JsonNode resDef = resources.get(logicalId); + if (!"AWS::Serverless::Function".equals(resDef.path("Type").asText())) { + continue; + } + JsonNode events = resDef.path("Properties").path("Events"); + if (!events.isObject()) { + continue; + } + Iterator> it = events.fields(); + while (it.hasNext()) { + JsonNode ev = it.next().getValue(); + if (!"Api".equals(ev.path("Type").asText())) { + continue; + } + JsonNode p = ev.path("Properties"); + JsonNode restApiId = p.path("RestApiId"); + if (!restApiId.isMissingNode() && !restApiId.isNull()) { + continue; // bound to an explicit API — not an implicit-API route (null == implicit) + } + JsonNode pathNode = p.path("Path"); + if (!pathNode.isTextual()) { + continue; // implicit routing needs a literal path; skip intrinsics (Ref/Fn::Sub) + } + JsonNode methodNode = p.path("Method"); + String method = methodNode.isTextual() ? methodNode.asText() : "ANY"; + routes.add(new ApiRoute(logicalId, pathNode.asText(), method)); + } + } + return routes; + } + + private void generateImplicitApi(List routes, JsonNode globals, ObjectNode resources) { + // Collision-safe: reuse "ServerlessRestApi" when free, otherwise a suffixed id, so an existing + // resource with that logical id is never silently overwritten. + final String apiId = uniqueId("ServerlessRestApi", resources); + + ObjectNode api = objectMapper.createObjectNode(); + api.put("Type", "AWS::ApiGateway::RestApi"); + ObjectNode apiProps = objectMapper.createObjectNode(); + JsonNode globalName = globals.path("Api").path("Name"); + if (globalName.isMissingNode() || globalName.isNull()) { + apiProps.put("Name", apiId); + } else { + apiProps.set("Name", globalName.deepCopy()); + } + api.set("Properties", apiProps); + resources.set(apiId, api); + + Map pathToResource = new java.util.LinkedHashMap<>(); + List methodIds = new ArrayList<>(); + java.util.Set permissionFns = new java.util.LinkedHashSet<>(); + java.util.Set seenRoutes = new java.util.LinkedHashSet<>(); + + for (ApiRoute r : routes) { + String method = r.httpMethod().toUpperCase(); + if (!seenRoutes.add(r.path() + " " + method)) { + continue; // API Gateway allows one method per verb per resource — skip duplicate (path, method) + } + String resourceId = ensureResourcePath(apiId, r.path(), pathToResource, resources); + + String methodLogicalId = uniqueId(apiId + "Method" + sanitize(r.path()) + capitalize(method.toLowerCase()), resources); + ObjectNode m = objectMapper.createObjectNode(); + m.put("Type", "AWS::ApiGateway::Method"); + ObjectNode mp = objectMapper.createObjectNode(); + mp.set("RestApiId", ref(apiId)); + mp.set("ResourceId", resourceId == null ? getAtt(apiId, "RootResourceId") : ref(resourceId)); + mp.put("HttpMethod", method); + mp.put("AuthorizationType", "NONE"); + ObjectNode integ = objectMapper.createObjectNode(); + integ.put("Type", "AWS_PROXY"); + integ.put("IntegrationHttpMethod", "POST"); + integ.set("Uri", lambdaInvokeUri(r.functionLogicalId())); + mp.set("Integration", integ); + m.set("Properties", mp); + resources.set(methodLogicalId, m); + methodIds.add(methodLogicalId); + permissionFns.add(r.functionLogicalId()); + } + + for (String fn : permissionFns) { + ObjectNode perm = objectMapper.createObjectNode(); + perm.put("Type", "AWS::Lambda::Permission"); + ObjectNode pp = objectMapper.createObjectNode(); + pp.set("FunctionName", ref(fn)); + pp.put("Action", "lambda:InvokeFunction"); + pp.put("Principal", "apigateway.amazonaws.com"); + perm.set("Properties", pp); + resources.set(uniqueId(fn + "ApiPermission", resources), perm); + } + + String deploymentId = uniqueId(apiId + "Deployment", resources); + ObjectNode dep = objectMapper.createObjectNode(); + dep.put("Type", "AWS::ApiGateway::Deployment"); + ObjectNode dp = objectMapper.createObjectNode(); + dp.set("RestApiId", ref(apiId)); + dep.set("Properties", dp); + ArrayNode dependsOn = objectMapper.createArrayNode(); + methodIds.forEach(dependsOn::add); + dep.set("DependsOn", dependsOn); + resources.set(deploymentId, dep); + + ObjectNode stage = objectMapper.createObjectNode(); + stage.put("Type", "AWS::ApiGateway::Stage"); + ObjectNode sp = objectMapper.createObjectNode(); + sp.set("RestApiId", ref(apiId)); + sp.set("DeploymentId", ref(deploymentId)); + sp.put("StageName", "Prod"); + stage.set("Properties", sp); + resources.set(uniqueId(apiId + "ProdStage", resources), stage); + } + + /** Builds the API Gateway resource chain for a path; returns the leaf resource logical id (null = root). */ + private String ensureResourcePath(String apiId, String path, Map pathToResource, ObjectNode resources) { + String trimmed = path.startsWith("/") ? path.substring(1) : path; + if (trimmed.isEmpty()) { + return null; + } + String cumulative = ""; + String parentResourceId = null; + String leaf = null; + for (String segment : trimmed.split("/")) { + if (segment.isEmpty()) { + continue; + } + cumulative = cumulative + "/" + segment; + String resId = pathToResource.get(cumulative); + if (resId == null) { + resId = uniqueId(apiId + "Resource" + sanitize(cumulative), resources); + ObjectNode res = objectMapper.createObjectNode(); + res.put("Type", "AWS::ApiGateway::Resource"); + ObjectNode rp = objectMapper.createObjectNode(); + rp.set("RestApiId", ref(apiId)); + rp.set("ParentId", parentResourceId == null ? getAtt(apiId, "RootResourceId") : ref(parentResourceId)); + rp.put("PathPart", segment); + res.set("Properties", rp); + resources.set(resId, res); + pathToResource.put(cumulative, resId); + } + parentResourceId = resId; + leaf = resId; + } + return leaf; + } + + private ObjectNode ref(String logicalId) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("Ref", logicalId); + return n; + } + + private ObjectNode getAtt(String logicalId, String attribute) { + ObjectNode n = objectMapper.createObjectNode(); + ArrayNode a = objectMapper.createArrayNode(); + a.add(logicalId); + a.add(attribute); + n.set("Fn::GetAtt", a); + return n; + } + + /** Two-arg Fn::Sub producing the AWS_PROXY integration URI for a function (the form floci resolves). */ + private ObjectNode lambdaInvokeUri(String functionLogicalId) { + ObjectNode sub = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + arr.add("arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${FnArn}/invocations"); + ObjectNode vars = objectMapper.createObjectNode(); + vars.set("FnArn", getAtt(functionLogicalId, "Arn")); + arr.add(vars); + sub.set("Fn::Sub", arr); + return sub; + } + + private String sanitize(String s) { + StringBuilder b = new StringBuilder(); + boolean upper = true; + for (char c : s.toCharArray()) { + if (Character.isLetterOrDigit(c)) { + b.append(upper ? Character.toUpperCase(c) : c); + upper = false; + } else { + upper = true; + } + } + return b.length() == 0 ? "Root" : b.toString(); + } + + private String capitalize(String s) { + return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1); + } + + private String uniqueId(String base, ObjectNode resources) { + String id = base; + int i = 2; + while (resources.has(id)) { + id = base + i++; + } + return id; + } + private void expandServerlessFunction(String logicalId, JsonNode properties, ObjectNode resources) { resources.remove(logicalId); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java index f82816ef43..eaa081cf50 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java @@ -5,6 +5,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.Iterator; +import java.util.Map; + import static org.junit.jupiter.api.Assertions.*; /** @@ -395,4 +398,131 @@ class SamTransformProcessorTest { esmProps.path("EventSourceArn").asText()); assertEquals(10, esmProps.path("BatchSize").asInt()); } + + @Test + void expandSamTemplate_generatesImplicitApiFromApiEvents() throws Exception { + // Functions with Api events and no explicit RestApiId must produce a full implicit REST API. + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Globals": { "Api": { "Name": "MyServiceApi" } }, + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "bootstrap", + "Runtime": "provided.al2023", + "InlineCode": "x", + "Events": { + "Docs": { "Type": "Api", "Properties": { "Path": "/docs", "Method": "GET" } }, + "Proxy": { "Type": "Api", "Properties": { "Path": "/{proxy+}", "Method": "ANY" } } + } + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + + // RestApi created, with the name from Globals.Api + assertEquals("AWS::ApiGateway::RestApi", resources.path("ServerlessRestApi").path("Type").asText()); + assertEquals("MyServiceApi", resources.path("ServerlessRestApi").path("Properties").path("Name").asText()); + + // Deployment + Prod stage + assertEquals("AWS::ApiGateway::Deployment", resources.path("ServerlessRestApiDeployment").path("Type").asText()); + assertEquals("Prod", resources.path("ServerlessRestApiProdStage").path("Properties").path("StageName").asText()); + + // A /docs resource exists, and there is a Method with an AWS_PROXY integration + a Lambda permission + boolean hasDocsResource = false; + boolean hasProxyMethod = false; + boolean hasPermission = false; + Iterator> it = resources.fields(); + while (it.hasNext()) { + JsonNode n = it.next().getValue(); + String type = n.path("Type").asText(); + if ("AWS::ApiGateway::Resource".equals(type) && "docs".equals(n.path("Properties").path("PathPart").asText())) { + hasDocsResource = true; + } + if ("AWS::ApiGateway::Method".equals(type) + && "AWS_PROXY".equals(n.path("Properties").path("Integration").path("Type").asText())) { + hasProxyMethod = true; + } + if ("AWS::Lambda::Permission".equals(type) + && "apigateway.amazonaws.com".equals(n.path("Properties").path("Principal").asText())) { + hasPermission = true; + } + } + assertTrue(hasDocsResource, "expected an API Gateway Resource for /docs"); + assertTrue(hasProxyMethod, "expected an API Gateway Method with AWS_PROXY integration"); + assertTrue(hasPermission, "expected a Lambda permission for apigateway.amazonaws.com"); + } + + @Test + void expandSamTemplate_dedupesDuplicateApiRoutes() throws Exception { + // Two events resolving to the same (path, method) must collapse to a single API Gateway Method. + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "bootstrap", + "Runtime": "provided.al2023", + "InlineCode": "x", + "Events": { + "A": { "Type": "Api", "Properties": { "Path": "/docs", "Method": "GET" } }, + "B": { "Type": "Api", "Properties": { "Path": "/docs", "Method": "GET" } } + } + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + int methods = 0; + Iterator> it = resources.fields(); + while (it.hasNext()) { + if ("AWS::ApiGateway::Method".equals(it.next().getValue().path("Type").asText())) { + methods++; + } + } + assertEquals(1, methods, "duplicate (path, method) routes must collapse to a single Method"); + } + + @Test + void expandSamTemplate_skipsApiRouteWithNonLiteralPath() throws Exception { + // A Path given as an intrinsic (Ref/Fn::Sub) can't be turned into a literal API Gateway + // resource path, so the route must be skipped rather than registered as the API root. + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "bootstrap", + "Runtime": "provided.al2023", + "InlineCode": "x", + "Events": { + "A": { "Type": "Api", "Properties": { "Path": { "Ref": "SomePath" }, "Method": "GET" } } + } + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + int methods = 0; + Iterator> it = resources.fields(); + while (it.hasNext()) { + if ("AWS::ApiGateway::Method".equals(it.next().getValue().path("Type").asText())) { + methods++; + } + } + assertEquals(0, methods, "a route with a non-literal Path must not be registered"); + } }