|
| 1 | +import fs from "fs"; |
| 2 | +import os from "os"; |
| 3 | +import path from "path"; |
| 4 | +import pg from "pg"; |
| 5 | +import { FailedToReadCertificate } from "./failed-to-read-certificate.js"; |
| 6 | + |
| 7 | +/** |
| 8 | + * PEM handling behind the PostgreSQL `sslrootcert` / `sslcert` / `sslkey` DSN |
| 9 | + * parameters: reading the files (once at parse time, and again on every new |
| 10 | + * pool connection so a rotated certificate is picked up without a restart), |
| 11 | + * rejecting encrypted client keys, and the pg.Client subclass that does the |
| 12 | + * per-connection reload. |
| 13 | + */ |
| 14 | + |
| 15 | +/** SSL modes in which a client certificate is presented to the server. */ |
| 16 | +export const CLIENT_CERT_SSL_MODES = ["require", "verify-ca", "verify-full"]; |
| 17 | + |
| 18 | +/** SSL modes the DSN parser maps to a node-postgres `ssl` setting. */ |
| 19 | +export const SUPPORTED_SSL_MODES = ["disable", ...CLIENT_CERT_SSL_MODES]; |
| 20 | + |
| 21 | +export const SSL_ROOT_CERT_LABEL = "SSL root certificate"; |
| 22 | +export const SSL_CLIENT_CERT_LABEL = "SSL client certificate"; |
| 23 | +export const SSL_CLIENT_KEY_LABEL = "SSL client key"; |
| 24 | + |
| 25 | +/** Paths of the PEM files behind a pool's `ssl` setting. */ |
| 26 | +export interface PemPaths { |
| 27 | + sslrootcert?: string; |
| 28 | + sslcert?: string; |
| 29 | + sslkey?: string; |
| 30 | +} |
| 31 | + |
| 32 | +/** PEM contents keyed by the node-postgres `ssl` property they populate. */ |
| 33 | +export interface PemContents { |
| 34 | + ca?: string; |
| 35 | + cert?: string; |
| 36 | + key?: string; |
| 37 | +} |
| 38 | + |
| 39 | +/** Expand a leading `~/` in a PEM path referenced by an SSL DSN parameter. */ |
| 40 | +function resolvePemPath(filePath: string): string { |
| 41 | + return filePath.startsWith("~/") ? path.join(os.homedir(), filePath.slice(2)) : filePath; |
| 42 | +} |
| 43 | + |
| 44 | +function failedToRead(label: string, resolved: string, err: unknown): FailedToReadCertificate { |
| 45 | + return new FailedToReadCertificate( |
| 46 | + `Failed to read ${label} at '${resolved}': ${err instanceof Error ? err.message : String(err)}` |
| 47 | + ); |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Read a PEM file referenced by an SSL DSN parameter, expanding a leading `~/`. |
| 52 | + * Wraps any read failure in FailedToReadCertificate so callers can tell a |
| 53 | + * misconfigured cert path apart from a malformed DSN. |
| 54 | + */ |
| 55 | +export async function readPemFile(filePath: string, label: string): Promise<string> { |
| 56 | + const resolved = resolvePemPath(filePath); |
| 57 | + try { |
| 58 | + return await fs.promises.readFile(resolved, "utf-8"); |
| 59 | + } catch (err) { |
| 60 | + throw failedToRead(label, resolved, err); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +/** Synchronous variant of readPemFile for the per-connection reload. */ |
| 65 | +function readPemFileSync(filePath: string, label: string): string { |
| 66 | + const resolved = resolvePemPath(filePath); |
| 67 | + try { |
| 68 | + return fs.readFileSync(resolved, "utf-8"); |
| 69 | + } catch (err) { |
| 70 | + throw failedToRead(label, resolved, err); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +/** |
| 75 | + * Node's TLS layer needs a passphrase to open an encrypted PEM key and fails |
| 76 | + * with an opaque decoder error otherwise. Detect the common PEM markers and |
| 77 | + * fail with a clear message instead (sslpassword is not supported yet). |
| 78 | + */ |
| 79 | +export function isEncryptedPemKey(pem: string): boolean { |
| 80 | + return pem.includes("ENCRYPTED PRIVATE KEY") || pem.includes("Proc-Type: 4,ENCRYPTED"); |
| 81 | +} |
| 82 | + |
| 83 | +export function encryptedKeyMessage(keyPath: string): string { |
| 84 | + return ( |
| 85 | + `SSL client key at '${keyPath}' is encrypted; encrypted private keys are not supported. ` + |
| 86 | + `Decrypt it first, e.g. 'openssl pkey -in client.key -out client-plain.key'` |
| 87 | + ); |
| 88 | +} |
| 89 | + |
| 90 | +/** |
| 91 | + * Read every configured PEM file. The client key is rejected when encrypted. |
| 92 | + * Throws FailedToReadCertificate naming the file on any problem, so nothing is |
| 93 | + * returned unless the whole set is readable. The files are read back to back |
| 94 | + * rather than as an atomic snapshot: a rotation that renames cert and key |
| 95 | + * separately can, in the microseconds between the two reads, yield one file |
| 96 | + * from each generation. libpq has the same window. TLS then rejects that one |
| 97 | + * connection attempt with a key mismatch error and the next attempt re-reads. |
| 98 | + */ |
| 99 | +function loadPems(paths: PemPaths): PemContents { |
| 100 | + const pems: PemContents = {}; |
| 101 | + if (paths.sslrootcert !== undefined) { |
| 102 | + pems.ca = readPemFileSync(paths.sslrootcert, SSL_ROOT_CERT_LABEL); |
| 103 | + } |
| 104 | + if (paths.sslcert !== undefined && paths.sslkey !== undefined) { |
| 105 | + const key = readPemFileSync(paths.sslkey, SSL_CLIENT_KEY_LABEL); |
| 106 | + if (isEncryptedPemKey(key)) { |
| 107 | + throw new FailedToReadCertificate(encryptedKeyMessage(paths.sslkey)); |
| 108 | + } |
| 109 | + pems.key = key; |
| 110 | + pems.cert = readPemFileSync(paths.sslcert, SSL_CLIENT_CERT_LABEL); |
| 111 | + } |
| 112 | + return pems; |
| 113 | +} |
| 114 | + |
| 115 | +/** |
| 116 | + * A pg.Client that re-reads the configured PEM files every time it connects, so |
| 117 | + * a certificate rotated on disk reaches new pool connections without a restart. |
| 118 | + * libpq likewise opens sslrootcert/sslcert/sslkey per connection, and like |
| 119 | + * libpq the connection fails, with the file named, when a file cannot be read. |
| 120 | + * |
| 121 | + * pg-pool constructs one of these per physical connection and passes it the |
| 122 | + * pool config, so `this.ssl` is the very object the pool config holds and the |
| 123 | + * one the Connection copies into the TLS options once the socket is open. |
| 124 | + * Writing the fresh contents onto it before connecting is enough; reading all |
| 125 | + * files up front, before any socket is opened, means a failure surfaces as an |
| 126 | + * ordinary connection error from `pool.connect()` rather than from inside the |
| 127 | + * TLS handshake. |
| 128 | + */ |
| 129 | +export function rotatingPemClient(paths: PemPaths): typeof pg.Client { |
| 130 | + return class RotatingPemClient extends pg.Client { |
| 131 | + connect(): Promise<void>; |
| 132 | + connect(callback: (err: Error) => void): void; |
| 133 | + connect(callback?: (err: Error) => void): Promise<void> | void { |
| 134 | + let pems: PemContents; |
| 135 | + try { |
| 136 | + pems = loadPems(paths); |
| 137 | + } catch (err) { |
| 138 | + const error = err instanceof Error ? err : new Error(String(err)); |
| 139 | + if (callback) { |
| 140 | + callback(error); |
| 141 | + return; |
| 142 | + } |
| 143 | + return Promise.reject(error); |
| 144 | + } |
| 145 | + // ssl is always an object when PEM paths are configured (see parse()). |
| 146 | + Object.assign(this.ssl as unknown as object, pems); |
| 147 | + return callback ? super.connect(callback) : super.connect(); |
| 148 | + } |
| 149 | + }; |
| 150 | +} |
0 commit comments