OnFinality
New RPC users get 35% off their first monthView the offer
OnFinality Learn
Troubleshooting9 min read

Python HTTPS Certificates: Verify Servers and Fix TLS Errors

Find the cause of Python HTTPS certificate errors, configure trust for private endpoints, and confirm that verification still rejects invalid certificates.

TL;DR

Python HTTPS clients verify the server certificate by default when you use Requests or the standard library's default HTTPS configuration. To fix a certificate error, identify whether the client lacks the right CA, the server sends an incomplete chain, or the certificate does not match the URL hostname. For private endpoints, configure trust with a CA certificate obtained through an approved channel instead of disabling verification. This guide shows how to test from the Python runtime that fails, configure trust, and confirm that invalid certificates are still rejected.

The first check for a Python HTTPS certificate error

Keep verification enabled and reproduce the failure from the same Python environment as the application. A browser succeeding on your laptop does not prove a container or CI runner will succeed: the two may use different trust stores, proxies, or network routes. For a public endpoint, start with the client's default trust settings. For an internal service, find out which certificate authority (CA) is supposed to issue its certificate before changing anything.

The examples assume Python 3, an HTTPS URL you are authorized to test, and, for the Requests examples, requests installed in the same virtual environment or container as your application. Set RPC_URL to the endpoint under test and use an approved URL without credentials for the initial probe. The OpenSSL check also requires the openssl CLI. If you're setting up a new RPC integration, use the API service overview and network directory to find the intended endpoint; test the hostname the application actually uses, not just the host that resolves behind it.

The certificate chain, hostname, and trust store

During TLS, the server presents its leaf certificate and typically the intermediate certificates needed to link that leaf to a trusted root. The client builds and validates a chain against its own trust store, checks certificate validity periods, and checks that the URL hostname matches the certificate identity. Issue DNS certificates with the DNS name in the Subject Alternative Name (SAN). If the URL uses an IP address, it needs a matching IP SAN; a DNS name that resolves to that address is not enough.

verify in Requests controls how the client verifies the server. cert supplies the client's certificate and private key when a server requires mutual TLS (mTLS). A CA bundle is a PEM file containing trusted certificates, not private keys. Adding a CA can resolve a missing trust anchor, but it cannot make a certificate valid for the wrong host or extend an expired certificate.

A baseline probe in the failing Python runtime

Run this inside the application container, CI runner, or virtual environment. It uses Requests' normal configuration, including applicable environment settings, and stops at the first HTTP response instead of following a redirect to another hostname. It does not print the URL or send an RPC payload.

An HTTP status means TLS verification succeeded for that connection. A 401 can still mean credentials are missing, and a 405 can mean the endpoint expects POST; neither status is a certificate failure. If the probe fails, keep the full exception in local diagnostics after redacting secrets. The exit labels below are intentionally broad: a Requests SSLError is not always a certificate verification error.

import os
import ssl
import sys

import requests

print('Python:', sys.version.split()[0])
print('TLS library:', ssl.OPENSSL_VERSION)
print('Requests:', requests.__version__)
print('Requests default CA file:', requests.certs.where())
for name in ('REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'HTTPS_PROXY',
             'https_proxy', 'NO_PROXY', 'no_proxy'):
    print(f'{name} set:', bool(os.getenv(name)))

try:
    with requests.get(os.environ['RPC_URL'], timeout=(5, 10),
                      allow_redirects=False, stream=True) as response:
        print('HTTP status:', response.status_code)
except requests.exceptions.SSLError:
    raise SystemExit('TLS failed: inspect the original exception in local application logs.')
except requests.exceptions.RequestException as exc:
    raise SystemExit(f'Request failed: {type(exc).__name__}')

The chain presented by the server

Set RPC_HOST to the DNS hostname from RPC_URL, without the scheme, path, or port. The command below assumes port 443. -servername sends Server Name Indication (SNI), which lets a shared TLS listener select the certificate for that hostname. -verify_hostname checks the name, and -verify_return_error makes certificate verification errors fatal.

Compare the presented chain with what the server operator expects. -showcerts displays the certificates the server sent, not a verified chain reconstructed by the client. This command uses OpenSSL's configured trust by default and opens a direct connection; it does not reproduce Requests' CA bundle or automatically follow its proxy settings. For a direct comparison, run it from the same environment and add -CAfile "$CA_BUNDLE" with the intended trust file. Use the output as diagnostic evidence, not as a source of certificates to trust.

openssl s_client -connect "${RPC_HOST}:443" -servername "$RPC_HOST" -verify_hostname "$RPC_HOST" -verify_return_error -showcerts </dev/null

Private CA trust in Requests

For a private service, ask its operator for the approved CA certificate or bundle through a trusted channel and confirm its fingerprint against a separately authenticated source. Prefer a private CA that signs the service certificate; the service can then renew its leaf without redistributing trust to every client. For a controlled development service that uses a self-signed leaf, you can try trusting that specific certificate if your runtime accepts it as a trust anchor. It still needs the correct hostname and valid dates, and replacing it may require updating every client's trust file.

Pass the CA bundle path as verify to scope the change to this call. An explicit Requests bundle replaces the default trust list for that call. If the same configuration must also reach public HTTPS services, use a maintained bundle containing both the required public roots and the approved private CA, or keep separate configurations for public and private traffic.

