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
SES v2 tenants and resource associations (#2072)
Adrian-Ryan Acalabbb765e050a1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db6fdefa..0b602fba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -46,6 +46,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **SES — receipt-rule metadata** — Receipt rule sets can be created, activated, described, listed and deleted, and rules can be created in order, described and deleted through signed or unsigned Query requests. Resources are isolated by account and region and persisted. Names and recipients are validated; headers that cannot be represented in XML return AWS-shaped readback errors. Receipt actions are limited to AddHeader and Stop without an SNS topic; unsupported actions fail explicitly. Inbound email receiving is not emulated.- **CloudFront — custom error responses on the data plane** — a distribution's `CustomErrorResponses` were stored but never applied, so an origin error reached the viewer unchanged. When the origin answers a configured `ErrorCode`, the data plane now fetches `ResponsePagePath` through the cache behavior that path matches and returns it with `ResponseCode`; a page that cannot be fetched is answered with the status its origin returned, as the Developer Guide describes. `ErrorCachingMinTTL` is stored only, since the data plane does not cache.- **IoT — job templates and `AWS::IoT::JobTemplate`** — `CreateJobTemplate`, `DescribeJobTemplate`, `ListJobTemplates` and `DeleteJobTemplate` were missing, so a `jobTemplateArn` could not be created or used. Templates now store a document or a `documentSource` (not fetched, like `CreateJob`'s), every job configuration member, maintenance windows and tags, can be copied from a job through `jobArn`, list newest first with `maxResults` / `nextToken` paging, and answer AWS's errors and messages. `CreateJob` with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a member the request names replaces the template's. CloudFormation creates and deletes `AWS::IoT::JobTemplate` (Ref is the id, `Fn::GetAtt` `Arn`); every property is create-only, so an update under the same `JobTemplateId` fails with AWS's custom-name sentence and a new id replaces the template. Contributed by @iot-rocket.+- **SES v2 — tenants and resource associations** — supports tenant creation, readback, listing, deletion, tags and suppression attributes (`PutTenantSuppressionAttributes`), with configuration-set, identity and template resource associations and readback in both directions. Tenants and associations are isolated by account and region and persisted; deleting an associated configuration set, template or identity through either API version requires removing tenant associations first. Associations recognize resources created through either API version, and foreign ARN partitions are accepted and normalized for storage, matching and readback.### Fixed- **DynamoDB — transactions are authorized per item under `AUTH=true`** — `TransactWriteItems` and `TransactGetItems` were checked as `dynamodb:TransactWriteItems` / `dynamodb:TransactGetItems` on the first item's table, which are not IAM actions, so a policy granting the item actions was refused and one granting the transaction name was accepted. Each item is now checked as the action it performs (`dynamodb:PutItem`, `UpdateItem`, `DeleteItem`, `ConditionCheckItem`, `GetItem`) on its own table. Each item check carries `dynamodb:EnclosingOperation`, so policies that allow or deny only transactional calls evaluate as on AWS. Contributed by @drakeo338.diff --git a/ministack/services/ses.py b/ministack/services/ses.pyindex 58731405..7724398f 100644--- a/ministack/services/ses.py+++ b/ministack/services/ses.py@@ -812,8 +812,25 @@ def _get_identity_verification_attributes(params):f"</GetIdentityVerificationAttributesResult>")+def _tenant_delete_block(kind, name):+ """Refuse v1 deletes of resources with SESv2 tenant associations, as AWS does."""+ from ministack.services import ses_v2++ arn = f"arn:aws:ses:{get_region()}:{get_account_id()}:{kind}/{name}"+ if any(arn in resources for resources in ses_v2._tenant_resources.values()):+ return _error(+ "InvalidParameterValue",+ f"Cannot delete <{arn}> because it has tenant associations. Remove all tenant associations and try again.",+ 400,+ )+ return None++def _delete_identity(params):identity = _p(params, "Identity")+ blocked = _tenant_delete_block("identity", identity)+ if blocked:+ return blocked_identities.pop(identity, None)return _xml(200, "DeleteIdentityResponse", "<DeleteIdentityResult/>")@@ -923,6 +940,9 @@ def _create_configuration_set(params):def _delete_configuration_set(params):name = _p(params, "ConfigurationSetName")+ blocked = _tenant_delete_block("configuration-set", name)+ if blocked:+ return blockedif name not in _configuration_sets:return _error("ConfigurationSetDoesNotExist",f"Configuration set {name} does not exist", 400)@@ -992,6 +1012,9 @@ def _get_template(params):def _delete_template(params):name = _p(params, "TemplateName")+ blocked = _tenant_delete_block("template", name)+ if blocked:+ return blocked_templates.pop(name, None)return _xml(200, "DeleteTemplateResponse", "<DeleteTemplateResult/>")diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.pyindex 4ddb75dc..f5004d03 100644--- a/ministack/services/ses_v2.py+++ b/ministack/services/ses_v2.py@@ -9,7 +9,9 @@ Supports: SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity,GetEmailTemplate, UpdateEmailTemplate, DeleteEmailTemplate,ListEmailTemplates, GetAccount, ListSuppressedDestinations,PutAccountSuppressionAttributes, TagResource, UntagResource,- ListTagsForResource.+ ListTagsForResource, CreateTenant, GetTenant, ListTenants, DeleteTenant,+ CreateTenantResourceAssociation, DeleteTenantResourceAssociation,+ ListTenantResources, ListResourceTenants, PutTenantSuppressionAttributes.Email templates live in the v1 store, so either API version sees the other's."""@@ -43,6 +45,12 @@ from ministack.services.ses import (_smtp_relay,_templates,)+from ministack.services.ses import (+ _configuration_sets as _v1_config_sets,+)+from ministack.services.ses import (+ _identities as _v1_identities,+)logger = logging.getLogger("ses-v2")@@ -52,6 +60,8 @@ TEMPLATE_PAGE_SIZE = 10 # ListEmailTemplates default per the AWS API reference_identities = AccountRegionScopedDict() # identity -> dict_config_sets = AccountRegionScopedDict() # name -> dict_ses_tags = AccountRegionScopedDict() # resource_arn -> [tags]+_tenants = AccountRegionScopedDict()+_tenant_resources = AccountRegionScopedDict() # tenant name -> {ARN: timestamp}def get_state() -> dict:@@ -59,6 +69,8 @@ def get_state() -> dict:"_identities": _identities,"_config_sets": _config_sets,"_ses_tags": _ses_tags,+ "_tenants": _tenants,+ "_tenant_resources": _tenant_resources,})@@ -70,6 +82,8 @@ def _restore_state(data: dict):_restore_regional_store(_identities, data.get("_identities", {}))_restore_regional_store(_config_sets, data.get("_config_sets", {}))_restore_tag_store(data.get("_ses_tags", {}))+ _restore_regional_store(_tenants, data.get("_tenants", {}))+ _restore_regional_store(_tenant_resources, data.get("_tenant_resources", {}))def _restore_tag_store(restored):@@ -181,9 +195,15 @@ def _page_size(query_params, default, maximum=100):size = int(raw)except (TypeError, ValueError):return default, _json_err("BadRequestException", f"Invalid PageSize: {raw}")- if size < 1 or size > maximum:+ if size < 1:+ return default, _json_err(+ "BadRequestException",+ f"1 validation error detected: Value '{raw}' at 'pageSize' failed to satisfy constraint: Member must have value greater than or equal to 1",+ )+ if size > maximum:return default, _json_err(- "BadRequestException", f"PageSize must be between 1 and {maximum}"+ "BadRequestException",+ f"1 validation error detected: Value '{raw}' at 'pageSize' failed to satisfy constraint: Member must have value less than or equal to {maximum}",)return size, None@@ -274,15 +294,15 @@ def _local_ses_v2_resource_arn(arn):return None, _invalid_resource_arn(arn)if (- spec.partition != "aws"- or spec.service != "ses"+ spec.service != "ses"or spec.account_id != get_account_id()or spec.region != get_region()):return None, _invalid_resource_arn(arn)+ canonical = f"arn:aws:{spec.service}:{spec.region}:{spec.account_id}:{spec.resource}"kind, sep, name = spec.resource.partition("/")- if sep != "/" or not name or "/" in name:+ if sep != "/" or not name or ("/" in name and kind != "tenant"):return None, _invalid_resource_arn(arn)if kind == "identity":@@ -291,10 +311,289 @@ def _local_ses_v2_resource_arn(arn):elif kind == "configuration-set":if name not in _config_sets:return None, _not_found_resource_arn(arn)+ elif kind == "tenant":+ parts = name.split("/")+ if len(parts) == 1:+ return None, _json_err(+ "NotFoundException",+ f"No Tenant present with name: nullwith tenantId: {name}",+ 404,+ )+ if len(parts) != 2 or not all(parts):+ return None, _invalid_resource_arn(arn)+ tenant_name, tenant_id = parts+ rec = _tenants.get(tenant_name)+ if not rec or rec["TenantArn"] != canonical:+ return None, _json_err(+ "NotFoundException",+ f"No Tenant present with name: {tenant_name}with tenantId: {tenant_id}",+ 404,+ )else:return None, _invalid_resource_arn(arn)- return str(spec), None+ return canonical, None+++def _missing_tenant(name):+ return _json_err("NotFoundException", f"The requested tenant <{name}> does not exist.", 404)+++def _association_resource(arn):+ """Validate an association ARN; returns (kind, canonical aws-partition ARN, error)."""+ try:+ spec = parse_arn(arn)+ except (ArnParseError, TypeError):+ return None, None, _json_err("BadRequestException", "Provided resource identifier is not an SES resource")+ if spec.service != "ses":+ return None, None, _json_err("BadRequestException", "Provided ARN is not in SES resource ARN format")+ kind, _, name = spec.resource.partition("/")+ if kind not in ("configuration-set", "identity", "template"):+ return None, None, _json_err("BadRequestException", f"Unsupported resource type: {kind}")+ if spec.region != get_region():+ return None, None, _json_err("BadRequestException", f"Resource <{arn}> must be in the same region")+ if spec.account_id != get_account_id():+ return None, None, _json_err("BadRequestException", f"Resource <{arn}> must be in the same account")+ stores, label = {+ "configuration-set": ((_v1_config_sets, _config_sets), "Configuration set"),+ "identity": ((_v1_identities, _identities), "Identity"),+ "template": ((_templates,), "Template"),+ }[kind]+ if not any(name in store for store in stores):+ return None, None, _json_err("NotFoundException", f"{label} <{name}> does not exist:", 404)+ canonical = f"arn:aws:{spec.service}:{spec.region}:{spec.account_id}:{spec.resource}"+ return kind, canonical, None+++_SUPPRESSED_REASONS = ("BOUNCE", "COMPLAINT")+_SUPPRESSION_SCOPES = ("TENANT", "ACCOUNT")+++def _suppression_enum_errors(prefix, reasons, reasons_present, scope, scope_present):+ """Model-level enum errors for suppression attributes, in member order."""+ errors = []+ if reasons_present:+ members = reasons if isinstance(reasons, list) else [reasons]+ if any(m not in _SUPPRESSED_REASONS for m in members):+ errors.append(+ f"Value at '{prefix}suppressedReasons' failed to satisfy constraint: Member must satisfy constraint: [Member must satisfy enum value set: [BOUNCE, COMPLAINT]]"+ )+ if scope_present and scope not in _SUPPRESSION_SCOPES:+ errors.append(+ f"Value at '{prefix}suppressionScope' failed to satisfy constraint: Member must satisfy enum value set: [TENANT, ACCOUNT]"+ )+ return errors+++def _combined_validation_error(errors):+ noun = "error" if len(errors) == 1 else "errors"+ return _json_err("BadRequestException", f"{len(errors)} validation {noun} detected: {'; '.join(errors)}")+++def _create_suppression_pairing(attrs):+ """Pairing/null rules for CreateTenant SuppressionAttributes; returns (value, error)."""+ reasons_present = "SuppressedReasons" in attrs+ scope_present = "SuppressionScope" in attrs+ reasons = attrs.get("SuppressedReasons")+ scope = attrs.get("SuppressionScope")+ if bool(reasons) and not scope_present:+ return None, _json_err("BadRequestException", "SuppressedReasons cannot be specified without SuppressionScope.")+ if scope_present and not reasons_present:+ return None, _json_err("BadRequestException", "SuppressionScope cannot be specified without SuppressedReasons.")+ if not bool(reasons) and not scope_present:+ nulls = []+ if not reasons_present:+ nulls.append("Value null at 'suppressionAttributes.suppressedReasons' failed to satisfy constraint: Member must not be null")+ if not scope_present:+ nulls.append("Value null at 'suppressionAttributes.suppressionScope' failed to satisfy constraint: Member must not be null")+ return None, _combined_validation_error(nulls)+ return {"SuppressedReasons": list(reasons) if isinstance(reasons, list) else reasons, "SuppressionScope": scope}, None+++def _put_suppression_pairing(data):+ """Pairing rules for PutTenantSuppressionAttributes; returns (value, clear, error)."""+ reasons_present = "SuppressedReasons" in data+ scope_present = "SuppressionScope" in data+ if not reasons_present and not scope_present:+ return None, True, None+ reasons = data.get("SuppressedReasons")+ scope = data.get("SuppressionScope")+ if bool(reasons) and not scope_present:+ return None, False, _json_err("BadRequestException", "SuppressedReasons cannot be specified without SuppressionScope.")+ if reasons_present and not scope_present:+ return None, False, _json_err("BadRequestException", "SuppressionScope is required when SuppressedReasons are provided. Valid values are: TENANT, ACCOUNT")+ if scope_present and not reasons_present:+ return None, False, _json_err("BadRequestException", "SuppressionScope cannot be specified without SuppressedReasons.")+ return {"SuppressedReasons": list(reasons) if isinstance(reasons, list) else reasons, "SuppressionScope": scope}, False, None+++def _tenant_delete_block(arn):+ if any(arn in resources for resources in _tenant_resources.values()):+ return _json_err(+ "BadRequestException",+ f"Cannot delete <{arn}> because it has tenant associations. Remove all tenant associations and try again.",+ )+ return None+++def _tenant_request(method, sub, data):+ if method == "POST" and sub == "/resources/tenants/list":+ arn = data.get("ResourceArn", "")+ _, canonical, err = _association_resource(arn)+ if err:+ return err+ items = [+ {+ "TenantName": name,+ "TenantId": _tenants[name]["TenantId"],+ "ResourceArn": canonical,+ "AssociatedTimestamp": resources[canonical],+ }+ for name, resources in _tenant_resources.items()+ if canonical in resources+ ]+ page, token, err = _paginate(items, _body_paging(data), 100)+ return err or json_response({"ResourceTenants": page, **({"NextToken": token} if token else {})})+ if method == "POST" and sub == "/tenant/suppression":+ enum_errors = _suppression_enum_errors(+ "",+ data.get("SuppressedReasons"), "SuppressedReasons" in data,+ data.get("SuppressionScope"), "SuppressionScope" in data,+ )+ if enum_errors:+ return _combined_validation_error(enum_errors)+ value, clear, err = _put_suppression_pairing(data)+ if err:+ return err+ rec = _tenants.get(data.get("TenantName", ""))+ if rec is None:+ return _missing_tenant(data.get("TenantName", ""))+ if clear:+ rec.pop("SuppressionAttributes", None)+ else:+ rec["SuppressionAttributes"] = value+ return json_response({})+ if method != "POST" or not sub.startswith("/tenants"):+ return None+ name = data.get("TenantName", "")+ if sub == "/tenants":+ attrs = data.get("SuppressionAttributes")+ if attrs is not None:+ if not isinstance(attrs, dict):+ attrs = {}+ enum_errors = _suppression_enum_errors(+ "suppressionAttributes.",+ attrs.get("SuppressedReasons"), "SuppressedReasons" in attrs,+ attrs.get("SuppressionScope"), "SuppressionScope" in attrs,+ )+ if enum_errors:+ return _combined_validation_error(enum_errors)+ if not re.fullmatch(r"[A-Za-z0-9_-]+", name):+ return _json_err(+ "BadRequestException",+ f"Invalid tenant name <{name}>: only alphanumeric ASCII characters, '_', and '-' are allowed.",+ )+ suppression = None+ if attrs is not None:+ suppression, err = _create_suppression_pairing(attrs)+ if err:+ return err+ if name in _tenants:+ return _json_err(+ "AlreadyExistsException", f"Tenant with name {name} already exists in account {get_account_id()}"+ )+ tenant_id = "tn-" + new_uuid().replace("-", "")[:29]+ arn = _resource_arn("tenant", f"{name}/{tenant_id}")+ rec = {+ "TenantName": name,+ "TenantId": tenant_id,+ "TenantArn": arn,+ "CreatedTimestamp": time.time(),+ "Tags": copy.deepcopy(data.get("Tags", [])),+ "SendingStatus": "ENABLED",+ }+ if suppression is not None:+ rec["SuppressionAttributes"] = suppression+ _tenants[name] = rec+ _tenant_resources[name] = {}+ _ses_tags[arn] = copy.deepcopy(rec["Tags"])+ return json_response(rec)+ if sub == "/tenants/list":+ filters = data.get("Filter") or {}+ if filters.keys() - {"SENDING_STATUS", "TENANT_NAME_CONTAINS"}:+ return _json_err(+ "BadRequestException",+ "1 validation error detected: Value at 'filter' failed to satisfy constraint: Map keys must satisfy constraint: [Member must satisfy enum value set: [SENDING_STATUS, TENANT_NAME_CONTAINS]]",+ )+ status = filters.get("SENDING_STATUS")+ if status is not None and status not in ("ENABLED", "REINSTATED", "DISABLED"):+ return _json_err("BadRequestException", f"Invalid sending status <{status}>.")+ items = sorted(+ (+ {k: v for k, v in rec.items() if k not in ("Tags", "SuppressionAttributes")}+ for rec in _tenants.values()+ if filters.get("TENANT_NAME_CONTAINS", "") in rec["TenantName"]+ and (not filters.get("SENDING_STATUS") or filters["SENDING_STATUS"] == rec["SendingStatus"])+ ),+ key=lambda item: item["TenantName"],+ )+ page, token, err = _paginate(items, _body_paging(data), 100)+ return err or json_response({"Tenants": page, **({"NextToken": token} if token else {})})+ if sub not in (+ "/tenants/get",+ "/tenants/delete",+ "/tenants/resources",+ "/tenants/resources/delete",+ "/tenants/resources/list",+ ):+ return None+ rec = _tenants.get(name)+ if rec is None:+ return _missing_tenant(name)+ if sub == "/tenants/get":+ out = copy.deepcopy(rec)+ out["Tags"] = _ses_tags.get(rec["TenantArn"], [])+ return json_response({"Tenant": out})+ if sub == "/tenants/delete":+ _tenants.pop(name)+ _tenant_resources.pop(name, None)+ _ses_tags.pop(rec["TenantArn"], None)+ return json_response({})+ resources = _tenant_resources[name]+ if sub == "/tenants/resources/list":+ items = [{"ResourceType": parse_arn(arn).resource.split("/")[0], "ResourceArn": arn} for arn in resources]+ filters = data.get("Filter") or {}+ if filters.keys() - {"RESOURCE_TYPE"}:+ return _json_err(+ "BadRequestException",+ "1 validation error detected: Value at 'filter' failed to satisfy constraint: Map keys must satisfy constraint: [Member must satisfy enum value set: [RESOURCE_TYPE]]",+ )+ resource_type = filters.get("RESOURCE_TYPE")+ if resource_type is not None and resource_type not in ("configuration-set", "identity", "template"):+ return _json_err("BadRequestException", f"Invalid resource type {resource_type} specified.")+ items = sorted(+ (+ item+ for item in items+ if not filters.get("RESOURCE_TYPE") or item["ResourceType"] == filters["RESOURCE_TYPE"]+ ),+ key=lambda item: item["ResourceArn"],+ )+ page, token, err = _paginate(items, _body_paging(data), 100)+ return err or json_response({"TenantResources": page, **({"NextToken": token} if token else {})})+ arn = data.get("ResourceArn", "")+ _, canonical, err = _association_resource(arn)+ if err:+ return err+ if sub.endswith("/delete"):+ resources.pop(canonical, None)+ else:+ if canonical in resources:+ return _json_err(+ "AlreadyExistsException", f"Resources {arn} has already been associated with tenant {name}"+ )+ resources[canonical] = time.time()+ return json_response({})async def handle_request(method, path, headers, body, query_params):@@ -310,6 +609,10 @@ async def handle_request(method, path, headers, body, query_params):except json.JSONDecodeError:data = {}+ result = _tenant_request(method, sub, data)+ if result is not None:+ return result+# GET /v2/email/accountif sub == "/account" and method == "GET":cutoff = time.time() - 86400@@ -554,6 +857,9 @@ async def handle_request(method, path, headers, body, query_params):return _json_err("NotFoundException", f"Identity {identity} not found", 404)return json_response(rec)if method == "DELETE":+ blocked = _tenant_delete_block(_resource_arn("identity", identity))+ if blocked:+ return blocked_identities.pop(identity, None)return json_response({})@@ -592,7 +898,12 @@ async def handle_request(method, path, headers, body, query_params):return _json_err("NotFoundException", f"ConfigurationSet {name} not found", 404)return json_response(rec)if method == "DELETE":+ arn = _resource_arn("configuration-set", name)+ blocked = _tenant_delete_block(arn)+ if blocked:+ return blocked_config_sets.pop(name, None)+ _ses_tags.pop(arn, None)return json_response({})# POST /v2/email/templates (CreateEmailTemplate)@@ -653,6 +964,9 @@ async def handle_request(method, path, headers, body, query_params):stored.update(_template_parts(template_content))return json_response({})if method == "DELETE":+ blocked = _tenant_delete_block(_resource_arn("template", name))+ if blocked:+ return blocked_templates.pop(name, None)return json_response({})@@ -692,3 +1006,5 @@ def reset():_identities.clear()_config_sets.clear()_ses_tags.clear()+ _tenants.clear()+ _tenant_resources.clear()diff --git a/tests/test_ses_tenants.py b/tests/test_ses_tenants.pynew file mode 100644index 00000000..761eb5b2--- /dev/null+++ b/tests/test_ses_tenants.py@@ -0,0 +1,575 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+"""SES tenant lifecycle, resource associations, and AWS-observed errors."""++import copy+import json+import re+import uuid++import pytest+from botocore.exceptions import ClientError++from ministack.core.responses import set_request_account_id, set_request_region+++def _error(client, operation, code, message, **params):+ with pytest.raises(ClientError) as caught:+ getattr(client, operation)(**params)+ response = caught.value.response+ assert response["Error"] == {"Code": code, "Message": message}+ assert response["ResponseMetadata"]["HTTPStatusCode"] == (404 if code == "NotFoundException" else 400)+++def test_tenant_configuration_set_association_lifecycle(sesv2):+ name = "tenant-" + uuid.uuid4().hex[:10]+ tags = [{"Key": "purpose", "Value": "regression"}]+ sesv2.create_configuration_set(ConfigurationSetName=name, Tags=tags)+ tenant = sesv2.create_tenant(TenantName=name, Tags=tags)+ assert re.fullmatch(r"tn-[a-f0-9]{29}", tenant["TenantId"])+ assert tenant["TenantArn"].endswith(f"tenant/{name}/{tenant['TenantId']}")+ assert tenant["SendingStatus"] == "ENABLED"+ assert tenant["Tags"] == tags+ assert sesv2.get_tenant(TenantName=name)["Tenant"] == {k: v for k, v in tenant.items() if k != "ResponseMetadata"}+ _error(+ sesv2,+ "create_tenant",+ "AlreadyExistsException",+ f"Tenant with name {name} already exists in account 000000000000",+ TenantName=name,+ )+ listed = sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": name, "SENDING_STATUS": "ENABLED"})["Tenants"]+ assert listed == [{k: v for k, v in tenant.items() if k not in ("ResponseMetadata", "Tags")}]+ assert sesv2.list_tags_for_resource(ResourceArn=tenant["TenantArn"])["Tags"] == tags+ sesv2.tag_resource(ResourceArn=tenant["TenantArn"], Tags=[{"Key": "updated", "Value": "yes"}])+ sesv2.untag_resource(ResourceArn=tenant["TenantArn"], TagKeys=["purpose"])+ assert sesv2.get_tenant(TenantName=name)["Tenant"]["Tags"] == [{"Key": "updated", "Value": "yes"}]+ arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{name}"+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=arn)+ _error(+ sesv2,+ "create_tenant_resource_association",+ "AlreadyExistsException",+ f"Resources {arn} has already been associated with tenant {name}",+ TenantName=name,+ ResourceArn=arn,+ )+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == [+ {"ResourceType": "configuration-set", "ResourceArn": arn}+ ]+ inverse = sesv2.list_resource_tenants(ResourceArn=arn)["ResourceTenants"]+ assert inverse[0]["TenantId"] == tenant["TenantId"]+ assert inverse[0]["ResourceArn"] == arn+ _error(+ sesv2,+ "delete_configuration_set",+ "BadRequestException",+ f"Cannot delete <{arn}> because it has tenant associations. Remove all tenant associations and try again.",+ ConfigurationSetName=name,+ )+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=arn)+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=arn)+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == []+ sesv2.delete_tenant(TenantName=name)+ _error(sesv2, "get_tenant", "NotFoundException", f"The requested tenant <{name}> does not exist.", TenantName=name)+ _error(+ sesv2,+ "list_tags_for_resource",+ "NotFoundException",+ f"No Tenant present with name: {name}with tenantId: {tenant['TenantId']}",+ ResourceArn=tenant["TenantArn"],+ )+ for operation, params in [+ ("tag_resource", {"Tags": [{"Key": "purpose", "Value": "regression"}]}),+ ("untag_resource", {"TagKeys": ["purpose"]}),+ ]:+ _error(sesv2, operation, "NotFoundException", f"No Tenant present with name: {name}with tenantId: {tenant['TenantId']}",+ ResourceArn=tenant["TenantArn"], **params)+ sesv2.delete_configuration_set(ConfigurationSetName=name)+++def test_tenant_invalid_and_missing_resources(sesv2):+ name = "tenant-errors-" + uuid.uuid4().hex[:10]+ _error(+ sesv2,+ "create_tenant",+ "BadRequestException",+ f"Invalid tenant name <{name} bad>: only alphanumeric ASCII characters, '_', and '-' are allowed.",+ TenantName=name + " bad",+ )+ _error(+ sesv2,+ "create_tenant_resource_association",+ "NotFoundException",+ f"The requested tenant <{name}> does not exist.",+ TenantName=name,+ ResourceArn="invalid-arn",+ )+ sesv2.create_tenant(TenantName=name)+ _error(+ sesv2,+ "create_tenant_resource_association",+ "BadRequestException",+ "Provided resource identifier is not an SES resource",+ TenantName=name,+ ResourceArn="invalid-arn",+ )+ arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{name}"+ _error(+ sesv2,+ "create_tenant_resource_association",+ "NotFoundException",+ f"Configuration set <{name}> does not exist:",+ TenantName=name,+ ResourceArn=arn,+ )+ other = arn.replace("us-east-1", "us-west-2")+ _error(+ sesv2,+ "create_tenant_resource_association",+ "BadRequestException",+ f"Resource <{other}> must be in the same region",+ TenantName=name,+ ResourceArn=other,+ )+ sesv2.delete_tenant(TenantName=name)++[email protected]("filters,message", [+ ({"INVALID": "template"},+ "1 validation error detected: Value at 'filter' failed to satisfy constraint: Map keys must satisfy constraint: [Member must satisfy enum value set: [RESOURCE_TYPE]]"),+ ({"RESOURCE_TYPE": "bogus"}, "Invalid resource type bogus specified."),+ ({"RESOURCE_TYPE": "template,configuration-set"},+ "Invalid resource type template,configuration-set specified."),+])+def test_tenant_resource_filter_errors(sesv2, filters, message):+ name = "tenant-filter-" + uuid.uuid4().hex[:10]+ sesv2.create_tenant(TenantName=name)+ _error(sesv2, "list_tenant_resources", "BadRequestException", message,+ TenantName=name, Filter=filters)+ sesv2.delete_tenant(TenantName=name)+++def test_tenant_sending_status_filter(sesv2):+ name = "tenant-status-" + uuid.uuid4().hex[:10]+ sesv2.create_tenant(TenantName=name)+ _error(sesv2, "list_tenants", "BadRequestException", "Invalid sending status <bogus>.",+ Filter={"TENANT_NAME_CONTAINS": name, "SENDING_STATUS": "bogus"})+ for status in ("REINSTATED", "DISABLED"):+ assert sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": name, "SENDING_STATUS": status})["Tenants"] == []+ sesv2.delete_tenant(TenantName=name)+++def test_tenant_template_association_and_delete_with_associations(sesv2):+ name = "tenant-template-" + uuid.uuid4().hex[:10]+ sesv2.create_email_template(TemplateName=name, TemplateContent={"Subject": "probe", "Text": "probe"})+ sesv2.create_configuration_set(ConfigurationSetName=name)+ template_arn = f"arn:aws:ses:us-east-1:000000000000:template/{name}"+ config_arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{name}"+ tenants = [name + suffix for suffix in ("-a", "-b")]+ for tenant_name in tenants:+ sesv2.create_tenant(TenantName=tenant_name)+ for arn in (config_arn, template_arn):+ sesv2.create_tenant_resource_association(TenantName=tenant_name, ResourceArn=arn)+ assert sesv2.list_tenant_resources(TenantName=tenant_name, Filter={"RESOURCE_TYPE": "template"})["TenantResources"] == [+ {"ResourceType": "template", "ResourceArn": template_arn}+ ]+ first = sesv2.list_tenant_resources(TenantName=tenant_name, PageSize=1)+ second = sesv2.list_tenant_resources(TenantName=tenant_name, PageSize=1, NextToken=first["NextToken"])+ assert first["TenantResources"] + second["TenantResources"] == [+ {"ResourceType": "configuration-set", "ResourceArn": config_arn},+ {"ResourceType": "template", "ResourceArn": template_arn},+ ]+ assert "NextToken" not in second+ first = sesv2.list_resource_tenants(ResourceArn=config_arn, PageSize=1)+ second = sesv2.list_resource_tenants(ResourceArn=config_arn, PageSize=1, NextToken=first["NextToken"])+ assert [item["TenantName"] for item in first["ResourceTenants"] + second["ResourceTenants"]] == tenants+ assert "NextToken" not in second+ sesv2.delete_tenant(TenantName=tenants[0])+ assert [item["TenantName"] for item in sesv2.list_resource_tenants(ResourceArn=config_arn)["ResourceTenants"]] == tenants[1:]+ _error(sesv2, "delete_configuration_set", "BadRequestException",+ f"Cannot delete <{config_arn}> because it has tenant associations. Remove all tenant associations and try again.",+ ConfigurationSetName=name)+ sesv2.delete_tenant(TenantName=tenants[1])+ assert sesv2.list_resource_tenants(ResourceArn=config_arn)["ResourceTenants"] == []+ sesv2.delete_configuration_set(ConfigurationSetName=name)+ sesv2.delete_email_template(TemplateName=name)+++def test_tenant_state_roundtrip_and_account_region_isolation():+ from ministack.core.persistence import _json_default, _json_object_hook+ from ministack.services import ses_v2++ snapshot = copy.deepcopy(ses_v2.get_state())+ scopes = [+ ("000000000000", "us-east-1"),+ ("111111111111", "us-east-1"),+ ("000000000000", "us-west-2"),+ ]+ saved_tenants = {}+ try:+ for account, region in scopes:+ set_request_account_id(account)+ set_request_region(region)+ assert "same" not in ses_v2._tenants+ assert "same" not in ses_v2._tenant_resources+ status, _, body = ses_v2._tenant_request(+ "POST", "/tenants", {"TenantName": "same", "Tags": [{"Key": "region", "Value": region}]}+ )+ assert status == 200+ saved_tenants[(account, region)] = json.loads(body)+ arn = f"arn:aws:ses:{region}:{account}:configuration-set/same"+ ses_v2._config_sets["same"] = {"ConfigurationSetName": "same"}+ assert ses_v2._tenant_request(+ "POST", "/tenants/resources", {"TenantName": "same", "ResourceArn": arn}+ )[0] == 200++ encoded = json.dumps(ses_v2.get_state(), default=_json_default, sort_keys=True)+ saved = json.loads(encoded, object_hook=_json_object_hook)+ ses_v2.reset()+ for account, region in scopes:+ set_request_account_id(account)+ set_request_region(region)+ assert not ses_v2._tenants+ assert not ses_v2._tenant_resources+ ses_v2.load_persisted_state(saved)+ assert json.dumps(ses_v2.get_state(), default=_json_default, sort_keys=True) == encoded+ for account, region in scopes:+ set_request_account_id(account)+ set_request_region(region)+ tenant = saved_tenants[(account, region)]+ assert ses_v2._tenants["same"] == tenant+ assert ses_v2._ses_tags[tenant["TenantArn"]] == [{"Key": "region", "Value": region}]+ arn = f"arn:aws:ses:{region}:{account}:configuration-set/same"+ assert list(ses_v2._tenant_resources["same"]) == [arn]+ inverse = json.loads(ses_v2._tenant_request(+ "POST", "/resources/tenants/list", {"ResourceArn": arn}+ )[2])["ResourceTenants"]+ assert inverse == [{+ "TenantName": "same",+ "TenantId": tenant["TenantId"],+ "ResourceArn": arn,+ "AssociatedTimestamp": ses_v2._tenant_resources["same"][arn],+ }]+ finally:+ ses_v2.reset()+ ses_v2.load_persisted_state(snapshot)+++def test_tenant_suppression_lifecycle(sesv2):+ name = "tenant-suppr-" + uuid.uuid4().hex[:10]+ attrs = {"SuppressedReasons": ["BOUNCE"], "SuppressionScope": "TENANT"}+ created = sesv2.create_tenant(TenantName=name, SuppressionAttributes=attrs)+ assert created["SuppressionAttributes"] == attrs+ assert sesv2.get_tenant(TenantName=name)["Tenant"]["SuppressionAttributes"] == attrs+ listed = sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": name})["Tenants"]+ assert listed and "SuppressionAttributes" not in listed[0]+ updated = {"SuppressedReasons": ["BOUNCE", "COMPLAINT"], "SuppressionScope": "ACCOUNT"}+ sesv2.put_tenant_suppression_attributes(TenantName=name, **updated)+ assert sesv2.get_tenant(TenantName=name)["Tenant"]["SuppressionAttributes"] == updated+ sesv2.put_tenant_suppression_attributes(TenantName=name)+ assert "SuppressionAttributes" not in sesv2.get_tenant(TenantName=name)["Tenant"]+ sesv2.put_tenant_suppression_attributes(+ TenantName=name, SuppressedReasons=[], SuppressionScope="TENANT"+ )+ assert sesv2.get_tenant(TenantName=name)["Tenant"]["SuppressionAttributes"] == {+ "SuppressedReasons": [],+ "SuppressionScope": "TENANT",+ }+ sesv2.delete_tenant(TenantName=name)+++def test_tenant_suppression_validation(sesv2):+ name = "tenant-supval-" + uuid.uuid4().hex[:10]+ create_reasons = (+ "1 validation error detected: Value at 'suppressionAttributes.suppressedReasons'"+ " failed to satisfy constraint: Member must satisfy constraint:"+ " [Member must satisfy enum value set: [BOUNCE, COMPLAINT]]"+ )+ create_scope = (+ "1 validation error detected: Value at 'suppressionAttributes.suppressionScope'"+ " failed to satisfy constraint: Member must satisfy enum value set: [TENANT, ACCOUNT]"+ )+ put_reasons = create_reasons.replace("suppressionAttributes.suppressedReasons", "suppressedReasons")+ put_scope = create_scope.replace("suppressionAttributes.suppressionScope", "suppressionScope")+ null_reasons = (+ "1 validation error detected: Value null at 'suppressionAttributes.suppressedReasons'"+ " failed to satisfy constraint: Member must not be null"+ )+ null_scope = (+ "1 validation error detected: Value null at 'suppressionAttributes.suppressionScope'"+ " failed to satisfy constraint: Member must not be null"+ )+ both_null = "2 validation errors detected: " + "; ".join(+ [null_reasons.split(": ", 1)[1], null_scope.split(": ", 1)[1]]+ )+ both_create = "2 validation errors detected: " + "; ".join(+ [create_reasons.split(": ", 1)[1], create_scope.split(": ", 1)[1]]+ )+ both_put = "2 validation errors detected: " + "; ".join(+ [put_reasons.split(": ", 1)[1], put_scope.split(": ", 1)[1]]+ )+ bad_attrs = {"SuppressedReasons": ["NOPE"], "SuppressionScope": "TENANT"}+ _error(sesv2, "create_tenant", "BadRequestException", create_reasons,+ TenantName=name, SuppressionAttributes=bad_attrs)+ _error(sesv2, "create_tenant", "BadRequestException", create_scope,+ TenantName=name,+ SuppressionAttributes={"SuppressedReasons": ["BOUNCE"], "SuppressionScope": "NOPE"})+ _error(sesv2, "create_tenant", "BadRequestException", both_create,+ TenantName=name,+ SuppressionAttributes={"SuppressedReasons": ["NOPE"], "SuppressionScope": "NOPE"})+ _error(sesv2, "create_tenant", "BadRequestException",+ "SuppressedReasons cannot be specified without SuppressionScope.",+ TenantName=name, SuppressionAttributes={"SuppressedReasons": ["BOUNCE"]})+ _error(sesv2, "create_tenant", "BadRequestException",+ "SuppressionScope cannot be specified without SuppressedReasons.",+ TenantName=name, SuppressionAttributes={"SuppressionScope": "TENANT"})+ _error(sesv2, "create_tenant", "BadRequestException", both_null,+ TenantName=name, SuppressionAttributes={})+ _error(sesv2, "create_tenant", "BadRequestException", null_scope,+ TenantName=name, SuppressionAttributes={"SuppressedReasons": []})+ # Precedence: model enum errors beat the name check, which beats pairing rules,+ # which beat the duplicate check.+ _error(sesv2, "create_tenant", "BadRequestException", create_reasons,+ TenantName="bad name", SuppressionAttributes=bad_attrs)+ _error(sesv2, "create_tenant", "BadRequestException",+ "Invalid tenant name <bad name>: only alphanumeric ASCII characters, '_', and '-' are allowed.",+ TenantName="bad name", SuppressionAttributes={"SuppressedReasons": ["BOUNCE"]})+ sesv2.create_tenant(TenantName=name)+ _error(sesv2, "create_tenant", "BadRequestException", create_reasons,+ TenantName=name, SuppressionAttributes=bad_attrs)+ _error(sesv2, "create_tenant", "BadRequestException",+ "SuppressedReasons cannot be specified without SuppressionScope.",+ TenantName=name, SuppressionAttributes={"SuppressedReasons": ["BOUNCE"]})+ _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", put_reasons,+ TenantName=name, SuppressedReasons=["NOPE"], SuppressionScope="TENANT")+ _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", put_scope,+ TenantName=name, SuppressedReasons=["BOUNCE"], SuppressionScope="NOPE")+ _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", both_put,+ TenantName=name, SuppressedReasons=["NOPE"], SuppressionScope="NOPE")+ _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",+ "SuppressedReasons cannot be specified without SuppressionScope.",+ TenantName=name, SuppressedReasons=["BOUNCE"])+ _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",+ "SuppressionScope is required when SuppressedReasons are provided. Valid values are: TENANT, ACCOUNT",+ TenantName=name, SuppressedReasons=[])+ _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",+ "SuppressionScope cannot be specified without SuppressedReasons.",+ TenantName=name, SuppressionScope="TENANT")+ missing = name + "-missing"+ _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException", put_reasons,+ TenantName=missing, SuppressedReasons=["NOPE"], SuppressionScope="TENANT")+ _error(sesv2, "put_tenant_suppression_attributes", "BadRequestException",+ "SuppressionScope cannot be specified without SuppressedReasons.",+ TenantName=missing, SuppressionScope="TENANT")+ _error(sesv2, "put_tenant_suppression_attributes", "NotFoundException",+ f"The requested tenant <{missing}> does not exist.", TenantName=missing)+ sesv2.delete_tenant(TenantName=name)+++def test_tenant_list_ordering(sesv2):+ prefix = "tenant-ord-" + uuid.uuid4().hex[:10]+ first, second = prefix + "-zz", prefix + "-aa"+ sesv2.create_tenant(TenantName=first)+ sesv2.create_tenant(TenantName=second)+ names = [+ t["TenantName"]+ for t in sesv2.list_tenants(Filter={"TENANT_NAME_CONTAINS": prefix})["Tenants"]+ ]+ assert names == [second, first]+ cs_b, cs_a = prefix + "-cs-b", prefix + "-cs-a"+ sesv2.create_configuration_set(ConfigurationSetName=cs_b)+ sesv2.create_configuration_set(ConfigurationSetName=cs_a)+ dom = prefix + ".example.com"+ sesv2.create_email_identity(EmailIdentity=dom)+ arns = [+ f"arn:aws:ses:us-east-1:000000000000:{kind}/{leaf}"+ for kind, leaf in [+ ("configuration-set", cs_b),+ ("identity", dom),+ ("configuration-set", cs_a),+ ]+ ]+ for arn in arns:+ sesv2.create_tenant_resource_association(TenantName=first, ResourceArn=arn)+ listed = sesv2.list_tenant_resources(TenantName=first)["TenantResources"]+ assert [item["ResourceArn"] for item in listed] == sorted(arns)+ for arn in arns:+ sesv2.delete_tenant_resource_association(TenantName=first, ResourceArn=arn)+ sesv2.delete_tenant(TenantName=first)+ sesv2.delete_tenant(TenantName=second)+ sesv2.delete_configuration_set(ConfigurationSetName=cs_b)+ sesv2.delete_configuration_set(ConfigurationSetName=cs_a)+ sesv2.delete_email_identity(EmailIdentity=dom)+++def test_tenant_resource_tenants_keep_creation_order(sesv2):+ prefix = "tenant-rto-" + uuid.uuid4().hex[:10]+ cs = prefix + "-cs"+ sesv2.create_configuration_set(ConfigurationSetName=cs)+ arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"+ early, late = prefix + "-early", prefix + "-late"+ sesv2.create_tenant(TenantName=early)+ sesv2.create_tenant(TenantName=late)+ sesv2.create_tenant_resource_association(TenantName=late, ResourceArn=arn)+ sesv2.create_tenant_resource_association(TenantName=early, ResourceArn=arn)+ names = [+ item["TenantName"]+ for item in sesv2.list_resource_tenants(ResourceArn=arn)["ResourceTenants"]+ ]+ assert names == [early, late]+ sesv2.delete_tenant(TenantName=early)+ sesv2.delete_tenant(TenantName=late)+ sesv2.delete_configuration_set(ConfigurationSetName=cs)+++def test_tenant_resource_delete_guards(sesv2, ses):+ prefix = "tenant-guard-" + uuid.uuid4().hex[:10]+ cs, tpl, dom = prefix + "-cs", prefix + "-tpl", prefix + ".example.com"+ sesv2.create_configuration_set(ConfigurationSetName=cs)+ sesv2.create_email_template(TemplateName=tpl, TemplateContent={"Subject": "s", "Text": "t"})+ sesv2.create_email_identity(EmailIdentity=dom)+ name = prefix + "-t"+ sesv2.create_tenant(TenantName=name)+ arns = {+ kind: f"arn:aws:ses:us-east-1:000000000000:{kind}/{leaf}"+ for kind, leaf in [("configuration-set", cs), ("template", tpl), ("identity", dom)]+ }+ for arn in arns.values():+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=arn)+ for operation, params in [+ ("delete_configuration_set", {"ConfigurationSetName": cs}),+ ("delete_email_template", {"TemplateName": tpl}),+ ("delete_email_identity", {"EmailIdentity": dom}),+ ]:+ kind = {"delete_configuration_set": "configuration-set",+ "delete_email_template": "template",+ "delete_email_identity": "identity"}[operation]+ _error(sesv2, operation, "BadRequestException",+ f"Cannot delete <{arns[kind]}> because it has tenant associations."+ " Remove all tenant associations and try again.",+ **params)+ for operation, params in [+ ("delete_configuration_set", {"ConfigurationSetName": cs}),+ ("delete_template", {"TemplateName": tpl}),+ ("delete_identity", {"Identity": dom}),+ ]:+ kind = {"delete_configuration_set": "configuration-set",+ "delete_template": "template",+ "delete_identity": "identity"}[operation]+ _error(ses, operation, "InvalidParameterValue",+ f"Cannot delete <{arns[kind]}> because it has tenant associations."+ " Remove all tenant associations and try again.",+ **params)+ for arn in arns.values():+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=arn)+ sesv2.delete_tenant(TenantName=name)+ sesv2.delete_configuration_set(ConfigurationSetName=cs)+ sesv2.delete_email_template(TemplateName=tpl)+ sesv2.delete_email_identity(EmailIdentity=dom)+++def test_tenant_association_rejects_non_ses_arn(sesv2):+ name = "tenant-nonses-" + uuid.uuid4().hex[:10]+ sesv2.create_tenant(TenantName=name)+ _error(sesv2, "create_tenant_resource_association", "BadRequestException",+ "Provided ARN is not in SES resource ARN format",+ TenantName=name, ResourceArn=f"arn:aws:s3:::{name}-bucket")+ _error(sesv2, "list_tags_for_resource", "NotFoundException",+ f"No Tenant present with name: nullwith tenantId: {name}",+ ResourceArn=f"arn:aws:ses:us-east-1:000000000000:tenant/{name}")+ sesv2.delete_tenant(TenantName=name)+++def test_tenant_list_pagesize_bounds(sesv2):+ name = "tenant-pages-" + uuid.uuid4().hex[:10]+ sesv2.create_tenant(TenantName=name)+ _error(sesv2, "list_tenants", "BadRequestException",+ "1 validation error detected: Value '0' at 'pageSize' failed to satisfy"+ " constraint: Member must have value greater than or equal to 1",+ PageSize=0)+ over = ("1 validation error detected: Value '101' at 'pageSize' failed to satisfy"+ " constraint: Member must have value less than or equal to 100")+ _error(sesv2, "list_tenants", "BadRequestException", over, PageSize=101)+ _error(sesv2, "list_tenant_resources", "BadRequestException", over,+ TenantName=name, PageSize=101)+ cs = name + "-cs"+ sesv2.create_configuration_set(ConfigurationSetName=cs)+ arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"+ _error(sesv2, "list_resource_tenants", "BadRequestException", over,+ ResourceArn=arn, PageSize=101)+ sesv2.delete_tenant(TenantName=name)+ sesv2.delete_configuration_set(ConfigurationSetName=cs)+++def test_tenant_v1_resources_can_be_associated(sesv2, ses):+ prefix = "tenant-v1res-" + uuid.uuid4().hex[:10]+ cs, dom = prefix + "-cs", prefix + ".example.com"+ ses.create_configuration_set(ConfigurationSet={"Name": cs})+ ses.verify_domain_identity(Domain=dom)+ name = prefix + "-t"+ sesv2.create_tenant(TenantName=name)+ cs_arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"+ idn_arn = f"arn:aws:ses:us-east-1:000000000000:identity/{dom}"+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=cs_arn)+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=idn_arn)+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == [+ {"ResourceType": "configuration-set", "ResourceArn": cs_arn},+ {"ResourceType": "identity", "ResourceArn": idn_arn},+ ]+ blocked = "because it has tenant associations. Remove all tenant associations and try again."+ _error(sesv2, "delete_configuration_set", "BadRequestException",+ f"Cannot delete <{cs_arn}> {blocked}", ConfigurationSetName=cs)+ _error(sesv2, "delete_email_identity", "BadRequestException",+ f"Cannot delete <{idn_arn}> {blocked}", EmailIdentity=dom)+ _error(ses, "delete_configuration_set", "InvalidParameterValue",+ f"Cannot delete <{cs_arn}> {blocked}", ConfigurationSetName=cs)+ _error(ses, "delete_identity", "InvalidParameterValue",+ f"Cannot delete <{idn_arn}> {blocked}", Identity=dom)+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=cs_arn)+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=idn_arn)+ sesv2.delete_tenant(TenantName=name)+ ses.delete_configuration_set(ConfigurationSetName=cs)+ ses.delete_identity(Identity=dom)+++def test_tenant_association_normalizes_foreign_partitions(sesv2):+ prefix = "tenant-part-" + uuid.uuid4().hex[:10]+ cs = prefix + "-cs"+ sesv2.create_configuration_set(ConfigurationSetName=cs)+ name = prefix + "-t"+ tenant = sesv2.create_tenant(TenantName=name)+ aws_arn = f"arn:aws:ses:us-east-1:000000000000:configuration-set/{cs}"+ cn_arn = f"arn:aws-cn:ses:us-east-1:000000000000:configuration-set/{cs}"+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=cn_arn)+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == [+ {"ResourceType": "configuration-set", "ResourceArn": aws_arn}+ ]+ _error(sesv2, "create_tenant_resource_association", "AlreadyExistsException",+ f"Resources {aws_arn} has already been associated with tenant {name}",+ TenantName=name, ResourceArn=aws_arn)+ inverse = sesv2.list_resource_tenants(ResourceArn=cn_arn)["ResourceTenants"]+ assert [(item["TenantName"], item["ResourceArn"]) for item in inverse] == [(name, aws_arn)]+ _error(sesv2, "delete_configuration_set", "BadRequestException",+ f"Cannot delete <{aws_arn}> because it has tenant associations."+ " Remove all tenant associations and try again.",+ ConfigurationSetName=cs)+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=aws_arn)+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == []+ sesv2.create_tenant_resource_association(TenantName=name, ResourceArn=aws_arn)+ sesv2.delete_tenant_resource_association(TenantName=name, ResourceArn=cn_arn)+ assert sesv2.list_tenant_resources(TenantName=name)["TenantResources"] == []+ xacct = f"arn:aws-cn:ses:us-east-1:111122223333:configuration-set/{cs}"+ _error(sesv2, "create_tenant_resource_association", "BadRequestException",+ f"Resource <{xacct}> must be in the same account",+ TenantName=name, ResourceArn=xacct)+ cn_tenant = tenant["TenantArn"].replace("arn:aws:", "arn:aws-cn:", 1)+ sesv2.tag_resource(ResourceArn=cn_tenant, Tags=[{"Key": "pk", "Value": "v"}])+ assert sesv2.list_tags_for_resource(ResourceArn=tenant["TenantArn"])["Tags"] == [+ {"Key": "pk", "Value": "v"}+ ]+ sesv2.tag_resource(ResourceArn=cn_arn, Tags=[{"Key": "ck", "Value": "v"}])+ assert sesv2.list_tags_for_resource(ResourceArn=aws_arn)["Tags"] == [+ {"Key": "ck", "Value": "v"}+ ]+ sesv2.delete_tenant(TenantName=name)+ sesv2.delete_configuration_set(ConfigurationSetName=cs)diff --git a/tests/test_ses_v2.py b/tests/test_ses_v2.pyindex 93581f5b..f77163c7 100644--- a/tests/test_ses_v2.py+++ b/tests/test_ses_v2.py@@ -260,7 +260,6 @@ def test_ses_v2_configuration_set_tag_resource_uses_parser_backed_resource_arn(s["not-an-arn",f"arn:aws:ses:{REGION}:{ACCOUNT_ID}",- _arn("identity", "parser.example.com", partition="aws-cn"),_arn("identity", "parser.example.com", service="sesv2"),_arn("identity", "parser.example.com", region="us-west-2"),_arn("identity", "parser.example.com", account="111111111111"),@@ -303,6 +302,22 @@ def test_ses_v2_tag_apis_reject_invalid_resource_arns_before_touching_tags(ses_vassert body["Tags"] == [{"Key": "keep", "Value": "yes"}]+def test_ses_v2_tag_apis_accept_foreign_partitions_on_one_store(ses_v2):+ identity = "partition.example.com"+ aws_arn = _arn("identity", identity)+ cn_arn = _arn("identity", identity, partition="aws-cn")+ _call(ses_v2, "POST", "/v2/email/identities", body={"EmailIdentity": identity})++ status, _ = _call(+ ses_v2, "POST", body={"ResourceArn": cn_arn, "Tags": [{"Key": "team", "Value": "email"}]}+ )+ assert status == 200+ for arn in (aws_arn, cn_arn):+ status, body = _call(ses_v2, "GET", query={"ResourceArn": [arn]})+ assert status == 200+ assert body["Tags"] == [{"Key": "team", "Value": "email"}]++@pytest.mark.parametrize("method", ["GET", "POST", "DELETE"])def test_ses_v2_tag_apis_reject_missing_local_resources_before_touching_tags(ses_v2, method):missing_arn = _arn("identity", "missing.example.com")