diff --git a/.env.example b/.env.example index 3bffb1c8..953c7c24 100644 --- a/.env.example +++ b/.env.example @@ -14,3 +14,4 @@ EOD_API_KEY= QM_USERNAME= QM_PASSWORD= IB_ACCOUNT= +IB_PROXY_URL= diff --git a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges.action.ts b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges.action.ts index 567a0f3b..0743195f 100644 --- a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges.action.ts @@ -1,5 +1,5 @@ import type { IServiceContainer } from '@stock-bot/services'; -import { IB_CONFIG } from '../shared/config'; +import { IB_CONFIG, getIbProxyUrl } from '../shared/config'; import { fetchSession } from './fetch-session.action'; export async function fetchExchanges(services: IServiceContainer): Promise { @@ -33,11 +33,13 @@ export async function fetchExchanges(services: IServiceContainer): Promise | undefined> { try { + const proxy = getIbProxyUrl(); const { browser } = requireServices(services, 'browser'); await browser.initialize({ headless: true, @@ -16,9 +17,9 @@ export async function fetchSession( const { page } = await browser.createPageWithProxy( IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE, - IB_CONFIG.DEFAULT_PROXY + proxy ); - services.logger.info('✅ Page created with proxy'); + services.logger.info('✅ Page created', { usingProxy: Boolean(proxy) }); const headersPromise = new Promise | undefined>(resolve => { let resolved = false; diff --git a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-symbols.action.ts b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-symbols.action.ts index 57d979df..8f75c0e7 100644 --- a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-symbols.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-symbols.action.ts @@ -1,6 +1,6 @@ import type { IServiceContainer } from '@stock-bot/handlers'; import { requireServices } from '@stock-bot/services'; -import { IB_CONFIG } from '../shared/config'; +import { IB_CONFIG, getIbProxyUrl } from '../shared/config'; import { fetchSession } from './fetch-session.action'; export async function fetchSymbols(services: IServiceContainer): Promise { @@ -38,11 +38,13 @@ export async function fetchSymbols(services: IServiceContainer): Promise + `${scheme}://${user}:${pass}@${host}`; + +const originalEnvProxy = process.env['IB_PROXY_URL']; +const originalFetch = globalThis.fetch; + +afterEach(() => { + if (originalEnvProxy === undefined) { + delete process.env['IB_PROXY_URL']; + } else { + process.env['IB_PROXY_URL'] = originalEnvProxy; + } + globalThis.fetch = originalFetch; +}); + +function createMockServices() { + const logs: Array<{ level: string; message: string; meta?: unknown }> = []; + const createPageWithProxy = mock(async (_url: string, _proxy?: string) => { + let networkHandler: ((event: { url: string; type: string; headers: Record }) => void) | undefined; + const locator = () => ({ + waitFor: mock(async () => {}), + click: mock(async () => { + networkHandler?.({ + type: 'request', + url: `${IB_CONFIG.BASE_URL}${IB_CONFIG.SUMMARY_API}`, + headers: { cookie: 'ib-session=1' }, + }); + }), + first() { + return this; + }, + }); + return { + contextId: 'ctx-test', + page: { + onNetworkEvent: mock( + (handler: (event: { url: string; type: string; headers: Record }) => void) => { + networkHandler = handler; + } + ), + waitForLoadState: mock(async () => {}), + locator, + close: mock(async () => {}), + }, + }; + }); + + const batchUpsert = mock(async (_collection: string, _docs: unknown[], _keys: string[]) => {}); + + const services = { + logger: { + info: (message: string, meta?: unknown) => logs.push({ level: 'info', message, meta }), + warn: (message: string, meta?: unknown) => logs.push({ level: 'warn', message, meta }), + error: (message: string, meta?: unknown) => logs.push({ level: 'error', message, meta }), + debug: (message: string, meta?: unknown) => logs.push({ level: 'debug', message, meta }), + }, + browser: { + initialize: mock(async () => {}), + createPageWithProxy, + }, + mongodb: { + batchUpsert, + }, + } as unknown as IServiceContainer; + + return { services, logs, createPageWithProxy, batchUpsert }; +} + +describe('IB config and proxy handling', () => { + test('IB_CONFIG has no DEFAULT_PROXY and getIbProxyUrl validates env safely', () => { + expect('DEFAULT_PROXY' in IB_CONFIG).toBe(false); + + expect(getIbProxyUrl({})).toBeUndefined(); + expect(getIbProxyUrl({ IB_PROXY_URL: ' ' })).toBeUndefined(); + + const httpProxy = buildProxyUrl('http'); + const httpsProxy = buildProxyUrl('https'); + expect(getIbProxyUrl({ IB_PROXY_URL: ` ${httpProxy} ` })).toBe(httpProxy); + expect(getIbProxyUrl({ IB_PROXY_URL: httpsProxy })).toBe(httpsProxy); + + const invalidSecret = buildProxyUrl('socks5', 'leaked-user', 'leaked-pass', 'proxy.test:1080'); + for (const bad of ['not-a-url', invalidSecret, 'ftp://u:p@proxy.test:21']) { + let caught: Error | undefined; + try { + getIbProxyUrl({ IB_PROXY_URL: bad }); + } catch (error) { + caught = error as Error; + } + expect(caught).toBeInstanceOf(Error); + expect(caught?.message).toBe('IB_PROXY_URL must be a valid http(s) URL'); + expect(caught?.message).not.toContain('leaked-pass'); + expect(caught?.message).not.toContain('leaked-user'); + } + }); + + test('fetchSession forwards IB_PROXY_URL when set, omits when unset, and never logs the proxy URL', async () => { + const proxyUrl = buildProxyUrl('http', 'session-user', 'session-secret', 'proxy.test:8080'); + process.env['IB_PROXY_URL'] = proxyUrl; + + const withProxy = createMockServices(); + const headersWithProxy = await fetchSession(withProxy.services); + expect(headersWithProxy).toEqual({ cookie: 'ib-session=1' }); + expect(withProxy.createPageWithProxy).toHaveBeenCalledWith( + IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE, + proxyUrl + ); + expect(withProxy.logs).toContainEqual({ + level: 'info', + message: '✅ Page created', + meta: { usingProxy: true }, + }); + expect(JSON.stringify(withProxy.logs)).not.toContain('session-secret'); + expect(JSON.stringify(withProxy.logs)).not.toContain('session-user'); + + delete process.env['IB_PROXY_URL']; + const withoutProxy = createMockServices(); + const headersWithoutProxy = await fetchSession(withoutProxy.services); + expect(headersWithoutProxy).toEqual({ cookie: 'ib-session=1' }); + expect(withoutProxy.createPageWithProxy).toHaveBeenCalledWith( + IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE, + undefined + ); + expect(withoutProxy.logs).toContainEqual({ + level: 'info', + message: '✅ Page created', + meta: { usingProxy: false }, + }); + }); + + test('fetchExchanges forwards proxy when set and omits proxy option when unset', async () => { + const proxyUrl = buildProxyUrl('https', 'ex-user', 'ex-secret', 'proxy.test:8443'); + const capturedOptions: Array> = []; + + globalThis.fetch = mock(async (_url: string | URL | Request, init?: RequestInit) => { + capturedOptions.push((init ?? {}) as Record); + return new Response(JSON.stringify({ exchanges: [{ id: 'NASDAQ', country_code: 'US' }] }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + }) as unknown as typeof fetch; + + process.env['IB_PROXY_URL'] = proxyUrl; + const withProxy = createMockServices(); + const res1 = await fetchExchanges(withProxy.services); + expect(res1).toEqual([{ id: 'NASDAQ', country_code: 'US' }]); + expect(capturedOptions[0]?.['proxy']).toBe(proxyUrl); + expect(JSON.stringify(withProxy.logs)).not.toContain('ex-secret'); + + delete process.env['IB_PROXY_URL']; + const withoutProxy = createMockServices(); + const res2 = await fetchExchanges(withoutProxy.services); + expect(res2).toEqual([{ id: 'NASDAQ', country_code: 'US' }]); + expect('proxy' in (capturedOptions[1] ?? {})).toBe(false); + }); + + test('fetchSymbols forwards/omits proxy and writes to ibSymbols collection', async () => { + const proxyUrl = buildProxyUrl('http', 'sym-user', 'sym-secret', 'proxy.test:8080'); + const capturedOptions: Array> = []; + const sampleSymbols = [{ symbol: 'AAPL', exchangeId: 'NASDAQ' }]; + + globalThis.fetch = mock(async (url: string | URL | Request, init?: RequestInit) => { + capturedOptions.push((init ?? {}) as Record); + const urlStr = String(url); + if (urlStr.includes(IB_CONFIG.SUMMARY_API)) { + return new Response(JSON.stringify([{ totalCount: 1 }]), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + return new Response(JSON.stringify({ products: sampleSymbols }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + }) as unknown as typeof fetch; + + process.env['IB_PROXY_URL'] = proxyUrl; + const withProxy = createMockServices(); + const symbols1 = await fetchSymbols(withProxy.services); + expect(symbols1).toEqual(sampleSymbols); + expect(capturedOptions[0]?.['proxy']).toBe(proxyUrl); + expect(capturedOptions[1]?.['proxy']).toBe(proxyUrl); + expect(withProxy.batchUpsert).toHaveBeenCalledWith('ibSymbols', sampleSymbols, [ + 'symbol', + 'exchangeId', + ]); + expect(JSON.stringify(withProxy.logs)).not.toContain('sym-secret'); + + capturedOptions.length = 0; + delete process.env['IB_PROXY_URL']; + const withoutProxy = createMockServices(); + const symbols2 = await fetchSymbols(withoutProxy.services); + expect(symbols2).toEqual(sampleSymbols); + expect('proxy' in (capturedOptions[0] ?? {})).toBe(false); + expect('proxy' in (capturedOptions[1] ?? {})).toBe(false); + expect(withoutProxy.batchUpsert).toHaveBeenCalledWith('ibSymbols', sampleSymbols, [ + 'symbol', + 'exchangeId', + ]); + }); +}); diff --git a/apps/stock/data-ingestion/src/handlers/ib/shared/config.ts b/apps/stock/data-ingestion/src/handlers/ib/shared/config.ts index 6a1d7e51..39e1b2d2 100644 --- a/apps/stock/data-ingestion/src/handlers/ib/shared/config.ts +++ b/apps/stock/data-ingestion/src/handlers/ib/shared/config.ts @@ -16,8 +16,29 @@ export const IB_CONFIG = { HEADERS_TIMEOUT: 30000, // API configuration - DEFAULT_PROXY: 'http://doimvbnb-US-rotate:w5fpiwrb9895@p.webshare.io:80', PAGE_SIZE: 500, PRODUCT_COUNTRIES: ['CA', 'US'], PRODUCT_TYPES: ['STK'], }; + +const INVALID_IB_PROXY_URL_ERROR = 'IB_PROXY_URL must be a valid http(s) URL'; + +export function getIbProxyUrl(env: NodeJS.ProcessEnv = process.env): string | undefined { + const raw = env['IB_PROXY_URL']?.trim(); + if (!raw) { + return undefined; + } + + let parsed: URL; + try { + parsed = new URL(raw); + } catch { + throw new Error(INVALID_IB_PROXY_URL_ERROR); + } + + if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || !parsed.hostname) { + throw new Error(INVALID_IB_PROXY_URL_ERROR); + } + + return raw; +} diff --git a/scripts/audit-secrets.ts b/scripts/audit-secrets.ts index 5ac732b4..2aa9d0c8 100644 --- a/scripts/audit-secrets.ts +++ b/scripts/audit-secrets.ts @@ -1,6 +1,97 @@ +import { readFileSync } from 'node:fs'; + // Explicit private local-development exceptions, not a general permission to track secrets. const localDevelopmentEnvironmentFiles = new Set(['.env', 'apps/stock/web-app/.env']); +const placeholderHosts = new Set([ + 'example.com', + 'example.org', + 'example.net', + 'example.test', + 'localhost', + '127.0.0.1', + '[::1]', + 'host', +]); + +const httpCredentialPattern = + /\bhttps?:\/\/([^\s"'`<>\\/@:]+):([^\s"'`<>\\/@]+)@(\[[^\s"'`<>\\/]+\]|[^\s"'`<>\\/:?#]+)/gi; + +export interface HttpCredentialFinding { + path: string; + line: number; +} + +function isPlaceholderHost(rawHost: string): boolean { + const host = rawHost.toLowerCase(); + return ( + placeholderHosts.has(host) || + host.endsWith('.example') || + host.endsWith('.test') || + host.endsWith('.invalid') || + host.endsWith('.example.com') || + host.endsWith('.example.org') || + host.endsWith('.example.net') + ); +} + +/** Return 1-based line numbers containing embedded http(s)://user:pass@host credentials. */ +export function findEmbeddedHttpCredentials(content: string): number[] { + const lines = content.split(/\r?\n/); + const matchedLines: number[] = []; + + for (let index = 0; index < lines.length; index++) { + const line = lines[index] ?? ''; + for (const match of line.matchAll(httpCredentialPattern)) { + const fullMatch = match[0] ?? ''; + const host = match[3] ?? ''; + if ( + fullMatch.includes('${') || + host.startsWith('.') || + host.endsWith('.') || + isPlaceholderHost(host) + ) { + continue; + } + matchedLines.push(index + 1); + break; + } + } + + return matchedLines; +} + +function defaultReadFile(path: string): Buffer | null { + try { + return readFileSync(path); + } catch { + return null; + } +} + +/** Scan tracked text files for embedded http(s)://user:pass@host credentials without echoing values. */ +export function scanTrackedFilesForHttpCredentials( + paths: readonly string[], + readFile: (path: string) => Buffer | null = defaultReadFile +): HttpCredentialFinding[] { + const findings: HttpCredentialFinding[] = []; + + for (const path of paths) { + if (!path || path.startsWith('apps/wcag-ada/') || localDevelopmentEnvironmentFiles.has(path)) { + continue; + } + const content = readFile(path); + if (!content || content.includes(0)) { + continue; + } + for (const line of findEmbeddedHttpCredentials(content.toString('utf8'))) { + findings.push({ path, line }); + } + } + + return findings; +} + /** Refuse unexpected tracked environment files without printing contents or values. */ export function unexpectedTrackedEnvironmentFiles(paths: readonly string[]): string[] { return paths.filter(path => { @@ -18,15 +109,25 @@ export function unexpectedTrackedEnvironmentFiles(paths: readonly string[]): str 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 files = unexpectedTrackedEnvironmentFiles( - new TextDecoder().decode(result.stdout).split('\0') - ); - if (files.length) { - process.stderr.write(`Unexpected tracked environment files: ${files.join(', ')}\n`); + const trackedPaths = new TextDecoder() + .decode(result.stdout) + .split('\0') + .filter(Boolean); + const envFiles = unexpectedTrackedEnvironmentFiles(trackedPaths); + const credentialHits = scanTrackedFilesForHttpCredentials(trackedPaths); + + if (envFiles.length) { + process.stderr.write(`Unexpected tracked environment files: ${envFiles.join(', ')}\n`); process.exitCode = 1; - } else { + } + if (credentialHits.length) { + const locations = credentialHits.map(hit => `${hit.path}:${hit.line}`).join(', '); + process.stderr.write(`Embedded HTTP(S) credentials found: ${locations}\n`); + process.exitCode = 1; + } + if (!envFiles.length && !credentialHits.length) { process.stdout.write( - 'Tracked environment-file audit passed (two local-development exceptions; WCAG excluded).\n' + 'Secret audit passed (no unexpected env files or embedded HTTP(S) credentials; two local-development exceptions; WCAG excluded).\n' ); } } diff --git a/scripts/test/security.test.ts b/scripts/test/security.test.ts index 78fca88c..e6f050fb 100644 --- a/scripts/test/security.test.ts +++ b/scripts/test/security.test.ts @@ -11,7 +11,11 @@ import { createWebSocketRoute } from '../../apps/stock/web-api/src/routes/websoc import { createHttpSecurity, getVerifiedHttpPrincipal, type HttpSecurityOptions } from '../../libs/core/di/src/http/security'; import { redactLogValue } from '../../libs/core/logger/src/redact'; import { parseReferenceDataResetRequest } from '../../libs/core/types/src/reference-data'; -import { unexpectedTrackedEnvironmentFiles } from '../audit-secrets'; +import { + findEmbeddedHttpCredentials, + scanTrackedFilesForHttpCredentials, + unexpectedTrackedEnvironmentFiles, +} from '../audit-secrets'; import { checks } from '../check'; const options: HttpSecurityOptions = { @@ -357,3 +361,59 @@ test('native tests and credential-file audit remain mandatory repository gates', expect(compose).not.toMatch(/^\s*-\s*["']?(?:0\.0\.0\.0:)?\d+:\d+/m); } }); + +test('embedded HTTP(S) credential audit catches real credentials with line numbers and ignores placeholders or binaries', () => { + const buildUrl = (scheme: string, user: string, pass: string, host: string) => + `${scheme}://${user}:${pass}@${host}`; + + const httpCred = buildUrl('http', 'proxy-user', 's3cr3t-pass', 'proxy.vendor.io:8080'); + const httpsCred = buildUrl('https', 'api-user', 'tok3n-val', 'gateway.vendor.io/v1'); + + const sample = [ + 'const safe = "https://public.vendor.io/api";', + `const leakedHttp = "${httpCred}";`, + 'const rfc2606 = "https://user:pass@example.test/api";', + 'const exampleCom = "http://user:pass@example.com:80";', + 'const exampleSub = "https://user:pass@sub.example.org/path";', + 'const invalidTld = "http://user:pass@proxy.invalid:80";', + 'const dotExample = "http://user:pass@service.example:80";', + 'const loopback = "http://user:pass@127.0.0.1:8080";', + 'const loopbackV6 = "http://user:pass@[::1]:8080";', + 'const local = "http://user:pass@localhost:3000";', + 'const docHost = "http://user:pass@host:80";', + 'const template = `http://${user}:${pass}@proxy.vendor.io:80`;', + 'const angle = "http://:@proxy.vendor.io:80";', + 'const angleHost = "http://user:pass@:80";', + 'const mongo = "mongodb://admin:secret@prod-db.internal:27017/stock";', + `const leakedHttps = '${httpsCred}';`, + ].join('\n'); + + expect(findEmbeddedHttpCredentials(sample)).toEqual([2, 16]); + + const files = new Map([ + ['apps/stock/data-ingestion/src/clean.ts', Buffer.from('export const ok = true;\n')], + ['apps/stock/data-ingestion/src/leaked.ts', Buffer.from(`line1\nconst p = "${httpCred}";\n`)], + ['apps/wcag-ada/src/ignored.ts', Buffer.from(`const p = "${httpCred}";\n`)], + ['.env', Buffer.from(`IB_PROXY_URL=${httpCred}\n`)], + ['apps/stock/web-app/.env', Buffer.from(`PROXY=${httpsCred}\n`)], + ['assets/binary.dat', Buffer.concat([Buffer.from([0x00, 0x01]), Buffer.from(httpCred)])], + ]); + + const findings = scanTrackedFilesForHttpCredentials( + [ + 'apps/stock/data-ingestion/src/clean.ts', + 'apps/stock/data-ingestion/src/leaked.ts', + 'apps/wcag-ada/src/ignored.ts', + '.env', + 'apps/stock/web-app/.env', + 'assets/binary.dat', + 'missing/file.ts', + ], + path => files.get(path) ?? null + ); + + expect(findings).toEqual([{ path: 'apps/stock/data-ingestion/src/leaked.ts', line: 2 }]); + const serialized = JSON.stringify(findings); + expect(serialized).not.toContain('s3cr3t-pass'); + expect(serialized).not.toContain('proxy-user'); +}); diff --git a/test/integration/paper-deployments-api.test.ts b/test/integration/paper-deployments-api.test.ts index fd0c9f4d..c8f72d3a 100644 --- a/test/integration/paper-deployments-api.test.ts +++ b/test/integration/paper-deployments-api.test.ts @@ -165,7 +165,7 @@ test('unconfigured fixed origin and mismatched upstream identity fail honestly w await expect(forwardPaperCommand(request, id, 'bind', {}, {})).rejects.toThrow('not configured'); for (const origin of [ 'file:///tmp/private', - 'http://user:pass@paper', + 'http://user:pass@paper.test', 'http://paper/other', 'http://paper?token=x', ]) {