Light, fluffy, and always free - The AWS Local Emulator alternative
feat(lambdaweb): Lambda Web Functions control plane (#5706)
TATSUNO “Taz” Yasuhiro6f7808308004
diff --git a/README.md b/README.mdindex f64a4133ab..1c3542bb32 100644--- a/README.md+++ b/README.md@@ -293,7 +293,7 @@ Floci supports local emulation for application services, data services, eventing| Category | Services ||---|---|-| Core app services | S3, SQS, SNS, DynamoDB, Lambda, Lambda MicroVMs, IAM, STS, KMS, Secrets Manager, SSM |+| Core app services | S3, SQS, SNS, DynamoDB, Lambda, Lambda MicroVMs, Lambda Web Functions, IAM, STS, KMS, Secrets Manager, SSM || Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics, CloudWatch OAM, CloudWatch RUM, Managed Prometheus (AMP) || API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, Cognito Identity, ACM, Route53, Route 53 Resolver, Cloud Map, Global Accelerator || Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, EFS, CodeBuild, CodeDeploy, CodePipeline, CodeGuru Reviewer, CodeArtifact, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2, ELB Classic |diff --git a/compatibility-tests/sdk-test-awscli/test/lambda-web.bats b/compatibility-tests/sdk-test-awscli/test/lambda-web.batsnew file mode 100644index 0000000000..1d8d960aeb--- /dev/null+++ b/compatibility-tests/sdk-test-awscli/test/lambda-web.bats@@ -0,0 +1,143 @@+#!/usr/bin/env bats+# Lambda Web Functions integration tests+#+# The `lambda-web` service model signs as lambda and is served under the lambda+# service. Code comes from an S3 object, so each test seeds one first.++setup() {+ load 'test_helper/common-setup'+ FUNCTION_NAME=""+ BUCKET="cli-lambda-web-code-$$"+ ROLE_ARN="arn:aws:iam::000000000000:role/lambda-web"+ aws_cmd s3api create-bucket --bucket "$BUCKET" >/dev/null 2>&1 || true+ printf 'zip' > "$BATS_TEST_TMPDIR/app.zip"+ aws_cmd s3api put-object --bucket "$BUCKET" --key app.zip --body "$BATS_TEST_TMPDIR/app.zip" >/dev/null+}++teardown() {+ if [ -n "$FUNCTION_NAME" ]; then+ aws_cmd lambda-web delete-web-function --function-name "$FUNCTION_NAME" >/dev/null 2>&1 || true+ fi+ aws_cmd s3 rb "s3://$BUCKET" --force >/dev/null 2>&1 || true+}++build_config() {+ printf '{"codeConfig":{"s3Object":{"bucket":"%s","key":"app.zip"}},"runtimeConfig":{"runtime":"nodejs24.x"}}' "$BUCKET"+}++create_function() {+ local name="$1"+ aws_cmd lambda-web create-web-function \+ --function-name "$name" \+ --revision-config "{\"buildConfig\":$(build_config),\"serviceConfig\":{\"executionRoleArn\":\"$ROLE_ARN\"}}" \+ --endpoint-config '{"endpointName":"dev","endpointType":"HomeRegion","authType":"ApplicationManaged","autoDeploymentMode":"LatestRevision"}'+}++@test "Lambda Web: create a function with its first revision and endpoint" {+ FUNCTION_NAME=$(unique_name "cli-web")+ run create_function "$FUNCTION_NAME"+ assert_success+ state=$(json_get "$output" '.state')+ revision_state=$(json_get "$output" '.revision.state')+ endpoint_state=$(json_get "$output" '.endpoint.state')+ domain=$(json_get "$output" '.endpoint.domainName')+ [ "$state" = "Active" ]+ [ "$revision_state" = "Pending" ]+ [ "$endpoint_state" = "Pending" ]+ [[ "$domain" =~ \.lambda-web\.us-east-1\. ]]++ run aws_cmd lambda-web wait web-function-endpoint-active --function-name "$FUNCTION_NAME" --endpoint-name dev+ assert_success+}++@test "Lambda Web: a new revision moves a LatestRevision endpoint" {+ FUNCTION_NAME=$(unique_name "cli-web")+ create_function "$FUNCTION_NAME" >/dev/null++ run aws_cmd lambda-web create-web-function-revision \+ --function-name "$FUNCTION_NAME" \+ --build-config "$(build_config)" \+ --service-config "{\"executionRoleArn\":\"$ROLE_ARN\",\"timeoutSeconds\":60}"+ assert_success+ revision_id=$(json_get "$output" '.revisionId')+ [[ "$revision_id" =~ ^rev-[a-z0-9]{5}$ ]]++ run aws_cmd lambda-web wait web-function-revision-active --function-name "$FUNCTION_NAME" --revision-id "$revision_id"+ assert_success++ run aws_cmd lambda-web get-web-function-endpoint --function-name "$FUNCTION_NAME" --endpoint-name dev+ assert_success+ routed=$(json_get "$output" '.revisionWeights[0].revisionId')+ [ "$routed" = "$revision_id" ]+}++@test "Lambda Web: weighted routing and the in-use revision guard" {+ FUNCTION_NAME=$(unique_name "cli-web")+ create_function "$FUNCTION_NAME" >/dev/null+ first=$(aws_cmd lambda-web list-web-function-revisions --function-name "$FUNCTION_NAME" | jq -r '.revisions[0].revisionId')++ run aws_cmd lambda-web update-web-function-endpoint \+ --function-name "$FUNCTION_NAME" --endpoint-name dev \+ --auto-deployment-mode Disabled \+ --revision-weights "[{\"revisionId\":\"$first\",\"weight\":100}]"+ assert_success+ status=$(json_get "$output" '.updateStatus')+ [ "$status" = "InProgress" ]++ run aws_cmd lambda-web wait web-function-endpoint-updated --function-name "$FUNCTION_NAME" --endpoint-name dev+ assert_success++ run aws_cmd lambda-web delete-web-function-revision --function-name "$FUNCTION_NAME" --revision-id "$first"+ assert_failure+ assert_output --partial "ConflictException"+ assert_output --partial "the endpoints [dev] are using it"+}++@test "Lambda Web: tags and the resource policy" {+ FUNCTION_NAME=$(unique_name "cli-web")+ create_function "$FUNCTION_NAME" >/dev/null+ arn="arn:aws:lambda:us-east-1:000000000000:web-function/$FUNCTION_NAME"++ run aws_cmd lambda-web tag-resource --resource "$arn" --tags env=test+ assert_success+ run aws_cmd lambda-web list-tags --resource "$arn"+ assert_success+ env_tag=$(json_get "$output" '.tags.env')+ [ "$env_tag" = "test" ]++ run aws_cmd lambda-web put-resource-policy --resource-arn "$arn" \+ --policy "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"},\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"$arn/endpoint/*\"}]}"+ assert_success+ revision_id=$(json_get "$output" '.revisionId')+ [ -n "$revision_id" ]++ run aws_cmd lambda-web delete-resource-policy --resource-arn "$arn" --revision-id "$revision_id"+ assert_success+ run aws_cmd lambda-web get-resource-policy --resource-arn "$arn"+ assert_failure+ assert_output --partial "does not have a policy"+}++@test "Lambda Web: invalid names and missing functions" {+ run aws_cmd lambda-web get-web-function --function-name cli-no-such-web-function+ assert_failure+ assert_output --partial "ResourceNotFoundException"++ # The = form keeps the CLI from reading a name that starts with a dash as an option.+ run aws_cmd lambda-web create-web-function --function-name=-bad \+ --revision-config "{\"buildConfig\":$(build_config),\"serviceConfig\":{\"executionRoleArn\":\"$ROLE_ARN\"}}" \+ --endpoint-config '{"endpointName":"dev","endpointType":"HomeRegion","authType":"ApplicationManaged"}'+ assert_failure+ assert_output --partial "Invalid function name or ARN '-bad'"+}++@test "Lambda Web: delete removes the function and the waiter settles" {+ FUNCTION_NAME=$(unique_name "cli-web")+ create_function "$FUNCTION_NAME" >/dev/null++ run aws_cmd lambda-web delete-web-function --function-name "$FUNCTION_NAME"+ assert_success+ run aws_cmd lambda-web wait web-function-deleted --function-name "$FUNCTION_NAME"+ assert_success+ FUNCTION_NAME=""+}diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xmlindex d85e44997b..5633c15a20 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -128,6 +128,10 @@<groupId>software.amazon.awssdk</groupId><artifactId>lambda</artifactId></dependency>+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>lambdaweb</artifactId>+ </dependency><dependency><groupId>software.amazon.awssdk</groupId><artifactId>apigateway</artifactId>diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex 56eb0f1ac5..3fb67fb84c 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -87,6 +87,7 @@ import software.amazon.awssdk.services.lambda.model.InvocationType;import software.amazon.awssdk.services.lambda.model.InvokeRequest;import software.amazon.awssdk.services.lambda.model.InvokeResponse;import software.amazon.awssdk.services.lambda.model.Runtime;+import software.amazon.awssdk.services.lambdaweb.LambdaWebClient;import software.amazon.awssdk.services.lightsail.LightsailClient;import software.amazon.awssdk.services.macie2.Macie2Client;import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;@@ -828,6 +829,14 @@ public final class TestFixtures {.build();}+ public static LambdaWebClient lambdaWebClient() {+ return LambdaWebClient.builder()+ .endpointOverride(ENDPOINT)+ .region(REGION)+ .credentialsProvider(CREDENTIALS)+ .build();+ }+public static IamClient iamClient() {return iamClient("test");}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaWebTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaWebTest.javanew file mode 100644index 0000000000..88779b0e4e--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaWebTest.java@@ -0,0 +1,251 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;+import software.amazon.awssdk.core.sync.RequestBody;+import software.amazon.awssdk.services.lambdaweb.LambdaWebClient;+import software.amazon.awssdk.services.lambdaweb.model.AuthType;+import software.amazon.awssdk.services.lambdaweb.model.AutoDeploymentMode;+import software.amazon.awssdk.services.lambdaweb.model.BuildConfig;+import software.amazon.awssdk.services.lambdaweb.model.CodeConfig;+import software.amazon.awssdk.services.lambdaweb.model.ConflictException;+import software.amazon.awssdk.services.lambdaweb.model.CreateWebFunctionResponse;+import software.amazon.awssdk.services.lambdaweb.model.CreateWebFunctionRevisionResponse;+import software.amazon.awssdk.services.lambdaweb.model.EndpointConfig;+import software.amazon.awssdk.services.lambdaweb.model.EndpointType;+import software.amazon.awssdk.services.lambdaweb.model.GetWebFunctionEndpointResponse;+import software.amazon.awssdk.services.lambdaweb.model.ListWebFunctionRevisionsResponse;+import software.amazon.awssdk.services.lambdaweb.model.PutResourcePolicyResponse;+import software.amazon.awssdk.services.lambdaweb.model.ResourceNotFoundException;+import software.amazon.awssdk.services.lambdaweb.model.RevisionConfig;+import software.amazon.awssdk.services.lambdaweb.model.RevisionWeight;+import software.amazon.awssdk.services.lambdaweb.model.RuntimeConfig;+import software.amazon.awssdk.services.lambdaweb.model.S3Object;+import software.amazon.awssdk.services.lambdaweb.model.ServiceConfig;+import software.amazon.awssdk.services.lambdaweb.model.UpdateWebFunctionEndpointResponse;+import software.amazon.awssdk.services.lambdaweb.model.ValidationException;+import software.amazon.awssdk.services.s3.S3Client;+import software.amazon.awssdk.services.s3.model.NoSuchBucketException;++import java.util.Map;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++@DisplayName("Lambda Web Functions")+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class LambdaWebTest {++ private static final String FUNCTION_NAME = "sdk-test-web-fn";+ private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-web-role";+ private static LambdaWebClient lambdaWeb;+ private static S3Client s3;+ private static String bucket;+ private static String functionArn;+ private static String firstRevisionId;+ private static String secondRevisionId;++ @BeforeAll+ static void setup() {+ lambdaWeb = TestFixtures.lambdaWebClient();+ s3 = TestFixtures.s3Client();+ bucket = TestFixtures.uniqueName("sdk-test-web-code");+ s3.createBucket(r -> r.bucket(bucket));+ s3.putObject(r -> r.bucket(bucket).key("app.zip"), RequestBody.fromString("zip"));+ }++ /** Only "already gone" is tolerated; any other failure to clean up fails the run. */+ @AfterAll+ static void cleanup() {+ if (lambdaWeb != null) {+ try {+ lambdaWeb.deleteWebFunction(r -> r.functionName(FUNCTION_NAME));+ } catch (ResourceNotFoundException expected) {+ // The last test deletes the function itself.+ }+ lambdaWeb.close();+ }+ if (s3 != null) {+ try {+ s3.deleteObject(r -> r.bucket(bucket).key("app.zip"));+ s3.deleteBucket(r -> r.bucket(bucket));+ } catch (NoSuchBucketException expected) {+ // Setup did not get as far as creating the bucket.+ }+ s3.close();+ }+ }++ private static BuildConfig buildConfig() {+ return BuildConfig.builder()+ .codeConfig(CodeConfig.builder().s3Object(S3Object.builder().bucket(bucket).key("app.zip").build()).build())+ .runtimeConfig(RuntimeConfig.builder().runtime("nodejs24.x").build())+ .build();+ }++ @Test+ @Order(1)+ void createWebFunctionReportsPendingChildren() {+ CreateWebFunctionResponse created = lambdaWeb.createWebFunction(r -> r+ .functionName(FUNCTION_NAME)+ .revisionConfig(RevisionConfig.builder()+ .buildConfig(buildConfig())+ .serviceConfig(ServiceConfig.builder().executionRoleArn(ROLE).build())+ .build())+ .endpointConfig(EndpointConfig.builder()+ .endpointName("dev")+ .endpointType(EndpointType.HOME_REGION)+ .authType(AuthType.APPLICATION_MANAGED)+ .autoDeploymentMode(AutoDeploymentMode.LATEST_REVISION)+ .build())+ .tags(Map.of("env", "sdk")));++ functionArn = created.functionArn();+ firstRevisionId = created.revision().revisionId();+ assertThat(functionArn).endsWith(":web-function/" + FUNCTION_NAME);+ assertThat(created.stateAsString()).isEqualTo("Active");+ assertThat(created.revision().stateAsString()).isEqualTo("Pending");+ assertThat(created.endpoint().stateAsString()).isEqualTo("Pending");+ assertThat(created.endpoint().domainName()).contains(".lambda-web.");+ assertThat(created.createdAt()).isNotNull();++ lambdaWeb.waiter().waitUntilWebFunctionEndpointActive(r -> r.functionName(FUNCTION_NAME).endpointName("dev"));+ GetWebFunctionEndpointResponse endpoint = lambdaWeb.getWebFunctionEndpoint(r -> r+ .functionName(FUNCTION_NAME).endpointName("dev"));+ assertThat(endpoint.stateAsString()).isEqualTo("Active");+ assertThat(endpoint.revisionWeights()).extracting(RevisionWeight::revisionId).containsExactly(firstRevisionId);+ assertThat(endpoint.regionalEndpoints()).containsKey(TestFixtures.region().id());+ assertThat(endpoint.updateStatusAsString()).isNull();+ }++ @Test+ @Order(2)+ void functionsAreAddressableByNameAndArn() {+ assertThat(lambdaWeb.getWebFunction(r -> r.functionName(functionArn)).functionName()).isEqualTo(FUNCTION_NAME);+ assertThat(lambdaWeb.listWebFunctions(r -> {}).functions())+ .extracting(f -> f.functionName()).contains(FUNCTION_NAME);+ assertThat(lambdaWeb.getWebAccountSettings(r -> {}).accountQuotas().maxEndpointsPerFunction()).isEqualTo(10);++ String foreignRegion = functionArn.replace(":" + TestFixtures.region().id() + ":", ":eu-west-1:");+ assertThatThrownBy(() -> lambdaWeb.getWebFunction(r -> r.functionName(foreignRegion)))+ .isInstanceOf(ValidationException.class)+ .hasMessageContaining("The operation is only allowed in the function's home region eu-west-1.");+ assertThatThrownBy(() -> lambdaWeb.getWebFunction(r -> r.functionName("sdk-test-no-such-web-fn")))+ .isInstanceOf(ResourceNotFoundException.class)+ .hasMessageContaining("does not exist.");+ }++ @Test+ @Order(3)+ void aNewRevisionMovesALatestRevisionEndpoint() {+ CreateWebFunctionRevisionResponse revision = lambdaWeb.createWebFunctionRevision(r -> r+ .functionName(FUNCTION_NAME)+ .description("second")+ .buildConfig(buildConfig())+ .serviceConfig(ServiceConfig.builder().executionRoleArn(ROLE).timeoutSeconds(60)+ .environmentVariables(Map.of("APP_VERSION", "2")).build()));+ secondRevisionId = revision.revisionId();+ assertThat(revision.stateAsString()).isEqualTo("Pending");+ assertThat(revision.serviceConfig().timeoutSeconds()).isEqualTo(60);+ assertThat(revision.serviceConfig().maxConcurrencyPerEnvironment()).isEqualTo(64);+ assertThat(revision.serviceConfig().telemetryConfig().loggingConfig().logGroup())+ .isEqualTo("/aws/lambda/web/" + FUNCTION_NAME);++ lambdaWeb.waiter().waitUntilWebFunctionRevisionActive(r -> r.functionName(FUNCTION_NAME).revisionId(secondRevisionId));+ ListWebFunctionRevisionsResponse revisions = lambdaWeb.listWebFunctionRevisions(r -> r.functionName(FUNCTION_NAME));+ assertThat(revisions.revisions()).extracting(s -> s.revisionId()).containsExactly(secondRevisionId, firstRevisionId);+ assertThat(lambdaWeb.getWebFunctionEndpoint(r -> r.functionName(FUNCTION_NAME).endpointName("dev"))+ .revisionWeights()).extracting(RevisionWeight::revisionId).containsExactly(secondRevisionId);+ }++ @Test+ @Order(4)+ void weightedRoutingAndTheInUseGuard() {+ UpdateWebFunctionEndpointResponse update = lambdaWeb.updateWebFunctionEndpoint(r -> r+ .functionName(FUNCTION_NAME).endpointName("dev")+ .autoDeploymentMode(AutoDeploymentMode.DISABLED)+ .revisionWeights(RevisionWeight.builder().revisionId(firstRevisionId).weight(90).build(),+ RevisionWeight.builder().revisionId(secondRevisionId).weight(10).build()));+ assertThat(update.updateStatusAsString()).isEqualTo("InProgress");+ assertThat(update.revisionWeights()).hasSize(2);++ lambdaWeb.waiter().waitUntilWebFunctionEndpointUpdated(r -> r.functionName(FUNCTION_NAME).endpointName("dev"));+ assertThat(lambdaWeb.getWebFunctionEndpoint(r -> r.functionName(FUNCTION_NAME).endpointName("dev"))+ .updateStatusAsString()).isEqualTo("Successful");++ assertThatThrownBy(() -> lambdaWeb.deleteWebFunctionRevision(r -> r+ .functionName(FUNCTION_NAME).revisionId(firstRevisionId)))+ .isInstanceOf(ConflictException.class)+ .hasMessageContaining("the endpoints [dev] are using it");+ assertThatThrownBy(() -> lambdaWeb.updateWebFunctionEndpoint(r -> r+ .functionName(FUNCTION_NAME).endpointName("dev")+ .revisionWeights(RevisionWeight.builder().revisionId("rev-zzzzz").weight(100).build())))+ .isInstanceOf(ResourceNotFoundException.class)+ .hasMessageContaining("The revision rev-zzzzz does not exist.");+ }++ @Test+ @Order(5)+ void validationErrorsUseTheAwsWording() {+ assertThatThrownBy(() -> lambdaWeb.createWebFunctionRevision(r -> r+ .functionName(FUNCTION_NAME)+ .buildConfig(buildConfig())+ .serviceConfig(ServiceConfig.builder().executionRoleArn(ROLE).timeoutSeconds(2).build())))+ .isInstanceOf(ValidationException.class)+ .hasMessageContaining("1 validation error detected: Value '2' at 'serviceConfig.timeoutSeconds' failed"+ + " to satisfy constraint: Member must have value greater than or equal to 3");+ assertThatThrownBy(() -> lambdaWeb.getWebFunctionRevision(r -> r.functionName(FUNCTION_NAME).revisionId("nope")))+ .isInstanceOf(ValidationException.class)+ .hasMessageContaining("Invalid revision id or ARN 'nope'");+ assertThatThrownBy(() -> lambdaWeb.createWebFunctionEndpoint(r -> r+ .functionName(FUNCTION_NAME).endpointName("prod")+ .endpointType(EndpointType.HOME_REGION).authType(AuthType.APPLICATION_MANAGED)))+ .isInstanceOf(ValidationException.class)+ .hasMessageContaining("The revisionWeights must be specified when the autoDeploymentMode is Disabled.");+ }++ @Test+ @Order(6)+ void tagsAndResourcePolicy() {+ lambdaWeb.tagResource(r -> r.resource(functionArn).tags(Map.of("team", "web")));+ assertThat(lambdaWeb.listTags(r -> r.resource(functionArn)).tags())+ .containsEntry("env", "sdk").containsEntry("team", "web");+ lambdaWeb.untagResource(r -> r.resource(functionArn).tagKeys("env"));+ assertThat(lambdaWeb.listTags(r -> r.resource(functionArn)).tags()).containsOnlyKeys("team");++ String publicPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\","+ + "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + functionArn + "/endpoint/*\"}]}";+ assertThatThrownBy(() -> lambdaWeb.putResourcePolicy(r -> r.resourceArn(functionArn).policy(publicPolicy)))+ .isInstanceOf(ValidationException.class)+ .hasMessageContaining("Lambda blocked the creation of this policy");+ assertThatThrownBy(() -> lambdaWeb.putResourcePolicy(r -> r.resourceArn(functionArn).policy("{}")))+ .isInstanceOf(ValidationException.class)+ .hasMessageContaining("Policy has syntax errors.");++ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":"+ + "{\"AWS\":\"arn:aws:iam::000000000000:root\"},\"Action\":\"lambda:InvokeWebFunctionEndpoint\","+ + "\"Resource\":\"" + functionArn + "/endpoint/*\"}]}";+ PutResourcePolicyResponse put = lambdaWeb.putResourcePolicy(r -> r.resourceArn(functionArn).policy(policy));+ assertThat(put.policy()).isEqualTo(policy);+ assertThat(put.revisionId()).matches("[0-9a-f-]{36}");+ assertThat(lambdaWeb.getResourcePolicy(r -> r.resourceArn(functionArn)).revisionId()).isEqualTo(put.revisionId());+ lambdaWeb.deleteResourcePolicy(r -> r.resourceArn(functionArn).revisionId(put.revisionId()));+ assertThatThrownBy(() -> lambdaWeb.getResourcePolicy(r -> r.resourceArn(functionArn)))+ .isInstanceOf(ResourceNotFoundException.class)+ .hasMessageContaining("The function does not have a policy.");+ }++ @Test+ @Order(7)+ void deleteRemovesTheFunction() {+ lambdaWeb.deleteWebFunction(r -> r.functionName(FUNCTION_NAME));+ lambdaWeb.waiter().waitUntilWebFunctionDeleted(r -> r.functionName(FUNCTION_NAME));+ assertThatThrownBy(() -> lambdaWeb.getWebFunction(r -> r.functionName(FUNCTION_NAME)))+ .isInstanceOf(ResourceNotFoundException.class);+ }+}diff --git a/docs/services/index.md b/docs/services/index.mdindex 7945a4dd3a..c52882c359 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -20,6 +20,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 || [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 55 || [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 |+| [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 || [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 || [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane || [IAM](iam.md) | `POST /` with `Action=` param | Query | 167 |diff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.mdnew file mode 100644index 0000000000..d4bfa6a676--- /dev/null+++ b/docs/services/lambda-web-functions.md@@ -0,0 +1,54 @@+# Lambda Web Functions++**Protocol:** REST JSON+**Endpoint:** `http://localhost:4566/2025-03-07/web-functions/...`++The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the AWS CLI) signs as `lambda`, so it is served under Floci's existing lambda service and is enabled by it. A Web Function owns immutable revisions (code and configuration) and endpoints (a domain name that routes to one or two revisions).++## Supported Actions++<!-- floci:actions:start -->+| Action | Description |+| --- | --- |+| `CreateWebFunction` | Create a function with its first revision and endpoint |+| `ListWebFunctions` | List functions by name; `state` is the only filter |+| `GetWebFunction` | Function detail |+| `DeleteWebFunction` | Delete a function with its revisions and endpoints |+| `CreateWebFunctionRevision` | Create a revision from an S3 object; endpoints in `LatestRevision` mode move to it |+| `ListWebFunctionRevisions` | List revisions, newest first |+| `GetWebFunctionRevision` | Revision detail with the defaults the service fills in |+| `DeleteWebFunctionRevision` | Delete a revision no endpoint routes to |+| `CreateWebFunctionEndpoint` | Create a `HomeRegion`, `MultiRegion` or `PerRegion` endpoint |+| `ListWebFunctionEndpoints` | List endpoints by name |+| `GetWebFunctionEndpoint` | Endpoint detail with its per-region block |+| `UpdateWebFunctionEndpoint` | Change auth type, description, auto-deployment mode, revision weights, scaling and throttling |+| `DeleteWebFunctionEndpoint` | Delete an endpoint |+| `GetWebAccountSettings` | Account quotas and the function count |+| `ListTags` | Tags of a function |+| `TagResource` | Tag a function |+| `UntagResource` | Untag a function |+| `PutResourcePolicy` | Set the function's resource policy with an optimistic `revisionId` |+| `GetResourcePolicy` | Read the resource policy |+| `DeleteResourcePolicy` | Delete the resource policy |+<!-- floci:actions:end -->++## Emulation Behavior++- **Instant convergence:** a revision and an endpoint are stored `Active` and an endpoint update is stored `Successful`. The create and update responses still report the transitional state AWS reports (`Pending`, `updateStatus: InProgress`, and the per-region block as it was before the update), so a waiter sees one poll.+- **Code comes from S3 only.** The object named in `buildConfig.codeConfig.s3Object` must exist in Floci's S3, as on AWS. AWS also requires bucket versioning and a bucket policy for the Lambda service principal. Floci does not check them yet, and the revision does not pin a `versionId` the request did not give yet.+- **Execution role and network connector** ARNs are checked for shape only. The assume-role check AWS makes is not done yet.+- **Resource policies** are checked the way AWS checks them before storing: the document grammar, a `lambda:` action, a `Resource` that names the function, a valid principal, and no public `Allow`. A wildcard principal needs a positive condition (`StringEquals`, `StringLike`, `ArnLike`, `Bool`) on a trusted key such as `aws:PrincipalAccount` or `aws:PrincipalArn`, with no wildcard in the account it names. The policy is not evaluated on requests yet.+- **ARNs** given as identifiers must name the request's region and the caller's account, as on AWS. A revision or endpoint ARN resolves by its id or name only.+- **Page tokens** are base64 cursors that carry the request and the position of the page, not the UUIDs AWS issues. A token reused with other parameters gets the AWS "does not match the request" error, and any other token the "invalid or has expired" error.+- **Domain names** take the form `<id>.001.lambda-web.<region>.<floci host>` and `<id>.lambda-web.global.<floci host>`, with the host and port of `floci.base-url`. A `PerRegion` endpoint gets one domain per region in `regionalEndpoints`.+- **Not implemented yet:** invoking a function through its endpoint domain, execution environments, `IamAuth` on requests, the automatic deletion of revisions past 50, and the `AWS::Lambda::WebFunction*` CloudFormation types. The endpoint domain does not answer requests yet.++### `aws lambda-web deploy`++The CLI's `deploy` command works against Floci with `AWS_ENDPOINT_URL` set:++```bash+AWS_ENDPOINT_URL=http://localhost:4566 aws lambda-web deploy --name my-app --hello-world --create+```++The command passes `--endpoint-url` only to the Lambda Web client. Its STS, S3 and IAM calls use the default endpoints, so the environment variable is what routes them to Floci. The `endpointUrl` it prints is the Floci domain name behind `https://`, which Floci does not serve yet.diff --git a/mkdocs.yml b/mkdocs.ymlindex 69fdeb67a3..27eebbe6a4 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -105,6 +105,7 @@ nav:- DynamoDB: services/dynamodb.md- Lambda: services/lambda.md- Lambda MicroVMs: services/lambda-microvms.md+ - Lambda Web Functions: services/lambda-web-functions.md- API Gateway: services/api-gateway.md- Cognito: services/cognito.md- Cognito Identity: services/cognitoidentity.mddiff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex 4cbc317215..e047555e03 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -45,6 +45,7 @@ import io.github.hectorvent.floci.services.lambda.LambdaController;import io.github.hectorvent.floci.services.lambda.durable.DurableExecutionController;import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsController;import io.github.hectorvent.floci.services.lambdamicrovms.LambdaNetworkConnectorsController;+import io.github.hectorvent.floci.services.lambdaweb.LambdaWebController;import io.github.hectorvent.floci.services.macie2.MacieController;import io.github.hectorvent.floci.services.marketplace.MarketplaceCatalogController;import io.github.hectorvent.floci.services.marketplace.MarketplaceDeploymentController;@@ -147,7 +148,8 @@ public class ResolvedServiceCatalog {Set.of(LambdaController.class,DurableExecutionController.class,LambdaMicrovmsController.class,- LambdaNetworkConnectorsController.class)),+ LambdaNetworkConnectorsController.class,+ LambdaWebController.class)),descriptor("apigateway", "apigateway", config.services().apigateway().enabled(), true,"apigateway", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,protocols(ServiceProtocol.REST_JSON),diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.javaindex dc3e272eb2..d62f73b59d 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java@@ -77,6 +77,28 @@ public class IamActionRegistry {rule("lambda", "POST", ".*/durable-execution-callbacks/.+/heartbeat$","lambda:SendDurableExecutionCallbackHeartbeat"),+ // ── Lambda Web Functions (/2025-03-07, signs as lambda) ─────────────────+ rule("lambda", "PUT", "^/2025-03-07/web-functions$", "lambda:CreateWebFunction"),+ rule("lambda", "POST", "^/2025-03-07/web-functions$", "lambda:ListWebFunctions"),+ rule("lambda", "GET", "^/2025-03-07/web-functions/[^/]+$", "lambda:GetWebFunction"),+ rule("lambda", "DELETE", "^/2025-03-07/web-functions/[^/]+$", "lambda:DeleteWebFunction"),+ rule("lambda", "POST", "^/2025-03-07/web-functions/[^/]+/revisions$", "lambda:CreateWebFunctionRevision"),+ rule("lambda", "POST", "^/2025-03-07/web-functions/[^/]+/list-revisions$", "lambda:ListWebFunctionRevisions"),+ rule("lambda", "GET", "^/2025-03-07/web-functions/[^/]+/revisions/[^/]+$", "lambda:GetWebFunctionRevision"),+ rule("lambda", "DELETE", "^/2025-03-07/web-functions/[^/]+/revisions/[^/]+$", "lambda:DeleteWebFunctionRevision"),+ rule("lambda", "PUT", "^/2025-03-07/web-functions/[^/]+/endpoints$", "lambda:CreateWebFunctionEndpoint"),+ rule("lambda", "POST", "^/2025-03-07/web-functions/[^/]+/list-endpoints$", "lambda:ListWebFunctionEndpoints"),+ rule("lambda", "GET", "^/2025-03-07/web-functions/[^/]+/endpoints/[^/]+$", "lambda:GetWebFunctionEndpoint"),+ rule("lambda", "PATCH", "^/2025-03-07/web-functions/[^/]+/endpoints/[^/]+$", "lambda:UpdateWebFunctionEndpoint"),+ rule("lambda", "DELETE", "^/2025-03-07/web-functions/[^/]+/endpoints/[^/]+$", "lambda:DeleteWebFunctionEndpoint"),+ rule("lambda", "GET", "^/2025-03-07/web-account-settings$", "lambda:GetWebAccountSettings"),+ rule("lambda", "GET", "^/2025-03-07/tags/.+", "lambda:ListTags"),+ rule("lambda", "POST", "^/2025-03-07/tags/.+", "lambda:TagResource"),+ rule("lambda", "DELETE", "^/2025-03-07/tags/.+", "lambda:UntagResource"),+ rule("lambda", "PUT", "^/2025-03-07/resource-policy/.+", "lambda:PutResourcePolicy"),+ rule("lambda", "GET", "^/2025-03-07/resource-policy/.+", "lambda:GetResourcePolicy"),+ rule("lambda", "DELETE", "^/2025-03-07/resource-policy/.+", "lambda:DeleteResourcePolicy"),+// ── DynamoDB (JSON 1.1, action from X-Amz-Target handled separately) ──// Handled via Query-style action extraction in the filterdiff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.javaindex 31166b9ea9..781b7b0615 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java@@ -596,6 +596,10 @@ public class ResourceArnBuilder {* given.*/private String buildLambdaArn(String path, ContainerRequestContext ctx, String region, String accountId) {+ String webFunctionArn = webFunctionArn(path, region, accountId);+ if (webFunctionArn != null) {+ return webFunctionArn;+ }String executionArn = durableExecutionArn(path);if (executionArn == null) {executionArn = durableCallbackExecutionArn(path);@@ -631,6 +635,51 @@ public class ResourceArnBuilder {}}+ /**+ * The resource of a Lambda Web Functions route. An action on a revision or an endpoint is evaluated+ * against that child's ARN; an action on the function, a create of a revision or endpoint, the list of+ * either, and the tag and resource-policy routes against the function's (Lambda Developer Guide,+ * "Lambda Web Function permissions"). ListWebFunctions, GetWebAccountSettings and CreateWebFunction+ * name no resource. Null for every other Lambda route.+ */+ private static String webFunctionArn(String path, String region, String accountId) {+ if (!path.startsWith("/2025-03-07/")) {+ return null;+ }+ String rest = path.substring("/2025-03-07/".length());+ if (rest.startsWith("tags/") || rest.startsWith("resource-policy/")) {+ String arn = rest.substring(rest.indexOf('/') + 1);+ return arn.startsWith("arn:") ? arn : "*";+ }+ if (!rest.startsWith("web-functions/")) {+ return "*";+ }+ List<String> segments = new ArrayList<>(List.of(rest.substring("web-functions/".length()).split("/")));+ if (segments.isEmpty() || segments.getFirst().isEmpty()) {+ return "*";+ }+ String functionArn;+ if (segments.getFirst().startsWith("arn:") && segments.size() > 1) {+ // A function ARN carries one slash: arn:...:web-function/<name>.+ functionArn = segments.get(0) + "/" + segments.get(1);+ segments.subList(0, 2).clear();+ } else {+ functionArn = AwsArnUtils.Arn.of("lambda", region, accountId,+ "web-function/" + segments.getFirst()).toString();+ segments.removeFirst();+ }+ if (segments.size() >= 2 && ("revisions".equals(segments.get(0)) || "endpoints".equals(segments.get(0)))) {+ String child = "revisions".equals(segments.get(0)) ? "revision" : "endpoint";+ String id = String.join("/", segments.subList(1, segments.size()));+ if (id.startsWith("arn:") && id.contains("/" + child + "/")) {+ // A revision or endpoint ARN ends in its id: arn:...:web-function/<name>/revision/<id>.+ id = id.substring(id.lastIndexOf('/') + 1);+ }+ return functionArn + "/" + child + "/" + id;+ }+ return functionArn;+ }+/*** {@code GetFunction}, {@code GetFunctionConfiguration} and {@code ListDurableExecutionsByFunction}* read a function named by a qualified full ARN in the account the ARN names, where the version ordiff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebController.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebController.javanew file mode 100644index 0000000000..0e26866146--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebController.java@@ -0,0 +1,247 @@+package io.github.hectorvent.floci.services.lambdaweb;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.services.lambdaweb.LambdaWebResponses.View;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;+import jakarta.inject.Inject;+import jakarta.ws.rs.Consumes;+import jakarta.ws.rs.DELETE;+import jakarta.ws.rs.GET;+import jakarta.ws.rs.PATCH;+import jakarta.ws.rs.POST;+import jakarta.ws.rs.PUT;+import jakarta.ws.rs.Path;+import jakarta.ws.rs.PathParam;+import jakarta.ws.rs.Produces;+import jakarta.ws.rs.QueryParam;+import jakarta.ws.rs.core.Context;+import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;+import jakarta.ws.rs.core.UriInfo;++import java.util.List;+import java.util.Map;++/**+ * Lambda Web Functions (apiVersion 2025-03-07, rest-json, signs as {@code lambda}). The tag and+ * resource-policy bodies carry {@code Tags}, {@code Policy} and {@code RevisionId}. Every other+ * member is camelCase.+ */+@Path("/2025-03-07")+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.WILDCARD)+public class LambdaWebController {++ private final LambdaWebService service;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;++ @Inject+ public LambdaWebController(LambdaWebService service, RegionResolver regionResolver, ObjectMapper objectMapper) {+ this.service = service;+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ }++ @PUT+ @Path("/web-functions")+ public Response createWebFunction(@Context HttpHeaders headers, String body) {+ String region = regionResolver.resolveRegion(headers);+ WebFunction fn = service.createFunction(region, parse(body));+ WebFunctionRevision revision = fn.revisions.values().iterator().next();+ WebFunctionEndpoint endpoint = fn.endpoints.values().iterator().next();+ return Response.status(202).entity(LambdaWebResponses.createdFunction(fn, revision, endpoint)).build();+ }++ @POST+ @Path("/web-functions")+ public Response listWebFunctions(@Context HttpHeaders headers, String body) {+ String region = regionResolver.resolveRegion(headers);+ PaginatedResult<WebFunction> page = service.listFunctions(region, parse(body));+ return Response.ok(LambdaWebResponses.list("functions",+ page.items().stream().map(LambdaWebResponses::function).toList(), page.nextToken())).build();+ }++ @GET+ @Path("/web-functions/{functionName}")+ public Response getWebFunction(@Context HttpHeaders headers, @PathParam("functionName") String functionName) {+ String region = regionResolver.resolveRegion(headers);+ return Response.ok(LambdaWebResponses.function(service.getFunction(region, functionName))).build();+ }++ @DELETE+ @Path("/web-functions/{functionName}")+ public Response deleteWebFunction(@Context HttpHeaders headers, @PathParam("functionName") String functionName) {+ String region = regionResolver.resolveRegion(headers);+ service.deleteFunction(region, functionName);+ return Response.noContent().build();+ }++ @POST+ @Path("/web-functions/{functionName}/revisions")+ public Response createWebFunctionRevision(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName, String body) {+ String region = regionResolver.resolveRegion(headers);+ WebFunctionRevision revision = service.createRevision(region, functionName, parse(body));+ return Response.status(202).entity(LambdaWebResponses.revision(revision, View.CREATED)).build();+ }++ @POST+ @Path("/web-functions/{functionName}/list-revisions")+ public Response listWebFunctionRevisions(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName, String body) {+ String region = regionResolver.resolveRegion(headers);+ PaginatedResult<WebFunctionRevision> page = service.listRevisions(region, functionName, parse(body));+ return Response.ok(LambdaWebResponses.list("revisions",+ page.items().stream().map(r -> LambdaWebResponses.revisionSummary(r, View.STORED)).toList(),+ page.nextToken())).build();+ }++ @GET+ @Path("/web-functions/{functionName}/revisions/{revisionId}")+ public Response getWebFunctionRevision(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName,+ @PathParam("revisionId") String revisionId) {+ String region = regionResolver.resolveRegion(headers);+ WebFunctionRevision revision = service.getRevision(region, functionName, revisionId);+ return Response.ok(LambdaWebResponses.revision(revision, View.STORED)).build();+ }++ @DELETE+ @Path("/web-functions/{functionName}/revisions/{revisionId}")+ public Response deleteWebFunctionRevision(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName,+ @PathParam("revisionId") String revisionId) {+ String region = regionResolver.resolveRegion(headers);+ service.deleteRevision(region, functionName, revisionId);+ return Response.noContent().build();+ }++ @PUT+ @Path("/web-functions/{functionName}/endpoints")+ public Response createWebFunctionEndpoint(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName, String body) {+ String region = regionResolver.resolveRegion(headers);+ WebFunctionEndpoint endpoint = service.createEndpoint(region, functionName, parse(body));+ return Response.status(202).entity(LambdaWebResponses.endpoint(endpoint, endpoint, View.CREATED)).build();+ }++ @POST+ @Path("/web-functions/{functionName}/list-endpoints")+ public Response listWebFunctionEndpoints(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName, String body) {+ String region = regionResolver.resolveRegion(headers);+ PaginatedResult<WebFunctionEndpoint> page = service.listEndpoints(region, functionName, parse(body));+ return Response.ok(LambdaWebResponses.list("endpoints",+ page.items().stream().map(e -> LambdaWebResponses.endpointSummary(e, View.STORED)).toList(),+ page.nextToken())).build();+ }++ @GET+ @Path("/web-functions/{functionName}/endpoints/{endpointName}")+ public Response getWebFunctionEndpoint(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName,+ @PathParam("endpointName") String endpointName) {+ String region = regionResolver.resolveRegion(headers);+ WebFunctionEndpoint endpoint = service.getEndpoint(region, functionName, endpointName);+ return Response.ok(LambdaWebResponses.endpoint(endpoint, endpoint, View.STORED)).build();+ }++ @PATCH+ @Path("/web-functions/{functionName}/endpoints/{endpointName}")+ public Response updateWebFunctionEndpoint(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName,+ @PathParam("endpointName") String endpointName, String body) {+ String region = regionResolver.resolveRegion(headers);+ LambdaWebService.EndpointUpdate update = service.updateEndpoint(region, functionName, endpointName, parse(body));+ return Response.status(202)+ .entity(LambdaWebResponses.endpoint(update.after(), update.before(), View.UPDATED)).build();+ }++ @DELETE+ @Path("/web-functions/{functionName}/endpoints/{endpointName}")+ public Response deleteWebFunctionEndpoint(@Context HttpHeaders headers,+ @PathParam("functionName") String functionName,+ @PathParam("endpointName") String endpointName) {+ String region = regionResolver.resolveRegion(headers);+ service.deleteEndpoint(region, functionName, endpointName);+ return Response.noContent().build();+ }++ @GET+ @Path("/web-account-settings")+ public Response getWebAccountSettings(@Context HttpHeaders headers) {+ String region = regionResolver.resolveRegion(headers);+ return Response.ok(LambdaWebResponses.accountSettings(service.accountSettings(region))).build();+ }++ @GET+ @Path("/tags/{resource: .+}")+ public Response listTags(@Context HttpHeaders headers, @PathParam("resource") String resource) {+ String region = regionResolver.resolveRegion(headers);+ return Response.ok(Map.of("Tags", service.listTags(region, resource))).build();+ }++ @POST+ @Path("/tags/{resource: .+}")+ public Response tagResource(@Context HttpHeaders headers, @PathParam("resource") String resource, String body) {+ String region = regionResolver.resolveRegion(headers);+ service.tagResource(region, resource, parse(body));+ return Response.noContent().build();+ }++ @DELETE+ @Path("/tags/{resource: .+}")+ public Response untagResource(@Context HttpHeaders headers, @Context UriInfo uriInfo,+ @PathParam("resource") String resource,+ @QueryParam("tagKeys") List<String> tagKeys) {+ String region = regionResolver.resolveRegion(headers);+ service.untagResource(region, resource, tagKeys(uriInfo, tagKeys));+ return Response.noContent().build();+ }++ /** JAX-RS drops an empty query value, which AWS reads as one empty key. */+ private static List<String> tagKeys(UriInfo uriInfo, List<String> tagKeys) {+ if (tagKeys != null && !tagKeys.isEmpty()) {+ return tagKeys;+ }+ String query = uriInfo.getRequestUri().getRawQuery();+ boolean present = query != null && (query.startsWith("tagKeys=") || query.contains("&tagKeys="));+ return present ? List.of("") : null;+ }++ @PUT+ @Path("/resource-policy/{resourceArn: .+}")+ public Response putResourcePolicy(@Context HttpHeaders headers, @PathParam("resourceArn") String resourceArn,+ String body) {+ String region = regionResolver.resolveRegion(headers);+ LambdaWebService.ResourcePolicy policy = service.putResourcePolicy(region, resourceArn, parse(body));+ return Response.ok(LambdaWebResponses.policy(policy)).build();+ }++ @GET+ @Path("/resource-policy/{resourceArn: .+}")+ public Response getResourcePolicy(@Context HttpHeaders headers, @PathParam("resourceArn") String resourceArn) {+ String region = regionResolver.resolveRegion(headers);+ return Response.ok(LambdaWebResponses.policy(service.getResourcePolicy(region, resourceArn))).build();+ }++ @DELETE+ @Path("/resource-policy/{resourceArn: .+}")+ public Response deleteResourcePolicy(@Context HttpHeaders headers, @PathParam("resourceArn") String resourceArn,+ @QueryParam("RevisionId") String revisionId) {+ String region = regionResolver.resolveRegion(headers);+ service.deleteResourcePolicy(region, resourceArn, revisionId);+ return Response.noContent().build();+ }++ private JsonNode parse(String body) {+ return LambdaWebJson.parseBody(objectMapper, body);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebJson.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebJson.javanew file mode 100644index 0000000000..9c73bf109d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebJson.java@@ -0,0 +1,165 @@+package io.github.hectorvent.floci.services.lambdaweb;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * Reads request members with the type checks of the AWS rest-json deserializer. A member of the+ * wrong JSON type is a {@code SerializationException}, a JSON null counts as absent, and a number+ * outside the int range saturates.+ */+final class LambdaWebJson {++ private static final String START_OF_LIST = "Start of list found where not expected";+ private static final String START_OF_STRUCTURE = "Start of structure or map found where not expected.";++ private LambdaWebJson() {+ }++ static JsonNode parseBody(ObjectMapper mapper, String body) {+ JsonNode document;+ try {+ document = mapper.readTree(body == null || body.isBlank() ? "{}" : body);+ } catch (JsonProcessingException e) {+ throw new AwsException("SerializationException", null, 400);+ }+ if (document.isArray()) {+ throw serialization(START_OF_LIST);+ }+ if (!document.isObject()) {+ throw serialization("Expected null");+ }+ return document;+ }++ static boolean present(JsonNode node) {+ return node != null && !node.isNull() && !node.isMissingNode();+ }++ static String text(JsonNode parent, String field) {+ JsonNode value = member(parent, field);+ return value == null ? null : textValue(value);+ }++ static Integer integer(JsonNode parent, String field) {+ JsonNode value = member(parent, field);+ if (value == null) {+ return null;+ }+ if (value.isIntegralNumber()) {+ if (value.canConvertToInt()) {+ return value.intValue();+ }+ return value.bigIntegerValue().signum() > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;+ }+ if (value.isFloatingPointNumber()) {+ return (int) value.doubleValue();+ }+ throw serialization(scalarToken(value) + " can not be converted to an Integer");+ }++ /** A structure member, or null when absent. */+ static JsonNode structure(JsonNode parent, String field) {+ JsonNode value = member(parent, field);+ if (value == null || value.isObject()) {+ return value;+ }+ if (value.isArray()) {+ throw serialization(START_OF_LIST);+ }+ throw serialization("Expected null");+ }++ /** A list member, or null when absent. */+ static JsonNode list(JsonNode parent, String field) {+ JsonNode value = member(parent, field);+ if (value == null || value.isArray()) {+ return value;+ }+ if (value.isObject()) {+ throw serialization(START_OF_STRUCTURE);+ }+ throw serialization("Expected null");+ }++ static List<String> strings(JsonNode list) {+ List<String> out = new ArrayList<>();+ if (list == null) {+ return out;+ }+ for (JsonNode item : list) {+ if (present(item)) {+ out.add(textValue(item));+ }+ }+ return out;+ }++ /**+ * A map of strings, or null when absent. A null value is kept as null when the caller rejects it+ * itself and dropped otherwise, which is what the deserializer does with an absent member.+ */+ static Map<String, String> stringMap(JsonNode parent, String field, boolean keepNulls) {+ JsonNode value = member(parent, field);+ if (value == null) {+ return null;+ }+ if (value.isArray()) {+ throw serialization(START_OF_LIST);+ }+ if (!value.isObject()) {+ throw serialization("Expected map or null");+ }+ Map<String, String> out = new LinkedHashMap<>();+ value.fields().forEachRemaining(entry -> {+ if (present(entry.getValue())) {+ out.put(entry.getKey(), textValue(entry.getValue()));+ } else if (keepNulls) {+ out.put(entry.getKey(), null);+ }+ });+ return out;+ }++ private static JsonNode member(JsonNode parent, String field) {+ JsonNode value = parent == null ? null : parent.get(field);+ return present(value) ? value : null;+ }++ private static String textValue(JsonNode value) {+ if (value.isTextual()) {+ return value.textValue();+ }+ if (value.isArray()) {+ throw serialization(START_OF_LIST);+ }+ if (value.isObject()) {+ throw serialization(START_OF_STRUCTURE);+ }+ throw serialization(scalarToken(value) + " can not be converted to a String");+ }++ private static String scalarToken(JsonNode value) {+ if (value.isArray()) {+ throw serialization(START_OF_LIST);+ }+ if (value.isObject()) {+ throw serialization(START_OF_STRUCTURE);+ }+ if (value.isBoolean()) {+ return value.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE";+ }+ return value.isNumber() ? "NUMBER_VALUE" : "STRING_VALUE";+ }++ private static AwsException serialization(String message) {+ return new AwsException("SerializationException", message, 400);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebResponses.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebResponses.javanew file mode 100644index 0000000000..67118baa17--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebResponses.java@@ -0,0 +1,225 @@+package io.github.hectorvent.floci.services.lambdaweb;++import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;++import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.TreeMap;++/** The wire shapes of Lambda Web responses. AWS emits members in alphabetical order with microsecond timestamps. */+final class LambdaWebResponses {++ private static final DateTimeFormatter TIMESTAMP =+ DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC);++ /** How a resource is shown: as stored, or in the transitional state a create or update reports. */+ enum View { STORED, CREATED, UPDATED }++ private LambdaWebResponses() {+ }++ static Map<String, Object> function(WebFunction fn) {+ Map<String, Object> out = node();+ out.put("functionName", fn.functionName);+ out.put("functionArn", fn.functionArn);+ out.put("state", "Active");+ out.put("stateReason", "The function is active.");+ out.put("createdAt", timestamp(fn.createdAt));+ out.put("updatedAt", timestamp(fn.updatedAt));+ return out;+ }++ /** CreateWebFunction shows its first revision and endpoint as Pending. */+ static Map<String, Object> createdFunction(WebFunction fn, WebFunctionRevision revision,+ WebFunctionEndpoint endpoint) {+ Map<String, Object> out = function(fn);+ out.put("revision", revisionSummary(revision, View.CREATED));+ out.put("endpoint", endpointSummary(endpoint, View.CREATED));+ if (!fn.tags.isEmpty()) {+ out.put("tags", new TreeMap<>(fn.tags));+ }+ return out;+ }++ static Map<String, Object> revisionSummary(WebFunctionRevision revision, View view) {+ Map<String, Object> out = node();+ out.put("revisionArn", revision.revisionArn);+ out.put("revisionId", revision.revisionId);+ putIfPresent(out, "description", revision.description);+ putRevisionState(out, view);+ out.put("createdAt", timestamp(revision.createdAt));+ return out;+ }++ static Map<String, Object> revision(WebFunctionRevision revision, View view) {+ Map<String, Object> out = revisionSummary(revision, view);+ out.put("functionArn", revision.functionArn);+ putIfPresent(out, "kmsKeyArn", revision.kmsKeyArn);+ Map<String, Object> s3Object = node();+ s3Object.put("bucket", revision.buildConfig.bucket);+ s3Object.put("key", revision.buildConfig.key);+ putIfPresent(s3Object, "versionId", revision.buildConfig.versionId);+ Map<String, Object> buildConfig = node();+ buildConfig.put("codeConfig", Map.of("s3Object", s3Object));+ buildConfig.put("runtimeConfig", Map.of("runtime", revision.buildConfig.runtime));+ out.put("buildConfig", buildConfig);+ WebFunctionRevision.ServiceConfig service = revision.serviceConfig;+ Map<String, Object> serviceConfig = node();+ serviceConfig.put("executionRoleArn", service.executionRoleArn);+ serviceConfig.put("timeoutSeconds", service.timeoutSeconds);+ serviceConfig.put("maxConcurrencyPerEnvironment", service.maxConcurrencyPerEnvironment);+ putIfPresent(serviceConfig, "egressNetworkConnectorArn", service.egressNetworkConnectorArn);+ if (service.environmentVariables != null) {+ serviceConfig.put("environmentVariables", new TreeMap<>(service.environmentVariables));+ }+ Map<String, Object> loggingConfig = node();+ loggingConfig.put("logGroup", service.logGroup);+ loggingConfig.put("applicationLogLevel", service.applicationLogLevel);+ loggingConfig.put("systemLogLevel", service.systemLogLevel);+ serviceConfig.put("telemetryConfig", Map.of("loggingConfig", loggingConfig));+ out.put("serviceConfig", serviceConfig);+ return out;+ }++ private static void putRevisionState(Map<String, Object> out, View view) {+ if (view == View.CREATED) {+ out.put("state", "Pending");+ out.put("stateReason", "The revision is being activated.");+ } else {+ out.put("state", "Active");+ out.put("stateReason", "The revision is active.");+ }+ }++ /** The summary has no functionArn and no per-region block. */+ static Map<String, Object> endpointSummary(WebFunctionEndpoint endpoint, View view) {+ Map<String, Object> out = node();+ out.put("endpointArn", endpoint.endpointArn);+ out.put("endpointName", endpoint.endpointName);+ putIfPresent(out, "description", endpoint.description);+ out.put("endpointType", endpoint.endpointType);+ out.put("domainName", endpoint.domainName);+ out.put("authType", endpoint.authType);+ out.put("autoDeploymentMode", endpoint.autoDeploymentMode);+ out.put("revisionWeights", weights(endpoint.revisionWeights));+ out.put("regions", List.copyOf(endpoint.regions));+ putConfigs(out, endpoint);+ putEndpointState(out, endpoint, view, false);+ out.put("createdAt", timestamp(endpoint.createdAt));+ out.put("updatedAt", timestamp(endpoint.updatedAt));+ return out;+ }++ /** An update response shows the per-region block as it was before the update. */+ static Map<String, Object> endpoint(WebFunctionEndpoint endpoint, WebFunctionEndpoint regionalSource, View view) {+ Map<String, Object> out = endpointSummary(endpoint, view);+ out.put("functionArn", endpoint.functionArn);+ Map<String, Object> regional = node();+ for (String region : endpoint.regions) {+ Map<String, Object> entry = node();+ String regionalDomain = regionalSource.regionalDomainNames.get(region);+ if ("PerRegion".equals(endpoint.endpointType) && regionalDomain != null) {+ entry.put("domainName", regionalDomain);+ }+ entry.put("authType", regionalSource.authType);+ entry.put("revisionWeights", weights(regionalSource.revisionWeights));+ putConfigs(entry, regionalSource);+ putEndpointState(entry, regionalSource, view, true);+ regional.put(region, entry);+ }+ out.put("regionalEndpoints", regional);+ return out;+ }++ private static void putConfigs(Map<String, Object> out, WebFunctionEndpoint endpoint) {+ if (endpoint.scalingConfig != null) {+ Map<String, Object> scaling = node();+ putIfPresent(scaling, "maxEnvironments", endpoint.scalingConfig.maxEnvironments);+ out.put("scalingConfig", scaling);+ }+ if (endpoint.throttleConfig != null) {+ Map<String, Object> throttle = node();+ putIfPresent(throttle, "rateLimit", endpoint.throttleConfig.rateLimit);+ out.put("throttleConfig", throttle);+ }+ }++ private static void putEndpointState(Map<String, Object> out, WebFunctionEndpoint endpoint, View view,+ boolean regional) {+ if (view == View.CREATED) {+ out.put("state", "Pending");+ out.put("stateReason", regional+ ? "The endpoint is being activated in the region."+ : "The endpoint is being activated and is not yet invokable in any region.");+ return;+ }+ out.put("state", "Active");+ out.put("stateReason", regional ? "The endpoint is active in the region." : "The endpoint is active and invokable.");+ if (view == View.UPDATED) {+ out.put("updateStatus", "InProgress");+ out.put("updateStatusReason", regional+ ? "The endpoint is being updated in the region."+ : "The endpoint is being updated.");+ } else if (endpoint.updateStatus != null) {+ out.put("updateStatus", endpoint.updateStatus);+ out.put("updateStatusReason", regional ? "The endpoint is updated in the region." : "The endpoint is updated.");+ }+ }++ private static List<Map<String, Object>> weights(List<WebFunctionEndpoint.RevisionWeight> weights) {+ List<Map<String, Object>> out = new ArrayList<>();+ for (WebFunctionEndpoint.RevisionWeight weight : weights) {+ Map<String, Object> entry = node();+ entry.put("revisionId", weight.revisionId);+ entry.put("weight", weight.weight);+ out.add(entry);+ }+ return out;+ }++ static Map<String, Object> accountSettings(LambdaWebService.AccountSettings settings) {+ Map<String, Object> quotas = node();+ quotas.put("maxTotalArmVCpus", LambdaWebService.ACCOUNT_MAX_ARM_VCPUS);+ quotas.put("maxTotalRateLimit", LambdaWebService.ACCOUNT_MAX_RATE_LIMIT);+ quotas.put("maxRevisionsPerFunction", LambdaWebService.MAX_REVISIONS_PER_FUNCTION);+ quotas.put("maxEndpointsPerFunction", LambdaWebService.MAX_ENDPOINTS_PER_FUNCTION);+ Map<String, Object> out = node();+ out.put("accountQuotas", quotas);+ out.put("accountUsage", Map.of("functionCount", settings.functionCount()));+ return out;+ }++ static Map<String, Object> policy(LambdaWebService.ResourcePolicy policy) {+ Map<String, Object> out = node();+ out.put("Policy", policy.policy());+ out.put("RevisionId", policy.revisionId());+ return out;+ }++ static Map<String, Object> list(String member, List<Map<String, Object>> items, String nextToken) {+ Map<String, Object> out = node();+ out.put(member, items);+ putIfPresent(out, "nextToken", nextToken);+ return out;+ }++ static String timestamp(Instant instant) {+ return TIMESTAMP.format(instant);+ }++ private static void putIfPresent(Map<String, Object> out, String member, Object value) {+ if (value != null) {+ out.put(member, value);+ }+ }++ private static Map<String, Object> node() {+ return new TreeMap<>();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.javanew file mode 100644index 0000000000..bbbd40da3d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebService.java@@ -0,0 +1,1405 @@+package io.github.hectorvent.floci.services.lambdaweb;++import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+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.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.Pagination;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.RequestContext;+import io.github.hectorvent.floci.core.common.Resettable;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;+import io.github.hectorvent.floci.services.s3.S3Service;+import jakarta.annotation.PostConstruct;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.context.ContextNotActiveException;+import jakarta.enterprise.inject.Instance;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.net.URI;+import java.nio.charset.StandardCharsets;+import java.time.Instant;+import java.time.temporal.ChronoUnit;+import java.util.ArrayList;+import java.util.Base64;+import java.util.Comparator;+import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import java.util.UUID;+import java.util.concurrent.ConcurrentHashMap;+import java.util.function.Function;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++/**+ * Control plane of Lambda Web Functions (apiVersion 2025-03-07). A revision and an endpoint are+ * stored Active and an endpoint update is stored Successful. The create and update responses show+ * the transitional state AWS reports. Invocation through an endpoint domain is not part of this+ * service.+ */+@ApplicationScoped+public class LambdaWebService implements Resettable {++ private static final Logger LOG = Logger.getLogger(LambdaWebService.class);++ static final String SUPPORTED_RUNTIME = "nodejs24.x";+ static final int MAX_ENDPOINTS_PER_FUNCTION = 10;+ /** Reported as the quota. AWS deletes unused revisions past it instead of rejecting a create. */+ static final int MAX_REVISIONS_PER_FUNCTION = 50;+ static final int ACCOUNT_MAX_ARM_VCPUS = 2000;+ static final int ACCOUNT_MAX_RATE_LIMIT = 100000;+ static final List<Integer> SUPPORTED_RATE_LIMITS = List.of(+ 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,+ 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000);+ static final List<String> AUTH_TYPES = List.of("ApplicationManaged", "IamAuth");+ static final List<String> ENDPOINT_TYPES = List.of("HomeRegion", "MultiRegion", "PerRegion");+ static final List<String> AUTO_DEPLOYMENT_MODES = List.of("LatestRevision", "Disabled");+ static final List<String> APPLICATION_LOG_LEVELS = List.of("TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL");+ static final List<String> SYSTEM_LOG_LEVELS = List.of("DEBUG", "INFO", "WARN");+ static final Set<String> RESERVED_ENVIRONMENT_KEYS = Set.of(+ "AWS_ACCESS_KEY", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SECRET_KEY",+ "AWS_SECURITY_TOKEN", "AWS_SESSION_TOKEN", "AWS_DEFAULT_REGION", "AWS_REGION",+ "AWS_LAMBDA_HTTP_ENDPOINT", "AWS_LAMBDA_RUNTIME_API", "AWS_LAMBDA_INITIALIZATION_TYPE",+ "AWS_LAMBDA_FUNCTION_MEMORY_SIZE", "AWS_LAMBDA_METADATA_API", "AWS_LAMBDA_METADATA_TOKEN");+ /** A wildcard principal pinned by one of these condition keys does not make a policy public. */+ static final Set<String> TRUSTED_CONDITION_KEYS = Set.of(+ "aws:PrincipalAccount", "aws:PrincipalArn", "aws:PrincipalOrgID", "aws:PrincipalOrgPaths",+ "aws:SourceAccount", "aws:SourceArn", "aws:SourceOrgID", "aws:SourceOrgPaths", "aws:SourceVpc",+ "aws:SourceVpcArn", "aws:SourceVpce", "aws:VpceAccount", "aws:VpceOrgID", "aws:VpceOrgPaths",+ "aws:Ec2InstanceSourceVpc", "aws:UserId", "aws:PrincipalServiceName", "aws:PrincipalServiceNamesList",+ "aws:PrincipalIsAWSService", "lambda:SourceFunctionArn");+ /** The operators whose match pins the caller. Negated and IfExists forms do not. */+ private static final Set<String> PINNING_OPERATORS = Set.of(+ "StringEquals", "StringEqualsIgnoreCase", "StringLike", "ArnEquals", "ArnLike", "Bool");+ private static final Set<String> ARN_CONDITION_KEYS = Set.of(+ "aws:PrincipalArn", "aws:SourceArn", "aws:SourceVpcArn", "lambda:SourceFunctionArn");+ private static final Set<String> STATEMENT_KEYS = Set.of(+ "Sid", "Effect", "Principal", "NotPrincipal", "Action", "NotAction", "Resource", "NotResource", "Condition");+ private static final Set<String> PRINCIPAL_KEYS = Set.of("AWS", "Service", "Federated", "CanonicalUser");+ private static final String POLICY_SYNTAX = "Policy has syntax errors.";+ private static final String INVALID_PRINCIPAL = "The provided principal was invalid. Please check the principal and try again.";+ private static final String INVALID_TAGS = "One or more of your tags are invalid. Please ensure none of your tag keys"+ + " start with \"aws:\", none are empty, and there are no duplicate tag keys.";++ private static final Pattern FUNCTION_NAME = Pattern.compile("(?![-_])[a-zA-Z0-9_-]{2,64}(?<![-_])");+ private static final Pattern REVISION_ID = Pattern.compile("rev-[a-z0-9]{5}");+ private static final Pattern WEB_FUNCTION_ARN = Pattern.compile(+ "arn:[^:]+:lambda:([^:]*):([0-9]{12}):web-function/([^/]+)(?:/(revision|endpoint)/([^/]+))?");+ static final Pattern RESOURCE_ARN = Pattern.compile("arn:[^:]+:lambda:[^:]+:\\d{12}:web-function/[^/]+");+ static final Pattern ROLE_ARN = Pattern.compile(+ "arn:(" + AwsArnUtils.PARTITION_REGEX + "):iam::[0-9]{12}:role/[a-zA-Z0-9+=,.@_/-]+");+ static final Pattern KMS_KEY_ARN = Pattern.compile(+ "arn:(" + AwsArnUtils.PARTITION_REGEX + "):kms:[a-z0-9-]+:[0-9]{12}:key/[a-z0-9-]+");+ static final Pattern NETWORK_CONNECTOR_ARN = Pattern.compile(+ "arn:(" + AwsArnUtils.PARTITION_REGEX + "):lambda:[a-z0-9-]+:[0-9]{12}:network-connector:[a-zA-Z0-9_-]+:[0-9]+");+ static final Pattern S3_BUCKET = Pattern.compile("([a-z0-9][a-z0-9\\.\\-]{1,61}[a-z0-9])");+ static final Pattern RUNTIME = Pattern.compile("[a-z][a-z0-9]*(\\.[a-z0-9]+)*");+ static final Pattern ENVIRONMENT_KEY = Pattern.compile("[a-zA-Z]([a-zA-Z0-9_])*");+ static final Pattern LOG_GROUP = Pattern.compile("[a-zA-Z0-9\\.\\-_/#]+");+ static final Pattern REGION = Pattern.compile("([a-z]{2,}-){2,}[0-9]");+ static final Pattern TAG_KEY = Pattern.compile("[a-zA-Z0-9 _\\.:/=+\\-@]+");+ static final Pattern TAG_VALUE = Pattern.compile("[a-zA-Z0-9 _\\.:/=+\\-@]*");+ private static final String TOKEN_MARKER = "lambda-web|";+ static final Pattern POLICY_REVISION_ID = Pattern.compile("[0-9a-f-]{36}");+ private static final Pattern FILTER_NAME = Pattern.compile("[a-zA-Z0-9]+");+ private static final Pattern FILTER_VALUE = Pattern.compile("[a-zA-Z0-9_-]+");+ private static final Pattern PRINCIPAL_AWS = Pattern.compile("[\\w+=,.@\\:-]*");+ private static final Pattern PRINCIPAL_SERVICE = Pattern.compile("[\\w+=,.@-]*");++ /** AWS assigns one shard label per cell. */+ private static final String DOMAIN_SHARD = "001";+ private static final int DOMAIN_ID_LENGTH = 16;+ private static final int DEFAULT_PAGE_SIZE = 50;+ private static final String LOWERCASE_ALNUM = "abcdefghijklmnopqrstuvwxyz0123456789";++ private final RegionResolver regionResolver;+ private final StorageFactory storageFactory;+ private final EmulatorConfig config;+ private final S3Service s3Service;+ private final ObjectMapper objectMapper;+ private final Instance<RequestContext> requestContext;++ /** Keyed {@code region/functionName}. The backend adds the caller's account to every key. */+ private StorageBackend<String, WebFunction> functions;+ private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();++ @Inject+ public LambdaWebService(RegionResolver regionResolver, StorageFactory storageFactory, EmulatorConfig config,+ S3Service s3Service, ObjectMapper objectMapper, Instance<RequestContext> requestContext) {+ this.regionResolver = regionResolver;+ this.storageFactory = storageFactory;+ this.config = config;+ this.s3Service = s3Service;+ this.objectMapper = objectMapper;+ this.requestContext = requestContext;+ }++ @PostConstruct+ void init() {+ initializeStorage();+ }++ void initializeStorage() {+ this.functions = storageFactory.create("lambda", "lambda-web-functions.json",+ new TypeReference<Map<String, WebFunction>>() {});+ }++ @Override+ public void clear() {+ functions.clear();+ }++ /** An endpoint before and after an update. The update response shows both. */+ public record EndpointUpdate(WebFunctionEndpoint before, WebFunctionEndpoint after) {+ }++ public record ResourcePolicy(String policy, String revisionId) {+ }++ public record AccountSettings(int functionCount) {+ }++ // ---------------------------------------------------------------- functions++ public WebFunction createFunction(String region, JsonNode request) {+ String functionName = LambdaWebJson.text(request, "functionName");+ JsonNode revisionConfig = LambdaWebJson.structure(request, "revisionConfig");+ JsonNode endpointConfig = LambdaWebJson.structure(request, "endpointConfig");+ Map<String, String> tags = LambdaWebJson.stringMap(request, "tags", true);+ LambdaWebValidation validation = new LambdaWebValidation();+ validation.required("functionName", functionName);+ if (revisionConfig != null) {+ validateRevisionShape(validation, revisionConfig, "revisionConfig.");+ }+ if (endpointConfig != null) {+ validateEndpointShape(validation, endpointConfig, "endpointConfig.", true);+ }+ validateTagsShape(validation, "tags", tags);+ validation.throwIfAny();++ if (!FUNCTION_NAME.matcher(functionName).matches()) {+ throw invalidFunctionName(functionName);+ }+ if (revisionConfig == null || endpointConfig == null) {+ throw new AwsException("ValidationException",+ "The revisionConfig and endpointConfig must be specified.", 400);+ }+ requireValidTags(tags);+ validateRevisionRules(revisionConfig);+ String accountId = regionResolver.getAccountId();+ WebFunctionEndpoint endpoint = draftEndpoint(region, accountId, functionName, endpointConfig, false);+ String arn = functionArn(region, accountId, functionName);+ synchronized (lockFor(region, functionName)) {+ if (functions.get(key(region, functionName)).isPresent()) {+ throw new AwsException("ConflictException", "The function " + arn + " already exists.", 409);+ }+ WebFunction fn = newFunction(region, accountId, functionName, tags == null ? Map.of() : tags);+ WebFunctionRevision revision = buildRevision(fn, revisionConfig);+ attachEndpoint(region, fn, endpoint, revision);+ fn.revisions.put(revision.revisionId, revision);+ fn.endpoints.put(endpoint.endpointName, endpoint);+ functions.put(key(region, functionName), fn);+ LOG.infov("Created web function {0} with revision {1} and endpoint {2}",+ functionName, revision.revisionId, endpoint.endpointName);+ return copy(fn, WebFunction.class);+ }+ }++ private WebFunction newFunction(String region, String accountId, String functionName, Map<String, String> tags) {+ WebFunction fn = new WebFunction();+ fn.functionName = functionName;+ fn.functionArn = functionArn(region, accountId, functionName);+ fn.createdAt = now();+ fn.updatedAt = fn.createdAt;+ fn.tags = new LinkedHashMap<>(tags);+ return fn;+ }++ public WebFunction getFunction(String region, String functionNameOrArn) {+ String functionName = resolveFunctionName(region, functionNameOrArn, "GetWebFunction");+ synchronized (lockFor(region, functionName)) {+ return copy(function(region, functionName), WebFunction.class);+ }+ }++ public PaginatedResult<WebFunction> listFunctions(String region, JsonNode request) {+ ListRequest list = parseListRequest(request);+ List<WebFunction> snapshots = in(region).stream()+ .map(fn -> {+ synchronized (lockFor(region, fn.functionName)) {+ return copy(fn, WebFunction.class);+ }+ })+ .toList();+ return page(list.matchesState("Active") ? snapshots : List.of(), list,+ scope("ListWebFunctions", region, null, list), f -> f.functionName);+ }++ public void deleteFunction(String region, String functionNameOrArn) {+ String functionName = resolveFunctionName(region, functionNameOrArn, "DeleteWebFunction");+ synchronized (lockFor(region, functionName)) {+ function(region, functionName);+ functions.delete(key(region, functionName));+ }+ LOG.infov("Deleted web function {0}", functionName);+ }++ public AccountSettings accountSettings(String region) {+ String prefix = region + "/";+ return new AccountSettings((int) functions.keys().stream().filter(k -> k.startsWith(prefix)).count());+ }++ // ---------------------------------------------------------------- revisions++ public WebFunctionRevision createRevision(String region, String functionNameOrArn, JsonNode request) {+ LambdaWebValidation validation = new LambdaWebValidation();+ validateRevisionShape(validation, request, "");+ validation.throwIfAny();+ validateRevisionRules(request);+ String functionName = resolveFunctionName(region, functionNameOrArn, "CreateWebFunctionRevision");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ WebFunctionRevision revision = buildRevision(fn, request);+ fn.revisions.put(revision.revisionId, revision);+ for (WebFunctionEndpoint endpoint : fn.endpoints.values()) {+ if ("LatestRevision".equals(endpoint.autoDeploymentMode)) {+ endpoint.revisionWeights = List.of(weight(revision.revisionId, 100));+ endpoint.updatedAt = now();+ }+ }+ fn.updatedAt = now();+ persist(region, fn);+ return copy(revision, WebFunctionRevision.class);+ }+ }++ public WebFunctionRevision getRevision(String region, String functionNameOrArn, String revisionIdOrArn) {+ String functionName = resolveFunctionName(region, functionNameOrArn, "GetWebFunctionRevision");+ String revisionId = resolveRevisionId(region, revisionIdOrArn, "GetWebFunctionRevision");+ synchronized (lockFor(region, functionName)) {+ return copy(revision(function(region, functionName), revisionId), WebFunctionRevision.class);+ }+ }++ public PaginatedResult<WebFunctionRevision> listRevisions(String region, String functionNameOrArn,+ JsonNode request) {+ ListRequest list = parseListRequest(request);+ String functionName = resolveFunctionName(region, functionNameOrArn, "ListWebFunctionRevisions");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ List<WebFunctionRevision> snapshots = fn.revisions.values().stream()+ .map(r -> copy(r, WebFunctionRevision.class))+ .toList();+ return page(list.matchesState("Active") ? snapshots : List.of(), list,+ scope("ListWebFunctionRevisions", region, functionName, list), LambdaWebService::newestFirst);+ }+ }++ /** A cursor that sorts revisions newest first. */+ private static String newestFirst(WebFunctionRevision revision) {+ long micros = ChronoUnit.MICROS.between(Instant.EPOCH, revision.createdAt);+ return String.format(Locale.ROOT, "%019d", Long.MAX_VALUE - micros) + " " + revision.revisionId;+ }++ public void deleteRevision(String region, String functionNameOrArn, String revisionIdOrArn) {+ String functionName = resolveFunctionName(region, functionNameOrArn, "DeleteWebFunctionRevision");+ String revisionId = resolveRevisionId(region, revisionIdOrArn, "DeleteWebFunctionRevision");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ WebFunctionRevision revision = revision(fn, revisionId);+ List<String> using = fn.endpoints.values().stream()+ .filter(e -> e.revisionWeights.stream().anyMatch(w -> w.revisionId.equals(revision.revisionId)))+ .map(e -> e.endpointName)+ .sorted()+ .toList();+ if (!using.isEmpty()) {+ throw new AwsException("ConflictException", "The revision " + revision.revisionId+ + " cannot be deleted because the endpoints " + using+ + " are using it. Update the endpoints to use other revisions first.", 409);+ }+ fn.revisions.remove(revision.revisionId);+ fn.updatedAt = now();+ persist(region, fn);+ }+ }++ private static WebFunctionRevision revision(WebFunction fn, String revisionId) {+ WebFunctionRevision revision = fn.revisions.get(revisionId);+ if (revision == null) {+ throw new AwsException("ResourceNotFoundException",+ "The revision " + revisionId + " does not exist.", 404);+ }+ return revision;+ }++ /** The rules a revision request must meet before the function is looked up. */+ private static void validateRevisionRules(JsonNode request) {+ JsonNode service = LambdaWebJson.structure(request, "serviceConfig");+ Map<String, String> environment = LambdaWebJson.stringMap(service, "environmentVariables", false);+ if (environment != null) {+ List<String> reserved = environment.keySet().stream().filter(RESERVED_ENVIRONMENT_KEYS::contains).toList();+ if (!reserved.isEmpty()) {+ throw new AwsException("ValidationException", "The environmentVariables cannot contain reserved keys."+ + " The request specified the reserved keys " + reserved + ".", 400);+ }+ }+ String logGroup = LambdaWebJson.text(loggingConfig(service), "logGroup");+ if (logGroup != null && logGroup.toLowerCase(Locale.ROOT).startsWith("aws/")) {+ throw new AwsException("ValidationException", "The logGroup " + logGroup+ + " is invalid. Log group names starting with aws/ (case-insensitive) are reserved for AWS.", 400);+ }+ }++ private WebFunctionRevision buildRevision(WebFunction fn, JsonNode request) {+ WebFunctionRevision revision = new WebFunctionRevision();+ revision.buildConfig = buildConfigOf(LambdaWebJson.structure(request, "buildConfig"));+ if (!SUPPORTED_RUNTIME.equals(revision.buildConfig.runtime)) {+ throw new AwsException("ValidationException",+ "The runtime " + revision.buildConfig.runtime + " is invalid.", 400);+ }+ revision.serviceConfig = serviceConfigOf(LambdaWebJson.structure(request, "serviceConfig"),+ "/aws/lambda/web/" + fn.functionName);+ requireCodeObject(revision.buildConfig);+ revision.description = LambdaWebJson.text(request, "description");+ revision.kmsKeyArn = LambdaWebJson.text(request, "kmsKeyArn");+ String revisionId;+ do {+ revisionId = "rev-" + randomLowercase(5);+ } while (fn.revisions.containsKey(revisionId));+ revision.revisionId = revisionId;+ revision.functionArn = fn.functionArn;+ revision.revisionArn = fn.functionArn + "/revision/" + revisionId;+ revision.createdAt = now();+ return revision;+ }++ private static WebFunctionRevision.BuildConfig buildConfigOf(JsonNode build) {+ WebFunctionRevision.BuildConfig out = new WebFunctionRevision.BuildConfig();+ JsonNode s3Object = LambdaWebJson.structure(LambdaWebJson.structure(build, "codeConfig"), "s3Object");+ out.bucket = LambdaWebJson.text(s3Object, "bucket");+ out.key = LambdaWebJson.text(s3Object, "key");+ out.versionId = LambdaWebJson.text(s3Object, "versionId");+ out.runtime = LambdaWebJson.text(LambdaWebJson.structure(build, "runtimeConfig"), "runtime");+ return out;+ }++ private static WebFunctionRevision.ServiceConfig serviceConfigOf(JsonNode service, String defaultLogGroup) {+ WebFunctionRevision.ServiceConfig out = new WebFunctionRevision.ServiceConfig();+ out.executionRoleArn = LambdaWebJson.text(service, "executionRoleArn");+ Integer timeoutSeconds = LambdaWebJson.integer(service, "timeoutSeconds");+ if (timeoutSeconds != null) {+ out.timeoutSeconds = timeoutSeconds;+ }+ Integer maxConcurrency = LambdaWebJson.integer(service, "maxConcurrencyPerEnvironment");+ if (maxConcurrency != null) {+ out.maxConcurrencyPerEnvironment = maxConcurrency;+ }+ out.egressNetworkConnectorArn = LambdaWebJson.text(service, "egressNetworkConnectorArn");+ out.environmentVariables = LambdaWebJson.stringMap(service, "environmentVariables", false);+ JsonNode logging = loggingConfig(service);+ String logGroup = LambdaWebJson.text(logging, "logGroup");+ out.logGroup = logGroup != null ? logGroup : defaultLogGroup;+ String applicationLogLevel = LambdaWebJson.text(logging, "applicationLogLevel");+ if (applicationLogLevel != null) {+ out.applicationLogLevel = applicationLogLevel;+ }+ String systemLogLevel = LambdaWebJson.text(logging, "systemLogLevel");+ if (systemLogLevel != null) {+ out.systemLogLevel = systemLogLevel;+ }+ return out;+ }++ private static JsonNode loggingConfig(JsonNode service) {+ return LambdaWebJson.structure(LambdaWebJson.structure(service, "telemetryConfig"), "loggingConfig");+ }++ /** The code object must exist in the bucket's current version or the version the request pins. */+ private void requireCodeObject(WebFunctionRevision.BuildConfig build) {+ if (s3Service == null) {+ return;+ }+ try {+ s3Service.headObject(build.bucket, build.key, build.versionId);+ } catch (AwsException e) {+ LOG.debugv("Web function code object s3://{0}/{1} is not readable: {2}", build.bucket, build.key,+ e.getMessage());+ throw new AwsException("ValidationException", "The specified S3 object does not exist: s3://"+ + build.bucket + "/" + build.key + ". Verify the object exists in the bucket.", 400);+ }+ }++ private static void validateRevisionShape(LambdaWebValidation v, JsonNode request, String prefix) {+ JsonNode build = LambdaWebJson.structure(request, "buildConfig");+ v.required(prefix + "buildConfig", build);+ if (build != null) {+ JsonNode codeConfig = LambdaWebJson.structure(build, "codeConfig");+ v.required(prefix + "buildConfig.codeConfig", codeConfig);+ if (codeConfig != null) {+ JsonNode s3Object = LambdaWebJson.structure(codeConfig, "s3Object");+ v.required(prefix + "buildConfig.codeConfig.s3Object", s3Object);+ if (s3Object != null) {+ String bucket = LambdaWebJson.text(s3Object, "bucket");+ String key = LambdaWebJson.text(s3Object, "key");+ v.required(prefix + "buildConfig.codeConfig.s3Object.bucket", bucket)+ .length(prefix + "buildConfig.codeConfig.s3Object.bucket", bucket, 3, 63)+ .pattern(prefix + "buildConfig.codeConfig.s3Object.bucket", bucket, S3_BUCKET)+ .required(prefix + "buildConfig.codeConfig.s3Object.key", key)+ .length(prefix + "buildConfig.codeConfig.s3Object.key", key, 1, 1024)+ .length(prefix + "buildConfig.codeConfig.s3Object.versionId",+ LambdaWebJson.text(s3Object, "versionId"), 1, 1024);+ }+ }+ JsonNode runtimeConfig = LambdaWebJson.structure(build, "runtimeConfig");+ v.required(prefix + "buildConfig.runtimeConfig", runtimeConfig);+ if (runtimeConfig != null) {+ String runtime = LambdaWebJson.text(runtimeConfig, "runtime");+ v.required(prefix + "buildConfig.runtimeConfig.runtime", runtime)+ .length(prefix + "buildConfig.runtimeConfig.runtime", runtime, 1, 30)+ .pattern(prefix + "buildConfig.runtimeConfig.runtime", runtime, RUNTIME);+ }+ }+ JsonNode service = LambdaWebJson.structure(request, "serviceConfig");+ v.required(prefix + "serviceConfig", service);+ if (service != null) {+ String role = LambdaWebJson.text(service, "executionRoleArn");+ v.required(prefix + "serviceConfig.executionRoleArn", role)+ .length(prefix + "serviceConfig.executionRoleArn", role, 20, 2048)+ .pattern(prefix + "serviceConfig.executionRoleArn", role, ROLE_ARN)+ .range(prefix + "serviceConfig.timeoutSeconds", LambdaWebJson.integer(service, "timeoutSeconds"), 3, 900)+ .range(prefix + "serviceConfig.maxConcurrencyPerEnvironment",+ LambdaWebJson.integer(service, "maxConcurrencyPerEnvironment"), 1, 128)+ .pattern(prefix + "serviceConfig.egressNetworkConnectorArn",+ LambdaWebJson.text(service, "egressNetworkConnectorArn"), NETWORK_CONNECTOR_ARN);+ Map<String, String> environment = LambdaWebJson.stringMap(service, "environmentVariables", false);+ if (environment != null) {+ v.sensitiveMapKeys(prefix + "serviceConfig.environmentVariables", environment, 1, ENVIRONMENT_KEY)+ .sensitiveMapValues(prefix + "serviceConfig.environmentVariables", environment, 1);+ }+ JsonNode logging = loggingConfig(service);+ if (logging != null) {+ String loggingPath = prefix + "serviceConfig.telemetryConfig.loggingConfig.";+ String logGroup = LambdaWebJson.text(logging, "logGroup");+ v.length(loggingPath + "logGroup", logGroup, 1, 500)+ .pattern(loggingPath + "logGroup", logGroup, LOG_GROUP)+ .enumeration(loggingPath + "applicationLogLevel", LambdaWebJson.text(logging, "applicationLogLevel"),+ APPLICATION_LOG_LEVELS)+ .enumeration(loggingPath + "systemLogLevel", LambdaWebJson.text(logging, "systemLogLevel"),+ SYSTEM_LOG_LEVELS);+ }+ }+ String kmsKeyArn = LambdaWebJson.text(request, "kmsKeyArn");+ v.length(prefix + "description", LambdaWebJson.text(request, "description"), 0, 256)+ .length(prefix + "kmsKeyArn", kmsKeyArn, 20, 2048)+ .pattern(prefix + "kmsKeyArn", kmsKeyArn, KMS_KEY_ARN);+ }++ // ---------------------------------------------------------------- endpoints++ public WebFunctionEndpoint createEndpoint(String region, String functionNameOrArn, JsonNode request) {+ LambdaWebValidation validation = new LambdaWebValidation();+ validateEndpointShape(validation, request, "", true);+ validation.throwIfAny();+ String functionName = resolveFunctionName(region, functionNameOrArn, "CreateWebFunctionEndpoint");+ WebFunctionEndpoint endpoint = draftEndpoint(region, regionResolver.getAccountId(), functionName, request, true);+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ attachEndpoint(region, fn, endpoint, null);+ fn.endpoints.put(endpoint.endpointName, endpoint);+ fn.updatedAt = now();+ persist(region, fn);+ }+ LOG.infov("Created web function endpoint {0} on {1}: {2}", endpoint.endpointName, functionName,+ endpoint.domainName);+ return copy(endpoint, WebFunctionEndpoint.class);+ }++ public WebFunctionEndpoint getEndpoint(String region, String functionNameOrArn, String endpointNameOrArn) {+ String functionName = resolveFunctionName(region, functionNameOrArn, "GetWebFunctionEndpoint");+ String endpointName = resolveEndpointName(region, endpointNameOrArn, "GetWebFunctionEndpoint");+ synchronized (lockFor(region, functionName)) {+ return copy(endpoint(function(region, functionName), endpointName), WebFunctionEndpoint.class);+ }+ }++ public PaginatedResult<WebFunctionEndpoint> listEndpoints(String region, String functionNameOrArn,+ JsonNode request) {+ ListRequest list = parseListRequest(request);+ String functionName = resolveFunctionName(region, functionNameOrArn, "ListWebFunctionEndpoints");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ List<WebFunctionEndpoint> snapshots = fn.endpoints.values().stream()+ .map(e -> copy(e, WebFunctionEndpoint.class))+ .toList();+ return page(list.matchesState("Active") ? snapshots : List.of(), list,+ scope("ListWebFunctionEndpoints", region, functionName, list), e -> e.endpointName);+ }+ }++ public EndpointUpdate updateEndpoint(String region, String functionNameOrArn, String endpointNameOrArn,+ JsonNode request) {+ LambdaWebValidation validation = new LambdaWebValidation();+ validateEndpointShape(validation, request, "", false);+ validation.throwIfAny();+ String mode = LambdaWebJson.text(request, "autoDeploymentMode");+ JsonNode weights = LambdaWebJson.list(request, "revisionWeights");+ String authType = LambdaWebJson.text(request, "authType");+ String description = LambdaWebJson.text(request, "description");+ JsonNode scaling = LambdaWebJson.structure(request, "scalingConfig");+ JsonNode throttle = LambdaWebJson.structure(request, "throttleConfig");+ String functionName = resolveFunctionName(region, functionNameOrArn, "UpdateWebFunctionEndpoint");+ String endpointName = resolveEndpointName(region, endpointNameOrArn, "UpdateWebFunctionEndpoint");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ WebFunctionEndpoint endpoint = endpoint(fn, endpointName);+ WebFunctionEndpoint before = copy(endpoint, WebFunctionEndpoint.class);++ String effectiveMode = mode != null ? mode : endpoint.autoDeploymentMode;+ rejectWeightsWithLatestRevision(effectiveMode, weights);+ List<WebFunctionEndpoint.RevisionWeight> newWeights = null;+ if (mode != null && !mode.equals(endpoint.autoDeploymentMode)) {+ requireModeAllowed(mode, endpoint.endpointType);+ if ("LatestRevision".equals(mode)) {+ newWeights = latestRevision(fn).map(id -> List.of(weight(id, 100))).orElse(null);+ }+ }+ if (weights != null) {+ newWeights = resolveWeights(fn, requestedWeights(weights));+ }+ WebFunctionEndpoint.ScalingConfig newScaling = scaling != null ? scalingConfigOf(scaling) : null;+ WebFunctionEndpoint.ThrottleConfig newThrottle = throttle != null ? throttleConfigOf(throttle) : null;++ if (mode != null) {+ endpoint.autoDeploymentMode = mode;+ }+ if (newWeights != null) {+ endpoint.revisionWeights = newWeights;+ }+ if (authType != null) {+ endpoint.authType = authType;+ }+ if (description != null) {+ endpoint.description = description;+ }+ if (newScaling != null) {+ endpoint.scalingConfig = newScaling;+ }+ if (newThrottle != null) {+ endpoint.throttleConfig = newThrottle;+ }+ endpoint.updateStatus = "Successful";+ endpoint.updatedAt = now();+ fn.updatedAt = endpoint.updatedAt;+ persist(region, fn);+ return new EndpointUpdate(before, copy(endpoint, WebFunctionEndpoint.class));+ }+ }++ public void deleteEndpoint(String region, String functionNameOrArn, String endpointNameOrArn) {+ String functionName = resolveFunctionName(region, functionNameOrArn, "DeleteWebFunctionEndpoint");+ String endpointName = resolveEndpointName(region, endpointNameOrArn, "DeleteWebFunctionEndpoint");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ WebFunctionEndpoint endpoint = endpoint(fn, endpointName);+ fn.endpoints.remove(endpoint.endpointName);+ fn.updatedAt = now();+ persist(region, fn);+ }+ }++ private static WebFunctionEndpoint endpoint(WebFunction fn, String endpointName) {+ WebFunctionEndpoint endpoint = fn.endpoints.get(endpointName);+ if (endpoint == null) {+ throw new AwsException("ResourceNotFoundException",+ "The endpoint " + endpointName + " does not exist.", 404);+ }+ return endpoint;+ }++ /**+ * The endpoint a request describes, checked against every rule that does not need the function.+ * {@code revisionWeights} holds the requested weights until {@link #attachEndpoint} resolves them.+ */+ private static WebFunctionEndpoint draftEndpoint(String region, String accountId, String functionName,+ JsonNode request, boolean standalone) {+ String endpointName = LambdaWebJson.text(request, "endpointName");+ if (!FUNCTION_NAME.matcher(endpointName).matches()) {+ throw new AwsException("ValidationException", "The endpoint ARN " + endpointName+ + " with the function name " + functionName + ", the region " + region+ + " and the account id " + accountId + " is invalid.", 400);+ }+ String endpointType = LambdaWebJson.text(request, "endpointType");+ String mode = LambdaWebJson.text(request, "autoDeploymentMode");+ if (mode == null) {+ mode = "Disabled";+ }+ requireModeAllowed(mode, endpointType);+ JsonNode weights = LambdaWebJson.list(request, "revisionWeights");+ rejectWeightsWithLatestRevision(mode, weights);+ if (standalone && "Disabled".equals(mode) && weights == null) {+ throw new AwsException("ValidationException",+ "The revisionWeights must be specified when the autoDeploymentMode is Disabled.", 400);+ }+ WebFunctionEndpoint endpoint = new WebFunctionEndpoint();+ endpoint.endpointName = endpointName;+ endpoint.description = LambdaWebJson.text(request, "description");+ endpoint.endpointType = endpointType;+ endpoint.authType = LambdaWebJson.text(request, "authType");+ endpoint.autoDeploymentMode = mode;+ endpoint.regions = resolveRegions(region, endpointType, LambdaWebJson.list(request, "regions"));+ endpoint.revisionWeights = weights == null ? List.of() : requestedWeights(weights);+ JsonNode scaling = LambdaWebJson.structure(request, "scalingConfig");+ if (scaling != null) {+ endpoint.scalingConfig = scalingConfigOf(scaling);+ }+ JsonNode throttle = LambdaWebJson.structure(request, "throttleConfig");+ if (throttle != null) {+ endpoint.throttleConfig = throttleConfigOf(throttle);+ }+ return endpoint;+ }++ /**+ * Finishes a draft against its function. The first endpoint of CreateWebFunction routes to+ * {@code initialRevision}. A standalone endpoint routes to the requested weights, or to the+ * latest revision in LatestRevision mode.+ */+ private void attachEndpoint(String region, WebFunction fn, WebFunctionEndpoint endpoint,+ WebFunctionRevision initialRevision) {+ if (fn.endpoints.containsKey(endpoint.endpointName)) {+ throw new AwsException("ConflictException", "The endpoint " + endpoint.endpointName + " already exists.", 409);+ }+ if (fn.endpoints.size() >= MAX_ENDPOINTS_PER_FUNCTION) {+ throw new AwsException("ServiceQuotaExceededException", "The function " + fn.functionArn+ + " has reached the maxEndpointsPerFunction quota of " + MAX_ENDPOINTS_PER_FUNCTION + ".", 402);+ }+ if (initialRevision != null) {+ endpoint.revisionWeights = List.of(weight(initialRevision.revisionId, 100));+ } else if (!endpoint.revisionWeights.isEmpty()) {+ endpoint.revisionWeights = resolveWeights(fn, endpoint.revisionWeights);+ } else {+ endpoint.revisionWeights = latestRevision(fn).map(id -> List.of(weight(id, 100))).orElse(List.of());+ }+ endpoint.endpointArn = fn.functionArn + "/endpoint/" + endpoint.endpointName;+ endpoint.functionArn = fn.functionArn;+ String host = URI.create(config.effectiveBaseUrl()).getAuthority();+ if ("MultiRegion".equals(endpoint.endpointType)) {+ endpoint.domainName = randomLowercase(DOMAIN_ID_LENGTH) + ".lambda-web.global." + host;+ } else {+ for (String each : endpoint.regions) {+ endpoint.regionalDomainNames.put(each, regionalDomain(each, host));+ }+ endpoint.domainName = endpoint.regionalDomainNames.get(region);+ }+ endpoint.createdAt = now();+ endpoint.updatedAt = endpoint.createdAt;+ }++ private static String regionalDomain(String region, String host) {+ return randomLowercase(DOMAIN_ID_LENGTH) + "." + DOMAIN_SHARD + ".lambda-web." + region + "." + host;+ }++ private static void requireModeAllowed(String mode, String endpointType) {+ if ("LatestRevision".equals(mode) && !"HomeRegion".equals(endpointType)) {+ throw new AwsException("ValidationException", "The autoDeploymentMode can only be Disabled when the"+ + " endpointType is " + endpointType + ".", 400);+ }+ }++ private static void rejectWeightsWithLatestRevision(String mode, JsonNode weights) {+ if ("LatestRevision".equals(mode) && weights != null) {+ throw new AwsException("ValidationException",+ "The revisionWeights cannot be specified when the autoDeploymentMode is LatestRevision.", 400);+ }+ }++ /** The home region leads the list and is added when absent. */+ private static List<String> resolveRegions(String home, String endpointType, JsonNode requested) {+ LinkedHashSet<String> regions = new LinkedHashSet<>();+ regions.add(home);+ regions.addAll(LambdaWebJson.strings(requested));+ List<String> resolved = new ArrayList<>(regions);+ if ("HomeRegion".equals(endpointType) && resolved.size() > 1) {+ throw new AwsException("ValidationException", "The endpointType HomeRegion supports only the home region "+ + home + ". The request results in the regions " + resolved + ".", 400);+ }+ if (!"HomeRegion".equals(endpointType) && resolved.size() < 2) {+ throw new AwsException("ValidationException", "The endpointType " + endpointType+ + " requires at least 2 distinct regions. The home region " + home+ + " is added automatically, so specify at least 1 additional region."+ + " The request results in the regions " + resolved + ".", 400);+ }+ return resolved;+ }++ /** The weights of a request, unique and totalling 100. Whether the revisions exist is checked against the function. */+ private static List<WebFunctionEndpoint.RevisionWeight> requestedWeights(JsonNode weights) {+ List<WebFunctionEndpoint.RevisionWeight> out = new ArrayList<>();+ Set<String> ids = new LinkedHashSet<>();+ int total = 0;+ for (JsonNode node : weights) {+ WebFunctionEndpoint.RevisionWeight weight = weight(LambdaWebJson.text(node, "revisionId"),+ LambdaWebJson.integer(node, "weight"));+ ids.add(weight.revisionId);+ total += weight.weight;+ out.add(weight);+ }+ if (ids.size() != out.size() || total != 100) {+ throw new AwsException("ValidationException",+ "The revisionWeights must contain unique revisionIds, and the weights must total exactly 100.", 400);+ }+ return out;+ }++ private static List<WebFunctionEndpoint.RevisionWeight> resolveWeights(WebFunction fn,+ List<WebFunctionEndpoint.RevisionWeight> weights) {+ for (WebFunctionEndpoint.RevisionWeight weight : weights) {+ if (!fn.revisions.containsKey(weight.revisionId)) {+ throw new AwsException("ResourceNotFoundException",+ "The revision " + weight.revisionId + " does not exist.", 404);+ }+ }+ return List.copyOf(weights);+ }++ private static Optional<String> latestRevision(WebFunction fn) {+ return fn.revisions.values().stream()+ .max(Comparator.comparing((WebFunctionRevision r) -> r.createdAt))+ .map(r -> r.revisionId);+ }++ private static WebFunctionEndpoint.RevisionWeight weight(String revisionId, int weight) {+ WebFunctionEndpoint.RevisionWeight out = new WebFunctionEndpoint.RevisionWeight();+ out.revisionId = revisionId;+ out.weight = weight;+ return out;+ }++ private static WebFunctionEndpoint.ScalingConfig scalingConfigOf(JsonNode node) {+ WebFunctionEndpoint.ScalingConfig out = new WebFunctionEndpoint.ScalingConfig();+ out.maxEnvironments = LambdaWebJson.integer(node, "maxEnvironments");+ return out;+ }++ private static WebFunctionEndpoint.ThrottleConfig throttleConfigOf(JsonNode node) {+ Integer rateLimit = LambdaWebJson.integer(node, "rateLimit");+ if (rateLimit != null && !SUPPORTED_RATE_LIMITS.contains(rateLimit)) {+ throw new AwsException("ValidationException", "The rateLimit " + rateLimit+ + " is invalid. Supported rate limits are: " + SUPPORTED_RATE_LIMITS + ".", 400);+ }+ WebFunctionEndpoint.ThrottleConfig out = new WebFunctionEndpoint.ThrottleConfig();+ out.rateLimit = rateLimit;+ return out;+ }++ private static void validateEndpointShape(LambdaWebValidation v, JsonNode request, String prefix, boolean create) {+ String endpointName = LambdaWebJson.text(request, "endpointName");+ String endpointType = LambdaWebJson.text(request, "endpointType");+ String authType = LambdaWebJson.text(request, "authType");+ if (create) {+ v.required(prefix + "endpointType", endpointType)+ .required(prefix + "endpointName", endpointName)+ .required(prefix + "authType", authType);+ }+ v.length(prefix + "endpointName", endpointName, 1, 256)+ .enumeration(prefix + "endpointType", endpointType, ENDPOINT_TYPES)+ .enumeration(prefix + "authType", authType, AUTH_TYPES)+ .enumeration(prefix + "autoDeploymentMode", LambdaWebJson.text(request, "autoDeploymentMode"),+ AUTO_DEPLOYMENT_MODES)+ .length(prefix + "description", LambdaWebJson.text(request, "description"), 0, 256);+ JsonNode regions = LambdaWebJson.list(request, "regions");+ if (regions != null) {+ v.listSize(prefix + "regions", regions.size(), 1, 100);+ int index = 1;+ for (String region : LambdaWebJson.strings(regions)) {+ v.length(prefix + "regions." + index + ".member", region, 1, 50)+ .pattern(prefix + "regions." + index + ".member", region, REGION);+ index++;+ }+ }+ JsonNode weights = LambdaWebJson.list(request, "revisionWeights");+ if (weights != null) {+ v.listSize(prefix + "revisionWeights", weights.size(), 1, 2);+ int index = 1;+ for (JsonNode weight : weights) {+ String member = prefix + "revisionWeights." + index + ".member.";+ String revisionId = LambdaWebJson.text(weight, "revisionId");+ Integer value = LambdaWebJson.integer(weight, "weight");+ v.required(member + "revisionId", revisionId)+ .length(member + "revisionId", revisionId, 1, 256)+ .required(member + "weight", value)+ .range(member + "weight", value, 1, 100);+ index++;+ }+ }+ JsonNode scaling = LambdaWebJson.structure(request, "scalingConfig");+ if (scaling != null) {+ v.range(prefix + "scalingConfig.maxEnvironments", LambdaWebJson.integer(scaling, "maxEnvironments"), 2, 10000);+ }+ JsonNode throttle = LambdaWebJson.structure(request, "throttleConfig");+ if (throttle != null) {+ v.range(prefix + "throttleConfig.rateLimit", LambdaWebJson.integer(throttle, "rateLimit"), 0, Integer.MAX_VALUE);+ }+ }++ // ---------------------------------------------------------------- tags++ public Map<String, String> listTags(String region, String resourceArn) {+ new LambdaWebValidation().pattern("resource", resourceArn, RESOURCE_ARN).throwIfAny();+ String functionName = resolveFunctionName(region, resourceArn, "ListTags");+ synchronized (lockFor(region, functionName)) {+ return new LinkedHashMap<>(function(region, functionName).tags);+ }+ }++ public void tagResource(String region, String resourceArn, JsonNode request) {+ Map<String, String> tags = LambdaWebJson.stringMap(request, "Tags", true);+ LambdaWebValidation validation = new LambdaWebValidation();+ validation.pattern("resource", resourceArn, RESOURCE_ARN).required("tags", tags);+ validateTagsShape(validation, "tags", tags);+ validation.throwIfAny();+ requireValidTags(tags);+ String functionName = resolveFunctionName(region, resourceArn, "TagResource");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ fn.tags.putAll(tags);+ fn.updatedAt = now();+ persist(region, fn);+ }+ }++ public void untagResource(String region, String resourceArn, List<String> tagKeys) {+ LambdaWebValidation validation = new LambdaWebValidation();+ validation.pattern("resource", resourceArn, RESOURCE_ARN);+ if (tagKeys == null) {+ validation.required("tagKeys", null);+ } else {+ validation.listSize("tagKeys", tagKeys.size(), 1, 200).listMembers("tagKeys", tagKeys, 1, 128, TAG_KEY);+ }+ validation.throwIfAny();+ String functionName = resolveFunctionName(region, resourceArn, "UntagResource");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ tagKeys.forEach(fn.tags::remove);+ fn.updatedAt = now();+ persist(region, fn);+ }+ }++ private static void validateTagsShape(LambdaWebValidation v, String path, Map<String, String> tags) {+ if (tags == null || tags.isEmpty()) {+ return;+ }+ Map<String, String> present = new LinkedHashMap<>();+ tags.forEach((key, value) -> present.put(key, value == null ? "" : value));+ v.mapKeys(path, present, 1, 128, TAG_KEY).mapValues(path, present, 0, 256, TAG_VALUE);+ }++ private static void requireValidTags(Map<String, String> tags) {+ if (tags == null) {+ return;+ }+ boolean invalid = tags.entrySet().stream()+ .anyMatch(e -> e.getValue() == null || e.getKey().toLowerCase(Locale.ROOT).startsWith("aws:"));+ if (invalid) {+ throw new AwsException("ValidationException", INVALID_TAGS, 400);+ }+ }++ // ---------------------------------------------------------------- resource policy++ public ResourcePolicy putResourcePolicy(String region, String resourceArn, JsonNode request) {+ String policy = LambdaWebJson.text(request, "Policy");+ String revisionId = LambdaWebJson.text(request, "RevisionId");+ new LambdaWebValidation().pattern("resourceArn", resourceArn, RESOURCE_ARN)+ .required("policy", policy)+ .length("policy", policy, 1, 20480)+ .pattern("revisionId", revisionId, POLICY_REVISION_ID)+ .throwIfAny();+ validatePolicy(policy, resourceArn);+ String functionName = resolveFunctionName(region, resourceArn, "PutResourcePolicy");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ if (revisionId != null && !revisionId.equals(fn.policyRevisionId)) {+ throw new AwsException("ConflictException", "The policy was updated or deleted by another request."+ + " Try again with the latest policy revisionId.", 409);+ }+ fn.policy = policy;+ fn.policyRevisionId = UUID.randomUUID().toString();+ fn.updatedAt = now();+ persist(region, fn);+ return new ResourcePolicy(fn.policy, fn.policyRevisionId);+ }+ }++ public ResourcePolicy getResourcePolicy(String region, String resourceArn) {+ new LambdaWebValidation().pattern("resourceArn", resourceArn, RESOURCE_ARN).throwIfAny();+ WebFunction fn = function(region, resolveFunctionName(region, resourceArn, "GetResourcePolicy"));+ if (fn.policy == null) {+ throw noPolicy();+ }+ return new ResourcePolicy(fn.policy, fn.policyRevisionId);+ }++ public void deleteResourcePolicy(String region, String resourceArn, String revisionId) {+ new LambdaWebValidation().pattern("resourceArn", resourceArn, RESOURCE_ARN)+ .pattern("revisionId", revisionId, POLICY_REVISION_ID)+ .throwIfAny();+ String functionName = resolveFunctionName(region, resourceArn, "DeleteResourcePolicy");+ synchronized (lockFor(region, functionName)) {+ WebFunction fn = function(region, functionName);+ if (fn.policy == null) {+ throw noPolicy();+ }+ if (revisionId != null && !revisionId.equals(fn.policyRevisionId)) {+ throw new AwsException("ConflictException", "The policy was updated by another request. Try again.", 409);+ }+ fn.policy = null;+ fn.policyRevisionId = null;+ fn.updatedAt = now();+ persist(region, fn);+ }+ }++ private static AwsException noPolicy() {+ return new AwsException("ResourceNotFoundException", "The function does not have a policy.", 404);+ }++ /** The checks AWS runs on a policy document before it looks the function up. */+ private void validatePolicy(String policy, String functionArn) {+ JsonNode document;+ try {+ document = objectMapper.readTree(policy);+ } catch (Exception e) {+ throw policySyntax();+ }+ if (document == null || !document.isObject()) {+ throw policySyntax();+ }+ JsonNode statements = document.get("Statement");+ List<JsonNode> each = new ArrayList<>();+ if (statements != null && statements.isArray()) {+ statements.forEach(each::add);+ } else if (statements != null && statements.isObject()) {+ each.add(statements);+ }+ if (each.isEmpty()) {+ throw policySyntax();+ }+ for (JsonNode statement : each) {+ validateStatement(statement, functionArn);+ }+ }++ private static void validateStatement(JsonNode statement, String functionArn) {+ if (!statement.isObject()) {+ throw policySyntax();+ }+ if (!statement.has("Effect")) {+ throw new AwsException("ValidationException", "Effect must be explicitly available for a statement", 400);+ }+ Iterator<String> keys = statement.fieldNames();+ while (keys.hasNext()) {+ if (!STATEMENT_KEYS.contains(keys.next())) {+ throw new AwsException("ValidationException", "Syntax error at position (-1,-1)", 400);+ }+ }+ String effect = statement.path("Effect").asText();+ if (!effect.equalsIgnoreCase("Allow") && !effect.equalsIgnoreCase("Deny")) {+ throw policySyntax();+ }+ if (statement.has("NotPrincipal") || statement.has("NotAction") || statement.has("NotResource")) {+ throw policySyntax();+ }+ JsonNode principal = statement.get("Principal");+ validatePrincipal(principal);+ for (String action : policyValues(statement.get("Action"))) {+ if (!action.startsWith("lambda:")) {+ throw policySyntax();+ }+ }+ for (String resource : policyValues(statement.get("Resource"))) {+ if (!resource.equals(functionArn) && !resource.startsWith(functionArn + "/")) {+ throw policySyntax();+ }+ }+ if (effect.equalsIgnoreCase("Allow") && isWildcardPrincipal(principal)+ && !hasTrustedCondition(statement.path("Condition"))) {+ throw new AwsException("ValidationException", "Lambda blocked the creation of this policy"+ + " because it would grant public access to your function.", 400);+ }+ }++ private static void validatePrincipal(JsonNode principal) {+ if (principal == null || principal.isNull() || (principal.isObject() && principal.isEmpty())) {+ throw new AwsException("ValidationException", INVALID_PRINCIPAL, 400);+ }+ if (principal.isTextual()) {+ if (!"*".equals(principal.textValue())) {+ throw policySyntax();+ }+ return;+ }+ if (!principal.isObject()) {+ throw policySyntax();+ }+ Iterator<Map.Entry<String, JsonNode>> fields = principal.fields();+ while (fields.hasNext()) {+ Map.Entry<String, JsonNode> field = fields.next();+ if (!PRINCIPAL_KEYS.contains(field.getKey())) {+ throw policySyntax();+ }+ Pattern allowed = "Service".equals(field.getKey()) ? PRINCIPAL_SERVICE : PRINCIPAL_AWS;+ if (field.getValue().isArray() && field.getValue().isEmpty()) {+ throw new AwsException("ValidationException", INVALID_PRINCIPAL, 400);+ }+ for (String value : policyValues(field.getValue())) {+ if (!"*".equals(value) && !allowed.matcher(value).matches()) {+ throw new AwsException("ValidationException", "The provided input'" + value+ + "'was invalid. Member must satisfy expression: " + allowed.pattern()+ + " Please check your input and try again.", 400);+ }+ if ("Service".equals(field.getKey()) && "*".equals(value)) {+ throw new AwsException("ValidationException", "The provided input'*'was invalid."+ + " Member must satisfy expression: " + PRINCIPAL_SERVICE.pattern()+ + " Please check your input and try again.", 400);+ }+ }+ }+ }++ /** A string or a list of strings. Anything else is a syntax error, and so is an absent member. */+ private static List<String> policyValues(JsonNode node) {+ if (node == null || node.isNull()) {+ throw policySyntax();+ }+ if (node.isTextual()) {+ return List.of(node.textValue());+ }+ if (!node.isArray()) {+ throw policySyntax();+ }+ List<String> values = new ArrayList<>();+ for (JsonNode item : node) {+ if (!item.isTextual()) {+ throw policySyntax();+ }+ values.add(item.textValue());+ }+ if (values.isEmpty()) {+ throw policySyntax();+ }+ return values;+ }++ /** AWS counts a bare "*" and a "*" under AWS as public. Service and Federated wildcards are not. */+ private static boolean isWildcardPrincipal(JsonNode principal) {+ if (principal.isTextual()) {+ return "*".equals(principal.textValue());+ }+ JsonNode aws = principal.get("AWS");+ return aws != null && policyValues(aws).contains("*");+ }++ private static boolean hasTrustedCondition(JsonNode condition) {+ if (!condition.isObject()) {+ return false;+ }+ Iterator<Map.Entry<String, JsonNode>> operators = condition.fields();+ while (operators.hasNext()) {+ Map.Entry<String, JsonNode> operator = operators.next();+ if (!PINNING_OPERATORS.contains(operator.getKey())) {+ continue;+ }+ boolean pattern = operator.getKey().endsWith("Like") || "ArnEquals".equals(operator.getKey());+ Iterator<Map.Entry<String, JsonNode>> keys = operator.getValue().fields();+ while (keys.hasNext()) {+ Map.Entry<String, JsonNode> key = keys.next();+ if (TRUSTED_CONDITION_KEYS.contains(key.getKey()) && (!pattern || pinned(key.getKey(), key.getValue()))) {+ return true;+ }+ }+ }+ return false;+ }++ /** Under a pattern operator a value pins the caller only without a wildcard, or none in an ARN's account. */+ private static boolean pinned(String key, JsonNode values) {+ List<String> each = new ArrayList<>();+ if (values.isArray()) {+ values.forEach(value -> each.add(value.asText()));+ } else {+ each.add(values.asText());+ }+ for (String value : each) {+ String checked = value;+ if (ARN_CONDITION_KEYS.contains(key)) {+ String[] fields = value.split(":", 6);+ if (fields.length < 6) {+ return false;+ }+ checked = fields[4];+ }+ if (checked.contains("*") || checked.contains("?")) {+ return false;+ }+ }+ return !each.isEmpty();+ }++ private static AwsException policySyntax() {+ return new AwsException("ValidationException", POLICY_SYNTAX, 400);+ }++ // ---------------------------------------------------------------- identifiers++ private WebFunction function(String region, String functionName) {+ WebFunction fn = functions.get(key(region, functionName)).orElse(null);+ if (fn == null) {+ throw new AwsException("ResourceNotFoundException",+ "The function " + functionArn(region, regionResolver.getAccountId(), functionName)+ + " does not exist.", 404);+ }+ return fn;+ }++ /** A function given as a name or as its ARN. A child ARN is not a function identifier. */+ String resolveFunctionName(String region, String functionNameOrArn, String action) {+ if (functionNameOrArn == null) {+ throw invalidFunctionName(null);+ }+ Matcher arn = WEB_FUNCTION_ARN.matcher(functionNameOrArn);+ String name = functionNameOrArn;+ if (arn.matches()) {+ if (arn.group(4) != null) {+ throw invalidFunctionName(functionNameOrArn);+ }+ requireOwn(region, arn, functionNameOrArn, action);+ name = arn.group(3);+ }+ if (!FUNCTION_NAME.matcher(name).matches()) {+ throw invalidFunctionName(functionNameOrArn);+ }+ return name;+ }++ /** A revision given as an id or as any revision ARN. AWS reads only the id off the ARN. */+ String resolveRevisionId(String region, String revisionIdOrArn, String action) {+ String id = revisionIdOrArn;+ Matcher arn = revisionIdOrArn == null ? null : WEB_FUNCTION_ARN.matcher(revisionIdOrArn);+ if (arn != null && arn.matches()) {+ if (!"revision".equals(arn.group(4))) {+ throw invalidRevisionId(revisionIdOrArn);+ }+ requireOwn(region, arn, revisionIdOrArn, action);+ id = arn.group(5);+ }+ if (id == null || !REVISION_ID.matcher(id).matches()) {+ throw invalidRevisionId(revisionIdOrArn);+ }+ return id;+ }++ /** An endpoint given as a name or as any endpoint ARN. AWS reads only the name off the ARN. */+ String resolveEndpointName(String region, String endpointNameOrArn, String action) {+ Matcher arn = endpointNameOrArn == null ? null : WEB_FUNCTION_ARN.matcher(endpointNameOrArn);+ if (arn == null || !arn.matches()) {+ return endpointNameOrArn;+ }+ if (!"endpoint".equals(arn.group(4))) {+ throw new AwsException("ValidationException", "Invalid endpoint name or ARN '" + endpointNameOrArn + "'", 400);+ }+ requireOwn(region, arn, endpointNameOrArn, action);+ return arn.group(5);+ }++ private void requireOwn(String region, Matcher arn, String givenArn, String action) {+ if (!region.equals(arn.group(1))) {+ throw new AwsException("ValidationException",+ "The operation is only allowed in the function's home region " + arn.group(1) + ".", 400);+ }+ String callerAccount = regionResolver.getAccountId();+ if (!callerAccount.equals(arn.group(2))) {+ String user = regionResolver.buildGlobalArn("iam", callerAccount, "user/" + accessKeyId());+ throw new AwsException("AccessDeniedException", "User: " + user + " is not authorized to perform: lambda:"+ + action + " on resource: " + givenArn + " because no resource-based policy allows the lambda:"+ + action + " action", 403);+ }+ }++ private String accessKeyId() {+ if (requestContext != null) {+ try {+ String akid = requestContext.get().getAccessKeyId();+ if (akid != null) {+ return akid;+ }+ } catch (ContextNotActiveException ignored) {+ // Outside a request there is no caller key. The placeholder below names the account only.+ }+ }+ return "unknown";+ }++ private static AwsException invalidFunctionName(String functionName) {+ return new AwsException("ValidationException", "Invalid function name or ARN '" + functionName + "'", 400);+ }++ private static AwsException invalidRevisionId(String revisionId) {+ return new AwsException("ValidationException", "Invalid revision id or ARN '" + revisionId + "'", 400);+ }++ private String functionArn(String region, String accountId, String functionName) {+ return regionResolver.buildArn("lambda", region, accountId, "web-function/" + functionName);+ }++ /** A deep copy, so a caller never holds the stored object a later request mutates. */+ private <T> T copy(T value, Class<T> type) {+ return objectMapper.convertValue(objectMapper.valueToTree(value), type);+ }++ // ---------------------------------------------------------------- listing++ private record ListRequest(List<String> states, int maxResults, String nextToken) {+ boolean matchesState(String state) {+ return states == null || states.contains(state);+ }+ }++ private ListRequest parseListRequest(JsonNode request) {+ Integer maxResults = LambdaWebJson.integer(request, "maxResults");+ String nextToken = LambdaWebJson.text(request, "nextToken");+ JsonNode filters = LambdaWebJson.list(request, "filters");+ LambdaWebValidation validation = new LambdaWebValidation();+ validation.range("maxResults", maxResults, 1, 50);+ List<String> badNames = new ArrayList<>();+ List<String> states = null;+ if (filters != null) {+ validation.listSize("filters", filters.size(), 1, 10);+ int index = 1;+ for (JsonNode filter : filters) {+ String member = "filters." + index + ".member.";+ String name = LambdaWebJson.text(filter, "name");+ JsonNode values = LambdaWebJson.list(filter, "values");+ validation.required(member + "name", name)+ .length(member + "name", name, 1, 64)+ .pattern(member + "name", name, FILTER_NAME)+ .required(member + "values", values);+ List<String> filterValues = LambdaWebJson.strings(values);+ if (values != null) {+ validation.listSize(member + "values", values.size(), 1, 10);+ int valueIndex = 1;+ for (String value : filterValues) {+ validation.length(member + "values." + valueIndex + ".member", value, 1, 64)+ .pattern(member + "values." + valueIndex + ".member", value, FILTER_VALUE);+ valueIndex++;+ }+ }+ if ("state".equals(name)) {+ if (states == null) {+ states = new ArrayList<>();+ }+ if (filterValues != null) {+ states.addAll(filterValues);+ }+ } else if (name != null) {+ badNames.add(name);+ }+ index++;+ }+ }+ validation.throwIfAny();+ if (!badNames.isEmpty()) {+ throw new AwsException("ValidationException", "The filter names " + badNames+ + " are invalid. Supported filter names are: [state].", 400);+ }+ return new ListRequest(states, maxResults == null ? DEFAULT_PAGE_SIZE : maxResults, nextToken);+ }++ private String scope(String operation, String region, String functionName, ListRequest list) {+ return TOKEN_MARKER + operation + "|" + region + "|" + regionResolver.getAccountId() + "|" + functionName+ + "|" + list.states() + "|" + list.maxResults();+ }++ /**+ * Pages a listing in {@code cursorOf} order. The token carries the request it was issued for and the+ * cursor of the item its page ended on, so the next page starts past that item even when it is gone,+ * as on AWS.+ */+ private static <T> PaginatedResult<T> page(List<T> items, ListRequest list, String scope,+ Function<T, String> cursorOf) {+ return Pagination.paginate(items, cursorOf, list.maxResults(), list.nextToken(), scope,+ LambdaWebService::tokenError);+ }++ private static AwsException tokenError(String token) {+ String decoded;+ try {+ decoded = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);+ } catch (IllegalArgumentException expected) {+ // Not base64, so not a token Floci issued.+ decoded = "";+ }+ if (decoded.startsWith(TOKEN_MARKER)) {+ return new AwsException("ValidationException", "The nextToken " + token+ + " does not match the request. Subsequent pagination requests must use the same"+ + " parameters as the initial request.", 400);+ }+ return new AwsException("ValidationException", "The nextToken " + token + " is invalid or has expired.", 400);+ }++ // ---------------------------------------------------------------- storage++ private static String randomLowercase(int length) {+ StringBuilder out = new StringBuilder(length);+ while (out.length() < length) {+ UUID uuid = UUID.randomUUID();+ long bits = uuid.getMostSignificantBits() ^ uuid.getLeastSignificantBits();+ for (int i = 0; i < 12 && out.length() < length; i++) {+ out.append(LOWERCASE_ALNUM.charAt((int) Math.floorMod(bits, LOWERCASE_ALNUM.length())));+ bits = bits / LOWERCASE_ALNUM.length();+ }+ }+ return out.toString();+ }++ private static Instant now() {+ return Instant.now().truncatedTo(ChronoUnit.MICROS);+ }++ public static String formatTimestamp(Instant instant) {+ return LambdaWebResponses.timestamp(instant);+ }++ private static String key(String region, String functionName) {+ return region + "/" + functionName;+ }++ private Object lockFor(String region, String functionName) {+ return locks.computeIfAbsent(key(region, functionName), k -> new Object());+ }++ private List<WebFunction> in(String region) {+ String prefix = region + "/";+ return functions.scan(k -> k.startsWith(prefix));+ }++ /** The backend only tracks put and delete, so a function mutated in place is written back. */+ private void persist(String region, WebFunction fn) {+ functions.put(key(region, fn.functionName), fn);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebValidation.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebValidation.javanew file mode 100644index 0000000000..87b444fa2e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebValidation.java@@ -0,0 +1,145 @@+package io.github.hectorvent.floci.services.lambdaweb;++import io.github.hectorvent.floci.core.common.AwsException;++import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.regex.Pattern;++/**+ * Collects the input-shape errors of one request into the single {@code ValidationException} AWS+ * reports, which counts the errors and joins them with "; ".+ */+final class LambdaWebValidation {++ private final List<String> errors = new ArrayList<>();++ /** A member read by {@link LambdaWebJson}, so an absent JSON member arrives as null. */+ LambdaWebValidation required(String path, Object value) {+ if (value == null) {+ errors.add("Value null at '" + path + "' failed to satisfy constraint: Member must not be null");+ }+ return this;+ }++ LambdaWebValidation length(String path, String value, int min, int max) {+ if (value == null) {+ return this;+ }+ if (value.length() < min) {+ errors.add(valueAt(value, path) + "Member must have length greater than or equal to " + min);+ } else if (value.length() > max) {+ errors.add(valueAt(value, path) + "Member must have length less than or equal to " + max);+ }+ return this;+ }++ LambdaWebValidation listSize(String path, int size, int min, int max) {+ if (size < min) {+ errors.add("Value at '" + path + "' failed to satisfy constraint: "+ + "Member must have length greater than or equal to " + min);+ } else if (size > max) {+ errors.add("Value at '" + path + "' failed to satisfy constraint: "+ + "Member must have length less than or equal to " + max);+ }+ return this;+ }++ /** AWS reports one error for the whole list, printing it, when any member breaks a constraint. */+ LambdaWebValidation listMembers(String path, List<String> values, int min, int max, Pattern pattern) {+ boolean bad = values.stream().anyMatch(v -> v.length() < min || v.length() > max || !pattern.matcher(v).matches());+ if (bad) {+ errors.add(valueAt(values, path) + "Member must satisfy constraint: [" + lengthConstraints(min, max)+ + ", Member must satisfy regular expression pattern: " + pattern.pattern() + "]");+ }+ return this;+ }++ LambdaWebValidation pattern(String path, String value, Pattern pattern) {+ if (value != null && !pattern.matcher(value).matches()) {+ errors.add(valueAt(value, path) + "Member must satisfy regular expression pattern: " + pattern.pattern());+ }+ return this;+ }++ LambdaWebValidation range(String path, Integer value, int min, int max) {+ if (value == null) {+ return this;+ }+ if (value < min) {+ errors.add(valueAt(value, path) + "Member must have value greater than or equal to " + min);+ } else if (value > max) {+ errors.add(valueAt(value, path) + "Member must have value less than or equal to " + max);+ }+ return this;+ }++ LambdaWebValidation enumeration(String path, String value, List<String> allowed) {+ if (value != null && !allowed.contains(value)) {+ errors.add(valueAt(value, path) + "Member must satisfy enum value set: " + allowed);+ }+ return this;+ }++ /** AWS lists every key constraint whichever one failed. */+ LambdaWebValidation mapKeys(String path, Map<String, ?> map, int min, int max, Pattern pattern) {+ boolean bad = map.keySet().stream()+ .anyMatch(k -> k.length() < min || k.length() > max || !pattern.matcher(k).matches());+ if (bad) {+ errors.add("Value at '" + path + "' failed to satisfy constraint: Map keys must satisfy constraint: ["+ + lengthConstraints(min, max) + ", Member must satisfy regular expression pattern: "+ + pattern.pattern() + "]");+ }+ return this;+ }++ /** As {@link #mapKeys}, for values. AWS prints the whole map as the offending value. */+ LambdaWebValidation mapValues(String path, Map<String, String> map, int min, int max, Pattern pattern) {+ boolean bad = map.values().stream()+ .anyMatch(v -> v == null || v.length() < min || v.length() > max || !pattern.matcher(v).matches());+ if (bad) {+ errors.add(valueAt(map, path) + "Map value must satisfy constraint: ["+ + lengthConstraints(min, max) + ", Member must satisfy regular expression pattern: "+ + pattern.pattern() + "]");+ }+ return this;+ }++ /** A sensitive map: AWS prints no value and the keys have a minimum length and a pattern only. */+ LambdaWebValidation sensitiveMapKeys(String path, Map<String, ?> map, int min, Pattern pattern) {+ boolean bad = map.keySet().stream().anyMatch(k -> k.length() < min || !pattern.matcher(k).matches());+ if (bad) {+ errors.add("Value at '" + path + "' failed to satisfy constraint: Map keys must satisfy constraint: ["+ + "Member must have length greater than or equal to " + min+ + ", Member must satisfy regular expression pattern: " + pattern.pattern() + "]");+ }+ return this;+ }++ LambdaWebValidation sensitiveMapValues(String path, Map<String, String> map, int min) {+ boolean bad = map.values().stream().anyMatch(v -> v.length() < min);+ if (bad) {+ errors.add("Value at '" + path + "' failed to satisfy constraint: Map value must satisfy constraint: ["+ + "Member must have length greater than or equal to " + min + "]");+ }+ return this;+ }++ private static String lengthConstraints(int min, int max) {+ return "Member must have length less than or equal to " + max+ + ", Member must have length greater than or equal to " + min;+ }++ private static String valueAt(Object value, String path) {+ return "Value '" + value + "' at '" + path + "' failed to satisfy constraint: ";+ }++ void throwIfAny() {+ if (errors.isEmpty()) {+ return;+ }+ String head = errors.size() == 1 ? "1 validation error detected: " : errors.size() + " validation errors detected: ";+ throw new AwsException("ValidationException", head + String.join("; ", errors), 400);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/model/WebFunction.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/model/WebFunction.javanew file mode 100644index 0000000000..ab6be18c73--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/model/WebFunction.java@@ -0,0 +1,22 @@+package io.github.hectorvent.floci.services.lambdaweb.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.LinkedHashMap;+import java.util.Map;++/** A Lambda Web Function with its revisions and endpoints. The function is the stored aggregate. */+@RegisterForReflection+public final class WebFunction {++ public String functionName;+ public String functionArn;+ public Instant createdAt;+ public Instant updatedAt;+ public Map<String, String> tags = new LinkedHashMap<>();+ public String policy;+ public String policyRevisionId;+ public Map<String, WebFunctionRevision> revisions = new LinkedHashMap<>();+ public Map<String, WebFunctionEndpoint> endpoints = new LinkedHashMap<>();+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/model/WebFunctionEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/model/WebFunctionEndpoint.javanew file mode 100644index 0000000000..34a6edbcf1--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/model/WebFunctionEndpoint.java@@ -0,0 +1,48 @@+package io.github.hectorvent.floci.services.lambdaweb.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/** A network entry point of a Web Function: a domain name and the revisions it routes to. */+@RegisterForReflection+public final class WebFunctionEndpoint {++ public String endpointName;+ public String endpointArn;+ public String functionArn;+ public String description;+ public String endpointType;+ public String domainName;+ public String authType;+ public String autoDeploymentMode;+ public List<RevisionWeight> revisionWeights = new ArrayList<>();+ public List<String> regions = new ArrayList<>();+ /** Clearing a config on AWS leaves an empty object, which the wire shows as {@code {}}. */+ public ScalingConfig scalingConfig;+ public ThrottleConfig throttleConfig;+ public String updateStatus;+ public Map<String, String> regionalDomainNames = new LinkedHashMap<>();+ public Instant createdAt;+ public Instant updatedAt;++ @RegisterForReflection+ public static final class RevisionWeight {+ public String revisionId;+ public int weight;+ }++ @RegisterForReflection+ public static final class ScalingConfig {+ public Integer maxEnvironments;+ }++ @RegisterForReflection+ public static final class ThrottleConfig {+ public Integer rateLimit;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdaweb/model/WebFunctionRevision.java b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/model/WebFunctionRevision.javanew file mode 100644index 0000000000..96da7a543f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambdaweb/model/WebFunctionRevision.java@@ -0,0 +1,40 @@+package io.github.hectorvent.floci.services.lambdaweb.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.Map;++/** A snapshot of a Web Function's code and configuration. The wire nesting is rebuilt when rendered. */+@RegisterForReflection+public final class WebFunctionRevision {++ public String revisionId;+ public String revisionArn;+ public String functionArn;+ public String description;+ public String kmsKeyArn;+ public BuildConfig buildConfig = new BuildConfig();+ public ServiceConfig serviceConfig = new ServiceConfig();+ public Instant createdAt;++ @RegisterForReflection+ public static final class BuildConfig {+ public String bucket;+ public String key;+ public String versionId;+ public String runtime;+ }++ @RegisterForReflection+ public static final class ServiceConfig {+ public String executionRoleArn;+ public int timeoutSeconds = 30;+ public String egressNetworkConnectorArn;+ public int maxConcurrencyPerEnvironment = 64;+ public Map<String, String> environmentVariables;+ public String logGroup;+ public String applicationLogLevel = "INFO";+ public String systemLogLevel = "INFO";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.javaindex f6ad878d49..1af1c5d9c4 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java@@ -44,7 +44,7 @@ class PartitionCrossServiceSmokeIntegrationTest {"configservice", "connect", "controlcatalog", "controltower", "datasync", "dlm", "dms", "dynamodb", "ec2","ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elbv2", "emr", "emrserverless","eventbridge", "firehose", "fis", "glue", "guardduty", "iot", "kinesis", "kinesisanalytics", "lambda",- "lambdamicrovms", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations",+ "lambdamicrovms", "lambdaweb", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations","pipes", "ram", "rds", "redshift", "redshiftserverless", "resourceexplorer2", "route53resolver","s3tables", "s3vectors", "sagemaker", "scheduler", "secretsmanager", "servicequotas", "ses", "sns", "sqs","stepfunctions", "timestreaminfluxdb", "transfer", "verifiedpermissions", "wafv2");@@ -893,6 +893,16 @@ class PartitionCrossServiceSmokeIntegrationTest {PartitionMatrix.assertArnIn(partitionCase, arn);}+ @ParameterizedTest+ @MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)+ void lambdaWebFunctionArn(PartitionCase partitionCase) {+ String region = offered(partitionCase, "lambda");+ String message = signed(region, "lambda").when().get("/2025-03-07/web-functions/smoke-missing-web-function")+ .then().statusCode(404).extract().jsonPath().getString("message");+ String arn = message.substring("The function ".length(), message.indexOf(" does not exist."));+ PartitionMatrix.assertArnIn(partitionCase, arn);+ }+@ParameterizedTest@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)void dlmLifecyclePolicyArn(PartitionCase partitionCase) {diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.javaindex 4beb5a09c6..bf464560ff 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java@@ -258,6 +258,32 @@ class IamActionRegistryTest {assertEquals("lambda:SendDurableExecutionCallbackHeartbeat", lambdaAction("POST", callback + "/heartbeat"));}+ @Test+ void lambdaWebRoutesResolveToTheirActions() {+ String arn = "arn%3Aaws%3Alambda%3Aus-east-1%3A000000000000%3Aweb-function%2Fapp";+ assertEquals("lambda:CreateWebFunction", lambdaAction("PUT", "/2025-03-07/web-functions"));+ assertEquals("lambda:ListWebFunctions", lambdaAction("POST", "/2025-03-07/web-functions"));+ assertEquals("lambda:GetWebFunction", lambdaAction("GET", "/2025-03-07/web-functions/" + arn));+ assertEquals("lambda:DeleteWebFunction", lambdaAction("DELETE", "/2025-03-07/web-functions/app"));+ assertEquals("lambda:CreateWebFunctionRevision", lambdaAction("POST", "/2025-03-07/web-functions/app/revisions"));+ assertEquals("lambda:ListWebFunctionRevisions", lambdaAction("POST", "/2025-03-07/web-functions/app/list-revisions"));+ assertEquals("lambda:GetWebFunctionRevision", lambdaAction("GET", "/2025-03-07/web-functions/app/revisions/rev-aaaaa"));+ assertEquals("lambda:DeleteWebFunctionRevision",+ lambdaAction("DELETE", "/2025-03-07/web-functions/app/revisions/rev-aaaaa"));+ assertEquals("lambda:CreateWebFunctionEndpoint", lambdaAction("PUT", "/2025-03-07/web-functions/app/endpoints"));+ assertEquals("lambda:ListWebFunctionEndpoints", lambdaAction("POST", "/2025-03-07/web-functions/app/list-endpoints"));+ assertEquals("lambda:GetWebFunctionEndpoint", lambdaAction("GET", "/2025-03-07/web-functions/app/endpoints/dev"));+ assertEquals("lambda:UpdateWebFunctionEndpoint", lambdaAction("PATCH", "/2025-03-07/web-functions/app/endpoints/dev"));+ assertEquals("lambda:DeleteWebFunctionEndpoint", lambdaAction("DELETE", "/2025-03-07/web-functions/app/endpoints/dev"));+ assertEquals("lambda:GetWebAccountSettings", lambdaAction("GET", "/2025-03-07/web-account-settings"));+ assertEquals("lambda:ListTags", lambdaAction("GET", "/2025-03-07/tags/" + arn));+ assertEquals("lambda:TagResource", lambdaAction("POST", "/2025-03-07/tags/" + arn));+ assertEquals("lambda:UntagResource", lambdaAction("DELETE", "/2025-03-07/tags/" + arn));+ assertEquals("lambda:PutResourcePolicy", lambdaAction("PUT", "/2025-03-07/resource-policy/" + arn));+ assertEquals("lambda:GetResourcePolicy", lambdaAction("GET", "/2025-03-07/resource-policy/" + arn));+ assertEquals("lambda:DeleteResourcePolicy", lambdaAction("DELETE", "/2025-03-07/resource-policy/" + arn));+ }+private String lambdaAction(String method, String path) {return registry.resolveRoute("lambda",mockCtx(method, path, new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}"));diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.javaindex 2b38fcd593..e0bd07efbc 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java@@ -1001,6 +1001,43 @@ class ResourceArnBuilderTest {builder.build("lambda", ctx, "us-east-1", "000000000000"));}+ @Test+ void lambdaWebRoutesResolveTheFunctionRevisionOrEndpointTheyActOn() {+ String fn = "arn:aws:lambda:us-east-1:000000000000:web-function/app";+ when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app");+ assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));+ when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/revisions");+ assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));+ when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/list-endpoints");+ assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));+ when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/revisions/rev-abcde");+ assertEquals(fn + "/revision/rev-abcde", builder.build("lambda", ctx, "us-east-1", "000000000000"));+ when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/endpoints/prod");+ assertEquals(fn + "/endpoint/prod", builder.build("lambda", ctx, "us-east-1", "000000000000"));+ // A function named by its ARN keeps the account and region it names.+ when(uriInfo.getPath()).thenReturn(+ "/2025-03-07/web-functions/arn:aws:lambda:us-east-1:111122223333:web-function/app/endpoints/prod");+ assertEquals("arn:aws:lambda:us-east-1:111122223333:web-function/app/endpoint/prod",+ builder.build("lambda", ctx, "us-east-1", "000000000000"));+ // A revision or endpoint named by its ARN resolves to its id under the path's function.+ when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/revisions/"+ + "arn:aws:lambda:us-east-1:000000000000:web-function/app/revision/rev-abcde");+ assertEquals(fn + "/revision/rev-abcde", builder.build("lambda", ctx, "us-east-1", "000000000000"));+ when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/endpoints/"+ + "arn:aws:lambda:us-east-1:000000000000:web-function/app/endpoint/prod");+ assertEquals(fn + "/endpoint/prod", builder.build("lambda", ctx, "us-east-1", "000000000000"));+ // The tag and policy routes carry the function ARN in the path.+ when(uriInfo.getPath()).thenReturn("/2025-03-07/tags/" + fn);+ assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));+ when(uriInfo.getPath()).thenReturn("/2025-03-07/resource-policy/" + fn);+ assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));+ // Listing functions, the account settings and creating a function name no resource.+ when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions");+ assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));+ when(uriInfo.getPath()).thenReturn("/2025-03-07/web-account-settings");+ assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));+ }+@Testvoid lambdaRoutesOtherThanInvokeAreCheckedAgainstTheCallersUnqualifiedFunction() {when(uriInfo.getPath()).thenReturn(diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.javanew file mode 100644index 0000000000..8df8590544--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebIntegrationTest.java@@ -0,0 +1,587 @@+package io.github.hectorvent.floci.services.lambdaweb;++import io.github.hectorvent.floci.services.s3.S3Service;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestInstance;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URLEncoder;+import java.nio.charset.StandardCharsets;+import java.util.List;+import java.util.Map;+import java.util.regex.Pattern;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasSize;+import static org.hamcrest.Matchers.matchesPattern;+import static org.hamcrest.Matchers.nullValue;++/**+ * The Lambda Web control plane as the AWS CLI and SDKs drive it. Shapes, state words and error+ * wording follow responses recorded against the live service.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+@TestInstance(TestInstance.Lifecycle.PER_CLASS)+class LambdaWebIntegrationTest {++ private static final String BASE = "/2025-03-07";+ private static final String FN = "web-it-app";+ private static final String ARN = "arn:aws:lambda:us-east-1:000000000000:web-function/" + FN;+ private static final String BUCKET = "web-it-code";+ private static final String KEY = "app.zip";+ private static final String ROLE = "arn:aws:iam::000000000000:role/web-it-role";+ private static final String BUILD = """+ {"codeConfig": {"s3Object": {"bucket": "%s", "key": "%s"}}, "runtimeConfig": {"runtime": "nodejs24.x"}}+ """.formatted(BUCKET, KEY);++ @Inject+ S3Service s3Service;++ private static String revision1;+ private static String revision2;+ private static String domainName;++ @BeforeAll+ void seedCode() {+ s3Service.createBucket(BUCKET, "us-east-1");+ s3Service.putObject(BUCKET, KEY, "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());+ }++ @Test+ @Order(1)+ void createWebFunctionReportsPendingChildren() {+ revision1 = given()+ .contentType("application/json")+ .body("""+ {"functionName": "%s",+ "revisionConfig": {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s"}},+ "endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",+ "authType": "ApplicationManaged", "autoDeploymentMode": "LatestRevision"},+ "tags": {"env": "it"}}+ """.formatted(FN, BUILD, ROLE))+ .when().put(BASE + "/web-functions")+ .then()+ .statusCode(202)+ .body("functionName", equalTo(FN))+ .body("functionArn", equalTo(ARN))+ .body("state", equalTo("Active"))+ .body("stateReason", equalTo("The function is active."))+ .body("tags.env", equalTo("it"))+ .body("revision.state", equalTo("Pending"))+ .body("revision.stateReason", equalTo("The revision is being activated."))+ .body("revision.revisionId", matchesPattern("rev-[a-z0-9]{5}"))+ .body("revision.revisionArn", matchesPattern(Pattern.quote(ARN + "/revision/") + "rev-[a-z0-9]{5}"))+ .body("endpoint.state", equalTo("Pending"))+ .body("endpoint.stateReason",+ equalTo("The endpoint is being activated and is not yet invokable in any region."))+ .body("endpoint.endpointArn", equalTo(ARN + "/endpoint/dev"))+ .body("endpoint.autoDeploymentMode", equalTo("LatestRevision"))+ .body("endpoint.regions", equalTo(List.of("us-east-1")))+ .body("endpoint.revisionWeights[0].weight", equalTo(100))+ .body("endpoint.domainName", matchesPattern("[a-z0-9]{16}\\.001\\.lambda-web\\.us-east-1\\..+"))+ .body("createdAt", matchesPattern("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{6}Z"))+ .extract().path("revision.revisionId");+ }++ @Test+ @Order(2)+ void readsSettleToActive() {+ given().when().get(BASE + "/web-functions/" + FN)+ .then().statusCode(200)+ .body("state", equalTo("Active"));++ domainName = given().when().get(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(200)+ .body("state", equalTo("Active"))+ .body("stateReason", equalTo("The endpoint is active and invokable."))+ .body("updateStatus", nullValue())+ .body("regionalEndpoints.us-east-1.state", equalTo("Active"))+ .body("regionalEndpoints.us-east-1.stateReason", equalTo("The endpoint is active in the region."))+ .body("regionalEndpoints.us-east-1.revisionWeights[0].revisionId", equalTo(revision1))+ .body("functionArn", equalTo(ARN))+ .extract().path("domainName");++ given().when().get(BASE + "/web-functions/" + FN + "/revisions/" + revision1)+ .then().statusCode(200)+ .body("state", equalTo("Active"))+ .body("stateReason", equalTo("The revision is active."))+ .body("buildConfig.codeConfig.s3Object.bucket", equalTo(BUCKET))+ .body("buildConfig.codeConfig.s3Object.versionId", nullValue())+ .body("buildConfig.runtimeConfig.runtime", equalTo("nodejs24.x"))+ .body("serviceConfig.timeoutSeconds", equalTo(30))+ .body("serviceConfig.maxConcurrencyPerEnvironment", equalTo(64))+ .body("serviceConfig.environmentVariables", nullValue())+ .body("serviceConfig.telemetryConfig.loggingConfig.logGroup", equalTo("/aws/lambda/web/" + FN))+ .body("serviceConfig.telemetryConfig.loggingConfig.applicationLogLevel", equalTo("INFO"))+ .body("serviceConfig.telemetryConfig.loggingConfig.systemLogLevel", equalTo("INFO"));++ // The function is addressable by its ARN too, and the account settings count it.+ given().urlEncodingEnabled(false)+ .when().get(BASE + "/web-functions/" + URLEncoder.encode(ARN, StandardCharsets.UTF_8))+ .then().statusCode(200).body("functionName", equalTo(FN));+ given().when().get(BASE + "/web-account-settings")+ .then().statusCode(200)+ .body("accountQuotas.maxEndpointsPerFunction", equalTo(10))+ .body("accountQuotas.maxRevisionsPerFunction", equalTo(50))+ .body("accountQuotas.maxTotalArmVCpus", equalTo(2000))+ .body("accountQuotas.maxTotalRateLimit", equalTo(100000))+ .body("accountUsage.functionCount", equalTo(1));+ }++ @Test+ @Order(3)+ void newRevisionMovesALatestRevisionEndpoint() {+ revision2 = given()+ .contentType("application/json")+ .body("""+ {"buildConfig": %s, "description": "second",+ "serviceConfig": {"executionRoleArn": "%s", "timeoutSeconds": 60,+ "maxConcurrencyPerEnvironment": 8,+ "environmentVariables": {"APP_VERSION": "2"},+ "telemetryConfig": {"loggingConfig": {"systemLogLevel": "DEBUG"}}}}+ """.formatted(BUILD, ROLE))+ .when().post(BASE + "/web-functions/" + FN + "/revisions")+ .then()+ .statusCode(202)+ .body("state", equalTo("Pending"))+ .body("description", equalTo("second"))+ .body("serviceConfig.timeoutSeconds", equalTo(60))+ .body("serviceConfig.environmentVariables.APP_VERSION", equalTo("2"))+ .body("serviceConfig.telemetryConfig.loggingConfig.systemLogLevel", equalTo("DEBUG"))+ .extract().path("revisionId");++ given().when().get(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(200)+ .body("revisionWeights", hasSize(1))+ .body("revisionWeights[0].revisionId", equalTo(revision2))+ .body("updateStatus", nullValue());++ // Newest first.+ given().contentType("application/json").body("{}")+ .when().post(BASE + "/web-functions/" + FN + "/list-revisions")+ .then().statusCode(200)+ .body("revisions", hasSize(2))+ .body("revisions[0].revisionId", equalTo(revision2))+ .body("revisions[1].revisionId", equalTo(revision1))+ .body("nextToken", nullValue());+ }++ @Test+ @Order(4)+ void weightedRoutingUpdate() {+ given().contentType("application/json")+ .body("""+ {"revisionWeights": [{"revisionId": "%s", "weight": 100}]}+ """.formatted(revision1))+ .when().patch(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(400)+ .header("X-Amzn-Errortype", "ValidationException")+ .body("message",+ equalTo("The revisionWeights cannot be specified when the autoDeploymentMode is LatestRevision."));++ given().contentType("application/json")+ .body("""+ {"autoDeploymentMode": "Disabled",+ "revisionWeights": [{"revisionId": "%s", "weight": 90}, {"revisionId": "%s", "weight": 10}]}+ """.formatted(revision1, revision2))+ .when().patch(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(202)+ .body("autoDeploymentMode", equalTo("Disabled"))+ .body("revisionWeights[0].revisionId", equalTo(revision1))+ .body("revisionWeights[0].weight", equalTo(90))+ .body("state", equalTo("Active"))+ .body("updateStatus", equalTo("InProgress"))+ .body("updateStatusReason", equalTo("The endpoint is being updated."))+ // The per-region block still shows the weights from before the update.+ .body("regionalEndpoints.us-east-1.revisionWeights", hasSize(1))+ .body("regionalEndpoints.us-east-1.revisionWeights[0].revisionId", equalTo(revision2))+ .body("regionalEndpoints.us-east-1.updateStatus", equalTo("InProgress"))+ .body("regionalEndpoints.us-east-1.updateStatusReason",+ equalTo("The endpoint is being updated in the region."));++ given().when().get(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(200)+ .body("updateStatus", equalTo("Successful"))+ .body("updateStatusReason", equalTo("The endpoint is updated."))+ .body("regionalEndpoints.us-east-1.revisionWeights", hasSize(2))+ .body("regionalEndpoints.us-east-1.updateStatus", equalTo("Successful"))+ .body("regionalEndpoints.us-east-1.updateStatusReason", equalTo("The endpoint is updated in the region."));++ given().when().delete(BASE + "/web-functions/" + FN + "/revisions/" + revision2)+ .then().statusCode(409)+ .header("X-Amzn-Errortype", "ConflictException")+ .body("message", equalTo("The revision " + revision2 + " cannot be deleted because the endpoints [dev]"+ + " are using it. Update the endpoints to use other revisions first."));++ given().contentType("application/json")+ .body("""+ {"revisionWeights": [{"revisionId": "%s", "weight": 50}, {"revisionId": "%s", "weight": 40}]}+ """.formatted(revision1, revision2))+ .when().patch(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(400)+ .body("message",+ equalTo("The revisionWeights must contain unique revisionIds, and the weights must total exactly 100."));++ given().contentType("application/json")+ .body("""+ {"revisionWeights": [{"revisionId": "rev-zzzzz", "weight": 100}]}+ """)+ .when().patch(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(404)+ .body("message", equalTo("The revision rev-zzzzz does not exist."));++ // Back to LatestRevision: the newest revision takes all traffic without weights in the request.+ given().contentType("application/json").body("{\"autoDeploymentMode\": \"LatestRevision\"}")+ .when().patch(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(202)+ .body("revisionWeights", hasSize(1))+ .body("revisionWeights[0].revisionId", equalTo(revision2));+ }++ @Test+ @Order(5)+ void scalingAndThrottleConfigs() {+ given().contentType("application/json")+ .body("{\"scalingConfig\": {\"maxEnvironments\": 2}, \"throttleConfig\": {\"rateLimit\": 100}}")+ .when().patch(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(202)+ .body("scalingConfig.maxEnvironments", equalTo(2))+ .body("throttleConfig.rateLimit", equalTo(100));++ given().contentType("application/json").body("{\"scalingConfig\": {}}")+ .when().patch(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(202)+ .body("scalingConfig", equalTo(Map.of()))+ .body("throttleConfig.rateLimit", equalTo(100))+ .body("regionalEndpoints.us-east-1.scalingConfig.maxEnvironments", equalTo(2));++ given().contentType("application/json").body("{\"throttleConfig\": {\"rateLimit\": 150}}")+ .when().patch(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(400)+ .body("message", equalTo("The rateLimit 150 is invalid. Supported rate limits are: [0, 100, 200, 300, 400,"+ + " 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]."));++ given().contentType("application/json").body("{\"scalingConfig\": {\"maxEnvironments\": 1}}")+ .when().patch(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value '1' at 'scalingConfig.maxEnvironments'"+ + " failed to satisfy constraint: Member must have value greater than or equal to 2"));+ }++ @Test+ @Order(6)+ void endpointRules() {+ String endpoints = BASE + "/web-functions/" + FN + "/endpoints";+ given().contentType("application/json")+ .body("{\"endpointName\": \"dev\", \"endpointType\": \"HomeRegion\", \"authType\": \"ApplicationManaged\","+ + " \"autoDeploymentMode\": \"LatestRevision\"}")+ .when().put(endpoints)+ .then().statusCode(409)+ .body("message", equalTo("The endpoint dev already exists."));++ given().contentType("application/json")+ .body("{\"endpointName\": \"prod\", \"endpointType\": \"HomeRegion\", \"authType\": \"ApplicationManaged\"}")+ .when().put(endpoints)+ .then().statusCode(400)+ .body("message", equalTo("The revisionWeights must be specified when the autoDeploymentMode is Disabled."));++ given().contentType("application/json")+ .body("{\"endpointName\": \"prod\", \"endpointType\": \"MultiRegion\", \"regions\": [\"us-west-2\"],"+ + " \"authType\": \"ApplicationManaged\", \"autoDeploymentMode\": \"LatestRevision\"}")+ .when().put(endpoints)+ .then().statusCode(400)+ .body("message", equalTo("The autoDeploymentMode can only be Disabled when the endpointType is MultiRegion."));++ given().contentType("application/json")+ .body("{\"endpointName\": \"prod\", \"endpointType\": \"HomeRegion\", \"regions\": [\"us-west-2\"],"+ + " \"authType\": \"ApplicationManaged\", \"autoDeploymentMode\": \"LatestRevision\"}")+ .when().put(endpoints)+ .then().statusCode(400)+ .body("message", equalTo("The endpointType HomeRegion supports only the home region us-east-1."+ + " The request results in the regions [us-east-1, us-west-2]."));++ given().contentType("application/json")+ .body("{\"endpointName\": \"prod\", \"endpointType\": \"MultiRegion\", \"regions\": [\"us-east-1\"],"+ + " \"authType\": \"ApplicationManaged\","+ + " \"revisionWeights\": [{\"revisionId\": \"" + revision1 + "\", \"weight\": 100}]}")+ .when().put(endpoints)+ .then().statusCode(400)+ .body("message", equalTo("The endpointType MultiRegion requires at least 2 distinct regions. The home region"+ + " us-east-1 is added automatically, so specify at least 1 additional region."+ + " The request results in the regions [us-east-1]."));++ given().contentType("application/json")+ .body("{\"endpointName\": \"prod\", \"endpointType\": \"HomeRegion\", \"authType\": \"NONE\"}")+ .when().put(endpoints)+ .then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value 'NONE' at 'authType' failed to satisfy"+ + " constraint: Member must satisfy enum value set: [ApplicationManaged, IamAuth]"));++ given().contentType("application/json")+ .body("{\"endpointName\": \"-x\", \"endpointType\": \"HomeRegion\", \"authType\": \"ApplicationManaged\","+ + " \"autoDeploymentMode\": \"LatestRevision\"}")+ .when().put(endpoints)+ .then().statusCode(400)+ .body("message", equalTo("The endpoint ARN -x with the function name " + FN+ + ", the region us-east-1 and the account id 000000000000 is invalid."));++ // A MultiRegion endpoint gets a global domain and a per-region block for every region.+ given().contentType("application/json")+ .body("{\"endpointName\": \"global\", \"endpointType\": \"MultiRegion\", \"regions\": [\"us-west-2\"],"+ + " \"authType\": \"IamAuth\", \"description\": \"d\","+ + " \"revisionWeights\": [{\"revisionId\": \"" + revision1 + "\", \"weight\": 100}]}")+ .when().put(endpoints)+ .then().statusCode(202)+ .body("domainName", matchesPattern("[a-z0-9]{16}\\.lambda-web\\.global\\..+"))+ .body("regions", equalTo(List.of("us-east-1", "us-west-2")))+ .body("regionalEndpoints.us-west-2.state", equalTo("Pending"))+ .body("regionalEndpoints.us-west-2.authType", equalTo("IamAuth"))+ .body("description", equalTo("d"));++ given().contentType("application/json").body("{}")+ .when().post(BASE + "/web-functions/" + FN + "/list-endpoints")+ .then().statusCode(200)+ .body("endpoints", hasSize(2))+ .body("endpoints[0].endpointName", equalTo("dev"))+ .body("endpoints[1].endpointName", equalTo("global"))+ .body("endpoints[0].functionArn", nullValue());++ given().when().delete(endpoints + "/global").then().statusCode(204);+ given().when().get(endpoints + "/global")+ .then().statusCode(404)+ .header("X-Amzn-Errortype", "ResourceNotFoundException")+ .body("message", equalTo("The endpoint global does not exist."));+ }++ @Test+ @Order(7)+ void revisionRules() {+ String revisions = BASE + "/web-functions/" + FN + "/revisions";+ given().contentType("application/json")+ .body("""+ {"buildConfig": {"codeConfig": {"s3Object": {"bucket": "%s", "key": "%s"}},+ "runtimeConfig": {"runtime": "nodejs22.x"}},+ "serviceConfig": {"executionRoleArn": "%s"}}+ """.formatted(BUCKET, KEY, ROLE))+ .when().post(revisions)+ .then().statusCode(400)+ .body("message", equalTo("The runtime nodejs22.x is invalid."));++ given().contentType("application/json")+ .body("""+ {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s", "timeoutSeconds": 2}}+ """.formatted(BUILD, ROLE))+ .when().post(revisions)+ .then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value '2' at 'serviceConfig.timeoutSeconds' failed"+ + " to satisfy constraint: Member must have value greater than or equal to 3"));++ given().contentType("application/json")+ .body("""+ {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s",+ "environmentVariables": {"AWS_REGION": "x"}}}+ """.formatted(BUILD, ROLE))+ .when().post(revisions)+ .then().statusCode(400)+ .body("message", equalTo("The environmentVariables cannot contain reserved keys."+ + " The request specified the reserved keys [AWS_REGION]."));++ given().contentType("application/json")+ .body("""+ {"buildConfig": %s, "serviceConfig": {}}+ """.formatted(BUILD))+ .when().post(revisions)+ .then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value null at 'serviceConfig.executionRoleArn'"+ + " failed to satisfy constraint: Member must not be null"));++ given().contentType("application/json")+ .body("""+ {"buildConfig": {"codeConfig": {"s3Object": {"bucket": "%s", "key": "missing.zip"}},+ "runtimeConfig": {"runtime": "nodejs24.x"}},+ "serviceConfig": {"executionRoleArn": "%s"}}+ """.formatted(BUCKET, ROLE))+ .when().post(revisions)+ .then().statusCode(400)+ .body("message", equalTo("The specified S3 object does not exist: s3://" + BUCKET+ + "/missing.zip. Verify the object exists in the bucket."));++ given().contentType("application/json")+ .body("""+ {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s",+ "telemetryConfig": {"loggingConfig": {"logGroup": "aws/lambda/x"}}}}+ """.formatted(BUILD, ROLE))+ .when().post(revisions)+ .then().statusCode(400)+ .body("message", equalTo("The logGroup aws/lambda/x is invalid. Log group names starting with aws/"+ + " (case-insensitive) are reserved for AWS."));++ given().contentType("application/json")+ .body("""+ {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s", "timeoutSeconds": "60"}}+ """.formatted(BUILD, ROLE))+ .when().post(revisions)+ .then().statusCode(400)+ .header("X-Amzn-Errortype", "SerializationException")+ .body("message", equalTo("STRING_VALUE can not be converted to an Integer"));++ given().contentType("application/json").body("not json")+ .when().post(revisions)+ .then().statusCode(400)+ .header("X-Amzn-Errortype", "SerializationException");++ given().when().get(revisions + "/rev-nope")+ .then().statusCode(400)+ .body("message", equalTo("Invalid revision id or ARN 'rev-nope'"));+ given().when().get(revisions + "/rev-zzzzz")+ .then().statusCode(404)+ .body("message", equalTo("The revision rev-zzzzz does not exist."));+ }++ @Test+ @Order(8)+ void tagsAndResourcePolicy() {+ given().contentType("application/json").body("{\"Tags\": {\"owner\": \"floci\"}}")+ .when().post(BASE + "/tags/" + ARN)+ .then().statusCode(204);+ given().when().get(BASE + "/tags/" + ARN)+ .then().statusCode(200)+ .body("Tags.env", equalTo("it"))+ .body("Tags.owner", equalTo("floci"));+ given().queryParam("tagKeys", "env").when().delete(BASE + "/tags/" + ARN)+ .then().statusCode(204);+ given().when().get(BASE + "/tags/" + ARN)+ .then().statusCode(200)+ .body("Tags.env", nullValue())+ .body("Tags.owner", equalTo("floci"));+ given().when().get(BASE + "/tags/" + ARN + "/endpoint/dev")+ .then().statusCode(400)+ .body("message", containsString("at 'resource' failed to satisfy constraint:"+ + " Member must satisfy regular expression pattern: arn:[^:]+:lambda:[^:]+:\\d{12}:web-function/[^/]+"));++ String policyPath = BASE + "/resource-policy/" + ARN;+ given().when().get(policyPath)+ .then().statusCode(404)+ .body("message", equalTo("The function does not have a policy."));++ String publicPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\","+ + "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + ARN + "/endpoint/*\"}]}";+ given().contentType("application/json").body(Map.of("Policy", publicPolicy))+ .when().put(policyPath)+ .then().statusCode(400)+ .body("message", equalTo("Lambda blocked the creation of this policy because it would grant public"+ + " access to your function."));++ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":"+ + "{\"AWS\":\"arn:aws:iam::000000000000:root\"},\"Action\":\"lambda:InvokeWebFunctionEndpoint\","+ + "\"Resource\":\"" + ARN + "/endpoint/*\"}]}";+ String revisionId = given().contentType("application/json").body(Map.of("Policy", policy))+ .when().put(policyPath)+ .then().statusCode(200)+ .body("Policy", equalTo(policy))+ .body("RevisionId", matchesPattern("[0-9a-f-]{36}"))+ .extract().path("RevisionId");++ given().contentType("application/json")+ .body(Map.of("Policy", policy, "RevisionId", "00000000-0000-0000-0000-000000000000"))+ .when().put(policyPath)+ .then().statusCode(409)+ .body("message", equalTo("The policy was updated or deleted by another request."+ + " Try again with the latest policy revisionId."));+ given().queryParam("RevisionId", "00000000-0000-0000-0000-000000000000").when().delete(policyPath)+ .then().statusCode(409)+ .body("message", equalTo("The policy was updated by another request. Try again."));+ given().queryParam("RevisionId", revisionId).when().delete(policyPath)+ .then().statusCode(204);+ given().when().delete(policyPath)+ .then().statusCode(404)+ .body("message", equalTo("The function does not have a policy."));+ }++ @Test+ @Order(9)+ void listingAndNames() {+ given().contentType("application/json").body("{\"filters\": [{\"name\": \"nope\", \"values\": [\"x\"]}]}")+ .when().post(BASE + "/web-functions")+ .then().statusCode(400)+ .body("message", equalTo("The filter names [nope] are invalid. Supported filter names are: [state]."));+ given().contentType("application/json").body("{\"filters\": [{\"name\": \"state\", \"values\": [\"Bogus\"]}]}")+ .when().post(BASE + "/web-functions")+ .then().statusCode(200)+ .body("functions", hasSize(0));+ given().contentType("application/json").body("{\"nextToken\": \"not-a-token\"}")+ .when().post(BASE + "/web-functions")+ .then().statusCode(400)+ .body("message", equalTo("The nextToken not-a-token is invalid or has expired."));++ given().contentType("application/json").body("{\"functionName\": \"-bad\"}")+ .when().put(BASE + "/web-functions")+ .then().statusCode(400)+ .body("message", equalTo("Invalid function name or ARN '-bad'"));+ given().contentType("application/json").body("{\"functionName\": \"lonely\"}")+ .when().put(BASE + "/web-functions")+ .then().statusCode(400)+ .body("message", equalTo("The revisionConfig and endpointConfig must be specified."));+ given().contentType("application/json").body("{}")+ .when().put(BASE + "/web-functions")+ .then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value null at 'functionName' failed to satisfy"+ + " constraint: Member must not be null"));+ given().contentType("application/json")+ .body("""+ {"functionName": "%s",+ "revisionConfig": {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s"}},+ "endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",+ "authType": "ApplicationManaged"}}+ """.formatted(FN, BUILD, ROLE))+ .when().put(BASE + "/web-functions")+ .then().statusCode(409)+ .body("message", equalTo("The function " + ARN + " already exists."));+ given().when().get(BASE + "/web-functions/does-not-exist")+ .then().statusCode(404)+ .body("message", equalTo("The function arn:aws:lambda:us-east-1:000000000000:web-function/does-not-exist"+ + " does not exist."));+ given().urlEncodingEnabled(false)+ .when().get(BASE + "/web-functions/" + URLEncoder.encode(ARN.replace(":us-east-1:", ":eu-west-1:"),+ StandardCharsets.UTF_8))+ .then().statusCode(400)+ .body("message", equalTo("The operation is only allowed in the function's home region eu-west-1."));+ given().urlEncodingEnabled(false)+ .when().get(BASE + "/web-functions/" + URLEncoder.encode(ARN.replace("000000000000", "111111111111"),+ StandardCharsets.UTF_8))+ .then().statusCode(403)+ .header("X-Amzn-Errortype", "AccessDeniedException")+ .body("message", equalTo("User: arn:aws:iam::000000000000:user/unknown is not authorized to perform:"+ + " lambda:GetWebFunction on resource: arn:aws:lambda:us-east-1:111111111111:web-function/" + FN+ + " because no resource-based policy allows the lambda:GetWebFunction action"));+ given().contentType("application/json").body("{\"nextToken\": \"00000000-0000-0000-0000-000000000000\"}")+ .when().post(BASE + "/web-functions")+ .then().statusCode(400)+ .body("message", equalTo("The nextToken 00000000-0000-0000-0000-000000000000 is invalid or has expired."));+ }++ @Test+ @Order(10)+ void deleteRemovesEverything() {+ given().when().delete(BASE + "/web-functions/" + FN).then().statusCode(204);+ given().when().get(BASE + "/web-functions/" + FN)+ .then().statusCode(404)+ .body("message", equalTo("The function " + ARN + " does not exist."));+ given().when().get(BASE + "/web-functions/" + FN + "/endpoints/dev")+ .then().statusCode(404)+ .body("message", equalTo("The function " + ARN + " does not exist."));+ given().when().delete(BASE + "/web-functions/" + FN)+ .then().statusCode(404);+ given().when().get(BASE + "/web-account-settings")+ .then().statusCode(200)+ .body("accountUsage.functionCount", equalTo(0));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.javanew file mode 100644index 0000000000..b46636ff61--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebServiceTest.java@@ -0,0 +1,572 @@+package io.github.hectorvent.floci.services.lambdaweb;++import com.fasterxml.jackson.core.type.TypeReference;+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.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.PersistentStorage;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;+import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Path;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++class LambdaWebServiceTest {++ private static final String REGION = "us-east-1";+ private static final String ACCOUNT_ID = "000000000000";+ private static final String ARN = "arn:aws:lambda:us-east-1:000000000000:web-function/app";+ private static final String ROLE = "arn:aws:iam::000000000000:role/web";++ private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();++ @TempDir+ Path storageDir;++ private LambdaWebService service() {+ return service(new MemoryStorageFactory());+ }++ private LambdaWebService service(StorageFactory storage) {+ EmulatorConfig config = mock(EmulatorConfig.class);+ when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");+ LambdaWebService service = new LambdaWebService(new RegionResolver(REGION, ACCOUNT_ID), storage, config, null,+ mapper, null);+ service.initializeStorage();+ return service;+ }++ private ObjectNode revisionConfig(int timeoutSeconds) {+ ObjectNode config = mapper.createObjectNode();+ ObjectNode build = config.putObject("buildConfig");+ build.putObject("codeConfig").putObject("s3Object").put("bucket", "code").put("key", "app.zip");+ build.putObject("runtimeConfig").put("runtime", "nodejs24.x");+ config.putObject("serviceConfig").put("executionRoleArn", ROLE).put("timeoutSeconds", timeoutSeconds);+ return config;+ }++ private ObjectNode endpointConfig(String name) {+ return mapper.createObjectNode().put("endpointName", name).put("endpointType", "HomeRegion")+ .put("authType", "ApplicationManaged").put("autoDeploymentMode", "LatestRevision");+ }++ private ObjectNode createRequest(String name) {+ ObjectNode request = mapper.createObjectNode().put("functionName", name);+ request.set("revisionConfig", revisionConfig(30));+ request.set("endpointConfig", endpointConfig("dev"));+ return request;+ }++ private static String message(Runnable call) {+ return assertThrows(AwsException.class, call::run).getMessage();+ }++ private static AwsException error(Runnable call) {+ return assertThrows(AwsException.class, call::run);+ }++ @Test+ void shapeErrorsAreCountedAndJoinedBeforeAnyBusinessRule() {+ ObjectNode request = createRequest("-bad-name-");+ ((ObjectNode) request.path("revisionConfig").path("buildConfig").path("codeConfig").path("s3Object"))+ .put("bucket", "b");+ AwsException e = error(() -> service().createFunction(REGION, request));+ assertEquals("ValidationException", e.getErrorCode());+ assertEquals("2 validation errors detected: Value 'b' at 'revisionConfig.buildConfig.codeConfig.s3Object.bucket'"+ + " failed to satisfy constraint: Member must have length greater than or equal to 3; Value 'b' at"+ + " 'revisionConfig.buildConfig.codeConfig.s3Object.bucket' failed to satisfy constraint: Member must"+ + " satisfy regular expression pattern: ([a-z0-9][a-z0-9\\.\\-]{1,61}[a-z0-9])", e.getMessage());+ }++ @Test+ void endpointConfigMembersAreRequiredInTheOrderAwsReportsThem() {+ ObjectNode request = createRequest("app");+ request.putObject("endpointConfig");+ assertEquals("3 validation errors detected: Value null at 'endpointConfig.endpointType' failed to satisfy"+ + " constraint: Member must not be null; Value null at 'endpointConfig.endpointName' failed to satisfy"+ + " constraint: Member must not be null; Value null at 'endpointConfig.authType' failed to satisfy"+ + " constraint: Member must not be null", message(() -> service().createFunction(REGION, request)));++ ObjectNode noAuth = createRequest("app");+ ((ObjectNode) noAuth.get("endpointConfig")).remove("authType");+ assertEquals("1 validation error detected: Value null at 'endpointConfig.authType' failed to satisfy constraint:"+ + " Member must not be null", message(() -> service().createFunction(REGION, noAuth)));+ }++ @Test+ void integerMembersAreNotCoercedFromOtherTypes() {+ LambdaWebService service = service();+ ObjectNode text = createRequest("app");+ ((ObjectNode) text.path("revisionConfig").path("serviceConfig")).put("timeoutSeconds", "60");+ AwsException e = error(() -> service.createFunction(REGION, text));+ assertEquals("SerializationException", e.getErrorCode());+ assertEquals("STRING_VALUE can not be converted to an Integer", e.getMessage());++ ObjectNode bool = createRequest("app");+ ((ObjectNode) bool.path("revisionConfig").path("serviceConfig")).put("timeoutSeconds", true);+ assertEquals("TRUE_VALUE can not be converted to an Integer", message(() -> service.createFunction(REGION, bool)));++ ObjectNode big = createRequest("app");+ ((ObjectNode) big.path("revisionConfig").path("serviceConfig")).put("timeoutSeconds", 4294967299L);+ assertEquals("1 validation error detected: Value '2147483647' at 'revisionConfig.serviceConfig.timeoutSeconds'"+ + " failed to satisfy constraint: Member must have value less than or equal to 900",+ message(() -> service.createFunction(REGION, big)));++ ObjectNode number = createRequest("app");+ ((ObjectNode) number.path("revisionConfig").path("serviceConfig")).put("executionRoleArn", 12345);+ assertEquals("NUMBER_VALUE can not be converted to a String", message(() -> service.createFunction(REGION, number)));+ }++ @Test+ void mapMembersMustBeObjects() {+ LambdaWebService service = service();+ ObjectNode list = createRequest("app");+ list.putArray("tags").add("env=test");+ AwsException e = error(() -> service.createFunction(REGION, list));+ assertEquals("SerializationException", e.getErrorCode());+ assertEquals("Start of list found where not expected", e.getMessage());++ ObjectNode text = createRequest("app");+ text.put("tags", "x");+ assertEquals("Expected map or null", message(() -> service.createFunction(REGION, text)));++ ObjectNode weights = endpointConfig("dev").put("autoDeploymentMode", "Disabled");+ weights.putObject("revisionWeights").put("revisionId", "rev-aaaaa").put("weight", 100);+ assertEquals("Start of structure or map found where not expected.",+ message(() -> service.createEndpoint(REGION, "app", weights)));+ }++ @Test+ void tagValuesAreValidatedAsAMap() {+ ObjectNode request = createRequest("app");+ request.putObject("tags").put("team", "has;semicolon");+ assertEquals("1 validation error detected: Value '{team=has;semicolon}' at 'tags' failed to satisfy constraint:"+ + " Map value must satisfy constraint: [Member must have length less than or equal to 256, Member must"+ + " have length greater than or equal to 0, Member must satisfy regular expression pattern:"+ + " [a-zA-Z0-9 _\\.:/=+\\-@]*]", message(() -> service().createFunction(REGION, request)));+ }++ @Test+ void tagRulesFollowTheAwsTagMessage() {+ LambdaWebService service = service();+ service.createFunction(REGION, createRequest("app"));+ String rule = "One or more of your tags are invalid. Please ensure none of your tag keys start with \"aws:\","+ + " none are empty, and there are no duplicate tag keys.";+ ObjectNode nullValue = mapper.createObjectNode();+ nullValue.putObject("Tags").putNull("env");+ assertEquals(rule, message(() -> service.tagResource(REGION, ARN, nullValue)));+ ObjectNode reserved = mapper.createObjectNode();+ reserved.putObject("Tags").put("aws:cloudformation:stack-name", "s");+ assertEquals(rule, message(() -> service.tagResource(REGION, ARN, reserved)));++ ObjectNode empty = mapper.createObjectNode();+ empty.putObject("Tags").put("team", "");+ service.tagResource(REGION, ARN, empty);+ assertEquals("", service.listTags(REGION, ARN).get("team"));++ assertEquals("2 validation errors detected: Value 'not-an-arn' at 'resource' failed to satisfy constraint: Member"+ + " must satisfy regular expression pattern: arn:[^:]+:lambda:[^:]+:\\d{12}:web-function/[^/]+; Value"+ + " null at 'tags' failed to satisfy constraint: Member must not be null",+ message(() -> service.tagResource(REGION, "not-an-arn", mapper.createObjectNode())));+ }++ @Test+ void untagValidatesEveryKey() {+ LambdaWebService service = service();+ service.createFunction(REGION, createRequest("app"));+ assertEquals("1 validation error detected: Value '[]' at 'tagKeys' failed to satisfy constraint: Member must"+ + " satisfy constraint: [Member must have length less than or equal to 128, Member must have length"+ + " greater than or equal to 1, Member must satisfy regular expression pattern: [a-zA-Z0-9 _\\.:/=+\\-@]+]",+ message(() -> service.untagResource(REGION, ARN, List.of(""))));+ assertEquals("1 validation error detected: Value '[bad#key]' at 'tagKeys' failed to satisfy constraint: Member"+ + " must satisfy constraint: [Member must have length less than or equal to 128, Member must have length"+ + " greater than or equal to 1, Member must satisfy regular expression pattern: [a-zA-Z0-9 _\\.:/=+\\-@]+]",+ message(() -> service.untagResource(REGION, ARN, List.of("bad#key"))));+ assertEquals("1 validation error detected: Value null at 'tagKeys' failed to satisfy constraint: Member must not"+ + " be null", message(() -> service.untagResource(REGION, ARN, null)));+ service.untagResource(REGION, ARN, List.of("absent"));+ }++ @Test+ void environmentVariablesAreASensitiveMap() {+ LambdaWebService service = service();+ ObjectNode badKey = revisionConfig(30);+ ((ObjectNode) badKey.get("serviceConfig")).putObject("environmentVariables").put("1BAD", "x");+ assertEquals("1 validation error detected: Value at 'serviceConfig.environmentVariables' failed to satisfy"+ + " constraint: Map keys must satisfy constraint: [Member must have length greater than or equal to 1,"+ + " Member must satisfy regular expression pattern: [a-zA-Z]([a-zA-Z0-9_])*]",+ message(() -> service.createRevision(REGION, "app", badKey)));++ ObjectNode both = revisionConfig(30);+ ((ObjectNode) both.get("serviceConfig")).putObject("environmentVariables").put("1BAD", "");+ assertEquals("2 validation errors detected: Value at 'serviceConfig.environmentVariables' failed to satisfy"+ + " constraint: Map keys must satisfy constraint: [Member must have length greater than or equal to 1,"+ + " Member must satisfy regular expression pattern: [a-zA-Z]([a-zA-Z0-9_])*]; Value at"+ + " 'serviceConfig.environmentVariables' failed to satisfy constraint: Map value must satisfy constraint:"+ + " [Member must have length greater than or equal to 1]",+ message(() -> service.createRevision(REGION, "app", both)));++ ObjectNode nullValue = revisionConfig(30);+ ((ObjectNode) nullValue.get("serviceConfig")).putObject("environmentVariables").putNull("FOO").put("BAR", "1");+ service.createFunction(REGION, createRequest("app"));+ WebFunctionRevision revision = service.createRevision(REGION, "app", nullValue);+ assertEquals(Map.of("BAR", "1"), revision.serviceConfig.environmentVariables);+ }++ @Test+ void requestRulesRunBeforeTheFunctionLookup() {+ LambdaWebService service = service();+ ObjectNode reserved = revisionConfig(30);+ ((ObjectNode) reserved.get("serviceConfig")).putObject("environmentVariables").put("AWS_REGION", "x");+ assertEquals("The environmentVariables cannot contain reserved keys. The request specified the reserved keys"+ + " [AWS_REGION].", message(() -> service.createRevision(REGION, "missing", reserved)));++ ObjectNode rate = endpointConfig("dev").put("autoDeploymentMode", "Disabled");+ rate.putArray("revisionWeights").addObject().put("revisionId", "rev-aaaaa").put("weight", 100);+ rate.putObject("throttleConfig").put("rateLimit", 150);+ assertEquals("The rateLimit 150 is invalid. Supported rate limits are: [0, 100, 200, 300, 400, 500, 600, 700,"+ + " 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000].",+ message(() -> service.createEndpoint(REGION, "missing", rate)));++ ObjectNode update = mapper.createObjectNode();+ update.putObject("throttleConfig").put("rateLimit", 150);+ assertEquals("ResourceNotFoundException",+ error(() -> service.updateEndpoint(REGION, "missing", "dev", update)).getErrorCode());+ }++ @Test+ void aRejectedEndpointUpdateChangesNothing() {+ LambdaWebService service = service();+ service.createFunction(REGION, createRequest("app"));++ ObjectNode partial = mapper.createObjectNode().put("authType", "IamAuth").put("description", "d");+ partial.putObject("throttleConfig").put("rateLimit", 150);+ assertEquals("ValidationException", error(() -> service.updateEndpoint(REGION, "app", "dev", partial)).getErrorCode());+ WebFunctionEndpoint endpoint = service.getEndpoint(REGION, "app", "dev");+ assertEquals("ApplicationManaged", endpoint.authType);+ assertNull(endpoint.description);+ assertNull(endpoint.updateStatus);++ ObjectNode unknownRevision = mapper.createObjectNode().put("autoDeploymentMode", "Disabled");+ unknownRevision.putArray("revisionWeights").addObject().put("revisionId", "rev-zzzzz").put("weight", 100);+ assertEquals("The revision rev-zzzzz does not exist.",+ message(() -> service.updateEndpoint(REGION, "app", "dev", unknownRevision)));+ assertEquals("LatestRevision", service.getEndpoint(REGION, "app", "dev").autoDeploymentMode);+ }++ @Test+ void listsPageByNameWithCursorTokens() {+ LambdaWebService service = service();+ for (String name : List.of("charlie", "alpha", "bravo")) {+ service.createFunction(REGION, createRequest(name));+ }+ ObjectNode request = mapper.createObjectNode().put("maxResults", 2);+ PaginatedResult<WebFunction> first = service.listFunctions(REGION, request);+ assertEquals(List.of("alpha", "bravo"), first.items().stream().map(f -> f.functionName).toList());+ assertNotNull(first.nextToken());++ request.put("nextToken", first.nextToken());+ PaginatedResult<WebFunction> second = service.listFunctions(REGION, request);+ assertEquals(List.of("charlie"), second.items().stream().map(f -> f.functionName).toList());+ assertNull(second.nextToken());++ assertEquals(3, service.accountSettings(REGION).functionCount());+ assertEquals(0, service.accountSettings("eu-west-1").functionCount());++ ObjectNode unknown = mapper.createObjectNode().put("nextToken", "00000000-0000-0000-0000-000000000000");+ assertEquals("The nextToken 00000000-0000-0000-0000-000000000000 is invalid or has expired.",+ message(() -> service.listFunctions(REGION, unknown)));+ // The item a page ended on is gone: the next page starts past it in sort order, as on AWS.+ service.deleteFunction(REGION, "bravo");+ assertEquals(List.of("charlie"),+ service.listFunctions(REGION, request).items().stream().map(f -> f.functionName).toList());+ }++ @Test+ void pageTokensBelongToTheRequestThatIssuedThem() {+ LambdaWebService service = service();+ service.createFunction(REGION, createRequest("alpha"));+ service.createFunction(REGION, createRequest("bravo"));+ service.createRevision(REGION, "alpha", revisionConfig(60));+ ObjectNode request = mapper.createObjectNode().put("maxResults", 1);+ String functionsToken = service.listFunctions(REGION, request).nextToken();+ String mismatch = "The nextToken " + functionsToken + " does not match the request. Subsequent pagination"+ + " requests must use the same parameters as the initial request.";+ ObjectNode reused = mapper.createObjectNode().put("maxResults", 1).put("nextToken", functionsToken);+ assertEquals(mismatch, message(() -> service.listRevisions(REGION, "alpha", reused)));+ assertEquals(mismatch, message(() -> service.listEndpoints(REGION, "alpha", reused)));+ ObjectNode otherSize = mapper.createObjectNode().put("maxResults", 2).put("nextToken", functionsToken);+ assertEquals(mismatch, message(() -> service.listFunctions(REGION, otherSize)));++ ObjectNode revisions = mapper.createObjectNode().put("maxResults", 1);+ PaginatedResult<WebFunctionRevision> newest = service.listRevisions(REGION, "alpha", revisions);+ assertEquals(60, newest.items().get(0).serviceConfig.timeoutSeconds);+ revisions.put("nextToken", newest.nextToken());+ assertEquals(30, service.listRevisions(REGION, "alpha", revisions).items().get(0).serviceConfig.timeoutSeconds);+ }++ @Test+ void readsAreSnapshotsOfTheStoredState() {+ LambdaWebService service = service();+ service.createFunction(REGION, createRequest("app"));+ WebFunctionEndpoint endpoint = service.getEndpoint(REGION, "app", "dev");+ endpoint.description = "changed by the caller";+ endpoint.revisionWeights.clear();+ WebFunctionEndpoint again = service.getEndpoint(REGION, "app", "dev");+ assertNull(again.description);+ assertEquals(1, again.revisionWeights.size());+ WebFunction fn = service.getFunction(REGION, "app");+ fn.tags.put("leak", "x");+ assertFalse(service.getFunction(REGION, "app").tags.containsKey("leak"));+ }++ @Test+ void stateFilterMatchesOnlyActive() {+ LambdaWebService service = service();+ service.createFunction(REGION, createRequest("app"));+ ObjectNode filtered = mapper.createObjectNode();+ filtered.putArray("filters").addObject().put("name", "state").putArray("values").add("Failed");+ assertTrue(service.listFunctions(REGION, filtered).items().isEmpty());+ ObjectNode unknown = mapper.createObjectNode();+ unknown.putArray("filters").addObject().put("name", "nope").putArray("values").add("x");+ assertEquals("The filter names [nope] are invalid. Supported filter names are: [state].",+ message(() -> service.listFunctions(REGION, unknown)));+ // A repeated state filter adds its values, whatever the order, as on AWS.+ for (List<String> order : List.of(List.of("Failed", "Active"), List.of("Active", "Failed"))) {+ ObjectNode repeated = mapper.createObjectNode();+ ArrayNode filters = repeated.putArray("filters");+ for (String state : order) {+ filters.addObject().put("name", "state").putArray("values").add(state);+ }+ assertEquals(1, service.listFunctions(REGION, repeated).items().size(), order.toString());+ }+ }++ @Test+ void identifiersAcceptArnsOfTheHomeRegionAndAccount() {+ LambdaWebService service = service();+ WebFunction fn = service.createFunction(REGION, createRequest("app"));+ WebFunctionEndpoint endpoint = fn.endpoints.get("dev");+ WebFunctionRevision revision = fn.revisions.values().iterator().next();+ assertEquals("dev", service.getEndpoint(REGION, fn.functionArn, endpoint.endpointArn).endpointName);+ assertEquals(revision.revisionId, service.getRevision(REGION, "app", revision.revisionArn).revisionId);+ assertEquals("dev", service.getEndpoint(REGION, "app",+ "arn:aws:lambda:us-east-1:000000000000:web-function/other/endpoint/dev").endpointName);++ assertEquals("Invalid revision id or ARN 'nope'", message(() -> service.getRevision(REGION, "app", "nope")));+ assertEquals("Invalid revision id or ARN '" + endpoint.endpointArn + "'",+ message(() -> service.getRevision(REGION, "app", endpoint.endpointArn)));+ assertEquals("Invalid endpoint name or ARN '" + revision.revisionArn + "'",+ message(() -> service.getEndpoint(REGION, "app", revision.revisionArn)));+ assertEquals("Invalid function name or ARN 'a'", message(() -> service.getFunction(REGION, "a")));+ assertEquals("Invalid function name or ARN '" + endpoint.endpointArn + "'",+ message(() -> service.getFunction(REGION, endpoint.endpointArn)));++ String foreignRegion = "arn:aws:lambda:eu-west-1:000000000000:web-function/app";+ assertEquals("The operation is only allowed in the function's home region eu-west-1.",+ message(() -> service.getFunction(REGION, foreignRegion)));+ assertEquals("The operation is only allowed in the function's home region eu-west-1.",+ message(() -> service.getEndpoint(REGION, "app", foreignRegion + "/endpoint/dev")));++ AwsException denied = error(() -> service.getFunction(REGION,+ "arn:aws:lambda:us-east-1:111111111111:web-function/app"));+ assertEquals("AccessDeniedException", denied.getErrorCode());+ assertEquals(403, denied.getHttpStatus());+ assertEquals("User: arn:aws:iam::000000000000:user/unknown is not authorized to perform: lambda:GetWebFunction"+ + " on resource: arn:aws:lambda:us-east-1:111111111111:web-function/app because no resource-based policy"+ + " allows the lambda:GetWebFunction action", denied.getMessage());+ }++ @Test+ void endpointQuotaAndInUseMessages() {+ LambdaWebService service = service();+ service.createFunction(REGION, createRequest("app"));+ for (int i = 2; i <= 10; i++) {+ service.createEndpoint(REGION, "app", endpointConfig("ep" + i));+ }+ AwsException quota = error(() -> service.createEndpoint(REGION, "app", endpointConfig("ep11")));+ assertEquals("ServiceQuotaExceededException", quota.getErrorCode());+ assertEquals(402, quota.getHttpStatus());+ assertEquals("The function " + ARN + " has reached the maxEndpointsPerFunction quota of 10.", quota.getMessage());++ String revisionId = service.listRevisions(REGION, "app", mapper.createObjectNode()).items().get(0).revisionId;+ assertEquals("The revision " + revisionId + " cannot be deleted because the endpoints [dev, ep10, ep2, ep3, ep4,"+ + " ep5, ep6, ep7, ep8, ep9] are using it. Update the endpoints to use other revisions first.",+ message(() -> service.deleteRevision(REGION, "app", revisionId)));+ }++ @Test+ void resourcePolicyDocumentsAreCheckedBeforeTheLookup() {+ LambdaWebService service = service();+ String missing = "arn:aws:lambda:us-east-1:000000000000:web-function/missing";+ String resource = missing + "/endpoint/*";+ assertEquals("Policy has syntax errors.", message(() -> service.putResourcePolicy(REGION, missing, policy("[]"))));+ assertEquals("Policy has syntax errors.", message(() -> service.putResourcePolicy(REGION, missing, policy("{}"))));+ assertEquals("Policy has syntax errors.", message(() -> service.putResourcePolicy(REGION, missing,+ policy("{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"},"+ + "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"*\"}]}"))));+ assertEquals("Effect must be explicitly available for a statement", message(() -> service.putResourcePolicy(+ REGION, missing, policy("{\"Statement\":[{\"Principal\":\"*\",\"Action\":\"lambda:InvokeWebFunctionEndpoint\","+ + "\"Resource\":\"" + resource + "\"}]}"))));+ assertEquals("Syntax error at position (-1,-1)", message(() -> service.putResourcePolicy(REGION, missing,+ policy("{\"Statement\":[{\"Foo\":\"bar\",\"Effect\":\"Allow\",\"Principal\":\"*\","+ + "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + resource + "\"}]}"))));+ assertEquals("The provided principal was invalid. Please check the principal and try again.",+ message(() -> service.putResourcePolicy(REGION, missing, policy("{\"Statement\":[{\"Effect\":\"Allow\","+ + "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + resource + "\"}]}"))));+ // Empty arrays: the principal is checked first, then the action and resource grammar.+ String members = "{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":%s,\"Action\":%s,\"Resource\":%s}]}";+ String root = "{\"AWS\":\"arn:aws:iam::000000000000:root\"}";+ String invoke = "\"lambda:InvokeWebFunctionEndpoint\"";+ assertEquals("Policy has syntax errors.", message(() -> service.putResourcePolicy(REGION, missing,+ policy(members.formatted(root, "[]", "\"" + resource + "\"")))));+ assertEquals("Policy has syntax errors.", message(() -> service.putResourcePolicy(REGION, missing,+ policy(members.formatted(root, invoke, "[]")))));+ assertEquals("The provided principal was invalid. Please check the principal and try again.",+ message(() -> service.putResourcePolicy(REGION, missing,+ policy(members.formatted("{\"AWS\":[]}", invoke, "\"" + resource + "\"")))));+ assertEquals("The provided principal was invalid. Please check the principal and try again.",+ message(() -> service.putResourcePolicy(REGION, missing,+ policy(members.formatted("{\"AWS\":[]}", "[]", "[]")))));+ assertEquals("The provided input'*'was invalid. Member must satisfy expression: [\\w+=,.@-]* Please check your"+ + " input and try again.", message(() -> service.putResourcePolicy(REGION, missing,+ policy("{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"*\"},"+ + "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + resource + "\"}]}"))));+ assertEquals("Lambda blocked the creation of this policy because it would grant public access to your function.",+ message(() -> service.putResourcePolicy(REGION, missing, policy("{\"Statement\":[{\"Effect\":\"Allow\","+ + "\"Principal\":{\"AWS\":[\"arn:aws:iam::000000000000:root\",\"*\"]},"+ + "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + resource + "\"}]}"))));+ // A wildcard principal is public unless a positive operator pins a trusted key without a wildcard.+ String blocked = "Lambda blocked the creation of this policy because it would grant public access"+ + " to your function.";+ for (String condition : List.of(+ "{\"StringNotEquals\":{\"aws:PrincipalAccount\":\"000000000000\"}}",+ "{\"StringLike\":{\"aws:PrincipalAccount\":\"0000*\"}}",+ "{\"StringEqualsIfExists\":{\"aws:PrincipalAccount\":\"000000000000\"}}",+ "{\"ArnLike\":{\"aws:PrincipalArn\":\"arn:aws:iam::*:role/x\"}}",+ "{\"StringLike\":{\"aws:PrincipalOrgID\":\"o-*\"}}",+ "{\"StringEquals\":{\"aws:username\":\"alice\"}}")) {+ assertEquals(blocked, message(() -> service.putResourcePolicy(REGION, missing,+ policy(conditioned(resource, condition)))), condition);+ }+ for (String pinned : List.of(+ "{\"StringEquals\":{\"aws:SourceAccount\":\"000000000000\"}}",+ "{\"StringLike\":{\"aws:PrincipalAccount\":\"000000000000\"}}",+ "{\"StringEquals\":{\"aws:PrincipalAccount\":[\"000000000000\",\"*\"]}}",+ "{\"ArnLike\":{\"aws:PrincipalArn\":\"arn:aws:iam::000000000000:*\"}}",+ "{\"StringNotEquals\":{\"aws:PrincipalAccount\":\"111122223333\"},"+ + "\"StringEquals\":{\"aws:PrincipalArn\":\"arn:aws:iam::000000000000:root\"}}",+ "{\"Bool\":{\"aws:PrincipalIsAWSService\":\"true\"}}")) {+ assertEquals("ResourceNotFoundException", error(() -> service.putResourcePolicy(REGION, missing,+ policy(conditioned(resource, pinned)))).getErrorCode(), pinned);+ }+ for (String accepted : List.of(+ "{\"Statement\":{\"Effect\":\"Deny\",\"Principal\":\"*\",\"Action\":\"lambda:*\",\"Resource\":\"" + missing + "\"}}",+ "{\"Statement\":[{\"Effect\":\"allow\",\"Principal\":{\"Federated\":\"*\"},"+ + "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + resource + "\"}]}")) {+ assertEquals("ResourceNotFoundException",+ error(() -> service.putResourcePolicy(REGION, missing, policy(accepted))).getErrorCode(), accepted);+ }+ }++ private ObjectNode policy(String document) {+ return mapper.createObjectNode().put("Policy", document);+ }++ private static String conditioned(String resource, String condition) {+ return "{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"lambda:InvokeWebFunctionEndpoint\","+ + "\"Resource\":\"" + resource + "\",\"Condition\":" + condition + "}]}";+ }++ @Test+ void functionsSurviveARestart() {+ LambdaWebService first = service(new FileStorageFactory(storageDir));+ WebFunction created = first.createFunction(REGION, createRequest("durable"));+ first.createRevision(REGION, "durable", revisionConfig(60));+ ObjectNode update = mapper.createObjectNode().put("description", "updated");+ first.updateEndpoint(REGION, "durable", "dev", update);++ LambdaWebService second = service(new FileStorageFactory(storageDir));+ WebFunction restored = second.getFunction(REGION, "durable");+ assertEquals(created.functionArn, restored.functionArn);+ assertEquals(2, restored.revisions.size());+ WebFunctionEndpoint endpoint = second.getEndpoint(REGION, "durable", "dev");+ assertEquals("updated", endpoint.description);+ assertEquals("Successful", endpoint.updateStatus);+ assertEquals(60, second.listRevisions(REGION, "durable", mapper.createObjectNode())+ .items().get(0).serviceConfig.timeoutSeconds);+ assertEquals(endpoint.revisionWeights.get(0).revisionId,+ second.listRevisions(REGION, "durable", mapper.createObjectNode()).items().get(0).revisionId,+ "the LatestRevision endpoint moved to the newer revision and that move was written back");+ }++ private static final class MemoryStorageFactory extends StorageFactory {+ private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();++ private MemoryStorageFactory() {+ super(null, null);+ }++ @Override+ @SuppressWarnings("unchecked")+ public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,+ TypeReference<Map<String, V>> typeReference) {+ return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName,+ ignored -> AccountAwareStorageBackend.inMemory(ACCOUNT_ID));+ }+ }++ /** Real files rather than memory, so only what reached the backend comes back. */+ private static final class FileStorageFactory extends StorageFactory {+ private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();+ private final Path directory;++ private FileStorageFactory(Path directory) {+ super(null, null);+ this.directory = directory;+ }++ @Override+ @SuppressWarnings("unchecked")+ public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,+ TypeReference<Map<String, V>> typeReference) {+ return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName, ignored -> {+ PersistentStorage<String, V> inner = new PersistentStorage<>(directory.resolve(fileName), typeReference);+ inner.load();+ return new AccountAwareStorageBackend<V>(inner, null, ACCOUNT_ID);+ });+ }+ }++ @Test+ void jsonTreeOfARevisionRoundTrips() {+ LambdaWebService service = service();+ WebFunction fn = service.createFunction(REGION, createRequest("app"));+ JsonNode tree = mapper.valueToTree(fn);+ WebFunction back = mapper.convertValue(tree, WebFunction.class);+ assertEquals(fn.revisions.keySet(), back.revisions.keySet());+ assertEquals(fn.endpoints.get("dev").domainName, back.endpoints.get("dev").domainName);+ }+}diff --git a/tools/docs/service_inventory.py b/tools/docs/service_inventory.pyindex 8994d47057..b3379cab15 100644--- a/tools/docs/service_inventory.py+++ b/tools/docs/service_inventory.py@@ -62,6 +62,7 @@ PACKAGE_NOTES = {"cloudwatch": "one package, two descriptors: cloudwatchlogs and cloudwatchmetrics","floci": "Floci's own control surface, not an AWS service","lambdamicrovms": "controllers attached to the lambda descriptor",+ "lambdaweb": "controller attached to the lambda descriptor","resourcegroupstagging": "registered under the AWS signing name, tagging","securityadmin": "shared admin-accounts endpoint over GuardDuty and Macie","signin": "controller attached to the signin descriptor, which is keyed iam",diff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex cc1eadae87..3cc24422a1 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -100,6 +100,10 @@ services:- TagResourceByBody- TagResourcePut- UntagResourceByQuery+ - service: lambdaweb+ doc: docs/services/lambda-web-functions.md+ sources:+ - { path: src/main/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebController.java, mode: rest }- service: marketplacedoc: docs/services/marketplace.mdsources: