diff --git a/bun.lock b/bun.lock index 9a537c0b..fef35d9e 100644 --- a/bun.lock +++ b/bun.lock @@ -360,6 +360,7 @@ "version": "1.0.0", "dependencies": { "@duckdb/node-api": "^1.4.4-r.1", + "@stock-bot/questdb": "workspace:*", "@stock-bot/research": "workspace:*", }, "devDependencies": { diff --git a/libs/data/questdb/src/index.ts b/libs/data/questdb/src/index.ts index 90102ae0..79b6f2ae 100644 --- a/libs/data/questdb/src/index.ts +++ b/libs/data/questdb/src/index.ts @@ -38,9 +38,13 @@ export { type M2IntradayTableName, } from './schema'; export { + assertNoConflictingQuestDbSsl, + hasConflictingQuestDbUrlSsl, openQuestDbPgExecutor, + type OpenQuestDbPgExecutorOptions, type QuestDbPgExecutorConfig, type QuestDbPgExecutorHandle, + type QuestDbPgPoolLike, type QuestDbPgQueryExecutor, } from './pg-executor'; diff --git a/libs/data/questdb/src/pg-executor.ts b/libs/data/questdb/src/pg-executor.ts index c89da4f4..922158ab 100644 --- a/libs/data/questdb/src/pg-executor.ts +++ b/libs/data/questdb/src/pg-executor.ts @@ -25,13 +25,179 @@ export interface QuestDbPgExecutorHandle { close(): Promise; } +/** Minimal `pg.Pool` surface used by {@link openQuestDbPgExecutor}. */ +export interface QuestDbPgPoolLike { + on(event: 'error', listener: (err: Error) => void): unknown; + query( + sql: string, + params?: unknown[] + ): Promise<{ readonly rows: readonly unknown[] }>; + end(): Promise; +} + +export interface OpenQuestDbPgExecutorOptions { + /** Optional pool factory override for unit tests; defaults to `new Pool(cfg)`. */ + readonly createPool?: (poolConfig: PoolConfig) => QuestDbPgPoolLike; + /** + * Optional diagnostic callback invoked when an idle pool client emits `'error'`. + * Always receives a credential-safe `Error`. + */ + readonly onPoolError?: (error: Error) => void; +} + +const SAFE_ERROR_CODE_RE = /^[A-Z0-9_]{1,32}$/; + +/** + * Returns `true` when an explicit boolean `ssl` setting conflicts with SSL + * query parameters (`sslmode`, `ssl`, `sslcert`, `sslkey`, `sslrootcert`) + * embedded in `rawUrl`. + */ +export function hasConflictingQuestDbUrlSsl(rawUrl: string, explicitSsl: boolean): boolean { + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + return false; + } + + for (const [rawKey, rawValue] of parsed.searchParams.entries()) { + const key = rawKey.toLowerCase(); + const value = rawValue.trim().toLowerCase(); + + if (key === 'sslmode') { + if (value === 'disable') { + if (explicitSsl) { + return true; + } + } else if ( + value === 'require' || + value === 'verify-ca' || + value === 'verify-full' || + value === 'no-verify' + ) { + if (!explicitSsl) { + return true; + } + } else { + // `allow`, `prefer`, or any unrecognized sslmode conflicts with an explicit boolean override. + return true; + } + } else if (key === 'ssl') { + if (value === 'false' || value === '0') { + if (explicitSsl) { + return true; + } + } else if (value === 'true' || value === '1') { + if (!explicitSsl) { + return true; + } + } else { + return true; + } + } else if ( + (key === 'sslcert' || key === 'sslkey' || key === 'sslrootcert') && + value.length > 0 && + !explicitSsl + ) { + return true; + } + } + + return false; +} + +/** + * Throws a credential-free `RangeError` if `explicitSsl` conflicts with SSL + * query parameters in `rawUrl`. + */ +export function assertNoConflictingQuestDbSsl(rawUrl: string, explicitSsl: boolean): void { + if (hasConflictingQuestDbUrlSsl(rawUrl, explicitSsl)) { + throw new RangeError( + 'Conflicting QuestDB SSL configuration: explicit "ssl" option conflicts with SSL query parameters in the QuestDB URL.' + ); + } +} + +function addRawAndDecodedNeedle(needles: Set, raw: string): void { + if (raw.length === 0) { + return; + } + needles.add(raw); + try { + const decoded = decodeURIComponent(raw); + if (decoded.length > 0) { + needles.add(decoded); + } + } catch { + // Malformed percent-encoding: raw needle is already registered. + } +} + +function collectConfigSecretNeedles(config: QuestDbPgExecutorConfig): readonly string[] { + const needles = new Set(); + if (typeof config.password === 'string' && config.password.length > 0) { + addRawAndDecodedNeedle(needles, config.password); + } + if (typeof config.url === 'string' && config.url.length > 0) { + needles.add(config.url); + try { + const parsed = new URL(config.url); + if (parsed.href.length > 0) { + needles.add(parsed.href); + } + addRawAndDecodedNeedle(needles, parsed.password); + for (const [key, value] of parsed.searchParams.entries()) { + if (key.toLowerCase() === 'password' && value.length > 0) { + addRawAndDecodedNeedle(needles, value); + } + } + } catch { + // Non-URL string: raw string is already covered. + } + } + return Array.from(needles); +} + +function sanitizePoolError(err: unknown, needles: readonly string[]): Error { + const rawCode = + typeof err === 'object' && err !== null && 'code' in err + ? (err as { readonly code?: unknown }).code + : undefined; + const safeCode = + typeof rawCode === 'string' && SAFE_ERROR_CODE_RE.test(rawCode) ? rawCode : undefined; + + if (err instanceof Error) { + const messageHasSecret = needles.some(needle => err.message.includes(needle)); + const stackHasSecret = + typeof err.stack === 'string' && needles.some(needle => err.stack?.includes(needle) === true); + if (!messageHasSecret && !stackHasSecret) { + return err; + } + } + + const message = + safeCode !== undefined + ? `QuestDB PGWire idle pool client error (${safeCode}; details redacted).` + : 'QuestDB PGWire idle pool client error (details redacted).'; + const sanitized = new Error(message); + if (safeCode !== undefined) { + (sanitized as Error & { code?: string }).code = safeCode; + } + return sanitized; +} + /** * Opens a lightweight PGWire `pg.Pool` executor for QuestDB read queries or * opt-in DDL without creating legacy tables or starting background health timers. */ export async function openQuestDbPgExecutor( - config: QuestDbPgExecutorConfig + config: QuestDbPgExecutorConfig, + options?: OpenQuestDbPgExecutorOptions ): Promise { + if (config.url !== undefined && config.ssl !== undefined) { + assertNoConflictingQuestDbSsl(config.url, config.ssl); + } + const poolConfig: PoolConfig = { max: config.max ?? 4, connectionTimeoutMillis: config.connectionTimeoutMillis ?? 5_000, @@ -48,7 +214,25 @@ export async function openQuestDbPgExecutor( ...(config.ssl !== undefined ? { ssl: config.ssl } : {}), }; - const pool = new Pool(poolConfig); + const secretNeedles = collectConfigSecretNeedles(config); + const createPool = options?.createPool ?? ((cfg: PoolConfig) => new Pool(cfg)); + const pool = createPool(poolConfig); + + // Register an idle-client error listener before the startup probe so backend + // restarts or network disconnects on idle connections cannot crash the host + // with an unhandled EventEmitter 'error' event; pg-pool automatically drops + // the failed idle client and opens a fresh connection on the next query. + pool.on('error', (err: Error) => { + if (options?.onPoolError !== undefined) { + const safeError = sanitizePoolError(err, secretNeedles); + try { + options.onPoolError(safeError); + } catch { + // Never allow diagnostic callbacks to re-throw from an EventEmitter error handler. + } + } + }); + try { await pool.query('SELECT 1'); } catch (err: unknown) { diff --git a/libs/data/questdb/test/questdb.test.ts b/libs/data/questdb/test/questdb.test.ts index 6cd925dd..ea295b5c 100644 --- a/libs/data/questdb/test/questdb.test.ts +++ b/libs/data/questdb/test/questdb.test.ts @@ -1,6 +1,11 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { EventEmitter } from 'node:events'; import { QuestDBHealthMonitor } from '../src/health'; import { QuestDBInfluxWriter } from '../src/influx-writer'; +import { + openQuestDbPgExecutor, + type QuestDbPgPoolLike, +} from '../src/pg-executor'; import { QuestDBQueryBuilder } from '../src/query-builder'; import { applyM2IntradayDDL, @@ -571,4 +576,143 @@ describe('QuestDB', () => { monitor.stopMonitoring(); }); }); + + describe('openQuestDbPgExecutor', () => { + it('registers pool error listener before SELECT 1, redacts credentials, and recovers on next query after idle disconnect', async () => { + const secret = 'qdb_idle_s3cr3t!'; + const url = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`; + + class FakePool extends EventEmitter implements QuestDbPgPoolLike { + connectionEpoch = 1; + probeSawErrorListener = false; + ended = false; + readonly queries: Array<{ readonly sql: string; readonly epoch: number }> = []; + + async query(sql: string): Promise<{ readonly rows: readonly unknown[] }> { + if (sql === 'SELECT 1') { + this.probeSawErrorListener = this.listenerCount('error') > 0; + this.queries.push({ sql, epoch: this.connectionEpoch }); + return { rows: [{ '?column?': 1 }] }; + } + this.queries.push({ sql, epoch: this.connectionEpoch }); + return { rows: [{ ok: true, epoch: this.connectionEpoch }] }; + } + + async end(): Promise { + this.ended = true; + } + } + + const fakePool = new FakePool(); + const observedErrors: Error[] = []; + + const handle = await openQuestDbPgExecutor( + { url }, + { + createPool: () => fakePool, + onPoolError: err => { + observedErrors.push(err); + }, + } + ); + + try { + // Listener must be attached before the startup probe runs. + expect(fakePool.probeSawErrorListener).toBe(true); + expect(fakePool.listenerCount('error')).toBeGreaterThan(0); + + // Simulate QuestDB restarting while the connection opened by SELECT 1 is idle. + const idleErr = Object.assign( + new Error(`idle connection dropped for ${url} (password=${secret})`), + { code: 'ECONNRESET' } + ); + expect(() => fakePool.emit('error', idleErr)).not.toThrow(); + + // Diagnostic callback receives a credential-free Error with the safe error code. + expect(observedErrors).toHaveLength(1); + expect(observedErrors[0]?.message).not.toContain(secret); + expect(observedErrors[0]?.message).not.toContain(url); + expect(observedErrors[0]?.message).toContain('ECONNRESET'); + expect((observedErrors[0] as Error & { code?: string }).code).toBe('ECONNRESET'); + + // Pool replaces the failed idle client and serves the next query cleanly. + fakePool.connectionEpoch = 2; + const result = await handle.executor.query('SELECT pair FROM fx_1m LIMIT 1'); + expect(result.rows).toEqual([{ ok: true, epoch: 2 }]); + expect(fakePool.queries).toEqual([ + { sql: 'SELECT 1', epoch: 1 }, + { sql: 'SELECT pair FROM fx_1m LIMIT 1', epoch: 2 }, + ]); + } finally { + await handle.close(); + await handle.close(); + } + expect(fakePool.ended).toBe(true); + }); + + it('rejects conflicting URL SSL query parameters and explicit ssl before creating a pool', async () => { + const secret = 'qdb_ssl_s3cr3t!'; + const base = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`; + + const conflictingCases: ReadonlyArray = [ + [`${base}?sslmode=disable`, true], + [`${base}?SSLMODE=DISABLE`, true], + [`${base}?sslmode=require`, false], + [`${base}?sslmode=verify-ca`, false], + [`${base}?sslmode=verify-full`, false], + [`${base}?sslmode=no-verify`, false], + [`${base}?sslmode=prefer`, true], + [`${base}?sslmode=prefer`, false], + [`${base}?sslmode=allow`, true], + [`${base}?ssl=false`, true], + [`${base}?ssl=0`, true], + [`${base}?ssl=true`, false], + [`${base}?ssl=1`, false], + [`${base}?sslrootcert=/etc/ssl/ca.pem`, false], + ]; + + let createPoolCalls = 0; + for (const [url, ssl] of conflictingCases) { + let caught: unknown; + try { + await openQuestDbPgExecutor( + { url, ssl }, + { + createPool: () => { + createPoolCalls += 1; + throw new Error('createPool must not be called on conflicting SSL config'); + }, + } + ); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(RangeError); + expect((caught as Error).message).toContain('SSL'); + expect((caught as Error).message).not.toContain(secret); + expect((caught as Error).message).not.toContain(url); + } + expect(createPoolCalls).toBe(0); + + // Compatible combinations proceed to pool creation. + const compatibleCases: ReadonlyArray = [ + [base, true], + [`${base}?sslmode=require`, true], + [`${base}?sslmode=disable`, false], + [`${base}?ssl=true`, true], + [`${base}?ssl=false`, false], + ]; + for (const [url, ssl] of compatibleCases) { + const pool = Object.assign(new EventEmitter(), { + query: async () => ({ rows: [{ '?column?': 1 }] }), + end: async () => {}, + }) as unknown as QuestDbPgPoolLike; + const handle = await openQuestDbPgExecutor( + { url, ssl }, + { createPool: () => pool } + ); + await handle.close(); + } + }); + }); }); diff --git a/libs/research/src/mcp/host/stdio-host.ts b/libs/research/src/mcp/host/stdio-host.ts index 7d4f8bf8..363cd2f8 100644 --- a/libs/research/src/mcp/host/stdio-host.ts +++ b/libs/research/src/mcp/host/stdio-host.ts @@ -282,6 +282,60 @@ function parseQuestDbPort(raw: string): number { return port; } +function hasConflictingUrlSslSetting(rawUrl: string, explicitSsl: boolean): boolean { + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + return false; + } + + for (const [rawKey, rawValue] of parsed.searchParams.entries()) { + const key = rawKey.toLowerCase(); + const value = rawValue.trim().toLowerCase(); + + if (key === 'sslmode') { + if (value === 'disable') { + if (explicitSsl) { + return true; + } + } else if ( + value === 'require' || + value === 'verify-ca' || + value === 'verify-full' || + value === 'no-verify' + ) { + if (!explicitSsl) { + return true; + } + } else { + // `allow`, `prefer`, or any unrecognized sslmode conflicts with an explicit boolean override. + return true; + } + } else if (key === 'ssl') { + if (value === 'false' || value === '0') { + if (explicitSsl) { + return true; + } + } else if (value === 'true' || value === '1') { + if (!explicitSsl) { + return true; + } + } else { + return true; + } + } else if ( + (key === 'sslcert' || key === 'sslkey' || key === 'sslrootcert') && + value.length > 0 && + !explicitSsl + ) { + return true; + } + } + + return false; +} + function parseQuestDbConfig(data: { readonly [ENV_QUESTDB_URL]?: string; readonly [ENV_QUESTDB_HOST]?: string; @@ -320,6 +374,12 @@ function parseQuestDbConfig(data: { ); } const url = parsePgWireUrl(rawUrl, ENV_QUESTDB_URL); + if (ssl !== undefined && hasConflictingUrlSslSetting(url, ssl)) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_SSL, + `Conflicting configuration variable "${ENV_QUESTDB_SSL}": conflicts with SSL query parameters in "${ENV_QUESTDB_URL}".` + ); + } return { url, ...(ssl !== undefined ? { ssl } : {}), diff --git a/libs/research/test/mcp-stdio-host.test.ts b/libs/research/test/mcp-stdio-host.test.ts index 22c56f8b..cdd0e785 100644 --- a/libs/research/test/mcp-stdio-host.test.ts +++ b/libs/research/test/mcp-stdio-host.test.ts @@ -1242,20 +1242,73 @@ describe('runResearchCopilotStdioHost', () => { ssl: false, }); - // 4. Rejects conflicting URL + host, partial port-without-host, bad port, bad ssl, unknown var. + // 4. Rejects conflicting URL + host, partial port-without-host, bad port, bad ssl, unknown var, + // and conflicting URL SSL query parameters vs RESEARCH_MCP_QUESTDB_SSL without leaking secrets. const invalidEnvs: Array> = [ { RESEARCH_MCP_QUESTDB_URL: questUrl, RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51' }, { RESEARCH_MCP_QUESTDB_PG_PORT: '8812' }, { RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', RESEARCH_MCP_QUESTDB_PG_PORT: '99999' }, { RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', RESEARCH_MCP_QUESTDB_SSL: 'maybe' }, { RESEARCH_MCP_QUESTDB_UNKNOWN: '1' }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=false`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=true`, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=prefer`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslrootcert=/etc/ssl/ca.pem`, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }, ]; for (const override of invalidEnvs) { - expect(() => parseResearchCopilotHostConfig(buildValidEnv(override))).toThrow( - ResearchCopilotHostConfigError - ); + let caughtInvalid: unknown; + try { + parseResearchCopilotHostConfig(buildValidEnv(override)); + } catch (err) { + caughtInvalid = err; + } + expect(caughtInvalid).toBeInstanceOf(ResearchCopilotHostConfigError); + expect((caughtInvalid as Error).message).not.toContain(questSecret); + expect((caughtInvalid as Error).message).not.toContain(questUrl); } + // Compatible URL SSL query params + matching RESEARCH_MCP_QUESTDB_SSL are accepted. + const consistentSslEnable = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }) + ); + expect(consistentSslEnable.questdb).toEqual({ + url: `${questUrl}?sslmode=require`, + ssl: true, + }); + const consistentSslDisable = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }) + ); + expect(consistentSslDisable.questdb).toEqual({ + url: `${questUrl}?sslmode=disable`, + ssl: false, + }); + // 5. Redacts QuestDB URL / password on openStore and cleanup errors. for (const cfg of [urlConfig, hostFullConfig]) { let caught: unknown; diff --git a/scripts/questdb-init-m2.ts b/scripts/questdb-init-m2.ts index f0094709..696a3450 100644 --- a/scripts/questdb-init-m2.ts +++ b/scripts/questdb-init-m2.ts @@ -15,12 +15,17 @@ import { applyM2IntradayDDL, + assertNoConflictingQuestDbSsl, openQuestDbPgExecutor, type QuestDbPgExecutorConfig, } from '@stock-bot/questdb'; -function readEnv(primary: string, fallback: string): string | undefined { - const value = process.env[primary] ?? process.env[fallback]; +function readEnv( + env: Readonly>, + primary: string, + fallback: string +): string | undefined { + const value = env[primary] ?? env[fallback]; if (value === undefined) { return undefined; } @@ -28,34 +33,47 @@ function readEnv(primary: string, fallback: string): string | undefined { return trimmed.length > 0 ? trimmed : undefined; } -function resolveConfig(): QuestDbPgExecutorConfig { - const url = readEnv('QUESTDB_URL', 'RESEARCH_MCP_QUESTDB_URL'); - const sslRaw = readEnv('QUESTDB_SSL', 'RESEARCH_MCP_QUESTDB_SSL'); - const ssl = - sslRaw === undefined - ? undefined - : sslRaw.toLowerCase() === 'true' || sslRaw === '1' - ? true - : sslRaw.toLowerCase() === 'false' || sslRaw === '0' - ? false - : undefined; +function parseSslFlag(raw: string): boolean { + const normalized = raw.trim().toLowerCase(); + if (normalized === 'true' || normalized === '1') { + return true; + } + if (normalized === 'false' || normalized === '0') { + return false; + } + throw new RangeError( + 'Invalid QuestDB SSL configuration: expected "true", "false", "1", or "0".' + ); +} + +export function resolveQuestDbInitM2Config( + env: Readonly> = process.env +): QuestDbPgExecutorConfig { + const url = readEnv(env, 'QUESTDB_URL', 'RESEARCH_MCP_QUESTDB_URL'); + const sslRaw = readEnv(env, 'QUESTDB_SSL', 'RESEARCH_MCP_QUESTDB_SSL'); + const ssl = sslRaw !== undefined ? parseSslFlag(sslRaw) : undefined; if (url !== undefined) { + if (ssl !== undefined) { + assertNoConflictingQuestDbSsl(url, ssl); + } return { url, ...(ssl !== undefined ? { ssl } : {}), }; } - const host = readEnv('QUESTDB_HOST', 'RESEARCH_MCP_QUESTDB_HOST') ?? 'localhost'; - const portRaw = readEnv('QUESTDB_PG_PORT', 'RESEARCH_MCP_QUESTDB_PG_PORT'); + const host = readEnv(env, 'QUESTDB_HOST', 'RESEARCH_MCP_QUESTDB_HOST') ?? 'localhost'; + const portRaw = readEnv(env, 'QUESTDB_PG_PORT', 'RESEARCH_MCP_QUESTDB_PG_PORT'); const port = portRaw !== undefined ? Number(portRaw) : 8812; if (!Number.isInteger(port) || port < 1 || port > 65535) { - throw new Error(`Invalid QuestDB PGWire port "${String(portRaw)}". Expected 1..65535.`); + throw new RangeError( + `Invalid QuestDB PGWire port "${String(portRaw)}". Expected 1..65535.` + ); } - const database = readEnv('QUESTDB_DATABASE', 'RESEARCH_MCP_QUESTDB_DATABASE') ?? 'qdb'; - const user = readEnv('QUESTDB_USER', 'RESEARCH_MCP_QUESTDB_USER'); - const password = readEnv('QUESTDB_PASSWORD', 'RESEARCH_MCP_QUESTDB_PASSWORD'); + const database = readEnv(env, 'QUESTDB_DATABASE', 'RESEARCH_MCP_QUESTDB_DATABASE') ?? 'qdb'; + const user = readEnv(env, 'QUESTDB_USER', 'RESEARCH_MCP_QUESTDB_USER'); + const password = readEnv(env, 'QUESTDB_PASSWORD', 'RESEARCH_MCP_QUESTDB_PASSWORD'); return { host, @@ -67,21 +85,29 @@ function resolveConfig(): QuestDbPgExecutorConfig { }; } -async function main(): Promise { - const config = resolveConfig(); - const handle = await openQuestDbPgExecutor(config); +export async function runQuestDbInitM2( + env: Readonly> = process.env, + openExecutor: typeof openQuestDbPgExecutor = openQuestDbPgExecutor +): Promise<{ readonly appliedTables: readonly string[] }> { + const config = resolveQuestDbInitM2Config(env); + const handle = await openExecutor(config); try { - const result = await applyM2IntradayDDL(handle.executor); - process.stdout.write( - `Initialized QuestDB M2 intraday tables: ${result.appliedTables.join(', ')}\n` - ); + return await applyM2IntradayDDL(handle.executor); } finally { await handle.close(); } } -main().catch((err: unknown) => { - const message = err instanceof Error ? err.message : String(err); - process.stderr.write(`questdb-init-m2 failed: ${message}\n`); - process.exit(1); -}); +if (import.meta.main) { + runQuestDbInitM2() + .then(result => { + process.stdout.write( + `Initialized QuestDB M2 intraday tables: ${result.appliedTables.join(', ')}\n` + ); + }) + .catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + process.stderr.write(`questdb-init-m2 failed: ${message}\n`); + process.exit(1); + }); +} diff --git a/scripts/test/questdb-init-m2.test.ts b/scripts/test/questdb-init-m2.test.ts new file mode 100644 index 00000000..0e4c1b35 --- /dev/null +++ b/scripts/test/questdb-init-m2.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, test } from 'bun:test'; +import { M2_INTRADAY_TABLE_NAMES } from '@stock-bot/questdb'; +import { resolveQuestDbInitM2Config, runQuestDbInitM2 } from '../questdb-init-m2'; + +describe('scripts/questdb-init-m2', () => { + test('rejects conflicting URL SSL settings before opening a QuestDB connection', async () => { + const secret = 'ddl_init_s3cr3t!'; + const baseUrl = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`; + + const conflictingEnvs: Array> = [ + { QUESTDB_URL: `${baseUrl}?sslmode=disable`, QUESTDB_SSL: 'true' }, + { RESEARCH_MCP_QUESTDB_URL: `${baseUrl}?sslmode=disable`, RESEARCH_MCP_QUESTDB_SSL: 'true' }, + { QUESTDB_URL: `${baseUrl}?sslmode=require`, QUESTDB_SSL: 'false' }, + { QUESTDB_URL: `${baseUrl}?ssl=false`, QUESTDB_SSL: 'true' }, + { QUESTDB_URL: `${baseUrl}?sslmode=prefer`, QUESTDB_SSL: 'true' }, + ]; + + let openCalls = 0; + for (const env of conflictingEnvs) { + let caught: unknown; + try { + await runQuestDbInitM2(env, async () => { + openCalls += 1; + throw new Error('openExecutor must not be called on conflicting SSL config'); + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(RangeError); + expect((caught as Error).message).toContain('SSL'); + expect((caught as Error).message).not.toContain(secret); + expect((caught as Error).message).not.toContain(baseUrl); + } + expect(openCalls).toBe(0); + }); + + test('rejects invalid SSL flag values and accepts consistent URL + SSL configs', async () => { + expect(() => + resolveQuestDbInitM2Config({ + QUESTDB_HOST: '10.0.0.51', + QUESTDB_SSL: 'maybe', + }) + ).toThrow(RangeError); + + const resolved = resolveQuestDbInitM2Config({ + QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=require', + QUESTDB_SSL: 'true', + }); + expect(resolved).toEqual({ + url: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=require', + ssl: true, + }); + + const executed: string[] = []; + let closed = false; + const result = await runQuestDbInitM2( + { + QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=disable', + QUESTDB_SSL: 'false', + }, + async () => ({ + executor: { + async query(sql: string) { + executed.push(sql); + return { rows: [] }; + }, + }, + async close() { + closed = true; + }, + }) + ); + + expect(result.appliedTables).toEqual([...M2_INTRADAY_TABLE_NAMES]); + expect(executed).toHaveLength(3); + expect(closed).toBe(true); + }); +});