Light, fluffy, and always free - The AWS Local Emulator alternative
feat(iam): check lambda:PassNetworkConnector from a table generated from the Service Reference (#6699)
TATSUNO “Taz” Yasuhirob0cd70401b82
diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.ymlindex 4af040ba4f..6700ceeb2f 100644--- a/.github/workflows/iam-data-drift.yml+++ b/.github/workflows/iam-data-drift.yml@@ -1,9 +1,10 @@name: IAM Data Drift-# Checks the six vendored files that come from AWS's live service reference rather than from a+# Checks the seven 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, and the table of the resources each# operation's request names. That# needs the live service reference index, so unlike every other check here it can@@ -45,6 +46,9 @@ on:- 'src/main/resources/aws/iam-passed-roles.json'- 'tools/aws/regen_iam_passed_roles.py'- 'tools/aws/test_regen_iam_passed_roles.py'+ - 'src/main/resources/aws/iam-passed-network-connectors.json'+ - 'tools/aws/regen_iam_passed_network_connectors.py'+ - 'tools/aws/test_regen_iam_passed_network_connectors.py'- 'src/main/resources/aws/iam-tag-on-create.json'- 'tools/aws/regen_iam_tag_on_create.py'- 'tools/aws/test_regen_iam_tag_on_create.py'diff --git a/Makefile b/Makefileindex 31ab382573..2da6cbdda9 100644--- a/Makefile+++ b/Makefile@@ -71,7 +71,9 @@ PREFIX ?= $(HOME)/.localiam-action-resources-test iam-authorized-actions-sync iam-authorized-actions-check \cfn-property-types-sync cfn-property-types-check cfn-property-types-verify cfn-property-types-test \iam-authorized-actions-verify iam-authorized-actions-test iam-passed-roles-sync iam-passed-roles-check \- iam-passed-roles-verify iam-passed-roles-test iam-tag-on-create-sync iam-tag-on-create-check \+ iam-passed-roles-verify iam-passed-roles-test iam-passed-network-connectors-sync \+ iam-passed-network-connectors-check iam-passed-network-connectors-verify \+ iam-passed-network-connectors-test iam-tag-on-create-sync iam-tag-on-create-check \iam-tag-on-create-verify iam-tag-on-create-test iam-request-resources-sync iam-request-resources-check \iam-request-resources-verify iam-request-resources-test iam-data-verify@@ -339,6 +341,7 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generationexit 1; \}@$(MAKE) --no-print-directory iam-passed-roles-check+ @$(MAKE) --no-print-directory iam-passed-network-connectors-check@$(MAKE) --no-print-directory iam-tag-on-create-check@$(MAKE) --no-print-directory iam-request-resources-check@@ -411,6 +414,9 @@ IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.jstools/aws/regen_iam_authorized_actions.py tools/aws/test_regen_iam_authorized_actions.pyIAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \tools/aws/test_regen_iam_passed_roles.py+IAM_PASSED_NETWORK_CONNECTORS_PATHS := src/main/resources/aws/iam-passed-network-connectors.json \+ tools/aws/regen_iam_passed_network_connectors.py $(IAM_PASSED_ROLES_GENERATOR) \+ tools/aws/test_regen_iam_passed_network_connectors.pyIAM_TAG_ON_CREATE_PATHS := src/main/resources/aws/iam-tag-on-create.json tools/aws/regen_iam_tag_on_create.py \$(IAM_PASSED_ROLES_GENERATOR) tools/aws/test_regen_iam_tag_on_create.pyIAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \@@ -421,7 +427,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; tagged=0; requested=0; \+ @namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; \covers() { \[ -z "$(strip $(CHANGED))" ] && return 0; \for path in $(CHANGED); do case " $$1 " in *" $$path "*) return 0;; esac; done; \@@ -440,6 +446,9 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match Aif covers "$(IAM_PASSED_ROLES_PATHS)" "the table of the roles operations pass"; then \$(MAKE) --no-print-directory iam-passed-roles-verify || passed=$$?; \fi; \+ if covers "$(IAM_PASSED_NETWORK_CONNECTORS_PATHS)" "the table of the network connectors operations pass"; then \+ $(MAKE) --no-print-directory iam-passed-network-connectors-verify || connectors=$$?; \+ fi; \if covers "$(IAM_TAG_ON_CREATE_PATHS)" "the table of the tagging actions creates need"; then \$(MAKE) --no-print-directory iam-tag-on-create-verify || tagged=$$?; \fi; \@@ -447,7 +456,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A$(MAKE) --no-print-directory iam-request-resources-verify || requested=$$?; \fi; \if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ] || [ $$authorized -ne 0 ] || [ $$passed -ne 0 ] \- || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ]; then \+ || [ $$connectors -ne 0 ] || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ]; then \echo ""; \echo "error: vendored IAM data does not match upstream:"; \if [ $$namespaces -ne 0 ]; then \@@ -462,6 +471,9 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match Aif [ $$passed -ne 0 ]; then \echo " the table of the roles operations pass, see its message above"; \fi; \+ if [ $$connectors -ne 0 ]; then \+ echo " the table of the network connectors operations pass, see its message above"; \+ fi; \if [ $$tagged -ne 0 ]; then \echo " the table of the tagging actions creates need, see its message above"; \fi; \@@ -529,6 +541,33 @@ iam-passed-roles-verify: ## CI gate (online): every vendored operation must stiliam-passed-roles-test: ## Run the IAM passed role generator's unit tests$(PYTHON) -m pytest tools/aws/test_regen_iam_passed_roles.py -q+iam-passed-network-connectors-sync: ## Regenerate src/main/resources/aws/iam-passed-network-connectors.json from AWS and botocore (commit the result)+ $(PYTHON) tools/aws/regen_iam_passed_network_connectors.py++iam-passed-network-connectors-check: ## CI gate (offline): every vendored connector member must be what the pinned botocore gives+ @$(PYTHON) tools/aws/regen_iam_passed_network_connectors.py --check || { \+ echo ""; \+ echo "error: src/main/resources/aws/iam-passed-network-connectors.json is malformed or out of date."; \+ echo " Run 'make iam-passed-network-connectors-sync' and commit the result."; \+ exit 1; \+ }++iam-passed-network-connectors-verify: ## CI gate (online): every vendored operation must still pass a connector as AWS says+ @$(PYTHON) tools/aws/regen_iam_passed_network_connectors.py --verify; status=$$?; \+ if [ $$status -eq 2 ]; then \+ echo ""; \+ echo "error: could not reach AWS's service reference, so nothing was verified."; \+ exit 1; \+ elif [ $$status -ne 0 ]; then \+ echo ""; \+ echo "error: the vendored table reads a connector from an operation AWS does not check it for."; \+ echo " Run 'make iam-passed-network-connectors-sync' and commit the result."; \+ exit 1; \+ fi++iam-passed-network-connectors-test: ## Run the IAM passed network connector generator's unit tests+ $(PYTHON) -m pytest tools/aws/test_regen_iam_passed_network_connectors.py -q+iam-tag-on-create-sync: ## Regenerate src/main/resources/aws/iam-tag-on-create.json from AWS and botocore (commit the result)$(PYTHON) tools/aws/regen_iam_tag_on_create.pydiff --git a/docs/services/iam.md b/docs/services/iam.mdindex 86b30de879..be048ba271 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -1803,6 +1803,26 @@ when the caller may not pass the role.REST services whose routes no rule maps yet, and API Gateway, which is authorized by HTTP method,are not read either.+A request that names a Lambda network connector also needs `lambda:PassNetworkConnector` on it. The+Lambda developer guide has "The caller must have `lambda:PassNetworkConnector` on the referenced+connector whenever a `create-web-function` or `create-web-function-revision` call sets+`egressNetworkConnectorArn`." Every operation the Service Reference lists with the action is checked+from a table generated the same way, `src/main/resources/aws/iam-passed-network-connectors.json`: a+Web Function's `egressNetworkConnectorArn`, and the `egressNetworkConnectors` of a MicroVM image and a+MicroVM and the `ingressNetworkConnectors` of a MicroVM. Each connector is checked as the request+names it, the egress ones before the ingress ones, after `iam:PassRole`, as on AWS. A MicroVM request+that names no egress connector, or an empty list, is checked on the Lambda-managed connector+`arn:aws:lambda:<Region>:aws:network-connector:aws-network-connector:INTERNET_EGRESS`, and a+`RunMicrovm` with no ingress connector on `aws-network-connector:HTTP_INGRESS`, as on AWS. A refusal+is Lambda's `403 AccessDeniedException` with `{"Message":"User: <caller> is not authorized to+perform: lambda:PassNetworkConnector on resource: <connector> <reason>"}`. The reason names the first+policy type that refuses, in the order service control policies, identity policies, permissions+boundary, session policy, by its explicit deny or by the allow it lacks, and an explicit deny in a+managed policy or a boundary also names that policy's ARN. The check runs before the request reaches+Lambda, so it comes before Lambda's own checks of the connector ARN, which AWS runs first. AppSync's+`CreateDataSource` and `UpdateDataSource` are listed too, but botocore's model has no member for their+connector, so they are not read.+A request that tags the resource it creates also needs the service's tagging action. The SNS APIreference has "To be able to tag a topic on creation, you must have the sns:CreateTopic andsns:TagResource permissions.", and the EC2 user guide "If tags are specified in the resource-creatingdiff --git a/docs/services/lambda-microvms.md b/docs/services/lambda-microvms.mdindex ad36574439..ae0edd9913 100644--- a/docs/services/lambda-microvms.md+++ b/docs/services/lambda-microvms.md@@ -51,6 +51,7 @@ Two AWS service models, not one. `Lambda Microvms` (apiVersion 2025-09-09) carri- **Per-operation projections:** an image is returned in four different shapes and a connector in four. Create and Update carry full detail, Get is a smaller summary, and only the list summaries carry `Type`. Absent members are absent rather than null — a connector that has never been updated has no `LastUpdateStatus` at all.- **Members the model marks optional but the service enforces:** a connector requires `ClientToken`, `OperatorRole`, `NetworkProtocol` and `AssociatedComputeResourceTypes`. A client written from the Smithy model alone receives four validation errors in turn.- **ARN or bare identifier:** images, MicroVMs and connectors resolve by either in URI paths.+- **Passing a connector:** when IAM enforcement is on, `CreateMicrovmImage`, `UpdateMicrovmImage` and `RunMicrovm` need `lambda:PassNetworkConnector` on each connector the request names, and on the Lambda-managed `INTERNET_EGRESS` connector, or `HTTP_INGRESS` for ingress, when it names none, as on AWS (see [IAM](iam.md)).- **Connector versions:** a connector starts at version 1. As on AWS, an update that changes the subnets, the security groups, the network protocol or the operator role makes the next version, and one that only lists the subnets in another order changes nothing. A connector also resolves by its name, and `:<version>` after an id, a name or an ARN names one version. The latest version cannot be deleted on its own, and `AssociatedComputeResourceTypes` cannot change. Errors use the AWS wording.- **Builds per generation:** each version is built once per Graviton generation the service targets, so a version has more than one build.- **Not emulated:** auth tokens, the per-VM endpoint, idle and suspend timers, and suspend/resume. Those belong to a full-fidelity MicroVMs emulator rather than to CloudFormation provisioning; see [m80](https://github.com/INTENTIUS/m80).diff --git a/docs/services/lambda-web-functions.md b/docs/services/lambda-web-functions.mdindex c03c199363..89cfe10198 100644--- a/docs/services/lambda-web-functions.md+++ b/docs/services/lambda-web-functions.md@@ -40,7 +40,7 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A- **Each revision keeps its own copy of the code**, read at creation from the version the request names or the current one, under the Lambda `code-path`. As on AWS, a later write or delete in the bucket does not change what the revision runs. AWS moves a revision to `Failed` when it later finds its object version gone, which Floci does not do.- **Revision cleanup:** when a revision turns `Active` and the function has more than 50, the oldest revisions that no endpoint routes to are deleted until 50 are left, `Failed` ones included, as on AWS. A new `Failed` revision deletes nothing. The revision that a `LatestRevision` endpoint leaves is not deleted before the next revision turns `Active`, as on AWS.- **Execution role:** a role in another account is `403 AccessDeniedException` "Cross-account pass role is not allowed.". A role that does not exist in IAM, or whose trust policy does not let `lambda.amazonaws.com` assume it, is `400 ValidationException` "The execution role <arn> cannot be assumed by lambda.amazonaws.com. Verify its trust policy. If the role was just created, retry in a few seconds.". As on AWS, this check sets no `aws:SourceAccount` or `aws:SourceArn`, so a trust policy that requires either refuses the role.-- **Egress network connectors:** `egressNetworkConnectorArn` names a connector version by the connector id, in the function's region, as on AWS. A version that does not exist, a connector name, or another region is `404 ResourceNotFoundException` "The egress network connector <arn> does not exist.". A connector without `WebFunction` in its `AssociatedComputeResourceTypes` is `400 ValidationException`. An unknown region, a partition that is not the region's, or a version such as `0` or `01` is `400 ValidationException` "The egress network connector ARN: '<arn>' is not valid. ...", and a connector in another account is `403 AccessDeniedException`. A version past the 64-bit range is `500 InternalServerException` with the body `{}`, as on AWS. Only a `HomeRegion` endpoint can serve such a revision: `CreateWebFunction` with another endpoint type, and weights of a `PerRegion` or `MultiRegion` endpoint that name such a revision, are `400 ValidationException`. Floci settles a connector at once, so the AWS refusal of a `PENDING` version never happens. Floci does not check `lambda:PassNetworkConnector`, and the connector does not change the network of the function's container.+- **Egress network connectors:** `egressNetworkConnectorArn` names a connector version by the connector id, in the function's region, as on AWS. A version that does not exist, a connector name, or another region is `404 ResourceNotFoundException` "The egress network connector <arn> does not exist.". A connector without `WebFunction` in its `AssociatedComputeResourceTypes` is `400 ValidationException`. An unknown region, a partition that is not the region's, or a version such as `0` or `01` is `400 ValidationException` "The egress network connector ARN: '<arn>' is not valid. ...", and a connector in another account is `403 AccessDeniedException`. A version past the 64-bit range is `500 InternalServerException` with the body `{}`, as on AWS. Only a `HomeRegion` endpoint can serve such a revision: `CreateWebFunction` with another endpoint type, and weights of a `PerRegion` or `MultiRegion` endpoint that name such a revision, are `400 ValidationException`. Floci settles a connector at once, so the AWS refusal of a `PENDING` version never happens. When IAM enforcement is on, the caller also needs `lambda:PassNetworkConnector` on the version ARN as the request gives it, refused as on AWS (see [IAM](iam.md)). Floci checks it before the request reaches Lambda, so a refusal comes before the ARN checks above, which AWS runs first. The connector does not change the network of the function's container.- **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. An `IamAuth` endpoint evaluates it on requests, as below.- **Function names** are unique across the regions of an account, as on AWS. A name that another region already has is `409 ConflictException` "A function named <name> already exists in the account. Function names must be unique across all regions in an account.".- **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.diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.javaindex 71a3af0a42..b6913e31b4 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common;import com.fasterxml.jackson.databind.JsonNode;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;+import io.github.hectorvent.floci.services.iam.AccessDeniedMessages;import io.github.hectorvent.floci.services.iam.IamActionRegistry;import io.github.hectorvent.floci.services.iam.IamAuthorizedActions;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;@@ -541,6 +542,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {region, accountId, akid)) {return;}+ if (abortIfConnectorPassDenied(ctx, caller, callerArns.orElse(null), resolvedAuthorization.operation(),+ region, accountId, akid)) {+ return;+ }if (tagOnCreate.isPresent() && abortIfTagOnCreateDenied(ctx, caller, principal, callerArns.orElse(null),action, resolvedAuthorization.operation(), tagOnCreate.get(), credentialScope, resources, region,accountId, akid)) {@@ -958,6 +963,41 @@ public class IamEnforcementFilter implements ContainerRequestFilter {return false;}+ /**+ * A request that names a Lambda network connector also needs {@code lambda:PassNetworkConnector} on it (see+ * {@link PassedNetworkConnectors}), checked as the caller on the connector as the request names it, with the+ * keys that say who is calling. A connector has no resource policy. The refusal is Lambda's, which names the+ * policy type that refused it and the ARN of a managed policy or boundary that denies. Returns true when the+ * request was aborted.+ */+ private boolean abortIfConnectorPassDenied(ContainerRequestContext ctx, CallerContext caller,+ CallerArns callerArns, String operation, String region,+ String accountId, String akid) {+ String action = PassedNetworkConnectors.ACTION;+ for (String connector : PassedNetworkConnectors.of(operation, ctx, region)) {+ Map<String, List<String>> context = new HashMap<>();+ if (callerArns != null) {+ callerArns.putPrincipalKeys(context);+ }+ Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(+ context, connector, region, accountId, accountId);+ if (evaluator.evaluate(caller, null, action, connector, effectiveContext) != Decision.DENY) {+ continue;+ }+ LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, connector);+ String user = callerArns != null ? callerArns.callerArn()+ : AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid).toString();+ String reason = AccessDeniedMessages.firstRefusal(evaluator, caller,+ iamService.heldPolicies(akid).orElse(null), action, connector, effectiveContext);+ ctx.abortWith(Response.status(403).type(MediaType.APPLICATION_JSON)+ .header("X-Amzn-Errortype", "AccessDeniedException")+ .entity(Map.of("Message", AccessDeniedMessages.notAuthorized(user, action, connector, reason)))+ .build());+ return true;+ }+ return false;+ }+/*** The context once for each set of tags the request carries, with that set's keys where the context has* none of its own, so each resource's tags are checked apart; the context alone when it carries none.diff --git a/src/main/java/io/github/hectorvent/floci/core/common/PassedNetworkConnectors.java b/src/main/java/io/github/hectorvent/floci/core/common/PassedNetworkConnectors.javanew file mode 100644index 0000000000..0c2b811d23--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/core/common/PassedNetworkConnectors.java@@ -0,0 +1,101 @@+package io.github.hectorvent.floci.core.common;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import jakarta.ws.rs.container.ContainerRequestContext;++import java.io.IOException;+import java.io.InputStream;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * The Lambda network connectors a request passes, which the caller also needs+ * {@code lambda:PassNetworkConnector} on. The Lambda developer guide: "The caller must have+ * {@code lambda:PassNetworkConnector} on the referenced connector whenever a {@code create-web-function} or+ * {@code create-web-function-revision} call sets {@code egressNetworkConnectorArn}."+ *+ * <p>Where each operation's request names them is read once from the vendored+ * {@code aws/iam-passed-network-connectors.json}, generated by+ * {@code tools/aws/regen_iam_passed_network_connectors.py} from AWS's Service Reference and botocore's models.+ * A member the request leaves out or gives as an empty list passes the Lambda-managed connector the file names+ * for it, as AWS checks a MicroVM's default connectors.+ *+ * <p>A missing or malformed resource is a build defect, so loading fails with+ * {@link IllegalStateException} rather than leaving every operation it reads unchecked.+ */+final class PassedNetworkConnectors {++ static final String RESOURCE_NAME = "aws/iam-passed-network-connectors.json";+ static final String ACTION = "lambda:PassNetworkConnector";++ private static final ObjectMapper MAPPER = new ObjectMapper();++ /** A member of a request that names connectors, and the Lambda-managed connector it passes when it names none. */+ record Member(String path, List<PassedRoleMembers.Step> steps, String whenAbsent) {+ }++ private static final class Holder {+ static final Map<String, List<Member>> TABLE = VendoredResources.read(RESOURCE_NAME,+ "IAM passed network connector table", PassedNetworkConnectors::parse);+ }++ private PassedNetworkConnectors() {+ }++ /** The connectors a request for {@code operation} passes, in the order AWS checks them; empty when it passes none. */+ static List<String> of(String operation, ContainerRequestContext ctx, String region) {+ List<Member> members = Holder.TABLE.get(operation);+ if (members == null) {+ return List.of();+ }+ JsonNode body = PassedRoles.jsonBody(ctx);+ List<String> connectors = new ArrayList<>();+ for (Member member : members) {+ List<String> named = new ArrayList<>();+ PassedRoles.collect(body, member.steps(), 0, named);+ if (named.isEmpty() && member.whenAbsent() != null) {+ named.add(AwsArnUtils.Arn.of("lambda", region, "aws", "network-connector:" + member.whenAbsent())+ .toString());+ }+ connectors.addAll(named);+ }+ return connectors;+ }++ static Map<String, List<Member>> table() {+ return Holder.TABLE;+ }++ static Map<String, List<Member>> parse(InputStream in) throws IOException {+ JsonNode operations = MAPPER.readTree(in).path("operations");+ if (!operations.isObject() || operations.isEmpty()) {+ throw new IllegalStateException(RESOURCE_NAME + " carries no operations");+ }+ Map<String, List<Member>> table = new LinkedHashMap<>();+ operations.properties().forEach(operation -> {+ JsonNode entry = operation.getValue();+ if (entry.has("notRead")) {+ return;+ }+ if (!entry.path("connectors").isArray() || entry.path("connectors").isEmpty()) {+ throw new IllegalStateException(RESOURCE_NAME + " says nothing usable for " + operation.getKey());+ }+ List<Member> members = new ArrayList<>();+ for (JsonNode connector : entry.path("connectors")) {+ String path = connector.path("member").asText("");+ List<PassedRoleMembers.Step> steps = PassedRoleMembers.steps(path);+ if (steps == null) {+ throw new IllegalStateException(RESOURCE_NAME + " reads " + operation.getKey() + " at " + path+ + ", which is no member path");+ }+ members.add(new Member(path, steps, connector.hasNonNull("whenAbsent")+ ? connector.get("whenAbsent").asText() : null));+ }+ table.put(operation.getKey(), List.copyOf(members));+ });+ return Map.copyOf(table);+ }+}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.javaindex 9b11769c4b..53c034aced 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@@ -370,7 +370,7 @@ final class PassedRoles {return passed;}- private static void collect(JsonNode node, List<PassedRoleMembers.Step> steps, int index, List<String> found) {+ static void collect(JsonNode node, List<PassedRoleMembers.Step> steps, int index, List<String> found) {if (node == null) {return;}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputRoleAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputRoleAuthorizer.javaindex 46219fb412..2e249653c5 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputRoleAuthorizer.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/GetStackOutputRoleAuthorizer.java@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.cloudformation;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.iam.AccessDeniedMessages;+import io.github.hectorvent.floci.services.iam.AccessDeniedMessages.PolicyType;import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.SimulationDecision;@@ -58,8 +60,9 @@ public class GetStackOutputRoleAuthorizer {if (role.isEmpty() || (enforced() && !trustEvaluator.allowsAnyPrincipalOf(role.get().getAssumeRolePolicyDocument(), consumerAccount, partition))) {throw new AwsException("AccessDenied", CloudFormationTemplateEngine.sdkErrorMessage(- "User: " + AwsArnUtils.Arn.global(partition, "iam", consumerAccount, "root")- + " is not authorized to perform: sts:AssumeRole on resource: " + roleArn,+ AccessDeniedMessages.notAuthorized(+ AwsArnUtils.Arn.global(partition, "iam", consumerAccount, "root").toString(),+ "sts:AssumeRole", roleArn, null),"AWSSecurityTokenService", 403, "AccessDenied"), 403);}return AwsArnUtils.parse(roleArn).accountId();@@ -83,14 +86,12 @@ public class GetStackOutputRoleAuthorizer {if (decision == SimulationDecision.ALLOWED) {return;}- String reason = decision == SimulationDecision.EXPLICIT_DENY- ? "with an explicit deny in an identity-based policy"- : "because no identity-based policy allows the " + DESCRIBE_STACKS + " action";String session = AwsArnUtils.Arn.global(partition, "sts", stack.accountId(),"assumed-role/" + role.getRoleName() + "/" + SESSION_NAME).toString();throw new AwsException("AccessDenied", CloudFormationTemplateEngine.sdkErrorMessage(- "User: " + session + " is not authorized to perform: " + DESCRIBE_STACKS + " on resource: "- + stackId + " " + reason, "AmazonCloudFormation", 403, "AccessDenied"), 403);+ AccessDeniedMessages.notAuthorized(session, DESCRIBE_STACKS, stackId,+ PolicyType.IDENTITY_BASED_POLICY.refusal(decision, DESCRIBE_STACKS, null)),+ "AmazonCloudFormation", 403, "AccessDenied"), 403);}private boolean enforced() {diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AccessDeniedMessages.java b/src/main/java/io/github/hectorvent/floci/services/iam/AccessDeniedMessages.javanew file mode 100644index 0000000000..3624dc6ddf--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iam/AccessDeniedMessages.java@@ -0,0 +1,114 @@+package io.github.hectorvent.floci.services.iam;++import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.SimulationDecision;+import io.github.hectorvent.floci.services.iam.IamService.HeldPolicies;+import io.github.hectorvent.floci.services.iam.IamService.HeldPolicy;+import io.github.hectorvent.floci.services.iam.model.CallerContext;++import java.util.List;+import java.util.Map;++/**+ * The access denied message AWS returns when a policy refuses a call, and the end of it that names the+ * policy type that refused it (IAM User Guide, "Access denied error message examples").+ */+public final class AccessDeniedMessages {++ /** A policy type the end of the message names, as AWS words it. */+ public enum PolicyType {+ SERVICE_CONTROL_POLICY("a", "service control policy"),+ RESOURCE_BASED_POLICY("a", "resource-based policy"),+ ROLE_TRUST_POLICY("the", "role trust policy"),+ IDENTITY_BASED_POLICY("an", "identity-based policy"),+ PERMISSIONS_BOUNDARY("a", "permissions boundary"),+ SESSION_POLICY("a", "session policy");++ private final String article;+ private final String name;++ PolicyType(String article, String name) {+ this.article = article;+ this.name = name;+ }++ public String explicitDeny() {+ return explicitDeny(null);+ }++ /** Names the policy by its ARN too when one is given, as AWS names a managed policy or a boundary. */+ public String explicitDeny(String policyArn) {+ return "with an explicit deny in " + article + " " + name + (policyArn == null ? "" : ": " + policyArn);+ }++ public String noAllow(String action) {+ return "because no " + name + " allows the " + action + " action";+ }++ public String refusal(SimulationDecision decision, String action, String policyArn) {+ return decision == SimulationDecision.EXPLICIT_DENY ? explicitDeny(policyArn) : noAllow(action);+ }+ }++ private AccessDeniedMessages() {+ }++ /** The message, ending with {@code reason} when there is one. */+ public static String notAuthorized(String callerArn, String action, String resource, String reason) {+ return "User: " + callerArn + " is not authorized to perform: " + action + " on resource: " + resource+ + (reason == null ? "" : " " + reason);+ }++ /**+ * Why {@code caller} may not perform {@code action} on {@code resource}, or null when it may, for a+ * resource with no policy of its own. Each policy type is checked in turn, service control policies,+ * identity policies, permissions boundary, then session policy, and the first that refuses names the+ * reason, by its explicit deny or by the allow it lacks. So identity policies with no allow win over+ * an explicit deny in the boundary (measured for {@code lambda:PassNetworkConnector}). AWS names one+ * of several denying identity policies at random, and this names the first in {@code held}, which is+ * null when the caller holds no policies by ARN.+ */+ public static String firstRefusal(IamPolicyEvaluator evaluator, CallerContext caller,+ HeldPolicies held, String action, String resource,+ Map<String, List<String>> context) {+ for (List<String> level : caller.scpLevels() == null ? List.<List<String>>of() : caller.scpLevels()) {+ SimulationDecision decision = level.isEmpty()+ ? SimulationDecision.ALLOWED : simulate(evaluator, level, action, resource, context);+ if (decision != SimulationDecision.ALLOWED) {+ return PolicyType.SERVICE_CONTROL_POLICY.refusal(decision, action, null);+ }+ }+ SimulationDecision identity = simulate(evaluator, caller.identityPolicies(), action, resource, context);+ if (identity != SimulationDecision.ALLOWED) {+ String denying = identity == SimulationDecision.EXPLICIT_DENY && held != null+ ? held.identity().stream()+ .filter(policy -> simulate(evaluator, List.of(policy.document()), action, resource,+ context) == SimulationDecision.EXPLICIT_DENY)+ .findFirst()+ .map(HeldPolicy::arn)+ .orElse(null)+ : null;+ return PolicyType.IDENTITY_BASED_POLICY.refusal(identity, action, denying);+ }+ if (caller.boundaryPolicyDocument() != null) {+ SimulationDecision boundary = simulate(evaluator, List.of(caller.boundaryPolicyDocument()), action,+ resource, context);+ if (boundary != SimulationDecision.ALLOWED) {+ return PolicyType.PERMISSIONS_BOUNDARY.refusal(boundary, action,+ held == null ? null : held.permissionsBoundaryArn());+ }+ }+ if (caller.sessionPolicyDocument() != null) {+ SimulationDecision session = simulate(evaluator, List.of(caller.sessionPolicyDocument()), action,+ resource, context);+ if (session != SimulationDecision.ALLOWED) {+ return PolicyType.SESSION_POLICY.refusal(session, action, null);+ }+ }+ return null;+ }++ private static SimulationDecision simulate(IamPolicyEvaluator evaluator, List<String> documents, String action,+ String resource, Map<String, List<String>> context) {+ return evaluator.simulatePrincipalPolicy(CallerContext.of(documents), action, resource, context);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex 1b87fd7112..318100ec78 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -6005,64 +6005,68 @@ public class IamService implements SessionAccountLookup, ResourceProvider {return passwordPolicies.get(ACCOUNT_PASSWORD_POLICY_KEY);}- private List<String> collectUserPolicies(String userArnOrName) {- Optional<IamUser> userOpt = userFromArnOrName(userArnOrName);- if (userOpt.isEmpty()) {- return null;- }- IamUser user = userOpt.get();+ /** An identity policy as an access denied message names it: a managed one by its ARN, an inline one by none. */+ public record HeldPolicy(String arn, String document) {}- // User inline policies- List<String> docs = new ArrayList<>(user.getInlinePolicies().values());+ /** The identity policies of an IAM user or role, in the order they are collected, and its permissions boundary. */+ public record HeldPolicies(List<HeldPolicy> identity, String permissionsBoundaryArn) {}- // User attached managed policies- for (String arn : user.getAttachedPolicyArns()) {- Optional<IamPolicy> p = resolvePolicy(arn);- if (p.isPresent() && p.get().getDefaultDocument() != null) {- docs.add(p.get().getDefaultDocument());- }+ /** What the IAM user or role behind {@code accessKeyId} holds, or nothing for any other caller. */+ public Optional<HeldPolicies> heldPolicies(String accessKeyId) {+ Optional<AccessKey> key = accessKeys.get(accessKeyId);+ if (key.isPresent()) {+ return users.get(key.get().getUserName()).map(this::heldPolicies);}-- // Group policies- for (String groupName : user.getGroupNames()) {- Optional<IamGroup> groupOpt = groups.get(groupName);- if (groupOpt.isEmpty()) continue;- IamGroup group = groupOpt.get();- docs.addAll(group.getInlinePolicies().values());- for (String arn : group.getAttachedPolicyArns()) {- Optional<IamPolicy> p = resolvePolicy(arn);- if (p.isPresent() && p.get().getDefaultDocument() != null) {- docs.add(p.get().getDefaultDocument());- }- }+ Optional<SessionCredential> session = findSessionForCallerContext(accessKeyId)+ .filter(found -> found.getDelegatedApproverArn() == null && !isFederatedUserSession(found));+ if (session.isPresent() && session.get().getRoleArn() == null) {+ // GetSessionToken credentials act with the policies of the user that minted them.+ return session.filter(found -> found.getPresignedAction() == null)+ .flatMap(this::issuingUser)+ .map(this::heldPolicies);}+ return session.flatMap(found -> roleFromArnOrName(found.getRoleArn()))+ .map(role -> new HeldPolicies(rolePolicies(role), role.getPermissionsBoundaryArn()));+ }- return docs;+ private HeldPolicies heldPolicies(IamUser user) {+ return new HeldPolicies(userPolicies(user), user.getPermissionsBoundaryArn());+ }++ private List<String> collectUserPolicies(String userArnOrName) {+ return userFromArnOrName(userArnOrName).map(user -> documents(userPolicies(user))).orElse(null);}private List<String> collectRolePolicies(String roleArn) {- if (roleArn == null) {- return null;- }- Optional<IamRole> roleOpt = roleFromArnOrName(roleArn);- if (roleOpt.isEmpty()) {- return null;+ return roleFromArnOrName(roleArn).map(role -> documents(rolePolicies(role))).orElse(null);+ }++ /** The user's inline and managed policies, then each group's. */+ private List<HeldPolicy> userPolicies(IamUser user) {+ List<HeldPolicy> held = inlineThenManaged(user.getInlinePolicies(), user.getAttachedPolicyArns());+ for (String groupName : user.getGroupNames()) {+ groups.get(groupName).ifPresent(group ->+ held.addAll(inlineThenManaged(group.getInlinePolicies(), group.getAttachedPolicyArns())));}- IamRole role = roleOpt.get();- List<String> docs = new ArrayList<>();+ return held;+ }- // Role inline policies- docs.addAll(role.getInlinePolicies().values());+ private List<HeldPolicy> rolePolicies(IamRole role) {+ return inlineThenManaged(role.getInlinePolicies(), role.getAttachedPolicyArns());+ }- // Role attached managed policies- for (String arn : role.getAttachedPolicyArns()) {- Optional<IamPolicy> p = resolvePolicy(arn);- if (p.isPresent() && p.get().getDefaultDocument() != null) {- docs.add(p.get().getDefaultDocument());- }+ private List<HeldPolicy> inlineThenManaged(Map<String, String> inline, List<String> attachedArns) {+ List<HeldPolicy> held = new ArrayList<>();+ inline.values().forEach(document -> held.add(new HeldPolicy(null, document)));+ for (String arn : attachedArns) {+ resolvePolicy(arn).map(IamPolicy::getDefaultDocument)+ .ifPresent(document -> held.add(new HeldPolicy(arn, document)));}+ return held;+ }- return docs;+ private static List<String> documents(List<HeldPolicy> held) {+ return held.stream().map(HeldPolicy::document).collect(Collectors.toCollection(ArrayList::new));}/**diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.javaindex 9cf7f27744..d937057dd6 100644--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.stepfunctions;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.IamConditionContextResolver;+import io.github.hectorvent.floci.services.iam.AccessDeniedMessages;+import io.github.hectorvent.floci.services.iam.AccessDeniedMessages.PolicyType;import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator.TrustDecision;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;@@ -76,8 +78,7 @@ public class LambdaTaskAuthorizer {Optional<IamRole> invokingRole = role(roleArn);if (invokingRole.isEmpty()) {LOG.infov("Role {0} names no existing role, so it cannot invoke {1}", roleArn, resourceArn);- return Optional.of(denied(roleArn, action, resourceArn, "because no identity-based policy allows the "- + action + " action"));+ return Optional.of(denied(roleArn, action, resourceArn, PolicyType.IDENTITY_BASED_POLICY.noAllow(action)));}// The role is evaluated as itself, under the ARN IAM holds for it, whichever form names it.String invokingRoleArn = invokingRole.get().getArn();@@ -122,8 +123,8 @@ public class LambdaTaskAuthorizer {Optional<IamRole> executionRole = role(executionRoleArn);if (executionRole.isEmpty()) {LOG.infov("Execution role {0} names no existing role, so it cannot assume {1}", executionRoleArn, roleArn);- return Optional.of(denied(executionRoleArn, ASSUME_ROLE, roleArn, "because no identity-based policy allows the "- + ASSUME_ROLE + " action"));+ return Optional.of(denied(executionRoleArn, ASSUME_ROLE, roleArn,+ PolicyType.IDENTITY_BASED_POLICY.noAllow(ASSUME_ROLE)));}String callerRoleArn = executionRole.get().getArn();Optional<IamRole> target = role(roleArn);@@ -215,27 +216,27 @@ public class LambdaTaskAuthorizer {boolean crossAccount = relationship == ResourceAccountRelationship.CROSS_ACCOUNT;if (scps.contains(SimulationDecision.EXPLICIT_DENY)) {- return "with an explicit deny in a service control policy";+ return PolicyType.SERVICE_CONTROL_POLICY.explicitDeny();}if (grant.explicitDeny()) {- return "with an explicit deny in " + grant.deniedIn();+ return grant.type().explicitDeny();}if (identity == SimulationDecision.EXPLICIT_DENY) {- return "with an explicit deny in an identity-based policy";+ return PolicyType.IDENTITY_BASED_POLICY.explicitDeny();}if (boundary == SimulationDecision.EXPLICIT_DENY) {- return "with an explicit deny in a permissions boundary";+ return PolicyType.PERMISSIONS_BOUNDARY.explicitDeny();}if (scps.contains(SimulationDecision.IMPLICIT_DENY)) {- return "because no service control policy allows the " + action + " action";+ return PolicyType.SERVICE_CONTROL_POLICY.noAllow(action);}if ((grant.required() || crossAccount) && !grant.allows()) {- return "because no " + grant.kind() + " allows the " + action + " action";+ return grant.type().noAllow(action);}if (identity != SimulationDecision.ALLOWED && (crossAccount || !grant.sufficient())) {- return "because no identity-based policy allows the " + action + " action";+ return PolicyType.IDENTITY_BASED_POLICY.noAllow(action);}- return "because no permissions boundary allows the " + action + " action";+ return PolicyType.PERMISSIONS_BOUNDARY.noAllow(action);}private SimulationDecision simulate(List<String> documents, String action, String resource,@@ -244,8 +245,7 @@ public class LambdaTaskAuthorizer {}private static String denied(String roleArn, String action, String resource, String reason) {- return "User: " + sessionArn(roleArn) + " is not authorized to perform: " + action + " on resource: "- + resource + (reason == null ? "" : " " + reason);+ return AccessDeniedMessages.notAuthorized(sessionArn(roleArn), action, resource, reason);}/**@@ -272,24 +272,23 @@ public class LambdaTaskAuthorizer {* caller's identity-based policies* @param required whether the call needs it to allow even within one account, as a role's* trust policy does- * @param deniedIn the policy, as an explicit denial names it- * @param kind the policy type, as an implicit denial names it+ * @param type the policy type, as the access denied message names it*/private record ResourceGrant(boolean explicitDeny, boolean allows, boolean sufficient, boolean required,- String deniedIn, String kind) {+ PolicyType type) {static ResourceGrant of(ResourcePolicyDecision functionPolicy) {boolean sufficient = functionPolicy == ResourcePolicyDecision.ALLOW|| functionPolicy == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER;return new ResourceGrant(functionPolicy == ResourcePolicyDecision.EXPLICIT_DENY,sufficient || functionPolicy == ResourcePolicyDecision.ALLOW_ACCOUNT, sufficient, false,- "a resource-based policy", "resource-based policy");+ PolicyType.RESOURCE_BASED_POLICY);}static ResourceGrant of(TrustDecision trust) {return new ResourceGrant(trust == TrustDecision.EXPLICIT_DENY,trust == TrustDecision.ALLOW || trust == TrustDecision.ALLOW_ACCOUNT,- trust == TrustDecision.ALLOW, true, "the role trust policy", "role trust policy");+ trust == TrustDecision.ALLOW, true, PolicyType.ROLE_TRUST_POLICY);}}}diff --git a/src/main/resources/aws/iam-passed-network-connectors.json b/src/main/resources/aws/iam-passed-network-connectors.jsonnew file mode 100644index 0000000000..6cc0337657--- /dev/null+++ b/src/main/resources/aws/iam-passed-network-connectors.json@@ -0,0 +1,24 @@+{+ "_source": {"generator": "tools/aws/regen_iam_passed_network_connectors.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.113 (installed package)", "retrieved": "2026-10-27", "note": "make iam-passed-network-connectors-check re-derives every member from botocore; make iam-passed-network-connectors-verify checks every operation against AWS."},+ "namespaces": {"appsync": ["appsync"], "lambda": ["lambda-microvms", "lambda-web"]},+ "operations": {+ "appsync:CreateDataSource": {"notRead": "botocore's model has no request member that names a connector"},+ "appsync:UpdateDataSource": {"notRead": "botocore's model has no request member that names a connector"},+ "lambda:CreateMicrovmImage": {"connectors": [+ {"member": "egressNetworkConnectors[]", "whenAbsent": "aws-network-connector:INTERNET_EGRESS"}+ ]},+ "lambda:CreateWebFunction": {"connectors": [+ {"member": "revisionConfig.serviceConfig.egressNetworkConnectorArn"}+ ]},+ "lambda:CreateWebFunctionRevision": {"connectors": [+ {"member": "serviceConfig.egressNetworkConnectorArn"}+ ]},+ "lambda:RunMicrovm": {"connectors": [+ {"member": "egressNetworkConnectors[]", "whenAbsent": "aws-network-connector:INTERNET_EGRESS"},+ {"member": "ingressNetworkConnectors[]", "whenAbsent": "aws-network-connector:HTTP_INGRESS"}+ ]},+ "lambda:UpdateMicrovmImage": {"connectors": [+ {"member": "egressNetworkConnectors[]", "whenAbsent": "aws-network-connector:INTERNET_EGRESS"}+ ]}+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PassedNetworkConnectorsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PassedNetworkConnectorsIntegrationTest.javanew file mode 100644index 0000000000..a758ccb25a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/core/common/PassedNetworkConnectorsIntegrationTest.java@@ -0,0 +1,176 @@+package io.github.hectorvent.floci.core.common;++import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.lambdaweb.LambdaWebRoles;+import io.github.hectorvent.floci.testing.EnforcementFixtures;+import io.github.hectorvent.floci.testing.EnforcementFixtures.Session;+import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials;+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.path.xml.XmlPath;+import io.restassured.response.ValidatableResponse;+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 static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;+import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;++/** Under IAM enforcement a request needs lambda:PassNetworkConnector on each network connector it passes. */+@QuarkusTest+@TestProfile(IamEnforcementProfile.class)+class PassedNetworkConnectorsIntegrationTest {++ private static final String ACCOUNT = "000000000000";+ private static final String ROLE = "arn:aws:iam::000000000000:role/web";+ private static final String CONNECTOR =+ "arn:aws:lambda:us-east-1:000000000000:network-connector:nc-0123456789abcdef0";+ private static final String MANAGED = "arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:";+ private static final String DENY = """+ {"Version":"2012-10-17","Statement":[+ {"Effect":"Deny","Action":"lambda:PassNetworkConnector","Resource":"*"}]}""";++ @TestHTTPResource("/")+ static URI baseUri;++ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();++ @Inject+ IamService iamService;++ @Test+ void aRevisionNeedsPassNetworkConnectorOnTheVersionItNames() {+ int port = baseUri.getPort();+ String name = "connector-pass-" + Long.toString(System.nanoTime(), 36);+ String denyArn = "arn:aws:iam::" + ACCOUNT + ":policy/" + name;+ cleanup.register(() -> EnforcementFixtures.removePolicy(port, auth(ACCOUNT, "iam"), denyArn));+ LambdaWebRoles.trustLambda(iamService, ROLE);+ String roleArn = EnforcementFixtures.createRole(cleanup, port, ACCOUNT, "/", name,+ policy("lambda:CreateWebFunctionRevision", ""));+ Session session = EnforcementFixtures.assumeRole(port, ACCOUNT, roleArn);+ String denied = "User: arn:aws:sts::" + ACCOUNT + ":assumed-role/" + name + "/s is not authorized to perform:"+ + " lambda:PassNetworkConnector on resource: " + CONNECTOR + ":1 ";++ revision(session, CONNECTOR + ":1").statusCode(403)+ .header("X-Amzn-Errortype", "AccessDeniedException")+ .body("Message", equalTo(denied+ + "because no identity-based policy allows the lambda:PassNetworkConnector action"));++ iamService.putRolePolicy(name, "p", policy("lambda:CreateWebFunctionRevision", allow(CONNECTOR + ":1")));+ revision(session, CONNECTOR + ":1").statusCode(404)+ .body("message", equalTo("The function arn:aws:lambda:us-east-1:" + ACCOUNT+ + ":web-function/missing does not exist."));+ revision(session, CONNECTOR + ":2").statusCode(403);++ iamService.createPolicy(name, "/", null, DENY, null);+ iamService.attachRolePolicy(name, denyArn);+ revision(session, CONNECTOR + ":1").statusCode(403)+ .body("Message", equalTo(denied + "with an explicit deny in an identity-based policy: " + denyArn));+ }++ @Test+ void aUserAndItsSessionTokenNameTheManagedPolicyThatDenies() {+ int port = baseUri.getPort();+ String name = "connector-pass-" + Long.toString(System.nanoTime(), 36);+ String denyArn = "arn:aws:iam::" + ACCOUNT + ":policy/" + name;+ cleanup.register(() -> EnforcementFixtures.removePolicy(port, auth(ACCOUNT, "iam"), denyArn));+ LambdaWebRoles.trustLambda(iamService, ROLE);+ UserCredentials user = EnforcementFixtures.createUser(cleanup, port, auth(ACCOUNT, "iam"), name);+ EnforcementFixtures.putUserPolicy(port, auth(ACCOUNT, "iam"), name, "p",+ policy("lambda:CreateWebFunctionRevision", allow("*")));+ iamService.createPolicy(name, "/", null, DENY, null);+ iamService.attachUserPolicy(name, denyArn);+ Session token = sessionToken(user.accessKeyId());+ String denied = "User: arn:aws:iam::" + ACCOUNT + ":user/" + name + " is not authorized to perform:"+ + " lambda:PassNetworkConnector on resource: " + CONNECTOR + ":1"+ + " with an explicit deny in an identity-based policy: " + denyArn;++ revision(new Session(user.accessKeyId(), null), CONNECTOR + ":1").statusCode(403)+ .body("Message", equalTo(denied));+ revision(token, CONNECTOR + ":1").statusCode(403).body("Message", equalTo(denied));+ }++ @Test+ void aMicrovmPassesTheManagedConnectorsWhenItNamesNone() {+ int port = baseUri.getPort();+ String name = "connector-pass-" + Long.toString(System.nanoTime(), 36);+ String roleArn = EnforcementFixtures.createRole(cleanup, port, ACCOUNT, "/", name,+ policy("lambda:RunMicrovm", ""));+ Session session = EnforcementFixtures.assumeRole(port, ACCOUNT, roleArn);+ String denied = "User: arn:aws:sts::" + ACCOUNT + ":assumed-role/" + name + "/s is not authorized to perform:"+ + " lambda:PassNetworkConnector on resource: ";+ String noAllow = " because no identity-based policy allows the lambda:PassNetworkConnector action";++ microvm(session, "").statusCode(403).body("Message", equalTo(denied + MANAGED + "INTERNET_EGRESS" + noAllow));+ microvm(session, ", \"egressNetworkConnectors\": []").statusCode(403)+ .body("Message", equalTo(denied + MANAGED + "INTERNET_EGRESS" + noAllow));++ iamService.putRolePolicy(name, "p", policy("lambda:RunMicrovm",+ allow(MANAGED + "INTERNET_EGRESS") + allow(CONNECTOR + ":1")));+ microvm(session, "").statusCode(403).body("Message", equalTo(denied + MANAGED + "HTTP_INGRESS" + noAllow));+ microvm(session, ", \"ingressNetworkConnectors\": [\"" + CONNECTOR + ":2\"]").statusCode(403)+ .body("Message", equalTo(denied + CONNECTOR + ":2" + noAllow));+ microvm(session, ", \"egressNetworkConnectors\": [\"" + CONNECTOR + ":1\", \"" + CONNECTOR + ":3\"],"+ + " \"ingressNetworkConnectors\": [\"" + CONNECTOR + ":2\"]").statusCode(403)+ .body("Message", equalTo(denied + CONNECTOR + ":3" + noAllow));++ iamService.putRolePolicy(name, "p", policy("lambda:RunMicrovm", allow("*")));+ microvm(session, "").statusCode(404);+ }++ private static Session sessionToken(String accessKeyId) {+ XmlPath credentials = given().header("Authorization", auth(accessKeyId, "sts"))+ .formParam("Action", "GetSessionToken")+ .when().post("/")+ .then().statusCode(200).extract().xmlPath();+ return new Session(+ credentials.getString("GetSessionTokenResponse.GetSessionTokenResult.Credentials.AccessKeyId"),+ credentials.getString("GetSessionTokenResponse.GetSessionTokenResult.Credentials.SessionToken"));+ }++ private static ValidatableResponse revision(Session session, String connectorArn) {+ return signed(session).contentType("application/json")+ .body("""+ {"buildConfig": {"codeConfig": {"s3Object": {"bucket": "web-code", "key": "app.zip"}},+ "runtimeConfig": {"runtime": "nodejs24.x"}},+ "serviceConfig": {"executionRoleArn": "%s", "egressNetworkConnectorArn": "%s"}}+ """.formatted(ROLE, connectorArn))+ .when().post("/2025-03-07/web-functions/missing/revisions")+ .then();+ }++ private static ValidatableResponse microvm(Session session, String connectors) {+ return signed(session).contentType("application/json")+ .body("{\"imageIdentifier\": \"arn:aws:lambda:us-east-1:" + ACCOUNT + ":microvm-image:missing\""+ + connectors + "}")+ .when().post("/2025-09-09/microvms")+ .then();+ }++ private static RequestSpecification signed(Session session) {+ RequestSpecification request = given().header("Authorization", auth(session.accessKeyId(), "lambda"));+ if (session.sessionToken() != null) {+ request.header("X-Amz-Security-Token", session.sessionToken());+ }+ return request;+ }++ private static String allow(String resource) {+ return ",{\"Effect\":\"Allow\",\"Action\":\"lambda:PassNetworkConnector\",\"Resource\":\"" + resource + "\"}";+ }++ private static String policy(String action, String more) {+ return """+ {"Version":"2012-10-17","Statement":[+ {"Effect":"Allow","Action":"%s","Resource":"*"},+ {"Effect":"Allow","Action":"iam:PassRole","Resource":"*"}%s]}""".formatted(action, more);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PassedNetworkConnectorsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PassedNetworkConnectorsTest.javanew file mode 100644index 0000000000..3c8286b29f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/core/common/PassedNetworkConnectorsTest.java@@ -0,0 +1,84 @@+package io.github.hectorvent.floci.core.common;++import jakarta.ws.rs.container.ContainerRequestContext;+import jakarta.ws.rs.core.MediaType;+import org.junit.jupiter.api.Test;++import java.io.ByteArrayInputStream;+import java.nio.charset.StandardCharsets;+import java.util.List;+import java.util.Set;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/** The vendored table of where each operation's request names the network connectors it passes. */+class PassedNetworkConnectorsTest {++ private static final String CONNECTOR = "arn:aws:lambda:us-east-1:111122223333:network-connector:nc-1";+ private static final String MANAGED = "arn:aws:lambda:us-west-2:aws:network-connector:aws-network-connector:";++ @Test+ void theTableReadsTheLambdaOperationsAndLeavesOutTheUnreadOnes() {+ assertEquals(Set.of("lambda:CreateMicrovmImage", "lambda:CreateWebFunction", "lambda:CreateWebFunctionRevision",+ "lambda:RunMicrovm", "lambda:UpdateMicrovmImage"), PassedNetworkConnectors.table().keySet());+ }++ @Test+ void aWebFunctionPassesTheConnectorItsRevisionNames() {+ assertEquals(List.of(CONNECTOR + ":1"), PassedNetworkConnectors.of("lambda:CreateWebFunctionRevision",+ json("{\"serviceConfig\":{\"egressNetworkConnectorArn\":\"" + CONNECTOR + ":1\"}}"), "us-west-2"));+ assertEquals(List.of(CONNECTOR + ":2"), PassedNetworkConnectors.of("lambda:CreateWebFunction",+ json("{\"revisionConfig\":{\"serviceConfig\":{\"egressNetworkConnectorArn\":\"" + CONNECTOR + ":2\"}}}"),+ "us-west-2"));+ assertEquals(List.of(), PassedNetworkConnectors.of("lambda:CreateWebFunctionRevision",+ json("{\"serviceConfig\":{\"executionRoleArn\":\"arn:aws:iam::111122223333:role/r\"}}"), "us-west-2"));+ }++ @Test+ void aMicrovmPassesItsEgressConnectorsThenItsIngressOnes() {+ assertEquals(List.of(CONNECTOR + ":1", CONNECTOR + ":3", CONNECTOR + ":2"), PassedNetworkConnectors.of(+ "lambda:RunMicrovm", json("{\"ingressNetworkConnectors\":[\"" + CONNECTOR + ":2\"],"+ + "\"egressNetworkConnectors\":[\"" + CONNECTOR + ":1\",\"" + CONNECTOR + ":3\"]}"), "us-west-2"));+ }++ @Test+ void aMicrovmThatNamesNoConnectorPassesTheManagedOnes() {+ assertEquals(List.of(MANAGED + "INTERNET_EGRESS", MANAGED + "HTTP_INGRESS"),+ PassedNetworkConnectors.of("lambda:RunMicrovm", json("{\"imageIdentifier\":\"i\"}"), "us-west-2"));+ assertEquals(List.of(MANAGED + "INTERNET_EGRESS", CONNECTOR + ":2"), PassedNetworkConnectors.of(+ "lambda:RunMicrovm", json("{\"egressNetworkConnectors\":[],\"ingressNetworkConnectors\":[\""+ + CONNECTOR + ":2\"]}"), "us-west-2"));+ assertEquals(List.of(MANAGED + "INTERNET_EGRESS"),+ PassedNetworkConnectors.of("lambda:CreateMicrovmImage", json("{\"name\":\"n\"}"), "us-west-2"));+ assertEquals(List.of("arn:aws-cn:lambda:cn-north-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS"),+ PassedNetworkConnectors.of("lambda:UpdateMicrovmImage", json("{}"), "cn-north-1"));+ }++ @Test+ void anOperationTheTableDoesNotReadPassesNothing() {+ assertEquals(List.of(), PassedNetworkConnectors.of("appsync:CreateDataSource", json("{}"), "us-west-2"));+ assertEquals(List.of(), PassedNetworkConnectors.of("lambda:CreateFunction", json("{}"), "us-west-2"));+ }++ @Test+ void aMalformedTableFailsToLoad() {+ assertThrows(IllegalStateException.class, () -> PassedNetworkConnectors.parse(stream("{\"operations\":{}}")));+ assertThrows(IllegalStateException.class, () -> PassedNetworkConnectors.parse(stream(+ "{\"operations\":{\"lambda:RunMicrovm\":{\"connectors\":[{\"member\":\"a..b\"}]}}}")));+ }++ private static ByteArrayInputStream stream(String text) {+ return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));+ }++ private static ContainerRequestContext json(String body) {+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);+ ContainerRequestContext request = mock(ContainerRequestContext.class);+ when(request.getMediaType()).thenReturn(MediaType.APPLICATION_JSON_TYPE);+ when(request.getEntityStream()).thenAnswer(invocation -> new ByteArrayInputStream(bytes));+ return request;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AccessDeniedMessagesTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AccessDeniedMessagesTest.javanew file mode 100644index 0000000000..a883ff6066--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/AccessDeniedMessagesTest.java@@ -0,0 +1,122 @@+package io.github.hectorvent.floci.services.iam;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.iam.AccessDeniedMessages.PolicyType;+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.SimulationDecision;+import io.github.hectorvent.floci.services.iam.IamService.HeldPolicies;+import io.github.hectorvent.floci.services.iam.IamService.HeldPolicy;+import io.github.hectorvent.floci.services.iam.model.CallerContext;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;++class AccessDeniedMessagesTest {++ private static final String ACTION = "lambda:PassNetworkConnector";+ private static final String CONNECTOR = "arn:aws:lambda:us-east-1:111111111111:network-connector:nc-1";+ private static final String MANAGED = "arn:aws:iam::111111111111:policy/deny";+ private static final String BOUNDARY = "arn:aws:iam::111111111111:policy/boundary";+ private static final String NO_IDENTITY_ALLOW =+ "because no identity-based policy allows the lambda:PassNetworkConnector action";++ private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());++ @Test+ void eachPolicyTypeIsWordedAsAwsWordsIt() {+ assertEquals("with an explicit deny in a service control policy", PolicyType.SERVICE_CONTROL_POLICY.explicitDeny());+ assertEquals("with an explicit deny in the role trust policy", PolicyType.ROLE_TRUST_POLICY.explicitDeny());+ assertEquals("with an explicit deny in an identity-based policy: " + MANAGED,+ PolicyType.IDENTITY_BASED_POLICY.explicitDeny(MANAGED));+ assertEquals("because no resource-based policy allows the s3:GetObject action",+ PolicyType.RESOURCE_BASED_POLICY.noAllow("s3:GetObject"));+ assertEquals("because no session policy allows the s3:GetObject action",+ PolicyType.SESSION_POLICY.refusal(SimulationDecision.IMPLICIT_DENY, "s3:GetObject", MANAGED));+ assertEquals("User: arn:aws:iam::111111111111:root is not authorized to perform: sts:AssumeRole on resource: r",+ AccessDeniedMessages.notAuthorized("arn:aws:iam::111111111111:root", "sts:AssumeRole", "r", null));+ }++ @Test+ void theVersionArnAsGivenHasToBeAllowed() {+ assertNull(refusal(policy(allow(CONNECTOR + ":1")), CONNECTOR + ":1"));+ assertEquals(NO_IDENTITY_ALLOW, refusal(policy(allow(CONNECTOR + ":1")), CONNECTOR + ":2"));+ assertEquals(NO_IDENTITY_ALLOW, refusal(policy(allow(CONNECTOR)), CONNECTOR + ":1"));+ assertNull(refusal(policy(allow(CONNECTOR + ":*")), CONNECTOR + ":1"));+ }++ @Test+ void anExplicitDenyNamesTheManagedPolicyThatHoldsIt() {+ HeldPolicies held = new HeldPolicies(List.of(new HeldPolicy(null, policy(allow("*"))),+ new HeldPolicy(MANAGED, policy(deny("*")))), null);+ assertEquals("with an explicit deny in an identity-based policy: " + MANAGED,+ AccessDeniedMessages.firstRefusal(evaluator, caller(held, null, null), held, ACTION, CONNECTOR, Map.of()));++ HeldPolicies inlineFirst = new HeldPolicies(List.of(new HeldPolicy(null, policy(allow("*"), deny("*"))),+ new HeldPolicy(MANAGED, policy(deny("*")))), null);+ assertEquals("with an explicit deny in an identity-based policy", AccessDeniedMessages.firstRefusal(+ evaluator, caller(inlineFirst, null, null), inlineFirst, ACTION, CONNECTOR, Map.of()));+ assertEquals("with an explicit deny in an identity-based policy", AccessDeniedMessages.firstRefusal(+ evaluator, caller(held, null, null), null, ACTION, CONNECTOR, Map.of()));+ }++ @Test+ void theIdentityPoliciesThenTheBoundaryThenTheSessionPolicyNameTheReason() {+ String allowAll = policy(allow("*"));+ String denyAll = policy(allow("*"), deny("*"));+ String allowNothing = policy(allowCreate());++ assertEquals(NO_IDENTITY_ALLOW, refusal(allowNothing, denyAll, denyAll));+ assertEquals("because no permissions boundary allows the lambda:PassNetworkConnector action",+ refusal(allowAll, allowNothing, denyAll));+ assertEquals("with an explicit deny in a permissions boundary: " + BOUNDARY, refusal(allowAll, denyAll, allowNothing));+ assertEquals("because no session policy allows the lambda:PassNetworkConnector action",+ refusal(allowAll, allowAll, allowNothing));+ assertEquals("with an explicit deny in a session policy", refusal(allowAll, null, denyAll));+ assertNull(refusal(allowAll, allowAll, allowAll));+ }++ @Test+ void serviceControlPoliciesComeFirstAndAnEmptyLevelIsSkipped() {+ CallerContext caller = CallerContext.of(List.of(policy(allowCreate())));+ assertEquals("with an explicit deny in a service control policy", AccessDeniedMessages.firstRefusal(evaluator,+ caller.withScpLevels(List.of(List.of(), List.of(policy(allow("*"), deny("*"))))), null, ACTION,+ CONNECTOR, Map.of()));+ assertEquals("because no service control policy allows the lambda:PassNetworkConnector action",+ AccessDeniedMessages.firstRefusal(evaluator, caller.withScpLevels(List.of(List.of(policy(allowCreate())))),+ null, ACTION, CONNECTOR, Map.of()));+ }++ private String refusal(String identity, String resource) {+ return AccessDeniedMessages.firstRefusal(evaluator, CallerContext.of(List.of(identity)), null, ACTION, resource,+ Map.of());+ }++ private String refusal(String identity, String boundary, String session) {+ HeldPolicies held = new HeldPolicies(List.of(new HeldPolicy(null, identity)), boundary == null ? null : BOUNDARY);+ return AccessDeniedMessages.firstRefusal(evaluator, caller(held, boundary, session), held, ACTION, CONNECTOR,+ Map.of());+ }++ private static CallerContext caller(HeldPolicies held, String boundary, String session) {+ return new CallerContext(held.identity().stream().map(HeldPolicy::document).toList(), session, boundary);+ }++ private static String policy(String... statements) {+ return "{\"Version\":\"2012-10-17\",\"Statement\":[" + String.join(",", statements) + "]}";+ }++ private static String allow(String resource) {+ return "{\"Effect\":\"Allow\",\"Action\":\"" + ACTION + "\",\"Resource\":\"" + resource + "\"}";+ }++ private static String deny(String resource) {+ return "{\"Effect\":\"Deny\",\"Action\":\"" + ACTION + "\",\"Resource\":\"" + resource + "\"}";+ }++ private static String allowCreate() {+ return "{\"Effect\":\"Allow\",\"Action\":\"lambda:CreateWebFunctionRevision\",\"Resource\":\"*\"}";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.javaindex 59defc61f3..188ccb33a4 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java@@ -567,7 +567,9 @@ class IamPassRoleEnforcementIntegrationTest {user.policy(allow("lambda:CreateMicrovmImage", "*"));denied(user.rest("lambda").body(createImage).post("/2025-09-09/microvm-images").then());- user.policy(allow("lambda:CreateMicrovmImage", "*") + "," + passRole(build, LAMBDA));+ // It also passes the managed egress connector an image gets when it names none.+ user.policy(allow("lambda:CreateMicrovmImage", "*") + "," + passRole(build, LAMBDA) + ","+ + allow("lambda:PassNetworkConnector", "*"));user.rest("lambda").body(createImage).post("/2025-09-09/microvm-images").then().statusCode(201);cleanup.register(() -> admin("lambda").delete("/2025-09-09/microvm-images/" + image));// Reading it is checked against the image's ARN.diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteEnforcementIntegrationTest.javaindex 662b1ae20a..f2c6420638 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteEnforcementIntegrationTest.java@@ -430,7 +430,8 @@ class IamRestRouteEnforcementIntegrationTest {policy(user, allow("lambda:RunMicrovm", "*") + "," + deny("lambda:RunMicrovm", image));refused(as(user, "lambda").body(run).post("/2025-09-09/microvms").then(), "lambda:RunMicrovm");- policy(user, allow("lambda:RunMicrovm", image));+ // It also passes the managed connectors a MicroVM gets when it names none.+ policy(user, allow("lambda:RunMicrovm", image) + "," + allow("lambda:PassNetworkConnector", "*"));String microvm = as(user, "lambda").body(run).post("/2025-09-09/microvms").then().statusCode(200).extract().path("microvmId");cleanup.register(() -> admin().delete("/2025-09-09/microvms/" + microvm));diff --git a/tools/aws/regen_iam_passed_network_connectors.py b/tools/aws/regen_iam_passed_network_connectors.pynew file mode 100644index 0000000000..5335cd5c71--- /dev/null+++ b/tools/aws/regen_iam_passed_network_connectors.py@@ -0,0 +1,370 @@+#!/usr/bin/env python3+"""Regenerate src/main/resources/aws/iam-passed-network-connectors.json from AWS's Service Reference and botocore.++A request that names a Lambda network connector also needs `lambda:PassNetworkConnector` on it. The Lambda+developer guide, for Web Functions: "The caller must have `lambda:PassNetworkConnector` on the referenced+connector whenever a `create-web-function` or `create-web-function-revision` call sets+`egressNetworkConnectorArn`." `PassedNetworkConnectors` finds the connectors a request passes, and this file+tells it where each operation's request carries them. It comes from the same two sources as+`regen_iam_passed_roles.py`:++- AWS's Service Reference, which lists `lambda:PassNetworkConnector` among an operation's `AuthorizedActions`+ but does not say which request member names the connector:++ https://servicereference.us-east-1.amazonaws.com/ (the index of services)+ https://servicereference.us-east-1.amazonaws.com/v1/<svc>/<svc>.json++- botocore's model of each SDK client the reference lists the operation for (Apache-2.0,+ https://github.com/boto/botocore, the pinned release), which gives the request's members.++Every operation the reference lists with the action is read, in any namespace. A member of its request names+a connector when its name ends in `NetworkConnector`, `NetworkConnectorArn` or the plural of one, and it is a+string or a list of strings without an enum. The members are kept in sorted order, which is the order AWS+checks them in: RunMicrovm's egress connectors before its ingress ones.++Where a request names no connector in a member, or an empty list, AWS checks the Lambda-managed connector the+MicroVM gets instead (measured, us-east-1). Those are recorded in `WHEN_ABSENT` and vendored as `whenAbsent`,+the connector's name, which Floci reads as `arn:<partition>:lambda:<region>:aws:network-connector:<name>`.+An operation whose request names no connector this rule reads is in `NOT_READ` with its reason, and generation+fails on one that is in neither.++The two gates split along the sources, as for the passed role table:++- `--check` is offline and needs the pinned botocore. The file must be well-formed, and every operation's+ members must be exactly what the rule and `WHEN_ABSENT` give from botocore for the models the file names.+- `--verify` is online and stdlib-only. Every operation the file carries must still list the action, for the+ same SDK clients. An operation AWS has added is reported without failing: until the next sync it passes+ connectors unchecked, which is where it was before this file existed.++Run from anywhere in the repo:+ python3 tools/aws/regen_iam_passed_network_connectors.py # rewrite the vendored file in place+ python3 tools/aws/regen_iam_passed_network_connectors.py --check # offline: members match botocore+ python3 tools/aws/regen_iam_passed_network_connectors.py --verify # online: operations match AWS+ python3 tools/aws/regen_iam_passed_network_connectors.py --source-dir <dir> # read saved <svc>.json files+"""+from __future__ import annotations++import argparse+import json+import re+import sys+from datetime import datetime, timezone+from pathlib import Path++from regen_iam_authorized_actions import fetch_references+from regen_iam_passed_roles import (BODY_LOCATIONS, MEMBER_PATH_RE, NAMESPACE_RE, OPERATION_RE, _leaf, _shown, _step,+ load_models, namespace_of, readable)+from regen_partitions import resolve_botocore_data++REPO_ROOT = Path(__file__).resolve().parents[2]+OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-passed-network-connectors.json"++ACTION = ("lambda", "PassNetworkConnector")++# A member that names a connector: NetworkConnector, NetworkConnectorArn and their plurals.+CONNECTOR_MEMBER_RE = re.compile(r"networkconnector(arn)?s?$", re.IGNORECASE)+# A Lambda-managed connector's name.+MANAGED_CONNECTOR_RE = re.compile(r"^aws-network-connector:[A-Z_]+$")++# The connector AWS checks for a member the request leaves out or gives as an empty list, measured on AWS+# with a caller allowed every other action the request needs.+WHEN_ABSENT = {+ "lambda:CreateMicrovmImage": {"egressNetworkConnectors[]": "aws-network-connector:INTERNET_EGRESS"},+ "lambda:RunMicrovm": {"egressNetworkConnectors[]": "aws-network-connector:INTERNET_EGRESS",+ "ingressNetworkConnectors[]": "aws-network-connector:HTTP_INGRESS"},+ "lambda:UpdateMicrovmImage": {"egressNetworkConnectors[]": "aws-network-connector:INTERNET_EGRESS"},+}++# Operations the reference lists with the action whose request names no connector this file can read.+NOT_READ = {+ # AWS checks the connector in httpConfig.networkConnectorArn (measured, us-east-1), which botocore's+ # model does not have yet.+ "appsync:CreateDataSource": "botocore's model has no request member that names a connector",+ "appsync:UpdateDataSource": "botocore's model has no request member that names a connector",+}+++# --------------------------------------------------------------------------- #+# The Service Reference: which operations pass a connector+# --------------------------------------------------------------------------- #+def passed_connector_operations(documents: list[dict]) -> dict[str, dict]:+ """Every operation of every namespace that lists lambda:PassNetworkConnector, with the SDK clients it is+ listed for."""+ found: dict[str, set[str]] = {}+ for document in documents:+ namespace = document.get("Name")+ if not isinstance(namespace, str) or not NAMESPACE_RE.match(namespace):+ raise ValueError(f"{namespace!r} is not usable as an IAM namespace")+ for operation in document.get("Operations", []):+ name = operation.get("Name") if isinstance(operation, dict) else None+ if not isinstance(name, str):+ raise ValueError(f"{namespace}: operation entry without a usable 'Name': {operation!r}")+ authorized = operation.get("AuthorizedActions") or []+ if not isinstance(authorized, list) or not all(isinstance(entry, dict) for entry in authorized):+ raise ValueError(f"{namespace}:{name}: 'AuthorizedActions' is not a list of objects")+ if not any((entry.get("Service"), entry.get("Name")) == ACTION for entry in authorized):+ continue+ clients = {sdk["Name"] for sdk in operation.get("SDK") or []+ if isinstance(sdk, dict) and sdk.get("Package") == "Boto3" and isinstance(sdk.get("Name"), str)}+ found.setdefault(f"{namespace}:{name}", set()).update(clients)+ return {key: {"clients": sorted(clients)} for key, clients in sorted(found.items())}+++# --------------------------------------------------------------------------- #+# botocore: which members of the request name a connector+# --------------------------------------------------------------------------- #+def connector_members(model: dict, operation: str) -> list[str]:+ """The members of the operation's request the rule reads, as vendored paths, sorted."""+ spec = model["operations"].get(operation)+ if spec is None or "input" not in spec or not readable(model):+ return []+ root = model["shapes"][spec["input"]["shape"]]+ payload = root.get("payload")+ found: set[str] = set()++ def walk(shape_name: str, prefix: str, top: bool, seen: frozenset) -> None:+ if shape_name in seen:+ return+ shape = model["shapes"][shape_name]+ seen = seen | {shape_name}+ if shape["type"] == "list":+ walk(shape["member"]["shape"], prefix + _step(shape), False, seen)+ elif shape["type"] == "map":+ walk(shape["value"]["shape"], prefix + _step(shape), False, seen)+ elif shape["type"] == "structure":+ for name, member in shape.get("members", {}).items():+ if top and member.get("location") not in BODY_LOCATIONS:+ continue+ serialized = member.get("locationName", name)+ path = f"{prefix}.{serialized}" if prefix else serialized+ if CONNECTOR_MEMBER_RE.search(name) and _leaf(model, member["shape"]) is not None:+ found.add(path + _step(model["shapes"][member["shape"]]))+ else:+ walk(member["shape"], path, False, seen)++ if payload is not None:+ walk(root["members"][payload]["shape"], "", False, frozenset())+ else:+ walk(spec["input"]["shape"], "", True, frozenset())+ return sorted(found)+++# --------------------------------------------------------------------------- #+# The vendored document+# --------------------------------------------------------------------------- #+def entry_for(operation: str, models: dict[str, dict]) -> dict:+ """What the file says for one operation, from the models of its namespace."""+ name = operation.split(":", 1)[1]+ members = sorted({path for model in models.values() for path in connector_members(model, name)})+ if operation in NOT_READ:+ if members:+ raise ValueError(f"{operation}: NOT_READ says it names no connector, but its request has {members}")+ return {"notRead": NOT_READ[operation]}+ if not members:+ raise ValueError(f"{operation}: no request member names a network connector; "+ f"say why it is not read (NOT_READ)")+ absent = WHEN_ABSENT.get(operation, {})+ unknown = sorted(set(absent) - set(members))+ if unknown:+ raise ValueError(f"{operation}: WHEN_ABSENT names {unknown}, which its request does not have")+ connectors = []+ for path in members:+ connector: dict = {"member": path}+ if path in absent:+ connector["whenAbsent"] = absent[path]+ connectors.append(connector)+ return {"connectors": connectors}+++def build(documents: list[dict], provenance: str, data: Path, botocore: str) -> dict:+ upstream = passed_connector_operations(documents)+ stale = sorted((set(WHEN_ABSENT) | set(NOT_READ)) - set(upstream)) + sorted(set(WHEN_ABSENT) & set(NOT_READ))+ if stale:+ raise ValueError(f"WHEN_ABSENT or NOT_READ names {stale}, which the reference does not list with "+ f"{ACTION[0]}:{ACTION[1]}, or both name it")+ namespaces: dict[str, set[str]] = {}+ for operation, value in upstream.items():+ namespaces.setdefault(namespace_of(operation), set()).update(value["clients"])+ operations = {}+ unread = []+ for operation in upstream:+ try:+ operations[operation] = entry_for(operation, load_models(data, namespaces[namespace_of(operation)]))+ except ValueError as e:+ unread.append(str(e))+ if unread:+ raise ValueError("\n".join(unread))+ return {+ "_source": {+ "generator": "tools/aws/regen_iam_passed_network_connectors.py",+ "reference": provenance,+ "botocore": botocore,+ "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),+ "note": "make iam-passed-network-connectors-check re-derives every member from botocore; "+ "make iam-passed-network-connectors-verify checks every operation against AWS.",+ },+ "namespaces": {namespace: sorted(clients) for namespace, clients in sorted(namespaces.items())},+ "operations": operations,+ }+++def render(document: dict) -> str:+ """The document with one operation to a line and one connector to a line under it."""+ lines = ["{"]+ for key in ("_source", "namespaces"):+ lines.append(f' "{key}": {json.dumps(document[key])},')+ lines.append(' "operations": {')+ operations = list(document["operations"].items())+ for index, (operation, entry) in enumerate(operations):+ if "connectors" not in entry:+ lines.append(f" {json.dumps(operation)}: {json.dumps(entry)}{',' if index < len(operations) - 1 else ''}")+ continue+ lines.append(f' {json.dumps(operation)}: {{"connectors": [')+ connectors = entry["connectors"]+ for connector_index, connector in enumerate(connectors):+ lines.append(f" {json.dumps(connector)}{',' if connector_index < len(connectors) - 1 else ''}")+ lines.append(f" ]}}{',' if index < len(operations) - 1 else ''}")+ lines += [" }", "}"]+ return "\n".join(lines) + "\n"+++# --------------------------------------------------------------------------- #+# Gates+# --------------------------------------------------------------------------- #+def validate(document: dict) -> list[str]:+ """Problems that make the vendored file unusable, rather than out of date."""+ problems: list[str] = []+ namespaces = document.get("namespaces")+ operations = document.get("operations")+ if not isinstance(namespaces, dict) or not namespaces:+ return ["namespaces is missing or empty"]+ if not isinstance(operations, dict) or not operations:+ return ["operations is missing or empty"]+ if list(namespaces) != sorted(namespaces):+ problems.append("namespaces is not sorted")+ if list(operations) != sorted(operations):+ problems.append("operations is not sorted")+ for operation, entry in operations.items():+ if not OPERATION_RE.match(operation) or namespace_of(operation) not in namespaces:+ problems.append(f"{operation!r} is not an operation of a namespace the file reads")+ continue+ if isinstance(entry, dict) and set(entry) == {"notRead"}:+ if not isinstance(entry["notRead"], str) or not entry["notRead"]:+ problems.append(f"{operation} gives no reason for notRead")+ continue+ connectors = entry.get("connectors") if isinstance(entry, dict) else None+ if not isinstance(connectors, list) or not connectors or set(entry) != {"connectors"}:+ problems.append(f"{operation} is not exactly one of connectors and notRead")+ continue+ paths = [connector.get("member") if isinstance(connector, dict) else None for connector in connectors]+ if paths != sorted(path for path in paths if isinstance(path, str)):+ problems.append(f"{operation}: the connectors are not in sorted order")+ for connector in connectors:+ path = connector.get("member") if isinstance(connector, dict) else None+ if not isinstance(path, str) or not MEMBER_PATH_RE.match(path):+ problems.append(f"{operation} reads {connector!r}, which is no member path")+ continue+ if set(connector) - {"member", "whenAbsent"}:+ problems.append(f"{operation}: the connector at {path} carries an unknown field")+ absent = connector.get("whenAbsent")+ if absent is not None and (not isinstance(absent, str) or not MANAGED_CONNECTOR_RE.match(absent)):+ problems.append(f"{operation}: the connector at {path} falls back to {absent!r}, "+ f"which is no Lambda-managed connector")+ return problems+++def derive(document: dict, data: Path) -> list[str]:+ """Where the members the file gives differ from what botocore gives for the models it names."""+ problems: list[str] = []+ for operation, entry in document["operations"].items():+ models = load_models(data, set(document["namespaces"][namespace_of(operation)]))+ try:+ expected = entry_for(operation, models)+ except ValueError as e:+ problems.append(str(e))+ continue+ if expected != entry:+ problems.append(f"{operation}: the file has {json.dumps(entry)}, botocore gives {json.dumps(expected)}")+ return problems+++def verify_against(vendored: dict, upstream: dict[str, dict]) -> tuple[list[str], list[str]]:+ """What the file claims and AWS does not, and the operations AWS has added since."""+ untrue: list[str] = []+ for operation in vendored["operations"]:+ actual = upstream.get(operation)+ if actual is None:+ untrue.append(f"AWS no longer lists {ACTION[0]}:{ACTION[1]} for {operation}")+ elif not set(actual["clients"]) <= set(vendored["namespaces"][namespace_of(operation)]):+ untrue.append(f"AWS lists {operation} for {actual['clients']}, which the file does not read")+ added = sorted(operation for operation in upstream if operation not in vendored["operations"])+ return untrue, added+++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 match the pinned botocore")+ parser.add_argument("--verify", action="store_true", help="online: operations match AWS")+ parser.add_argument("--source-dir", type=Path, default=None,+ help="read saved <service>.json reference files instead of fetching them")+ parser.add_argument("--botocore-data", type=Path, default=None, help="botocore data directory")+ parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)+ args = parser.parse_args(argv)++ if args.check or args.verify:+ if not args.output.exists():+ print(f"error: {args.output} does not exist", file=sys.stderr)+ return 1+ document = json.loads(args.output.read_text(encoding="utf-8"))+ problems = validate(document)+ if not problems and args.check:+ data, _ = resolve_botocore_data(args.botocore_data)+ problems = derive(document, data)+ for problem in problems:+ print(f"error: {problem}", file=sys.stderr)+ if problems:+ return 1+ entries = len(document["operations"])+ if args.check:+ print(f"{_shown(args.output)} matches botocore ({entries} operations)")+ return 0+ try:+ documents, provenance = fetch_references(args.source_dir)+ upstream = passed_connector_operations(documents)+ except (OSError, ValueError) as e:+ print(f"error: could not read the Service Reference ({e})", file=sys.stderr)+ return 2+ untrue, added = verify_against(document, upstream)+ for claim in untrue:+ print(f"error: {claim}", file=sys.stderr)+ if untrue:+ print(f"error: {len(untrue)} vendored operation(s) do not hold upstream.", file=sys.stderr)+ return 1+ if added:+ print(f"{_shown(args.output)}: all {entries} operations verified. AWS has since added "+ f"{len(added)}, so the file is incomplete but not wrong (run without --verify to refresh): "+ f"{', '.join(added)}")+ else:+ print(f"{_shown(args.output)}: all {entries} operations verified against {provenance}, "+ f"nothing added upstream.")+ return 0++ data, botocore = resolve_botocore_data(args.botocore_data)+ try:+ documents, provenance = fetch_references(args.source_dir)+ document = build(documents, provenance, data, botocore)+ except (OSError, ValueError) as e:+ print(f"error: {e}", file=sys.stderr)+ return 2+ problems = validate(document)+ for problem in problems:+ print(f"error: {problem}", file=sys.stderr)+ if problems:+ return 1+ args.output.write_text(render(document), encoding="utf-8")+ print(f"wrote {_shown(args.output)} ({len(document['operations'])} operations, from {provenance})")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tools/aws/test_regen_iam_passed_network_connectors.py b/tools/aws/test_regen_iam_passed_network_connectors.pynew file mode 100644index 0000000000..8bf5c1f0e8--- /dev/null+++ b/tools/aws/test_regen_iam_passed_network_connectors.py@@ -0,0 +1,218 @@+"""Tests for regen_iam_passed_network_connectors.++Run with: pytest tools/aws -q (or: make iam-passed-network-connectors-test)+"""+from __future__ import annotations++import json++import pytest++import regen_iam_passed_network_connectors as r+++def reference(namespace: str, operations: dict[str, bool], clients: dict[str, list[str]] | None = None) -> dict:+ """A Service Reference document. Each operation maps to whether it lists lambda:PassNetworkConnector;+ `clients` gives an operation's SDK clients, the namespace by default."""+ entries = []+ for name, passes in operations.items():+ authorized = [{"Service": namespace, "Name": name}]+ if passes:+ authorized.append({"Service": "lambda", "Name": "PassNetworkConnector"})+ sdk = [{"Name": c, "Method": name, "Package": "Boto3"} for c in (clients or {}).get(name, [namespace])]+ entries.append({"Name": name, "AuthorizedActions": authorized, "SDK": sdk})+ return {"Name": namespace, "Operations": entries}+++def model(operations: dict[str, str], shapes: dict[str, dict], protocol: str = "rest-json") -> dict:+ """A botocore model whose operations take the input shape each names."""+ return {"metadata": {"protocol": protocol},+ "operations": {name: {"input": {"shape": shape}} for name, shape in operations.items()},+ "shapes": {"String": {"type": "string"}, **shapes}}+++def structure(**members) -> dict:+ return {"type": "structure", "members": {name: ({"shape": spec} if isinstance(spec, str) else spec)+ for name, spec in members.items()}}+++CONNECTORS = {"type": "list", "member": {"shape": "String"}}+++def corrections(monkeypatch):+ """No corrections at all, so a test sees the rule alone and sets what it needs."""+ monkeypatch.setattr(r, "WHEN_ABSENT", {})+ monkeypatch.setattr(r, "NOT_READ", {})+ return monkeypatch+++# --------------------------------------------------------------------------- #+# The Service Reference+# --------------------------------------------------------------------------- #+def test_only_operations_listing_the_action_are_kept_with_their_clients():+ found = r.passed_connector_operations([+ reference("lambda", {"RunMicrovm": True, "GetMicrovm": False}, {"RunMicrovm": ["lambda-microvms"]}),+ reference("appsync", {"CreateDataSource": True})])+ assert found == {"appsync:CreateDataSource": {"clients": ["appsync"]},+ "lambda:RunMicrovm": {"clients": ["lambda-microvms"]}}+++def test_pass_role_alone_does_not_count():+ document = reference("svc", {"CreateThing": False})+ document["Operations"][0]["AuthorizedActions"].append({"Service": "iam", "Name": "PassRole"})+ assert r.passed_connector_operations([document]) == {}+++def test_an_unusable_namespace_is_rejected():+ with pytest.raises(ValueError, match="not usable"):+ r.passed_connector_operations([{"Name": "Not A Namespace", "Operations": []}])+++# --------------------------------------------------------------------------- #+# botocore: the members that name a connector+# --------------------------------------------------------------------------- #+def test_a_member_is_a_connector_by_its_name_when_it_holds_a_string_or_a_list_of_them():+ m = model({"Op": "In"}, {+ "In": structure(egressNetworkConnectorArn="String", ingressNetworkConnectors="Connectors",+ NetworkConnector="String", networkConnectorType="String", ConnectorArn="String",+ connectorKind="Kind"),+ "Connectors": CONNECTORS,+ "Kind": {"type": "string", "enum": ["VPC_EGRESS"]},+ })+ assert r.connector_members(m, "Op") == ["NetworkConnector", "egressNetworkConnectorArn",+ "ingressNetworkConnectors[]"]+++def test_an_enum_names_no_connector():+ m = model({"Op": "In"}, {"In": structure(networkConnector="Kind"),+ "Kind": {"type": "string", "enum": ["VPC_EGRESS"]}})+ assert r.connector_members(m, "Op") == []+++def test_a_nested_member_is_written_as_its_path():+ m = model({"Op": "In"}, {"In": structure(revisionConfig="Revision"),+ "Revision": structure(serviceConfig="Service"),+ "Service": structure(egressNetworkConnectorArn="String")})+ assert r.connector_members(m, "Op") == ["revisionConfig.serviceConfig.egressNetworkConnectorArn"]+++def test_a_member_bound_to_the_uri_is_not_read():+ m = model({"Op": "In"}, {"In": structure(networkConnectorArn={"shape": "String", "location": "uri"})})+ assert r.connector_members(m, "Op") == []+++# --------------------------------------------------------------------------- #+# One operation's entry+# --------------------------------------------------------------------------- #+RUN = {"lambda-microvms": model({"RunMicrovm": "In"}, {+ "In": structure(ingressNetworkConnectors="Connectors", egressNetworkConnectors="Connectors"),+ "Connectors": CONNECTORS})}+++def test_the_members_are_sorted_with_the_connector_checked_when_one_is_absent(corrections):+ corrections.setattr(r, "WHEN_ABSENT", {"lambda:RunMicrovm": {+ "ingressNetworkConnectors[]": "aws-network-connector:HTTP_INGRESS"}})+ assert r.entry_for("lambda:RunMicrovm", RUN) == {"connectors": [+ {"member": "egressNetworkConnectors[]"},+ {"member": "ingressNetworkConnectors[]", "whenAbsent": "aws-network-connector:HTTP_INGRESS"}]}+++def test_a_fallback_for_a_member_the_request_does_not_have_fails(corrections):+ corrections.setattr(r, "WHEN_ABSENT", {"lambda:RunMicrovm": {"missing[]": "aws-network-connector:X"}})+ with pytest.raises(ValueError, match="does not have"):+ r.entry_for("lambda:RunMicrovm", RUN)+++def test_an_operation_naming_no_connector_must_say_why(corrections):+ empty = {"appsync": model({"CreateDataSource": "In"}, {"In": structure(name="String")})}+ with pytest.raises(ValueError, match="NOT_READ"):+ r.entry_for("appsync:CreateDataSource", empty)+ corrections.setattr(r, "NOT_READ", {"appsync:CreateDataSource": "no member names a connector"})+ assert r.entry_for("appsync:CreateDataSource", empty) == {"notRead": "no member names a connector"}+++def test_an_unread_operation_whose_request_gains_a_connector_fails(corrections):+ corrections.setattr(r, "NOT_READ", {"lambda:RunMicrovm": "no member names a connector"})+ with pytest.raises(ValueError, match="NOT_READ says"):+ r.entry_for("lambda:RunMicrovm", RUN)+++# --------------------------------------------------------------------------- #+# The whole document+# --------------------------------------------------------------------------- #+def write_models(root, models: dict[str, dict]):+ for name, value in models.items():+ directory = root / name / "2020-01-01"+ directory.mkdir(parents=True)+ (directory / "service-2.json").write_text(json.dumps(value), encoding="utf-8")+++def test_a_built_document_validates_and_matches_botocore(corrections, tmp_path):+ write_models(tmp_path, RUN)+ document = r.build([reference("lambda", {"RunMicrovm": True}, {"RunMicrovm": ["lambda-microvms"]})],+ "test", tmp_path, "botocore test")+ assert r.validate(document) == []+ assert r.derive(document, tmp_path) == []+ assert document["namespaces"] == {"lambda": ["lambda-microvms"]}+ assert json.loads(r.render(document)) == document+++def test_a_hand_edited_member_does_not_match_botocore(corrections, tmp_path):+ write_models(tmp_path, RUN)+ document = r.build([reference("lambda", {"RunMicrovm": True}, {"RunMicrovm": ["lambda-microvms"]})],+ "test", tmp_path, "botocore test")+ document["operations"]["lambda:RunMicrovm"]["connectors"].append({"member": "other"})+ assert r.validate(document) == []+ assert len(r.derive(document, tmp_path)) == 1+++def test_a_correction_naming_an_operation_the_reference_does_not_list_fails(corrections, tmp_path):+ write_models(tmp_path, RUN)+ corrections.setattr(r, "NOT_READ", {"lambda:Gone": "no member names a connector"})+ with pytest.raises(ValueError, match="lambda:Gone"):+ r.build([reference("lambda", {"RunMicrovm": True}, {"RunMicrovm": ["lambda-microvms"]})],+ "test", tmp_path, "botocore test")+++def good_document() -> dict:+ return {"namespaces": {"lambda": ["lambda-web"]}, "operations": {+ "lambda:A": {"connectors": [{"member": "egress[]", "whenAbsent": "aws-network-connector:INTERNET_EGRESS"},+ {"member": "serviceConfig.egressNetworkConnectorArn"}]},+ "lambda:B": {"notRead": "no member names a connector"}}}+++def test_a_well_formed_document_validates():+ assert r.validate(good_document()) == []++[email protected]("change, problem", [+ (lambda d: d["operations"]["lambda:A"].update(notRead="x"), "exactly one"),+ (lambda d: d["operations"]["lambda:A"]["connectors"][1].update(member="a..b"), "no member path"),+ (lambda d: d["operations"]["lambda:A"]["connectors"].reverse(), "sorted order"),+ (lambda d: d["operations"]["lambda:A"]["connectors"][0].update(whenAbsent="my-connector"), "Lambda-managed"),+ (lambda d: d["operations"]["lambda:A"]["connectors"][0].update(passedTo="lambda"), "unknown field"),+ (lambda d: d["operations"].update({"other:C": {"notRead": "x"}}), "namespace the file reads"),+])+def test_a_malformed_document_is_rejected(change, problem):+ document = good_document()+ change(document)+ assert any(problem in p for p in r.validate(document)), r.validate(document)+++def test_verify_fails_on_a_claim_aws_does_not_make_and_reports_an_added_operation():+ upstream = {"lambda:A": {"clients": ["lambda-web", "lambda-microvms"]},+ "lambda:D": {"clients": ["lambda-web"]}}+ untrue, added = r.verify_against(good_document(), upstream)+ assert untrue == ["AWS lists lambda:A for ['lambda-web', 'lambda-microvms'], which the file does not read",+ "AWS no longer lists lambda:PassNetworkConnector for lambda:B"]+ assert added == ["lambda:D"]+++def test_the_vendored_file_is_well_formed():+ document = json.loads(r.OUTPUT.read_text(encoding="utf-8"))+ assert r.validate(document) == []+ assert document["operations"]["lambda:CreateWebFunctionRevision"]["connectors"] == [+ {"member": "serviceConfig.egressNetworkConnectorArn"}]+ assert [c["member"] for c in document["operations"]["lambda:RunMicrovm"]["connectors"]] == [+ "egressNetworkConnectors[]", "ingressNetworkConnectors[]"]