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

Python SSL Certificates: Verify HTTPS and Fix Certificate Errors

Find out which certificates Python trusts, configure a private CA safely, and diagnose HTTPS and JSON-RPC certificate failures without disabling verification.

TL;DR

To fix a Python SSL certificate error, keep verification enabled and identify whether the problem is the server's certificate chain, the URL hostname, the client clock, or the CA bundle Python actually uses. A public HTTPS endpoint normally needs no certificate installed in your application, but a private endpoint or approved inspection proxy may require an organization-managed CA. This guide shows how to inspect the failing runtime, configure trust in Python and Requests, and verify a JSON-RPC call separately from the TLS handshake.

Certificate verification and the scope of the fix

A Python SSL certificate error means the client could not authenticate the TLS peer under its current verification settings. The term “SSL certificate” is common, but HTTPS uses TLS. For a public endpoint with a valid certificate and a complete chain, Python normally verifies the connection using the trust roots already available to the HTTP client. You do not normally download the server's certificate or install a client certificate.

Fix the side that owns the problem: deploy the correct certificate and intermediates on the server, use a hostname the certificate covers, correct the client clock, or configure the client to trust the approved issuing CA. Do not use verify=False as a fix. A request can appear to work with verification disabled without establishing that the peer is the intended service. For an RPC client, that puts credentials and the integrity of returned data at risk.

Prerequisites for a comparable diagnosis

Run the checks with the same Python interpreter, dependencies, service account, container image, and network route as the failing workload. A browser or host shell can succeed while a worker fails because it uses a different trust store, a different proxy, or a different certificate chain. Use the exact HTTPS hostname from the failing URL, not a resolved IP address or an internal alias.

The standard-library probes require a Python build with ssl; the Requests example assumes requests is installed in that interpreter. For the direct TLS probe, RPC_URL can be a credential-free HTTPS URL containing just the target hostname and port. For the later RPC example, supply the real URL through your application's secret configuration. Don't paste API keys, credential-bearing URLs, proxy credentials, or raw exception dumps into tickets.

Server identity, certificate chains, and trust roots

The TLS server presents a leaf certificate for its identity and typically sends the intermediate certificates needed to build a chain to a trusted root. The client checks that chain against its trust store, checks certificate validity against its clock, and verifies that the URL hostname matches a name on the leaf certificate. A DNS name should appear in a DNS Subject Alternative Name (SAN); if the URL uses a literal IP address, the certificate needs a matching IP SAN. Server Name Indication (SNI) helps a shared server choose which certificate to present; it is not a substitute for hostname verification.

The trust store belongs to the client. Python's ssl.create_default_context() uses the runtime's default CA-loading behavior, which can vary by platform and build. Requests normally uses a CA bundle supplied through certifi, although packaging or application configuration can change the effective trust source. A server certificate and private key belong at the TLS terminator. A client certificate and key are a separate identity used only when the service requires mutual TLS (mTLS).

Runtime and CA configuration inventory

Run this snippet from the failing environment before changing anything. The standard-library paths are OpenSSL's reported defaults and do not enumerate every trusted certificate. The Requests bundle path is the library's reported default, not proof that a particular call used it: environment variables, explicit verify settings, or custom adapters can change the result. Check the application configuration alongside this inventory.

If the environment differs from a working deployment, compare the Python and OpenSSL builds, CA package or bundle versions, and mounted file paths. A file on the host does not help a container unless the container can read it.

import os
import ssl
import sys

print('Python executable:', sys.executable)
print('Python version:', sys.version.split()[0])
print('TLS library:', ssl.OPENSSL_VERSION)
print('OpenSSL default verify paths:', ssl.get_default_verify_paths())

try:
    import requests
except ImportError:
    print('Requests is not installed in this interpreter')
else:
    print('Requests version:', requests.__version__)
    print('Requests default CA bundle:', requests.certs.where())

for name in ('SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE',
             'CURL_CA_BUNDLE', 'HTTPS_PROXY', 'HTTP_PROXY', 'ALL_PROXY', 'NO_PROXY'):
    print(name, 'set' if os.environ.get(name) else 'unset')

