From 385ffcfdd01c115e9da3d5de5107693e20401b17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Thu, 29 Oct 2026 13:54:49 +0900 Subject: [PATCH] feat(lambdaweb): set the WebFunctionAuthType condition keys on endpoint routes (#6893) --- .github/workflows/iam-data-drift.yml | 9 +- .github/workflows/partition-literals.yml | 3 + Makefile | 19 ++- docs/services/iam.md | 9 ++ .../common/IamConditionContextResolver.java | 47 +++++- .../core/common/LambdaWebConditionKeys.java | 43 +++++ .../floci/core/common/PassedRoles.java | 2 +- .../services/iam/ResourceArnBuilder.java | 2 +- .../aws/lambda-web-condition-keys.json | 46 ++++++ .../IamConditionContextResolverTest.java | 59 ++++++- .../dynamodb/backend/DynamoDbFacadeTest.java | 3 +- ...bAuthTypeConditionKeysIntegrationTest.java | 131 +++++++++++++++ tools/aws/regen_lambda_web_condition_keys.py | 151 ++++++++++++++++++ .../test_regen_lambda_web_condition_keys.py | 92 +++++++++++ 14 files changed, 604 insertions(+), 12 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/LambdaWebConditionKeys.java create mode 100644 src/main/resources/aws/lambda-web-condition-keys.json create mode 100644 src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebAuthTypeConditionKeysIntegrationTest.java create mode 100644 tools/aws/regen_lambda_web_condition_keys.py create mode 100644 tools/aws/test_regen_lambda_web_condition_keys.py diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 74a834fede..77a6050ac5 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -1,13 +1,13 @@ name: IAM Data Drift -# Checks the ten vendored files that come from AWS's live service reference rather than from a +# Checks the eleven vendored files that come from AWS's live service reference rather than from a # pinned dependency: the IAM service namespace list, the map of which resource each IAM action is # authorized against, the map of operations AWS authorizes as an action of another name, the # table of the operations that pass a role and the services they pass it to, the table of the # operations that pass a Lambda network connector, the table of the # tagging actions operations that tag what they create need, the table of the resources each -# operation's request names, the DynamoDB condition key table, the IAM condition key table, and -# the S3 Control tag condition key table. That +# operation's request names, the DynamoDB condition key table, the IAM condition key table, the +# S3 Control tag condition key table, and the Lambda Web condition key table. That # needs the live service reference index, so unlike every other check here it can # fail without anything in the repository having changed: an AWS outage, or a namespace AWS has # retired. It therefore runs on its own, never as part of a job that ordinary changes trigger. @@ -66,6 +66,9 @@ on: - 'src/main/resources/aws/s3control-tag-condition-keys.json' - 'tools/aws/regen_s3control_tag_condition_keys.py' - 'tools/aws/test_regen_s3control_tag_condition_keys.py' + - 'src/main/resources/aws/lambda-web-condition-keys.json' + - 'tools/aws/regen_lambda_web_condition_keys.py' + - 'tools/aws/test_regen_lambda_web_condition_keys.py' - 'tools/aws/regen_partitions.py' - 'tools/aws/regen_query_services.py' - '.github/workflows/iam-data-drift.yml' diff --git a/.github/workflows/partition-literals.yml b/.github/workflows/partition-literals.yml index aa3f511943..bb4f89a2a7 100644 --- a/.github/workflows/partition-literals.yml +++ b/.github/workflows/partition-literals.yml @@ -108,6 +108,9 @@ jobs: - name: Check S3 Control tag condition request members run: make s3control-tag-condition-keys-check + - name: Check Lambda Web condition request members + run: make lambda-web-condition-keys-check + - name: Check partitions.json against a fresh generation run: make aws-data-check diff --git a/Makefile b/Makefile index a0ca3494ea..876f1a9657 100644 --- a/Makefile +++ b/Makefile @@ -437,6 +437,9 @@ IAM_CONDITION_KEYS_PATHS := src/main/resources/aws/iam-condition-keys.json \ S3CONTROL_TAG_CONDITION_KEYS_PATHS := src/main/resources/aws/s3control-tag-condition-keys.json \ tools/aws/regen_s3control_tag_condition_keys.py tools/aws/test_regen_s3control_tag_condition_keys.py \ tools/aws/regen_iam_tag_on_create.py $(IAM_PASSED_ROLES_GENERATOR) +LAMBDA_WEB_CONDITION_KEYS_PATHS := src/main/resources/aws/lambda-web-condition-keys.json \ + tools/aws/regen_lambda_web_condition_keys.py tools/aws/test_regen_lambda_web_condition_keys.py \ + tools/aws/regen_dynamodb_condition_keys.py tools/aws/regen_iam_tag_on_create.py $(IAM_PASSED_ROLES_GENERATOR) IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \ tools/aws/regen_iam_request_resources.py $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/test_regen_iam_request_resources.py @@ -445,7 +448,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A @# Every check runs even when an earlier one fails, so one file's drift cannot hide another's @# state. Sequential steps in CI stop at the first failure, which once left the action @# resource gate unexercised while the namespace list was stale. - @namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; dynamodb=0; conditionkeys=0; s3control=0; \ + @namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; dynamodb=0; conditionkeys=0; s3control=0; lambdaweb=0; \ covers() { \ [ -z "$(strip $(CHANGED))" ] && return 0; \ for path in $(CHANGED); do case " $$1 " in *" $$path "*) return 0;; esac; done; \ @@ -482,9 +485,12 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A if covers "$(S3CONTROL_TAG_CONDITION_KEYS_PATHS)" "the S3 Control tag condition key table"; then \ $(MAKE) --no-print-directory s3control-tag-condition-keys-verify || s3control=$$?; \ fi; \ + if covers "$(LAMBDA_WEB_CONDITION_KEYS_PATHS)" "the Lambda Web condition key table"; then \ + $(MAKE) --no-print-directory lambda-web-condition-keys-verify || lambdaweb=$$?; \ + fi; \ if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ] || [ $$authorized -ne 0 ] || [ $$passed -ne 0 ] \ || [ $$connectors -ne 0 ] || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ] || [ $$dynamodb -ne 0 ] \ - || [ $$conditionkeys -ne 0 ] || [ $$s3control -ne 0 ]; then \ + || [ $$conditionkeys -ne 0 ] || [ $$s3control -ne 0 ] || [ $$lambdaweb -ne 0 ]; then \ echo ""; \ echo "error: vendored IAM data does not match upstream:"; \ if [ $$namespaces -ne 0 ]; then \ @@ -511,6 +517,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A if [ $$dynamodb -ne 0 ]; then echo " the DynamoDB condition key table"; fi; \ if [ $$conditionkeys -ne 0 ]; then echo " the IAM condition key table"; fi; \ if [ $$s3control -ne 0 ]; then echo " the S3 Control tag condition key table"; fi; \ + if [ $$lambdaweb -ne 0 ]; then echo " the Lambda Web condition key table"; fi; \ exit 1; \ fi @@ -704,3 +711,11 @@ s3control-tag-condition-keys-check: ## Check the S3 Control tag condition reques $(PYTHON) tools/aws/regen_s3control_tag_condition_keys.py --check s3control-tag-condition-keys-verify: ## Check the S3 Control tag condition action keys against AWS $(PYTHON) tools/aws/regen_s3control_tag_condition_keys.py --verify + +.PHONY: lambda-web-condition-keys-sync lambda-web-condition-keys-check lambda-web-condition-keys-verify +lambda-web-condition-keys-sync: ## Regenerate the Lambda Web condition keys from AWS and botocore + $(PYTHON) tools/aws/regen_lambda_web_condition_keys.py +lambda-web-condition-keys-check: ## Check the Lambda Web condition request members against pinned botocore + $(PYTHON) tools/aws/regen_lambda_web_condition_keys.py --check +lambda-web-condition-keys-verify: ## Check the Lambda Web condition action keys against AWS + $(PYTHON) tools/aws/regen_lambda_web_condition_keys.py --verify diff --git a/docs/services/iam.md b/docs/services/iam.md index 9b6b67925f..a58a127698 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2435,6 +2435,15 @@ floci populates: when they are requested together; `NONE` plus `ALL_OLD` needs only `ALL_OLD`. Omitted or null parameters use the execution default. Read and batch operations do not acquire this key from unrelated fields. Transaction failure-image context is described below. +- `lambda:Request/WebFunctionAuthType`: the `authType` a `CreateWebFunction`, + `CreateWebFunctionEndpoint` or `UpdateWebFunctionEndpoint` request names, absent from an update + that names none. `lambda:Resource/WebFunctionAuthType`: the endpoint's `authType` before the + request, for `GetWebFunctionEndpoint`, `UpdateWebFunctionEndpoint` and + `DeleteWebFunctionEndpoint`, absent when the endpoint does not exist, as on AWS. An + `IamAuth` endpoint request carries it too (see [Lambda Web Functions](lambda-web-functions.md)). + The actions and request members come from `lambda-web-condition-keys.json`, which + `tools/aws/regen_lambda_web_condition_keys.py` generates from the Service Reference and pinned + botocore. Regenerate with `make lambda-web-condition-keys-sync`. **Any other condition key is absent from the request context.** A positive scalar operator without `IfExists` on an absent key makes the whole statement *not apply*: it neither matches nor diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java index d3620b19e3..891de014ad 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java @@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.ResourceArnBuilder; import io.github.hectorvent.floci.services.iam.model.IamRole; import io.github.hectorvent.floci.services.iam.model.IamUser; +import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService; import io.github.hectorvent.floci.services.s3.S3ControlTagConditionKeys; import io.github.hectorvent.floci.services.s3.S3ObjectActions; import io.github.hectorvent.floci.services.s3.S3ObjectKeys; @@ -86,12 +87,15 @@ public class IamConditionContextResolver { public static final String OBJECT_LOCK_RETAIN_UNTIL_DATE = "s3:object-lock-retain-until-date"; public static final String OBJECT_LOCK_REMAINING_RETENTION_DAYS = "s3:object-lock-remaining-retention-days"; public static final String OBJECT_LOCK_LEGAL_HOLD = "s3:object-lock-legal-hold"; + static final String REQUEST_AUTH_TYPE = "lambda:Request/WebFunctionAuthType"; + static final String RESOURCE_AUTH_TYPE = "lambda:Resource/WebFunctionAuthType"; private final Instance dynamoDbFacade; private final Instance ec2Service; private final Instance s3Service; private final Instance logsService; private final Instance iamService; + private final Instance lambdaWebService; private final RequestContext requestContext; private final EmulatorConfig config; private final CurrentVertxRequest currentVertxRequest; @@ -108,12 +112,13 @@ public class IamConditionContextResolver { Instance s3Service, Instance logsService, Instance iamService, + Instance lambdaWebService, RequestContext requestContext, EmulatorConfig config, CurrentVertxRequest currentVertxRequest, ResolvedServiceCatalog serviceCatalog) { - this(dynamoDbFacade, ec2Service, s3Service, logsService, iamService, requestContext, config, currentVertxRequest, - serviceCatalog, Clock.systemUTC()); + this(dynamoDbFacade, ec2Service, s3Service, logsService, iamService, lambdaWebService, requestContext, + config, currentVertxRequest, serviceCatalog, Clock.systemUTC()); } IamConditionContextResolver(Instance dynamoDbFacade, @@ -121,6 +126,7 @@ public class IamConditionContextResolver { Instance s3Service, Instance logsService, Instance iamService, + Instance lambdaWebService, RequestContext requestContext, EmulatorConfig config, CurrentVertxRequest currentVertxRequest, @@ -130,6 +136,7 @@ public class IamConditionContextResolver { this.s3Service = s3Service; this.logsService = logsService; this.iamService = iamService; + this.lambdaWebService = lambdaWebService; this.requestContext = requestContext; this.config = config; this.currentVertxRequest = currentVertxRequest; @@ -145,6 +152,7 @@ public class IamConditionContextResolver { case "dynamodb" -> dynamoDbConditionContext(action, ctx); case "iam" -> iamConditionContext(action, ctx); case "logs" -> logsConditionContext(action, ctx); + case "lambda" -> lambdaConditionContext(action, ctx); default -> null; }; } @@ -321,6 +329,41 @@ public class IamConditionContextResolver { } } + // ── Lambda ────────────────────────────────────────────────────────────────── + + /** The authType a web function endpoint request names, and the one the endpoint has before it. */ + private Map> lambdaConditionContext(String action, ContainerRequestContext ctx) { + Map> conditions = new LinkedHashMap<>(); + for (String member : LambdaWebConditionKeys.members(action, REQUEST_AUTH_TYPE)) { + PassedRoles.values(PassedRoles.jsonBody(ctx), member.split("\\.")) + .forEach(value -> putIfPresent(conditions, REQUEST_AUTH_TYPE, value)); + } + if (LambdaWebConditionKeys.takes(action, RESOURCE_AUTH_TYPE)) { + putIfPresent(conditions, RESOURCE_AUTH_TYPE, storedAuthType(ctx)); + } + return conditions.isEmpty() ? null : conditions; + } + + private String storedAuthType(ContainerRequestContext ctx) { + if (!lambdaWebService.isResolvable()) { + return null; + } + String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion(); + String endpointArn = ResourceArnBuilder.webFunctionArn(ctx.getUriInfo().getPath(), region, + requestContext.getAccountId()); + int child = endpointArn.lastIndexOf("/endpoint/"); + if (child < 0) { + return null; + } + try { + return lambdaWebService.get().getEndpoint(region, endpointArn.substring(0, child), + endpointArn.substring(child + "/endpoint/".length())).authType; + } catch (AwsException expected) { + // The handler refuses the same names, so the key is only left out, as for a missing endpoint on AWS. + return null; + } + } + // ── S3 ────────────────────────────────────────────────────────────────────── private Map> s3ConditionContext(String action, ContainerRequestContext ctx) { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/LambdaWebConditionKeys.java b/src/main/java/io/github/hectorvent/floci/core/common/LambdaWebConditionKeys.java new file mode 100644 index 0000000000..260c75c3cf --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/LambdaWebConditionKeys.java @@ -0,0 +1,43 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.ArrayList; +import java.util.List; + +/** + * The Lambda Web Functions authType condition keys each action takes, and the request members that + * carry the request key, generated from the AWS Service Reference and pinned botocore by + * {@code tools/aws/regen_lambda_web_condition_keys.py}. + */ +final class LambdaWebConditionKeys { + + private static final JsonNode TABLE = VendoredResources.read("aws/lambda-web-condition-keys.json", + "Lambda Web condition keys", input -> { + JsonNode document = new ObjectMapper().readTree(input); + if (!document.path("actions").isObject() || document.path("actions").isEmpty() + || !document.path("members").isObject() || document.path("members").isEmpty()) { + throw new IllegalStateException("Malformed Lambda Web condition key table"); + } + return document; + }); + + private LambdaWebConditionKeys() {} + + static boolean takes(String action, String key) { + for (JsonNode taken : TABLE.path("actions").path(action)) { + if (key.equals(taken.asText())) { + return true; + } + } + return false; + } + + /** The dotted paths of the request members that carry {@code key} for {@code action}; empty when none. */ + static List members(String action, String key) { + List members = new ArrayList<>(); + TABLE.path("members").path(action).path(key).forEach(member -> members.add(member.asText())); + return members; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java index 53c034aced..689888f9eb 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java @@ -820,7 +820,7 @@ final class PassedRoles { } /** The strings at {@code path} in {@code node}, where a {@code []} step takes each element of an array. */ - private static List values(JsonNode node, String... path) { + static List values(JsonNode node, String... path) { List found = new ArrayList<>(); collect(node, path, 0, found); return found; diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index 489e9bdd5b..4e62c8860a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -1348,7 +1348,7 @@ public class ResourceArnBuilder { * "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) { + public static String webFunctionArn(String path, String region, String accountId) { if (!path.startsWith("/2025-03-07/")) { return null; } diff --git a/src/main/resources/aws/lambda-web-condition-keys.json b/src/main/resources/aws/lambda-web-condition-keys.json new file mode 100644 index 0000000000..0642fde77c --- /dev/null +++ b/src/main/resources/aws/lambda-web-condition-keys.json @@ -0,0 +1,46 @@ +{ + "_source": { + "generator": "tools/aws/regen_lambda_web_condition_keys.py", + "reference": "https://servicereference.us-east-1.amazonaws.com/v1/lambda/lambda.json", + "botocore": "botocore 1.43.113 (installed package)", + "note": "make lambda-web-condition-keys-check re-derives members from botocore; make lambda-web-condition-keys-verify checks actions against AWS." + }, + "actions": { + "lambda:CreateWebFunction": [ + "lambda:Request/WebFunctionAuthType" + ], + "lambda:CreateWebFunctionEndpoint": [ + "lambda:Request/WebFunctionAuthType" + ], + "lambda:DeleteWebFunctionEndpoint": [ + "lambda:Resource/WebFunctionAuthType" + ], + "lambda:GetWebFunctionEndpoint": [ + "lambda:Resource/WebFunctionAuthType" + ], + "lambda:InvokeWebFunctionEndpoint": [ + "lambda:Resource/WebFunctionAuthType" + ], + "lambda:UpdateWebFunctionEndpoint": [ + "lambda:Request/WebFunctionAuthType", + "lambda:Resource/WebFunctionAuthType" + ] + }, + "members": { + "lambda:CreateWebFunction": { + "lambda:Request/WebFunctionAuthType": [ + "endpointConfig.authType" + ] + }, + "lambda:CreateWebFunctionEndpoint": { + "lambda:Request/WebFunctionAuthType": [ + "authType" + ] + }, + "lambda:UpdateWebFunctionEndpoint": { + "lambda:Request/WebFunctionAuthType": [ + "authType" + ] + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java index 18e98d5cf7..fc6b01e83b 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java @@ -16,6 +16,8 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.model.IamRole; import io.github.hectorvent.floci.services.iam.model.IamUser; +import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService; +import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint; import io.github.hectorvent.floci.services.s3.S3Service; import jakarta.enterprise.inject.Instance; import jakarta.ws.rs.container.ContainerRequestContext; @@ -64,6 +66,7 @@ class IamConditionContextResolverTest { private S3Service s3Service; private CloudWatchLogsService logsService; private IamService iamService; + private LambdaWebService lambdaWebService; private RequestContext requestContext; private EmulatorConfig config; private IamConditionContextResolver resolver; @@ -94,6 +97,10 @@ class IamConditionContextResolverTest { Instance iamServiceInstance = mock(Instance.class); when(iamServiceInstance.isResolvable()).thenReturn(true); when(iamServiceInstance.get()).thenReturn(iamService); + lambdaWebService = mock(LambdaWebService.class); + Instance lambdaWebServiceInstance = mock(Instance.class); + when(lambdaWebServiceInstance.isResolvable()).thenReturn(true); + when(lambdaWebServiceInstance.get()).thenReturn(lambdaWebService); requestContext = new RequestContext(); requestContext.setAccountId("123456789012"); requestContext.setRegion("us-east-1"); @@ -108,10 +115,48 @@ class IamConditionContextResolverTest { when(serviceCatalog.matchTarget(any())).thenAnswer(call -> catalog.matchTarget(call.getArgument(0))); resolver = new IamConditionContextResolver( dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance, iamServiceInstance, + lambdaWebServiceInstance, requestContext, config, null, serviceCatalog); } + @Test + void aWebFunctionEndpointRequestCarriesTheAuthTypeItNamesAndTheOneItHas() throws Exception { + String function = "arn:aws:lambda:us-east-1:123456789012:web-function/app"; + WebFunctionEndpoint stored = new WebFunctionEndpoint(); + stored.authType = "ApplicationManaged"; + when(lambdaWebService.getEndpoint("us-east-1", function, "dev")).thenReturn(stored); + when(lambdaWebService.getEndpoint("us-east-1", function, "gone")) + .thenThrow(new AwsException("ResourceNotFoundException", "The endpoint gone does not exist.", 404)); + String request = "lambda:Request/WebFunctionAuthType"; + String resource = "lambda:Resource/WebFunctionAuthType"; + + assertEquals(Map.of(request, List.of("IamAuth")), resolver.resolve("lambda", "lambda:CreateWebFunction", + webRequest("/2025-03-07/web-functions", "{\"endpointConfig\":{\"authType\":\"IamAuth\"}}"))); + assertEquals(Map.of(request, List.of("IamAuth")), resolver.resolve("lambda", + "lambda:CreateWebFunctionEndpoint", webRequest("/2025-03-07/web-functions/app/endpoints", + "{\"authType\":\"IamAuth\"}"))); + assertEquals(Map.of(request, List.of("IamAuth"), resource, List.of("ApplicationManaged")), + resolver.resolve("lambda", "lambda:UpdateWebFunctionEndpoint", + webRequest("/2025-03-07/web-functions/app/endpoints/dev", "{\"authType\":\"IamAuth\"}"))); + assertEquals(Map.of(resource, List.of("ApplicationManaged")), resolver.resolve("lambda", + "lambda:UpdateWebFunctionEndpoint", webRequest("/2025-03-07/web-functions/app/endpoints/dev", + "{\"description\":\"d\"}")), "an update without authType names none"); + for (String action : List.of("lambda:GetWebFunctionEndpoint", "lambda:DeleteWebFunctionEndpoint")) { + assertEquals(Map.of(resource, List.of("ApplicationManaged")), resolver.resolve("lambda", action, + webRequest("/2025-03-07/web-functions/" + function + "/endpoints/" + function + "/endpoint/dev", + ""))); + assertNull(resolver.resolve("lambda", action, + webRequest("/2025-03-07/web-functions/app/endpoints/gone", "")), "a missing endpoint has none"); + } + assertNull(resolver.resolve("lambda", "lambda:GetWebFunctionEndpoint", + webRequest("/2025-03-07/web-functions/arn:bad/endpoints/dev", "")), "a malformed ARN has none"); + assertNull(resolver.resolve("lambda", "lambda:GetWebFunction", + webRequest("/2025-03-07/web-functions/app", ""))); + assertNull(resolver.resolve("lambda", "lambda:ListWebFunctionEndpoints", + webRequest("/2025-03-07/web-functions/app/list-endpoints", "{}"))); + } + @Test void logStreamTagsUseRawParentNameAndRequestRegion() throws Exception { ContainerRequestContext request = mock(ContainerRequestContext.class); @@ -161,6 +206,16 @@ class IamConditionContextResolverTest { return containerRequest; } + private ContainerRequestContext webRequest(String path, String body) throws Exception { + ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + UriInfo uriInfo = mock(UriInfo.class); + when(containerRequest.getUriInfo()).thenReturn(uriInfo); + when(uriInfo.getPath()).thenReturn(path); + when(containerRequest.getProperty("floci.bufferedJsonBody")) + .thenReturn(body.isEmpty() ? null : mapper.readTree(body)); + return containerRequest; + } + private static ContainerRequestContext s3Request(String path, String body) { ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); UriInfo uriInfo = mock(UriInfo.class); @@ -550,8 +605,8 @@ class IamConditionContextResolverTest { @SuppressWarnings("unchecked") private IamConditionContextResolver resolverAt(Instant now) { return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class), - mock(Instance.class), mock(Instance.class), requestContext, config, null, serviceCatalog, - Clock.fixed(now, ZoneOffset.UTC)); + mock(Instance.class), mock(Instance.class), mock(Instance.class), requestContext, config, null, + serviceCatalog, Clock.fixed(now, ZoneOffset.UTC)); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java index 4daa616d6a..d8554268fb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java @@ -152,7 +152,8 @@ class DynamoDbFacadeTest { RequestContext requestContext = new RequestContext(); requestContext.setRegion(OTHER_REGION); IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb, - mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class), requestContext, + mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class), + requestContext, mock(EmulatorConfig.class), null, mock(io.github.hectorvent.floci.core.common.ResolvedServiceCatalog.class)); ContainerRequestContext request = mock(ContainerRequestContext.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebAuthTypeConditionKeysIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebAuthTypeConditionKeysIntegrationTest.java new file mode 100644 index 0000000000..699c5ad8e1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambdaweb/LambdaWebAuthTypeConditionKeysIntegrationTest.java @@ -0,0 +1,131 @@ +package io.github.hectorvent.floci.services.lambdaweb; + +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.EnforcementFixtures.Session; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.Map; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** Under IAM enforcement the endpoint routes carry the authType they name and the one the endpoint has. */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class LambdaWebAuthTypeConditionKeysIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/web-auth-type"; + private static final String BUCKET = "web-code-auth-type"; + private static final String BASE = "/2025-03-07/web-functions"; + private static final String BUILD = """ + {"codeConfig": {"s3Object": {"bucket": "%s", "key": "app.zip"}}, "runtimeConfig": {"runtime": "nodejs24.x"}} + """.formatted(BUCKET); + private static final String POLICY = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["lambda:*","iam:PassRole"],"Resource":"*"}, + {"Effect":"Deny","Action":["lambda:CreateWebFunction","lambda:CreateWebFunctionEndpoint"],"Resource":"*", + "Condition":{"StringEquals":{"lambda:Request/WebFunctionAuthType":"ApplicationManaged"}}}, + {"Effect":"Deny","Action":["lambda:GetWebFunctionEndpoint","lambda:DeleteWebFunctionEndpoint"], + "Resource":"*", + "Condition":{"StringEquals":{"lambda:Resource/WebFunctionAuthType":"ApplicationManaged"}}}, + {"Effect":"Deny","Action":"lambda:UpdateWebFunctionEndpoint","Resource":"*", + "Condition":{"Null":{"lambda:Request/WebFunctionAuthType":"true"}}}]}"""; + + @TestHTTPResource("/") + static URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Inject + IamService iamService; + + @Inject + S3Service s3Service; + + @Test + void anEndpointRouteIsDeniedByTheAuthTypeItNamesOrHas() { + int port = baseUri.getPort(); + String name = "auth-type-" + Long.toString(System.nanoTime(), 36); + LambdaWebRoles.trustLambda(iamService, ROLE); + LambdaWebCodeBuckets.create(s3Service, BUCKET); + s3Service.putObject(BUCKET, "app.zip", LambdaWebZips.indexJs(""), "application/zip", Map.of()); + cleanup.register(() -> given().header("Authorization", auth(ACCOUNT, "lambda")) + .when().delete(BASE + "/" + name)); + given().header("Authorization", auth(ACCOUNT, "lambda")).contentType("application/json") + .body(function(name, "ApplicationManaged")) + .when().put(BASE) + .then().statusCode(202); + String roleArn = EnforcementFixtures.createRole(cleanup, port, ACCOUNT, "/", name, POLICY); + Session session = EnforcementFixtures.assumeRole(port, ACCOUNT, roleArn); + String endpoints = BASE + "/" + name + "/endpoints"; + + signed(session).contentType("application/json").body(endpoint("am", "ApplicationManaged")) + .when().put(endpoints) + .then().statusCode(403) + .header("X-Amzn-Errortype", "AccessDeniedException"); + signed(session).contentType("application/json").body(endpoint("iam", "IamAuth")) + .when().put(endpoints) + .then().statusCode(202); + signed(session).contentType("application/json").body(function(name + "-b", "ApplicationManaged")) + .when().put(BASE) + .then().statusCode(403) + .header("X-Amzn-Errortype", "AccessDeniedException"); + + signed(session).when().get(endpoints + "/dev") + .then().statusCode(403) + .header("X-Amzn-Errortype", "AccessDeniedException"); + signed(session).when().get(endpoints + "/iam").then().statusCode(200); + signed(session).when().get(BASE + "/arn:bad/endpoints/dev") + .then().statusCode(400) + .header("X-Amzn-Errortype", "ValidationException"); + signed(session).when().get(endpoints + "/missing") + .then().statusCode(404) + .body("message", equalTo("The endpoint missing does not exist.")); + + signed(session).contentType("application/json").body("{\"description\": \"d\"}") + .when().patch(endpoints + "/iam") + .then().statusCode(403) + .header("X-Amzn-Errortype", "AccessDeniedException"); + signed(session).contentType("application/json").body("{\"authType\": \"IamAuth\"}") + .when().patch(endpoints + "/iam") + .then().statusCode(202); + + signed(session).when().delete(endpoints + "/dev") + .then().statusCode(403) + .header("X-Amzn-Errortype", "AccessDeniedException"); + signed(session).when().delete(endpoints + "/iam").then().statusCode(204); + } + + private static String function(String name, String authType) { + return """ + {"functionName": "%s", + "revisionConfig": {"buildConfig": %s, "serviceConfig": {"executionRoleArn": "%s"}}, + "endpointConfig": %s} + """.formatted(name, BUILD, ROLE, endpoint("dev", authType)); + } + + private static String endpoint(String name, String authType) { + return """ + {"endpointName": "%s", "endpointType": "HomeRegion", "authType": "%s", + "autoDeploymentMode": "LatestRevision"}""".formatted(name, authType); + } + + private static RequestSpecification signed(Session session) { + return given().header("Authorization", auth(session.accessKeyId(), "lambda")) + .header("X-Amz-Security-Token", session.sessionToken()); + } +} diff --git a/tools/aws/regen_lambda_web_condition_keys.py b/tools/aws/regen_lambda_web_condition_keys.py new file mode 100644 index 0000000000..29163de8aa --- /dev/null +++ b/tools/aws/regen_lambda_web_condition_keys.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Regenerate src/main/resources/aws/lambda-web-condition-keys.json from AWS's Service Reference and botocore. + +A Lambda Web Functions request is checked with the endpoint's authType as +`lambda:Request/WebFunctionAuthType`, the one the request names, and `lambda:Resource/WebFunctionAuthType`, +the one the endpoint has before the request. The table comes from two sources: + +- AWS's Service Reference for `lambda`, which gives each action's condition keys, for the action and + for each resource type it acts on: + + https://servicereference.us-east-1.amazonaws.com/v1/lambda/lambda.json + +- botocore's `lambda-web` model (Apache-2.0, https://github.com/boto/botocore, the pinned release), + which gives where each request carries the authType. + +`actions` holds every `lambda` action that takes either key, with the ones it takes. `members` holds, +for every action that takes the request key, the paths of the request members named `authType`, +dotted for a nested one. The resource key is read from the stored endpoint, so it has no member. + +The two gates split along the sources: + +- `--check` is offline and needs the pinned botocore: `members` must be exactly what botocore gives. +- `--verify` is online and stdlib-only: `actions` must be exactly what the reference gives. + +Run from anywhere in the repo: + python3 tools/aws/regen_lambda_web_condition_keys.py # rewrite the vendored file in place + python3 tools/aws/regen_lambda_web_condition_keys.py --check # offline: members match botocore + python3 tools/aws/regen_lambda_web_condition_keys.py --verify # online: actions match AWS + python3 tools/aws/regen_lambda_web_condition_keys.py --source # read a saved reference +""" +from __future__ import annotations + +import argparse +import json +import sys +import urllib.request +from pathlib import Path + +from regen_dynamodb_condition_keys import member_paths +from regen_iam_tag_on_create import _condition_keys, _resource_keys +from regen_partitions import resolve_botocore_data +from regen_query_services import latest_model_dir, load_model + +OUTPUT = Path(__file__).resolve().parents[2] / "src/main/resources/aws/lambda-web-condition-keys.json" +URL = "https://servicereference.us-east-1.amazonaws.com/v1/lambda/lambda.json" +NAMESPACE = "lambda" +MODEL = "lambda-web" +REQUEST_KEY = "lambda:Request/WebFunctionAuthType" +RESOURCE_KEY = "lambda:Resource/WebFunctionAuthType" +MEMBER = "authType" + + +def action_keys(reference: dict) -> dict[str, list[str]]: + """Every action of the namespace that takes either key, with the ones it takes.""" + resource_keys = _resource_keys([reference]) + found = {} + for action in sorted(reference["Actions"], key=lambda entry: entry["Name"]): + keys = {REQUEST_KEY, RESOURCE_KEY} & _condition_keys(NAMESPACE, action, resource_keys) + if keys: + found[f"{NAMESPACE}:{action['Name']}"] = sorted(keys) + return found + + +def request_members(model: dict, actions: dict[str, list[str]]) -> dict[str, dict[str, list[str]]]: + """For every action that takes the request key, where its request carries the value.""" + found = {} + for action, keys in sorted(actions.items()): + if REQUEST_KEY not in keys: + continue + operation = model["operations"].get(action.split(":", 1)[1]) + if operation is None or "input" not in operation: + raise ValueError(f"{action} takes {REQUEST_KEY} but botocore has no request for it") + paths = member_paths(model, operation["input"]["shape"], {MEMBER}) + if not paths: + raise ValueError(f"{action} takes {REQUEST_KEY} but its request has no {MEMBER} member") + found[action] = {REQUEST_KEY: paths} + return found + + +def render(document: dict) -> str: + return json.dumps(document, indent=2) + "\n" + + +def validate(document: dict) -> list[str]: + """Problems that make the vendored file unusable, rather than merely out of date.""" + problems = [] + for section in ("actions", "members"): + if not isinstance(document.get(section), dict) or not document[section]: + problems.append(f"{section} is missing or empty") + if problems: + return problems + if REQUEST_KEY not in document["actions"].get("lambda:CreateWebFunctionEndpoint", []): + problems.append(f"lambda:CreateWebFunctionEndpoint takes no {REQUEST_KEY}") + if RESOURCE_KEY not in document["actions"].get("lambda:GetWebFunctionEndpoint", []): + problems.append(f"lambda:GetWebFunctionEndpoint takes no {RESOURCE_KEY}") + return problems + + +def _reference(source: Path | None) -> dict: + if source is not None: + return json.loads(source.read_text(encoding="utf-8")) + request = urllib.request.Request(URL, headers={"Accept": "application/json"}) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def _model(botocore_data: Path | None) -> tuple[dict, str]: + data, provenance = resolve_botocore_data(botocore_data) + return load_model(latest_model_dir(data, MODEL)), provenance + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--check", action="store_true", help="offline: members must match the pinned botocore") + parser.add_argument("--verify", action="store_true", help="online: actions must match the Service Reference") + parser.add_argument("--source", type=Path, help="a saved lambda.json Service Reference document") + parser.add_argument("--botocore-data", type=Path, help="botocore data directory") + args = parser.parse_args(argv) + + if args.check or args.verify: + document = json.loads(OUTPUT.read_text(encoding="utf-8")) + problems = validate(document) + if args.check and not problems: + model, provenance = _model(args.botocore_data) + if document["members"] != request_members(model, document["actions"]): + problems.append(f"members differ from {provenance}") + if args.verify and document.get("actions") != action_keys(_reference(args.source)): + problems.append("actions differ from the AWS Service Reference") + for problem in problems: + print(f"{OUTPUT.name}: {problem}", file=sys.stderr) + return 1 if problems else 0 + + model, provenance = _model(args.botocore_data) + actions = action_keys(_reference(args.source)) + document = {"_source": {"generator": "tools/aws/regen_lambda_web_condition_keys.py", "reference": URL, + "botocore": provenance, + "note": "make lambda-web-condition-keys-check re-derives members from botocore; " + "make lambda-web-condition-keys-verify checks actions against AWS."}, + "actions": actions, "members": request_members(model, actions)} + problems = validate(document) + if problems: + for problem in problems: + print(f"error: {problem}", file=sys.stderr) + return 1 + OUTPUT.write_text(render(document), encoding="utf-8") + print(f"wrote {OUTPUT.name} from {provenance}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/test_regen_lambda_web_condition_keys.py b/tools/aws/test_regen_lambda_web_condition_keys.py new file mode 100644 index 0000000000..9523cae82b --- /dev/null +++ b/tools/aws/test_regen_lambda_web_condition_keys.py @@ -0,0 +1,92 @@ +"""Action coverage and request members for the Lambda Web Functions authType condition keys.""" +import json +import subprocess + +import pytest + +from regen_lambda_web_condition_keys import OUTPUT, action_keys, request_members, validate + + +def test_resource_and_action_keys_are_combined(): + reference = {"Name": "lambda", "Resources": [{"Name": "webFunctionEndpoint", + "ConditionKeys": ["lambda:Resource/WebFunctionAuthType"]}], + "Actions": [{"Name": "UpdateWebFunctionEndpoint", + "ActionConditionKeys": ["lambda:Request/WebFunctionAuthType", "aws:TagKeys"], + "Resources": [{"Name": "webFunctionEndpoint"}]}, + {"Name": "GetWebFunction", "ActionConditionKeys": ["aws:ResourceTag/${TagKey}"]}]} + assert action_keys(reference) == {"lambda:UpdateWebFunctionEndpoint": [ + "lambda:Request/WebFunctionAuthType", "lambda:Resource/WebFunctionAuthType"]} + + +def test_a_nested_member_is_found_and_a_resource_key_has_none(): + model = {"operations": {"CreateWebFunction": {"input": {"shape": "Input"}}, + "GetWebFunctionEndpoint": {"input": {"shape": "Get"}}}, "shapes": { + "Input": {"members": {"endpointConfig": {"shape": "Config"}, "functionName": {"shape": "String"}}}, + "Config": {"members": {"authType": {"shape": "AuthType"}}}, + "Get": {"members": {"endpointName": {"shape": "String"}}}, "AuthType": {}, "String": {}}} + assert request_members(model, {"lambda:CreateWebFunction": ["lambda:Request/WebFunctionAuthType"], + "lambda:GetWebFunctionEndpoint": ["lambda:Resource/WebFunctionAuthType"]}) == { + "lambda:CreateWebFunction": {"lambda:Request/WebFunctionAuthType": ["endpointConfig.authType"]}} + + +def test_a_request_key_without_a_member_fails(): + model = {"operations": {"CreateWebFunctionEndpoint": {"input": {"shape": "Input"}}}, + "shapes": {"Input": {"members": {"endpointName": {"shape": "String"}}}, "String": {}}} + with pytest.raises(ValueError, match="no authType member"): + request_members(model, {"lambda:CreateWebFunctionEndpoint": ["lambda:Request/WebFunctionAuthType"]}) + + +def test_the_vendored_table_covers_the_endpoint_routes(): + document = json.loads(OUTPUT.read_text()) + assert validate(document) == [] + assert document["actions"]["lambda:UpdateWebFunctionEndpoint"] == [ + "lambda:Request/WebFunctionAuthType", "lambda:Resource/WebFunctionAuthType"] + assert document["members"]["lambda:CreateWebFunction"] == { + "lambda:Request/WebFunctionAuthType": ["endpointConfig.authType"]} + + +@pytest.mark.parametrize("changed", [ + "src/main/resources/aws/lambda-web-condition-keys.json", + "tools/aws/regen_lambda_web_condition_keys.py", + "tools/aws/test_regen_lambda_web_condition_keys.py", + "tools/aws/regen_dynamodb_condition_keys.py", + "tools/aws/regen_iam_tag_on_create.py", + "tools/aws/regen_iam_passed_roles.py", + "tools/aws/regen_partitions.py", + "tools/aws/regen_query_services.py", + "", +]) +def test_aggregate_gate_checks_the_table_and_its_imports(tmp_path, changed): + result = run_aggregate_gate(tmp_path, changed, fail=True) + assert "checked:lambda-web-condition-keys-verify" in result.stdout + assert result.returncode != 0 + assert "the Lambda Web condition key table" in result.stdout + + +@pytest.mark.parametrize("changed", [ + "docs/services/lambda-web-functions.md", + "src/main/resources/aws/dynamodb-condition-keys.json", + "src/main/resources/aws/lambda-web-condition-keys.json.bak", +]) +def test_aggregate_gate_does_not_check_unrelated_data(tmp_path, changed): + result = run_aggregate_gate(tmp_path, changed, fail=True) + assert "checked:lambda-web-condition-keys-verify" not in result.stdout + assert result.returncode == 0 + + +def test_aggregate_gate_accepts_a_successful_check(tmp_path): + result = run_aggregate_gate(tmp_path, "src/main/resources/aws/lambda-web-condition-keys.json", fail=False) + assert "checked:lambda-web-condition-keys-verify" in result.stdout + assert result.returncode == 0 + + +def run_aggregate_gate(tmp_path, changed, fail): + recursive_make = tmp_path / "check-gate" + recursive_make.write_text( + '#!/bin/sh\nprintf "checked:%s\\n" "$2"\n' + + ('[ "$2" != lambda-web-condition-keys-verify ]\n' if fail else 'exit 0\n')) + recursive_make.chmod(0o700) + return subprocess.run( + ["make", "--no-print-directory", "iam-data-verify", "CHANGED=" + changed, + "MAKE=" + str(recursive_make)], + cwd=OUTPUT.parents[4], capture_output=True, text=True, check=False)