Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(apigateway): deliver JWT claims to a Lambda as strings (#1998)
Antonie Popovic8a8e28306d84
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 299ba215..2e0a46dd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **API Gateway v2 — JWT claims reach a Lambda as strings** — `requestContext.authorizer.jwt.claims` holds every claim as a string, as on AWS: numbers as digits, booleans as `true`/`false` and arrays as their items in brackets, e.g. `[admin dev]`. Typed event models (for example `aws_lambda_events` in Rust, or Go's `map[string]string`) parse the event.- **Lambda — throttle `retryAfterSeconds` is a string** — a `TooManyRequestsException` returns `retryAfterSeconds` as a string, as the Lambda API model declares, so SDK clients such as the AWS SDK for Rust parse the response as a throttle.- **Step Functions — `States.TaskFailed` no longer matches `States.Timeout`** — a `Retry` or `Catch` on `States.TaskFailed` also matched a timeout, so a state machine retried or caught a timeout where AWS does not. `States.TaskFailed` now matches every error except `States.Timeout`, as the Step Functions error handling guide describes.- **AppConfig — predefined deployment strategies** — `AppConfig.AllAtOnce`, `AppConfig.Linear50PercentEvery30Seconds`, `AppConfig.Canary10Percent20Minutes` and `AppConfig.Linear20PercentEvery6Minutes` now exist in every account and region and cannot be updated or deleted, as on AWS. A deployment records its strategy's parameters, and `StartDeployment` and `AWS::AppConfig::Deployment` fail with `ResourceNotFoundException` for a strategy that does not exist, where they used to accept any id. Contributed by @koh-sh.diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex 2d6ef0b8..d52c2068 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -1588,6 +1588,16 @@ def _v2_request_body_is_text(content_type: str | None) -> bool:)+def _jwt_claim_to_string(value):+ """API Gateway hands every JWT claim to a Lambda as a string: numbers as digits,+ booleans as true/false, and an array as its items in brackets, e.g. "[admin dev]"."""+ if isinstance(value, str):+ return value+ if isinstance(value, list):+ return "[" + " ".join(_jwt_claim_to_string(v) for v in value) + "]"+ return json.dumps(value)++async def _invoke_lambda_proxy(integration,api_id,@@ -1687,7 +1697,7 @@ async def _invoke_lambda_proxy(if authorizer_claims is not None:event["requestContext"]["authorizer"] = {"jwt": {- "claims": authorizer_claims or {},+ "claims": {k: _jwt_claim_to_string(v) for k, v in (authorizer_claims or {}).items()},"scopes": authorizer_scopes or [],}}diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex 2045f638..187a95aa 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -1940,6 +1940,69 @@ def test_apigw_request_authorizer_iam_policy_response_enforced_in_data_plane(apilam.delete_function(FunctionName=int_fn)+def test_apigw_jwt_claims_delivered_to_lambda_as_strings(apigw, lam, cognito_idp):+ """Every JWT claim value reaches the Lambda event as a string, as on AWS."""+ import urllib.request as _urlreq++ suffix = _uuid_mod.uuid4().hex[:8]+ fn = f"jwt-claims-str-{suffix}"+ code = (+ b"import json\n"+ b"def handler(event, context):\n"+ b" claims = event['requestContext']['authorizer']['jwt']['claims']\n"+ b" return {'statusCode': 200, 'body': json.dumps(claims)}\n"+ )+ lam.create_function(+ FunctionName=fn, Runtime="python3.12", Role=_LAMBDA_ROLE,+ Handler="index.handler", Code={"ZipFile": _make_zip(code)},+ )+ pool_id = cognito_idp.create_user_pool(PoolName=f"jwt-str-{suffix}")["UserPool"]["Id"]+ issuer = f"https://cognito-idp.us-east-1.amazonaws.com/{pool_id}"+ api_id = apigw.create_api(Name=f"jwt-str-{suffix}", ProtocolType="HTTP")["ApiId"]+ try:+ integ_id = apigw.create_integration(+ ApiId=api_id,+ IntegrationType="AWS_PROXY",+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fn}",+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ auth_id = apigw.create_authorizer(+ ApiId=api_id,+ AuthorizerType="JWT",+ Name="jwt-str-auth",+ IdentitySource=["$request.header.Authorization"],+ JwtConfiguration={"Audience": ["ms-client"], "Issuer": issuer},+ )["AuthorizerId"]+ apigw.create_route(+ ApiId=api_id,+ RouteKey="GET /secure",+ Target=f"integrations/{integ_id}",+ AuthorizationType="JWT",+ AuthorizerId=auth_id,+ )+ apigw.create_stage(ApiId=api_id, StageName="$default")++ now = int(time.time())+ token = _make_signed_token(+ {"sub": "u1", "iss": issuer, "aud": "ms-client", "iat": now, "exp": now + 3600,+ "email_verified": True, "cognito:groups": ["admin", "dev"]}+ )+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/$default/secure"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")+ req.add_header("Authorization", f"Bearer {token}")+ claims = json.loads(_urlreq.urlopen(req).read())+ assert claims["iat"] == str(now)+ assert claims["exp"] == str(now + 3600)+ assert claims["email_verified"] == "true"+ assert claims["cognito:groups"] == "[admin dev]"+ assert all(isinstance(v, str) for v in claims.values())+ finally:+ apigw.delete_api(ApiId=api_id)+ cognito_idp.delete_user_pool(UserPoolId=pool_id)+ lam.delete_function(FunctionName=fn)++def test_apigw_request_mapping_claims_to_headers(apigw, cognito_idp):import urllib.request as _urlreq