From b56ed6e4dd52c2ae745bd8ccc154aede760c5141 Mon Sep 17 00:00:00 2001 From: Nikhil Reddy Donapati Date: Mon, 30 Nov 2026 06:49:47 -0600 Subject: [PATCH 1/4] Add optional Postgres TLS settings to the Java services Read PLANDEV_DB_SSL_MODE and PLANDEV_DB_SSL_ROOT_CERT into the PostgresStore records of merlin-server, scheduler-server and workspace-server, and pass them to pgjdbc as the sslMode/sslRootCert data source properties in all five app drivers. Nothing is set when both variables are unset, so the pgjdbc default is unchanged. Invalid settings (unknown mode, verify-* without a root cert, missing or malformed PEM file) fail at startup. Refs #1773 --- .../plandev/merlin/server/AerieAppDriver.java | 6 +- .../merlin/server/config/PostgresStore.java | 104 +++++++++++++++++- .../server/config/PostgresStoreTest.java | 98 +++++++++++++++++ .../src/test/resources/db-ssl/ca-bundle.pem | 24 ++++ .../src/test/resources/db-ssl/ca.pem | 12 ++ .../src/test/resources/db-ssl/malformed.pem | 3 + .../merlin/worker/MerlinWorkerAppDriver.java | 5 +- .../scheduler/server/SchedulerAppDriver.java | 6 +- .../server/config/PostgresStore.java | 104 +++++++++++++++++- .../server/config/PostgresStoreTest.java | 98 +++++++++++++++++ .../src/test/resources/db-ssl/ca-bundle.pem | 24 ++++ .../src/test/resources/db-ssl/ca.pem | 12 ++ .../src/test/resources/db-ssl/malformed.pem | 3 + .../worker/SchedulerWorkerAppDriver.java | 5 +- .../workspace/server/WorkspaceAppDriver.java | 6 +- .../server/config/PostgresStore.java | 104 +++++++++++++++++- .../server/config/PostgresStoreTest.java | 98 +++++++++++++++++ .../src/test/resources/db-ssl/ca-bundle.pem | 24 ++++ .../src/test/resources/db-ssl/ca.pem | 12 ++ .../src/test/resources/db-ssl/malformed.pem | 3 + 20 files changed, 743 insertions(+), 8 deletions(-) create mode 100644 merlin-server/src/test/java/gov/nasa/ammos/plandev/merlin/server/config/PostgresStoreTest.java create mode 100644 merlin-server/src/test/resources/db-ssl/ca-bundle.pem create mode 100644 merlin-server/src/test/resources/db-ssl/ca.pem create mode 100644 merlin-server/src/test/resources/db-ssl/malformed.pem create mode 100644 scheduler-server/src/test/java/gov/nasa/ammos/plandev/scheduler/server/config/PostgresStoreTest.java create mode 100644 scheduler-server/src/test/resources/db-ssl/ca-bundle.pem create mode 100644 scheduler-server/src/test/resources/db-ssl/ca.pem create mode 100644 scheduler-server/src/test/resources/db-ssl/malformed.pem create mode 100644 workspace-server/src/test/java/gov/nasa/ammos/plandev/workspace/server/config/PostgresStoreTest.java create mode 100644 workspace-server/src/test/resources/db-ssl/ca-bundle.pem create mode 100644 workspace-server/src/test/resources/db-ssl/ca.pem create mode 100644 workspace-server/src/test/resources/db-ssl/malformed.pem diff --git a/merlin-server/src/main/java/gov/nasa/ammos/plandev/merlin/server/AerieAppDriver.java b/merlin-server/src/main/java/gov/nasa/ammos/plandev/merlin/server/AerieAppDriver.java index 681ec66262..bad3d913af 100644 --- a/merlin-server/src/main/java/gov/nasa/ammos/plandev/merlin/server/AerieAppDriver.java +++ b/merlin-server/src/main/java/gov/nasa/ammos/plandev/merlin/server/AerieAppDriver.java @@ -40,6 +40,7 @@ import java.net.URI; import java.nio.file.Path; import java.time.Instant; +import java.util.Optional; public final class AerieAppDriver { @@ -170,6 +171,7 @@ private static Stores loadStores(final AppConfiguration config) { hikariConfig.addDataSourceProperty("portNumber", c.port()); hikariConfig.addDataSourceProperty("databaseName", c.database()); hikariConfig.addDataSourceProperty("applicationName", "Merlin Server"); + c.sslDataSourceProperties().forEach(hikariConfig::addDataSourceProperty); hikariConfig.setUsername(c.user()); hikariConfig.setPassword(c.password()); @@ -204,7 +206,9 @@ private static AppConfiguration loadConfiguration() { getEnv("PLANDEV_DB_HOST", getEnv("AERIE_DB_HOST", "postgres")), Integer.parseInt(getEnv("PLANDEV_DB_PORT", getEnv("AERIE_DB_PORT", "5432"))), getEnv("MERLIN_DB_USER", ""), - getEnv("MERLIN_DB_PASSWORD", "") + getEnv("MERLIN_DB_PASSWORD", ""), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_MODE")), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_ROOT_CERT")) ), Instant.parse(getEnv("UNTRUE_PLAN_START", "")), URI.create(getEnv("HASURA_GRAPHQL_URL", "http://localhost:8080/v1/graphql")), diff --git a/merlin-server/src/main/java/gov/nasa/ammos/plandev/merlin/server/config/PostgresStore.java b/merlin-server/src/main/java/gov/nasa/ammos/plandev/merlin/server/config/PostgresStore.java index 85babf0cb5..a884976c65 100644 --- a/merlin-server/src/main/java/gov/nasa/ammos/plandev/merlin/server/config/PostgresStore.java +++ b/merlin-server/src/main/java/gov/nasa/ammos/plandev/merlin/server/config/PostgresStore.java @@ -1,19 +1,121 @@ package gov.nasa.ammos.plandev.merlin.server.config; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Objects; +import java.util.Optional; +import java.util.Set; +/** + * Connection settings for the PlanDev Postgres database. + * + *

