TL;DR: One Message, Seven Codes, Three Alerts
ssl.SSLCertVerificationErroris one exception type with one message prefix and 7 different causes in these runs. The words after the colon are a hint;verify_codeis the field that names the check.- The server cannot tell you which one it was: 7 client causes arrived there as 3 alert names, and a name mismatch shared its alert with a certificate that was not yet valid.
- Every fix below is configuration – send the intermediate, point the client at the store it actually reads, cover the name, correct the clock. Another attempt changes none of them.
Scope. Everything here was measured on one Linux host: kernel 6.12.118-guest-1.1, CPython 3.12.16, OpenSSL 3.5.7, 2 CPUs, loopback only, with 10 certificates generated for the probes and 5 repeats per arm. A browser, a Go client or a load balancer may read the same rules differently, and where this build does, the text says so.
Fix It First: Eight Changes, in the Order They Cost
Start from the line in your log and stop at the first row that matches. The middle column is ordered by what a change costs: reading verify_code is free, a store is a configuration edit, and a new certificate reaches everyone who owns the name.
| What the log shows | Change to make | Measured on this page |
|---|---|---|
| Any verification failure | Log verify_code and verify_message, not just the exception type; the number is the branch you need | 7 codes arrived under one exception type |
unable to get local issuer certificate | Send the intermediate with the leaf; adding the root again does not help | the same leaf failed with code 20 alone and verified with its issuer beside it |
self-signed certificate in certificate chain | Stop serving your own root: trust it on the client, or reissue under a public one | a foreign root sent with its leaf produced code 19, not code 20 |
hostname mismatch | Connect by a name in the subjectAltName; the trust store is not the problem | a certificate for server.test refused a.b.wild.test and wild.test alike |
certificate has expired or not yet valid | Renew on the server, or fix the client’s clock; store and chain are fine | one chain verified until its dates changed, then raised codes 10 and 9 |
Fails only inside requests | Set REQUESTS_CA_BUNDLE or pass verify=; SSL_CERT_FILE alone is not read there | the httpx call passed with the variable set, the requests call beside it still failed |
Browser fine, Python ssl/urllib fails: corporate proxy, minimal image, macOS | Add the proxy’s root to the bundle and point SSL_CERT_FILE at it; install ca-certificates in the image; or run Install Certificates.command – section 5 | the store and chain mechanism of sections 3 and 4, applied where it appears; none of the three reproduced on this host |
| A request you are about to retry | Do not: fix the store, the chain, the name or the clock, then send once | every arm returned an identical code in all 5 repeats, and 0 of 7 codes are retryable |
ssl/urllib failing – which states how the mechanism of sections 3 and 4 applies off this host: none of its three cases was reproduced here. A code is worth reading before a store is changed, and a store before a certificate is reissued.1. What the Message Hides
ssl.SSLCertVerificationError subclasses SSLError and carries three fields worth a handler’s time: the OpenSSL verify_code, the verify_message that puts the failing check into words, and the library’s generic reason, which reads the same whichever check failed. The type’s own docstring is one sentence – A certificate could not be verified. – and that sentence is the whole of what it promises.
The prefix, [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:, is added before the OpenSSL string, so the part that varies sits at the end – exactly where a fixed-width log field cuts first. A service that writes str(exc)[:120] keeps the prefix and loses the reason; one that writes the type alone keeps neither, and the next person to open the incident starts from zero.
The function below is the part worth copying. It takes whatever the client raised and follows the wrapper links until it finds the certificate error, because the error a caller catches is rarely the one that decided the outcome.
from __future__ import annotations
import ssl
def verify_code_of(exc: BaseException | None) -> tuple[int, str] | None:
"""The ``verify_code`` and ``verify_message`` inside a wrapper chain, if one is there.
Clients wrap the original exception: ``urllib`` puts it in ``URLError.reason``, ``requests``
hides it behind a pool error, ``httpx`` keeps it as ``__cause__``. Walking those links is
the difference between logging "connect error" and logging code 20. Eight links is more
than any client measured here used, and the bound stops a cycle in a badly built exception.
"""
depth = 0
current: BaseException | None = exc
while current is not None and depth < 8:
if isinstance(current, ssl.SSLCertVerificationError):
return int(current.verify_code), current.verify_message
nested = getattr(current, "reason", None)
current = nested if isinstance(nested, BaseException) else (
current.__cause__ or current.__context__)
depth += 1
return None
Two details in it matter more than the loop. It checks for SSLCertVerificationError rather than SSLError, because the verification error is a subclass and a handler that catches the parent first falls into the general branch with no numbers at all. And it returns the fields rather than a verdict: the code and its message are what a log line needs, and a caller that wants the remedy can classify them afterwards.
2. Seven Causes, Nine Codes
One store, certs/root.pem, was trusted by every arm in this section; only the served chain or the requested name changed. Eight arms were served and six codes came out of them, each identical in every repeat. The table adds the codes the package maps but no probe produced, and the address code from section 6, so the nine rows are the whole vocabulary this page uses.
| Code | Which check failed | Produced here by | Change that removes it |
|---|---|---|---|
| 18 | the certificate is its own issuer | a leaf signed by itself | trust that certificate, or issue under a known root |
| 19 | a self-signed certificate in the chain | a foreign root sent with its leaf | remove the private root from what the server sends |
| 20 | no path from the leaf to a trusted root | a leaf sent without its issuer | send the intermediate beside the leaf |
| 21 | the same missing issuer, reported one step earlier | the table only; OpenSSL’s number | the same: send the intermediate |
| 9 | the certificate is not valid yet | a leaf whose window starts later | fix the client’s clock, or reissue |
| 10 | the certificate has expired | a leaf whose window ended | renew on the server |
| 23 | the certificate was revoked | the table only; OpenSSL’s number | replace the certificate |
| 62 | the name is not in the certificate | a name the certificate does not carry | connect by a covered name, or reissue with it |
| 64 | the address is not in the certificate | a connection by IP | add an address entry, or connect by name |
trustpath.codes.Fault are here – the code, its short meaning and the remedy; the kind is the group a row belongs to, and retryable is false for all nine. A code outside this table keeps its number instead of being guessed at.Two rows of evidence are worth stopping at, because both look like something else. A certificate with no subjectAltName at all verified, code 0: this OpenSSL falls back to the subject common name when the extension is absent, so deleting the extension does not make a client stricter – it makes the name check depend on a field that browsers and Go no longer read. Section 6 has both sides of that. And the expired leaf needed its issuer beside it before the time check could run at all: sent alone it raised code 20 and the expiry was never reached, because a path is built before it is checked for time.
3. Two Trust Stores in One Process
A TLS context on this stack loads a file store and a directory store, in that order. ssl.get_default_verify_paths() reports the two it would open, and its docstring is one line: Return paths to default cafile and capath. An argument or an environment variable replaces either one, which is how the same image can trust a private root in one container and fail in the next without a line of code changing.
Six runs, one variable each, against the same server. The server presented server.test under its intermediate every time, so the only thing that differed between a verification and a failure was where the root was looked for. The count is what get_ca_certs() reports after the context is built – the file store only, which is worth knowing on its own: a health check that asserts that number is above zero cannot see a root sitting in the directory store.
| How the store was chosen | Loaded CAs | Code |
|---|---|---|
| nothing set: the compiled-in file and directory | 148 | 20 |
SSL_CERT_FILE = the probe root | 1 | 0 |
SSL_CERT_DIR = a hashed directory | 148 | 0 |
SSL_CERT_FILE = an empty file | 0 | 20 |
cafile = the probe root | 1 | 0 |
cafile = the certifi bundle | 118 | 20 |
The fourth row is the one that breaks a deploy. Pointing SSL_CERT_FILE at an empty file did not fall back to the system bundle: it replaced the bundle with nothing, the context loaded 0 authorities, and the handshake failed with code 20 while the directory store it still names held the system roots. A volume that mounts empty, or a secret that resolves to a zero-byte file, is enough – the path exists, so nothing warns.
The system file and the bundle requests ships are not the same set: 148 certificates against 118. Compared by subject rather than by count, the two files share 108 roots, the system file carries 40 the bundle does not, and the bundle carries 10 the system file does not – so “the system store minus 30” describes neither file. Which one a client reads is a property of the client, and section 9 follows that difference through four of them.
4. The Chain Is What the Server Sends
The path from a leaf to a trusted root is assembled by matching each certificate’s issuer to the next certificate’s subject. The client starts at the leaf the server sent and walks forward through the list it was given; the store answers for the last link, not for the middle ones. That is why adding a root to a client’s store cannot repair a missing intermediate: the walk never gets far enough to consult it.
Nine chain shapes were served from the same key pairs. Six of them are in Table 4. Four of the six fail and two verify: the leaf with its intermediate, and the same chain with the root added on top. A break in the served order is not the same thing as a failure, and the row that shows it still builds a path – the intermediate sent first fails on a name check, not on trust.
| Served chain | Certs | Code | What happened |
|---|---|---|---|
| leaf + intermediate | 2 | 0 | the ordinary shape |
| leaf alone | 1 | 20 | the issuer was never sent |
| intermediate first, then leaf | 2 | 62 | the intermediate was read as the peer certificate |
| leaf + root | 2 | 20 | the issuer was replaced by the root |
| leaf + intermediate + root | 3 | 0 | the root in the chain was ignored |
| a foreign leaf + its foreign root | 2 | 19 | a complete path to an untrusted root |
The reversed pair is the useful surprise. Sent intermediate first, the client treated the intermediate as the peer certificate and checked the requested name against it; the path itself was fine and the root was trusted, yet the failure came back as code 62 – a hostname mismatch, which points an operator at the certificate’s names instead of at the order of a file. The last row sends a complete, well-ordered path to a root the client does not trust, and reports code 19 rather than the missing-issuer code, which reads like a different problem again.
Two rules follow, and neither needs a probe to state: the leaf goes first, and every intermediate between it and the root is sent. A server that also sends its root is not wrong – the extra certificate is ignored – but if the client does not trust that root, sending it changes the code from a missing issuer to a self-signed certificate in the chain, and the reader of the log starts in the wrong place.
Reading a served chain without a certificate store
A client disagrees with a chain by failing. Reading the same file offline needs no store at all: parse the PEM bundle for each certificate’s subject and issuer, and compare them in order to say where the walk would stop.
from __future__ import annotations
import dataclasses
from cryptography import x509
@dataclasses.dataclass(frozen=True)
class Link:
"""One certificate in the list: who it is for, who signed it, and when it is valid."""
subject: str
issuer: str
not_before: str
not_after: str
key: tuple[tuple[str, str], ...] = ()
issuer_key: tuple[tuple[str, str], ...] = ()
@property
def self_signed(self) -> bool:
return self.key == self.issuer_key
@dataclasses.dataclass(frozen=True)
class Gap:
"""A place where the next certificate does not continue the current one."""
index: int
expected: str
found: str
def _key(name: x509.Name) -> tuple[tuple[str, str], ...]:
"""A name as comparable pairs: attribute order and spacing do not change identity."""
pairs = []
for attribute in name.rdns:
for part in attribute:
pairs.append((part.oid.dotted_string, str(part.value).strip().lower()))
return tuple(sorted(pairs))
def _label(name: x509.Name) -> str:
common = name.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
if common:
return f"CN={common[0].value}"
return name.rfc4514_string()[:60]
def links(pem_text: str) -> list[Link]:
"""Every certificate in a PEM bundle, in the order the bundle lists them."""
out: list[Link] = []
for cert in x509.load_pem_x509_certificates(pem_text.encode()):
out.append(Link(
subject=_label(cert.subject),
issuer=_label(cert.issuer),
not_before=cert.not_valid_before_utc.strftime("%Y-%m-%d"),
not_after=cert.not_valid_after_utc.strftime("%Y-%m-%d"),
key=_key(cert.subject),
issuer_key=_key(cert.issuer),
))
return out
def gaps(chain: list[Link]) -> list[Gap]:
"""The indices where the served order stops matching issuer to subject."""
out: list[Gap] = []
for index in range(len(chain) - 1):
expected = chain[index].issuer
found = chain[index + 1].subject
if chain[index].issuer_key != chain[index + 1].key:
out.append(Gap(index, expected, found))
return out
5. The Three Causes You Meet in the Field
Sections 3 and 4 describe the pair that produces code 20: a store that does not hold the issuer, and a chain that never reaches it. Send a root the client does not trust along with the leaf and the same pair reports code 19 instead, which is the difference the first case below turns on. In practice that pair arrives in three shapes, and in all three the certificate on the server is the one it should be. None of the three was reproduced on this host – each is the mechanism measured above, seen where this page cannot reach – so what follows is how the mechanism applies, not another measurement.
A proxy that terminates TLS
A corporate proxy or firewall that inspects HTTPS does not pass the site’s certificate through; it presents its own, signed by a root the company controls. The browser on the same machine trusts that root because it reads the operating system’s store. A Python process reads the bundle its interpreter was built with, which has never heard of that root. What the proxy forwards then decides which code the client reports, and both are in Table 2. A leaf sent on its own leaves the issuer missing and fails with code 20, unable to get local issuer certificate. A leaf sent with the proxy’s own root beside it – the shape the last row of Table 4 measures – fails with code 19 instead, self-signed certificate in the chain, which sends an operator looking at a private root on the server rather than at a bundle on the client. Append the proxy’s root to the bundle the process already reads and point the client at that file – SSL_CERT_FILE for a context, REQUESTS_CA_BUNDLE for requests – keeping the system certificates in the same file. The variable replaces a bundle rather than adding to one: pointed at a file that held only the probe root, a context loaded 1 of the 148 authorities the system file holds, which is the second row of Table 3 and the reason a public site starts failing the moment the proxy’s root is added alone. Turning verification off gets past the proxy and removes the only check that would tell you the proxy is there.
A container from a minimal base image
Minimal base images drop the packages nothing links against, and the CA bundle is one of them: a base such as debian:slim can arrive without ca-certificates and without the directory it fills, though the official python:*-slim images install it as a runtime dependency. get_default_verify_paths() still returns a path, because the interpreter was compiled with one – the path is simply not there, the context loads no authorities, and the handshake fails the way the empty SSL_CERT_FILE row of Table 3 did. The clients that break are the ones that read that store – ssl, urllib, aiohttp – while requests and httpx keep working, because they ship certifi and read that bundle by default. Install the package in the image, or copy a bundle in and set SSL_CERT_FILE to it, then have the build assert that a fresh context’s get_ca_certs() is not empty: that assertion fails at build time instead of during a deploy, and a check that only calls requests passes in the broken image.
A macOS install from python.org
The official macOS installer leaves the interpreter without a link to the system keychain and puts a script for making one, Install Certificates.command, in the Python folder under /Applications. An install that never ran it has an interpreter whose store is empty or names a file that is not on disk, so a call through ssl or urllib fails on every HTTPS request. The two clients beside them answer normally, for different reasons: requests ships certifi and uses that bundle by default, without asking the interpreter for a store, and curl reads the keychain. That split is also the quickest way to tell this case from the proxy, where the client carrying its own bundle is the one that still fails. Run the script once for each installed version; it installs certifi and links the bundle into the interpreter, and the store the process reads stops depending on which shell started it.
The three have one thing in common, and it is the reason section 3 comes before any certificate is read: the server was serving what it should, the client read a store the operator did not have in mind, and the code was 20 – or 19 where the proxy sent the root that signed its certificate – with the message changing and the cause not. Each fix changes which file the process reads – not the certificate, and not the number of attempts.
6. The Name Check: One Label per Wildcard
The certificate behind this section carries three subjectAltName entries: server.test, *.wild.test and 127.0.0.1. Ten names were asked of it, and the package’s matches was asked the same ten questions before the handshake ran. The two agreed on all of them, which is the only reason the rule below is stated as measured rather than recalled.
| Name asked for | Covered by the certificate | Code |
|---|---|---|
server.test | an exact entry | 0 |
server.test. | the trailing dot is kept, so no | 62 |
a.wild.test | one label under the wildcard | 0 |
a.b.wild.test | two labels, so no | 62 |
wild.test | the wildcard itself needs a label | 62 |
10.0.0.1 | no address entry | 64 |
A wildcard stands for exactly one label, so a certificate for *.wild.test covers a.wild.test and refuses a.b.wild.test with code 62: a service that moves from one subdomain to two needs a new certificate, not a new trust store. A trailing dot is not folded either – server.test. was refused with code 62 although it names the same host, so a URL assembled from a configured host that ends in a dot fails a check that looks identical in the log.
Addresses are their own case. 10.0.0.1 produced code 64, not code 62, because the address family has its own OpenSSL result and an address is never matched against a DNS wildcard. A service that connects by IP to a certificate issued for a name fails here and not in a browser that was given the name.
from __future__ import annotations
def normalize(host: str) -> str:
"""Lowercase, strip space and unwrap IPv6 brackets; a trailing dot is left alone.
The dot is not folded here because the verification path on this stack does not fold it: a
certificate for ``server.test`` did not cover ``server.test.`` and the handshake failed with
code 62 (probe 04). A rule that is kinder than the handshake hides that failure instead of
reporting it.
"""
name = host.strip().lower()
if name.startswith("[") and name.endswith("]"):
name = name[1:-1]
return name
def matches(pattern: str, host: str) -> bool:
"""True when one subjectAltName entry covers ``host``."""
rule = normalize(pattern)
name = normalize(host)
if not rule or not name:
return False
if rule == name:
return True
if not rule.startswith("*."):
return False
suffix = rule[2:]
if not suffix or "*" in suffix:
return False
# One label exactly: the host must end in ".suffix" and have no further dot before it.
return name.endswith("." + suffix) and name.count(".") == suffix.count(".") + 1
That is the rule the handshake applied, and it is smaller than most implementations assume. The common name does not enter it: asked for cn.test, a certificate with no subjectAltName at all verified with code 0, and the same certificate refused other.test with code 62. The fallback belongs to this OpenSSL build, not to TLS – a browser or a Go client rejects a certificate with no subjectAltName whatever its common name says – which is the reason to issue with the extension rather than rely on what one host accepts.
7. The Clock Is the Client’s
The same leaf, the same issuer, the same store; only the validity window moved. Three arms, five repeats each, one server process throughout, so whatever decided the outcome was reading a clock that did not belong to the server.
The expired leaf, valid until 2021-01-01, raised code 10; the future leaf, valid from 2030-01-01, raised code 9. Neither code changed in five repeats, and both are reported after the path is built and before any name is checked. That order is why the expired leaf sent without its issuer raised the missing-issuer code 20 instead: the time check never ran.
A client whose clock is behind sees a certificate that is not yet valid; one whose clock is ahead sees an expired certificate. Both are the same window read from the wrong side, and nothing in the certificate or the store can correct either. These two codes are the only ones here whose fix lives on the client host rather than in the chain or the bundle, which is worth remembering before a certificate is reissued over a clock.
8. What the Server Logs Is Not What the Client Saw
Seven client-side causes were run against a server that records the alert it receives. Every one ended the same way on the server: wrap_socket raised, the server never reached a request handler, and no response was written. The alert it logged, though, was one of only 3 names for 7 causes.
| Alert the server logged | Client codes behind it | How many |
|---|---|---|
| ssl:TLSV1_ALERT_UNKNOWN_CA | 18, 19, 20 | three trust failures |
| ssl:SSLV3_ALERT_BAD_CERTIFICATE | 9, 62, 64 | not yet valid, name, address |
| ssl:SSLV3_ALERT_CERTIFICATE_EXPIRED | 10 | expiry alone |
Three client codes – not yet valid, name mismatch and address mismatch – arrived as one alert, and the three trust failures arrived as another. Expiry did not join the first group, which is the one place the server’s vocabulary separates the two time checks. An operator watching server logs sees a handshake that failed and a name for the alert; the certificate, the store and the name that decided the outcome are all on the other host.
It is also why “the certificate is fine, curl works” settles nothing. A refused handshake looks the same from the server whether the client lacked a root, read the wrong clock or asked for a name the certificate does not carry, and in all three cases the certificate is exactly what it was. The side that knows why is the side that usually logs least.
9. What the Wrapper Hides
The same failing handshake was made through four clients, and the question asked of each was whether a caller can still reach verify_code from the exception it catches. One client keeps the number where it is raised; the others bury it under a wrapper whose type says nothing about certificates, and each buries it at its own depth.
http.client raises SSLCertVerificationError at the top. urllib wraps it in URLError and leaves it one link down, in reason. requests reports a pool error and keeps the certificate error 3 links down, behind a retry wrapper; httpx reports ConnectError with the same error 2 links down as its cause. A handler written for one client and copied to another usually logs the outer type and loses the one field that identifies the fix.
The store difference from section 3 shows up in the same experiment. Under requests 2.34.2, setting SSL_CERT_FILE changed nothing: the call failed exactly as it had with no variable set, because the session resolves verify=True to its own bundle and never reads the variable – REQUESTS_CA_BUNDLE or an explicit verify= is the way in. The same variable, in the same process, made the httpx call pass.
That second half is worth stating precisely, because the version of the client does not enter it. The same four calls – no variable, SSL_CERT_FILE, SSL_CERT_DIR, and verify= – were run through four httpx releases on this host – 0.23.3, 0.25.2, 0.27.2, 0.28.1 – against the same server and the same certificate, three times each. All four releases behaved the same way: with no variable set the call failed with code 20, with either variable set it verified, and verify= verified as well. requests 2.34.2 read neither variable in the same process; only REQUESTS_CA_BUNDLE or verify= changed its answer. The store question is therefore settled per client, not per upgrade.
What a verified peer exposes follows the same design in reverse. An unvalidated certificate is not an error on the socket object: getpeercert returns an empty dictionary, and its docstring says so – Return None if no certificate was provided, {} if a certificate was provided, but not validated. Code that reads a name out of that dictionary is reading nothing and treating the absence as a fact about the peer.
10. A Retry Is the Wrong Reflex
Each arm in sections 2, 6, 7 and 8 ran 5 times and returned the same code every time: no store emptied itself, no clock corrected, no name changed between attempts. A failure whose inputs are configuration is decided before the first packet, so another attempt asks the same question of the same store and gets the same answer.
The price of the check is not the reason to skip it. The same handshake with verification on and off measured 1.811 ms and 1.815 ms at the median. The unverified arm was slower by 4.0 µs, and one arm’s own five run medians moved between 1.792 ms and 1.814 ms – a spread of 22 µs. Five runs of twenty handshakes cannot resolve a difference smaller than that spread, so the honest reading is “no measurable difference on this host”, not “verification is free”. Turning it off buys no time and deletes the only fields that say why a connection failed.
What a retry does buy is delay. A store that lacks a root lacks it on every attempt, and an alert that should have fired once fires on every request until someone reads the code – and when the certificate expires everywhere at once, the request volume that a retry policy multiplies is exactly what turns one failing instance into a fleet-wide incident.
One line is enough to stop that loop before it starts. It names the code, the check and the fix, and it carries the retry budget so a caller cannot read the line and reach for a loop by accident:
tls verify failure at api.test: code 20 (unable to get local issuer certificate); check=chain; retries=0; fix: Send the intermediate with the leaf; adding the root to the store does not replace it.
11. Triage in Sixty Seconds
The order below follows the evidence, not the alphabet. Each step either names the cause or narrows it to one check, and none of them is a retry.
- Read
verify_codefrom the exception or the log. If only text survived, match it against the message stems infrom_message; if neither is available, the server’s log cannot classify the failure, because the server never received the client’s reason. - For codes 18 and 19, either the leaf or a root sent with it is self-signed: look at what the server sends first, then at what the client’s store holds. For codes 20 and 21 the issuer is missing, so the chain file on the server is the place to look, not the client.
- For codes 9 and 10 compare the certificate’s two dates with the client host’s clock. A store change fixes neither, and a renewed certificate fixes only the second.
- For codes 62 and 64 print the subjectAltName entries beside the exact name or address the client asked for. A trailing dot, one extra label or an address in a name field accounts for most of what remains.
- If a fix works from a shell and not from the service, print the stores the library actually reads –
store.effectivereturns them per client – and compare that with the shell’s. A configuration file is not evidence about the store a process loaded. - Set the retry budget to zero for any code in table 2, alert on the first occurrence, and attach the code and the check to the alert so the next reader starts at the check instead of at the message.
The list is short because the checks are few. What makes a verification failure expensive is not the diagnosis – 7 codes, 3 alerts from the server, one question about a store – but the time spent retrying a condition that cannot change.
Frequently asked questions
The message says unable to get local issuer certificate, but the root is installed. Why?
The field that says which check failed is verify_code, and this one is about building a path, not about trusting a root. The client can only build a path from the leaf through the certificates the server sent; if the issuer named inside the leaf is not among them, the walk stops before the installed root is consulted. Send the intermediate beside the leaf. The trust store is not implicated.
Is SSL_CERT_FILE enough for every Python client?
No. Contexts built on ssl read it, and so did every release of httpx measured here, from 0.23.3 to 0.28.1. requests resolves verify=True to its own certifi bundle and never reads the variable, so REQUESTS_CA_BUNDLE or verify= is the only way in. In the same process and with the same variable, one client passed and the other failed.
Does a wildcard certificate cover every subdomain?
It covers one label. A certificate for a wildcard in the first position matched a single label and refused a name with two labels before it, in every repeat. A deeper name needs its own subjectAltName entry or a certificate that carries it.
Why does connecting by IP fail when the certificate is valid?
An address is checked against IP entries in the subjectAltName, never against DNS names and never through a wildcard. The handshake returned an address code rather than the name-mismatch code, which is the clue that the certificate needs an address entry or the client needs a name.
Is it worth retrying a verification failure?
Not once. Every arm returned the same code in every repeat, and no code in the table is marked retryable; the inputs that decided the outcome are configuration, not weather. A retry budget here only delays the alert and multiplies the log lines.
curl works and Python does not. What is different?
Usually the store. curl and Python on one host can read different bundles, and a private root added to one is invisible to the other. Compare what each reads rather than what each is configured with, because the configuration and the effective store are not the same list.
What does getpeercert return when verification failed?
An empty dictionary, not an error: the socket still has a peer certificate, it was simply not validated. Code that reads a subject from that dictionary gets nothing back, so the certificate’s names have to be read before a decision depends on them.
How can this be reproduced without a public certificate?
The probes generate their own two roots, an intermediate and seven leaves, then serve them from loopback with one property changed per arm. Generation is in certs.py and needs no network, so the whole article can be re-run on a laptop.
Take the next step
- Zero-Crash Python – one measured failure per issue, with its probe. Free.
- Runbook checklists on Gumroad – these tables as an incident-doc checklist.
Everything the tables quote was produced by the files below, unchanged. The package is 6 files and 555 lines, the probes are 12 files beside the two helpers they share, and the certificate generator writes the same subjects, serials and windows on every run, so a rebuild produces the same codes and the same verdicts; the keys and the handshake timings differ run to run, and no table prints a key while the cost section states its own resolution. The folded blocks are here for the reader who wants to run them, not to be scrolled through: the body carries only the parts a fix depends on.
Appendix: Every File This Page Quotes
Four directories, laid out as printed: the package under module/, the probes and their certificates under sandbox/, one results file per probe, and the per-release output probe 12 writes. The package itself is not installed – the probes put module/ on their own path and import it in place – and the only packages the probes need from outside are cryptography, certifi, requests and httpx. The six test files are named in the tree and run in an optional step below, but they are not reprinted in this appendix: the folds carry the package’s six files, the two helpers and the twelve probes.
Folder structure
module/ the package the probes import, not installed
└── trustpath/
├── __init__.py codes.py store.py chain.py hosts.py report.py
└── tests/ conftest.py test_codes.py test_chain.py
test_hosts.py test_store.py test_report.py
sandbox/ the probes, and the two helpers they share
├── 01_conditions.py … 12_httpx.py one probe per table, numbered in page order
├── certs.py two roots, one intermediate, seven leaves, offline
├── certs/ what certs.py writes: the PEM chains and a hashed store
└── probe.py one attempt: one server, one client, one recorded code
results/ one JSON per probe - the source of every number here
scratch/ per-release output of 12_httpx.py; working files, not reprinted
Run order
The packages once, then the certificates, then a probe at a time: those steps need nothing the folds do not carry, so the listing below runs as printed, in order. The package’s own tests come after them and only if you have the tests/ tree beside module/, which this appendix does not reprint, so that step is marked optional. The commands are the ones used here, and the paths in them are the reason each step starts in a different directory – the probes open their certificates by a relative path, and pytest reads the package from the working directory.
# 0. the four third-party packages the probes import, once per interpreter python3 -m pip install cryptography certifi requests httpx # 1. the certificates, from sandbox/: each probe calls certs.build() and reads them by relative path cd sandbox && python3 certs.py # 2. one probe at a time, from the same directory; each rewrites its own results file python3 04_hostname.py # 05_chain.py, 06_time.py and the rest run the same way # 3. optional, only if you also have tests/, which this appendix does not reprint: the package's # own tests, from inside module/, with nothing of the package installed (90 passed) cd ../module && python3 -m pytest trustpath/tests -q # 4. probe 12 runs once under each httpx release and writes scratch/httpx_<version>.json; # --merge then collects those files into results/12_httpx.json, which is what the page quotes cd ../sandbox && python3 12_httpx.py python3 12_httpx.py --merge
The verify code table, the field read and the wrapper walk. codes.py
"""A verification failure, named by the check that raised it rather than by the message.
Python raises one exception type for every certificate check - ``SSLCertVerificationError`` -
and one message prefix, ``certificate verify failed``. The part that says which check failed is
``verify_code``: an OpenSSL ``X509_V_ERR_*`` value that survives translation and is the only
field in the exception a program can act on.
``TABLE`` maps the codes this package knows to the one thing an operator can change. Nothing in
it is marked retryable: a store that does not contain a root, a clock that is wrong and a name
that does not match do not change because a request was sent again.
"""
from __future__ import annotations
import dataclasses
import enum
import ssl
CHECK_ORDER = ("trust", "chain", "time", "hostname", "revocation")
class Kind(str, enum.Enum):
"""Which of the checks in a verification path failed."""
TRUST = "trust"
CHAIN = "chain"
HOSTNAME = "hostname"
EXPIRED = "expired"
NOT_YET_VALID = "not_yet_valid"
REVOKED = "revoked"
OTHER = "other"
@dataclasses.dataclass(frozen=True)
class Fault:
"""One code, what it means, and what changes it."""
code: int
kind: Kind
short: str
remedy: str
retryable: bool = False
TABLE: dict[int, Fault] = {
18: Fault(18, Kind.TRUST, "self-signed certificate",
"The leaf is its own issuer: add that certificate to the client's store, or have "
"the service present a certificate a known root signed."),
19: Fault(19, Kind.CHAIN, "self-signed certificate in chain",
"The server sends a root the client does not trust: remove the self-signed root "
"from the served chain and trust it explicitly, or reissue under a public root."),
20: Fault(20, Kind.CHAIN, "unable to get local issuer certificate",
"The client cannot build a path from the leaf to a trusted root. Send the "
"intermediate with the leaf; adding the root to the store does not replace it."),
21: Fault(21, Kind.CHAIN, "unable to verify the first certificate",
"The client cannot build a path from the leaf to a trusted root. Send the "
"intermediate with the leaf; adding the root to the store does not replace it."),
9: Fault(9, Kind.NOT_YET_VALID, "certificate is not yet valid",
"The client's clock is behind the certificate's notBefore. Fix the clock, or "
"reissue the certificate with a notBefore that is already past."),
10: Fault(10, Kind.EXPIRED, "certificate has expired",
"The certificate's notAfter is behind the client's clock. Renew on the server; a "
"client-side trust change will not bring back an expired leaf."),
23: Fault(23, Kind.REVOKED, "certificate revoked",
"The issuer published a revocation. Replace the certificate; the trust store is "
"not the problem."),
62: Fault(62, Kind.HOSTNAME, "hostname mismatch",
"The name the client asked for is not in the certificate's subjectAltName. Connect "
"by a name the certificate covers, or reissue with the name in its SAN."),
64: Fault(64, Kind.HOSTNAME, "IP address mismatch",
"The client asked for an address and the certificate lists no such IP entry. "
"Addresses are matched as addresses, never against a DNS wildcard."),
}
# Spelling variants of the same missing-issuer condition, grouped so a caller that only has the
# message can still reach the right row.
MESSAGE_HINTS: tuple[tuple[str, int], ...] = (
("unable to get local issuer", 20),
("unable to verify the first", 21),
("self-signed certificate in certificate chain", 19),
("self-signed certificate", 18),
("certificate has expired", 10),
("certificate is not yet valid", 9),
("hostname mismatch", 62),
("ip address mismatch", 64),
("certificate revoked", 23),
)
def classify(code: int) -> Fault:
"""Return the fault for one ``verify_code``; unknown codes keep their number."""
return TABLE.get(int(code), Fault(int(code), Kind.OTHER, "unrecognised verify code",
"Read the code against the X509_V_ERR table and add it "
"to this map.", retryable=False))
def verify_code_of(exc: BaseException | None) -> tuple[int, str] | None:
"""The ``verify_code`` and ``verify_message`` inside a wrapper chain, if one is there.
Clients wrap the original exception: ``urllib`` puts it in ``URLError.reason``, ``requests``
hides it behind a pool error, ``httpx`` keeps it as ``__cause__``. Walking those links is
the difference between logging "connect error" and logging code 20. Eight links is more
than any client measured here used, and the bound stops a cycle in a badly built exception.
"""
depth = 0
current: BaseException | None = exc
while current is not None and depth < 8:
if isinstance(current, ssl.SSLCertVerificationError):
return int(current.verify_code), current.verify_message
nested = getattr(current, "reason", None)
current = nested if isinstance(nested, BaseException) else (
current.__cause__ or current.__context__)
depth += 1
return None
def from_exception(exc: BaseException | None) -> Fault | None:
"""Classify the verification error inside a wrapper chain, or return nothing."""
found = verify_code_of(exc)
return None if found is None else classify(found[0])
def retry_budget(fault: Fault | None, attempts: int = 3) -> int:
"""How many times it is worth trying again: zero for every verification fault."""
if fault is None:
return attempts
return attempts if fault.retryable else 0
def from_message(text: str) -> Fault | None:
"""Classify a failure that reached the log as text, with no exception object left."""
lowered = text.lower()
for hint, code in MESSAGE_HINTS:
if hint in lowered:
return classify(code)
return None
The store order per client, and the empty-file case. store.py
"""Which certificate store a client actually reads, in the order it reads them.
The same process can use three different stores without anyone choosing one: ``ssl`` and the
libraries built on it take ``SSL_CERT_FILE`` before the compiled-in path, ``httpx`` takes
``SSL_CERT_FILE`` before its own ``certifi`` bundle, ``requests`` never reads ``SSL_CERT_FILE``
at all, and a ``verify=`` argument outranks every one of them. This module names that order so
a probe can measure it and a runbook can print it.
``Candidate.certificates`` counts the certificates in a file (or a hashed directory), which is
what makes a wrong store visible: the path exists, the context loads, and the root is not in it.
"""
from __future__ import annotations
import dataclasses
import os
import pathlib
import ssl
@dataclasses.dataclass(frozen=True)
class Candidate:
"""One store a client may read, and whether it holds anything."""
source: str
path: str
exists: bool
certificates: int
@property
def usable(self) -> bool:
return self.exists and self.certificates > 0
def count_certificates(path: str) -> int:
"""Count distinct certificates in a bundle, or in a hashed directory of bundles.
A hashed directory names the same certificate once per lookup alias, so the count is of
distinct bodies, not of files: the number should say how many roots are reachable, not how
many names they answer to.
"""
target = pathlib.Path(path)
try:
if target.is_dir():
seen: set[str] = set()
for entry in sorted(target.iterdir()):
if entry.is_file() and not entry.name.endswith(".key"):
try:
text = entry.read_text(errors="ignore")
except OSError:
continue
for block in _blocks(text):
seen.add(block)
return len(seen)
return len(_blocks(target.read_text(errors="ignore")))
except OSError:
return 0
def _blocks(text: str) -> list[str]:
"""The body of every PEM certificate in one file, whitespace removed."""
out: list[str] = []
for piece in text.split("-----BEGIN CERTIFICATE-----")[1:]:
out.append("".join(piece.split("-----END CERTIFICATE-----")[0].split()))
return out
def _candidate(source: str, path: str | None) -> Candidate:
if not path:
return Candidate(source, "", False, 0)
target = pathlib.Path(path)
return Candidate(source, str(path), target.exists(), count_certificates(path))
def ssl_candidates(env: dict[str, str] | None = None,
explicit: str | None = None) -> list[Candidate]:
"""The stores ``ssl.create_default_context()`` consults, highest priority first."""
environment = os.environ if env is None else env
opened = ssl.get_default_verify_paths()
rows = [
_candidate("verify argument", explicit),
_candidate("SSL_CERT_FILE", environment.get("SSL_CERT_FILE")),
_candidate("compiled-in cafile", opened.openssl_cafile),
_candidate("SSL_CERT_DIR", environment.get("SSL_CERT_DIR")),
_candidate("compiled-in capath", opened.openssl_capath),
]
return rows
def requests_candidates(env: dict[str, str] | None = None,
explicit: str | None = None) -> list[Candidate]:
"""The stores ``requests`` consults: its own bundle first, the environment second.
``SSL_CERT_FILE`` is not on this list. ``requests`` resolves ``verify=True`` to ``certifi``
itself and hands that path to urllib3, so the variable that fixes every other client on
the host is never read here - the row that a reader expects is the one that is absent.
"""
environment = os.environ if env is None else env
import certifi
return [
_candidate("verify argument", explicit),
_candidate("REQUESTS_CA_BUNDLE", environment.get("REQUESTS_CA_BUNDLE")),
_candidate("CURL_CA_BUNDLE", environment.get("CURL_CA_BUNDLE")),
_candidate("certifi", certifi.where()),
]
def httpx_candidates(env: dict[str, str] | None = None,
explicit: str | None = None) -> list[Candidate]:
"""The stores ``httpx`` consults: the variables, then its own bundle.
``httpx`` builds its context with ``certifi`` rather than the compiled-in path, so an
unset host trusts 118 roots where ``ssl.create_default_context()`` trusts 148. A
``SSL_CERT_FILE`` or ``SSL_CERT_DIR`` in the environment replaces that bundle before it is
reached, on each of the four releases measured here (0.23.3 through 0.28.1).
"""
environment = os.environ if env is None else env
import certifi
return [
_candidate("verify argument", explicit),
_candidate("SSL_CERT_FILE", environment.get("SSL_CERT_FILE")),
_candidate("SSL_CERT_DIR", environment.get("SSL_CERT_DIR")),
_candidate("certifi", certifi.where()),
]
def candidates(client: str = "ssl", env: dict[str, str] | None = None,
explicit: str | None = None) -> list[Candidate]:
if client in ("requests", "urllib3"):
return requests_candidates(env, explicit)
if client == "httpx":
return httpx_candidates(env, explicit)
if client in ("ssl", "urllib", "aiohttp", "http.client"):
return ssl_candidates(env, explicit)
raise ValueError(f"unknown client {client!r}")
def resolve(client: str = "ssl", env: dict[str, str] | None = None,
explicit: str | None = None) -> Candidate | None:
"""The bundle (file store) the client would read first, if it holds certificates.
A TLS context on this stack loads a file store and a directory store together; this returns
the file one. ``effective`` returns both.
"""
rows = candidates(client, env, explicit)
for row in rows:
if row.usable and row.source in FILE_STORES.get(client, FILE_STORES["ssl"]):
return row
return None
FILE_STORES = {
"ssl": ("verify argument", "SSL_CERT_FILE", "compiled-in cafile", "REQUESTS_CA_BUNDLE",
"CURL_CA_BUNDLE", "certifi"),
"httpx": ("verify argument", "SSL_CERT_FILE", "certifi"),
"requests": ("verify argument", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "certifi"),
}
DIR_STORES = ("SSL_CERT_DIR", "compiled-in capath")
def _first_set(rows: list[Candidate], sources: tuple[str, ...]) -> Candidate | None:
"""The first source that was actually given a path, even an empty or missing one."""
for row in rows:
if row.source in sources and row.path:
return row
return None
def effective(client: str = "ssl", env: dict[str, str] | None = None,
explicit: str | None = None) -> list[Candidate]:
"""Every store the client actually loads, in the order it loads them.
A store named by an argument or a variable is used even when it is empty: an empty
``SSL_CERT_FILE`` replaces the bundle with nothing rather than falling back to the system
one, which is why the row for it shows zero certificates and a verification failure.
``ssl`` loads one file store and one directory store, ``httpx`` one bundle or one file
store plus a directory store, and ``requests`` one bundle.
"""
rows = candidates(client, env, explicit)
if client in ("requests", "urllib3"):
chosen = _first_set(rows, ("verify argument", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"))
if chosen is None:
chosen = next((row for row in rows if row.source == "certifi" and row.usable), None)
return [chosen] if chosen is not None else []
out: list[Candidate] = []
file_store = _first_set(rows, ("verify argument", "SSL_CERT_FILE"))
if file_store is None:
fallback = "certifi" if client == "httpx" else "compiled-in cafile"
file_store = next((row for row in rows
if row.source == fallback and row.usable), None)
if file_store is not None:
out.append(file_store)
dir_store = _first_set(rows, ("SSL_CERT_DIR",))
if dir_store is None:
dir_rows = ssl_candidates(env) if client == "httpx" else rows
dir_store = next((row for row in dir_rows
if row.source == "compiled-in capath" and row.usable), None)
if dir_store is not None:
out.append(dir_store)
return out
def precedence(client: str = "ssl", env: dict[str, str] | None = None) -> list[str]:
"""The names in the order they are tried, whether or not they exist on this host."""
return [row.source for row in candidates(client, env)]
Reading a served chain and reporting where it stops. chain.py
"""Read the chain a server sent and say where the path breaks.
A TLS server sends an ordered list of certificates: the leaf first, then the intermediates a
client needs to reach a root it already trusts. OpenSSL builds the path by matching each
certificate's issuer to the next certificate's subject, so one link out of order stops the walk
exactly where the order changes.
``gaps`` reports those places by index, and ``summary`` says whether the list is leaf-first and
whether it is self-contained. It reads what was served; it cannot say what the server meant to
serve.
"""
from __future__ import annotations
import dataclasses
from cryptography import x509
@dataclasses.dataclass(frozen=True)
class Link:
"""One certificate in the list: who it is for, who signed it, and when it is valid."""
subject: str
issuer: str
not_before: str
not_after: str
key: tuple[tuple[str, str], ...] = ()
issuer_key: tuple[tuple[str, str], ...] = ()
@property
def self_signed(self) -> bool:
return self.key == self.issuer_key
@dataclasses.dataclass(frozen=True)
class Gap:
"""A place where the next certificate does not continue the current one."""
index: int
expected: str
found: str
def _key(name: x509.Name) -> tuple[tuple[str, str], ...]:
"""A name as comparable pairs: attribute order and spacing do not change identity."""
pairs = []
for attribute in name.rdns:
for part in attribute:
pairs.append((part.oid.dotted_string, str(part.value).strip().lower()))
return tuple(sorted(pairs))
def _label(name: x509.Name) -> str:
common = name.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
if common:
return f"CN={common[0].value}"
return name.rfc4514_string()[:60]
def links(pem_text: str) -> list[Link]:
"""Every certificate in a PEM bundle, in the order the bundle lists them."""
out: list[Link] = []
for cert in x509.load_pem_x509_certificates(pem_text.encode()):
out.append(Link(
subject=_label(cert.subject),
issuer=_label(cert.issuer),
not_before=cert.not_valid_before_utc.strftime("%Y-%m-%d"),
not_after=cert.not_valid_after_utc.strftime("%Y-%m-%d"),
key=_key(cert.subject),
issuer_key=_key(cert.issuer),
))
return out
def gaps(chain: list[Link]) -> list[Gap]:
"""The indices where the served order stops matching issuer to subject."""
out: list[Gap] = []
for index in range(len(chain) - 1):
expected = chain[index].issuer
found = chain[index + 1].subject
if chain[index].issuer_key != chain[index + 1].key:
out.append(Gap(index, expected, found))
return out
def leaf_first(chain: list[Link]) -> bool:
"""True when the first certificate is not its own issuer and the list continues from it."""
if not chain or chain[0].self_signed:
return False
return not gaps(chain)
def summary(pem_text: str) -> dict:
"""What the served list is, in the terms the article's table uses."""
chain = links(pem_text)
return {
"count": len(chain),
"leaf_first": leaf_first(chain),
"self_signed_leaf": bool(chain) and chain[0].self_signed,
"gaps": [dataclasses.asdict(gap) for gap in gaps(chain)],
"subjects": [link.subject for link in chain],
"issuers": [link.issuer for link in chain],
"not_after": [link.not_after for link in chain],
}
The subjectAltName rule, one label per wildcard. hosts.py
"""Hostname matching as the verification path does it: subjectAltName, one wildcard label.
A certificate is valid for a name if the name appears in its subjectAltName extension. A
wildcard in the first label - ``*.example.com`` - covers one label, so it covers
``api.example.com`` and not ``v1.api.example.com``; a wildcard anywhere else is not a wildcard.
The subject's common name is not consulted when a subjectAltName is present.
``matches`` is the rule this package's tests pin; the probes compare it against what OpenSSL
decided on a real handshake, which is the only opinion that matters in production.
"""
from __future__ import annotations
import ipaddress
def normalize(host: str) -> str:
"""Lowercase, strip space and unwrap IPv6 brackets; a trailing dot is left alone.
The dot is not folded here because the verification path on this stack does not fold it: a
certificate for ``server.test`` did not cover ``server.test.`` and the handshake failed with
code 62 (probe 04). A rule that is kinder than the handshake hides that failure instead of
reporting it.
"""
name = host.strip().lower()
if name.startswith("[") and name.endswith("]"):
name = name[1:-1]
return name
def is_address(host: str) -> bool:
try:
ipaddress.ip_address(normalize(host).split("%")[0])
return True
except ValueError:
return False
def matches(pattern: str, host: str) -> bool:
"""True when one subjectAltName entry covers ``host``."""
rule = normalize(pattern)
name = normalize(host)
if not rule or not name:
return False
if rule == name:
return True
if not rule.startswith("*."):
return False
suffix = rule[2:]
if not suffix or "*" in suffix:
return False
# One label exactly: the host must end in ".suffix" and have no further dot before it.
return name.endswith("." + suffix) and name.count(".") == suffix.count(".") + 1
def covers(patterns: list[str], host: str) -> bool:
return any(matches(pattern, host) for pattern in patterns)
def why(patterns: list[str], host: str) -> str:
"""A sentence for a log line: which entry covered the name, or why none could."""
name = normalize(host)
for pattern in patterns:
if matches(pattern, name):
return f"{pattern} covers {name}"
if any(pattern.startswith("*.") for pattern in patterns):
return (f"no entry covers {name}: a leading *. stands for exactly one label, so "
f"{name} has one more label than any wildcard here")
return f"no subjectAltName entry equals {name}"
The single log line, with its zero retry budget. report.py
"""One log line a service can write for a verification failure.
A handler that catches the outer exception of whichever client it uses can hand it here: the
number is found through the wrapper chain, the failing check is named, and the retry budget is
zero for every verification fault. The line is meant for an incident channel, not for a retry
loop.
"""
from __future__ import annotations
from .codes import from_exception, retry_budget
def describe_failure(exc: BaseException, host: str = "") -> str:
"""A single line naming the code, the check and the fix, or saying it was not a check."""
fault = from_exception(exc)
where = host or "peer"
if fault is None:
return f"tls failure at {where}: no certificate verification error in the chain"
return (f"tls verify failure at {where}: code {fault.code} ({fault.short}); "
f"check={fault.kind.value}; retries={retry_budget(fault)}; fix: {fault.remedy}")
What the package exports. __init__.py
"""Four small pieces used to read a certificate verification failure on the client side.
``codes`` turns a ``verify_code`` into the check that failed and the change that fixes it,
``store`` says which trust store a client will actually read, ``chain`` reports where a served
chain stops continuing, and ``hosts`` applies the subjectAltName rule the handshake applies.
"""
from __future__ import annotations
from .chain import Gap, Link, gaps, leaf_first, links, summary
from .codes import TABLE, CHECK_ORDER, Fault, Kind, classify, from_exception, retry_budget
from .hosts import covers, is_address, matches, normalize, why
from .report import describe_failure
from .store import (Candidate, candidates, count_certificates, effective, precedence,
resolve)
__all__ = [
"TABLE", "CHECK_ORDER", "Candidate", "Fault", "Gap", "Kind", "Link",
"candidates", "classify", "count_certificates", "covers", "describe_failure",
"effective", "from_exception", "gaps",
"is_address", "leaf_first", "links", "matches", "normalize", "precedence", "resolve",
"retry_budget", "summary", "why",
]
The attempt, the repeat and the HTTPS server used by the probes. probe.py
"""Shared helpers for the certificate-verification probes.
Each attempt starts its own loopback TLS server that presents one chain, connects one client
that trusts one store, and records three things the article keeps apart: what the client raised
(and the ``verify_code`` inside it), how long the handshake took, and what the server saw - which
is a different error, in a different place, and often arrives after the server believed the
handshake was over.
A verdict that says only "verification failed" is the reason this file exists: the code, the
alert and the side that recorded it are three separate facts.
"""
from __future__ import annotations
import json
import os
import pathlib
import platform
import socket
import ssl
import statistics
import threading
import time
SANDBOX = pathlib.Path(__file__).resolve().parent
HERE = SANDBOX.parent
RESULTS = HERE / "results"
CERTS = SANDBOX / "certs"
TIMEOUT = 4.0
# The package the article prints lives beside the probes; import it the way a reader would.
import sys # noqa: E402 (after the path this file needs to add)
if str(HERE / "module") not in sys.path:
sys.path.insert(0, str(HERE / "module"))
def percentiles(samples: list[float]) -> dict:
"""The numbers the article quotes, from one list of samples."""
ordered = sorted(samples)
if not ordered:
return {"count": 0}
def pick(fraction: float) -> float:
index = min(len(ordered) - 1, max(0, int(round(fraction * (len(ordered) - 1)))))
return ordered[index]
return {
"count": len(ordered),
"min": ordered[0],
"p50": pick(0.50),
"p90": pick(0.90),
"p95": pick(0.95),
"p99": pick(0.99),
"max": ordered[-1],
"mean": statistics.fmean(ordered),
}
def describe(name: str, samples: list[float]) -> dict:
summary = percentiles(samples)
summary["name"] = name
summary["samples"] = len(samples)
return summary
def save(name: str, payload: dict) -> None:
RESULTS.mkdir(exist_ok=True)
(RESULTS / name).write_text(json.dumps(payload, ensure_ascii=False, indent=1) + "\n",
encoding="utf-8")
def sysctl(path: str) -> str:
try:
return pathlib.Path(path).read_text().strip()
except OSError:
return ""
def host_facts() -> dict:
"""The conditions every probe ran under, read from the host rather than assumed."""
import certifi
paths = ssl.get_default_verify_paths()
default = ssl.create_default_context()
bundle = pathlib.Path(certifi.where())
facts = {
"kernel": platform.release(),
"machine": platform.machine(),
"python": platform.python_version(),
"openssl": ssl.OPENSSL_VERSION.split(" ")[1],
"cpu_count": os.cpu_count(),
"clock_resolution_ns": time.get_clock_info("monotonic").resolution * 1e9,
"default_cafile": paths.cafile or "",
"default_capath": paths.capath or "",
"openssl_cafile": paths.openssl_cafile,
"openssl_capath": paths.openssl_capath,
"default_ca_count": len(default.get_ca_certs()),
"certifi_path": str(bundle),
"certifi_ca_count": bundle.read_text().count("BEGIN CERTIFICATE"),
"env_cert_file": os.environ.get("SSL_CERT_FILE", ""),
"env_cert_dir": os.environ.get("SSL_CERT_DIR", ""),
"env_requests_bundle": os.environ.get("REQUESTS_CA_BUNDLE", ""),
"min_version": default.minimum_version.name,
"max_version": default.maximum_version.name,
"verify_mode": int(default.verify_mode),
"check_hostname": default.check_hostname,
"has_verify_flags": int(default.verify_flags),
}
return facts
class Verdict(dict):
"""One attempt, as the page reads it: client fault, cost, server view."""
@property
def pass_(self) -> bool:
return self["client"]["code"] == 0
def _server_name(host: str) -> str:
return host
def _leaf_for(chain: str) -> str:
"""The key that belongs to the first certificate in a served chain, found by its bytes."""
stem = pathlib.Path(chain).stem
if not stem.startswith("chain-"):
return stem
head = (CERTS / chain).read_text().split("-----END CERTIFICATE-----")[0].strip()
for path in sorted(CERTS.glob("*.pem")):
if path.name.startswith("chain-") or path.name.endswith("-root.pem"):
continue
if path.read_text().split("-----END CERTIFICATE-----")[0].strip() == head:
return path.stem
return "server"
def attempt(chain: str = "chain-leaf-inter.pem", hostname: str = "server.test",
cafile: str | None = None, verify: bool = True,
cadata: str | None = None, capath: str | None = None,
timeout: float = TIMEOUT) -> Verdict:
"""Run one handshake against a server presenting ``chain`` and report all three sides.
``chain`` names a file in ``sandbox/certs``; the leaf's key is assumed to sit beside it as
``<leaf>.key`` unless the chain name says otherwise (chains start with ``server`` or
``direct``). ``verify=False`` disables both the store and the hostname check, which is what
a client that "just wants it to work" does, and is the control arm for the cost table.
"""
leaf = _leaf_for(chain)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(str(CERTS / chain), str(CERTS / f"{leaf}.key"))
context.set_alpn_protocols(["h1"])
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 0))
listener.listen(8)
port = listener.getsockname()[1]
server: dict = {"accepted": None, "wrap_ms": None, "read": None, "peer": None}
ready = threading.Event()
def run_server() -> None:
ready.set()
try:
listener.settimeout(timeout)
conn, _ = listener.accept()
except OSError as exc:
server["accepted"] = f"accept:{type(exc).__name__}"
return
started = time.perf_counter()
try:
tls = context.wrap_socket(conn, server_side=True)
server["wrap_ms"] = (time.perf_counter() - started) * 1000
server["accepted"] = "ok"
server["peer"] = tls.version()
tls.settimeout(timeout)
try:
server["read"] = tls.recv(64).decode("utf-8", "replace")
except ssl.SSLError as exc:
server["read"] = f"ssl:{exc.reason}"
except (OSError, ValueError) as exc:
server["read"] = f"{type(exc).__name__}:{exc}"
finally:
tls.close()
except ssl.SSLError as exc:
server["wrap_ms"] = (time.perf_counter() - started) * 1000
server["accepted"] = "failed"
server["read"] = f"ssl:{exc.reason}"
except (OSError, ValueError) as exc:
server["accepted"] = "failed"
server["read"] = f"{type(exc).__name__}"
finally:
try:
conn.close()
except OSError:
pass
thread = threading.Thread(target=run_server, daemon=True)
thread.start()
ready.wait(1.0)
if verify:
client_context = ssl.create_default_context(cafile=cafile, capath=capath, cadata=cadata)
else:
client_context = ssl.create_default_context()
client_context.check_hostname = False
client_context.verify_mode = ssl.CERT_NONE
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(timeout)
client_error: dict = {"type": "none", "code": 0, "message": "", "reason": ""}
version = ""
started = time.perf_counter()
try:
client.connect(("127.0.0.1", port))
tls = client_context.wrap_socket(client, server_hostname=_server_name(hostname))
elapsed = (time.perf_counter() - started) * 1000
version = tls.version() or ""
try:
tls.sendall(b"ping")
tls.recv(64)
except (OSError, ValueError):
pass
tls.close()
except ssl.SSLCertVerificationError as exc:
elapsed = (time.perf_counter() - started) * 1000
client_error = {"type": type(exc).__name__, "code": int(exc.verify_code),
"message": exc.verify_message,
"reason": f"{exc.reason}" if getattr(exc, "reason", None) else ""}
except (ssl.SSLError, OSError) as exc:
elapsed = (time.perf_counter() - started) * 1000
client_error = {"type": type(exc).__name__, "code": -1, "message": str(exc)[:120],
"reason": getattr(exc, "reason", "") or ""}
finally:
try:
client.close()
except OSError:
pass
thread.join(timeout + 1.0)
listener.close()
return Verdict({
"chain": chain,
"hostname": hostname,
"verify": verify,
"cafile": cafile or "",
"handshake_ms": round(elapsed, 3),
"version": version,
"client": client_error,
"server": {"accepted": server["accepted"], "wrap_ms": server["wrap_ms"],
"read": server["read"], "peer": server["peer"]},
})
def repeat(arms: list[dict], times: int, **shared) -> list[dict]:
"""Run every arm ``times`` times and keep each verdict; the probes summarise afterwards."""
out: list[dict] = []
for arm in arms:
settings = dict(arm)
name = settings.pop("name", "")
runs = [attempt(**{**shared, **settings}) for _ in range(times)]
codes = [run["client"]["code"] for run in runs]
out.append({
"name": name,
"arm": settings,
"runs": runs,
"code": statistics.mode(codes),
"codes": sorted(set(codes)),
"message": stats_message([run["client"]["message"] for run in runs]),
"handshake_ms": percentiles([run["handshake_ms"] for run in runs]),
"client_types": sorted({run["client"]["type"] for run in runs}),
"server_accepted": sorted({str(run["server"]["accepted"]) for run in runs}),
"server_read": stats_message([str(run["server"]["read"]) for run in runs]),
"version": stats_message([run["version"] for run in runs]),
})
return out
def stats_message(values: list[str]) -> str:
"""The message that appeared in every run, or the most common one if they differed."""
if not values:
return ""
unique = sorted(set(values))
if len(unique) == 1:
return unique[0]
return statistics.mode(values)
class HttpsServer:
"""A one-shot HTTPS server that answers any request with 200 and a body of one line."""
def __init__(self, chain: str = "chain-leaf-inter.pem") -> None:
leaf = _leaf_for(chain)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(str(CERTS / chain), str(CERTS / f"{leaf}.key"))
self.context = context
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(("127.0.0.1", 0))
self.socket.listen(16)
self.port = self.socket.getsockname()[1]
self.stop = threading.Event()
self.thread = threading.Thread(target=self._serve, daemon=True)
self.thread.start()
def _serve(self) -> None:
self.socket.settimeout(0.2)
while not self.stop.is_set():
try:
conn, _ = self.socket.accept()
except socket.timeout:
continue
except OSError:
return
try:
tls = self.context.wrap_socket(conn, server_side=True)
tls.settimeout(2.0)
tls.recv(4096)
body = b"ok"
tls.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n"
+ body)
tls.close()
except (ssl.SSLError, OSError):
try:
conn.close()
except OSError:
pass
@property
def url(self) -> str:
return f"https://127.0.0.1:{self.port}/"
def close(self) -> None:
self.stop.set()
self.thread.join(2.0)
self.socket.close()
def __enter__(self) -> "HttpsServer":
return self
def __exit__(self, *exc: object) -> None:
self.close()
def walk_for_code(exc: BaseException) -> dict:
"""Follow the wrapper chain a client leaves and report where, if anywhere, a code survives."""
depth = 0
found: dict = {"depth": None, "code": None, "type": type(exc).__name__,
"chain": [], "message": str(exc)[:160]}
current: BaseException | None = exc
while current is not None and depth < 8:
found["chain"].append(type(current).__name__)
if isinstance(current, ssl.SSLCertVerificationError):
found["depth"] = depth
found["code"] = int(current.verify_code)
found["verify_message"] = current.verify_message
nested = getattr(current, "reason", None)
if isinstance(nested, BaseException):
current = nested
else:
current = current.__cause__ or current.__context__
depth += 1
return found
Two roots, one intermediate and seven leaves, generated offline. certs.py
"""The test PKI the probes verify against: two roots, one intermediate, seven leaves.
Everything is written once into ``sandbox/certs`` and reused, so the certificate a table
describes is the file the handshake presented. Serial numbers and validity windows are fixed
rather than generated, which makes a rebuild produce the same names and the same verdicts; only
the keys differ, and no table prints a key.
One leaf is the good certificate, one is signed directly by a root, and the other five each
break a single verification check:
* ``server`` - signed by the intermediate, SANs for ``server.test``, ``*.wild.test`` and
``127.0.0.1``: the good certificate the other probes change one property of.
* ``direct`` - signed by the root itself, so the chain is one certificate long.
* ``selfsigned`` - its own issuer, trusted by nothing.
* ``expired`` and ``future`` - the same chain as ``server``, wrong only in time.
* ``cnonly`` - no SAN at all, a subject common name and nothing else.
* ``foreign`` - signed by a second root the client is not given.
"""
from __future__ import annotations
import datetime as dt
import pathlib
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
HERE = pathlib.Path(__file__).resolve().parent
CERTS = HERE / "certs"
EPOCH = dt.datetime(2020, 1, 1, tzinfo=dt.timezone.utc)
FUTURE = dt.datetime(2030, 1, 1, tzinfo=dt.timezone.utc)
LONG_AGO = dt.datetime(2019, 1, 1, tzinfo=dt.timezone.utc)
FAR = dt.datetime(2039, 1, 1, tzinfo=dt.timezone.utc)
ROOT_SERIAL = 1000
INTERMEDIATE_SERIAL = 2000
FOREIGN_SERIAL = 3000
LEAF_SERIALS = {
"server": 4001,
"direct": 4002,
"selfsigned": 4003,
"expired": 4004,
"future": 4005,
"cnonly": 4006,
"foreign": 4007,
}
def _key() -> rsa.RSAPrivateKey:
return rsa.generate_private_key(public_exponent=65537, key_size=2048)
def _name(common: str) -> x509.Name:
return x509.Name([
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "TechBobby Test"),
x509.NameAttribute(NameOID.COMMON_NAME, common),
])
def _write(path: pathlib.Path, data: bytes) -> None:
path.write_bytes(data)
def _pem_cert(cert: x509.Certificate) -> bytes:
return cert.public_bytes(serialization.Encoding.PEM)
def _pem_key(key: rsa.RSAPrivateKey) -> bytes:
return key.private_bytes(serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption())
def _ca(name: str, serial: int, issuer: x509.Certificate | None,
issuer_key: rsa.RSAPrivateKey | None, path_length: int | None) -> tuple:
key = _key()
subject = _name(name)
builder = (x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer.subject if issuer else subject)
.public_key(key.public_key())
.serial_number(serial)
.not_valid_before(LONG_AGO)
.not_valid_after(FAR)
.add_extension(x509.BasicConstraints(ca=True, path_length=path_length),
critical=True)
.add_extension(x509.KeyUsage(
digital_signature=True, content_commitment=False, key_encipherment=False,
data_encipherment=False, key_agreement=False, key_cert_sign=True,
crl_sign=True, encipher_only=False, decipher_only=False), critical=True)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
critical=False))
if issuer is not None:
builder = builder.add_extension(
x509.AuthorityKeyIdentifier.from_issuer_public_key(issuer.public_key()),
critical=False)
cert = builder.sign(issuer_key or key, hashes.SHA256())
return key, cert
def _leaf(name: str, serial: int, issuer: x509.Certificate, issuer_key: rsa.RSAPrivateKey,
sans: list[x509.GeneralName] | None, not_before: dt.datetime = EPOCH,
not_after: dt.datetime = FAR) -> tuple:
key = _key()
builder = (x509.CertificateBuilder()
.subject_name(_name(name))
.issuer_name(issuer.subject)
.public_key(key.public_key())
.serial_number(serial)
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.KeyUsage(
digital_signature=True, content_commitment=False, key_encipherment=True,
data_encipherment=False, key_agreement=False, key_cert_sign=False,
crl_sign=False, encipher_only=False, decipher_only=False), critical=True)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]),
critical=False)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(
issuer.public_key()), critical=False))
if sans is not None:
builder = builder.add_extension(x509.SubjectAlternativeName(sans), critical=False)
cert = builder.sign(issuer_key, hashes.SHA256())
return key, cert
def build(force: bool = False) -> pathlib.Path:
"""Write the PKI once and return the directory that holds it."""
marker = CERTS / "root.pem"
if marker.exists() and not force:
return CERTS
CERTS.mkdir(parents=True, exist_ok=True)
root_key, root = _ca("TechBobby Test Root CA", ROOT_SERIAL, None, None, None)
inter_key, inter = _ca("TechBobby Test Intermediate CA", INTERMEDIATE_SERIAL, root,
root_key, 0)
foreign_key, foreign_root = _ca("Other Test Root CA", FOREIGN_SERIAL, None, None, None)
server_sans = [
x509.DNSName("server.test"),
x509.DNSName("*.wild.test"),
x509.IPAddress(__import__("ipaddress").ip_address("127.0.0.1")),
]
leaves = {
"server": _leaf("server.test", LEAF_SERIALS["server"], inter, inter_key, server_sans),
"direct": _leaf("direct.test", LEAF_SERIALS["direct"], root, root_key,
[x509.DNSName("direct.test")]),
"selfsigned": (None, None),
"expired": _leaf("expired.test", LEAF_SERIALS["expired"], inter, inter_key,
[x509.DNSName("expired.test")], EPOCH,
dt.datetime(2021, 1, 1, tzinfo=dt.timezone.utc)),
"future": _leaf("future.test", LEAF_SERIALS["future"], inter, inter_key,
[x509.DNSName("future.test")], FUTURE,
dt.datetime(2031, 1, 1, tzinfo=dt.timezone.utc)),
"cnonly": _leaf("cn.test", LEAF_SERIALS["cnonly"], inter, inter_key, None),
"foreign": _leaf("foreign.test", LEAF_SERIALS["foreign"], foreign_root, foreign_key,
[x509.DNSName("foreign.test")]),
}
# The self-signed leaf needs its own key before it can sign itself.
self_key, self_cert = _leaf("self.test", LEAF_SERIALS["selfsigned"], root, root_key,
[x509.DNSName("self.test")])
# Re-sign the same subject and key with itself: issuer == subject, trusted by nothing.
builder = (x509.CertificateBuilder()
.subject_name(self_cert.subject)
.issuer_name(self_cert.subject)
.public_key(self_key.public_key())
.serial_number(LEAF_SERIALS["selfsigned"])
.not_valid_before(EPOCH)
.not_valid_after(FAR)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.SubjectAlternativeName([x509.DNSName("self.test")]),
critical=False))
leaves["selfsigned"] = (self_key, builder.sign(self_key, hashes.SHA256()))
_write(CERTS / "root.pem", _pem_cert(root))
_write(CERTS / "root.key", _pem_key(root_key))
_write(CERTS / "intermediate.pem", _pem_cert(inter))
_write(CERTS / "intermediate.key", _pem_key(inter_key))
_write(CERTS / "foreign-root.pem", _pem_cert(foreign_root))
_write(CERTS / "foreign-root.key", _pem_key(foreign_key))
for label, (key, cert) in leaves.items():
_write(CERTS / f"{label}.pem", _pem_cert(cert))
if key is not None:
_write(CERTS / f"{label}.key", _pem_key(key))
inter_pem = (CERTS / "intermediate.pem").read_text()
root_pem = (CERTS / "root.pem").read_text()
leaf_pem = (CERTS / "server.pem").read_text()
_write(CERTS / "chain-leaf-inter.pem", (leaf_pem + inter_pem).encode())
for label in ("expired", "future", "cnonly"):
own = (CERTS / f"{label}.pem").read_text()
_write(CERTS / f"chain-{label}.pem", (own + inter_pem).encode())
_write(CERTS / "chain-leaf-root.pem", (leaf_pem + root_pem).encode())
_write(CERTS / "chain-inter-leaf.pem", (inter_pem + leaf_pem).encode())
_write(CERTS / "chain-leaf-inter-root.pem", (leaf_pem + inter_pem + root_pem).encode())
_write(CERTS / "chain-leaf-inter-inter.pem", (leaf_pem + inter_pem + inter_pem).encode())
direct_pem = (CERTS / "direct.pem").read_text()
_write(CERTS / "chain-direct-root.pem", (direct_pem + root_pem).encode())
foreign_pem = (CERTS / "foreign.pem").read_text()
foreign_root_pem = (CERTS / "foreign-root.pem").read_text()
_write(CERTS / "chain-foreign-root.pem", (foreign_pem + foreign_root_pem).encode())
return CERTS
if __name__ == "__main__":
print(build(force=True))
for name in sorted(p.name for p in CERTS.iterdir()):
print(name, (CERTS / name).stat().st_size)
Host, interpreter, OpenSSL and the certificate inventory. 01_conditions.py
"""Probe 01: the conditions - host, interpreter, OpenSSL, and the certificates used.
Nothing here fails; it fixes the ground the other ten probes stand on. The certificate inventory
is read from the files themselves, so a table that says "expired in 2021" is quoting the served
certificate, not the script that made it.
"""
from __future__ import annotations
import ipaddress
import pathlib
import sys
import certs
import probe
from trustpath.codes import TABLE
from cryptography import x509
def inventory(directory: pathlib.Path) -> list[dict]:
rows = []
for path in sorted(directory.glob("*.pem")):
if path.name.startswith("chain-") or "key" in path.name:
continue
data = path.read_bytes()
try:
cert = x509.load_pem_x509_certificate(data)
except ValueError:
continue
sans: list[str] = []
try:
extension = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName)
for name in extension.value:
if isinstance(name, x509.DNSName):
sans.append(name.value)
elif isinstance(name, x509.IPAddress):
sans.append(str(ipaddress.ip_address(name.value)))
except x509.ExtensionNotFound:
sans = []
rows.append({
"file": path.name,
"subject": cert.subject.rfc4514_string(),
"issuer": cert.issuer.rfc4514_string(),
"sans": sans,
"serial": cert.serial_number,
"not_before": cert.not_valid_before_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
"not_after": cert.not_valid_after_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
"key_bits": cert.public_key().key_size,
"signature": cert.signature_algorithm_oid._name,
"self_signed": cert.subject == cert.issuer,
})
return rows
def main() -> None:
directory = certs.build()
payload = {
"facts": probe.host_facts(),
"inventory": inventory(directory),
"chain_files": {path.name: len(path.read_text().split("BEGIN CERTIFICATE")) - 1
for path in sorted(directory.glob("chain-*.pem"))},
"table_codes": len(TABLE),
"served_dir": str(directory.relative_to(probe.HERE)),
}
probe.save("01_conditions.json", payload)
facts = payload["facts"]
print("python", facts["python"], "openssl", facts["openssl"], "kernel", facts["kernel"])
print("default cafile", facts["default_cafile"], "CAs", facts["default_ca_count"])
print("certifi", facts["certifi_path"], "CAs", facts["certifi_ca_count"])
for row in payload["inventory"]:
print(row["file"], row["subject"], row["not_before"], row["not_after"], row["sans"])
if __name__ == "__main__":
sys.exit(main())
One certificate property changed per arm. 02_codes.py
"""Probe 02: one certificate property at a time - the code, and the message that never says it.
Every arm trusts the same store (``certs/root.pem``) and differs only in what the server
presented or which name the client asked for. Five repeats per arm, and the table keeps the
distinct codes rather than the chosen one, so a code that flipped would show up instead of being
averaged away.
"""
from __future__ import annotations
import sys
import certs
import probe
ARMS = [
{"name": "good", "chain": "chain-leaf-inter.pem", "hostname": "server.test"},
{"name": "self_signed_leaf", "chain": "selfsigned.pem", "hostname": "self.test"},
{"name": "expired_leaf", "chain": "chain-expired.pem", "hostname": "expired.test"},
{"name": "future_leaf", "chain": "chain-future.pem", "hostname": "future.test"},
{"name": "wrong_host", "chain": "chain-leaf-inter.pem", "hostname": "other.test"},
{"name": "cn_only", "chain": "chain-cnonly.pem", "hostname": "cn.test"},
{"name": "missing_intermediate", "chain": "chain-leaf-root.pem", "hostname": "server.test"},
{"name": "untrusted_root", "chain": "chain-foreign-root.pem", "hostname": "foreign.test"},
]
def main() -> None:
certs.build()
rows = probe.repeat(ARMS, times=5, cafile="certs/root.pem")
payload = {"repeats": 5, "cafile": "certs/root.pem", "arms": rows}
probe.save("02_codes.json", payload)
for row in rows:
print(f"{row['name']:22s} code={row['code']:>3} {row['message'][:44]:44s} "
f"{row['handshake_ms']['p50']:7.2f} ms server={row['server_accepted']} "
f"{row['server_read']}")
if __name__ == "__main__":
sys.exit(main())
Store resolution measured in fresh interpreters. 03_store.py
"""Probe 03: which store a client reads, measured by moving one variable at a time.
Each arm starts a fresh interpreter, because the store a context uses is decided when the
context is created: an environment variable that changes after the first handshake changes
nothing. The child reports the code it raised, how many certificates the context loaded, and
which store this package says it read; the table cannot be right by accident.
"""
from __future__ import annotations
import json
import os
import pathlib
import subprocess
import sys
import certs
import probe
HERE = pathlib.Path(__file__).resolve().parent
CHILD = r"""
import json, os, pathlib, ssl, sys
sys.path.insert(0, {sandbox!r})
import probe
from trustpath.store import effective, resolve
spec = json.loads(os.environ["ARM_SPEC"])
if spec.get("cafile"):
os.environ.pop("SSL_CERT_FILE", None)
os.environ.pop("SSL_CERT_DIR", None)
cafile = spec.get("cafile") or None
verdict = probe.attempt(cafile=cafile)
paths = ssl.get_default_verify_paths()
context_cas = len(ssl.create_default_context(cafile=cafile).get_ca_certs())
stores = effective("ssl", env=dict(os.environ), explicit=cafile)
chosen = resolve("ssl", env=dict(os.environ), explicit=cafile)
print(json.dumps({{
"code": verdict["client"]["code"],
"message": verdict["client"]["message"],
"ca_count": context_cas,
"opened_file": paths.cafile or "",
"opened_dir": paths.capath or "",
"resolved": chosen.source if chosen is not None else "",
"resolved_cas": chosen.certificates if chosen is not None else 0,
"stores": [[row.source, row.certificates] for row in stores],
}}))
"""
def hashed_dir() -> pathlib.Path:
"""A capath directory: one file per certificate, named by OpenSSL's subject hash."""
directory = certs.CERTS / "hashed"
directory.mkdir(exist_ok=True)
root = certs.CERTS / "root.pem"
digest = subprocess.run(["openssl", "x509", "-hash", "-noout", "-in", str(root)],
capture_output=True, text=True, check=True).stdout.strip()
target = directory / f"{digest}.0"
target.write_bytes(root.read_bytes())
return directory
def empty_file() -> pathlib.Path:
path = certs.CERTS / "empty.pem"
path.write_text("")
return path
def short(path: str) -> str:
"""Name a store the way the table can print it: the system's, or the probe's own file."""
if not path:
return "none"
known = {str(certs.CERTS / "root.pem"): "root.pem", str(certs.CERTS / "empty.pem"): "empty.pem",
str(certs.CERTS / "hashed"): "hashed dir"}
if path in known:
return known[path]
if path.startswith("/usr/"):
return "system " + ("file" if "cert.pem" in path else "dir")
if path.startswith("/etc/"):
return "system " + ("file" if path.endswith(".pem") else "dir")
if path.startswith("/workspace") and "site-packages" in path:
return "certifi bundle"
return path.rsplit("/", 1)[-1]
def bundle_diff() -> dict:
"""How two bundles differ by subject, where a count comparison only shows a gap.
The system file and certifi hold 148 and 118 certificates, but the two numbers do not say
that one is the other minus 30. Reading the subjects shows the overlap, the roots that
only the system trusts and the roots that only a requests call would trust.
"""
import ssl as ssl_module
import certifi
from cryptography import x509
def parsed(path: str) -> tuple[int, set[bytes]]:
certificates = x509.load_pem_x509_certificates(pathlib.Path(path).read_bytes())
return len(certificates), {cert.subject.public_bytes() for cert in certificates}
system_path = ssl_module.get_default_verify_paths().cafile or ""
system_count, system = parsed(system_path)
certifi_count, bundle = parsed(certifi.where())
return {
"system_path": system_path,
"certifi_path": certifi.where(),
"system_certificates": system_count,
"certifi_certificates": certifi_count,
"system_subjects": len(system),
"certifi_subjects": len(bundle),
"common": len(system & bundle),
"system_only": len(system - bundle),
"certifi_only": len(bundle - system),
}
def run_arm(spec: dict) -> dict:
environment = {k: v for k, v in os.environ.items()
if k not in ("SSL_CERT_FILE", "SSL_CERT_DIR")}
environment.update(spec.get("env", {}))
environment["ARM_SPEC"] = json.dumps(spec)
result = subprocess.run(
[sys.executable, "-c", CHILD.format(sandbox=str(HERE))],
cwd=str(HERE), env=environment, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
raise SystemExit(f"child failed for {spec['name']}: {result.stderr[-400:]}")
return json.loads(result.stdout.strip().splitlines()[-1])
def main() -> None:
certs.build()
root = str(certs.CERTS / "root.pem")
hashed = str(hashed_dir())
empty = str(empty_file())
import certifi
import httpx
import requests
import urllib3
arms = [
{"name": "no_store_override", "env": {}},
{"name": "ssl_cert_file", "env": {"SSL_CERT_FILE": root}},
{"name": "ssl_cert_dir", "env": {"SSL_CERT_DIR": hashed}},
{"name": "ssl_cert_file_empty", "env": {"SSL_CERT_FILE": empty}},
{"name": "verify_argument", "cafile": root},
{"name": "certifi_as_store", "cafile": certifi.where()},
]
rows = []
for spec in arms:
outcomes = [run_arm(spec) for _ in range(3)]
first = outcomes[0]
rows.append({
"name": spec["name"],
"env": spec.get("env", {}),
"cafile": spec.get("cafile", ""),
"code": first["code"],
"codes": sorted({item["code"] for item in outcomes}),
"message": first["message"],
"resolved": first["resolved"],
"resolved_cas": first["resolved_cas"],
"stores": first["stores"],
"context_cas": first["ca_count"],
"opened_file": short(first["opened_file"]),
"opened_dir": short(first["opened_dir"]),
})
payload = {"repeats": 3, "arms": rows,
"bundle_diff": bundle_diff(),
"versions": {"httpx": httpx.__version__, "requests": requests.__version__,
"urllib3": urllib3.__version__},
"precedence_ssl": [row.source for row in
__import__("trustpath.store", fromlist=["candidates"])
.candidates("ssl", env={})],
"precedence_httpx": [row.source for row in
__import__("trustpath.store", fromlist=["candidates"])
.candidates("httpx", env={})],
"precedence_requests": [row.source for row in
__import__("trustpath.store", fromlist=["candidates"])
.candidates("requests", env={})]}
probe.save("03_store.json", payload)
for row in rows:
print(f"{row['name']:22s} code={row['code']:>3} stores={row['stores']} "
f"cas={row['context_cas']} {row['message'][:36]}")
if __name__ == "__main__":
sys.exit(main())
Ten names against one certificate, and the package’s prediction. 04_hostname.py
"""Probe 04: the names one certificate covers, decided by a handshake rather than by a reading.
The certificate has three subjectAltName entries: an exact name, a wildcard in the first label,
and one address. Nine names are asked for the same certificate, and the package's `matches` is
asked the same question, so a disagreement between the rule and OpenSSL would appear in the
result rather than in the prose.
"""
from __future__ import annotations
import sys
import certs
import probe
from trustpath.hosts import covers
HOSTS = [
"server.test",
"SERVER.TEST",
"server.test.",
"127.0.0.1",
"a.wild.test",
"a.b.wild.test",
"wild.test",
"other.test",
"localhost",
"10.0.0.1",
]
CERT_SANS = ["server.test", "*.wild.test", "127.0.0.1"]
def main() -> None:
certs.build()
arms = [{"name": host, "chain": "chain-leaf-inter.pem", "hostname": host} for host in HOSTS]
rows = probe.repeat(arms, times=5, cafile="certs/root.pem")
for row in rows:
row["predicted"] = covers(CERT_SANS, row["name"])
row["agrees"] = (row["code"] == 0) == row["predicted"]
cn_arms = [{"name": f"cn:{host}", "chain": "chain-cnonly.pem", "hostname": host}
for host in ("cn.test", "other.test", "CN.TEST")]
cn_rows = probe.repeat(cn_arms, times=5, cafile="certs/root.pem")
payload = {
"repeats": 5,
"sans": CERT_SANS,
"arms": rows,
"cn_only": cn_rows,
"disagreements": [row["name"] for row in rows if not row["agrees"]],
}
probe.save("04_hostname.json", payload)
for row in rows:
print(f"{row['name']:16s} code={row['code']:>3} predicted={str(row['predicted']):5s} "
f"agrees={row['agrees']}")
for row in cn_rows:
print(f"{row['name']:16s} code={row['code']:>3} sans=[]")
if __name__ == "__main__":
sys.exit(main())
Nine served chain shapes. 05_chain.py
"""Probe 05: what a served chain has to contain, and in what order.
Each arm sends a different list from the same key pair and the same store, so the verdict is a
property of the list and nothing else. The package's `chain.summary` reads the same files the
server sent, which lets the table put "one gap at index 0" next to the code the handshake raised.
"""
from __future__ import annotations
import sys
import certs
import probe
from trustpath.chain import summary
CHAINS = [
"chain-leaf-inter.pem",
"server.pem",
"chain-inter-leaf.pem",
"chain-leaf-root.pem",
"chain-leaf-inter-root.pem",
"chain-leaf-inter-inter.pem",
"chain-direct-root.pem",
"direct.pem",
]
def main() -> None:
directory = certs.build()
arms = [{"name": name, "chain": name,
"hostname": "direct.test" if "direct" in name else "server.test"}
for name in CHAINS]
arms.append({"name": "chain-foreign-root.pem", "chain": "chain-foreign-root.pem",
"hostname": "foreign.test"})
rows = probe.repeat(arms, times=5, cafile="certs/root.pem")
for row in rows:
row["summary"] = summary((directory / row["name"]).read_text())
payload = {"repeats": 5, "cafile": "certs/root.pem", "arms": rows}
probe.save("05_chain.json", payload)
for row in rows:
gap = row["summary"]["gaps"][0] if row["summary"]["gaps"] else None
print(f"{row['name']:26s} certs={row['summary']['count']} "
f"leaf_first={str(row['summary']['leaf_first']):5s} "
f"gap={'none' if gap is None else gap['index']} code={row['code']:>3} "
f"{row['message'][:34]}")
if __name__ == "__main__":
sys.exit(main())
Expired, not yet valid, and the control. 06_time.py
"""Probe 06: the same chain, wrong only in time.
Three arms: a certificate that expired in 2021, one that is not valid until 2030, and the good
leaf beside them as the control. The dates are read from the served files; the code comes from
the handshake. Nothing here changes the client's clock, so what is measured is which side's time
the check uses - the client's, since the server is the same in all three arms.
"""
from __future__ import annotations
import datetime as dt
import sys
import certs
import probe
from cryptography import x509
ARMS = [
{"name": "good", "chain": "chain-leaf-inter.pem", "hostname": "server.test"},
{"name": "expired", "chain": "chain-expired.pem", "hostname": "expired.test"},
{"name": "not_yet_valid", "chain": "chain-future.pem", "hostname": "future.test"},
{"name": "expired_without_issuer", "chain": "expired.pem", "hostname": "expired.test"},
]
FILES = {"good": "server.pem", "expired": "expired.pem", "not_yet_valid": "future.pem",
"expired_without_issuer": "expired.pem"}
def window(path) -> dict:
cert = x509.load_pem_x509_certificate(path.read_bytes())
now = dt.datetime.now(dt.timezone.utc)
return {
"not_before": cert.not_valid_before_utc.strftime("%Y-%m-%d"),
"not_after": cert.not_valid_after_utc.strftime("%Y-%m-%d"),
"days_since_expiry": (now - cert.not_valid_after_utc).days,
"days_until_start": (cert.not_valid_before_utc - now).days,
}
def main() -> None:
directory = certs.build()
rows = probe.repeat(ARMS, times=5, cafile="certs/root.pem")
for row in rows:
row["window"] = window(directory / FILES[row["name"]])
payload = {
"repeats": 5,
"today": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d"),
"arms": rows,
}
probe.save("06_time.json", payload)
for row in rows:
print(f"{row['name']:14s} code={row['code']:>3} {row['message'][:34]:34s} "
f"{row['window']['not_before']}..{row['window']['not_after']} "
f"server={row['server_read']}")
if __name__ == "__main__":
sys.exit(main())
What the server logs for each client cause. 07_server.py
"""Probe 07: what the server records, for each thing the client refused.
A client that fails verification sends an alert, and the alert name is what lands in the server's
log. Seven client-side causes are run against a server that logs the alert it received, which is
the whole reason a server-side log cannot tell an operator which of the seven happened.
"""
from __future__ import annotations
import sys
import certs
import probe
ARMS = [
{"name": "self_signed", "chain": "selfsigned.pem", "hostname": "self.test"},
{"name": "missing_issuer", "chain": "server.pem", "hostname": "server.test"},
{"name": "untrusted_root", "chain": "chain-foreign-root.pem", "hostname": "foreign.test"},
{"name": "expired", "chain": "chain-expired.pem", "hostname": "expired.test"},
{"name": "not_yet_valid", "chain": "chain-future.pem", "hostname": "future.test"},
{"name": "name_mismatch", "chain": "chain-leaf-inter.pem", "hostname": "other.test"},
{"name": "address_mismatch", "chain": "chain-leaf-inter.pem", "hostname": "10.0.0.1"},
]
def main() -> None:
certs.build()
rows = probe.repeat(ARMS, times=5, cafile="certs/root.pem")
alerts: dict[str, set[str]] = {}
for row in rows:
for run in row["runs"]:
alerts.setdefault(str(run["server"]["read"]), set()).add(str(row["code"]))
payload = {
"repeats": 5,
"arms": rows,
"alert_to_codes": {alert: sorted(codes) for alert, codes in sorted(alerts.items())},
"distinct_alerts": len(alerts),
"distinct_codes": len({row["code"] for row in rows}),
}
probe.save("07_server.json", payload)
for row in rows:
print(f"{row['name']:18s} client={row['code']:>3} server={row['server_accepted']} "
f"{row['server_read']}")
print("alerts:", payload["alert_to_codes"])
if __name__ == "__main__":
sys.exit(main())
Four clients and the depth at which the code survives. 08_clients.py
"""Probe 08: the same failure through four clients, and whether the code survives the wrapper.
Each client connects to the same local HTTPS server with the same store choices, and the probe
records what the caller actually catches: the exception type, where in the wrapper chain a
``verify_code`` can still be found, and whether the client honours ``SSL_CERT_FILE`` at all.
That last column is the difference between a fix that works and one that appears to.
"""
from __future__ import annotations
import http.client
import os
import ssl
import sys
import urllib.error
import urllib.request
import certs
import probe
ROOT = str(probe.CERTS / "root.pem")
REPEATS = 3
def plain(exc: BaseException) -> dict:
found = probe.walk_for_code(exc)
return {
"ok": False,
"type": type(exc).__name__,
"message": str(exc)[:110].replace("\n", " "),
"code": found["code"],
"depth": found["depth"],
"chain": found["chain"][:4],
}
def under(env: dict[str, str], call) -> dict:
"""Run one call with variables applied and removed again."""
saved = {key: os.environ.get(key) for key in env}
try:
for key in ("SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):
os.environ.pop(key, None)
os.environ.update(env)
return call()
finally:
for key, value in saved.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def http_client(url: str, cafile: str | None) -> dict:
host, port = "127.0.0.1", int(url.rsplit(":", 1)[1].split("/")[0])
context = ssl.create_default_context(cafile=cafile)
try:
conn = http.client.HTTPSConnection(host, port, context=context, timeout=5)
conn.request("GET", "/")
response = conn.getresponse()
response.read()
conn.close()
return {"ok": True, "type": "", "message": "", "code": None, "depth": None, "chain": []}
except Exception as exc: # noqa: BLE001 - the point is which type arrives
return plain(exc)
def urlopen_arm(url: str, cafile: str | None) -> dict:
try:
context = ssl.create_default_context(cafile=cafile)
with urllib.request.urlopen(url, context=context, timeout=5) as response:
response.read()
return {"ok": True, "type": "", "message": "", "code": None, "depth": None, "chain": []}
except Exception as exc: # noqa: BLE001
return plain(exc)
def requests_arm(url: str, verify) -> dict:
import requests
try:
response = requests.get(url, verify=verify, timeout=5)
response.close()
return {"ok": True, "type": "", "message": "", "code": None, "depth": None, "chain": []}
except Exception as exc: # noqa: BLE001
return plain(exc)
def httpx_arm(url: str, verify) -> dict:
import httpx
try:
response = httpx.get(url, verify=verify, timeout=5)
response.close()
return {"ok": True, "type": "", "message": "", "code": None, "depth": None, "chain": []}
except Exception as exc: # noqa: BLE001
return plain(exc)
def main() -> None:
certs.build()
summary: dict[str, dict] = {}
with probe.HttpsServer("chain-leaf-inter.pem") as server:
url = server.url
arms = {
"http.client_default": lambda: http_client(url, None),
"http.client_root": lambda: http_client(url, ROOT),
"urllib_default": lambda: urlopen_arm(url, None),
"urllib_root": lambda: urlopen_arm(url, ROOT),
"requests_default": lambda: requests_arm(url, True),
"requests_verify_root": lambda: requests_arm(url, ROOT),
"requests_bundle_env": lambda: under({"REQUESTS_CA_BUNDLE": ROOT},
lambda: requests_arm(url, True)),
"requests_ssl_cert_file_env": lambda: under({"SSL_CERT_FILE": ROOT},
lambda: requests_arm(url, True)),
"httpx_default": lambda: httpx_arm(url, True),
"httpx_verify_root": lambda: httpx_arm(url, ROOT),
"httpx_ssl_cert_file_env": lambda: under({"SSL_CERT_FILE": ROOT},
lambda: httpx_arm(url, True)),
}
for name, call in arms.items():
outcomes = [under({}, call) for _ in range(REPEATS)]
first = outcomes[0]
summary[name] = {
**first,
"ok_all": [item["ok"] for item in outcomes],
"codes": sorted({item["code"] for item in outcomes if item["code"] is not None}),
"survives": first["code"] is not None,
}
print(f"{name:30s} ok={str(first['ok']):5s} {first['type']:24s} "
f"code={first['code']} depth={first['depth']}")
arms_out = [{"name": name, **row} for name, row in summary.items()]
payload = {"repeats": REPEATS, "root": "certs/root.pem", "arms": arms_out}
probe.save("08_clients.json", payload)
print("codes preserved in", sum(1 for row in summary.values() if row["survives"]),
"of", len(summary))
if __name__ == "__main__":
sys.exit(main())
The package’s own counts, read from the tree and from pytest. 09_tests.py
"""Probe 09: the package's own numbers, counted from the tree and from pytest.
The article prints how many tests pass, how many files and lines the package and the probes
have. All of it is read here, once, so a number in the prose cannot disagree with the tree.
"""
from __future__ import annotations
import pathlib
import subprocess
import sys
import probe
HERE = pathlib.Path(__file__).resolve().parent
PACKAGE = probe.HERE / "module" / "trustpath"
TESTS = PACKAGE / "tests"
def lines(paths: list[pathlib.Path]) -> int:
return sum(len(path.read_text(encoding="utf-8").splitlines()) for path in paths)
def main() -> None:
result = subprocess.run(
[sys.executable, "-m", "pytest", "trustpath/tests", "-q", "-p", "no:warnings"],
cwd=str(probe.HERE / "module"), capture_output=True, text=True)
tail = result.stdout.strip().splitlines()[-1]
passed = int(tail.split()[0]) if tail[:1].isdigit() else 0
package = sorted(path for path in PACKAGE.glob("*.py"))
tests = sorted(path for path in TESTS.glob("*.py"))
probes = sorted(path for path in HERE.glob("[0-9][0-9]_*.py"))
payload = {
"pytest_rc": result.returncode,
"pytest_tail": tail,
"pytest_passed": passed,
"test_files": len(tests),
"test_lines": lines(tests),
"package_files": len(package),
"package_lines": lines(package),
"probe_files": len(probes),
"probe_lines": lines(probes) + len(pathlib.Path(probe.__file__).read_text().splitlines()),
"package_names": [path.name for path in package],
"test_names": [path.name for path in tests],
}
probe.save("09_tests.json", payload)
print(tail, "| package", len(package), "files", lines(package), "lines | tests",
len(tests), "files", lines(tests), "lines | probes", len(probes))
if result.returncode != 0:
raise SystemExit("pytest failed")
if __name__ == "__main__":
sys.exit(main())
The price of the check, measured against the same handshake without it. 10_cost.py
"""Probe 10: what verification costs, measured against the same handshake with it switched off.
Two arms, one variable: the client either checks the chain and the name or accepts anything. The
difference is the price of the check on this host, which is the figure a retry policy is argued
against - and the reason a verification failure should not be turned into three retries.
"""
from __future__ import annotations
import sys
import certs
import probe
REPEATS = 5
PER_RUN = 20
def main() -> None:
certs.build()
arms = []
for name, verify in (("verified", True), ("unverified", False)):
runs = []
for _ in range(REPEATS):
samples = []
for _ in range(PER_RUN):
verdict = probe.attempt(chain="chain-leaf-inter.pem", hostname="server.test",
cafile="certs/root.pem" if verify else None,
verify=verify)
samples.append(verdict["handshake_ms"])
runs.append({
"p50": probe.percentiles(samples)["p50"],
"p90": probe.percentiles(samples)["p90"],
"min": min(samples),
"max": max(samples),
})
medians = [run["p50"] for run in runs]
arms.append({
"name": name,
"verify": verify,
"per_run": PER_RUN,
"runs": runs,
"p50": probe.percentiles(medians)["p50"],
"min": min(medians),
"max": max(medians),
})
print(name, "median of medians", round(arms[-1]["p50"], 3), "ms", medians)
payload = {"repeats": REPEATS, "per_run": PER_RUN,
"delta_ms": arms[0]["p50"] - arms[1]["p50"], "arms": arms}
probe.save("10_cost.json", payload)
print("delta", round(payload["delta_ms"], 3), "ms")
if __name__ == "__main__":
sys.exit(main())
Every observed code asked of the classifier. 11_policy.py
"""Probe 11: does the package classify everything the probes actually raised?
Reads the recorded results, collects every distinct code, and asks `classify` about each one. The
count of unmapped codes is the honest measure of whether the table is a runbook or a guess.
"""
from __future__ import annotations
import json
import sys
import probe
from trustpath.codes import Kind, classify, retry_budget
SOURCES = ("02_codes.json", "04_hostname.json", "05_chain.json", "06_time.json",
"07_server.json", "08_clients.json")
def codes_from(payload: dict) -> set[int]:
found: set[int] = set()
arms = payload.get("arms", [])
rows = arms.values() if isinstance(arms, dict) else arms
for row in rows:
if "code" in row and row["code"] is not None:
found.add(int(row["code"]))
if "codes" in row:
found.update(int(code) for code in row["codes"])
for run in row.get("runs", []):
found.add(int(run["client"]["code"]))
for row in payload.get("cn_only", []):
found.add(int(row["code"]))
return {code for code in found if code > 0}
def main() -> None:
observed: dict[str, set[int]] = {}
for name in SOURCES:
path = probe.RESULTS / name
if path.exists():
observed[name] = codes_from(json.loads(path.read_text(encoding="utf-8")))
every = sorted(set().union(*observed.values()))
rows = []
for code in every:
fault = classify(code)
rows.append({
"code": code,
"kind": fault.kind.value,
"short": fault.short,
"retryable": fault.retryable,
"retry_budget": retry_budget(fault),
})
unmapped = [row["code"] for row in rows if row["kind"] == Kind.OTHER.value]
payload = {
"per_file": {name: sorted(codes) for name, codes in observed.items()},
"codes": rows,
"distinct": len(every),
"kinds": sorted({row["kind"] for row in rows}),
"unmapped": unmapped,
"retryable_total": sum(1 for row in rows if row["retryable"]),
}
probe.save("11_policy.json", payload)
print("distinct codes", len(every), "kinds", payload["kinds"], "unmapped", unmapped,
"retryable", payload["retryable_total"])
if __name__ == "__main__":
sys.exit(main())
One store question asked of four httpx releases on the same server. 12_httpx.py
"""Probe 12: does httpx read SSL_CERT_FILE, and does the answer depend on the release?
The article's FAQ says how a client resolves a store, and a version claim is the part of that
which ages. This probe runs the same three calls - no variable, the variable, and ``verify=`` -
through whatever httpx is installed, so a second interpreter with an older release answers the
question with the same server and the same certificate instead of with a changelog.
Each interpreter writes ``scratch/httpx_<version>.json``; ``--merge`` collects them into
``results/12_httpx.json``, one row per release, so the page can quote four measured versions
rather than a remembered change.
"""
from __future__ import annotations
import json
import os
import pathlib
import sys
import probe
HERE = pathlib.Path(__file__).resolve().parent
SCRATCH = HERE.parent / "scratch"
RESULTS = HERE.parent / "results"
REPEATS = 3
def under(env: dict[str, str], call):
"""Run one call with only the named variables set, and restore the environment after."""
saved = {key: os.environ.get(key) for key in env}
try:
for key in ("SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):
os.environ.pop(key, None)
os.environ.update(env)
return call()
finally:
for key, value in saved.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def arm(url: str, verify) -> dict:
import httpx
try:
response = httpx.get(url, verify=verify, timeout=5)
response.close()
return {"ok": True, "type": "", "message": "", "code": None, "depth": None}
except Exception as exc: # noqa: BLE001 - the point is which type and code arrive
found = probe.walk_for_code(exc)
return {"ok": False, "type": type(exc).__name__, "message": str(exc)[:110],
"code": found["code"], "depth": found["depth"]}
def run() -> dict:
import httpx
root = str(probe.CERTS / "root.pem")
hashed = str(probe.CERTS / "hashed")
arms = {
"default": lambda: under({}, lambda: arm(url, True)),
"ssl_cert_file": lambda: under({"SSL_CERT_FILE": root}, lambda: arm(url, True)),
"ssl_cert_dir": lambda: under({"SSL_CERT_DIR": hashed}, lambda: arm(url, True)),
"verify_root": lambda: arm(url, root),
}
rows = []
with probe.HttpsServer("chain-leaf-inter.pem") as server:
url = server.url
for name, call in arms.items():
outcomes = [call() for _ in range(REPEATS)]
first = outcomes[0]
rows.append({
"name": name,
"ok": first["ok"],
"ok_all": [item["ok"] for item in outcomes],
"type": first["type"],
"code": first["code"],
"depth": first["depth"],
"message": first["message"],
})
print(f" {name:16s} ok={str(first['ok']):5s} {first['type']:20s} "
f"code={first['code']} depth={first['depth']}")
return {"version": httpx.__version__, "python": sys.version.split()[0],
"repeats": REPEATS, "root": "certs/root.pem", "arms": rows}
def merge() -> None:
rows = []
for path in sorted(SCRATCH.glob("httpx_*.json")):
payload = json.loads(path.read_text(encoding="utf-8"))
if "version" in payload:
rows.append(payload)
rows.sort(key=lambda row: tuple(int(part) for part in row["version"].split(".")))
RESULTS.mkdir(exist_ok=True)
(RESULTS / "12_httpx.json").write_text(
json.dumps({"releases": rows}, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
print("merged", len(rows), "releases:",
", ".join(row["version"] for row in rows))
def main() -> None:
if "--merge" in sys.argv:
merge()
return
payload = run()
SCRATCH.mkdir(exist_ok=True)
out = SCRATCH / f"httpx_{payload['version']}.json"
out.write_text(json.dumps(payload, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
print("httpx", payload["version"], "written", out)
if __name__ == "__main__":
main()
