Skip to content

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

fix(tls): minted leaf certificates carry an Authority Key Identifier (#1369)

iot-rocket5eb3038ce024
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 06bd8b1f..142d33c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **API Gateway (HTTP API / v2) — custom Lambda (`REQUEST`) authorizers are now invoked and enforced** — `_handle_execute_in_scope` only branched on `auth_type == "JWT"`, so a route with a `CUSTOM` authorization type (the type a route gets when it references a `REQUEST` authorizer) fell through unauthenticated: the authorizer Lambda was never invoked at all, regardless of whether the request carried a valid, invalid, or missing token. Adds a REQUEST-authorizer data-plane path mirroring the REST (v1) fix from 1.4.16 (`_authorize_request_v1`) — honors `authorizerPayloadFormatVersion` (1.0 IAM-policy-shaped event vs. 2.0), `enableSimpleResponses` (`{isAuthorized, context}`) vs. IAM policy (`{principalId, policyDocument, context}`) response formats, and `authorizerResultTtlInSeconds` caching — and populates `requestContext.authorizer.lambda` for the downstream integration. Reported against real-world usage; the earlier REST (v1) authorizer fix covered v1 only. Contributed by @ryan-bennett.
- **EventBridge — API destination delivery no longer leaks credentials, and caller-supplied outbound values are validated** — API destination requests now validate every caller-controlled value before it reaches the wire. (1) Delivery and OAuth token requests no longer follow redirects, preventing credentials from reaching another host; `3xx` responses are non-retryable failures. (2) `InvocationEndpoint` and OAuth `AuthorizationEndpoint` must be dialable `http(s)://` URLs. The outbound opener also rejects non-HTTP(S) schemes, while loopback/private/link-local hosts remain allowed for the local emulator. (3) `HttpMethod` and `AuthorizationType` are validated against their API enums. (4) `ApiKeyName` can no longer override reserved headers. (5) `DeauthorizeConnection` removes authorization parameters, and delivery skips connections that are not `AUTHORIZED`. (6) OAuth token responses are capped at 1 MiB. Contributed by @t-rech.
- **Lambda — uncaught handler exceptions report `X-Amz-Function-Error: Unhandled`** — the Docker/RIE executor read the error class off a response header the RIE never sets, so every failure was reported `Handled` and API Gateway consumers keying off the 502-for-Unhandled contract never took the error path. Headerless payloads are now classified by shape: the runtime's error serialization reports `Unhandled`, an HTTP-style envelope with `statusCode` stays `Handled`. Contributed by @iot-rocket.
+- **TLS — minted leaf certificates carry an Authority Key Identifier** — `sign_leaf_certificate` omitted it, and RFC 5280 requires it on every certificate that is not self-issued. Python 3.13 enables `ssl.VERIFY_X509_STRICT` in `ssl.create_default_context()`, so any client on a current Python rejected what MiniStack minted with "Missing Authority Key Identifier" — `CreateKeysAndCertificate` certificates included. Contributed by @iot-rocket.
- **IoT — `CreateThingType` is idempotent for identical re-creates** — re-creating an existing thing type always returned `ResourceAlreadyExistsException`, so a retried request or a re-run provisioning script failed where AWS succeeds. The same `thingTypeProperties` now return the existing ids — absent, `null` and empty compare equal, `searchableAttributes` is unordered — and only a real mismatch keeps the `409`, as `CreateThing` already did. Contributed by @iot-rocket.
- **EC2 — `RevokeSecurityGroupIngress` / `RevokeSecurityGroupEgress` honour `SecurityGroupRuleIds`** — both read only `IpPermissions`, so a revoke by rule id (as Terraform does) returned `Return=true` while removing nothing, leaving the rule in place forever. Ids now resolve against the group's `sgr-*` rules, which are removed with their tags and echoed in `revokedSecurityGroupRuleSet`; one unknown id rejects the whole call with `InvalidSecurityGroupRuleId.NotFound`. Contributed by @iot-rocket.
- **Cognito — `/oauth2/userInfo` returns custom attributes and the plain `username`** — the response filtered attributes through a fixed standard-OIDC allowlist, dropping `custom:` attributes; it now returns them (as AWS does for `openid` and `openid profile`), plus the plain `username` claim alongside `cognito:username`, and `middle_name`. Contributed by @rjmackay.
diff --git a/ministack/core/x509_utils.py b/ministack/core/x509_utils.py
index fa80f6c6..766ea594 100644
--- a/ministack/core/x509_utils.py
+++ b/ministack/core/x509_utils.py
@@ -6,6 +6,13 @@ service for its local CA and available for reuse by ACM, API Gateway
custom domains, or any other service that needs local certificate
operations.
+Certificates minted here are meant to be verified by ordinary clients, so
+they follow RFC 5280 rather than the minimum OpenSSL will tolerate: a leaf
+carries an Authority Key Identifier naming its issuer. Python 3.13 turns on
+``ssl.VERIFY_X509_STRICT`` in ``ssl.create_default_context()``, and a strict
+verifier rejects a leaf without one ("Missing Authority Key Identifier"). A
+self-signed CA is exempt and does not carry it.
+
Requires the ``cryptography`` library (declared as part of ``[full]``
optional deps). Functions raise ``RuntimeError`` with a clear message
when it is not importable.
@@ -150,6 +157,12 @@ def sign_leaf_certificate(
.not_valid_before(now - _dt.timedelta(minutes=1))
.not_valid_after(now + _dt.timedelta(days=days_valid))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
+ # RFC 5280 §4.2.1.1: a certificate that is not self-issued must name the
+ # key that signed it, and a strict verifier enforces it (see above).
+ .add_extension(
+ x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_cert.public_key()),
+ critical=False,
+ )
.add_extension(
x509.KeyUsage(
digital_signature=True,
diff --git a/tests/test_x509_utils.py b/tests/test_x509_utils.py
new file mode 100644
index 00000000..f72b76e6
--- /dev/null
+++ b/tests/test_x509_utils.py
@@ -0,0 +1,101 @@
+"""Unit tests for ``ministack.core.x509_utils``.
+
+These run entirely in-process: the handshake below is between two ends of a
+``socketpair``, so nothing binds a port and no server is needed.
+"""
+
+import socket
+import ssl
+import threading
+
+import pytest
+
+pytest.importorskip("cryptography")
+
+from cryptography import x509 # noqa: E402
+
+from ministack.core.x509_utils import generate_ca, sign_leaf_certificate # noqa: E402
+
+
+def _handshake(ca_pem: str, cert_pem: str, key_pem: str, tmp_path) -> None:
+ """Verify ``cert_pem`` against ``ca_pem`` the way a real client would.
+
+ The ``ssl`` module exposes no "validate this chain" entry point, so the
+ check is an actual TLS handshake against a default-configured client —
+ which is the thing that has to work. Raises the client's exception.
+ """
+ chain = tmp_path / "chain.pem"
+ chain.write_text(cert_pem + key_pem)
+ server_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ server_ctx.load_cert_chain(str(chain))
+ # Python 3.13 enables VERIFY_X509_STRICT here; that is deliberately not
+ # relaxed, since a client on a current Python is exactly what must succeed.
+ client_ctx = ssl.create_default_context(cadata=ca_pem)
+
+ server_sock, client_sock = socket.socketpair()
+
+ def _serve():
+ try:
+ with server_ctx.wrap_socket(server_sock, server_side=True) as tls:
+ tls.recv(1)
+ except OSError:
+ # The client's rejection surfaces here as an alert; the client's
+ # own exception is the one worth reporting, so this end stays quiet.
+ server_sock.close()
+
+ server = threading.Thread(target=_serve, daemon=True)
+ server.start()
+ try:
+ with client_ctx.wrap_socket(client_sock, server_hostname="localhost") as tls:
+ tls.send(b"x")
+ finally:
+ server.join(timeout=5)
+ for sock in (server_sock, client_sock):
+ try:
+ sock.close()
+ except OSError:
+ pass
+
+
+def test_signed_leaf_verifies_under_a_strict_default_client(tmp_path):
+ """A minted leaf is accepted by ``ssl.create_default_context()``.
+
+ Python 3.13 turns on ``VERIFY_X509_STRICT`` there, which enforces RFC 5280's
+ rule that a certificate which is not self-issued must carry an Authority Key
+ Identifier. Without one this fails with "Missing Authority Key Identifier",
+ and every client on a current Python refuses the certificates Ministack
+ mints — CreateKeysAndCertificate's among them.
+ """
+ ca_pem, ca_key_pem = generate_ca()
+ cert_pem, key_pem, _public_pem = sign_leaf_certificate(
+ ca_pem, ca_key_pem, common_name="localhost", san_dns=["localhost"]
+ )
+
+ _handshake(ca_pem, cert_pem, key_pem, tmp_path)
+
+
+def test_signed_leaf_authority_key_identifier_names_the_issuing_ca():
+ """The identifier has to point at the signing CA, not merely be present."""
+ ca_pem, ca_key_pem = generate_ca()
+ cert_pem, _key_pem, _public_pem = sign_leaf_certificate(
+ ca_pem, ca_key_pem, common_name="device"
+ )
+
+ leaf = x509.load_pem_x509_certificate(cert_pem.encode("utf-8"))
+ ca = x509.load_pem_x509_certificate(ca_pem.encode("utf-8"))
+ aki = leaf.extensions.get_extension_for_class(x509.AuthorityKeyIdentifier).value
+ ski = ca.extensions.get_extension_for_class(x509.SubjectKeyIdentifier).value
+
+ assert aki.key_identifier == ski.digest
+
+
+def test_generated_ca_is_self_signed_and_needs_no_authority_key_identifier():
+ """The CA is its own issuer, so RFC 5280 exempts it — and a strict verifier
+ accepts it as a trust anchor, which the handshake above already relies on."""
+ ca_pem, _ca_key_pem = generate_ca()
+
+ ca = x509.load_pem_x509_certificate(ca_pem.encode("utf-8"))
+
+ assert ca.issuer == ca.subject
+ with pytest.raises(x509.ExtensionNotFound):
+ ca.extensions.get_extension_for_class(x509.AuthorityKeyIdentifier)