Direct TLS verification with Python

This probe opens a verified TLS socket without sending HTTP headers, an RPC payload, or an API key. Save it as a Python script and run it with RPC_URL set. With no EXTRA_CA_PEM, it tests the standard-library defaults. If your security or platform team provides an approved CA file, set EXTRA_CA_PEM to that path and repeat. Loading it after creating the context adds trust to the defaults rather than selecting a replacement CA file at context creation.

Success prints the negotiated TLS version and the leaf certificate's expiration. A verification failure prints the verification code and message and exits unsuccessfully. The expiration is for this connection's leaf certificate only; it is not an inventory of every certificate in the chain or across a fleet. This socket connects directly and does not honor Requests' HTTP proxy settings. If the application uses a proxy, also test the real HTTP client before drawing conclusions.

import os
import socket
import ssl
from urllib.parse import urlsplit

url = urlsplit(os.environ['RPC_URL'])
if url.scheme != 'https' or not url.hostname:
    raise SystemExit('Set RPC_URL to an HTTPS URL')

ctx = ssl.create_default_context()
extra_ca = os.environ.get('EXTRA_CA_PEM')
if extra_ca:
    ctx.load_verify_locations(cafile=extra_ca)

try:
    with socket.create_connection((url.hostname, url.port or 443), timeout=10) as raw:
        with ctx.wrap_socket(raw, server_hostname=url.hostname) as tls:
            leaf = tls.getpeercert()
            print('Verified TLS:', tls.version())
            print('Leaf certificate expires:', leaf.get('notAfter', 'not reported'))
except ssl.SSLCertVerificationError as exc:
    print('Verification failed:', exc.verify_code, exc.verify_message)
    raise SystemExit(1) from None

CA bundle configuration in Requests

For normal Requests calls, use verify=True to leave verification enabled with the configured defaults. To select a CA bundle for one call, pass its PEM file path as verify. For standard environment-aware Requests calls, REQUESTS_CA_BUNDLE can set the bundle without a code change, with CURL_CA_BUNDLE as a fallback. If your code manually prepares requests and calls Session.send(), merge environment settings explicitly or pass the required verification settings yourself.

A bundle selected by path replaces Requests' default bundle for that call. An approved private CA may be enough for an internal-only endpoint. If the same configuration must reach public endpoints as well, use a maintained bundle containing both sets of roots, or scope the private bundle to just the calls that need it. Don't edit an installed certifi file: package upgrades can overwrite the change, and the trust policy becomes harder to audit. For a development service with a self-signed leaf, prefer issuing a leaf from a dedicated development CA. Obtain trust material through a trusted channel, not from the connection that's failing verification.

Verified HTTPS and JSON-RPC smoke test

This example uses a read-only Ethereum-compatible eth_chainId request. Set RPC_URL to your actual endpoint and, if needed, set APP_CA_BUNDLE to its approved custom bundle. For another protocol, keep the verification settings and substitute a documented read-only method and matching response check. Redirects are disabled so the result applies to the URL you intended to test.

Success means the HTTPS request completed with verification enabled, returned a 2xx status, and produced a JSON-RPC result with the expected ID and a parseable chain ID. Compare the printed ID with the intended network; TLS authenticates the hostname, not the chain behind it. A 401, 403, or 429 response, or a JSON-RPC error after a successful HTTPS response, calls for HTTP or application-level troubleshooting rather than a new CA bundle.

import os
from urllib.parse import urlsplit

import requests

url = os.environ['RPC_URL']
parsed = urlsplit(url)
if parsed.scheme != 'https' or not parsed.hostname:
    raise SystemExit('Set RPC_URL to an HTTPS URL')

try:
    response = requests.post(
        url,
        json={'jsonrpc': '2.0', 'id': 1, 'method': 'eth_chainId', 'params': []},
        verify=os.environ.get('APP_CA_BUNDLE') or True,
        timeout=(5, 15),
        allow_redirects=False,
    )
except requests.exceptions.SSLError:
    raise SystemExit('Requests TLS failed; inspect the trust source and network route') from None
