diff --git a/AGENTS.md b/AGENTS.md index 452eafe9..e17d8648 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,6 +6,12 @@ - Typecheck: `bun run typecheck` - Tests: `bun test` (PostgreSQL safety tests require `PIPELINE_TEST_DATABASE_URL` pointing to a dedicated `stock_bot_safety*` database, configured via `/home/boki/.studio/test-env/stock-bot.env`). +### Check Gates & Sandbox Split +- **Why `bun run check` (`scripts/check.ts`) cannot pass end-to-end inside the agent sandbox**: worktree `.git` metadata lives outside the sandbox (breaking `audit:secrets` and the worktree-git tooling tests in `scripts/test/audit-secrets-repo.test.ts`, `strategy-packaging.test.ts`, `benchmark-research.test.ts`, `benchmark-replay.test.ts`, and `benchmark-sma.test.ts`), and sandbox network isolation blocks host PostgreSQL `127.0.0.1:5432` for `PIPELINE_TEST_DATABASE_URL` suites. +- **Sandbox-runnable gates (run locally before handoff)**: `bun run typecheck`, `bun run test:contracts`, `bun run lint:check`, `CARGO_BUILD_JOBS=2 bun run test:native`, `bun run test:utils`, `bun run test:calculations`, and targeted non-git/non-Postgres tests (e.g. `bun test scripts/test/security.test.ts`). +- **Studio unsandboxed verification (`bun run build` and `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test`)**: authoritatively covers `build`, `audit:secrets` (via `scripts/test/audit-secrets-repo.test.ts`), `test:tooling` (including all worktree-git tests), `test:integration`, and PostgreSQL-backed tests. Sandbox-only `.git`/PostgreSQL failures are not a review deadlock when Studio's unsandboxed run is green, and agents must never skip or mock out those checks to make them pass inside the sandbox. +- **Full host verification outside a sandbox**: run `CARGO_BUILD_JOBS=2 bun run check`. + ## Environments (`dev` / `qa` / `prod`) | Environment | `NODE_ENV` | Compose File | PostgreSQL | MongoDB (Write) | MongoDB (Read / Pipeline) | Dragonfly | QuestDB | diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index fda0dad9..740e1395 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -162,6 +162,66 @@ function isLoopbackHost(host?: string): boolean { ); } +const MAX_MONGO_HOST_DECODE_PASSES = 8; +const VALID_IPV6_ZONE_ID = /^[a-z0-9._~-]+$/i; +// Any URL authority/path/query/fragment delimiter, whitespace, or control char inside a +// decoded MongoDB seed host would be re-interpreted by ServerDescription.hostAddress's +// WHATWG URL re-parse (e.g., "localhost%2f:27018" -> "localhost/:27018" -> localhost:27017). +const FORBIDDEN_MONGO_HOST_CHARS = /[/?#@:\\[\],\s\x00-\x1f\x7f]/; +const FORBIDDEN_MONGO_IPV6_HOST_CHARS = /[/?#@\\[\],\s\x00-\x1f\x7f]/; + +function isValidIpv6WithZoneId(host: string): boolean { + const zoneIdx = host.indexOf('%'); + if (zoneIdx <= 0 || host.indexOf('%', zoneIdx + 1) !== -1) { + return false; + } + const addr = host.slice(0, zoneIdx); + const zone = host.slice(zoneIdx + 1); + return parseIpv6Hextets(addr) !== null && VALID_IPV6_ZONE_ID.test(zone); +} + +function decodeMongoHost(rawHost: string, isBracketedIpv6 = false): string { + // MongoDB driver 6.22.0 decodes seed hostnames once in HostAddress.fromString during + // URI parsing and a second time when ServerDescription.hostAddress reparses the + // serialized address for ConnectionPool/Monitor. Decode iteratively to a fixed point + // so double- or multi-encoded loopback hosts cannot bypass the guard. + let current = rawHost; + for (let pass = 0; pass < MAX_MONGO_HOST_DECODE_PASSES; pass++) { + let decoded: string; + try { + decoded = decodeURIComponent(current); + } catch (error) { + if (error instanceof URIError) { + // After the first decode of a bracketed IPv6 literal, a literal '%' is allowed + // only when it separates a valid IPv6 address from a valid zone identifier + // (e.g., "::1%25lo" -> "::1%lo"). + if (isBracketedIpv6 && pass > 0 && isValidIpv6WithZoneId(current)) { + break; + } + throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`); + } + throw error; + } + if (decoded === current) { + break; + } + current = decoded; + if (isBracketedIpv6 && isValidIpv6WithZoneId(current)) { + break; + } + } + if (current.includes('%') && !(isBracketedIpv6 && isValidIpv6WithZoneId(current))) { + throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`); + } + const forbiddenChars = isBracketedIpv6 + ? FORBIDDEN_MONGO_IPV6_HOST_CHARS + : FORBIDDEN_MONGO_HOST_CHARS; + if (forbiddenChars.test(current)) { + throw new Error(`Safety guard: invalid characters in MongoDB host "${rawHost}".`); + } + return current.toLowerCase(); +} + function parseMongoHostPort( segment: string, defaultPort: number | undefined @@ -176,7 +236,11 @@ function parseMongoHostPort( if (closeIdx <= 1) { return null; } - const host = trimmed.slice(1, closeIdx).trim(); + const rawHost = trimmed.slice(1, closeIdx).trim(); + if (!rawHost) { + return null; + } + const host = decodeMongoHost(rawHost, true).trim(); if (!host) { return null; } @@ -200,14 +264,22 @@ function parseMongoHostPort( const colonIdx = trimmed.indexOf(':'); if (colonIdx === -1) { - return { host: trimmed, port: defaultPort }; + const host = decodeMongoHost(trimmed).trim(); + if (!host) { + return null; + } + return { host, port: defaultPort }; } if (trimmed.indexOf(':', colonIdx + 1) !== -1) { return null; } - const host = trimmed.slice(0, colonIdx).trim(); + const rawHost = trimmed.slice(0, colonIdx).trim(); const portStr = trimmed.slice(colonIdx + 1).trim(); + if (!rawHost) { + return null; + } + const host = decodeMongoHost(rawHost).trim(); if (!host) { return null; } diff --git a/scripts/audit-secrets.ts b/scripts/audit-secrets.ts index ff757830..7a2312ad 100644 --- a/scripts/audit-secrets.ts +++ b/scripts/audit-secrets.ts @@ -1,4 +1,5 @@ import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; // Explicit private local-development exceptions, not a general permission to track secrets. const localDevelopmentEnvironmentFiles = new Set(['.env', 'apps/stock/web-app/.env']); @@ -109,15 +110,40 @@ export function unexpectedTrackedEnvironmentFiles(paths: readonly string[]): str }); } +/** Resolve the top-level Git repository root for the given working directory. */ +export function resolveRepoRoot(cwd: string = process.cwd()): string { + const result = Bun.spawnSync(['git', 'rev-parse', '--show-toplevel'], { + cwd, + stdout: 'pipe', + stderr: 'pipe', + }); + const repoRoot = new TextDecoder().decode(result.stdout).replace(/\r?\n$/, ''); + if (result.exitCode !== 0 || !repoRoot) { + throw new Error('Cannot inspect tracked files for the secret audit'); + } + return repoRoot; +} + +/** List all tracked repository paths relative to the top-level Git repository root. */ +export function listTrackedFiles(repoRoot: string): string[] { + const result = Bun.spawnSync(['git', 'ls-files', '-z', '--full-name'], { + cwd: repoRoot, + stdout: 'pipe', + stderr: 'pipe', + }); + if (result.exitCode !== 0) { + throw new Error('Cannot inspect tracked files for the secret audit'); + } + return new TextDecoder().decode(result.stdout).split('\0').filter(Boolean); +} + if (import.meta.main) { - const result = Bun.spawnSync(['git', 'ls-files', '-z']); - if (result.exitCode !== 0) throw new Error('Cannot inspect tracked files for the secret audit'); - const trackedPaths = new TextDecoder() - .decode(result.stdout) - .split('\0') - .filter(Boolean); + const repoRoot = resolveRepoRoot(); + const trackedPaths = listTrackedFiles(repoRoot); const envFiles = unexpectedTrackedEnvironmentFiles(trackedPaths); - const credentialHits = scanTrackedFilesForHttpCredentials(trackedPaths); + const credentialHits = scanTrackedFilesForHttpCredentials(trackedPaths, path => + defaultReadFile(join(repoRoot, path)) + ); if (envFiles.length) { process.stderr.write(`Unexpected tracked environment files: ${envFiles.join(', ')}\n`); diff --git a/scripts/test/audit-secrets-repo.test.ts b/scripts/test/audit-secrets-repo.test.ts new file mode 100644 index 00000000..cbcd3297 --- /dev/null +++ b/scripts/test/audit-secrets-repo.test.ts @@ -0,0 +1,285 @@ +import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { expect, test } from 'bun:test'; + +const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); +const auditScript = fileURLToPath(new URL('../audit-secrets.ts', import.meta.url)); + +function isolatedGitEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(baseEnv)) { + if (value !== undefined && !key.startsWith('GIT_')) { + env[key] = value; + } + } + return env; +} + +function decodeRun(result: ReturnType) { + return { + exitCode: result.exitCode, + stdout: new TextDecoder().decode(result.stdout), + stderr: new TextDecoder().decode(result.stderr), + }; +} + +function runAuditSecrets( + cwd: string, + baseEnv: NodeJS.ProcessEnv = process.env, + fixtureEnv: Record = {} +) { + return decodeRun( + Bun.spawnSync([process.execPath, auditScript], { + cwd, + env: { ...isolatedGitEnv(baseEnv), ...fixtureEnv }, + stdout: 'pipe', + stderr: 'pipe', + }) + ); +} + +// Stop Git discovery at the fixture directory so a TMPDIR inside a checkout cannot +// make Git find the parent repository and audit an unrelated (or empty) file list. +function ceilingAt(dir: string): Record { + return { GIT_CEILING_DIRECTORIES: dirname(realpathSync(dir)) }; +} + +/** A throwaway Git repo whose index tracks one file containing a non-placeholder credential URL. */ +function createLeakingRepo( + root: string, + relativePath = 'leaked.ts' +): { gitDir: string; indexFile: string } { + const env = isolatedGitEnv(); + expect(Bun.spawnSync(['git', 'init', '-q'], { cwd: root, env }).exitCode).toBe(0); + const leakedUrl = `${'https'}://repo-fixture-user:repo-fixture-pass@proxy.vendor.io`; + const targetPath = join(root, relativePath); + mkdirSync(dirname(targetPath), { recursive: true }); + writeFileSync(targetPath, `export const url = "${leakedUrl}";\n`, 'utf8'); + expect(Bun.spawnSync(['git', 'add', relativePath], { cwd: root, env }).exitCode).toBe(0); + return { gitDir: join(root, '.git'), indexFile: join(root, '.git', 'index') }; +} + +/** A throwaway Git repo tracking the specified files with benign contents. */ +function createFixtureRepo(root: string, files: Record): void { + const env = isolatedGitEnv(); + expect(Bun.spawnSync(['git', 'init', '-q'], { cwd: root, env }).exitCode).toBe(0); + for (const [relativePath, content] of Object.entries(files)) { + const targetPath = join(root, relativePath); + mkdirSync(dirname(targetPath), { recursive: true }); + writeFileSync(targetPath, content, 'utf8'); + expect(Bun.spawnSync(['git', 'add', '-f', relativePath], { cwd: root, env }).exitCode).toBe(0); + } +} + +test('audit:secrets passes on the real repository', () => { + const result = runAuditSecrets(repoRoot); + + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toBe(''); + expect(result.stdout).toContain('Secret audit passed'); +}); + +test('audit:secrets fails closed when git metadata is unavailable', () => { + const tempDir = mkdtempSync(join(tmpdir(), 'audit-secrets-no-git-')); + + try { + const result = runAuditSecrets(tempDir, process.env, ceilingAt(tempDir)); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain('Cannot inspect tracked files for the secret audit'); + expect(result.stdout).not.toContain('Secret audit passed'); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('audit:secrets fails closed in a non-repo directory nested inside another checkout', () => { + const outerRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-outer-repo-')); + + try { + createLeakingRepo(outerRepo); + const nestedDir = join(outerRepo, 'tmp', 'audit-secrets-no-git'); + mkdirSync(nestedDir, { recursive: true }); + + const result = runAuditSecrets(nestedDir, process.env, ceilingAt(nestedDir)); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain('Cannot inspect tracked files for the secret audit'); + expect(result.stdout).not.toContain('Secret audit passed'); + } finally { + rmSync(outerRepo, { recursive: true, force: true }); + } +}); + +test('real-repository audit ignores inherited GIT_DIR, GIT_WORK_TREE and GIT_INDEX_FILE', () => { + const callerRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-polluted-env-')); + + try { + const { gitDir, indexFile } = createLeakingRepo(callerRepo); + const pollutedEnv: NodeJS.ProcessEnv = { + ...process.env, + GIT_DIR: gitDir, + GIT_WORK_TREE: callerRepo, + GIT_INDEX_FILE: indexFile, + }; + + // Sensitivity check: unstripped, these variables really do redirect the audit to the + // leaking fixture repo, so a pass below proves the stripping is what protects it. + const redirected = decodeRun( + Bun.spawnSync([process.execPath, auditScript], { + cwd: callerRepo, + env: pollutedEnv as Record, + stdout: 'pipe', + stderr: 'pipe', + }) + ); + expect(redirected.exitCode).toBe(1); + expect(redirected.stderr).toContain('leaked.ts:1'); + + const indexBefore = readFileSync(indexFile); + const result = runAuditSecrets(repoRoot, pollutedEnv); + + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toBe(''); + expect(result.stdout).toContain('Secret audit passed'); + expect(readFileSync(indexFile)).toEqual(indexBefore); + } finally { + rmSync(callerRepo, { recursive: true, force: true }); + } +}); + +test('audit:secrets never echoes the leaked credential when reporting a finding', () => { + const leakingRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-leak-')); + + try { + createLeakingRepo(leakingRepo); + + const result = runAuditSecrets(leakingRepo, process.env, ceilingAt(leakingRepo)); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Embedded HTTP(S) credentials found: leaked.ts:1'); + expect(result.stdout).not.toContain('Secret audit passed'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-pass'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-user'); + } finally { + rmSync(leakingRepo, { recursive: true, force: true }); + } +}); + +test('audit:secrets audits full repo from a nested empty subdirectory', () => { + const leakingRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-subdir-empty-')); + + try { + createLeakingRepo(leakingRepo); + const emptySubdir = join(leakingRepo, 'sub', 'empty'); + mkdirSync(emptySubdir, { recursive: true }); + + const result = runAuditSecrets(emptySubdir, process.env, ceilingAt(leakingRepo)); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Embedded HTTP(S) credentials found: leaked.ts:1'); + expect(result.stdout).not.toContain('Secret audit passed'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-user'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-pass'); + } finally { + rmSync(leakingRepo, { recursive: true, force: true }); + } +}); + +test('audit:secrets audits full repo from a sibling subdirectory', () => { + const leakingRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-subdir-sibling-')); + + try { + createLeakingRepo(leakingRepo, 'pkg-a/leaked.ts'); + const siblingDir = join(leakingRepo, 'pkg-b'); + mkdirSync(siblingDir, { recursive: true }); + + const result = runAuditSecrets(siblingDir, process.env, ceilingAt(leakingRepo)); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Embedded HTTP(S) credentials found: pkg-a/leaked.ts:1'); + expect(result.stdout).not.toContain('Secret audit passed'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-user'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-pass'); + } finally { + rmSync(leakingRepo, { recursive: true, force: true }); + } +}); + +test('audit:secrets catches unexpected tracked .env from subdirectories without false root exemption', () => { + const repo = mkdtempSync(join(tmpdir(), 'audit-secrets-subdir-env-')); + + try { + createFixtureRepo(repo, { + 'apps/stock/web-api/.env': 'API_KEY=dummy\n', + }); + const emptySubdir = join(repo, 'empty'); + mkdirSync(emptySubdir, { recursive: true }); + + const fromEmpty = runAuditSecrets(emptySubdir, process.env, ceilingAt(repo)); + expect(fromEmpty.exitCode).toBe(1); + expect(fromEmpty.stderr).toContain( + 'Unexpected tracked environment files: apps/stock/web-api/.env' + ); + expect(fromEmpty.stdout).not.toContain('Secret audit passed'); + + const fromWebApi = runAuditSecrets( + join(repo, 'apps', 'stock', 'web-api'), + process.env, + ceilingAt(repo) + ); + expect(fromWebApi.exitCode).toBe(1); + expect(fromWebApi.stderr).toContain( + 'Unexpected tracked environment files: apps/stock/web-api/.env' + ); + expect(fromWebApi.stdout).not.toContain('Secret audit passed'); + } finally { + rmSync(repo, { recursive: true, force: true }); + } +}); + +test('audit:secrets preserves documented .env exception when run from a subdirectory', () => { + const repo = mkdtempSync(join(tmpdir(), 'audit-secrets-subdir-allowed-env-')); + + try { + createFixtureRepo(repo, { + 'apps/stock/web-app/.env': 'PUBLIC_URL=http://localhost:3000\n', + }); + const scriptsDir = join(repo, 'scripts'); + mkdirSync(scriptsDir, { recursive: true }); + + const result = runAuditSecrets(scriptsDir, process.env, ceilingAt(repo)); + + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toBe(''); + expect(result.stdout).toContain('Secret audit passed'); + } finally { + rmSync(repo, { recursive: true, force: true }); + } +}); + +test('audit:secrets fails closed when run inside a repository .git directory', () => { + const repo = mkdtempSync(join(tmpdir(), 'audit-secrets-gitdir-')); + + try { + const { gitDir } = createLeakingRepo(repo); + + const result = runAuditSecrets(gitDir, process.env, ceilingAt(repo)); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain('Cannot inspect tracked files for the secret audit'); + expect(result.stdout).not.toContain('Secret audit passed'); + } finally { + rmSync(repo, { recursive: true, force: true }); + } +}); + +test('audit:secrets passes on the real repository when run from scripts subdirectory', () => { + const result = runAuditSecrets(join(repoRoot, 'scripts')); + + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toBe(''); + expect(result.stdout).toContain('Secret audit passed'); +}); diff --git a/test/unit/environment-safety-encoded-host.test.ts b/test/unit/environment-safety-encoded-host.test.ts new file mode 100644 index 00000000..0cab3edc --- /dev/null +++ b/test/unit/environment-safety-encoded-host.test.ts @@ -0,0 +1,811 @@ +import { createRequire } from 'node:module'; +import { describe, expect, test } from 'bun:test'; +import { + assertEnvironmentSafety, + stockAppSchema, + type StockAppConfig, +} from '@stock-bot/stock-config'; +import { MongoClient, type HostAddress, type ServerDescription } from 'mongodb'; + +const requireFromHere = createRequire(import.meta.url); +const { ServerDescription: DriverServerDescription } = requireFromHere( + 'mongodb/lib/sdam/server_description' +) as { + ServerDescription: new (address: HostAddress | string) => ServerDescription; +}; + +function getDriverDialHostAddress(seed: HostAddress): HostAddress { + // Mirrors Topology -> ServerDescription -> Server/Monitor (description.hostAddress) + // without opening any socket or calling connect(). + return new DriverServerDescription(seed).hostAddress; +} + +function makeConfig( + overrides: { + environment?: 'development' | 'qa' | 'test' | 'production'; + pgHost?: string; + pgPort?: number; + pgDatabase?: string; + pgPassword?: string; + mongoUri?: string; + mongoReadUri?: string; + mongoReadOnly?: boolean; + mongoDatabase?: string; + bypassSchemaValidation?: boolean; + } = {} +): StockAppConfig { + const defaultMongoUri = + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin'; + const defaultMongoReadUri = + 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock'; + + const parsed = stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + environment: overrides.environment ?? 'development', + service: { + name: 'stock-bot', + port: 2002, + host: '127.0.0.1', + }, + log: { + level: 'info', + format: 'json', + }, + database: { + postgres: { + enabled: true, + host: overrides.pgHost ?? 'localhost', + port: overrides.pgPort ?? 5433, + database: overrides.pgDatabase ?? 'trading_bot_dev', + user: 'dev_user', + password: overrides.pgPassword ?? 'dev_pass', + ssl: false, + }, + mongodb: { + enabled: true, + uri: overrides.bypassSchemaValidation + ? defaultMongoUri + : (overrides.mongoUri ?? defaultMongoUri), + readUri: overrides.bypassSchemaValidation + ? defaultMongoReadUri + : (overrides.mongoReadUri ?? defaultMongoReadUri), + readOnly: overrides.mongoReadOnly ?? false, + database: overrides.mongoDatabase ?? 'stock_dev', + }, + questdb: { + enabled: false, + host: 'localhost', + ilpPort: 9010, + httpPort: 9100, + pgPort: 8813, + }, + dragonfly: { + enabled: true, + host: 'localhost', + port: 6380, + }, + }, + providers: { + yahoo: { + name: 'yahoo', + enabled: false, + priority: 1, + timeout: 30000, + baseUrl: 'https://query1.finance.yahoo.com', + }, + qm: { + name: 'qm', + enabled: false, + priority: 2, + username: '', + password: '', + baseUrl: 'https://app.quotemedia.com/quotetools', + webmasterId: '', + }, + ib: { + name: 'ib', + enabled: false, + priority: 3, + gateway: { host: 'localhost', port: 5000, clientId: 1 }, + marketDataType: 'delayed', + }, + eod: { + name: 'eod', + enabled: false, + priority: 4, + apiKey: '', + baseUrl: 'https://eodhistoricaldata.com/api', + tier: 'free', + }, + }, + features: {}, + }); + + if (overrides.bypassSchemaValidation) { + if (overrides.mongoUri !== undefined) { + parsed.database.mongodb.uri = overrides.mongoUri; + } + if (overrides.mongoReadUri !== undefined) { + parsed.database.mongodb.readUri = overrides.mongoReadUri; + } + } + + return parsed; +} + +function isDriverHostLoopback(host: string): boolean { + const normalized = host + .trim() + .replace(/^\[|\]$/g, '') + .replace(/\.+$/, '') + .toLowerCase(); + if (normalized === 'localhost' || normalized === '0.0.0.0' || normalized === '::1') { + return true; + } + if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized)) { + return true; + } + if (normalized.startsWith('::1%')) { + return true; + } + if (/^::ffff:(?:7f[0-9a-f]{2}:[0-9a-f]{1,4}|127\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(normalized)) { + return true; + } + return false; +} + +describe('Environment safety — percent-encoded MongoDB seed hosts', () => { + test('blocks percent-encoded localhost QA URI for dataIngestion and unsafe dataPipeline', () => { + const encodedQaUri = 'mongodb://u:p@%6cocalhost:27017/stock'; + + const ingestionCfg = makeConfig({ + environment: 'development', + mongoUri: encodedQaUri, + mongoDatabase: 'stock', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + + const pipelineNonReadOnly = makeConfig({ + environment: 'development', + mongoReadUri: encodedQaUri, + mongoReadOnly: false, + mongoDatabase: 'stock', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(pipelineNonReadOnly, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + + const pipelineAdmin = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://trading_admin:pass@%6cocalhost:27017/stock', + mongoReadOnly: true, + mongoDatabase: 'stock', + bypassSchemaValidation: true, + }); + expect(() => + assertEnvironmentSafety(pipelineAdmin, 'dataPipeline', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/); + }); + + test('blocks encoded loopback variants (IPv4, mixed-case, trailing dot, omitted port, srv, IPv6)', () => { + const encodedLoopbackUris = [ + 'mongodb://u:p@%6cocalhost:27017/stock', + 'mongodb://u:p@%31%32%37%2e%30%2e%30%2e%31:27017/stock', + 'mongodb://u:p@127%2E0.0.1:27017/stock', + 'mongodb://u:p@%4C%6fCalHost:27017/stock', + 'mongodb://u:p@%4C%4F%43%41%4C%48%4F%53%54:27017/stock', + 'mongodb://u:p@%6cocalhost%2e:27017/stock', + 'mongodb://u:p@%6cocalhost/stock', + 'mongodb+srv://u:p@%6cocalhost/stock', + 'mongodb://u:p@[::1%25lo]:27017/stock', + 'mongodb://u:p@[::ffff:%37%66%30%30:1]:27017/stock', + ]; + + for (const mongoUri of encodedLoopbackUris) { + const ingestionCfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + + const pipelineCfg = makeConfig({ + environment: 'development', + mongoReadUri: mongoUri, + mongoReadOnly: false, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + } + }); + + test('blocks encoded QA loopback hosts inside multi-host seed lists', () => { + const multiHostUris = [ + 'mongodb://u:p@localhost:27018,%6cocalhost:27017/stock_dev', + 'mongodb://u:p@localhost:27018,%31%32%37.0.0.1/stock_dev', + ]; + + for (const mongoUri of multiHostUris) { + const ingestionCfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + + const pipelineCfg = makeConfig({ + environment: 'development', + mongoReadUri: mongoUri, + mongoReadOnly: false, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + } + }); + + test('allows safe dev URIs, read-only encoded QA dataPipeline, and explicit escape hatch', () => { + const safeDevUris = [ + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev', + 'mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27018/stock_dev', + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev', + ]; + + for (const mongoUri of safeDevUris) { + const cfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); + } + + const readOnlyEncodedPipeline = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://studio_stock_bot_read:secret@%6cocalhost:27017/stock?authSource=stock', + mongoReadOnly: true, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(readOnlyEncodedPipeline, 'dataPipeline', {})).not.toThrow(); + + const escapedEncodedIngestion = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://u:p@%6cocalhost:27017/stock', + mongoDatabase: 'stock', + bypassSchemaValidation: true, + }); + expect(() => + assertEnvironmentSafety(escapedEncodedIngestion, 'dataIngestion', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).not.toThrow(); + }); + + test('fails closed with an explicit error on malformed percent-encoding in MongoDB host', () => { + const malformedUris = [ + 'mongodb://u:p@%zz:27017/stock', + 'mongodb://u:p@%zz:27018/stock_dev', + 'mongodb://u:p@localhost:27018,%zz:27017/stock_dev', + 'mongodb://u:p@local%2:27017/stock', + 'mongodb://u:p@localhost%:27017/stock', + 'mongodb://u:p@[::1%zz]:27017/stock', + 'mongodb://u:p@[not-ipv6%25zz]:27017/stock', + 'mongodb://u:p@[::1%25]:27017/stock', + 'mongodb://u:p@[::1%25lo%2f]:27017/stock', + ]; + + for (const mongoUri of malformedUris) { + const ingestionCfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( + /Safety guard: invalid percent-encoding in MongoDB host/ + ); + expect(() => + assertEnvironmentSafety(ingestionCfg, 'dataIngestion', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).toThrow(/Safety guard: invalid percent-encoding in MongoDB host/); + + const pipelineCfg = makeConfig({ + environment: 'development', + mongoReadUri: mongoUri, + mongoReadOnly: true, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow( + /Safety guard: invalid percent-encoding in MongoDB host/ + ); + expect(() => + assertEnvironmentSafety(pipelineCfg, 'dataPipeline', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).toThrow(/Safety guard: invalid percent-encoding in MongoDB host/); + } + }); + + test('blocks double-encoded and multi-encoded loopback seeds that ServerDescription reparses to loopback', () => { + // Strictly offline: verify MongoDB 6.22.0 ServerDescription.hostAddress decodes a second time. + const doubleEncodedLocalhost = 'mongodb://u:p@%256cocalhost:27017/stock'; + const doubleEncodedIpv4 = 'mongodb://u:p@%2531%2532%2537.0.0.1:27017/stock'; + + const localhostSeed = new MongoClient(doubleEncodedLocalhost).options.hosts[0]; + expect(localhostSeed?.toString()).toBe('%6cocalhost:27017'); + expect(getDriverDialHostAddress(localhostSeed!).toString()).toBe('localhost:27017'); + + const ipv4Seed = new MongoClient(doubleEncodedIpv4).options.hosts[0]; + expect(ipv4Seed?.toString()).toBe('%31%32%37.0.0.1:27017'); + expect(getDriverDialHostAddress(ipv4Seed!).toString()).toBe('127.0.0.1:27017'); + + const multiEncodedQaUris = [ + doubleEncodedLocalhost, + doubleEncodedIpv4, + 'mongodb://u:p@localhost:27018,%256cocalhost:27017/stock_dev', + 'mongodb://u:p@%25256cocalhost:27017/stock', + ]; + + for (const mongoUri of multiEncodedQaUris) { + const ingestionCfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + + const pipelineNonReadOnly = makeConfig({ + environment: 'development', + mongoReadUri: mongoUri, + mongoReadOnly: false, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(pipelineNonReadOnly, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + } + + const pipelineAdmin = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://trading_admin:pass@%256cocalhost:27017/stock', + mongoReadOnly: true, + mongoDatabase: 'stock', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(pipelineAdmin, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + + // Safe dev port and read-only dataPipeline with double-encoded loopback still pass. + const devPortCfg = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://dev_admin:dev_mongo_pass@%256cocalhost:27018/stock_dev', + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(devPortCfg, 'dataIngestion', {})).not.toThrow(); + + const readOnlyPipelineCfg = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://studio_stock_bot_read:secret@%256cocalhost:27017/stock?authSource=stock', + mongoReadOnly: true, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(readOnlyPipelineCfg, 'dataPipeline', {})).not.toThrow(); + + // Double-encoded malformed escape (%25zz -> %zz) and excessive nesting fail closed. + const doubleMalformedUri = 'mongodb://u:p@%25zz:27017/stock'; + const doubleMalformedSeed = new MongoClient(doubleMalformedUri).options.hosts[0]; + expect(() => getDriverDialHostAddress(doubleMalformedSeed!)).toThrow(); + + for (const badUri of [ + doubleMalformedUri, + 'mongodb://u:p@%2525252525252525256cocalhost:27017/stock', + ]) { + const cfg = makeConfig({ + environment: 'development', + mongoUri: badUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( + /Safety guard: invalid percent-encoding in MongoDB host/ + ); + } + }); + + test('matches MongoDB driver ServerDescription.hostAddress dial target offline without connecting', () => { + const parityCases = [ + 'mongodb://u:p@localhost:27017/stock', + 'mongodb://u:p@%6cocalhost:27017/stock', + 'mongodb://u:p@%256cocalhost:27017/stock', + 'mongodb://u:p@%4C%6fCalHost:27017/stock', + 'mongodb://u:p@%31%32%37%2e%30%2e%30%2e%31:27017/stock', + 'mongodb://u:p@%2531%2532%2537.0.0.1:27017/stock', + 'mongodb://u:p@127%2E0.0.1:27017/stock', + 'mongodb://u:p@%6cocalhost/stock', + 'mongodb://u:p@localhost:27018,%6cocalhost:27017/stock_dev', + 'mongodb://u:p@localhost:27018,%256cocalhost:27017/stock_dev', + 'mongodb://u:p@localhost:27018,%31%32%37.0.0.1/stock_dev', + 'mongodb://u:p@localhost:27018/stock_dev', + 'mongodb://u:p@%6cocalhost:27018/stock_dev', + 'mongodb://u:p@%256cocalhost:27018/stock_dev', + 'mongodb://u:p@mongo.internal:27017/stock', + ]; + + for (const uri of parityCases) { + // Strictly offline: inspect the final HostAddress produced by ServerDescription.hostAddress; never call connect(). + const client = new MongoClient(uri); + const driverTargetsQa = client.options.hosts.some(entry => { + const dialHost = getDriverDialHostAddress(entry); + return ( + typeof dialHost.host === 'string' && + isDriverHostLoopback(dialHost.host) && + (dialHost.port === undefined || dialHost.port === 27017) + ); + }); + + const cfg = makeConfig({ + environment: 'development', + mongoUri: uri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + + let guardBlocked = false; + try { + assertEnvironmentSafety(cfg, 'dataIngestion', {}); + } catch { + guardBlocked = true; + } + + expect(guardBlocked).toBe(driverTargetsQa); + } + + // Malformed percent-encoding: both guard and MongoClient reject it offline. + const malformedUri = 'mongodb://u:p@%zz:27017/stock'; + expect(() => new MongoClient(malformedUri)).toThrow(); + const malformedCfg = makeConfig({ + environment: 'development', + mongoUri: malformedUri, + mongoDatabase: 'stock', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(malformedCfg, 'dataIngestion', {})).toThrow( + /Safety guard: invalid percent-encoding in MongoDB host/ + ); + }); + + test('blocks seeds whose decoded host smuggles a URL delimiter that ServerDescription reparses to QA loopback', () => { + // QA regression: HostAddress decodes "localhost%2f" to host "localhost/" and keeps the explicit + // port, so the seed serializes as "localhost/:27018". ServerDescription.hostAddress then reparses + // that string with WHATWG URL, which stops the authority at "/" and dials localhost:27017 (QA). + const delimiterSmuggledUris = [ + 'mongodb://u:p@localhost%2f:27018/stock_dev', + 'mongodb://u:p@%6cocalhost%2f:27018/stock_dev', + 'mongodb://u:p@localhost%3f:27018/stock_dev', + 'mongodb://u:p@localhost%23:27018/stock_dev', + 'mongodb://u:p@%6cocalhost%3a27017%2f:27018/stock_dev', + 'mongodb://u:p@x%40localhost%3a27017%2f:27018/stock_dev', + 'mongodb://u:p@%5b%3a%3a1%5d%3a27017%2f:27018/stock_dev', + 'mongodb://u:p@localhost:27018,localhost%2f:27019/stock_dev', + ]; + + for (const mongoUri of delimiterSmuggledUris) { + // Arrange: prove offline that the driver's final dial target is QA MongoDB. + const dialTargets = new MongoClient(mongoUri).options.hosts.map(seed => + getDriverDialHostAddress(seed) + ); + expect( + dialTargets.some( + target => + typeof target.host === 'string' && isDriverHostLoopback(target.host) && target.port === 27017 + ) + ).toBe(true); + + const ingestionCfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + const pipelineCfg = makeConfig({ + environment: 'development', + mongoReadUri: mongoUri, + mongoReadOnly: false, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + + // Act + assert: the guard must not allow either service to start. + expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( + /Safety guard/ + ); + expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow(/Safety guard/); + } + }); + + test('never allows a seed whose driver dial target is QA loopback:27017 (offline parity sweep)', () => { + // Every case is built so the guard sees a non-QA seed unless it follows the driver's reparse. + const hostSpellings = [ + 'localhost', + '%6cocalhost', + '%256cocalhost', + '127.0.0.1', + '%31%32%37.0.0.1', + '[::1]', + 'localhost%2f', + 'localhost%3f', + 'localhost%23', + 'localhost%3a27017%2f', + 'localhost%3a27017', + 'localhost%2c127.0.0.1', + 'mongo.internal', + 'mongo.internal%2f', + ]; + const ports = [':27017', ':27018', '']; + + const bypasses: string[] = []; + for (const host of hostSpellings) { + for (const port of ports) { + const uri = `mongodb://u:p@${host}${port}/stock_dev`; + let dialsQa = false; + try { + dialsQa = new MongoClient(uri).options.hosts.some(seed => { + const target = getDriverDialHostAddress(seed); + return ( + typeof target.host === 'string' && + isDriverHostLoopback(target.host) && + target.port === 27017 + ); + }); + } catch { + // The driver refuses this URI before dialing, so no QA connection is possible. + dialsQa = false; + } + + const cfg = makeConfig({ + environment: 'development', + mongoUri: uri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + let guardBlocked = false; + try { + assertEnvironmentSafety(cfg, 'dataIngestion', {}); + } catch { + guardBlocked = true; + } + + if (dialsQa && !guardBlocked) { + bypasses.push(uri); + } + } + } + + expect(bypasses).toEqual([]); + }); + + test('does not throw on literal IPv6 zone ID in raw PostgreSQL host', () => { + const cfg = makeConfig({ + environment: 'development', + pgHost: 'fe80::1%eth0', + pgPort: 5432, + pgDatabase: 'trading_bot', + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); + }); + + test('fails closed with an explicit error on decoded URL delimiters, backslashes, or whitespace in MongoDB host', () => { + const smuggledUris = [ + 'mongodb://u:p@localhost%252f:27018/stock_dev', + 'mongodb://u:p@localhost%5c:27018/stock_dev', + 'mongodb://u:p@localhost%20:27018/stock_dev', + 'mongodb://u:p@[::1%2f]:27018/stock_dev', + ]; + + for (const mongoUri of smuggledUris) { + const cfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( + /Safety guard: invalid characters in MongoDB host/ + ); + expect(() => + assertEnvironmentSafety(cfg, 'dataIngestion', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).toThrow(/Safety guard: invalid characters in MongoDB host/); + } + }); + + test('seeded random percent-encoding sweep never allows a seed the driver dials as QA loopback:27017', () => { + // Deterministic LCG (fixed seed) so the sweep is reproducible; strictly offline, no connect(). + let state = 20261127; + const nextRandom = (): number => { + state = (Math.imul(state, 1103515245) + 12345) & 0x7fffffff; + return state / 0x7fffffff; + }; + const encodeChar = (ch: string): string => { + const hex = ch.charCodeAt(0).toString(16).padStart(2, '0'); + return `%${nextRandom() < 0.5 ? hex.toUpperCase() : hex}`; + }; + const encodeHost = (host: string, depth: number): string => { + let out = ''; + for (const ch of host) { + out += nextRandom() < 0.4 ? encodeChar(ch) : ch; + } + for (let level = 1; level < depth; level++) { + out = out.replace(/%/g, '%25'); + } + return out; + }; + + const baseHosts = [ + 'localhost', + 'LocalHost', + 'localhost.', + '127.0.0.1', + '127.1.2.3', + '0.0.0.0', + '[::1]', + 'localhost/', + 'localhost?', + 'localhost#', + 'localhost:27017', + 'localhost:27017/', + '[::1]:27017/', + 'localhost,localhost', + 'loc%0aalhost', + 'localhost%09', + 'loc%00alhost', + 'x%40localhost', + '%5b::1%5d', + 'mongo.internal', + ]; + const portSuffixes = [':27017', ':27018', '']; + + const bypasses: string[] = []; + let driverQaDialCount = 0; + for (let iteration = 0; iteration < 3000; iteration++) { + const base = baseHosts[Math.floor(nextRandom() * baseHosts.length)] ?? 'localhost'; + const port = portSuffixes[Math.floor(nextRandom() * portSuffixes.length)] ?? ''; + const depth = 1 + Math.floor(nextRandom() * 3); + const uri = `mongodb://u:p@${encodeHost(base, depth)}${port}/stock_dev`; + + let dialsQa = false; + try { + dialsQa = new MongoClient(uri).options.hosts.some(seed => { + const target = getDriverDialHostAddress(seed); + return ( + typeof target.host === 'string' && + isDriverHostLoopback(target.host) && + target.port === 27017 + ); + }); + } catch { + // Driver refuses the URI or seed before dialing, so no QA socket can be opened. + dialsQa = false; + } + if (!dialsQa) { + continue; + } + driverQaDialCount++; + + const cfg = makeConfig({ + environment: 'development', + mongoUri: uri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + let guardBlocked = false; + try { + assertEnvironmentSafety(cfg, 'dataIngestion', {}); + } catch { + guardBlocked = true; + } + if (!guardBlocked) { + bypasses.push(uri); + } + } + + // Guard against a vacuous sweep: plenty of generated URIs must really dial QA. + expect(driverQaDialCount).toBeGreaterThan(500); + expect(bypasses).toEqual([]); + }); + + test('allows encoded dev-port loopback seeds that the driver dials on 27018', () => { + const devUris = [ + 'mongodb://dev_admin:dev_mongo_pass@%6C%4F%63%61%6C%68%6F%73%74:27018/stock_dev', + 'mongodb://dev_admin:dev_mongo_pass@%2531%2532%2537.0.0.1:27018/stock_dev', + 'mongodb://dev_admin:dev_mongo_pass@[::1]:27018/stock_dev', + 'mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27018,127%2e0.0.1:27019/stock_dev', + ]; + + for (const mongoUri of devUris) { + // Arrange: confirm offline the driver never dials QA for these seeds. + const dialTargets = new MongoClient(mongoUri).options.hosts.map(seed => + getDriverDialHostAddress(seed) + ); + expect(dialTargets.every(target => target.port !== 27017)).toBe(true); + + const cfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); + } + }); + + test('schema-validated config path blocks percent-encoded QA seed for dataIngestion', () => { + // No bypassSchemaValidation: the URI must survive stockAppSchema.parse and still be blocked. + const cfg = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27017/stock?authSource=admin', + mongoDatabase: 'stock', + }); + + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + }); + + test('production and qa guards still accept ordinary TCP and SRV MongoDB hosts', () => { + const prodUris = [ + 'mongodb+srv://prod_user:Str0ngProdSecret@cluster0.prod-db.example.net/stock?retryWrites=true', + 'mongodb://prod_user:Str0ngProdSecret@mongo-0.prod.internal:27017,mongo-1.prod.internal:27017/stock?replicaSet=rs0', + 'mongodb://prod_user:Str0ngProdSecret@%6dongo-0.prod.internal:27017/stock', + ]; + + for (const mongoUri of prodUris) { + const prodCfg = makeConfig({ + environment: 'production', + pgPassword: 'Str0ngProdPgSecret', + mongoUri, + mongoDatabase: 'stock', + }); + expect(() => assertEnvironmentSafety(prodCfg, 'dataIngestion', {})).not.toThrow(); + + const qaCfg = makeConfig({ + environment: 'qa', + pgDatabase: 'trading_bot', + mongoUri, + mongoDatabase: 'stock', + }); + expect(() => assertEnvironmentSafety(qaCfg, 'dataIngestion', {})).not.toThrow(); + } + }); +});