Square CloudSquare Cloud

self signed certificate in certificate chain: TLS errors when connecting to a database

The error appears when the client gets a certificate signed by a CA it doesn't know, which is common with databases that use their own CA. The fix is to give the driver the CA file, not to turn verification off.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Recognize the certificate error messages in Node.js, Python and libpq
  • Use openssl to see which certificate the server presents and whether your CA validates it
  • Configure the CA and the client certificate in pg, psycopg, mysql2 and MongoDB without disabling verification
On this page

You point your app at the database, turn on TLS, and the connection dies before the first query with self-signed certificate in certificate chain. The password is right and the host answers, yet nothing works. This isn't a network or credentials problem. It's about trust: the client received a certificate and couldn't find whoever signed it among the authorities it knows.

The error is common with hosted databases, because many servers use a certificate signed by their own certificate authority (CA), which is in neither the operating system's public list nor Node.js's. The answer you see on every forum, turning verification off, makes the error go away and leaves the connection open to interception. This guide shows the proper fix for each client.

What does the error look like?#

In Node.js, every driver built on the tls module (pg, mysql2, the MongoDB driver, node-redis, ioredis) gets the same OpenSSL error, with a code in err.code:

text
Error: self-signed certificate in certificate chain
    at TLSSocket.onConnectSecure (node:_tls_wrap:...)
  code: 'SELF_SIGNED_CERT_IN_CHAIN'

OpenSSL spells it "self-signed", with a hyphen. Older releases wrote "self signed", which is how many people still search for it. In the MongoDB Node.js driver, the error arrives as a MongoServerSelectionError that repeats the connection failure's message. Related codes show up in the same situations:

Node.js code Message What it means
SELF_SIGNED_CERT_IN_CHAIN self-signed certificate in certificate chain The chain ends at a root CA the client doesn't know
DEPTH_ZERO_SELF_SIGNED_CERT self-signed certificate The server's own certificate is self-signed, with no CA above it
UNABLE_TO_GET_ISSUER_CERT_LOCALLY unable to get local issuer certificate The client doesn't have the issuer's certificate
UNABLE_TO_VERIFY_LEAF_SIGNATURE unable to verify the first certificate An intermediate is missing, or the CA you gave isn't the one that signed it
ERR_TLS_CERT_ALTNAME_INVALID Hostname/IP does not match certificate's altnames The chain is valid, but the host name isn't in the certificate

In Python, the ssl module prints the OpenSSL reason after CERTIFICATE_VERIFY_FAILED. Libraries such as PyMySQL and redis-py repeat that text inside their own exception:

text
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain (_ssl.c:...)

PostgreSQL through psql, and psycopg inside an OperationalError, use libpq's wording. The first message shows up when the chain doesn't close; the second when you ask for verification and the CA file isn't where libpq looks:

text
psql: error: connection to server at "db.example.com" (203.0.113.10), port 5432 failed: SSL error: certificate verify failed

root certificate file "/home/app/.postgresql/root.crt" does not exist
Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.

What does the error actually mean?#

