mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
feat(lambdaweb): Lambda Web Functions control plane (#5706)
* feat(lambdaweb): Lambda Web Functions control plane The lambda-web service model (apiVersion 2025-03-07) signs as lambda, so it is served under the lambda service at /2025-03-07/... with the AWS wire shapes, state words and error wording of the 20 operations on web functions, revisions, endpoints, tags and the resource policy. Revisions and endpoints converge at once. They are stored Active and an endpoint update is stored Successful, while the create and update responses report the transitional state AWS reports, so a CLI waiter settles on its first poll. Code comes from an S3 object that must exist. IamAuth, the resource policy and the endpoint domain are stored but not served yet. Part of #5699 * fix(lambdaweb): carry the page position in the token The nextToken of a list operation was a UUID keyed into an in-memory anchor map that only grew and was not scoped to the account. The token is now a core Pagination cursor that encodes the request (operation, region, account, function, filters and page size) and the cursor of the item the page ended on. A token reused with other parameters gets the AWS "does not match the request" error and any other token the AWS "invalid or has expired" error. AWS issues UUID tokens and rejects any other shape, so Floci no longer reproduces the pattern error for a malformed token. * fix(iam): resolve a Lambda Web revision or endpoint named by its ARN The route resource for IAM enforcement took the path segment after revisions or endpoints as the id. A revision or endpoint ARN in that position carries slashes, so the resource ARN ended in the ARN's first segment and a policy scoped to the revision or endpoint did not apply. The id is now the last segment of such an ARN. * fix(lambdaweb): add the values of a repeated state filter AWS lists a function when any state filter in the request names its state. A later state filter replaced the earlier one, so a request with state=Active followed by state=Failed listed nothing. * fix(lambdaweb): refuse empty arrays in a resource policy AWS answers an empty Action or Resource array with the policy syntax error and an empty principal array with the invalid principal error, which wins when all three are empty. Floci stored such a policy. * fix(lambdaweb): judge a wildcard principal by the operator and value of its condition A trusted condition key alone kept an Allow for every principal out of the public check. AWS blocks the policy unless a positive operator pins the key: StringNotEquals and the IfExists forms do not count, nor does a wildcard in an account value or in the account field of an ARN value, while a wildcard elsewhere in an ARN and a literal * under StringEquals do.
This commit is contained in:
1 parent
ee15f502bf
commit
6f78083080
26 files changed
+4073
-3
No files matched your search
@@ -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 |
|
||||
|
||||
@@ -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=""
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 |
|
||||
|
||||
@@ -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.
|
||||
@@ -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.md
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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 filter
|
||||
|
||||
|
||||
@@ -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 or
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<>();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<>();
|
||||
}
|
||||
+48
@@ -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;
|
||||
}
|
||||
}
|
||||
+40
@@ -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";
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -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) {
|
||||
|
||||
@@ -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, "{}"));
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaRoutesOtherThanInvokeAreCheckedAgainstTheCallersUnqualifiedFunction() {
|
||||
when(uriInfo.getPath()).thenReturn(
|
||||
|
||||
+587
@@ -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));
|
||||
}
|
||||
}
|
||||
+572
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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: marketplace
|
||||
doc: docs/services/marketplace.md
|
||||
sources:
|
||||
|
||||
Reference in new issue
Block a user