Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat: add RDS Data API service (ExecuteStatement, BeginTransaction, CommitTransaction, RollbackTransaction, BatchExecuteStatement) (#193)
Jay Janssen4f1883eb660a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e10f8061..d334ce97 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [Unreleased]++### Added+- **RDS Data API service** — `ExecuteStatement`, `BatchExecuteStatement`, `BeginTransaction`, `CommitTransaction`, `RollbackTransaction`. Routes SQL to the real database containers MiniStack spins up for RDS instances. Supports both MySQL and PostgreSQL engines.++---+## [1.1.52] — 2026-04-08### Fixeddiff --git a/README.md b/README.mdindex f44046f0..598fb75c 100644--- a/README.md+++ b/README.md@@ -383,6 +383,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if| **ECR** | CreateRepository, DescribeRepositories, DeleteRepository, ListImages, DescribeImages, PutImage, BatchGetImage, BatchDeleteImage, GetAuthorizationToken, GetRepositoryPolicy, SetRepositoryPolicy, DeleteRepositoryPolicy, PutLifecyclePolicy, GetLifecyclePolicy, DeleteLifecyclePolicy, ListTagsForResource, TagResource, UntagResource, PutImageTagMutability, PutImageScanningConfiguration, DescribeRegistry, GetDownloadUrlForLayer, BatchCheckLayerAvailability, InitiateLayerUpload, UploadLayerPart, CompleteLayerUpload | In-memory image registry; Docker V2 manifest support; authorization token generation; lifecycle policies; tag mutability; Pro-only on LocalStack — free here || **AppSync** | CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis, UpdateGraphQLApi, DeleteGraphQLApi, CreateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource | Control plane + data plane; GraphQL queries/mutations execute against DynamoDB resolvers (create/get/list/update/delete); Lambda resolvers supported; designed for Amplify/CDK CRUD patterns — not a full GraphQL spec engine || **Cloud Map** | CreateHttpNamespace, CreatePrivateDnsNamespace, CreatePublicDnsNamespace, GetNamespace, ListNamespaces, DeleteNamespace, UpdateHttpNamespace, UpdatePrivateDnsNamespace, UpdatePublicDnsNamespace, CreateService, GetService, ListServices, DeleteService, UpdateService, RegisterInstance, DeregisterInstance, DiscoverInstances, DiscoverInstancesRevision, ListInstances, GetInstancesHealthStatus, UpdateInstanceCustomHealthStatus, GetServiceAttributes, UpdateServiceAttributes, DeleteServiceAttributes, GetOperation, ListOperations, TagResource, UntagResource, ListTagsForResource | DNS namespaces create Route53 hosted zones; operation tracking; Terraform `aws_service_discovery_*` compatible |+| **RDS Data API** | ExecuteStatement, BatchExecuteStatement, BeginTransaction, CommitTransaction, RollbackTransaction | Routes SQL to real Docker-backed RDS database containers; supports MySQL (pymysql) and PostgreSQL (psycopg2); REST paths (`/Execute`, `/BeginTransaction`, etc.) || **S3 Files** | CreateFileSystem, GetFileSystem, ListFileSystems, DeleteFileSystem, CreateMountTarget, GetMountTarget, ListMountTargets, UpdateMountTarget, DeleteMountTarget, CreateAccessPoint, GetAccessPoint, ListAccessPoints, DeleteAccessPoint, GetFileSystemPolicy, PutFileSystemPolicy, DeleteFileSystemPolicy, GetSynchronizationConfiguration, PutSynchronizationConfiguration, TagResource, UntagResource, ListTagsForResource | 21 operations; control plane for the new S3 Files service (launched April 2026); file systems, mount targets, access points, policies |---diff --git a/ministack/app.py b/ministack/app.pyindex 7b1e1c6f..0f702072 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -64,6 +64,7 @@ from ministack.services import (kms,lambda_svc,rds,+ rds_data,route53,s3,secretsmanager,@@ -145,6 +146,7 @@ SERVICE_NAME_ALIASES = {"elbv2": "elasticloadbalancing","elb": "elasticloadbalancing","ecr": "ecr",+ "rds-data": "rds-data",}@@ -182,7 +184,7 @@ BANNER = r"""SSM, EventBridge, Kinesis, CloudWatch, SES, SES v2, ACM, WAF v2, Step Functions,ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation, KMS, ECR, CloudFront,- AppSync, Cloud Map, S3 Files+ AppSync, Cloud Map, S3 Files, RDS Data API"""@@ -374,6 +376,12 @@ async def app(scope, receive, send):}, b"{}")return+ # RDS Data API — /Execute, /BeginTransaction, /CommitTransaction, /RollbackTransaction, /BatchExecute+ if path in ("/Execute", "/BeginTransaction", "/CommitTransaction", "/RollbackTransaction", "/BatchExecute"):+ status, resp_headers, resp_body = await rds_data.handle_request(method, path, headers, body, query_params)+ await _send_response(send, status, resp_headers, resp_body)+ return+# SES v2 REST API — /v2/email/...if path.startswith("/v2/email"):status, resp_headers, resp_body = await ses_v2.handle_request(method, path, headers, body, query_params)@@ -745,6 +753,7 @@ def _reset_all_state():(ecr, ecr.reset),(appsync, appsync.reset),(servicediscovery, servicediscovery.reset),+ (rds_data, rds_data.reset),(s3files, s3files.reset),]:try:diff --git a/ministack/core/router.py b/ministack/core/router.pyindex bcf0f051..4dbda57c 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -177,6 +177,10 @@ SERVICE_PATTERNS = {"credential_scope": "s3files","path_prefixes": ["/file-systems", "/mount-targets", "/access-points"],},+ "rds-data": {+ "host_patterns": [r"rds-data\."],+ "credential_scope": "rds-data",+ },}@@ -231,6 +235,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"appsync": "appsync","servicediscovery": "servicediscovery","s3files": "s3files",+ "rds-data": "rds-data",}if svc_name in scope_map:return scope_map[svc_name]diff --git a/ministack/services/rds_data.py b/ministack/services/rds_data.pynew file mode 100644index 00000000..60b0a7be--- /dev/null+++ b/ministack/services/rds_data.py@@ -0,0 +1,390 @@+"""+RDS Data API Service Emulator.+REST-style JSON API (POST /Execute, /BeginTransaction, etc.)+Routes SQL to real database containers managed by the RDS service emulator.+"""++import json+import logging+import os+import uuid++from ministack.core.responses import error_response_json, json_response++logger = logging.getLogger("rds-data")++ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")++# Active transactions: txn_id -> {conn, engine, resourceArn, database}+_transactions: dict = {}+++def _error(code, message, status=400):+ return error_response_json(code, message, status)+++def _resolve_cluster(resource_arn):+ """Find RDS cluster and a member instance from a resourceArn."""+ from ministack.services import rds++ # Parse ARN: arn:aws:rds:REGION:ACCOUNT:cluster:IDENTIFIER+ parts = resource_arn.split(":")+ if len(parts) >= 7 and parts[5] == "cluster":+ cluster_id = parts[6]+ elif len(parts) >= 7 and parts[5] == "db":+ # Instance ARN: arn:aws:rds:REGION:ACCOUNT:db:IDENTIFIER+ instance_id = parts[6]+ instance = rds._instances.get(instance_id)+ if instance:+ return instance, instance.get("Engine", "postgres")+ return None, None+ else:+ return None, None++ cluster = rds._clusters.get(cluster_id)+ if not cluster:+ return None, None++ engine = cluster.get("Engine", "postgres")++ # Find an instance belonging to this cluster+ for inst in rds._instances.values():+ if inst.get("DBClusterIdentifier") == cluster_id:+ return inst, engine++ # No instance found — return cluster info but no connectable instance+ return cluster, engine+++def _get_secret_password(secret_arn):+ """Extract password from a Secrets Manager secret."""+ from ministack.services import secretsmanager++ for _name, secret in secretsmanager._secrets.items():+ if secret.get("ARN") == secret_arn or _name == secret_arn:+ # Find the AWSCURRENT version+ for _vid, ver in secret.get("Versions", {}).items():+ if "AWSCURRENT" in ver.get("Stages", []):+ secret_string = ver.get("SecretString")+ if secret_string:+ try:+ parsed = json.loads(secret_string)+ return parsed.get("password", secret_string)+ except (json.JSONDecodeError, TypeError):+ return secret_string+ # Fallback to any version+ for _vid, ver in secret.get("Versions", {}).items():+ secret_string = ver.get("SecretString")+ if secret_string:+ try:+ parsed = json.loads(secret_string)+ return parsed.get("password", secret_string)+ except (json.JSONDecodeError, TypeError):+ return secret_string+ return None+++def _connect(instance, engine, database=None, password=None):+ """Create a database connection to the real container."""+ host = instance.get("Endpoint", {}).get("Address", "localhost")+ port = instance.get("Endpoint", {}).get("Port", 5432)+ user = instance.get("MasterUsername", "admin")+ db = database or instance.get("DBName", "")+ pw = password or "password"++ if "mysql" in engine or "aurora-mysql" in engine or "mariadb" in engine:+ try:+ import pymysql+ except ImportError:+ raise ImportError(+ "pymysql is required for MySQL/Aurora MySQL rds-data support. "+ "Install with: pip install pymysql"+ )+ return pymysql.connect(+ host=host, port=int(port), user=user,+ password=pw, database=db or None, autocommit=True,+ )+ else:+ try:+ import psycopg2+ except ImportError:+ raise ImportError(+ "psycopg2 is required for PostgreSQL/Aurora PostgreSQL rds-data support. "+ "Install with: pip install psycopg2-binary"+ )+ return psycopg2.connect(+ host=host, port=int(port), user=user,+ password=pw, dbname=db or "postgres",+ )+++def _field_value(val, type_name=None):+ """Convert a Python value to an RDS Data API Field object."""+ if val is None:+ return {"isNull": True}+ if isinstance(val, bool):+ return {"booleanValue": val}+ if isinstance(val, int):+ return {"longValue": val}+ if isinstance(val, float):+ return {"doubleValue": val}+ if isinstance(val, bytes):+ import base64+ return {"blobValue": base64.b64encode(val).decode()}+ return {"stringValue": str(val)}+++def _column_metadata(description, engine):+ """Convert DB-API cursor.description to RDS Data API columnMetadata."""+ if not description:+ return []+ metadata = []+ for col in description:+ name = col[0]+ type_code = col[1]+ metadata.append({+ "arrayBaseColumnType": 0,+ "isAutoIncrement": False,+ "isCaseSensitive": True,+ "isCurrency": False,+ "isSigned": True,+ "label": name,+ "name": name,+ "nullable": 1,+ "precision": col[4] if col[4] else 0,+ "scale": col[5] if col[5] else 0,+ "schemaName": "",+ "tableName": "",+ "type": type_code if isinstance(type_code, int) else 12,+ "typeName": "VARCHAR",+ })+ return metadata+++async def handle_request(method, path, headers, body, query_params):+ """Route RDS Data API requests by path."""+ try:+ data = json.loads(body) if body else {}+ except (json.JSONDecodeError, TypeError):+ return _error("BadRequestException", "Invalid JSON in request body")++ handlers = {+ "/Execute": _execute_statement,+ "/BeginTransaction": _begin_transaction,+ "/CommitTransaction": _commit_transaction,+ "/RollbackTransaction": _rollback_transaction,+ "/BatchExecute": _batch_execute_statement,+ }++ handler = handlers.get(path)+ if not handler:+ return _error("BadRequestException", f"Unknown RDS Data API path: {path}")+ return handler(data)+++def _execute_statement(data):+ resource_arn = data.get("resourceArn")+ secret_arn = data.get("secretArn")+ sql = data.get("sql")+ database = data.get("database")+ txn_id = data.get("transactionId")+ include_metadata = data.get("includeResultMetadata", False)++ if not resource_arn:+ return _error("BadRequestException", "resourceArn is required")+ if not secret_arn:+ return _error("BadRequestException", "secretArn is required")+ if not sql:+ return _error("BadRequestException", "sql is required")++ instance, engine = _resolve_cluster(resource_arn)+ if not instance:+ return _error("BadRequestException",+ f"Database cluster not found for ARN: {resource_arn}")++ # Check if instance has a real endpoint (Docker container running)+ endpoint = instance.get("Endpoint", {})+ if not endpoint.get("Port"):+ return _error("BadRequestException",+ "No database endpoint available. "+ "RDS Data API requires Docker-backed RDS instances.")++ password = _get_secret_password(secret_arn)++ try:+ if txn_id and txn_id in _transactions:+ conn = _transactions[txn_id]["conn"]+ cursor = conn.cursor()+ else:+ conn = _connect(instance, engine, database, password)+ cursor = conn.cursor()++ cursor.execute(sql)++ response = {+ "numberOfRecordsUpdated": cursor.rowcount if cursor.rowcount >= 0 else 0,+ "generatedFields": [],+ }++ if cursor.description:+ rows = cursor.fetchall()+ records = []+ for row in rows:+ record = [_field_value(val) for val in row]+ records.append(record)+ response["records"] = records++ if include_metadata:+ response["columnMetadata"] = _column_metadata(+ cursor.description, engine)+ else:+ response["records"] = []++ cursor.close()+ if not txn_id or txn_id not in _transactions:+ conn.close()++ return json_response(response)++ except ImportError as e:+ return _error("BadRequestException", str(e))+ except Exception as e:+ return _error("BadRequestException", f"Database error: {e}")+++def _begin_transaction(data):+ resource_arn = data.get("resourceArn")+ secret_arn = data.get("secretArn")+ database = data.get("database")++ if not resource_arn:+ return _error("BadRequestException", "resourceArn is required")+ if not secret_arn:+ return _error("BadRequestException", "secretArn is required")++ instance, engine = _resolve_cluster(resource_arn)+ if not instance:+ return _error("BadRequestException",+ f"Database cluster not found for ARN: {resource_arn}")++ password = _get_secret_password(secret_arn)++ try:+ conn = _connect(instance, engine, database, password)+ if "mysql" in engine or "aurora-mysql" in engine:+ conn.autocommit(False)+ else:+ conn.autocommit = False+ except ImportError as e:+ return _error("BadRequestException", str(e))+ except Exception as e:+ return _error("BadRequestException", f"Database connection error: {e}")++ txn_id = str(uuid.uuid4())+ _transactions[txn_id] = {+ "conn": conn,+ "engine": engine,+ "resourceArn": resource_arn,+ "database": database,+ }++ return json_response({"transactionId": txn_id})+++def _commit_transaction(data):+ txn_id = data.get("transactionId")+ if not txn_id:+ return _error("BadRequestException", "transactionId is required")++ txn = _transactions.pop(txn_id, None)+ if not txn:+ return _error("NotFoundException",+ f"Transaction {txn_id} not found", 404)++ try:+ txn["conn"].commit()+ txn["conn"].close()+ except Exception as e:+ return _error("BadRequestException", f"Commit failed: {e}")++ return json_response({"transactionStatus": "Transaction Committed"})+++def _rollback_transaction(data):+ txn_id = data.get("transactionId")+ if not txn_id:+ return _error("BadRequestException", "transactionId is required")++ txn = _transactions.pop(txn_id, None)+ if not txn:+ return _error("NotFoundException",+ f"Transaction {txn_id} not found", 404)++ try:+ txn["conn"].rollback()+ txn["conn"].close()+ except Exception as e:+ return _error("BadRequestException", f"Rollback failed: {e}")++ return json_response({"transactionStatus": "Transaction Rolled Back"})+++def _batch_execute_statement(data):+ resource_arn = data.get("resourceArn")+ secret_arn = data.get("secretArn")+ sql = data.get("sql")+ parameter_sets = data.get("parameterSets", [])+ database = data.get("database")+ txn_id = data.get("transactionId")++ if not resource_arn:+ return _error("BadRequestException", "resourceArn is required")+ if not secret_arn:+ return _error("BadRequestException", "secretArn is required")+ if not sql:+ return _error("BadRequestException", "sql is required")++ instance, engine = _resolve_cluster(resource_arn)+ if not instance:+ return _error("BadRequestException",+ f"Database cluster not found for ARN: {resource_arn}")++ password = _get_secret_password(secret_arn)++ try:+ if txn_id and txn_id in _transactions:+ conn = _transactions[txn_id]["conn"]+ else:+ conn = _connect(instance, engine, database, password)++ cursor = conn.cursor()+ update_results = []++ if not parameter_sets:+ cursor.execute(sql)+ update_results.append({"generatedFields": []})+ else:+ for _params in parameter_sets:+ cursor.execute(sql)+ update_results.append({"generatedFields": []})++ cursor.close()+ if not txn_id or txn_id not in _transactions:+ conn.close()++ return json_response({"updateResults": update_results})++ except ImportError as e:+ return _error("BadRequestException", str(e))+ except Exception as e:+ return _error("BadRequestException", f"Database error: {e}")+++def reset():+ for txn in _transactions.values():+ try:+ txn["conn"].close()+ except Exception:+ pass+ _transactions.clear()diff --git a/tests/conftest.py b/tests/conftest.pyindex 79871de5..f4c0e2a4 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -220,6 +220,10 @@ def sfn_sync():def cloudfront():return make_client("cloudfront")[email protected](scope="session")+def rds_data():+ return make_client("rds-data")+@pytest.fixture(scope="session")def sd():"""SD client for DiscoverInstances — forces same endpoint (boto3 normally prefixes data-)."""diff --git a/tests/test_rds_data.py b/tests/test_rds_data.pynew file mode 100644index 00000000..6195c09e--- /dev/null+++ b/tests/test_rds_data.py@@ -0,0 +1,195 @@+"""+Tests for RDS Data API service emulator.+Since no real DB containers are available in CI, these tests focus on:+- API routing (requests reach the handler, not 404)+- Parameter validation (missing resourceArn, missing sql, etc.)+- Transaction lifecycle error paths+- Invalid resource ARN handling+"""++import json+import urllib.request+import os++import pytest+from botocore.exceptions import ClientError++ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+REGION = "us-east-1"+ACCOUNT_ID = "000000000000"++FAKE_CLUSTER_ARN = f"arn:aws:rds:{REGION}:{ACCOUNT_ID}:cluster:nonexistent-cluster"+FAKE_SECRET_ARN = f"arn:aws:secretsmanager:{REGION}:{ACCOUNT_ID}:secret:nonexistent-secret"+++def _raw_post(path, body):+ """Send a raw POST to the MiniStack endpoint (bypassing boto3 since+ rds-data uses REST paths like /Execute)."""+ data = json.dumps(body).encode()+ req = urllib.request.Request(+ f"{ENDPOINT}{path}",+ data=data,+ headers={"Content-Type": "application/json"},+ method="POST",+ )+ try:+ resp = urllib.request.urlopen(req, timeout=10)+ return resp.status, json.loads(resp.read())+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read())+++# ── Routing tests ──────────────────────────────────────────++def test_execute_route_exists():+ """POST /Execute reaches the rds-data handler (not a 404)."""+ status, body = _raw_post("/Execute", {})+ # Should get a 400 (missing params), not 404+ assert status == 400+ assert "BadRequestException" in str(body) or "resourceArn" in str(body)+++def test_begin_transaction_route_exists():+ """POST /BeginTransaction reaches the rds-data handler."""+ status, body = _raw_post("/BeginTransaction", {})+ assert status == 400+++def test_commit_transaction_route_exists():+ """POST /CommitTransaction reaches the rds-data handler."""+ status, body = _raw_post("/CommitTransaction", {})+ assert status == 400+++def test_rollback_transaction_route_exists():+ """POST /RollbackTransaction reaches the rds-data handler."""+ status, body = _raw_post("/RollbackTransaction", {})+ assert status == 400+++def test_batch_execute_route_exists():+ """POST /BatchExecute reaches the rds-data handler."""+ status, body = _raw_post("/BatchExecute", {})+ assert status == 400+++# ── Parameter validation ───────────────────────────────────++def test_execute_missing_resource_arn():+ status, body = _raw_post("/Execute", {+ "secretArn": FAKE_SECRET_ARN,+ "sql": "SELECT 1",+ })+ assert status == 400+ assert "resourceArn" in body.get("message", body.get("Message", ""))+++def test_execute_missing_secret_arn():+ status, body = _raw_post("/Execute", {+ "resourceArn": FAKE_CLUSTER_ARN,+ "sql": "SELECT 1",+ })+ assert status == 400+ assert "secretArn" in body.get("message", body.get("Message", ""))+++def test_execute_missing_sql():+ status, body = _raw_post("/Execute", {+ "resourceArn": FAKE_CLUSTER_ARN,+ "secretArn": FAKE_SECRET_ARN,+ })+ assert status == 400+ assert "sql" in body.get("message", body.get("Message", ""))+++def test_batch_execute_missing_sql():+ status, body = _raw_post("/BatchExecute", {+ "resourceArn": FAKE_CLUSTER_ARN,+ "secretArn": FAKE_SECRET_ARN,+ })+ assert status == 400+ assert "sql" in body.get("message", body.get("Message", ""))+++# ── Invalid ARN ────────────────────────────────────────────++def test_execute_nonexistent_cluster():+ """ExecuteStatement with a non-existent cluster ARN returns an error."""+ status, body = _raw_post("/Execute", {+ "resourceArn": FAKE_CLUSTER_ARN,+ "secretArn": FAKE_SECRET_ARN,+ "sql": "SELECT 1",+ })+ assert status == 400+ assert "not found" in body.get("message", body.get("Message", "")).lower()+++def test_begin_transaction_nonexistent_cluster():+ """BeginTransaction with a non-existent cluster ARN returns an error."""+ status, body = _raw_post("/BeginTransaction", {+ "resourceArn": FAKE_CLUSTER_ARN,+ "secretArn": FAKE_SECRET_ARN,+ })+ assert status == 400+ assert "not found" in body.get("message", body.get("Message", "")).lower()+++def test_batch_execute_nonexistent_cluster():+ status, body = _raw_post("/BatchExecute", {+ "resourceArn": FAKE_CLUSTER_ARN,+ "secretArn": FAKE_SECRET_ARN,+ "sql": "INSERT INTO t VALUES (1)",+ })+ assert status == 400+ assert "not found" in body.get("message", body.get("Message", "")).lower()+++# ── Transaction lifecycle (error paths) ────────────────────++def test_commit_missing_transaction_id():+ status, body = _raw_post("/CommitTransaction", {})+ assert status == 400+ assert "transactionId" in body.get("message", body.get("Message", ""))+++def test_rollback_missing_transaction_id():+ status, body = _raw_post("/RollbackTransaction", {})+ assert status == 400+ assert "transactionId" in body.get("message", body.get("Message", ""))+++def test_commit_nonexistent_transaction():+ status, body = _raw_post("/CommitTransaction", {+ "transactionId": "nonexistent-txn-id",+ })+ assert status == 404+ assert "not found" in body.get("message", body.get("Message", "")).lower()+++def test_rollback_nonexistent_transaction():+ status, body = _raw_post("/RollbackTransaction", {+ "transactionId": "nonexistent-txn-id",+ })+ assert status == 404+ assert "not found" in body.get("message", body.get("Message", "")).lower()+++# ── Invalid JSON ───────────────────────────────────────────++def test_execute_invalid_json():+ """Malformed JSON body returns BadRequestException."""+ req = urllib.request.Request(+ f"{ENDPOINT}/Execute",+ data=b"not-json{{{",+ headers={"Content-Type": "application/json"},+ method="POST",+ )+ try:+ resp = urllib.request.urlopen(req, timeout=10)+ status = resp.status+ body = json.loads(resp.read())+ except urllib.error.HTTPError as e:+ status = e.code+ body = json.loads(e.read())+ assert status == 400+ assert "Invalid JSON" in body.get("message", body.get("Message", ""))