Skip to content

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

fix(apigateway): refuse non-SigV4 Authorization headers on AWS_IAM (#2370)

iot-rocket7d3c81e103fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4052f6df..ce708707 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **API Gateway — `AWS_IAM` methods refuse an `Authorization` header that is not SigV4** — under `AUTH=true` a REST API method with `AWS_IAM` authorization served a bearer token or an algorithm in lower case, and answered the SigV4a algorithm name without a signed `x-amz-region-set` or an unknown `AWS4-` algorithm with `UnrecognizedClientException`; it now answers 403 `IncompleteSignatureException` with API Gateway's message for each, while a method without `AWS_IAM` still serves such calls. Contributed by @iot-rocket.
- **S3 — access point policies and unsigned requests** — an access point policy was stored but never applied, and an unsigned request through an access point was served. With `AUTH=true` a request through an access point alias or ARN is allowed on the access point by an identity policy or the access point policy (a Deny in either refuses it), and an unsigned one gets 400 `InvalidRequest`; S3 Control calls on the access point are unaffected. Contributed by @iot-rocket.
## [1.5.31] — 2026-10-21
diff --git a/ministack/app.py b/ministack/app.py
index 3bb93d14..ffe43b95 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -1881,12 +1881,22 @@ def _enforce_execute_api(api_id: str, stage: str, method: str, execute_path: str
which AWS authorizes under that separate action.
"""
from ministack.core.arn import execute_api_arn
+ from ministack.core.iam_evaluator import AuthError
from ministack.core.responses import get_account_id
+ from ministack.core.sigv4 import foreign_authorization_failure
+ authorization = _execute_api_authorization_type(
+ api_id, stage, method, execute_path) if AUTH and iam_action == "execute-api:Invoke" else None
# Only an AWS_IAM method reads the caller's signature and policies.
- if AUTH and iam_action == "execute-api:Invoke" and _execute_api_authorization_type(
- api_id, stage, method, execute_path) not in (None, "AWS_IAM"):
+ if authorization not in (None, "AWS_IAM"):
return None
+ header = headers.get("authorization", "")
+ if authorization == "AWS_IAM" and header and not header.startswith("AWS4-HMAC-SHA256"):
+ # A REST method with AWS_IAM refuses an Authorization header that is not SigV4.
+ apigw_v1 = _get_module("apigateway_v1")
+ refused = foreign_authorization_failure(headers) if apigw_v1.find_api_scope(api_id) is not None else None
+ if refused:
+ return apigw_v1.authentication_error_response(api_id, stage, AuthError(*refused), headers, query_params)
return _enforce_data_plane(
"apigateway", iam_action, headers, query_params, "",
resource_arn=execute_api_arn(
diff --git a/ministack/core/sigv4.py b/ministack/core/sigv4.py
index c7c3f75d..e19b82fe 100644
--- a/ministack/core/sigv4.py
+++ b/ministack/core/sigv4.py
@@ -204,6 +204,30 @@ def parse_header_signature(headers: Mapping[str, Any]) -> HeaderSignature | tupl
return HeaderSignature(*scope[:4], fields["SignedHeaders"], fields["Signature"], amz_date)
+def foreign_authorization_failure(headers: Mapping[str, Any]) -> tuple[str, str] | None:
+ """Why API Gateway refuses an Authorization header that is not a SigV4 one, or None for a SigV4a header."""
+ authorization = headers.get("authorization", "")
+ algorithm, _, rest = authorization.partition(" ")
+ if any("=" not in part for part in rest.split(",") if part.strip()):
+ digest = base64.b64encode(hashlib.sha256(authorization.encode("utf-8")).digest()).decode()
+ return "IncompleteSignature", (
+ f"Invalid key=value pair (missing equal-sign) in Authorization header "
+ f"(hashed with SHA-256 and encoded with Base64): '{digest}'.")
+ if algorithm == "AWS4-ECDSA-P256-SHA256":
+ fields = dict(part.strip().partition("=")[::2] for part in rest.split(","))
+ if "x-amz-region-set" in fields.get("SignedHeaders", "").split(";"):
+ return None
+ return "IncompleteSignature", (
+ "'x-amz-region-set' must be a 'SignedHeader' in Authorization or passed as a Query Parameter "
+ "'X-Amz-Region-Set'")
+ signature = parse_header_signature(headers)
+ if isinstance(signature, tuple):
+ return signature
+ if not algorithm.startswith("AWS4-"):
+ return "IncompleteSignature", f"Algorithm must start with 'AWS4-'; got '{algorithm}'"
+ return "IncompleteSignature", f"Unsupported AWS 'algorithm': '{algorithm}'. "
+
+
def _query_value(query_params: Mapping[str, Any], name: str) -> str:
value = query_params.get(name, query_params.get(name.lower(), ""))
return (value[0] if value else "") if isinstance(value, list) else value
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 53f97b1c..a32ef936 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -4784,6 +4784,73 @@ def test_apigwv1_methods_without_aws_iam_read_no_credentials(auth_enabled, iam_u
cognito_idp.delete_user_pool(UserPoolId=pool["Id"])
+def test_apigwv1_aws_iam_method_refuses_an_authorization_header_that_is_not_sigv4(auth_enabled, iam_user, apigw_v1):
+ """An AWS_IAM method refuses an Authorization header that is not SigV4, with API Gateway's message for each."""
+ import http.client as _http
+ from urllib.parse import urlsplit
+
+ from botocore.auth import SigV4Auth
+ from botocore.awsrequest import AWSRequest
+
+ api = apigw_v1.create_rest_api(name="foreign-authorization")["id"]
+ try:
+ root = apigw_v1.get_resources(restApiId=api)["items"][0]["id"]
+ for part, kind in (("iam", "AWS_IAM"), ("open", "NONE")):
+ resource = apigw_v1.create_resource(restApiId=api, parentId=root, pathPart=part)["id"]
+ method = {"restApiId": api, "resourceId": resource, "httpMethod": "GET"}
+ apigw_v1.put_method(**method, authorizationType=kind)
+ apigw_v1.put_integration(
+ **method, type="MOCK", requestTemplates={"application/json": '{"statusCode": 200}'})
+ apigw_v1.put_method_response(**method, statusCode="200")
+ apigw_v1.put_integration_response(**method, statusCode="200", responseTemplates={"application/json": "{}"})
+ apigw_v1.create_deployment(restApiId=api, stageName="s")
+ host = f"{api}.execute-api.localhost:{_EXECUTE_PORT}"
+
+ edits = {
+ "bearer": lambda v: "Bearer x",
+ "lower-case": lambda v: v.replace("AWS4-HMAC-SHA256", "aws4-hmac-sha256", 1),
+ "sha512": lambda v: v.replace("AWS4-HMAC-SHA256", "AWS4-HMAC-SHA512", 1),
+ "sigv4a-name": lambda v: v.replace("AWS4-HMAC-SHA256", "AWS4-ECDSA-P256-SHA256", 1),
+ "leading-space": lambda v: " " + v,
+ }
+
+ def call(path, credentials, change=""):
+ request = AWSRequest(method="GET", url=f"http://{host}{path}", headers={"Host": host})
+ SigV4Auth(credentials, "execute-api", "us-east-1").add_auth(request)
+ if change:
+ request.headers.replace_header("Authorization", edits[change](request.headers["Authorization"]))
+ conn = _http.HTTPConnection("127.0.0.1", _EXECUTE_PORT, timeout=10)
+ try:
+ conn.request("GET", urlsplit(request.url).path, headers=dict(request.headers))
+ response = conn.getresponse()
+ body = json.loads(response.read() or b"{}")
+ return response.status, response.getheader("x-amzn-ErrorType"), body.get("message")
+ finally:
+ conn.close()
+
+ user = iam_user(policy=_ALLOW_INVOKE)
+ with _contract_signing_credentials(user) as key:
+ assert call("/s/iam", key)[0] == 200
+ assert call("/s/iam", key, "leading-space")[0] == 200
+ foreign = {change: call("/s/iam", key, change) for change in list(edits)[:4]}
+ if auth_enabled:
+ assert {change: answer[:2] for change, answer in foreign.items()} == dict.fromkeys(
+ foreign, (403, "IncompleteSignatureException"))
+ assert foreign["bearer"][2].startswith("Invalid key=value pair (missing equal-sign) in Authorization")
+ assert foreign["lower-case"][2] == "Algorithm must start with 'AWS4-'; got 'aws4-hmac-sha256'"
+ assert foreign["sha512"][2] == "Unsupported AWS 'algorithm': 'AWS4-HMAC-SHA512'. "
+ assert foreign["sigv4a-name"][2] == (
+ "'x-amz-region-set' must be a 'SignedHeader' in Authorization or passed as a Query Parameter "
+ "'X-Amz-Region-Set'")
+ else:
+ assert {answer[0] for answer in foreign.values()} == {200}
+ for change in edits:
+ assert call("/s/open", key, change)[0] == 200
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api)
+
+
def _v1_signed_token(claims: dict) -> str:
"""Mint an RS256 token signed with the local Cognito pool key."""
import base64 as _b64