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): authorize RDS Data and S3 Control tagging under AUTH=true (#2275)
iot-rocketaae1df571a0f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6c3241ee..56718618 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,12 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **RDS Data, S3 Control — calls are authorized under `AUTH=true`** — RDS Data calls and S3 Control tagging calls were served whatever the caller's policies allowed; each RDS Data call is now authorized as `rds-data:<operation>` on the cluster its `resourceArn` names, and `ListTagsForResource`, `TagResource` and `UntagResource` as `s3:<operation>` on the bucket, with a 403 denial (`AccessDeniedException` from RDS Data, `AccessDenied` from S3 Control) naming the action and resource, as on AWS. Contributed by @iot-rocket.+- **SES v2 — calls are authorized under `AUTH=true`** — SES v2 calls were served whatever the caller's policies allowed; each is now authorized as `ses:<operation>` on the configuration set, contact list, custom verification email template, dedicated IP pool, identity or template its path or create body names (`*` otherwise), and a denial answers 403 `AccessDeniedException` naming the action and resource, as on AWS. Contributed by @iot-rocket.++### Fixed+- **Auth — requests that map to no IAM action are authenticated** — under `AUTH=true` a request MiniStack maps to no IAM action (SES v2, RDS Data, S3 Control, or a service MiniStack does not implement such as X-Ray) was served with a wrong secret, an unknown key, a session key without its token or a stale signature; it now answers the credential error AWS sends for the service, for example `InvalidSignatureException` 403 from SES v2 and RDS Data and `SignatureDoesNotMatch` 403 from S3 Control. Contributed by @iot-rocket.### Fixed- **Cognito — `AdminDisableUser` revokes the user's tokens under `AUTH=true`** — a disabled user's access and refresh tokens kept working, also after `AdminEnableUser`; with `AUTH=true` they are now refused with `User is disabled.` while the user is disabled, and the sessions from before stay revoked once the user is enabled again (`Access Token has been revoked`, `Refresh Token has been revoked`, `invalid_grant` at `/oauth2/token`), as AWS does, and the access token of a deleted user gets `UserNotFoundException: User does not exist.` Contributed by @iot-rocket.- **Cognito — `/oauth2/userInfo` requires the `openid` scope under `AUTH=true`** — an access token without the `openid` scope, such as the token of a user pool API sign-in or of a Hosted UI grant of `email` alone, returned the user's attributes; with `AUTH=true` it now answers 401 `invalid_token` `Access token does not contain the 'openid' scope` once the token, its `username` and the user have passed the other checks. Contributed by @iot-rocket.diff --git a/ministack/app.py b/ministack/app.pyindex 30d9ac33..85bf46cc 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -168,6 +168,10 @@ _BODY_METHODS = ("POST", "PUT", "PATCH")_COGNITO_USERINFO_PATHS = ("/oauth2/userInfo", "/oauth2/userinfo")_RDS_DATA_PATHS = ("/Execute", "/BeginTransaction", "/CommitTransaction", "/RollbackTransaction", "/BatchExecute")_S3_CONTROL_PREFIX = "/v20180820/"+# S3 Control tagging calls on a bucket ARN; older SDKs send TagResource as PUT.+_S3_CONTROL_TAG_ACTIONS = {+ "GET": "s3:ListTagsForResource", "POST": "s3:TagResource", "PUT": "s3:TagResource", "DELETE": "s3:UntagResource",+}_SES_V2_PREFIX = "/v2/email"_ALB_PATH_PREFIX = "/_alb/"_NON_S3_VHOST_NAMES = frozenset(@@ -1612,6 +1616,8 @@ async def _handle_s3_control_request(path: str, method: str, body: bytes, query_resource_arn=resource)if denied:return denied+ elif failure := _authenticate_only("s3", headers, query_params, request_id):+ return failureif is_mrap:handler = s3.handle_mrap_controlelif is_object_lambda:@@ -1628,6 +1634,14 @@ async def _handle_s3_control_request(path: str, method: str, body: bytes, query_raw_arn = path[len("/v20180820/tags/") :]arn = unquote(raw_arn)bucket_name = arn.split(":::")[-1].split("/")[0] if ":::" in arn else arn.split("/")[0]+ resource_arn = arn if arn.startswith("arn:") else f"arn:aws:s3:::{bucket_name}"+ iam_action = _S3_CONTROL_TAG_ACTIONS.get(method)+ if iam_action and (denied := _enforce_data_plane("s3", iam_action, headers, query_params, request_id,+ resource_arn=resource_arn,+ named_resource=f'"{resource_arn}"')):+ return denied+ if not iam_action and (failure := _authenticate_only("s3", headers, query_params, request_id)):+ return failureif method == "GET":tags = _get_module("s3")._bucket_tags.get(bucket_name, {})@@ -1708,6 +1722,8 @@ async def _handle_s3_control_request(path: str, method: str, body: bytes, query_b"{}",)+ if failure := _authenticate_only("s3", headers, query_params, request_id):+ return failure# An undefined /v20180820 path answers 400 InvalidURI inside an# <ErrorResponse> wrapper, with <URI> echoing the bad segment (measured eu-north-1 2026-09-19).from xml.sax.saxutils import escape as _xml_esc@@ -1734,17 +1750,37 @@ async def _handle_s3_control_request(path: str, method: str, body: bytes, query_)-async def _handle_rds_data_request(method: str, path: str, headers: dict, body: bytes, query_params: dict):+async def _handle_rds_data_request(+ method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str+):"""Handle RDS Data API operations before generic routing."""if path not in _RDS_DATA_PATHS:return None+ if AUTH and (denied := _enforce_rds_data(method, path, headers, body, query_params, request_id)):+ return deniedreturn await _get_module("rds_data").handle_request(method, path, headers, body, query_params)-async def _handle_ses_v2_request(method: str, path: str, headers: dict, body: bytes, query_params: dict):+def _enforce_rds_data(method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str):+ """Authorize an RDS Data call as rds-data:<operation> on the cluster its body names."""+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn++ iam_action = extract_iam_action("rds-data", method, path, headers, body, query_params)+ if iam_action is None:+ return _authenticate_only("rds-data", headers, query_params, request_id)+ resource_arn = extract_resource_arn("rds-data", method, path, headers, body, query_params, "", "")+ return _enforce_data_plane("rds-data", iam_action, headers, query_params, request_id,+ resource_arn=resource_arn, named_resource=resource_arn)+++async def _handle_ses_v2_request(+ method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str+):"""Handle SES v2 REST API operations before generic routing."""if not path.startswith(_SES_V2_PREFIX):return None+ if denied := _enforce_ses_v2(method, path, headers, body, query_params, request_id):+ return deniedreturn await _get_module("ses_v2").handle_request(method, path, headers, body, query_params)@@ -2315,19 +2351,31 @@ def _credential_failure(service: str, iam_action: str, request_id: str, denied,return status, resp_headers, body+def _authenticate_only(service: str, headers: dict, query_params: dict, request_id: str):+ """Under AUTH, refuse a request no IAM action covers when its credentials fail."""+ if not AUTH:+ return None+ from ministack.core.iam_evaluator import check_credentials++ failure = check_credentials(extract_access_key_id(headers, query_params))+ return _credential_failure(service, "", request_id, failure, headers) if failure else None++def _enforce_data_plane(service: str, iam_action: str, headers: dict, query_params: dict, request_id: str, resource_arn: str = "*",- service_context: dict | None = None, auth_error_response=None,+ service_context: dict | None = None, auth_error_response=None, named_resource: str = "",):"""Enforce IAM auth on a data-plane path. Returns error tuple or None.``service_context`` carries the request's own condition keys, for a paththat has them. The generic router resolves those itself; a data-planehandler has to pass them, because it knows the resource the router does not.+ ``named_resource`` is the resource an identity-policy denial names, in the+ error Content-Type of the service, for the services that word it so."""if not AUTH:return None- from ministack.core.iam_actions import access_denied_response+ from ministack.core.iam_actions import access_denied_response, identity_denial_messagefrom ministack.core.iam_evaluator import AuthError, enforceaccess_key = extract_access_key_id(headers, query_params)@@ -2337,12 +2385,35 @@ def _enforce_data_plane(if isinstance(denied, AuthError):response = auth_error_response(denied) if auth_error_response else Nonereturn response or _credential_failure(service, iam_action, request_id, denied, headers)- return access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers,- explicit_deny=denied.decision == "Deny",- resource_policy_arn=denied.resource_policy_arn)+ explicit = denied.decision == "Deny"+ message = ""+ if named_resource and not (explicit and denied.resource_policy_arn):+ message = identity_denial_message(iam_action, denied.principal_arn, named_resource, explicit)+ response = access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers,+ message=message, explicit_deny=explicit,+ resource_policy_arn=denied.resource_policy_arn)+ if named_resource:+ fix_error_content_type(service, response[0], response[1])+ return responsereturn None+def _enforce_ses_v2(method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str):+ """Authorize an SES v2 call as ses:<operation> on the resource it names, which its denial names too."""+ if not AUTH:+ return None+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn+ from ministack.core.responses import get_account_id++ iam_action = extract_iam_action("ses", method, path, headers, body, query_params)+ if iam_action is None:+ return _authenticate_only("sesv2", headers, query_params, request_id)+ resource_arn = extract_resource_arn("ses", method, path, headers, body, query_params,+ extract_region(headers, query_params), get_account_id())+ return _enforce_data_plane("sesv2", iam_action, headers, query_params, request_id, resource_arn=resource_arn,+ named_resource=resource_arn)++def _iceberg_targets_glue_catalog(path, query_params):"""Decide whether an ``/iceberg`` REST request belongs to the Glue DataCatalog (Glue jobs + Firehose lakehouse) or to S3 Tables.@@ -2410,9 +2481,9 @@ async def _handle_special_data_plane_request(return 500, {"Content-Type": "application/json"}, json.dumps({"error": str(e)}).encode()if response := await _handle_s3_control_request(path, method, body, query_params, request_id, headers):return response- if response := await _handle_rds_data_request(method, path, headers, body, query_params):+ if response := await _handle_rds_data_request(method, path, headers, body, query_params, request_id):return response- if response := await _handle_ses_v2_request(method, path, headers, body, query_params):+ if response := await _handle_ses_v2_request(method, path, headers, body, query_params, request_id):return responseif response := await _handle_ecr_registry_request(method, path, headers, body, query_params):return _with_data_plane_headers(response, request_id)@@ -2729,6 +2800,8 @@ async def _dispatch_service_request(pin_request_caller(headers, query_params)iam_action = extract_iam_action(service, method, path, headers, body, routing_params)+ if iam_action is None and (failure := _authenticate_only(service, headers, query_params, request_id)):+ return failureif iam_action is not None:access_key = extract_access_key_id(headers, query_params)resource_arn = extract_resource_arn(diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 5fece287..fb6dae89 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -550,11 +550,13 @@ _BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {"airflow": ["mwaa"],"opensearch": ["opensearch"],"pipes": ["pipes"],+ "rds-data": ["rds-data"],"resource-groups": ["resource-groups"],"route53": ["route53"],"s3files": [], # uses S3 namespace but different paths"s3tables": ["s3tables"],"scheduler": ["scheduler"],+ "ses": ["sesv2"], # the v2 REST API; v1 names its Action"signer": ["signer"],}@@ -809,6 +811,8 @@ def extract_iam_action(service: str, method: str, path: str,action_name = _match_rest_action(service, method, path, query_params)if action_name:return f"{_IAM_NAMESPACE_BY_OPERATION.get((service, action_name), namespace)}:{action_name}"+ if service == "ses" and method == "GET" and path.rstrip("/") in _SES_V2_LEGACY_LIST_ROUTES:+ return f"ses:{_SES_V2_LEGACY_LIST_ROUTES[path.rstrip('/')]}"logger.debug("AUTH: could not extract action for %s %s %s — allowing",service, method, path)@@ -934,6 +938,33 @@ def _kms_key_id_from_ciphertext(ciphertext_b64: str) -> str:return candidate if _KMS_KEY_ID_RE.match(candidate) else ""+# Older SDK models send these SES v2 list calls as GET on the collection; the current model lists with POST.+_SES_V2_LEGACY_LIST_ROUTES = {+ "/v2/email/identities": "ListEmailIdentities",+ "/v2/email/configuration-sets": "ListConfigurationSets",+}++# SES v2 path collection -> the resource type it names, and the body field that names it on create.+_SES_V2_RESOURCES = {+ "configuration-sets": ("configuration-set", "ConfigurationSetName"),+ "contact-lists": ("contact-list", "ContactListName"),+ "custom-verification-email-templates": ("custom-verification-email-template", "TemplateName"),+ "dedicated-ip-pools": ("dedicated-ip-pool", "PoolName"),+ "identities": ("identity", "EmailIdentity"),+ "templates": ("template", "TemplateName"),+}+++def _ses_v2_resource_arn(method: str, path: str, body: bytes, region: str, account_id: str) -> str:+ """The SES v2 resource a /v2/email path or create body names, or '*'."""+ parts = [p for p in path.split("/") if p]+ if parts[:2] != ["v2", "email"] or len(parts) < 3 or parts[2] not in _SES_V2_RESOURCES:+ return "*"+ resource_type, create_field = _SES_V2_RESOURCES[parts[2]]+ name = parts[3] if len(parts) > 3 else _safe_json_field(body, create_field) if method == "POST" else ""+ return f"arn:aws:ses:{region}:{account_id}:{resource_type}/{name}" if name else "*"++def extract_resource_arn(service: str, method: str, path: str,headers: dict, body: bytes,query_params: dict, region: str,@@ -1338,7 +1369,7 @@ def extract_resource_arn(service: str, method: str, path: str,identity = _query_param(query_params, "Identity")if identity:return f"arn:aws:ses:{region}:{account_id}:identity/{identity}"- return "*"+ return _ses_v2_resource_arn(method, path, body, region, account_id)if service == "signer":# StartSigningJob, GetSigningProfile, CancelSigningProfile and the@@ -2074,6 +2105,15 @@ def _resource_policy_denial(service: str, action: str, principal_arn: str, resou"with an explicit deny in a resource-based policy")+def identity_denial_message(action: str, principal_arn: str, resource: str, explicit_deny: bool) -> str:+ """The message of a denial an identity-based policy decided, naming the resource."""+ reason = (+ "with an explicit deny in an identity-based policy" if explicit_deny+ else f"because no identity-based policy allows the {action} action"+ )+ return f"User: {principal_arn} is not authorized to perform: {action} on resource: {resource} {reason}"++def access_denied_response(service: str, action: str, principal_arn: str,request_id: str, *, error_code: str = "",message: str = "", headers: dict | None = None,@@ -2089,14 +2129,7 @@ def access_denied_response(service: str, action: str, principal_arn: str,if service in {"ssm", "logs"} and not error_code:# SSM and Logs authorization denials are HTTP 400, JSON 1.1, with a# capitalized Message naming the resource, as observed on live AWS.- reason = (- "with an explicit deny in an identity-based policy" if explicit_deny- else f"because no identity-based policy allows the {action} action"- )- message = (- f"User: {principal_arn} is not authorized to perform: {action} "- f"on resource: {resource_arn} {reason}"- )+ message = identity_denial_message(action, principal_arn, resource_arn, explicit_deny)return (400, {"Content-Type": "application/x-amz-json-1.1"},json.dumps({"__type": "AccessDeniedException", "Message": message}).encode(),diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex 3d57c649..51da1d17 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -1333,6 +1333,17 @@ def authenticate(access_key_id: str, account_id: str) -> AuthError | ResolvedCrereturn AuthError(*failure) if failure else credential+def check_credentials(access_key_id: str) -> AuthError | None:+ """Authenticate a request no IAM action covers, with the checks enforce() makes before any policy."""+ from ministack.core.responses import get_account_id++ account_id = get_account_id()+ checked = authenticate(access_key_id or "", account_id)+ if checked is None:+ checked = resolve_principal(access_key_id or "", account_id)+ return checked if isinstance(checked, AuthError) else None++# ---------------------------------------------------------------------------# Top-level enforcement entry point# ---------------------------------------------------------------------------diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex b43ed3c9..583215e7 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -2215,6 +2215,24 @@ class TestResourceArn:from ministack.core.iam_actions import extract_resource_arnassert extract_resource_arn("ssm", "POST", "/", {}, b"", {"Name": ["/app/config"]}, "us-east-1", "123") == "arn:aws:ssm:us-east-1:123:parameter/app/config"+ @pytest.mark.parametrize("method,path,body,resource", [+ ("GET", "/v2/email/account", b"", "*"),+ ("POST", "/v2/email/list-identities", b"{}", "*"),+ ("POST", "/v2/email/configuration-sets", b'{"ConfigurationSetName": "cs"}', "configuration-set/cs"),+ ("DELETE", "/v2/email/configuration-sets/cs", b"", "configuration-set/cs"),+ ("PUT", "/v2/email/configuration-sets/cs/event-destinations/d", b"{}", "configuration-set/cs"),+ ("POST", "/v2/email/templates", b'{"TemplateName": "t"}', "template/t"),+ ("GET", "/v2/email/templates/t", b"", "template/t"),+ ("POST", "/v2/email/contact-lists", b'{"ContactListName": "c"}', "contact-list/c"),+ ("GET", "/v2/email/identities/a.example.com", b"", "identity/a.example.com"),+ ("GET", "/v2/email/custom-verification-email-templates/v", b"", "custom-verification-email-template/v"),+ ("GET", "/v2/email/dedicated-ip-pools/p", b"", "dedicated-ip-pool/p"),+ ("POST", "/v2/email/outbound-emails", b"{}", "*"),+ ])+ def test_ses_v2_resource(self, method, path, body, resource):+ arn = extract_resource_arn("ses", method, path, {}, body, {}, "us-east-1", "123")+ assert arn == (resource if resource == "*" else f"arn:aws:ses:us-east-1:123:{resource}")+def test_signer_profile_and_job(self):from ministack.core.iam_actions import extract_resource_arnjob_body = b'{"profileName": "fleet", "source": {"s3": {}}}'@@ -2978,6 +2996,25 @@ class TestActionExtraction:assert extract_iam_action("lambda", "DELETE", path, {}, b"", {"tagKeys": ["a"]}) == "lambda:UntagResource"assert extract_iam_action("lambda", "GET", path, {}, b"", {}) == "lambda:ListTags"+ def test_ses_v2_rest(self):+ assert extract_iam_action("ses", "GET", "/v2/email/account", {}, b"", {}) == "ses:GetAccount"+ assert extract_iam_action("ses", "POST", "/v2/email/list-identities", {}, b"{}", {}) == (+ "ses:ListEmailIdentities")+ assert extract_iam_action("ses", "DELETE", "/v2/email/configuration-sets/cs", {}, b"", {}) == (+ "ses:DeleteConfigurationSet")+ assert extract_iam_action("ses", "GET", "/v2/email/templates/t", {}, b"", {}) == "ses:GetEmailTemplate"+ assert extract_iam_action("ses", "POST", "/", {}, b"", {"Action": ["ListIdentities"]}) == "ses:ListIdentities"+ # older SDK models list with GET on the collection+ assert extract_iam_action("ses", "GET", "/v2/email/identities", {}, b"", {}) == "ses:ListEmailIdentities"+ assert extract_iam_action("ses", "GET", "/v2/email/configuration-sets", {}, b"", {}) == (+ "ses:ListConfigurationSets")++ def test_rds_data_rest(self):+ for path, action in (("/Execute", "ExecuteStatement"), ("/BatchExecute", "BatchExecuteStatement"),+ ("/BeginTransaction", "BeginTransaction"), ("/CommitTransaction", "CommitTransaction"),+ ("/RollbackTransaction", "RollbackTransaction")):+ assert extract_iam_action("rds-data", "POST", path, {}, b"{}", {}) == f"rds-data:{action}"+def test_unknown_service_returns_none(self):from ministack.core.iam_actions import extract_iam_actionassert extract_iam_action("unknown_svc", "GET", "/", {}, b"", {}) is None@@ -5182,6 +5219,77 @@ class TestQuerySignatures:assert _presigned(user_key[0], "wrong-secret", "iam", _LIST_USERS)[:2] == (None, 200)+# SES v2 is authorized in its own handler; RDS Data, S3 Control and X-Ray (no+# MiniStack service) map to no IAM action. All of them check credentials.+_NO_ACTION_CALLS = {+ "sesv2": lambda c: c.get_account(),+ "xray": lambda c: c.get_sampling_rules(),+ "rds-data": lambda c: c.execute_statement(+ resourceArn="arn:aws:rds:us-east-1:000000000000:cluster:none",+ secretArn="arn:aws:secretsmanager:us-east-1:000000000000:secret:none", sql="select 1"),+ "s3control": lambda c: c.list_tags_for_resource(AccountId="000000000000", ResourceArn="arn:aws:s3:::none"),+}+++def _contract_client(service, key, secret, token=None):+ """A client of the running server with the given credentials and no retries."""+ import boto3+ from botocore.config import Config+ from conftest import ENDPOINT, REGION++ return boto3.client(service, endpoint_url=ENDPOINT, region_name=REGION, aws_access_key_id=key,+ aws_secret_access_key=secret, aws_session_token=token,+ config=Config(retries={"total_max_attempts": 1}, inject_host_prefix=False))++[email protected]_contract[email protected]("service,wrong_secret,unknown_key,expired,content_type", [+ ("sesv2", "InvalidSignatureException", "UnrecognizedClientException", "InvalidSignatureException",+ "application/x-amz-json-1.1"),+ ("xray", "InvalidSignatureException", "UnrecognizedClientException", "InvalidSignatureException",+ "application/json"),+ ("rds-data", "InvalidSignatureException", "UnrecognizedClientException", "InvalidSignatureException",+ "application/json"),+ ("s3control", "SignatureDoesNotMatch", "InvalidAccessKeyId", "RequestTimeTooSkewed", "application/xml"),+], ids=["sesv2", "xray", "rds-data", "s3control"])+def test_credentials_without_an_iam_action_contract(auth_enabled, iam_user, service, wrong_secret, unknown_key,+ expired, content_type):+ """A wrong secret, an unknown key, a session key without its token and a stale signature are refused."""+ from botocore.config import Config+ from conftest import make_client++ user = iam_user(policy={"Version": "2012-10-17",+ "Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]})+ key_id = make_client("iam").list_access_keys(UserName=user.name)["AccessKeyMetadata"][0]["AccessKeyId"]+ session = user.client("sts").get_session_token()["Credentials"]+ call = _NO_ACTION_CALLS[service]++ def answer(client):+ try:+ call(client)+ except ClientError as e:+ return e.response["Error"]["Code"], e.response["ResponseMetadata"]["HTTPStatusCode"], (+ e.response["ResponseMetadata"]["HTTPHeaders"].get("content-type"))+ return None, 200, None++ with _signing_clock(-960):+ stale = answer(user.client(service, config=Config(inject_host_prefix=False)))+ answers = [+ answer(_contract_client(service, key_id, "wrong-secret")),+ answer(_contract_client(service, "AKIAUNKNOWNKEY000001", "secret")),+ answer(_contract_client(service, session["AccessKeyId"], session["SecretAccessKey"])),+ stale,+ ]+ control = answer(user.client(service, config=Config(inject_host_prefix=False)))+ assert control[1] != 403+ if auth_enabled:+ assert [a[:2] for a in answers] == [(wrong_secret, 403), (unknown_key, 403), (unknown_key, 403),+ (expired, 403)]+ assert answers[0][2] == content_type+ else:+ assert answers == [control] * 4++class TestSessionTokens:@pytest.fixturedef session(self, user_key):diff --git a/tests/test_rds_data.py b/tests/test_rds_data.pyindex 6a40ebfe..f7648e7b 100644--- a/tests/test_rds_data.py+++ b/tests/test_rds_data.py@@ -145,6 +145,45 @@ def test_execute_nonexistent_cluster():assert "not found" in body.get("message", body.get("Message", "")).lower()[email protected]_contract[email protected]("operation,action,params,cluster,reason", [+ ("execute_statement", "ExecuteStatement", {"sql": "select 1"}, "other", None),+ ("batch_execute_statement", "BatchExecuteStatement", {"sql": "select 1"}, "other", None),+ ("begin_transaction", "BeginTransaction", {}, "other", None),+ ("commit_transaction", "CommitTransaction", {"transactionId": "t"}, "other", None),+ ("rollback_transaction", "RollbackTransaction", {"transactionId": "t"}, "other", None),+ ("execute_statement", "ExecuteStatement", {"sql": "select 1"}, "denied",+ "with an explicit deny in an identity-based policy"),+], ids=["execute", "batch-execute", "begin", "commit", "rollback", "explicit-deny"])+def test_rds_data_authorization_contract(auth_enabled, iam_user, operation, action, params, cluster, reason):+ """An RDS Data call is authorized as rds-data:<operation> on the cluster its resourceArn names."""+ name = f"rdsdata-{uuid.uuid4().hex[:8]}"+ clusters = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:cluster:{name}"+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": ["rds-data:ExecuteStatement", "rds-data:BeginTransaction"],+ "Resource": f"{clusters}-allowed"},+ {"Effect": "Deny", "Action": "rds-data:ExecuteStatement", "Resource": f"{clusters}-denied"},+ ]})+ rds = user.client("rds-data")+ allowed = {"resourceArn": f"{clusters}-allowed", "secretArn": FAKE_SECRET_ARN}+ for call in (lambda: rds.execute_statement(**allowed, sql="select 1"), lambda: rds.begin_transaction(**allowed)):+ with pytest.raises(ClientError) as served:+ call()+ assert served.value.response["Error"]["Code"] == "BadRequestException"+ with pytest.raises(ClientError) as exc:+ getattr(rds, operation)(resourceArn=f"{clusters}-{cluster}", secretArn=FAKE_SECRET_ARN, **params)+ response = exc.value.response+ if not auth_enabled:+ assert response["Error"]["Code"] == "BadRequestException"+ return+ reason = reason or f"because no identity-based policy allows the rds-data:{action} action"+ assert (response["ResponseMetadata"]["HTTPStatusCode"], response["Error"]["Code"]) == (+ 403, "AccessDeniedException")+ assert response["Error"]["Message"] == (+ f"User: {user.arn} is not authorized to perform: rds-data:{action} on resource: {clusters}-{cluster} {reason}")+ assert response["ResponseMetadata"]["HTTPHeaders"]["content-type"] == "application/json"++def test_rds_data_resolves_cluster_arn_by_arn_region(rds, sm):east_rds = _regional_client("rds", "us-east-1")west_rds = _regional_client("rds", "us-west-2")diff --git a/tests/test_s3.py b/tests/test_s3.pyindex ade8f333..c56b1d4c 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -1156,6 +1156,49 @@ def test_s3_control_list_tags_via_s3_control_host(s3):assert "env" in bodyassert "test" in body+[email protected]_contract[email protected]("bucket,operation,action,reason", [+ ("other", "list_tags_for_resource", "ListTagsForResource", None),+ ("other", "tag_resource", "TagResource", None),+ ("other", "untag_resource", "UntagResource", None),+ ("allowed", "untag_resource", "UntagResource", "with an explicit deny in an identity-based policy"),+], ids=["list", "tag", "untag", "explicit-deny"])+def test_s3_control_tagging_authorization_contract(auth_enabled, iam_user, s3, bucket, operation, action, reason):+ """S3 Control tagging calls are authorized as s3:<operation> on the bucket."""+ name = f"s3c-auth-{_uuid_mod.uuid4().hex[:8]}"+ for suffix in ("allowed", "other"):+ s3.create_bucket(Bucket=f"{name}-{suffix}")+ try:+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": ["s3:ListTagsForResource", "s3:TagResource"],+ "Resource": f"arn:aws:s3:::{name}-allowed"},+ {"Effect": "Deny", "Action": "s3:UntagResource", "Resource": f"arn:aws:s3:::{name}-allowed"},+ ]})+ control = user.client("s3control", config=Config(inject_host_prefix=False))+ allowed = f"arn:aws:s3:::{name}-allowed"+ control.tag_resource(AccountId="000000000000", ResourceArn=allowed, Tags=[{"Key": "k", "Value": "v"}])+ assert control.list_tags_for_resource(AccountId="000000000000", ResourceArn=allowed)["Tags"] == [+ {"Key": "k", "Value": "v"}]+ arn = f"arn:aws:s3:::{name}-{bucket}"+ params = {"tag_resource": {"Tags": [{"Key": "k", "Value": "v"}]}, "untag_resource": {"TagKeys": ["k"]}}+ call = getattr(control, operation)+ if not auth_enabled:+ call(AccountId="000000000000", ResourceArn=arn, **params.get(operation, {}))+ return+ with pytest.raises(ClientError) as exc:+ call(AccountId="000000000000", ResourceArn=arn, **params.get(operation, {}))+ reason = reason or f"because no identity-based policy allows the s3:{action} action"+ response = exc.value.response+ assert (response["ResponseMetadata"]["HTTPStatusCode"], response["Error"]["Code"]) == (403, "AccessDenied")+ assert response["Error"]["Message"] == (+ f'User: {user.arn} is not authorized to perform: s3:{action} on resource: "{arn}" {reason}')+ assert response["ResponseMetadata"]["HTTPHeaders"]["content-type"] == "application/xml"+ finally:+ for suffix in ("allowed", "other"):+ s3.delete_bucket(Bucket=f"{name}-{suffix}")++class TestS3VhostGetPutObject:"""Ensure vhost style and path style requests work correctly.diff --git a/tests/test_ses.py b/tests/test_ses.pyindex 1b9b2efe..d8621cda 100644--- a/tests/test_ses.py+++ b/tests/test_ses.py@@ -517,6 +517,64 @@ def test_ses_v2_get_account(sesv2):assert resp["SendingEnabled"] is Trueassert resp["ProductionAccessEnabled"] is True++_SES_V2_ARN = "arn:aws:ses:us-east-1:000000000000"++[email protected]_contract[email protected]("call,action,resource,reason", [+ (lambda ses, n: ses.get_account(), "GetAccount", "*", None),+ (lambda ses, n: ses.list_email_identities(), "ListEmailIdentities", "*", None),+ (lambda ses, n: ses.create_configuration_set(ConfigurationSetName=f"{n}-other"),+ "CreateConfigurationSet", "configuration-set/{n}-other", None),+ (lambda ses, n: ses.get_configuration_set(ConfigurationSetName=f"{n}-other"),+ "GetConfigurationSet", "configuration-set/{n}-other", None),+ (lambda ses, n: ses.create_email_template(TemplateName=f"{n}-other", TemplateContent={"Subject": "s"}),+ "CreateEmailTemplate", "template/{n}-other", None),+ (lambda ses, n: ses.get_email_identity(EmailIdentity=f"{n}-other.example.com"),+ "GetEmailIdentity", "identity/{n}-other.example.com", None),+ (lambda ses, n: ses.get_email_template(TemplateName=f"{n}-denied"),+ "GetEmailTemplate", "template/{n}-denied", "with an explicit deny in an identity-based policy"),+], ids=["account", "list", "create-set", "get-set", "create-template", "identity", "explicit-deny"])+def test_ses_v2_authorization_contract(auth_enabled, iam_user, sesv2, call, action, resource, reason):+ """An SES v2 call is authorized as ses:<operation> on the resource its path or create body names."""+ name = f"sesv2-{_uuid_mod.uuid4().hex[:8]}"+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow",+ "Action": ["ses:CreateConfigurationSet", "ses:GetConfigurationSet", "ses:DeleteConfigurationSet"],+ "Resource": f"{_SES_V2_ARN}:configuration-set/{name}-allowed"},+ {"Effect": "Allow", "Action": "ses:GetEmailTemplate", "Resource": f"{_SES_V2_ARN}:template/{name}-allowed"},+ {"Effect": "Deny", "Action": "ses:GetEmailTemplate", "Resource": f"{_SES_V2_ARN}:template/{name}-denied"},+ ]})+ ses = user.client("sesv2")+ try:+ ses.create_configuration_set(ConfigurationSetName=f"{name}-allowed")+ ses.get_configuration_set(ConfigurationSetName=f"{name}-allowed")+ ses.delete_configuration_set(ConfigurationSetName=f"{name}-allowed")+ assert _sesv2_error(ses.get_email_template, TemplateName=f"{name}-allowed")[0] == "NotFoundException"+ if not auth_enabled:+ try:+ call(ses, name)+ except ClientError as error:+ assert error.response["Error"]["Code"] == "NotFoundException"+ return+ with pytest.raises(ClientError) as exc:+ call(ses, name)+ resource = resource if resource == "*" else f"{_SES_V2_ARN}:{resource.format(n=name)}"+ reason = reason or f"because no identity-based policy allows the ses:{action} action"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403+ assert exc.value.response["Error"]["Code"] == "AccessDeniedException"+ assert exc.value.response["Error"]["Message"] == (+ f"User: {user.arn} is not authorized to perform: ses:{action} on resource: {resource} {reason}")+ finally:+ for cleanup in (lambda: sesv2.delete_configuration_set(ConfigurationSetName=f"{name}-other"),+ lambda: sesv2.delete_email_template(TemplateName=f"{name}-other")):+ try:+ cleanup()+ except ClientError:+ pass++def test_ses_v2_send_email_with_v1_template(ses, sesv2):"""A template created with v1 CreateTemplate renders through v2 SendEmail."""import urllib.request