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
fix/september aws parity test (#1618)
Nahuel Nucerad6ca72a8216e
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.pyindex c08fedcf..d66d7a19 100644--- a/ministack/services/appsync.py+++ b/ministack/services/appsync.py@@ -2402,7 +2402,7 @@ def _ddb_scan(table, table_name, args, sub_fields):filtered.append(item)items = filtered- return {"items": items, "nextToken": None}+ return {"items": items}def _ddb_put_item(table, table_name, args):diff --git a/ministack/services/bedrock_agent_runtime.py b/ministack/services/bedrock_agent_runtime.pyindex 97857eeb..509990f8 100644--- a/ministack/services/bedrock_agent_runtime.py+++ b/ministack/services/bedrock_agent_runtime.py@@ -272,7 +272,7 @@ def _invoke_inline_agent(session_id: str, body) -> tuple:def _get_agent_memory(agent_id: str, alias_id: str, query_params) -> tuple:key = f"{agent_id}/{alias_id}"memories = _agent_memories.get(key, [])- return _json({"MemoryContents": memories, "NextToken": None})+ return _json({"MemoryContents": memories})def _delete_agent_memory(agent_id: str, alias_id: str, query_params) -> tuple:@@ -317,7 +317,7 @@ def _retrieve(kb_id: str, body) -> tuple:"Location": {"Type": "S3", "S3Location": {"Uri": doc["Uri"]}},"Score": round(score, 4),} for score, doc in scored[:number_of_results]]- return _json({"RetrievalResults": results, "NextToken": None})+ return _json({"RetrievalResults": results})def _retrieve_and_generate(body) -> tuple:@@ -365,7 +365,7 @@ def _rerank(body) -> tuple:sources = body_obj.get("sources", [])results = [{"Index": i, "RelevanceScore": 1.0 - (i * 0.1)}for i in range(len(sources))]- return _json({"Results": results, "NextToken": None})+ return _json({"Results": results})def _generate_query(body) -> tuple:diff --git a/ministack/services/bedrock_runtime.py b/ministack/services/bedrock_runtime.pyindex 766266d5..8ae9df46 100644--- a/ministack/services/bedrock_runtime.py+++ b/ministack/services/bedrock_runtime.py@@ -1105,7 +1105,6 @@ def _list_async_invokes(query_params) -> tuple:continuesummaries.append(rec)return 200, {"Content-Type": "application/json"}, json.dumps({- "nextToken": None,"asyncInvokeSummaries": summaries,}).encode()diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.pyindex 8cd4edb6..264d0250 100644--- a/ministack/services/cloudwatch_logs.py+++ b/ministack/services/cloudwatch_logs.py@@ -1112,7 +1112,12 @@ def _fanout_to_subscription_filters(group_name, stream_name, events):from ministack.services import lambda_svcrec = lambda_svc._functions.get(fn)if rec:- threading.Thread(target=lambda_svc._execute_function,+ # Scope the invoke from the function's own config: a bare+ # thread has an empty context, so plain _execute_function would+ # run the subscriber (and its side effects — own log group,+ # downstream calls) under the default account for any+ # non-default tenant.+ threading.Thread(target=lambda_svc._execute_function_with_config_scope,args=(rec, awslogs_event), daemon=True).start()else:logger.warning("subscription filter %s: destination Lambda %s not found",diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex ee0e679a..6cd6a391 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -88,7 +88,7 @@ _pitr_settings = AccountRegionScopedDict()_kinesis_destinations = AccountRegionScopedDict()# Contributor Insights — key is "TableName" or "TableName/index/IndexName".# Value: {"ContributorInsightsStatus": "ENABLED"|"DISABLED",-# "LastUpdateDateTime": float epoch, "ContributorInsightsRuleList": [str, ...]}.+# "LastUpdateDateTime": int epoch, "ContributorInsightsRuleList": [str, ...]}._backups = AccountRegionScopedDict() # BackupArn -> BackupDescription dict_contributor_insights = AccountRegionScopedDict()# Resource-based policies — ResourceArn -> {"Policy": str, "RevisionId": str}.@@ -4222,7 +4222,7 @@ def _update_contributor_insights(data):new_status = "ENABLING" if action == "ENABLE" else "DISABLING"_contributor_insights[key] = {"ContributorInsightsStatus": new_status,- "LastUpdateDateTime": time.time(),+ "LastUpdateDateTime": int(time.time()),"ContributorInsightsRuleList": [],}resp = {@@ -4261,11 +4261,11 @@ def _describe_contributor_insights(data):if cur == "ENABLING":cur = "ENABLED"entry["ContributorInsightsStatus"] = "ENABLED"- entry["LastUpdateDateTime"] = time.time()+ entry["LastUpdateDateTime"] = int(time.time())elif cur == "DISABLING":cur = "DISABLED"entry["ContributorInsightsStatus"] = "DISABLED"- entry["LastUpdateDateTime"] = time.time()+ entry["LastUpdateDateTime"] = int(time.time())status = curlast_update = entry.get("LastUpdateDateTime")rules = list(entry.get("ContributorInsightsRuleList") or [])diff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex a5a4bbf2..56429260 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -1195,10 +1195,16 @@ def _reboot_instances(p):# (ami_id, name, description, platform, root_device_name)# platform: "windows" or "" (Linux/Unix — matches AWS's empty-field behaviour)# root_device_name: Windows AMIs use /dev/sda1, Linux HVM uses /dev/xvda.+# (ami_id, name, description, platform, root_device, owner_id, owner_alias).+# Owner ids are the real publishing accounts — 137112412989 (Amazon Linux),+# 801119661308 (Windows), 099720109477 (Canonical) — with ImageOwnerAlias+# "amazon" on the Amazon-published pair and none on Canonical's, exactly as+# DescribeImages reports them on AWS. That is what makes Owners=["amazon"]+# (Terraform's aws_ami data source) select the same images it selects there._STUB_AMIS = [- ("ami-0abcdef1234567890", "amzn2-ami-hvm-2.0.20231116.0-x86_64-gp2", "Amazon Linux 2", "", "/dev/xvda"),- ("ami-0123456789abcdef0", "ubuntu/images/hvm-ssd/ubuntu-22.04-amd64-server", "Ubuntu 22.04", "", "/dev/xvda"),- ("ami-0fedcba9876543210", "Windows_Server-2022-English-Full-Base", "Windows Server 2022", "windows", "/dev/sda1"),+ ("ami-0abcdef1234567890", "amzn2-ami-hvm-2.0.20231116.0-x86_64-gp2", "Amazon Linux 2", "", "/dev/xvda", "137112412989", "amazon"),+ ("ami-0123456789abcdef0", "ubuntu/images/hvm-ssd/ubuntu-22.04-amd64-server", "Ubuntu 22.04", "", "/dev/xvda", "099720109477", None),+ ("ami-0fedcba9876543210", "Windows_Server-2022-English-Full-Base", "Windows Server 2022", "windows", "/dev/sda1", "801119661308", "amazon"),]@@ -1223,7 +1229,7 @@ def _image_view(image):}-def _stub_image_view(ami_id, name, desc, platform, root_device):+def _stub_image_view(ami_id, name, desc, platform, root_device, owner_id, owner_alias):return {"ImageId": ami_id,"Name": name,@@ -1234,7 +1240,8 @@ def _stub_image_view(ami_id, name, desc, platform, root_device):"BlockDeviceMappings": [],"Architecture": "x86_64","VirtualizationType": "hvm",- "OwnerId": get_account_id(),+ "OwnerId": owner_id,+ "ImageOwnerAlias": owner_alias,"IsPublic": "true","Backed": False,}@@ -1250,6 +1257,8 @@ def _image_matches_filters(view, filters):actual = [view["Description"]]elif name == "owner-id":actual = [view["OwnerId"]]+ elif name == "owner-alias":+ actual = [view.get("ImageOwnerAlias") or ""]elif name == "architecture":actual = [view["Architecture"]]elif name == "virtualization-type":@@ -1318,10 +1327,19 @@ def _image_bdm_xml(view):def _image_owner_matches(view, owners):"""Owner.N: "a combination of AWS account IDs, self, amazon, aws-backup-vault, and- aws-marketplace". Every image here belongs to the calling account, so an alias or another- account's id matches nothing."""+ aws-marketplace". A registered image belongs to the calling account (matched by id or+ ``self``); the seeded public images carry their real publishing account and, for the+ Amazon-published ones, the ``amazon`` alias — so ``Owners=["amazon"]`` selects them as+ it does on AWS."""account = get_account_id()- return view["OwnerId"] == account and any(o in ("self", account) for o in owners)+ for o in owners:+ if o == view["OwnerId"]:+ return True+ if o == "self" and view["OwnerId"] == account:+ return True+ if o == view.get("ImageOwnerAlias"):+ return True+ return Falsedef _image_executable_by_matches(view, users):@@ -1356,6 +1374,10 @@ def _describe_images(p):# provider on aws_instance — it resolves them from DescribeImages before# RunInstances and fails with "finding Root Device Name for AMI" if absent.platform_xml = f"<platform>{view['Platform']}</platform>" if view["Platform"] else ""+ owner_alias_xml = (+ f"<imageOwnerAlias>{view['ImageOwnerAlias']}</imageOwnerAlias>"+ if view.get("ImageOwnerAlias") else ""+ )tag_items = "".join(f"<item><key>{_esc(t['Key'])}</key><value>{_esc(t.get('Value', ''))}</value></item>"for t in _tags.get(view["ImageId"], []))@@ -1365,6 +1387,7 @@ def _describe_images(p):<imageLocation>{_esc(view['Name'])}</imageLocation><imageState>available</imageState><imageOwnerId>{view['OwnerId']}</imageOwnerId>+ {owner_alias_xml}<isPublic>{view['IsPublic']}</isPublic><architecture>{view['Architecture']}</architecture><imageType>machine</imageType>diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.pyindex d025936a..8d83e8a7 100644--- a/ministack/services/elasticache.py+++ b/ministack/services/elasticache.py@@ -2348,9 +2348,17 @@ def _cluster_xml_inner(c):parameter_group = c.get("CacheParameterGroup", {})security_groups_xml = _security_groups_xml(c.get("SecurityGroups", []))log_delivery_configs_xml = _log_delivery_configs_xml(c.get("LogDeliveryConfigurations", []))+ # CacheClusterCreateTime is a TStamp; the store keeps a float epoch, the+ # wire wants ISO8601 (same conversion as CacheNodeCreateTime below).+ cluster_created = c.get("CacheClusterCreateTime") or time.time()+ if isinstance(cluster_created, (int, float)):+ cluster_created_iso = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(cluster_created))+ else:+ cluster_created_iso = str(cluster_created)return (f"<CacheClusterId>{c['CacheClusterId']}</CacheClusterId>"f"<CacheClusterStatus>{c['CacheClusterStatus']}</CacheClusterStatus>"+ f"<CacheClusterCreateTime>{cluster_created_iso}</CacheClusterCreateTime>"f"<Engine>{c['Engine']}</Engine>"f"<EngineVersion>{c['EngineVersion']}</EngineVersion>"f"<CacheNodeType>{c['CacheNodeType']}</CacheNodeType>"diff --git a/ministack/services/lambda_durable.py b/ministack/services/lambda_durable.pyindex 2647ad51..3baaa74a 100644--- a/ministack/services/lambda_durable.py+++ b/ministack/services/lambda_durable.py@@ -545,7 +545,6 @@ def handle_checkpoint(arn_path: str, body: bytes) -> tuple:return json_response({"CheckpointToken": new_token,"NewExecutionState": {- "NextMarker": "","Operations": _serialize_operations(rec["Operations"]),},})diff --git a/ministack/services/lambda_microvms.py b/ministack/services/lambda_microvms.pyindex 327314d0..04453358 100644--- a/ministack/services/lambda_microvms.py+++ b/ministack/services/lambda_microvms.py@@ -206,7 +206,7 @@ def _list_microvms(query_params):if version_filter and record.get("imageVersion") != version_filter:continueitems.append(_microvm_item(record))- return json_response({"items": items, "nextToken": None})+ return json_response({"items": items})def _suspend_microvm(microvm_id):diff --git a/ministack/services/msk.py b/ministack/services/msk.pyindex 298c1e5c..a26d1058 100644--- a/ministack/services/msk.py+++ b/ministack/services/msk.py@@ -313,7 +313,6 @@ def _list_clusters(query_params) -> tuple:summaries.append(info)return _json({"ClusterInfoList": summaries,- "NextToken": None,})@@ -365,7 +364,7 @@ def _list_nodes(arn: str) -> tuple:"Endpoints": [bootstrap["BootstrapBrokerString"].split(",")[0]],},})- return _json({"NodeInfoList": nodes, "NextToken": None})+ return _json({"NodeInfoList": nodes})# ---------------------------------------------------------------------------@@ -424,7 +423,6 @@ def _create_configuration(body) -> tuple:def _list_configurations(query_params) -> tuple:return _json({"Configurations": list(_configurations.values()),- "NextToken": None,})@@ -446,7 +444,7 @@ def _list_configuration_revisions(arn: str) -> tuple:"Description": r["Description"],"Revision": r["Revision"],} for r in revs]- return _json({"Revisions": summaries, "NextToken": None})+ return _json({"Revisions": summaries})def _describe_configuration_revision(arn: str, revision: str) -> tuple:@@ -530,7 +528,6 @@ def _list_scram_secrets(arn: str) -> tuple:return validation_errorreturn _json({"SecretArnList": list(_scram_secrets.get(arn, [])),- "NextToken": None,})diff --git a/ministack/services/organizations.py b/ministack/services/organizations.pyindex a7431b38..4f3021f7 100644--- a/ministack/services/organizations.py+++ b/ministack/services/organizations.py@@ -123,14 +123,13 @@ def _describe_organization(_payload):def _list_roots(_payload):_ensure_org()- return _json(200, {"Roots": list(_roots.values()), "NextToken": None})+ return _json(200, {"Roots": list(_roots.values())})def _list_accounts(_payload):_ensure_org()return _json(200, {"Accounts": [_public_account(a) for a in _accounts.values()],- "NextToken": None,})@@ -150,7 +149,7 @@ def _list_organizational_units_for_parent(payload):_ensure_org()parent_id = payload.get("ParentId") or ""out = [_public_ou(o) for o in _ous.values() if o.get("_ParentId") == parent_id]- return _json(200, {"OrganizationalUnits": out, "NextToken": None})+ return _json(200, {"OrganizationalUnits": out})def _list_accounts_for_parent(payload):@@ -158,7 +157,7 @@ def _list_accounts_for_parent(payload):parent_id = payload.get("ParentId") or ""out = [_public_account(a) for a in _accounts.values()if a.get("_ParentId") == parent_id]- return _json(200, {"Accounts": out, "NextToken": None})+ return _json(200, {"Accounts": out})def _list_parents(payload):@@ -178,7 +177,7 @@ def _list_parents(payload):)parent_id = rec.get("_ParentId")parent_type = "ROOT" if str(parent_id).startswith("r-") else "ORGANIZATIONAL_UNIT"- return _json(200, {"Parents": [{"Id": parent_id, "Type": parent_type}], "NextToken": None})+ return _json(200, {"Parents": [{"Id": parent_id, "Type": parent_type}]})def _create_organizational_unit(payload):@@ -290,7 +289,7 @@ def _list_tags_for_resource(payload):return err# A consumer's Read of any taggable org resource calls ListTagsForResource on# create + refresh; without it the read-back fails and apply can't converge.- return _json(200, {"Tags": _tag_list(rid), "NextToken": None})+ return _json(200, {"Tags": _tag_list(rid)})_DISPATCH = {diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex 76f2c3c8..b9fc5590 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -18,6 +18,7 @@ FIFO topics: .fifo naming validation, MessageGroupId/MessageDeduplicationId enfo"""import asyncio+import contextvarsimport copyimport hashlibimport json@@ -970,9 +971,15 @@ def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,# subscriber's execution. Deliver on a background thread, mirroring# the http(s) path above; a slow or failing subscriber Lambda no# longer stalls the Publish call (or its upstream caller).+ # The publisher's account/region contextvars must travel into the+ # thread: _get_func_record_for_ref rejects an ARN whose account+ # differs from get_account_id(), and a fresh thread's empty context+ # reads back the default account — dropping every delivery for a+ # non-default tenant.+ _sns_ctx = contextvars.copy_context()_threading.Thread(- target=_deliver_to_lambda,- args=(endpoint, envelope, topic_arn, sub["arn"], msg_id, effective_message, message_attributes or {}),+ target=_sns_ctx.run,+ args=(_deliver_to_lambda, endpoint, envelope, topic_arn, sub["arn"], msg_id, effective_message, message_attributes or {}),daemon=True,).start()elif protocol == "email" or protocol == "email-json":diff --git a/ministack/services/waf_v1.py b/ministack/services/waf_v1.pyindex f0683324..1fa5eeeb 100644--- a/ministack/services/waf_v1.py+++ b/ministack/services/waf_v1.py@@ -76,10 +76,9 @@ async def handle_request(method, path, headers, body, query_params):# ListTagsForResource returns a struct, not a listif op == "ListTagsForResource":return _v1_response({- "NextMarker": None,"TagInfoForResource": {"ResourceARN": "", "TagList": []},})- return _v1_response({key: [], "NextMarker": None})+ return _v1_response({key: []})if op == "GetChangeToken":return _v1_response({"ChangeToken": _change_token()})diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.pyindex ba1932c1..f4052e6e 100644--- a/tests/test_cloudwatch_logs.py+++ b/tests/test_cloudwatch_logs.py@@ -1776,3 +1776,79 @@ def test_logs_delivery_source_tag_round_trip(logs):logs.untag_resource(resourceArn=arn, tagKeys=["env"])assert logs.list_tags_for_resource(resourceArn=arn)["tags"] == {"team": "events"}logs.delete_delivery_source(name=src_name)+++def test_logs_subscription_filter_delivers_for_non_default_account():+ """Subscription-filter → Lambda delivery under a 12-digit-key tenant.++ Guards the account-scoped path end-to-end: the destination function is+ resolved in the caller's account and invoked via the config-scope wrapper+ (a bare-thread invoke would otherwise run the subscriber's bookkeeping+ under the default account)."""+ import io+ import zipfile++ account = "271828182845"++ def _acct(service):+ return boto3.client(+ service,+ endpoint_url=_endpoint,+ region_name="us-east-1",+ aws_access_key_id=account,+ aws_secret_access_key="test",+ config=Config(retries={"mode": "standard"}),+ )++ logs_c = _acct("logs")+ lam_c = _acct("lambda")+ sqs_c = _acct("sqs")+ suffix = _uuid_mod.uuid4().hex[:8]++ qname = f"subfilter-xacct-signal-{suffix}"+ q_url = sqs_c.create_queue(QueueName=qname)["QueueUrl"]++ fn = f"subfilter-xacct-{suffix}"+ code = (+ "import os, boto3\n"+ f"QNAME = {qname!r}\n"+ "def handler(event, context):\n"+ " sqs = boto3.client('sqs', endpoint_url=os.environ['AWS_ENDPOINT_URL'])\n"+ " url = sqs.get_queue_url(QueueName=QNAME)['QueueUrl']\n"+ " sqs.send_message(QueueUrl=url, MessageBody='delivered')\n"+ " return {'ok': True}\n"+ )+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam_c.create_function(+ FunctionName=fn,+ Runtime="python3.12",+ Role=f"arn:aws:iam::{account}:role/lambda-role",+ Handler="index.handler",+ Timeout=30,+ Code={"ZipFile": buf.getvalue()},+ )+ func_arn = f"arn:aws:lambda:us-east-1:{account}:function:{fn}"++ group = f"/intg/subfilter-xacct/{suffix}"+ logs_c.create_log_group(logGroupName=group)+ logs_c.create_log_stream(logGroupName=group, logStreamName="s1")+ logs_c.put_subscription_filter(+ logGroupName=group,+ filterName="xacct-filter",+ filterPattern="ERROR",+ destinationArn=func_arn,+ )+ logs_c.put_log_events(+ logGroupName=group,+ logStreamName="s1",+ logEvents=[{"timestamp": int(time.time() * 1000), "message": "ERROR boom"}],+ )++ deadline = time.time() + 30+ got = []+ while time.time() < deadline and not got:+ msgs = sqs_c.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=2)+ got = msgs.get("Messages", [])+ assert got, "subscription-filter → Lambda delivery never arrived for a non-default account"diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.pyindex d8a92966..0cf635c6 100644--- a/tests/test_dynamodb.py+++ b/tests/test_dynamodb.py@@ -7085,3 +7085,29 @@ def test_unicode_dynamodb_item(ddb):ddb.put_item(TableName=table, Item=item)resp = ddb.get_item(TableName=table, Key={"pk": {"S": "ключ"}})assert resp["Item"]["value"]["S"] == "значение 日本語 مرحبا"+++def test_contributor_insights_last_update_is_int_epoch(ddb):+ """LastUpdateDateTime rides the wire as an int epoch (project convention;+ a float breaks Java SDK v2 timestamp parsing). Raw HTTP because boto3+ converts either form to datetime and hides the difference."""+ table = "ci-int-epoch"+ ddb.create_table(+ TableName=table,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ try:+ code, _ = _raw_ddb("UpdateContributorInsights", {+ "TableName": table,+ "ContributorInsightsAction": "ENABLE",+ })+ assert code == 200+ code, body = _raw_ddb("DescribeContributorInsights", {"TableName": table})+ assert code == 200+ lud = body.get("LastUpdateDateTime")+ if lud is not None:+ assert isinstance(lud, int), f"expected int epoch, got {type(lud).__name__}: {lud}"+ finally:+ ddb.delete_table(TableName=table)diff --git a/tests/test_ec2.py b/tests/test_ec2.pyindex 646ed5d6..d7130c69 100644--- a/tests/test_ec2.py+++ b/tests/test_ec2.py@@ -541,11 +541,43 @@ def test_ec2_run_multiple_instances(ec2):ec2.terminate_instances(InstanceIds=ids)def test_ec2_describe_images(ec2):- resp = ec2.describe_images(Owners=["self"])- assert len(resp["Images"]) >= 1+ resp = ec2.describe_images()+ assert len(resp["Images"]) >= 3assert all("ImageId" in img for img in resp["Images"])+def test_ec2_describe_images_amazon_owner_matches_aws_shape(ec2):+ """Owners=["amazon"] selects the Amazon-published images with their real+ publishing accounts and ImageOwnerAlias, as on AWS — a Terraform aws_ami+ data source with owners = ["amazon"] must find them."""+ amazon = ec2.describe_images(Owners=["amazon"])["Images"]+ names = {img["Name"] for img in amazon}+ assert any(n.startswith("amzn2-ami-hvm") for n in names)+ assert any(n.startswith("Windows_Server") for n in names)+ assert not any("ubuntu" in n for n in names)+ by_name = {img["Name"]: img for img in amazon}+ al2 = next(img for n, img in by_name.items() if n.startswith("amzn2-ami-hvm"))+ assert al2["OwnerId"] == "137112412989"+ assert al2["ImageOwnerAlias"] == "amazon"++ # Canonical's Ubuntu carries its real account and no amazon alias.+ ubuntu = ec2.describe_images(Owners=["099720109477"])["Images"]+ assert any("ubuntu" in img["Name"] for img in ubuntu)+ assert all("ImageOwnerAlias" not in img or img["ImageOwnerAlias"] != "amazon"+ for img in ubuntu)++ # owner-alias filter, same selection.+ via_filter = ec2.describe_images(+ Filters=[{"Name": "owner-alias", "Values": ["amazon"]}])["Images"]+ assert {img["ImageId"] for img in via_filter} == {img["ImageId"] for img in amazon}++ # The seeded public images are not the caller's: self selects only+ # registered/created images, empty when there are none — as on AWS.+ mine = ec2.describe_images(Owners=["self"])["Images"]+ assert not any(img["Name"].startswith(("amzn2-ami-hvm", "Windows_Server"))+ or "ubuntu" in img["Name"] for img in mine)++def test_ec2_describe_images_has_root_device_and_block_mappings(ec2):# Terraform's AWS provider resolves these before aws_instance creation;# absence produced "finding Root Device Name for AMI" and blocked apply.@@ -4254,14 +4286,18 @@ def test_ec2_image_with_an_entrypoint_is_left_alone(monkeypatch):def test_ec2_describe_images_scopes_by_owner(ec2):- """Owner.N: account ids and `self` select ours; an alias or another account selects nothing."""+ """Owner.N: account ids and `self` select ours; `amazon` selects the+ Amazon-published public images (their real publishing accounts, as on+ AWS); an alias nothing carries, or a foreign account, selects nothing."""ami = ec2.register_image(Name=f"owned-{_uuid_mod.uuid4().hex[:8]}",ImageLocation="alpine:3")["ImageId"]try:assert ami in [i["ImageId"] for i in ec2.describe_images(Owners=["self"])["Images"]]assert ami in [i["ImageId"] for i inec2.describe_images(Owners=["000000000000"])["Images"]]- for scope in (["amazon"], ["aws-marketplace"], ["123456789012"]):+ amazon = [i["ImageId"] for i in ec2.describe_images(Owners=["amazon"])["Images"]]+ assert "ami-0abcdef1234567890" in amazon and ami not in amazon+ for scope in (["aws-marketplace"], ["123456789012"]):assert ec2.describe_images(Owners=scope)["Images"] == [], scopefinally:ec2.deregister_image(ImageId=ami)diff --git a/tests/test_elasticache.py b/tests/test_elasticache.pyindex 2afff868..ee367fe6 100644--- a/tests/test_elasticache.py+++ b/tests/test_elasticache.py@@ -1831,3 +1831,22 @@ def test_elasticache_delete_during_deferred_start_leaves_no_container(fake_dockeassert fake_docker.live() == [], (f"leaked container(s) {fake_docker.live()} — running, and no API call can reach them")+++def test_elasticache_cluster_create_time_present_and_parsed(ec):+ """DescribeCacheClusters emits CacheClusterCreateTime as an ISO8601 TStamp+ (it was stored as a float epoch and previously absent from the XML)."""+ import datetime++ ec.create_cache_cluster(+ CacheClusterId="cluster-createtime",+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ try:+ cluster = ec.describe_cache_clusters(+ CacheClusterId="cluster-createtime")["CacheClusters"][0]+ assert isinstance(cluster.get("CacheClusterCreateTime"), datetime.datetime)+ finally:+ ec.delete_cache_cluster(CacheClusterId="cluster-createtime")diff --git a/tests/test_msk.py b/tests/test_msk.pyindex 61430de1..32975ef6 100644--- a/tests/test_msk.py+++ b/tests/test_msk.py@@ -405,3 +405,17 @@ def test_msk_clusters_isolated_by_region():assert "east-only" not in west_namesassert "west-only" in west_namesassert "west-only" not in east_names+++def test_msk_list_responses_omit_empty_next_token():+ """Empty NextToken must be omitted, not emitted as null — a literal null+ reads as a real token to Go/Java SDK pagination and Terraform sees drift."""+ kafka = _kafka()+ arn = _create_basic_cluster("mst-no-token")["ClusterArn"]+ try:+ assert "NextToken" not in kafka.list_clusters()+ assert "NextToken" not in kafka.list_nodes(ClusterArn=arn)+ assert "NextToken" not in kafka.list_configurations()+ assert "NextToken" not in kafka.list_scram_secrets(ClusterArn=arn)+ finally:+ kafka.delete_cluster(ClusterArn=arn)diff --git a/tests/test_organizations.py b/tests/test_organizations.pyindex e59626d7..5350fb11 100644--- a/tests/test_organizations.py+++ b/tests/test_organizations.py@@ -205,3 +205,13 @@ def test_organizations_tags_are_account_scoped():assert tags == {"owner": "a"}finally:a.delete_organizational_unit(OrganizationalUnitId=ou_a["Id"])+++def test_organizations_list_responses_omit_empty_next_token(orgs):+ """Empty NextToken is omitted (null breaks non-boto pagination clients)."""+ orgs.describe_organization()+ assert "NextToken" not in orgs.list_roots()+ assert "NextToken" not in orgs.list_accounts()+ root_id = orgs.list_roots()["Roots"][0]["Id"]+ assert "NextToken" not in orgs.list_organizational_units_for_parent(ParentId=root_id)+ assert "NextToken" not in orgs.list_accounts_for_parent(ParentId=root_id)diff --git a/tests/test_sns.py b/tests/test_sns.pyindex 8dc5804d..9188aaff 100644--- a/tests/test_sns.py+++ b/tests/test_sns.py@@ -2107,3 +2107,63 @@ def test_sns_publish_internal_rejections(sns_internal):with pytest.raises(sns_internal.SnsPublishError) as ei:sns_internal.publish_internal(standard, "x" * (256 * 1024 + 1))assert ei.value.code == "InvalidParameter"+++def test_sns_to_lambda_fanout_non_default_account(sqs):+ """Regression: SNS→Lambda delivery ran on a bare thread whose empty+ context read back the default account, so ``_get_func_record_for_ref``+ rejected the subscriber's ARN for any 12-digit-key tenant and the+ notification was silently dropped. The delivery thread now carries the+ publisher's contextvars."""+ account = "314159265358"++ def _acct(service):+ return boto3.client(+ service,+ endpoint_url=ENDPOINT,+ region_name="us-east-1",+ aws_access_key_id=account,+ aws_secret_access_key="test",+ config=Config(retries={"mode": "standard"}),+ )++ sns_c = _acct("sns")+ lam_c = _acct("lambda")+ sqs_c = _acct("sqs")+ suffix = _uuid_mod.uuid4().hex[:8]++ qname = f"sns-xacct-signal-{suffix}"+ q_url = sqs_c.create_queue(QueueName=qname)["QueueUrl"]++ fn = f"sns-xacct-{suffix}"+ # The worker's env creds derive from the FunctionArn, so the inner SQS+ # client resolves the queue in the function's own account.+ code = (+ "import os, boto3\n"+ f"QNAME = {qname!r}\n"+ "def handler(event, context):\n"+ " sqs = boto3.client('sqs', endpoint_url=os.environ['AWS_ENDPOINT_URL'])\n"+ " url = sqs.get_queue_url(QueueName=QNAME)['QueueUrl']\n"+ " sqs.send_message(QueueUrl=url, MessageBody='delivered')\n"+ " return {'ok': True}\n"+ )+ lam_c.create_function(+ FunctionName=fn,+ Runtime="python3.12",+ Role=f"arn:aws:iam::{account}:role/lambda-role",+ Handler="index.handler",+ Timeout=30,+ Code={"ZipFile": _make_zip(code)},+ )+ func_arn = f"arn:aws:lambda:us-east-1:{account}:function:{fn}"++ topic_arn = sns_c.create_topic(Name=f"sns-xacct-topic-{suffix}")["TopicArn"]+ sns_c.subscribe(TopicArn=topic_arn, Protocol="lambda", Endpoint=func_arn)+ sns_c.publish(TopicArn=topic_arn, Message="hello-cross-account")++ deadline = time.time() + 30+ got = []+ while time.time() < deadline and not got:+ msgs = sqs_c.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=2)+ got = msgs.get("Messages", [])+ assert got, "SNS→Lambda delivery never arrived for a non-default account"diff --git a/tests/test_waf_v1.py b/tests/test_waf_v1.pyindex eb8c4aa9..a5cd2582 100644--- a/tests/test_waf_v1.py+++ b/tests/test_waf_v1.py@@ -89,3 +89,10 @@ def test_waf_v1_module_exposes_no_op_reset():from ministack.services import waf_v1assert callable(getattr(waf_v1, "reset", None))waf_v1.reset()+++def test_waf_v1_list_responses_omit_empty_next_marker(waf_classic):+ """Empty NextMarker is omitted from the v1 stub's list responses."""+ assert "NextMarker" not in waf_classic.list_web_acls()+ assert "NextMarker" not in waf_classic.list_tags_for_resource(+ ResourceARN="arn:aws:waf::000000000000:webacl/none")