except (requests.exceptions.RequestException, OSError) as exc:
    raise SystemExit(f'Request or configuration failed: {type(exc).__name__}') from None

print('HTTP status:', response.status_code)
if not 200 <= response.status_code < 300:
    raise SystemExit('Unexpected HTTP status')
try:
    body = response.json()
except ValueError:
    raise SystemExit('Expected a JSON response') from None
if (not isinstance(body, dict) or body.get('jsonrpc') != '2.0'
        or body.get('id') != 1 or 'error' in body or 'result' not in body):
    raise SystemExit('Expected a successful JSON-RPC response with id 1')
try:
    result = body['result']
    if not isinstance(result, str) or not result.startswith('0x'):
        raise ValueError
    chain_id = int(result, 16)
except ValueError:
    raise SystemExit('Expected a hexadecimal chain ID') from None
print('Chain ID:', chain_id)

Failure signatures and the right place to fix them

Treat the verification message as a clue, not a complete diagnosis. Reproduce the failure before changing a setting, then change one variable at a time. Use the same route and hostname where possible; a direct connection and a proxied connection can legitimately see different peer certificates.

  • unable to get local issuer certificate: Check both sides. The server may be omitting an intermediate, or the application may lack the required root. If you manage the TLS terminator, configure it to serve the leaf and required intermediates. Installing a root on the client is appropriate only when that root is intentionally trusted.
  • self-signed certificate or self-signed certificate in certificate chain: Confirm whether a private CA or approved TLS inspection proxy is expected on that route. Obtain the designated CA through your organization and scope it to the workloads that need it. Escalate an unexpected issuer rather than trusting it.
  • hostname mismatch: Use the documented hostname or reissue the certificate with the correct SAN. Check the load balancer or ingress certificate selection if the correct name still receives the wrong certificate. Adding a CA does not fix a name mismatch.
  • certificate has expired or certificate is not yet valid: Check the workload's UTC clock, then have the service operator inspect the leaf and intermediate validity periods and confirm that affected listeners present the renewed chain.
  • TLS alerts or protocol errors without a verification message: Confirm the scheme and port, proxy configuration, and whether the service requires mTLS. Adding a server trust root does not provide the client certificate and key required for mTLS.

Reproducible before-and-after verification

Record the baseline from the failing runtime. Apply one fix, start a fresh process to avoid reusing pooled TLS connections, and repeat with the same hostname and route. Fill in the table with observed results; the fields are a recording procedure, not benchmark data. If the direct route is unavailable or differs from the application's route, mark it as not comparable.

StageRuntime and routeTrust sourceTLS outcome or verification messageHTTP status and RPC result
Before fixRecord image or interpreter and proxy useRecord default or bundle identifierRecord direct probe outcome if comparableRecord app outcome or not reached
After fixRepeat from the same runtime and route where possibleRecord what changedRepeat the comparable probeRecord status and compare chain ID
Regression checkUse the deployed app configurationKeep the deployed trust policyVerify an intended public destination if the app uses oneRecord the expected application result

If failures are intermittent behind a load balancer, repeat fresh connections from affected environments and ask the operator to check certificate deployment across listeners. A single successful handshake verifies one connection, not every replica. In a controlled test environment, also confirm that the client still rejects a certificate for the wrong hostname.

Trust policy and operational next steps

Prefer an application-scoped bundle when only one integration needs a private CA. A managed system store can simplify rotation for many workloads, but it broadens the trust change and helps only clients configured to use that store. Keep CA files under deployment control, document who owns rotation, and rerun verification after changes to the image, proxy, ingress, or CA bundle. If you manage your own TLS terminator, include intermediate deployment and certificate renewal in the same operational checklist.

For managed RPC, use the OnFinality API service and network directory to confirm the intended service and network before checking the hostname in your configuration. If you operate your own deployment, see dedicated node infrastructure for deployment context. Once TLS succeeds, separate application access issues from RPC plan limits, and use OnFinality Learn integration and troubleshooting guides to continue debugging above the transport layer.

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