Skip to content

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

feat(tls): native HTTPS support via USE_SSL (#527)

Gabriel Prando1af673bd519c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f22e9072..fdab8a97 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
+---
+
+## [Unreleased]
+
+### Added
+- **Native HTTPS via `USE_SSL=1`** — the gateway listener now speaks TLS when `USE_SSL=1` (also accepts `true` / `yes`). Drop-in compatible with LocalStack's `USE_SSL=true`, so a `compose.yml` switching from LocalStack to MiniStack doesn't need TLS-specific changes. By default, MiniStack auto-generates a self-signed RSA cert (CN: `ministack-local`, SAN: `localhost`, `ministack`, `127.0.0.1`, `::1`) cached under `${TMPDIR}/ministack-tls/` so the cert survives restarts. To pin a specific cert (e.g. an `mkcert`-issued one for browser trust), set `MINISTACK_SSL_CERT` and `MINISTACK_SSL_KEY` to PEM paths. Auto-generation uses the `cryptography` package (already shipped in both the regular and `:full` images). Unblocks AWS SDKs that hardcode `https://` against Cognito Hosted UI endpoints (e.g. Amplify v6) without needing a separate TLS-terminating proxy. Closes #526.
---
diff --git a/Dockerfile b/Dockerfile
index 140c60a6..47afe509 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -24,7 +24,7 @@ LABEL maintainer="MiniStack" \
description="Local AWS Service Emulator — drop-in LocalStack replacement"
# Upgrade base packages to pick up latest security patches.
-RUN apk upgrade --no-cache && apk add --no-cache nodejs bash && rm -f /usr/bin/wget /bin/wget \
+RUN apk upgrade --no-cache && apk add --no-cache nodejs bash openssl && rm -f /usr/bin/wget /bin/wget \
&& rm -rf /usr/local/lib/python3.12/site-packages/pip* \
/usr/local/bin/pip*
@@ -62,12 +62,13 @@ ENV MINISTACK_VERSION=${MINISTACK_VERSION} \
RDS_PERSIST=0 \
ELASTICACHE_BASE_PORT=16379 \
LAMBDA_EXECUTOR=local \
+ USE_SSL=0 \
PYTHONUNBUFFERED=1
EXPOSE 4566 2222
-# Pure Python healthcheck — no curl dependency
+# Pure Python healthcheck — honours USE_SSL so it works for both HTTP and HTTPS.
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
- CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:4566/_ministack/health')" || exit 1
+ CMD python -c "import os,ssl,urllib.request as r; t=os.environ.get('USE_SSL','').strip().lower() in ('1','true','yes'); r.urlopen(('https' if t else 'http')+'://localhost:'+os.environ.get('GATEWAY_PORT','4566')+'/_ministack/health',context=ssl._create_unverified_context() if t else None)" || exit 1
-ENTRYPOINT ["python", "-m", "hypercorn", "ministack.app:app", "--bind", "0.0.0.0:4566", "--keep-alive", "75"]
+ENTRYPOINT ["python", "-m", "hypercorn", "ministack.app:app", "-c", "file:ministack/core/hypercorn_conf.py", "--bind", "0.0.0.0:4566", "--keep-alive", "75"]
diff --git a/Dockerfile.full b/Dockerfile.full
index daac07de..2fb71040 100644
--- a/Dockerfile.full
+++ b/Dockerfile.full
@@ -77,12 +77,13 @@ ENV MINISTACK_VERSION=${MINISTACK_VERSION} \
RDS_PERSIST=0 \
ELASTICACHE_BASE_PORT=16379 \
LAMBDA_EXECUTOR=local \
+ USE_SSL=0 \
PYTHONUNBUFFERED=1
EXPOSE 4566 2222
-# Pure Python healthcheck — no curl dependency
+# Pure Python healthcheck — honours USE_SSL so it works for both HTTP and HTTPS.
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
- CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:4566/_ministack/health')" || exit 1
+ CMD python -c "import os,ssl,urllib.request as r; t=os.environ.get('USE_SSL','').strip().lower() in ('1','true','yes'); r.urlopen(('https' if t else 'http')+'://localhost:'+os.environ.get('GATEWAY_PORT','4566')+'/_ministack/health',context=ssl._create_unverified_context() if t else None)" || exit 1
-ENTRYPOINT ["python", "-m", "hypercorn", "ministack.app:app", "--bind", "0.0.0.0:4566", "--keep-alive", "75"]
+ENTRYPOINT ["python", "-m", "hypercorn", "ministack.app:app", "-c", "file:ministack/core/hypercorn_conf.py", "--bind", "0.0.0.0:4566", "--keep-alive", "75"]
diff --git a/ministack/core/hypercorn_conf.py b/ministack/core/hypercorn_conf.py
new file mode 100644
index 00000000..2265d0d6
--- /dev/null
+++ b/ministack/core/hypercorn_conf.py
@@ -0,0 +1,14 @@
+"""Hypercorn config — applied via `-c file:` in the Dockerfile ENTRYPOINT.
+
+Hypercorn's `from_pyfile` collects every non-module, non-dunder
+module-level attribute and `setattr`s it onto the Config object, so the
+exported names must match Hypercorn's own (lowercase `certfile` /
+`keyfile`). When USE_SSL is unset (default), nothing is exported and
+the listener stays plain HTTP — same behaviour as before this flag was
+introduced.
+"""
+
+import ministack.core.tls as _tls
+
+if _tls.use_ssl_enabled():
+ certfile, keyfile = _tls.resolve_tls_material()
diff --git a/ministack/core/tls.py b/ministack/core/tls.py
new file mode 100644
index 00000000..c5116e5d
--- /dev/null
+++ b/ministack/core/tls.py
@@ -0,0 +1,53 @@
+"""TLS material helpers — env-driven cert/key resolution for the gateway.
+
+`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.
+"""
+
+import os
+import subprocess
+import sys
+import tempfile
+
+
+def use_ssl_enabled() -> bool:
+ return os.environ.get("USE_SSL", "").strip().lower() in ("1", "true", "yes")
+
+
+def resolve_tls_material() -> "tuple[str, str]":
+ """Return (certfile, keyfile) PEM paths.
+
+ BYO via `MINISTACK_SSL_CERT` + `MINISTACK_SSL_KEY` (e.g. `mkcert`),
+ otherwise auto-generate a self-signed cert under `${TMPDIR}/ministack-tls/`
+ and cache it across restarts.
+ """
+ cert = os.environ.get("MINISTACK_SSL_CERT", "").strip()
+ key = os.environ.get("MINISTACK_SSL_KEY", "").strip()
+ if cert or key:
+ if not cert or not key:
+ print("ERROR: MINISTACK_SSL_CERT and MINISTACK_SSL_KEY must be set together.",
+ file=sys.stderr)
+ raise SystemExit(1)
+ for label, path in (("MINISTACK_SSL_CERT", cert), ("MINISTACK_SSL_KEY", key)):
+ if not os.path.exists(path):
+ print(f"ERROR: {label} path not found: {path}", file=sys.stderr)
+ raise SystemExit(1)
+ return cert, key
+
+ tls_dir = os.path.join(tempfile.gettempdir(), "ministack-tls")
+ 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 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",
+ ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ os.chmod(cert_path, 0o600)
+ os.chmod(key_path, 0o600)
+ return cert_path, key_path
diff --git a/tests/test_tls.py b/tests/test_tls.py
new file mode 100644
index 00000000..96463d33
--- /dev/null
+++ b/tests/test_tls.py
@@ -0,0 +1,145 @@
+"""TLS / HTTPS support for the gateway listener (USE_SSL=1).
+
+Each test spawns its own hypercorn process on a free port (the same way
+the Docker ENTRYPOINT does) so the suite-wide fixture (port 4566, plain
+HTTP) is unaffected.
+"""
+
+import os
+import socket
+import ssl
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+import pytest
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+HYPERCORN_CONF = "file:ministack/core/hypercorn_conf.py"
+
+
+def _free_port() -> int:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+def _ctx_no_verify() -> ssl.SSLContext:
+ ctx = ssl.create_default_context()
+ ctx.check_hostname = False
+ ctx.verify_mode = ssl.CERT_NONE
+ return ctx
+
+
+def _wait_health(url: str, *, ctx: "ssl.SSLContext | None" = None, timeout: float = 30.0) -> None:
+ deadline = time.time() + timeout
+ last = None
+ while time.time() < deadline:
+ try:
+ urllib.request.urlopen(url, context=ctx, timeout=2)
+ return
+ except Exception as e:
+ last = e
+ time.sleep(0.3)
+ raise AssertionError(f"{url} did not come up within {timeout}s: {last!r}")
+
+
+def _byo_cert(tmp_path):
+ """Generate a short-lived BYO cert via the openssl CLI for the BYO-path tests."""
+ cert_path = tmp_path / "test.crt"
+ key_path = tmp_path / "test.key"
+ subprocess.run([
+ "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
+ "-keyout", str(key_path), "-out", str(cert_path),
+ "-days", "1", "-subj", "/CN=test",
+ "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
+ ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ return str(cert_path), str(key_path)
+
+
+def _spawn(env_extra: dict, port: int) -> subprocess.Popen:
+ env = {**os.environ, "LOG_LEVEL": "WARNING", **env_extra}
+ return subprocess.Popen(
+ [sys.executable, "-m", "hypercorn", "ministack.app:app",
+ "-c", HYPERCORN_CONF,
+ "--bind", f"127.0.0.1:{port}",
+ "--log-level", "warning",
+ "--keep-alive", "75"],
+ env=env,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.STDOUT,
+ cwd=REPO_ROOT,
+ )
+
+
+def _terminate(proc: subprocess.Popen) -> None:
+ proc.terminate()
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait(timeout=5)
+
+
+def test_tls_use_ssl_with_byo_cert(tmp_path):
+ cert, key = _byo_cert(tmp_path)
+ port = _free_port()
+ proc = _spawn(
+ {"USE_SSL": "1", "MINISTACK_SSL_CERT": cert, "MINISTACK_SSL_KEY": key},
+ port,
+ )
+ try:
+ _wait_health(f"https://127.0.0.1:{port}/_ministack/health", ctx=_ctx_no_verify())
+ finally:
+ _terminate(proc)
+
+
+def test_tls_use_ssl_auto_generated_cert():
+ port = _free_port()
+ proc = _spawn({"USE_SSL": "1"}, port)
+ try:
+ _wait_health(f"https://127.0.0.1:{port}/_ministack/health", ctx=_ctx_no_verify())
+ finally:
+ _terminate(proc)
+
+
+def test_tls_use_ssl_accepts_true_value(tmp_path):
+ cert, key = _byo_cert(tmp_path)
+ port = _free_port()
+ proc = _spawn(
+ {"USE_SSL": "true", "MINISTACK_SSL_CERT": cert, "MINISTACK_SSL_KEY": key},
+ port,
+ )
+ try:
+ _wait_health(f"https://127.0.0.1:{port}/_ministack/health", ctx=_ctx_no_verify())
+ finally:
+ _terminate(proc)
+
+
+def test_tls_disabled_by_default_serves_http():
+ """Without USE_SSL the gateway speaks plain HTTP (existing behaviour)."""
+ port = _free_port()
+ proc = _spawn({}, port)
+ try:
+ _wait_health(f"http://127.0.0.1:{port}/_ministack/health")
+ finally:
+ _terminate(proc)
+
+
+def test_tls_partial_cert_config_rejected():
+ """Setting only one of MINISTACK_SSL_CERT / KEY must error out fast."""
+ port = _free_port()
+ proc = _spawn({"USE_SSL": "1", "MINISTACK_SSL_CERT": "/nonexistent.crt"}, port)
+ try:
+ rc = proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ _terminate(proc)
+ pytest.fail("hypercorn should have exited when SSL cert/key were partially configured")
+ assert rc != 0