# 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.

Original: https://fdetimes.net/en/guides/practice-mtls-on-your-laptop/

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:

```bash
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`:

```bash
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`:

```python
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.

```python
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`:

```python
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.

**Key point:** When a client hands over a password-protected key, switch libraries instead of stripping the password from the key.

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.

**Try this week:**

- Complete the lab: CA, server.py, the Requests client, the HTTPX client, then trigger the three errors on purpose and record the messages you see
- Run openssl verify -purpose sslclient -x509_strict on a real client certificate you have, and see whether it passes
- Write a one-page mTLS checklist (which CA signed it, expiry, EKU, whether the key is encrypted) to send the client before the integration session

## Sources

- [Advanced Usage - Requests documentation](https://requests.readthedocs.io/en/latest/user/advanced/)

- [ssl — TLS/SSL wrapper for socket objects](https://docs.python.org/3/library/ssl.html)

- [openssl-verification-options - OpenSSL Documentation](https://docs.openssl.org/master/man1/openssl-verification-options/)

- [openssl-x509 - OpenSSL Documentation](https://docs.openssl.org/master/man1/openssl-x509/)

- [SSL - HTTPX](https://www.python-httpx.org/advanced/ssl/)

- [HTTPX CHANGELOG.md](https://raw.githubusercontent.com/encode/httpx/master/CHANGELOG.md)

- [SSL_connect() returns success for revoked cert in 1.1.1 · Issue #8500 · openssl/openssl](https://github.com/openssl/openssl/issues/8500)

- [RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3](https://www.rfc-editor.org/rfc/rfc8446.html)

- [Using mTLS to Access Mastercard APIs - Mastercard Developers](https://developer.mastercard.com/platform/documentation/authentication/using-mtls-to-access-mastercard-apis/)
