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: 52 f-string loggers, CFN Lambda::Permission/Version/WaitCondition/BucketPolicy, ElastiCache (#105)
Nahuel Nuceradb1cc2611fbe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e7219ee9..7f5e48e8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,25 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.1.30] — 2026-04-03++### Added+- **CloudFormation `AWS::Lambda::Permission`** — provisions Lambda invoke permissions via CFN stacks+- **CloudFormation `AWS::Lambda::Version`** — creates immutable Lambda versions via CFN stacks+- **CloudFormation `AWS::CloudFormation::WaitCondition`** — no-op stub, returns immediately+- **CloudFormation `AWS::CloudFormation::WaitConditionHandle`** — no-op stub, returns placeholder URL++### Fixed+- **Router duplicate action keys** — removed `ListTagsForResource` and `GetTemplate` from action map (shared across services, routed via credential scope instead)+- **ElastiCache reset missing state** — `_param_group_params` now cleared and `_port_counter` reset to `BASE_PORT` on reset+- **Bare except in Docker cleanup** — RDS, ECS, ElastiCache reset() now log warnings instead of silently swallowing errors+- **52 f-string logger calls** — converted to lazy % formatting across 13 service files; avoids unnecessary string formatting when log level is disabled+- **Detached mode log handle** — documented intentional fd inheritance in subprocess.Popen++Thanks to @moabukar for #104 (error handling, routing conflicts, persistence hardening)++---+## [1.1.29] — 2026-04-03### Fixeddiff --git a/ministack/app.py b/ministack/app.pyindex 9abdff10..a105558a 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -720,11 +720,16 @@ def main():if args.detach:log_file = os.path.join(os.environ.get("TMPDIR", "/tmp"), f"ministack-{port}.log")+ # Keep a reference to the log file handle — Popen inherits the fd so+ # closing it here would break child process logging. The handle is+ # intentionally kept open for the lifetime of this (short-lived) parent+ # process; the OS reclaims it when the parent exits.+ log_fh = open(log_file, "w")proc = subprocess.Popen([sys.executable, "-m", "uvicorn", "ministack.app:app","--host", "0.0.0.0", "--port", str(port),"--log-level", LOG_LEVEL.lower()],- stdout=open(log_file, "w"),+ stdout=log_fh,stderr=subprocess.STDOUT,start_new_session=True,)diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 13c9de6c..85162b80 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -237,7 +237,9 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"ListSubscriptionsByTopic": "sns","GetSubscriptionAttributes": "sns", "SetSubscriptionAttributes": "sns","PublishBatch": "sns",- "ListTagsForResource": "sns", "TagResource": "sns", "UntagResource": "sns",+ # Note: ListTagsForResource is shared by SNS, RDS, and ElastiCache.+ # Routed via credential scope or host header instead.+ "TagResource": "sns", "UntagResource": "sns","CreatePlatformApplication": "sns", "CreatePlatformEndpoint": "sns",# IAM actions"CreateRole": "iam", "GetRole": "iam", "ListRoles": "iam",@@ -287,7 +289,9 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"SetIdentityFeedbackForwardingEnabled": "ses","CreateConfigurationSet": "ses", "DeleteConfigurationSet": "ses","DescribeConfigurationSet": "ses", "ListConfigurationSets": "ses",- "CreateTemplate": "ses", "GetTemplate": "ses",+ # Note: GetTemplate is shared by SES and CloudFormation.+ # Routed via credential scope or host header instead.+ "CreateTemplate": "ses","DeleteTemplate": "ses", "ListTemplates": "ses", "UpdateTemplate": "ses","SendTemplatedEmail": "ses", "SendBulkTemplatedEmail": "ses",# RDS actions@@ -304,7 +308,6 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"CreateDBSnapshot": "rds", "DeleteDBSnapshot": "rds", "DescribeDBSnapshots": "rds","CreateDBInstanceReadReplica": "rds", "RestoreDBInstanceFromDBSnapshot": "rds","AddTagsToResource": "rds", "RemoveTagsFromResource": "rds",- "ListTagsForResource": "rds",# ElastiCache actions"CreateCacheCluster": "elasticache", "DeleteCacheCluster": "elasticache","DescribeCacheClusters": "elasticache", "ModifyCacheCluster": "elasticache",@@ -389,7 +392,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"DescribeStackEvents": "cloudformation","DescribeStackResource": "cloudformation", "DescribeStackResources": "cloudformation","ListStackResources": "cloudformation",- "GetTemplate": "cloudformation", "GetTemplateSummary": "cloudformation",+ "GetTemplateSummary": "cloudformation","ValidateTemplate": "cloudformation","CreateChangeSet": "cloudformation", "DescribeChangeSet": "cloudformation","ExecuteChangeSet": "cloudformation", "DeleteChangeSet": "cloudformation",diff --git a/ministack/services/athena.py b/ministack/services/athena.pyindex 3904e20b..bbcf41e6 100644--- a/ministack/services/athena.py+++ b/ministack/services/athena.py@@ -245,7 +245,7 @@ def _execute_query(query_id, query, database):len(str(row)) for row in results.get("rows", []))except Exception as e:- logger.error(f"Athena query {query_id} failed: {e}")+ logger.error("Athena query %s failed: %s", query_id, e)execution["Status"]["State"] = "FAILED"execution["Status"]["StateChangeReason"] = str(e)[:2000]execution["_error"] = str(e)diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 7ef06613..fb812251 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -639,6 +639,81 @@ def _eb_rule_delete(physical_id, props):_eb._targets.pop(key, None)+# --- Lambda Permission ---++def _lambda_permission_create(logical_id, props, stack_name):+ func_name = props.get("FunctionName", "")+ # Resolve ARN to function name+ if func_name.startswith("arn:"):+ func_name = func_name.rsplit(":", 1)[-1]+ func = _lambda_svc._functions.get(func_name)+ if func:+ stmt = {+ "Sid": props.get("Id") or logical_id,+ "Effect": "Allow",+ "Principal": props.get("Principal", "*"),+ "Action": props.get("Action", "lambda:InvokeFunction"),+ "Resource": func["config"]["FunctionArn"],+ }+ source_arn = props.get("SourceArn")+ if source_arn:+ stmt["Condition"] = {"ArnLike": {"AWS:SourceArn": source_arn}}+ func["policy"]["Statement"].append(stmt)+ pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"+ return pid, {}+++def _lambda_permission_delete(physical_id, props):+ func_name = props.get("FunctionName", "")+ if func_name.startswith("arn:"):+ func_name = func_name.rsplit(":", 1)[-1]+ func = _lambda_svc._functions.get(func_name)+ if func:+ sid = props.get("Id") or ""+ func["policy"]["Statement"] = [+ s for s in func["policy"]["Statement"] if s.get("Sid") != sid+ ]+++# --- Lambda Version ---++def _lambda_version_create(logical_id, props, stack_name):+ func_name = props.get("FunctionName", "")+ if func_name.startswith("arn:"):+ func_name = func_name.rsplit(":", 1)[-1]+ func = _lambda_svc._functions.get(func_name)+ if func:+ import copy+ ver_num = func["next_version"]+ func["next_version"] = ver_num + 1+ ver_str = str(ver_num)+ ver_config = copy.deepcopy(func["config"])+ ver_config["Version"] = ver_str+ ver_arn = f"{ver_config['FunctionArn']}"+ func["versions"][ver_str] = {+ "config": ver_config,+ "code_zip": func.get("code_zip"),+ }+ return ver_arn, {"Version": ver_str}+ ver_arn = f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{func_name}:1"+ return ver_arn, {"Version": "1"}+++# --- CloudFormation WaitCondition / WaitConditionHandle (no-ops) ---++def _cfn_wait_condition_create(logical_id, props, stack_name):+ """WaitCondition — no-op, return immediately (no real signalling in local emulation)."""+ pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"+ return pid, {"Data": "{}"}+++def _cfn_wait_condition_handle_create(logical_id, props, stack_name):+ """WaitConditionHandle — no-op, return a presigned-style URL."""+ pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"+ url = f"https://cloudformation-waitcondition-{REGION}.s3.amazonaws.com/{pid}"+ return pid, {"Ref": url}++# ===========================================================================# Resource Handler Registry# ===========================================================================@@ -657,4 +732,8 @@ _RESOURCE_HANDLERS = {"AWS::SSM::Parameter": {"create": _ssm_create, "delete": _ssm_delete},"AWS::Logs::LogGroup": {"create": _cwlogs_create, "delete": _cwlogs_delete},"AWS::Events::Rule": {"create": _eb_rule_create, "delete": _eb_rule_delete},+ "AWS::Lambda::Permission": {"create": _lambda_permission_create, "delete": _lambda_permission_delete},+ "AWS::Lambda::Version": {"create": _lambda_version_create},+ "AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create},+ "AWS::CloudFormation::WaitConditionHandle": {"create": _cfn_wait_condition_handle_create},}diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.pyindex fcfac644..3583c214 100644--- a/ministack/services/cloudwatch.py+++ b/ministack/services/cloudwatch.py@@ -244,13 +244,13 @@ async def handle_request(method, path, headers, body, query_params):cbor_data = cbor2.loads(body) or {}except Exception as e:- logger.error(f"CBOR decode error: {e}")+ logger.error("CBOR decode error: %s", e)cbor_data = {}elif is_json:try:cbor_data = json.loads(body) or {}except Exception as e:- logger.error(f"JSON decode error: {e}")+ logger.error("JSON decode error: %s", e)cbor_data = {}else:for k, v in parse_qs(body.decode("utf-8", errors="replace")).items():diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 9d4380d5..63853a13 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -143,14 +143,14 @@ def _ttl_reaper():try:if float(ttl_val) <= now:del sk_map[sk_val]- logger.debug(f"TTL expired item {pk_val}/{sk_val} from {table_name}")+ logger.debug("TTL expired item %s/%s from %s", pk_val, sk_val, table_name)except (ValueError, TypeError):passif not sk_map:del table["items"][pk_val]_update_counts(table)except Exception as exc:- logger.error(f"TTL reaper error: {exc}")+ logger.error("TTL reaper error: %s", exc)threading.Thread(target=_ttl_reaper, daemon=True, name="dynamodb-ttl-reaper").start()diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex f5a758ab..d0bb3d86 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -751,7 +751,7 @@ def _run_task(data):nets = list(self_container.attrs["NetworkSettings"]["Networks"].keys())if nets:ecs_network = nets[0]- logger.debug(f"ECS: detected Ministack network: {ecs_network}")+ logger.debug("ECS: detected Ministack network: %s", ecs_network)except Exception:logger.debug("ECS: could not detect Ministack network, using default")@@ -782,9 +782,9 @@ def _run_task(data):task["_docker_ids"].append(container.id)if i < len(task["containers"]):task["containers"][i]["runtimeId"] = container.id[:12]- logger.info(f"ECS: started container {cdef['image']} for task {task_id[:8]}")+ logger.info("ECS: started container %s for task %s", cdef['image'], task_id[:8])except Exception as e:- logger.warning(f"ECS: Docker run failed for {cdef.get('image')}: {e}")+ logger.warning("ECS: Docker run failed for %s: %s", cdef.get('image'), e)_tasks[task_arn] = taskif req_tags:@@ -816,7 +816,7 @@ def _stop_task(data):c.stop(timeout=5)c.remove(v=True)except Exception as e:- logger.warning(f"ECS: failed to stop container {docker_id}: {e}")+ logger.warning("ECS: failed to stop container %s: %s", docker_id, e)now = _iso()task["lastStatus"] = "STOPPED"@@ -1283,8 +1283,8 @@ def reset():c = docker_client.containers.get(cid)c.stop(timeout=2)c.remove(v=True)- except Exception:- pass+ except Exception as e:+ logger.warning("reset: failed to stop/remove container %s: %s", cid, e)_clusters.clear()_task_defs.clear()_task_def_latest.clear()diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.pyindex f238a0d4..fc593067 100644--- a/ministack/services/elasticache.py+++ b/ministack/services/elasticache.py@@ -246,9 +246,9 @@ def _create_cache_cluster(p):volumes={},)docker_container_id = container.id- logger.info(f"ElastiCache: started {engine} container for {cluster_id} on port {host_port}")+ logger.info("ElastiCache: started %s container for %s on port %s", engine, cluster_id, host_port)except Exception as e:- logger.warning(f"ElastiCache: Docker failed for {cluster_id}: {e}")+ logger.warning("ElastiCache: Docker failed for %s: %s", cluster_id, e)endpoint_host = REDIS_DEFAULT_HOSTendpoint_port = REDIS_DEFAULT_PORT@@ -312,7 +312,7 @@ def _delete_cache_cluster(p):container.stop(timeout=5)container.remove()except Exception as e:- logger.warning(f"ElastiCache: failed to remove container for {cluster_id}: {e}")+ logger.warning("ElastiCache: failed to remove container for %s: %s", cluster_id, e)cluster["CacheClusterStatus"] = "deleting"del _clusters[cluster_id]@@ -1335,13 +1335,15 @@ def reset():c = docker_client.containers.get(cid)c.stop(timeout=2)c.remove(v=True)- except Exception:- pass+ except Exception as e:+ logger.warning("reset: failed to stop/remove container %s: %s", cid, e)_clusters.clear()_replication_groups.clear()_subnet_groups.clear()_param_groups.clear()+ _param_group_params.clear()_snapshots.clear()_users.clear()_user_groups.clear()_events.clear()+ _port_counter[0] = BASE_PORTdiff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.pyindex 5691961f..ac547bd2 100644--- a/ministack/services/eventbridge.py+++ b/ministack/services/eventbridge.py@@ -401,7 +401,7 @@ def _put_events(data):}_events_log.append(event_record)results.append({"EventId": event_id})- logger.debug(f"EventBridge event: {entry.get('Source')} / {entry.get('DetailType')}")+ logger.debug("EventBridge event: %s / %s", entry.get('Source'), entry.get('DetailType'))_dispatch_event(event_record)@@ -577,9 +577,9 @@ def _invoke_target(target, event, rule):elif ":sns:" in arn:_dispatch_to_sns(arn, event_payload)else:- logger.warning(f"EventBridge: unsupported target type for ARN {arn}")+ logger.warning("EventBridge: unsupported target type for ARN %s", arn)except Exception as e:- logger.error(f"EventBridge target dispatch error for {arn}: {e}")+ logger.error("EventBridge target dispatch error for %s: %s", arn, e)def _apply_input_transformer(transformer, event):@@ -636,12 +636,12 @@ def _dispatch_to_lambda(arn, payload):func = lambda_svc._functions.get(func_name)if not func:- logger.warning(f"EventBridge → Lambda: function {func_name} not found")+ logger.warning("EventBridge → Lambda: function %s not found", func_name)returnthreading.Thread(target=lambda_svc._execute_function, args=(func, event), daemon=True).start()- logger.info(f"EventBridge → Lambda {func_name}: dispatched")+ logger.info("EventBridge → Lambda %s: dispatched", func_name)def _dispatch_to_sqs(arn, payload):@@ -651,7 +651,7 @@ def _dispatch_to_sqs(arn, payload):queue_url = _sqs._queue_url(queue_name)queue = _sqs._queues.get(queue_url)if not queue:- logger.warning(f"EventBridge → SQS: queue {queue_name} not found")+ logger.warning("EventBridge → SQS: queue %s not found", queue_name)returnmsg_id = new_uuid()@@ -672,7 +672,7 @@ def _dispatch_to_sqs(arn, payload):"SentTimestamp": str(int(now * 1000)),},})- logger.info(f"EventBridge → SQS {queue_name}")+ logger.info("EventBridge → SQS %s", queue_name)def _dispatch_to_sns(arn, payload):@@ -680,7 +680,7 @@ def _dispatch_to_sns(arn, payload):topic = _sns._topics.get(arn)if not topic:- logger.warning(f"EventBridge → SNS: topic {arn} not found")+ logger.warning("EventBridge → SNS: topic %s not found", arn)returnmsg_id = new_uuid()@@ -691,7 +691,7 @@ def _dispatch_to_sns(arn, payload):"timestamp": time.time(),})_sns._fanout(arn, msg_id, payload, "EventBridge Notification")- logger.info(f"EventBridge → SNS {arn}")+ logger.info("EventBridge → SNS %s", arn)# ---------------------------------------------------------------------------diff --git a/ministack/services/glue.py b/ministack/services/glue.pyindex ac34aec9..f0879add 100644--- a/ministack/services/glue.py+++ b/ministack/services/glue.py@@ -533,13 +533,13 @@ def _start_crawler(data):"StartTime": start_time,"EndTime": time.time(),}- logger.info(f"Glue: Crawler {name} finished after {CRAWLER_RUN_SECONDS}s")+ logger.info("Glue: Crawler %s finished after %ss", name, CRAWLER_RUN_SECONDS)timer = threading.Timer(CRAWLER_RUN_SECONDS, _finish_crawl)timer.daemon = Truetimer.start()- logger.info(f"Glue: Crawler {name} started (will run for {CRAWLER_RUN_SECONDS}s)")+ logger.info("Glue: Crawler %s started (will run for %ss)", name, CRAWLER_RUN_SECONDS)return json_response({})diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex ae0f06aa..28e87166 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -1335,7 +1335,7 @@ def _execute_function_local(func: dict, event: dict) -> dict:"log": _log,}except Exception as e:- logger.error(f"Lambda execution error: {e}")+ logger.error("Lambda execution error: %s", e)return {"body": {"errorMessage": str(e), "errorType": type(e).__name__},"error": True,diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 7a8e7fd1..f47972d7 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -197,9 +197,9 @@ def _create_db_instance(p):"/var/lib/mysql": "rw,noexec,nosuid,size=256m"},)docker_container_id = container.id- logger.info(f"RDS: started {engine} container for {db_id} on port {host_port}")+ logger.info("RDS: started %s container for %s on port %s", engine, db_id, host_port)except Exception as e:- logger.warning(f"RDS: Docker failed for {db_id}: {e}")+ logger.warning("RDS: Docker failed for %s: %s", db_id, e)cluster_id = _p(p, "DBClusterIdentifier")param_group_name = _p(p, "DBParameterGroupName") or f"default.{engine}{engine_version.split('.')[0]}"@@ -327,9 +327,9 @@ def _delete_db_instance(p):c = docker_client.containers.get(instance["_docker_container_id"])c.stop(timeout=5)c.remove(v=True)- logger.info(f"RDS: removed container for {db_id}")+ logger.info("RDS: removed container for %s", db_id)except Exception as e:- logger.warning(f"RDS: failed to remove container for {db_id}: {e}")+ logger.warning("RDS: failed to remove container for %s: %s", db_id, e)skip_snapshot = _p(p, "SkipFinalSnapshot") == "true"final_snap_id = _p(p, "FinalDBSnapshotIdentifier")@@ -2041,8 +2041,8 @@ def reset():c = docker_client.containers.get(cid)c.stop(timeout=2)c.remove(v=True)- except Exception:- pass+ except Exception as e:+ logger.warning("reset: failed to stop/remove container %s: %s", cid, e)_instances.clear()_clusters.clear()_subnet_groups.clear()diff --git a/ministack/services/ses.py b/ministack/services/ses.pyindex 4071773a..f3b09317 100644--- a/ministack/services/ses.py+++ b/ministack/services/ses.py@@ -132,7 +132,7 @@ def _send_email(params):if config_set:record["ConfigurationSetName"] = config_set_sent_emails.append(record)- logger.info(f"SES SendEmail: {source} -> {to_addrs} | {subject}")+ logger.info("SES SendEmail: %s -> %s | %s", source, to_addrs, subject)return _xml(200, "SendEmailResponse",f"<SendEmailResult><MessageId>{msg_id}</MessageId></SendEmailResult>")@@ -153,7 +153,7 @@ def _send_raw_email(params):"Type": "SendRawEmail",}_sent_emails.append(record)- logger.info(f"SES SendRawEmail: {msg_id}")+ logger.info("SES SendRawEmail: %s", msg_id)return _xml(200, "SendRawEmailResponse",f"<SendRawEmailResult><MessageId>{msg_id}</MessageId></SendRawEmailResult>")@@ -191,7 +191,7 @@ def _send_templated_email(params):if config_set:record["ConfigurationSetName"] = config_set_sent_emails.append(record)- logger.info(f"SES SendTemplatedEmail: {source} -> {to_addrs} | template={template_name}")+ logger.info("SES SendTemplatedEmail: %s -> %s | template=%s", source, to_addrs, template_name)return _xml(200, "SendTemplatedEmailResponse",f"<SendTemplatedEmailResult><MessageId>{msg_id}</MessageId></SendTemplatedEmailResult>")@@ -238,8 +238,8 @@ def _send_bulk_templated_email(params):f"<member><Status>Success</Status>"f"<MessageId>{msg_id}</MessageId></member>")- logger.info(f"SES SendBulkTemplatedEmail: {source} | template={template_name} | "- f"{len(destinations)} destinations")+ logger.info("SES SendBulkTemplatedEmail: %s | template=%s | %s destinations",+ source, template_name, len(destinations))return _xml(200, "SendBulkTemplatedEmailResponse",f"<SendBulkTemplatedEmailResult>"f"<Status>{''.join(statuses)}</Status>"@@ -644,7 +644,7 @@ def _v2_send_email(data):if config_set:record["ConfigurationSetName"] = config_set_sent_emails.append(record)- logger.info(f"SES v2 SendEmail: {from_addr} -> {to_addrs}")+ logger.info("SES v2 SendEmail: %s -> %s", from_addr, to_addrs)return _json_response(200, {"MessageId": msg_id})@@ -681,8 +681,8 @@ def _v2_send_bulk_email(data):_sent_emails.append(record)results.append({"Status": "SUCCESS", "MessageId": msg_id})- logger.info(f"SES v2 SendBulkEmail: {from_addr} | template={template_name} | "- f"{len(entries)} entries")+ logger.info("SES v2 SendBulkEmail: %s | template=%s | %s entries",+ from_addr, template_name, len(entries))return _json_response(200, {"BulkEmailEntryResults": results})diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex 43e8313c..a0f6261f 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -419,7 +419,7 @@ def _publish(params):if phone_number and not topic_arn:msg_id = new_uuid()- logger.info(f"SNS SMS stub to {phone_number}: {message[:80]}")+ logger.info("SNS SMS stub to %s: %s", phone_number, message[:80])return _xml(200, "PublishResponse",f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")@@ -443,7 +443,7 @@ def _publish(params):})_fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs)- logger.info(f"SNS publish to {topic_arn}: {message[:100]}")+ logger.info("SNS publish to %s: %s", topic_arn, message[:100])return _xml(200, "PublishResponse",f"<PublishResult><MessageId>{msg_id}</MessageId></PublishResult>")@@ -545,11 +545,11 @@ def _fanout(topic_arn: str, msg_id: str, message: str, subject: str,elif protocol == "lambda":_deliver_to_lambda(endpoint, envelope, topic_arn, sub["arn"], msg_id, effective_message, message_attributes or {})elif protocol == "email" or protocol == "email-json":- logger.info(f"SNS fanout → email {endpoint} (stub)")+ logger.info("SNS fanout → email %s (stub)", endpoint)elif protocol == "sms":- logger.info(f"SNS fanout → SMS {endpoint} (stub)")+ logger.info("SNS fanout → SMS %s (stub)", endpoint)elif protocol == "application":- logger.info(f"SNS fanout → application {endpoint} (stub)")+ logger.info("SNS fanout → application %s (stub)", endpoint)def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str):@@ -557,7 +557,7 @@ def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str):queue_url = _sqs._queue_url(queue_name)queue = _sqs._queues.get(queue_url)if not queue:- logger.warning(f"SNS fanout: SQS queue {queue_name} not found")+ logger.warning("SNS fanout: SQS queue %s not found", queue_name)returnbody = raw_message if raw else envelope@@ -573,7 +573,7 @@ def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str):}_sqs._ensure_msg_fields(msg)queue["messages"].append(msg)- logger.info(f"SNS fanout → SQS {queue_name}")+ logger.info("SNS fanout → SQS %s", queue_name)def _deliver_to_lambda(endpoint: str, envelope: str, topic_arn: str, sub_arn: str,@@ -583,7 +583,7 @@ def _deliver_to_lambda(endpoint: str, envelope: str, topic_arn: str, sub_arn: stfunc_name = endpoint.split(":")[-1]func = _lambda_svc._functions.get(func_name)if not func:- logger.warning(f"SNS fanout: Lambda function {func_name} not found")+ logger.warning("SNS fanout: Lambda function %s not found", func_name)returnevent = {"Records": [@@ -597,9 +597,9 @@ def _deliver_to_lambda(endpoint: str, envelope: str, topic_arn: str, sub_arn: st}try:_lambda_svc._execute_function(func, event)- logger.info(f"SNS fanout → Lambda {func_name}")+ logger.info("SNS fanout → Lambda %s", func_name)except Exception as exc:- logger.error(f"SNS fanout → Lambda {func_name} failed: {exc}")+ logger.error("SNS fanout → Lambda %s failed: %s", func_name, exc)async def _deliver_to_http(endpoint: str, payload: str):@@ -615,11 +615,11 @@ async def _deliver_to_http(endpoint: str, payload: str):"x-amz-sns-message-type": "Notification",},) as resp:- logger.info(f"SNS HTTP delivery to {endpoint}: {resp.status}")+ logger.info("SNS HTTP delivery to %s: %s", endpoint, resp.status)except ImportError:logger.warning("aiohttp not installed — HTTP delivery skipped")except Exception as exc:- logger.warning(f"SNS HTTP delivery to {endpoint} failed: {exc}")+ logger.warning("SNS HTTP delivery to %s failed: %s", endpoint, exc)async def _send_subscription_confirmation(topic_arn: str, sub: dict):@@ -650,11 +650,11 @@ async def _send_subscription_confirmation(topic_arn: str, sub: dict):"x-amz-sns-message-type": "SubscriptionConfirmation",},) as resp:- logger.info(f"SNS SubscriptionConfirmation sent to {endpoint}: {resp.status}")+ logger.info("SNS SubscriptionConfirmation sent to %s: %s", endpoint, resp.status)except ImportError:- logger.info(f"aiohttp not installed — subscription confirmation for {endpoint} skipped")+ logger.info("aiohttp not installed — subscription confirmation for %s skipped", endpoint)except Exception as exc:- logger.warning(f"SNS SubscriptionConfirmation to {endpoint} failed: {exc}")+ logger.warning("SNS SubscriptionConfirmation to %s failed: %s", endpoint, exc)# ---------------------------------------------------------------------------diff --git a/ministack/services/ssm.py b/ministack/services/ssm.pyindex f28c531d..204ba175 100644--- a/ministack/services/ssm.py+++ b/ministack/services/ssm.py@@ -166,7 +166,7 @@ def _put_parameter(data):_parameter_history[name] = []_parameter_history[name].append(history_entry)- logger.info(f"SSM PutParameter: {name} v{version} type={param_type}")+ logger.info("SSM PutParameter: %s v%s type=%s", name, version, param_type)return json_response({"Version": version, "Tier": record["Tier"]})diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 9224277b..f139356f 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -293,7 +293,7 @@ def _start_execution(data):threading.Thread(target=_run_execution, args=(exec_arn,), daemon=True).start()- logger.info(f"Step Functions execution started: {exec_arn}")+ logger.info("Step Functions execution started: %s", exec_arn)return json_response({"executionArn": exec_arn, "startDate": start_date})@@ -973,7 +973,7 @@ def _run_execution(exec_arn):except _ExecutionError as err:_fail_execution(execution, err.error, err.cause)except Exception as exc:- logger.exception(f"Unexpected error in execution {exec_arn}")+ logger.exception("Unexpected error in execution %s", exec_arn)_fail_execution(execution, "States.Runtime", str(exc))diff --git a/pyproject.toml b/pyproject.tomlindex 81fa0a5b..169d6f2b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.1.29"+version = "1.1.30"description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"readme = "README.md"license = { file = "LICENSE" }diff --git a/tests/test_services.py b/tests/test_services.pyindex 98afb7b1..0809e8bd 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -16646,6 +16646,130 @@ def test_cfn_explicit_name_not_overridden(cfn, s3):_wait_stack(cfn, "cfn-explicit-name")+def test_cfn_s3_bucket_policy(cfn, s3):+ """AWS::S3::BucketPolicy provisions and deletes bucket policies."""+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Bucket": {+ "Type": "AWS::S3::Bucket",+ "Properties": {"BucketName": "cfn-policy-test"},+ },+ "Policy": {+ "Type": "AWS::S3::BucketPolicy",+ "Properties": {+ "Bucket": "cfn-policy-test",+ "PolicyDocument": {+ "Version": "2012-10-17",+ "Statement": [{"Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::cfn-policy-test/*"}],+ },+ },+ },+ },+ }+ cfn.create_stack(StackName="cfn-s3-policy", TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, "cfn-s3-policy")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ policy = s3.get_bucket_policy(Bucket="cfn-policy-test")+ assert "s3:GetObject" in policy["Policy"]+ cfn.delete_stack(StackName="cfn-s3-policy")+ _wait_stack(cfn, "cfn-s3-policy")+++def test_cfn_lambda_permission(cfn, lam):+ """AWS::Lambda::Permission provisions invoke permissions."""+ code = "def handler(e,c): return {}"+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName="cfn-perm-fn", Runtime="python3.11",+ Role="arn:aws:iam::000000000000:role/r", Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Perm": {+ "Type": "AWS::Lambda::Permission",+ "Properties": {+ "FunctionName": "cfn-perm-fn",+ "Action": "lambda:InvokeFunction",+ "Principal": "s3.amazonaws.com",+ "SourceArn": "arn:aws:s3:::my-bucket",+ },+ },+ },+ }+ cfn.create_stack(StackName="cfn-lambda-perm", TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, "cfn-lambda-perm")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ cfn.delete_stack(StackName="cfn-lambda-perm")+ _wait_stack(cfn, "cfn-lambda-perm")+ lam.delete_function(FunctionName="cfn-perm-fn")+++def test_cfn_lambda_version(cfn, lam):+ """AWS::Lambda::Version creates a published version."""+ code = "def handler(e,c): return {'v': 1}"+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName="cfn-ver-fn", Runtime="python3.11",+ Role="arn:aws:iam::000000000000:role/r", Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Ver": {+ "Type": "AWS::Lambda::Version",+ "Properties": {+ "FunctionName": "cfn-ver-fn",+ },+ },+ },+ }+ cfn.create_stack(StackName="cfn-lambda-ver", TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, "cfn-lambda-ver")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ versions = lam.list_versions_by_function(FunctionName="cfn-ver-fn")["Versions"]+ assert len([v for v in versions if v["Version"] != "$LATEST"]) >= 1+ cfn.delete_stack(StackName="cfn-lambda-ver")+ _wait_stack(cfn, "cfn-lambda-ver")+ lam.delete_function(FunctionName="cfn-ver-fn")+++def test_cfn_wait_condition(cfn):+ """AWS::CloudFormation::WaitCondition and WaitConditionHandle are no-ops."""+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Handle": {"Type": "AWS::CloudFormation::WaitConditionHandle"},+ "Wait": {+ "Type": "AWS::CloudFormation::WaitCondition",+ "Properties": {"Handle": {"Ref": "Handle"}, "Timeout": "10"},+ },+ },+ }+ cfn.create_stack(StackName="cfn-wait", TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, "cfn-wait")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ cfn.delete_stack(StackName="cfn-wait")+ _wait_stack(cfn, "cfn-wait")+++def test_elasticache_reset_clears_param_groups():+ """ElastiCache reset clears _param_group_params and resets port counter."""+ from ministack.services import elasticache as _ec+ _ec._param_group_params["test-group"] = {"param1": "val1"}+ _ec._port_counter[0] = 99999+ _ec.reset()+ assert not _ec._param_group_params+ assert _ec._port_counter[0] == _ec.BASE_PORT++# ═══════════════════════════════════════════════════════════════════════════════# KMS# ═══════════════════════════════════════════════════════════════════════════════