Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(apigateway): scope v1 authorizer cache to method ARN and stage (#1367)

iot-rocket7b7588b028a6
diff --git a/README.md b/README.md
index d7b832cb..40aace12 100644
--- a/README.md
+++ b/README.md
@@ -431,7 +431,7 @@ subnet = ec2.create_subnet(
| **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked |
| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TestState, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel; TestState API with mock and inspectionLevel support; SFN_MOCK_CONFIG for AWS SFN Local compatible mock testing; intrinsic functions (States.StringToJson, States.JsonToString, States.JsonMerge, States.Format); nested startExecution.sync |
| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; request parameter mapping for HTTP_PROXY (`append/overwrite/remove` for headers/querystring plus `overwrite:path`) with context variables including `$context.authorizer.jwt.claims`; JWT data-plane authorization for HTTP routes (issuer/audience/time/scope checks) and claim propagation to integrations; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; JWT/Lambda authorizer CRUD; pin `apiId` across runs with the `ms-custom-id` tag |
-| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag |
+| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; TOKEN and REQUEST Lambda authorizers on the data plane, with the returned IAM policy evaluated against each request's own method ARN and `authorizerResultTtlInSeconds` caching the policy per stage and identity source; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag |
| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateMac, VerifyMac, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, UpdateKeyDescription, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 32 actions; CMK specs: RSA (2048/3072/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), HMAC (`HMAC_224`/`HMAC_256`/`HMAC_384`/`HMAC_512` with `KeyUsage=GENERATE_VERIFY_MAC`), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; real RFC 2104 HMAC via `GenerateMac`/`VerifyMac` (4096-byte message cap, `KMSInvalidMacException` on mismatch, `DryRun` supported); envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |
| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **Policies**: CreateCachePolicy, GetCachePolicy, GetCachePolicyConfig, UpdateCachePolicy, DeleteCachePolicy, ListDistributionsByCachePolicyId, CreateOriginRequestPolicy, GetOriginRequestPolicy, GetOriginRequestPolicyConfig, UpdateOriginRequestPolicy, DeleteOriginRequestPolicy, ListDistributionsByOriginRequestPolicyId, CreateResponseHeadersPolicy, GetResponseHeadersPolicy, GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy, DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; cache / origin request / response headers policies round-trip their full config with `ETag` / `If-Match` optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again |
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 9506710d..58432cd1 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -125,10 +125,18 @@ _resources = AccountRegionScopedDict() # rest_api_id -> {resource_id -
_stages_v1 = AccountRegionScopedDict() # rest_api_id -> {stage_name -> Stage}
_deployments_v1 = AccountRegionScopedDict() # rest_api_id -> {deployment_id -> Deployment}
_authorizers_v1 = AccountRegionScopedDict() # rest_api_id -> {authorizer_id -> Authorizer}
-# Data-plane cache of evaluated Lambda-authorizer results, keyed by
-# (rest_api_id, authorizer_id, cache_key). Value: (expiry_epoch, decision, context).
-# Ephemeral (not persisted); honors authorizerResultTtlInSeconds.
+# Data-plane cache of Lambda-authorizer OUTPUT — the policy document and the
+# context, not the allow/deny verdict — keyed by (account, region, rest_api_id,
+# authorizer_id, stage, identity values). Value: (expiry_epoch, policy, context).
+# The policy is re-evaluated against every request's own method ARN, so a cached
+# Allow issued for one method or one stage cannot answer another. Ephemeral (not
+# persisted); honors authorizerResultTtlInSeconds.
_authorizer_cache = {}
+# Entries are keyed on caller-supplied tokens, so the cache is capped rather than
+# left to grow with every distinct token a long-lived instance ever sees.
+_AUTHORIZER_CACHE_MAX = 1024
+# AWS's default when CreateAuthorizer omits authorizerResultTtlInSeconds.
+_DEFAULT_AUTHORIZER_TTL = 300
_models = AccountRegionScopedDict() # rest_api_id -> {model_id -> Model}
_api_keys = AccountRegionScopedDict() # key_id -> ApiKey
_usage_plans = AccountRegionScopedDict() # plan_id -> UsagePlan
@@ -1337,6 +1345,40 @@ def _request_identity_sources(identity_source, headers, query_params, stage):
return present, values
+def _authorizer_ttl(authorizer):
+ """``authorizerResultTtlInSeconds`` as a non-negative int.
+
+ CreateAuthorizer already defaults the field to ``_DEFAULT_AUTHORIZER_TTL``,
+ so a record reaching here without one was reshaped by UpdateAuthorizer —
+ which applies JSON Patch verbatim and never validates the value. Absent and
+ unparsable therefore mean the same thing and both fall back to the AWS
+ default, instead of silently disabling caching in one case and enabling it
+ in the other. An explicit 0 still disables it.
+ """
+ raw = authorizer.get("authorizerResultTtlInSeconds")
+ if raw is None or raw == "":
+ return _DEFAULT_AUTHORIZER_TTL
+ try:
+ return max(int(raw), 0)
+ except (TypeError, ValueError):
+ return _DEFAULT_AUTHORIZER_TTL
+
+
+def _cache_authorizer_result(key, expires_at, policy_doc, context):
+ """Store one authorizer result, keeping ``_authorizer_cache`` bounded.
+
+ Expired entries are dropped once the cap is reached; if that is not enough,
+ the oldest insertions are evicted.
+ """
+ if len(_authorizer_cache) >= _AUTHORIZER_CACHE_MAX:
+ now = time.time()
+ for stale in [k for k, v in _authorizer_cache.items() if v[0] <= now]:
+ del _authorizer_cache[stale]
+ while len(_authorizer_cache) >= _AUTHORIZER_CACHE_MAX:
+ del _authorizer_cache[next(iter(_authorizer_cache))]
+ _authorizer_cache[key] = (expires_at, policy_doc, context)
+
+
async def _authorize_request_v1(
api_id, stage_name, method_obj, method, request_path, resource,
headers, body, query_params, path_params, stage,
@@ -1370,7 +1412,7 @@ async def _authorize_request_v1(
owner_region, owner_account_id, api_id, stage_name, method, request_path
)
atype = (authorizer.get("type") or "TOKEN").upper()
- ttl = int(authorizer.get("authorizerResultTtlInSeconds") or 0)
+ ttl = _authorizer_ttl(authorizer)
if atype == "TOKEN":
identity_source = authorizer.get("identitySource") or "method.request.header.Authorization"
@@ -1383,9 +1425,18 @@ async def _authorize_request_v1(
if not token:
return _gw_error(401, "Unauthorized"), None
val_expr = authorizer.get("identityValidationExpression")
- if val_expr and not re.fullmatch(val_expr, token):
- return _gw_error(401, "Unauthorized"), None
- cache_key = token
+ if val_expr:
+ try:
+ token_matches = re.fullmatch(val_expr, token) is not None
+ except re.error:
+ # CreateAuthorizer stores the expression verbatim, so an
+ # uncompilable one only surfaces here. That is a
+ # misconfiguration (AUTHORIZER_CONFIGURATION_ERROR), not an
+ # exception that should escape the request handler.
+ return _gw_error(500, "Internal server error"), None
+ if not token_matches:
+ return _gw_error(401, "Unauthorized"), None
+ identity_values = (token,)
event = {"type": "TOKEN", "authorizationToken": token, "methodArn": method_arn}
else: # REQUEST
identity_source = authorizer.get("identitySource") or ""
@@ -1396,7 +1447,7 @@ async def _authorize_request_v1(
# 401 without invoking the authorizer (matches AWS).
if ttl > 0 and identity_source and not all_present:
return _gw_error(401, "Unauthorized"), None
- cache_key = "|".join(id_values)
+ identity_values = tuple(id_values)
single_headers = {k: (v if isinstance(v, str) else v[-1]) for k, v in headers.items()}
multi_headers = {k: ([v] if isinstance(v, str) else list(v)) for k, v in headers.items()}
qs_params = {k: v[0] for k, v in query_params.items()} if query_params else None
@@ -1423,54 +1474,70 @@ async def _authorize_request_v1(
},
}
- # TTL cache: a hit replays the prior decision without invoking the Lambda.
- ckey = (api_id, authorizer_id, cache_key)
+ # TTL cache: a hit replays the authorizer's OUTPUT without invoking the
+ # Lambda, but never its verdict — the policy is evaluated below against this
+ # request's own method ARN. The stage and the identity values are part of the
+ # key for the same reason: the canonical `Resource: event['methodArn']` policy
+ # is issued for exactly one method on one stage.
+ ckey = (owner_account_id, owner_region, api_id, authorizer_id, stage_name, identity_values)
+ cached = None
if ttl > 0:
hit = _authorizer_cache.get(ckey)
if hit and hit[0] > time.time():
- _, decision, cached_ctx = hit
- if decision == "Allow":
- return None, cached_ctx
- return _deny_error(decision == "Deny"), None
+ cached = (hit[1], hit[2])
- result = await _invoke_authorizer_lambda(
- authorizer, event, owner_account_id, owner_region
- )
- if result is None:
- # Authorizer Lambda unresolved / not found → connection failure.
- return _gw_error(500, "Internal server error"), None
- if result.get("error"):
- err_body = result.get("body") or {}
- msg = err_body.get("errorMessage", "") if isinstance(err_body, dict) else str(err_body)
- # A function that raises exactly "Unauthorized" maps to 401; any other
- # uncaught error is an authorizer failure → 500.
- if isinstance(msg, str) and msg.strip().lower() == "unauthorized":
- return _gw_error(401, "Unauthorized"), None
- return _gw_error(500, "Internal server error"), None
-
- policy = result.get("body")
- if isinstance(policy, (str, bytes)):
- if isinstance(policy, bytes):
- policy = policy.decode("utf-8", errors="replace")
- try:
- policy = json.loads(policy)
- except json.JSONDecodeError:
- policy = None
- if not isinstance(policy, dict):
- return _gw_error(500, "Internal server error"), None
+ if cached is None:
+ result = await _invoke_authorizer_lambda(
+ authorizer, event, owner_account_id, owner_region
+ )
+ if result is None:
+ # Authorizer Lambda unresolved / not found → connection failure.
+ return _gw_error(500, "Internal server error"), None
+ if result.get("error"):
+ err_body = result.get("body") or {}
+ msg = err_body.get("errorMessage", "") if isinstance(err_body, dict) else str(err_body)
+ # A function that raises exactly "Unauthorized" maps to 401; any other
+ # uncaught error is an authorizer failure → 500.
+ if isinstance(msg, str) and msg.strip().lower() == "unauthorized":
+ return _gw_error(401, "Unauthorized"), None
+ return _gw_error(500, "Internal server error"), None
+
+ policy = result.get("body")
+ if isinstance(policy, (str, bytes)):
+ if isinstance(policy, bytes):
+ policy = policy.decode("utf-8", errors="replace")
+ try:
+ policy = json.loads(policy)
+ except json.JSONDecodeError:
+ policy = None
+ if not isinstance(policy, dict):
+ return _gw_error(500, "Internal server error"), None
+
+ principal_id = policy.get("principalId")
+ if principal_id is None or str(principal_id) == "":
+ # AWS demands a principal. Without one the response is an
+ # AUTHORIZER_CONFIGURATION_ERROR, not an Allow that reaches the
+ # backend carrying an empty principalId.
+ return _gw_error(500, "Internal server error"), None
+
+ policy_doc = policy.get("policyDocument")
+ if not isinstance(policy_doc, dict):
+ # Same AUTHORIZER_CONFIGURATION_ERROR shape: a response without a
+ # policyDocument is a misconfigured authorizer, not an implicit
+ # deny — and it must not be cached.
+ return _gw_error(500, "Internal server error"), None
+
+ auth_ctx = _stringify_context(policy.get("context"))
+ auth_ctx["principalId"] = str(principal_id)
+ # Only a well-formed response is cached; failures re-invoke next time.
+ cached = (policy_doc, auth_ctx)
+ if ttl > 0:
+ _cache_authorizer_result(ckey, time.time() + ttl, *cached)
- decision = _evaluate_policy(policy.get("policyDocument"), method_arn)
+ policy_doc, auth_ctx = cached
+ decision = _evaluate_policy(policy_doc, method_arn)
if decision != "Allow":
- if ttl > 0:
- _authorizer_cache[ckey] = (time.time() + ttl, decision, None)
return _deny_error(decision == "Deny"), None
-
- auth_ctx = _stringify_context(policy.get("context"))
- principal_id = policy.get("principalId")
- if principal_id is not None:
- auth_ctx["principalId"] = str(principal_id)
- if ttl > 0:
- _authorizer_cache[ckey] = (time.time() + ttl, "Allow", auth_ctx)
return None, auth_ctx
@@ -2673,7 +2740,9 @@ def _create_authorizer(api_id, data):
"authorizerCredentials": data.get("authorizerCredentials"),
"identitySource": data.get("identitySource", "method.request.header.Authorization"),
"identityValidationExpression": data.get("identityValidationExpression", ""),
- "authorizerResultTtlInSeconds": data.get("authorizerResultTtlInSeconds", 300),
+ "authorizerResultTtlInSeconds": data.get(
+ "authorizerResultTtlInSeconds", _DEFAULT_AUTHORIZER_TTL
+ ),
"providerARNs": data.get("providerARNs", []),
}
_authorizers_v1.setdefault(api_id, {})[auth_id] = authorizer
diff --git a/tests/conftest.py b/tests/conftest.py
index f872f4bf..eac1d7ad 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -83,6 +83,16 @@ _SERIAL_TESTS = {
"tests/test_apigatewayv2.py::test_apigwv1_path_based_restapi_legacy_user_request",
"tests/test_apigatewayv2.py::test_apigwv2_named_stage_still_requires_prefix",
"tests/test_apigatewayv2.py::test_apigwv2_integration_wrapped_function_arn",
+ # v1 Lambda-authorizer cache tests. Same cold-start-burst sensitivity as the
+ # apigw tests above, doubled: every guarded request cold-starts TWO Lambdas
+ # (the authorizer and the backend), and the invocation-count assertions that
+ # prove a cache hit or miss leave no slack for a retry.
+ "tests/test_apigatewayv1.py::test_apigwv1_authorizer_cache_is_scoped_per_method_arn",
+ "tests/test_apigatewayv1.py::test_apigwv1_authorizer_cache_is_scoped_per_stage",
+ "tests/test_apigatewayv1.py::test_apigwv1_authorizer_invalid_validation_expression_is_500",
+ "tests/test_apigatewayv1.py::test_apigwv1_authorizer_without_principal_id_is_500_and_not_cached",
+ "tests/test_apigatewayv1.py::test_apigwv1_authorizer_without_policy_document_is_500_and_not_cached",
+ "tests/test_apigatewayv1.py::test_apigwv1_authorizer_unparsable_ttl_falls_back_to_the_default",
# v2 REQUEST-authorizer cache tests. Same cold-start-burst sensitivity as
# the apigw tests above, doubled: every guarded request cold-starts TWO
# Lambdas (the authorizer and the integration), and the invocation-count
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index a0f0409d..08c1cff8 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -3194,3 +3194,423 @@ def test_apigatewayv1_load_persisted_state_backfills_taggable_resource_regions()
)
assert status == 204
assert body == {}
+
+
+# ---- Data plane: Lambda-authorizer result caching ----
+
+_AUTH_ECHO_BACKEND = (
+ "import json\n"
+ "def handler(event, context):\n"
+ " return {'statusCode': 200,\n"
+ " 'body': json.dumps(event['requestContext'].get('authorizer'))}\n"
+)
+
+# Prelude for authorizer sources: counts invocations by pushing one SQS message
+# per call. The counter has to live INSIDE the emulator — writing to a
+# ``tmp_path`` file only works while the server runs in-process, and silently
+# breaks (FileNotFoundError on every counted test) under the documented
+# ``docker compose up`` workflow where the Lambda runs in its own container.
+_AUTH_MARK_PRELUDE = (
+ "import os, boto3\n"
+ "def _mark(qname):\n"
+ " sqs = boto3.client('sqs', endpoint_url=os.environ['AWS_ENDPOINT_URL'])\n"
+ " url = sqs.get_queue_url(QueueName=qname)['QueueUrl']\n"
+ " sqs.send_message(QueueUrl=url, MessageBody='1')\n"
+)
+
+
+def _auth_counter_queue(sqs):
+ """Create the SQS queue an authorizer marks on every invocation."""
+ qname = f"v1-auth-count-{_uuid_mod.uuid4().hex[:8]}"
+ sqs.create_queue(QueueName=qname)
+ return qname
+
+
+def _auth_count(sqs, qname):
+ """How many times the authorizer behind ``qname`` has run."""
+ url = sqs.get_queue_url(QueueName=qname)["QueueUrl"]
+ attrs = sqs.get_queue_attributes(
+ QueueUrl=url, AttributeNames=["ApproximateNumberOfMessages"]
+ )["Attributes"]
+ return int(attrs["ApproximateNumberOfMessages"])
+
+
+def _auth_delete_queue(sqs, qname):
+ try:
+ sqs.delete_queue(QueueUrl=sqs.get_queue_url(QueueName=qname)["QueueUrl"])
+ except ClientError:
+ pass
+
+
+def _auth_make_lambda(lam, label, code):
+ fname = f"v1-auth-{label}-{_uuid_mod.uuid4().hex[:8]}"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Timeout=30,
+ Code={"ZipFile": buf.getvalue()},
+ )
+ return fname
+
+
+def _auth_drop_lambda(lam, fname):
+ try:
+ lam.delete_function(FunctionName=fname)
+ except ClientError:
+ pass
+
+
+def _auth_drop_api(apigw_v1, api_id):
+ try:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ except ClientError:
+ pass
+
+
+def _auth_lambda_uri(fname):
+ return (
+ "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ f"arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations"
+ )
+
+
+def _auth_token_authorizer_code(qname):
+ """TOKEN authorizer: Allow for `allow*` tokens, Deny otherwise.
+
+ The policy's ``Resource`` is the canonical ``event['methodArn']`` — the
+ shape every AWS sample emits, and the one whose per-request evaluation
+ keeps a cached policy from granting another method or stage. The methodArn
+ is echoed through ``context`` so a test can see which one was issued.
+ """
+ return (
+ _AUTH_MARK_PRELUDE
+ + "def handler(event, context):\n"
+ f" _mark({qname!r})\n"
+ " token = event.get('authorizationToken', '')\n"
+ " effect = 'Allow' if token.startswith('allow') else 'Deny'\n"
+ " return {\n"
+ " 'principalId': 'user|' + token,\n"
+ " 'policyDocument': {'Version': '2012-10-17', 'Statement': [\n"
+ " {'Action': 'execute-api:Invoke', 'Effect': effect,\n"
+ " 'Resource': event['methodArn']}]},\n"
+ " 'context': {'arn': event['methodArn']},\n"
+ " }\n"
+ )
+
+
+def _auth_http(url, method="GET", headers=None, timeout=30):
+ """(status, body_bytes) without raising on 4xx/5xx.
+
+ An explicit timeout keeps a wedged request from hanging the whole session.
+ """
+ import urllib.error as _urlerr
+ import urllib.request as _urlreq
+
+ req = _urlreq.Request(url, method=method)
+ for k, v in (headers or {}).items():
+ req.add_header(k, v)
+ try:
+ resp = _urlreq.urlopen(req, timeout=timeout)
+ return resp.status, resp.read()
+ except _urlerr.HTTPError as e:
+ return e.code, e.read()
+
+
+def _auth_root_id(apigw_v1, api_id):
+ return next(
+ r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/"
+ )
+
+
+def _auth_execute_url(api_id, stage, path):
+ # Path-based execute form: no *.localhost DNS needed.
+ return f"http://localhost:{_EXECUTE_PORT}/_aws/execute-api/{api_id}/{stage}/{path}"
+
+
+def _auth_wire_lambda_method(apigw_v1, api_id, resource_id, backend_fname, authorizer_id):
+ apigw_v1.put_method(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ authorizationType="CUSTOM",
+ authorizerId=authorizer_id,
+ )
+ apigw_v1.put_integration(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ type="AWS_PROXY",
+ integrationHttpMethod="POST",
+ uri=_auth_lambda_uri(backend_fname),
+ )
+
+
+def _auth_build_api(apigw_v1, backend_fname, authorizer_kwargs, path_parts=("secure",)):
+ """API with a CUSTOM-guarded `GET /{part}` per entry in ``path_parts``."""
+ api_id = apigw_v1.create_rest_api(name=f"v1-auth-{_uuid_mod.uuid4().hex[:6]}")["id"]
+ root_id = _auth_root_id(apigw_v1, api_id)
+ authorizer_id = apigw_v1.create_authorizer(restApiId=api_id, **authorizer_kwargs)["id"]
+ for part in path_parts:
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root_id, pathPart=part
+ )["id"]
+ _auth_wire_lambda_method(apigw_v1, api_id, resource_id, backend_fname, authorizer_id)
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+ return api_id, authorizer_id
+
+
+def test_apigwv1_authorizer_cache_is_scoped_per_method_arn(apigw_v1, lam, sqs):
+ """A cached Allow grants only the method it was issued for.
+
+ The canonical `Resource: event['methodArn']` policy covers exactly one
+ method. Caching the allow/deny *decision* under a key without the method ARN
+ replays that Allow on every other method the same token touches; caching the
+ *policy* and re-evaluating it per request does not.
+ """
+ qname = _auth_counter_queue(sqs)
+ backend = _auth_make_lambda(lam, "be", _AUTH_ECHO_BACKEND)
+ authz = _auth_make_lambda(lam, "tok", _auth_token_authorizer_code(qname))
+ api_id, _ = _auth_build_api(
+ apigw_v1, backend,
+ dict(name="tok", type="TOKEN", authorizerUri=_auth_lambda_uri(authz),
+ authorizerResultTtlInSeconds=300),
+ path_parts=("alpha", "beta"),
+ )
+ try:
+ status, _ = _auth_http(
+ _auth_execute_url(api_id, "test", "alpha"), headers={"Authorization": "allow-abc"}
+ )
+ assert status == 200
+ assert _auth_count(sqs, qname) == 1
+
+ status, body = _auth_http(
+ _auth_execute_url(api_id, "test", "beta"), headers={"Authorization": "allow-abc"}
+ )
+ assert status == 403, "an Allow issued for /alpha must not carry over to /beta"
+ assert json.loads(body) == {"Message": "User is not authorized to access this resource"}
+ assert _auth_count(sqs, qname) == 1, "the cached policy is what gets re-evaluated"
+ finally:
+ _auth_drop_api(apigw_v1, api_id)
+ _auth_drop_lambda(lam, backend)
+ _auth_drop_lambda(lam, authz)
+ _auth_delete_queue(sqs, qname)
+
+
+def test_apigwv1_authorizer_cache_is_scoped_per_stage(apigw_v1, lam, sqs):
+ """API Gateway caches authorizer results per stage: a verdict computed on
+ one stage never answers the same token on another."""
+ qname = _auth_counter_queue(sqs)
+ backend = _auth_make_lambda(lam, "be", _AUTH_ECHO_BACKEND)
+ authz = _auth_make_lambda(lam, "tok", _auth_token_authorizer_code(qname))
+ api_id, _ = _auth_build_api(
+ apigw_v1, backend,
+ dict(name="tok", type="TOKEN", authorizerUri=_auth_lambda_uri(authz),
+ authorizerResultTtlInSeconds=300),
+ )
+ try:
+ dep_id = apigw_v1.get_deployments(restApiId=api_id)["items"][0]["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="prod", deploymentId=dep_id)
+
+ status, body = _auth_http(
+ _auth_execute_url(api_id, "test", "secure"), headers={"Authorization": "allow-abc"}
+ )
+ assert status == 200
+ assert "/test/GET/secure" in json.loads(body)["arn"]
+ assert _auth_count(sqs, qname) == 1
+
+ status, body = _auth_http(
+ _auth_execute_url(api_id, "prod", "secure"), headers={"Authorization": "allow-abc"}
+ )
+ assert status == 200, body
+ assert _auth_count(sqs, qname) == 2, "the test-stage entry must not serve prod"
+ assert "/prod/GET/secure" in json.loads(body)["arn"]
+
+ # The per-stage entries are independent: both now answer from cache.
+ for stage in ("test", "prod"):
+ status, _ = _auth_http(
+ _auth_execute_url(api_id, stage, "secure"), headers={"Authorization": "allow-abc"}
+ )
+ assert status == 200
+ assert _auth_count(sqs, qname) == 2
+ finally:
+ _auth_drop_api(apigw_v1, api_id)
+ _auth_drop_lambda(lam, backend)
+ _auth_drop_lambda(lam, authz)
+ _auth_delete_queue(sqs, qname)
+
+
+def test_apigwv1_authorizer_invalid_validation_expression_is_500(apigw_v1, lam):
+ """CreateAuthorizer stores identityValidationExpression verbatim, so an
+ uncompilable expression only fails on the data path — as a 500
+ AUTHORIZER_CONFIGURATION_ERROR, not an exception out of the handler."""
+ backend = _auth_make_lambda(lam, "be", _AUTH_ECHO_BACKEND)
+ authz = _auth_make_lambda(
+ lam, "tok",
+ "def handler(event, context):\n"
+ " return {'principalId': 'p',\n"
+ " 'policyDocument': {'Version': '2012-10-17', 'Statement': [\n"
+ " {'Action': 'execute-api:Invoke', 'Effect': 'Allow',\n"
+ " 'Resource': event['methodArn']}]}}\n",
+ )
+ api_id, _ = _auth_build_api(
+ apigw_v1, backend,
+ dict(name="tok", type="TOKEN", authorizerUri=_auth_lambda_uri(authz),
+ identityValidationExpression="allow-[a-z",
+ authorizerResultTtlInSeconds=0),
+ )
+ try:
+ status, body = _auth_http(
+ _auth_execute_url(api_id, "test", "secure"), headers={"Authorization": "allow-abc"}
+ )
+ assert status == 500
+ assert json.loads(body) == {"message": "Internal server error"}
+ finally:
+ _auth_drop_api(apigw_v1, api_id)
+ _auth_drop_lambda(lam, backend)
+ _auth_drop_lambda(lam, authz)
+
+
+def test_apigwv1_authorizer_without_principal_id_is_500_and_not_cached(apigw_v1, lam, sqs):
+ """AWS requires a principal. An Allow policy with no principalId is an
+ AUTHORIZER_CONFIGURATION_ERROR, not an allow that reaches the backend with
+ an empty principalId — and a configuration error is never cached."""
+ qname = _auth_counter_queue(sqs)
+ backend = _auth_make_lambda(lam, "be", _AUTH_ECHO_BACKEND)
+ authz = _auth_make_lambda(
+ lam, "noprincipal",
+ _AUTH_MARK_PRELUDE
+ + "def handler(event, context):\n"
+ f" _mark({qname!r})\n"
+ " return {'policyDocument': {'Version': '2012-10-17', 'Statement': [\n"
+ " {'Action': 'execute-api:Invoke', 'Effect': 'Allow',\n"
+ " 'Resource': event['methodArn']}]}}\n",
+ )
+ api_id, _ = _auth_build_api(
+ apigw_v1, backend,
+ dict(name="noprincipal", type="TOKEN", authorizerUri=_auth_lambda_uri(authz),
+ authorizerResultTtlInSeconds=300),
+ )
+ try:
+ url = _auth_execute_url(api_id, "test", "secure")
+ for _ in range(2):
+ status, body = _auth_http(url, headers={"Authorization": "allow-abc"})
+ assert status == 500
+ assert json.loads(body) == {"message": "Internal server error"}
+ assert _auth_count(sqs, qname) == 2, "a configuration error must not be cached"
+ finally:
+ _auth_drop_api(apigw_v1, api_id)
+ _auth_drop_lambda(lam, backend)
+ _auth_drop_lambda(lam, authz)
+ _auth_delete_queue(sqs, qname)
+
+
+def test_apigwv1_authorizer_without_policy_document_is_500_and_not_cached(apigw_v1, lam, sqs):
+ """A response with no policyDocument is a misconfigured authorizer: AWS
+ answers 500 AuthorizerConfigurationException, not an implicit deny — and
+ the malformed response is never cached."""
+ qname = _auth_counter_queue(sqs)
+ backend = _auth_make_lambda(lam, "be", _AUTH_ECHO_BACKEND)
+ authz = _auth_make_lambda(
+ lam, "nopolicy",
+ _AUTH_MARK_PRELUDE
+ + "def handler(event, context):\n"
+ f" _mark({qname!r})\n"
+ " return {'principalId': 'user|abc'}\n",
+ )
+ api_id, _ = _auth_build_api(
+ apigw_v1, backend,
+ dict(name="nopolicy", type="TOKEN", authorizerUri=_auth_lambda_uri(authz),
+ authorizerResultTtlInSeconds=300),
+ )
+ try:
+ url = _auth_execute_url(api_id, "test", "secure")
+ for _ in range(2):
+ status, body = _auth_http(url, headers={"Authorization": "allow-abc"})
+ assert status == 500
+ assert json.loads(body) == {"message": "Internal server error"}
+ assert _auth_count(sqs, qname) == 2, "a configuration error must not be cached"
+ finally:
+ _auth_drop_api(apigw_v1, api_id)
+ _auth_drop_lambda(lam, backend)
+ _auth_drop_lambda(lam, authz)
+ _auth_delete_queue(sqs, qname)
+
+
+def test_apigwv1_authorizer_unparsable_ttl_falls_back_to_the_default(apigw_v1, lam, sqs):
+ """UpdateAuthorizer applies JSON Patch without validating, so the TTL can be
+ any string by the time the data plane reads it. An unparsable value falls
+ back to the same default an absent one does (and does not raise).
+
+ The PATCH goes over raw HTTP: botocore models the field as an integer and
+ would raise while parsing the *response*, after the server already stored
+ the string — which is exactly how an authorizer ends up in this state.
+ """
+ import urllib.request as _urlreq
+
+ qname = _auth_counter_queue(sqs)
+ backend = _auth_make_lambda(lam, "be", _AUTH_ECHO_BACKEND)
+ authz = _auth_make_lambda(lam, "tok", _auth_token_authorizer_code(qname))
+ api_id, authorizer_id = _auth_build_api(
+ apigw_v1, backend,
+ dict(name="tok", type="TOKEN", authorizerUri=_auth_lambda_uri(authz),
+ authorizerResultTtlInSeconds=300),
+ )
+ try:
+ patch = _urlreq.Request(
+ f"{_endpoint}/restapis/{api_id}/authorizers/{authorizer_id}",
+ data=json.dumps({"patchOperations": [{
+ "op": "replace",
+ "path": "/authorizerResultTtlInSeconds",
+ "value": "not-a-number",
+ }]}).encode(),
+ headers={"Content-Type": "application/json"},
+ method="PATCH",
+ )
+ patched = json.loads(_urlreq.urlopen(patch, timeout=30).read())
+ assert patched["authorizerResultTtlInSeconds"] == "not-a-number"
+
+ url = _auth_execute_url(api_id, "test", "secure")
+ for _ in range(2):
+ status, _ = _auth_http(url, headers={"Authorization": "allow-abc"})
+ assert status == 200
+ assert _auth_count(sqs, qname) == 1, "caching stays on at the default TTL"
+ finally:
+ _auth_drop_api(apigw_v1, api_id)
+ _auth_drop_lambda(lam, backend)
+ _auth_drop_lambda(lam, authz)
+ _auth_delete_queue(sqs, qname)
+
+
+def test_apigwv1_authorizer_cache_is_bounded():
+ """The result cache is keyed on caller-supplied tokens, so it is capped
+ rather than left to grow for the life of the process. Expired entries go
+ first; beyond that the oldest insertions are evicted."""
+ cache = apigateway_v1._authorizer_cache
+ cap = apigateway_v1._AUTHORIZER_CACHE_MAX
+ saved = dict(cache)
+ cache.clear()
+ try:
+ expired_at = time.time() - 1
+ for i in range(cap):
+ apigateway_v1._cache_authorizer_result(("stale", i), expired_at, {}, {})
+ assert len(cache) == cap
+
+ # The next write is over the cap and prunes the expired entries first.
+ apigateway_v1._cache_authorizer_result(("live", 0), time.time() + 300, {}, {})
+ assert len(cache) == 1
+ assert ("live", 0) in cache
+
+ # With nothing expired to reclaim, the oldest insertions are evicted.
+ for i in range(cap + 50):
+ apigateway_v1._cache_authorizer_result(("live", i), time.time() + 300, {}, {})
+ assert len(cache) <= cap
+ assert ("live", cap + 49) in cache
+ finally:
+ cache.clear()
+ cache.update(saved)