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
feat(apigateway): answer failed SigV4 authentication through gateway responses (#2153)
iot-rocket0d93193a5dad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1d1e6973..e24e5a23 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Added+- **API Gateway — failed SigV4 authentication answers through the gateway responses** — under `AUTH=true` a REST API invoke that failed authentication got the generic JSON error and ignored the API's gateway responses; a wrong secret, a skewed clock or a credential date other than the request date now answers `INVALID_SIGNATURE` (`InvalidSignatureException`), an expired session `EXPIRED_TOKEN` (`ExpiredTokenException`), and an unknown key or a malformed `Authorization` header `DEFAULT_4XX` with the matching `x-amzn-ErrorType`, 403 with `{"message": ...}`. Contributed by @iot-rocket.- **Auth — the request time of a header-signed request is checked** — under `AUTH=true` a request signed with an IAM user or STS session key was served whatever its time; one signed more than 15 minutes (STS, IAM, SNS, SQS, DynamoDB, S3, ECR, RDS, ElastiCache) or 5 minutes (the default for other services) from the server clock answers `SignatureDoesNotMatch` / `InvalidSignatureException` with AWS's `Signature expired` or `Signature not yet current` message, `RequestTimeTooSkewed` from S3 and `AuthFailure` from EC2. Contributed by @iot-rocket.- **Auth — the session token of a header-signed request is checked** — under `AUTH=true` an STS session key sent without its token was accepted and now answers as an unknown key, and a wrong token, or a token with an IAM user key, answers `InvalidClientTokenId` (`UnrecognizedClientException` from JSON services, `InvalidToken` 400 from S3), as on AWS. Contributed by @iot-rocket.- **Auth — header signatures are verified for IAM user and STS session keys** — under `AUTH=true` a request signed with such a key and the wrong secret, or changed after signing, was served; it now answers `SignatureDoesNotMatch` (or the service's `InvalidSignatureException`), an `Authorization` header without its `Signature` or `SignedHeaders` answers `IncompleteSignature` (Lambda `MissingAuthenticationTokenException`, S3 `AuthorizationHeaderMalformed`) and a credential date other than the request date `SignatureDoesNotMatch` (S3 `AuthorizationHeaderMalformed`), S3 unsigned, streaming and signed-chunk payloads are checked the same way, and the root key still accepts any secret. Contributed by @iot-rocket.diff --git a/ministack/app.py b/ministack/app.pyindex 61a27695..01fc8d09 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1777,6 +1777,8 @@ def _enforce_execute_api(api_id: str, stage: str, method: str, execute_path: strextract_region(headers, query_params), get_account_id(),api_id, stage, method, execute_path,),+ auth_error_response=lambda error: _get_module("apigateway_v1").authentication_error_response(+ api_id, stage, error, headers, query_params),)@@ -2203,7 +2205,7 @@ def _credential_failure(service: str, iam_action: str, request_id: str, denied,def _enforce_data_plane(service: str, iam_action: str, headers: dict, query_params: dict, request_id: str, resource_arn: str = "*",- service_context: dict | None = None,+ service_context: dict | None = None, auth_error_response=None,):"""Enforce IAM auth on a data-plane path. Returns error tuple or None.@@ -2221,7 +2223,8 @@ def _enforce_data_plane(resource_arn=resource_arn, service_context=service_context)if denied:if isinstance(denied, AuthError):- return _credential_failure(service, iam_action, request_id, denied, headers)+ response = auth_error_response(denied) if auth_error_response else None+ return response or _credential_failure(service, iam_action, request_id, denied, headers)return access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers,explicit_deny=denied.decision == "Deny")return Nonediff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex 3df0cc68..7eb08935 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -1416,9 +1416,10 @@ class _GatewayError:of ``response_type`` in the stage's deployment (see:func:`_gateway_error_response`)."""- def __init__(self, response_type, message):+ def __init__(self, response_type, message, error_type=None):self.response_type = response_typeself.message = message+ self.error_type = error_typedef _gw_error(response_type, message):@@ -1493,7 +1494,7 @@ def _gateway_error_response(error, request):value = _gateway_request_value(source, request)if value is not None:headers[dest[len("gatewayresponse.header."):]] = value- error_type = _GATEWAY_RESPONSE_ERROR_TYPES.get(response_type)+ error_type = error.error_type or _GATEWAY_RESPONSE_ERROR_TYPES.get(response_type)if error_type:headers["x-amzn-ErrorType"] = error_typeheaders["x-amzn-requestid"] = request["request_id"]@@ -1521,7 +1522,35 @@ def _gateway_error_response(error, request):body = _GATEWAY_TEMPLATE_VARIABLE.sub(lambda m: variables.get(m.group(1) or m.group(2), m.group(0)), template)- return int(response.get("statusCode") or 500), headers, body.encode("utf-8")+ status = response.get("statusCode") or (403 if response_type == "DEFAULT_4XX" else 500)+ return int(status), headers, body.encode("utf-8")+++# A failed SigV4 authentication of an execute-api caller: the gateway response and x-amzn-ErrorType.+_AUTHENTICATION_GATEWAY_ERRORS = {+ "SignatureDoesNotMatch": ("INVALID_SIGNATURE", "InvalidSignatureException"),+ "RequestTimeTooSkewed": ("INVALID_SIGNATURE", "InvalidSignatureException"),+ "ExpiredTokenException": ("EXPIRED_TOKEN", "ExpiredTokenException"),+ "CredentialDateMismatch": ("INVALID_SIGNATURE", "InvalidSignatureException"),+ "IncompleteSignature": ("DEFAULT_4XX", "IncompleteSignatureException"),+ "MissingAuthorizationParameter": ("DEFAULT_4XX", "IncompleteSignatureException"),+}+++def authentication_error_response(api_id, stage_name, error, headers, query_params):+ """Answer a failed SigV4 authentication through a REST API stage's gateway responses, or None."""+ scope = find_api_scope(api_id)+ stage = stages_for_api(api_id).get(stage_name)+ if scope is None or stage is None:+ return None+ response_type, error_type = _AUTHENTICATION_GATEWAY_ERRORS.get(+ error.code, ("DEFAULT_4XX", "UnrecognizedClientException"))+ request = {+ "api_id": api_id, "stage_name": stage_name, "stage": stage, "headers": headers or {},+ "query_params": query_params or {}, "path_params": {}, "resource_path": "", "request_id": new_uuid(),+ }+ with request_scope(*scope):+ return _gateway_error_response(_GatewayError(response_type, error.message, error_type), request)def _arn_matches(pattern, arn):@@ -1865,8 +1894,8 @@ async def _authorize_request_v1(if auth_type in ("", "NONE"):return None, Noneif auth_type == "AWS_IAM":- # We do not verify SigV4 signatures; match AWS only to the extent that a- # request with no Authorization header is rejected as unauthenticated.+ # Signatures are verified only under AUTH; here match AWS only to the extent+ # that a request with no Authorization header is rejected as unauthenticated.if not _header_ci(headers, "authorization"):return _gw_error("MISSING_AUTHENTICATION_TOKEN", "Missing Authentication Token"), Nonereturn None, Nonediff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex 84016a74..9f0dfb60 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -1276,7 +1276,7 @@ def _capture_enforced_arn(monkeypatch) -> dict:seen: dict[str, str] = {}def _capture(service, iam_action, headers, query_params, request_id, resource_arn="*",- service_context=None):+ service_context=None, auth_error_response=None):seen["action"] = iam_actionseen["arn"] = resource_arnseen["context"] = service_context@@ -4609,6 +4609,71 @@ class TestClockSkew:_local_client("dynamodb", *user_key).list_tables()+class TestExecuteApiAuthentication:+ @pytest.fixture+ def invoke(self, user_key):+ from botocore.auth import SigV4Auth+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials++ apigw = _local_client("apigateway")+ api = apigw.create_rest_api(name="iam-auth")["id"]+ root = apigw.get_resources(restApiId=api)["items"][0]["id"]+ method = {"restApiId": api, "resourceId": root, "httpMethod": "GET"}+ apigw.put_method(**method, authorizationType="AWS_IAM")+ apigw.put_integration(**method, type="MOCK", requestTemplates={"application/json": '{"statusCode": 200}'})+ apigw.put_method_response(**method, statusCode="200")+ apigw.put_integration_response(**method, statusCode="200", responseTemplates={"application/json": '{"ok": 1}'})+ for response_type in ("INVALID_SIGNATURE", "EXPIRED_TOKEN", "DEFAULT_4XX"):+ apigw.put_gateway_response(restApiId=api, responseType=response_type, responseParameters={+ "gatewayresponse.header.x-type": f"'{response_type}'"})+ apigw.create_deployment(restApiId=api, stageName="p")++ def call(key, secret, seconds=0, authorization=None, token=None):+ request = AWSRequest(method="GET", url=f"http://{api}.execute-api.localhost:4566/p/")+ with _signing_clock(seconds):+ SigV4Auth(Credentials(key, secret, token), "execute-api", "us-east-1").add_auth(request)+ if authorization:+ request.headers.replace_header("Authorization", authorization(request.headers["Authorization"]))+ response = _asgi_send(request.prepare())+ return (response.status_code, response.headers.get("x-type"), response.headers.get("x-amzn-ErrorType"),+ json.loads(response.content).get("message"))++ yield call+ apigw.delete_rest_api(restApiId=api)++ def test_aws_iam_failures_answer_through_gateway_responses(self, user_key, invoke):+ assert invoke(*user_key)[0] == 200+ assert invoke(user_key[0], "wrong-secret")[:3] == (403, "INVALID_SIGNATURE", "InvalidSignatureException")+ status, response_type, error_type, message = invoke(*user_key, seconds=-1200)+ assert (status, response_type, error_type) == (403, "INVALID_SIGNATURE", "InvalidSignatureException")+ assert message.startswith("Signature expired: ") and message.endswith(" - 5 min.)")+ assert invoke("AKIAUNKNOWNKEY000001", "secret") == (+ 403, "DEFAULT_4XX", "UnrecognizedClientException", "The security token included in the request is invalid.")+ assert invoke(*user_key, authorization=lambda value: value.split(", Signature=")[0])[:3] == (+ 403, "DEFAULT_4XX", "IncompleteSignatureException")+ assert invoke(*user_key, authorization=lambda value: re.sub(r"/\d{8}/", "/20200101/", value, count=1))[:3] == (+ 403, "INVALID_SIGNATURE", "InvalidSignatureException")++ def test_expired_session_answers_through_expired_token(self, invoke, monkeypatch):+ from ministack.services import sts as sts_svc++ monkeypatch.setitem(sts_svc._sessions, "ASIAEXPIREDSESSION01", {+ "Arn": "arn:aws:iam::000000000000:user/alice", "UserId": "AIDAALICE",+ "SecretAccessKey": "session-secret", "SessionToken": "session-token",+ "Expiration": time.time() - 1, "AccountId": "000000000000", "PrincipalType": "User",+ })+ assert invoke("ASIAEXPIREDSESSION01", "session-secret", token="session-token") == (+ 403, "EXPIRED_TOKEN", "ExpiredTokenException", "The security token included in the request is expired")++ def test_root_key_and_auth_off_are_unchanged(self, user_key, invoke, monkeypatch):+ from ministack import app as app_mod++ assert invoke("test", "anything")[0] == 200+ monkeypatch.setattr(app_mod, "AUTH", False)+ assert invoke(user_key[0], "wrong-secret")[0] == 200++# ---------------------------------------------------------------------------# AssumeRole trust policy: matching denies and STS request conditions (AUTH=true)# ---------------------------------------------------------------------------