# psycopg2.OperationalError: could not connect to server: SSL error: certificate verify failed

- **ID:** `database/ssl-certificate-verify-failed`
- **Domain:** database
- **Category:** auth_error
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

PostgreSQL client cannot verify the server's SSL certificate because the CA certificate is missing, expired, or the server hostname does not match the certificate's CN/SAN.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| PostgreSQL 14 | active | — | — |
| PostgreSQL 15 | active | — | — |
| PostgreSQL 16 | active | — | — |
| psycopg2 2.9.9 | active | — | — |
| libpq 15.4 | active | — | — |

## Workarounds

1. **Set the sslrootcert parameter to the correct CA certificate file. Example: sslrootcert=/etc/ssl/certs/ca-certificates.crt in the connection string or ~/.pgpass.** (80% success)
   ```
   Set the sslrootcert parameter to the correct CA certificate file. Example: sslrootcert=/etc/ssl/certs/ca-certificates.crt in the connection string or ~/.pgpass.
   ```
2. **If the server uses a self-signed certificate, add the server's certificate to the client's trust store. Command: echo 'my_server_cert_pem' >> ~/.postgresql/root.crt && chmod 600 ~/.postgresql/root.crt** (85% success)
   ```
   If the server uses a self-signed certificate, add the server's certificate to the client's trust store. Command: echo 'my_server_cert_pem' >> ~/.postgresql/root.crt && chmod 600 ~/.postgresql/root.crt
   ```
3. **Verify the server hostname matches the certificate's Common Name (CN) or Subject Alternative Name (SAN). Use openssl s_client -connect host:5432 to check the certificate.** (90% success)
   ```
   Verify the server hostname matches the certificate's Common Name (CN) or Subject Alternative Name (SAN). Use openssl s_client -connect host:5432 to check the certificate.
   ```

## Dead Ends

- **Disable SSL verification by setting sslmode=disable in the connection string.** — This bypasses security entirely and may violate compliance requirements (e.g., PCI-DSS). It also fails if the server requires SSL. (90% fail)
- **Reinstall PostgreSQL server without changing certificate configuration.** — Reinstalling the server does not fix the certificate trust chain; the root cause is the client's CA store or certificate mismatch. (95% fail)
