diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index a377421218..7b985b7ba3 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -118,6 +118,9 @@ on: - 'tools/aws/fetch_secretsmanager_required_permissions.py' - 'tools/aws/sources/secretsmanager-required-permissions.json' - 'tools/aws/test_fetch_secretsmanager_required_permissions.py' + - 'tools/aws/fetch_lambda_response_permissions.py' + - 'tools/aws/sources/lambda-response-permissions.json' + - 'tools/aws/test_fetch_lambda_response_permissions.py' - 'tools/aws/fetch_lambda_layer_permissions.py' - 'tools/aws/sources/lambda-layer-permissions.json' - 'tools/aws/test_fetch_lambda_layer_permissions.py' diff --git a/Makefile b/Makefile index 2746c4d81e..89101c8c0a 100644 --- a/Makefile +++ b/Makefile @@ -625,7 +625,9 @@ IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.js tools/aws/test_fetch_sts_source_identity.py tools/aws/sources/sts-session-tags.json \ tools/aws/fetch_sts_session_tags.py tools/aws/test_fetch_sts_session_tags.py \ tools/aws/sources/secretsmanager-required-permissions.json tools/aws/fetch_secretsmanager_required_permissions.py \ - tools/aws/test_fetch_secretsmanager_required_permissions.py + tools/aws/test_fetch_secretsmanager_required_permissions.py \ + tools/aws/sources/lambda-response-permissions.json tools/aws/fetch_lambda_response_permissions.py \ + tools/aws/test_fetch_lambda_response_permissions.py IAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/test_regen_iam_passed_roles.py tools/aws/sources/eks-roles.json tools/aws/fetch_eks_roles.py \ tools/aws/test_fetch_eks_roles.py tools/aws/sources/emr-roles.json tools/aws/fetch_emr_roles.py \ diff --git a/docs/services/iam.md b/docs/services/iam.md index 1d4c0ee2c1..565000cc77 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2977,7 +2977,12 @@ you must also have secretsmanager:ListSecrets") when it carries the member the w always needs ("secretsmanager:ValidateResourcePolicy and secretsmanager:PutResourcePolicy") on what it names; one it needs for each thing ("you must have secretsmanager:GetSecretValue for each secret") is an action the authorized-actions table gives the operation on each entry of the type the words name (`perEntry`), which its handler checks on each -secret it reads, answering a denied one in the response's `Errors`. A Lambda +secret it reads, answering a denied one in the response's `Errors`. A response member an operation's API reference +page says is returned only with a permission ("Lambda returns tag data only if you have explicit allow permissions +for lambda:ListTags"), which its own script vendors (`tools/aws/fetch_lambda_response_permissions.py`), is in the +authorized-actions table's `returnedOnlyIf`, where botocore's response has a member of that name and the Service +Reference lists the action among the operation's; the handler leaves it out for a caller not allowed the action on +what the operation reads, as `GetFunction` does with `Tags`. A Lambda operation the Service Reference lists as authorized by an action is also checked as it on the resource the Lambda developer guide asks permission to call that action's API on, which its own script vendors (`tools/aws/fetch_lambda_layer_permissions.py`): "Make sure that you have permission to call the GetLayerVersion API diff --git a/docs/services/lambda.md b/docs/services/lambda.md index fa425305a8..7c65c69d48 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -652,6 +652,12 @@ that layer. A request giving no `Layers` is not checked as it. Another account's checked on its own ARN alone, against its owner's policy, never as a same-named layer of the caller's, as Lambda never substitutes one. +**GetFunction's tags under IAM enforcement:** `GetFunction` returns `Tags` only to a caller allowed +`lambda:ListTags` on the function, as the API reference says ("Lambda returns tag data only if you +have explicit allow permissions for lambda:ListTags"); a caller allowed `GetFunction` alone, or +denied `lambda:ListTags`, reads the function without them. `TagsError` is not set, as no recording +of AWS's error for that case gives its code and message. + ## Provisioned concurrency Published versions with `SnapStart.ApplyOn=PublishedVersions` reject provisioned concurrency diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 7ac6a2b5ea..f9d2660387 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -1885,12 +1885,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter { * {@link #authorizeAdditionalResource} hands it the same caller this filter evaluated, whichever * way the request was signed. * - * @return the {@code Authorization} header, else a {@code Credential=...} string built from - * {@code X-Amz-Credential}, else {@code null} + * @return the {@code Authorization} header when it is not blank, else a {@code Credential=...} string built + * from {@code X-Amz-Credential}, else {@code null} */ public static String requestAuthorization(String authorizationHeader, MultivaluedMap queryParameters) { - if (authorizationHeader != null) { + // A blank header is no credential, as filter() reads it, so a handler checks the caller the filter evaluated. + if (authorizationHeader != null && !authorizationHeader.isBlank()) { return authorizationHeader; } String credential = queryParameters == null ? null : queryParameters.getFirst("X-Amz-Credential"); diff --git a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java index 7fe4f0285b..286280df0f 100644 --- a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java +++ b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java @@ -83,7 +83,16 @@ public final class IamAuthorizedActions { */ record Table(Map actions, Set withoutResourceTypes, Set byMethod, Map byModel, Map versioned, Map spellings, - Map> companions, Map> perEntry) { + Map> companions, Map> perEntry, + Map> returnedOnlyIf) { + } + + /** + * A member an operation's response carries only when its caller is allowed {@code action} on what the operation + * reads, which its handler leaves out otherwise: "Lambda returns tag data only if you have explicit allow + * permissions for lambda:ListTags" (GetFunction's {@code Tags}). + */ + public record ReturnedOnlyIf(String member, String action) { } /** @@ -219,6 +228,14 @@ public final class IamAuthorizedActions { return Holder.TABLE.perEntry().getOrDefault(operation, List.of()); } + /** + * The members {@code operation}, as {@code :}, returns only to a caller allowed an action + * beside its own; none for an operation the file gives none. + */ + public static List returnedOnlyIf(String operation) { + return Holder.TABLE.returnedOnlyIf().getOrDefault(operation, List.of()); + } + /** * The companion of {@code operation} reading the session tags an identity provider passes: the SAML attribute or * token claim carrying them and the action a trust policy has to allow for them. Empty for an operation the file @@ -257,7 +274,27 @@ public final class IamAuthorizedActions { return new Table(Map.copyOf(actions), withoutResourceTypes(document.path("actionsWithoutResourceTypes")), byMethod(document.path("authorizedByMethod")), byModel(document.path("authorizedByModel")), versioned(document.path("versioned")), spellings(document.path("spellings")), - companions(document.path("companions")), perEntry(document.path("perEntry"))); + companions(document.path("companions")), perEntry(document.path("perEntry")), + returnedOnlyIf(document.path("returnedOnlyIf"))); + } + + /** Each namespace's operations' members returned only with an action, keyed {@code :}. */ + private static Map> returnedOnlyIf(JsonNode namespaces) { + Map> found = new LinkedHashMap<>(); + namespaces.properties().forEach(namespace -> namespace.getValue().properties().forEach(operation -> { + List gated = new ArrayList<>(); + for (JsonNode gate : operation.getValue()) { + String member = gate.path("member").asText(""); + if (member.isEmpty()) { + throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + ":" + + operation.getKey() + " a response member returned only with an action naming none"); + } + gated.add(new ReturnedOnlyIf(member, actionOf(namespace.getKey(), operation.getKey(), + gate.path("action")))); + } + found.put(namespace.getKey() + ":" + operation.getKey(), List.copyOf(gated)); + })); + return Map.copyOf(found); } /** Each namespace's operations' actions on each entry they read, keyed {@code :}. */ diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaController.java b/src/main/java/io/floci/aws/services/lambda/LambdaController.java index 2fc8bbed62..c74099ec04 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaController.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaController.java @@ -8,8 +8,10 @@ import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.EpochSeconds; +import io.floci.aws.core.common.IamEnforcementFilter; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.iam.IamAuthorizedActions; import io.floci.aws.services.lambda.model.EventSourceMapping; import io.floci.aws.services.lambda.model.InvocationType; import io.floci.aws.services.lambda.model.InvokeResult; @@ -59,14 +61,16 @@ public class LambdaController { private final RegionResolver regionResolver; private final ObjectMapper objectMapper; private final PreSignedUrlGenerator presignGenerator; + private final IamEnforcementFilter iamEnforcementFilter; @Inject public LambdaController(LambdaService lambdaService, RegionResolver regionResolver, ObjectMapper objectMapper, - PreSignedUrlGenerator presignGenerator) { + PreSignedUrlGenerator presignGenerator, IamEnforcementFilter iamEnforcementFilter) { this.lambdaService = lambdaService; this.regionResolver = regionResolver; this.objectMapper = objectMapper; this.presignGenerator = presignGenerator; + this.iamEnforcementFilter = iamEnforcementFilter; } // ──────────────────────────── CreateFunction ──────────────────────────── @@ -139,9 +143,39 @@ public class LambdaController { root.putObject("Concurrency").put("ReservedConcurrentExecutions", reservedConcurrency); } + withoutUnallowedMembers(root, "lambda:GetFunction", fn.getFunctionArn(), + IamEnforcementFilter.requestAuthorization(headers.getHeaderString(HttpHeaders.AUTHORIZATION), + uriInfo.getQueryParameters())); return Response.ok(root).build(); } + /** + * Leaves out of {@code response} each member the authorized-actions table says {@code operation} returns only to + * a caller allowed an action ({@link IamAuthorizedActions#returnedOnlyIf}), where the caller is not allowed it on + * {@code resource}: "Lambda returns tag data only if you have explicit allow permissions for lambda:ListTags", so a + * GetFunction by a caller not allowed {@code lambda:ListTags} on the function carries no {@code Tags}. Nothing is + * left out with IAM enforcement off or for a request carrying no caller credential. + */ + private void withoutUnallowedMembers(ObjectNode response, String operation, String resource, + String authorization) { + if (iamEnforcementFilter == null) { + return; + } + for (IamAuthorizedActions.ReturnedOnlyIf gate : IamAuthorizedActions.returnedOnlyIf(operation)) { + if (!response.has(gate.member())) { + continue; + } + try { + iamEnforcementFilter.authorizeEntryResource(authorization, gate.action(), resource); + } catch (AwsException e) { + if (!"AccessDenied".equals(e.getErrorCode())) { + throw e; + } + response.remove(gate.member()); + } + } + } + // ──────────────────────────── ListFunctions ──────────────────────────── @GET diff --git a/src/main/resources/aws/iam-authorized-actions.json b/src/main/resources/aws/iam-authorized-actions.json index 071be5fe9d..9bf3a43ab0 100644 --- a/src/main/resources/aws/iam-authorized-actions.json +++ b/src/main/resources/aws/iam-authorized-actions.json @@ -1912,5 +1912,15 @@ } ] } + }, + "returnedOnlyIf": { + "lambda": { + "GetFunction": [ + { + "member": "Tags", + "action": "lambda:ListTags" + } + ] + } } } diff --git a/src/test/java/io/floci/aws/core/common/IamEnforcementFilterRequestAuthorizationTest.java b/src/test/java/io/floci/aws/core/common/IamEnforcementFilterRequestAuthorizationTest.java new file mode 100644 index 0000000000..98454b91ff --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/IamEnforcementFilterRequestAuthorizationTest.java @@ -0,0 +1,46 @@ +package io.floci.aws.core.common; + +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * The credential a handler authorizes a second resource with is the one {@link IamEnforcementFilter} evaluated: the + * {@code Authorization} header, else the presigned {@code X-Amz-Credential}, a blank header being no credential as the + * filter reads it, so a request carrying one cannot pass a handler's check as unsigned. + */ +class IamEnforcementFilterRequestAuthorizationTest { + + private static final String CREDENTIAL = "query/20261130/us-east-1/lambda/aws4_request"; + + @Test + void aHeaderIsTheCredential() { + String header = "AWS4-HMAC-SHA256 Credential=header/20261130/us-east-1/lambda/aws4_request"; + assertEquals(header, IamEnforcementFilter.requestAuthorization(header, presigned())); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {" ", "\t"}) + void anAbsentOrBlankHeaderFallsBackToThePresignedCredential(String header) { + assertEquals("AWS4-HMAC-SHA256 Credential=" + CREDENTIAL, + IamEnforcementFilter.requestAuthorization(header, presigned())); + } + + @Test + void neitherIsNoCredential() { + assertNull(IamEnforcementFilter.requestAuthorization(" ", new MultivaluedHashMap<>())); + } + + private static MultivaluedMap presigned() { + MultivaluedMap query = new MultivaluedHashMap<>(); + query.putSingle("X-Amz-Credential", CREDENTIAL); + return query; + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/EventSourceMappingSerializationTest.java b/src/test/java/io/floci/aws/services/lambda/EventSourceMappingSerializationTest.java index 04c0859181..345de0a659 100644 --- a/src/test/java/io/floci/aws/services/lambda/EventSourceMappingSerializationTest.java +++ b/src/test/java/io/floci/aws/services/lambda/EventSourceMappingSerializationTest.java @@ -22,7 +22,7 @@ class EventSourceMappingSerializationTest { @BeforeEach void setUp() { objectMapper = new ObjectMapper(); - controller = new LambdaController(null, null, objectMapper, null); + controller = new LambdaController(null, null, objectMapper, null, null); } @Test diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaGetFunctionTagsIamIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaGetFunctionTagsIamIntegrationTest.java new file mode 100644 index 0000000000..585da8d2c7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/LambdaGetFunctionTagsIamIntegrationTest.java @@ -0,0 +1,84 @@ +package io.floci.aws.services.lambda; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.LambdaCodeFixtures; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.GetFunctionResponse; + +import java.net.URI; +import java.util.Map; +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * GetFunction carries the function's tags only to a caller allowed {@code lambda:ListTags} on it, as the API reference + * says of its Tags: "Lambda returns tag data only if you have explicit allow permissions for lambda:ListTags". A + * caller allowed GetFunction alone, or denied ListTags, reads the function without them. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class LambdaGetFunctionTagsIamIntegrationTest { + + private static final String ACCOUNT = "741681410004"; + private static final Region REGION = Region.US_EAST_1; + + @TestHTTPResource("/") + URI endpoint; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aFunctionsTagsAreReturnedOnlyToACallerAllowedListTags() { + String name = "tagged-" + UUID.randomUUID().toString().substring(0, 8); + String function = "arn:aws:lambda:" + REGION.id() + ":" + ACCOUNT + ":function:" + name; + try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, REGION, endpoint)) { + owner.createFunction(r -> r.functionName(name).runtime("nodejs22.x").handler("index.handler") + .role(AwsArnUtils.Arn.global("aws", "iam", ACCOUNT, "role/tags").toString()) + .code(code -> code.zipFile(SdkBytes.fromByteArray(LambdaCodeFixtures.nodeJsZip( + "exports.handler = async () => 'ok';")))) + .tags(Map.of("team", "blue"))); + cleanup.register(() -> owner.deleteFunction(r -> r.functionName(name))); + assertEquals(Map.of("team", "blue"), owner.getFunction(r -> r.functionName(name)).tags()); + } + String readFunction = """ + {"Effect":"Allow","Action":"lambda:GetFunction","Resource":"*"}"""; + try (LambdaClient reading = caller(readFunction); + LambdaClient listing = caller(readFunction + """ + ,{"Effect":"Allow","Action":"lambda:ListTags","Resource":"%s"}""".formatted(function)); + LambdaClient denied = caller(readFunction + """ + ,{"Effect":"Allow","Action":"lambda:ListTags","Resource":"*"}, + {"Effect":"Deny","Action":"lambda:ListTags","Resource":"%s"}""".formatted(function))) { + GetFunctionResponse withoutListTags = reading.getFunction(r -> r.functionName(name)); + assertEquals(name, withoutListTags.configuration().functionName()); + assertFalse(withoutListTags.hasTags(), withoutListTags.tags().toString()); + assertEquals(Map.of("team", "blue"), listing.getFunction(r -> r.functionName(name)).tags()); + assertFalse(denied.getFunction(r -> r.functionName(name)).hasTags()); + } + } + + private LambdaClient caller(String statements) { + String user = "tags-" + UUID.randomUUID().toString().substring(0, 8); + String authorization = auth(ACCOUNT, REGION.id(), "iam"); + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, user); + EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, user, "read", + "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}"); + return AwsTestClients.create(LambdaClient.builder(), credentials.accessKeyId(), credentials.secretAccessKey(), + REGION, endpoint); + } +} diff --git a/tools/aws/fetch_lambda_response_permissions.py b/tools/aws/fetch_lambda_response_permissions.py new file mode 100644 index 0000000000..5fb339d1e0 --- /dev/null +++ b/tools/aws/fetch_lambda_response_permissions.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Vendor what the AWS Lambda API reference says a response returns only with a permission into +tools/aws/sources/lambda-response-permissions.json, a source of the IAM tables. + +The Service Reference lists lambda:ListTags among the actions GetFunction is authorized by, without saying what for, +and botocore's model is not a source the generators read sentences from. The operation's page in the API reference +says it of one of its response elements: + + Tags + The function's tags. Lambda returns tag data only if you have explicit allow permissions for lambda:ListTags. + + https://docs.aws.amazon.com/lambda/latest/api/API_GetFunction.html + +This script reads the Service Reference for the operations it lists as authorized by an action beside their own, +keeps those the API reference's operations page lists, and copies each response element's sentence saying the +element is returned only with an action's permission, with the element and the action. A sentence saying so in any +other wording is refused, so a reworded page fails rather than dropping a check. Nothing in the output is written by +hand, and the generators read it against the Service Reference's authorized actions and botocore's responses. + +Run from anywhere in the repo: + python3 tools/aws/fetch_lambda_response_permissions.py # rewrite the vendored file + python3 tools/aws/fetch_lambda_response_permissions.py --verify # online: the file still says it +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +REFERENCE = "https://servicereference.us-east-1.amazonaws.com/v1/lambda/lambda.json" +OPERATIONS_PAGE = "https://docs.aws.amazon.com/lambda/latest/api/API_Operations.html" +API_PAGE = "https://docs.aws.amazon.com/lambda/latest/api/API_{operation}.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/lambda-response-permissions.json" +NAMESPACE = "lambda" + +ACTION = rf"{NAMESPACE}:[A-Za-z]+" +# A sentence about a permission an element needs, which names an action of the namespace and a permission, and the +# wording the reference gives it in. +PERMISSION_RE = re.compile(rf"\bpermissions?\b.*\b{ACTION}|\b{ACTION}.*\bpermissions?\b|\bonly (?:if|when) you have\b") +RETURNED_RE = re.compile(rf"^Lambda returns (?P[a-z]+(?: [a-z]+)*) only if you have explicit allow " + rf"permissions for (?P{ACTION})\.$") +SENTENCE_RE = re.compile(r"(?<=\.)\s+(?=[A-Z])") +# An operation's page's response elements, up to the next section; and what one with none says instead. +SECTION_RE = '

.*?\s*' + r'
(?P.*?)
', re.S) + + +def text(fragment: str) -> str: + """A fragment of a page as text, spaces collapsed, and none left before a mark an inline tag ends ahead of.""" + collapsed = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() + return re.sub(r" (?=[.,;:)])", "", re.sub(r"\( ", "(", collapsed)) + + +def body(page: str) -> str: + """The page's own content, its navigation left out.""" + match = re.search(r'
(?P.*?)(?:
set[str]: + """The operations the API reference's operations page links to.""" + found = set(re.findall(r'href="\./API_([A-Za-z]+)\.html"', body(index))) + if not found: + raise ValueError(f"{OPERATIONS_PAGE} links to no operation: its layout changed") + return found + + +def operations(reference: dict, index: str) -> list[str]: + """The operations the Service Reference lists as authorized by an action of the namespace beside their own and + the API reference documents.""" + documented = listed(index) + found = [] + for operation in reference.get("Operations", []): + actions = {f"{action['Service']}:{action['Name']}" for action in operation.get("AuthorizedActions") or []} + if operation["Name"] in documented and any(action.startswith(NAMESPACE + ":") + and action != f"{NAMESPACE}:{operation['Name']}" + for action in actions): + found.append(operation["Name"]) + return sorted(found) + + +def response_section(operation: str, page: str) -> str: + """The operation's page's response elements section, refused when the page has none or it lists no element and + does not say the response is empty.""" + content = body(page) + start = content.find(SECTION_RE.format(operation=operation)) + if start < 0: + raise ValueError(f"{API_PAGE.format(operation=operation)} has no response elements section: its layout " + f"changed") + end = content.find(" list[dict]: + """Each response element of the operation's page returned only with a permission, with its sentence and action. A + sentence naming a permission and an action of the namespace in any other wording is refused, as is a page whose + response elements cannot be read, so a reworded or relaid page fails rather than dropping a check.""" + found = [] + for element in ELEMENT_RE.finditer(response_section(operation, page)): + if element.group("operation") != operation: + raise ValueError(f"{API_PAGE.format(operation=operation)} lists the response element " + f"{element.group('element')} of {element.group('operation')}: its layout changed") + for sentence in SENTENCE_RE.split(text(element.group("description"))): + if not PERMISSION_RE.search(sentence): + continue + matched = RETURNED_RE.match(sentence) + if matched is None: + raise ValueError(f"{API_PAGE.format(operation=operation)} says of {element.group('element')} " + f"'{sentence}', which returns it only with a permission in no wording it used: its " + f"wording changed") + found.append({"operation": operation, "element": element.group("element"), "sentence": sentence, + "action": matched.group("action")}) + return found + + +def build(reference: dict, index: str, pages: dict[str, str]) -> dict: + named = operations(reference, index) + return { + "_source": { + "pages": [REFERENCE, OPERATIONS_PAGE, *(API_PAGE.format(operation=operation) for operation in named)], + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "Each response element the API reference page of an operation the Service Reference lists as " + "authorized by an action beside its own says is returned only with a permission, with the " + "sentence that says so and the action.", + }, + "returnedOnlyIf": [found for operation in named for found in read_returned(operation, pages[operation])], + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def fetch_all(fetch=fetch_url) -> tuple[dict, str, dict[str, str]]: + """The Service Reference, the operations page and the page of each operation `operations` keeps.""" + reference = json.loads(fetch(REFERENCE)) + index = fetch(OPERATIONS_PAGE) + return reference, index, {operation: fetch(API_PAGE.format(operation=operation)) + for operation in operations(reference, index)} + + +def stale(vendored: dict, reference: dict, index: str, pages: dict[str, str]) -> bool: + """Whether the reference and the pages now give something other than the vendored file, its date aside.""" + built = build(reference, index, pages) + return any(vendored.get(key) != built[key] for key in built if key != "_source") + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages") + args = parser.parse_args(argv) + try: + reference, index, pages = fetch_all(fetch) + except OSError as e: + print(f"error: could not read the AWS Lambda API reference ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, reference, index, pages): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the AWS Lambda API reference does: " + f"run tools/aws/fetch_lambda_response_permissions.py and then make iam-authorized-actions-sync", + file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AWS Lambda API reference") + return 0 + built = build(reference, index, pages) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['returnedOnlyIf'])} elements)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_iam_authorized_actions.py b/tools/aws/regen_iam_authorized_actions.py index 4769061d0a..a896a0fbe1 100644 --- a/tools/aws/regen_iam_authorized_actions.py +++ b/tools/aws/regen_iam_authorized_actions.py @@ -156,6 +156,9 @@ SESSION_TAGS = REPO_ROOT / "tools/aws/sources/sts-session-tags.json" # The AWS Secrets Manager API reference's required permissions of each operation the Service Reference lists as # authorized by another of its actions, as tools/aws/fetch_secretsmanager_required_permissions.py copies them. REQUIRED_PERMISSIONS = REPO_ROOT / "tools/aws/sources/secretsmanager-required-permissions.json" +# The response elements the AWS Lambda API reference says an operation returns only with a permission, as +# tools/aws/fetch_lambda_response_permissions.py copies them. +RESPONSE_PERMISSIONS = REPO_ROOT / "tools/aws/sources/lambda-response-permissions.json" CARRIED_KEY_RE = re.compile(r"^aws:[A-Za-z]+(?:/\$\{TagKey\})?$") LEVEL_RE = re.compile(r"^([A-Z][A-Za-z0-9]+)(?: \((Bucket|Account)-level\))?$") SPECIFYING_RE = re.compile(r"\bspecifying (\w+) in the request") @@ -593,6 +596,51 @@ def load_required_permissions(source: Path = REQUIRED_PERMISSIONS) -> dict | Non return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None +def load_response_permissions(source: Path = RESPONSE_PERMISSIONS) -> dict | None: + """The vendored API reference's response elements returned only with a permission, none when the file is + missing.""" + return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None + + +def response_members(namespace: str) -> dict[str, set[str]]: + """The members of each operation's response in botocore's model of the namespace.""" + data, _ = resolve_botocore_data(None) + model = load_model(latest_model_dir(data, namespace)) + return {name: set(model["shapes"][operation["output"]["shape"]].get("members", {})) + for name, operation in model["operations"].items() if "output" in operation} + + +def returned_only_if(documents: list[dict], source: dict | None, + responses: dict[str, dict[str, set[str]]] | None = None) -> dict[str, dict[str, list[dict]]]: + """The members an operation's response carries only when its caller is allowed an action beside its own, from an + API reference's response elements (`source`, `load_response_permissions`): "Lambda returns tag data only if you + have explicit allow permissions for lambda:ListTags" (GetFunction's Tags). Each is the element, where botocore's + response of the operation has a member of that name (`responses` by namespace, `response_members` unless given), + and the action, where the Service Reference lists it among the operation's actions; the operation's handler + leaves the member out of a response to a caller not allowed the action on what the operation reads.""" + if not source: + return {} + found: dict[str, dict[str, list[dict]]] = {} + for document in documents: + namespace = document.get("Name") + operations = {operation.get("Name"): operation for operation in document.get("Operations") or []} + entries = [entry for entry in source["returnedOnlyIf"] if entry["action"].split(":", 1)[0] == namespace] + if not entries: + continue + members = (responses or {}).get(namespace) + if members is None: + members = response_members(namespace) + for entry in entries: + operation = operations.get(entry["operation"]) + authorized = set() if operation is None else { + f"{service}:{name}" for service, name in _authorized_actions(namespace, operation)} + if entry["action"] not in authorized or entry["element"] not in members.get(entry["operation"], set()): + continue + found.setdefault(namespace, {}).setdefault(entry["operation"], []).append( + {"member": entry["element"], "action": entry["action"]}) + return {namespace: dict(sorted(operations.items())) for namespace, operations in sorted(found.items())} + + def request_members(namespace: str) -> dict[str, set[str]]: """The members of each operation's request in botocore's model of the namespace.""" data, _ = resolve_botocore_data(None) @@ -805,6 +853,7 @@ def build(documents: list[dict], provenance: str, routed: list[str], **vendored_sections(documents, page, models, query, renamed), "companions": companions(documents, source_identity, requests, session_tags, load_required_permissions()), "perEntry": per_entry_actions(documents, load_required_permissions()), + "returnedOnlyIf": returned_only_if(documents, load_response_permissions()), } @@ -890,6 +939,13 @@ def _section_problems(document: dict) -> list[str]: or not action_of(namespace, each.get("action")) or not NAME_RE.match(str(each.get("type"))): problems.append(f"perEntry {namespace}:{operation} is not an action of {namespace} and a " f"resource type") + for namespace, operations in (document.get("returnedOnlyIf") or {}).items(): + for operation, gated in (operations.items() if isinstance(operations, dict) else []): + for gate in (gated if isinstance(gated, list) else [None]): + if not isinstance(gate, dict) or set(gate) != {"member", "action"} \ + or not action_of(namespace, gate.get("action")) or not NAME_RE.match(str(gate.get("member"))): + problems.append(f"returnedOnlyIf {namespace}:{operation} is not a response member and an " + f"action of {namespace}") return problems @@ -1092,6 +1148,14 @@ def main(argv: list[str] | None = None) -> int: f"{fetch_sts_session_tags.PAGE} does (run tools/aws/fetch_sts_session_tags.py)", file=sys.stderr) return 1 + response_permissions = load_response_permissions() + if args.source_dir is None and response_permissions is not None: + import fetch_lambda_response_permissions + if fetch_lambda_response_permissions.stale(response_permissions, + *fetch_lambda_response_permissions.fetch_all()): + print(f"error: {RESPONSE_PERMISSIONS.relative_to(REPO_ROOT)} no longer says what the AWS Lambda " + f"API reference does (run tools/aws/fetch_lambda_response_permissions.py)", file=sys.stderr) + return 1 if args.source_dir is None and source_identity is not None: import fetch_sts_source_identity if fetch_sts_source_identity.stale(source_identity, fetch_sts_source_identity.fetch_url( @@ -1116,7 +1180,8 @@ def main(argv: list[str] | None = None) -> int: sections = {**vendored_sections(documents, page, models, query, upstream), "companions": companions(documents, source_identity, None, session_tags, load_required_permissions()), - "perEntry": per_entry_actions(documents, load_required_permissions())} + "perEntry": per_entry_actions(documents, load_required_permissions()), + "returnedOnlyIf": returned_only_if(documents, load_response_permissions())} for section, value in sections.items(): if vendored_document.get(section, {}) != value: untrue.append(f"{section} differs from what AWS gives: expected {json.dumps(value)}") diff --git a/tools/aws/sources/lambda-response-permissions.json b/tools/aws/sources/lambda-response-permissions.json new file mode 100644 index 0000000000..00815cb82e --- /dev/null +++ b/tools/aws/sources/lambda-response-permissions.json @@ -0,0 +1,31 @@ +{ + "_source": { + "pages": [ + "https://servicereference.us-east-1.amazonaws.com/v1/lambda/lambda.json", + "https://docs.aws.amazon.com/lambda/latest/api/API_Operations.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_CreateCapacityProvider.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_CreateCodeSigningConfig.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_CreateEventSourceMapping.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_CreateFunction.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_DeleteResourcePolicy.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_GetFunction.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_GetLayerVersionByArn.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_GetResourcePolicy.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_Invoke.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_InvokeWithResponseStream.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_PutResourcePolicy.html", + "https://docs.aws.amazon.com/lambda/latest/api/API_UpdateFunctionConfiguration.html" + ], + "fetcher": "tools/aws/fetch_lambda_response_permissions.py", + "retrieved": "2026-11-29", + "note": "Each response element the API reference page of an operation the Service Reference lists as authorized by an action beside its own says is returned only with a permission, with the sentence that says so and the action." + }, + "returnedOnlyIf": [ + { + "operation": "GetFunction", + "element": "Tags", + "sentence": "Lambda returns tag data only if you have explicit allow permissions for lambda:ListTags.", + "action": "lambda:ListTags" + } + ] +} diff --git a/tools/aws/test_fetch_lambda_response_permissions.py b/tools/aws/test_fetch_lambda_response_permissions.py new file mode 100644 index 0000000000..a5878692bb --- /dev/null +++ b/tools/aws/test_fetch_lambda_response_permissions.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Tests for fetch_lambda_response_permissions.py, on the Service Reference and pages in the AWS Lambda API +reference's markup.""" +from __future__ import annotations + +import pytest + +import fetch_lambda_response_permissions as f + + +def operation(name: str, *actions: str) -> dict: + return {"Name": name, "AuthorizedActions": [{"Service": action.split(":")[0], "Name": action.split(":")[1]} + for action in (f"lambda:{name}", *actions)]} + + +REFERENCE = {"Operations": [ + operation("GetFunction", "lambda:ListTags"), + # An operation authorized by its own action alone has no page read, nor one the API reference does not list. + operation("GetAlias"), + operation("RunMicrovm", "lambda:GetMicrovmImage"), +]} +INDEX = ('
') +TAGS = ('
Tags
\n' + '

The function\'s tags. Lambda\n returns tag data only if you have explicit allow ' + 'permissions for lambda:ListTags.

Type: String to string map

') +CONFIGURATION = ('
Configuration' + '

The configuration of the function or version.

') + + +def page(*elements: str, operation: str = "GetFunction") -> str: + section = (f"
{''.join(elements)}
" if elements + else "

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP " + "body.

") + return (f'

{operation}

Response ' + f'Elements

{section}

Errors

Errors.

' + f'
') + + +def test_a_response_element_returned_only_with_a_permission_is_read_with_its_action(): + built = f.build(REFERENCE, INDEX, {"GetFunction": page(CONFIGURATION, TAGS)}) + assert built["returnedOnlyIf"] == [{ + "operation": "GetFunction", "element": "Tags", + "sentence": "Lambda returns tag data only if you have explicit allow permissions for lambda:ListTags.", + "action": "lambda:ListTags"}] + assert f.operations(REFERENCE, INDEX) == ["GetFunction"] + + +def test_a_page_whose_layout_or_wording_changed_is_refused(): + with pytest.raises(ValueError, match="links to no operation"): + f.operations(REFERENCE, "
") + # A sentence AWS rewords is refused rather than dropping its action, however it says it. + for reworded in (TAGS.replace("Lambda\n returns tag data", "Tags are returned"), + TAGS.replace("only if you have", "only when you have"), + TAGS.replace("Lambda\n returns tag data only if you have explicit allow permissions for", + "Reading tags requires the permission")): + with pytest.raises(ValueError, match="in no wording it used"): + f.build(REFERENCE, INDEX, {"GetFunction": page(reworded)}) + # A page whose response elements cannot be found is refused, not read as returning everything. + with pytest.raises(ValueError, match="no response elements section"): + f.build(REFERENCE, INDEX, {"GetFunction": page(TAGS).replace("_ResponseElements", "_Output")}) + with pytest.raises(ValueError, match="lists no response element and does not say its response is empty"): + f.build(REFERENCE, INDEX, {"GetFunction": page(TAGS).replace('
', + "
")}) + + +def test_a_page_saying_its_response_is_empty_returns_nothing_only_with_a_permission(): + assert f.read_returned("GetFunction", page()) == [] + + +def test_the_file_is_stale_when_the_reference_or_a_page_says_something_else(): + pages = {"GetFunction": page(TAGS)} + vendored = f.build(REFERENCE, INDEX, pages) + assert not f.stale(vendored, REFERENCE, INDEX, pages) + assert f.stale(vendored, REFERENCE, INDEX, {"GetFunction": page(TAGS.replace("lambda:ListTags", "lambda:GetTags"))}) diff --git a/tools/aws/test_regen_iam_authorized_actions.py b/tools/aws/test_regen_iam_authorized_actions.py index 88513d6b38..fab48652cf 100644 --- a/tools/aws/test_regen_iam_authorized_actions.py +++ b/tools/aws/test_regen_iam_authorized_actions.py @@ -843,6 +843,29 @@ def test_an_each_clause_naming_no_type_of_its_action_or_an_action_not_authorizin assert r.per_entry_actions([unlisted], REQUIRED) == {} +RETURNED = {"returnedOnlyIf": [{"operation": "GetFunction", "element": "Tags", "action": "lambda:ListTags", + "sentence": "Lambda returns tag data only if you have explicit allow permissions for " + "lambda:ListTags."}]} +LAMBDA = service("lambda", {"GetFunction": ["lambda:GetFunction", "lambda:ListTags"]}, ["GetFunction", "ListTags"]) +LAMBDA_RESPONSES = {"lambda": {"GetFunction": {"Code", "Concurrency", "Configuration", "Tags", "TagsError"}}} + + +def test_a_response_element_returned_only_with_a_permission_gates_the_member_of_its_name(): + assert r.returned_only_if([LAMBDA], RETURNED, LAMBDA_RESPONSES) == {"lambda": { + "GetFunction": [{"member": "Tags", "action": "lambda:ListTags"}]}} + document = r.build([SECRETS, *ANCHOR_SERVICES], "a test", [], requests=SECRET_REQUESTS) + document["returnedOnlyIf"] = r.returned_only_if([LAMBDA], RETURNED, LAMBDA_RESPONSES) + assert r.validate(document, []) == [] + document["returnedOnlyIf"] = {"lambda": {"GetFunction": [{"member": "Tags", "action": "s3:ListTags"}]}} + assert any("returnedOnlyIf lambda:GetFunction" in problem for problem in r.validate(document, [])) + + +def test_an_element_botocore_does_not_return_or_an_action_not_authorizing_the_operation_gates_nothing(): + assert r.returned_only_if([LAMBDA], RETURNED, {"lambda": {"GetFunction": {"Configuration"}}}) == {} + unlisted = service("lambda", {"GetFunction": ["lambda:GetFunction"]}, ["GetFunction", "ListTags"]) + assert r.returned_only_if([unlisted], RETURNED, LAMBDA_RESPONSES) == {} + + def test_an_action_the_reference_does_not_list_the_operation_as_authorized_by_is_no_companion(): unlisted = service("secretsmanager", {"BatchGetSecretValue": ["secretsmanager:BatchGetSecretValue"]}, ["BatchGetSecretValue", "ListSecrets"])