|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import math |
| 4 | +import re |
| 5 | +from typing import TYPE_CHECKING, Any, Literal |
| 6 | + |
| 7 | +from aws_lambda_powertools.utilities.auth._authorization import ( |
| 8 | + ForbiddenError, |
| 9 | + bearer_token, |
| 10 | + enforce_scopes, |
| 11 | + header_token, |
| 12 | + required_scopes, |
| 13 | +) |
| 14 | +from aws_lambda_powertools.utilities.auth._validation import string_list |
| 15 | +from aws_lambda_powertools.utilities.auth.exceptions import InvalidClaimsError, InvalidTokenError |
| 16 | +from aws_lambda_powertools.utilities.data_classes.api_gateway_authorizer_event import APIGatewayAuthorizerResponseV2 |
| 17 | +from aws_lambda_powertools.utilities.data_classes.common import DictWrapper |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from aws_lambda_powertools.utilities.auth._base import Verifier |
| 21 | + |
| 22 | +_ARN = re.compile(r"arn:[a-z0-9-]+:execute-api:[a-z0-9-]+:\d{12}:[a-z0-9]+/[^/]+/[A-Z]+/.*") |
| 23 | + |
| 24 | + |
| 25 | +def authorize_event( |
| 26 | + verifier: Verifier, |
| 27 | + event: dict[str, Any] | DictWrapper, |
| 28 | + scopes: list[str] | None, |
| 29 | + response_format: Literal["iam", "simple"], |
| 30 | + context_claims: list[str] | None, |
| 31 | +) -> dict[str, Any]: |
| 32 | + raw = event.raw_event if isinstance(event, DictWrapper) else event |
| 33 | + _validate_event(raw, response_format) |
| 34 | + arn = _request_arn(raw) if response_format == "iam" else None |
| 35 | + expected = required_scopes(scopes) |
| 36 | + selected = string_list(context_claims if context_claims is not None else []) |
| 37 | + if "claims" in selected: |
| 38 | + raise ValueError("claims is reserved in API Gateway authorizer context") |
| 39 | + claims = _verified_claims(verifier, raw, expected, require_principal=response_format == "iam") |
| 40 | + context = _context(claims, selected) if claims is not None else {} |
| 41 | + if response_format == "simple": |
| 42 | + return APIGatewayAuthorizerResponseV2(authorize=claims is not None, context=context).asdict() |
| 43 | + return _iam_response(claims, arn, context) |
| 44 | + |
| 45 | + |
| 46 | +def _validate_event(raw: dict[str, Any], response_format: str) -> None: |
| 47 | + if not isinstance(raw, dict) or raw.get("type") not in ("TOKEN", "REQUEST"): |
| 48 | + raise ValueError("An API Gateway TOKEN or REQUEST authorizer event is required") |
| 49 | + if response_format not in ("iam", "simple"): |
| 50 | + raise ValueError("response_format must be iam or simple") |
| 51 | + if response_format == "simple" and (raw.get("version") != "2.0" or raw["type"] != "REQUEST"): |
| 52 | + raise ValueError("Simple authorizer responses require HTTP API payload version 2.0") |
| 53 | + |
| 54 | + |
| 55 | +def _verified_claims( |
| 56 | + verifier: Verifier, |
| 57 | + raw: dict[str, Any], |
| 58 | + expected: tuple[str, ...], |
| 59 | + *, |
| 60 | + require_principal: bool, |
| 61 | +) -> dict[str, Any] | None: |
| 62 | + try: |
| 63 | + candidate = verifier.verify(_token(raw)) |
| 64 | + enforce_scopes(candidate, expected) |
| 65 | + if require_principal: |
| 66 | + _validate_principal(candidate) |
| 67 | + return candidate |
| 68 | + except (InvalidTokenError, ForbiddenError): |
| 69 | + return None |
| 70 | + |
| 71 | + |
| 72 | +def _token(raw: dict[str, Any]) -> str: |
| 73 | + if raw["type"] == "TOKEN": |
| 74 | + return bearer_token(raw.get("authorizationToken")) |
| 75 | + return header_token(raw.get("headers"), raw.get("multiValueHeaders")) |
| 76 | + |
| 77 | + |
| 78 | +def _validate_principal(claims: dict[str, Any]) -> None: |
| 79 | + if not isinstance(claims.get("sub"), str) or not claims["sub"].strip(): |
| 80 | + raise InvalidClaimsError() |
| 81 | + |
| 82 | + |
| 83 | +def _iam_response(claims: dict[str, Any] | None, arn: str | None, context: dict[str, Any]) -> dict[str, Any]: |
| 84 | + # Preserve the exact supplied resource, including its partition and encoded |
| 85 | + # path. Route builders normalize paths and cannot represent every ARN here. |
| 86 | + result: dict[str, Any] = { |
| 87 | + "principalId": claims["sub"] if claims is not None else "unauthorized", |
| 88 | + "policyDocument": { |
| 89 | + "Version": "2012-10-17", |
| 90 | + "Statement": [ |
| 91 | + { |
| 92 | + "Action": "execute-api:Invoke", |
| 93 | + "Effect": "Allow" if claims is not None else "Deny", |
| 94 | + "Resource": [arn], |
| 95 | + }, |
| 96 | + ], |
| 97 | + }, |
| 98 | + } |
| 99 | + if context: |
| 100 | + result["context"] = context |
| 101 | + return result |
| 102 | + |
| 103 | + |
| 104 | +def _request_arn(event: dict[str, Any]) -> str: |
| 105 | + arn = event.get("routeArn") if event.get("version") == "2.0" else event.get("methodArn") |
| 106 | + if ( |
| 107 | + not isinstance(arn, str) |
| 108 | + or len(arn) > 512 |
| 109 | + or not _ARN.fullmatch(arn) |
| 110 | + or any(character in arn for character in ("*", "?", "\r", "\n")) |
| 111 | + ): |
| 112 | + raise ValueError("A concrete API Gateway method or route ARN of at most 512 characters is required") |
| 113 | + return arn |
| 114 | + |
| 115 | + |
| 116 | +def _context(claims: dict[str, Any], selected: tuple[str, ...]) -> dict[str, Any]: |
| 117 | + context = {} |
| 118 | + for name in selected: |
| 119 | + value = claims.get(name) |
| 120 | + if isinstance(value, (str, bool, int)) or isinstance(value, float) and math.isfinite(value): |
| 121 | + context[name] = value |
| 122 | + return context |
0 commit comments