When changing code is impractical, REQUESTS_CA_BUNDLE sets the bundle for normal Requests calls that use environment settings; Requests falls back to CURL_CA_BUNDLE when the former is unset. If you manually prepare and send requests, use Session.merge_environment_settings before sending when you want those overrides applied. Check the Requests certificate verification documentation for the prepared-request workflow.

import os
import requests

with requests.get(os.environ['RPC_URL'], verify=os.environ['CA_BUNDLE'],
                  timeout=(5, 10), allow_redirects=False, stream=True) as response:
    print('Verified HTTP status:', response.status_code)

Standard-library trust and mutual TLS

With urllib.request, pass an ssl.SSLContext to urlopen. Calling ssl.create_default_context() first and then load_verify_locations() adds the private CA to that context's default trust, rather than replacing it. Requests normally uses its packaged CA bundle from certifi, though downstream distributions can change the default. Installing a CA in the operating system therefore does not guarantee that your Requests process will pick it up.

For mTLS, add client credentials only when the server requires them. Use context.load_cert_chain(client_cert_path, client_key_path) with ssl, or cert=(client_cert_path, client_key_path) in Requests while keeping verify configured separately. The client private key is a secret; never place it in the trust bundle or diagnostic logs. A server rejecting a client certificate is a different problem from Python rejecting the server certificate.

import os
import ssl
from urllib.error import HTTPError
from urllib.request import urlopen

context = ssl.create_default_context()
context.load_verify_locations(cafile=os.environ['CA_BUNDLE'])
try:
    with urlopen(os.environ['RPC_URL'], context=context, timeout=10) as response:
        print('Final HTTP status:', response.status)
except HTTPError as exc:
    print('HTTP error status after TLS:', exc.code)
    exc.close()

Certificate error messages and targeted fixes

Read the reason after CERTIFICATE_VERIFY_FAILED before changing the bundle. Python's ssl.SSLCertVerificationError exposes verify_code and verify_message when you have access to the underlying exception. Requests may wrap that exception, and message wording varies across TLS library versions.

  • Unable to get local issuer certificate: Check both sides. The client may lack a trusted root, or the server may omit an intermediate. Fix a missing intermediate at the TLS listener; don't add arbitrary certificates to every client.
  • Self-signed certificate in the chain: Confirm that the expected private CA or an approved TLS-inspecting proxy is involved. If the issuer is unexpected, investigate the route before importing anything.
  • Hostname mismatch: Check the URL, SANs, and certificate selected by the TLS listener. Fix the URL or reissue and deploy the right certificate. An HTTP Host header cannot change a TLS identity check that happens before HTTP.
  • Expired or not yet valid: Check the runner's clock and the validity of the leaf and intermediates. Renew or replace the affected certificate, then check that the listener is actually serving the replacement.
  • Only fails in CI or a container: Check the mounted bundle path, permissions, dependency versions, and proxy settings inside that runtime. Ensure the application process received the same environment settings as the probe.

Certificate issuance and deployment for a service you own

If you are serving HTTPS rather than calling it, configure the component that terminates TLS. For a public DNS name, use a publicly trusted CA and automate issuance and renewal, for example through ACME with Let's Encrypt. For an internal service, use your organization's private CA and distribute its trust anchor independently. Configure the listener with the private key and the leaf certificate followed by the required intermediates; clients normally already hold the root.

If Python terminates TLS directly, use ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) and load_cert_chain() with the server chain and key. If a reverse proxy or load balancer terminates TLS instead, changing certificate files in the Python app won't change what clients see. For infrastructure you operate, such as a dedicated node deployment, verify the externally visible certificate after deployment and renewal using a fresh client connection.

Positive and negative verification checks

Run these checks in the deployment runtime using your application's HTTP client and a new connection for each case. Reusing an open pooled connection can skip a new handshake and conceal a certificate rotation problem. Use controlled test fixtures for negative cases. The table gives expected outcomes, not measured results; record the status or verification reason you actually observe.

Test caseExpected outcomeObserved outcome
Trusted chain, correct hostname, valid datesHTTP response; application success checked separatelyRecord status
Private test CA omitted from the trust configurationTLS verification fails before an HTTP responseRecord reason
Trusted test CA, but URL hostname absent from the SANTLS verification fails on identityRecord reason
Valid replacement leaf deployed under the same trusted CAA fresh connection receives an HTTP responseRecord status

Record the runtime or image version, bundle source, and whether a proxy was in use. If a negative case unexpectedly passes, check whether the test used the intended hostname, whether another trust source supplied the private CA, or whether verification was disabled. verify=False bypasses both chain and hostname checks and is not a repair.

Operational follow-through for HTTPS RPC

Keep private trust scoped to the workloads that need it. An organization-wide trust store simplifies deployment but broadens which issuers those workloads accept. A per-service bundle narrows that scope but needs an owner, a distribution path, and a rotation plan. During a CA change, coordinate the client trust update with the server rollout so fresh connections can verify the chain at every stage.

Once TLS is verified, test a separate read-only JSON-RPC call to confirm authentication, HTTP handling, and the expected JSON-RPC response. For production triage, log TLS errors separately from HTTP statuses and RPC errors so a certificate renewal issue does not look like an application failure. Use the OnFinality Learn library for follow-on integration guidance and the RPC plan details when evaluating usage limits separately from transport health.

RPC Assistant

Related RPC Assistant resources

Never Worry about Infrastructure Again

OnFinality takes away the heavy lifting of DevOps so you can build smarter and faster.

Get Started