Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

poc: mint cert from docker host (#1806)

Nahuel Nucera54def7b891c3
diff --git a/ministack/app.py b/ministack/app.py
index af913b7d..2ea6624b 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -494,6 +494,19 @@ def _resolve_port():
return os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"
+def _port_is_bindable(host: str, port: int) -> bool:
+ """Whether `port` can be opened here: free, and permitted to this process."""
+ import socket as _socket
+
+ with _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM) as probe:
+ probe.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
+ try:
+ probe.bind(("" if host == "0.0.0.0" else host, port))
+ except OSError:
+ return False
+ return True
+
+
if os.environ.get("LOCALSTACK_PERSISTENCE") == "1" and os.environ.get("S3_PERSIST") != "1":
os.environ["S3_PERSIST"] = "1"
logger.info("LOCALSTACK_PERSISTENCE=1 detected — enabling S3_PERSIST")
@@ -3239,8 +3252,19 @@ def main():
if _tls.use_ssl_enabled():
config.certfile, config.keyfile = _tls.resolve_tls_material()
+ # A Cognito token's `iss` is https with no port, so clients ask 443.
+ if port != "443" and _port_is_bindable(bind_host, 443):
+ config.bind.append(f"{bind_host}:443")
- asyncio.run(hypercorn_serve(app, config))
+ try:
+ asyncio.run(hypercorn_serve(app, config))
+ except OSError:
+ if len(config.bind) == 1:
+ raise
+ config.bind = config.bind[:1]
+ logger.warning("Port 443 became unavailable; serving on %s only",
+ config.bind[0])
+ asyncio.run(hypercorn_serve(app, config))
finally:
_cleanup()
diff --git a/ministack/core/tls.py b/ministack/core/tls.py
index cefc7462..ca4abbc3 100644
--- a/ministack/core/tls.py
+++ b/ministack/core/tls.py
@@ -4,8 +4,8 @@
`USE_SSL=1` enables HTTPS (LocalStack-compatible). Self-signed cert
generation shells out to the `openssl` CLI present in both base images
-(alpine adds it via `apk add openssl`; debian/slim already ships it),
-so this module has no Python crypto dep.
+(alpine adds it via `apk add openssl`; debian/slim already ships it). Only the
+Java truststore needs a Python crypto dep, and degrades to None without one.
"""
import os
@@ -14,10 +14,102 @@ import sys
import tempfile
+def _write_atomic(path: str, data: bytes) -> "str | None":
+ """Write `data` to `path` via a rename, or None on failure.
+
+ Containers spawn concurrently and mount these files, so a reader must never
+ see a half-written one.
+ """
+ try:
+ handle, staging = tempfile.mkstemp(dir=os.path.dirname(path))
+ with os.fdopen(handle, "wb") as out:
+ out.write(data)
+ os.replace(staging, path)
+ except OSError:
+ return None
+ return path
+
+
def use_ssl_enabled() -> bool:
return os.environ.get("USE_SSL", "").strip().lower() in ("1", "true", "yes")
+def cognito_idp_host() -> str:
+ """The host a Cognito token's `iss` names, which clients fetch keys from."""
+ region = os.environ.get("MINISTACK_REGION", "us-east-1")
+ return f"cognito-idp.{region}.amazonaws.com"
+
+
+def ca_bundle_path(cert_path: str) -> "str | None":
+ """Public roots plus `cert_path`, or None.
+
+ AWS_CA_BUNDLE and REQUESTS_CA_BUNDLE replace the trust store rather than
+ adding to it, so ours alone would cost the caller every other endpoint.
+ """
+ import ssl
+
+ paths = ssl.get_default_verify_paths()
+ system = paths.cafile or paths.openssl_cafile
+ if not system or not os.path.exists(system):
+ return None
+ try:
+ blob = b"\n".join(open(source, "rb").read() for source in (system, cert_path))
+ except OSError:
+ return None
+ return _write_atomic(os.path.join(os.path.dirname(cert_path), "ca-bundle.pem"), blob)
+
+
+JAVA_TRUSTSTORE_PASSWORD = "changeit"
+
+
+def java_truststore_path(cert_path: str) -> "str | None":
+ """The same trust as `ca_bundle_path` in the PKCS12 a JVM reads, or None.
+
+ Written here rather than with `keytool` so no JDK is needed on this side.
+ """
+ try:
+ from cryptography import x509
+ from cryptography.hazmat.primitives.serialization import (
+ BestAvailableEncryption,
+ pkcs12,
+ )
+ except ImportError:
+ return None
+ import ssl
+ import warnings
+
+ paths = ssl.get_default_verify_paths()
+ system = paths.cafile or paths.openssl_cafile
+ if not system or not os.path.exists(system):
+ return None
+ try:
+ with warnings.catch_warnings():
+ # Non-positive serials in the shipped roots: warns now, raises later.
+ warnings.simplefilter("ignore")
+ roots = x509.load_pem_x509_certificates(open(system, "rb").read())
+ roots.extend(x509.load_pem_x509_certificates(open(cert_path, "rb").read()))
+ blob = pkcs12.serialize_key_and_certificates(
+ name=b"ministack", key=None, cert=None, cas=roots,
+ encryption_algorithm=BestAvailableEncryption(
+ JAVA_TRUSTSTORE_PASSWORD.encode()),
+ )
+ except Exception:
+ return None
+ return _write_atomic(os.path.join(os.path.dirname(cert_path), "truststore.p12"), blob)
+
+
+def _cert_names(cert_path: str, name: str) -> bool:
+ """Whether the certificate at `cert_path` carries `name` as a SAN."""
+ try:
+ out = subprocess.run(
+ ["openssl", "x509", "-in", cert_path, "-noout", "-ext", "subjectAltName"],
+ capture_output=True, text=True, check=False,
+ )
+ except OSError:
+ return True # No openssl to check with; leave the cached cert alone.
+ return name in (out.stdout or "")
+
+
def resolve_tls_material() -> "tuple[str, str]":
"""Return (certfile, keyfile) PEM paths.
@@ -42,13 +134,20 @@ def resolve_tls_material() -> "tuple[str, str]":
os.makedirs(tls_dir, exist_ok=True)
cert_path = os.path.join(tls_dir, "server.crt")
key_path = os.path.join(tls_dir, "server.key")
+ if (os.path.exists(cert_path) and os.path.exists(key_path)
+ and not _cert_names(cert_path, cognito_idp_host())):
+ # Cached by an older build or another region: cannot serve that name.
+ os.remove(cert_path)
+ os.remove(key_path)
if not (os.path.exists(cert_path) and os.path.exists(key_path)):
subprocess.run([
"openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
"-keyout", key_path, "-out", cert_path,
"-days", "825",
"-subj", "/CN=ministack-local/O=MiniStack",
- "-addext", "subjectAltName=DNS:localhost,DNS:ministack,IP:127.0.0.1,IP:0:0:0:0:0:0:0:1",
+ "-addext",
+ "subjectAltName=DNS:localhost,DNS:ministack,"
+ f"DNS:{cognito_idp_host()},IP:127.0.0.1,IP:0:0:0:0:0:0:0:1",
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
os.chmod(cert_path, 0o600)
os.chmod(key_path, 0o600)
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 973ed479..800db387 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -4083,6 +4083,52 @@ def _parse_docker_flags(flags: str) -> dict:
return kwargs
+_CONTAINER_CA_PATH = "/var/ministack/ministack-ca.pem"
+_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=""):
+ """Resolve the host a Cognito token's `iss` names to the gateway, and trust it.
+
+ A verifier built from the pool id alone has no other way to reach us. Only
+ under USE_SSL=1: `iss` is https, so plain HTTP has nothing to resolve to.
+ """
+ from ministack.core import tls as _tls
+
+ if not _tls.use_ssl_enabled():
+ return
+ try:
+ cert_path, _key_path = _tls.resolve_tls_material()
+ except SystemExit:
+ return
+ run_kwargs.setdefault("extra_hosts", {}).setdefault(
+ _tls.cognito_idp_host(), "host-gateway")
+ if not os.path.exists(cert_path):
+ 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))
+ 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))
+ 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))
+ container_env.setdefault("JAVA_TOOL_OPTIONS", " ".join((
+ f"-Djavax.net.ssl.trustStore={_CONTAINER_TRUSTSTORE_PATH}",
+ "-Djavax.net.ssl.trustStoreType=pkcs12",
+ f"-Djavax.net.ssl.trustStorePassword={_tls.JAVA_TRUSTSTORE_PASSWORD}",
+ )))
+
+
def _declared_docker_platform(config: dict):
"""The linux/* platform to pin, or None when the function never declared one.
@@ -4459,6 +4505,8 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,
container_env["_MS_REAL_HANDLER"] = handler
run_kwargs["command"] = [shim_cmd]
+ _wire_cognito_issuer_host(run_kwargs, container_env, mounts, runtime)
+
if mounts:
run_kwargs["mounts"] = mounts
if LAMBDA_DOCKER_NETWORK:
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index c95e9e91..9621da90 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -13677,6 +13677,82 @@ def test_function_changes_invalidate_provided_workers(monkeypatch, isolated_pool
assert not lambda_runtime._workers
+# ---------------------------------------------------------------------------
+# Reaching Cognito at the host its tokens name. AWS's own CognitoJwtVerifier
+# derives the expected issuer and the JWKS URL from the pool id and overrides
+# neither, so a verifying handler must find the gateway at
+# cognito-idp.{region}.amazonaws.com.
+# ---------------------------------------------------------------------------
+
+
+def _wire(monkeypatch, **env):
+ from ministack.services import lambda_svc as lsvc
+
+ for key, value in env.items():
+ monkeypatch.setenv(key, value)
+ run_kwargs, container_env, mounts = {}, {}, []
+ lsvc._wire_cognito_issuer_host(run_kwargs, container_env, mounts)
+ return run_kwargs, container_env, mounts
+
+
+def test_cognito_issuer_host_is_not_wired_without_use_ssl(monkeypatch, tmp_path):
+ """`iss` is https, so with a plain gateway there is nothing for the name to
+ usefully resolve to and the container must be left alone."""
+ monkeypatch.delenv("USE_SSL", raising=False)
+ run_kwargs, container_env, mounts = _wire(monkeypatch, TMPDIR=str(tmp_path))
+ assert (run_kwargs, container_env, mounts) == ({}, {}, [])
+
+
+def test_cognito_issuer_host_resolves_to_the_gateway_under_use_ssl(monkeypatch, tmp_path):
+ from ministack.services import lambda_svc as lsvc
+
+ run_kwargs, container_env, mounts = _wire(
+ monkeypatch, USE_SSL="1", TMPDIR=str(tmp_path), MINISTACK_REGION="us-east-1")
+ assert run_kwargs["extra_hosts"] == {
+ "cognito-idp.us-east-1.amazonaws.com": "host-gateway"}
+ # NODE_EXTRA_CA_CERTS adds to node's roots, so it takes the bare certificate.
+ assert container_env["NODE_EXTRA_CA_CERTS"] == lsvc._CONTAINER_CA_PATH
+ # The other two replace the trust store, so they take the public roots with
+ # ours appended, or the handler loses every other HTTPS endpoint.
+ for var in ("AWS_CA_BUNDLE", "REQUESTS_CA_BUNDLE"):
+ assert container_env[var] == lsvc._CONTAINER_BUNDLE_PATH
+ assert [(m["Target"], m["ReadOnly"]) for m in mounts] == [
+ (lsvc._CONTAINER_CA_PATH, True), (lsvc._CONTAINER_BUNDLE_PATH, 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
+
+ monkeypatch.setenv("USE_SSL", "1")
+ monkeypatch.setenv("TMPDIR", str(tmp_path))
+ monkeypatch.setenv("MINISTACK_REGION", "us-east-1")
+ host = "cognito-idp.us-east-1.amazonaws.com"
+ run_kwargs = {"extra_hosts": {host: "10.0.0.9"}}
+ container_env = {"NODE_EXTRA_CA_CERTS": "/opt/mine.pem"}
+ lsvc._wire_cognito_issuer_host(run_kwargs, container_env, [])
+ assert run_kwargs["extra_hosts"][host] == "10.0.0.9"
+ assert container_env["NODE_EXTRA_CA_CERTS"] == "/opt/mine.pem"
+
+
+def test_cognito_issuer_wiring_gives_a_java_runtime_its_own_truststore(monkeypatch, tmp_path):
+ """JAVA_TOOL_OPTIONS makes every JVM announce itself on stderr, so it is
+ set only where a JVM will read it."""
+ pytest.importorskip("cryptography")
+ from ministack.services import lambda_svc as lsvc
+
+ _rk, java_env, java_mounts = _wire(
+ monkeypatch, USE_SSL="1", TMPDIR=str(tmp_path), MINISTACK_REGION="us-east-1")
+ java_env.clear(), java_mounts.clear()
+ lsvc._wire_cognito_issuer_host({}, java_env, java_mounts, "java21")
+ assert lsvc._CONTAINER_TRUSTSTORE_PATH in java_env["JAVA_TOOL_OPTIONS"]
+ assert "trustStoreType=pkcs12" in java_env["JAVA_TOOL_OPTIONS"]
+ assert lsvc._CONTAINER_TRUSTSTORE_PATH in [m["Target"] for m in java_mounts]
+
+ _rk2, py_env, py_mounts = {}, {}, []
+ lsvc._wire_cognito_issuer_host(_rk2, py_env, py_mounts, "python3.12")
+ assert "JAVA_TOOL_OPTIONS" not in py_env
+ assert lsvc._CONTAINER_TRUSTSTORE_PATH not in [m["Target"] for m in py_mounts]
class _ProxyHandler(BaseHTTPRequestHandler):
received: list[dict] = []
response: tuple[int, bytes, dict] = (200, b'{"ok":true}', {"Content-Type": "application/json"})
diff --git a/tests/test_tls.py b/tests/test_tls.py
index 96463d33..236ff7ff 100644
--- a/tests/test_tls.py
+++ b/tests/test_tls.py
@@ -143,3 +143,111 @@ def test_tls_partial_cert_config_rejected():
_terminate(proc)
pytest.fail("hypercorn should have exited when SSL cert/key were partially configured")
assert rc != 0
+
+
+# ---------------------------------------------------------------------------
+# The Cognito issuer host: a token's `iss` names
+# cognito-idp.{region}.amazonaws.com, so the gateway certificate has to as
+# well for a client that follows it to complete a handshake.
+# ---------------------------------------------------------------------------
+
+
+def _san_of(cert_path):
+ out = subprocess.run(
+ ["openssl", "x509", "-in", cert_path, "-noout", "-ext", "subjectAltName"],
+ capture_output=True, text=True, check=True)
+ return out.stdout
+
+
+def test_generated_cert_names_the_cognito_issuer_host(tmp_path, monkeypatch):
+ from ministack.core import tls
+
+ monkeypatch.setenv("TMPDIR", str(tmp_path))
+ monkeypatch.setenv("MINISTACK_REGION", "eu-west-2")
+ monkeypatch.delenv("MINISTACK_SSL_CERT", raising=False)
+ monkeypatch.delenv("MINISTACK_SSL_KEY", raising=False)
+ cert_path, _key = tls.resolve_tls_material()
+ assert "DNS:cognito-idp.eu-west-2.amazonaws.com" in _san_of(cert_path)
+ assert tls.cognito_idp_host() == "cognito-idp.eu-west-2.amazonaws.com"
+
+
+def test_cached_cert_without_the_issuer_host_is_regenerated(tmp_path, monkeypatch):
+ """A cert cached by an older build, or for another region, cannot serve the
+ issuer host, so reusing it would fail the handshake."""
+ from ministack.core import tls
+
+ monkeypatch.setenv("TMPDIR", str(tmp_path))
+ monkeypatch.delenv("MINISTACK_SSL_CERT", raising=False)
+ monkeypatch.delenv("MINISTACK_SSL_KEY", raising=False)
+ monkeypatch.setenv("MINISTACK_REGION", "eu-west-2")
+ first, _ = tls.resolve_tls_material()
+ first_bytes = open(first, "rb").read()
+
+ monkeypatch.setenv("MINISTACK_REGION", "us-east-1")
+ second, _ = tls.resolve_tls_material()
+ assert "DNS:cognito-idp.us-east-1.amazonaws.com" in _san_of(second)
+ assert open(second, "rb").read() != first_bytes
+
+
+def test_byo_certificate_is_never_regenerated(tmp_path, monkeypatch):
+ """MINISTACK_SSL_CERT is the operator's, so the issuer host is their
+ business and we must hand it back untouched."""
+ from ministack.core import tls
+
+ cert, key = tmp_path / "c.pem", tmp_path / "k.pem"
+ cert.write_text("cert"), key.write_text("key")
+ monkeypatch.setenv("MINISTACK_SSL_CERT", str(cert))
+ monkeypatch.setenv("MINISTACK_SSL_KEY", str(key))
+ assert tls.resolve_tls_material() == (str(cert), str(key))
+ assert cert.read_text() == "cert"
+
+
+def test_port_is_bindable_reports_a_taken_port():
+ from ministack.app import _port_is_bindable
+
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as taken:
+ taken.bind(("127.0.0.1", 0))
+ taken.listen(1)
+ port = taken.getsockname()[1]
+ assert _port_is_bindable("127.0.0.1", port) is False
+ assert _port_is_bindable("127.0.0.1", _free_port()) is True
+
+
+def test_ca_bundle_keeps_the_public_roots(tmp_path, monkeypatch):
+ """AWS_CA_BUNDLE and REQUESTS_CA_BUNDLE replace the trust store, so the
+ bundle we hand a container must still verify everything else it calls."""
+ from ministack.core import tls
+
+ monkeypatch.setenv("TMPDIR", str(tmp_path))
+ monkeypatch.delenv("MINISTACK_SSL_CERT", raising=False)
+ monkeypatch.delenv("MINISTACK_SSL_KEY", raising=False)
+ cert_path, _key = tls.resolve_tls_material()
+ bundle = tls.ca_bundle_path(cert_path)
+ assert bundle, "no system trust store to build a bundle from"
+ ctx = ssl.create_default_context(cafile=bundle)
+ assert len(ctx.get_ca_certs()) > 5
+ assert open(cert_path).read() in open(bundle).read()
+
+
+def test_java_truststore_carries_our_cert_and_the_public_roots(tmp_path, monkeypatch):
+ """A JVM reads neither AWS_CA_BUNDLE nor a PEM bundle, so a Java handler
+ gets a PKCS12 store, and it must not cost it the public roots either."""
+ pytest.importorskip("cryptography")
+ from cryptography import x509
+ from cryptography.hazmat.primitives.serialization import pkcs12
+
+ from ministack.core import tls
+
+ monkeypatch.setenv("TMPDIR", str(tmp_path))
+ monkeypatch.delenv("MINISTACK_SSL_CERT", raising=False)
+ monkeypatch.delenv("MINISTACK_SSL_KEY", raising=False)
+ cert_path, _key = tls.resolve_tls_material()
+ store = tls.java_truststore_path(cert_path)
+ assert store and store.endswith(".p12")
+
+ loaded = pkcs12.load_pkcs12(
+ open(store, "rb").read(), tls.JAVA_TRUSTSTORE_PASSWORD.encode())
+ ours = x509.load_pem_x509_certificate(open(cert_path, "rb").read())
+ subjects = [entry.certificate.subject for entry in loaded.additional_certs]
+ assert ours.subject in subjects
+ assert len(subjects) > 5