back

loading SSL certs and keys from memory for httpx

the problem

If you store your keys and certificates in a unified config file that’s loaded into your Python app on start, like we do at work, then you’ll face some trouble creating ssl contexts for your httpx clients.

The heart of the problem is you can’t load certificates and keys from in memory strings when creating SSL contexts – you have to pass file paths to be read from.

And while httpx has a workaround, in so far as a way to load certificates and keys from the environment through SSL_CERT_FILE and SSL_CERT_DIR, it doesn’t really solve our problem; we would have to break apart our application config.

a solution

Credit where credit is due, Andreas Pelme pointed to this solution in the github issue.

The idea is to use tempfile.NamedTemporaryFile, to securely create a temporary file-like object that will be destroyed as soon as it’s closed.

If you had a certificate and api key as strings stored in api_cert and api_key variables respectively. Then implementing this solution would look something like:

import ssl
import httpx

from tempfile import NamedTemporaryFile

with (
        NamedTemporaryFile(mode='w+', delete_on_close=False) as cert_file,
        NamedTemporaryFile(mode='w+', delete_on_close=False) as key_file,
):
    cert_file.write(api_cert)
    cert_file.close()
    key_file.write(api+key)
    key_file.close()

    ctx = ssl.create_default_context()
    ctx.load_cert_chain(certfile=cert_filen.name, keyfile=key_file.name)

client = httpx.Client(verify=ctx)

Setting delete_on_close to False ensures the file is deleted on context manager exit only.

It’s not as elegant as just passing strings to the certfile and keyfile arguments would be. But it gets the job done.

mail@jonahv.com