A TLS certificate is trusted when the client can build a chain from it up to a root CA it already knows. Node.js ships its own list of public CAs (Mozilla's), Python uses the operating system's store, and libpq uses the root.crt file or whatever you set in sslrootcert. The protocol basics are in what is SSL/TLS.

When the database server uses its own CA, that CA's root is self-signed (every root is) and sits in none of those lists. OpenSSL builds the chain, reaches the unknown root and stops: hence "self-signed certificate in certificate chain". Nothing is wrong with the certificate. The client just hasn't been told that this CA is trusted, which you do by handing it the CA file.

Certificate errors on a website follow the same logic with different typical causes (expired certificate, wrong domain), covered in SSL certificate errors.

What are the most common causes?#

From most to least frequent:

  1. The driver never got the CA. TLS is on, but no option points to the CA file, so the client only uses public CAs.
  2. The connection string overrides pg's ssl option. In node-postgres, if the URL contains sslmode, sslrootcert, sslcert or sslkey, the ssl object you passed is replaced by what the URL describes, and your ca is lost.
  3. Wrong file or wrong path. The client certificate was passed instead of the CA, a relative path resolves from a different directory, or the file wasn't included in the deploy.
  4. The certificate changed. The server got a new certificate or CA and the app still loads the old file.
  5. The host name doesn't match. You connect by IP or by an alias that isn't in the certificate. The error is different here (ERR_TLS_CERT_ALTNAME_INVALID or "server certificate for ... does not match host name"), and the fix is to use the name the certificate carries.

How do you diagnose it before touching code?#

openssl s_client shows the certificate the server presents and whether your CA file validates it. PostgreSQL and MySQL negotiate TLS inside their own protocol, so they need -starttls; MongoDB and Redis speak TLS directly:

bash
openssl s_client -connect db.example.com:5432 -starttls postgres -CAfile ca.pem -showcerts </dev/null
openssl s_client -connect db.example.com:3306 -starttls mysql -CAfile ca.pem </dev/null
openssl s_client -connect db.example.com:27017 -CAfile ca.pem </dev/null

Look for the last line of the summary:

  • Verify return code: 0 (ok): the CA validates the server. The problem is in your code's configuration (causes 1 to 3).
  • Verify return code: 19 (self-signed certificate in certificate chain): that file isn't the CA that signed the certificate. Compare the printed issuer with the file you have.

If the server requires a client certificate, add -cert and -key with the client files. Then check what the app really loads: print the path it reads and whether the file exists in that environment.

How do you fix it in each client?#

The rule is the same everywhere: point the driver to the server's CA and, if the server asks for it, to the client certificate and key as well (mutual TLS). Keep the paths in environment variables, never hardcoded, and treat the client certificate and key like a password: out of public repositories (see where to store secrets).

Node.js with pg#

Keep sslmode out of the URL and pass everything in the ssl object:

js
import { readFileSync } from "node:fs";
import pg from "pg";

const pool = new pg.Pool({
  connectionString: process.env.DATABASE_URL, // no sslmode in the URL
  ssl: {
    ca: readFileSync(process.env.DB_CA_PATH, "utf8"),
    // only if the server requires a client certificate:
    cert: readFileSync(process.env.DB_CERT_PATH, "utf8"),
    key: readFileSync(process.env.DB_KEY_PATH, "utf8"),
  },
});

const { rows } = await pool.query("select now()");
console.log(rows[0]);
await pool.end();

The alternative is to put everything in the URL: ?sslmode=verify-full&sslrootcert=/path/ca.pem&sslcert=...&sslkey=.... pg reads those files and builds the ssl object itself, and verify-full checks the chain and the host name in every version. The full walkthrough is in how to connect PostgreSQL to Node.js.

Python with psycopg#

psycopg hands the parameters to libpq. Use verify-full, which checks both the chain and the host name:

python
import os
import psycopg

with psycopg.connect(
    os.environ["DATABASE_URL"],
    sslmode="verify-full",
    sslrootcert=os.environ["DB_CA_PATH"],
    # only if the server requires a client certificate:
    sslcert=os.environ["DB_CERT_PATH"],
    sslkey=os.environ["DB_KEY_PATH"],
) as conn:
    print(conn.execute("select now()").fetchone())

More in how to connect PostgreSQL to Python.

MySQL with mysql2 and on the command line#

js
import { readFileSync } from "node:fs";
import mysql from "mysql2/promise";

const pool = mysql.createPool({
  uri: process.env.DATABASE_URL,
  ssl: { ca: readFileSync(process.env.DB_CA_PATH, "utf8") },
});

const [rows] = await pool.query("SELECT NOW() AS now");
console.log(rows[0]);
await pool.end();

In the mysql client, --ssl-mode=REQUIRED only encrypts. To check the server, use --ssl-mode=VERIFY_IDENTITY --ssl-ca=ca.pem.

MongoDB#

js
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI, {
  tls: true,
  tlsCAFile: process.env.DB_CA_PATH,
  // .pem with the client certificate and key, if the server requires it:
  tlsCertificateKeyFile: process.env.DB_CERT_PATH,
});

