Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

feat: support client TLS for Postgres connections (#749)

Sujai Kumar Guptac4078c6477ce
diff --git a/.changeset/postgres-ssl-client-cert.md b/.changeset/postgres-ssl-client-cert.md
new file mode 100644
index 000000000..ea2ede293
--- /dev/null
+++ b/.changeset/postgres-ssl-client-cert.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": patch
+---
+
+Apply Postgres TLS via Pool `ssl` like servicefoundry (`POSTGRES_SSL_MODE` + cert/key/CA paths), not `sslmode` on the URL.
diff --git a/charts/trueforge/templates/_helpers.tpl b/charts/trueforge/templates/_helpers.tpl
index 5e79e2332..643029cd5 100644
--- a/charts/trueforge/templates/_helpers.tpl
+++ b/charts/trueforge/templates/_helpers.tpl
@@ -430,6 +430,15 @@ fields, wires bundled Postgres/Redis, optional OIDC, then server.extraEnv.
{{- if .Values.externalPostgres.sslMode -}}
{{- $env = append $env (dict "name" "POSTGRES_SSL_MODE" "value" .Values.externalPostgres.sslMode) -}}
{{- end -}}
+{{- if .Values.externalPostgres.sslCertPath -}}
+{{- $env = append $env (dict "name" "POSTGRES_SSL_CERT_PATH" "value" .Values.externalPostgres.sslCertPath) -}}
+{{- end -}}
+{{- if .Values.externalPostgres.sslKeyPath -}}
+{{- $env = append $env (dict "name" "POSTGRES_SSL_KEY_PATH" "value" .Values.externalPostgres.sslKeyPath) -}}
+{{- end -}}
+{{- if .Values.externalPostgres.sslCaPath -}}
+{{- $env = append $env (dict "name" "POSTGRES_SSL_CA_PATH" "value" .Values.externalPostgres.sslCaPath) -}}
+{{- end -}}
{{- end -}}
{{- if .Values.configs.oidc.enabled -}}
diff --git a/charts/trueforge/values.yaml b/charts/trueforge/values.yaml
index e0ac6f8d8..bcc7b1cb7 100644
--- a/charts/trueforge/values.yaml
+++ b/charts/trueforge/values.yaml
@@ -235,7 +235,14 @@ externalPostgres:
# key: host # or port / database / user / password
# Optional TLS for the app → Postgres pool (`POSTGRES_SSL_MODE`). Empty = unset (no TLS).
# Modes: disable | prefer | require | verify-ca | verify-full | no-verify.
+ # prefer/require/verify-ca/verify-full all enable TLS with Node default verification
+ # (≈ verify-full). Use no-verify to encrypt without verifying the server cert.
sslMode: ""
+ # Optional client / CA TLS material. Mount the PEMs with extraVolumes / extraVolumeMounts,
+ # then set these to the in-pod paths.
+ sslCertPath: ""
+ sslKeyPath: ""
+ sslCaPath: ""
externalRedis:
# Full connection URL, e.g. redis://:[email protected]:6379.
# string, or { valueFrom: { secretKeyRef: { name, key } } }. Prefer valueFrom in prod.
diff --git a/packages/trueforge/.env.example b/packages/trueforge/.env.example
index 2950d0de0..f3d164ece 100644
--- a/packages/trueforge/.env.example
+++ b/packages/trueforge/.env.example
@@ -23,45 +23,6 @@ PORT=8790
## When unset, the catalog inlined at build time (catalog/model-catalog.yaml) is used.
# MODEL_CATALOG_PATH=/path/to/model-catalog.yaml
-## TrueFoundry mode (STANDALONE=false only; ignored when STANDALONE=true). When set, GET /models
-## lists tenant-enabled chat models from the TrueFoundry ServiceFoundry server (caller token) and
-## turns call the tenant's default AI Gateway. Unset = local API-key model catalog. Mutually
-## exclusive with OIDC.
-# TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL=https://servicefoundry-server.truefoundry.svc.cluster.local
-## Required when TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL is set. Used only to vend agent tokens for saved-agent turns.
-# TRUEFOUNDRY_API_KEY=
-## Max ms for non-agent ServiceFoundry HTTP calls. Default 10000.
-# TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS=10000
-## Max ms for ServiceFoundry agent create/update/delete calls. Default 3000.
-# TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS=3000
-## Optional per-tenant allowlist of model provider account names (JSON object).
-## Tenants omitted are unfiltered. Example: {"internal":["openai-main","anthropic-main"]}
-# TRUEFOUNDRY_TENANT_ID_TO_ALLOWED_MODEL_PROVIDER_ACCOUNTS={"internal":["openai-main"]}
-
-## Mutual TLS for this process's HTTPS listener and controller→server. Off by default (plain HTTP).
-## When true, serves HTTPS with client-cert enforcement (except /healthz) and the controller
-## presents tls.crt/tls.key from TRUEFORGE_MTLS_CERTS_DIR. Chart probes must use scheme HTTPS.
-# TRUEFORGE_MTLS_ENABLED=false
-# TRUEFORGE_MTLS_CERTS_DIR=/etc/tls
-
-## Internal mutual TLS for calls to the ServiceFoundry server. When true, trueforge presents its client
-## certificate (and upgrades a mesh-direct http:// peer URL to https://). Only meaningful in-cluster,
-## where TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL points at the ServiceFoundry server Service directly.
-# TRUEFOUNDRY_MTLS_ENABLED=false
-## Directory holding the mTLS cert triple (tls.crt / tls.key / ca.crt) when TRUEFOUNDRY_MTLS_ENABLED=true.
-# TRUEFOUNDRY_MTLS_CERTS_DIR=/etc/tls/truefoundry
-
-## Shared sandbox for all tenants (TrueFoundry mode only). PUT settings is disabled (424).
-# TRUEFOUNDRY_SANDBOX_ENABLED=false
-# TRUEFOUNDRY_SANDBOX_PROVIDER=daytona
-## Required for daytona; optional for truefoundry.
-# TRUEFOUNDRY_SANDBOX_API_KEY=
-## Required when provider is truefoundry.
-# TRUEFOUNDRY_SANDBOX_SERVER_URL=http://sandbox-server
-## Static JSON settings (provider-specific). Daytona: snapshot + timeouts. TrueFoundry: nats_bridge_url.
-# TRUEFOUNDRY_SANDBOX_SETTINGS={"snapshotName":"my-snap","timeoutMs":60000,"autoStopIntervalInMinutes":5,"autoArchiveIntervalInMinutes":60,"autoDeleteIntervalInMinutes":43200}
-# TRUEFOUNDRY_SANDBOX_SETTINGS={"nats_bridge_url":"ws://nats-bridge"}
-
## Optional override for the MCP catalog YAML (GET /catalog/mcp-servers).
## When unset, the catalog inlined at build time (catalog/mcp-catalog.yaml) is used.
# MCP_CATALOG_PATH=/path/to/mcp-catalog.yaml
@@ -191,9 +152,18 @@ POSTGRES_PORT=5432
## Shared by the app pool and migrations. Optional, defaults to 60000 each.
# POSTGRES_STATEMENT_TIMEOUT_MS=60000
# POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS=60000
-## Appended as `sslmode` on DATABASE_URL / the built postgres:// URL.
+## Postgres TLS for the pg Pool (not appended to the connection URL).
## disable | prefer | require | verify-ca | verify-full | no-verify.
+## prefer/require/verify-ca/verify-full → ssl:true (Node default verify ≈ verify-full).
+## no-verify → encrypt without verifying the server cert.
# POSTGRES_SSL_MODE=require
+## Optional client / CA PEM paths (mTLS or custom CA).
+# POSTGRES_SSL_CERT_PATH=/path/to/client.crt
+# POSTGRES_SSL_KEY_PATH=/path/to/client.key
+# POSTGRES_SSL_CA_PATH=/path/to/ca.crt
+
+## When set, automatically move TrueForge tables from the public schema to the trueforge schema.
+# AUTOMATICALLY_MOVE_TRUEFORGE_TABLES_FROM_PUBLIC_TO_TRUEFORGE_SCHEMA=true
## ---------------------------------------------------------------------------
## OIDC (used when STANDALONE=false). All three must be set together, or all
@@ -215,4 +185,46 @@ POSTGRES_PORT=5432
## Optional comma-separated email allowlist (exact addresses and/or * globs).
## When set, only ID tokens whose `email` claim matches an entry may sign in.
## Example: [email protected],*@partner.com Empty / unset = unrestricted.
-# OIDC_ALLOWED_EMAILS=
\ No newline at end of file
+# OIDC_ALLOWED_EMAILS=
+
+## ---------------------------------------------------------------------------
+## Mutual TLS for this process's HTTPS listener and controller→server.
+## ---------------------------------------------------------------------------
+
+## Mutual TLS for this process's HTTPS listener and controller→server. Off by default (plain HTTP).
+## When true, serves HTTPS with client-cert enforcement (except /healthz) and the controller
+## presents tls.crt/tls.key from TRUEFORGE_MTLS_CERTS_DIR. Chart probes must use scheme HTTPS.
+# TRUEFORGE_MTLS_ENABLED=false
+# TRUEFORGE_MTLS_CERTS_DIR=/etc/tls
+
+## ---------------------------------------------------------------------------
+## TrueForge mode (STANDALONE=false only; ignored when STANDALONE=true).
+## ---------------------------------------------------------------------------
+# TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL=https://servicefoundry-server.truefoundry.svc.cluster.local
+## Required when TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL is set. Used only to vend agent tokens for saved-agent turns.
+# TRUEFOUNDRY_API_KEY=
+## Max ms for non-agent ServiceFoundry HTTP calls. Default 10000.
+# TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS=10000
+## Max ms for ServiceFoundry agent create/update/delete calls. Default 3000.
+# TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS=3000
+## Optional per-tenant allowlist of model provider account names (JSON object).
+## Tenants omitted are unfiltered. Example: {"internal":["openai-main","anthropic-main"]}
+# TRUEFOUNDRY_TENANT_ID_TO_ALLOWED_MODEL_PROVIDER_ACCOUNTS={"internal":["openai-main"]}
+
+## Internal mutual TLS for calls to the ServiceFoundry server. When true, trueforge presents its client
+## certificate (and upgrades a mesh-direct http:// peer URL to https://). Only meaningful in-cluster,
+## where TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL points at the ServiceFoundry server Service directly.
+# TRUEFOUNDRY_MTLS_ENABLED=false
+## Directory holding the mTLS cert triple (tls.crt / tls.key / ca.crt) when TRUEFOUNDRY_MTLS_ENABLED=true.
+# TRUEFOUNDRY_MTLS_CERTS_DIR=/etc/tls/truefoundry
+
+## Shared sandbox for all tenants (TrueFoundry mode only). PUT settings is disabled (424).
+# TRUEFOUNDRY_SANDBOX_ENABLED=false
+# TRUEFOUNDRY_SANDBOX_PROVIDER=daytona
+## Required for daytona; optional for truefoundry.
+# TRUEFOUNDRY_SANDBOX_API_KEY=
+## Required when provider is truefoundry.
+# TRUEFOUNDRY_SANDBOX_SERVER_URL=http://sandbox-server
+## Static JSON settings (provider-specific). Daytona: snapshot + timeouts. TrueFoundry: nats_bridge_url.
+# TRUEFOUNDRY_SANDBOX_SETTINGS={"snapshotName":"my-snap","timeoutMs":60000,"autoStopIntervalInMinutes":5,"autoArchiveIntervalInMinutes":60,"autoDeleteIntervalInMinutes":43200}
+# TRUEFOUNDRY_SANDBOX_SETTINGS={"nats_bridge_url":"ws://nats-bridge"}
diff --git a/packages/trueforge/src/config.ts b/packages/trueforge/src/config.ts
index 770f68367..cc9f1e8a7 100644
--- a/packages/trueforge/src/config.ts
+++ b/packages/trueforge/src/config.ts
@@ -11,7 +11,7 @@
* - `false`: Postgres + Redis (defaults to local trueforge credentials /
* `redis://localhost:6379`).
*/
-import { existsSync } from 'node:fs';
+import { existsSync, readFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -60,6 +60,17 @@ export interface GetEnvOptions {
required?: boolean;
}
+const POSTGRES_SSL_MODES = ['disable', 'prefer', 'require', 'verify-ca', 'verify-full', 'no-verify'] as const;
+type PostgresSslMode = (typeof POSTGRES_SSL_MODES)[number];
+
+/** pg Pool `ssl` object fields (client certs / CA / no-verify). */
+export interface PostgresSslConfig {
+ cert?: string;
+ key?: string;
+ ca?: string;
+ rejectUnauthorized?: boolean;
+}
+
function getEnv(key: string, options?: GetEnvOptions): string | undefined {
const value = process.env[key];
if (value !== undefined) {
@@ -211,28 +222,19 @@ function parseTrueFoundrySandboxProvider(raw: string | undefined): 'daytona' | '
}
/** Parses `POSTGRES_SSL_MODE`. Unset/blank → `''`. Unknown values throw. */
-function parsePostgresSslMode(raw: string | undefined): string {
- if (!raw) {
+function validatePostgresSslMode(raw: string | undefined): PostgresSslMode | '' {
+ const mode = raw?.trim() ?? '';
+ if (!mode) {
return '';
}
- const mode = raw.trim();
- if (mode === '') {
- return '';
- }
- switch (mode) {
- case 'disable':
- case 'prefer':
- case 'require':
- case 'verify-ca':
- case 'verify-full':
- case 'no-verify':
- return mode;
- default:
- throw new Error(
- 'Environment variable POSTGRES_SSL_MODE must be one of disable, prefer, require, verify-ca, ' +
- `verify-full, no-verify; got "${mode}"`,
- );
+ for (const allowed of POSTGRES_SSL_MODES) {
+ if (mode === allowed) {
+ return allowed;
+ }
}
+ throw new Error(
+ `Environment variable POSTGRES_SSL_MODE must be one of ${POSTGRES_SSL_MODES.join(', ')}; got "${mode}"`,
+ );
}
/**
@@ -298,6 +300,7 @@ function resolveRedisUrl(): string {
/**
* Postgres connection string for distributed mode.
* Prefers `DATABASE_URL` when set (Railway / managed Postgres); otherwise builds from `POSTGRES_*`.
+ * TLS is not put on the URL — see `resolvePostgresSsl` / `DATABASE_SSL` (servicefoundry-style).
*/
function resolvePostgresDatabaseUrl(): string {
const databaseUrl = getEnv('DATABASE_URL');
@@ -315,7 +318,6 @@ function resolvePostgresDatabaseUrl(): string {
raw: getEnv('POSTGRES_PORT'),
defaultValue: DEFAULT_POSTGRES_PORT,
});
- const postgresSslMode = parsePostgresSslMode(getEnv('POSTGRES_SSL_MODE'));
if (
postgresUser.trim() === '' ||
postgresPassword.trim() === '' ||
@@ -333,24 +335,61 @@ function resolvePostgresDatabaseUrl(): string {
host: postgresHost,
port: postgresPort,
database: postgresDb,
- sslMode: postgresSslMode,
});
}
-/** Builds a Postgres connection URL from discrete `POSTGRES_*` parts. */
+/**
+ * Postgres TLS for the pg Pool — same shape as servicefoundry `getSSLConfig`.
+ * Env: `POSTGRES_SSL_MODE`, `POSTGRES_SSL_CERT_PATH`, `POSTGRES_SSL_KEY_PATH`, `POSTGRES_SSL_CA_PATH`.
+ * Not written into `DATABASE_URL`. `prefer` / `require` / `verify-ca` / `verify-full` all map to
+ * `ssl: true` (or the cert object); use `no-verify` for encrypt-without-verify.
+ */
+function resolvePostgresSsl(): boolean | PostgresSslConfig {
+ const sslMode = getEnv('POSTGRES_SSL_MODE');
+ const cert = readOptionalFileContentsEnv('POSTGRES_SSL_CERT_PATH');
+ const key = readOptionalFileContentsEnv('POSTGRES_SSL_KEY_PATH');
+ // Cloud SQL / private CA often fail verify-full; Node cannot express verify-ca without hostname check.
+ const ca = readOptionalFileContentsEnv('POSTGRES_SSL_CA_PATH');
+
+ let ssl: boolean | PostgresSslConfig = false;
+ if (cert || key || ca) {
+ ssl = {
+ ...(cert ? { cert } : {}),
+ ...(key ? { key } : {}),
+ ...(ca ? { ca } : {}),
+ };
+ }
+
+ switch (validatePostgresSslMode(sslMode)) {
+ case 'disable':
+ return false;
+ case 'prefer':
+ case 'require':
+ case 'verify-ca':
+ case 'verify-full':
+ return ssl || true;
+ case 'no-verify':
+ return { ...(ssl || {}), rejectUnauthorized: false };
+ default:
+ return ssl;
+ }
+}
+
+/** Reads a PEM file from an optional path env; unset/blank → `undefined`. */
+function readOptionalFileContentsEnv(envKey: string): string | undefined {
+ const filePath = resolveOptionalPathEnv(envKey);
+ return filePath ? readFileSync(filePath, 'utf8') : undefined;
+}
+
+/** Builds a Postgres connection URL from discrete `POSTGRES_*` parts (no TLS query params). */
function buildPostgresConnectionString(parts: {
user: string;
password: string;
host: string;
port: number;
database: string;
- sslMode: string;
}): string {
- let connectionString = `postgres://${encodeURIComponent(parts.user)}:${encodeURIComponent(parts.password)}@${parts.host}:${String(parts.port)}/${encodeURIComponent(parts.database)}`;
- if (parts.sslMode !== '') {
- connectionString += `?sslmode=${encodeURIComponent(parts.sslMode)}`;
- }
- return connectionString;
+ return `postgres://${encodeURIComponent(parts.user)}:${encodeURIComponent(parts.password)}@${parts.host}:${String(parts.port)}/${encodeURIComponent(parts.database)}`;
}
function resolveOIDCConfig(): OIDCConfig | undefined {
@@ -603,11 +642,16 @@ export type DistributedServerConfiguration = SharedServerConfiguration & {
*/
STANDALONE: false;
/**
- * Postgres connection string. Env: `DATABASE_URL` when set; otherwise built from `POSTGRES_*`
- * (including optional `POSTGRES_SSL_MODE` as `sslmode`).
+ * Postgres connection string. Env: `DATABASE_URL` when set; otherwise built from `POSTGRES_*`.
* Form: `postgres://USER:PASSWORD@HOST:PORT/DB` (or `postgresql://…`) with user/password URL-encoded.
+ * TLS is not encoded here — see `DATABASE_SSL`.
*/
DATABASE_URL: string;
+ /**
+ * Postgres TLS for the pg Pool (servicefoundry-style).
+ * Env: `POSTGRES_SSL_MODE`, `POSTGRES_SSL_CERT_PATH`, `POSTGRES_SSL_KEY_PATH`, `POSTGRES_SSL_CA_PATH`.
+ */
+ DATABASE_SSL: boolean | PostgresSslConfig;
/** Max connections in the `pg` Pool. Env: `DATABASE_POOL_MAX`. Default 10. */
DATABASE_POOL_MAX: number;
/**
@@ -632,6 +676,15 @@ export type DistributedServerConfiguration = SharedServerConfiguration & {
* caller's token. Unset = local Postgres stores. Mutually exclusive with OIDC.
* Env: `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL`.
*/
+ /**
+ * When set, automatically move public TrueForge tables to the TrueForge schema.
+ * Env: `AUTOMATICALLY_MOVE_TRUEFORGE_TABLES_FROM_PUBLIC_TO_TRUEFORGE_SCHEMA`. Default true.
+ */
+ AUTOMATICALLY_MOVE_TRUEFORGE_TABLES_FROM_PUBLIC_TO_TRUEFORGE_SCHEMA: boolean;
+ /**
+ * The URL of the TrueFoundry ServiceFoundry server.
+ * Env: `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL`.
+ */
TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: string | undefined;
/**
* Required when `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set. Env: `TRUEFOUNDRY_API_KEY`.
@@ -815,6 +868,7 @@ const configuration: ServerConfiguration = standalone
...shared,
STANDALONE: false,
DATABASE_URL: resolvePostgresDatabaseUrl(),
+ DATABASE_SSL: resolvePostgresSsl(),
DATABASE_POOL_MAX: parsePositiveInt({
envKey: 'DATABASE_POOL_MAX',
raw: getEnv('DATABASE_POOL_MAX'),
@@ -832,6 +886,11 @@ const configuration: ServerConfiguration = standalone
}),
REDIS_URL: resolveRedisUrl(),
OIDC: resolveOIDCConfig(),
+ AUTOMATICALLY_MOVE_TRUEFORGE_TABLES_FROM_PUBLIC_TO_TRUEFORGE_SCHEMA: parseBoolean({
+ envKey: 'AUTOMATICALLY_MOVE_TRUEFORGE_TABLES_FROM_PUBLIC_TO_TRUEFORGE_SCHEMA',
+ raw: getEnv('AUTOMATICALLY_MOVE_TRUEFORGE_TABLES_FROM_PUBLIC_TO_TRUEFORGE_SCHEMA'),
+ defaultValue: true,
+ }),
TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL', { required: false }),
TRUEFOUNDRY_API_KEY: getEnv('TRUEFOUNDRY_API_KEY', { required: false }),
TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS: parsePositiveInt({
diff --git a/packages/trueforge/src/controller-main.ts b/packages/trueforge/src/controller-main.ts
index d786a38f8..5171d527c 100644
--- a/packages/trueforge/src/controller-main.ts
+++ b/packages/trueforge/src/controller-main.ts
@@ -40,6 +40,7 @@ try {
poolMax: configuration.DATABASE_POOL_MAX,
statementTimeoutMs: configuration.POSTGRES_STATEMENT_TIMEOUT_MS,
idleInTransactionSessionTimeoutMs: configuration.POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS,
+ ssl: configuration.DATABASE_SSL,
});
logger.info('Controller starting', {
diff --git a/packages/trueforge/src/db/migratePostgres.ts b/packages/trueforge/src/db/migratePostgres.ts
index df853deec..3294fc8d0 100644
--- a/packages/trueforge/src/db/migratePostgres.ts
+++ b/packages/trueforge/src/db/migratePostgres.ts
@@ -3,7 +3,6 @@ import path from 'node:path';
import type { Kysely } from 'kysely';
import { FileMigrationProvider, Migrator } from 'kysely/migration';
-
import { importAbsoluteModule } from '../util/crossPlatform';
import { ensureTrueforgeSchema, TRUEFORGE_SCHEMA } from './postgres/schema';
import type { Database } from './postgres/types';
@@ -23,7 +22,6 @@ function createMigrator(db: Kysely<Database>): Migrator {
async function runMigrations(input: { db: Kysely<Database>; targetMigrationName: string | undefined }): Promise<void> {
await ensureTrueforgeSchema(input.db);
-
const migrator = createMigrator(input.db);
const { error, results } =
diff --git a/packages/trueforge/src/db/postgres/AGENTS.md b/packages/trueforge/src/db/postgres/AGENTS.md
index 380038e50..2999d0170 100644
--- a/packages/trueforge/src/db/postgres/AGENTS.md
+++ b/packages/trueforge/src/db/postgres/AGENTS.md
@@ -2,4 +2,4 @@
- Application timestamps MUST be treated as UTC instants. Serialize with `Date.prototype.toISOString()` (always `...Z` with milliseconds).
- Do not run DB queries inside loops (N+1). Prefer a single batched query, a join, or an `IN`/`ANY` lookup over per-item round-trips.
- Postgres migrations MUST start `up`/`down` with `SET LOCAL lock_timeout = '5s'` so waiting DDL fails fast instead of blocking later queries (including `SELECT`s) behind it in the lock queue.
-- All app tables and Kysely migration bookkeeping live in the `trueforge` schema (not `public`). `runMigrations` bootstraps that schema (CREATE + move legacy `public` tables) before the Migrator runs; `createDb` sets `search_path=trueforge`.
+- All app tables and Kysely migration bookkeeping live in the `trueforge` schema (not `public`). The init migration owns `CREATE SCHEMA` (the Migrator also creates it for `migrationTableSchema`); `createDb` sets `search_path=trueforge`.
diff --git a/packages/trueforge/src/db/postgres/client.ts b/packages/trueforge/src/db/postgres/client.ts
index 84bdfaa1f..a92f595b9 100644
--- a/packages/trueforge/src/db/postgres/client.ts
+++ b/packages/trueforge/src/db/postgres/client.ts
@@ -1,6 +1,7 @@
import { Kysely, PostgresDialect } from 'kysely';
import pg, { Pool } from 'pg';
+import type { PostgresSslConfig } from '../../config';
import { TRUEFORGE_SCHEMA } from './schema';
import type { Database } from './types';
@@ -41,8 +42,10 @@ export function createDb(options: {
statementTimeoutMs: number;
/** Postgres `idle_in_transaction_session_timeout` in ms. Applied to every pooled connection. */
idleInTransactionSessionTimeoutMs: number;
+ /** Client TLS for the pg Pool (`false` | `true` | `{ cert, key, ca, rejectUnauthorized }`). */
+ ssl?: boolean | PostgresSslConfig | undefined;
}): Kysely<Database> {
- const { connectionString, poolMax, statementTimeoutMs, idleInTransactionSessionTimeoutMs } = options;
+ const { connectionString, poolMax, statementTimeoutMs, idleInTransactionSessionTimeoutMs, ssl } = options;
configurePgTypeParsers();
return new Kysely<Database>({
dialect: new PostgresDialect({
@@ -52,6 +55,7 @@ export function createDb(options: {
statement_timeout: statementTimeoutMs,
idle_in_transaction_session_timeout: idleInTransactionSessionTimeoutMs,
options: `-c search_path=${TRUEFORGE_SCHEMA}`,
+ ...(ssl !== undefined ? { ssl } : {}),
}),
}),
});
diff --git a/packages/trueforge/src/db/postgres/migrate-cli.ts b/packages/trueforge/src/db/postgres/migrate-cli.ts
index 4c7540966..54ede4194 100644
--- a/packages/trueforge/src/db/postgres/migrate-cli.ts
+++ b/packages/trueforge/src/db/postgres/migrate-cli.ts
@@ -18,6 +18,7 @@ const db = createDb({
poolMax: configuration.DATABASE_POOL_MAX,
statementTimeoutMs: configuration.POSTGRES_STATEMENT_TIMEOUT_MS,
idleInTransactionSessionTimeoutMs: configuration.POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS,
+ ssl: configuration.DATABASE_SSL,
});
try {
diff --git a/packages/trueforge/src/db/postgres/migrations/20260727_000001_init.ts b/packages/trueforge/src/db/postgres/migrations/20260727_000001_init.ts
index b220d4a9d..eb7bff33f 100644
--- a/packages/trueforge/src/db/postgres/migrations/20260727_000001_init.ts
+++ b/packages/trueforge/src/db/postgres/migrations/20260727_000001_init.ts
@@ -1,10 +1,13 @@
import { type Kysely, sql } from 'kysely';
+import { TRUEFORGE_SCHEMA } from '../schema';
+
export async function up(db: Kysely<unknown>): Promise<void> {
await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
- await sql`SELECT 1`.execute(db);
+ await sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(TRUEFORGE_SCHEMA)}`.execute(db);
}
+// No-op: dropping the schema would take the Migrator's own bookkeeping table with it.
export async function down(db: Kysely<unknown>): Promise<void> {
await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
await sql`SELECT 1`.execute(db);
diff --git a/packages/trueforge/src/db/postgres/schema.ts b/packages/trueforge/src/db/postgres/schema.ts
index 07ab2a08f..992fca6c0 100644
--- a/packages/trueforge/src/db/postgres/schema.ts
+++ b/packages/trueforge/src/db/postgres/schema.ts
@@ -1,5 +1,6 @@
import { type Kysely, sql } from 'kysely';
+import configuration from '../../config';
import type { Database } from './types';
export const TRUEFORGE_SCHEMA = 'trueforge';
@@ -41,10 +42,15 @@ export async function ensureTrueforgeSchema(db: Kysely<Database>): Promise<void>
}
await sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(TRUEFORGE_SCHEMA)}`.execute(txn);
- for (const tableName of TABLES_TO_MOVE) {
- await sql`
- ALTER TABLE IF EXISTS ${sql.id('public', tableName)} SET SCHEMA ${sql.id(TRUEFORGE_SCHEMA)}
- `.execute(txn);
+ if (
+ !configuration.STANDALONE &&
+ configuration.AUTOMATICALLY_MOVE_TRUEFORGE_TABLES_FROM_PUBLIC_TO_TRUEFORGE_SCHEMA
+ ) {
+ for (const tableName of TABLES_TO_MOVE) {
+ await sql`
+ ALTER TABLE IF EXISTS ${sql.id('public', tableName)} SET SCHEMA ${sql.id(TRUEFORGE_SCHEMA)}
+ `.execute(txn);
+ }
}
});
}
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index a08c8f38e..f2dc59083 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -349,6 +349,7 @@ async function createDistributedPersistence(options: {
const { configuration, logger } = options;
const {
DATABASE_URL: databaseUrl,
+ DATABASE_SSL: databaseSsl,
DATABASE_POOL_MAX: databasePoolMax,
POSTGRES_STATEMENT_TIMEOUT_MS: statementTimeoutMs,
POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS: idleInTransactionSessionTimeoutMs,
@@ -390,6 +391,7 @@ async function createDistributedPersistence(options: {
poolMax: databasePoolMax,
statementTimeoutMs,
idleInTransactionSessionTimeoutMs,
+ ssl: databaseSsl,
});
await migrateToLatest(db);
logger.info(`Executor id: ${executorId}`);