Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(lambda): copy the TLS trust files into Lambda containers when MiniStack runs in Docker (#1932)
Jeff Hellerfd7a9a1ac483
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e19049d1..e0a716ff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed++- **Lambda — Docker executor under `USE_SSL=1` when MiniStack runs in a container** — the gateway certificate, CA bundle and Java truststore were bind-mounted into every Lambda container from MiniStack's own filesystem (`MINISTACK_SSL_CERT`, or the generated `ministack-tls/server.crt` under the temp directory), paths the host Docker daemon cannot see, so every invocation failed with `bind source path does not exist`. In a container they are now copied into the Lambda container, as function code already is.- **ECS — forced rolling deployments replace tasks and refresh images** — `UpdateService(forceNewDeployment=True)` replaces tasks even when the task definition is unchanged or omitted. Rolling deployments preserve scheduling limits, wait for replacement tasks to stabilize, and retain circuit-breaker rollback; zero-sized deployments drain old tasks and complete. Docker-backed services pin image digests per deployment, honor `versionConsistency: disabled`, and use Secrets Manager credentials for private registries. Tasks report resolved image digests and Fargate platform fields. Cached images remain usable on both launch types, including MiniStack ECR images, preserving MiniStack’s intentional offline fallback.- **IoT — mTLS trusts every registered device certificate** — the listener no longer fails the TLS handshake for an ACTIVE certificate whose CA was deactivated or deleted before its first connect, or that was registered without a CA; as on AWS, only the certificate's own status refuses it.### Addeddiff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 2db5fcae..0be8d9aa 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -3845,6 +3845,18 @@ def _docker_cp_dir(container, src_dir: str, dest_dir: str, arcname: str = "."):container.put_archive(dest_dir, buf)+def _docker_cp_file(container, src_path: str, dest_path: str):+ """Copy one local file into a Docker container at ``dest_path``, creating+ its parent directories (``put_archive`` needs an existing destination).+ A symlinked source is followed, as a bind mount would."""+ import tarfile+ buf = io.BytesIO()+ with tarfile.open(fileobj=buf, mode="w", dereference=True) as tar:+ tar.add(src_path, arcname=dest_path.lstrip("/"))+ buf.seek(0)+ container.put_archive("/", buf)++# Bare-text body the RIE answers with (HTTP 200) when a run hits the function# timeout (#1845); it is not a JSON error payload._RIE_TIMEOUT_TEXT_RE = re.compile(r"Task timed out after \d+\.\d\d seconds")@@ -4119,8 +4131,13 @@ _CONTAINER_BUNDLE_PATH = "/var/ministack/ca-bundle.pem"_CONTAINER_TRUSTSTORE_PATH = "/var/ministack/truststore.p12"-def _wire_cognito_issuer_host(run_kwargs, container_env, mounts, runtime=""):- """Under USE_SSL=1, resolve the Cognito issuer hosts to the gateway and trust its cert."""+def _wire_cognito_issuer_host(run_kwargs, container_env, mounts, runtime="", copies=None):+ """Under USE_SSL=1, resolve the Cognito issuer hosts to the gateway and trust its cert.++ With ``copies`` (DinD: the host daemon cannot see this container's files) the+ trust files are listed there as ``(container_path, local_path)`` for docker cp+ instead of being bind-mounted.+ """from ministack.core import tls as _tlsif not _tls.use_ssl_enabled():@@ -4136,20 +4153,24 @@ def _wire_cognito_issuer_host(run_kwargs, container_env, mounts, runtime=""):return# NODE_EXTRA_CA_CERTS adds to node's roots; the other two replace the store.bundle = _tls.ca_bundle_path(cert_path)- mounts.append(docker_lib.types.Mount(- _CONTAINER_CA_PATH, cert_path, type="bind", read_only=True))++ def trust(target, source):+ if copies is not None:+ copies.append((target, source))+ else:+ mounts.append(docker_lib.types.Mount(target, source, type="bind", read_only=True))++ trust(_CONTAINER_CA_PATH, cert_path)container_env.setdefault("NODE_EXTRA_CA_CERTS", _CONTAINER_CA_PATH)if bundle:- mounts.append(docker_lib.types.Mount(- _CONTAINER_BUNDLE_PATH, bundle, type="bind", read_only=True))+ trust(_CONTAINER_BUNDLE_PATH, bundle)for var in ("AWS_CA_BUNDLE", "REQUESTS_CA_BUNDLE"):container_env.setdefault(var, _CONTAINER_BUNDLE_PATH)# A JVM reads none of the above, and announces JAVA_TOOL_OPTIONS on stderr.if runtime.startswith("java"):store = _tls.java_truststore_path(cert_path)if store:- mounts.append(docker_lib.types.Mount(- _CONTAINER_TRUSTSTORE_PATH, store, type="bind", read_only=True))+ trust(_CONTAINER_TRUSTSTORE_PATH, store)container_env.setdefault("JAVA_TOOL_OPTIONS", " ".join((f"-Djavax.net.ssl.trustStore={_CONTAINER_TRUSTSTORE_PATH}","-Djavax.net.ssl.trustStoreType=pkcs12",@@ -4540,7 +4561,8 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,container_env["_MS_REAL_HANDLER"] = handlerrun_kwargs["command"] = [shim_cmd]- _wire_cognito_issuer_host(run_kwargs, container_env, mounts, runtime)+ trust_copies = [] if _running_in_container() else None+ _wire_cognito_issuer_host(run_kwargs, container_env, mounts, runtime, trust_copies)if mounts:run_kwargs["mounts"] = mounts@@ -4615,7 +4637,7 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,raise RuntimeError(f"Failed to pull image {image}: {exc}")try:- if _use_docker_cp or _cp_layers:+ if _use_docker_cp or _cp_layers or trust_copies:create_kwargs = {k: v for k, v in run_kwargs.items()if k not in ("detach", "stdin_open")}container = client.containers.create(**create_kwargs)@@ -4632,6 +4654,8 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,# layer ordering. Fixes issue #888.for ld in layers_dirs:_docker_cp_dir(container, ld, "/opt", arcname=".")+ for target, source in trust_copies or ():+ _docker_cp_file(container, source, target)container.start()else:container = client.containers.run(**run_kwargs)diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 7057b707..96463c6d 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -13957,6 +13957,52 @@ def test_cognito_issuer_host_resolves_to_the_gateway_under_use_ssl(monkeypatch,(lsvc._CONTAINER_CA_PATH, True), (lsvc._CONTAINER_BUNDLE_PATH, True)]+def test_lambda_trust_files_are_copied_not_mounted_when_ministack_runs_in_docker(monkeypatch, tmp_path):+ """In a container, a bind source resolves on the host daemon, where+ MiniStack's certificate does not exist: the trust files are docker cp'd+ instead, for a container-image function too, and a symlink is followed."""+ import tarfile++ real = tmp_path / "real.crt"+ real.write_text("-----BEGIN CERTIFICATE-----\n")+ (tmp_path / "server.crt").symlink_to(real)+ (tmp_path / "server.key").write_text("key")+ monkeypatch.setenv("USE_SSL", "1")+ monkeypatch.setenv("MINISTACK_SSL_CERT", str(tmp_path / "server.crt"))+ monkeypatch.setenv("MINISTACK_SSL_KEY", str(tmp_path / "server.key"))+ monkeypatch.setattr(lsvc, "_is_in_container", True)+ monkeypatch.setattr(lsvc, "_docker_available", True)+ monkeypatch.setattr(lsvc, "LAMBDA_DOCKER_FLAGS", "")++ captured, archived = {}, {}+ container = _mk_container()+ container.ports = {"8080/tcp": [{"HostPort": "9999"}]}++ def _put_archive(path, data):+ with tarfile.open(fileobj=data) as tar:+ archived.update({(path, m.name): m.isfile() for m in tar.getmembers()})++ container.put_archive.side_effect = _put_archive++ def _capture(**kwargs):+ captured.update(kwargs)+ return container++ client = MagicMock()+ client.containers.run = _capture+ client.containers.create = _capture+ monkeypatch.setattr(lsvc, "_get_docker_client", lambda: client)++ lsvc._spawn_lambda_container(+ {"FunctionName": "trust-fn", "PackageType": "Image", "ImageUri": "my-repo/my-image:latest",+ "Timeout": 3, "MemorySize": 128,+ "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:trust-fn"},+ None,+ )+ assert [m["Target"] for m in captured.get("mounts", []) if m["Target"].startswith("/var/ministack/")] == []+ assert archived[("/", "var/ministack/ministack-ca.pem")] is True++def test_cognito_issuer_wiring_never_overrides_the_caller(monkeypatch, tmp_path):"""LAMBDA_DOCKER_FLAGS --add-host and a function's own env come first."""from ministack.services import lambda_svc as lsvc