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
prerelease: validate partiy + adjustment (#1792)
Nahuel Nucerac27f926ad376
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1b4d6057..1dcff345 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -127,6 +127,8 @@ jobs:DOCKER_NETWORK: ministack-data-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.shard_index }}LAMBDA_EXECUTOR: dockerOPENSEARCH_DATAPLANE: "1"+ DSQL_STRICT: "1"+ MINISTACK_RDS_PG_CLUSTER_REPLICATION: "1"services:redis:image: redis:7-alpine@@ -142,6 +144,8 @@ jobs:with:python-version: "3.13"+ # Pinned to a full version: setup-uv stopped publishing floating major+ # tags after v7, so there is no `@v10` to track.- uses: astral-sh/[email protected]with:enable-cache: truediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1892ae9d..c9fa7e66 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,7 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed-- **RDS — PostgreSQL TLS with long endpoint names** — use a short certificate common name while retaining complete DNS and IP subject alternative names, so endpoints longer than 64 bytes no longer fail certificate generation.+- **KMS — imported key material for HMAC and asymmetric keys** — `CreateKey` with `Origin=EXTERNAL` refused every spec but `SYMMETRIC_DEFAULT`, where AWS supports imported material for symmetric encryption, HMAC and asymmetric keys, ML-DSA excepted. HMAC material is the raw bytes of the spec's length and asymmetric material is the private key alone, DER-encoded PKCS#8, from which the public key is derived; material that does not match the key's `KeySpec` answers `IncorrectKeyMaterialException`, and `GetPublicKey` on a key still awaiting material answers `KMSInvalidStateException`. Reported by @guymahieu.+- **RDS — the server certificate carries the endpoint AWS puts in it** — certificate generation raised `ValueError` once an endpoint passed the X.509 64-byte common-name bound, so a database with a long identifier could not start. The common name is now the advertised endpoint at its full length, the subject carries `OU=RDS, O=Amazon.com, L=Seattle, ST=Washington, C=US`, and the signing CA is named `Amazon RDS <region> Root CA RSA2048 G1`, matching a certificate captured from a real instance. Reported by @jayjanssen.- **API Gateway — an OpenAPI body's `securityDefinitions` reach the methods** — the import discarded security outright, so a SAM API declaring a Cognito authorizer created none and every method imported as `authorizationType: NONE`, serving anonymous callers where AWS answers 401. Each scheme carrying `x-amazon-apigateway-authorizer` now becomes an authorizer, and an operation's `security` — or the document's — sets the method's `authorizationType`, `authorizerId` and `authorizationScopes`, so the enforcement added in 1.5.10 engages for body-defined APIs.- **CloudFormation — `AWS::ApiGateway::Stage` method settings reach the stage as a map** — the template's `MethodSettings` list was stored verbatim, so the throttling lookup added in 1.5.14 raised on it and every request to a CloudFormation- or SAM-deployed API answered 500. The list is now keyed `"<resourcePath>/<httpMethod>"`, `"*/*"` for the stage-wide entry, over the account-level defaults AWS reports from `GetStage`.diff --git a/ministack/app.py b/ministack/app.pyindex da19e02f..77fa2b3a 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2493,11 +2493,9 @@ async def app(scope, receive, send):# Credential-bearing broker requests bypass generic body decoding, routing# and tenant inference. The capability, not a client claim, selects RDS.if scope["path"] == "/_ministack/rds/iam-auth":- from ministack.core import rds_iam_broker+ from ministack.core import rds_iam- async with _get_reset_lock():- pass- await rds_iam_broker.handle(scope, receive, send, auth_enabled=AUTH)+ await rds_iam.handle(scope, receive, send, auth_enabled=AUTH)returnmethod = scope["method"]diff --git a/ministack/core/rds_iam.py b/ministack/core/rds_iam.pyindex 7f81470a..e29e56b6 100644--- a/ministack/core/rds_iam.py+++ b/ministack/core/rds_iam.py@@ -6,12 +6,20 @@ This module has no runtime callers and does not consult AUTH. Later integrationmust explicitly gate authentication/authorization at the call site and definethe AUTH=false behavior; adding this primitive changes no existing request path.Resource enablement, rds-db:connect policies, and TLS are separate checks.++The broker half serves POST /_ministack/rds/iam-auth for the MySQL plugin.+Capabilities are process-local, never persisted, never issued over HTTP; AUTH+gates IAM enforcement only, not capability checks or resource enablement."""+import asyncioimport datetime as dtimport hashlib+import jsonimport mathimport re+import secrets+import threadingimport timefrom dataclasses import dataclassfrom urllib.parse import parse_qsl, urlsplit@@ -296,3 +304,167 @@ def authorize_rds_iam_token(if result.decision != "Allow":return RdsIamAuthorizationError(result.decision)return AuthorizedRdsConnection(verified, resource_arn)+++PATH = "/_ministack/rds/iam-auth"+MAX_BODY = 70 * 1024+BODY_TIMEOUT = 5+_lock = threading.RLock()+_bindings = {}+++@dataclass(frozen=True, repr=False)+class _Binding:+ account_id: str+ region: str+ resource_kind: str+ resource_identifier: str+ reader_endpoint: bool+ target: dict+ owner: dict+ resource_id: str+++def _resources(account_id, region, resource_kind, resource_identifier):+ from ministack.services import rds++ store = rds._instances if resource_kind == "instance" else rds._clusters+ target = store.get_scoped(account_id, region, resource_identifier)+ if not target or target.get("Engine") not in ("mysql", "aurora", "aurora-mysql"):+ return None, None+ owner = target+ if resource_kind == "instance" and target.get("DBClusterIdentifier"):+ owner = rds._clusters.get_scoped(account_id, region, target["DBClusterIdentifier"])+ if not owner or owner.get("Engine") not in ("aurora", "aurora-mysql"):+ return None, None+ elif target.get("Engine") != "mysql" and resource_kind == "instance":+ return None, None+ if resource_kind == "cluster" and target.get("Engine") == "mysql":+ return None, None+ return target, owner+++def _resource_id(target, owner, kind):+ return owner.get("DbClusterResourceId" if kind == "cluster" or owner is not target else "DbiResourceId")+++def issue_capability(*, account_id, region, resource_kind, resource_identifier, reader_endpoint=False):+ """In-process only; rotates this binding's capability. Re-issue after a+ restart or a resource replacement."""+ if (resource_kind not in ("instance", "cluster") or not account_id or not region+ or type(reader_endpoint) is not bool or (reader_endpoint and resource_kind != "cluster")):+ raise ValueError("Invalid RDS target")+ with _lock:+ target, owner = _resources(account_id, region, resource_kind, resource_identifier)+ resource_id = _resource_id(target, owner, resource_kind) if owner is not None else None+ if not resource_id:+ raise ValueError("Invalid RDS target")+ for digest, binding in list(_bindings.items()):+ if (binding.account_id, binding.region, binding.resource_kind, binding.resource_identifier,+ binding.reader_endpoint) == (account_id, region, resource_kind, resource_identifier, reader_endpoint):+ del _bindings[digest]+ capability = secrets.token_hex(32)+ _bindings[hashlib.sha256(capability.encode()).digest()] = _Binding(+ account_id, region, resource_kind, resource_identifier, reader_endpoint, target, owner, resource_id,+ )+ return capability+++def revoke_capability(capability):+ with _lock:+ _bindings.pop(hashlib.sha256(capability.encode()).digest(), None)+++def reset():+ with _lock:+ _bindings.clear()+++def _binding_current(binding):+ target, owner = _resources(binding.account_id, binding.region, binding.resource_kind,+ binding.resource_identifier)+ return (target is binding.target and owner is binding.owner+ and _resource_id(target, owner, binding.resource_kind) == binding.resource_id+ and owner.get("IAMDatabaseAuthenticationEnabled") is True)+++def _decision(capability, payload, auth_enabled):+ with _lock:+ binding = _bindings.get(hashlib.sha256(capability).digest())+ if binding is None:+ return False+ if not _binding_current(binding):+ return False+ if not auth_enabled:+ return True+ result = authorize_rds_iam_token(+ payload["token"], account_id=binding.account_id, region=binding.region,+ resource_kind=binding.resource_kind, resource_identifier=binding.resource_identifier,+ reader_endpoint=binding.reader_endpoint, db_user=payload["username"],+ )+ # RDS lifecycle workers do not hold the broker lock. Authorization+ # looks up state independently, so discard its result if the resource+ # or its owner was replaced or disabled while that lookup ran.+ return isinstance(result, AuthorizedRdsConnection) and _binding_current(binding)+++def _unique_object(pairs):+ result = {}+ for key, value in pairs:+ if key in result:+ raise ValueError("Duplicate field")+ result[key] = value+ return result+++async def _read_body(receive):+ body = bytearray()+ while True:+ message = await receive()+ if message["type"] != "http.request":+ raise ValueError("Disconnected")+ chunk = message.get("body", b"")+ if len(body) + len(chunk) > MAX_BODY:+ raise ValueError("Oversized request")+ body.extend(chunk)+ if not message.get("more_body", False):+ return bytes(body)+++async def handle(scope, receive, send, *, auth_enabled):+ """POST {username, token} with X-Ministack-RDS-Capability. Never logs request+ data: transport or schema failures deny, even in permissive mode."""+ status, allowed = 403, False+ try:+ headers = {}+ for name, value in scope.get("headers", []):+ name = name.lower()+ if name in headers:+ raise ValueError("Duplicate header")+ headers[name] = value+ capability = headers.get(b"x-ministack-rds-capability", b"")+ if (scope["method"] != "POST" or scope.get("query_string")+ or len(capability) != 64 or any(c not in b"0123456789abcdef" for c in capability)+ or headers.get(b"content-type", b"").split(b";", 1)[0].strip().lower() != b"application/json"+ or b"content-encoding" in headers):+ raise ValueError("Invalid request")+ with _lock:+ if hashlib.sha256(capability).digest() not in _bindings:+ raise ValueError("Invalid capability")+ body = await asyncio.wait_for(_read_body(receive), timeout=BODY_TIMEOUT)+ payload = json.loads(body.decode("utf-8"), object_pairs_hook=_unique_object)+ if (not isinstance(payload, dict) or payload.keys() != {"username", "token"}+ or not isinstance(payload["username"], str) or not 1 <= len(payload["username"]) <= 256+ or "\x00" in payload["username"] or not isinstance(payload["token"], str)+ or len(payload["token"]) > 65536):+ raise ValueError("Invalid payload")+ allowed = _decision(capability, payload, auth_enabled)+ status = 200 if allowed else 403+ except Exception:+ # Even unexpected verifier failures must not leak tokens through logs+ # or turn a failed request into an allow response.+ pass+ await send({"type": "http.response.start", "status": status, "headers": [+ (b"content-type", b"application/json"), (b"cache-control", b"no-store"),+ ]})+ await send({"type": "http.response.body", "body": b'{"allowed":true}' if allowed else b'{"allowed":false}'})diff --git a/ministack/core/rds_iam_broker.py b/ministack/core/rds_iam_broker.pydeleted file mode 100644index 5b3f37dc..00000000--- a/ministack/core/rds_iam_broker.py+++ /dev/null@@ -1,186 +0,0 @@-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT-# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).-"""Internal stage-6 broker (#1744). Capability provisioning is stage 8.--Capabilities are process-local, never persisted, and never issued over HTTP.-AUTH controls IAM enforcement, not capability protection or resource enablement.-No plugin/container calls this endpoint yet.-"""--import asyncio-import hashlib-import json-import secrets-import threading-from dataclasses import dataclass--from ministack.core.rds_iam import AuthorizedRdsConnection, authorize_rds_iam_token--PATH = "/_ministack/rds/iam-auth"-MAX_BODY = 70 * 1024-BODY_TIMEOUT = 5-_lock = threading.RLock()-_bindings = {}---@dataclass(frozen=True, repr=False)-class _Binding:- account_id: str- region: str- resource_kind: str- resource_identifier: str- reader_endpoint: bool- target: dict- owner: dict- resource_id: str---def _resources(account_id, region, resource_kind, resource_identifier):- from ministack.services import rds-- store = rds._instances if resource_kind == "instance" else rds._clusters- target = store.get_scoped(account_id, region, resource_identifier)- if not target or target.get("Engine") not in ("mysql", "aurora", "aurora-mysql"):- return None, None- owner = target- if resource_kind == "instance" and target.get("DBClusterIdentifier"):- owner = rds._clusters.get_scoped(account_id, region, target["DBClusterIdentifier"])- if not owner or owner.get("Engine") not in ("aurora", "aurora-mysql"):- return None, None- elif target.get("Engine") != "mysql" and resource_kind == "instance":- return None, None- if resource_kind == "cluster" and target.get("Engine") == "mysql":- return None, None- return target, owner---def _resource_id(target, owner, kind):- return owner.get("DbClusterResourceId" if kind == "cluster" or owner is not target else "DbiResourceId")---def issue_capability(*, account_id, region, resource_kind, resource_identifier, reader_endpoint=False):- """Trusted in-process API; rotates the capability for this endpoint binding.-- No production callers until container wiring. Call again after restart or- resource replacement; old capabilities cannot authorize recreated resources.- """- if (resource_kind not in ("instance", "cluster") or not account_id or not region- or type(reader_endpoint) is not bool or (reader_endpoint and resource_kind != "cluster")):- raise ValueError("Invalid RDS target")- with _lock:- target, owner = _resources(account_id, region, resource_kind, resource_identifier)- resource_id = _resource_id(target, owner, resource_kind) if owner is not None else None- if not resource_id:- raise ValueError("Invalid RDS target")- for digest, binding in list(_bindings.items()):- if (binding.account_id, binding.region, binding.resource_kind, binding.resource_identifier,- binding.reader_endpoint) == (account_id, region, resource_kind, resource_identifier, reader_endpoint):- del _bindings[digest]- capability = secrets.token_hex(32)- _bindings[hashlib.sha256(capability.encode()).digest()] = _Binding(- account_id, region, resource_kind, resource_identifier, reader_endpoint, target, owner, resource_id,- )- return capability---def revoke_capability(capability):- with _lock:- _bindings.pop(hashlib.sha256(capability.encode()).digest(), None)---def reset():- with _lock:- _bindings.clear()---def _binding_current(binding):- target, owner = _resources(binding.account_id, binding.region, binding.resource_kind,- binding.resource_identifier)- return (target is binding.target and owner is binding.owner- and _resource_id(target, owner, binding.resource_kind) == binding.resource_id- and owner.get("IAMDatabaseAuthenticationEnabled") is True)---def _decision(capability, payload, auth_enabled):- with _lock:- binding = _bindings.get(hashlib.sha256(capability).digest())- if binding is None:- return False- if not _binding_current(binding):- return False- if not auth_enabled:- return True- result = authorize_rds_iam_token(- payload["token"], account_id=binding.account_id, region=binding.region,- resource_kind=binding.resource_kind, resource_identifier=binding.resource_identifier,- reader_endpoint=binding.reader_endpoint, db_user=payload["username"],- )- # RDS lifecycle workers do not hold the broker lock. Authorization- # looks up state independently, so discard its result if the resource- # or its owner was replaced or disabled while that lookup ran.- return isinstance(result, AuthorizedRdsConnection) and _binding_current(binding)---def _unique_object(pairs):- result = {}- for key, value in pairs:- if key in result:- raise ValueError("Duplicate field")- result[key] = value- return result---async def _read_body(receive):- body = bytearray()- while True:- message = await receive()- if message["type"] != "http.request":- raise ValueError("Disconnected")- chunk = message.get("body", b"")- if len(body) + len(chunk) > MAX_BODY:- raise ValueError("Oversized request")- body.extend(chunk)- if not message.get("more_body", False):- return bytes(body)---async def handle(scope, receive, send, *, auth_enabled):- """POST {username, token}, with X-Ministack-RDS-Capability header.-- Transport/schema failures never grant access, even in permissive mode.- Do not log request data or exception details on this credential-bearing path.- """- status, allowed = 403, False- try:- headers = {}- for name, value in scope.get("headers", []):- name = name.lower()- if name in headers:- raise ValueError("Duplicate header")- headers[name] = value- capability = headers.get(b"x-ministack-rds-capability", b"")- if (scope["method"] != "POST" or scope.get("query_string")- or len(capability) != 64 or any(c not in b"0123456789abcdef" for c in capability)- or headers.get(b"content-type", b"").split(b";", 1)[0].strip().lower() != b"application/json"- or b"content-encoding" in headers):- raise ValueError("Invalid request")- with _lock:- if hashlib.sha256(capability).digest() not in _bindings:- raise ValueError("Invalid capability")- body = await asyncio.wait_for(_read_body(receive), timeout=BODY_TIMEOUT)- payload = json.loads(body.decode("utf-8"), object_pairs_hook=_unique_object)- if (not isinstance(payload, dict) or payload.keys() != {"username", "token"}- or not isinstance(payload["username"], str) or not 1 <= len(payload["username"]) <= 256- or "\x00" in payload["username"] or not isinstance(payload["token"], str)- or len(payload["token"]) > 65536):- raise ValueError("Invalid payload")- allowed = _decision(capability, payload, auth_enabled)- status = 200 if allowed else 403- except Exception:- # Even unexpected verifier failures must not leak tokens through logs- # or turn a failed request into an allow response.- pass- await send({"type": "http.response.start", "status": status, "headers": [- (b"content-type", b"application/json"), (b"cache-control", b"no-store"),- ]})- await send({"type": "http.response.body", "body": b'{"allowed":true}' if allowed else b'{"allowed":false}'})diff --git a/ministack/core/router.py b/ministack/core/router.pyindex e0214e63..0cd3c67b 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -37,10 +37,8 @@ _LAMBDA_PATH_RE = re.compile(# apiVersion — `/2026-04-04/network-connectors[/{Identifier}]`._LAMBDA_CORE_PATH_RE = re.compile(r"^/2026-04-04/network-connectors(?:/|$)")-# Lambda MicroVMs uses the Lambda endpoint prefix and, in the AWS CLI version-# currently published for this API, signs requests with the credential scope-# `lambda` rather than a distinct `lambda-microvms` scope. Keep the path-# check available so signed requests are not sent to Lambda's function router.+# The AWS CLI signs MicroVM requests with credential scope `lambda`, so only+# the path separates them from Lambda's function router._LAMBDA_MICROVM_PATH_RE = re.compile(r"^/2025-09-09/(?:microvms|microvm-images)(?:/|$)")@@ -87,9 +85,7 @@ SERVICE_PATTERNS = {"lambda-core": {"path_patterns": [r"^/2026-04-04/network-connectors"],},- # Lambda MicroVMs (2025-09-09) uses a distinct service host, while the- # AWS CLI currently signs the local endpoint with credential scope- # `lambda`; detect the path before the generic Lambda function router.+ # Detected by path: the AWS CLI signs these as `lambda`."lambda-microvms": {"path_patterns": [r"^/2025-09-09/microvm"],"host_patterns": [r"lambda-microvms\."],@@ -730,15 +726,11 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->or path.startswith("/async-invoke")):return "bedrock-runtime"return "bedrock"- # Lambda MicroVMs currently signs as `lambda` in the AWS CLI model,- # even though its API has a distinct service host. Resolve its- # versioned path before the generic Lambda credential-scope return.if svc_name == "lambda" and _LAMBDA_MICROVM_PATH_RE.match(path):return "lambda-microvms"- # Lambda Core also signs as `lambda`: its endpointPrefix AND- # signingName are both `lambda` (botocore lambda-core/2026-04-30),- # so the credential scope cannot distinguish it from the generic- # Lambda and MicroVM surfaces. The path checks must sit+ # Lambda Core also signs as `lambda`: endpointPrefix AND signingName+ # are both `lambda` (botocore lambda-core/2026-04-30), so the scope+ # cannot tell the three apart. The path checks must sit# before the SERVICE_PATTERNS early-return below, or `lambda`# matches there and the request reaches the function router, which# reads `/2026-04-04/network-connectors` as a function name.diff --git a/ministack/core/x509_utils.py b/ministack/core/x509_utils.pyindex 9e98d50e..e0dec800 100644--- a/ministack/core/x509_utils.py+++ b/ministack/core/x509_utils.py@@ -25,6 +25,7 @@ from __future__ import annotationsimport datetime as _dtimport hashlibimport logging+import warningslogger = logging.getLogger("x509_utils")@@ -117,6 +118,7 @@ def sign_leaf_certificate(san_ips: list[str] | None = None,days_valid: int = 825,key_type: str = "rsa2048",+ subject_rdns: list[tuple[str, str]] | None = None,) -> tuple[str, str, str]:"""Generate a fresh keypair and sign a leaf certificate with the given CA.@@ -128,6 +130,8 @@ def sign_leaf_certificate(san_ips: Optional list of IPv4/IPv6 strings to include as SubjectAltName.days_valid: Validity period in days (default 825, AWS-style).key_type: ``"rsa2048"`` (default) or ``"ec256"``.+ subject_rdns: extra subject attributes after the CN, as+ ``[("OU", "RDS"), ("O", "Amazon.com"), ...]`` in wire order.Returns:Tuple ``(cert_pem, private_key_pem, public_key_pem)``.@@ -146,9 +150,20 @@ def sign_leaf_certificate(else:raise ValueError(f"Unsupported key_type: {key_type!r}")- subject = x509.Name([- x509.NameAttribute(NameOID.COMMON_NAME, common_name),- ])+ _RDN_OIDS = {+ "OU": NameOID.ORGANIZATIONAL_UNIT_NAME,+ "O": NameOID.ORGANIZATION_NAME,+ "L": NameOID.LOCALITY_NAME,+ "ST": NameOID.STATE_OR_PROVINCE_NAME,+ "C": NameOID.COUNTRY_NAME,+ }+ with warnings.catch_warnings():+ # RDS ships the endpoint as CN, 105 bytes on a 63-char identifier.+ warnings.simplefilter("ignore")+ attributes = [x509.NameAttribute(NameOID.COMMON_NAME, common_name, _validate=False)]+ for key, value in subject_rdns or []:+ attributes.append(x509.NameAttribute(_RDN_OIDS[key], value))+ subject = x509.Name(attributes)now = _dt.datetime.now(_dt.timezone.utc)builder = (diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex 19c9ddc8..df12403f 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -1398,27 +1398,27 @@ def _build_run_kwargs(cdef, td, env, port_bindings, ecs_network,return kwargs-def _awslogs_config(cdef, task_id):- log_config = cdef.get("logConfiguration") or cdef.get("LogConfiguration") or {}- log_driver = log_config.get("logDriver") or log_config.get("LogDriver")- if log_driver != "awslogs":+def _awslogs_config(cdef, task_id, container_id):+ log_config = cdef.get("logConfiguration") or {}+ if log_config.get("logDriver") != "awslogs":return None- options = log_config.get("options") or log_config.get("Options") or {}+ options = log_config.get("options") or {}group_name = options.get("awslogs-group")if not group_name:return None- container_name = cdef.get("name", "container")stream_prefix = options.get("awslogs-stream-prefix")if stream_prefix:- stream_name = f"{stream_prefix}/{container_name}/{task_id}"+ stream_name = f"{stream_prefix}/{cdef.get('name', 'container')}/{task_id}"else:- stream_name = f"{container_name}/{task_id}"+ # Without a prefix AWS names the stream after the Docker container id.+ stream_name = container_idreturn {"group": group_name,"stream": stream_name,+ "region": options.get("awslogs-region"),"create_group": str(options.get("awslogs-create-group", "")).lower() == "true",}@@ -1481,11 +1481,12 @@ def _forward_awslogs(container, config, account_id, region):def _start_awslogs_forwarder(container, cdef, task_id):- config = _awslogs_config(cdef, task_id)+ config = _awslogs_config(cdef, task_id, container.id)if not config:returnaccount_id = get_account_id()- region = get_region()+ # awslogs-region is where the driver ships the logs, not where the task ran.+ region = config["region"] or get_region()thread = threading.Thread(target=_forward_awslogs,args=(container, config, account_id, region),diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex cf1750aa..06b47a8d 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -7605,7 +7605,8 @@ def _mtls_server_cert_sans() -> tuple[list[str], list[str]]:import ipaddressimport socket as _socket- dns_names = ["localhost"]+ region = os.environ.get("MINISTACK_REGION", "us-east-1")+ dns_names = [f"*.iot.{region}.{_MINISTACK_HOST}", "localhost"]ip_addresses = ["127.0.0.1", "::1"]candidates = [os.environ.get("MINISTACK_HOST", "localhost"), _socket.gethostname()]for candidate in candidates:@@ -7662,7 +7663,7 @@ def _mtls_ensure_server_cert() -> tuple[str, str]:cert_pem, key_pem, _public_pem = sign_leaf_certificate(ca_cert_pem,ca_key_pem,- common_name="Ministack IoT Broker",+ common_name=dns_names[0],san_dns=dns_names,san_ips=ip_addresses,)diff --git a/ministack/services/kms.py b/ministack/services/kms.pyindex 03f30b74..270b8f54 100644--- a/ministack/services/kms.py+++ b/ministack/services/kms.py@@ -375,6 +375,31 @@ def _require_crypto(operation):# ---- Operations ----+def _set_asymmetric_material(rec, private_key):+ """Record an asymmetric private key and the public key AWS derives from it."""+ rec["_private_key"] = private_key+ rec["_public_key_der"] = private_key.public_key().public_bytes(+ serialization.Encoding.DER,+ serialization.PublicFormat.SubjectPublicKeyInfo,+ )+++def _asymmetric_key_spec(private_key):+ """The KeySpec a loaded private key corresponds to, or None if unsupported."""+ if isinstance(private_key, rsa.RSAPrivateKey):+ return f"RSA_{private_key.key_size}"+ if isinstance(private_key, ed25519.Ed25519PrivateKey):+ return "ECC_NIST_EDWARDS25519"+ if isinstance(private_key, ec.EllipticCurvePrivateKey):+ return {+ "secp256r1": "ECC_NIST_P256",+ "secp384r1": "ECC_NIST_P384",+ "secp521r1": "ECC_NIST_P521",+ "secp256k1": "ECC_SECG_P256K1",+ }.get(private_key.curve.name)+ return None++def _create_key(data):# A multi-Region key's id carries the mrk- prefix, and the id is what ties# the primary and its replicas together across regions.@@ -404,11 +429,6 @@ def _create_key(data):return error_response_json("UnsupportedOperationException",f"Origin {origin} is not supported.", 400)- if origin == "EXTERNAL" and key_spec != "SYMMETRIC_DEFAULT":- return error_response_json(- "UnsupportedOperationException",- "Imported key material is supported for SYMMETRIC_DEFAULT keys only.",- 400)policy = data.get("Policy", json.dumps({"Version": "2012-10-17","Id": "key-default-1",@@ -456,20 +476,22 @@ def _create_key(data):rec["SigningAlgorithms"] = []elif key_spec in _HMAC_KEY_SPECS:mac_algorithm, material_len = _HMAC_KEY_SPECS[key_spec]- rec["_hmac_key"] = os.urandom(material_len)+ if origin == "EXTERNAL":+ rec["KeyState"] = "PendingImport"+ rec["Enabled"] = False+ else:+ rec["_hmac_key"] = os.urandom(material_len)rec["MacAlgorithms"] = [mac_algorithm]elif key_spec in ("RSA_2048", "RSA_3072", "RSA_4096"):err = _require_crypto("CreateKey")if err:return err- private_key = rsa.generate_private_key(- public_exponent=65537, key_size=int(key_spec.split("_")[1])- )- rec["_private_key"] = private_key- rec["_public_key_der"] = private_key.public_key().public_bytes(- serialization.Encoding.DER,- serialization.PublicFormat.SubjectPublicKeyInfo,- )+ if origin == "EXTERNAL":+ rec["KeyState"] = "PendingImport"+ rec["Enabled"] = False+ else:+ _set_asymmetric_material(rec, rsa.generate_private_key(+ public_exponent=65537, key_size=int(key_spec.split("_")[1])))if key_usage == "SIGN_VERIFY":rec["SigningAlgorithms"] = ["RSASSA_PKCS1_V1_5_SHA_256",@@ -496,12 +518,11 @@ def _create_key(data):"ECC_NIST_P521": ec.SECP521R1(),"ECC_SECG_P256K1": ec.SECP256K1(),}- private_key = ec.generate_private_key(curve_map[key_spec])- rec["_private_key"] = private_key- rec["_public_key_der"] = private_key.public_key().public_bytes(- serialization.Encoding.DER,- serialization.PublicFormat.SubjectPublicKeyInfo,- )+ if origin == "EXTERNAL":+ rec["KeyState"] = "PendingImport"+ rec["Enabled"] = False+ else:+ _set_asymmetric_material(rec, ec.generate_private_key(curve_map[key_spec]))signing_algo_map = {"ECC_NIST_P256": ["ECDSA_SHA_256"],"ECC_NIST_P384": ["ECDSA_SHA_384"],@@ -514,12 +535,11 @@ def _create_key(data):err = _require_crypto("CreateKey")if err:return err- private_key = ed25519.Ed25519PrivateKey.generate()- rec["_private_key"] = private_key- rec["_public_key_der"] = private_key.public_key().public_bytes(- serialization.Encoding.DER,- serialization.PublicFormat.SubjectPublicKeyInfo,- )+ if origin == "EXTERNAL":+ rec["KeyState"] = "PendingImport"+ rec["Enabled"] = False+ else:+ _set_asymmetric_material(rec, ed25519.Ed25519PrivateKey.generate())# Real AWS exposes both for ECC_NIST_EDWARDS25519 — verified against the# KMS Developer Guide "Supported signing algorithms for ECC key specs"# table. PH variant is listed in metadata even though Sign/Verify return@@ -563,6 +583,11 @@ def _get_public_key(data):err = _reject_hmac_key(rec, "GetPublicKey")if err:return err+ # An EXTERNAL asymmetric key has no public key until its material is+ # imported, so the absence below is a key state, not a symmetric key.+ if rec["KeyState"] == "PendingImport":+ return error_response_json(+ "KMSInvalidStateException", f"{rec['Arn']} is pending import.", 400)if "_public_key_der" not in rec:return error_response_json("UnsupportedOperationException",@@ -1751,6 +1776,44 @@ def _get_parameters_for_import(data):})+def _store_imported_material(rec, material):+ """Place unwrapped key material on the record, per the key's KeySpec.++ Symmetric and HMAC material is raw bytes of the spec's length; asymmetric+ material is the private key alone, DER-encoded PKCS#8, from which the+ public key is derived.+ """+ key_spec = rec.get("KeySpec", "SYMMETRIC_DEFAULT")+ if key_spec == "SYMMETRIC_DEFAULT":+ if len(material) != 32:+ return error_response_json(+ "IncorrectKeyMaterialException",+ "A SYMMETRIC_DEFAULT key takes 256 bits of key material.", 400)+ rec["_symmetric_key"] = material+ return None+ if key_spec in _HMAC_KEY_SPECS:+ material_len = _HMAC_KEY_SPECS[key_spec][1]+ if len(material) != material_len:+ return error_response_json(+ "IncorrectKeyMaterialException",+ f"A {key_spec} key takes {material_len * 8} bits of key material.",+ 400)+ rec["_hmac_key"] = material+ return None+ try:+ private_key = serialization.load_der_private_key(material, password=None)+ except Exception:+ return error_response_json(+ "IncorrectKeyMaterialException",+ f"A {key_spec} key takes a DER-encoded PKCS#8 private key.", 400)+ if _asymmetric_key_spec(private_key) != key_spec:+ return error_response_json(+ "IncorrectKeyMaterialException",+ f"The key material does not match KeySpec {key_spec}.", 400)+ _set_asymmetric_material(rec, private_key)+ return None++def _import_key_material(data):key_id = data.get("KeyId", "")rec = _resolve_key(key_id)@@ -1800,12 +1863,9 @@ def _import_key_material(data):"InvalidCiphertextException","The key material could not be unwrapped with the wrapping key.",400)- if len(material) != 32:- return error_response_json(- "IncorrectKeyMaterialException",- "A SYMMETRIC_DEFAULT key takes 256 bits of key material.", 400)-- rec["_symmetric_key"] = material+ err = _store_imported_material(rec, material)+ if err:+ return errrec["KeyState"] = "Enabled"rec["Enabled"] = Truerec["ExpirationModel"] = expiration@@ -1833,7 +1893,8 @@ def _delete_imported_key_material(data):if rec["KeyState"] == "PendingDeletion":return error_response_json("KMSInvalidStateException", f"{rec['Arn']} is pending deletion.", 400)- rec.pop("_symmetric_key", None)+ for field in ("_symmetric_key", "_hmac_key", "_private_key", "_public_key_der"):+ rec.pop(field, None)rec.pop("ValidTo", None)rec["KeyState"] = "PendingImport"rec["Enabled"] = Falsediff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex dc1e4fc9..06c947de 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -1081,7 +1081,11 @@ def _ensure_pg_ca() -> tuple[str, str]:if _pg_ca is None:from ministack.core.x509_utils import generate_ca- _pg_ca = generate_ca(common_name="Ministack RDS Root CA")+ region = os.environ.get("MINISTACK_REGION", "us-east-1")+ _pg_ca = generate_ca(+ org_name="Amazon Web Services, Inc.",+ common_name=f"Amazon RDS {region} Root CA RSA2048 G1",+ )logger.info("RDS: generated the server-certificate CA")return _pg_ca@@ -1093,10 +1097,10 @@ def _pg_server_material(names, ips) -> tuple[str, str]:ca_cert, ca_key = _ensure_pg_ca()cert_pem, key_pem, _public = sign_leaf_certificate(ca_cert, ca_key,- # X.509 limits CN to 64 bytes; valid RDS DNS endpoints can be longer.- # Connection identities belong in SANs, preserved in full below.- common_name="Ministack RDS Server",+ common_name=(names[0] if names else "localhost"),san_dns=names, san_ips=ips,+ subject_rdns=[("OU", "RDS"), ("O", "Amazon.com"), ("L", "Seattle"),+ ("ST", "Washington"), ("C", "US")],)return cert_pem, key_pem@@ -11095,9 +11099,9 @@ _ACTION_MAP = {def reset():- from ministack.core import rds_iam_broker+ from ministack.core import rds_iam- rds_iam_broker.reset()+ rds_iam.reset()# Serialize teardown with warm-boot shared-container startup. Otherwise a# restore worker can pass its membership check after reset has enumerated# resources, then create a container after the stores are cleared.diff --git a/pyproject.toml b/pyproject.tomlindex 900044c5..a3e9ecad 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -54,9 +54,8 @@ full = ["aws-sam-translator>=1.90",]# Exactly what CI installs to run the test suite — kept separate from `dev`-# (which also carries linters, type stubs and the DB drivers the container-backed-# RDS tests skip without) so the workflow has one name to install instead of an-# inline package list that drifts from this file.+# (which also carries linters and type stubs) so the workflow has one name to+# install instead of an inline package list that drifts from this file.test = ["boto3>=1.34","pytest>=8.0",diff --git a/tests/test_dsql.py b/tests/test_dsql.pyindex afbb91db..a264ebcb 100644--- a/tests/test_dsql.py+++ b/tests/test_dsql.py@@ -1723,14 +1723,12 @@ def _pg_connect(port, autocommit=True):@requires_docker[email protected]_planeclass TestContainersE2E:"""End-to-end for DSQL_STRICT=1: _create_cluster spins up a realPostgres container behind the wire proxy, reachable over SQL. Runsin-process (flag monkeypatched on) wherever a Docker daemon exists."""- # TODO: Move this extended live-container coverage into a dedicated DSQL- # lane; it was intentionally skipped by the pre-PR control-plane suite.-def test_env_flag_spins_up_real_backend(self, monkeypatch):import json@@ -1905,6 +1903,7 @@ class _WireResult:@requires_docker[email protected]_planeclass TestExtendedProtocol:"""The extended protocol must enforce the same DSQL subset as 'Q'.@@ -2022,6 +2021,7 @@ class TestExtendedProtocol:@requires_docker[email protected]_planeclass TestDropColumn:"""Aurora DSQL gained ALTER TABLE ... DROP COLUMN on 2026-08-03, includingseveral columns in one statement, but dropping a primary key column is not@@ -2094,6 +2094,7 @@ class TestDropColumn:@requires_docker[email protected]_planeclass TestLockingReads:"""A locking read has to reach the backend whatever its predicate lookslike — an ORM quotes every identifier, and DSQL itself places no@@ -2248,6 +2249,7 @@ class TestLockingReads:@requires_docker[email protected]_planeclass TestTransactionAbortSemantics:"""A statement the proxy rejects must poison the transaction block the waya real error does — otherwise the following statements still commit."""@@ -2287,6 +2289,7 @@ class TestTransactionAbortSemantics:@requires_docker[email protected]_planeclass TestLiveProxy:def test_create_insert_select_round_trip(self, dsql_proxy):conn = _pg_connect(dsql_proxy)@@ -2731,6 +2734,11 @@ class TestLiveProxy:@requires_docker[email protected]_plane+ os.environ.get("DSQL_STRICT", "0").lower() not in ("1", "true", "yes"),+ reason="the server needs DSQL_STRICT=1 to spawn the backend behind the endpoint",+)def test_cluster_data_plane_end_to_end(dsql):"""CreateCluster -> poll ACTIVE -> psycopg2 through the endpoint."""psycopg2 = pytest.importorskip("psycopg2")diff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex 7d67636c..b6b81ae0 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -152,6 +152,112 @@ def test_ecs_run_task_forwards_awslogs_to_cloudwatch_logs(ecs, logs):_wait_until(marker_reached_cloudwatch_logs, timeout=20)+def _logs_client(region):+ import boto3+ from botocore.config import Config+ from conftest import ENDPOINT+ return boto3.client("logs", endpoint_url=ENDPOINT, region_name=region,+ aws_access_key_id="test", aws_secret_access_key="test",+ config=Config(region_name=region, inject_host_prefix=False))++[email protected]_plane+def test_ecs_awslogs_without_stream_prefix_names_the_stream_after_the_container_id(ecs, logs):+ """AWS: "If you don't specify a prefix with this option, then the log stream+ is named after the container ID that's assigned by the Docker daemon"."""+ cluster = f"awslogs-noprefix-{_uuid_mod.uuid4().hex[:8]}"+ family = f"{cluster}-td"+ group = f"/ecs/{cluster}"+ marker = f"ECS-NOPREFIX-{_uuid_mod.uuid4().hex[:8]}"++ logs.create_log_group(logGroupName=group)+ ecs.create_cluster(clusterName=cluster)+ ecs.register_task_definition(+ family=family,+ containerDefinitions=[{+ "name": "app",+ "image": "alpine:latest",+ "command": ["sh", "-c", f"echo {marker}"],+ "essential": True,+ "logConfiguration": {+ "logDriver": "awslogs",+ "options": {"awslogs-group": group, "awslogs-region": "us-east-1"},+ },+ }],+ )++ task_arn = ecs.run_task(cluster=cluster, taskDefinition=family)["tasks"][0]["taskArn"]++ def runtime_id():+ containers = ecs.describe_tasks(cluster=cluster, tasks=[task_arn])["tasks"][0]["containers"]+ return containers[0].get("runtimeId")++ _wait_until(runtime_id, timeout=30)+ short_id = runtime_id()++ def stream_named_after_the_container():+ streams = logs.describe_log_streams(logGroupName=group)["logStreams"]+ names = {s["logStreamName"] for s in streams}+ if not names:+ return False+ assert not any("/" in n for n in names), f"expected a bare container id, got {names}"+ assert names == {n for n in names if n.startswith(short_id)}, names+ stream = next(iter(names))+ assert len(stream) == 64, f"expected the full docker container id, got {stream}"+ events = logs.get_log_events(logGroupName=group, logStreamName=stream)["events"]+ return any(marker in e["message"] for e in events)++ _wait_until(stream_named_after_the_container, timeout=30)++[email protected]_plane+def test_ecs_awslogs_region_option_decides_where_the_logs_land(ecs, logs):+ """awslogs-region is where the driver ships the logs, not where the task ran."""+ target_region = _different_region("us-east-1")+ remote_logs = _logs_client(target_region)+ cluster = f"awslogs-region-{_uuid_mod.uuid4().hex[:8]}"+ family = f"{cluster}-td"+ group = f"/ecs/{cluster}"+ marker = f"ECS-REGION-{_uuid_mod.uuid4().hex[:8]}"++ remote_logs.create_log_group(logGroupName=group)+ ecs.create_cluster(clusterName=cluster)+ ecs.register_task_definition(+ family=family,+ containerDefinitions=[{+ "name": "app",+ "image": "alpine:latest",+ "command": ["sh", "-c", f"echo {marker}"],+ "essential": True,+ "logConfiguration": {+ "logDriver": "awslogs",+ "options": {+ "awslogs-group": group,+ "awslogs-region": target_region,+ "awslogs-stream-prefix": "ecs",+ },+ },+ }],+ )++ task_arn = ecs.run_task(cluster=cluster, taskDefinition=family)["tasks"][0]["taskArn"]+ stream = f"ecs/app/{task_arn.rsplit('/', 1)[-1]}"++ def marker_in_target_region():+ streams = remote_logs.describe_log_streams(+ logGroupName=group, logStreamNamePrefix=stream)["logStreams"]+ if not streams:+ return False+ events = remote_logs.get_log_events(logGroupName=group, logStreamName=stream)["events"]+ return any(marker in e["message"] for e in events)++ _wait_until(marker_in_target_region, timeout=30)++ with pytest.raises(ClientError) as exc:+ logs.describe_log_streams(logGroupName=group)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++@pytest.mark.data_planedef test_ecs_list_tasks_reflects_natural_container_exit(ecs):"""ListTasks must also reconcile lifecycle when a container has exiteddiff --git a/tests/test_elasticache.py b/tests/test_elasticache.pyindex 66e6dd74..44e09f07 100644--- a/tests/test_elasticache.py+++ b/tests/test_elasticache.py@@ -1388,6 +1388,7 @@ def test_replication_group_tag_updates_propagate_to_member_clusters(ec):# ---------------------------------------------------------------------------@requires_docker[email protected]_planedef test_serverless_cache_not_implemented(ec):"""Serverless cache operations are not yet implemented; verify graceful error."""with pytest.raises(ClientError):@@ -1419,6 +1420,7 @@ def _make_zip_js(code: str) -> bytes:@requires_docker[email protected]_planedef test_elasticache_lambda_network_connectivity(ec, lam):"""Prove that Lambda containers can TCP-connect to an ElastiCache container."""cluster_id = "net-test-redis"diff --git a/tests/test_kms.py b/tests/test_kms.pyindex 51408aa7..f95c326e 100644--- a/tests/test_kms.py+++ b/tests/test_kms.py@@ -2159,8 +2159,8 @@ def _wrap_material(public_key_der, algorithm, material=_BYOK_MATERIAL):def _import_external_key(kms, algorithm="RSAES_OAEP_SHA_256", material=_BYOK_MATERIAL,- expiration=_NO_EXPIRY, valid_to=None):- key_id = kms.create_key(Origin="EXTERNAL")["KeyMetadata"]["KeyId"]+ expiration=_NO_EXPIRY, valid_to=None, **create_kwargs):+ key_id = kms.create_key(Origin="EXTERNAL", **create_kwargs)["KeyMetadata"]["KeyId"]params = kms.get_parameters_for_import(KeyId=key_id, WrappingAlgorithm=algorithm, WrappingKeySpec="RSA_2048")kwargs = {"ExpirationModel": expiration}@@ -2298,15 +2298,126 @@ def test_kms_import_flow_refuses_a_non_external_key():assert exc.value.response["Error"]["Code"] == "UnsupportedOperationException"-def test_kms_external_origin_is_symmetric_only_and_specs_are_validated():+def test_kms_external_origin_wrapping_key_specs_are_validated():pytest.importorskip("cryptography")kms = _regional_kms("us-east-1")- with pytest.raises(ClientError) as exc:- kms.create_key(Origin="EXTERNAL", KeySpec="RSA_2048")- assert exc.value.response["Error"]["Code"] == "UnsupportedOperationException"key_id = kms.create_key(Origin="EXTERNAL")["KeyMetadata"]["KeyId"]with pytest.raises(ClientError) as exc:kms.get_parameters_for_import(KeyId=key_id, WrappingAlgorithm="RSAES_OAEP_SHA_256",WrappingKeySpec="SM2")assert exc.value.response["Error"]["Code"] == "UnsupportedOperationException"+++def _pkcs8_der(private_key):+ """The private key alone, DER-encoded PKCS#8, which is the form AWS imports."""+ from cryptography.hazmat.primitives import serialization+ return private_key.private_bytes(+ serialization.Encoding.DER,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ )+++def test_kms_external_hmac_key_imports_its_own_material():+ """AWS supports imported key material for HMAC keys, and the imported bytes+ are the ones the MAC is computed with."""+ pytest.importorskip("cryptography")+ import hashlib+ import hmac+ kms = _regional_kms("us-east-1")+ material = bytes(range(32))+ key_id, _ = _import_external_key(+ kms, algorithm="RSAES_OAEP_SHA_256", material=material,+ KeySpec="HMAC_256", KeyUsage="GENERATE_VERIFY_MAC")+ metadata = kms.describe_key(KeyId=key_id)["KeyMetadata"]+ assert metadata["KeyState"] == "Enabled"+ assert metadata["Origin"] == "EXTERNAL"+ mac = kms.generate_mac(KeyId=key_id, Message=b"hmac byok",+ MacAlgorithm="HMAC_SHA_256")["Mac"]+ assert hmac.new(material, b"hmac byok", hashlib.sha256).digest() == mac++[email protected]("key_spec", [+ "RSA_2048", "ECC_NIST_P256", "ECC_NIST_EDWARDS25519",+])+def test_kms_external_asymmetric_key_imports_its_own_private_key(key_spec):+ """AWS imports the private key alone and derives the public key from it, so+ GetPublicKey returns the pair of the material the caller supplied."""+ pytest.importorskip("cryptography")+ from cryptography.hazmat.primitives import serialization+ from cryptography.hazmat.primitives.asymmetric import ec, ed25519, rsa+ kms = _regional_kms("us-east-1")+ if key_spec == "RSA_2048":+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ elif key_spec == "ECC_NIST_P256":+ private_key = ec.generate_private_key(ec.SECP256R1())+ else:+ private_key = ed25519.Ed25519PrivateKey.generate()+ # A private key is far larger than RSAES_OAEP can wrap directly, so+ # asymmetric material travels under the AES key-wrap algorithms.+ key_id, _ = _import_external_key(+ kms, algorithm="RSA_AES_KEY_WRAP_SHA_256", material=_pkcs8_der(private_key),+ KeySpec=key_spec, KeyUsage="SIGN_VERIFY")+ assert kms.describe_key(KeyId=key_id)["KeyMetadata"]["KeyState"] == "Enabled"+ assert kms.get_public_key(KeyId=key_id)["PublicKey"] == \+ private_key.public_key().public_bytes(+ serialization.Encoding.DER,+ serialization.PublicFormat.SubjectPublicKeyInfo)+++def test_kms_imported_asymmetric_key_signs_with_the_imported_material():+ pytest.importorskip("cryptography")+ from cryptography.hazmat.primitives.asymmetric import ec+ kms = _regional_kms("us-east-1")+ private_key = ec.generate_private_key(ec.SECP256R1())+ key_id, _ = _import_external_key(+ kms, algorithm="RSA_AES_KEY_WRAP_SHA_256", material=_pkcs8_der(private_key),+ KeySpec="ECC_NIST_P256", KeyUsage="SIGN_VERIFY")+ signature = kms.sign(KeyId=key_id, Message=b"sign byok",+ SigningAlgorithm="ECDSA_SHA_256")["Signature"]+ assert kms.verify(KeyId=key_id, Message=b"sign byok", Signature=signature,+ SigningAlgorithm="ECDSA_SHA_256")["SignatureValid"] is True++[email protected]("key_spec,key_usage,material", [+ ("HMAC_256", "GENERATE_VERIFY_MAC", bytes(16)),+ ("ECC_NIST_P256", "SIGN_VERIFY", b"not a der private key"),+])+def test_kms_import_rejects_material_that_does_not_fit_the_key_spec(+ key_spec, key_usage, material):+ pytest.importorskip("cryptography")+ kms = _regional_kms("us-east-1")+ with pytest.raises(ClientError) as exc:+ _import_external_key(+ kms, algorithm="RSA_AES_KEY_WRAP_SHA_256", material=material,+ KeySpec=key_spec, KeyUsage=key_usage)+ assert exc.value.response["Error"]["Code"] == "IncorrectKeyMaterialException"+++def test_kms_import_rejects_a_private_key_of_the_wrong_curve():+ """The material must be the key the KeySpec declares, not merely parseable."""+ pytest.importorskip("cryptography")+ from cryptography.hazmat.primitives.asymmetric import ec+ kms = _regional_kms("us-east-1")+ with pytest.raises(ClientError) as exc:+ _import_external_key(+ kms, algorithm="RSA_AES_KEY_WRAP_SHA_256",+ material=_pkcs8_der(ec.generate_private_key(ec.SECP384R1())),+ KeySpec="ECC_NIST_P256", KeyUsage="SIGN_VERIFY")+ assert exc.value.response["Error"]["Code"] == "IncorrectKeyMaterialException"+++def test_kms_delete_imported_material_clears_the_asymmetric_key():+ pytest.importorskip("cryptography")+ from cryptography.hazmat.primitives.asymmetric import ec+ kms = _regional_kms("us-east-1")+ key_id, _ = _import_external_key(+ kms, algorithm="RSA_AES_KEY_WRAP_SHA_256",+ material=_pkcs8_der(ec.generate_private_key(ec.SECP256R1())),+ KeySpec="ECC_NIST_P256", KeyUsage="SIGN_VERIFY")+ kms.delete_imported_key_material(KeyId=key_id)+ assert kms.describe_key(KeyId=key_id)["KeyMetadata"]["KeyState"] == "PendingImport"+ with pytest.raises(ClientError) as exc:+ kms.get_public_key(KeyId=key_id)+ assert exc.value.response["Error"]["Code"] == "KMSInvalidStateException"diff --git a/tests/test_rds.py b/tests/test_rds.pyindex 82964b68..27d23476 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -5,6 +5,8 @@ import ipaddressimport ioimport jsonimport os+import socket+import sslimport sysimport threadingimport time@@ -8019,12 +8021,40 @@ def _wait_for_instance(rds, db_id, timeout=120):raise TimeoutError(f"RDS instance {db_id} not available after {timeout}s")+def _host_dialable(endpoint):+ """Map an advertised endpoint onto an address this process can reach.++ A cluster endpoint is a Docker network alias resolvable only by containers+ on that network; pytest runs on the host, so dial the published port of the+ container carrying the alias.+ """+ address, port = endpoint["Address"], int(endpoint["Port"])+ try:+ socket.getaddrinfo(address, port)+ return address, port+ except socket.gaierror:+ pass+ import docker++ for container in docker.from_env().containers.list(+ filters={"label": "ministack=rds"},+ ):+ networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})+ if not any(address in (n.get("Aliases") or []) for n in networks.values()):+ continue+ published = container.attrs["NetworkSettings"]["Ports"].get(f"{port}/tcp") or []+ if published:+ return "127.0.0.1", int(published[0]["HostPort"])+ raise AssertionError(f"no container publishes {address}:{port}")++def _aurora_connect(endpoint, user="admin", password=PASSWORD, database=DATABASE):import pymysql+ host, port = _host_dialable(endpoint)return pymysql.connect(- host=endpoint["Address"],- port=int(endpoint["Port"]),+ host=host,+ port=port,user=user,password=password,database=database,@@ -8082,9 +8112,7 @@ def _live_cluster(rds, engine_version=None):if e.response["Error"]["Code"] != "DBClusterNotFoundFault":raise-# TODO: Keep extended Aurora live-container coverage out of standard CI until-# a dedicated live setup can run it reliably; these tests were skipped before-# the test-plane split as well.[email protected]_plane@pytest.mark.skipif(not os.environ.get("DOCKER_NETWORK"), reason="DOCKER_NETWORK not set -- live Aurora")def test_aurora_writer_data_is_visible_through_reader(rds):with _live_cluster(rds) as (_cid, _wid, _rid, writer, reader, _cluster):@@ -12251,8 +12279,7 @@ def _wait_for_gtid(f"result={result!r}, gtid={executed!r}")-# TODO: Re-enable this extended Aurora global/replication coverage in a-# dedicated live lane once its service dependencies are provisioned.[email protected]_plane@pytest.mark.skipif(not os.environ.get("DOCKER_NETWORK"),reason="DOCKER_NETWORK not set -- live Aurora",@@ -14759,9 +14786,10 @@ _PG_REPLICATION_LIVE = (def _pg_connect(endpoint, user="admin", password=PASSWORD, database=DATABASE):import psycopg2+ host, port = _host_dialable(endpoint)return psycopg2.connect(- host=endpoint["Address"],- port=int(endpoint["Port"]),+ host=host,+ port=port,user=user,password=password,dbname=database,@@ -14815,8 +14843,7 @@ def _live_pg_cluster(rds):if e.response["Error"]["Code"] != "DBClusterNotFoundFault":raise-# TODO: Re-enable this extended Aurora PostgreSQL live coverage in a dedicated-# live lane once its service dependencies are provisioned.[email protected]_plane@pytest.mark.skipif(not _PG_REPLICATION_LIVE,reason="DOCKER_NETWORK and MINISTACK_RDS_PG_CLUSTER_REPLICATION not set "@@ -14872,6 +14899,7 @@ def test_aurora_pg_replicating_reader_live(rds):assert excinfo.value.pgcode == "25006"[email protected]_plane@pytest.mark.skipif(not _PG_REPLICATION_LIVE,reason="DOCKER_NETWORK and MINISTACK_RDS_PG_CLUSTER_REPLICATION not set "@@ -15790,22 +15818,33 @@ def _rds_ca_pem(tmp_path):@pytest.mark.data_plane-# TODO: Re-enable Aurora verify-full coverage once data-plane pytest runs-# inside DOCKER_NETWORK, so Docker DNS resolves the advertised endpoint.-def test_rds_postgres_serves_verified_tls(rds, tmp_path):[email protected]("engine", ("postgres", "aurora-postgresql"))+def test_rds_postgres_serves_verified_tls(rds, tmp_path, engine):"""AWS installs the DB server certificate itself and every instance wereport carries CACertificateIdentifier, so TLS is on without asking: aclient using our CA connects, and plaintext still works as it does on AWSwithout rds.force_ssl."""psycopg2 = pytest.importorskip("psycopg2")- db_id = f"tls-postgres-{_uuid_mod.uuid4().hex[:8]}"+ db_id = f"tls-{engine.split('-')[-1]}-{_uuid_mod.uuid4().hex[:8]}"+ cluster_id = f"{db_id}-c"try:- rds.create_db_instance(- DBInstanceIdentifier=db_id, DBInstanceClass="db.t3.micro",- Engine="postgres", MasterUsername="admin",- MasterUserPassword="password", DBName="appdb",- AllocatedStorage=20,- )+ if engine == "aurora-postgresql":+ rds.create_db_cluster(+ DBClusterIdentifier=cluster_id, Engine=engine,+ MasterUsername="admin", MasterUserPassword="password",+ DatabaseName="appdb",+ )+ rds.create_db_instance(+ DBInstanceIdentifier=db_id, DBClusterIdentifier=cluster_id,+ DBInstanceClass="db.r6g.large", Engine=engine,+ )+ else:+ rds.create_db_instance(+ DBInstanceIdentifier=db_id, DBInstanceClass="db.t3.micro",+ Engine="postgres", MasterUsername="admin",+ MasterUserPassword="password", DBName="appdb",+ AllocatedStorage=20,+ )endpoint = Nonefor _ in range(90):detail = rds.describe_db_instances(DBInstanceIdentifier=db_id)["DBInstances"][0]@@ -15821,9 +15860,10 @@ def test_rds_postgres_serves_verified_tls(rds, tmp_path):def connect(sslmode):host = endpoint["Address"]+ dial_host, dial_port = _host_dialable(endpoint)connect_kwargs = {"host": host,- "port": endpoint["Port"],+ "port": dial_port,"user": "admin","password": "password","dbname": "appdb",@@ -15834,10 +15874,9 @@ def test_rds_postgres_serves_verified_tls(rds, tmp_path):try:ipaddress.ip_address(host)except ValueError:- pass+ if dial_host != host:+ connect_kwargs["hostaddr"] = dial_hostelse:- # Docker-network endpoints can be advertised as container IPs,- # while the generated certificate carries localhost SANs.connect_kwargs["hostaddr"] = hostconnect_kwargs["host"] = "localhost"connection = psycopg2.connect(**connect_kwargs)@@ -15859,6 +15898,11 @@ def test_rds_postgres_serves_verified_tls(rds, tmp_path):rds.delete_db_instance(DBInstanceIdentifier=db_id, SkipFinalSnapshot=True)except ClientError:pass+ if engine == "aurora-postgresql":+ try:+ rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)+ except ClientError:+ passdef test_rds_ca_endpoint_serves_one_stable_ca(tmp_path):@@ -15874,4 +15918,94 @@ def test_rds_ca_endpoint_serves_one_stable_ca(tmp_path):assert first == second, "the CA must not be re-minted per request"cert = x509.load_pem_x509_certificate(first)assert cert.issuer == cert.subject- assert "Ministack RDS Root CA" in cert.subject.rfc4514_string()+ assert "Root CA RSA2048 G1" in cert.subject.rfc4514_string()+++def _tls_handshake(ca_pem, cert_pem, key_pem, hostname, tmp_path):+ """A real verifying handshake, both ends in memory, SAN matching only."""+ import ssl++ chain = tmp_path / "server.pem"+ chain.write_text(cert_pem + key_pem)+ server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ server_context.load_cert_chain(chain)+ client_context = ssl.create_default_context(cadata=ca_pem)+ client_context.verify_flags |= ssl.VERIFY_X509_STRICT+ client_context.hostname_checks_common_name = False+ client_in, client_out = ssl.MemoryBIO(), ssl.MemoryBIO()+ server_in, server_out = ssl.MemoryBIO(), ssl.MemoryBIO()+ client = client_context.wrap_bio(client_in, client_out, server_hostname=hostname)+ server = server_context.wrap_bio(server_in, server_out, server_side=True)+ done = set()+ for _ in range(10):+ for endpoint in (client, server):+ if endpoint not in done:+ try:+ endpoint.do_handshake()+ done.add(endpoint)+ except ssl.SSLWantReadError:+ pass+ server_in.write(client_out.read())+ client_in.write(server_out.read())+ if len(done) == 2:+ return+ pytest.fail("TLS handshake did not complete")+++def _fresh_pg_ca(monkeypatch):+ from ministack.services import rds as rds_service++ monkeypatch.setattr(rds_service, "_pg_ca", None)+ return rds_service.pg_ca_cert_pem()++[email protected]("hostname", [+ "db.example.test",+ "db-" + "a" * 37 + ".cluster-abcdefghijkl.us-east-1.rds.amazonaws.com",+])+def test_rds_server_certificate_carries_every_endpoint_as_a_san(hostname, monkeypatch, tmp_path):+ """An endpoint longer than the 64-byte CN limit must still get a certificate,+ and every name it is reached by has to verify."""+ pytest.importorskip("cryptography")+ from cryptography import x509+ from cryptography.x509.oid import NameOID++ from ministack.services import rds as rds_service++ ca_pem = _fresh_pg_ca(monkeypatch)+ names = [hostname, "reader." + hostname, "localhost"]+ ips = ["127.0.0.1", "::1"]+ cert_pem, key_pem = rds_service._pg_server_material(names, ips)++ cert = x509.load_pem_x509_certificate(cert_pem.encode())+ cn = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value+ assert cn == hostname+ sans = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value+ assert sans.get_values_for_type(x509.DNSName) == names+ assert sans.get_values_for_type(x509.IPAddress) == [+ ipaddress.ip_address(ip) for ip in ips]++ for name in names + ips:+ _tls_handshake(ca_pem, cert_pem, key_pem, name, tmp_path)+ with pytest.raises(ssl.SSLCertVerificationError):+ _tls_handshake(ca_pem, cert_pem, key_pem, "unlisted.example.test", tmp_path)+++def test_rds_server_certificate_without_dns_names_verifies_its_ip(monkeypatch, tmp_path):+ from ministack.services import rds as rds_service++ pytest.importorskip("cryptography")+ ca_pem = _fresh_pg_ca(monkeypatch)+ cert_pem, key_pem = rds_service._pg_server_material([], ["127.0.0.1"])+ _tls_handshake(ca_pem, cert_pem, key_pem, "127.0.0.1", tmp_path)+++def test_rds_server_certificate_without_cryptography_raises(monkeypatch):+ pytest.importorskip("cryptography")+ from ministack.core import x509_utils+ from ministack.services import rds as rds_service++ _fresh_pg_ca(monkeypatch)+ monkeypatch.setattr(x509_utils, "HAS_CRYPTO", False)+ with pytest.raises(RuntimeError, match="requires the `cryptography` package"):+ rds_service._pg_server_material(["localhost"], [])diff --git a/tests/test_rds_iam.py b/tests/test_rds_iam.pyindex 78b5596c..c6d12902 100644--- a/tests/test_rds_iam.py+++ b/tests/test_rds_iam.py@@ -2,7 +2,10 @@# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE)."""Offline RDS tokens signed by boto3/botocore, not the verifier's helpers."""+import asyncioimport datetime as dt+import importlib+import jsonimport timefrom types import SimpleNamespacefrom urllib.parse import parse_qsl, urlencode, urlsplit@@ -503,3 +506,261 @@ class TestResourceBoundAuthorization:dict(reader_endpoint="false")])def test_invalid_target(self, override):assert authorize_rds_iam_token(_authz_token(), **{**AUTHZ_ARGS, **override}).code == "InvalidTarget"+++app_module = importlib.import_module("ministack.app")+++def ep_state(monkeypatch):+ """Isolate the rds_iam's resource and IAM ep_state using the shared _authz_token inputs."""+ for name in ("_users", "_access_keys", "_user_inline_policies", "_roles", "_groups",+ "_group_inline_policies", "_policies"):+ monkeypatch.setattr(iam, name, AccountScopedDict())+ monkeypatch.setattr(rds, "_instances", AccountRegionScopedDict())+ monkeypatch.setattr(rds, "_clusters", AccountRegionScopedDict())+ monkeypatch.setattr(sts, "_sessions", {})+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test")+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "root-secret")+ monkeypatch.delenv("AWS_SESSION_TOKEN", raising=False)+ iam._users.set_scoped(ACCOUNT, None, "alice", {+ "UserName": "alice", "Arn": f"arn:aws:iam::{ACCOUNT}:user/alice",+ })+ iam._access_keys.set_scoped(ACCOUNT, None, AUTHZ_KEY, {+ "UserName": "alice", "Status": "Active", "SecretAccessKey": AUTHZ_SECRET,+ })+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"connect": _authz_policy()})+ instance = dict(Engine="mysql", DbiResourceId="db-TEST", IAMDatabaseAuthenticationEnabled=True,+ Endpoint={"Address": AUTHZ_HOST, "Port": 3306})+ rds._instances.set_scoped(ACCOUNT, REGION, "database", instance)+ return instance++[email protected](autouse=True)+def clean_broker():+ rds_iam.reset()+ yield+ rds_iam.reset()+++def capability():+ return rds_iam.issue_capability(**{k: v for k, v in AUTHZ_ARGS.items() if k != "db_user"})+++def request(cap, *, payload=None, body=None, headers=None, method="POST", query=b"", chunks=None):+ if body is None:+ body = json.dumps(payload if payload is not None else {"username": AUTHZ_USER, "token": _authz_token()}).encode()+ messages = iter(chunks or [{"type": "http.request", "body": body}])+ sent = []++ async def receive():+ return next(messages)++ async def send(message):+ sent.append(message)++ scope = {"type": "http", "method": method, "path": rds_iam.PATH, "query_string": query,+ "headers": headers if headers is not None else [+ (b"content-type", b"application/json"), (b"x-ministack-rds-capability", cap.encode()),+ ]}+ asyncio.run(app_module.app(scope, receive, send))+ return sent[0]["status"], json.loads(sent[1]["body"])++[email protected]("auth", [False, True])[email protected]("enabled", [False, True])[email protected]("valid_token", [False, True])+def test_auth_and_enablement_matrix(ep_state, monkeypatch, auth, enabled, valid_token):+ monkeypatch.setattr(app_module, "AUTH", auth)+ ep_state["IAMDatabaseAuthenticationEnabled"] = enabled+ before = get_account_id(), get_region()+ result = request(capability(), payload={"username": AUTHZ_USER, "token": _authz_token() if valid_token else ""})+ allowed = enabled and (not auth or valid_token)+ assert result == (200 if allowed else 403, {"allowed": allowed})+ assert (get_account_id(), get_region()) == before+++def test_permissive_never_calls_authorizer(ep_state, monkeypatch):+ monkeypatch.setattr(app_module, "AUTH", False)++ def unexpected(*args, **kwargs):+ pytest.fail("Permissive mode called IAM authorizer")++ monkeypatch.setattr(rds_iam, "authorize_rds_iam_token", unexpected)+ assert request(capability(), payload={"username": AUTHZ_USER, "token": "not-a-token"})[0] == 200++[email protected]("auth", [False, True])+def test_missing_invalid_rotated_revoked_capabilities(ep_state, monkeypatch, auth):+ monkeypatch.setattr(app_module, "AUTH", auth)+ old = capability()+ new = capability()+ for cap in ("", "f" * 64, old):+ assert request(cap)[0] == 403+ assert request(new)[0] == 200+ rds_iam.revoke_capability(new)+ assert request(new)[0] == 403++[email protected]("change", ["replace", "delete", "id", "reset"])+def test_stale_binding_cannot_authorize(ep_state, monkeypatch, change):+ monkeypatch.setattr(app_module, "AUTH", False)+ cap = capability()+ if change == "replace":+ rds._instances.set_scoped(ACCOUNT, REGION, "database", dict(ep_state))+ elif change == "delete":+ rds._instances.pop_scoped(ACCOUNT, REGION, "database")+ elif change == "id":+ ep_state["DbiResourceId"] = "db-NEW"+ else:+ rds_iam.reset()+ assert request(cap)[0] == 403++[email protected]("body", [b"null", b"[]", b"{", b'{}', b'\xff',+ b'{"username":"x","username":"y","token":""}',+ b'{"username":"x","token":"","account_id":"123456789012"}',+ b'{"username":"","token":""}', b'{"username":"x","token":null}',+ b'{"username":"x","token":"","resource_identifier":"other"}'])+def test_malformed_payloads_denied_in_permissive_mode(ep_state, monkeypatch, body):+ monkeypatch.setattr(app_module, "AUTH", False)+ assert request(capability(), body=body) == (403, {"allowed": False})+++def test_chunked_body_limit_and_disconnect(ep_state, monkeypatch):+ monkeypatch.setattr(app_module, "AUTH", False)+ cap = capability()+ assert request(cap, chunks=[{"type": "http.request", "body": b" " * rds_iam.MAX_BODY, "more_body": True},+ {"type": "http.request", "body": b"x"}])[0] == 403+ assert request(cap, chunks=[{"type": "http.disconnect"}])[0] == 403+ assert request(cap, chunks=[{"type": "http.request", "body": b'{"username":"x",', "more_body": True},+ {"type": "http.request", "body": b'"token":""}'}])[0] == 200++[email protected]("kind", ["query", "get", "duplicate", "gzip"])+def test_transport_constraints(ep_state, monkeypatch, kind):+ monkeypatch.setattr(app_module, "AUTH", False)+ cap = capability()+ headers = [(b"content-type", b"application/json"), (b"x-ministack-rds-capability", cap.encode())]+ if kind == "duplicate":+ headers.append(headers[-1])+ if kind == "gzip":+ headers.append((b"content-encoding", b"gzip"))+ assert request(cap, headers=headers, query=b"token=secret" if kind == "query" else b"",+ method="GET" if kind == "get" else "POST")[0] == 403+++def test_timeout(ep_state, monkeypatch):+ monkeypatch.setattr(rds_iam, "BODY_TIMEOUT", 0.001)+ sent = []++ async def receive():+ await asyncio.sleep(1)++ async def send(message):+ sent.append(message)++ asyncio.run(rds_iam.handle({"method": "POST", "headers": [+ (b"content-type", b"application/json"), (b"x-ministack-rds-capability", capability().encode()),+ ]}, receive, send, auth_enabled=False))+ assert sent[0]["status"] == 403+++def test_authorizer_failure_does_not_log_secrets(ep_state, monkeypatch, caplog):+ monkeypatch.setattr(app_module, "AUTH", True)+ cap = capability()++ def broken(*args, **kwargs):+ raise RuntimeError("secret-_authz_token " + cap)++ monkeypatch.setattr(rds_iam, "authorize_rds_iam_token", broken)+ assert request(cap, payload={"username": AUTHZ_USER, "token": "secret-token"}) == (403, {"allowed": False})+ assert cap not in caplog.text+ assert "secret-token" not in caplog.text+++def test_aurora_parent_flag_and_replacement(ep_state, monkeypatch):+ monkeypatch.setattr(app_module, "AUTH", False)+ ep_state.update(Engine="aurora-mysql", DBClusterIdentifier="cluster")+ owner = {"Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",+ "IAMDatabaseAuthenticationEnabled": False}+ rds._clusters.set_scoped(ACCOUNT, REGION, "cluster", owner)+ cap = capability()+ assert request(cap)[0] == 403+ owner["IAMDatabaseAuthenticationEnabled"] = True+ assert request(cap)[0] == 200+ rds._clusters.set_scoped(ACCOUNT, REGION, "cluster", dict(owner))+ assert request(cap)[0] == 403++[email protected]("auth", [False, True])+def test_policy_denial_only_enforced_when_auth_enabled(ep_state, monkeypatch, auth):+ monkeypatch.setattr(app_module, "AUTH", auth)+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {})+ assert request(capability())[0] == (403 if auth else 200)+++def test_capability_selects_resource_even_with_identical_endpoint(ep_state, monkeypatch):+ monkeypatch.setattr(app_module, "AUTH", True)+ rds._instances.set_scoped(ACCOUNT, REGION, "other", {**ep_state, "DbiResourceId": "db-OTHER"})+ cap = rds_iam.issue_capability(account_id=ACCOUNT, region=REGION, resource_kind="instance",+ resource_identifier="other")+ assert request(cap)[0] == 403 # Token's user policy grants only db-TEST.+++def test_revocation_during_body_read_fails_closed(ep_state, monkeypatch):+ monkeypatch.setattr(app_module, "AUTH", False)+ cap = capability()+ sent = []++ async def receive():+ rds_iam.revoke_capability(cap)+ return {"type": "http.request", "body": b'{"username":"x","token":""}'}++ async def send(message):+ sent.append(message)++ asyncio.run(rds_iam.handle({"method": "POST", "headers": [+ (b"content-type", b"application/json"), (b"x-ministack-rds-capability", cap.encode()),+ ]}, receive, send, auth_enabled=False))+ assert sent[0]["status"] == 403++[email protected]("aurora", [False, True])[email protected]("change", ["target", "owner", "id", "disable", "delete"])+def test_binding_changed_during_authorization_fails_closed(ep_state, monkeypatch, aurora, change):+ monkeypatch.setattr(app_module, "AUTH", True)+ owner = ep_state+ if aurora:+ ep_state.update(Engine="aurora-mysql", DBClusterIdentifier="cluster")+ owner = {"Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",+ "IAMDatabaseAuthenticationEnabled": True}+ rds._clusters.set_scoped(ACCOUNT, REGION, "cluster", owner)+ cap = capability()+ authorize = rds_iam.authorize_rds_iam_token+ decisions = []++ def mutate_then_authorize(*args, **kwargs):+ if change == "target":+ rds._instances.set_scoped(ACCOUNT, REGION, "database", dict(ep_state))+ elif change == "owner":+ store, identifier = (rds._clusters, "cluster") if aurora else (rds._instances, "database")+ store.set_scoped(ACCOUNT, REGION, identifier, dict(owner))+ elif change == "id":+ owner["DbClusterResourceId" if aurora else "DbiResourceId"] = "cluster-NEW" if aurora else "db-NEW"+ # For replacement/id mutations, the real authorizer can allow the new+ # resource. For disable/delete, mutate just after a real allow result.+ result = authorize(*args, **kwargs)+ decisions.append(result)+ if change == "disable":+ owner["IAMDatabaseAuthenticationEnabled"] = False+ elif change == "delete":+ rds._instances.pop_scoped(ACCOUNT, REGION, "database")+ return result++ monkeypatch.setattr(rds_iam, "authorize_rds_iam_token", mutate_then_authorize)+ assert request(cap, payload={"username": AUTHZ_USER, "token": _authz_token(key="test", secret="root-secret")}) == (+ 403, {"allowed": False},+ )+ assert len(decisions) == 1+ assert isinstance(decisions[0], rds_iam.AuthorizedRdsConnection)diff --git a/tests/test_rds_iam_broker.py b/tests/test_rds_iam_broker.pydeleted file mode 100644index fd4b0a94..00000000--- a/tests/test_rds_iam_broker.py+++ /dev/null@@ -1,274 +0,0 @@-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT-# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).-"""Offline ASGI broker tests; no database or Docker resources required."""--import asyncio-import importlib-import json--import pytest-from test_rds_iam import ACCOUNT, AUTHZ_HOST, AUTHZ_KEY, AUTHZ_SECRET, REGION, _authz_policy-from test_rds_iam import AUTHZ_ARGS as ARGS-from test_rds_iam import AUTHZ_USER as USER-from test_rds_iam import _authz_token as token--from ministack.core import rds_iam_broker as broker-from ministack.core.responses import AccountRegionScopedDict, AccountScopedDict, get_account_id, get_region-from ministack.services import iam, rds, sts--app_module = importlib.import_module("ministack.app")---def state(monkeypatch):- """Isolate the broker's resource and IAM state using the shared token inputs."""- for name in ("_users", "_access_keys", "_user_inline_policies", "_roles", "_groups",- "_group_inline_policies", "_policies"):- monkeypatch.setattr(iam, name, AccountScopedDict())- monkeypatch.setattr(rds, "_instances", AccountRegionScopedDict())- monkeypatch.setattr(rds, "_clusters", AccountRegionScopedDict())- monkeypatch.setattr(sts, "_sessions", {})- monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test")- monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "root-secret")- monkeypatch.delenv("AWS_SESSION_TOKEN", raising=False)- iam._users.set_scoped(ACCOUNT, None, "alice", {- "UserName": "alice", "Arn": f"arn:aws:iam::{ACCOUNT}:user/alice",- })- iam._access_keys.set_scoped(ACCOUNT, None, AUTHZ_KEY, {- "UserName": "alice", "Status": "Active", "SecretAccessKey": AUTHZ_SECRET,- })- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"connect": _authz_policy()})- instance = dict(Engine="mysql", DbiResourceId="db-TEST", IAMDatabaseAuthenticationEnabled=True,- Endpoint={"Address": AUTHZ_HOST, "Port": 3306})- rds._instances.set_scoped(ACCOUNT, REGION, "database", instance)- return instance--[email protected](autouse=True)-def clean_broker():- broker.reset()- yield- broker.reset()---def capability():- return broker.issue_capability(**{k: v for k, v in ARGS.items() if k != "db_user"})---def request(cap, *, payload=None, body=None, headers=None, method="POST", query=b"", chunks=None):- if body is None:- body = json.dumps(payload if payload is not None else {"username": USER, "token": token()}).encode()- messages = iter(chunks or [{"type": "http.request", "body": body}])- sent = []-- async def receive():- return next(messages)-- async def send(message):- sent.append(message)-- scope = {"type": "http", "method": method, "path": broker.PATH, "query_string": query,- "headers": headers if headers is not None else [- (b"content-type", b"application/json"), (b"x-ministack-rds-capability", cap.encode()),- ]}- asyncio.run(app_module.app(scope, receive, send))- return sent[0]["status"], json.loads(sent[1]["body"])--[email protected]("auth", [False, True])[email protected]("enabled", [False, True])[email protected]("valid_token", [False, True])-def test_auth_and_enablement_matrix(state, monkeypatch, auth, enabled, valid_token):- monkeypatch.setattr(app_module, "AUTH", auth)- state["IAMDatabaseAuthenticationEnabled"] = enabled- before = get_account_id(), get_region()- result = request(capability(), payload={"username": USER, "token": token() if valid_token else ""})- allowed = enabled and (not auth or valid_token)- assert result == (200 if allowed else 403, {"allowed": allowed})- assert (get_account_id(), get_region()) == before---def test_permissive_never_calls_authorizer(state, monkeypatch):- monkeypatch.setattr(app_module, "AUTH", False)-- def unexpected(*args, **kwargs):- pytest.fail("Permissive mode called IAM authorizer")-- monkeypatch.setattr(broker, "authorize_rds_iam_token", unexpected)- assert request(capability(), payload={"username": USER, "token": "not-a-token"})[0] == 200--[email protected]("auth", [False, True])-def test_missing_invalid_rotated_revoked_capabilities(state, monkeypatch, auth):- monkeypatch.setattr(app_module, "AUTH", auth)- old = capability()- new = capability()- for cap in ("", "f" * 64, old):- assert request(cap)[0] == 403- assert request(new)[0] == 200- broker.revoke_capability(new)- assert request(new)[0] == 403--[email protected]("change", ["replace", "delete", "id", "reset"])-def test_stale_binding_cannot_authorize(state, monkeypatch, change):- monkeypatch.setattr(app_module, "AUTH", False)- cap = capability()- if change == "replace":- rds._instances.set_scoped(ACCOUNT, REGION, "database", dict(state))- elif change == "delete":- rds._instances.pop_scoped(ACCOUNT, REGION, "database")- elif change == "id":- state["DbiResourceId"] = "db-NEW"- else:- broker.reset()- assert request(cap)[0] == 403--[email protected]("body", [b"null", b"[]", b"{", b'{}', b'\xff',- b'{"username":"x","username":"y","token":""}',- b'{"username":"x","token":"","account_id":"123456789012"}',- b'{"username":"","token":""}', b'{"username":"x","token":null}',- b'{"username":"x","token":"","resource_identifier":"other"}'])-def test_malformed_payloads_denied_in_permissive_mode(state, monkeypatch, body):- monkeypatch.setattr(app_module, "AUTH", False)- assert request(capability(), body=body) == (403, {"allowed": False})---def test_chunked_body_limit_and_disconnect(state, monkeypatch):- monkeypatch.setattr(app_module, "AUTH", False)- cap = capability()- assert request(cap, chunks=[{"type": "http.request", "body": b" " * broker.MAX_BODY, "more_body": True},- {"type": "http.request", "body": b"x"}])[0] == 403- assert request(cap, chunks=[{"type": "http.disconnect"}])[0] == 403- assert request(cap, chunks=[{"type": "http.request", "body": b'{"username":"x",', "more_body": True},- {"type": "http.request", "body": b'"token":""}'}])[0] == 200--[email protected]("kind", ["query", "get", "duplicate", "gzip"])-def test_transport_constraints(state, monkeypatch, kind):- monkeypatch.setattr(app_module, "AUTH", False)- cap = capability()- headers = [(b"content-type", b"application/json"), (b"x-ministack-rds-capability", cap.encode())]- if kind == "duplicate":- headers.append(headers[-1])- if kind == "gzip":- headers.append((b"content-encoding", b"gzip"))- assert request(cap, headers=headers, query=b"token=secret" if kind == "query" else b"",- method="GET" if kind == "get" else "POST")[0] == 403---def test_timeout(state, monkeypatch):- monkeypatch.setattr(broker, "BODY_TIMEOUT", 0.001)- sent = []-- async def receive():- await asyncio.sleep(1)-- async def send(message):- sent.append(message)-- asyncio.run(broker.handle({"method": "POST", "headers": [- (b"content-type", b"application/json"), (b"x-ministack-rds-capability", capability().encode()),- ]}, receive, send, auth_enabled=False))- assert sent[0]["status"] == 403---def test_authorizer_failure_does_not_log_secrets(state, monkeypatch, caplog):- monkeypatch.setattr(app_module, "AUTH", True)- cap = capability()-- def broken(*args, **kwargs):- raise RuntimeError("secret-token " + cap)-- monkeypatch.setattr(broker, "authorize_rds_iam_token", broken)- assert request(cap, payload={"username": USER, "token": "secret-token"}) == (403, {"allowed": False})- assert cap not in caplog.text- assert "secret-token" not in caplog.text---def test_aurora_parent_flag_and_replacement(state, monkeypatch):- monkeypatch.setattr(app_module, "AUTH", False)- state.update(Engine="aurora-mysql", DBClusterIdentifier="cluster")- owner = {"Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",- "IAMDatabaseAuthenticationEnabled": False}- rds._clusters.set_scoped(ACCOUNT, REGION, "cluster", owner)- cap = capability()- assert request(cap)[0] == 403- owner["IAMDatabaseAuthenticationEnabled"] = True- assert request(cap)[0] == 200- rds._clusters.set_scoped(ACCOUNT, REGION, "cluster", dict(owner))- assert request(cap)[0] == 403--[email protected]("auth", [False, True])-def test_policy_denial_only_enforced_when_auth_enabled(state, monkeypatch, auth):- monkeypatch.setattr(app_module, "AUTH", auth)- iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {})- assert request(capability())[0] == (403 if auth else 200)---def test_capability_selects_resource_even_with_identical_endpoint(state, monkeypatch):- monkeypatch.setattr(app_module, "AUTH", True)- rds._instances.set_scoped(ACCOUNT, REGION, "other", {**state, "DbiResourceId": "db-OTHER"})- cap = broker.issue_capability(account_id=ACCOUNT, region=REGION, resource_kind="instance",- resource_identifier="other")- assert request(cap)[0] == 403 # Token's user policy grants only db-TEST.---def test_revocation_during_body_read_fails_closed(state, monkeypatch):- monkeypatch.setattr(app_module, "AUTH", False)- cap = capability()- sent = []-- async def receive():- broker.revoke_capability(cap)- return {"type": "http.request", "body": b'{"username":"x","token":""}'}-- async def send(message):- sent.append(message)-- asyncio.run(broker.handle({"method": "POST", "headers": [- (b"content-type", b"application/json"), (b"x-ministack-rds-capability", cap.encode()),- ]}, receive, send, auth_enabled=False))- assert sent[0]["status"] == 403--[email protected]("aurora", [False, True])[email protected]("change", ["target", "owner", "id", "disable", "delete"])-def test_binding_changed_during_authorization_fails_closed(state, monkeypatch, aurora, change):- monkeypatch.setattr(app_module, "AUTH", True)- owner = state- if aurora:- state.update(Engine="aurora-mysql", DBClusterIdentifier="cluster")- owner = {"Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",- "IAMDatabaseAuthenticationEnabled": True}- rds._clusters.set_scoped(ACCOUNT, REGION, "cluster", owner)- cap = capability()- authorize = broker.authorize_rds_iam_token- decisions = []-- def mutate_then_authorize(*args, **kwargs):- if change == "target":- rds._instances.set_scoped(ACCOUNT, REGION, "database", dict(state))- elif change == "owner":- store, identifier = (rds._clusters, "cluster") if aurora else (rds._instances, "database")- store.set_scoped(ACCOUNT, REGION, identifier, dict(owner))- elif change == "id":- owner["DbClusterResourceId" if aurora else "DbiResourceId"] = "cluster-NEW" if aurora else "db-NEW"- # For replacement/id mutations, the real authorizer can allow the new- # resource. For disable/delete, mutate just after a real allow result.- result = authorize(*args, **kwargs)- decisions.append(result)- if change == "disable":- owner["IAMDatabaseAuthenticationEnabled"] = False- elif change == "delete":- rds._instances.pop_scoped(ACCOUNT, REGION, "database")- return result-- monkeypatch.setattr(broker, "authorize_rds_iam_token", mutate_then_authorize)- assert request(cap, payload={"username": USER, "token": token(key="test", secret="root-secret")}) == (- 403, {"allowed": False},- )- assert len(decisions) == 1- assert isinstance(decisions[0], broker.AuthorizedRdsConnection)diff --git a/tests/test_rds_tls_material.py b/tests/test_rds_tls_material.pydeleted file mode 100644index 9fb57d26..00000000--- a/tests/test_rds_tls_material.py+++ /dev/null@@ -1,88 +0,0 @@-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT-# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).-"""In-process certificate tests; no Docker or running MiniStack is needed.--Run with ``pytest --noconftest tests/test_rds_tls_material.py`` to avoid the-integration suite's server-reset fixture.-"""--import ipaddress-import ssl--import pytest--pytest.importorskip("cryptography")--from cryptography import x509 # noqa: E402-from cryptography.x509.oid import NameOID # noqa: E402--from ministack.services import rds # noqa: E402---def _verify(ca_pem, cert_pem, key_pem, hostname, tmp_path):- """Perform a real verifying TLS handshake entirely through memory BIOs."""- chain = tmp_path / "server.pem"- chain.write_text(cert_pem + key_pem)- server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)- server_context.load_cert_chain(chain)- client_context = ssl.create_default_context(cadata=ca_pem)- client_context.verify_flags |= ssl.VERIFY_X509_STRICT- client_context.hostname_checks_common_name = False- client_in, client_out = ssl.MemoryBIO(), ssl.MemoryBIO()- server_in, server_out = ssl.MemoryBIO(), ssl.MemoryBIO()- client = client_context.wrap_bio(client_in, client_out, server_hostname=hostname)- server = server_context.wrap_bio(server_in, server_out, server_side=True)- done = set()- for _ in range(10):- for endpoint in (client, server):- if endpoint not in done:- try:- endpoint.do_handshake()- done.add(endpoint)- except ssl.SSLWantReadError:- pass- server_in.write(client_out.read())- client_in.write(server_out.read())- if len(done) == 2:- return- pytest.fail("TLS handshake did not complete")---def ca_pem(monkeypatch):- # Leave module-level CA state exactly as it was before this unit test.- monkeypatch.setattr(rds, "_pg_ca", None)- return rds.pg_ca_cert_pem()--[email protected]("hostname", [- "db.example.test",- "db-" + "a" * 37 + ".cluster-abcdefghijkl.us-east-1.rds.amazonaws.com",-])-def test_pg_certificate_preserves_and_verifies_all_sans(hostname, ca_pem, tmp_path):- names = [hostname, "reader." + hostname, "localhost"]- ips = ["127.0.0.1", "::1"]- cert_pem, key_pem = rds._pg_server_material(names, ips)- cert = x509.load_pem_x509_certificate(cert_pem.encode())- cn = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value- assert len(cn.encode("utf-8")) <= 64- sans = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value- assert sans.get_values_for_type(x509.DNSName) == names- assert sans.get_values_for_type(x509.IPAddress) == [ipaddress.ip_address(ip) for ip in ips]- for name in names + ips:- _verify(ca_pem, cert_pem, key_pem, name, tmp_path)- with pytest.raises(ssl.SSLCertVerificationError):- _verify(ca_pem, cert_pem, key_pem, "unlisted.example.test", tmp_path)---def test_pg_certificate_without_dns_names_verifies_ip(ca_pem, tmp_path):- cert_pem, key_pem = rds._pg_server_material([], ["127.0.0.1"])- _verify(ca_pem, cert_pem, key_pem, "127.0.0.1", tmp_path)---def test_pg_certificate_crypto_failure_propagates(monkeypatch, ca_pem):- from ministack.core import x509_utils-- monkeypatch.setattr(x509_utils, "HAS_CRYPTO", False)- with pytest.raises(RuntimeError, match="requires the `cryptography` package"):- rds._pg_server_material(["localhost"], [])