Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): provision AWS::Lambda::Url (#3423)

Anders Wasen10becc593fae
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index d5bf43ec3d..db2bb8b423 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -70,7 +70,7 @@ cross-resource references.
| SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) |
| SNS | `Topic`, `Subscription`, `TopicPolicy` |
| DynamoDB | `Table`, `GlobalTable` |
-| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig`, `MicrovmImage`, `NetworkConnector`. Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. |
+| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig`, `MicrovmImage`, `NetworkConnector`, `Url`. Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. |
| IAM | `Role`, `User`, `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` |
| Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` |
| SSM | `Parameter` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisioner.java
index 2baac4ec99..8189251751 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisioner.java
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.lambda.model.LambdaUrlConfig;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -16,9 +17,18 @@ import java.util.Map;
import java.util.Set;
/**
- * CloudFormation provisioning for {@code AWS::Lambda::Permission}. {@code AWS::Lambda::Version} and
+ * CloudFormation provisioning for the types that address a function from outside it:
+ * {@code AWS::Lambda::Permission} and {@code AWS::Lambda::Url}. {@code AWS::Lambda::Version} and
* {@code AWS::Lambda::Alias} belong to {@link LambdaVersionAliasCfnProvisioner}.
*
+ * <p>{@code AWS::Lambda::Url}: the physical id is the {@code FunctionArn} the URL is attached to
+ * (the alias ARN when {@code Qualifier} names one), which is both the schema's primary identifier
+ * and enough to address the config again, since a qualified ARN parses back into function and
+ * qualifier. {@code Fn::GetAtt FunctionUrl} is the URL itself; a template that omits the attribute
+ * would otherwise export the literal string {@code "LogicalId.FunctionUrl"}. The CloudFormation
+ * property names for the URL are already the ones the Lambda API takes, {@code Cors} members
+ * included, so they are passed through rather than translated.
+ *
* <p>The physical id doubles as the delete handle, since {@link #delete(String, String, String)}
* only receives the physical id. It stores {@code <functionName>|<statementId>}, and '|' cannot
* appear in a function name or ARN.
@@ -30,6 +40,9 @@ import java.util.Set;
@ApplicationScoped
public class LambdaAddressingCfnProvisioner implements CfnResourceProvisioner {
+ private static final String PERMISSION = "AWS::Lambda::Permission";
+ private static final String URL = "AWS::Lambda::Url";
+
private final LambdaService lambdaService;
@Inject
@@ -39,21 +52,33 @@ public class LambdaAddressingCfnProvisioner implements CfnResourceProvisioner {
@Override
public Set<String> resourceTypes() {
- return Set.of("AWS::Lambda::Permission");
+ return Set.of(PERMISSION, URL);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
- if (!"AWS::Lambda::Permission".equals(r.getResourceType())) {
- throw new IllegalStateException(
- "LambdaPermissionCfnProvisioner cannot handle " + r.getResourceType());
+ switch (r.getResourceType()) {
+ case PERMISSION -> provisionPermission(r, props, ctx);
+ case URL -> provisionUrl(r, props, ctx);
+ default -> throw new IllegalStateException(
+ "LambdaAddressingCfnProvisioner cannot handle " + r.getResourceType());
}
- provisionPermission(r, props, ctx);
}
@Override
public void delete(String resourceType, String physicalId, String region) {
- if (!"AWS::Lambda::Permission".equals(resourceType) || physicalId == null) {
+ if (physicalId == null) {
+ return;
+ }
+ if (URL.equals(resourceType)) {
+ // The physical id is the function (or alias) ARN, which resolveWithQualifier splits back
+ // into name and qualifier, so no create-time attribute is needed to find the config.
+ CfnDeletes.safeDelete("function URL", physicalId,
+ () -> lambdaService.deleteFunctionUrlConfig(region, physicalId, null),
+ "ResourceNotFoundException");
+ return;
+ }
+ if (!PERMISSION.equals(resourceType)) {
return;
}
int sep = physicalId.lastIndexOf('|');
@@ -110,6 +135,108 @@ public class LambdaAddressingCfnProvisioner implements CfnResourceProvisioner {
r.setPhysicalId(functionName + "|" + statementId);
}
+ private void provisionUrl(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String targetFunctionArn = ctx.resolveOptional(props, "TargetFunctionArn");
+ if (targetFunctionArn == null || targetFunctionArn.isBlank()) {
+ throw new AwsException("ValidationError", URL + " requires TargetFunctionArn.", 400);
+ }
+ String qualifier = ctx.resolveOptional(props, "Qualifier");
+ String authType = ctx.resolveOptional(props, "AuthType");
+
+ Map<String, Object> request = new HashMap<>();
+ // AWS_IAM in the template stays AWS_IAM; the service's own default is NONE, which is also
+ // what the Lambda API defaults an omitted AuthType to.
+ if (authType != null && !authType.isBlank()) {
+ request.put("AuthType", authType);
+ }
+ String invokeMode = ctx.resolveOptional(props, "InvokeMode");
+ if (invokeMode != null && !invokeMode.isBlank()) {
+ request.put("InvokeMode", invokeMode);
+ }
+ Map<String, Object> cors = corsRequest(props, ctx);
+ boolean updating = hasUrlConfig(ctx.region(), targetFunctionArn, qualifier);
+ if (cors != null) {
+ request.put("Cors", cors);
+ } else if (updating) {
+ // Present and null, which is how UpdateFunctionUrlConfig is told to clear the policy;
+ // omitting the member leaves the CORS rules the template no longer declares in place.
+ request.put("Cors", null);
+ }
+
+ // provision is the update path too, and CreateFunctionUrlConfig answers 409 on a function
+ // that already has one. Which call to make follows from whether the *intended* target
+ // already has a config, not from isUpdate(): TargetFunctionArn and Qualifier are
+ // create-only, so an update that changed either has to create against the new function.
+ LambdaUrlConfig urlConfig = updating
+ ? lambdaService.updateFunctionUrlConfig(ctx.region(), targetFunctionArn, qualifier, request)
+ : lambdaService.createFunctionUrlConfig(ctx.region(), targetFunctionArn, qualifier, request);
+
+ String priorPhysicalId = ctx.priorPhysicalId();
+ if (ctx.isUpdate() && !urlConfig.getFunctionArn().equals(priorPhysicalId)) {
+ // The URL moved to a different function. CloudFormation deletes the entity a replacing
+ // update displaced; a function URL is addressed only through its function, so the one
+ // left on the previous function would otherwise stay reachable forever.
+ CfnDeletes.safeDelete("displaced function URL", priorPhysicalId,
+ () -> lambdaService.deleteFunctionUrlConfig(ctx.region(), priorPhysicalId, null),
+ "ResourceNotFoundException");
+ }
+
+ r.setPhysicalId(urlConfig.getFunctionArn());
+ r.getAttributes().put("FunctionArn", urlConfig.getFunctionArn());
+ r.getAttributes().put("FunctionUrl", urlConfig.getFunctionUrl());
+ }
+
+ private boolean hasUrlConfig(String region, String functionName, String qualifier) {
+ try {
+ return lambdaService.getFunctionUrlConfig(region, functionName, qualifier) != null;
+ } catch (AwsException e) {
+ // Only "there is no config" means create. A missing function, or a qualifier that does
+ // not match the ARN, has to fail the resource rather than be retried as a create.
+ if ("ResourceNotFoundException".equals(e.getErrorCode())) {
+ return false;
+ }
+ throw e;
+ }
+ }
+
+ /**
+ * The {@code Cors} block as the Lambda API takes it, or null when the template has none.
+ * {@code AllowCredentials} must arrive as a Boolean and {@code MaxAge} as a number: the service
+ * reads them with {@code Boolean.TRUE.equals} and an int coercion, so the resolved strings the
+ * template engine hands back for scalars would read as false and 0.
+ */
+ private Map<String, Object> corsRequest(JsonNode props, ProvisionContext ctx) {
+ JsonNode cors = props == null ? null : props.get("Cors");
+ if (cors == null || cors.isNull() || !cors.isObject()) {
+ return null;
+ }
+ Map<String, Object> request = new HashMap<>();
+ putList(request, "AllowHeaders", ctx.resolveStringList(cors, "AllowHeaders"));
+ putList(request, "AllowMethods", ctx.resolveStringList(cors, "AllowMethods"));
+ putList(request, "AllowOrigins", ctx.resolveStringList(cors, "AllowOrigins"));
+ putList(request, "ExposeHeaders", ctx.resolveStringList(cors, "ExposeHeaders"));
+ String allowCredentials = ctx.resolveOptional(cors, "AllowCredentials");
+ if (allowCredentials != null && !allowCredentials.isBlank()) {
+ request.put("AllowCredentials", Boolean.parseBoolean(allowCredentials));
+ }
+ String maxAge = ctx.resolveOptional(cors, "MaxAge");
+ if (maxAge != null && !maxAge.isBlank()) {
+ try {
+ request.put("MaxAge", Integer.valueOf(maxAge.trim()));
+ } catch (NumberFormatException e) {
+ throw new AwsException("ValidationError",
+ URL + " Cors.MaxAge must be a number, got: " + maxAge, 400);
+ }
+ }
+ return request;
+ }
+
+ private static void putList(Map<String, Object> request, String key, List<String> values) {
+ if (values != null && !values.isEmpty()) {
+ request.put(key, values);
+ }
+ }
+
/** A statement taken off a function so it can be put back if the replacement fails. */
private record RemovedStatement(String functionName, Map<String, Object> statement) {}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisionerTest.java
index 660eb5cd15..7ef5bd2eb0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisionerTest.java
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.LambdaUrlConfig;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -16,6 +17,8 @@ import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
@@ -30,7 +33,8 @@ import static org.mockito.Mockito.when;
/**
* The permission-replacement path: a stack update removes the previous statement before adding
- * its replacement, so a rejected replacement must not leave the function with neither.
+ * its replacement, so a rejected replacement must not leave the function with neither. Plus
+ * {@code AWS::Lambda::Url}, whose {@code FunctionUrl} attribute is the one a template exports.
*/
class LambdaAddressingCfnProvisionerTest {
@@ -117,4 +121,175 @@ class LambdaAddressingCfnProvisionerTest {
.put("Action", "lambda:InvokeFunction")
.put("Principal", "s3.amazonaws.com");
}
+
+ // ── AWS::Lambda::Url ─────────────────────────────────────────────────────
+
+ private static final String FN_ARN = "arn:aws:lambda:us-east-1:000000000000:function:app-fn";
+
+ private StackResource urlResource() {
+ StackResource r = new StackResource();
+ r.setLogicalId("AppFnLambdaFunctionUrl");
+ r.setResourceType("AWS::Lambda::Url");
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private LambdaUrlConfig urlConfig(String functionArn) {
+ LambdaUrlConfig config = new LambdaUrlConfig();
+ config.setFunctionArn(functionArn);
+ config.setFunctionUrl("http://abc123.lambda-url.us-east-1.localhost:4566/");
+ return config;
+ }
+
+ private void noExistingUrlConfig() {
+ doThrow(new AwsException("ResourceNotFoundException", "Function URL config not found", 404))
+ .when(lambda).getFunctionUrlConfig(anyString(), anyString(), any());
+ }
+
+ @Test
+ void urlPublishesTheFunctionUrlAttribute() {
+ noExistingUrlConfig();
+ when(lambda.createFunctionUrlConfig(eq(REGION), eq(FN_ARN), isNull(), anyMap()))
+ .thenReturn(urlConfig(FN_ARN));
+ StackResource r = urlResource();
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("TargetFunctionArn", FN_ARN)
+ .put("AuthType", "NONE"), ctx());
+
+ // Without the attribute, Fn::GetAtt resolves to the literal "LogicalId.FunctionUrl" and
+ // that string is what a stack export hands out in place of a URL.
+ assertEquals("http://abc123.lambda-url.us-east-1.localhost:4566/",
+ r.getAttributes().get("FunctionUrl"));
+ assertEquals(FN_ARN, r.getAttributes().get("FunctionArn"));
+ assertEquals(FN_ARN, r.getPhysicalId());
+ }
+
+ @Test
+ void urlUpdatesTheConfigTheTargetAlreadyHas() {
+ when(lambda.getFunctionUrlConfig(REGION, FN_ARN, null)).thenReturn(urlConfig(FN_ARN));
+ when(lambda.updateFunctionUrlConfig(eq(REGION), eq(FN_ARN), isNull(), anyMap()))
+ .thenReturn(urlConfig(FN_ARN));
+ StackResource r = urlResource();
+ r.setPhysicalId(FN_ARN);
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("TargetFunctionArn", FN_ARN)
+ .put("AuthType", "AWS_IAM"), ctx());
+
+ // CreateFunctionUrlConfig answers 409 for a function that already has one, so a re-deploy
+ // has to update rather than create.
+ verify(lambda).updateFunctionUrlConfig(eq(REGION), eq(FN_ARN), isNull(), anyMap());
+ verify(lambda, never()).createFunctionUrlConfig(anyString(), anyString(), any(), anyMap());
+ }
+
+ @Test
+ void urlMovedToAnotherFunctionDeletesTheDisplacedOne() {
+ String newArn = "arn:aws:lambda:us-east-1:000000000000:function:other-fn";
+ noExistingUrlConfig();
+ when(lambda.createFunctionUrlConfig(eq(REGION), eq(newArn), isNull(), anyMap()))
+ .thenReturn(urlConfig(newArn));
+ StackResource r = urlResource();
+ r.setPhysicalId(FN_ARN);
+ ProvisionContext update = new ProvisionContext(ctx().engine(), REGION, "000000000000",
+ "test-stack", FN_ARN);
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("TargetFunctionArn", newArn)
+ .put("AuthType", "NONE"), update);
+
+ // TargetFunctionArn is create-only. The URL on the previous function is not addressable
+ // from any resource any more, so leaving it would keep it invokable forever.
+ verify(lambda).deleteFunctionUrlConfig(REGION, FN_ARN, null);
+ assertEquals(newArn, r.getPhysicalId());
+ }
+
+ @Test
+ void urlCorsArrivesTypedNotStringified() {
+ noExistingUrlConfig();
+ when(lambda.createFunctionUrlConfig(eq(REGION), eq(FN_ARN), isNull(), anyMap()))
+ .thenReturn(urlConfig(FN_ARN));
+ CloudFormationTemplateEngine engine = ctx().engine();
+ when(engine.resolveStringList(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ List<String> values = new java.util.ArrayList<>();
+ if (node != null && node.isArray()) {
+ node.forEach(element -> values.add(element.asText()));
+ }
+ return values;
+ });
+ ProvisionContext ctx = new ProvisionContext(engine, REGION, "000000000000", "test-stack");
+ ObjectNode props = mapper.createObjectNode()
+ .put("TargetFunctionArn", FN_ARN)
+ .put("AuthType", "NONE");
+ ObjectNode cors = props.putObject("Cors");
+ cors.put("AllowCredentials", true).put("MaxAge", 600);
+ cors.putArray("AllowOrigins").add("https://app.example.com");
+ cors.putArray("AllowMethods").add("GET").add("POST");
+
+ provisioner.provision(urlResource(), props, ctx);
+
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.captor();
+ verify(lambda).createFunctionUrlConfig(eq(REGION), eq(FN_ARN), isNull(), captor.capture());
+ Map<String, Object> cfg = (Map<String, Object>) captor.getValue().get("Cors");
+ // The service reads these with Boolean.TRUE.equals and an int coercion: the resolved
+ // strings a scalar resolve hands back would read as false and 0.
+ assertEquals(Boolean.TRUE, cfg.get("AllowCredentials"));
+ assertEquals(600, cfg.get("MaxAge"));
+ assertEquals(List.of("https://app.example.com"), cfg.get("AllowOrigins"));
+ assertEquals(List.of("GET", "POST"), cfg.get("AllowMethods"));
+ }
+
+ @Test
+ void anUpdateThatDroppedCorsClearsIt() {
+ when(lambda.getFunctionUrlConfig(REGION, FN_ARN, null)).thenReturn(urlConfig(FN_ARN));
+ when(lambda.updateFunctionUrlConfig(eq(REGION), eq(FN_ARN), isNull(), anyMap()))
+ .thenReturn(urlConfig(FN_ARN));
+ StackResource r = urlResource();
+ r.setPhysicalId(FN_ARN);
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("TargetFunctionArn", FN_ARN)
+ .put("AuthType", "NONE"), ctx());
+
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.captor();
+ verify(lambda).updateFunctionUrlConfig(eq(REGION), eq(FN_ARN), isNull(), captor.capture());
+ // UpdateFunctionUrlConfig clears the policy only for a Cors member that is present and
+ // null; omitting it left the rules the template no longer declares in force.
+ assertTrue(captor.getValue().containsKey("Cors"));
+ assertNull(captor.getValue().get("Cors"));
+ }
+
+ @Test
+ void urlWithoutATargetIsRefused() {
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(urlResource(),
+ mapper.createObjectNode().put("AuthType", "NONE"), ctx()));
+
+ assertTrue(e.getMessage().contains("TargetFunctionArn"), e.getMessage());
+ verify(lambda, never()).createFunctionUrlConfig(anyString(), anyString(), any(), anyMap());
+ }
+
+ @Test
+ void urlDeleteRemovesTheConfigTheArnPointsAt() {
+ provisioner.delete("AWS::Lambda::Url", FN_ARN, REGION);
+
+ // A qualified ARN parses back into function and qualifier, so the physical id is enough.
+ verify(lambda).deleteFunctionUrlConfig(REGION, FN_ARN, null);
+ }
+
+ @Test
+ void urlDeleteToleratesAnAlreadyGoneConfig() {
+ doThrow(new AwsException("ResourceNotFoundException", "not found", 404))
+ .when(lambda).deleteFunctionUrlConfig(REGION, FN_ARN, null);
+
+ provisioner.delete("AWS::Lambda::Url", FN_ARN, REGION);
+ }
+
+ @Test
+ void urlDeletePropagatesARealFailure() {
+ doThrow(new AwsException("ResourceConflictException", "update in progress", 409))
+ .when(lambda).deleteFunctionUrlConfig(REGION, FN_ARN, null);
+
+ assertThrows(AwsException.class, () -> provisioner.delete("AWS::Lambda::Url", FN_ARN, REGION));
+ }
}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index c000f283ed..99e4d8385b 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -101,6 +101,7 @@ AWS::Lambda::LayerVersion LEGACY_SWITCH
AWS::Lambda::MicrovmImage LambdaMicrovmsCfnProvisioner
AWS::Lambda::NetworkConnector LambdaMicrovmsCfnProvisioner
AWS::Lambda::Permission LambdaAddressingCfnProvisioner
+AWS::Lambda::Url LambdaAddressingCfnProvisioner
AWS::Lambda::Version LambdaVersionAliasCfnProvisioner
AWS::Logs::LogGroup LogsCfnProvisioner
AWS::Organizations::Account OrganizationsCfnProvisioner