FDE Times dataFDE jobs open 922▼2 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 64Companies hiring 201Remote-friendly 23%Median US pay $202kTop hirer Databricks 113
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Practice mTLS on your laptop before a client's API rejects you

A self-signed CA, a small Python server and a handful of errors worth triggering on purpose, so the real ones at a client site read like old friends.

ShareLinkedInFacebookX

In brief

  • Requests takes the client certificate through cert, while verify only checks the server's certificate; the two are often confused.
  • Requests does not accept an encrypted private key. If the client hands over a password-protected key, use SSLContext.load_cert_chain(password=...) with HTTPX.
  • In TLS 1.3, a missing client certificate error can surface only after the handshake has reported success, so do not log only at the connection step.
Decision tree for three mTLS faults. The root question: which message do you see? An SSLError when loading the key means the key does not match the certificate, so ask the customer again for the correct file pair. A certificate_required alert means the client sent no certificate, so add one rather than turning off verification. A certificate chain error means the CA lacks keyUsage, so reissue the CA with keyUsage. This branch is highlighted because it is new since Python 3.13.
Each fault has its own message, which shows which file to fix. The missing keyUsage error on a CA is new: since Python 3.13, create_default_context() enables strict mode by default.

Mastercard’s developer documentation states that its mTLS APIs require the client and Mastercard’s servers to exchange TLS certificates in both directions. Your client has to prove who it is at the TLS layer, before the first HTTP request is even read.

For an FDE, this tends to arrive at the worst possible moment: the client sends a certificate file and a key file and expects the integration to work the same day. TLS errors, meanwhile, are notoriously hard to read. The fastest way to learn is to build both sides on your laptop, then break each piece by hand.

You will build a self-signed CA, a Python server that only accepts clients with a certificate, and two clients written with Requests and HTTPX. You need Python 3 (ideally with 3.13 installed as well for the final step), OpenSSL 3.x, and pip install requests httpx.

Step 1: a small CA and two certificates

The commands below are a condensed lab version, not a production PKI process. Syntax can vary slightly between OpenSSL versions, so check them against the man pages for the version you have. First, create the CA:

openssl req -x509 -newkey rsa:2048 -nodes \
  -keyout ca.key -out ca.crt -days 7 -subj "/CN=Lab CA" \
  -addext "basicConstraints=critical,CA:TRUE" \
  -addext "keyUsage=critical,keyCertSign,cRLSign"

Do not drop the keyUsage line. In strict checking mode (-x509_strict), OpenSSL requires a CA certificate to declare the keyUsage extension explicitly. The OpenSSL documentation also lists requirements for authorityKeyIdentifier and subjectKeyIdentifier. Step 5 shows how much this detail matters on newer Python.

Next come two extension files. The server certificate needs the name localhost, and the client certificate needs clientAuth:

printf "subjectAltName=DNS:localhost,IP:127.0.0.1\nextendedKeyUsage=serverAuth\n" > server.ext
printf "extendedKeyUsage=clientAuth\n" > client.ext

for n in server client; do
  openssl req -newkey rsa:2048 -nodes -keyout $n.key -out $n.csr -subj "/CN=$n"
  openssl x509 -req -in $n.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
    -out $n.crt -days 7 -extfile $n.ext
done

Check: run openssl verify -CAfile ca.crt -purpose sslclient -x509_strict client.crt. When verifying for the sslclient purpose, if the certificate carries Extended Key Usage, that extension must permit clientAuth. Try changing client.ext to serverAuth, reissue, and run the command again to watch it fail.

Step 2: a Python server that requires a client certificate

Python’s ssl module is enough to build an mTLS server. Setting verify_mode = CERT_REQUIRED on the server-side socket forces the server to authenticate the client’s certificate. The server also needs to know which CA to trust, and that CA is loaded through load_verify_locations(). Save the following as server.py:

import http.server, ssl

class Hello(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"ok\n")

ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain("server.crt", "server.key")
ctx.load_verify_locations("ca.crt")
ctx.verify_mode = ssl.CERT_REQUIRED

httpd = http.server.HTTPServer(("127.0.0.1", 8443), Hello)
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()

This is a minimal server, for practice only. Run python server.py in a separate terminal and leave it running.

Step 3: calling with Requests, without confusing cert and verify

Requests uses two parameters for two different jobs. cert is your certificate, sent to the server. verify, which defaults to True and can point to a CA bundle file, is used only to check the server’s certificate.

import requests

