Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions action-server/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ export interface Config {
PLANDEV_DB: string;
PLANDEV_DB_HOST: string;
PLANDEV_DB_PORT: string;
PLANDEV_DB_SSL_MODE: string | undefined;
PLANDEV_DB_SSL_ROOT_CERT: string | undefined;
ACTION_COOKIE_NAMES: string[];
ACTION_CORS_ALLOWED_ORIGIN: string;
ACTION_DB_USER: string;
Expand All @@ -26,6 +28,8 @@ export const configuration = (): Config => {
PLANDEV_DB: env.PLANDEV_DB ?? env.AERIE_DB ?? "plandev",
PLANDEV_DB_HOST: env.PLANDEV_DB_HOST ?? env.AERIE_DB_HOST ?? "postgres",
PLANDEV_DB_PORT: env.PLANDEV_DB_PORT ?? env.AERIE_DB_PORT ?? "5432",
PLANDEV_DB_SSL_MODE: env.PLANDEV_DB_SSL_MODE,
PLANDEV_DB_SSL_ROOT_CERT: env.PLANDEV_DB_SSL_ROOT_CERT,
ACTION_COOKIE_NAMES: (env.ACTION_COOKIE_NAMES ?? '').split(',').map(s => s.trim()).filter(Boolean),
ACTION_CORS_ALLOWED_ORIGIN: env.ACTION_CORS_ALLOWED_ORIGIN ?? "",
ACTION_DB_USER: env.ACTION_DB_USER ?? "",
Expand Down
9 changes: 8 additions & 1 deletion action-server/src/db.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import type { Pool } from "pg";
import pg from "pg";
import { configuration } from "./config";
import { getDbSslConfig } from "./utils/dbSsl";
import logger from "./utils/logger";

const { PLANDEV_DB, PLANDEV_DB_HOST, PLANDEV_DB_PORT, ACTION_DB_USER, ACTION_DB_PASSWORD } = configuration();
const { PLANDEV_DB, PLANDEV_DB_HOST, PLANDEV_DB_PORT, PLANDEV_DB_SSL_MODE, PLANDEV_DB_SSL_ROOT_CERT, ACTION_DB_USER, ACTION_DB_PASSWORD } =
configuration();

// Validated at import time so an invalid TLS configuration fails at startup.
// `undefined` means unset: the `ssl` key is omitted to keep node-postgres defaults.
const ssl = getDbSslConfig(PLANDEV_DB_SSL_MODE, PLANDEV_DB_SSL_ROOT_CERT, PLANDEV_DB_HOST);

export class ActionsDbManager {
private static pool: Pool;
Expand All @@ -23,6 +29,7 @@ export class ActionsDbManager {
password: ACTION_DB_PASSWORD,
max: 3,
min: 3,
...(ssl === undefined ? {} : { ssl }),
});
return ActionsDbManager.pool;
} catch (error) {
Expand Down
8 changes: 7 additions & 1 deletion action-server/src/threads/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@ import { ActionResponse, ActionTask } from "../type/types";
import logger from "../utils/logger";
import { configuration } from "../config";
import pg from "pg";
import { getDbSslConfig } from "../utils/dbSsl";

const { PLANDEV_DB, PLANDEV_DB_HOST, PLANDEV_DB_PORT, ACTION_DB_USER, ACTION_DB_PASSWORD } = configuration();
const { PLANDEV_DB, PLANDEV_DB_HOST, PLANDEV_DB_PORT, PLANDEV_DB_SSL_MODE, PLANDEV_DB_SSL_ROOT_CERT, ACTION_DB_USER, ACTION_DB_PASSWORD } =
configuration();

// Same TLS settings as the main action-server pool (see db.ts).
const ssl = getDbSslConfig(PLANDEV_DB_SSL_MODE, PLANDEV_DB_SSL_ROOT_CERT, PLANDEV_DB_HOST);

let dbPool: pg.Pool | null = null;
let dbClient: pg.PoolClient | null = null;
Expand All @@ -27,6 +32,7 @@ function getDbPool() {
// should have exactly one client/connection
min: 1,
max: 1,
...(ssl === undefined ? {} : { ssl }),
});

dbPool.on("error", (err) => {
Expand Down
115 changes: 115 additions & 0 deletions action-server/src/utils/dbSsl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { X509Certificate } from "node:crypto";
import { readFileSync, statSync } from "node:fs";
import { checkServerIdentity } from "node:tls";
import type { ConnectionOptions } from "node:tls";

export const DB_SSL_MODES = ["disable", "require", "verify-ca", "verify-full"] as const;
export type DbSslMode = (typeof DB_SSL_MODES)[number];

function isDbSslMode(mode: string): mode is DbSslMode {
return (DB_SSL_MODES as readonly string[]).includes(mode);
}

function readRootCert(path: string): string[] {
let contents: string;

try {
if (!statSync(path).isFile()) {
throw new Error("not a regular file");
}

contents = readFileSync(path, "utf8");
} catch (error) {
throw new Error(`PLANDEV_DB_SSL_ROOT_CERT "${path}" could not be read: ${(error as Error).message}`);
}

const certificates = contents.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);

if (certificates === null) {
throw new Error(`PLANDEV_DB_SSL_ROOT_CERT "${path}" does not contain a PEM certificate.`);
}

// Do not silently discard incomplete certificates or other PEM blocks.
const delimiters = contents.match(/-{3,}\s*(?:BEGIN|END)\b/g) ?? [];
if (delimiters.length !== certificates.length * 2) {
throw new Error(`PLANDEV_DB_SSL_ROOT_CERT "${path}" contains an invalid certificate.`);
}

return certificates.map((certificate) => {
try {
// Parse each certificate so a malformed bundle fails at startup, not at first connection.
return new X509Certificate(certificate).toString();
} catch {
throw new Error(`PLANDEV_DB_SSL_ROOT_CERT "${path}" contains an invalid certificate.`);
}
});
}

/**
* Maps PLANDEV_DB_SSL_MODE and PLANDEV_DB_SSL_ROOT_CERT to the node-postgres `ssl` pool option.
*
* Returns `undefined` when both variables are unset or empty. Callers must then omit the `ssl` key
* entirely (not pass `ssl: false`), so node-postgres keeps its existing default behaviour,
* including honouring PGSSLMODE.
*
* Throws on any invalid configuration, so the service fails at startup instead of silently
* connecting with weaker settings than requested.
*
* Modes: `disable` uses no TLS. `require` uses TLS without verifying the server certificate
* (same as pgjdbc; a root cert is validated but not used). `verify-ca` verifies the certificate
* chain against the root cert but not the host name. `verify-full` verifies the chain and the host name.
*/
export function getDbSslConfig(sslMode: string | undefined, sslRootCert: string | undefined, host: string): false | ConnectionOptions | undefined {
const mode = sslMode?.trim() || undefined;
const rootCertPath = sslRootCert?.trim() || undefined;

if (mode === undefined) {
if (rootCertPath !== undefined) {
throw new Error(
"PLANDEV_DB_SSL_ROOT_CERT is set but PLANDEV_DB_SSL_MODE is not. " +
"Set PLANDEV_DB_SSL_MODE to verify-ca or verify-full to verify the server certificate.",
);
}

return undefined;
}

if (!isDbSslMode(mode)) {
throw new Error(`Unsupported PLANDEV_DB_SSL_MODE "${mode}". Expected one of: ${DB_SSL_MODES.join(", ")}.`);
}

if (mode === "disable") {
if (rootCertPath !== undefined) {
throw new Error('PLANDEV_DB_SSL_ROOT_CERT is set but PLANDEV_DB_SSL_MODE is "disable".');
}

return false;
}

if (rootCertPath === undefined) {
if (mode === "require") {
return { rejectUnauthorized: false };
}

throw new Error(`PLANDEV_DB_SSL_MODE is "${mode}" but PLANDEV_DB_SSL_ROOT_CERT is not set.`);
}

const ca = readRootCert(rootCertPath);

switch (mode) {
case "require": {
return { rejectUnauthorized: false };
}
case "verify-ca": {
// Chain verification stays on; only the host name check is skipped.
return { ca, checkServerIdentity: () => undefined, rejectUnauthorized: true };
}
case "verify-full": {
return {
ca,
rejectUnauthorized: true,
checkServerIdentity: (_servername, cert) => checkServerIdentity(host, cert),
};
}
}
}
37 changes: 37 additions & 0 deletions action-server/tests/dbPoolDefault.test.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import assert from "assert";
import { mock, test } from "node:test";

// With PLANDEV_DB_SSL_MODE and PLANDEV_DB_SSL_ROOT_CERT unset, the pools must not get an `ssl` key at all.
// Passing `ssl: false` would override node-postgres' own default (which honours PGSSLMODE).
delete process.env.PLANDEV_DB_SSL_MODE;
delete process.env.PLANDEV_DB_SSL_ROOT_CERT;

const poolOptions: Record<string, unknown>[] = [];

class FakePool {
constructor(options: Record<string, unknown>) {
poolOptions.push(options);
}
on() {}
async connect() {
return { query: async () => ({ rows: [] }), release: () => {} };
}
async end() {}
}

mock.module("pg", { defaultExport: { Pool: FakePool } });
mock.module("../src/utils/codeRunner", {
namedExports: { jsExecute: async () => ({ results: null, console: [], errors: null }) },
});

const { ActionsDbManager } = await import("../src/db.ts");
const { runAction } = await import("../src/threads/worker.ts");

test("pools omit the ssl option when the TLS variables are unset", async () => {
ActionsDbManager.getDb();
await runAction({ actionJS: "", action_run_id: "1", parameters: {}, settings: {}, workspaceId: 1, message_port: null });
assert.strictEqual(poolOptions.length, 2);
for (const options of poolOptions) {
assert.ok(!("ssl" in options), "ssl key must be omitted when unset");
}
});
48 changes: 48 additions & 0 deletions action-server/tests/dbPoolSsl.test.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import assert from "assert";
import { join } from "node:path";
import { mock, test } from "node:test";

// Checks that the TLS settings reach both node-postgres pools: the shared action-server pool (db.ts)
// and the per-action worker pool (threads/worker.ts). pg is mocked, so no database is needed.
// Settings are read when the modules load, so the environment is set before importing them.
process.env.PLANDEV_DB_SSL_MODE = "verify-full";
process.env.PLANDEV_DB_SSL_ROOT_CERT = join(import.meta.dirname, "fixtures", "db-ssl", "ca.pem");

const poolOptions: Record<string, unknown>[] = [];

class FakePool {
constructor(options: Record<string, unknown>) {
poolOptions.push(options);
}
on() {}
async connect() {
return { query: async () => ({ rows: [] }), release: () => {} };
}
async end() {}
}

mock.module("pg", { defaultExport: { Pool: FakePool } });
mock.module("../src/utils/codeRunner", {
namedExports: { jsExecute: async () => ({ results: null, console: [], errors: null }) },
});

const { ActionsDbManager } = await import("../src/db.ts");
const { runAction } = await import("../src/threads/worker.ts");

test("action-server pool receives the TLS settings", () => {
ActionsDbManager.getDb();
const ssl = poolOptions.at(-1)?.ssl as { ca: string[]; rejectUnauthorized: boolean };
assert.ok(ssl, "ssl option missing from the action-server pool");
assert.strictEqual(ssl.rejectUnauthorized, true);
assert.strictEqual(ssl.ca.length, 1);
});

test("action worker pool receives the TLS settings", async () => {
const before = poolOptions.length;
await runAction({ actionJS: "", action_run_id: "1", parameters: {}, settings: {}, workspaceId: 1, message_port: null });
assert.strictEqual(poolOptions.length, before + 1, "worker did not create its own pool");
const ssl = poolOptions.at(-1)?.ssl as { ca: string[]; rejectUnauthorized: boolean };
assert.ok(ssl, "ssl option missing from the worker pool");
assert.strictEqual(ssl.rejectUnauthorized, true);
assert.strictEqual(ssl.ca.length, 1);
});
106 changes: 106 additions & 0 deletions action-server/tests/dbSsl.test.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import assert from "assert";
import { chmodSync, copyFileSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import dbSsl from "../src/utils/dbSsl.ts";
const { getDbSslConfig: getDbSslConfigForHost } = dbSsl;
const getDbSslConfig = (mode: string | undefined, root: string | undefined, host = "localhost") =>
getDbSslConfigForHost(mode, root, host);

const fixtures = join(import.meta.dirname, "fixtures", "db-ssl");
const caPath = join(fixtures, "ca.pem");
const bundlePath = join(fixtures, "ca-bundle.pem");
const malformedPath = join(fixtures, "malformed.pem");
const scratch = mkdtempSync(join(tmpdir(), "db-ssl-"));

test("getDbSslConfig", async (t) => {
await t.test("unset or empty values keep the node-postgres default (ssl key omitted)", () => {
assert.strictEqual(getDbSslConfig(undefined, undefined), undefined);
assert.strictEqual(getDbSslConfig("", ""), undefined);
assert.strictEqual(getDbSslConfig(" ", undefined), undefined);
});

await t.test("disable turns TLS off", () => {
assert.strictEqual(getDbSslConfig("disable", undefined), false);
});

await t.test("require encrypts without verifying the server certificate", () => {
assert.deepStrictEqual(getDbSslConfig("require", undefined), { rejectUnauthorized: false });
assert.deepStrictEqual(getDbSslConfig("require", caPath), { rejectUnauthorized: false });
});

await t.test("verify-ca verifies the chain but not the host name", () => {
const ssl = getDbSslConfig("verify-ca", caPath);
assert.ok(ssl);
assert.strictEqual(ssl.rejectUnauthorized, true);
assert.strictEqual((ssl.ca as string[]).length, 1);
assert.strictEqual(typeof ssl.checkServerIdentity, "function");
assert.strictEqual(ssl.checkServerIdentity?.("any-host", {} as never), undefined);
});

await t.test("verify-full verifies the chain and the host name", () => {
const ssl = getDbSslConfig("verify-full", caPath);
assert.ok(ssl);
assert.strictEqual(ssl.rejectUnauthorized, true);
assert.strictEqual((ssl.ca as string[]).length, 1);
assert.strictEqual(typeof ssl.checkServerIdentity, "function");
const ipSsl = getDbSslConfig("verify-full", caPath, "127.0.0.1");
assert.ok(ipSsl);
assert.strictEqual(ipSsl.checkServerIdentity?.("localhost", { subjectaltname: "IP Address:127.0.0.1" } as never), undefined);
assert.ok(ipSsl.checkServerIdentity?.("localhost", { subjectaltname: "DNS:localhost" } as never));
});

await t.test("a CA bundle keeps every certificate", () => {
const ssl = getDbSslConfig("verify-full", bundlePath);
assert.ok(ssl);
assert.strictEqual((ssl.ca as string[]).length, 2);
});

await t.test("rejects unsupported modes", () => {
for (const mode of ["prefer", "allow", "no-verify", "VERIFY-FULL", "true"]) {
assert.throws(() => getDbSslConfig(mode, undefined), /Unsupported PLANDEV_DB_SSL_MODE/);
}
});

await t.test("rejects a root cert without a verifying mode", () => {
assert.throws(() => getDbSslConfig(undefined, caPath), /PLANDEV_DB_SSL_MODE is not/);
assert.throws(() => getDbSslConfig("disable", caPath), /"disable"/);
});

await t.test("verification modes require a root cert", () => {
assert.throws(() => getDbSslConfig("verify-ca", undefined), /PLANDEV_DB_SSL_ROOT_CERT is not set/);
assert.throws(() => getDbSslConfig("verify-full", ""), /PLANDEV_DB_SSL_ROOT_CERT is not set/);
});

await t.test("rejects missing, unreadable, empty and malformed root certs", () => {
const empty = join(scratch, "empty.pem");
const notPem = join(scratch, "not-pem.pem");
writeFileSync(empty, "");
writeFileSync(notPem, "not a certificate\n");

assert.throws(() => getDbSslConfig("verify-full", join(scratch, "missing.pem")), /could not be read/);
assert.throws(() => getDbSslConfig("verify-full", scratch), /could not be read: not a regular file/);
assert.throws(() => getDbSslConfig("verify-full", empty), /does not contain a PEM certificate/);
assert.throws(() => getDbSslConfig("verify-full", notPem), /does not contain a PEM certificate/);
assert.throws(() => getDbSslConfig("verify-full", malformedPath), /contains an invalid certificate/);
// A bad path is rejected even in require mode, rather than ignored.
assert.throws(() => getDbSslConfig("require", join(scratch, "missing.pem")), /could not be read/);
});

await t.test("rejects incomplete certificates and other PEM blocks in a CA bundle", () => {
const valid = readFileSync(caPath, "utf8");
const invalid = join(scratch, "mixed-bundle.pem");
for (const suffix of ["-----BEGIN CERTIFICATE-----\n", "-----BEGIN PRIVATE KEY-----\nAA==\n-----END PRIVATE KEY-----\n"]) {
writeFileSync(invalid, `${valid}\n${suffix}`);
assert.throws(() => getDbSslConfig("verify-full", invalid), /contains an invalid certificate/);
}
});

await t.test("rejects an unreadable root cert", { skip: process.getuid?.() === 0 ? "root can read any file" : false }, () => {
const unreadable = join(scratch, "unreadable.pem");
copyFileSync(caPath, unreadable);
chmodSync(unreadable, 0o000);
assert.throws(() => getDbSslConfig("verify-full", unreadable), /could not be read/);
});
});
Loading