await client.connect();
console.log(await client.db("admin").command({ ping: 1 }));
await client.close();

If the MongoDB error is a timeout with no certificate text, see MongoServerSelectionError.

Redis and libraries with no CA option#

For Redis, use rediss:// and pass the CA in the client's TLS option; each library's details are in Redis connection errors. If a Node.js library doesn't expose a ca option, NODE_EXTRA_CA_CERTS=/path/ca.pem adds the CA to the process's default list. It is read only when the process starts.

Why not just turn verification off?#

Because TLS does two jobs: it encrypts the traffic and it proves the right server is on the other end. Turning verification off keeps the first and throws away the second. Anyone who can get on the path (a Wi-Fi network, a compromised router, a tampered DNS answer) presents any certificate, the client accepts it, and the database password goes through them.

These options make the error disappear and leave the connection with no proof of identity. Use them only in a throwaway local test:

  • Node.js: rejectUnauthorized: false, or NODE_TLS_REJECT_UNAUTHORIZED=0, which disables verification for every TLS and HTTPS connection in the process.
  • PostgreSQL: sslmode=require in libpq (with no CA file) and sslmode=no-verify in pg.
  • MySQL: --ssl-mode=REQUIRED without --ssl-ca.
  • MongoDB: tlsAllowInvalidCertificates=true and tlsInsecure=true.

If one of these is already in production, replace it with the right CA as soon as the diagnosis above passes.

How to do this on Square Cloud#

Square Cloud's MongoDB, PostgreSQL, MySQL and Redis hosting, available from the Standard plan, requires TLS on every connection. The dashboard gives you the full connection URL, the host, the port and the certificate to download, and the client has to trust the downloaded CA: the case this article covers, where the fix is to give that CA to the driver, never to turn verification off.

On PostgreSQL and MongoDB the client also presents the .pem certificate. Besides the CA (ca, sslrootcert or tlsCAFile), fill in the client certificate options from the examples: cert and key in pg, sslcert and sslkey in psycopg, tlsCertificateKeyFile in MongoDB. For Redis, the URL uses rediss://.

Ship the files with your code (the app's disk persists across restarts and deploys) and keep the URL and the paths in the app's environment variables, which take effect on the next restart. Because the connection is external, you can test the same URL and certificate from your own machine, with the openssl s_client commands above, before you deploy.

See engines, limits and plans on the database hosting page.

Database hosting

MongoDB, PostgreSQL, MySQL and Redis next to your app

Database hosting

FAQs

Can I use rejectUnauthorized: false to fix it?

Only in a throwaway test. With verification off the connection is still encrypted, but anyone on the path can impersonate the database and capture the password and the data. In production, pass the right CA in the ca option.

What is the difference between sslmode=require and verify-full?

In libpq, require encrypts but doesn't check who the server is, unless a root CA file exists. verify-ca checks the chain, and verify-full checks the chain and the host name. In Node.js pg, what require means depends on the version and the uselibpqcompat option, so write verify-full.

Why does it work on my machine and fail in production?

Usually the CA file is on your machine but didn't ship with the deploy, the relative path changed, or the variable that points to it isn't set in production. Print the path your code uses and check that the file exists.

What does NODE_EXTRA_CA_CERTS do?

It adds CA certificates to the default list for the whole Node.js process. It is read only when the process starts and doesn't apply to connections that pass the ca option explicitly.

Next articleHow much does PostgreSQL hosting cost?PostgreSQL hosting costs from zero to hundreds of dollars a month. See what sets the price (RAM, disk, replicas, traffic), billing models and how to estimate yours.

More in Databases

See all 32 articles