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): harden AWS credential resolution (#1668)
Ian Oberst73961ad6740d
diff --git a/ministack/app.py b/ministack/app.pyindex 943dc84e..6d625852 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -197,10 +197,18 @@ _NON_S3_VHOST_NAMES = frozenset()from ministack.core import container_reaper+from ministack.core.aws_credentials import (+ AmbiguousAccessKeyError,+ find_iam_access_key_account,+)from ministack.core.concurrency import spawn_backgroundfrom ministack.core.hypercorn_compat import install as _install_hypercorn_compatfrom ministack.core.persistence import PERSIST_STATE, load_state, save_all-from ministack.core.responses import _12_DIGIT_RE, set_request_account_id, set_request_region+from ministack.core.responses import (+ _12_DIGIT_RE,+ set_request_account_id,+ set_request_region,+)from ministack.core.router import detect_service, extract_access_key_id, extract_region# Must run before hypercorn emits its first Expect: 100-continue reply.@@ -213,6 +221,11 @@ _install_hypercorn_compat()# ---------------------------------------------------------------------------_loaded_modules: dict = {}++def _request_account_scope(access_key_id: str) -> str:+ """Return the tenant selector for an AWS access key."""+ return find_iam_access_key_account(access_key_id) or access_key_id+# Execution state of ready.d scripts — surfaced via /_ministack/health and /_ministack/ready.# status: "pending" (not started) | "running" | "completed" (all scripts finished, errors included)_ready_scripts_state: dict = {@@ -1726,6 +1739,12 @@ def _resolve_mrap_host(host: str):async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict):"""Handle virtual-hosted S3 requests before generic routing."""+ if _MRAP_HOST_RE.match(host.split(":")[0].strip()):+ # Alias lookup is account-scoped and precedes the S3 handler. Verify+ # a SigV4 presign first so lookup uses its credential owner's account.+ error = _get_module("s3")._verify_presigned_sigv4(method, path, headers, query_params)+ if error:+ return errormrap_bucket = _resolve_mrap_host(host)if mrap_bucket:# SigV4A (`AWS4-ECDSA-P256-SHA256`) is what S3 requires for an MRAP and@@ -2388,7 +2407,25 @@ async def app(scope, receive, send):# If the access key is a 12-digit number, it becomes the account ID._access_key = extract_access_key_id(headers, query_params)if _access_key:- set_request_account_id(_access_key)+ try:+ set_request_account_id(_request_account_scope(_access_key) if AUTH else _access_key)+ except AmbiguousAccessKeyError:+ await _send_response(+ send,+ 403,+ {+ "Content-Type": "application/json",+ "x-amzn-requestid": request_id,+ "x-amz-request-id": request_id,+ },+ json.dumps(+ {+ "__type": "InvalidClientTokenId",+ "message": "The security token included in the request is invalid.",+ }+ ).encode(),+ )+ return# Set per-request region from SigV4 Credential scope so CFN's AWS::Region# pseudo-param and ARN-building use the caller's region, not MINISTACK_REGIONdiff --git a/ministack/core/aws_credentials.py b/ministack/core/aws_credentials.pynew file mode 100644index 00000000..b6fbdb26--- /dev/null+++ b/ministack/core/aws_credentials.py@@ -0,0 +1,240 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""Resolve AWS access keys to the credentials and principals MiniStack issued."""++import hmac+import os+import re+import time+from dataclasses import dataclass++from ministack.core.responses import get_account_id++_ACCOUNT_ID_RE = re.compile(r"^\d{12}$")+_SESSION_TOKEN_NOT_CHECKED = object()+++@dataclass(frozen=True)+class ResolvedCredential:+ access_key_id: str+ secret_access_key: str+ account_id: str+ principal_arn: str+ principal_id: str+ principal_type: str+ principal_name: str = ""+ session_token: str | None = None+ expiration: float | None = None+ source_access_key_id: str | None = None+++@dataclass(frozen=True)+class CredentialResolutionError:+ code: str+ message: str+++class AmbiguousAccessKeyError(ValueError):+ """Raised when more than one tenant owns the same IAM access key."""+++def is_root_access_key(access_key_id: str) -> bool:+ """Return whether a key represents MiniStack's configured root caller."""+ configured_key = os.environ.get("AWS_ACCESS_KEY_ID", "test")+ return (+ not access_key_id+ or access_key_id == "test"+ or access_key_id == configured_key+ or bool(_ACCOUNT_ID_RE.fullmatch(access_key_id))+ )+++def _unknown_access_key() -> CredentialResolutionError:+ return CredentialResolutionError(+ "UnrecognizedClientException",+ "The security token included in the request is invalid.",+ )+++def _invalid_session_token() -> CredentialResolutionError:+ return CredentialResolutionError(+ "InvalidToken",+ "The provided token is malformed or otherwise invalid.",+ )+++def _account_from_arn(arn: str) -> str | None:+ parts = arn.split(":")+ if len(parts) > 4 and _ACCOUNT_ID_RE.fullmatch(parts[4]):+ return parts[4]+ return None+++def _principal_type(arn: str, recorded_type: str) -> str:+ if recorded_type:+ return recorded_type+ if ":assumed-role/" in arn:+ return "AssumedRole"+ if ":user/" in arn:+ return "User"+ if arn.endswith(":root"):+ return "Root"+ return ""+++def _validate_session_token(expected: str | None, supplied) -> CredentialResolutionError | None:+ if supplied is _SESSION_TOKEN_NOT_CHECKED:+ return None+ supplied = supplied or ""+ if expected is None:+ return _invalid_session_token() if supplied else None+ if not isinstance(expected, str) or not isinstance(supplied, str) or not hmac.compare_digest(+ expected.encode("utf-8"), supplied.encode("utf-8")+ ):+ return _invalid_session_token()+ return None+++def find_iam_access_key_account(access_key_id: str) -> str | None:+ """Return the sole account that owns an IAM access key, if known.++ AWS access key IDs are globally unique. Duplicate emulator records raise+ instead of selecting either tenant.+ """+ if is_root_access_key(access_key_id):+ return None++ from ministack.services import sts as sts_svc++ if access_key_id in sts_svc._sessions:+ return None++ from ministack.services import iam as iam_svc++ accounts = {+ account_id+ for (account_id, stored_key) in iam_svc._access_keys.to_dict()+ if stored_key == access_key_id+ }+ if len(accounts) > 1:+ raise AmbiguousAccessKeyError(access_key_id)+ if accounts:+ return accounts.pop()+ return None+++def resolve_credential(+ access_key_id: str,+ account_id: str | None = None,+ session_token=_SESSION_TOKEN_NOT_CHECKED,+) -> ResolvedCredential | CredentialResolutionError:+ """Resolve a root, IAM, or STS key in an explicit account.++ Passing ``session_token`` also validates whether the caller supplied the+ exact token attached to temporary credentials. Omitting it leaves token+ validation to the caller, which keeps policy-only identity lookups usable.+ """+ account_id = account_id or get_account_id()++ if is_root_access_key(access_key_id):+ if _ACCOUNT_ID_RE.fullmatch(access_key_id):+ if account_id != access_key_id:+ return _unknown_access_key()+ account_id = access_key_id+ configured_key = os.environ.get("AWS_ACCESS_KEY_ID", "test")+ configured_token = os.environ.get("AWS_SESSION_TOKEN") or None+ numeric_token_supplied = (+ bool(_ACCOUNT_ID_RE.fullmatch(access_key_id))+ and isinstance(session_token, str)+ and bool(session_token)+ )+ expected_token = (+ configured_token+ if access_key_id == configured_key or numeric_token_supplied+ else None+ )+ token_error = _validate_session_token(expected_token, session_token)+ if token_error:+ return token_error+ return ResolvedCredential(+ access_key_id=access_key_id,+ secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY", "test"),+ session_token=expected_token,+ account_id=account_id,+ principal_arn=f"arn:aws:iam::{account_id}:root",+ principal_id=account_id,+ principal_type="Root",+ source_access_key_id=access_key_id,+ )++ from ministack.services import sts as sts_svc++ session = sts_svc._sessions.get(access_key_id)+ if session is not None:+ principal_arn = str(session.get("Arn", ""))+ session_account = session.get("AccountId") or _account_from_arn(principal_arn)+ if session_account and session_account != account_id:+ return _unknown_access_key()+ expiration = session.get("Expiration")+ if isinstance(expiration, (int, float)) and time.time() > expiration:+ return CredentialResolutionError(+ "ExpiredTokenException",+ "The security token included in the request is expired",+ )+ expected_token = session.get("SessionToken")+ token_error = _validate_session_token(expected_token, session_token)+ if token_error:+ return token_error+ secret = session.get("SecretAccessKey")+ principal_type = _principal_type(principal_arn, session.get("PrincipalType", ""))+ if not secret or not principal_type:+ return _unknown_access_key()+ principal_name = ""+ if principal_type == "User" and ":user/" in principal_arn:+ principal_name = str(session.get("PrincipalName") or "")+ if not principal_name:+ principal_name = principal_arn.rsplit("/", 1)[-1]+ return ResolvedCredential(+ access_key_id=access_key_id,+ secret_access_key=secret,+ session_token=expected_token,+ expiration=expiration if isinstance(expiration, (int, float)) else None,+ account_id=session_account or account_id,+ principal_arn=principal_arn,+ principal_id=str(session.get("UserId", "")),+ principal_type=principal_type,+ principal_name=principal_name,+ source_access_key_id=session.get("SourceAccessKeyId"),+ )++ from ministack.services import iam as iam_svc++ key_record = iam_svc._access_keys.get_scoped(account_id, None, access_key_id)+ if key_record is None:+ return _unknown_access_key()+ if key_record.get("Status") != "Active":+ return CredentialResolutionError(+ "InvalidClientTokenId",+ "The security token included in the request is invalid.",+ )+ token_error = _validate_session_token(None, session_token)+ if token_error:+ return token_error+ secret = key_record.get("SecretAccessKey")+ if not secret:+ return _unknown_access_key()+ user_name = str(key_record.get("UserName", ""))+ user = iam_svc._users.get_scoped(account_id, None, user_name) or {}+ principal_arn = str(+ user.get("Arn") or f"arn:aws:iam::{account_id}:user/{user_name}"+ )+ return ResolvedCredential(+ access_key_id=access_key_id,+ secret_access_key=secret,+ account_id=account_id,+ principal_arn=principal_arn,+ principal_id=str(user.get("UserId", "")),+ principal_type="User",+ principal_name=user_name,+ source_access_key_id=access_key_id,+ )diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex 78713825..2b1e1382 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -19,6 +19,12 @@ import refrom dataclasses import dataclass, fieldfrom typing import Any+from ministack.core.aws_credentials import (+ CredentialResolutionError,+ is_root_access_key,+ resolve_credential,+)+logger = logging.getLogger("ministack")@@ -75,10 +81,6 @@ class AuthError:message: str-# Default access keys that are always treated as root (backwards compat)-_ROOT_ACCESS_KEYS = frozenset({"test", ""})--# ---------------------------------------------------------------------------# Wildcard matching (IAM-style)# ---------------------------------------------------------------------------@@ -636,12 +638,8 @@ def _resolve_managed_policy_document(policy_arn: str,def _is_root_key(access_key_id: str) -> bool:- """Keys that are always treated as root: empty, 'test', 12-digit account IDs."""- if not access_key_id or access_key_id in _ROOT_ACCESS_KEYS:- return True- if re.match(r"^\d{12}$", access_key_id):- return True- return False+ """Keys treated as root: empty, ``test``, configured, or account IDs."""+ return is_root_access_key(access_key_id)def resolve_principal(access_key_id: str,@@ -651,64 +649,30 @@ def resolve_principal(access_key_id: str,Returns a ``PrincipalInfo`` on success or an ``AuthError`` whenauthentication fails (unknown key, inactive key, expired session)."""- import time-- from ministack.services import iam as iam_svc- from ministack.services import sts as sts_svc-- # Root / default keys — allow-all, no checks- if _is_root_key(access_key_id):- return PrincipalInfo(- arn=f"arn:aws:iam::{account_id}:root",- type="Root",- account=account_id,- policies=None,- )-- # Session credentials (AssumeRole) — ASIA prefix- if access_key_id in sts_svc._sessions:- session = sts_svc._sessions[access_key_id]- # Check expiry- expiration = session.get("Expiration")- if expiration is not None and time.time() > expiration:- return AuthError(- "ExpiredTokenException",- "The security token included in the request is expired",- )- assumed_arn = session.get("Arn", "")- role_name = _role_name_from_assumed_arn(assumed_arn)- arn_parts = assumed_arn.split(":")- session_account = arn_parts[4] if len(arn_parts) >= 6 else account_id- policies = _gather_role_policies(role_name, session_account)- return PrincipalInfo(- arn=assumed_arn,- type="AssumedRole",- account=session_account,- policies=policies,+ from ministack.core.responses import _account_from_sts_session++ account_id = _account_from_sts_session(access_key_id) or account_id+ credential = resolve_credential(access_key_id, account_id)+ if isinstance(credential, CredentialResolutionError):+ return AuthError(credential.code, credential.message)+ if credential.principal_type == "Root":+ policies = None+ elif credential.principal_type == "User":+ policies = _gather_user_policies(credential.principal_name, account_id)+ elif credential.principal_type == "AssumedRole":+ policies = _gather_role_policies(+ _role_name_from_assumed_arn(credential.principal_arn), account_id)-- # IAM user access key — AKIA prefix- key_record = iam_svc._access_keys.get_scoped(account_id, None, access_key_id)- if key_record is not None:- # Check key status- if key_record.get("Status") == "Inactive":- return AuthError(- "InvalidClientTokenId",- "The security token included in the request is invalid.",- )- user_name = key_record.get("UserName", "")- policies = _gather_user_policies(user_name, account_id)- return PrincipalInfo(- arn=f"arn:aws:iam::{account_id}:user/{user_name}",- type="User",- account=account_id,- policies=policies,+ else:+ return AuthError(+ "UnrecognizedClientException",+ "The security token included in the request is invalid.",)-- # Unknown access key — reject- return AuthError(- "UnrecognizedClientException",- "The security token included in the request is invalid.",+ return PrincipalInfo(+ arn=credential.principal_arn,+ type=credential.principal_type,+ account=credential.account_id,+ policies=policies,)@@ -781,7 +745,7 @@ def resolve_caller_identity(access_key_id: str) -> dict | None:return {"accessKey": access_key_id,"accountId": account_id,- "userArn": f"arn:aws:iam::{account_id}:user/{user_name}",+ "userArn": user.get("Arn") or f"arn:aws:iam::{account_id}:user/{user_name}","userId": user.get("UserId", ""),"principalOrgId": _principal_org_id(),"session": None,diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 80c81964..b5880de6 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -6536,6 +6536,7 @@ def _get_credentials_for_identity(data):access_key = f"ASIA{''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(16))}"secret_key = base64.b64encode(secrets.token_bytes(30)).decode()+ session_token = base64.b64encode(secrets.token_bytes(64)).decode()role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()# The cognito* identity fields API Gateway reports for IAM-authorized@@ -6568,7 +6569,10 @@ def _get_credentials_for_identity(data):f"{role_name}/CognitoIdentityCredentials"),"UserId": f"{role_id}:CognitoIdentityCredentials","SecretAccessKey": secret_key,+ "SessionToken": session_token,"Expiration": now + 3600,+ "AccountId": get_account_id(),+ "PrincipalType": "AssumedRole","_identity_id": identity_id,"_identity_pool_id": (pool or {}).get("IdentityPoolId", ""),"_logins": logins,@@ -6582,7 +6586,7 @@ def _get_credentials_for_identity(data):"Credentials": {"AccessKeyId": access_key,"SecretKey": secret_key,- "SessionToken": base64.b64encode(secrets.token_bytes(64)).decode(),+ "SessionToken": session_token,"Expiration": now + 3600,},})diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex f1f5a586..1be395dd 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -50,6 +50,12 @@ from xml.sax.saxutils import escape as _escfrom defusedxml.ElementTree import fromstringfrom ministack.core.arn import ArnParseError, parse_arn+from ministack.core.aws_credentials import (+ AmbiguousAccessKeyError,+ CredentialResolutionError,+ find_iam_access_key_account,+ resolve_credential,+)from ministack.core.persistence import load_statefrom ministack.core.responses import (AccountScopedDict,@@ -1504,37 +1510,14 @@ def _object_response_headers(obj: dict, bucket_name: str = "", key: str = "", in# ----------------------------------------------------------------------------def _resolve_presign_secret(access_key_id):- """The secret a presigned URL was signed with.-- STS temporary credentials are signed with the unique secret STS issued (not- the server's static one), so a presigned URL from an AssumeRole / session- token would never recompute against ``AWS_SECRET_ACCESS_KEY``. STS records- each issued secret by access key id; resolve it here, falling back to the- static server secret for a long-term (non-session) credential.- """- try:- from ministack.services import sts-- session = sts._sessions.get(access_key_id)- if session and session.get("SecretAccessKey"):- return session["SecretAccessKey"]- except Exception:- pass- return os.environ.get("AWS_SECRET_ACCESS_KEY", "test")--def _verify_presigned_sigv4(method, path, headers, query_params):"""Verify a SigV4 presigned S3 URL. Returns an error tuple for a badsignature, or None when the request is not a SigV4 presigned URL (header-signed and anonymous requests are handled elsewhere / left lax).- MiniStack has no IAM secret store, so it verifies against its own secret- (``AWS_SECRET_ACCESS_KEY``, default ``test``) — the same credential the- server and its Lambda runtimes use. A URL signed with any other secret, or- one whose signed headers (content-type, content-length, ...) were tampered- with after signing, does not recompute to the same signature and is- rejected with 403 SignatureDoesNotMatch, matching real S3.+ MiniStack resolves root, IAM-user, and STS credentials before recomputing+ the signature. Temporary credentials must include the exact session token+ STS issued."""signature = _qp(query_params, "X-Amz-Signature", "") or _qp(query_params, "x-amz-signature", "")if not signature:@@ -1585,8 +1568,38 @@ def _verify_presigned_sigv4(method, path, headers, query_params):canonical_request,)- secret = _resolve_presign_secret(_akid)- computed = calculate_signature(secret, date_stamp, region, service, string_to_sign)+ session_token = _qp(query_params, "X-Amz-Security-Token", "") or _qp(+ query_params, "x-amz-security-token", ""+ )+ # S3 presigned requests verify credentials even with AUTH disabled.+ # Resolve their tenant here, without changing routing for other requests.+ try:+ owner = find_iam_access_key_account(_akid)+ except AmbiguousAccessKeyError:+ return _error(+ "InvalidAccessKeyId", "The AWS Access Key Id is ambiguous.", 403, path+ )+ if owner:+ set_request_account_id(owner)+ credential = resolve_credential(_akid, get_account_id(), session_token)+ if isinstance(credential, CredentialResolutionError):+ if credential.code == "ExpiredTokenException":+ return _error("ExpiredToken", credential.message, 403, path)+ if credential.code == "InvalidToken":+ return _error("InvalidToken", credential.message, 403, path)+ return _error(+ "InvalidAccessKeyId",+ "The AWS Access Key Id you provided does not exist in our records.",+ 403,+ path,+ )+ computed = calculate_signature(+ credential.secret_access_key,+ date_stamp,+ region,+ service,+ string_to_sign,+ )if not signatures_match(computed, signature):return _bad_signature()diff --git a/ministack/services/sts.py b/ministack/services/sts.pyindex 8fe9ecd7..39d84747 100644--- a/ministack/services/sts.py+++ b/ministack/services/sts.py@@ -16,6 +16,7 @@ import timefrom urllib.parse import parse_qsfrom ministack.core.arn import ArnParseError, parse_arn+from ministack.core.aws_credentials import CredentialResolutionError, resolve_credentialfrom ministack.core.responses import get_account_id, json_response, new_uuidfrom ministack.core.router import extract_access_key_id@@ -48,6 +49,53 @@ def register_session(access_key: str, session: dict) -> None:_sessions[access_key] = session+def _caller_identity(+ headers: dict, query_params=None+) -> dict | CredentialResolutionError:+ """Return the best-known originating principal for a new STS session."""+ from ministack.app import AUTH++ access_key = extract_access_key_id(headers, query_params) or "test"+ if not AUTH:+ # Session metadata is descriptive in permissive mode; issuing a+ # session must not introduce credential rejection checks.+ from ministack.core.iam_evaluator import resolve_caller_identity++ identity = resolve_caller_identity(access_key)+ account_id = get_account_id()+ arn = identity["userArn"] if identity else f"arn:aws:iam::{account_id}:root"+ principal_type = (+ "AssumedRole" if ":assumed-role/" in arn+ else "User" if ":user/" in arn else "Root"+ )+ return {+ "accessKey": access_key,+ "accountId": account_id,+ "userArn": arn,+ "userId": identity["userId"] if identity else account_id,+ "principalType": principal_type,+ "principalName": arn.rsplit("/", 1)[-1] if principal_type == "User" else "",+ "isTemporary": bool(identity and identity.get("session")),+ }+ credential = resolve_credential(access_key, get_account_id())+ if isinstance(credential, CredentialResolutionError):+ return credential+ return {+ "accessKey": access_key,+ "accountId": credential.account_id,+ "userArn": credential.principal_arn,+ "userId": credential.principal_id,+ "principalType": credential.principal_type,+ "principalName": credential.principal_name,+ "isTemporary": credential.session_token is not None,+ }+++def _credential_error_response(error: CredentialResolutionError):+ code = "ExpiredToken" if error.code == "ExpiredTokenException" else error.code+ return _error(403, code, error.message, ns="sts")++def reset():_sessions.clear()@@ -135,6 +183,9 @@ async def handle_request(method, path, headers, body, query_params):assumed_arn, validation_error = _assumed_role_arn(role_arn, session_name)if validation_error:return validation_error+ caller = _caller_identity(headers, query_params)+ if isinstance(caller, CredentialResolutionError):+ return _credential_error_response(caller)# When AUTH=true, validate role exists and trust policy permits the callerfrom ministack.app import AUTH@@ -168,14 +219,7 @@ async def handle_request(method, path, headers, body, query_params):ns="sts")# Evaluate trust policytrust_doc = role.get("AssumeRolePolicyDocument", "{}")- caller_key = extract_access_key_id(headers)- caller_arn = f"arn:aws:iam::{get_account_id()}:root"- if caller_key in _sessions:- caller_arn = _sessions[caller_key].get("Arn", caller_arn)- else:- key_record = iam_svc._access_keys.get(caller_key)- if key_record:- caller_arn = f"arn:aws:iam::{get_account_id()}:user/{key_record['UserName']}"+ caller_arn = caller["userArn"]if not evaluate_trust_policy(trust_doc, caller_arn):return _error(403, "AccessDenied",f"User: {caller_arn} is not authorized to perform: "@@ -191,7 +235,12 @@ async def handle_request(method, path, headers, body, query_params):"Arn": assumed_arn,"UserId": f"{role_id}:{session_name}","SecretAccessKey": secret_key,+ "SessionToken": session_token,"Expiration": time.time() + duration,+ "AccountId": role_arn.split(":")[4],+ "PrincipalType": "AssumedRole",+ "SourceAccessKeyId": caller["accessKey"],+ "SourcePrincipalArn": caller["userArn"],})if use_json:return json_response({@@ -230,7 +279,10 @@ async def handle_request(method, path, headers, body, query_params):"Arn": assumed_arn,"UserId": f"{role_id}:{session}","SecretAccessKey": secret_key,+ "SessionToken": session_token,"Expiration": time.time() + duration,+ "AccountId": role_arn.split(":")[4],+ "PrincipalType": "AssumedRole",})provider = _p(params, "ProviderId") or "sts.amazonaws.com"if use_json:@@ -265,9 +317,29 @@ async def handle_request(method, path, headers, body, query_params):access_key = _gen_session_access_key()secret_key = _gen_secret()session_token = _gen_session_token()- # Record the secret so a presigned URL signed with these temporary- # credentials can be verified against the key it was actually signed with.- _sessions[access_key] = {"SecretAccessKey": secret_key}+ caller = _caller_identity(headers, query_params)+ if isinstance(caller, CredentialResolutionError):+ return _credential_error_response(caller)+ from ministack.app import AUTH+ if AUTH and caller["isTemporary"]:+ return _error(+ 403,+ "AccessDenied",+ "Cannot call GetSessionToken with session credentials",+ ns="sts",+ )+ register_session(access_key, {+ "Arn": caller["userArn"],+ "UserId": caller["userId"],+ "SecretAccessKey": secret_key,+ "SessionToken": session_token,+ "Expiration": time.time() + duration,+ "AccountId": caller["accountId"],+ "PrincipalType": caller["principalType"],+ "PrincipalName": caller["principalName"],+ "SourceAccessKeyId": caller["accessKey"],+ "SourcePrincipalArn": caller["userArn"],+ })if use_json:return json_response({"Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": int(time.time() + duration)},diff --git a/tests/test_aws_credentials.py b/tests/test_aws_credentials.pynew file mode 100644index 00000000..0a30be11--- /dev/null+++ b/tests/test_aws_credentials.py@@ -0,0 +1,407 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).++import asyncio+import time++import pytest++from ministack.core.aws_credentials import (+ AmbiguousAccessKeyError,+ CredentialResolutionError,+ ResolvedCredential,+ find_iam_access_key_account,+ resolve_credential,+)+from ministack.core.iam_evaluator import PrincipalInfo, resolve_principal+from ministack.services import iam as iam_svc+from ministack.services import sts as sts_svc+++def test_resolve_root_credential_from_environment(monkeypatch):+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "configured-root")+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "configured-secret")+ monkeypatch.setenv("AWS_SESSION_TOKEN", "configured-token")++ credential = resolve_credential(+ "configured-root", "123456789012", "configured-token"+ )++ assert isinstance(credential, ResolvedCredential)+ assert credential.secret_access_key == "configured-secret"+ assert credential.session_token == "configured-token"+ assert credential.principal_arn == "arn:aws:iam::123456789012:root"+++def test_resolve_root_credential_treats_empty_environment_token_as_absent(monkeypatch):+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "configured-root")+ monkeypatch.setenv("AWS_SESSION_TOKEN", "")++ credential = resolve_credential("configured-root", "123456789012", "")++ assert isinstance(credential, ResolvedCredential)+ assert credential.session_token is None+++def test_resolve_numeric_root_accepts_optional_ambient_session_token(monkeypatch):+ account_id = "123456789012"+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "configured-root")+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "configured-secret")+ monkeypatch.setenv("AWS_SESSION_TOKEN", "ambient-token")++ with_token = resolve_credential(account_id, account_id, "ambient-token")+ without_token = resolve_credential(account_id, account_id, "")+ wrong_token = resolve_credential(account_id, account_id, "wrong-token")++ assert isinstance(with_token, ResolvedCredential)+ assert with_token.session_token == "ambient-token"+ assert isinstance(without_token, ResolvedCredential)+ assert without_token.session_token is None+ assert isinstance(wrong_token, CredentialResolutionError)+ assert wrong_token.code == "InvalidToken"+++def test_resolve_iam_credential_is_account_scoped_and_requires_active_status():+ access_key = "AKIATESTSCOPED00001"+ first_account = "111111111111"+ second_account = "222222222222"+ iam_svc._access_keys.set_scoped(first_account, None, access_key, {+ "AccessKeyId": access_key,+ "SecretAccessKey": "first-secret",+ "Status": "Active",+ "UserName": "first-user",+ })+ iam_svc._access_keys.set_scoped(second_account, None, access_key, {+ "AccessKeyId": access_key,+ "SecretAccessKey": "second-secret",+ "Status": "Inactive",+ "UserName": "second-user",+ })+ try:+ first = resolve_credential(access_key, first_account, "")+ second = resolve_credential(access_key, second_account, "")++ assert isinstance(first, ResolvedCredential)+ assert first.secret_access_key == "first-secret"+ assert first.principal_arn == (+ "arn:aws:iam::111111111111:user/first-user"+ )+ assert isinstance(second, CredentialResolutionError)+ assert second.code == "InvalidClientTokenId"+ with pytest.raises(AmbiguousAccessKeyError):+ find_iam_access_key_account(access_key)+ finally:+ iam_svc._access_keys.pop_scoped(first_account, None, access_key, None)+ iam_svc._access_keys.pop_scoped(second_account, None, access_key, None)+++def test_resolve_sts_credential_checks_token_expiry_and_origin():+ access_key = "ASIATESTSESSION0001"+ account_id = "123456789012"+ sts_svc._sessions[access_key] = {+ "Arn": f"arn:aws:iam::{account_id}:user/alice",+ "UserId": "AIDAALICE",+ "SecretAccessKey": "session-secret",+ "SessionToken": "session-token",+ "Expiration": time.time() + 60,+ "AccountId": account_id,+ "PrincipalType": "User",+ "SourceAccessKeyId": "AKIAALICE",+ }+ try:+ credential = resolve_credential(access_key, account_id, "session-token")+ wrong = resolve_credential(access_key, account_id, "wrong-token")+ missing = resolve_credential(access_key, account_id, "")+ non_ascii = resolve_credential(access_key, account_id, "not-valid-☃")++ assert isinstance(credential, ResolvedCredential)+ assert credential.principal_type == "User"+ assert credential.principal_name == "alice"+ assert credential.source_access_key_id == "AKIAALICE"+ assert isinstance(wrong, CredentialResolutionError)+ assert wrong.code == "InvalidToken"+ assert isinstance(missing, CredentialResolutionError)+ assert missing.code == "InvalidToken"+ assert isinstance(non_ascii, CredentialResolutionError)+ assert non_ascii.code == "InvalidToken"++ sts_svc._sessions[access_key]["Expiration"] = time.time() - 1+ expired = resolve_credential(access_key, account_id, "session-token")+ assert isinstance(expired, CredentialResolutionError)+ assert expired.code == "ExpiredTokenException"+ finally:+ sts_svc._sessions.pop(access_key, None)+++def test_find_iam_access_key_account_returns_unique_owner():+ access_key = "test-account-lookup-key"+ account_id = "123456789012"+ iam_svc._access_keys.set_scoped(account_id, None, access_key, {+ "AccessKeyId": access_key,+ "SecretAccessKey": "secret",+ "Status": "Active",+ "UserName": "alice",+ })+ try:+ assert find_iam_access_key_account(access_key) == account_id+ finally:+ iam_svc._access_keys.pop_scoped(account_id, None, access_key, None)+++++def test_ambiguous_iam_access_key_is_rejected_before_http_routing(monkeypatch):+ from ministack import app as app_mod+ from ministack.core.responses import get_account_id, set_request_account_id++ monkeypatch.setattr(app_mod, "AUTH", True)+ access_key = "test-ambiguous-http-key"+ accounts = ("000000000000", "123456789012")+ original_account = get_account_id()+ sent = []+ for account_id in accounts:+ iam_svc._access_keys.set_scoped(account_id, None, access_key, {+ "AccessKeyId": access_key,+ "SecretAccessKey": f"secret-{account_id}",+ "Status": "Active",+ "UserName": f"user-{account_id}",+ })+ scope = {+ "type": "http",+ "method": "GET",+ "path": "/",+ "headers": [(b"host", b"s3.localhost")],+ "query_string": (+ f"X-Amz-Credential={access_key}/20260908/us-east-1/s3/aws4_request"+ ).encode(),+ }++ async def receive():+ return {"type": "http.request", "body": b"", "more_body": False}++ async def send(message):+ sent.append(message)++ try:+ asyncio.run(app_mod.app(scope, receive, send))++ assert sent[0]["type"] == "http.response.start"+ assert sent[0]["status"] == 403+ assert b"InvalidClientTokenId" in sent[1]["body"]+ finally:+ for account_id in accounts:+ iam_svc._access_keys.pop_scoped(account_id, None, access_key, None)+ set_request_account_id(original_account)++++[email protected]("auth_enabled", [False, True])[email protected]("ambiguous", [False, True])+def test_http_iam_routing_respects_auth_mode(monkeypatch, auth_enabled, ambiguous):+ from ministack import app as app_mod+ from ministack.core.responses import get_account_id, request_scope++ key = "test-routing-mode-key"+ owner = "123456789012"+ accounts = [owner, "234567890123"] if ambiguous else [owner]+ monkeypatch.setattr(app_mod, "AUTH", auth_enabled)+ monkeypatch.setenv("MINISTACK_ACCOUNT_ID", "000000000000")+ routed = []+ sent = []++ async def capture(*args):+ routed.append(get_account_id())+ return 200, {}, b"ok"++ async def receive():+ return {"type": "http.request", "body": b"", "more_body": False}++ async def send(message):+ sent.append(message)++ monkeypatch.setattr(app_mod, "_handle_pre_body_request", capture)+ for account in accounts:+ iam_svc._access_keys.set_scoped(account, None, key, {"UserName": "alice"})+ try:+ with request_scope("000000000000", "us-east-1"):+ asyncio.run(app_mod.app({+ "type": "http", "method": "GET", "path": "/",+ "headers": [(b"host", b"sts.localhost"), (+ b"authorization",+ f"AWS4-HMAC-SHA256 Credential={key}/20260911/us-east-1/sts/aws4_request".encode(),+ )],+ "query_string": b"",+ }, receive, send))+ assert sent[0]["status"] == (403 if auth_enabled and ambiguous else 200)+ assert routed == ([] if auth_enabled and ambiguous else [+ owner if auth_enabled else "000000000000"+ ])+ finally:+ for account in accounts:+ iam_svc._access_keys.pop_scoped(account, None, key, None)++[email protected]("auth_enabled", [False, True])[email protected]("bad_token", [False, True])+def test_s3_presign_verifies_in_both_auth_modes(monkeypatch, auth_enabled, bad_token):+ from urllib.parse import parse_qs, urlsplit++ import boto3+ from botocore.config import Config++ from ministack import app as app_mod+ from ministack.core.responses import get_account_id, request_scope+ from ministack.services import s3 as s3_svc++ key = "test-presign-mode-key"+ owner = "123456789012"+ monkeypatch.setattr(app_mod, "AUTH", auth_enabled)+ iam_svc._access_keys.set_scoped(owner, None, key, {+ "UserName": "alice", "Status": "Active", "SecretAccessKey": "secret",+ })+ client = boto3.client(+ "s3", endpoint_url="http://localhost:4566", region_name="us-east-1",+ aws_access_key_id=key, aws_secret_access_key="secret",+ aws_session_token="unexpected-token" if bad_token else None,+ config=Config(signature_version="s3v4"),+ )+ url = urlsplit(client.generate_presigned_url(+ "get_object", Params={"Bucket": "test-bucket", "Key": "object"},+ ))+ try:+ with request_scope("000000000000", "us-east-1"):+ error = s3_svc._verify_presigned_sigv4(+ "GET", url.path, {"host": url.netloc}, parse_qs(url.query),+ )+ assert get_account_id() == owner+ if bad_token:+ assert error[0] == 403+ else:+ assert error is None+ finally:+ iam_svc._access_keys.pop_scoped(owner, None, key, None)++[email protected]("auth_enabled", [False, True])[email protected]("action", ["GetSessionToken", "AssumeRole"])[email protected]("credential_kind", ["unknown", "inactive", "expired"])+def test_sts_credential_rejections_require_auth(monkeypatch, auth_enabled, action, credential_kind):+ from ministack import app as app_mod+ from ministack.core.responses import request_scope++ key = "test-sts-mode-key"+ account = "000000000000"+ monkeypatch.setattr(app_mod, "AUTH", auth_enabled)+ if credential_kind == "inactive":+ iam_svc._access_keys.set_scoped(account, None, key, {+ "UserName": "alice", "Status": "Inactive", "SecretAccessKey": "secret",+ })+ if credential_kind == "expired":+ sts_svc._sessions[key] = {+ "Arn": f"arn:aws:sts::{account}:assumed-role/role/session",+ "UserId": "role:session", "SecretAccessKey": "secret",+ "Expiration": time.time() - 60,+ }+ previous = set(sts_svc._sessions)+ try:+ with request_scope(account, "us-east-1"):+ status, _, _ = asyncio.run(sts_svc.handle_request(+ "GET", "/", {+ "authorization": f"AWS4-HMAC-SHA256 Credential={key}/20260911/us-east-1/sts/aws4_request",+ }, b"", {+ "Action": [action], "RoleArn": [f"arn:aws:iam::{account}:role/role"],+ "RoleSessionName": ["session"],+ },+ ))+ assert status == (403 if auth_enabled else 200)+ finally:+ iam_svc._access_keys.pop_scoped(account, None, key, None)+ for created in set(sts_svc._sessions) - previous:+ sts_svc._sessions.pop(created, None)+ sts_svc._sessions.pop(key, None)+++def test_presigned_mrap_resolves_alias_in_iam_owner_account(monkeypatch):+ from urllib.parse import parse_qs, urlsplit++ from botocore.auth import S3SigV4QueryAuth+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials++ from ministack import app as app_mod+ from ministack.core.responses import get_account_id, request_scope+ from ministack.services import s3 as s3_svc++ key, owner, alias = "test-mrap-owner-key", "123456789012", "testalias.mrap"+ host = f"{alias}.accesspoint.s3-global.amazonaws.com"+ monkeypatch.setattr(app_mod, "AUTH", False)+ request = AWSRequest(method="GET", url=f"http://{host}/object")+ S3SigV4QueryAuth(Credentials(key, "secret"), "s3", "us-east-1").add_auth(request)+ url = urlsplit(request.url)+ routed = []++ async def capture(method, path, headers, body, query_params, **kwargs):+ routed.append((get_account_id(), path))+ return 200, {}, b"object"++ monkeypatch.setattr(s3_svc, "handle_request", capture)+ iam_svc._access_keys.set_scoped(owner, None, key, {+ "UserName": "alice", "Status": "Active", "SecretAccessKey": "secret",+ })+ s3_svc._mraps.set_scoped(owner, None, alias, {"Regions": ["member-bucket"]})+ try:+ with request_scope("000000000000", "us-east-1"):+ result = asyncio.run(app_mod._handle_s3_vhost_request(+ host, url.path, "GET", {"host": host}, b"", parse_qs(url.query),+ ))+ assert result[0] == 200+ assert routed == [(owner, "/member-bucket/object")]+ finally:+ iam_svc._access_keys.pop_scoped(owner, None, key, None)+ s3_svc._mraps.pop_scoped(owner, None, alias, None)+++def test_resolve_get_session_token_principal_retains_user_policies():+ access_key = "test-session-access-key"+ account_id = "123456789012"+ user_name = "alice"+ iam_svc._users.set_scoped(account_id, None, user_name, {+ "UserName": user_name,+ "UserId": "AIDAALICE",+ "AttachedPolicies": [],+ })+ iam_svc._user_inline_policies[user_name] = {+ "allow-s3": {+ "Statement": [{+ "Effect": "Allow",+ "Action": "s3:GetObject",+ "Resource": "*",+ }],+ },+ }+ sts_svc._sessions[access_key] = {+ "Arn": f"arn:aws:iam::{account_id}:user/team/{user_name}",+ "UserId": "AIDAALICE",+ "SecretAccessKey": "session-secret",+ "SessionToken": "session-token",+ "Expiration": time.time() + 60,+ "AccountId": account_id,+ "PrincipalType": "User",+ "PrincipalName": user_name,+ "SourceAccessKeyId": "AKIAALICE",+ }+ try:+ principal = resolve_principal(access_key, account_id)++ assert isinstance(principal, PrincipalInfo)+ assert principal.type == "User"+ assert principal.arn == (+ f"arn:aws:iam::{account_id}:user/team/{user_name}"+ )+ assert principal.policies+ assert principal.policies[0][0].actions == ["s3:GetObject"]+ finally:+ sts_svc._sessions.pop(access_key, None)+ iam_svc._user_inline_policies.pop(user_name, None)+ iam_svc._users.pop_scoped(account_id, None, user_name, None)diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex e1d3100e..d97d4b93 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -1899,7 +1899,8 @@ def test_role_session_uses_account_from_session_arn():}_request_account_id.reset(token)sts_svc._sessions["ASIASESSIONACCOUNT"] = {- "Arn": f"arn:aws:sts::{account_id}:assumed-role/{role_name}/lambda"+ "Arn": f"arn:aws:sts::{account_id}:assumed-role/{role_name}/lambda",+ "SecretAccessKey": "test-session-secret",}try:principal = resolve_principal("ASIASESSIONACCOUNT", "000000000000")diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 279b48a4..a0c93b31 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -3765,6 +3765,144 @@ def test_s3_presigned_url_signature_is_verified():assert status(urllib.request.Request(u, method="GET")) == 200+def test_s3_presigned_url_uses_iam_access_key_secret_and_status():+ import urllib.error+ import urllib.request+ import uuid++ import boto3+ from botocore.config import Config++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ account_id = "123456789012"+ user_name = f"presign-user-{uuid.uuid4().hex[:8]}"+ bucket = f"presign-iam-{uuid.uuid4().hex[:8]}"+ key = "hello.txt"+ tenant_iam = boto3.client(+ "iam",+ endpoint_url=endpoint,+ region_name="us-east-1",+ aws_access_key_id=account_id,+ aws_secret_access_key="test",+ )+ tenant_s3 = boto3.client(+ "s3",+ endpoint_url=endpoint,+ region_name="us-east-1",+ aws_access_key_id=account_id,+ aws_secret_access_key="test",+ config=Config(s3={"addressing_style": "path"}),+ )+ tenant_iam.create_user(UserName=user_name)+ access_key = tenant_iam.create_access_key(UserName=user_name)["AccessKey"]+ tenant_s3.create_bucket(Bucket=bucket)+ tenant_s3.put_object(Bucket=bucket, Key=key, Body=b"hi")++ client = boto3.client(+ "s3",+ endpoint_url=endpoint,+ region_name="us-east-1",+ aws_access_key_id=access_key["AccessKeyId"],+ aws_secret_access_key=access_key["SecretAccessKey"],+ config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),+ )+ url = client.generate_presigned_url(+ "get_object", Params={"Bucket": bucket, "Key": key}, ExpiresIn=300+ )++ try:+ assert urllib.request.urlopen(url).status == 200+ tenant_iam.update_access_key(+ UserName=user_name,+ AccessKeyId=access_key["AccessKeyId"],+ Status="Inactive",+ )+ with pytest.raises(urllib.error.HTTPError) as exc:+ urllib.request.urlopen(url)+ assert exc.value.code == 403+ assert b"<Code>InvalidAccessKeyId</Code>" in exc.value.read()+ finally:+ tenant_iam.delete_access_key(+ UserName=user_name,+ AccessKeyId=access_key["AccessKeyId"],+ )+ tenant_iam.delete_user(UserName=user_name)+++def test_s3_presigned_url_requires_exact_sts_session_token(s3, sts):+ import urllib.error+ import urllib.request+ import uuid++ import boto3+ from botocore.config import Config++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ bucket = f"presign-sts-{uuid.uuid4().hex[:8]}"+ key = "hello.txt"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key=key, Body=b"hi")+ credentials = sts.get_session_token(DurationSeconds=900)["Credentials"]+ config = Config(signature_version="s3v4", s3={"addressing_style": "path"})++ def presign(session_token=None):+ client = boto3.client(+ "s3",+ endpoint_url=endpoint,+ region_name="us-east-1",+ aws_access_key_id=credentials["AccessKeyId"],+ aws_secret_access_key=credentials["SecretAccessKey"],+ aws_session_token=session_token,+ config=config,+ )+ return client.generate_presigned_url(+ "get_object", Params={"Bucket": bucket, "Key": key}, ExpiresIn=300+ )++ assert urllib.request.urlopen(presign(credentials["SessionToken"])).status == 200+ for bad_token in (None, "wrong-session-token"):+ with pytest.raises(urllib.error.HTTPError) as exc:+ urllib.request.urlopen(presign(bad_token))+ assert exc.value.code == 403+ assert b"<Code>InvalidToken</Code>" in exc.value.read()+++def test_s3_presigned_url_accepts_lenient_session_origin(s3):+ import urllib.request+ import uuid++ import boto3+ from botocore.config import Config++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ bucket = f"presign-lenient-sts-{uuid.uuid4().hex[:8]}"+ key = "hello.txt"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key=key, Body=b"hi")+ lenient_sts = boto3.client(+ "sts",+ endpoint_url=endpoint,+ region_name="us-east-1",+ aws_access_key_id="unknown-lenient-caller",+ aws_secret_access_key="unknown-lenient-secret",+ )+ credentials = lenient_sts.get_session_token(DurationSeconds=900)["Credentials"]+ client = boto3.client(+ "s3",+ endpoint_url=endpoint,+ region_name="us-east-1",+ aws_access_key_id=credentials["AccessKeyId"],+ aws_secret_access_key=credentials["SecretAccessKey"],+ aws_session_token=credentials["SessionToken"],+ config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),+ )+ url = client.generate_presigned_url(+ "get_object", Params={"Bucket": bucket, "Key": key}, ExpiresIn=300+ )++ assert urllib.request.urlopen(url).status == 200++def test_s3_presigned_url_virtual_hosted_style_is_verified():"""A virtual-hosted-style presigned URL signs the bucket-less canonical URIagainst the `{bucket}.host` Host header. MiniStack rewrites vhost → path-stylediff --git a/tests/test_sts.py b/tests/test_sts.pyindex 0aac308a..5dc1c484 100644--- a/tests/test_sts.py+++ b/tests/test_sts.py@@ -128,6 +128,210 @@ def test_sts_get_session_token(sts):assert "SessionToken" in credsassert "Expiration" in creds++def test_sts_get_session_token_retains_iam_user_identity(iam):+ import boto3++ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ user_name = "session-token-user"+ iam.create_user(UserName=user_name)+ source = iam.create_access_key(UserName=user_name)["AccessKey"]+ try:+ source_sts = boto3.client(+ "sts",+ endpoint_url=endpoint,+ region_name="us-east-1",+ aws_access_key_id=source["AccessKeyId"],+ aws_secret_access_key=source["SecretAccessKey"],+ )+ session = source_sts.get_session_token(DurationSeconds=900)["Credentials"]+ session_sts = boto3.client(+ "sts",+ endpoint_url=endpoint,+ region_name="us-east-1",+ aws_access_key_id=session["AccessKeyId"],+ aws_secret_access_key=session["SecretAccessKey"],+ aws_session_token=session["SessionToken"],+ )++ identity = session_sts.get_caller_identity()++ assert identity["Arn"] == f"arn:aws:iam::000000000000:user/{user_name}"+ assert identity["UserId"]+ finally:+ iam.delete_access_key(+ UserName=user_name,+ AccessKeyId=source["AccessKeyId"],+ )+ iam.delete_user(UserName=user_name)+++def test_sts_get_session_token_rejects_unknown_caller_when_auth_enabled(monkeypatch):+ import asyncio++ import ministack.app as app_mod+ from ministack.services import sts as sts_mod++ issued_key = "test-rejected-session-key"+ monkeypatch.setattr(app_mod, "AUTH", True)+ monkeypatch.setattr(sts_mod, "_gen_session_access_key", lambda: issued_key)+ body = b"Action=GetSessionToken&Version=2011-06-15&DurationSeconds=900"+ headers = {+ "authorization": (+ "AWS4-HMAC-SHA256 "+ "Credential=unknown-caller/20260908/us-east-1/sts/aws4_request"+ ),+ "content-type": "application/x-www-form-urlencoded",+ }++ status, _headers, payload = asyncio.run(+ sts_mod.handle_request("POST", "/", headers, body, {})+ )++ assert status == 403+ assert b"UnrecognizedClientException" in payload+ assert issued_key not in sts_mod._sessions+++def test_sts_get_session_token_resolves_query_signed_iam_caller(monkeypatch):+ import asyncio++ import ministack.app as app_mod+ from ministack.core.responses import get_account_id, set_request_account_id+ from ministack.services import iam as iam_svc+ from ministack.services import sts as sts_mod++ account_id = "123456789012"+ user_name = "query-user"+ source_key = "test-query-user-key"+ issued_key = "test-issued-session-key"+ original_account = get_account_id()+ monkeypatch.setattr(app_mod, "AUTH", True)+ monkeypatch.setattr(sts_mod, "_gen_session_access_key", lambda: issued_key)+ set_request_account_id(account_id)+ iam_svc._users.set_scoped(account_id, None, user_name, {+ "UserName": user_name,+ "UserId": "test-query-user-id",+ "Arn": f"arn:aws:iam::{account_id}:user/team/{user_name}",+ "Path": "/team/",+ "AttachedPolicies": [],+ })+ iam_svc._access_keys.set_scoped(account_id, None, source_key, {+ "AccessKeyId": source_key,+ "SecretAccessKey": "test-query-user-secret",+ "Status": "Active",+ "UserName": user_name,+ })+ query = {+ "Action": ["GetSessionToken"],+ "DurationSeconds": ["900"],+ "X-Amz-Credential": [+ f"{source_key}/20260908/us-east-1/sts/aws4_request"+ ],+ }+ try:+ status, _headers, _payload = asyncio.run(+ sts_mod.handle_request("GET", "/", {}, b"", query)+ )++ assert status == 200+ assert sts_mod._sessions[issued_key]["Arn"] == (+ f"arn:aws:iam::{account_id}:user/team/{user_name}"+ )+ assert sts_mod._sessions[issued_key]["PrincipalType"] == "User"+ assert sts_mod._sessions[issued_key]["PrincipalName"] == user_name+ assert sts_mod._sessions[issued_key]["SourceAccessKeyId"] == source_key+ finally:+ sts_mod._sessions.pop(issued_key, None)+ iam_svc._access_keys.pop_scoped(account_id, None, source_key, None)+ iam_svc._users.pop_scoped(account_id, None, user_name, None)+ set_request_account_id(original_account)++++[email protected]("auth_enabled", [False, True])+def test_sts_get_caller_identity_rejects_expired_session(monkeypatch, auth_enabled):+ import asyncio+ import time++ import ministack.app as app_mod+ from ministack.core.responses import get_account_id+ from ministack.services import sts as sts_mod++ account_id = get_account_id()+ access_key = "test-expired-identity-session"+ monkeypatch.setattr(app_mod, "AUTH", auth_enabled)+ sts_mod._sessions[access_key] = {+ "Arn": f"arn:aws:iam::{account_id}:user/expired-user",+ "UserId": "test-expired-user-id",+ "SecretAccessKey": "test-expired-secret",+ "SessionToken": "test-expired-token",+ "Expiration": time.time() - 1,+ "AccountId": account_id,+ "PrincipalType": "User",+ "PrincipalName": "expired-user",+ }+ query = {"Action": ["GetCallerIdentity"]}+ headers = {+ "authorization": (+ "AWS4-HMAC-SHA256 "+ f"Credential={access_key}/20260908/us-east-1/sts/aws4_request"+ )+ }+ try:+ status, _headers, payload = asyncio.run(+ sts_mod.handle_request("GET", "/", headers, b"", query)+ )++ assert status == 403+ assert b"<Code>ExpiredToken</Code>" in payload+ finally:+ sts_mod._sessions.pop(access_key, None)+++def test_sts_get_session_token_rejects_temporary_caller_when_auth_enabled(monkeypatch):+ import asyncio+ import time++ import ministack.app as app_mod+ from ministack.core.responses import get_account_id+ from ministack.services import sts as sts_mod++ account_id = get_account_id()+ source_key = "test-temporary-source-key"+ issued_key = "test-renewed-session-key"+ monkeypatch.setattr(app_mod, "AUTH", True)+ monkeypatch.setattr(sts_mod, "_gen_session_access_key", lambda: issued_key)+ sts_mod._sessions[source_key] = {+ "Arn": f"arn:aws:iam::{account_id}:user/session-user",+ "UserId": "test-session-user-id",+ "SecretAccessKey": "test-temporary-secret",+ "SessionToken": "test-temporary-token",+ "Expiration": time.time() + 900,+ "AccountId": account_id,+ "PrincipalType": "User",+ }+ body = b"Action=GetSessionToken&Version=2011-06-15&DurationSeconds=900"+ headers = {+ "authorization": (+ "AWS4-HMAC-SHA256 "+ f"Credential={source_key}/20260908/us-east-1/sts/aws4_request"+ ),+ "content-type": "application/x-www-form-urlencoded",+ }+ try:+ status, _headers, payload = asyncio.run(+ sts_mod.handle_request("POST", "/", headers, body, {})+ )++ assert status == 403+ assert b"AccessDenied" in payload+ assert issued_key not in sts_mod._sessions+ finally:+ sts_mod._sessions.pop(source_key, None)++def test_sts_assume_role_with_web_identity(sts, iam):iam.create_role(RoleName="test-oidc-role",