Skip to content

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

feat(auth): verify the signature of WebSocket handshakes (#2276)

iot-rocketfd52f26ab76e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 56718618..fdc14164 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
+- **Auth — WebSocket handshakes are verified for IAM user and STS session keys** — under `AUTH=true` an MQTT-over-WebSocket upgrade or an `AWS_IAM` WebSocket `$connect` signed with such a key was accepted with a wrong secret, a date more than 5 minutes off or a wrong session token; the signature in the query string or `Authorization` header is now checked like that of other requests, IoT answers 403 `Forbidden` and expects the session token after the signed part of the URL, and API Gateway names the canonical string it expected. Contributed by @iot-rocket.
- **RDS Data, S3 Control — calls are authorized under `AUTH=true`** — RDS Data calls and S3 Control tagging calls were served whatever the caller's policies allowed; each RDS Data call is now authorized as `rds-data:<operation>` on the cluster its `resourceArn` names, and `ListTagsForResource`, `TagResource` and `UntagResource` as `s3:<operation>` on the bucket, with a 403 denial (`AccessDeniedException` from RDS Data, `AccessDenied` from S3 Control) naming the action and resource, as on AWS. Contributed by @iot-rocket.
- **SES v2 — calls are authorized under `AUTH=true`** — SES v2 calls were served whatever the caller's policies allowed; each is now authorized as `ses:<operation>` on the configuration set, contact list, custom verification email template, dedicated IP pool, identity or template its path or create body names (`*` otherwise), and a denial answers 403 `AccessDeniedException` naming the action and resource, as on AWS. Contributed by @iot-rocket.
diff --git a/ministack/app.py b/ministack/app.py
index 6506a31c..573e4097 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -91,7 +91,7 @@ def _ws_resolve_iot_account_id(scope: dict, ws_headers: dict) -> str:
3. Fall back to ``MINISTACK_ACCOUNT_ID`` / ``000000000000``.
SigV4 signature *verification* is intentionally lax (any
- well-formed credential is accepted); IoT policy enforcement is not yet
+ well-formed credential is accepted) unless AUTH=true; IoT policy enforcement is not yet
feature. The point here is multi-tenancy isolation, not auth.
"""
qs = scope.get("query_string", b"").decode("utf-8", errors="replace")
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 51da1d17..e7085663 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -1248,13 +1248,16 @@ class SignedRequest:
headers: dict
body: bytes = b""
presigned: bool = False
+ handshake: bool = False
_signed_request: contextvars.ContextVar[SignedRequest | None] = contextvars.ContextVar(
"ministack_signed_request", default=None)
-def pin_signed_request(method: str, raw_path: str, query_params: dict, raw_headers: list) -> None:
+def pin_signed_request(
+ method: str, raw_path: str, query_params: dict, raw_headers: list, handshake: bool = False,
+) -> None:
"""Keep a request signed with an IAM user or STS session key as sent, for its signature check."""
from ministack.core.router import extract_access_key_id
from ministack.core.sigv4 import decode_header_value
@@ -1270,7 +1273,8 @@ def pin_signed_request(method: str, raw_path: str, query_params: dict, raw_heade
key, text = name.decode("latin-1").lower(), decode_header_value(value)
# SigV4 signs a header sent on several lines as its values joined by a bare comma.
headers[key] = f"{headers[key]},{text}" if key in headers else text
- _signed_request.set(SignedRequest(access_key_id, method, raw_path, query_params, headers, presigned=presigned))
+ _signed_request.set(SignedRequest(
+ access_key_id, method, raw_path, query_params, headers, presigned=presigned, handshake=handshake))
def _query_signed(query_params: dict) -> bool:
@@ -1291,6 +1295,25 @@ def pin_signed_body(body: bytes) -> None:
_signed_request.set(replace(request, body=body))
+def authenticate_handshake(scope: dict) -> AuthError | ResolvedCredential | None:
+ """Check a WebSocket upgrade signed in its Authorization header or query string, as ``authenticate`` does."""
+ from urllib.parse import parse_qs, quote
+
+ from ministack.core.responses import get_account_id
+
+ raw_path = scope.get("raw_path") or quote(scope.get("path", "")).encode()
+ query_params = parse_qs(scope.get("query_string", b"").decode("utf-8", "replace"), keep_blank_values=True)
+ pin_signed_request("GET", raw_path.decode("latin-1"), query_params, scope.get("headers", []), handshake=True)
+ request = _signed_request.get()
+ if request is None:
+ return None
+ try:
+ account_id = find_iam_access_key_account(request.access_key_id) or get_account_id()
+ except AmbiguousAccessKeyError:
+ account_id = get_account_id()
+ return authenticate(request.access_key_id, account_id)
+
+
def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCredential | None:
"""Check the pinned request's time, session token and signature: its credential, a failure, or None."""
from ministack.core.responses import _account_from_sts_session
@@ -1329,6 +1352,7 @@ def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCre
failure = header_signature_failure(
signature, credential.secret_access_key, request.method, request.raw_path,
request.query_params, request.headers, request.body, presigned=request.presigned,
+ explain=request.handshake,
)
return AuthError(*failure) if failure else credential
diff --git a/ministack/core/sigv4.py b/ministack/core/sigv4.py
index f05c5599..d021a327 100644
--- a/ministack/core/sigv4.py
+++ b/ministack/core/sigv4.py
@@ -285,6 +285,7 @@ def header_signature_failure(
body: bytes,
*,
presigned: bool = False,
+ explain: bool = False,
) -> tuple[str, str] | None:
"""Recompute a header (or, ``presigned``, query-string) signature; S3 signs its path as sent, other services
the normalized path encoded again."""
@@ -294,6 +295,9 @@ def header_signature_failure(
path = raw_path if signature.service == "s3" else uri_encode(_remove_dot_segments(raw_path), encode_slash=False)
payload_hash = headers.get("x-amz-content-sha256") or hashlib.sha256(body).hexdigest()
excluded = ("x-amz-signature",) if presigned else ()
+ if presigned and signature.service == "iotdevicegateway":
+ # AWS IoT signs the URL without the session token and appends the token afterwards.
+ excluded += ("x-amz-security-token",)
canonical_request = "\n".join([
method, path, build_canonical_query_string(query_params, exclude=excluded),
build_canonical_headers(headers, signature.signed_headers), signature.signed_headers, payload_hash,
@@ -307,6 +311,11 @@ def header_signature_failure(
payload_hash.startswith("STREAMING-AWS4-HMAC-SHA256-PAYLOAD")
and not _chunk_signatures_match(body, computed, signature, key)
):
+ if explain: # API Gateway names the strings it expected
+ return "SignatureDoesNotMatch", (
+ f"{SIGNATURE_MISMATCH}\n\nThe Canonical String for this request should have been\n'{canonical_request}'"
+ f"\n\nThe String-to-Sign should have been\n'{string_to_sign}'\n"
+ )
return "SignatureDoesNotMatch", SIGNATURE_MISMATCH
return None
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index d52c2068..de83b056 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -3047,16 +3047,18 @@ _WS_DENY_REASONS = {
}
-def _authorize_ws_iam(connect_arn, headers, query_params, region):
- """``(status, message)`` refusing an AWS_IAM $connect, or None; the policy check runs under AUTH=true."""
+def _authorize_ws_iam(scope, connect_arn, headers, query_params, region):
+ """``(status, message)`` refusing an AWS_IAM $connect, or None; signature and policy are checked under AUTH=true."""
from ministack.app import AUTH
- from ministack.core.iam_evaluator import AuthError, enforce
+ from ministack.core.iam_evaluator import AuthError, authenticate_handshake, enforce
from ministack.core.router import extract_access_key_id
access_key = extract_access_key_id(headers, query_params)
if not access_key:
return 403, "Missing Authentication Token"
- denied = AUTH and enforce(access_key, "execute-api:Invoke", "apigateway", region, resource_arn=connect_arn)
+ denied = AUTH and authenticate_handshake(scope)
+ if not isinstance(denied, AuthError):
+ denied = AUTH and enforce(access_key, "execute-api:Invoke", "apigateway", region, resource_arn=connect_arn)
if isinstance(denied, AuthError):
return 403, denied.message
if denied:
@@ -3195,7 +3197,7 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: str
)
elif auth_type == "AWS_IAM":
refusal = _authorize_ws_iam(
- execute_api_route_arn(owner_region, account_id, api_id, stage, "$connect"),
+ scope, execute_api_route_arn(owner_region, account_id, api_id, stage, "$connect"),
headers, query_params, owner_region,
)
elif auth_type == "JWT":
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index f22ad70c..3b1cc065 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -11603,6 +11603,25 @@ async def _feed_session(session: _WSSession, data: bytes, max_buffer: int) -> bo
return False
+def _ws_handshake_refused(scope: dict) -> bool:
+ """Under AUTH=true, whether the upgrade's SigV4 signature, time or session token fails."""
+ from ministack.app import AUTH
+ from ministack.core.iam_evaluator import AuthError, authenticate_handshake
+
+ return bool(AUTH) and isinstance(authenticate_handshake(scope), AuthError)
+
+
+async def _refuse_ws_handshake(scope: dict, send) -> None:
+ """Answer a refused upgrade with 403 and a trace id, the device gateway's answer to any credential failure."""
+ if "websocket.http.response" not in (scope.get("extensions") or {}):
+ await send({"type": "websocket.close", "code": 1008})
+ return
+ body = json.dumps({"message": "Forbidden", "traceId": str(uuid.uuid4())}, separators=(",", ":")).encode()
+ await send({"type": "websocket.http.response.start", "status": 403,
+ "headers": [(b"content-type", b"application/json")]})
+ await send({"type": "websocket.http.response.body", "body": body})
+
+
async def handle_websocket(
scope: dict, receive, send, account_id: str, region: str
) -> None:
@@ -11620,6 +11639,9 @@ async def handle_websocket(
sub_headers[name.decode("latin-1").lower()] = value.decode("utf-8")
except UnicodeDecodeError:
sub_headers[name.decode("latin-1").lower()] = value.decode("latin-1")
+ if _ws_handshake_refused(scope):
+ await _refuse_ws_handshake(scope, send)
+ return
requested = sub_headers.get("sec-websocket-protocol", "")
chosen = None
for proto in [p.strip() for p in requested.split(",") if p.strip()]:
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index 187a95aa..19eace35 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -2,6 +2,7 @@
import asyncio
import base64
+import contextlib
import io
import json
import os
@@ -15,6 +16,7 @@ import zipfile
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
+import boto3
import pytest
from botocore.exceptions import ClientError
from conftest import (
@@ -22,6 +24,7 @@ from conftest import (
ENDPOINT,
LoopProbe,
concurrent_burst,
+ make_client,
make_probe_lambda,
)
@@ -3262,6 +3265,105 @@ def test_ws_connect_aws_iam_needs_a_signed_request(apigw, lam):
assert _ws_handshake(api_id, presigned)[0] == 101
+_WS_IAM_POLICY = {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": ["execute-api:Invoke", "sts:GetSessionToken"], "Resource": "*"}]}
+
+
+def _second_access_key(user):
+ """A second access key of an ``iam_user`` user, to sign raw requests with; deleted on exit."""
+ iam = make_client("iam")
+ key = iam.create_access_key(UserName=user.name)["AccessKey"]
+ try:
+ yield key["AccessKeyId"], key["SecretAccessKey"]
+ finally:
+ iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])
+
+
+def _signed_ws_connect(host, key, secret, *, session=False, token=None, token_after=False, header=False,
+ expires=3600, skew=0, drop=""):
+ """Path and headers of a GET /prod handshake signed by botocore for execute-api."""
+ import datetime as dt
+ from unittest import mock
+ from urllib.parse import quote
+
+ import botocore.auth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ if session or token == "session":
+ credentials = boto3.client("sts", endpoint_url=ENDPOINT, aws_access_key_id=key, aws_secret_access_key=secret,
+ region_name="us-east-1").get_session_token()["Credentials"]
+ token = credentials["SessionToken"] if token == "session" else token
+ if session:
+ key, secret = credentials["AccessKeyId"], credentials["SecretAccessKey"]
+ request = AWSRequest(method="GET", url=f"http://{host}/prod")
+ signing = Credentials(key, secret, None if token_after else token)
+ signer = botocore.auth.SigV4Auth(signing, "execute-api", "us-east-1") if header else (
+ botocore.auth.SigV4QueryAuth(signing, "execute-api", "us-east-1", expires=expires))
+ now = botocore.auth.get_current_datetime() + dt.timedelta(seconds=skew)
+ with mock.patch.object(botocore.auth, "get_current_datetime", return_value=now):
+ signer.add_auth(request)
+ query = "&".join(p for p in urlparse(request.url).query.split("&") if not drop or not p.startswith(drop + "="))
+ if token_after and token:
+ query += "&X-Amz-Security-Token=" + quote(token, safe="")
+ return f"/prod?{query}" if query else "/prod", {k: v for k, v in request.headers.items() if k.lower() != "host"}
+
+
+_MISMATCH = (
+ "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key "
+ "and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request "
+ "should have been\n'GET\n/prod\n"
+)
+_INVALID_TOKEN = "The security token included in the request is invalid"
+_WS_CONNECT_CASES = { # case: (signing arguments, AWS's 403 message under AUTH=true, or None for 101)
+ "signed": ({}, None),
+ "wrong-secret": ({"secret": "wrong"}, _MISMATCH),
+ "signed-2-min-ago-expires-60": ({"skew": -120, "expires": 60}, None),
+ "signed-6-min-ago-expires-86400": ({"skew": -360, "expires": 86400}, "Signature expired: "),
+ "signed-16-min-ahead": ({"skew": 960}, "Signature not yet current: "),
+ "no-signature": ({"drop": "X-Amz-Signature"}, "AWS query-string parameters must include 'X-Amz-Signature'. "
+ "Re-examine the query-string parameters."),
+ "no-date": ({"drop": "X-Amz-Date"}, "AWS query-string parameters must include 'X-Amz-Date'. "
+ "Re-examine the query-string parameters."),
+ "header-signed": ({"header": True}, None),
+ "header-wrong-secret": ({"header": True, "secret": "wrong"}, _MISMATCH),
+ "unknown-key": ({"key": "AKIAUNKNOWNKEY000001"}, _INVALID_TOKEN + "."),
+ "session-token-signed": ({"session": True, "token": "session"}, None),
+ "session-token-appended": ({"session": True, "token": "session", "token_after": True}, _MISMATCH),
+ "session-no-token": ({"session": True}, _INVALID_TOKEN + "."),
+ "session-other-token": ({"session": True, "token": "other"}, _INVALID_TOKEN),
+ "user-key-with-token": ({"token": "session"}, _INVALID_TOKEN),
+}
+
+
[email protected]("case", list(_WS_CONNECT_CASES))
+def test_ws_connect_aws_iam_handshake_signature_contract(auth_enabled, iam_user, apigw, case):
+ """Under AUTH=true an AWS_IAM $connect verifies the handshake's signature before its policy."""
+ api_id = apigw.create_api(Name=f"ws-iam-sig-{uuid.uuid4().hex[:6]}", ProtocolType="WEBSOCKET",
+ RouteSelectionExpression="$request.body.action")["ApiId"]
+ try:
+ integration = apigw.create_integration(ApiId=api_id, IntegrationType="MOCK")["IntegrationId"]
+ apigw.create_route(ApiId=api_id, RouteKey="$connect", AuthorizationType="AWS_IAM",
+ Target=f"integrations/{integration}")
+ apigw.create_stage(ApiId=api_id, StageName="prod")
+ args, message = _WS_CONNECT_CASES[case]
+ host = f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"
+ with _second_access_key(iam_user(policy=_WS_IAM_POLICY)) as (key, secret):
+ args = {"key": key, "secret": secret, **args}
+ path, headers = _signed_ws_connect(host, args.pop("key"), args.pop("secret"), **args)
+ status, body = _ws_handshake(api_id, path, headers)
+ finally:
+ apigw.delete_api(ApiId=api_id)
+ if auth_enabled and message:
+ assert status == 403
+ assert body["message"].startswith(message) if message.endswith((" ", "\n")) else body["message"] == message
+ assert body["connectionId"] and body["requestId"]
+ else:
+ assert status == 101
+
+
@pytest.mark.parametrize("resource, message", [
({"Type": "AWS::ApiGatewayV2::Authorizer", "Properties": {
"AuthorizerType": "JWT", "Name": "jwt", "IdentitySource": ["route.request.querystring.token"],
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 69b266aa..130587b1 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -12,9 +12,11 @@ bridge layer.
from __future__ import annotations
import base64
+import contextlib
import io as _io
import json
import os
+import re
import socket
import ssl
import struct
@@ -31,7 +33,7 @@ import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
-from conftest import iot_test_ca, patch_endpoint_dns, sqs_policy_allow_sns
+from conftest import iot_test_ca, make_client, patch_endpoint_dns, sqs_policy_allow_sns
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
@@ -951,6 +953,113 @@ def test_iot_ws_same_account_publish_delivers(iot_data_client):
assert delivered_payload == payload
+_IOT_WS_POLICY = {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": ["iot:*", "sts:GetSessionToken"], "Resource": "*"}]}
+
+
+def _second_access_key(user):
+ """A second access key of an ``iam_user`` user, to sign raw requests with; deleted on exit."""
+ iam = make_client("iam")
+ key = iam.create_access_key(UserName=user.name)["AccessKey"]
+ try:
+ yield key["AccessKeyId"], key["SecretAccessKey"]
+ finally:
+ iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])
+
+
+def _iot_ws_host() -> str:
+ parsed = urlparse(ENDPOINT)
+ return f"prefix-ats.iot.us-east-1.{parsed.hostname or 'localhost'}:{parsed.port or 4566}"
+
+
+def _signed_mqtt_upgrade(key, secret, *, session=False, token=None, token_signed=False, header=False,
+ expires=3600, skew=0, extra="", drop=""):
+ """Query and headers of a GET /mqtt signed by botocore; IoT expects the session token appended afterwards."""
+ import datetime as dt
+ from unittest import mock
+
+ import botocore.auth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ if session or token == "session":
+ credentials = boto3.client("sts", endpoint_url=ENDPOINT, aws_access_key_id=key, aws_secret_access_key=secret,
+ region_name="us-east-1").get_session_token()["Credentials"]
+ token = credentials["SessionToken"] if token == "session" else token
+ if session:
+ key, secret = credentials["AccessKeyId"], credentials["SecretAccessKey"]
+ token_after = not header and not token_signed
+ request = AWSRequest(method="GET", url=f"http://{_iot_ws_host()}/mqtt")
+ signing = Credentials(key, secret, None if token_after else token)
+ signer = botocore.auth.SigV4Auth(signing, "iotdevicegateway", "us-east-1") if header else (
+ botocore.auth.SigV4QueryAuth(signing, "iotdevicegateway", "us-east-1", expires=expires))
+ now = botocore.auth.get_current_datetime() + dt.timedelta(seconds=skew)
+ with mock.patch.object(botocore.auth, "get_current_datetime", return_value=now):
+ signer.add_auth(request)
+ query = "&".join(p for p in urlparse(request.url).query.split("&") if not drop or not p.startswith(drop + "="))
+ if token_after and token:
+ query += "&X-Amz-Security-Token=" + quote(token, safe="")
+ return query + extra, {k: v for k, v in request.headers.items() if k.lower() != "host"}
+
+
+def _iot_ws_upgrade(query: str, headers: dict | None = None) -> tuple[int, str, dict]:
+ """Status, Content-Type and JSON body of an MQTT-over-WebSocket upgrade."""
+ import http.client
+
+ parsed = urlparse(ENDPOINT)
+ conn = http.client.HTTPConnection(parsed.hostname or "localhost", parsed.port or 4566, timeout=30)
+ try:
+ conn.request("GET", f"/mqtt?{query}" if query else "/mqtt", headers={
+ "Host": _iot_ws_host(), "Upgrade": "websocket", "Connection": "Upgrade",
+ "Sec-WebSocket-Key": base64.b64encode(os.urandom(16)).decode(), "Sec-WebSocket-Version": "13",
+ "Sec-WebSocket-Protocol": "mqtt", **(headers or {}),
+ })
+ resp = conn.getresponse()
+ if resp.status == 101:
+ return 101, "", {}
+ return resp.status, resp.getheader("content-type", ""), json.loads(resp.read() or b"{}")
+ finally:
+ conn.close()
+
+
+_IOT_WS_CASES = { # case: (signing arguments, refused under AUTH=true)
+ "signed": ({}, False),
+ "wrong-secret": ({"secret": "wrong"}, True),
+ "parameter-added": ({"extra": "&a=b"}, True),
+ "signed-4-min-ago": ({"skew": -240}, False),
+ "signed-6-min-ago-expires-86400": ({"skew": -360, "expires": 86400}, True),
+ "signed-6-min-ahead": ({"skew": 360}, True),
+ "no-signature": ({"drop": "X-Amz-Signature"}, True),
+ "no-date": ({"drop": "X-Amz-Date"}, True),
+ "header-signed": ({"header": True}, False),
+ "header-wrong-secret": ({"header": True, "secret": "wrong"}, True),
+ "unknown-key": ({"key": "AKIAUNKNOWNKEY000001"}, True),
+ "session-token-appended": ({"session": True, "token": "session"}, False),
+ "session-token-signed": ({"session": True, "token": "session", "token_signed": True}, True),
+ "session-no-token": ({"session": True}, True),
+ "session-other-token": ({"session": True, "token": "other"}, True),
+ "user-key-with-token": ({"token": "session"}, True),
+ "root-key-wrong-secret": ({"key": "test", "secret": "wrong"}, False),
+}
+
+
[email protected]("case", list(_IOT_WS_CASES))
+def test_iot_ws_handshake_signature_contract(auth_enabled, iam_user, case):
+ """Under AUTH=true an MQTT-over-WebSocket upgrade signed with an IAM key is verified like a request."""
+ args, refused = _IOT_WS_CASES[case]
+ with _second_access_key(iam_user(policy=_IOT_WS_POLICY)) as (key, secret):
+ args = {"key": key, "secret": secret, **args}
+ status, content_type, body = _iot_ws_upgrade(*_signed_mqtt_upgrade(args.pop("key"), args.pop("secret"),
+ **args))
+ if auth_enabled and refused:
+ assert (status, content_type, body["message"]) == (403, "application/json", "Forbidden")
+ assert re.fullmatch(r"[0-9a-f-]{36}", body["traceId"])
+ else:
+ assert status == 101
+
+
# ---------------------------------------------------------------------------
# Device Shadow (GetThingShadow / UpdateThingShadow / DeleteThingShadow)
# ---------------------------------------------------------------------------
diff --git a/tests/test_sigv4.py b/tests/test_sigv4.py
index aaafdf23..a92ba9ef 100644
--- a/tests/test_sigv4.py
+++ b/tests/test_sigv4.py
@@ -1,4 +1,5 @@
import datetime as dt
+import hashlib
import pytest
@@ -9,7 +10,9 @@ from ministack.core.sigv4 import (
build_string_to_sign,
calculate_signature,
derive_signing_key,
+ header_signature_failure,
parse_header_signature,
+ parse_query_signature,
presigned_request_is_expired,
request_time_failure,
signatures_match,
@@ -198,6 +201,60 @@ def test_parse_header_signature_takes_the_date_header_when_x_amz_date_is_absent(
"AKIAIOSFODNN7EXAMPLE", "sts", "20260930T120000Z")
+def _presigned(secret, token_signed, service="iotdevicegateway"):
+ """Query parameters of a GET /mqtt presigned for ``service``, with its session token."""
+ amz_date = "20260930T120000Z"
+ query = {"X-Amz-Algorithm": ["AWS4-HMAC-SHA256"],
+ "X-Amz-Credential": [f"ASIAEXAMPLE/20260930/us-east-1/{service}/aws4_request"],
+ "X-Amz-Date": [amz_date], "X-Amz-SignedHeaders": ["host"]}
+ if token_signed:
+ query["X-Amz-Security-Token"] = ["token/+="]
+ canonical = build_canonical_request("GET", "/mqtt", {"host": "iot.example"}, query, "host",
+ payload_hash=hashlib.sha256(b"").hexdigest())
+ string_to_sign = build_string_to_sign(amz_date, amz_date[:8], "us-east-1", service, canonical)
+ query["X-Amz-Signature"] = [calculate_signature(secret, amz_date[:8], "us-east-1", service, string_to_sign)]
+ query["X-Amz-Security-Token"] = ["token/+="]
+ return query
+
+
[email protected]("service, token_signed, expected", [
+ ("iotdevicegateway", False, None),
+ ("iotdevicegateway", True, "SignatureDoesNotMatch"),
+ ("execute-api", True, None),
+ ("execute-api", False, "SignatureDoesNotMatch"),
+])
+def test_presigned_iot_url_leaves_the_session_token_unsigned(service, token_signed, expected):
+ query = _presigned("secret", token_signed, service)
+ signature = parse_query_signature(query)
+
+ failure = header_signature_failure(signature, "secret", "GET", "/mqtt", query, {"host": "iot.example"}, b"",
+ presigned=True)
+
+ assert (failure and failure[0]) == expected
+
+
+def test_signature_failure_can_name_the_strings_it_expected():
+ query = _presigned("secret", True, "execute-api")
+ signature = parse_query_signature(query)
+
+ code, message = header_signature_failure(signature, "other", "GET", "/mqtt", query, {"host": "iot.example"}, b"",
+ presigned=True, explain=True)
+
+ canonical = (
+ "GET\n/mqtt\nX-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAEXAMPLE%2F20260930%2Fus-east-1"
+ "%2Fexecute-api%2Faws4_request&X-Amz-Date=20260930T120000Z&X-Amz-Security-Token=token%2F%2B%3D"
+ f"&X-Amz-SignedHeaders=host\nhost:iot.example\n\nhost\n{hashlib.sha256(b'').hexdigest()}"
+ )
+ string_to_sign = build_string_to_sign("20260930T120000Z", "20260930", "us-east-1", "execute-api", canonical)
+ assert code == "SignatureDoesNotMatch"
+ assert message == (
+ "The request signature we calculated does not match the signature you provided. Check your AWS Secret "
+ "Access Key and signing method. Consult the service documentation for details.\n\n"
+ f"The Canonical String for this request should have been\n'{canonical}'\n\n"
+ f"The String-to-Sign should have been\n'{string_to_sign}'\n"
+ )
+
+
@pytest.mark.parametrize(
"service, amz_date, expected",
[