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(auth): verify SigV4a signatures under AUTH=true (#2388)
iot-rocket12fc00bf18d1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 278aa712..103cf0f4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **Auth — SigV4a signatures are verified under `AUTH=true`** — requests signed with `AWS4-ECDSA-P256-SHA256`, which SDKs use for Multi-Region Access Points, were refused for every IAM user. Header and presigned S3 signatures are now checked with the P-256 key SigV4a derives from the secret, with their date or expiry, and an `X-Amz-Region-Set` that leaves out the serving region is refused (`RegionSetMismatch` on S3, the unknown-key error elsewhere). Contributed by @iot-rocket.+### Fixed- **S3 — Multi-Region Access Point requests are authorized** — under `AUTH=true`, requests through an MRAP hostname were served without an IAM check. They are now authorized on the member bucket and then on the MRAP, whose policy is evaluated like a bucket policy, and answer `AccessDenied` naming the resource that refused them. Contributed by @iot-rocket.- **Cognito — signing keys, managed login and federated users** — every user pool signed with one shared key (`kid` `ministack-key-1`); each pool now has two keys of its own, one for access tokens and one for ID tokens, both published at its JWKS URI, and a token verifies only against its own pool. Managed login refuses PKCE `plain` and a `code_challenge` without `S256` (`error=invalid_request`), any `redirect_uri` the client didn't register, also for a client with no callback URLs, and a `grant_type` other than `authorization_code`, `refresh_token` or `client_credentials` (400 `unsupported_grant_type`). Adding an identity provider creates the group `<user pool id>_<provider name>`, and a federated user's new profile joins it and carries its `identities`, so the ID token has both claims. Reported by @cupidchan.diff --git a/ministack/app.py b/ministack/app.pyindex 92b9781c..27c854bf 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2247,15 +2247,13 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dreturn errormrap_bucket = _resolve_mrap_host(host)if mrap_bucket:- # SigV4A (`AWS4-ECDSA-P256-SHA256`) is what S3 requires for an MRAP and- # what MiniStack does not implement: verifying it means ECDSA P-256 key- # derivation, and the emulator does not verify header-signed SigV4- # requests either. So the presign parameters are dropped and the request- # is served unverified rather than rejected for a signature that could- # never have matched. A plain SigV4 presign is left alone and still- # verifies.+ # SigV4A (`AWS4-ECDSA-P256-SHA256`) is what S3 requires for an MRAP.+ # Under AUTH=true its signature is verified with the request's other+ # credentials. Otherwise the presign parameters are dropped and the+ # request is served unverified, as header-signed requests are. A plain+ # SigV4 presign is left alone and still verifies.algorithm = (query_params.get("X-Amz-Algorithm") or [""])[0]- if "ECDSA" in str(algorithm).upper():+ if "ECDSA" in str(algorithm).upper() and not AUTH:query_params = {k: v for k, v in query_params.items()if not k.lower().startswith("x-amz-")diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 4223250b..8d1b507a 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -2109,6 +2109,10 @@ _AUTH_FAILURES: dict[str, tuple[str, int, str, tuple[str, int, str]]] = {"SignatureDoesNotMatch", 403, "InvalidSignatureException",("RequestTimeTooSkewed", 403, "The difference between the request time and the current time is too large."),),+ "RequestExpired": (+ "SignatureDoesNotMatch", 403, "InvalidSignatureException",+ ("AccessDenied", 403, "Request has expired"),+ ),"IncompleteSignature": _INCOMPLETE,"MissingAuthorizationParameter": _INCOMPLETE,"UnsupportedSignature": (diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex 02664f70..fa7b4473 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -1282,11 +1282,14 @@ def pin_signed_request(_verified_key.set("")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)+ payload_hash = decode_header_value(next((v for n, v in raw_headers if n.lower() == b"x-amz-content-sha256"), b""))+ presigned = not authorization.startswith("AWS4-HMAC-SHA256") and (+ _query_signed(query_params) or _sigv4a_s3_presign(query_params))access_key_id = extract_access_key_id({"authorization": authorization}, query_params if presigned else None)# The key the policy check will use; it must be the one the signature is checked for.claimed = extract_access_key_id({"authorization": authorization}, query_params)- verifiable = (authorization.startswith("AWS4-HMAC-SHA256") or presigned) and bool(claimed) and access_key_id == claimed+ header_signed = authorization.startswith("AWS4-HMAC-SHA256") or _sigv4a_header(authorization, payload_hash)+ verifiable = (header_signed or presigned) and bool(claimed) and access_key_id == claimedsigv2 = authorization.startswith("AWS ") or bool(_query_value(query_params or {}, "AWSAccessKeyId") and _query_value(query_params or {}, "Signature")and not _query_value(query_params or {}, "SignatureVersion"))@@ -1386,6 +1389,25 @@ def _s3_presigned_query(query_params: dict) -> bool:and len(scope) == 5 and scope[3] == "s3" and bool(_query_value(query_params, "X-Amz-Signature")))+def _sigv4a_header(authorization: str, payload_hash: str) -> bool:+ """A SigV4a header signature that signs its region set and does not sign its body in chunks."""+ from ministack.core.sigv4 import SIGV4A++ if not authorization.startswith(SIGV4A + " "):+ return False+ fields = dict(part.strip().partition("=")[::2] for part in authorization.split(" ", 1)[1].split(","))+ return ("x-amz-region-set" in fields.get("SignedHeaders", "").split(";")+ and not payload_hash.startswith("STREAMING-AWS4-ECDSA"))+++def _sigv4a_s3_presign(query_params: dict) -> bool:+ """A SigV4a presigned S3 URL; the S3 handler checks only SigV4 ones itself."""+ from ministack.core.sigv4 import SIGV4A++ scope = _query_value(query_params or {}, "X-Amz-Credential").split("/")+ return _query_value(query_params or {}, "X-Amz-Algorithm") == SIGV4A and len(scope) == 4 and scope[2] == "s3"++def _query_signed(query_params: dict) -> bool:"""A SigV4 query-string signature; S3 checks its own presigned URLs."""def value(name):@@ -1424,11 +1446,13 @@ def authenticate_handshake(scope: dict) -> AuthError | ResolvedCredential | Nonedef 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+ from ministack.core.responses import _account_from_sts_session, get_regionfrom ministack.core.sigv4 import (header_signature_failure,parse_header_signature,parse_query_signature,+ presigned_request_is_expired,+ region_set_covers,request_time_failure,)@@ -1446,9 +1470,24 @@ def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCresignature = parse_header_signature(request.headers)if isinstance(signature, tuple):return AuthError(*signature)- skewed = request_time_failure(signature)- if skewed:- return AuthError(*skewed)+ if request.presigned and signature.region_set is not None:+ # A SigV4a presigned URL is good until its X-Amz-Expires, however long ago it was signed.+ expires = _query_value(request.query_params, "X-Amz-Expires")+ try:+ expired = bool(expires) and presigned_request_is_expired(signature.amz_date, expires)+ except ValueError:+ expired = True+ if expired:+ return AuthError("RequestExpired", "Request has expired")+ else:+ skewed = request_time_failure(signature)+ if skewed:+ return AuthError(*skewed)+ if signature.region_set is not None and signature.service != "s3" and not region_set_covers(+ signature.region_set, get_region()):+ # A region set without the region serving the request is refused like an unknown key; S3 checks its own.+ unknown = _unknown_access_key()+ return AuthError(unknown.code, unknown.message)if request.presigned:token = (request.query_params.get("X-Amz-Security-Token") or [""])[0]else:diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 6de98991..a90c67ff 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -1446,12 +1446,19 @@ def extract_region(headers: dict, query_params=None) -> str:return extract_signed_region(headers, query_params) or os.environ.get("MINISTACK_REGION", "us-east-1")+def _sigv4a_verified() -> bool:+ """SigV4a header signatures name their key only where they are verified, under AUTH=true."""+ from ministack.app import AUTH++ return AUTH++def extract_access_key_id(headers: dict, query_params=None) -> str:"""Extract the AWS access key ID from the Authorization header, or from thequery-string credentials of a presigned URL — SigV4 ``X-Amz-Credential`` orSigV2 ``AWSAccessKeyId``."""auth = headers.get("authorization", "")- if auth.startswith("AWS4-HMAC"):+ if auth.startswith("AWS4-HMAC") or (auth.startswith("AWS4-ECDSA-P256-SHA256") and _sigv4a_verified()):match = re.search(r"Credential=([^/]+)/", auth)if match:return match.group(1)diff --git a/ministack/core/sigv4.py b/ministack/core/sigv4.pyindex e19b82fe..747f89e5 100644--- a/ministack/core/sigv4.py+++ b/ministack/core/sigv4.py@@ -7,6 +7,7 @@ mapping verification failures to service-specific responses.import base64import datetime as dt+import fnmatchimport functoolsimport hashlibimport hmac@@ -17,6 +18,9 @@ from typing import Anyfrom urllib.parse import quoteUNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"+SIGV4A = "AWS4-ECDSA-P256-SHA256"+# The order of the P-256 group, which bounds a SigV4a private key.+_P256_ORDER = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551def decode_header_value(value: bytes) -> str:@@ -125,6 +129,39 @@ def calculate_signature(return hmac.new(signing_key, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()[email protected]_cache(maxsize=256)+def sigv4a_signing_key(access_key_id: str, secret: str):+ """The ECDSA P-256 private key SigV4a derives from an access key and its secret."""+ from cryptography.hazmat.primitives.asymmetric import ec++ for counter in range(1, 255):+ label = b"\x00\x00\x00\x01" + SIGV4A.encode() + b"\x00" + access_key_id.encode("utf-8") + bytes([counter])+ digest = hmac.new(("AWS4A" + secret).encode("utf-8"), label + b"\x00\x00\x01\x00", hashlib.sha256).digest()+ candidate = int.from_bytes(digest, "big")+ if candidate <= _P256_ORDER - 2:+ return ec.derive_private_key(candidate + 1, ec.SECP256R1())+ raise ValueError("no SigV4a key for this secret")+++def sigv4a_signature_matches(access_key_id: str, secret: str, string_to_sign: str, signature: str) -> bool:+ """Whether a hex DER ECDSA signature signs the string with the key SigV4a derives."""+ from cryptography.exceptions import InvalidSignature+ from cryptography.hazmat.primitives import hashes+ from cryptography.hazmat.primitives.asymmetric import ec++ try:+ sigv4a_signing_key(access_key_id, secret).public_key().verify(+ bytes.fromhex(signature), string_to_sign.encode("utf-8"), ec.ECDSA(hashes.SHA256()))+ except (InvalidSignature, ValueError):+ return False+ return True+++def region_set_covers(region_set: str, region: str) -> bool:+ """Whether a SigV4a region set, a comma-separated list that may use ``*``, names the region."""+ return any(fnmatch.fnmatchcase(region, entry.strip()) for entry in region_set.split(","))++def presigned_request_is_expired(amz_date: str,expires: str | int,@@ -163,6 +200,8 @@ class HeaderSignature:signed_headers: strsignature: stramz_date: str+ # The X-Amz-Region-Set of a SigV4a signature, whose scope names no region.+ region_set: str | None = Nonedef _incomplete(authorization: str, reason: str, code: str = "IncompleteSignature") -> tuple[str, str]:@@ -194,13 +233,17 @@ def parse_header_signature(headers: Mapping[str, Any]) -> HeaderSignature | tuplreasons = [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:+ sigv4a = authorization.startswith(SIGV4A) and len(scope) == 4+ if len(scope) != 5 and not sigv4a: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)+ if sigv4a:+ return HeaderSignature(scope[0], scope[1], "", scope[2], fields["SignedHeaders"], fields["Signature"],+ amz_date, headers.get("x-amz-region-set", ""))return HeaderSignature(*scope[:4], fields["SignedHeaders"], fields["Signature"], amz_date)@@ -245,6 +288,10 @@ def parse_query_signature(query_params: Mapping[str, Any]) -> HeaderSignature |+ ["Re-examine the query-string parameters."])credential = _query_value(query_params, "X-Amz-Credential")scope = credential.split("/")+ if _query_value(query_params, "X-Amz-Algorithm") == SIGV4A and len(scope) == 4:+ return HeaderSignature(scope[0], scope[1], "", scope[2], _query_value(query_params, "X-Amz-SignedHeaders"),+ _query_value(query_params, "X-Amz-Signature"), _query_value(query_params, "X-Amz-Date"),+ _query_value(query_params, "X-Amz-Region-Set"))if len(scope) != 5:return "IncompleteSignature", ("Credential must have exactly 5 slash-delimited elements, e.g. keyid/date/region/service/term, "@@ -322,6 +369,8 @@ def header_signing_documents("""The canonical request and string to sign, also used in S3 signature errors."""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()+ if presigned and signature.service == "s3":+ payload_hash = UNSIGNED_PAYLOAD # an S3 presign does not sign its bodyexcluded = ("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.@@ -330,9 +379,15 @@ def header_signing_documents(method, path, build_canonical_query_string(query_params, exclude=excluded),build_canonical_headers(headers, signature.signed_headers), signature.signed_headers, payload_hash,])- string_to_sign = build_string_to_sign(- signature.amz_date, signature.date_stamp, signature.region, signature.service, canonical_request- )+ if signature.region_set is not None:+ string_to_sign = "\n".join([+ SIGV4A, signature.amz_date, f"{signature.date_stamp}/{signature.service}/aws4_request",+ hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(),+ ])+ else:+ string_to_sign = build_string_to_sign(+ signature.amz_date, signature.date_stamp, signature.region, signature.service, canonical_request+ )return canonical_request, string_to_sign@@ -359,12 +414,16 @@ def header_signature_failure(# Only an explicit streaming marker requires chunk verification; an absent# header's body hash was already computed in header_signing_documents.payload_hash = headers.get("x-amz-content-sha256") or ""- key = _cached_signing_key(secret, signature.date_stamp, signature.region, signature.service)- computed = hmac.new(key, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()- if not signatures_match(computed, signature.signature) or (- payload_hash.startswith("STREAMING-AWS4-HMAC-SHA256-PAYLOAD")- and not _chunk_signatures_match(body, computed, signature, key)- ):+ if signature.region_set is not None:+ matched = sigv4a_signature_matches(signature.access_key_id, secret, string_to_sign, signature.signature)+ else:+ key = _cached_signing_key(secret, signature.date_stamp, signature.region, signature.service)+ computed = hmac.new(key, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()+ matched = signatures_match(computed, signature.signature) and not (+ payload_hash.startswith("STREAMING-AWS4-HMAC-SHA256-PAYLOAD")+ and not _chunk_signatures_match(body, computed, signature, key)+ )+ if not matched:if explain: # API Gateway names the strings it expectedreturn "SignatureDoesNotMatch", (f"{SIGNATURE_MISMATCH}\n\nThe Canonical String for this request should have been\n'{canonical_request}'"diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex b89252b3..2a7c6b9b 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -1292,6 +1292,26 @@ def _check_bucket_region(method: str, bucket: str, key: str, headers: dict, querreturn region_mismatch_error(method, bucket, key, headers, query_params, signed, home)+def _region_set_mismatch(bucket: str, key: str, headers: dict, query_params: dict, home: str | None = None):+ """Under AUTH=true, refuse a SigV4a request whose region set leaves out the bucket's (or access point's) region."""+ from ministack.app import AUTH+ from ministack.core.sigv4 import SIGV4A, region_set_covers++ if not AUTH or not bucket:+ return None+ if headers.get("authorization", "").startswith(SIGV4A):+ region_set = headers.get("x-amz-region-set", "")+ elif (_qp(query_params, "X-Amz-Algorithm", "") or _qp(query_params, "x-amz-algorithm", "")) == SIGV4A:+ region_set = _qp(query_params, "X-Amz-Region-Set", "") or _qp(query_params, "x-amz-region-set", "")+ else:+ return None+ home = home or bucket_region(bucket)+ if home is None or region_set_covers(region_set, home):+ return None+ return _error("RegionSetMismatch", "The provided X-Amz-Region-Set doesn't match against the requested S3 region.",+ 400, f"/{bucket}/{key}" if key else f"/{bucket}")++def region_mismatch_error(method: str, bucket: str, key: str, headers: dict, query_params: dict,signed: str, home: str) -> tuple:"""The response to a request signed for ``signed`` that belongs to ``home``."""@@ -2468,6 +2488,8 @@ async def handle_request(return denieddenied = _apply_bucket_scope(method, bucket, key, headers, query_params, body, internal)+ if denied is None:+ denied = _region_set_mismatch(bucket, key, headers, query_params, home=access_point_region)if denied is None and enforce_bucket_region:# After the scope is pinned, so the owner's record names the home region.denied = _check_bucket_region(method, bucket, key, headers, query_params, home=access_point_region)diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex fd6a058c..2e0cd3d2 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -6367,3 +6367,123 @@ def test_s3_sigv2_signatures_are_verified_contract(auth_enabled, iam_user):finally:admin.delete_object(Bucket=bucket, Key="k")admin.delete_bucket(Bucket=bucket)+++def _sigv4a_request(credentials, method, url, service, region_set, *, host=None, body=b"", headers=None,+ presign=False, signed_at=None):+ """Send a SigV4a-signed request: botocore builds the canonical request, the key is the one SigV4a derives."""+ import datetime as dt+ from unittest import mock+ from urllib.parse import quote++ import requests+ from botocore.auth import S3SigV4Auth, S3SigV4QueryAuth, SigV4Auth+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials+ from cryptography.hazmat.primitives import hashes+ from cryptography.hazmat.primitives.asymmetric import ec++ from ministack.core.sigv4 import SIGV4A, sigv4a_signing_key++ base = (S3SigV4QueryAuth if presign else S3SigV4Auth) if service == "s3" else SigV4Auth++ class SigV4aAuth(base):+ def _modify_request_before_signing(self, request):+ if not presign:+ request.headers["X-Amz-Region-Set"] = region_set+ super()._modify_request_before_signing(request)+ if presign:+ request.url = (request.url.replace("X-Amz-Algorithm=AWS4-HMAC-SHA256", f"X-Amz-Algorithm={SIGV4A}")+ + f"&X-Amz-Region-Set={quote(region_set, safe='')}")++ def scope(self, request):+ return f"{self.credentials.access_key}/{self.credential_scope(request)}"++ def credential_scope(self, request):+ return f"{request.context['timestamp'][:8]}/{self._service_name}/aws4_request"++ def string_to_sign(self, request, canonical_request):+ return SIGV4A + super().string_to_sign(request, canonical_request).removeprefix("AWS4-HMAC-SHA256")++ def signature(self, string_to_sign, request):+ key = sigv4a_signing_key(self.credentials.access_key, self.credentials.secret_key)+ return key.sign(string_to_sign.encode(), ec.ECDSA(hashes.SHA256())).hex()++ def _inject_signature_to_request(self, request, signature):+ super()._inject_signature_to_request(request, signature)+ if not presign:+ authorization = request.headers["Authorization"].replace("AWS4-HMAC-SHA256", SIGV4A, 1)+ del request.headers["Authorization"]+ request.headers["Authorization"] = authorization++ request = AWSRequest(method, url, data=body, headers={**({"host": host} if host else {}), **(headers or {})})+ signer = SigV4aAuth(Credentials(*credentials), service, region_set, **({"expires": 60} if presign else {}))+ with mock.patch("botocore.auth.get_current_datetime", lambda: signed_at or dt.datetime.now(dt.timezone.utc)):+ signer.add_auth(request)+ response = requests.request(method, request.url, data=body or None, headers=dict(request.headers.items()),+ timeout=30)+ code = re.search(r"<Code>([^<]*)</Code>", response.text)+ return response.status_code, code.group(1) if code else ""++[email protected]_contract+def test_sigv4a_signatures_are_verified_contract(auth_enabled, iam_user):+ """SigV4a header and presigned signatures are checked for an IAM user, with their date and region set."""+ import datetime as dt+ import uuid++ import boto3+ from botocore.config import Config+ from conftest import ENDPOINT, make_client, second_access_key++ endpoint = ENDPOINT.rstrip("/")+ bucket, name = f"sigv4a-{uuid.uuid4().hex[:8]}", f"sigv4a-{uuid.uuid4().hex[:8]}"+ admin, account = make_client("s3"), make_client("sts").get_caller_identity()["Account"]+ admin.create_bucket(Bucket=bucket)+ admin.put_object(Bucket=bucket, Key="k", Body=b"v")+ control = boto3.client("s3control", endpoint_url=ENDPOINT, region_name="us-west-2", aws_access_key_id="test",+ aws_secret_access_key="test", config=Config(inject_host_prefix=False))+ control.create_multi_region_access_point(AccountId=account, ClientToken=uuid.uuid4().hex,+ Details={"Name": name, "Regions": [{"Bucket": bucket}]})+ alias = control.get_multi_region_access_point(AccountId=account, Name=name)["AccessPoint"]["Alias"]+ mrap = f"{alias}.accesspoint.s3-global.amazonaws.com"+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": ["s3:GetObject", "s3:ListBucket"], "Resource": "*"}]})+ old = dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=20)+ sts_call = {"body": b"Action=GetCallerIdentity&Version=2011-06-15",+ "headers": {"Content-Type": "application/x-www-form-urlencoded"}}+ try:+ with second_access_key(user) as (key, secret):+ cases = [+ # (service, method, url, host, region set, extra, refused under AUTH=true as)+ ("sts", "POST", f"{endpoint}/", None, "*", sts_call, None),+ ("sts", "POST", f"{endpoint}/", None, "*", {**sts_call, "wrong": True},+ (403, "SignatureDoesNotMatch")),+ ("sts", "POST", f"{endpoint}/", None, "ap-south-1,ap-east-1", sts_call, (403, "InvalidClientTokenId")),+ ("sts", "POST", f"{endpoint}/", None, "*", {**sts_call, "signed_at": old},+ (403, "SignatureDoesNotMatch")),+ ("s3", "GET", f"{endpoint}/{bucket}/k", None, "*", {}, None),+ ("s3", "GET", f"{endpoint}/{bucket}/k", None, "*", {"wrong": True}, (403, "SignatureDoesNotMatch")),+ ("s3", "GET", f"{endpoint}/{bucket}/k", None, "ap-south-1", {}, (400, "RegionSetMismatch")),+ ("s3", "GET", f"{endpoint}/{bucket}/k", None, "*", {"signed_at": old}, (403, "RequestTimeTooSkewed")),+ ("s3", "GET", f"{endpoint}/{bucket}/k", None, "*", {"presign": True}, None),+ ("s3", "GET", f"{endpoint}/{bucket}/k", None, "*", {"presign": True, "wrong": True},+ (403, "SignatureDoesNotMatch")),+ ("s3", "GET", f"{endpoint}/{bucket}/k", None, "*", {"presign": True, "signed_at": old},+ (403, "AccessDenied")),+ ("s3", "GET", f"{endpoint}/k", mrap, "*", {}, None),+ ("s3", "GET", f"{endpoint}/k", mrap, "*", {"presign": True}, None),+ ("s3", "GET", f"{endpoint}/k", mrap, "*", {"wrong": True}, (403, "SignatureDoesNotMatch")),+ ("s3", "GET", f"{endpoint}/k", mrap, "ap-south-1", {}, (400, "RegionSetMismatch")),+ ]+ for service, method, url, host, region_set, extra, refused in cases:+ extra = dict(extra)+ credentials = (key, "wrong" + secret if extra.pop("wrong", False) else secret)+ result = _sigv4a_request(credentials, method, url, service, region_set, host=host, **extra)+ expected = refused if auth_enabled and refused else (200, "")+ assert result == expected, (service, url, host, region_set, extra)+ finally:+ control.delete_multi_region_access_point(AccountId=account, ClientToken=uuid.uuid4().hex,+ Details={"Name": name})+ admin.delete_object(Bucket=bucket, Key="k")+ admin.delete_bucket(Bucket=bucket)diff --git a/tests/test_sigv4.py b/tests/test_sigv4.pyindex c0bc049a..1afbc3cf 100644--- a/tests/test_sigv4.py+++ b/tests/test_sigv4.py@@ -11,11 +11,15 @@ from ministack.core.sigv4 import (calculate_signature,derive_signing_key,header_signature_failure,+ header_signing_documents,parse_header_signature,parse_query_signature,presigned_request_is_expired,+ region_set_covers,request_time_failure,signatures_match,+ sigv4a_signature_matches,+ sigv4a_signing_key,uri_encode,)@@ -134,6 +138,62 @@ def test_signing_helpers_match_botocore_fixed_vector():) == "ca6159ff16837c055653a722d9f10b6a529b7c62c84174a2859958324bc78766"+# AWS's published SigV4a test vector "get-vanilla" (aws-c-auth v4a signing test suite).+_V4A_KEY_ID, _V4A_SECRET = "AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"+_V4A_HEADERS = {+ "host": "example.amazonaws.com",+ "x-amz-date": "20150830T123600Z",+ "x-amz-region-set": "us-east-1",+ "authorization": (+ "AWS4-ECDSA-P256-SHA256 Credential=AKIDEXAMPLE/20150830/service/aws4_request, "+ "SignedHeaders=host;x-amz-date;x-amz-region-set, Signature=3046022100fddaaf816a31e30d04973875b13bc27b98da1"+ "0907a3a1872fd5819a221334abc022100de2ee81d83b54f31efc82834de07e6cd4d5c6f25bfa08e0f29a15bb0977c343e"),+}+_V4A_HEADER_STRING_TO_SIGN = (+ "AWS4-ECDSA-P256-SHA256\n20150830T123600Z\n20150830/service/aws4_request\n"+ "cf59db423e841c8b7e3444158185aa261b724a5c27cbe762676f3eed19f4dc02"+)+_V4A_QUERY_STRING_TO_SIGN = (+ "AWS4-ECDSA-P256-SHA256\n20150830T123600Z\n20150830/service/aws4_request\n"+ "890c4ed28c1a1ac10b5862719b537afbe392e987dc1aab1efa16fe7de41d3c81"+)+_V4A_QUERY_SIGNATURE = (+ "3045022100b3246f8e1442dd58e73292ae1294720c3256ee58f6cea50f3a3f83b4a4b0331a0220329693f7745c9008a5887c0529ce"+ "ccb0fae4e16d707b712ea66acdbaf963769a"+)+++def test_sigv4a_key_derivation_matches_the_published_vector():+ public = sigv4a_signing_key(_V4A_KEY_ID, _V4A_SECRET).public_key().public_numbers()++ assert (f"{public.x:064x}", f"{public.y:064x}") == (+ "b6618f6a65740a99e650b33b6b4b5bd0d43b176d721a3edfea7e7d2d56d936b1",+ "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518",+ )+ assert sigv4a_signature_matches(_V4A_KEY_ID, _V4A_SECRET, _V4A_QUERY_STRING_TO_SIGN, _V4A_QUERY_SIGNATURE)+ assert not sigv4a_signature_matches(_V4A_KEY_ID, _V4A_SECRET, _V4A_HEADER_STRING_TO_SIGN, _V4A_QUERY_SIGNATURE)+ assert not sigv4a_signature_matches(_V4A_KEY_ID, "other", _V4A_QUERY_STRING_TO_SIGN, _V4A_QUERY_SIGNATURE)+ assert not sigv4a_signature_matches(_V4A_KEY_ID, _V4A_SECRET, _V4A_QUERY_STRING_TO_SIGN, "not hex")+++def test_sigv4a_header_signature_of_the_published_vector_verifies():+ signature = parse_header_signature(_V4A_HEADERS)++ assert (signature.access_key_id, signature.service, signature.region_set) == (_V4A_KEY_ID, "service", "us-east-1")+ assert header_signing_documents(signature, "GET", "/", {}, _V4A_HEADERS, b"")[1] == _V4A_HEADER_STRING_TO_SIGN+ assert header_signature_failure(signature, _V4A_SECRET, "GET", "/", {}, _V4A_HEADERS, b"") is None+ assert header_signature_failure(signature, _V4A_SECRET, "GET", "/x", {}, _V4A_HEADERS, b"")[0] == (+ "SignatureDoesNotMatch")++[email protected]("region_set, covered", [+ ("*", True), ("eu-central-1", True), ("us-west-2,eu-central-1", True), ("eu-*", True),+ ("us-west-2", False), ("eu-west-*", False),+])+def test_region_set_covers_lists_and_wildcards(region_set, covered):+ assert region_set_covers(region_set, "eu-central-1") is covered++def test_presigned_request_expiry_is_exclusive_at_boundary():expires_at = dt.datetime(2026, 9, 4, 12, 15, tzinfo=dt.timezone.utc)