mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(cloudformation): expand AWS::Serverless::HttpApi via SAM transform (#2146)
* fix(cloudformation): expand AWS::Serverless::HttpApi via SAM transform
SamTransformProcessor's switch on SAM resource types only handled
AWS::Serverless::Function, AWS::Serverless::SimpleTable, and
AWS::Serverless::Api (REST, v1) — AWS::Serverless::HttpApi fell into the
default branch and was silently dropped from the expanded template, along
with any Auth.Authorizers/DefaultAuthorizer config and any HttpApi-typed
Events on a sibling Function. A stack using AWS::Serverless::HttpApi
reported CREATE_COMPLETE with a synthesized physical id for the resource,
but no AWS::ApiGatewayV2::Api ever existed.
Adds expandServerlessHttpApi, mirroring the existing explicit-API pattern
(expandServerlessApi for REST v1) rather than the implicit-API path
(generateImplicitApi/collectApiRoutes), scoped to the explicit
AWS::Serverless::HttpApi + Function Events ApiId: {Ref: ...} form. For
each explicit HttpApi resource this synthesizes a real
AWS::ApiGatewayV2::Api, a $default auto-deploy Stage, one
AWS::ApiGatewayV2::Authorizer per Auth.Authorizers entry (mapping SAM's
mixed-case JwtConfiguration.issuer/audience onto the PascalCase
Issuer/Audience the raw CFN resource expects), and — for every Function
event bound to that API — an AWS_PROXY Integration, a Route wired to
Auth.DefaultAuthorizer when present, and a Lambda::Permission.
Implicit HttpApi (a Function's HttpApi event with no ApiId, where SAM
auto-creates the API) is intentionally out of scope here, matching how
this file already keeps generateImplicitApi/collectApiRoutes as a separate
concern from expandServerlessApi's explicit-resource handling.
Full JWT-authorizer enforcement additionally requires #1758
(AWS::ApiGatewayV2::Authorizer CloudFormation provisioning) — without it,
the Authorizer resource this transform synthesizes is itself dropped by
the provisioner's default branch, the same way it is for a raw (non-SAM)
template. Verified locally with both fixes applied together; #1758 is a
separate PR since the bugs are independent (raw-CFN provisioning vs. SAM
transform expansion) even though a SAM+JWT-authorizer template needs both.
Fixes #1759.
* fix(cloudformation): honor per-event Auth: {Authorizer: NONE} on HttpApi events
expandServerlessHttpApi applied the HttpApi's Auth.DefaultAuthorizer to every
route uniformly, ignoring SAM's documented per-event override
(Events.<Name>.Properties.Auth.Authorizer: NONE) that lets a specific route
opt out of the default authorizer — e.g. a route whose auth is handled
inside the application itself and needs a missing/invalid token to still
reach the handler rather than being rejected by the gateway.
HttpApiRoute now carries whether its event declared Auth.Authorizer: NONE,
collected in collectHttpApiRoutes alongside the existing path/method
fields, and expandHttpApiRoute skips wiring the default authorizer for
routes that opted out.
Found while validating #1759's fix against a template with this exact
pattern (one route using the default JWT authorizer, a second explicitly
set to Authorizer: NONE) — the original fix would have silently applied
the default authorizer to both.
* fix(cloudformation): forward SAM authorizer IdentitySource for HttpApi JWT authorizers
expandServerlessHttpApi's buildHttpApiAuthorizer hardcoded IdentitySource to
$request.header.Authorization regardless of what the SAM template's
Authorizers.<Name>.IdentitySource declared, silently overriding any
non-default source (e.g. $request.querystring.token) with the header form.
CloudFormationResourceProvisioner.resolveIdentitySource and
ApiGatewayExecuteController already support arbitrary identity sources,
including querystring, for raw (non-SAM) AWS::ApiGatewayV2::Authorizer
resources — this closes the same gap for the SAM transform, accepting either
the documented array form or a scalar string, matching the raw provisioner's
leniency.
Verified by reverting the fix and confirming
createStack_samHttpApiAuthorizerHonorsCustomIdentitySource fails.
* fix(cloudformation): reject SAM JWT authorizer with no IdentitySource
Real sam deploy rejects a JWT authorizer that omits IdentitySource
(_validate_jwt_authorizer in samtranslator/model/apigatewayv2.py) rather
than defaulting it. This transform was silently defaulting to
$request.header.Authorization instead, so a template real SAM refuses
would pass here quietly.
* fix(cloudformation): reject SAM HttpApi authorizer with no JwtConfiguration, honor case-insensitive Issuer/Audience
SAM's _validate_jwt_authorizer checks JwtConfiguration before IdentitySource,
rejecting a template that omits it. buildHttpApiAuthorizer treated it as
optional, silently producing an authorizer that would never validate a token
for real sam deploy. It now rejects in the same order SAM does.
SAM's _get_jwt_configuration also lower-cases every JwtConfiguration key
before reading it, so any casing of issuer/audience is accepted, not just the
two spellings the docs happen to show. Only the lowercase form was read here,
so a template using another casing silently produced an authorizer with an
empty JwtConfiguration instead of an error.
This commit is contained in:
2 files changed
+726
No files matched your search
+238
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -73,6 +74,11 @@ class SamTransformProcessor {
|
||||
// Collect implicit-API routes from function Api events before the functions are expanded.
|
||||
List<ApiRoute> apiRoutes = collectApiRoutes(samLogicalIds, resources);
|
||||
|
||||
// Collect explicit HttpApi routes (Function Events of Type HttpApi bound to an
|
||||
// AWS::Serverless::HttpApi via ApiId: {Ref: <logicalId>}) before either side is expanded,
|
||||
// so expansion order between the Function and the HttpApi resource doesn't matter.
|
||||
List<HttpApiRoute> httpApiRoutes = collectHttpApiRoutes(samLogicalIds, resources);
|
||||
|
||||
for (String logicalId : samLogicalIds) {
|
||||
JsonNode resDef = resources.get(logicalId);
|
||||
String type = resDef.path("Type").asText();
|
||||
@@ -85,6 +91,9 @@ class SamTransformProcessor {
|
||||
expandServerlessSimpleTable(logicalId, mergeGlobals(globals, "SimpleTable", properties), expandedResources);
|
||||
case "AWS::Serverless::Api" ->
|
||||
expandServerlessApi(logicalId, mergeGlobals(globals, "Api", properties), expandedResources);
|
||||
case "AWS::Serverless::HttpApi" ->
|
||||
expandServerlessHttpApi(logicalId, mergeGlobals(globals, "HttpApi", properties),
|
||||
httpApiRoutes, expandedResources);
|
||||
default -> LOG.debugv("Unsupported SAM resource type: {0} ({1})", type, logicalId);
|
||||
}
|
||||
}
|
||||
@@ -139,6 +148,232 @@ class SamTransformProcessor {
|
||||
return routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param noAuthorizer true when this event declares {@code Auth: {Authorizer: NONE}},
|
||||
* overriding the API's {@code DefaultAuthorizer} for this route specifically
|
||||
* (SAM's documented per-event opt-out of the default authorizer).
|
||||
*/
|
||||
private record HttpApiRoute(String functionLogicalId, String apiLogicalId, String path, String httpMethod,
|
||||
boolean noAuthorizer) {}
|
||||
|
||||
/**
|
||||
* Collects HttpApi-typed Function events bound to an explicit {@code AWS::Serverless::HttpApi}
|
||||
* via {@code ApiId: {Ref: <logicalId>}}. Events with no {@code ApiId} (SAM's implicit HttpApi,
|
||||
* auto-created rather than declared as its own resource) are intentionally not handled here —
|
||||
* that is a separate expansion path, mirroring how {@link #collectApiRoutes} and
|
||||
* {@link #generateImplicitApi} are already split out from {@link #expandServerlessApi}'s
|
||||
* explicit-REST-API handling.
|
||||
*/
|
||||
private List<HttpApiRoute> collectHttpApiRoutes(List<String> samLogicalIds, JsonNode resources) {
|
||||
List<HttpApiRoute> 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<Map.Entry<String, JsonNode>> it = events.fields();
|
||||
while (it.hasNext()) {
|
||||
JsonNode ev = it.next().getValue();
|
||||
if (!"HttpApi".equals(ev.path("Type").asText())) {
|
||||
continue;
|
||||
}
|
||||
JsonNode p = ev.path("Properties");
|
||||
String apiLogicalId = p.path("ApiId").path("Ref").asText(null);
|
||||
if (apiLogicalId == null) {
|
||||
continue; // no explicit ApiId (implicit HttpApi) — not handled by this path
|
||||
}
|
||||
JsonNode pathNode = p.path("Path");
|
||||
if (!pathNode.isTextual()) {
|
||||
continue; // needs a literal path; skip intrinsics (Ref/Fn::Sub)
|
||||
}
|
||||
JsonNode methodNode = p.path("Method");
|
||||
String method = methodNode.isTextual() ? methodNode.asText() : "ANY";
|
||||
boolean noAuthorizer = "NONE".equals(p.path("Auth").path("Authorizer").asText(null));
|
||||
routes.add(new HttpApiRoute(logicalId, apiLogicalId, pathNode.asText(), method, noAuthorizer));
|
||||
}
|
||||
}
|
||||
return routes;
|
||||
}
|
||||
|
||||
private void expandServerlessHttpApi(String logicalId, JsonNode properties,
|
||||
List<HttpApiRoute> allRoutes, ObjectNode resources) {
|
||||
resources.remove(logicalId);
|
||||
|
||||
ObjectNode apiDef = objectMapper.createObjectNode();
|
||||
apiDef.put("Type", "AWS::ApiGatewayV2::Api");
|
||||
ObjectNode apiProps = objectMapper.createObjectNode();
|
||||
JsonNode name = properties.path("Name");
|
||||
apiProps.set("Name", !name.isMissingNode() ? name.deepCopy() : objectMapper.getNodeFactory().textNode(logicalId));
|
||||
apiProps.put("ProtocolType", "HTTP");
|
||||
copyIfPresent(properties, "Description", apiProps);
|
||||
apiDef.set("Properties", apiProps);
|
||||
resources.set(logicalId, apiDef);
|
||||
|
||||
// Auth.Authorizers -> one AWS::ApiGatewayV2::Authorizer per entry, keyed by SAM authorizer
|
||||
// name so routes referencing Auth.DefaultAuthorizer (the only form handled here — per-route
|
||||
// Auth overrides are not expanded) can resolve the logical id to Ref.
|
||||
Map<String, String> authorizerLogicalIdsByName = new java.util.LinkedHashMap<>();
|
||||
JsonNode auth = properties.path("Auth");
|
||||
JsonNode authorizers = auth.path("Authorizers");
|
||||
if (authorizers.isObject()) {
|
||||
Iterator<Map.Entry<String, JsonNode>> it = authorizers.fields();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = it.next();
|
||||
String authorizerName = entry.getKey();
|
||||
String authorizerLogicalId = uniqueId(logicalId + sanitize(authorizerName) + "Authorizer", resources);
|
||||
resources.set(authorizerLogicalId, buildHttpApiAuthorizer(logicalId, authorizerName, entry.getValue()));
|
||||
authorizerLogicalIdsByName.put(authorizerName, authorizerLogicalId);
|
||||
}
|
||||
}
|
||||
String defaultAuthorizerName = auth.path("DefaultAuthorizer").asText(null);
|
||||
String defaultAuthorizerLogicalId = defaultAuthorizerName != null
|
||||
? authorizerLogicalIdsByName.get(defaultAuthorizerName) : null;
|
||||
|
||||
String stageLogicalId = uniqueId(logicalId + "ApiDefaultStage", resources);
|
||||
ObjectNode stageDef = objectMapper.createObjectNode();
|
||||
stageDef.put("Type", "AWS::ApiGatewayV2::Stage");
|
||||
ObjectNode stageProps = objectMapper.createObjectNode();
|
||||
stageProps.set("ApiId", ref(logicalId));
|
||||
stageProps.put("StageName", "$default");
|
||||
stageProps.put("AutoDeploy", true);
|
||||
stageDef.set("Properties", stageProps);
|
||||
resources.set(stageLogicalId, stageDef);
|
||||
|
||||
for (HttpApiRoute route : allRoutes) {
|
||||
if (!logicalId.equals(route.apiLogicalId())) {
|
||||
continue;
|
||||
}
|
||||
expandHttpApiRoute(logicalId, route, defaultAuthorizerLogicalId, resources);
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode buildHttpApiAuthorizer(String apiLogicalId, String authorizerName, JsonNode samAuthorizer) {
|
||||
ObjectNode authDef = objectMapper.createObjectNode();
|
||||
authDef.put("Type", "AWS::ApiGatewayV2::Authorizer");
|
||||
ObjectNode authProps = objectMapper.createObjectNode();
|
||||
authProps.set("ApiId", ref(apiLogicalId));
|
||||
authProps.put("Name", authorizerName);
|
||||
authProps.put("AuthorizerType", "JWT");
|
||||
|
||||
JsonNode jwtConfig = samAuthorizer.path("JwtConfiguration");
|
||||
if (!jwtConfig.isObject()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"OAuth2 Authorizer must define 'JwtConfiguration'; authorizer " + authorizerName, 400);
|
||||
}
|
||||
|
||||
authProps.set("IdentitySource", resolveIdentitySource(authorizerName, samAuthorizer));
|
||||
|
||||
ObjectNode jwtProps = objectMapper.createObjectNode();
|
||||
JsonNode issuer = fieldIgnoreCase(jwtConfig, "issuer");
|
||||
if (!issuer.isMissingNode()) {
|
||||
jwtProps.set("Issuer", issuer.deepCopy());
|
||||
}
|
||||
JsonNode audience = fieldIgnoreCase(jwtConfig, "audience");
|
||||
if (audience.isArray()) {
|
||||
jwtProps.set("Audience", audience.deepCopy());
|
||||
}
|
||||
authProps.set("JwtConfiguration", jwtProps);
|
||||
|
||||
authDef.set("Properties", authProps);
|
||||
return authDef;
|
||||
}
|
||||
|
||||
/**
|
||||
* SAM's {@code _get_jwt_configuration} lower-cases every key of the {@code JwtConfiguration}
|
||||
* map before reading it ({@code {k.lower(): v for k, v in props.items()}} in
|
||||
* samtranslator/model/apigatewayv2.py), so any casing of {@code issuer}/{@code audience} is
|
||||
* accepted, not just the two spellings the docs happen to show.
|
||||
*/
|
||||
private JsonNode fieldIgnoreCase(JsonNode node, String fieldName) {
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
if (field.getKey().equalsIgnoreCase(fieldName)) {
|
||||
return field.getValue();
|
||||
}
|
||||
}
|
||||
return objectMapper.missingNode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the SAM authorizer's {@code IdentitySource}, accepting either the documented array
|
||||
* form or a single scalar string — mirroring
|
||||
* {@code CloudFormationResourceProvisioner.resolveIdentitySource}, since the raw
|
||||
* {@code AWS::ApiGatewayV2::Authorizer} resource this expands to accepts both. SAM itself
|
||||
* rejects a JWT authorizer with no {@code IdentitySource} ({@code _validate_jwt_authorizer} in
|
||||
* samtranslator/model/apigatewayv2.py), so an absent or empty value is a template error here
|
||||
* too.
|
||||
*/
|
||||
private ArrayNode resolveIdentitySource(String authorizerName, JsonNode samAuthorizer) {
|
||||
ArrayNode identitySource = objectMapper.createArrayNode();
|
||||
JsonNode raw = samAuthorizer.path("IdentitySource");
|
||||
if (raw.isTextual()) {
|
||||
identitySource.add(raw.asText());
|
||||
} else if (raw.isArray() && !raw.isEmpty()) {
|
||||
raw.forEach(v -> identitySource.add(v.asText()));
|
||||
} else {
|
||||
throw new AwsException("ValidationError",
|
||||
"OAuth2 Authorizer must define 'IdentitySource'; authorizer " + authorizerName, 400);
|
||||
}
|
||||
return identitySource;
|
||||
}
|
||||
|
||||
private void expandHttpApiRoute(String apiLogicalId, HttpApiRoute route,
|
||||
String defaultAuthorizerLogicalId, ObjectNode resources) {
|
||||
String integrationLogicalId = uniqueId(
|
||||
apiLogicalId + "Integration" + sanitize(route.functionLogicalId()), resources);
|
||||
ObjectNode integDef = objectMapper.createObjectNode();
|
||||
integDef.put("Type", "AWS::ApiGatewayV2::Integration");
|
||||
ObjectNode integProps = objectMapper.createObjectNode();
|
||||
integProps.set("ApiId", ref(apiLogicalId));
|
||||
integProps.put("IntegrationType", "AWS_PROXY");
|
||||
integProps.set("IntegrationUri", lambdaInvokeUri(route.functionLogicalId()));
|
||||
integProps.put("PayloadFormatVersion", "2.0");
|
||||
integDef.set("Properties", integProps);
|
||||
resources.set(integrationLogicalId, integDef);
|
||||
|
||||
String routeKey = route.httpMethod().toUpperCase() + " " + route.path();
|
||||
String routeLogicalId = uniqueId(
|
||||
apiLogicalId + "Route" + sanitize(route.functionLogicalId()) + sanitize(route.path()), resources);
|
||||
ObjectNode routeDef = objectMapper.createObjectNode();
|
||||
routeDef.put("Type", "AWS::ApiGatewayV2::Route");
|
||||
ObjectNode routeProps = objectMapper.createObjectNode();
|
||||
routeProps.set("ApiId", ref(apiLogicalId));
|
||||
routeProps.put("RouteKey", routeKey);
|
||||
if (defaultAuthorizerLogicalId != null && !route.noAuthorizer()) {
|
||||
routeProps.put("AuthorizationType", "JWT");
|
||||
routeProps.set("AuthorizerId", ref(defaultAuthorizerLogicalId));
|
||||
} else {
|
||||
routeProps.put("AuthorizationType", "NONE");
|
||||
}
|
||||
ObjectNode join = objectMapper.createObjectNode();
|
||||
ArrayNode joinArgs = objectMapper.createArrayNode();
|
||||
joinArgs.add("/");
|
||||
ArrayNode joinValues = objectMapper.createArrayNode();
|
||||
joinValues.add("integrations");
|
||||
joinValues.add(ref(integrationLogicalId));
|
||||
joinArgs.add(joinValues);
|
||||
join.set("Fn::Join", joinArgs);
|
||||
routeProps.set("Target", join);
|
||||
routeDef.set("Properties", routeProps);
|
||||
resources.set(routeLogicalId, routeDef);
|
||||
|
||||
String permissionLogicalId = uniqueId(
|
||||
route.functionLogicalId() + "HttpApiPermission" + sanitize(apiLogicalId), resources);
|
||||
ObjectNode perm = objectMapper.createObjectNode();
|
||||
perm.put("Type", "AWS::Lambda::Permission");
|
||||
ObjectNode permProps = objectMapper.createObjectNode();
|
||||
permProps.set("FunctionName", ref(route.functionLogicalId()));
|
||||
permProps.put("Action", "lambda:InvokeFunction");
|
||||
permProps.put("Principal", "apigateway.amazonaws.com");
|
||||
perm.set("Properties", permProps);
|
||||
resources.set(permissionLogicalId, perm);
|
||||
}
|
||||
|
||||
private void generateImplicitApi(List<ApiRoute> 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.
|
||||
@@ -570,6 +805,9 @@ class SamTransformProcessor {
|
||||
case "Api" ->
|
||||
LOG.debugv("SAM Api event for {0}.{1} — handled by Api resource",
|
||||
functionLogicalId, eventName);
|
||||
case "HttpApi" ->
|
||||
LOG.debugv("SAM HttpApi event for {0}.{1} — handled by HttpApi resource",
|
||||
functionLogicalId, eventName);
|
||||
default ->
|
||||
LOG.debugv("SAM event type {0} for {1}.{2} not expanded",
|
||||
eventType, functionLogicalId, eventName);
|
||||
|
||||
Reference in new issue
Block a user