Skip to content

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

fix(auth): refuse SigV4 signatures that name no access key (#2288)

iot-rocketdbbb8117f3a6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a5b09326..7729ea19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,10 +7,11 @@ 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.
+
### Fixed
-- **Cognito Identity — identities merge on a login another identity holds under `AUTH=true`** — `GetCredentialsForIdentity` and `GetOpenIdToken` answered for the calling identity when its `Logins` belonged to another identity, `GetId` returned only one of two identities holding its logins, and an identity with a login took a call that carried none of its own; with `AUTH=true` an identity without a login now gives way to the login's identity, an identity with a login takes the other identity's logins, the merged-away identity is disabled (`DescribeIdentity` and `ListIdentities` list `DISABLED`, `HideDisabled` leaves it out, calls with its old login answer for the identity it merged into) and a call with none of the identity's own logins answers `NotAuthorizedException`. Contributed by @iot-rocket.
-- **Cognito Identity — `GetId` and `GetCredentialsForIdentity` check `Logins` under `AUTH=true`** — both calls took any token in `Logins`, `GetCredentialsForIdentity` vended authenticated credentials from the stored login when the request carried none, `GetId` created a new identity for a login that already had one, and a login given to an identity without one was not kept; with `AUTH=true` both calls refuse the tokens `GetOpenIdToken` refuses with the same `NotAuthorizedException` messages (and a Google login that is no JWT), `GetCredentialsForIdentity` refuses a request without `Logins` for an identity with a login, `GetId` returns the identity that holds the login, and `GetCredentialsForIdentity` and `GetOpenIdToken` link the login to an identity that had none, as AWS does. Contributed by @iot-rocket.
-- **Cognito Identity — `GetOpenIdToken` checks `Logins` under `AUTH=true`** — the call issued a token for an identity with a login when the request carried no `Logins`, and for any token in `Logins`; with `AUTH=true` it now answers `NotAuthorizedException` as AWS does, with `Access to Identity '<identity id>' is forbidden.` without `Logins` and, for a user pool login, when the token is no ID token of a trusted app client, has a bad signature, expired more than five minutes ago or belongs to another user than the identity's login. Contributed by @iot-rocket.
+- **Auth — SigV4 signatures that name no access key are refused** — under `AUTH=true` an `AWS4-HMAC-SHA256` `Authorization` header or a presigned query string without its credential, or with an empty access key, was served as the account root; it now answers `IncompleteSignature` naming every missing part, or the unknown-key error for an empty key, in each service's code and status, and Lambda answers a part that is left out as `MissingAuthenticationTokenException`. S3, API Gateway and Lambda function URLs, which take anonymous calls, are unchanged. Contributed by @iot-rocket.
## [1.5.29] — 2026-10-17
diff --git a/ministack/app.py b/ministack/app.py
index 753199da..74c79f8d 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -93,8 +93,8 @@ 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) unless AUTH=true, which also evaluates the key's IAM
- policies per MQTT action. The point here is multi-tenancy isolation, not auth.
+ 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")
qp = parse_qs(qs, keep_blank_values=True) if qs else {}
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index e7085663..8cf1221a 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -1265,7 +1265,9 @@ def pin_signed_request(
authorization = decode_header_value(next((v for n, v in raw_headers if n.lower() == b"authorization"), b""))
presigned = not authorization.startswith("AWS4-HMAC-SHA256") and _query_signed(query_params)
access_key_id = extract_access_key_id({"authorization": authorization}, query_params if presigned else None)
- if not (authorization.startswith("AWS4-HMAC-SHA256") or presigned) or _is_root_key(access_key_id):
+ # A signature that names no key is checked too: it is incomplete or names an unknown key.
+ if not (authorization.startswith("AWS4-HMAC-SHA256") or presigned) or (
+ access_key_id and _is_root_key(access_key_id)):
_signed_request.set(None)
return
headers: dict[str, str] = {}
@@ -1284,8 +1286,7 @@ def _query_signed(query_params: dict) -> bool:
return found[0] if isinstance(found, list) else found
scope = value("X-Amz-Credential").split("/")
- return value("X-Amz-Algorithm") == "AWS4-HMAC-SHA256" and bool(scope[0]) and (
- len(scope) < 4 or scope[3] != "s3")
+ return value("X-Amz-Algorithm") == "AWS4-HMAC-SHA256" and (len(scope) < 4 or scope[3] != "s3")
def pin_signed_body(body: bytes) -> None:
@@ -1305,7 +1306,7 @@ def authenticate_handshake(scope: dict) -> AuthError | ResolvedCredential | None
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:
+ if request is None or not request.access_key_id:
return None
try:
account_id = find_iam_access_key_account(request.access_key_id) or get_account_id()
@@ -1341,7 +1342,9 @@ def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCre
token = (request.query_params.get("X-Amz-Security-Token") or [""])[0]
else:
token = request.headers.get("x-amz-security-token", "")
- credential = resolve_credential(access_key_id, _account_from_sts_session(access_key_id) or account_id, token)
+ credential = resolve_credential(
+ access_key_id, _account_from_sts_session(access_key_id) or account_id, token,
+ ) if access_key_id else _unknown_access_key()
if isinstance(credential, CredentialResolutionError):
if credential.code == "InvalidToken":
# AWS treats a session key without its token as unknown, and any other token as invalid.
@@ -1449,7 +1452,9 @@ def enforce(access_key_id: str, iam_action: str, service: str,
from ministack.core.responses import get_account_id
account_id = get_account_id()
- checked = authenticate(access_key_id or "", account_id)
+ # S3, API Gateway methods and function URLs can be called anonymously: a request naming no key is not checked.
+ anonymous_ok = service == "s3" or iam_action in ("execute-api:Invoke", "lambda:InvokeFunctionUrl")
+ checked = None if anonymous_ok and not access_key_id else authenticate(access_key_id or "", account_id)
if isinstance(checked, AuthError):
return checked
diff --git a/ministack/core/sigv4.py b/ministack/core/sigv4.py
index d021a327..fcc12415 100644
--- a/ministack/core/sigv4.py
+++ b/ministack/core/sigv4.py
@@ -170,20 +170,17 @@ def _incomplete(authorization: str, reason: str, code: str = "IncompleteSignatur
return code, f"{reason} (Hashed with SHA-256 and encoded with Base64) Authorization={digest}"
+def _missing_parts(values: Mapping[str, Any], names: tuple[str, ...]) -> tuple[list[str], str]:
+ """The names without a value, and the code: MissingAuthorizationParameter when one is left out entirely."""
+ missing = [name for name in names if not values.get(name)]
+ absent = any(name not in values for name in missing)
+ return missing, "MissingAuthorizationParameter" if absent else "IncompleteSignature"
+
+
def parse_header_signature(headers: Mapping[str, Any]) -> HeaderSignature | tuple[str, str]:
- """Split a header signature into its parts, or name the part that is missing."""
+ """Split a header signature into its parts, or name every part that is missing."""
authorization = headers.get("authorization", "")
fields = dict(part.strip().partition("=")[::2] for part in authorization.split(" ", 1)[-1].split(","))
- for name in ("Credential", "SignedHeaders", "Signature"):
- if not fields.get(name):
- return _incomplete(
- authorization, f"Authorization header requires '{name}' parameter.", "MissingAuthorizationParameter")
- scope = fields["Credential"].split("/")
- if len(scope) != 5:
- return "IncompleteSignature", (
- "Credential must have exactly 5 slash-delimited elements, e.g. keyid/date/region/service/term, "
- f"got '{fields['Credential']}'"
- )
amz_date = headers.get("x-amz-date", "")
if not amz_date and headers.get("date"):
try:
@@ -191,10 +188,19 @@ def parse_header_signature(headers: Mapping[str, Any]) -> HeaderSignature | tupl
amz_date = signed_at.strftime("%Y%m%dT%H%M%SZ")
except (TypeError, ValueError):
pass
- if not amz_date:
- return _incomplete(
- authorization, "Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header."
+ no_date = "Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header."
+ missing, code = _missing_parts(fields, ("Credential", "Signature", "SignedHeaders"))
+ if missing:
+ reasons = [f"Authorization header requires '{name}' parameter." for name in missing]
+ return _incomplete(authorization, " ".join(reasons + ([] if amz_date else [no_date])), code)
+ scope = fields["Credential"].split("/")
+ if len(scope) != 5:
+ return "IncompleteSignature", (
+ "Credential must have exactly 5 slash-delimited elements, e.g. keyid/date/region/service/term, "
+ f"got '{fields['Credential']}'"
)
+ if not amz_date:
+ return _incomplete(authorization, no_date)
return HeaderSignature(*scope[:4], fields["SignedHeaders"], fields["Signature"], amz_date)
@@ -204,12 +210,16 @@ def _query_value(query_params: Mapping[str, Any], name: str) -> str:
def parse_query_signature(query_params: Mapping[str, Any]) -> HeaderSignature | tuple[str, str]:
- """Split a query-string (presigned) signature into its parts, or name the part that is missing."""
+ """Split a query-string (presigned) signature into its parts, or name every part that is missing."""
+ names = ("X-Amz-Credential", "X-Amz-Signature", "X-Amz-SignedHeaders", "X-Amz-Date")
+ missing, code = _missing_parts(
+ {name: _query_value(query_params, name) for name in names
+ if name in query_params or name.lower() in query_params}, names)
+ if missing:
+ return code, " ".join(
+ [f"AWS query-string parameters must include '{name}'." for name in missing]
+ + ["Re-examine the query-string parameters."])
credential = _query_value(query_params, "X-Amz-Credential")
- for name in ("X-Amz-Signature", "X-Amz-SignedHeaders", "X-Amz-Date"):
- if not _query_value(query_params, name):
- return "IncompleteSignature", (
- f"AWS query-string parameters must include '{name}'. Re-examine the query-string parameters.")
scope = credential.split("/")
if len(scope) != 5:
return "IncompleteSignature", (
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 5d677721..e9bc3c18 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -11673,12 +11673,12 @@ async def _feed_session(session: _WSSession, data: bytes, max_buffer: int) -> bo
return False
-def _ws_handshake_check(scope: dict) -> AuthError | ResolvedCredential | None:
- """Under AUTH=true, the upgrade's verified IAM credential or the ``AuthError`` refusing it; else None."""
+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 authenticate_handshake
+ from ministack.core.iam_evaluator import AuthError, authenticate_handshake
- return authenticate_handshake(scope) if AUTH else None
+ return bool(AUTH) and isinstance(authenticate_handshake(scope), AuthError)
async def _refuse_ws_handshake(scope: dict, send) -> None:
@@ -11709,8 +11709,7 @@ 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")
- checked = _ws_handshake_check(scope)
- if isinstance(checked, AuthError):
+ if _ws_handshake_refused(scope):
await _refuse_ws_handshake(scope, send)
return
requested = sub_headers.get("sec-websocket-protocol", "")
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index 05df6824..861885f1 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -876,6 +876,29 @@ def test_dynamodb_list_tables(ddb):
resp2 = ddb.list_tables(ExclusiveStartTableName=resp["LastEvaluatedTableName"], Limit=100)
assert len(resp2["TableNames"]) >= 1
+
+def test_dynamodb_list_tables_header_without_credential_contract(auth_enabled, iam_user):
+ """Under AUTH=true a header signature without Credential answers IncompleteSignatureException."""
+ client = iam_user(policy={"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "dynamodb:ListTables", "Resource": "*"}]}).client("dynamodb")
+ client.list_tables(Limit=1)
+
+ def strip_credential(request, **_):
+ algorithm, _, fields = request.headers["Authorization"].partition(b" ")
+ request.headers["Authorization"] = algorithm + b" " + fields.partition(b", ")[2]
+
+ client.meta.events.register_first("before-send", strip_credential)
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ client.list_tables(Limit=1)
+ response = exc.value.response
+ assert (response["Error"]["Code"], response["ResponseMetadata"]["HTTPStatusCode"]) == (
+ "IncompleteSignatureException", 400)
+ assert response["Error"]["Message"].startswith("Authorization header requires 'Credential' parameter.")
+ else:
+ assert "TableNames" in client.list_tables(Limit=1)
+
def test_dynamodb_put_get_item(ddb):
ddb.put_item(
TableName="t_hash_only",
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index d501deb5..8852349c 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -1144,6 +1144,32 @@ def test_lambda_list_functions(lam):
names = [f["FunctionName"] for f in _list_all_functions(lam)]
assert "lam-create-test" in names
+
[email protected]("credential, code, message", [
+ (b"", "MissingAuthenticationTokenException", "Missing Authentication Token"),
+ (b"Credential=, ", "IncompleteSignatureException", "Authorization header requires 'Credential' parameter."),
+], ids=["left-out", "empty"])
+def test_lambda_list_functions_header_without_credential_contract(auth_enabled, iam_user, credential, code, message):
+ """Under AUTH=true Lambda answers a header without Credential as unauthenticated, an empty one as incomplete."""
+ client = iam_user(policy={"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "lambda:ListFunctions", "Resource": "*"}]}).client("lambda")
+ client.list_functions(MaxItems=1)
+
+ def replace_credential(request, **_):
+ algorithm, _, fields = request.headers["Authorization"].partition(b" ")
+ request.headers["Authorization"] = algorithm + b" " + credential + fields.partition(b", ")[2]
+
+ client.meta.events.register_first("before-send", replace_credential)
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ client.list_functions(MaxItems=1)
+ response = exc.value.response
+ assert (response["Error"]["Code"], response["ResponseMetadata"]["HTTPStatusCode"]) == (code, 403)
+ assert response["Error"]["Message"].startswith(message)
+ else:
+ assert "Functions" in client.list_functions(MaxItems=1)
+
def test_lambda_delete_function(lam):
lam.create_function(
FunctionName="lam-to-delete",
diff --git a/tests/test_sigv4.py b/tests/test_sigv4.py
index a92ba9ef..c0bc049a 100644
--- a/tests/test_sigv4.py
+++ b/tests/test_sigv4.py
@@ -181,6 +181,25 @@ _SCOPE = "AKIAIOSFODNN7EXAMPLE/20260930/eu-central-1/sts/aws4_request"
"Credential must have exactly 5 slash-delimited elements, e.g. keyid/date/region/service/term, "
"got 'AKIAIOSFODNN7EXAMPLE/eu-central-1/sts/aws4_request'",
),
+ (
+ "AWS4-HMAC-SHA256 SignedHeaders=host;x-amz-date, Signature=abc",
+ "MissingAuthorizationParameter",
+ "Authorization header requires 'Credential' parameter. (Hashed with SHA-256 and encoded with Base64) "
+ "Authorization=ahJcBrcKAe4SBJto5I/CIJQro+xeLn5ihFrmUmERRpY=",
+ ),
+ (
+ "AWS4-HMAC-SHA256 Credential=, SignedHeaders=host;x-amz-date, Signature=abc",
+ "IncompleteSignature",
+ "Authorization header requires 'Credential' parameter. (Hashed with SHA-256 and encoded with Base64) "
+ "Authorization=Rso9P5e0/U0V+vZQW+PsjFTI/EYgUn2YbmHes/SFYPA=",
+ ),
+ (
+ "AWS4-HMAC-SHA256",
+ "MissingAuthorizationParameter",
+ "Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' "
+ "parameter. Authorization header requires 'SignedHeaders' parameter. (Hashed with SHA-256 and encoded "
+ "with Base64) Authorization=YI2YWea8FSxnksZL2ETHbs5elHm9HQufxTLK0W0ffV0=",
+ ),
],
)
def test_parse_header_signature_names_the_missing_part_as_aws_does(authorization, code, message):
@@ -201,6 +220,33 @@ def test_parse_header_signature_takes_the_date_header_when_x_amz_date_is_absent(
"AKIAIOSFODNN7EXAMPLE", "sts", "20260930T120000Z")
+def test_parse_header_signature_names_a_missing_date_with_the_missing_parameters():
+ headers = {"authorization": "AWS4-HMAC-SHA256 SignedHeaders=host, Signature=abc"}
+
+ assert parse_header_signature(headers) == (
+ "MissingAuthorizationParameter",
+ "Authorization header requires 'Credential' parameter. Authorization header requires existence of either "
+ "a 'X-Amz-Date' or a 'Date' header. (Hashed with SHA-256 and encoded with Base64) "
+ "Authorization=QtbsE59+Cww86WuNzDL08sE4JUxLk21/H/rRcBdVXrQ=",
+ )
+
+
[email protected]("query, code, missing", [
+ ({"X-Amz-Algorithm": ["AWS4-HMAC-SHA256"], "X-Amz-Date": ["20260930T120000Z"],
+ "X-Amz-SignedHeaders": ["host"], "X-Amz-Signature": ["abc"]},
+ "MissingAuthorizationParameter", ["X-Amz-Credential"]),
+ ({"X-Amz-Algorithm": ["AWS4-HMAC-SHA256"], "X-Amz-Credential": [""], "X-Amz-Date": ["20260930T120000Z"],
+ "X-Amz-SignedHeaders": ["host"], "X-Amz-Signature": ["abc"]},
+ "IncompleteSignature", ["X-Amz-Credential"]),
+ ({"X-Amz-Algorithm": ["AWS4-HMAC-SHA256"]},
+ "MissingAuthorizationParameter", ["X-Amz-Credential", "X-Amz-Signature", "X-Amz-SignedHeaders", "X-Amz-Date"]),
+], ids=["no-credential", "empty-credential", "only-algorithm"])
+def test_parse_query_signature_names_every_missing_parameter(query, code, missing):
+ assert parse_query_signature(query) == (code, " ".join(
+ [f"AWS query-string parameters must include '{name}'." for name in missing]
+ + ["Re-examine the query-string parameters."]))
+
+
def _presigned(secret, token_signed, service="iotdevicegateway"):
"""Query parameters of a GET /mqtt presigned for ``service``, with its session token."""
amz_date = "20260930T120000Z"
diff --git a/tests/test_sqs.py b/tests/test_sqs.py
index d9497618..c8df8615 100644
--- a/tests/test_sqs.py
+++ b/tests/test_sqs.py
@@ -88,6 +88,29 @@ def test_sqs_list_queues(sqs):
assert any("intg-sqs-list-alpha" in u for u in urls)
assert any("intg-sqs-list-beta" in u for u in urls)
+
+def test_sqs_list_queues_header_without_credential_contract(auth_enabled, iam_user):
+ """Under AUTH=true a header signature without Credential answers IncompleteSignature."""
+ client = iam_user(policy={"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "sqs:ListQueues", "Resource": "*"}]}).client("sqs")
+ client.list_queues(QueueNamePrefix="intg-sqs-nocred-")
+
+ def strip_credential(request, **_):
+ algorithm, _, fields = request.headers["Authorization"].partition(b" ")
+ request.headers["Authorization"] = algorithm + b" " + fields.partition(b", ")[2]
+
+ client.meta.events.register_first("before-send", strip_credential)
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ client.list_queues(QueueNamePrefix="intg-sqs-nocred-")
+ response = exc.value.response
+ assert (response["Error"]["Code"], response["ResponseMetadata"]["HTTPStatusCode"]) == (
+ "IncompleteSignature", 400)
+ assert response["Error"]["Message"].startswith("Authorization header requires 'Credential' parameter.")
+ else:
+ client.list_queues(QueueNamePrefix="intg-sqs-nocred-")
+
def test_sqs_list_queues_paginates_with_max_results(sqs):
prefix = f"intg-sqs-page-{_uuid_mod.uuid4().hex[:8]}-"
for i in range(5):
diff --git a/tests/test_sts.py b/tests/test_sts.py
index 1b3b5cb9..a1bb77bc 100644
--- a/tests/test_sts.py
+++ b/tests/test_sts.py
@@ -1,6 +1,7 @@
import contextlib
import json
import os
+import re
import pytest
from botocore.exceptions import ClientError
@@ -1017,6 +1018,68 @@ def test_sts_get_caller_identity_json_protocol_resolves_iam_user(iam):
assert data["UserId"]
+def _strip_credential(request, **_):
+ """Send the signed Authorization header without its Credential part."""
+ algorithm, _, fields = request.headers["Authorization"].partition(b" ")
+ request.headers["Authorization"] = algorithm + b" " + fields.partition(b", ")[2]
+
+
+def _empty_credential_key(request, **_):
+ """Send the signed Authorization header with the access key cut out of its Credential."""
+ algorithm, _, fields = request.headers["Authorization"].partition(b" ")
+ request.headers["Authorization"] = algorithm + b" Credential=/" + fields.split(b"/", 1)[1]
+
+
[email protected]("edit, code, status, message", [
+ (_strip_credential, "IncompleteSignature", 400,
+ "Authorization header requires 'Credential' parameter. (Hashed with SHA-256 and encoded with Base64) "),
+ (_empty_credential_key, "InvalidClientTokenId", 403, "The security token included in the request is invalid."),
+], ids=["no-credential", "empty-key"])
+def test_sts_header_signature_without_access_key_contract(auth_enabled, iam_user, edit, code, status, message):
+ """Under AUTH=true a header signature that names no access key is refused, not served as the root."""
+ user = iam_user()
+ client = user.client("sts")
+ assert client.get_caller_identity()["Arn"] == user.arn
+ client.meta.events.register_first("before-send", edit)
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ client.get_caller_identity()
+ response = exc.value.response
+ assert (response["Error"]["Code"], response["ResponseMetadata"]["HTTPStatusCode"]) == (code, status)
+ assert response["Error"]["Message"].startswith(message)
+ else:
+ assert client.get_caller_identity()["Arn"].endswith(":root")
+
+
+def test_sts_presigned_url_without_credential_contract(auth_enabled, iam_user):
+ """Under AUTH=true a presigned URL without X-Amz-Credential answers IncompleteSignature."""
+ import html
+ import urllib.error
+ import urllib.request
+
+ def post(url):
+ # botocore presigns a Query API call as a POST, as AWS checks it.
+ try:
+ with urllib.request.urlopen(urllib.request.Request(url, data=b"", method="POST"), timeout=10) as response:
+ return response.status, response.read().decode()
+ except urllib.error.HTTPError as err:
+ return err.code, err.read().decode()
+
+ url = iam_user().client("sts").generate_presigned_url("get_caller_identity", ExpiresIn=300)
+ assert post(url)[0] == 200
+ status, body = post(re.sub(r"X-Amz-Credential=[^&]*&", "", url))
+ if auth_enabled:
+ assert status == 400
+ assert "<Code>IncompleteSignature</Code>" in body
+ assert ("AWS query-string parameters must include 'X-Amz-Credential'. "
+ "Re-examine the query-string parameters.") in html.unescape(body)
+ else:
+ assert status == 200
+ assert ":root</Arn>" in body
+
+
@pytest.mark.parametrize("auth_enabled", [False, True])
@pytest.mark.parametrize("credential_kind", ["unknown", "inactive"])
def test_sts_get_caller_identity_credential_rejections_require_auth(