{@code sslMode} and {@code sslRootCert} come from {@code PLANDEV_DB_SSL_MODE} and + * {@code PLANDEV_DB_SSL_ROOT_CERT}. When both are empty no SSL properties are passed to the + * driver, so the pgjdbc default behavior is unchanged. Invalid settings are rejected here so + * that the service fails at startup instead of connecting with weaker settings than requested. + */ public record PostgresStore( String database, String server, Integer port, String user, - String password + String password, + Optional sslMode, + Optional sslRootCert ) implements Store { + /** Accepted values of {@code PLANDEV_DB_SSL_MODE}; these are the libpq/pgjdbc sslmode names. */ + public static final Set SSL_MODES = Set.of("disable", "require", "verify-ca", "verify-full"); + public PostgresStore { Objects.requireNonNull(database); Objects.requireNonNull(server); Objects.requireNonNull(port); Objects.requireNonNull(user); Objects.requireNonNull(password); + Objects.requireNonNull(sslMode); + Objects.requireNonNull(sslRootCert); + + // Treat empty values (e.g. `PLANDEV_DB_SSL_MODE: ""` in a compose file) as unset. + sslMode = sslMode.map(String::strip).filter(s -> !s.isEmpty()); + sslRootCert = sslRootCert.map(String::strip).filter(s -> !s.isEmpty()); + validateSsl(sslMode, sslRootCert); + } + + /** + * pgjdbc data source properties to apply through {@code HikariConfig#addDataSourceProperty}. + * Empty when no SSL settings were provided. + */ + public Map sslDataSourceProperties() { + final var properties = new LinkedHashMap(); + sslMode.ifPresent(mode -> properties.put("sslMode", mode)); + sslRootCert.ifPresent(path -> properties.put("sslRootCert", path)); + return properties; + } + + private static void validateSsl(final Optional sslMode, final Optional sslRootCert) { + if (sslMode.isEmpty()) { + if (sslRootCert.isPresent()) { + throw new IllegalArgumentException( + "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; + } + + final var mode = sslMode.get(); + if (!SSL_MODES.contains(mode)) { + throw new IllegalArgumentException( + "Unsupported PLANDEV_DB_SSL_MODE \"" + mode + "\". Expected one of: disable, require, verify-ca, verify-full."); + } + + if (mode.equals("disable") && sslRootCert.isPresent()) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT is set but PLANDEV_DB_SSL_MODE is \"disable\"."); + } + + if ((mode.equals("verify-ca") || mode.equals("verify-full")) && sslRootCert.isEmpty()) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_MODE is \"" + mode + "\" but PLANDEV_DB_SSL_ROOT_CERT is not set."); + } + + sslRootCert.ifPresent(PostgresStore::validateRootCert); + } + + private static void validateRootCert(final String location) { + final byte[] contents; + try { + final var path = Path.of(location); + if (!Files.isRegularFile(path)) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" does not exist or is not a regular file."); + } + contents = Files.readAllBytes(path); + } catch (final InvalidPathException | IOException | SecurityException e) { + throw new IllegalArgumentException("PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" could not be read.", e); + } + + if (!new String(contents, StandardCharsets.US_ASCII).contains("-----BEGIN CERTIFICATE-----")) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" does not contain a PEM certificate."); + } + try { + final var certificates = CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(contents)); + if (certificates.isEmpty()) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" does not contain a PEM certificate."); + } + } catch (final CertificateException e) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" contains an invalid certificate.", e); + } } } diff --git a/merlin-server/src/test/java/gov/nasa/ammos/plandev/merlin/server/config/PostgresStoreTest.java b/merlin-server/src/test/java/gov/nasa/ammos/plandev/merlin/server/config/PostgresStoreTest.java new file mode 100644 index 0000000000..aefba3b491 --- /dev/null +++ b/merlin-server/src/test/java/gov/nasa/ammos/plandev/merlin/server/config/PostgresStoreTest.java @@ -0,0 +1,98 @@ +package gov.nasa.ammos.plandev.merlin.server.config; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +class PostgresStoreTest { + @TempDir + Path tempDir; + + private static String fixture(final String name) throws URISyntaxException { + return Path.of(PostgresStoreTest.class.getResource("/db-ssl/" + name).toURI()).toString(); + } + + private static PostgresStore store(final String sslMode, final String sslRootCert) { + return new PostgresStore( + "plandev", "postgres", 5432, "user", "password", + Optional.ofNullable(sslMode), Optional.ofNullable(sslRootCert)); + } + + private static void assertRejected(final String sslMode, final String sslRootCert, final String message) { + final var error = assertThrows(IllegalArgumentException.class, () -> store(sslMode, sslRootCert)); + assertTrue(error.getMessage().contains(message), error.getMessage()); + assertTrue(!error.getMessage().contains("password"), "error must not leak the database password"); + } + + @Test + void unsetOrEmptyAddsNoDataSourceProperties() { + assertEquals(Map.of(), store(null, null).sslDataSourceProperties()); + assertEquals(Map.of(), store("", " ").sslDataSourceProperties()); + } + + @Test + void passesModeAndRootCertToPgjdbc() throws URISyntaxException { + final var ca = fixture("ca.pem"); + assertEquals(Map.of("sslMode", "disable"), store("disable", null).sslDataSourceProperties()); + assertEquals(Map.of("sslMode", "require"), store("require", null).sslDataSourceProperties()); + assertEquals(Map.of("sslMode", "verify-ca", "sslRootCert", ca), store("verify-ca", ca).sslDataSourceProperties()); + assertEquals(Map.of("sslMode", "verify-full", "sslRootCert", ca), store(" verify-full ", ca).sslDataSourceProperties()); + } + + @Test + void acceptsCertificateBundles() throws URISyntaxException { + final var bundle = fixture("ca-bundle.pem"); + assertEquals(bundle, store("verify-full", bundle).sslDataSourceProperties().get("sslRootCert")); + } + + @Test + void rejectsUnsupportedModes() { + for (final var mode : new String[] {"prefer", "allow", "no-verify", "VERIFY-FULL", "true"}) { + assertRejected(mode, null, "Unsupported PLANDEV_DB_SSL_MODE"); + } + } + + @Test + void rejectsInconsistentSettings() throws URISyntaxException { + final var ca = fixture("ca.pem"); + assertRejected(null, ca, "PLANDEV_DB_SSL_MODE is not"); + assertRejected("disable", ca, "\"disable\""); + assertRejected("verify-ca", null, "PLANDEV_DB_SSL_ROOT_CERT is not set"); + assertRejected("verify-full", "", "PLANDEV_DB_SSL_ROOT_CERT is not set"); + } + + @Test + void rejectsBadRootCertFiles() throws IOException, URISyntaxException { + final var empty = Files.writeString(tempDir.resolve("empty.pem"), ""); + final var notPem = Files.writeString(tempDir.resolve("not-pem.pem"), "not a certificate\n"); + assertRejected("verify-full", tempDir.resolve("missing.pem").toString(), "does not exist"); + assertRejected("verify-full", tempDir.toString(), "does not exist or is not a regular file"); + assertRejected("verify-full", empty.toString(), "does not contain a PEM certificate"); + assertRejected("verify-full", notPem.toString(), "does not contain a PEM certificate"); + assertRejected("verify-full", fixture("malformed.pem"), "contains an invalid certificate"); + assertRejected("require", tempDir.resolve("missing.pem").toString(), "does not exist"); + } + + @Test + void rejectsUnreadableRootCert() throws IOException, URISyntaxException { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"), "needs POSIX permissions"); + assumeFalse("root".equals(System.getProperty("user.name")), "root can read any file"); + final var unreadable = Files.copy(Path.of(fixture("ca.pem")), tempDir.resolve("unreadable.pem")); + Files.setPosixFilePermissions(unreadable, PosixFilePermissions.fromString("---------")); + assertRejected("verify-full", unreadable.toString(), "could not be read"); + } +} diff --git a/merlin-server/src/test/resources/db-ssl/ca-bundle.pem b/merlin-server/src/test/resources/db-ssl/ca-bundle.pem new file mode 100644 index 0000000000..3b353bbc69 --- /dev/null +++ b/merlin-server/src/test/resources/db-ssl/ca-bundle.pem @@ -0,0 +1,24 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUbGEWeq6Xzxp59KHODchUVIWKFgQwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMiAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAyIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASo4JEM +8UNL84RLUJPZBEL/jaxcSsr6Qutz0k7VUZG4HnikGVucW32MhhP7vRlK6aKow67A +A4brJtYhPeThd/0eo1MwUTAdBgNVHQ4EFgQUoDSl2JSoMenheDt51+4KF0rMZyYw +HwYDVR0jBBgwFoAUoDSl2JSoMenheDt51+4KF0rMZyYwDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEAnwI6yU1I82uJVH/JwN2f6plMY2/UDLldT/nh +K9qQO14CIQC4TmDym8OVQJIwxoqi76dSCr0aDlHHeeXeMvklwU7+lA== +-----END CERTIFICATE----- diff --git a/merlin-server/src/test/resources/db-ssl/ca.pem b/merlin-server/src/test/resources/db-ssl/ca.pem new file mode 100644 index 0000000000..afe69fa455 --- /dev/null +++ b/merlin-server/src/test/resources/db-ssl/ca.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- diff --git a/merlin-server/src/test/resources/db-ssl/malformed.pem b/merlin-server/src/test/resources/db-ssl/malformed.pem new file mode 100644 index 0000000000..39ae6744f9 --- /dev/null +++ b/merlin-server/src/test/resources/db-ssl/malformed.pem @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +TUlJQm5vdCBhIHJlYWwgY2VydGlmaWNhdGU= +-----END CERTIFICATE----- diff --git a/merlin-worker/src/main/java/gov/nasa/ammos/plandev/merlin/worker/MerlinWorkerAppDriver.java b/merlin-worker/src/main/java/gov/nasa/ammos/plandev/merlin/worker/MerlinWorkerAppDriver.java index 7aed0fb6ae..c34eeabf4e 100644 --- a/merlin-worker/src/main/java/gov/nasa/ammos/plandev/merlin/worker/MerlinWorkerAppDriver.java +++ b/merlin-worker/src/main/java/gov/nasa/ammos/plandev/merlin/worker/MerlinWorkerAppDriver.java @@ -41,6 +41,7 @@ public static void main(String[] args) throws InterruptedException { hikariConfig.addDataSourceProperty("portNumber", postgresStore.port()); hikariConfig.addDataSourceProperty("databaseName", postgresStore.database()); hikariConfig.addDataSourceProperty("applicationName", "Merlin Server"); + postgresStore.sslDataSourceProperties().forEach(hikariConfig::addDataSourceProperty); hikariConfig.setUsername(postgresStore.user()); hikariConfig.setPassword(postgresStore.password()); hikariConfig.setMaximumPoolSize(3); @@ -136,7 +137,9 @@ private static WorkerAppConfiguration loadConfiguration() { getEnv("PLANDEV_DB_HOST", getEnv("AERIE_DB_HOST", "postgres")), Integer.parseInt(getEnv("PLANDEV_DB_PORT", getEnv("AERIE_DB_PORT", "5432"))), getEnv("MERLIN_DB_USER", ""), - getEnv("MERLIN_DB_PASSWORD", "") + getEnv("MERLIN_DB_PASSWORD", ""), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_MODE")), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_ROOT_CERT")) ), Integer.parseInt(getEnv("SIMULATION_PROGRESS_POLL_PERIOD_MILLIS", "5000")), Instant.parse(getEnv("UNTRUE_PLAN_START", "")) diff --git a/scheduler-server/src/main/java/gov/nasa/ammos/plandev/scheduler/server/SchedulerAppDriver.java b/scheduler-server/src/main/java/gov/nasa/ammos/plandev/scheduler/server/SchedulerAppDriver.java index 464bf76828..ecda7b0401 100644 --- a/scheduler-server/src/main/java/gov/nasa/ammos/plandev/scheduler/server/SchedulerAppDriver.java +++ b/scheduler-server/src/main/java/gov/nasa/ammos/plandev/scheduler/server/SchedulerAppDriver.java @@ -1,6 +1,7 @@ package gov.nasa.ammos.plandev.scheduler.server; import java.net.URI; +import java.util.Optional; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import gov.nasa.ammos.plandev.permissions.PermissionsService; @@ -133,6 +134,7 @@ private static Stores loadStores( hikariConfig.addDataSourceProperty("portNumber", pgStore.port()); hikariConfig.addDataSourceProperty("databaseName", pgStore.database()); hikariConfig.addDataSourceProperty("applicationName", "Scheduler Server"); + pgStore.sslDataSourceProperties().forEach(hikariConfig::addDataSourceProperty); hikariConfig.setUsername(pgStore.user()); hikariConfig.setPassword(pgStore.password()); @@ -178,7 +180,9 @@ private static AppConfiguration loadConfiguration() { getEnv("PLANDEV_DB_HOST", getEnv("AERIE_DB_HOST", "postgres")), Integer.parseInt(getEnv("PLANDEV_DB_PORT", getEnv("AERIE_DB_PORT", "5432"))), getEnv("SCHEDULER_DB_USER", ""), - getEnv("SCHEDULER_DB_PASSWORD", "") + getEnv("SCHEDULER_DB_PASSWORD", ""), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_MODE")), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_ROOT_CERT")) ), URI.create(getEnv("MERLIN_GRAPHQL_URL", "http://localhost:8080/v1/graphql")), getEnv("HASURA_GRAPHQL_ADMIN_SECRET", "") diff --git a/scheduler-server/src/main/java/gov/nasa/ammos/plandev/scheduler/server/config/PostgresStore.java b/scheduler-server/src/main/java/gov/nasa/ammos/plandev/scheduler/server/config/PostgresStore.java index a458237352..03acdbc4ff 100644 --- a/scheduler-server/src/main/java/gov/nasa/ammos/plandev/scheduler/server/config/PostgresStore.java +++ b/scheduler-server/src/main/java/gov/nasa/ammos/plandev/scheduler/server/config/PostgresStore.java @@ -1,19 +1,121 @@ package gov.nasa.ammos.plandev.scheduler.server.config; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Objects; +import java.util.Optional; +import java.util.Set; +/** + * Connection settings for the PlanDev Postgres database. + * + *

{@code sslMode} and {@code sslRootCert} come from {@code PLANDEV_DB_SSL_MODE} and + * {@code PLANDEV_DB_SSL_ROOT_CERT}. When both are empty no SSL properties are passed to the + * driver, so the pgjdbc default behavior is unchanged. Invalid settings are rejected here so + * that the service fails at startup instead of connecting with weaker settings than requested. + */ public record PostgresStore( String database, String server, Integer port, String user, - String password + String password, + Optional sslMode, + Optional sslRootCert ) implements Store { + /** Accepted values of {@code PLANDEV_DB_SSL_MODE}; these are the libpq/pgjdbc sslmode names. */ + public static final Set SSL_MODES = Set.of("disable", "require", "verify-ca", "verify-full"); + public PostgresStore { Objects.requireNonNull(database); Objects.requireNonNull(server); Objects.requireNonNull(port); Objects.requireNonNull(user); Objects.requireNonNull(password); + Objects.requireNonNull(sslMode); + Objects.requireNonNull(sslRootCert); + + // Treat empty values (e.g. `PLANDEV_DB_SSL_MODE: ""` in a compose file) as unset. + sslMode = sslMode.map(String::strip).filter(s -> !s.isEmpty()); + sslRootCert = sslRootCert.map(String::strip).filter(s -> !s.isEmpty()); + validateSsl(sslMode, sslRootCert); + } + + /** + * pgjdbc data source properties to apply through {@code HikariConfig#addDataSourceProperty}. + * Empty when no SSL settings were provided. + */ + public Map sslDataSourceProperties() { + final var properties = new LinkedHashMap(); + sslMode.ifPresent(mode -> properties.put("sslMode", mode)); + sslRootCert.ifPresent(path -> properties.put("sslRootCert", path)); + return properties; + } + + private static void validateSsl(final Optional sslMode, final Optional sslRootCert) { + if (sslMode.isEmpty()) { + if (sslRootCert.isPresent()) { + throw new IllegalArgumentException( + "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; + } + + final var mode = sslMode.get(); + if (!SSL_MODES.contains(mode)) { + throw new IllegalArgumentException( + "Unsupported PLANDEV_DB_SSL_MODE \"" + mode + "\". Expected one of: disable, require, verify-ca, verify-full."); + } + + if (mode.equals("disable") && sslRootCert.isPresent()) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT is set but PLANDEV_DB_SSL_MODE is \"disable\"."); + } + + if ((mode.equals("verify-ca") || mode.equals("verify-full")) && sslRootCert.isEmpty()) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_MODE is \"" + mode + "\" but PLANDEV_DB_SSL_ROOT_CERT is not set."); + } + + sslRootCert.ifPresent(PostgresStore::validateRootCert); + } + + private static void validateRootCert(final String location) { + final byte[] contents; + try { + final var path = Path.of(location); + if (!Files.isRegularFile(path)) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" does not exist or is not a regular file."); + } + contents = Files.readAllBytes(path); + } catch (final InvalidPathException | IOException | SecurityException e) { + throw new IllegalArgumentException("PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" could not be read.", e); + } + + if (!new String(contents, StandardCharsets.US_ASCII).contains("-----BEGIN CERTIFICATE-----")) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" does not contain a PEM certificate."); + } + try { + final var certificates = CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(contents)); + if (certificates.isEmpty()) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" does not contain a PEM certificate."); + } + } catch (final CertificateException e) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" contains an invalid certificate.", e); + } } } diff --git a/scheduler-server/src/test/java/gov/nasa/ammos/plandev/scheduler/server/config/PostgresStoreTest.java b/scheduler-server/src/test/java/gov/nasa/ammos/plandev/scheduler/server/config/PostgresStoreTest.java new file mode 100644 index 0000000000..fbdfeb0798 --- /dev/null +++ b/scheduler-server/src/test/java/gov/nasa/ammos/plandev/scheduler/server/config/PostgresStoreTest.java @@ -0,0 +1,98 @@ +package gov.nasa.ammos.plandev.scheduler.server.config; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +class PostgresStoreTest { + @TempDir + Path tempDir; + + private static String fixture(final String name) throws URISyntaxException { + return Path.of(PostgresStoreTest.class.getResource("/db-ssl/" + name).toURI()).toString(); + } + + private static PostgresStore store(final String sslMode, final String sslRootCert) { + return new PostgresStore( + "plandev", "postgres", 5432, "user", "password", + Optional.ofNullable(sslMode), Optional.ofNullable(sslRootCert)); + } + + private static void assertRejected(final String sslMode, final String sslRootCert, final String message) { + final var error = assertThrows(IllegalArgumentException.class, () -> store(sslMode, sslRootCert)); + assertTrue(error.getMessage().contains(message), error.getMessage()); + assertTrue(!error.getMessage().contains("password"), "error must not leak the database password"); + } + + @Test + void unsetOrEmptyAddsNoDataSourceProperties() { + assertEquals(Map.of(), store(null, null).sslDataSourceProperties()); + assertEquals(Map.of(), store("", " ").sslDataSourceProperties()); + } + + @Test + void passesModeAndRootCertToPgjdbc() throws URISyntaxException { + final var ca = fixture("ca.pem"); + assertEquals(Map.of("sslMode", "disable"), store("disable", null).sslDataSourceProperties()); + assertEquals(Map.of("sslMode", "require"), store("require", null).sslDataSourceProperties()); + assertEquals(Map.of("sslMode", "verify-ca", "sslRootCert", ca), store("verify-ca", ca).sslDataSourceProperties()); + assertEquals(Map.of("sslMode", "verify-full", "sslRootCert", ca), store(" verify-full ", ca).sslDataSourceProperties()); + } + + @Test + void acceptsCertificateBundles() throws URISyntaxException { + final var bundle = fixture("ca-bundle.pem"); + assertEquals(bundle, store("verify-full", bundle).sslDataSourceProperties().get("sslRootCert")); + } + + @Test + void rejectsUnsupportedModes() { + for (final var mode : new String[] {"prefer", "allow", "no-verify", "VERIFY-FULL", "true"}) { + assertRejected(mode, null, "Unsupported PLANDEV_DB_SSL_MODE"); + } + } + + @Test + void rejectsInconsistentSettings() throws URISyntaxException { + final var ca = fixture("ca.pem"); + assertRejected(null, ca, "PLANDEV_DB_SSL_MODE is not"); + assertRejected("disable", ca, "\"disable\""); + assertRejected("verify-ca", null, "PLANDEV_DB_SSL_ROOT_CERT is not set"); + assertRejected("verify-full", "", "PLANDEV_DB_SSL_ROOT_CERT is not set"); + } + + @Test + void rejectsBadRootCertFiles() throws IOException, URISyntaxException { + final var empty = Files.writeString(tempDir.resolve("empty.pem"), ""); + final var notPem = Files.writeString(tempDir.resolve("not-pem.pem"), "not a certificate\n"); + assertRejected("verify-full", tempDir.resolve("missing.pem").toString(), "does not exist"); + assertRejected("verify-full", tempDir.toString(), "does not exist or is not a regular file"); + assertRejected("verify-full", empty.toString(), "does not contain a PEM certificate"); + assertRejected("verify-full", notPem.toString(), "does not contain a PEM certificate"); + assertRejected("verify-full", fixture("malformed.pem"), "contains an invalid certificate"); + assertRejected("require", tempDir.resolve("missing.pem").toString(), "does not exist"); + } + + @Test + void rejectsUnreadableRootCert() throws IOException, URISyntaxException { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"), "needs POSIX permissions"); + assumeFalse("root".equals(System.getProperty("user.name")), "root can read any file"); + final var unreadable = Files.copy(Path.of(fixture("ca.pem")), tempDir.resolve("unreadable.pem")); + Files.setPosixFilePermissions(unreadable, PosixFilePermissions.fromString("---------")); + assertRejected("verify-full", unreadable.toString(), "could not be read"); + } +} diff --git a/scheduler-server/src/test/resources/db-ssl/ca-bundle.pem b/scheduler-server/src/test/resources/db-ssl/ca-bundle.pem new file mode 100644 index 0000000000..3b353bbc69 --- /dev/null +++ b/scheduler-server/src/test/resources/db-ssl/ca-bundle.pem @@ -0,0 +1,24 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUbGEWeq6Xzxp59KHODchUVIWKFgQwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMiAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAyIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASo4JEM +8UNL84RLUJPZBEL/jaxcSsr6Qutz0k7VUZG4HnikGVucW32MhhP7vRlK6aKow67A +A4brJtYhPeThd/0eo1MwUTAdBgNVHQ4EFgQUoDSl2JSoMenheDt51+4KF0rMZyYw +HwYDVR0jBBgwFoAUoDSl2JSoMenheDt51+4KF0rMZyYwDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEAnwI6yU1I82uJVH/JwN2f6plMY2/UDLldT/nh +K9qQO14CIQC4TmDym8OVQJIwxoqi76dSCr0aDlHHeeXeMvklwU7+lA== +-----END CERTIFICATE----- diff --git a/scheduler-server/src/test/resources/db-ssl/ca.pem b/scheduler-server/src/test/resources/db-ssl/ca.pem new file mode 100644 index 0000000000..afe69fa455 --- /dev/null +++ b/scheduler-server/src/test/resources/db-ssl/ca.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- diff --git a/scheduler-server/src/test/resources/db-ssl/malformed.pem b/scheduler-server/src/test/resources/db-ssl/malformed.pem new file mode 100644 index 0000000000..39ae6744f9 --- /dev/null +++ b/scheduler-server/src/test/resources/db-ssl/malformed.pem @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +TUlJQm5vdCBhIHJlYWwgY2VydGlmaWNhdGU= +-----END CERTIFICATE----- diff --git a/scheduler-worker/src/main/java/gov/nasa/ammos/plandev/scheduler/worker/SchedulerWorkerAppDriver.java b/scheduler-worker/src/main/java/gov/nasa/ammos/plandev/scheduler/worker/SchedulerWorkerAppDriver.java index 82cce35634..e89d1a81a5 100644 --- a/scheduler-worker/src/main/java/gov/nasa/ammos/plandev/scheduler/worker/SchedulerWorkerAppDriver.java +++ b/scheduler-worker/src/main/java/gov/nasa/ammos/plandev/scheduler/worker/SchedulerWorkerAppDriver.java @@ -56,6 +56,7 @@ public static void main(String[] args) throws Exception { hikariConfig.addDataSourceProperty("portNumber", postgresStore.port()); hikariConfig.addDataSourceProperty("databaseName", postgresStore.database()); hikariConfig.addDataSourceProperty("applicationName", "Scheduler Worker"); + postgresStore.sslDataSourceProperties().forEach(hikariConfig::addDataSourceProperty); hikariConfig.setUsername(postgresStore.user()); hikariConfig.setPassword(postgresStore.password()); hikariConfig.setMaximumPoolSize(2); @@ -148,7 +149,9 @@ private static WorkerAppConfiguration loadConfiguration() { getEnv("PLANDEV_DB_HOST", getEnv("AERIE_DB_HOST", "postgres")), Integer.parseInt(getEnv("PLANDEV_DB_PORT", getEnv("AERIE_DB_PORT", "5432"))), getEnv("SCHEDULER_DB_USER", ""), - getEnv("SCHEDULER_DB_PASSWORD", "") + getEnv("SCHEDULER_DB_PASSWORD", ""), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_MODE")), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_ROOT_CERT")) ), URI.create(getEnv("MERLIN_GRAPHQL_URL", "http://localhost:8080/v1/graphql")), Path.of(getEnv("MERLIN_LOCAL_STORE", "/usr/src/app/merlin_file_store")), diff --git a/workspace-server/src/main/java/gov/nasa/ammos/plandev/workspace/server/WorkspaceAppDriver.java b/workspace-server/src/main/java/gov/nasa/ammos/plandev/workspace/server/WorkspaceAppDriver.java index f6b4e5324d..09011cf440 100644 --- a/workspace-server/src/main/java/gov/nasa/ammos/plandev/workspace/server/WorkspaceAppDriver.java +++ b/workspace-server/src/main/java/gov/nasa/ammos/plandev/workspace/server/WorkspaceAppDriver.java @@ -25,6 +25,7 @@ import java.io.StringReader; import java.net.URI; import java.nio.file.Path; +import java.util.Optional; public final class WorkspaceAppDriver { public static void main(final String[] args) { @@ -98,6 +99,7 @@ private static Stores loadStores(final AppConfiguration config) { hikariConfig.addDataSourceProperty("portNumber", c.port()); hikariConfig.addDataSourceProperty("databaseName", c.database()); hikariConfig.addDataSourceProperty("applicationName", "Merlin Server"); + c.sslDataSourceProperties().forEach(hikariConfig::addDataSourceProperty); hikariConfig.setUsername(c.user()); hikariConfig.setPassword(c.password()); @@ -145,7 +147,9 @@ private static AppConfiguration loadConfiguration() { getEnv("PLANDEV_DB_HOST", getEnv("AERIE_DB_HOST", "postgres")), Integer.parseInt(getEnv("PLANDEV_DB_PORT", getEnv("AERIE_DB_PORT", "5432"))), getEnv("SEQUENCING_DB_USER", ""), - getEnv("SEQUENCING_DB_PASSWORD", "") + getEnv("SEQUENCING_DB_PASSWORD", ""), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_MODE")), + Optional.ofNullable(System.getenv("PLANDEV_DB_SSL_ROOT_CERT")) ), RevisionNamingConvention.parseConvention(getEnv("WORKSPACE_REVISION_NAMING_CONVENTION", "NUMERIC")) ); diff --git a/workspace-server/src/main/java/gov/nasa/ammos/plandev/workspace/server/config/PostgresStore.java b/workspace-server/src/main/java/gov/nasa/ammos/plandev/workspace/server/config/PostgresStore.java index 1a2ad8b7d2..2658340b2a 100644 --- a/workspace-server/src/main/java/gov/nasa/ammos/plandev/workspace/server/config/PostgresStore.java +++ b/workspace-server/src/main/java/gov/nasa/ammos/plandev/workspace/server/config/PostgresStore.java @@ -1,19 +1,121 @@ package gov.nasa.ammos.plandev.workspace.server.config; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Objects; +import java.util.Optional; +import java.util.Set; +/** + * Connection settings for the PlanDev Postgres database. + * + *

{@code sslMode} and {@code sslRootCert} come from {@code PLANDEV_DB_SSL_MODE} and + * {@code PLANDEV_DB_SSL_ROOT_CERT}. When both are empty no SSL properties are passed to the + * driver, so the pgjdbc default behavior is unchanged. Invalid settings are rejected here so + * that the service fails at startup instead of connecting with weaker settings than requested. + */ public record PostgresStore( String database, String server, Integer port, String user, - String password + String password, + Optional sslMode, + Optional sslRootCert ) implements Store { + /** Accepted values of {@code PLANDEV_DB_SSL_MODE}; these are the libpq/pgjdbc sslmode names. */ + public static final Set SSL_MODES = Set.of("disable", "require", "verify-ca", "verify-full"); + public PostgresStore { Objects.requireNonNull(database); Objects.requireNonNull(server); Objects.requireNonNull(port); Objects.requireNonNull(user); Objects.requireNonNull(password); + Objects.requireNonNull(sslMode); + Objects.requireNonNull(sslRootCert); + + // Treat empty values (e.g. `PLANDEV_DB_SSL_MODE: ""` in a compose file) as unset. + sslMode = sslMode.map(String::strip).filter(s -> !s.isEmpty()); + sslRootCert = sslRootCert.map(String::strip).filter(s -> !s.isEmpty()); + validateSsl(sslMode, sslRootCert); + } + + /** + * pgjdbc data source properties to apply through {@code HikariConfig#addDataSourceProperty}. + * Empty when no SSL settings were provided. + */ + public Map sslDataSourceProperties() { + final var properties = new LinkedHashMap(); + sslMode.ifPresent(mode -> properties.put("sslMode", mode)); + sslRootCert.ifPresent(path -> properties.put("sslRootCert", path)); + return properties; + } + + private static void validateSsl(final Optional sslMode, final Optional sslRootCert) { + if (sslMode.isEmpty()) { + if (sslRootCert.isPresent()) { + throw new IllegalArgumentException( + "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; + } + + final var mode = sslMode.get(); + if (!SSL_MODES.contains(mode)) { + throw new IllegalArgumentException( + "Unsupported PLANDEV_DB_SSL_MODE \"" + mode + "\". Expected one of: disable, require, verify-ca, verify-full."); + } + + if (mode.equals("disable") && sslRootCert.isPresent()) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT is set but PLANDEV_DB_SSL_MODE is \"disable\"."); + } + + if ((mode.equals("verify-ca") || mode.equals("verify-full")) && sslRootCert.isEmpty()) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_MODE is \"" + mode + "\" but PLANDEV_DB_SSL_ROOT_CERT is not set."); + } + + sslRootCert.ifPresent(PostgresStore::validateRootCert); + } + + private static void validateRootCert(final String location) { + final byte[] contents; + try { + final var path = Path.of(location); + if (!Files.isRegularFile(path)) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" does not exist or is not a regular file."); + } + contents = Files.readAllBytes(path); + } catch (final InvalidPathException | IOException | SecurityException e) { + throw new IllegalArgumentException("PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" could not be read.", e); + } + + if (!new String(contents, StandardCharsets.US_ASCII).contains("-----BEGIN CERTIFICATE-----")) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" does not contain a PEM certificate."); + } + try { + final var certificates = CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(contents)); + if (certificates.isEmpty()) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" does not contain a PEM certificate."); + } + } catch (final CertificateException e) { + throw new IllegalArgumentException( + "PLANDEV_DB_SSL_ROOT_CERT \"" + location + "\" contains an invalid certificate.", e); + } } } diff --git a/workspace-server/src/test/java/gov/nasa/ammos/plandev/workspace/server/config/PostgresStoreTest.java b/workspace-server/src/test/java/gov/nasa/ammos/plandev/workspace/server/config/PostgresStoreTest.java new file mode 100644 index 0000000000..fcd1525c29 --- /dev/null +++ b/workspace-server/src/test/java/gov/nasa/ammos/plandev/workspace/server/config/PostgresStoreTest.java @@ -0,0 +1,98 @@ +package gov.nasa.ammos.plandev.workspace.server.config; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +class PostgresStoreTest { + @TempDir + Path tempDir; + + private static String fixture(final String name) throws URISyntaxException { + return Path.of(PostgresStoreTest.class.getResource("/db-ssl/" + name).toURI()).toString(); + } + + private static PostgresStore store(final String sslMode, final String sslRootCert) { + return new PostgresStore( + "plandev", "postgres", 5432, "user", "password", + Optional.ofNullable(sslMode), Optional.ofNullable(sslRootCert)); + } + + private static void assertRejected(final String sslMode, final String sslRootCert, final String message) { + final var error = assertThrows(IllegalArgumentException.class, () -> store(sslMode, sslRootCert)); + assertTrue(error.getMessage().contains(message), error.getMessage()); + assertTrue(!error.getMessage().contains("password"), "error must not leak the database password"); + } + + @Test + void unsetOrEmptyAddsNoDataSourceProperties() { + assertEquals(Map.of(), store(null, null).sslDataSourceProperties()); + assertEquals(Map.of(), store("", " ").sslDataSourceProperties()); + } + + @Test + void passesModeAndRootCertToPgjdbc() throws URISyntaxException { + final var ca = fixture("ca.pem"); + assertEquals(Map.of("sslMode", "disable"), store("disable", null).sslDataSourceProperties()); + assertEquals(Map.of("sslMode", "require"), store("require", null).sslDataSourceProperties()); + assertEquals(Map.of("sslMode", "verify-ca", "sslRootCert", ca), store("verify-ca", ca).sslDataSourceProperties()); + assertEquals(Map.of("sslMode", "verify-full", "sslRootCert", ca), store(" verify-full ", ca).sslDataSourceProperties()); + } + + @Test + void acceptsCertificateBundles() throws URISyntaxException { + final var bundle = fixture("ca-bundle.pem"); + assertEquals(bundle, store("verify-full", bundle).sslDataSourceProperties().get("sslRootCert")); + } + + @Test + void rejectsUnsupportedModes() { + for (final var mode : new String[] {"prefer", "allow", "no-verify", "VERIFY-FULL", "true"}) { + assertRejected(mode, null, "Unsupported PLANDEV_DB_SSL_MODE"); + } + } + + @Test + void rejectsInconsistentSettings() throws URISyntaxException { + final var ca = fixture("ca.pem"); + assertRejected(null, ca, "PLANDEV_DB_SSL_MODE is not"); + assertRejected("disable", ca, "\"disable\""); + assertRejected("verify-ca", null, "PLANDEV_DB_SSL_ROOT_CERT is not set"); + assertRejected("verify-full", "", "PLANDEV_DB_SSL_ROOT_CERT is not set"); + } + + @Test + void rejectsBadRootCertFiles() throws IOException, URISyntaxException { + final var empty = Files.writeString(tempDir.resolve("empty.pem"), ""); + final var notPem = Files.writeString(tempDir.resolve("not-pem.pem"), "not a certificate\n"); + assertRejected("verify-full", tempDir.resolve("missing.pem").toString(), "does not exist"); + assertRejected("verify-full", tempDir.toString(), "does not exist or is not a regular file"); + assertRejected("verify-full", empty.toString(), "does not contain a PEM certificate"); + assertRejected("verify-full", notPem.toString(), "does not contain a PEM certificate"); + assertRejected("verify-full", fixture("malformed.pem"), "contains an invalid certificate"); + assertRejected("require", tempDir.resolve("missing.pem").toString(), "does not exist"); + } + + @Test + void rejectsUnreadableRootCert() throws IOException, URISyntaxException { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"), "needs POSIX permissions"); + assumeFalse("root".equals(System.getProperty("user.name")), "root can read any file"); + final var unreadable = Files.copy(Path.of(fixture("ca.pem")), tempDir.resolve("unreadable.pem")); + Files.setPosixFilePermissions(unreadable, PosixFilePermissions.fromString("---------")); + assertRejected("verify-full", unreadable.toString(), "could not be read"); + } +} diff --git a/workspace-server/src/test/resources/db-ssl/ca-bundle.pem b/workspace-server/src/test/resources/db-ssl/ca-bundle.pem new file mode 100644 index 0000000000..3b353bbc69 --- /dev/null +++ b/workspace-server/src/test/resources/db-ssl/ca-bundle.pem @@ -0,0 +1,24 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUbGEWeq6Xzxp59KHODchUVIWKFgQwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMiAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAyIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASo4JEM +8UNL84RLUJPZBEL/jaxcSsr6Qutz0k7VUZG4HnikGVucW32MhhP7vRlK6aKow67A +A4brJtYhPeThd/0eo1MwUTAdBgNVHQ4EFgQUoDSl2JSoMenheDt51+4KF0rMZyYw +HwYDVR0jBBgwFoAUoDSl2JSoMenheDt51+4KF0rMZyYwDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEAnwI6yU1I82uJVH/JwN2f6plMY2/UDLldT/nh +K9qQO14CIQC4TmDym8OVQJIwxoqi76dSCr0aDlHHeeXeMvklwU7+lA== +-----END CERTIFICATE----- diff --git a/workspace-server/src/test/resources/db-ssl/ca.pem b/workspace-server/src/test/resources/db-ssl/ca.pem new file mode 100644 index 0000000000..afe69fa455 --- /dev/null +++ b/workspace-server/src/test/resources/db-ssl/ca.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- diff --git a/workspace-server/src/test/resources/db-ssl/malformed.pem b/workspace-server/src/test/resources/db-ssl/malformed.pem new file mode 100644 index 0000000000..39ae6744f9 --- /dev/null +++ b/workspace-server/src/test/resources/db-ssl/malformed.pem @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +TUlJQm5vdCBhIHJlYWwgY2VydGlmaWNhdGU= +-----END CERTIFICATE----- From ba2298bf850a6d961121b7d98aff84681c68e5b1 Mon Sep 17 00:00:00 2001 From: Nikhil Reddy Donapati Date: Mon, 30 Nov 2026 06:49:47 -0600 Subject: [PATCH 2/4] Add optional Postgres TLS settings to the action and sequencing servers Map PLANDEV_DB_SSL_MODE and PLANDEV_DB_SSL_ROOT_CERT to the node-postgres ssl option for the action-server pool, the per-action worker pool and the sequencing-server pool. The ssl key is omitted when both variables are unset, so the node-postgres default (including PGSSLMODE) is unchanged. verify-ca keeps chain verification and skips only the host name check. The helper is duplicated in each server rather than shared, as agreed on the issue. Refs #1773 --- action-server/src/config.ts | 4 + action-server/src/db.ts | 9 +- action-server/src/threads/worker.ts | 8 +- action-server/src/utils/dbSsl.ts | 104 +++++++++++++++++ action-server/tests/dbPoolDefault.test.mts | 37 ++++++ action-server/tests/dbPoolSsl.test.mts | 48 ++++++++ action-server/tests/dbSsl.test.mts | 91 +++++++++++++++ .../tests/fixtures/db-ssl/ca-bundle.pem | 24 ++++ action-server/tests/fixtures/db-ssl/ca.pem | 12 ++ .../tests/fixtures/db-ssl/malformed.pem | 3 + sequencing-server/src/db.ts | 11 +- sequencing-server/src/env.ts | 8 ++ sequencing-server/src/utils/dbSsl.ts | 107 ++++++++++++++++++ sequencing-server/test/db-ssl.spec.ts | 65 +++++++++++ .../test/fixtures/db-ssl/ca-bundle.pem | 24 ++++ sequencing-server/test/fixtures/db-ssl/ca.pem | 12 ++ .../test/fixtures/db-ssl/malformed.pem | 3 + 17 files changed, 567 insertions(+), 3 deletions(-) create mode 100644 action-server/src/utils/dbSsl.ts create mode 100644 action-server/tests/dbPoolDefault.test.mts create mode 100644 action-server/tests/dbPoolSsl.test.mts create mode 100644 action-server/tests/dbSsl.test.mts create mode 100644 action-server/tests/fixtures/db-ssl/ca-bundle.pem create mode 100644 action-server/tests/fixtures/db-ssl/ca.pem create mode 100644 action-server/tests/fixtures/db-ssl/malformed.pem create mode 100644 sequencing-server/src/utils/dbSsl.ts create mode 100644 sequencing-server/test/db-ssl.spec.ts create mode 100644 sequencing-server/test/fixtures/db-ssl/ca-bundle.pem create mode 100644 sequencing-server/test/fixtures/db-ssl/ca.pem create mode 100644 sequencing-server/test/fixtures/db-ssl/malformed.pem diff --git a/action-server/src/config.ts b/action-server/src/config.ts index 47b691e711..c8c0291c00 100644 --- a/action-server/src/config.ts +++ b/action-server/src/config.ts @@ -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; @@ -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 ?? "", diff --git a/action-server/src/db.ts b/action-server/src/db.ts index 70d3a4d0a0..b7ace5e081 100644 --- a/action-server/src/db.ts +++ b/action-server/src/db.ts @@ -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); export class ActionsDbManager { private static pool: Pool; @@ -23,6 +29,7 @@ export class ActionsDbManager { password: ACTION_DB_PASSWORD, max: 3, min: 3, + ...(ssl === undefined ? {} : { ssl }), }); return ActionsDbManager.pool; } catch (error) { diff --git a/action-server/src/threads/worker.ts b/action-server/src/threads/worker.ts index 07a120262e..523e3bcb84 100644 --- a/action-server/src/threads/worker.ts +++ b/action-server/src/threads/worker.ts @@ -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); let dbPool: pg.Pool | null = null; let dbClient: pg.PoolClient | null = null; @@ -27,6 +32,7 @@ function getDbPool() { // should have exactly one client/connection min: 1, max: 1, + ...(ssl === undefined ? {} : { ssl }), }); dbPool.on("error", (err) => { diff --git a/action-server/src/utils/dbSsl.ts b/action-server/src/utils/dbSsl.ts new file mode 100644 index 0000000000..94463b6d80 --- /dev/null +++ b/action-server/src/utils/dbSsl.ts @@ -0,0 +1,104 @@ +import { X509Certificate } from "node:crypto"; +import { readFileSync, statSync } from "node:fs"; +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.`); + } + + 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): 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 }; + } + } +} diff --git a/action-server/tests/dbPoolDefault.test.mts b/action-server/tests/dbPoolDefault.test.mts new file mode 100644 index 0000000000..381abff120 --- /dev/null +++ b/action-server/tests/dbPoolDefault.test.mts @@ -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[] = []; + +class FakePool { + constructor(options: Record) { + 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"); + } +}); diff --git a/action-server/tests/dbPoolSsl.test.mts b/action-server/tests/dbPoolSsl.test.mts new file mode 100644 index 0000000000..6ba7c248ee --- /dev/null +++ b/action-server/tests/dbPoolSsl.test.mts @@ -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[] = []; + +class FakePool { + constructor(options: Record) { + 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); +}); diff --git a/action-server/tests/dbSsl.test.mts b/action-server/tests/dbSsl.test.mts new file mode 100644 index 0000000000..06ed6394a5 --- /dev/null +++ b/action-server/tests/dbSsl.test.mts @@ -0,0 +1,91 @@ +import assert from "assert"; +import { chmodSync, copyFileSync, mkdtempSync, 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 } = dbSsl; + +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(ssl.checkServerIdentity, undefined); + }); + + 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 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/); + }); +}); diff --git a/action-server/tests/fixtures/db-ssl/ca-bundle.pem b/action-server/tests/fixtures/db-ssl/ca-bundle.pem new file mode 100644 index 0000000000..3b353bbc69 --- /dev/null +++ b/action-server/tests/fixtures/db-ssl/ca-bundle.pem @@ -0,0 +1,24 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUbGEWeq6Xzxp59KHODchUVIWKFgQwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMiAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAyIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASo4JEM +8UNL84RLUJPZBEL/jaxcSsr6Qutz0k7VUZG4HnikGVucW32MhhP7vRlK6aKow67A +A4brJtYhPeThd/0eo1MwUTAdBgNVHQ4EFgQUoDSl2JSoMenheDt51+4KF0rMZyYw +HwYDVR0jBBgwFoAUoDSl2JSoMenheDt51+4KF0rMZyYwDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEAnwI6yU1I82uJVH/JwN2f6plMY2/UDLldT/nh +K9qQO14CIQC4TmDym8OVQJIwxoqi76dSCr0aDlHHeeXeMvklwU7+lA== +-----END CERTIFICATE----- diff --git a/action-server/tests/fixtures/db-ssl/ca.pem b/action-server/tests/fixtures/db-ssl/ca.pem new file mode 100644 index 0000000000..afe69fa455 --- /dev/null +++ b/action-server/tests/fixtures/db-ssl/ca.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- diff --git a/action-server/tests/fixtures/db-ssl/malformed.pem b/action-server/tests/fixtures/db-ssl/malformed.pem new file mode 100644 index 0000000000..39ae6744f9 --- /dev/null +++ b/action-server/tests/fixtures/db-ssl/malformed.pem @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +TUlJQm5vdCBhIHJlYWwgY2VydGlmaWNhdGU= +-----END CERTIFICATE----- diff --git a/sequencing-server/src/db.ts b/sequencing-server/src/db.ts index 76ceeaa2ef..04e097f93f 100644 --- a/sequencing-server/src/db.ts +++ b/sequencing-server/src/db.ts @@ -2,6 +2,7 @@ import type { Pool, PoolConfig } from 'pg'; import pg from 'pg'; import getLogger from './utils/logger.js'; import { getEnv } from './env.js'; +import { getDbSslConfig } from './utils/dbSsl.js'; const { Pool: DbPool } = pg; @@ -9,12 +10,18 @@ const { PLANDEV_DB: database, PLANDEV_DB_HOST: host, PLANDEV_DB_PORT: port, + PLANDEV_DB_SSL_MODE: sslMode, + PLANDEV_DB_SSL_ROOT_CERT: sslRootCert, SEQUENCING_DB_USER: user, SEQUENCING_DB_PASSWORD: password, } = getEnv(); const logger = getLogger('packages/db/db'); +// Validated at import time (outside init's try/catch) so an invalid TLS configuration fails at startup. +// `undefined` means unset: the `ssl` key is omitted to keep node-postgres defaults. +const ssl = getDbSslConfig(sslMode, sslRootCert); + export class DbExpansion { private static pool: Pool; @@ -30,6 +37,7 @@ export class DbExpansion { password, port: parseInt(port, 10), user, + ...(ssl === undefined ? {} : { ssl }), }; logger.info(`Postgres Config:`); @@ -37,7 +45,8 @@ export class DbExpansion { { database: ${config.database}, host: ${config.host}, - port: ${config.port} + port: ${config.port}, + sslMode: ${sslMode.trim() || '(unset)'} }`); DbExpansion.pool = new DbPool(config); diff --git a/sequencing-server/src/env.ts b/sequencing-server/src/env.ts index ebcf479fc7..0670a4ea42 100644 --- a/sequencing-server/src/env.ts +++ b/sequencing-server/src/env.ts @@ -12,6 +12,8 @@ export type Env = { PLANDEV_DB: string; PLANDEV_DB_HOST: string; PLANDEV_DB_PORT: string; + PLANDEV_DB_SSL_MODE: string; + PLANDEV_DB_SSL_ROOT_CERT: string; SEQUENCING_DB_USER: string; SEQUENCING_DB_PASSWORD: string; SEQUENCING_LANGUAGE: SequencingLanguage; @@ -30,6 +32,8 @@ export const defaultEnv: Env = { PLANDEV_DB: 'plandev', PLANDEV_DB_HOST: 'localhost', PLANDEV_DB_PORT: '5432', + PLANDEV_DB_SSL_MODE: '', + PLANDEV_DB_SSL_ROOT_CERT: '', SEQUENCING_DB_PASSWORD: '', SEQUENCING_DB_USER: '', SEQUENCING_LANGUAGE: "SeqN" as SequencingLanguage, @@ -49,6 +53,8 @@ export function getEnv(): Env { const PLANDEV_DB = env['PLANDEV_DB'] ?? env['AERIE_DB'] ?? defaultEnv.PLANDEV_DB; const PLANDEV_DB_HOST = env['PLANDEV_DB_HOST'] ?? env['AERIE_DB_HOST'] ?? defaultEnv.PLANDEV_DB_HOST; const PLANDEV_DB_PORT = env['PLANDEV_DB_PORT'] ?? env['AERIE_DB_PORT'] ?? defaultEnv.PLANDEV_DB_PORT; + const PLANDEV_DB_SSL_MODE = env['PLANDEV_DB_SSL_MODE'] ?? defaultEnv.PLANDEV_DB_SSL_MODE; + const PLANDEV_DB_SSL_ROOT_CERT = env['PLANDEV_DB_SSL_ROOT_CERT'] ?? defaultEnv.PLANDEV_DB_SSL_ROOT_CERT; const SEQUENCING_DB_USER = env['SEQUENCING_DB_USER'] ?? defaultEnv.SEQUENCING_DB_USER; const SEQUENCING_DB_PASSWORD = env['SEQUENCING_DB_PASSWORD'] ?? defaultEnv.SEQUENCING_DB_PASSWORD; const SEQUENCING_LANGUAGE = env['SEQUENCING_LANGUAGE'] as SequencingLanguage ?? defaultEnv.SEQUENCING_LANGUAGE; @@ -65,6 +71,8 @@ export function getEnv(): Env { PLANDEV_DB, PLANDEV_DB_HOST, PLANDEV_DB_PORT, + PLANDEV_DB_SSL_MODE, + PLANDEV_DB_SSL_ROOT_CERT, SEQUENCING_DB_USER, SEQUENCING_DB_PASSWORD, SEQUENCING_LANGUAGE, diff --git a/sequencing-server/src/utils/dbSsl.ts b/sequencing-server/src/utils/dbSsl.ts new file mode 100644 index 0000000000..c3843b6d89 --- /dev/null +++ b/sequencing-server/src/utils/dbSsl.ts @@ -0,0 +1,107 @@ +import { X509Certificate } from 'node:crypto'; +import { readFileSync, statSync } from 'node:fs'; +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.`); + } + + 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, +): 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 }; + } + } +} diff --git a/sequencing-server/test/db-ssl.spec.ts b/sequencing-server/test/db-ssl.spec.ts new file mode 100644 index 0000000000..6530a27fcd --- /dev/null +++ b/sequencing-server/test/db-ssl.spec.ts @@ -0,0 +1,65 @@ +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { getDbSslConfig } from '../src/utils/dbSsl.js'; + +const fixtures = join(process.cwd(), 'test', 'fixtures', 'db-ssl'); +const caPath = join(fixtures, 'ca.pem'); +const scratch = mkdtempSync(join(tmpdir(), 'db-ssl-')); + +describe('getDbSslConfig', () => { + it('keeps the node-postgres default when unset or empty', () => { + expect(getDbSslConfig(undefined, undefined)).toBeUndefined(); + expect(getDbSslConfig('', '')).toBeUndefined(); + }); + + it('maps each mode to the node-postgres ssl option', () => { + expect(getDbSslConfig('disable', '')).toBe(false); + expect(getDbSslConfig('require', '')).toEqual({ rejectUnauthorized: false }); + + const verifyCa = getDbSslConfig('verify-ca', caPath); + expect(verifyCa).toMatchObject({ rejectUnauthorized: true }); + expect(verifyCa && verifyCa.ca).toHaveLength(1); + expect(verifyCa && verifyCa.checkServerIdentity?.('any-host', {} as never)).toBeUndefined(); + + const verifyFull = getDbSslConfig('verify-full', join(fixtures, 'ca-bundle.pem')); + expect(verifyFull).toMatchObject({ rejectUnauthorized: true }); + expect(verifyFull && verifyFull.ca).toHaveLength(2); + expect(verifyFull && verifyFull.checkServerIdentity).toBeUndefined(); + }); + + it('rejects invalid configuration', () => { + const notPem = join(scratch, 'not-pem.pem'); + writeFileSync(notPem, 'not a certificate\n'); + + expect(() => getDbSslConfig('prefer', '')).toThrow(/Unsupported PLANDEV_DB_SSL_MODE/); + expect(() => getDbSslConfig('', caPath)).toThrow(/PLANDEV_DB_SSL_MODE is not/); + expect(() => getDbSslConfig('disable', caPath)).toThrow(/"disable"/); + expect(() => getDbSslConfig('verify-full', '')).toThrow(/PLANDEV_DB_SSL_ROOT_CERT is not set/); + expect(() => getDbSslConfig('verify-ca', join(scratch, 'missing.pem'))).toThrow(/could not be read/); + expect(() => getDbSslConfig('verify-full', notPem)).toThrow(/does not contain a PEM certificate/); + expect(() => getDbSslConfig('verify-full', join(fixtures, 'malformed.pem'))).toThrow( + /contains an invalid certificate/, + ); + }); +}); + +describe('sequencing-server pool', () => { + const saved = { ...process.env }; + afterAll(() => { + process.env = saved; + }); + + it('passes the TLS settings to node-postgres', async () => { + process.env['PLANDEV_DB_SSL_MODE'] = 'verify-full'; + process.env['PLANDEV_DB_SSL_ROOT_CERT'] = caPath; + const { DbExpansion } = await import('../src/db.js'); + DbExpansion.init(); // creates the pool without connecting + const ssl = (DbExpansion.getDb() as unknown as { options: { ssl?: { rejectUnauthorized: boolean; ca: string[] } } }) + .options.ssl; + expect(ssl).toBeDefined(); + expect(ssl?.rejectUnauthorized).toBe(true); + expect(ssl?.ca).toHaveLength(1); + await DbExpansion.getDb().end(); + }); +}); diff --git a/sequencing-server/test/fixtures/db-ssl/ca-bundle.pem b/sequencing-server/test/fixtures/db-ssl/ca-bundle.pem new file mode 100644 index 0000000000..3b353bbc69 --- /dev/null +++ b/sequencing-server/test/fixtures/db-ssl/ca-bundle.pem @@ -0,0 +1,24 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUbGEWeq6Xzxp59KHODchUVIWKFgQwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMiAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAyIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASo4JEM +8UNL84RLUJPZBEL/jaxcSsr6Qutz0k7VUZG4HnikGVucW32MhhP7vRlK6aKow67A +A4brJtYhPeThd/0eo1MwUTAdBgNVHQ4EFgQUoDSl2JSoMenheDt51+4KF0rMZyYw +HwYDVR0jBBgwFoAUoDSl2JSoMenheDt51+4KF0rMZyYwDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEAnwI6yU1I82uJVH/JwN2f6plMY2/UDLldT/nh +K9qQO14CIQC4TmDym8OVQJIwxoqi76dSCr0aDlHHeeXeMvklwU7+lA== +-----END CERTIFICATE----- diff --git a/sequencing-server/test/fixtures/db-ssl/ca.pem b/sequencing-server/test/fixtures/db-ssl/ca.pem new file mode 100644 index 0000000000..afe69fa455 --- /dev/null +++ b/sequencing-server/test/fixtures/db-ssl/ca.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAXmgAwIBAgIUcw+S3MQknlCz6tE0OzuMG+h8rkEwCgYIKoZIzj0EAwIw +PjE8MDoGA1UEAwwzUGxhbkRldiB0ZXN0IGZpeHR1cmUgQ0EgMSAocHVibGljIGNl +cnRpZmljYXRlIG9ubHkpMCAXDTI2MTEzMDEyMzExM1oYDzIxMjYxMTA2MTIzMTEz +WjA+MTwwOgYDVQQDDDNQbGFuRGV2IHRlc3QgZml4dHVyZSBDQSAxIChwdWJsaWMg +Y2VydGlmaWNhdGUgb25seSkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR1GCw1 +CxNm5R1rrMt9X8rxUFHxJCG8O78UJBDgpLTUomET86B3hrlXwntnKUdT5PQb6X4W +KaehR9Am/4uFEpe8o1MwUTAdBgNVHQ4EFgQUZpFnRjTGOHawYoxEo2hId8IAAr4w +HwYDVR0jBBgwFoAUZpFnRjTGOHawYoxEo2hId8IAAr4wDwYDVR0TAQH/BAUwAwEB +/zAKBggqhkjOPQQDAgNJADBGAiEApEEsxaqvOXhMDO65T0sXYqtKOlHhL7kDh9U4 +Ht3B66kCIQDUZqz8Ce6n31+yQ6WE95MmuDJ8sQoABLRWY0Kh58HlFg== +-----END CERTIFICATE----- diff --git a/sequencing-server/test/fixtures/db-ssl/malformed.pem b/sequencing-server/test/fixtures/db-ssl/malformed.pem new file mode 100644 index 0000000000..39ae6744f9 --- /dev/null +++ b/sequencing-server/test/fixtures/db-ssl/malformed.pem @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +TUlJQm5vdCBhIHJlYWwgY2VydGlmaWNhdGU= +-----END CERTIFICATE----- From 7bb3261923c56398358a8b517965aaa8da88c258 Mon Sep 17 00:00:00 2001 From: Nikhil Reddy Donapati Date: Mon, 30 Nov 2026 06:49:47 -0600 Subject: [PATCH 3/4] Document Postgres TLS settings and add commented deployment examples Refs #1773 --- deployment/Environment.md | 58 +++++++++++++++++++ deployment/docker-compose.yml | 35 +++++++++++ deployment/kubernetes/hasura-deployment.yaml | 3 + .../kubernetes/plandev-action-deployment.yaml | 8 +++ .../plandev-gateway-deployment.yaml | 8 +++ .../kubernetes/plandev-merlin-deployment.yaml | 8 +++ .../plandev-merlin-worker-deployment.yaml | 8 +++ .../plandev-scheduler-deployment.yaml | 8 +++ .../plandev-scheduler-worker-deployment.yaml | 8 +++ .../plandev-sequencing-deployment.yaml | 8 +++ .../plandev-workspace-deployment.yaml | 8 +++ 11 files changed, 160 insertions(+) diff --git a/deployment/Environment.md b/deployment/Environment.md index 1c696bc743..d41a5fe4ee 100644 --- a/deployment/Environment.md +++ b/deployment/Environment.md @@ -11,6 +11,7 @@ This document provides detailed information about environment variables for each - [PlanDev UI](#plandev-ui) - [Hasura](#hasura) - [Postgres](#postgres) +- [Database TLS](#database-tls) ## PlanDev Gateway @@ -23,6 +24,8 @@ See the [environment variables document](https://github.com/NASA-AMMOS/plandev-g | `PLANDEV_DB` | The name of the PlanDev DB | `string` | plandev | | `PLANDEV_DB_HOST` | The DB instance that Merlin will connect with | `string` | postgres | | `PLANDEV_DB_PORT` | The DB instance port number that Merlin will connect with | `number` | 5432 | +| `PLANDEV_DB_SSL_MODE` | TLS mode for Postgres connections: `disable`, `require`, `verify-ca` or `verify-full`. See [Database TLS](#database-tls) | `string` | (unset) | +| `PLANDEV_DB_SSL_ROOT_CERT` | Path to a PEM CA certificate (bundle) used to verify the Postgres server. Required for `verify-ca` and `verify-full` | `string` | (unset) | | `JAVA_OPTS` | Configuration for Merlin's logging level and output file | `string` | log level: warn. output: stderr | | `MERLIN_PORT` | Port number for the Merlin server | `number` | 27183 | | `MERLIN_LOCAL_STORE` | Local storage for Merlin in the container | `string` | /usr/src/app/merlin_file_store | @@ -39,6 +42,8 @@ See the [environment variables document](https://github.com/NASA-AMMOS/plandev-g | `PLANDEV_DB` | The name of the PlanDev DB | `string` | plandev | | `PLANDEV_DB_HOST` | The DB instance that Merlin will connect with | `string` | postgres | | `PLANDEV_DB_PORT` | The DB instance port number that Merlin will connect with | `number` | 5432 | +| `PLANDEV_DB_SSL_MODE` | TLS mode for Postgres connections: `disable`, `require`, `verify-ca` or `verify-full`. See [Database TLS](#database-tls) | `string` | (unset) | +| `PLANDEV_DB_SSL_ROOT_CERT` | Path to a PEM CA certificate (bundle) used to verify the Postgres server. Required for `verify-ca` and `verify-full` | `string` | (unset) | | `JAVA_OPTS` | Configuration for Merlin's logging level and output file | `string` | log level: warn. output: stderr | | `MERLIN_WORKER_LOCAL_STORE` | The local storage as for the Merlin container | `string` | /usr/src/app/merlin_file_store | | `MERLIN_DB_USER` | Username of the Merlin DB User | `string` | merlin_service | @@ -53,6 +58,8 @@ See the [environment variables document](https://github.com/NASA-AMMOS/plandev-g | `PLANDEV_DB` | The name of the PlanDev DB | `string` | plandev | | `PLANDEV_DB_HOST` | The DB instance that the Scheduler will connect with | `string` | postgres | | `PLANDEV_DB_PORT` | The DB instance port number that the Scheduler will connect with | `number` | 5432 | +| `PLANDEV_DB_SSL_MODE` | TLS mode for Postgres connections: `disable`, `require`, `verify-ca` or `verify-full`. See [Database TLS](#database-tls) | `string` | (unset) | +| `PLANDEV_DB_SSL_ROOT_CERT` | Path to a PEM CA certificate (bundle) used to verify the Postgres server. Required for `verify-ca` and `verify-full` | `string` | (unset) | | `HASURA_GRAPHQL_ADMIN_SECRET` | The admin secret for Hasura which gives admin access if used. | `string` | | | `JAVA_OPTS` | Configuration for the scheduler's logging level and output file | `string` | log level: warn. output: stderr | | `MERLIN_GRAPHQL_URL` | URI of the Merlin graphql interface to call | `string` | http://hasura:8080/v1/graphql | @@ -67,6 +74,8 @@ See the [environment variables document](https://github.com/NASA-AMMOS/plandev-g | `PLANDEV_DB` | The name of the PlanDev DB | `string` | plandev | | `PLANDEV_DB_HOST` | The DB instance that the Scheduler will connect with | `string` | postgres | | `PLANDEV_DB_PORT` | The DB instance port number that the Scheduler will connect with | `number` | 5432 | +| `PLANDEV_DB_SSL_MODE` | TLS mode for Postgres connections: `disable`, `require`, `verify-ca` or `verify-full`. See [Database TLS](#database-tls) | `string` | (unset) | +| `PLANDEV_DB_SSL_ROOT_CERT` | Path to a PEM CA certificate (bundle) used to verify the Postgres server. Required for `verify-ca` and `verify-full` | `string` | (unset) | | `HASURA_GRAPHQL_ADMIN_SECRET` | The admin secret for Hasura which gives admin access if used. | `string` | | | `JAVA_OPTS` | Configuration for the scheduler's logging level and output file | `string` | log level: warn. output: stderr | | `MERLIN_GRAPHQL_URL` | URI of the Merlin graphql interface to call | `string` | http://hasura:8080/v1/graphql | @@ -83,6 +92,8 @@ See the [environment variables document](https://github.com/NASA-AMMOS/plandev-g | `PLANDEV_DB` | The name of the PlanDev DB | `string` | plandev | | `PLANDEV_DB_HOST` | Hostname of Postgres instance | `string` | postgres | | `PLANDEV_DB_PORT` | Port of Postgres instance | `number` | 5432 | +| `PLANDEV_DB_SSL_MODE` | TLS mode for Postgres connections: `disable`, `require`, `verify-ca` or `verify-full`. See [Database TLS](#database-tls) | `string` | (unset) | +| `PLANDEV_DB_SSL_ROOT_CERT` | Path to a PEM CA certificate (bundle) used to verify the Postgres server. Required for `verify-ca` and `verify-full` | `string` | (unset) | | `HASURA_GRAPHQL_ADMIN_SECRET` | The admin secret for Hasura which gives admin access if used. | `string` | | | `LOG_FILE` | Either an output filepath to log to, or 'console' | `string` | console | | `LOG_LEVEL` | Logging level for filtering logs | `string` | warn | @@ -99,6 +110,8 @@ See the [environment variables document](https://github.com/NASA-AMMOS/plandev-g | `PLANDEV_DB` | The name of the PlanDev DB | `string` | plandev | | `PLANDEV_DB_HOST` | Hostname of Postgres instance | `string` | postgres | | `PLANDEV_DB_PORT` | Port of Postgres instance | `number` | 5432 | +| `PLANDEV_DB_SSL_MODE` | TLS mode for Postgres connections: `disable`, `require`, `verify-ca` or `verify-full`. See [Database TLS](#database-tls) | `string` | (unset) | +| `PLANDEV_DB_SSL_ROOT_CERT` | Path to a PEM CA certificate (bundle) used to verify the Postgres server. Required for `verify-ca` and `verify-full` | `string` | (unset) | | `SEQUENCING_DB_USER` | Username of the Sequencing DB User | `string` | sequencing_service | | `SEQUENCING_DB_PASSWORD` | Password of the Sequencing DB User | `string` | | | `WORKSPACE_STORE` | Local storage for Workspace files within the contaner | `string` | /usr/src/ws | @@ -119,6 +132,8 @@ Plandev UI container to the same value, or else the UI will not behave correctly | `PLANDEV_DB` | The name of the PlanDev DB | `string` | plandev | | `PLANDEV_DB_HOST` | Hostname of Postgres instance | `string` | postgres | | `PLANDEV_DB_PORT` | Port of Postgres instance | `number` | 5432 | +| `PLANDEV_DB_SSL_MODE` | TLS mode for Postgres connections: `disable`, `require`, `verify-ca` or `verify-full`. See [Database TLS](#database-tls) | `string` | (unset) | +| `PLANDEV_DB_SSL_ROOT_CERT` | Path to a PEM CA certificate (bundle) used to verify the Postgres server. Required for `verify-ca` and `verify-full` | `string` | (unset) | | `ACTION_COOKIE_NAMES` | Comma-separated list of browser cookie names to extract and forward to actions as secrets (e.g. `ssosession`) | `string` | | | `ACTION_CORS_ALLOWED_ORIGIN` | Allowed CORS origin for the action server. If unset, reflects the request's `Origin` header | `string` | | | `ACTION_DB_USER` | Username of the Action Server DB User | `string` | | @@ -169,3 +184,46 @@ The default PlanDev deployment uses the default Postgres environment. See the [D | `SEQUENCING_DB_PASSWORD` | Password of the Sequencing DB User | `string` | [svelte-kit-adapter-node-docs]: https://github.com/sveltejs/kit/blob/master/packages/adapter-node/README.md + +## Database TLS + +TLS between PlanDev services and Postgres is opt-in. Set the same two variables on every service that connects to Postgres (Merlin, Merlin Worker, Scheduler, Scheduler Worker, Sequencing, Workspaces, Action Server and the [Gateway](https://github.com/NASA-AMMOS/plandev-gateway/blob/develop/docs/ENVIRONMENT.md)), and configure Hasura through its connection URLs as described below. + +| `PLANDEV_DB_SSL_MODE` | Encrypted | Server certificate chain verified | Host name verified | +|-----------------------|-----------|-----------------------------------|--------------------| +| (unset) | Unchanged driver default (see below) | Unchanged | Unchanged | +| `disable` | No | No | No | +| `require` | Yes | No | No | +| `verify-ca` | Yes | Yes | No | +| `verify-full` | Yes | Yes | Yes | + +- `verify-full` is recommended for production. +- `verify-ca` and `verify-full` require `PLANDEV_DB_SSL_ROOT_CERT`, the path inside the container to a PEM file containing one or more CA certificates (for example the [AWS RDS global bundle](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html)). Mount it read-only. +- Services refuse to start if the mode is not one of the values above, if a `verify-*` mode is set without a root certificate, if the root certificate file is missing, unreadable or not a valid PEM certificate, or if `PLANDEV_DB_SSL_ROOT_CERT` is set while the mode is unset or `disable`. `prefer` and `allow` are intentionally not supported because they can fall back to an unencrypted connection. +- In `require` mode the server certificate is not verified, even if `PLANDEV_DB_SSL_ROOT_CERT` is set (the file is still validated at startup). This matches pgjdbc; note that libpq (used by Hasura) instead verifies the chain when a root certificate is given. +- When both variables are unset, nothing changes: the Java services keep the pgjdbc default (`prefer`: TLS without verification if the server offers it, otherwise plaintext) and the Node services keep the node-postgres default (no TLS unless the standard `PGSSLMODE` variable is set). +- Empty values (e.g. `PLANDEV_DB_SSL_MODE: ""`) are treated as unset. +- Restart the services after replacing the CA bundle; the Node services read it once at startup. + +### Hasura + +Hasura does not read the variables above. It connects with `PLANDEV_DATABASE_URL` and `HASURA_GRAPHQL_METADATA_DATABASE_URL`, which accept the standard libpq `sslmode` and `sslrootcert` query parameters. Append them to both URLs, keeping existing parameters such as `options`: + +``` +postgres://user:password@db.example.com:5432/plandev?options=-c%20search_path%3D...&sslmode=verify-full&sslrootcert=/etc/plandev/certs/rds-global-bundle.pem +``` + +The certificate path must exist inside the Hasura container, so mount the same CA bundle there. Credentials containing reserved URL characters must be percent-encoded. + +### AWS RDS and Aurora + +The server side is controlled by the `rds.force_ssl` parameter. When it is `1`, the server rejects unencrypted connections and PlanDev must use `require`, `verify-ca` or `verify-full`. Its default is `1` for RDS for PostgreSQL 15 and later and for Aurora PostgreSQL 17 and later, and `0` for older versions; to change it, use a custom (cluster) parameter group. Download the [RDS CA bundle](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html) (`global-bundle.pem`), mount it into every PlanDev container and Hasura, and use `verify-full` with the instance or cluster endpoint as `PLANDEV_DB_HOST`. + +### Troubleshooting + +| Error | Likely cause | +|-------|--------------| +| `The server does not support SSL connections` | The server has TLS disabled but a TLS mode is set. | +| `unable to verify the first certificate` / `self-signed certificate in certificate chain` / `PKIX path building failed` | `PLANDEV_DB_SSL_ROOT_CERT` does not contain the CA that signed the server certificate. | +| `Hostname/IP does not match certificate's altnames` / `The hostname ... could not be verified` | `verify-full` with a `PLANDEV_DB_HOST` that is not in the server certificate. Use the name in the certificate, or `verify-ca` if that is not possible. | +| `PLANDEV_DB_SSL_ROOT_CERT ... could not be read` / `... does not exist or is not a regular file` | The file is not mounted, the path is wrong, or the container user cannot read it. | diff --git a/deployment/docker-compose.yml b/deployment/docker-compose.yml index 08960ab3b5..fbd160bf47 100755 --- a/deployment/docker-compose.yml +++ b/deployment/docker-compose.yml @@ -10,6 +10,10 @@ services: PLANDEV_DB: "${PLANDEV_DATABASE_NAME}" PLANDEV_DB_HOST: postgres PLANDEV_DB_PORT: 5432 + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Mount the CA read-only, + # e.g. volume "./certs/db-ca.pem:/etc/plandev/certs/db-ca.pem:ro". + # PLANDEV_DB_SSL_MODE: verify-full + # PLANDEV_DB_SSL_ROOT_CERT: /etc/plandev/certs/db-ca.pem ACTION_COOKIE_NAMES: "${ACTION_COOKIE_NAMES:-}" ACTION_CORS_ALLOWED_ORIGIN: "${ACTION_CORS_ALLOWED_ORIGIN:-}" ACTION_DB_USER: "${SEQUENCING_USERNAME}" @@ -38,6 +42,10 @@ services: PLANDEV_DB: "${PLANDEV_DATABASE_NAME}" PLANDEV_DB_HOST: postgres PLANDEV_DB_PORT: 5432 + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Mount the CA read-only, + # e.g. volume "./certs/db-ca.pem:/etc/plandev/certs/db-ca.pem:ro". + # PLANDEV_DB_SSL_MODE: verify-full + # PLANDEV_DB_SSL_ROOT_CERT: /etc/plandev/certs/db-ca.pem GATEWAY_DB_USER: "${GATEWAY_USERNAME}" GATEWAY_DB_PASSWORD: "${GATEWAY_PASSWORD}" image: "${REPOSITORY_DOCKER_URL}/plandev-gateway:${DOCKER_TAG}" @@ -56,6 +64,10 @@ services: PLANDEV_DB: "${PLANDEV_DATABASE_NAME}" PLANDEV_DB_HOST: postgres PLANDEV_DB_PORT: 5432 + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Mount the CA read-only, + # e.g. volume "./certs/db-ca.pem:/etc/plandev/certs/db-ca.pem:ro". + # PLANDEV_DB_SSL_MODE: verify-full + # PLANDEV_DB_SSL_ROOT_CERT: /etc/plandev/certs/db-ca.pem MERLIN_DB_USER: "${MERLIN_USERNAME}" MERLIN_DB_PASSWORD: "${MERLIN_PASSWORD}" MERLIN_LOCAL_STORE: /usr/src/app/merlin_file_store @@ -78,6 +90,10 @@ services: PLANDEV_DB: "${PLANDEV_DATABASE_NAME}" PLANDEV_DB_HOST: postgres PLANDEV_DB_PORT: 5432 + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Mount the CA read-only, + # e.g. volume "./certs/db-ca.pem:/etc/plandev/certs/db-ca.pem:ro". + # PLANDEV_DB_SSL_MODE: verify-full + # PLANDEV_DB_SSL_ROOT_CERT: /etc/plandev/certs/db-ca.pem MERLIN_DB_USER: "${MERLIN_USERNAME}" MERLIN_DB_PASSWORD: "${MERLIN_PASSWORD}" MERLIN_WORKER_LOCAL_STORE: /usr/src/app/merlin_file_store @@ -103,6 +119,10 @@ services: PLANDEV_DB: "${PLANDEV_DATABASE_NAME}" PLANDEV_DB_HOST: postgres PLANDEV_DB_PORT: 5432 + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Mount the CA read-only, + # e.g. volume "./certs/db-ca.pem:/etc/plandev/certs/db-ca.pem:ro". + # PLANDEV_DB_SSL_MODE: verify-full + # PLANDEV_DB_SSL_ROOT_CERT: /etc/plandev/certs/db-ca.pem SCHEDULER_DB_USER: "${SCHEDULER_USERNAME}" SCHEDULER_DB_PASSWORD: "${SCHEDULER_PASSWORD}" SCHEDULER_PORT: 27185 @@ -125,6 +145,10 @@ services: PLANDEV_DB: "${PLANDEV_DATABASE_NAME}" PLANDEV_DB_HOST: postgres PLANDEV_DB_PORT: 5432 + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Mount the CA read-only, + # e.g. volume "./certs/db-ca.pem:/etc/plandev/certs/db-ca.pem:ro". + # PLANDEV_DB_SSL_MODE: verify-full + # PLANDEV_DB_SSL_ROOT_CERT: /etc/plandev/certs/db-ca.pem SCHEDULER_DB_USER: "${SCHEDULER_USERNAME}" SCHEDULER_DB_PASSWORD: "${SCHEDULER_PASSWORD}" SCHEDULER_OUTPUT_MODE: UpdateInputPlanWithNewActivities @@ -152,6 +176,10 @@ services: PLANDEV_DB: "${PLANDEV_DATABASE_NAME}" PLANDEV_DB_HOST: postgres PLANDEV_DB_PORT: 5432 + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Mount the CA read-only, + # e.g. volume "./certs/db-ca.pem:/etc/plandev/certs/db-ca.pem:ro". + # PLANDEV_DB_SSL_MODE: verify-full + # PLANDEV_DB_SSL_ROOT_CERT: /etc/plandev/certs/db-ca.pem SEQUENCING_DB_USER: "${SEQUENCING_USERNAME}" SEQUENCING_DB_PASSWORD: "${SEQUENCING_PASSWORD}" SEQUENCING_LOCAL_STORE: /usr/src/app/sequencing_file_store @@ -171,6 +199,10 @@ services: PLANDEV_DB: "${PLANDEV_DATABASE_NAME}" PLANDEV_DB_HOST: postgres PLANDEV_DB_PORT: 5432 + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Mount the CA read-only, + # e.g. volume "./certs/db-ca.pem:/etc/plandev/certs/db-ca.pem:ro". + # PLANDEV_DB_SSL_MODE: verify-full + # PLANDEV_DB_SSL_ROOT_CERT: /etc/plandev/certs/db-ca.pem SEQUENCING_DB_USER: "${SEQUENCING_USERNAME}" SEQUENCING_DB_PASSWORD: "${SEQUENCING_PASSWORD}" WORKSPACE_STORE: /usr/src/ws @@ -213,6 +245,9 @@ services: container_name: hasura depends_on: ["postgres"] environment: + # Optional TLS to Postgres: append "&sslmode=verify-full&sslrootcert=/etc/plandev/certs/db-ca.pem" to + # PLANDEV_DATABASE_URL and "?sslmode=verify-full&sslrootcert=/etc/plandev/certs/db-ca.pem" to + # HASURA_GRAPHQL_METADATA_DATABASE_URL, and mount the CA read-only. See deployment/Environment.md#database-tls. PLANDEV_DATABASE_URL: "postgres://${PLANDEV_USERNAME:?PLANDEV_USERNAME has not been set}:${PLANDEV_PASSWORD:?PLANDEV_PASSWORD has not been set}@postgres:5432/${PLANDEV_DATABASE_NAME:?PLANDEV_DATABASE_NAME name is not set}?options=-c%20search_path%3Dutil_functions%2Chasura%2Cpermissions%2Ctags%2Cmerlin%2Cscheduler%2Csequencing%2Cactions%2Cui%2Cpublic" PLANDEV_MERLIN_URL: "http://plandev_merlin:27183" PLANDEV_SCHEDULER_URL: "http://plandev_scheduler:27185" diff --git a/deployment/kubernetes/hasura-deployment.yaml b/deployment/kubernetes/hasura-deployment.yaml index 5a4fe0176d..e0b7ff9d15 100644 --- a/deployment/kubernetes/hasura-deployment.yaml +++ b/deployment/kubernetes/hasura-deployment.yaml @@ -29,6 +29,9 @@ spec: secretKeyRef: name: dev-env key: PLANDEV_PASSWORD + # Optional TLS to Postgres: append "&sslmode=verify-full&sslrootcert=/etc/plandev/certs/db-ca.pem" to + # PLANDEV_DATABASE_URL and "?sslmode=verify-full&sslrootcert=/etc/plandev/certs/db-ca.pem" to + # HASURA_GRAPHQL_METADATA_DATABASE_URL, and mount the CA read-only (see deployment/Environment.md#database-tls). - name: PLANDEV_DATABASE_URL value: "postgres://$(PLANDEV_USERNAME):$(PLANDEV_PASSWORD)@postgres:5432/plandev?options=-c%20search_path%3Dutil_functions%2Chasura%2Cpermissions%2Ctags%2Cmerlin%2Cscheduler%2Csequencing%2Cactions%2Cui%2Cpublic" - name: PLANDEV_MERLIN_URL diff --git a/deployment/kubernetes/plandev-action-deployment.yaml b/deployment/kubernetes/plandev-action-deployment.yaml index b6d06499fb..900289320e 100644 --- a/deployment/kubernetes/plandev-action-deployment.yaml +++ b/deployment/kubernetes/plandev-action-deployment.yaml @@ -36,6 +36,14 @@ spec: value: http://hasura:8080/v1/graphql - name: PLANDEV_DB_PORT value: "5432" + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Put the CA bundle in a ConfigMap + # or Secret (kubectl create configmap plandev-db-ca --from-file=db-ca.pem) and mount it read-only: + # volumeMounts: [{name: plandev-db-ca, mountPath: /etc/plandev/certs, readOnly: true}] + # volumes: [{name: plandev-db-ca, configMap: {name: plandev-db-ca}}] + # - name: PLANDEV_DB_SSL_MODE + # value: verify-full + # - name: PLANDEV_DB_SSL_ROOT_CERT + # value: /etc/plandev/certs/db-ca.pem - name: PLANDEV_DB_HOST value: postgres - name: PLANDEV_DB diff --git a/deployment/kubernetes/plandev-gateway-deployment.yaml b/deployment/kubernetes/plandev-gateway-deployment.yaml index 0986660d21..76488344d2 100644 --- a/deployment/kubernetes/plandev-gateway-deployment.yaml +++ b/deployment/kubernetes/plandev-gateway-deployment.yaml @@ -43,6 +43,14 @@ spec: value: postgres - name: PLANDEV_DB_PORT value: "5432" + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Put the CA bundle in a ConfigMap + # or Secret (kubectl create configmap plandev-db-ca --from-file=db-ca.pem) and mount it read-only: + # volumeMounts: [{name: plandev-db-ca, mountPath: /etc/plandev/certs, readOnly: true}] + # volumes: [{name: plandev-db-ca, configMap: {name: plandev-db-ca}}] + # - name: PLANDEV_DB_SSL_MODE + # value: verify-full + # - name: PLANDEV_DB_SSL_ROOT_CERT + # value: /etc/plandev/certs/db-ca.pem - name: PLANDEV_DB value: plandev - name: GATEWAY_DB_USER diff --git a/deployment/kubernetes/plandev-merlin-deployment.yaml b/deployment/kubernetes/plandev-merlin-deployment.yaml index 757ba11e57..338a147f27 100644 --- a/deployment/kubernetes/plandev-merlin-deployment.yaml +++ b/deployment/kubernetes/plandev-merlin-deployment.yaml @@ -28,6 +28,14 @@ spec: -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -Dorg.slf4j.simpleLogger.logFile=System.err - name: PLANDEV_DB_PORT value: "5432" + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Put the CA bundle in a ConfigMap + # or Secret (kubectl create configmap plandev-db-ca --from-file=db-ca.pem) and mount it read-only: + # volumeMounts: [{name: plandev-db-ca, mountPath: /etc/plandev/certs, readOnly: true}] + # volumes: [{name: plandev-db-ca, configMap: {name: plandev-db-ca}}] + # - name: PLANDEV_DB_SSL_MODE + # value: verify-full + # - name: PLANDEV_DB_SSL_ROOT_CERT + # value: /etc/plandev/certs/db-ca.pem - name: PLANDEV_DB_HOST value: postgres - name: PLANDEV_DB diff --git a/deployment/kubernetes/plandev-merlin-worker-deployment.yaml b/deployment/kubernetes/plandev-merlin-worker-deployment.yaml index c7c4a30158..cbee16e96f 100644 --- a/deployment/kubernetes/plandev-merlin-worker-deployment.yaml +++ b/deployment/kubernetes/plandev-merlin-worker-deployment.yaml @@ -29,6 +29,14 @@ spec: -Dorg.slf4j.simpleLogger.defaultLogLevel=INFO -Dorg.slf4j.simpleLogger.log.com.zaxxer.hikari=WARN -Dorg.slf4j.simpleLogger.logFile=System.err - name: PLANDEV_DB_PORT value: "5432" + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Put the CA bundle in a ConfigMap + # or Secret (kubectl create configmap plandev-db-ca --from-file=db-ca.pem) and mount it read-only: + # volumeMounts: [{name: plandev-db-ca, mountPath: /etc/plandev/certs, readOnly: true}] + # volumes: [{name: plandev-db-ca, configMap: {name: plandev-db-ca}}] + # - name: PLANDEV_DB_SSL_MODE + # value: verify-full + # - name: PLANDEV_DB_SSL_ROOT_CERT + # value: /etc/plandev/certs/db-ca.pem - name: PLANDEV_DB_HOST value: postgres - name: PLANDEV_DB diff --git a/deployment/kubernetes/plandev-scheduler-deployment.yaml b/deployment/kubernetes/plandev-scheduler-deployment.yaml index ffb7bffa66..0446e4d1ea 100644 --- a/deployment/kubernetes/plandev-scheduler-deployment.yaml +++ b/deployment/kubernetes/plandev-scheduler-deployment.yaml @@ -35,6 +35,14 @@ spec: value: http://hasura:8080/v1/graphql - name: PLANDEV_DB_PORT value: "5432" + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Put the CA bundle in a ConfigMap + # or Secret (kubectl create configmap plandev-db-ca --from-file=db-ca.pem) and mount it read-only: + # volumeMounts: [{name: plandev-db-ca, mountPath: /etc/plandev/certs, readOnly: true}] + # volumes: [{name: plandev-db-ca, configMap: {name: plandev-db-ca}}] + # - name: PLANDEV_DB_SSL_MODE + # value: verify-full + # - name: PLANDEV_DB_SSL_ROOT_CERT + # value: /etc/plandev/certs/db-ca.pem - name: PLANDEV_DB_HOST value: postgres - name: PLANDEV_DB diff --git a/deployment/kubernetes/plandev-scheduler-worker-deployment.yaml b/deployment/kubernetes/plandev-scheduler-worker-deployment.yaml index 75366a03a0..985d221769 100644 --- a/deployment/kubernetes/plandev-scheduler-worker-deployment.yaml +++ b/deployment/kubernetes/plandev-scheduler-worker-deployment.yaml @@ -40,6 +40,14 @@ spec: value: UpdateInputPlanWithNewActivities - name: PLANDEV_DB_PORT value: "5432" + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Put the CA bundle in a ConfigMap + # or Secret (kubectl create configmap plandev-db-ca --from-file=db-ca.pem) and mount it read-only: + # volumeMounts: [{name: plandev-db-ca, mountPath: /etc/plandev/certs, readOnly: true}] + # volumes: [{name: plandev-db-ca, configMap: {name: plandev-db-ca}}] + # - name: PLANDEV_DB_SSL_MODE + # value: verify-full + # - name: PLANDEV_DB_SSL_ROOT_CERT + # value: /etc/plandev/certs/db-ca.pem - name: PLANDEV_DB_HOST value: postgres - name: PLANDEV_DB diff --git a/deployment/kubernetes/plandev-sequencing-deployment.yaml b/deployment/kubernetes/plandev-sequencing-deployment.yaml index 183b414413..0d69ad26ee 100644 --- a/deployment/kubernetes/plandev-sequencing-deployment.yaml +++ b/deployment/kubernetes/plandev-sequencing-deployment.yaml @@ -37,6 +37,14 @@ spec: value: http://hasura:8080/v1/graphql - name: PLANDEV_DB_PORT value: "5432" + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Put the CA bundle in a ConfigMap + # or Secret (kubectl create configmap plandev-db-ca --from-file=db-ca.pem) and mount it read-only: + # volumeMounts: [{name: plandev-db-ca, mountPath: /etc/plandev/certs, readOnly: true}] + # volumes: [{name: plandev-db-ca, configMap: {name: plandev-db-ca}}] + # - name: PLANDEV_DB_SSL_MODE + # value: verify-full + # - name: PLANDEV_DB_SSL_ROOT_CERT + # value: /etc/plandev/certs/db-ca.pem - name: PLANDEV_DB_HOST value: postgres - name: PLANDEV_DB diff --git a/deployment/kubernetes/plandev-workspace-deployment.yaml b/deployment/kubernetes/plandev-workspace-deployment.yaml index 00cce3a1a3..a1aef5bcc6 100644 --- a/deployment/kubernetes/plandev-workspace-deployment.yaml +++ b/deployment/kubernetes/plandev-workspace-deployment.yaml @@ -30,6 +30,14 @@ spec: value: postgres - name: PLANDEV_DB_PORT value: "5432" + # Optional TLS to Postgres, see deployment/Environment.md#database-tls. Put the CA bundle in a ConfigMap + # or Secret (kubectl create configmap plandev-db-ca --from-file=db-ca.pem) and mount it read-only: + # volumeMounts: [{name: plandev-db-ca, mountPath: /etc/plandev/certs, readOnly: true}] + # volumes: [{name: plandev-db-ca, configMap: {name: plandev-db-ca}}] + # - name: PLANDEV_DB_SSL_MODE + # value: verify-full + # - name: PLANDEV_DB_SSL_ROOT_CERT + # value: /etc/plandev/certs/db-ca.pem - name: PLANDEV_DB value: plandev - name: SEQUENCING_DB_USER From d8e1cb292b090f87423655630e3a692d9e0d29a8 Mon Sep 17 00:00:00 2001 From: nikhilred2619 Date: Mon, 30 Nov 2026 11:01:18 -0600 Subject: [PATCH 4/4] Enforce database certificate identity and reject malformed CA bundles --- action-server/src/db.ts | 2 +- action-server/src/threads/worker.ts | 2 +- action-server/src/utils/dbSsl.ts | 15 +++++++++++++-- action-server/tests/dbSsl.test.mts | 21 ++++++++++++++++++--- sequencing-server/src/db.ts | 2 +- sequencing-server/src/utils/dbSsl.ts | 14 +++++++++++++- sequencing-server/test/db-ssl.spec.ts | 24 +++++++++++++++++++++--- 7 files changed, 68 insertions(+), 12 deletions(-) diff --git a/action-server/src/db.ts b/action-server/src/db.ts index b7ace5e081..8f95c75c66 100644 --- a/action-server/src/db.ts +++ b/action-server/src/db.ts @@ -9,7 +9,7 @@ const { PLANDEV_DB, PLANDEV_DB_HOST, PLANDEV_DB_PORT, PLANDEV_DB_SSL_MODE, PLAND // 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); +const ssl = getDbSslConfig(PLANDEV_DB_SSL_MODE, PLANDEV_DB_SSL_ROOT_CERT, PLANDEV_DB_HOST); export class ActionsDbManager { private static pool: Pool; diff --git a/action-server/src/threads/worker.ts b/action-server/src/threads/worker.ts index 523e3bcb84..4d8f78c245 100644 --- a/action-server/src/threads/worker.ts +++ b/action-server/src/threads/worker.ts @@ -10,7 +10,7 @@ const { PLANDEV_DB, PLANDEV_DB_HOST, PLANDEV_DB_PORT, PLANDEV_DB_SSL_MODE, PLAND 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); +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; diff --git a/action-server/src/utils/dbSsl.ts b/action-server/src/utils/dbSsl.ts index 94463b6d80..2865cab43f 100644 --- a/action-server/src/utils/dbSsl.ts +++ b/action-server/src/utils/dbSsl.ts @@ -1,5 +1,6 @@ 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; @@ -28,6 +29,12 @@ function readRootCert(path: string): string[] { 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. @@ -52,7 +59,7 @@ function readRootCert(path: string): string[] { * (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): false | ConnectionOptions | undefined { +export function getDbSslConfig(sslMode: string | undefined, sslRootCert: string | undefined, host: string): false | ConnectionOptions | undefined { const mode = sslMode?.trim() || undefined; const rootCertPath = sslRootCert?.trim() || undefined; @@ -98,7 +105,11 @@ export function getDbSslConfig(sslMode: string | undefined, sslRootCert: string return { ca, checkServerIdentity: () => undefined, rejectUnauthorized: true }; } case "verify-full": { - return { ca, rejectUnauthorized: true }; + return { + ca, + rejectUnauthorized: true, + checkServerIdentity: (_servername, cert) => checkServerIdentity(host, cert), + }; } } } diff --git a/action-server/tests/dbSsl.test.mts b/action-server/tests/dbSsl.test.mts index 06ed6394a5..205f5ed78e 100644 --- a/action-server/tests/dbSsl.test.mts +++ b/action-server/tests/dbSsl.test.mts @@ -1,10 +1,12 @@ import assert from "assert"; -import { chmodSync, copyFileSync, mkdtempSync, writeFileSync } from "node:fs"; +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 } = dbSsl; +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"); @@ -42,7 +44,11 @@ test("getDbSslConfig", async (t) => { assert.ok(ssl); assert.strictEqual(ssl.rejectUnauthorized, true); assert.strictEqual((ssl.ca as string[]).length, 1); - assert.strictEqual(ssl.checkServerIdentity, undefined); + 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", () => { @@ -82,6 +88,15 @@ test("getDbSslConfig", async (t) => { 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); diff --git a/sequencing-server/src/db.ts b/sequencing-server/src/db.ts index 04e097f93f..f2c914ba7c 100644 --- a/sequencing-server/src/db.ts +++ b/sequencing-server/src/db.ts @@ -20,7 +20,7 @@ const logger = getLogger('packages/db/db'); // Validated at import time (outside init's try/catch) so an invalid TLS configuration fails at startup. // `undefined` means unset: the `ssl` key is omitted to keep node-postgres defaults. -const ssl = getDbSslConfig(sslMode, sslRootCert); +const ssl = getDbSslConfig(sslMode, sslRootCert, host); export class DbExpansion { private static pool: Pool; diff --git a/sequencing-server/src/utils/dbSsl.ts b/sequencing-server/src/utils/dbSsl.ts index c3843b6d89..65e60c38f0 100644 --- a/sequencing-server/src/utils/dbSsl.ts +++ b/sequencing-server/src/utils/dbSsl.ts @@ -1,5 +1,6 @@ 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; @@ -28,6 +29,12 @@ function readRootCert(path: string): string[] { 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. @@ -55,6 +62,7 @@ function readRootCert(path: string): string[] { export function getDbSslConfig( sslMode: string | undefined, sslRootCert: string | undefined, + host: string, ): false | ConnectionOptions | undefined { const mode = sslMode?.trim() || undefined; const rootCertPath = sslRootCert?.trim() || undefined; @@ -101,7 +109,11 @@ export function getDbSslConfig( return { ca, checkServerIdentity: () => undefined, rejectUnauthorized: true }; } case 'verify-full': { - return { ca, rejectUnauthorized: true }; + return { + ca, + rejectUnauthorized: true, + checkServerIdentity: (_servername, cert) => checkServerIdentity(host, cert), + }; } } } diff --git a/sequencing-server/test/db-ssl.spec.ts b/sequencing-server/test/db-ssl.spec.ts index 6530a27fcd..2d53bb2e9f 100644 --- a/sequencing-server/test/db-ssl.spec.ts +++ b/sequencing-server/test/db-ssl.spec.ts @@ -1,12 +1,15 @@ -import { mkdtempSync, writeFileSync } from 'node:fs'; +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { getDbSslConfig } from '../src/utils/dbSsl.js'; +import { getDbSslConfig as getDbSslConfigForHost } from '../src/utils/dbSsl.js'; const fixtures = join(process.cwd(), 'test', 'fixtures', 'db-ssl'); const caPath = join(fixtures, 'ca.pem'); const scratch = mkdtempSync(join(tmpdir(), 'db-ssl-')); +const getDbSslConfig = (mode: string | undefined, root: string | undefined, host = 'localhost') => + getDbSslConfigForHost(mode, root, host); + describe('getDbSslConfig', () => { it('keeps the node-postgres default when unset or empty', () => { expect(getDbSslConfig(undefined, undefined)).toBeUndefined(); @@ -25,7 +28,22 @@ describe('getDbSslConfig', () => { const verifyFull = getDbSslConfig('verify-full', join(fixtures, 'ca-bundle.pem')); expect(verifyFull).toMatchObject({ rejectUnauthorized: true }); expect(verifyFull && verifyFull.ca).toHaveLength(2); - expect(verifyFull && verifyFull.checkServerIdentity).toBeUndefined(); + expect(verifyFull && verifyFull.checkServerIdentity).toBeDefined(); + const ipSsl = getDbSslConfig('verify-full', caPath, '127.0.0.1'); + expect(ipSsl && ipSsl.checkServerIdentity?.('localhost', { subjectaltname: 'IP Address:127.0.0.1' } as never)).toBeUndefined(); + expect(ipSsl && ipSsl.checkServerIdentity?.('localhost', { subjectaltname: 'DNS:localhost' } as never)).toBeDefined(); + }); + + it('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}`); + expect(() => getDbSslConfig('verify-full', invalid)).toThrow(/contains an invalid certificate/); + } }); it('rejects invalid configuration', () => {