Skip to content

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

fix(apigateway): honour securityDefinitions on OpenAPI import (#1782)

maximoosemine5b524c025585
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91849689..fd293ef8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **API Gateway — an OpenAPI body's `securityDefinitions` reach the methods** — the import discarded security outright, so a SAM API declaring a Cognito authorizer created none and every method imported as `authorizationType: NONE`, serving anonymous callers where AWS answers 401. Each scheme carrying `x-amazon-apigateway-authorizer` now becomes an authorizer, and an operation's `security` — or the document's — sets the method's `authorizationType`, `authorizerId` and `authorizationScopes`, so the enforcement added in 1.5.10 engages for body-defined APIs.
- **CloudFormation — `AWS::ApiGateway::Stage` method settings reach the stage as a map** — the template's `MethodSettings` list was stored verbatim, so the throttling lookup added in 1.5.14 raised on it and every request to a CloudFormation- or SAM-deployed API answered 500. The list is now keyed `"<resourcePath>/<httpMethod>"`, `"*/*"` for the stage-wide entry, over the account-level defaults AWS reports from `GetStage`.
## [1.5.14] — 2026-09-20
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 9daddf12..a544727b 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -2895,6 +2895,103 @@ _OPENAPI_HTTP_METHODS = {
}
+def _security_schemes(spec):
+ """Security schemes, from swagger 2.0 or OAS 3.0."""
+ schemes = spec.get("securityDefinitions")
+ if not isinstance(schemes, dict):
+ schemes = (spec.get("components") or {}).get("securitySchemes")
+ return schemes if isinstance(schemes, dict) else {}
+
+
+def _import_identity_source(scheme, extension):
+ """The ``method.request.*`` identity source a security scheme names.
+
+ A ``request`` authorizer carries its own ``identitySource``; the others
+ derive it from the scheme's ``name`` and ``in``, which is how SAM and the
+ console spell the header carrying the token."""
+ if extension.get("identitySource"):
+ return extension["identitySource"]
+ name = scheme.get("name") or "Authorization"
+ location = (scheme.get("in") or "header").lower()
+ prefix = "method.request.querystring." if location == "query" else "method.request.header."
+ return prefix + name
+
+
+def _import_security_schemes(api_id, spec):
+ """Create an authorizer per ``x-amazon-apigateway-authorizer`` scheme.
+
+ Returns a scheme name -> method authorization mapping; this is the only
+ mechanism by which SAM's ``Auth`` property reaches a method, since the
+ translator emits no AWS::ApiGateway::Authorizer resource."""
+ mapping = {}
+ for scheme_name, scheme in _security_schemes(spec).items():
+ if not isinstance(scheme, dict):
+ continue
+ extension = scheme.get("x-amazon-apigateway-authorizer")
+ auth_type = str(scheme.get("x-amazon-apigateway-authtype") or "").lower()
+ if not isinstance(extension, dict):
+ if auth_type == "awssigv4":
+ mapping[scheme_name] = {"authorizationType": "AWS_IAM"}
+ elif scheme.get("type") == "apiKey" and (scheme.get("name") or "").lower() == "x-api-key":
+ mapping[scheme_name] = {"apiKeyRequired": True}
+ continue
+ kind = str(extension.get("type") or "").lower()
+ data = {
+ "name": scheme_name,
+ "identitySource": _import_identity_source(scheme, extension),
+ "authType": auth_type or kind,
+ }
+ if kind == "cognito_user_pools":
+ data["type"] = "COGNITO_USER_POOLS"
+ data["providerARNs"] = extension.get("providerARNs") or []
+ method_auth = "COGNITO_USER_POOLS"
+ elif kind in ("token", "request"):
+ data["type"] = kind.upper()
+ data["authorizerUri"] = extension.get("authorizerUri", "")
+ data["authorizerCredentials"] = extension.get("authorizerCredentials")
+ data["identityValidationExpression"] = extension.get(
+ "identityValidationExpression", ""
+ )
+ if extension.get("authorizerResultTtlInSeconds") is not None:
+ data["authorizerResultTtlInSeconds"] = extension[
+ "authorizerResultTtlInSeconds"
+ ]
+ method_auth = "CUSTOM"
+ else:
+ continue
+ _status, _headers, body = _create_authorizer(api_id, data)
+ if _status >= 400:
+ continue
+ mapping[scheme_name] = {
+ "authorizationType": method_auth,
+ "authorizerId": json.loads(body)["id"],
+ }
+ return mapping
+
+
+def _method_security(security, scheme_map):
+ """Resolve an operation's ``security`` list against the scheme map."""
+ data = {"authorizationType": "NONE"}
+ for requirement in security or []:
+ if not isinstance(requirement, dict):
+ continue
+ for scheme_name, scopes in requirement.items():
+ mapped = scheme_map.get(scheme_name)
+ if not mapped:
+ continue
+ if mapped.get("apiKeyRequired"):
+ data["apiKeyRequired"] = True
+ continue
+ if data["authorizationType"] != "NONE":
+ continue
+ data["authorizationType"] = mapped["authorizationType"]
+ if mapped.get("authorizerId"):
+ data["authorizerId"] = mapped["authorizerId"]
+ if isinstance(scopes, list) and scopes:
+ data["authorizationScopes"] = list(scopes)
+ return data
+
+
def _import_rest_api(spec, base_data=None):
data = dict(base_data or {})
info = spec.get("info") or {}
@@ -2905,12 +3002,14 @@ def _import_rest_api(spec, base_data=None):
_status, _headers, body = _create_rest_api(data)
api_id = json.loads(body)["id"]
+ scheme_map = _import_security_schemes(api_id, spec)
+ default_security = spec.get("security")
for path, path_item in (spec.get("paths") or {}).items():
- _import_path_item(api_id, path, path_item)
+ _import_path_item(api_id, path, path_item, scheme_map, default_security)
return api_id
-def _import_path_item(api_id, path, path_item):
+def _import_path_item(api_id, path, path_item, scheme_map=None, default_security=None):
resource_id = next(
rid for rid, res in _resources.get(api_id, {}).items()
if res.get("path") == "/"
@@ -2932,11 +3031,17 @@ def _import_path_item(api_id, path, path_item):
for method, operation in path_item.items():
if method.lower() in _OPENAPI_HTTP_METHODS:
- _import_operation(api_id, resource_id, method.upper(), operation)
+ _import_operation(api_id, resource_id, method.upper(), operation,
+ scheme_map, default_security)
-def _import_operation(api_id, resource_id, http_method, operation):
- _put_method(api_id, resource_id, http_method, {"authorizationType": "NONE"})
+def _import_operation(api_id, resource_id, http_method, operation,
+ scheme_map=None, default_security=None):
+ security = (operation or {}).get("security")
+ if security is None:
+ security = default_security
+ _put_method(api_id, resource_id, http_method,
+ _method_security(security, scheme_map or {}))
integration = (operation or {}).get("x-amazon-apigateway-integration")
if integration:
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 2e95ee2b..10834982 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -13757,6 +13757,203 @@ def test_cfn_restapi_openapi_body_petstore(cfn, apigw_v1):
assert api_id not in ids
+def test_cfn_restapi_openapi_body_security_definitions(cfn, apigw_v1, cognito_idp):
+ """securityDefinitions in a RestApi Body create authorizers and bind methods.
+
+ This is the only mechanism by which SAM's Auth property reaches a method —
+ the translator emits no AWS::ApiGateway::Authorizer resource — so before
+ this the method imported as authorizationType NONE and served everyone.
+ """
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ port = urlparse(endpoint).port or 4566
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"intg-cfn-restapi-security-{suffix}"
+
+ pool_id = cognito_idp.create_user_pool(PoolName=f"cfn-body-{suffix}")["UserPool"]["Id"]
+ pool_region = pool_id.split("_")[0]
+ pool_arn = f"arn:aws:cognito-idp:{pool_region}:000000000000:userpool/{pool_id}"
+
+ mock = {
+ "x-amazon-apigateway-integration": {"type": "mock", "httpMethod": "GET"},
+ "responses": {},
+ }
+ body = {
+ "swagger": "2.0",
+ "info": {"version": "1.0", "title": f"security-{suffix}"},
+ "securityDefinitions": {
+ "CognitoAuthorizer": {
+ "in": "header",
+ "type": "apiKey",
+ "name": "Authorization",
+ "x-amazon-apigateway-authtype": "cognito_user_pools",
+ "x-amazon-apigateway-authorizer": {
+ "type": "cognito_user_pools",
+ "providerARNs": [pool_arn],
+ },
+ },
+ "LambdaAuthorizer": {
+ "in": "header",
+ "type": "apiKey",
+ "name": "X-Token",
+ "x-amazon-apigateway-authtype": "custom",
+ "x-amazon-apigateway-authorizer": {
+ "type": "token",
+ "authorizerUri": (
+ "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/"
+ "functions/arn:aws:lambda:us-east-1:000000000000:"
+ "function:noop/invocations"
+ ),
+ "authorizerResultTtlInSeconds": 60,
+ },
+ },
+ },
+ "paths": {
+ "/devices": {
+ "get": dict(mock, security=[{"CognitoAuthorizer": ["devices/read"]}]),
+ },
+ "/tokens": {"get": dict(mock, security=[{"LambdaAuthorizer": []}])},
+ "/open": {"get": dict(mock)},
+ },
+ }
+ template = json.dumps({
+ "Resources": {
+ "Api": {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Body": body}},
+ "Deployment": {
+ "Type": "AWS::ApiGateway::Deployment",
+ "Properties": {"RestApiId": {"Ref": "Api"}, "StageName": "prod"},
+ },
+ },
+ "Outputs": {"ApiId": {"Value": {"Ref": "Api"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ api_id = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["ApiId"]
+
+ authorizers = {
+ a["name"]: a for a in apigw_v1.get_authorizers(restApiId=api_id)["items"]
+ }
+ assert set(authorizers) == {"CognitoAuthorizer", "LambdaAuthorizer"}
+ cognito_auth = authorizers["CognitoAuthorizer"]
+ assert cognito_auth["type"] == "COGNITO_USER_POOLS"
+ assert cognito_auth["providerARNs"] == [pool_arn]
+ assert cognito_auth["identitySource"] == "method.request.header.Authorization"
+ assert cognito_auth["authType"] == "cognito_user_pools"
+ lambda_auth = authorizers["LambdaAuthorizer"]
+ assert lambda_auth["type"] == "TOKEN"
+ assert lambda_auth["identitySource"] == "method.request.header.X-Token"
+ assert lambda_auth["authorizerResultTtlInSeconds"] == 60
+
+ resources = {
+ r["path"]: r["id"]
+ for r in apigw_v1.get_resources(restApiId=api_id, limit=500)["items"]
+ }
+ devices = apigw_v1.get_method(
+ restApiId=api_id, resourceId=resources["/devices"], httpMethod="GET",
+ )
+ assert devices["authorizationType"] == "COGNITO_USER_POOLS"
+ assert devices["authorizerId"] == cognito_auth["id"]
+ assert devices["authorizationScopes"] == ["devices/read"]
+
+ tokens = apigw_v1.get_method(
+ restApiId=api_id, resourceId=resources["/tokens"], httpMethod="GET",
+ )
+ assert tokens["authorizationType"] == "CUSTOM"
+ assert tokens["authorizerId"] == lambda_auth["id"]
+
+ open_method = apigw_v1.get_method(
+ restApiId=api_id, resourceId=resources["/open"], httpMethod="GET",
+ )
+ assert open_method["authorizationType"] == "NONE"
+
+ def _call(path):
+ req = urllib.request.Request(
+ f"http://127.0.0.1:{port}/prod{path}",
+ method="GET",
+ headers={"Host": f"{api_id}.execute-api.localhost:{port}"},
+ )
+ try:
+ with urllib.request.urlopen(req) as resp:
+ return resp.status
+ except urllib.error.HTTPError as exc:
+ return exc.code
+
+ # The gap this closes: both of these previously answered 200.
+ assert _call("/devices") == 401
+ assert _call("/tokens") == 401
+ assert _call("/open") == 200
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+
+
+def test_cfn_restapi_openapi_body_document_level_security(cfn, apigw_v1):
+ """A document-level security block applies to every operation that does not
+ override it, and an operation's empty security list opts back out."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"intg-cfn-restapi-security-doc-{suffix}"
+ mock = {
+ "x-amazon-apigateway-integration": {"type": "mock", "httpMethod": "GET"},
+ "responses": {},
+ }
+ body = {
+ "swagger": "2.0",
+ "info": {"version": "1.0", "title": f"security-doc-{suffix}"},
+ "securityDefinitions": {
+ "sigv4": {
+ "in": "header",
+ "type": "apiKey",
+ "name": "Authorization",
+ "x-amazon-apigateway-authtype": "awsSigv4",
+ },
+ "api_key": {"in": "header", "type": "apiKey", "name": "x-api-key"},
+ },
+ "security": [{"sigv4": []}],
+ "paths": {
+ "/inherited": {"get": dict(mock)},
+ "/keyed": {"get": dict(mock, security=[{"api_key": []}])},
+ "/public": {"get": dict(mock, security=[])},
+ },
+ }
+ template = json.dumps({
+ "Resources": {
+ "Api": {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Body": body}},
+ },
+ "Outputs": {"ApiId": {"Value": {"Ref": "Api"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ api_id = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["ApiId"]
+
+ # Neither scheme carries x-amazon-apigateway-authorizer, so no authorizer.
+ assert apigw_v1.get_authorizers(restApiId=api_id)["items"] == []
+
+ resources = {
+ r["path"]: r["id"]
+ for r in apigw_v1.get_resources(restApiId=api_id, limit=500)["items"]
+ }
+
+ def _method(path):
+ return apigw_v1.get_method(
+ restApiId=api_id, resourceId=resources[path], httpMethod="GET",
+ )
+
+ assert _method("/inherited")["authorizationType"] == "AWS_IAM"
+ keyed = _method("/keyed")
+ assert keyed["authorizationType"] == "NONE"
+ assert keyed["apiKeyRequired"] is True
+ assert _method("/public")["authorizationType"] == "NONE"
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
# ============================================================================
# Nested Stacks (AWS::CloudFormation::Stack)
# ============================================================================