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): include Lambda authorizers in the REST API export (#2220)
mishukdutta-cze774987058a8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5fc96563..91368097 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -106,6 +106,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **IAM — permissions boundaries are enforced** — the boundaries of users and roles were stored and never applied; under `AUTH=true` a boundary now limits what the identity policies allow and a `Deny` in it denies, a boundary must name a known managed policy (`ValidationError` for a malformed ARN, CloudFormation `AWS::IAM::User` included), deleting an absent boundary answers `NoSuchEntity`, and a policy in use as a boundary cannot be deleted. `ListUsers` and `ListRoles` leave the boundary out, `ListEntitiesForPolicy` lists boundary users and roles and honours `PolicyUsageFilter`, and a managed policy reports `PermissionsBoundaryUsageCount`. Contributed by @iot-rocket.### Fixed+- **API Gateway — `GetExport` includes Lambda authorizers** — a REST API export had no security scheme for a `TOKEN` or `REQUEST` authorizer and no `security` field on its methods, so tools such as Swagger UI showed no "Authorize" button. Each authorizer that a `CUSTOM` method uses is now a scheme in `components.securitySchemes` (OAS 3.0) or `securityDefinitions` (Swagger 2.0), and the method has `security`. With `extensions=authorizers` or `extensions=apigateway`, the scheme also has the `x-amazon-apigateway-authorizer` block. Checked against a real AWS export and the `x-amazon-apigateway-authorizer` docs.- **STS — trust policies see principal tags, session tags and web identities under `AUTH=true`** — `AssumeRole` trust conditions had no `aws:PrincipalTag/*`, a `Service` principal matched any IAM user whose ARN contained the service name, `Tags` passed without `sts:TagSession` in the trust policy, and `AssumeRoleWithWebIdentity` skipped the trust policy; trust conditions now see the caller's keys and the session tags as `aws:RequestTag/*` and `aws:TagKeys`, a `Service` principal no longer matches an IAM user, session tags need `sts:TagSession`, and a web identity needs a `Federated` principal naming its issuer, with `<issuer>:aud`, `:sub` and `:amr` evaluated. Under `AUTH=true` session tag keys that differ only in case answer `InvalidParameterValue`. Contributed by @iot-rocket.- **IAM — `aws:ResourceTag/*` under `AUTH=true`** — the key was always absent outside CloudWatch Logs, so a tag-scoped grant denied every request; a request on an existing SQS queue, SNS topic, DynamoDB table, Lambda function, IAM user or role, SSM parameter, Secrets Manager secret or KMS key now sees that resource's tags. Contributed by @iot-rocket.- **IAM — `aws:RequestTag/*` and `aws:TagKeys` under `AUTH=true`** — only CloudWatch Logs filled them; a call whose API takes `Tags` or `TagKeys` (create, tag and untag calls such as `CreateQueue`, `CreateTable`, `CreateUser`, `PutParameter`, `CreateSecret`, `CreateKey`) now carries the tags it sets and the keys it names, `aws:TagKeys` is absent on a call that names none, and Lambda `TagResource`, `UntagResource` and `ListTags` are authorized against the ARN in the path instead of skipped. Contributed by @iot-rocket.diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex d69709ec..ca6968cf 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -3962,7 +3962,46 @@ def _export_integration(integration):return {key: value for key, value in result.items() if value is not None}-def _export_operation(method_obj, export_type, include_integrations):+def _export_security_scheme(authorizer, include_authorizers):+ """Security scheme for a TOKEN or REQUEST authorizer.++ More than one identity source, or one that is not a header or query+ string, gives the name ``Unused``, as the AWS docs show."""+ source = authorizer["identitySource"]+ name = "Unused"+ location = "header"+ if "," not in source:+ if source.startswith("method.request.header."):+ name = source.removeprefix("method.request.header.")+ elif source.startswith("method.request.querystring."):+ name = source.removeprefix("method.request.querystring.")+ location = "query"++ scheme = {+ "type": "apiKey",+ "name": name,+ "in": location,+ "x-amazon-apigateway-authtype": authorizer.get("authType") or "custom",+ }+ if not include_authorizers:+ return scheme++ extension = {+ "type": authorizer["type"].lower(),+ "authorizerUri": authorizer["authorizerUri"],+ "authorizerResultTtlInSeconds": authorizer["authorizerResultTtlInSeconds"],+ }+ if authorizer["type"] == "REQUEST":+ extension["identitySource"] = source+ if authorizer["type"] == "TOKEN" and authorizer.get("identityValidationExpression"):+ extension["identityValidationExpression"] = authorizer["identityValidationExpression"]+ if authorizer.get("authorizerCredentials"):+ extension["authorizerCredentials"] = authorizer["authorizerCredentials"]+ scheme["x-amazon-apigateway-authorizer"] = extension+ return scheme+++def _export_operation(method_obj, export_type, include_integrations, authorizer):operation = {"responses": _export_method_responses(method_obj, export_type)}if method_obj.get("operationName"):operation["operationId"] = method_obj["operationName"]@@ -3999,8 +4038,14 @@ def _export_operation(method_obj, export_type, include_integrations):if export_type == "swagger" and produced_types:operation["produces"] = sorted(produced_types)+ # One requirement object: the client must send all these schemes+ requirement = {}+ if authorizer:+ requirement[authorizer["name"]] = []if method_obj.get("apiKeyRequired"):- operation["security"] = [{"api_key": []}]+ requirement["api_key"] = []+ if requirement:+ operation["security"] = [requirement]integration = method_obj.get("methodIntegration")if include_integrations and integration:@@ -4026,7 +4071,7 @@ def _get_export_extensions(query_params):}-def _build_api_export(api_id, stage_name, export_type, include_integrations):+def _build_api_export(api_id, stage_name, export_type, include_integrations, include_authorizers):api = _rest_apis[api_id]version = api.get("version") or "1.0"info = {"title": api.get("name", "unnamed"), "version": version}@@ -4036,6 +4081,7 @@ def _build_api_export(api_id, stage_name, export_type, include_integrations):schemas = _export_model_schemas(api_id)paths = {}has_api_key_method = False+ used_authorizers = {}for resource in _resources.get(api_id, {}).values():exported_methods = {}for http_method, method_obj in resource.get("resourceMethods", {}).items():@@ -4044,21 +4090,32 @@ def _build_api_export(api_id, stage_name, export_type, include_integrations):if http_method.upper() == "ANY"else http_method.lower())+ authorizer = None+ if method_obj.get("authorizationType") == "CUSTOM":+ authorizer = _authorizers_v1.get(api_id, {}).get(method_obj.get("authorizerId"))+ if authorizer:+ used_authorizers[authorizer["name"]] = authorizerexported_methods[method_key] = _export_operation(- method_obj, export_type, include_integrations+ method_obj, export_type, include_integrations, authorizer)has_api_key_method = has_api_key_method or bool(method_obj.get("apiKeyRequired"))if exported_methods:paths[resource.get("path", "/")] = exported_methods+ # AWS exports only the authorizers that methods use+ security_schemes = {+ name: _export_security_scheme(authorizer, include_authorizers)+ for name, authorizer in used_authorizers.items()+ }+ if has_api_key_method:+ security_schemes["api_key"] = {"type": "apiKey", "name": "x-api-key", "in": "header"}+region = get_region()execute_url = f"https://{api_id}.execute-api.{region}.amazonaws.com/{stage_name}"if export_type == "oas30":components = {"schemas": schemas}- if has_api_key_method:- components["securitySchemes"] = {- "api_key": {"type": "apiKey", "name": "x-api-key", "in": "header"}- }+ if security_schemes:+ components["securitySchemes"] = security_schemesreturn {"openapi": "3.0.1","info": info,@@ -4076,10 +4133,8 @@ def _build_api_export(api_id, stage_name, export_type, include_integrations):"paths": paths,"definitions": schemas,}- if has_api_key_method:- document["securityDefinitions"] = {- "api_key": {"type": "apiKey", "name": "x-api-key", "in": "header"}- }+ if security_schemes:+ document["securityDefinitions"] = security_schemesreturn document@@ -4113,7 +4168,8 @@ def _get_export(api_id, stage_name, export_type, headers, query_params):export_extensions = _get_export_extensions(query_params)include_integrations = bool({"integrations", "apigateway"} & export_extensions)- document = _build_api_export(api_id, stage_name, export_type, include_integrations)+ include_authorizers = bool({"authorizers", "apigateway"} & export_extensions)+ document = _build_api_export(api_id, stage_name, export_type, include_integrations, include_authorizers)if extension == "json":body = json.dumps(document, ensure_ascii=False).encode("utf-8")else:diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex d639d6e2..436dbb04 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -795,6 +795,145 @@ def test_apigatewayv1_get_export_validates_stage_and_format(apigw_v1):apigw_v1.delete_rest_api(restApiId=api_id)+_AUTHORIZER_URI = (+ "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"+ "arn:aws:lambda:us-east-1:000000000000:function:auth/invocations"+)+++def _deploy(apigw_v1, api_id):+ deployment_id = apigw_v1.create_deployment(restApiId=api_id)["id"]+ apigw_v1.create_stage(restApiId=api_id, stageName="prod", deploymentId=deployment_id)+++def _export(apigw_v1, api_id, export_type="oas30", extensions=None):+ response = apigw_v1.get_export(+ restApiId=api_id,+ stageName="prod",+ exportType=export_type,+ accepts="application/json",+ parameters={"extensions": extensions} if extensions else {},+ )+ return json.loads(response["body"].read())+++def test_apigatewayv1_get_export_token_authorizer(apigw_v1):+ """Methods that use a Lambda authorizer get a security scheme and an operation security field."""+ api_id = apigw_v1.create_rest_api(name="v1-export-token-auth")["id"]+ try:+ root_id = apigw_v1.get_resources(restApiId=api_id)["items"][0]["id"]+ token_auth_id = apigw_v1.create_authorizer(+ restApiId=api_id,+ name="TokenAuth",+ type="TOKEN",+ authorizerUri=_AUTHORIZER_URI,+ identitySource="method.request.header.Authorization",+ authorizerResultTtlInSeconds=300,+ )["id"]+ apigw_v1.create_authorizer(+ restApiId=api_id,+ name="UnusedAuth",+ type="TOKEN",+ authorizerUri=_AUTHORIZER_URI,+ identitySource="method.request.header.Authorization",+ )+ apigw_v1.put_method(+ restApiId=api_id,+ resourceId=root_id,+ httpMethod="GET",+ authorizationType="CUSTOM",+ authorizerId=token_auth_id,+ )+ apigw_v1.put_method(+ restApiId=api_id, resourceId=root_id, httpMethod="OPTIONS", authorizationType="NONE"+ )+ _deploy(apigw_v1, api_id)++ document = _export(apigw_v1, api_id)+ assert document["components"]["securitySchemes"] == {+ "TokenAuth": {+ "type": "apiKey",+ "name": "Authorization",+ "in": "header",+ "x-amazon-apigateway-authtype": "custom",+ }+ }+ assert document["paths"]["/"]["get"]["security"] == [{"TokenAuth": []}]+ assert "security" not in document["paths"]["/"]["options"]++ document = _export(apigw_v1, api_id, extensions="authorizers")+ assert document["components"]["securitySchemes"]["TokenAuth"]["x-amazon-apigateway-authorizer"] == {+ "type": "token",+ "authorizerUri": _AUTHORIZER_URI,+ "authorizerResultTtlInSeconds": 300,+ }++ document = _export(apigw_v1, api_id, export_type="swagger", extensions="apigateway")+ assert "x-amazon-apigateway-authorizer" in document["securityDefinitions"]["TokenAuth"]+ finally:+ apigw_v1.delete_rest_api(restApiId=api_id)+++def test_apigatewayv1_get_export_request_authorizer_with_two_sources(apigw_v1):+ """A REQUEST authorizer with two identity sources uses the name Unused, as the AWS docs show."""+ api_id = apigw_v1.create_rest_api(name="v1-export-request-auth")["id"]+ try:+ root_id = apigw_v1.get_resources(restApiId=api_id)["items"][0]["id"]+ identity_source = "method.request.header.Auth, method.request.querystring.token"+ authorizer_id = apigw_v1.create_authorizer(+ restApiId=api_id,+ name="RequestAuth",+ type="REQUEST",+ authorizerUri=_AUTHORIZER_URI,+ identitySource=identity_source,+ )["id"]+ apigw_v1.put_method(+ restApiId=api_id,+ resourceId=root_id,+ httpMethod="GET",+ authorizationType="CUSTOM",+ authorizerId=authorizer_id,+ )+ _deploy(apigw_v1, api_id)++ scheme = _export(apigw_v1, api_id, extensions="authorizers")["components"]["securitySchemes"]["RequestAuth"]+ assert scheme["name"] == "Unused"+ assert scheme["in"] == "header"+ assert scheme["x-amazon-apigateway-authorizer"]["type"] == "request"+ assert scheme["x-amazon-apigateway-authorizer"]["identitySource"] == identity_source+ finally:+ apigw_v1.delete_rest_api(restApiId=api_id)+++def test_apigatewayv1_get_export_skips_deleted_authorizer(apigw_v1):+ """A method whose authorizer was deleted is exported without security."""+ api_id = apigw_v1.create_rest_api(name="v1-export-deleted-auth")["id"]+ try:+ root_id = apigw_v1.get_resources(restApiId=api_id)["items"][0]["id"]+ authorizer_id = apigw_v1.create_authorizer(+ restApiId=api_id,+ name="TokenAuth",+ type="TOKEN",+ authorizerUri=_AUTHORIZER_URI,+ identitySource="method.request.header.Authorization",+ )["id"]+ apigw_v1.put_method(+ restApiId=api_id,+ resourceId=root_id,+ httpMethod="GET",+ authorizationType="CUSTOM",+ authorizerId=authorizer_id,+ )+ apigw_v1.delete_authorizer(restApiId=api_id, authorizerId=authorizer_id)+ _deploy(apigw_v1, api_id)++ document = _export(apigw_v1, api_id)+ assert "security" not in document["paths"]["/"]["get"]+ assert "securitySchemes" not in document["components"]+ finally:+ apigw_v1.delete_rest_api(restApiId=api_id)++def test_apigwv1_update_stage(apigw_v1):"""UpdateStage (PATCH) updates stage variables."""api_id = apigw_v1.create_rest_api(name="v1-stage-update")["id"]diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 6a12b7f1..8ee927df 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -16583,6 +16583,66 @@ def test_cfn_restapi_openapi_body_security_definitions(cfn, apigw_v1, cognito_idcognito_idp.delete_user_pool(UserPoolId=pool_id)+def test_cfn_restapi_body_from_export_keeps_authorizer(cfn, apigw_v1):+ """An export with extensions=authorizers, used as a RestApi Body, creates the same authorizer."""+ authorizer_uri = (+ "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"+ "arn:aws:lambda:us-east-1:000000000000:function:auth/invocations"+ )+ source_id = apigw_v1.create_rest_api(name="cfn-export-source")["id"]+ stack_name = f"intg-cfn-export-roundtrip-{_uuid_mod.uuid4().hex[:8]}"+ try:+ root_id = apigw_v1.get_resources(restApiId=source_id)["items"][0]["id"]+ authorizer_id = apigw_v1.create_authorizer(+ restApiId=source_id,+ name="TokenAuth",+ type="TOKEN",+ authorizerUri=authorizer_uri,+ identitySource="method.request.header.X-Token",+ )["id"]+ apigw_v1.put_method(+ restApiId=source_id,+ resourceId=root_id,+ httpMethod="GET",+ authorizationType="CUSTOM",+ authorizerId=authorizer_id,+ )+ deployment_id = apigw_v1.create_deployment(restApiId=source_id)["id"]+ apigw_v1.create_stage(restApiId=source_id, stageName="prod", deploymentId=deployment_id)+ body = json.loads(apigw_v1.get_export(+ restApiId=source_id,+ stageName="prod",+ exportType="oas30",+ accepts="application/json",+ parameters={"extensions": "authorizers"},+ )["body"].read())++ template = json.dumps({+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"Api": {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Body": body}}},+ "Outputs": {"ApiId": {"Value": {"Ref": "Api"}}},+ })+ cfn.create_stack(StackName=stack_name, TemplateBody=template)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ api_id = stack["Outputs"][0]["OutputValue"]++ [authorizer] = apigw_v1.get_authorizers(restApiId=api_id)["items"]+ assert authorizer["name"] == "TokenAuth"+ assert authorizer["type"] == "TOKEN"+ assert authorizer["authorizerUri"] == authorizer_uri+ assert authorizer["identitySource"] == "method.request.header.X-Token"++ root_id = apigw_v1.get_resources(restApiId=api_id)["items"][0]["id"]+ method = apigw_v1.get_method(restApiId=api_id, resourceId=root_id, httpMethod="GET")+ assert method["authorizationType"] == "CUSTOM"+ assert method["authorizerId"] == authorizer["id"]+ finally:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ apigw_v1.delete_rest_api(restApiId=source_id)++def test_cfn_restapi_openapi_body_document_level_security(cfn, apigw_v1):"""A document-level security block applies to every operation that does notoverride it, and an operation's empty security list opts back out."""