r = requests.get(
    "https://localhost:8443/",
    cert=("client.crt", "client.key"),  # who you are
    verify="ca.crt",                    # which server you trust
)
print(r.status_code, r.text)

Check: you should get 200 ok. Requests also accepts cert as a single file containing both the private key and the certificate. Try cat client.crt client.key > client.pem and pass cert="client.pem"; the result should be identical.

At client sites, these two parameters get mixed up in a familiar way. The server reports a certificate error, someone turns verify off to make it work, and the error persists. The reason is that verify has nothing to do with the client certificate.

Step 4: HTTPX the current way, and password-protected keys

Since version 0.28.0, released on November 28, 2024, HTTPX marks the cert parameter as deprecated and emits a warning. Passing verify as a string is deprecated too. The approach the HTTPX documentation recommends is to build your own SSLContext, load the client certificate into it with load_cert_chain(), and pass the context through verify:

import ssl, httpx

ctx = ssl.create_default_context(cafile="ca.crt")
ctx.load_cert_chain(certfile="client.crt", keyfile="client.key")
# password-protected key: load_cert_chain(..., password="...")

with httpx.Client(verify=ctx) as client:
    print(client.get("https://localhost:8443/").text)

The password comment above is why you may have to switch libraries. Requests does not support encrypted private keys, so a key passed through cert must be unencrypted. Python’s load_cert_chain(), by contrast, has a password parameter.

Faced with a password-protected key, many engineers remove the password so Requests will work, and leave the bare key file sitting on disk. Going through SSLContext avoids that, and makes the conversation with the client’s security team far easier.

Step 5: break three things on purpose

A key that does not match the certificate. In the HTTPX client, change keyfile to server.key. load_cert_chain() raises SSLError because the private key does not match the certificate, and the failure happens locally, before any network connection is opened. If you see this at a client site, someone almost certainly sent the wrong pair of files.

No certificate sent. Remove cert from the Requests call. The server has set CERT_REQUIRED, so the request cannot return 200 ok. In TLS 1.3 the refusal has its own name: the certificate_required alert, reserved for when the server wants a client certificate and the client sends none. Look for that name in the error message and copy down the exact text you see.

What confuses people is when the error appears. Matt Caswell, a member of the OpenSSL project, has explained that in TLS 1.3 the client side may already have reported a successful handshake before the server verifies the client certificate, so the rejection arrives later. Log at the response-reading step as well, not only at the connection step.

A CA without keyUsage on Python 3.13. Copy the current set of files to another directory to keep a working version. Then recreate the CA without the keyUsage line, rerun the loop from Step 1 to reissue both the server and client certificates from the new CA, restart server.py, and run the HTTPX client under Python 3.13. Reissuing both leaves the CA as the only variable, with no extra error from a client signed by the old CA.

Since 3.13, create_default_context() enables VERIFY_X509_PARTIAL_CHAIN and VERIFY_X509_STRICT by default, and OpenSSL’s strict mode requires the CA to declare keyUsage. The client will reject the server’s certificate as soon as it checks the chain, so the request never reaches server.py.

To confirm the CA is the cause, run openssl verify -CAfile ca.crt -x509_strict server.crt: it should fail too. The practical lesson is that an internal CA that has worked for years can start being rejected simply because you upgraded Python, since the strict flag can reject certificates that predate RFC 5280 or are malformed.

At the client site, certificates are harder than code

Before writing a line of Python, run openssl verify -purpose sslclient -x509_strict on the certificate the client gives you. Ask three questions up front: which CA signed it, whether the key is encrypted, and when the certificate expires.

The expiry question sounds redundant, but openssl x509 issues certificates valid for 30 days by default if -days is not specified. A certificate issued in a hurry for a test environment can break the integration on its own exactly a month after go-live. Record the expiry date in the handover runbook.

On the career side, when an FDE job posting mentions mTLS, client certificates or PKI, this lab is worth putting on your record. On your CV, do not just write “knows TLS”.

Say specifically that you integrated an mTLS API, how you handled encrypted keys and how you diagnosed certificate chain errors. This lab repo, with notes on the errors you triggered on purpose, is short evidence an interviewer can read in five minutes.

The next time a client sends you two files and says “it should just work,” you will know which file to check first.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
9 sources
Read next on the roadmap · Stage 2: Broad engineeringYour pandas mean says 38.33. The plant historian says 31.38Historians usually store a value only when it changes enough, so each row covers a different stretch of time, and weighting every row equally gives the wrong report.