Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Doctor judges Postgres TLS from this machine's side of the connection
garrytanbd61bce0d14a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3f21c1c360..e1433ccb4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,11 +21,11 @@ identifiers and attribution are available in the pre-removal Git revision- `src/core/pg-tls.ts` (new): `resolvePgTls` / `withPgTls`, the one TLS resolver every `postgres()` call site in `src/` uses (the module pool in `db.ts`, worker instance pools in `postgres-engine.ts`, the read and direct pools in `connection-manager.ts`, the graduation target probe and the schema-lock diagnostic connection). An `ssl` option, `sslmode` / `ssl` / `sslrootcert=system` in the URL, or the driver's `PGSSL` variable is explicit and left alone; a loopback host or socket keeps the driver default; anything else gets `ssl: 'require'`. After a failed default-required connect, `tlsRequiredDefaultError` sends the protocol's SSLRequest to the server and turns a "no" into `postgres_tls_required` (DNS, refused and timeout failures are not probed).- `src/core/error-registry.ts`: new code `postgres_tls_required` (host_only, actor user; fix asks the user, reads `gbrain engine status --probe --json`, verifies with `gbrain doctor --only postgres_tls --json`). `docs/guides/error-codes.md` regenerated.- `src/core/pg-access-classify.ts`: new reason `tls_required_default` (manual tier in `gbrain db-repair`, which never removes TLS on its own; fatal for persistence reads).-- `src/commands/doctor/checks/postgres-tls.ts` (new): `postgres_tls` (ops) reads the session's `pg_stat_ssl` row; warns for a non-loopback host without TLS, notes when `require` does not verify the certificate, says when a pooler hop may be the unencrypted link, emits nothing on PGLite.+- `src/commands/doctor/checks/postgres-tls.ts` (new): `postgres_tls` (ops) judges TLS from the client side, from the mode the driver used for the URL the engine connected with. It warns on `sslmode=disable` and on a `sslmode=prefer` connection that fell back to plaintext, and is ok for a TLS client behind a pooler. The session's `pg_stat_ssl` row, which behind a pooler describes the pooler's hop, is detail only. It emits nothing on PGLite.- `src/core/behavior-change-notice.ts`: one row (`postgres_tls_default`) disclosing the new default and the opt-out.- `gbrain init` prints the Supabase URL format with `?sslmode=require`; `docs/ENGINES.md#tls-for-postgres-connections` documents the modes, `verify-full` with Supabase's CA, and the opt-out; the personal-brain tutorial and the other documented Postgres URLs carry `?sslmode=require`.- `scripts/ci-local.sh`, `scripts/run-e2e.sh`: the Docker CI gate reaches its untrusted-by-name service hosts (`postgres-N`, `pgbouncer`) with an explicit `sslmode=disable`, and the derived PgBouncer E2E URL keeps the base URL's query.-- Tests: `test/pg-tls.test.ts` (loopback, remote, explicit modes, opt-out, a guard that every `postgres()` pool in `src/` goes through `withPgTls`), `test/pg-tls-default-refusal.test.ts` (a fake server without TLS on a non-loopback interface gets the coded error; `sslmode=disable` and a TLS-capable server do not), `test/doctor-postgres-tls.test.ts`, `test/e2e/pg-tls-postgres.test.ts` (real servers: a TLS server through a non-loopback address connects with `pg_stat_ssl.ssl = true` on both pool kinds; an `ssl=off` server refuses, then connects with `sslmode=disable` and doctor warns).+- Tests: `test/pg-tls.test.ts` (loopback, remote, explicit modes, opt-out, a guard that every `postgres()` pool in `src/` goes through `withPgTls`), `test/pg-tls-default-refusal.test.ts` (a fake server without TLS on a non-loopback interface gets the coded error; `sslmode=disable` and a TLS-capable server do not), `test/doctor-postgres-tls.test.ts`, `test/e2e/pg-tls-postgres.test.ts` (real servers: a TLS server through a non-loopback address connects with `pg_stat_ssl.ssl = true` on both pool kinds; an `ssl=off` server refuses, then connects with `sslmode=disable` and doctor warns; `sslmode=prefer` falls back and doctor says so; an opt-in TLS-client pooler with a plaintext upstream reads ok).## [0.60.626.0] - 2026-11-09diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 8726a805f2..1b561f83e5 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -219,9 +219,15 @@ A server that does not accept TLS fails the connection with[`postgres_tls_required`](guides/error-codes.md#postgres_tls_required),which names both choices: turn TLS on at the server, or add`sslmode=disable` to the URL. Nothing falls back to plaintext on its own.-`gbrain doctor --only postgres_tls` reports whether the current session is-encrypted (`pg_stat_ssl`) and warns for a non-local brain that is not. PGLite-opens no network connection, so none of this applies to it.+`gbrain doctor --only postgres_tls` reports whether this machine's own+connection to a non-local server uses TLS. It judges that from the client side:+`sslmode=require`, `verify-ca` and `verify-full` make the driver refuse a+server without TLS. It warns on `sslmode=disable`, and on `sslmode=prefer` when+the server does not offer TLS (prefer then falls back to plaintext). Behind a+pooler, the server's `pg_stat_ssl` row describes the pooler's own hop to the+database, which can't be checked from your machine, so doctor shows it as detail+and never warns about it. PGLite opens no network connection, so none of this+applies to it.### Vector index sizingdiff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex 6ed3b905e7..ca90faeee5 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/integrations-memorable.ts` — `memorable_relay_health` (OPS category), the doctor surface for the optional third-party relay. Engine-free (file-plane reads only), pushed unconditionally so it survives `--fast`/`--scope`. Rung ladder: gate off → quiet ok; enabled WITHOUT the gbrain disclosure stamp → FAIL naming the exact fix (the `memorable enable` out-of-band state); CLI-side consent absent → warn; no runnable binary → FAIL; last relay run failed → warn with the CLAMPED cause (the shared `clampRelayCause`; child text never lands in a doctor message verbatim) — EXCEPT the documented openclaw `no_decisive_steps` rejection, which becomes an ok-with-note (`expected_openclaw_rejection`, name-only capture refused until argument capture lands) held as a DEFERRED note that surfaces only after the codex rung below passes: on a mixed openclaw+codex host the rejection is the persistent last-relay state, and an early return would paint the check green while a trust-stale codex hook sits silently dead; receipts written but the child never reported → warn; codex hooks wired but no codex-harness receipt in the recent receipt window (tail-200 read) → warn (`codex_hooks_never_fired` — codex hooks fail silently on a stale trust entry); healthy → ok with structured details (`out_of_band_settable: true` always rides — the enable flag can be flipped by the external CLI, which is exactly why the gate also demands the stamp). Pinned by `test/doctor-memorable.test.ts`.- `src/commands/doctor/checks/routing-federation.ts` — `checkOauthClientScopeHealth` (`oauth_client_scope_health`, re-exported by the doctor.ts façade) has three warn arms: (a) dangling federated read grants, (b) orphaned empty `<name>-workspace` sources, (c) privileged self-registered clients — active `oauth_clients` rows whose scope word-matches `DCR_PRIVILEGED_SCOPES` — the DERIVED complement `ALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES` (exported; bound as a `$1` regex parameter, never interpolated) — and the `(read/write)` / `--scopes read,write` copy is built from `DCR_REGISTRABLE_SCOPES`; pinned by the set-equality + per-scope loop in `test/doctor-oauth-client-scope-health.test.ts`; rows with `grant_revision = 0` and no `oauth_grant_audit` row with `action = 'register'` (every operator path writes one; the anonymous DCR insert does not). Arm (c) is advisory (the signature also matches operator clients that predate the grant audit log) and carries the `gbrain auth rescope-client <client_id> --scopes read,write` / `gbrain auth revoke-client <client_id>` remedy; when the audit table or `grant_revision` column is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned by `test/doctor-oauth-client-scope-health.test.ts`.-- `src/commands/doctor/checks/postgres-tls.ts` — `postgres_tls` (OPS, after `rls`): the session's own `pg_stat_ssl` row on a Postgres brain. Warns (fix asks the user; verify `gbrain doctor --only postgres_tls`) for a non-loopback host without TLS, saying whether the URL opted out (`sslmode=disable`) or a pooler hop reads unencrypted; ok when encrypted, noting that `require` does not verify the certificate; ok on a loopback host; nothing on PGLite or when `pg_stat_ssl` is unreadable. `postgresTlsCheck(url, session)` is the pure half (`test/doctor-postgres-tls.test.ts`).+- `src/commands/doctor/checks/postgres-tls.ts` — `postgres_tls` (OPS, after `rls`), judged from the client side: the mode `resolvePgTls` gives for `engine.connectedDatabaseUrl` (the config URL only as a fallback). `require`, `allow`, `verify-ca` and `verify-full` are ok, because the driver refuses a server without TLS; `sslmode=disable` warns; `sslmode=prefer` sends one SSLRequest probe (`probeServerTls`) and warns when the answer is no, since the driver then falls back to plaintext. The session's `pg_stat_ssl` row is detail only: behind a pooler it describes the pooler's hop to the database. Ok on a loopback host, nothing on PGLite. The fix asks the user; verify is `gbrain doctor --only postgres_tls`. `postgresTlsCheck(url, session, env, preferAnswer)` is the pure half (`test/doctor-postgres-tls.test.ts`; real servers and a TLS-client pooler in `test/e2e/pg-tls-postgres.test.ts`).- `src/commands/doctor/checks/embedding-identity.ts` — `embedding_identity_unqualified` (#6113, BRAIN, right after `embedding_env_override`): warns when the DB `config` row `embedding_model` has no provider prefix (managed fact extraction reads only that row and `config set` refuses it). The fix is the read-only `gbrain migrate embeddings --to <provider:model> --dry-run`, filled from `loadConfig()`'s provider-qualified `embedding_model`, or `<PROVIDER_MODEL>` plus an `inputs` entry when none is configured; `details.target_differs` flags a configured model with another name (applying it switches models). Applying re-embeds active facts (paid, user's call). The free relabel is parked (TODOS). Test: `test/doctor-embedding-identity-unqualified.test.ts`.- `src/commands/doctor/checks/embedding-state.ts` — `embedding_state` (#6696 B3, BRAIN, `tier: 'ops'`, `opsPglite: 'not_applicable'`, after `embeddings`): `readEmbeddingState` in `ops` mode on the ops tier, `full` otherwise. Warns only on chunks of pages soft-deleted past the 72 h purge window (`deleted_page_chunks_overdue`, fix `pages purge-deleted`) and, on a keyed brain, live pages with body text but no chunks (`chunkless_pages_healable`, fix `embed --stale`); the pending backlog stays `embeddings`' warning and quarantined pages `quarantined_pages`'. keyword_only, deleted chunks inside the window and a keyless brain are `infoCheck`; ops without a covering index warns with `details.health: 'unknown'` (`embedding_state_unknown`). Test: `test/doctor-embedding-state.test.ts`.- `src/commands/doctor/checks/knowledge-health.ts` — `facts_extraction_health` reads the last 24 h of `facts:absorb` rows in `ingest_log` (written by `src/core/facts/absorb-log.ts`) per source and reason (`split_part(summary, ':', 1)`) and warns when a failure reason reaches `facts.absorb_warn_threshold` (default 10) in a source. Two reasons are not failures and never count: `write_pending_accepted` (the absorb log read the facts write's receipt back from the journal and it is still queued, running or recovering after the job's publish wait) and `write_deferred_unadmitted` (`writer_lock_unavailable` before admission, no receipt; the job retries). Deferrals warn on their own when, in a source, more than 10 or one over an hour old have no later completed `facts-absorb` job for the same page; that warning's fix is the read-only `gbrain sources writer status --source <id> --json`. The failure count is history: the message gives the incidents in the rolling 24 h window and when the newest ages out, and `details.facts_absorb` (`incidents_24h`, `ages_out_at`, `jobs_still_dead`, `dead_jobs`) adds the current state, the `facts-absorb` jobs dead or failed in the last 24 h with no later completed job for the same page (source and slug); they never change the status, and when no other fix applies the newest one gets the paid `gbrain jobs retry <id>` fix (`retry_job` over MCP, asks first). Tests: `test/doctor-facts-absorb-contention-6778.test.ts`, `test/facts-absorb-publish-wait-6778.test.ts`, `test/doctor-facts-absorb-history-6761.test.ts`.diff --git a/src/commands/doctor/checks/postgres-tls.ts b/src/commands/doctor/checks/postgres-tls.tsindex 101cbd7cde..e68165439f 100644--- a/src/commands/doctor/checks/postgres-tls.ts+++ b/src/commands/doctor/checks/postgres-tls.ts@@ -1,19 +1,18 @@/**- * postgres_tls: is this Postgres brain's connection encrypted? A brain on a- * non-loopback host connected without TLS (the session's own pg_stat_ssl row)- * is a warning that names the fix; an encrypted one is ok, with a note when- * sslmode=require encrypts without verifying the server certificate. PGLite- * opens no network connection and emits nothing. The TLS default itself is- * src/core/pg-tls.ts.- *- * Behind a pooler (PgBouncer, Supavisor) pg_stat_ssl describes the pooler's- * link to the database, not this client's link to the pooler; the message- * says so when the URL asked for TLS but the session reads unencrypted.+ * postgres_tls: is this Postgres brain's own connection encrypted? The verdict+ * comes from the client side: the TLS mode the driver used for the URL the+ * engine connected with (sslmode=require, verify-ca and verify-full make the+ * driver refuse a server without TLS). Behind a pooler (PgBouncer, Supavisor)+ * pg_stat_ssl describes the pooler's hop to the database, so it is reported as+ * detail and never turns a TLS client into a warning. sslmode=disable warns, and+ * so does sslmode=prefer when the server's SSLRequest answer shows the driver+ * fell back to plaintext. PGLite opens no network connection and emits nothing.+ * The TLS default itself is src/core/pg-tls.ts.*/import { loadConfig } from '../../../core/config.ts';import type { Action } from '../../../core/agent-output.ts';-import { pgConnectHosts, isLoopbackPgHost, resolvePgTls } from '../../../core/pg-tls.ts';+import { pgConnectHosts, pgFirstHostPort, isLoopbackPgHost, probeServerTls, resolvePgTls } from '../../../core/pg-tls.ts';import { doctorVerify } from '../check-fix.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';@@ -30,30 +29,45 @@ const TLS_FIX: Action = {docs: 'docs/guides/error-codes.md#postgres_tls_required',};-/** Pure: the finding for a connected Postgres brain, from its URL and its session's pg_stat_ssl row (null when unreadable). */-export function postgresTlsCheck(url: string, session: SessionTls | null, env: Record<string, string | undefined> = process.env): Check | null {+/**+ * Pure: the finding for a connected Postgres brain, judged from this machine's side: the TLS mode the+ * driver used for the URL the engine connected with. pg_stat_ssl (null when unreadable) is detail only,+ * since behind a pooler it describes the pooler's hop. preferAnswer is the server's SSLRequest answer,+ * read only for sslmode=prefer, the one mode whose driver falls back to plaintext.+ */+export function postgresTlsCheck(+ url: string,+ session: SessionTls | null,+ env: Record<string, string | undefined> = process.env,+ preferAnswer: 'S' | 'N' | null = null,+): Check | null {const hosts = pgConnectHosts(url, {}, env);if (hosts.length > 0 && hosts.every(isLoopbackPgHost)) {return { name: 'postgres_tls', status: 'ok', message: 'The Postgres host is on this machine; TLS is not required.' };}- const tls = resolvePgTls(url, {}, env);- const optedOut = tls.mode === 'disable';- if (!session && !optedOut) return null;- if (session?.ssl && !optedOut) {- const unverified = tls.mode === 'require' || tls.mode === 'prefer' || tls.mode === 'allow';+ const { mode } = resolvePgTls(url, {}, env);+ const serverView = session ? { server_reports_ssl: session.ssl, server_ssl_version: session.version } : {};+ if (mode === 'disable' || (mode === 'prefer' && preferAnswer === 'N')) {return {- name: 'postgres_tls', status: 'ok',- message: `The connection to the non-local Postgres host is encrypted (${session.version ?? 'TLS'}).${unverified ? ' sslmode=' + tls.mode + ' does not verify the server certificate; sslmode=verify-full with the server CA also verifies it.' : ''}`,- details: { ssl: true, version: session.version, sslmode: tls.mode },+ name: 'postgres_tls', status: 'warn',+ message: mode === 'disable'+ ? 'Connected to a non-local Postgres host without TLS (sslmode=disable in the database URL): the password and page contents cross the network in plaintext. Turn TLS on at the server and use sslmode=require or sslmode=verify-full.'+ : 'sslmode=prefer fell back to plaintext: the non-local Postgres server does not offer TLS, so the password and page contents cross the network unencrypted. Turn TLS on at the server and use sslmode=require, which refuses to fall back.',+ details: { client_tls: false, sslmode: mode, ...serverView },+ fix: TLS_FIX,};}+ if (mode === 'prefer' && preferAnswer !== 'S') return null;+ const unverified = mode === 'require' || mode === 'prefer' || mode === 'allow';+ const notes = [+ mode === 'prefer' ? 'sslmode=prefer falls back to plaintext if the server ever stops offering TLS; sslmode=require refuses to.' : '',+ unverified ? 'sslmode=' + mode + ' does not verify the server certificate; sslmode=verify-full with the server CA also verifies it.' : '',+ session && !session.ssl ? 'The server reports this session unencrypted: behind a pooler that is the pooler\'s own hop to the database, which cannot be checked from this machine.' : '',+ ].filter(Boolean).join(' ');return {- name: 'postgres_tls', status: 'warn',- message: optedOut- ? 'Connected to a non-local Postgres host without TLS (sslmode=disable in the database URL): the password and page contents cross the network in plaintext. Turn TLS on at the server and use sslmode=require or sslmode=verify-full.'- : `The non-local Postgres server reports this session as unencrypted although the URL asks for sslmode=${tls.mode}. Behind a pooler, this is the pooler's own link to the database; make sure that link is encrypted too.`,- details: { ssl: false, sslmode: tls.mode },- fix: TLS_FIX,+ name: 'postgres_tls', status: 'ok',+ message: 'This connection to the non-local Postgres host uses TLS' + (session?.ssl && session.version ? ' (' + session.version + ')' : '') + '.' + (notes ? ' ' + notes : ''),+ details: { client_tls: true, sslmode: mode, ...serverView },};}@@ -61,14 +75,19 @@ async function runPostgresTls(ctx: DoctorContext): Promise<Check[]> {const engine = connectedEngine(ctx);const checks: Check[] = [];if (engine.kind !== 'postgres') return checks;- const url = loadConfig()?.database_url;+ const url = (engine as { connectedDatabaseUrl?: string }).connectedDatabaseUrl ?? loadConfig()?.database_url;if (!url) return checks;let session: SessionTls | null = null;try {const rows = await engine.executeRaw<{ ssl: boolean; version: string | null }>('SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid()');if (rows[0]) session = { ssl: rows[0].ssl === true, version: rows[0].version ?? null };- } catch { /* pg_stat_ssl unreadable: no finding */ }- const check = postgresTlsCheck(url, session);+ } catch { /* pg_stat_ssl unreadable: the client-side verdict stands */ }+ let preferAnswer: 'S' | 'N' | null = null;+ if (resolvePgTls(url).mode === 'prefer') {+ const target = pgFirstHostPort(url);+ if (target) preferAnswer = await probeServerTls(target.host, target.port);+ }+ const check = postgresTlsCheck(url, session, process.env, preferAnswer);if (check) checks.push({ name: 'postgres_tls', status: check.status, message: check.message, ...(check.details ? { details: check.details } : {}), ...(check.fix ? { fix: check.fix } : {}) });return checks;}diff --git a/src/core/pg-tls.ts b/src/core/pg-tls.tsindex 858163e9ff..5f5ef07e59 100644--- a/src/core/pg-tls.ts+++ b/src/core/pg-tls.ts@@ -115,7 +115,8 @@ export function probeServerTls(host: string, port: number, timeoutMs = 3000): Pr/** Failures that happen before or after the TLS handshake (DNS, refused, timeout, a server SQLSTATE): no probe. */const NOT_A_TLS_REFUSAL: ReadonlySet<string> = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ETIMEDOUT', 'CONNECT_TIMEOUT', 'ENETUNREACH', 'EHOSTUNREACH']);-function firstHostPort(url: string, opts: Record<string, unknown>, env: Env): { host: string; port: number } | null {+/** The first host and port the driver dials, or null for a Unix socket. */+export function pgFirstHostPort(url: string, opts: Record<string, unknown> = {}, env: Env = processEnv()): { host: string; port: number } | null {const host = pgConnectHosts(url, opts, env)[0];if (!host || host.startsWith('/')) return null;if (typeof opts.port === 'number') return { host, port: opts.port };@@ -146,7 +147,7 @@ export async function tlsRequiredDefaultError(if (resolvePgTls(url, opts, env).source !== 'default') return null;const code = String((error as { code?: unknown } | null)?.code ?? '');if (NOT_A_TLS_REFUSAL.has(code) || /^[0-9A-Z]{5}$/.test(code)) return null;- const target = firstHostPort(url, opts, env);+ const target = pgFirstHostPort(url, opts, env);if (!target) return null;return (await probe(target.host, target.port)) === 'N' ? await postgresTlsRequiredError() : null;}diff --git a/test/doctor-postgres-tls.test.ts b/test/doctor-postgres-tls.test.tsindex b2d0d0e6d6..aca635c30b 100644--- a/test/doctor-postgres-tls.test.ts+++ b/test/doctor-postgres-tls.test.ts@@ -40,10 +40,34 @@ describe('postgres_tls doctor check', () => {expect(c.message).toContain('sslmode=disable');});- test('a session the server reports unencrypted warns even when the URL asked for TLS (a pooler hop)', () => {- const c = postgresTlsCheck(REMOTE, { ssl: false, version: null }, {})!;- expect(c.status).toBe('warn');+ test('a TLS client behind a pooler is ok: pg_stat_ssl describes the pooler hop, not this connection', () => {+ const pooler = 'postgres://u:[email protected]:6543/postgres';+ const c = postgresTlsCheck(pooler, { ssl: false, version: null }, {})!;+ expect(c.status).toBe('ok');expect(c.message).toContain('pooler');+ expect(c.message).toContain('cannot be checked from this machine');+ expect(c.fix).toBeUndefined();+ expect(JSON.stringify(c)).not.toContain('plaintext');+ });++ test('a required mode is judged from the client side even when pg_stat_ssl is unreadable', () => {+ const c = postgresTlsCheck(REMOTE + '?sslmode=verify-full', null, {})!;+ expect(c.status).toBe('ok');+ expect(c.details?.client_tls).toBe(true);+ });++ test('sslmode=prefer that fell back to plaintext is described as exactly that', () => {+ const c = postgresTlsCheck(REMOTE + '?sslmode=prefer', { ssl: false, version: null }, {}, 'N')!;+ expect(c.status).toBe('warn');+ expect(c.message).toContain('fell back to plaintext');+ expect(c.message).not.toContain('pooler');+ expect(c.fix).toBeDefined();+ });++ test('sslmode=prefer against a server that offers TLS is ok and says require would refuse a fallback', () => {+ const c = postgresTlsCheck(REMOTE + '?sslmode=prefer', { ssl: true, version: 'TLSv1.3' }, {}, 'S')!;+ expect(c.status).toBe('ok');+ expect(c.message).toContain('sslmode=require');});test('an encrypted non-loopback session is ok and says require does not verify the certificate', () => {@@ -59,8 +83,8 @@ describe('postgres_tls doctor check', () => {expect(postgresTlsCheck('postgres://[email protected]:5432/brain', { ssl: false, version: null }, {})!.status).toBe('ok');});- test('an unreadable pg_stat_ssl on a remote host emits nothing', () => {- expect(postgresTlsCheck(REMOTE, null, {})).toBeNull();+ test('sslmode=prefer with no answer from the server emits nothing', () => {+ expect(postgresTlsCheck(REMOTE + '?sslmode=prefer', null, {}, null)).toBeNull();});test('the entry is registered and emits nothing on PGLite', async () => {diff --git a/test/e2e/pg-tls-postgres.test.ts b/test/e2e/pg-tls-postgres.test.tsindex e4153e6f14..67791b644f 100644--- a/test/e2e/pg-tls-postgres.test.ts+++ b/test/e2e/pg-tls-postgres.test.ts@@ -9,7 +9,11 @@* - GBRAIN_TEST_PG_PLAIN_REMOTE_URL: a server with ssl=off reached through a* non-loopback address, no sslmode. connect() refuses with* postgres_tls_required; the same URL plus sslmode=disable connects and the- * doctor finding warns.+ * doctor finding warns; sslmode=prefer falls back to plaintext and the doctor+ * says so.+ * - GBRAIN_TEST_PG_TLS_POOLER_URL: a transaction pooler that takes TLS from the+ * client and talks plaintext to the database. pg_stat_ssl reads unencrypted+ * (the pooler's hop), and the doctor judges the client hop: ok, no fix.** The two remote URLs need a container reached through its bridge address, so* they are opt-in (they skip when unset); see the PR for the docker commands.@@ -18,11 +22,12 @@import { describe, test, expect } from 'bun:test';import * as db from '../../src/core/db.ts';import { PostgresEngine } from '../../src/core/postgres-engine.ts';-import { postgresTlsCheck } from '../../src/commands/doctor/checks/postgres-tls.ts';+import { postgresTlsCheck, postgresTlsEntry } from '../../src/commands/doctor/checks/postgres-tls.ts';const LOCAL = process.env.DATABASE_URL;const TLS_REMOTE = process.env.GBRAIN_TEST_PG_TLS_REMOTE_URL;const PLAIN_REMOTE = process.env.GBRAIN_TEST_PG_PLAIN_REMOTE_URL;+const TLS_POOLER = process.env.GBRAIN_TEST_PG_TLS_POOLER_URL;const SESSION_SSL = 'SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid()';async function moduleSessionTls(url: string): Promise<{ ssl: boolean; version: string | null }> {@@ -33,6 +38,12 @@ async function moduleSessionTls(url: string): Promise<{ ssl: boolean; version: s} finally { await db.disconnect(); }}+async function doctorOn(url: string): Promise<{ status: string; message: string; fix?: unknown }[]> {+ const engine = new PostgresEngine();+ await engine.connect({ database_url: url, poolSize: 1 } as never);+ try { return await postgresTlsEntry.run({ engine } as never) as never; } finally { await engine.disconnect(); }+}+function withParam(url: string, param: string): string {return url + (url.includes('?') ? '&' : '?') + param;}@@ -87,3 +98,26 @@ describe.skipIf(!PLAIN_REMOTE)('non-loopback Postgres with ssl=off', () => {expect(check.message).toContain('sslmode=disable');}, 60_000);});++describe.skipIf(!PLAIN_REMOTE)('sslmode=prefer against a server without TLS', () => {+ test('the driver falls back to plaintext and doctor says exactly that', async () => {+ const [check] = await doctorOn(withParam(PLAIN_REMOTE!, 'sslmode=prefer'));+ expect(check.status).toBe('warn');+ expect(check.message).toContain('fell back to plaintext');+ }, 60_000);+});++describe.skipIf(!TLS_POOLER)('a TLS client behind a transaction pooler with a plaintext upstream', () => {+ test('pg_stat_ssl reads the pooler hop, and doctor judges the client hop: ok, no fix', async () => {+ const engine = new PostgresEngine();+ await engine.connect({ database_url: TLS_POOLER!, poolSize: 1 } as never);+ try {+ const [row] = await engine.executeRaw<{ ssl: boolean }>(SESSION_SSL);+ expect(row.ssl).toBe(false);+ const [check] = await postgresTlsEntry.run({ engine } as never) as { status: string; message: string; fix?: unknown }[];+ expect(check.status).toBe('ok');+ expect(check.message).toContain('pooler');+ expect(check.fix).toBeUndefined();+ } finally { await engine.disconnect(); }+ }, 60_000);+});