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(cloudfront-keyvaluestore): add data-plane service for KVS key operations (#544)
Davi Reis Vieira8138a69432d8
diff --git a/ministack/app.py b/ministack/app.pyindex 2874b573..0b0941fa 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -29,6 +29,7 @@ _VERSION = os.environ.get("MINISTACK_VERSION") or "dev"if _VERSION == "dev":try:from importlib.metadata import version as _pkg_version+_VERSION = _pkg_version("ministack")except Exception:pass@@ -126,14 +127,22 @@ _ready_scripts_state: dict = {class _ErrorModule:"""Stub returned when a service module fails to import."""+def __init__(self, name: str, error: str):self._name = nameself._error = errorasync def handle_request(self, method, path, headers, body, query_params):- return 500, {"Content-Type": "application/json"}, \- json.dumps({"__type": "ServiceUnavailable",- "message": f"Service module '{self._name}' failed to load: {self._error}"}).encode()+ return (+ 500,+ {"Content-Type": "application/json"},+ json.dumps(+ {+ "__type": "ServiceUnavailable",+ "message": f"Service module '{self._name}' failed to load: {self._error}",+ }+ ).encode(),+ )def get_state(self):return {}@@ -163,11 +172,14 @@ def _get_module(name: str):def _lazy_handler(module_name: str):"""Return a callable that lazily imports module_name and delegates to handle_request."""+async def _handler(method, path, headers, body, query_params):mod = _get_module(module_name)return await mod.handle_request(method, path, headers, body, query_params)+return _handler+LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()logging.basicConfig(level=getattr(logging, LOG_LEVEL, logging.INFO),@@ -191,6 +203,7 @@ SERVICE_REGISTRY = {"autoscaling": {"module": "autoscaling"},"cloudformation": {"module": "cloudformation"},"cloudfront": {"module": "cloudfront"},+ "cloudfront-keyvaluestore": {"module": "cloudfront_keyvaluestore"},"codebuild": {"module": "codebuild"},"cognito-identity": {"module": "cognito"},"cognito-idp": {"module": "cognito"},@@ -238,8 +251,7 @@ SERVICE_REGISTRY = {}SERVICE_HANDLERS = {- service_name: _lazy_handler(service_config["module"])- for service_name, service_config in SERVICE_REGISTRY.items()+ service_name: _lazy_handler(service_config["module"]) for service_name, service_config in SERVICE_REGISTRY.items()}# Maps the on-disk persistence key to the service module name. `save_all`@@ -329,6 +341,7 @@ def _get_reset_lock() -> asyncio.Lock:# Request I/O helpers# ---------------------------------------------------------------------------+def _decode_aws_chunked_body(body: bytes, headers: dict) -> bytes:"""Decode AWS chunked request bodies and normalize content-encoding headers."""sha256_header = headers.get("x-amz-content-sha256", "")@@ -355,8 +368,8 @@ def _decode_aws_chunked_body(body: bytes, headers: dict) -> bytes:if chunk_size == 0:breakdata_start = crlf + 2- decoded += remaining[data_start:data_start + chunk_size]- remaining = remaining[data_start + chunk_size + 2:] # skip trailing \r\n+ decoded += remaining[data_start : data_start + chunk_size]+ remaining = remaining[data_start + chunk_size + 2 :] # skip trailing \r\nbody = decodedif "aws-chunked" in content_encoding:@@ -382,6 +395,7 @@ async def _read_request_body(receive, method: str, headers: dict) -> bytes:async def _send_response(send, status, headers, body):"""Send ASGI HTTP response."""+def _encode_header_value(v: str) -> bytes:try:return v.encode("latin-1")@@ -392,16 +406,20 @@ async def _send_response(send, status, headers, body):if "content-length" not in {k.lower() for k in headers}:headers["Content-Length"] = str(len(body_bytes))header_list = [(k.encode("latin-1"), _encode_header_value(str(v))) for k, v in headers.items()]- await send({- "type": "http.response.start",- "status": status,- "headers": header_list,- })- await send({- "type": "http.response.body",- "body": body_bytes,- "more_body": False,- })+ await send(+ {+ "type": "http.response.start",+ "status": status,+ "headers": header_list,+ }+ )+ await send(+ {+ "type": "http.response.body",+ "body": body_bytes,+ "more_body": False,+ }+ )async def _send_if_handled(send, response) -> bool:@@ -416,34 +434,45 @@ async def _send_if_handled(send, response) -> bool:# Tier 1 — Pre-body handlers (no request body needed)# ---------------------------------------------------------------------------+def _handle_options_request(method: str, request_id: str):"""Return the standard CORS preflight response when applicable."""if method != "OPTIONS":return None- return 200, {- "Access-Control-Allow-Origin": "*",- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH",- "Access-Control-Allow-Headers": "*",- "Access-Control-Expose-Headers": "*",- "Access-Control-Max-Age": "86400",- "Content-Length": "0",- "x-amzn-requestid": request_id,- }, b""+ return (+ 200,+ {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH",+ "Access-Control-Allow-Headers": "*",+ "Access-Control-Expose-Headers": "*",+ "Access-Control-Max-Age": "86400",+ "Content-Length": "0",+ "x-amzn-requestid": request_id,+ },+ b"",+ )def _handle_health_request(path: str, request_id: str):"""Return health responses for MiniStack and LocalStack-compatible endpoints."""if path not in _HEALTH_PATHS:return None- return 200, {- "Content-Type": "application/json",- "x-amzn-requestid": request_id,- }, json.dumps({- "services": {s: "available" for s in SERVICE_HANDLERS},- "edition": os.environ.get("MINISTACK_EDITION", "light"),- "version": _VERSION,- "ready_scripts": dict(_ready_scripts_state),- }).encode()+ return (+ 200,+ {+ "Content-Type": "application/json",+ "x-amzn-requestid": request_id,+ },+ json.dumps(+ {+ "services": {s: "available" for s in SERVICE_HANDLERS},+ "edition": os.environ.get("MINISTACK_EDITION", "light"),+ "version": _VERSION,+ "ready_scripts": dict(_ready_scripts_state),+ }+ ).encode(),+ )def _handle_ready_request(path: str, request_id: str):@@ -452,10 +481,14 @@ def _handle_ready_request(path: str, request_id: str):return Noneready = _ready_scripts_state["status"] == "completed"status = 200 if ready else 503- return status, {- "Content-Type": "application/json",- "x-amzn-requestid": request_id,- }, json.dumps(dict(_ready_scripts_state)).encode()+ return (+ status,+ {+ "Content-Type": "application/json",+ "x-amzn-requestid": request_id,+ },+ json.dumps(dict(_ready_scripts_state)).encode(),+ )def _handle_unknown_localstack_request(path: str, request_id: str):@@ -467,16 +500,22 @@ def _handle_unknown_localstack_request(path: str, request_id: str):"""if not path.startswith("/_localstack/"):return None- return 404, {- "Content-Type": "application/json",- "x-amzn-requestid": request_id,- }, json.dumps({- "error": (- f"Unknown LocalStack endpoint: {path}. "- "Ministack exposes /_ministack/health, /_ministack/ready, and /_ministack/reset. "- "See https://github.com/ministackorg/ministack for the full API."- )- }).encode()+ return (+ 404,+ {+ "Content-Type": "application/json",+ "x-amzn-requestid": request_id,+ },+ json.dumps(+ {+ "error": (+ f"Unknown LocalStack endpoint: {path}. "+ "Ministack exposes /_ministack/health, /_ministack/ready, and /_ministack/reset. "+ "See https://github.com/ministackorg/ministack for the full API."+ )+ }+ ).encode(),+ )def _handle_lambda_download_request(path: str, method: str):@@ -546,10 +585,16 @@ async def _handle_ses_messages_request(method: str, path: str, headers: dict, quraw_account = query_params["account"]account_id = raw_account[0] if isinstance(raw_account, (list, tuple)) else raw_accountif not _12_DIGIT_RE.match(account_id):- return 400, {"Content-Type": "application/json"}, json.dumps({- "__type": "InvalidAccountID",- "message": f"Account ID must be 12 digits, got: {account_id}",- }).encode()+ return (+ 400,+ {"Content-Type": "application/json"},+ json.dumps(+ {+ "__type": "InvalidAccountID",+ "message": f"Account ID must be 12 digits, got: {account_id}",+ }+ ).encode(),+ )try:mod = _get_module("ses")@@ -611,7 +656,7 @@ async def _handle_pre_body_request(method: str, path: str, headers: dict, query_response = await _handle_cognito_get_request(method, path, headers, query_params)if response is not None:return response-+response = await _handle_ses_messages_request(method, path, headers, query_params)if response is not None:return response@@ -636,6 +681,7 @@ def _handle_transfer_sftp_ports_request(method: str, path: str):return Nonetry:from ministack.services import transfer+body = {"enabled": transfer._sftp_enabled(),"port_per_server": transfer._port_per_server(),@@ -651,6 +697,7 @@ def _handle_transfer_sftp_ports_request(method: str, path: str):# Tier 2 — Post-body shortcuts (body required, before generic routing)# ---------------------------------------------------------------------------+async def _handle_cognito_body_request(method: str, path: str, headers: dict, body: bytes, query_params: dict):"""Handle Cognito routes that require the parsed request body."""if path in ("/oauth2/login", "/login") and method == "POST":@@ -668,7 +715,8 @@ async def _handle_admin_config_request(path: str, method: str, body: bytes):return Noneallowed_config_keys = {- "athena.ATHENA_ENGINE", "athena.ATHENA_DATA_DIR",+ "athena.ATHENA_ENGINE",+ "athena.ATHENA_DATA_DIR","stepfunctions._sfn_mock_config","stepfunctions._SFN_WAIT_SCALE","lambda_svc.LAMBDA_EXECUTOR",@@ -718,32 +766,34 @@ async def _handle_post_body_shortcuts(method: str, path: str, headers: dict, bod# Tier 3 — Special data-plane handlers (host/path-based routing)# ---------------------------------------------------------------------------+async def _handle_s3_control_request(path: str, method: str, body: bytes, query_params: dict, request_id: str):"""Handle S3 Control operations addressed via the /v20180820 path prefix."""if not path.startswith(_S3_CONTROL_PREFIX):return Noneif path.startswith("/v20180820/tags/"):- raw_arn = path[len("/v20180820/tags/"):]+ raw_arn = path[len("/v20180820/tags/") :]arn = unquote(raw_arn)bucket_name = arn.split(":::")[-1].split("/")[0] if ":::" in arn else arn.split("/")[0]if method == "GET":tags = _get_module("s3")._bucket_tags.get(bucket_name, {})- tag_members = "".join(- f"<member><Key>{k}</Key><Value>{v}</Value></member>"- for k, v in tags.items()- )+ tag_members = "".join(f"<member><Key>{k}</Key><Value>{v}</Value></member>" for k, v in tags.items())xml_body = ('<?xml version="1.0" encoding="UTF-8"?>''<ListTagsForResourceResult xmlns="https://awss3control.amazonaws.com/doc/2018-08-20/">'f"<Tags>{tag_members}</Tags>""</ListTagsForResourceResult>").encode()- return 200, {- "Content-Type": "application/xml",- "x-amzn-requestid": request_id,- }, xml_body+ return (+ 200,+ {+ "Content-Type": "application/xml",+ "x-amzn-requestid": request_id,+ },+ xml_body,+ )if method in ("POST", "PUT"):# AWS SDK Go v2 (used by terraform-aws-provider v6+) sends@@ -758,10 +808,13 @@ async def _handle_s3_control_request(path: str, method: str, body: bytes, query_if stripped.startswith("<"):# XML: <TagResourceRequest><Tags><Tag><Key>..</Key><Value>..</Value></Tag>...</Tags></TagResourceRequest>from xml.etree.ElementTree import fromstring+root = fromstring(raw)+def _local(el):t = el.tagreturn t.split("}")[-1] if "}" in t else t+for child in root.iter():if _local(child) != "Tag":continue@@ -790,15 +843,23 @@ async def _handle_s3_control_request(path: str, method: str, body: bytes, query__get_module("s3")._bucket_tags[bucket_name] = tagsreturn 204, {"x-amzn-requestid": request_id}, b""- return 200, {+ return (+ 200,+ {+ "Content-Type": "application/json",+ "x-amzn-requestid": request_id,+ },+ b"{}",+ )++ return (+ 200,+ {"Content-Type": "application/json","x-amzn-requestid": request_id,- }, b"{}"-- return 200, {- "Content-Type": "application/json",- "x-amzn-requestid": request_id,- }, b"{}"+ },+ b"{}",+ )async def _handle_rds_data_request(method: str, path: str, headers: dict, body: bytes, query_params: dict):@@ -836,7 +897,7 @@ def _parse_execute_api_url(host: str, path: str) -> tuple[str, str, str] | None:# LocalStack-compat: /_aws/execute-api/{apiId}/{stage}/{path...}if path.startswith("/_aws/execute-api/"):- rest = path[len("/_aws/execute-api/"):]+ rest = path[len("/_aws/execute-api/") :]parts = rest.split("/", 2)if len(parts) >= 2 and parts[0]:api_id = parts[0]@@ -846,7 +907,7 @@ def _parse_execute_api_url(host: str, path: str) -> tuple[str, str, str] | None:# LocalStack v1 legacy: /restapis/{apiId}/{stage}/_user_request_/{path...}if path.startswith("/restapis/"):- rest = path[len("/restapis/"):]+ rest = path[len("/restapis/") :]parts = rest.split("/", 3)if len(parts) >= 3 and parts[2] == "_user_request_":api_id = parts[0]@@ -890,7 +951,9 @@ def _resolve_stage_and_path(api_id: str, tentative_stage: str, execute_path: strreturn tentative_stage, execute_path-async def _handle_execute_api_request(host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict):+async def _handle_execute_api_request(+ host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict+):"""Handle API Gateway execute-api data plane requests (Host-based + path-based)."""parsed = _parse_execute_api_url(host, path)if parsed is None:@@ -900,7 +963,7 @@ async def _handle_execute_api_request(host: str, path: str, method: str, headers# WebSocket @connections management API — /{stage}/@connections/{id}.# The @connections prefix is authoritative; skip $default resolution.if execute_path.startswith("/@connections/"):- connection_id = execute_path[len("/@connections/"):].split("/", 1)[0]+ connection_id = execute_path[len("/@connections/") :].split("/", 1)[0]return await _get_module("apigateway").handle_connections_api(method, api_id, tentative_stage, connection_id, body, headers)@@ -920,7 +983,11 @@ async def _handle_execute_api_request(host: str, path: str, method: str, headersdef _is_potential_alb_request(host: str, path: str) -> bool:"""Cheap ALB gate so ordinary requests avoid loading the ALB module."""hostname = host.split(":")[0].lower()- return path.startswith(_ALB_PATH_PREFIX) or hostname.endswith(".elb.amazonaws.com") or hostname.endswith(".alb.localhost")+ return (+ path.startswith(_ALB_PATH_PREFIX)+ or hostname.endswith(".elb.amazonaws.com")+ or hostname.endswith(".alb.localhost")+ )async def _handle_alb_request(host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict):@@ -933,7 +1000,7 @@ async def _handle_alb_request(host: str, path: str, method: str, headers: dict,dispatch_path = pathif load_balancer is None and path.startswith(_ALB_PATH_PREFIX):- path_parts = path[len(_ALB_PATH_PREFIX):].split("/", 1)+ path_parts = path[len(_ALB_PATH_PREFIX) :].split("/", 1)load_balancer = alb_module._find_lb_by_name(path_parts[0])if load_balancer:dispatch_path = "/" + path_parts[1] if len(path_parts) > 1 else "/"@@ -962,6 +1029,8 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dbucket = _extract_s3_vhost_bucket(host)if not bucket or _S3_VHOST_EXCLUDE_RE.search(host) or bucket in _NON_S3_VHOST_NAMES:return None+ if path.startswith("/key-value-stores/"):+ return Nonevhost_path = "/" + bucket + path if path != "/" else "/" + bucket + "/"try:@@ -970,8 +1039,10 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: dlogger.exception("Error handling virtual-hosted S3 request: %s", e)from xml.sax.saxutils import escape as _xml_esc- return 500, {"Content-Type": "application/xml"}, (- f"<Error><Code>InternalError</Code><Message>{_xml_esc(str(e))}</Message></Error>".encode()+ return (+ 500,+ {"Content-Type": "application/xml"},+ (f"<Error><Code>InternalError</Code><Message>{_xml_esc(str(e))}</Message></Error>".encode()),)@@ -1025,17 +1096,22 @@ async def _handle_special_data_plane_request(# Tier 4 — Generic service dispatch# ---------------------------------------------------------------------------+def _routing_params(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> dict:"""Augment routing params for unsigned form-encoded requests whose Action lives in the body."""routing_params = query_params- if not query_params.get("Action") and headers.get("content-type", "").startswith("application/x-www-form-urlencoded"):+ if not query_params.get("Action") and headers.get("content-type", "").startswith(+ "application/x-www-form-urlencoded"+ ):body_params = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)if body_params.get("Action"):routing_params = {**query_params, "Action": body_params["Action"]}return routing_params-async def _dispatch_service_request(method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str):+async def _dispatch_service_request(+ method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str+):"""Dispatch a request through the generic service router."""routing_params = _routing_params(method, path, headers, body, query_params)service = detect_service(method, path, headers, routing_params)@@ -1045,23 +1121,33 @@ async def _dispatch_service_request(method: str, path: str, headers: dict, body:handler = SERVICE_HANDLERS.get(service)if not handler:- return 400, {"Content-Type": "application/json"}, json.dumps({"error": f"Unsupported service: {service}"}).encode()+ return (+ 400,+ {"Content-Type": "application/json"},+ json.dumps({"error": f"Unsupported service: {service}"}).encode(),+ )try:status, resp_headers, resp_body = await handler(method, path, headers, body, query_params)except Exception as e:logger.exception("Error handling %s request: %s", service, e)- return 500, {"Content-Type": "application/json"}, json.dumps({"__type": "InternalError", "message": str(e)}).encode()-- resp_headers.update({- "Access-Control-Allow-Origin": "*",- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH",- "Access-Control-Allow-Headers": "*",- "Access-Control-Expose-Headers": "*",- "x-amzn-requestid": request_id,- "x-amz-request-id": request_id,- "x-amz-id-2": base64.b64encode(os.urandom(48)).decode(),- })+ return (+ 500,+ {"Content-Type": "application/json"},+ json.dumps({"__type": "InternalError", "message": str(e)}).encode(),+ )++ resp_headers.update(+ {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH",+ "Access-Control-Allow-Headers": "*",+ "Access-Control-Expose-Headers": "*",+ "x-amzn-requestid": request_id,+ "x-amz-request-id": request_id,+ "x-amz-id-2": base64.b64encode(os.urandom(48)).decode(),+ }+ )return status, resp_headers, resp_body@@ -1069,6 +1155,7 @@ async def _dispatch_service_request(method: str, path: str, headers: dict, body:# ASGI entry point# ---------------------------------------------------------------------------+async def app(scope, receive, send):"""ASGI application entry point."""if scope["type"] == "lifespan":@@ -1156,9 +1243,9 @@ async def app(scope, receive, send):if await _send_if_handled(send, await _handle_post_body_shortcuts(method, path, headers, body, query_params)):return- if await _send_if_handled(send, await _handle_special_data_plane_request(- method, path, headers, body, query_params, request_id- )):+ if await _send_if_handled(+ send, await _handle_special_data_plane_request(method, path, headers, body, query_params, request_id)+ ):returnawait _send_response(send, *await _dispatch_service_request(method, path, headers, body, query_params, request_id))@@ -1168,6 +1255,7 @@ async def app(scope, receive, send):# Lifecycle, init scripts, and server administration# ---------------------------------------------------------------------------+async def _handle_lifespan(scope, receive, send):"""Handle ASGI lifespan events."""while True:@@ -1183,6 +1271,7 @@ async def _handle_lifespan(scope, receive, send):# before the handler ever runs. 64 is plenty — threads are cheap# and idle. Override with MINISTACK_WORKER_THREADS.import concurrent.futures+_max_workers = int(os.environ.get("MINISTACK_WORKER_THREADS", "64"))asyncio.get_running_loop().set_default_executor(concurrent.futures.ThreadPoolExecutor(@@ -1205,6 +1294,7 @@ async def _handle_lifespan(scope, receive, send):# installed or SFTP_ENABLED=0.try:from ministack.services import transfer+await transfer.sftp_start()except Exception as e:logger.warning("Transfer SFTP startup failed: %s", e)@@ -1224,6 +1314,7 @@ async def _handle_lifespan(scope, receive, send):save_all(save_dict)try:from ministack.services import transfer+await transfer.sftp_stop()except Exception as e:logger.debug("Transfer SFTP shutdown error: %s", e)@@ -1237,6 +1328,7 @@ def _stop_docker_containers():Uses container labels to find them — does not touch service state."""try:import docker+client = docker.from_env()except Exception:return@@ -1281,28 +1373,29 @@ def _load_persisted_state():async def _wait_for_port(port, timeout=30):"""Wait until the server is accepting TCP connections."""import time+deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:try:- reader, writer = await asyncio.open_connection('127.0.0.1', port)+ reader, writer = await asyncio.open_connection("127.0.0.1", port)writer.close()await writer.wait_closed()returnexcept OSError:await asyncio.sleep(0.1)- logger.warning('Server did not become ready within %ds — skipping ready.d scripts', timeout)+ logger.warning("Server did not become ready within %ds — skipping ready.d scripts", timeout)async def _run_ready_scripts():"""Execute .sh/.py scripts from ready.d directories after the server is ready."""- scripts = _collect_scripts('/docker-entrypoint-initaws.d/ready.d', '/etc/localstack/init/ready.d')+ scripts = _collect_scripts("/docker-entrypoint-initaws.d/ready.d", "/etc/localstack/init/ready.d")if not scripts:_ready_scripts_state.update({"status": "completed", "total": 0, "completed": 0, "failed": 0})return_ready_scripts_state.update({"status": "running", "total": len(scripts), "completed": 0, "failed": 0})port = int(_resolve_port())await _wait_for_port(port)- logger.info('Found %d ready script(s)', len(scripts))+ logger.info("Found %d ready script(s)", len(scripts))# Provide sensible defaults so init scripts can use aws cli / boto3# without requiring manual credential configuration. Skip credential# defaults when the user has mounted ~/.aws/credentials so the CLI@@ -1318,18 +1411,20 @@ async def _run_ready_scripts():script_env.setdefault("AWS_SECRET_ACCESS_KEY", "test")script_env.setdefault("AWS_DEFAULT_REGION", os.environ.get("MINISTACK_REGION", "us-east-1"))script_env.setdefault("AWS_ENDPOINT_URL", f"http://{_MINISTACK_HOST}:{port}")- for ready_dir in ('/docker-entrypoint-initaws.d/ready.d', '/etc/localstack/init/ready.d'):+ for ready_dir in ("/docker-entrypoint-initaws.d/ready.d", "/etc/localstack/init/ready.d"):if os.path.isdir(ready_dir):script_env.setdefault("MINISTACK_INIT_READY_DIR", ready_dir)breakfor script_path in scripts:- logger.info('Running ready script: %s', script_path)+ logger.info("Running ready script: %s", script_path)script_failed = Falsetry:- cmd = [sys.executable, script_path] if script_path.endswith('.py') else ['sh', script_path]- per_script_env = {**script_env,- "MINISTACK_INIT_SCRIPT_DIR": os.path.dirname(script_path),- "MINISTACK_INIT_SCRIPT_PATH": script_path}+ cmd = [sys.executable, script_path] if script_path.endswith(".py") else ["sh", script_path]+ per_script_env = {+ **script_env,+ "MINISTACK_INIT_SCRIPT_DIR": os.path.dirname(script_path),+ "MINISTACK_INIT_SCRIPT_PATH": script_path,+ }proc = await asyncio.create_subprocess_exec(*cmd,stdout=asyncio.subprocess.PIPE,@@ -1338,20 +1433,24 @@ async def _run_ready_scripts():)stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=300)if stdout:- logger.info(' stdout: %s', stdout.decode('utf-8', errors='replace').rstrip())+ logger.info(" stdout: %s", stdout.decode("utf-8", errors="replace").rstrip())if proc.returncode != 0:script_failed = True- logger.error('Ready script %s failed (exit %d): %s', script_path, proc.returncode,- stderr.decode('utf-8', errors='replace'))+ logger.error(+ "Ready script %s failed (exit %d): %s",+ script_path,+ proc.returncode,+ stderr.decode("utf-8", errors="replace"),+ )else:- logger.info('Ready script %s completed successfully', script_path)+ logger.info("Ready script %s completed successfully", script_path)except asyncio.TimeoutError:script_failed = True- logger.error('Ready script %s timed out after 300s', script_path)+ logger.error("Ready script %s timed out after 300s", script_path)proc.kill()except Exception as e:script_failed = True- logger.error('Failed to execute ready script %s: %s', script_path, e)+ logger.error("Failed to execute ready script %s: %s", script_path, e)_ready_scripts_state["completed"] += 1if script_failed:_ready_scripts_state["failed"] += 1@@ -1365,32 +1464,37 @@ def _collect_scripts(*dirs):if not os.path.isdir(d):continuefor f in sorted(os.listdir(d)):- if f.endswith(('.sh', '.py')) and f not in seen:+ if f.endswith((".sh", ".py")) and f not in seen:seen[f] = os.path.join(d, f)return [seen[f] for f in sorted(seen)]def _run_init_scripts():"""Execute .sh/.py scripts from init directories in alphabetical order."""- scripts = _collect_scripts('/docker-entrypoint-initaws.d', '/etc/localstack/init/boot.d')+ scripts = _collect_scripts("/docker-entrypoint-initaws.d", "/etc/localstack/init/boot.d")if not scripts:returnlogger.info("Found %d init script(s)", len(scripts))base_env = {**os.environ}- for boot_dir in ('/docker-entrypoint-initaws.d', '/etc/localstack/init/boot.d'):+ for boot_dir in ("/docker-entrypoint-initaws.d", "/etc/localstack/init/boot.d"):if os.path.isdir(boot_dir):base_env.setdefault("MINISTACK_INIT_BOOT_DIR", boot_dir)breakfor script_path in scripts:logger.info("Running init script: %s", script_path)try:- cmd = [sys.executable, script_path] if script_path.endswith('.py') else ["sh", script_path]- per_script_env = {**base_env,- "MINISTACK_INIT_SCRIPT_DIR": os.path.dirname(script_path),- "MINISTACK_INIT_SCRIPT_PATH": script_path}+ cmd = [sys.executable, script_path] if script_path.endswith(".py") else ["sh", script_path]+ per_script_env = {+ **base_env,+ "MINISTACK_INIT_SCRIPT_DIR": os.path.dirname(script_path),+ "MINISTACK_INIT_SCRIPT_PATH": script_path,+ }result = subprocess.run(- cmd, env=per_script_env,- capture_output=True, text=True, timeout=300,+ cmd,+ env=per_script_env,+ capture_output=True,+ text=True,+ timeout=300,)if result.stdout:logger.info(" stdout: %s", result.stdout.rstrip())@@ -1493,9 +1597,11 @@ def main():probe_host = "127.0.0.1" if bind_host == "0.0.0.0" else bind_hostwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:if s.connect_ex((probe_host, port)) == 0:- print(f"ERROR: {probe_host}:{port} is already in use. Is MiniStack already running?\n"- f" Stop it with: ministack --stop\n"- f" Or use a different port: GATEWAY_PORT=4567 ministack")+ print(+ f"ERROR: {probe_host}:{port} is already in use. Is MiniStack already running?\n"+ f" Stop it with: ministack --stop\n"+ f" Or use a different port: GATEWAY_PORT=4567 ministack"+ )raise SystemExit(1)if args.detach:@@ -1506,10 +1612,18 @@ def main():# process; the OS reclaims it when the parent exits.log_fh = open(log_file, "w")proc = subprocess.Popen(- [sys.executable, "-m", "hypercorn", "ministack.app:app",- "--bind", f"{bind_host}:{port}",- "--log-level", LOG_LEVEL.upper(),- "--keep-alive", "75"],+ [+ sys.executable,+ "-m",+ "hypercorn",+ "ministack.app:app",+ "--bind",+ f"{bind_host}:{port}",+ "--log-level",+ LOG_LEVEL.upper(),+ "--keep-alive",+ "75",+ ],stdout=log_fh,stderr=subprocess.STDOUT,start_new_session=True,diff --git a/ministack/core/router.py b/ministack/core/router.pyindex e4d4b6d4..f771c015 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -156,10 +156,18 @@ SERVICE_PATTERNS = {},"ec2": {"host_patterns": [r"ec2\."],- "path_patterns": [r"Action=.*Instance", r"Action=.*Security", r"Action=.*KeyPair",- r"Action=.*Vpc", r"Action=.*Subnet", r"Action=.*Address",- r"Action=.*Image", r"Action=.*Tag", r"Action=.*InternetGateway",- r"Action=.*AvailabilityZone"],+ "path_patterns": [+ r"Action=.*Instance",+ r"Action=.*Security",+ r"Action=.*KeyPair",+ r"Action=.*Vpc",+ r"Action=.*Subnet",+ r"Action=.*Address",+ r"Action=.*Image",+ r"Action=.*Tag",+ r"Action=.*InternetGateway",+ r"Action=.*AvailabilityZone",+ ],},"elasticloadbalancing": {"host_patterns": [r"elasticloadbalancing\."],@@ -187,9 +195,12 @@ SERVICE_PATTERNS = {"opensearch": {"host_patterns": [r"^es\.", r"^aos\.", r"^opensearch\."],"path_prefixes": [- "/2021-01-01/domain", "/2021-01-01/opensearch",- "/2021-01-01/versions", "/2021-01-01/compatibleVersions",- "/2021-01-01/tags", "/2021-01-01/tags-removal",+ "/2021-01-01/domain",+ "/2021-01-01/opensearch",+ "/2021-01-01/versions",+ "/2021-01-01/compatibleVersions",+ "/2021-01-01/tags",+ "/2021-01-01/tags-removal",],"credential_scope": "es",},@@ -200,9 +211,14 @@ SERVICE_PATTERNS = {},"account": {"host_patterns": [r"^account\."],- "path_prefixes": ["/getAccountInformation", "/getContactInformation",- "/listRegions", "/getRegionOptStatus",- "/getAlternateContact", "/getPrimaryEmail"],+ "path_prefixes": [+ "/getAccountInformation",+ "/getContactInformation",+ "/listRegions",+ "/getRegionOptStatus",+ "/getAlternateContact",+ "/getPrimaryEmail",+ ],"credential_scope": "account",},"batch": {@@ -213,14 +229,16 @@ SERVICE_PATTERNS = {"cloudformation": {"host_patterns": [r"cloudformation\."],},- "kms": {- "target_prefixes": ["TrentService"],- "host_patterns": [r"kms\."]- },+ "kms": {"target_prefixes": ["TrentService"], "host_patterns": [r"kms\."]},"cloudfront": {"host_patterns": [r"cloudfront\."],"credential_scope": "cloudfront",},+ "cloudfront-keyvaluestore": {+ "host_patterns": [r"cloudfront-kvs\."],+ "credential_scope": "cloudfront-keyvaluestore",+ "path_prefixes": ["/key-value-stores/"],+ },"codebuild": {"target_prefixes": ["CodeBuild_20161006"],"host_patterns": [r"codebuild\."],@@ -372,143 +390,262 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->return scope_map[svc_name]# 3. Check query parameters for Action-based APIs (SQS, SNS, IAM, STS, CloudWatch)- action = query_params.get("Action", [""])[0] if isinstance(query_params.get("Action"), list) else query_params.get("Action", "")+ action = (+ query_params.get("Action", [""])[0]+ if isinstance(query_params.get("Action"), list)+ else query_params.get("Action", "")+ )if action:action_service_map = {# SQS actions- "SendMessage": "sqs", "ReceiveMessage": "sqs", "DeleteMessage": "sqs",- "CreateQueue": "sqs", "DeleteQueue": "sqs", "ListQueues": "sqs",- "GetQueueUrl": "sqs", "GetQueueAttributes": "sqs", "SetQueueAttributes": "sqs",- "PurgeQueue": "sqs", "ChangeMessageVisibility": "sqs",+ "SendMessage": "sqs",+ "ReceiveMessage": "sqs",+ "DeleteMessage": "sqs",+ "CreateQueue": "sqs",+ "DeleteQueue": "sqs",+ "ListQueues": "sqs",+ "GetQueueUrl": "sqs",+ "GetQueueAttributes": "sqs",+ "SetQueueAttributes": "sqs",+ "PurgeQueue": "sqs",+ "ChangeMessageVisibility": "sqs","ChangeMessageVisibilityBatch": "sqs",- "SendMessageBatch": "sqs", "DeleteMessageBatch": "sqs",- "ListQueueTags": "sqs", "TagQueue": "sqs", "UntagQueue": "sqs",+ "SendMessageBatch": "sqs",+ "DeleteMessageBatch": "sqs",+ "ListQueueTags": "sqs",+ "TagQueue": "sqs",+ "UntagQueue": "sqs",# SNS actions- "Publish": "sns", "Subscribe": "sns", "Unsubscribe": "sns",- "CreateTopic": "sns", "DeleteTopic": "sns", "ListTopics": "sns",- "ListSubscriptions": "sns", "ConfirmSubscription": "sns",- "SetTopicAttributes": "sns", "GetTopicAttributes": "sns",+ "Publish": "sns",+ "Subscribe": "sns",+ "Unsubscribe": "sns",+ "CreateTopic": "sns",+ "DeleteTopic": "sns",+ "ListTopics": "sns",+ "ListSubscriptions": "sns",+ "ConfirmSubscription": "sns",+ "SetTopicAttributes": "sns",+ "GetTopicAttributes": "sns","ListSubscriptionsByTopic": "sns",- "GetSubscriptionAttributes": "sns", "SetSubscriptionAttributes": "sns",+ "GetSubscriptionAttributes": "sns",+ "SetSubscriptionAttributes": "sns","PublishBatch": "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",+ "TagResource": "sns",+ "UntagResource": "sns",+ "CreatePlatformApplication": "sns",+ "CreatePlatformEndpoint": "sns",# IAM actions- "CreateRole": "iam", "GetRole": "iam", "ListRoles": "iam",- "DeleteRole": "iam", "CreateUser": "iam", "GetUser": "iam",- "ListUsers": "iam", "DeleteUser": "iam",- "CreatePolicy": "iam", "GetPolicy": "iam", "DeletePolicy": "iam",- "GetPolicyVersion": "iam", "ListPolicyVersions": "iam",- "CreatePolicyVersion": "iam", "DeletePolicyVersion": "iam",+ "CreateRole": "iam",+ "GetRole": "iam",+ "ListRoles": "iam",+ "DeleteRole": "iam",+ "CreateUser": "iam",+ "GetUser": "iam",+ "ListUsers": "iam",+ "DeleteUser": "iam",+ "CreatePolicy": "iam",+ "GetPolicy": "iam",+ "DeletePolicy": "iam",+ "GetPolicyVersion": "iam",+ "ListPolicyVersions": "iam",+ "CreatePolicyVersion": "iam",+ "DeletePolicyVersion": "iam","ListPolicies": "iam",- "AttachRolePolicy": "iam", "DetachRolePolicy": "iam",+ "AttachRolePolicy": "iam",+ "DetachRolePolicy": "iam","ListAttachedRolePolicies": "iam",- "PutRolePolicy": "iam", "GetRolePolicy": "iam",- "DeleteRolePolicy": "iam", "ListRolePolicies": "iam",- "CreateAccessKey": "iam", "ListAccessKeys": "iam", "DeleteAccessKey": "iam",- "CreateInstanceProfile": "iam", "DeleteInstanceProfile": "iam",- "GetInstanceProfile": "iam", "AddRoleToInstanceProfile": "iam",+ "PutRolePolicy": "iam",+ "GetRolePolicy": "iam",+ "DeleteRolePolicy": "iam",+ "ListRolePolicies": "iam",+ "CreateAccessKey": "iam",+ "ListAccessKeys": "iam",+ "DeleteAccessKey": "iam",+ "CreateInstanceProfile": "iam",+ "DeleteInstanceProfile": "iam",+ "GetInstanceProfile": "iam",+ "AddRoleToInstanceProfile": "iam","RemoveRoleFromInstanceProfile": "iam",- "ListInstanceProfiles": "iam", "ListInstanceProfilesForRole": "iam",+ "ListInstanceProfiles": "iam",+ "ListInstanceProfilesForRole": "iam","UpdateAssumeRolePolicy": "iam",- "AttachUserPolicy": "iam", "DetachUserPolicy": "iam",+ "AttachUserPolicy": "iam",+ "DetachUserPolicy": "iam","ListAttachedUserPolicies": "iam",- "TagRole": "iam", "UntagRole": "iam", "ListRoleTags": "iam",- "TagUser": "iam", "UntagUser": "iam", "ListUserTags": "iam",- "SimulatePrincipalPolicy": "iam", "SimulateCustomPolicy": "iam",+ "TagRole": "iam",+ "UntagRole": "iam",+ "ListRoleTags": "iam",+ "TagUser": "iam",+ "UntagUser": "iam",+ "ListUserTags": "iam",+ "SimulatePrincipalPolicy": "iam",+ "SimulateCustomPolicy": "iam",# STS actions- "GetCallerIdentity": "sts", "AssumeRole": "sts",- "GetSessionToken": "sts", "AssumeRoleWithWebIdentity": "sts",+ "GetCallerIdentity": "sts",+ "AssumeRole": "sts",+ "GetSessionToken": "sts",+ "AssumeRoleWithWebIdentity": "sts","AssumeRoleWithSAML": "sts",# CloudWatch actions- "PutMetricData": "monitoring", "GetMetricData": "monitoring",- "ListMetrics": "monitoring", "PutMetricAlarm": "monitoring",- "DescribeAlarms": "monitoring", "DeleteAlarms": "monitoring",- "GetMetricStatistics": "monitoring", "SetAlarmState": "monitoring",- "EnableAlarmActions": "monitoring", "DisableAlarmActions": "monitoring",- "DescribeAlarmsForMetric": "monitoring", "DescribeAlarmHistory": "monitoring",+ "PutMetricData": "monitoring",+ "GetMetricData": "monitoring",+ "ListMetrics": "monitoring",+ "PutMetricAlarm": "monitoring",+ "DescribeAlarms": "monitoring",+ "DeleteAlarms": "monitoring",+ "GetMetricStatistics": "monitoring",+ "SetAlarmState": "monitoring",+ "EnableAlarmActions": "monitoring",+ "DisableAlarmActions": "monitoring",+ "DescribeAlarmsForMetric": "monitoring",+ "DescribeAlarmHistory": "monitoring","PutCompositeAlarm": "monitoring",# SES actions- "SendEmail": "ses", "SendRawEmail": "ses",- "VerifyEmailIdentity": "ses", "VerifyEmailAddress": "ses",- "VerifyDomainIdentity": "ses", "VerifyDomainDkim": "ses",- "ListIdentities": "ses", "DeleteIdentity": "ses",- "GetSendQuota": "ses", "GetSendStatistics": "ses",+ "SendEmail": "ses",+ "SendRawEmail": "ses",+ "VerifyEmailIdentity": "ses",+ "VerifyEmailAddress": "ses",+ "VerifyDomainIdentity": "ses",+ "VerifyDomainDkim": "ses",+ "ListIdentities": "ses",+ "DeleteIdentity": "ses",+ "GetSendQuota": "ses",+ "GetSendStatistics": "ses","ListVerifiedEmailAddresses": "ses","GetIdentityVerificationAttributes": "ses","GetIdentityDkimAttributes": "ses","SetIdentityNotificationTopic": "ses","SetIdentityFeedbackForwardingEnabled": "ses",- "CreateConfigurationSet": "ses", "DeleteConfigurationSet": "ses",- "DescribeConfigurationSet": "ses", "ListConfigurationSets": "ses",+ "CreateConfigurationSet": "ses",+ "DeleteConfigurationSet": "ses",+ "DescribeConfigurationSet": "ses",+ "ListConfigurationSets": "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",+ "DeleteTemplate": "ses",+ "ListTemplates": "ses",+ "UpdateTemplate": "ses",+ "SendTemplatedEmail": "ses",+ "SendBulkTemplatedEmail": "ses",# RDS actions- "CreateDBInstance": "rds", "DeleteDBInstance": "rds", "DescribeDBInstances": "rds",- "StartDBInstance": "rds", "StopDBInstance": "rds", "RebootDBInstance": "rds",- "ModifyDBInstance": "rds", "CreateDBCluster": "rds", "DeleteDBCluster": "rds",+ "CreateDBInstance": "rds",+ "DeleteDBInstance": "rds",+ "DescribeDBInstances": "rds",+ "StartDBInstance": "rds",+ "StopDBInstance": "rds",+ "RebootDBInstance": "rds",+ "ModifyDBInstance": "rds",+ "CreateDBCluster": "rds",+ "DeleteDBCluster": "rds","ModifyDBCluster": "rds",- "DescribeDBClusters": "rds", "CreateDBSubnetGroup": "rds", "DescribeDBSubnetGroups": "rds",+ "DescribeDBClusters": "rds",+ "CreateDBSubnetGroup": "rds",+ "DescribeDBSubnetGroups": "rds","DeleteDBSubnetGroup": "rds",- "CreateDBParameterGroup": "rds", "DescribeDBParameterGroups": "rds",- "DeleteDBParameterGroup": "rds", "DescribeDBParameters": "rds",- "ModifyDBParameterGroup": "rds", "ResetDBParameterGroup": "rds",- "CreateDBClusterParameterGroup": "rds", "DescribeDBClusterParameterGroups": "rds",- "DeleteDBClusterParameterGroup": "rds", "DescribeDBClusterParameters": "rds",- "ModifyDBClusterParameterGroup": "rds", "ResetDBClusterParameterGroup": "rds",+ "CreateDBParameterGroup": "rds",+ "DescribeDBParameterGroups": "rds",+ "DeleteDBParameterGroup": "rds",+ "DescribeDBParameters": "rds",+ "ModifyDBParameterGroup": "rds",+ "ResetDBParameterGroup": "rds",+ "CreateDBClusterParameterGroup": "rds",+ "DescribeDBClusterParameterGroups": "rds",+ "DeleteDBClusterParameterGroup": "rds",+ "DescribeDBClusterParameters": "rds",+ "ModifyDBClusterParameterGroup": "rds",+ "ResetDBClusterParameterGroup": "rds","DescribeDBEngineVersions": "rds","DescribeOrderableDBInstanceOptions": "rds",- "CreateDBSnapshot": "rds", "DeleteDBSnapshot": "rds", "DescribeDBSnapshots": "rds",- "CreateDBInstanceReadReplica": "rds", "RestoreDBInstanceFromDBSnapshot": "rds",- "AddTagsToResource": "rds", "RemoveTagsFromResource": "rds",+ "CreateDBSnapshot": "rds",+ "DeleteDBSnapshot": "rds",+ "DescribeDBSnapshots": "rds",+ "CreateDBInstanceReadReplica": "rds",+ "RestoreDBInstanceFromDBSnapshot": "rds",+ "AddTagsToResource": "rds",+ "RemoveTagsFromResource": "rds",# ElastiCache actions- "CreateCacheCluster": "elasticache", "DeleteCacheCluster": "elasticache",- "DescribeCacheClusters": "elasticache", "ModifyCacheCluster": "elasticache",+ "CreateCacheCluster": "elasticache",+ "DeleteCacheCluster": "elasticache",+ "DescribeCacheClusters": "elasticache",+ "ModifyCacheCluster": "elasticache","RebootCacheCluster": "elasticache",- "CreateReplicationGroup": "elasticache", "DeleteReplicationGroup": "elasticache",- "DescribeReplicationGroups": "elasticache", "ModifyReplicationGroup": "elasticache",- "CreateCacheSubnetGroup": "elasticache", "DescribeCacheSubnetGroups": "elasticache",+ "CreateReplicationGroup": "elasticache",+ "DeleteReplicationGroup": "elasticache",+ "DescribeReplicationGroups": "elasticache",+ "ModifyReplicationGroup": "elasticache",+ "CreateCacheSubnetGroup": "elasticache",+ "DescribeCacheSubnetGroups": "elasticache","DeleteCacheSubnetGroup": "elasticache",- "CreateCacheParameterGroup": "elasticache", "DescribeCacheParameterGroups": "elasticache",+ "CreateCacheParameterGroup": "elasticache",+ "DescribeCacheParameterGroups": "elasticache","DeleteCacheParameterGroup": "elasticache",- "DescribeCacheParameters": "elasticache", "ModifyCacheParameterGroup": "elasticache",+ "DescribeCacheParameters": "elasticache",+ "ModifyCacheParameterGroup": "elasticache","DescribeCacheEngineVersions": "elasticache",- "CreateSnapshot": "elasticache", "DeleteSnapshot": "elasticache",+ "CreateSnapshot": "elasticache",+ "DeleteSnapshot": "elasticache","DescribeSnapshots": "elasticache",- "IncreaseReplicaCount": "elasticache", "DecreaseReplicaCount": "elasticache",+ "IncreaseReplicaCount": "elasticache",+ "DecreaseReplicaCount": "elasticache",# EC2 actions- "RunInstances": "ec2", "DescribeInstances": "ec2", "TerminateInstances": "ec2",- "StopInstances": "ec2", "StartInstances": "ec2", "RebootInstances": "ec2",+ "RunInstances": "ec2",+ "DescribeInstances": "ec2",+ "TerminateInstances": "ec2",+ "StopInstances": "ec2",+ "StartInstances": "ec2",+ "RebootInstances": "ec2","DescribeImages": "ec2",- "CreateSecurityGroup": "ec2", "DeleteSecurityGroup": "ec2",+ "CreateSecurityGroup": "ec2",+ "DeleteSecurityGroup": "ec2","DescribeSecurityGroups": "ec2",- "AuthorizeSecurityGroupIngress": "ec2", "RevokeSecurityGroupIngress": "ec2",- "AuthorizeSecurityGroupEgress": "ec2", "RevokeSecurityGroupEgress": "ec2",- "CreateKeyPair": "ec2", "DeleteKeyPair": "ec2", "DescribeKeyPairs": "ec2",+ "AuthorizeSecurityGroupIngress": "ec2",+ "RevokeSecurityGroupIngress": "ec2",+ "AuthorizeSecurityGroupEgress": "ec2",+ "RevokeSecurityGroupEgress": "ec2",+ "CreateKeyPair": "ec2",+ "DeleteKeyPair": "ec2",+ "DescribeKeyPairs": "ec2","ImportKeyPair": "ec2",- "DescribeVpcs": "ec2", "CreateVpc": "ec2", "DeleteVpc": "ec2",- "DescribeSubnets": "ec2", "CreateSubnet": "ec2", "DeleteSubnet": "ec2",- "CreateInternetGateway": "ec2", "DeleteInternetGateway": "ec2",+ "DescribeVpcs": "ec2",+ "CreateVpc": "ec2",+ "DeleteVpc": "ec2",+ "DescribeSubnets": "ec2",+ "CreateSubnet": "ec2",+ "DeleteSubnet": "ec2",+ "CreateInternetGateway": "ec2",+ "DeleteInternetGateway": "ec2","DescribeInternetGateways": "ec2",- "AttachInternetGateway": "ec2", "DetachInternetGateway": "ec2",+ "AttachInternetGateway": "ec2",+ "DetachInternetGateway": "ec2","DescribeAvailabilityZones": "ec2",- "AllocateAddress": "ec2", "ReleaseAddress": "ec2",- "AssociateAddress": "ec2", "DisassociateAddress": "ec2",+ "AllocateAddress": "ec2",+ "ReleaseAddress": "ec2",+ "AssociateAddress": "ec2",+ "DisassociateAddress": "ec2","DescribeAddresses": "ec2",- "CreateTags": "ec2", "DeleteTags": "ec2", "DescribeTags": "ec2",- "ModifyVpcAttribute": "ec2", "ModifySubnetAttribute": "ec2",- "CreateRouteTable": "ec2", "DeleteRouteTable": "ec2", "DescribeRouteTables": "ec2",- "AssociateRouteTable": "ec2", "DisassociateRouteTable": "ec2",- "CreateRoute": "ec2", "ReplaceRoute": "ec2", "DeleteRoute": "ec2",- "CreateNetworkInterface": "ec2", "DeleteNetworkInterface": "ec2",+ "CreateTags": "ec2",+ "DeleteTags": "ec2",+ "DescribeTags": "ec2",+ "ModifyVpcAttribute": "ec2",+ "ModifySubnetAttribute": "ec2",+ "CreateRouteTable": "ec2",+ "DeleteRouteTable": "ec2",+ "DescribeRouteTables": "ec2",+ "AssociateRouteTable": "ec2",+ "DisassociateRouteTable": "ec2",+ "CreateRoute": "ec2",+ "ReplaceRoute": "ec2",+ "DeleteRoute": "ec2",+ "CreateNetworkInterface": "ec2",+ "DeleteNetworkInterface": "ec2","DescribeNetworkInterfaces": "ec2",- "AttachNetworkInterface": "ec2", "DetachNetworkInterface": "ec2",- "CreateVpcEndpoint": "ec2", "DeleteVpcEndpoints": "ec2",+ "AttachNetworkInterface": "ec2",+ "DetachNetworkInterface": "ec2",+ "CreateVpcEndpoint": "ec2",+ "DeleteVpcEndpoints": "ec2","DescribeVpcEndpoints": "ec2",# ELBv2 / ALB actions"CreateLoadBalancer": "elasticloadbalancing",@@ -538,42 +675,62 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"RemoveTags": "elasticloadbalancing","DescribeTags": "elasticloadbalancing",# EBS Volumes- "CreateVolume": "ec2", "DeleteVolume": "ec2", "DescribeVolumes": "ec2",- "DescribeVolumeStatus": "ec2", "AttachVolume": "ec2", "DetachVolume": "ec2",- "ModifyVolume": "ec2", "DescribeVolumesModifications": "ec2",- "EnableVolumeIO": "ec2", "ModifyVolumeAttribute": "ec2",+ "CreateVolume": "ec2",+ "DeleteVolume": "ec2",+ "DescribeVolumes": "ec2",+ "DescribeVolumeStatus": "ec2",+ "AttachVolume": "ec2",+ "DetachVolume": "ec2",+ "ModifyVolume": "ec2",+ "DescribeVolumesModifications": "ec2",+ "EnableVolumeIO": "ec2",+ "ModifyVolumeAttribute": "ec2","DescribeVolumeAttribute": "ec2",# CloudFormation actions- "CreateStack": "cloudformation", "DescribeStacks": "cloudformation",- "UpdateStack": "cloudformation", "DeleteStack": "cloudformation",+ "CreateStack": "cloudformation",+ "DescribeStacks": "cloudformation",+ "UpdateStack": "cloudformation",+ "DeleteStack": "cloudformation","ListStacks": "cloudformation","DescribeStackEvents": "cloudformation",- "DescribeStackResource": "cloudformation", "DescribeStackResources": "cloudformation",+ "DescribeStackResource": "cloudformation",+ "DescribeStackResources": "cloudformation","ListStackResources": "cloudformation","GetTemplateSummary": "cloudformation","ValidateTemplate": "cloudformation",- "CreateChangeSet": "cloudformation", "DescribeChangeSet": "cloudformation",- "ExecuteChangeSet": "cloudformation", "DeleteChangeSet": "cloudformation",+ "CreateChangeSet": "cloudformation",+ "DescribeChangeSet": "cloudformation",+ "ExecuteChangeSet": "cloudformation",+ "DeleteChangeSet": "cloudformation","ListChangeSets": "cloudformation",- "ListExports": "cloudformation", "ListImports": "cloudformation",+ "ListExports": "cloudformation",+ "ListImports": "cloudformation","UpdateTerminationProtection": "cloudformation",- "SetStackPolicy": "cloudformation", "GetStackPolicy": "cloudformation",+ "SetStackPolicy": "cloudformation",+ "GetStackPolicy": "cloudformation",# EBS Snapshots# Note: CreateSnapshot, DeleteSnapshot, DescribeSnapshots are intentionally# omitted here because they conflict with ElastiCache actions of the same# name. These are routed via credential scope or host header instead.- "CopySnapshot": "ec2", "ModifySnapshotAttribute": "ec2",+ "CopySnapshot": "ec2",+ "ModifySnapshotAttribute": "ec2","DescribeSnapshotAttribute": "ec2",# AutoScaling actions- "CreateAutoScalingGroup": "autoscaling", "DescribeAutoScalingGroups": "autoscaling",- "UpdateAutoScalingGroup": "autoscaling", "DeleteAutoScalingGroup": "autoscaling",- "CreateLaunchConfiguration": "autoscaling", "DescribeLaunchConfigurations": "autoscaling",+ "CreateAutoScalingGroup": "autoscaling",+ "DescribeAutoScalingGroups": "autoscaling",+ "UpdateAutoScalingGroup": "autoscaling",+ "DeleteAutoScalingGroup": "autoscaling",+ "CreateLaunchConfiguration": "autoscaling",+ "DescribeLaunchConfigurations": "autoscaling","DeleteLaunchConfiguration": "autoscaling",- "PutScalingPolicy": "autoscaling", "DescribePolicies": "autoscaling",+ "PutScalingPolicy": "autoscaling",+ "DescribePolicies": "autoscaling","DeletePolicy": "autoscaling",- "PutLifecycleHook": "autoscaling", "DescribeLifecycleHooks": "autoscaling",+ "PutLifecycleHook": "autoscaling",+ "DescribeLifecycleHooks": "autoscaling","DeleteLifecycleHook": "autoscaling",- "PutScheduledUpdateGroupAction": "autoscaling", "DescribeScheduledActions": "autoscaling",+ "PutScheduledUpdateGroupAction": "autoscaling",+ "DescribeScheduledActions": "autoscaling","DeleteScheduledAction": "autoscaling","DescribeAutoScalingInstances": "autoscaling",}@@ -586,6 +743,8 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->return "imds"if path_lower.startswith("/v1/apis") or path_lower.startswith("/v1/tags/arn:aws:appsync"):return "appsync"+ if path_lower.startswith("/key-value-stores/"):+ return "cloudfront-keyvaluestore"if path_lower.startswith("/2020-05-31/"):return "cloudfront"if path_lower.startswith("/2013-04-01/"):@@ -596,8 +755,12 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->return "appsync-events"if path_lower.startswith("/v2/apis"):return "apigateway"- if (path_lower.startswith("/restapis") or path_lower.startswith("/apikeys")- or path_lower.startswith("/usageplans") or path_lower.startswith("/domainnames")):+ if (+ path_lower.startswith("/restapis")+ or path_lower.startswith("/apikeys")+ or path_lower.startswith("/usageplans")+ or path_lower.startswith("/domainnames")+ ):return "apigateway"if _LAMBDA_PATH_RE.match(path_lower):return "lambda"@@ -647,4 +810,5 @@ def extract_account_id(headers: dict) -> str:"""Extract account ID from credentials or env var.If the access key is a 12-digit number, use it as the account ID."""from ministack.core.responses import get_account_id+return get_account_id()diff --git a/ministack/services/cloudfront_keyvaluestore.py b/ministack/services/cloudfront_keyvaluestore.pynew file mode 100644index 00000000..df8a77e3--- /dev/null+++ b/ministack/services/cloudfront_keyvaluestore.py@@ -0,0 +1,301 @@+"""+CloudFront KeyValueStore Data-Plane Service Emulator.+JSON REST API — signing name: cloudfront-keyvaluestore.++Paths are under /key-value-stores/{KvsARN}/...++Supports:+ DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys+"""++import copy+import json+import logging+import re+from urllib.parse import unquote++from ministack.core.persistence import load_state+from ministack.core.responses import AccountScopedDict, json_response, new_uuid++logger = logging.getLogger("cloudfront-keyvaluestore")++# ---------------------------------------------------------------------------+# Path regexes — ARN contains a slash (e.g. arn:aws:cloudfront::123:key-value-store/name)+# The store name portion ([a-zA-Z0-9-_]+) never contains a slash, so we anchor+# the /keys boundary against the name segment to avoid ambiguity.+# ---------------------------------------------------------------------------+_KEY_RE = re.compile(r"^/key-value-stores/(arn:.+?/[a-zA-Z0-9_-]+)/keys/(.+)$")+_KEYS_RE = re.compile(r"^/key-value-stores/(arn:.+?/[a-zA-Z0-9_-]+)/keys/?$")+_STORE_RE = re.compile(r"^/key-value-stores/(arn:.+)$")++# ---------------------------------------------------------------------------+# In-memory state — keyed by KVS ARN+# ---------------------------------------------------------------------------+_stores = AccountScopedDict() # arn -> {"etag": str, "items": {key: value}}+++def reset():+ _stores.clear()+++def get_state():+ return copy.deepcopy({"stores": _stores})+++def restore_state(data):+ if not data:+ return+ _stores.clear()+ for k, v in (data.get("stores") or {}).items():+ _stores[k] = v+++try:+ _restored = load_state("cloudfront_keyvaluestore")+ if _restored:+ restore_state(_restored)+except Exception:+ logging.getLogger(__name__).exception("Failed to restore persisted state; continuing with fresh store")+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _error(code: str, message: str, status: int) -> tuple:+ body = json.dumps({"Message": message, "__type": code}).encode()+ return status, {"Content-Type": "application/json"}, body+++def _get_store(arn: str):+ store = _stores.get(arn)+ if store is None:+ from ministack.services.cloudfront import _kvstores++ kvs = None+ for v in _kvstores.values():+ if v["ARN"] == arn:+ kvs = v+ break+ if kvs is None:+ return None+ store = {"etag": new_uuid(), "items": {}}+ _stores[arn] = store+ return store+++def _compute_size(items: dict) -> int:+ total = 0+ for k, v in items.items():+ total += len(k.encode("utf-8")) + len(v.encode("utf-8"))+ return total+++# ---------------------------------------------------------------------------+# Request dispatcher+# ---------------------------------------------------------------------------+++async def handle_request(method, path, headers, body, query_params):+ logger.debug("%s %s", method, path)++ m = _KEY_RE.match(path)+ if m:+ arn = unquote(m.group(1))+ key = unquote(m.group(2))+ if method == "GET":+ return _get_key(arn, key)+ if method == "PUT":+ return _put_key(arn, key, headers, body)+ if method == "DELETE":+ return _delete_key(arn, key, headers)++ m = _KEYS_RE.match(path)+ if m:+ arn = unquote(m.group(1))+ if method == "GET":+ return _list_keys(arn, query_params)+ if method == "POST":+ return _update_keys(arn, headers, body)++ m = _STORE_RE.match(path)+ if m:+ arn = unquote(m.group(1))+ if method == "GET":+ return _describe_store(arn)++ return _error("InvalidRequestException", f"No route for {method} {path}", 400)+++# ---------------------------------------------------------------------------+# Handlers+# ---------------------------------------------------------------------------+++def _describe_store(arn: str):+ store = _get_store(arn)+ if store is None:+ return _error("ResourceNotFoundException", f"Key value store {arn} was not found.", 404)++ from ministack.services.cloudfront import _kvstores++ kvs_meta = None+ for v in _kvstores.values():+ if v["ARN"] == arn:+ kvs_meta = v+ break++ items = store["items"]+ resp = {+ "KvsARN": arn,+ "ItemCount": len(items),+ "TotalSizeInBytes": _compute_size(items),+ "Status": "READY",+ "Created": 0,+ "LastModified": 0,+ }+ if kvs_meta and kvs_meta.get("LastModifiedTime"):+ resp["Created"] = 0+ resp["LastModified"] = 0++ return 200, {"Content-Type": "application/json", "ETag": store["etag"]}, json.dumps(resp).encode()+++def _list_keys(arn: str, query_params):+ store = _get_store(arn)+ if store is None:+ return _error("ResourceNotFoundException", f"Key value store {arn} was not found.", 404)++ max_results = (+ int((query_params.get("MaxResults") or [None])[0] or "10")+ if isinstance(query_params.get("MaxResults"), list)+ else int(query_params.get("MaxResults", "10") or "10")+ )+ next_token = None+ if isinstance(query_params.get("NextToken"), list):+ next_token = query_params["NextToken"][0] if query_params["NextToken"] else None+ elif isinstance(query_params.get("NextToken"), str):+ next_token = query_params["NextToken"] or None++ all_keys = sorted(store["items"].keys())+ start_idx = 0+ if next_token and next_token in all_keys:+ start_idx = all_keys.index(next_token)++ page = all_keys[start_idx : start_idx + max_results]+ items = [{"Key": k, "Value": store["items"][k]} for k in page]++ resp = {"Items": items}+ if start_idx + max_results < len(all_keys):+ resp["NextToken"] = all_keys[start_idx + max_results]++ return json_response(resp)+++def _get_key(arn: str, key: str):+ store = _get_store(arn)+ if store is None:+ return _error("ResourceNotFoundException", f"Key value store {arn} was not found.", 404)++ value = store["items"].get(key)+ if value is None:+ return _error("ResourceNotFoundException", f"Key {key} was not found.", 404)++ resp = {+ "Key": key,+ "Value": value,+ "ItemCount": len(store["items"]),+ "TotalSizeInBytes": _compute_size(store["items"]),+ }+ return json_response(resp)+++def _put_key(arn: str, key: str, headers, body):+ store = _get_store(arn)+ if store is None:+ return _error("ResourceNotFoundException", f"Key value store {arn} was not found.", 404)++ if_match = headers.get("if-match")+ if not if_match:+ return _error("ValidationException", "If-Match header is required.", 400)+ if if_match != store["etag"]:+ return _error("ConflictException", "The provided If-Match value does not match the current ETag.", 409)++ try:+ data = json.loads(body) if body else {}+ except (json.JSONDecodeError, TypeError):+ return _error("ValidationException", "Invalid JSON body.", 400)++ value = data.get("Value")+ if value is None:+ return _error("ValidationException", "Value is required.", 400)++ store["items"][key] = value+ store["etag"] = new_uuid()++ resp = {+ "ItemCount": len(store["items"]),+ "TotalSizeInBytes": _compute_size(store["items"]),+ }+ return 200, {"Content-Type": "application/json", "ETag": store["etag"]}, json.dumps(resp).encode()+++def _delete_key(arn: str, key: str, headers):+ store = _get_store(arn)+ if store is None:+ return _error("ResourceNotFoundException", f"Key value store {arn} was not found.", 404)++ if_match = headers.get("if-match")+ if not if_match:+ return _error("ValidationException", "If-Match header is required.", 400)+ if if_match != store["etag"]:+ return _error("ConflictException", "The provided If-Match value does not match the current ETag.", 409)++ store["items"].pop(key, None)+ store["etag"] = new_uuid()++ resp = {+ "ItemCount": len(store["items"]),+ "TotalSizeInBytes": _compute_size(store["items"]),+ }+ return 200, {"Content-Type": "application/json", "ETag": store["etag"]}, json.dumps(resp).encode()+++def _update_keys(arn: str, headers, body):+ store = _get_store(arn)+ if store is None:+ return _error("ResourceNotFoundException", f"Key value store {arn} was not found.", 404)++ if_match = headers.get("if-match")+ if not if_match:+ return _error("ValidationException", "If-Match header is required.", 400)+ if if_match != store["etag"]:+ return _error("ConflictException", "The provided If-Match value does not match the current ETag.", 409)++ try:+ data = json.loads(body) if body else {}+ except (json.JSONDecodeError, TypeError):+ return _error("ValidationException", "Invalid JSON body.", 400)++ puts = data.get("Puts", [])+ deletes = data.get("Deletes", [])++ for item in puts:+ k = item.get("Key")+ v = item.get("Value")+ if k is not None and v is not None:+ store["items"][k] = v++ for item in deletes:+ k = item.get("Key")+ if k is not None:+ store["items"].pop(k, None)++ store["etag"] = new_uuid()++ resp = {+ "ItemCount": len(store["items"]),+ "TotalSizeInBytes": _compute_size(store["items"]),+ }+ return 200, {"Content-Type": "application/json", "ETag": store["etag"]}, json.dumps(resp).encode()diff --git a/tests/conftest.py b/tests/conftest.pyindex 9b039c66..74bb98cf 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,6 +1,7 @@"""Pytest fixtures for MiniStack integration tests."""+import contextlibimport osimport socket@@ -21,11 +22,11 @@ _default_kwargs = dict(aws_secret_access_key="test",region_name=REGION,)- # Hardcoded retry and pool settings to reduce transient connection flakes+# Hardcoded retry and pool settings to reduce transient connection flakes_default_config_kwargs = dict(- region_name=REGION,- retries={"mode": "standard"},- max_pool_connections=50,+ region_name=REGION,+ retries={"mode": "standard"},+ max_pool_connections=50,)@@ -112,26 +113,32 @@ def reset_server():def s3():return make_client("s3")+@pytest.fixture(scope="session")def sqs():return make_client("sqs")+@pytest.fixture(scope="session")def sns():return make_client("sns")+@pytest.fixture(scope="session")def ddb():return make_client("dynamodb")+@pytest.fixture(scope="session")def ddb_streams():return make_client("dynamodbstreams")+@pytest.fixture(scope="session")def sts():return make_client("sts")+@pytest.fixturedef sts_as_role(sts):def _make(role_arn, session_name="test-session"):@@ -145,68 +152,85 @@ def sts_as_role(sts):region_name=REGION,config=Config(retries={"mode": "standard"}),)+return _make+@pytest.fixture(scope="session")def sm():return make_client("secretsmanager")+@pytest.fixture(scope="session")def logs():return make_client("logs")+@pytest.fixture(scope="session")def lam():return make_client("lambda")+@pytest.fixture(scope="session")def iam():return make_client("iam")+@pytest.fixture(scope="session")def ssm():return make_client("ssm")+@pytest.fixture(scope="session")def eb():return make_client("events")+@pytest.fixture(scope="session")def kin():return make_client("kinesis")+@pytest.fixture(scope="session")def cw():return make_client("cloudwatch")+@pytest.fixture(scope="session")def ses():return make_client("ses")+@pytest.fixture(scope="session")def sfn():return make_client("stepfunctions")+@pytest.fixture(scope="session")def ecs():return make_client("ecs")+@pytest.fixture(scope="session")def rds():return make_client("rds")+@pytest.fixture(scope="session")def ecr():return make_client("ecr")+@pytest.fixture(scope="session")def ec():return make_client("elasticache")+@pytest.fixture(scope="session")def glue():return make_client("glue")+@pytest.fixture(scope="session")def athena():return make_client("athena")@@ -215,6 +239,7 @@ def athena():def _ministack_config(settings):"""Set runtime config on the running server via POST /_ministack/config."""import json+req = urllib.request.Request(f"{ENDPOINT}/_ministack/config",data=json.dumps(settings).encode(),@@ -228,66 +253,82 @@ def _ministack_config(settings):def fh():return make_client("firehose")+@pytest.fixture(scope="session")def apigw():return make_client("apigatewayv2")+@pytest.fixture(scope="session")def apigw_v1():return make_client("apigateway")+@pytest.fixture(scope="session")def r53():return make_client("route53")+@pytest.fixture(scope="session")def cognito_idp():return make_client("cognito-idp")+@pytest.fixture(scope="session")def cognito_identity():return make_client("cognito-identity")+@pytest.fixture(scope="session")def ec2():return make_client("ec2")+@pytest.fixture(scope="session")def emr():return make_client("emr")+@pytest.fixture(scope="session")def elbv2():return make_client("elbv2")-++@pytest.fixture(scope="session")def efs():return make_client("efs")+@pytest.fixture(scope="session")def acm_client():return make_client("acm")+@pytest.fixture(scope="session")def wafv2():return make_client("wafv2")+@pytest.fixture(scope="session")def sesv2():return make_client("sesv2")+@pytest.fixture(scope="session")def cfn():return make_client("cloudformation")+@pytest.fixture(scope="session")def kms_client():return make_client("kms")+@pytest.fixture(scope="session")def sfn_sync():"""SFN client for StartSyncExecution — forces same endpoint (boto3 normally prefixes sync-)."""from botocore.config import Config as BotoConfig+return boto3.client("stepfunctions",endpoint_url=ENDPOINT,@@ -302,26 +343,53 @@ def sfn_sync():),)+@pytest.fixture(scope="session")def cloudfront():return make_client("cloudfront")+[email protected](scope="session")+def cloudfront_kvs():+ from botocore import UNSIGNED+ from botocore.config import Config as BotoConfig++ return boto3.client(+ "cloudfront-keyvaluestore",+ endpoint_url=ENDPOINT,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ region_name=REGION,+ config=BotoConfig(+ region_name=REGION,+ signature_version=UNSIGNED,+ retries={"mode": "standard"},+ max_pool_connections=50,+ inject_host_prefix=False,+ ),+ )++@pytest.fixture(scope="session")def rds_data():return make_client("rds-data")+@pytest.fixture(scope="session")def appconfig_client():return make_client("appconfig")+@pytest.fixture(scope="session")def appconfigdata_client():return make_client("appconfigdata")+@pytest.fixture(scope="session")def sd():"""SD client for DiscoverInstances — forces same endpoint (boto3 normally prefixes data-)."""from botocore.config import Config as BotoConfig+return boto3.client("servicediscovery",endpoint_url=ENDPOINT,@@ -336,30 +404,37 @@ def sd():),)+@pytest.fixture(scope="session")def codebuild():return make_client("codebuild")+@pytest.fixture(scope="session")def autoscaling():return make_client("autoscaling")+@pytest.fixture(scope="session")def transfer():return make_client("transfer")+@pytest.fixture(scope="session")def eks():return make_client("eks")+@pytest.fixture(scope="session")def appsync():return make_client("appsync")+@pytest.fixture(scope="session")def scheduler():return make_client("scheduler")+@pytest.fixture(scope="session")def tagging():return make_client("resourcegroupstaggingapi")diff --git a/tests/test_cloudfront_kvs.py b/tests/test_cloudfront_kvs.pynew file mode 100644index 00000000..bea52edb--- /dev/null+++ b/tests/test_cloudfront_kvs.py@@ -0,0 +1,178 @@+import json+import uuid as _uuid_mod++import pytest+from botocore.exceptions import ClientError+++def test_kvs_dataplane_describe(cloudfront, cloudfront_kvs):+ name = f"dp-desc-{_uuid_mod.uuid4().hex[:8]}"+ create_resp = cloudfront.create_key_value_store(Name=name, Comment="describe test")+ arn = create_resp["KeyValueStore"]["ARN"]++ resp = cloudfront_kvs.describe_key_value_store(KvsARN=arn)+ assert resp["KvsARN"] == arn+ assert resp["ItemCount"] == 0+ assert resp["TotalSizeInBytes"] == 0+ assert resp["Status"] == "READY"+ assert "etag" in resp["ResponseMetadata"]["HTTPHeaders"]+++def test_kvs_dataplane_put_and_get_key(cloudfront, cloudfront_kvs):+ name = f"dp-put-{_uuid_mod.uuid4().hex[:8]}"+ create_resp = cloudfront.create_key_value_store(Name=name, Comment="put/get test")+ arn = create_resp["KeyValueStore"]["ARN"]++ desc = cloudfront_kvs.describe_key_value_store(KvsARN=arn)+ etag = desc["ResponseMetadata"]["HTTPHeaders"]["etag"]++ put_resp = cloudfront_kvs.put_key(KvsARN=arn, Key="route/home", Value="/index.html", IfMatch=etag)+ assert put_resp["ItemCount"] == 1+ assert put_resp["TotalSizeInBytes"] > 0+ new_etag = put_resp["ResponseMetadata"]["HTTPHeaders"]["etag"]+ assert new_etag != etag++ get_resp = cloudfront_kvs.get_key(KvsARN=arn, Key="route/home")+ assert get_resp["Key"] == "route/home"+ assert get_resp["Value"] == "/index.html"+ assert get_resp["ItemCount"] == 1+++def test_kvs_dataplane_delete_key(cloudfront, cloudfront_kvs):+ name = f"dp-del-{_uuid_mod.uuid4().hex[:8]}"+ create_resp = cloudfront.create_key_value_store(Name=name, Comment="delete test")+ arn = create_resp["KeyValueStore"]["ARN"]++ desc = cloudfront_kvs.describe_key_value_store(KvsARN=arn)+ etag = desc["ResponseMetadata"]["HTTPHeaders"]["etag"]++ put_resp = cloudfront_kvs.put_key(KvsARN=arn, Key="to-delete", Value="val", IfMatch=etag)+ etag = put_resp["ResponseMetadata"]["HTTPHeaders"]["etag"]++ del_resp = cloudfront_kvs.delete_key(KvsARN=arn, Key="to-delete", IfMatch=etag)+ assert del_resp["ItemCount"] == 0++ with pytest.raises(ClientError) as exc:+ cloudfront_kvs.get_key(KvsARN=arn, Key="to-delete")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_kvs_dataplane_list_keys(cloudfront, cloudfront_kvs):+ name = f"dp-list-{_uuid_mod.uuid4().hex[:8]}"+ create_resp = cloudfront.create_key_value_store(Name=name, Comment="list test")+ arn = create_resp["KeyValueStore"]["ARN"]++ desc = cloudfront_kvs.describe_key_value_store(KvsARN=arn)+ etag = desc["ResponseMetadata"]["HTTPHeaders"]["etag"]++ put_resp = cloudfront_kvs.put_key(KvsARN=arn, Key="key-a", Value="val-a", IfMatch=etag)+ etag = put_resp["ResponseMetadata"]["HTTPHeaders"]["etag"]+ put_resp = cloudfront_kvs.put_key(KvsARN=arn, Key="key-b", Value="val-b", IfMatch=etag)+ etag = put_resp["ResponseMetadata"]["HTTPHeaders"]["etag"]+ cloudfront_kvs.put_key(KvsARN=arn, Key="key-c", Value="val-c", IfMatch=etag)++ resp = cloudfront_kvs.list_keys(KvsARN=arn)+ keys = [item["Key"] for item in resp["Items"]]+ assert "key-a" in keys+ assert "key-b" in keys+ assert "key-c" in keys+++def test_kvs_dataplane_update_keys(cloudfront, cloudfront_kvs):+ name = f"dp-upd-{_uuid_mod.uuid4().hex[:8]}"+ create_resp = cloudfront.create_key_value_store(Name=name, Comment="update keys test")+ arn = create_resp["KeyValueStore"]["ARN"]++ desc = cloudfront_kvs.describe_key_value_store(KvsARN=arn)+ etag = desc["ResponseMetadata"]["HTTPHeaders"]["etag"]++ put_resp = cloudfront_kvs.put_key(KvsARN=arn, Key="existing", Value="old", IfMatch=etag)+ etag = put_resp["ResponseMetadata"]["HTTPHeaders"]["etag"]++ resp = cloudfront_kvs.update_keys(+ KvsARN=arn,+ IfMatch=etag,+ Puts=[+ {"Key": "new-key", "Value": "new-val"},+ {"Key": "existing", "Value": "updated"},+ ],+ Deletes=[],+ )+ assert resp["ItemCount"] == 2++ get_resp = cloudfront_kvs.get_key(KvsARN=arn, Key="existing")+ assert get_resp["Value"] == "updated"++ get_resp = cloudfront_kvs.get_key(KvsARN=arn, Key="new-key")+ assert get_resp["Value"] == "new-val"+++def test_kvs_dataplane_update_keys_with_deletes(cloudfront, cloudfront_kvs):+ name = f"dp-upddel-{_uuid_mod.uuid4().hex[:8]}"+ create_resp = cloudfront.create_key_value_store(Name=name, Comment="update+delete test")+ arn = create_resp["KeyValueStore"]["ARN"]++ desc = cloudfront_kvs.describe_key_value_store(KvsARN=arn)+ etag = desc["ResponseMetadata"]["HTTPHeaders"]["etag"]++ put_resp = cloudfront_kvs.put_key(KvsARN=arn, Key="keep", Value="yes", IfMatch=etag)+ etag = put_resp["ResponseMetadata"]["HTTPHeaders"]["etag"]+ put_resp = cloudfront_kvs.put_key(KvsARN=arn, Key="remove", Value="bye", IfMatch=etag)+ etag = put_resp["ResponseMetadata"]["HTTPHeaders"]["etag"]++ resp = cloudfront_kvs.update_keys(+ KvsARN=arn,+ IfMatch=etag,+ Puts=[{"Key": "added", "Value": "hello"}],+ Deletes=[{"Key": "remove"}],+ )+ assert resp["ItemCount"] == 2++ with pytest.raises(ClientError) as exc:+ cloudfront_kvs.get_key(KvsARN=arn, Key="remove")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++ get_resp = cloudfront_kvs.get_key(KvsARN=arn, Key="added")+ assert get_resp["Value"] == "hello"+++def test_kvs_dataplane_etag_conflict(cloudfront, cloudfront_kvs):+ name = f"dp-conflict-{_uuid_mod.uuid4().hex[:8]}"+ create_resp = cloudfront.create_key_value_store(Name=name, Comment="conflict test")+ arn = create_resp["KeyValueStore"]["ARN"]++ with pytest.raises(ClientError) as exc:+ cloudfront_kvs.put_key(KvsARN=arn, Key="x", Value="y", IfMatch="wrong-etag")+ assert exc.value.response["Error"]["Code"] == "ConflictException"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409+++def test_kvs_dataplane_not_found(cloudfront_kvs):+ fake_arn = "arn:aws:cloudfront::000000000000:key-value-store/nonexistent"+ with pytest.raises(ClientError) as exc:+ cloudfront_kvs.describe_key_value_store(KvsARN=fake_arn)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+++def test_kvs_dataplane_list_keys_pagination(cloudfront, cloudfront_kvs):+ name = f"dp-page-{_uuid_mod.uuid4().hex[:8]}"+ create_resp = cloudfront.create_key_value_store(Name=name, Comment="pagination test")+ arn = create_resp["KeyValueStore"]["ARN"]++ desc = cloudfront_kvs.describe_key_value_store(KvsARN=arn)+ etag = desc["ResponseMetadata"]["HTTPHeaders"]["etag"]++ for i in range(5):+ put_resp = cloudfront_kvs.put_key(KvsARN=arn, Key=f"k{i:02d}", Value=f"v{i}", IfMatch=etag)+ etag = put_resp["ResponseMetadata"]["HTTPHeaders"]["etag"]++ resp = cloudfront_kvs.list_keys(KvsARN=arn, MaxResults=2)+ assert len(resp["Items"]) == 2+ assert "NextToken" in resp++ resp2 = cloudfront_kvs.list_keys(KvsARN=arn, MaxResults=2, NextToken=resp["NextToken"])+ assert len(resp2["Items"]) == 2++ all_keys = [item["Key"] for item in resp["Items"] + resp2["Items"]]+ assert len(set(all_keys)) == 4