From 36489a1e91cad5ed45447a1d2d88f5e59e977a74 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 10:51:13 -0500 Subject: [PATCH 1/4] T-3: M0.4 Purge hardcoded proxy credential + fix IB collection typo --- .env.example | 1 + .../ib/actions/fetch-exchanges.action.ts | 8 +- .../ib/actions/fetch-session.action.ts | 7 +- .../ib/actions/fetch-symbols.action.ts | 10 +- .../data-ingestion/src/handlers/ib/ib.test.ts | 207 ++++++++++++++++++ .../src/handlers/ib/shared/config.ts | 23 +- scripts/audit-secrets.ts | 115 +++++++++- scripts/test/security.test.ts | 62 +++++- .../integration/paper-deployments-api.test.ts | 2 +- 9 files changed, 415 insertions(+), 20 deletions(-) create mode 100644 apps/stock/data-ingestion/src/handlers/ib/ib.test.ts 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', ]) { From 316607b3c2127d281dcaf5b251ab5457ab76e70d Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 10:55:00 -0500 Subject: [PATCH 2/4] T-3: M0.4 Purge hardcoded proxy credential + fix IB collection typo --- libs/services/browser/src/browser.ts | 38 +++++++--- libs/services/browser/test/browser.test.ts | 87 ++++++++++++++++++++++ scripts/audit-secrets.ts | 9 ++- scripts/test/security.test.ts | 41 +++++++++- 4 files changed, 159 insertions(+), 16 deletions(-) create mode 100644 libs/services/browser/test/browser.test.ts diff --git a/libs/services/browser/src/browser.ts b/libs/services/browser/src/browser.ts index d79791de..e6aebe2b 100644 --- a/libs/services/browser/src/browser.ts +++ b/libs/services/browser/src/browser.ts @@ -173,22 +173,40 @@ export class Browser { }; if (proxy) { - const [protocol, rest] = proxy.split('://'); - if (!rest) { + let parsed: URL; + try { + parsed = new URL(proxy); + } catch { throw new Error( - 'Invalid proxy format. Expected protocol://host:port or protocol://user:pass@host:port' + 'Invalid proxy format. Expected protocol://host[:port] or protocol://user:pass@host[:port]' ); } - const [auth, hostPort] = rest.includes('@') ? rest.split('@') : [null, rest]; - const finalHostPort = hostPort || rest; - const [host, port] = finalHostPort.split(':'); + if (!parsed.hostname) { + throw new Error( + 'Invalid proxy format. Expected protocol://host[:port] or protocol://user:pass@host[:port]' + ); + } - contextOptions['proxy'] = { - server: `${protocol}://${host}:${port}`, - username: auth?.split(':')[0] || '', - password: auth?.split(':')[1] || '', + const decodeCredential = (value: string): string => { + try { + return decodeURIComponent(value); + } catch { + return value; + } }; + + const proxyConfig: { server: string; username?: string; password?: string } = { + server: parsed.origin === 'null' ? `${parsed.protocol}//${parsed.host}` : parsed.origin, + }; + if (parsed.username) { + proxyConfig.username = decodeCredential(parsed.username); + } + if (parsed.password) { + proxyConfig.password = decodeCredential(parsed.password); + } + + contextOptions['proxy'] = proxyConfig; } const context = await this.browser.newContext(contextOptions); diff --git a/libs/services/browser/test/browser.test.ts b/libs/services/browser/test/browser.test.ts new file mode 100644 index 00000000..b56e055a --- /dev/null +++ b/libs/services/browser/test/browser.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, mock, test } from 'bun:test'; +import type { Browser as PlaywrightBrowser } from 'playwright'; +import { Browser } from '../src/browser'; + +function createBrowserWithMockPlaywright() { + const capturedContextOptions: Array> = []; + const gotoMock = mock(async () => {}); + const page = { + setDefaultTimeout: mock(() => {}), + setDefaultNavigationTimeout: mock(() => {}), + goto: gotoMock, + on: mock(() => {}), + }; + const context = { + route: mock(async () => {}), + newPage: mock(async () => page), + close: mock(async () => {}), + }; + const newContext = mock(async (options: Record) => { + capturedContextOptions.push(options); + return context; + }); + + const browser = new Browser({ + info: () => {}, + warn: () => {}, + error: () => {}, + debug: () => {}, + }); + (browser as unknown as { browser: PlaywrightBrowser }).browser = { + newContext, + close: mock(async () => {}), + } as unknown as PlaywrightBrowser; + + return { browser, capturedContextOptions, newContext, gotoMock }; +} + +describe('Browser.createPageWithProxy', () => { + test('parses default-port HTTPS proxy URLs into origin and separate credentials without appending :undefined', async () => { + const { browser, capturedContextOptions } = createBrowserWithMockPlaywright(); + const proxyUrl = `${'https'}://${'ib-user'}:${'ib-secret'}@proxy.test`; + + await browser.createPageWithProxy('https://example.test/page', proxyUrl); + + expect(capturedContextOptions[0]?.['proxy']).toEqual({ + server: 'https://proxy.test', + username: 'ib-user', + password: 'ib-secret', + }); + }); + + test('parses explicit-port and percent-encoded credentials, unauthenticated proxies, and omitted proxies', async () => { + const { browser, capturedContextOptions } = createBrowserWithMockPlaywright(); + + const encodedProxy = `${'http'}://${encodeURIComponent('user@org')}:${encodeURIComponent('p:ass%1')}@proxy.test:8080`; + await browser.createPageWithProxy('https://example.test/1', encodedProxy); + expect(capturedContextOptions[0]?.['proxy']).toEqual({ + server: 'http://proxy.test:8080', + username: 'user@org', + password: 'p:ass%1', + }); + + await browser.createPageWithProxy('https://example.test/2', 'http://proxy.test'); + expect(capturedContextOptions[1]?.['proxy']).toEqual({ + server: 'http://proxy.test', + }); + + await browser.createPageWithProxy('https://example.test/3', undefined); + expect('proxy' in (capturedContextOptions[2] ?? {})).toBe(false); + }); + + test('rejects malformed proxy URLs without echoing credentials', async () => { + const { browser } = createBrowserWithMockPlaywright(); + const badProxy = 'not-a-valid-proxy-with-secret-token-xyz'; + + let caught: Error | undefined; + try { + await browser.createPageWithProxy('https://example.test/page', badProxy); + } catch (error) { + caught = error as Error; + } + + expect(caught).toBeInstanceOf(Error); + expect(caught?.message).toContain('Invalid proxy format'); + expect(caught?.message).not.toContain('secret-token-xyz'); + }); +}); diff --git a/scripts/audit-secrets.ts b/scripts/audit-secrets.ts index 2aa9d0c8..c57435f8 100644 --- a/scripts/audit-secrets.ts +++ b/scripts/audit-secrets.ts @@ -23,7 +23,7 @@ export interface HttpCredentialFinding { } function isPlaceholderHost(rawHost: string): boolean { - const host = rawHost.toLowerCase(); + const host = rawHost.toLowerCase().replace(/\.$/, ''); return ( placeholderHosts.has(host) || host.endsWith('.example') || @@ -45,11 +45,12 @@ export function findEmbeddedHttpCredentials(content: string): number[] { for (const match of line.matchAll(httpCredentialPattern)) { const fullMatch = match[0] ?? ''; const host = match[3] ?? ''; + const normalizedHost = host.replace(/\.$/, ''); if ( fullMatch.includes('${') || - host.startsWith('.') || - host.endsWith('.') || - isPlaceholderHost(host) + !normalizedHost || + normalizedHost.startsWith('.') || + isPlaceholderHost(normalizedHost) ) { continue; } diff --git a/scripts/test/security.test.ts b/scripts/test/security.test.ts index e6f050fb..6cd0a0c9 100644 --- a/scripts/test/security.test.ts +++ b/scripts/test/security.test.ts @@ -1,4 +1,7 @@ -import { readFileSync } from 'node:fs'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { expect, test } from 'bun:test'; import { Hono } from 'hono'; import { createHttpSecurity as createApiSecurity } from '@stock-bot/di'; @@ -368,13 +371,16 @@ test('embedded HTTP(S) credential audit catches real credentials with line numbe 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 fqdnCred = buildUrl('https', 'fqdn-user', 'fqdn-pass', 'proxy.vendor.io.:8443'); 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 exampleComDot = "http://user:pass@example.com.:80";', 'const exampleSub = "https://user:pass@sub.example.org/path";', + 'const exampleSubDot = "https://user:pass@sub.example.test./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";', @@ -386,9 +392,10 @@ test('embedded HTTP(S) credential audit catches real credentials with line numbe 'const angleHost = "http://user:pass@:80";', 'const mongo = "mongodb://admin:secret@prod-db.internal:27017/stock";', `const leakedHttps = '${httpsCred}';`, + `const leakedFqdn = "${fqdnCred}";`, ].join('\n'); - expect(findEmbeddedHttpCredentials(sample)).toEqual([2, 16]); + expect(findEmbeddedHttpCredentials(sample)).toEqual([2, 18, 19]); const files = new Map([ ['apps/stock/data-ingestion/src/clean.ts', Buffer.from('export const ok = true;\n')], @@ -417,3 +424,33 @@ test('embedded HTTP(S) credential audit catches real credentials with line numbe expect(serialized).not.toContain('s3cr3t-pass'); expect(serialized).not.toContain('proxy-user'); }); + +test('audit-secrets CLI reports path:line to stderr, exits 1, and never echoes credentials', () => { + const tempDir = mkdtempSync(join(tmpdir(), 'audit-secrets-cli-')); + const auditScript = fileURLToPath(new URL('../audit-secrets.ts', import.meta.url)); + const fakeUser = 'cli-audit-user'; + const fakePass = 'cli-audit-s3cr3t'; + const leakedUrl = `${'https'}://${fakeUser}:${fakePass}@proxy.vendor.io.`; + + try { + const init = Bun.spawnSync(['git', 'init'], { cwd: tempDir }); + expect(init.exitCode).toBe(0); + + writeFileSync(join(tempDir, 'leaked.ts'), `const ok = 1;\nconst url = "${leakedUrl}";\n`, 'utf8'); + const add = Bun.spawnSync(['git', 'add', 'leaked.ts'], { cwd: tempDir }); + expect(add.exitCode).toBe(0); + + const run = Bun.spawnSync([process.execPath, auditScript], { cwd: tempDir }); + const stdout = new TextDecoder().decode(run.stdout); + const stderr = new TextDecoder().decode(run.stderr); + + expect(run.exitCode).toBe(1); + expect(stderr).toContain('leaked.ts:2'); + expect(stdout).not.toContain(fakeUser); + expect(stdout).not.toContain(fakePass); + expect(stderr).not.toContain(fakeUser); + expect(stderr).not.toContain(fakePass); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); From e182c640d2c4f96806cb55e6cdb4a0f3960e76aa Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 10:57:38 -0500 Subject: [PATCH 3/4] T-3: M0.4 Purge hardcoded proxy credential + fix IB collection typo --- scripts/test/security.test.ts | 83 +++++++++++++++++++++++++++++------ 1 file changed, 70 insertions(+), 13 deletions(-) diff --git a/scripts/test/security.test.ts b/scripts/test/security.test.ts index 6cd0a0c9..9b5f9756 100644 --- a/scripts/test/security.test.ts +++ b/scripts/test/security.test.ts @@ -425,32 +425,89 @@ test('embedded HTTP(S) credential audit catches real credentials with line numbe expect(serialized).not.toContain('proxy-user'); }); -test('audit-secrets CLI reports path:line to stderr, exits 1, and never echoes credentials', () => { +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 runAuditSecretsCliFixture(baseEnv: NodeJS.ProcessEnv = process.env) { const tempDir = mkdtempSync(join(tmpdir(), 'audit-secrets-cli-')); const auditScript = fileURLToPath(new URL('../audit-secrets.ts', import.meta.url)); const fakeUser = 'cli-audit-user'; const fakePass = 'cli-audit-s3cr3t'; const leakedUrl = `${'https'}://${fakeUser}:${fakePass}@proxy.vendor.io.`; + const env = isolatedGitEnv(baseEnv); try { - const init = Bun.spawnSync(['git', 'init'], { cwd: tempDir }); + const init = Bun.spawnSync(['git', 'init'], { cwd: tempDir, env }); expect(init.exitCode).toBe(0); writeFileSync(join(tempDir, 'leaked.ts'), `const ok = 1;\nconst url = "${leakedUrl}";\n`, 'utf8'); - const add = Bun.spawnSync(['git', 'add', 'leaked.ts'], { cwd: tempDir }); + const add = Bun.spawnSync(['git', 'add', 'leaked.ts'], { cwd: tempDir, env }); expect(add.exitCode).toBe(0); - const run = Bun.spawnSync([process.execPath, auditScript], { cwd: tempDir }); - const stdout = new TextDecoder().decode(run.stdout); - const stderr = new TextDecoder().decode(run.stderr); - - expect(run.exitCode).toBe(1); - expect(stderr).toContain('leaked.ts:2'); - expect(stdout).not.toContain(fakeUser); - expect(stdout).not.toContain(fakePass); - expect(stderr).not.toContain(fakeUser); - expect(stderr).not.toContain(fakePass); + const run = Bun.spawnSync([process.execPath, auditScript], { cwd: tempDir, env }); + return { + exitCode: run.exitCode, + stdout: new TextDecoder().decode(run.stdout), + stderr: new TextDecoder().decode(run.stderr), + fakeUser, + fakePass, + }; } finally { rmSync(tempDir, { recursive: true, force: true }); } +} + +test('audit-secrets CLI reports path:line to stderr, exits 1, and never echoes credentials', () => { + const result = runAuditSecretsCliFixture(); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('leaked.ts:2'); + expect(result.stdout).not.toContain(result.fakeUser); + expect(result.stdout).not.toContain(result.fakePass); + expect(result.stderr).not.toContain(result.fakeUser); + expect(result.stderr).not.toContain(result.fakePass); +}); + +test('audit-secrets CLI fixture ignores inherited Git repository and index env vars', () => { + const callerDir = mkdtempSync(join(tmpdir(), 'audit-secrets-caller-')); + const cleanEnv = isolatedGitEnv(); + + try { + const callerIndex = join(callerDir, 'caller.index'); + const callerEnv = { + ...cleanEnv, + GIT_DIR: join(callerDir, '.git'), + GIT_WORK_TREE: callerDir, + GIT_INDEX_FILE: callerIndex, + }; + + const init = Bun.spawnSync(['git', 'init'], { cwd: callerDir, env: cleanEnv }); + expect(init.exitCode).toBe(0); + + writeFileSync(join(callerDir, 'caller.ts'), 'export const caller = true;\n', 'utf8'); + const add = Bun.spawnSync(['git', 'add', 'caller.ts'], { cwd: callerDir, env: callerEnv }); + expect(add.exitCode).toBe(0); + + const indexBefore = readFileSync(callerIndex); + + const result = runAuditSecretsCliFixture(callerEnv); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('leaked.ts:2'); + + const indexAfter = readFileSync(callerIndex); + expect(indexAfter).toEqual(indexBefore); + + const ls = Bun.spawnSync(['git', 'ls-files'], { cwd: callerDir, env: callerEnv }); + expect(ls.exitCode).toBe(0); + expect(new TextDecoder().decode(ls.stdout).trim()).toBe('caller.ts'); + } finally { + rmSync(callerDir, { recursive: true, force: true }); + } }); From e88044e4b84d85a03010c25258852202ce95d42c Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:01:40 -0500 Subject: [PATCH 4/4] T-3: tests --- .../data-ingestion/src/handlers/ib/ib.test.ts | 78 ++++++++++++ libs/services/browser/test/browser.test.ts | 36 ++++++ .../audit-secrets-http-credentials.test.ts | 119 ++++++++++++++++++ 3 files changed, 233 insertions(+) create mode 100644 test/unit/audit-secrets-http-credentials.test.ts diff --git a/apps/stock/data-ingestion/src/handlers/ib/ib.test.ts b/apps/stock/data-ingestion/src/handlers/ib/ib.test.ts index 79e445d5..7feff4eb 100644 --- a/apps/stock/data-ingestion/src/handlers/ib/ib.test.ts +++ b/apps/stock/data-ingestion/src/handlers/ib/ib.test.ts @@ -205,3 +205,81 @@ describe('IB config and proxy handling', () => { ]); }); }); + +describe('IB proxy edge cases (QA)', () => { + test('getIbProxyUrl accepts unauthenticated and upper-case-scheme proxies and rejects host-less URLs', () => { + expect(getIbProxyUrl({ IB_PROXY_URL: 'http://proxy.test:3128' })).toBe('http://proxy.test:3128'); + const upper = buildProxyUrl('HTTPS', 'u', 'p', 'proxy.test'); + expect(getIbProxyUrl({ IB_PROXY_URL: upper })).toBe(upper); + + for (const bad of ['http://', 'https://', `${'http'}://hostless-user:hostless-pass@`]) { + expect(() => getIbProxyUrl({ IB_PROXY_URL: bad })).toThrow( + 'IB_PROXY_URL must be a valid http(s) URL' + ); + } + }); + + test('fetchSession with an invalid IB_PROXY_URL fails before launching a browser and never logs the value', async () => { + process.env['IB_PROXY_URL'] = buildProxyUrl('socks5', 'bad-user', 'bad-secret', 'proxy.test:1080'); + const { services, logs, createPageWithProxy } = createMockServices(); + const initialize = (services as unknown as { browser: { initialize: ReturnType } }) + .browser.initialize; + + const headers = await fetchSession(services); + + expect(headers).toBeUndefined(); + expect(initialize).not.toHaveBeenCalled(); + expect(createPageWithProxy).not.toHaveBeenCalled(); + const serialized = JSON.stringify(logs, (_key, value) => + value instanceof Error ? { message: value.message, stack: value.stack } : value + ); + expect(serialized).toContain('IB_PROXY_URL must be a valid http(s) URL'); + expect(serialized).not.toContain('bad-secret'); + expect(serialized).not.toContain('bad-user'); + }); + + test('fetchSymbols with an invalid IB_PROXY_URL makes no API calls and writes nothing', async () => { + process.env['IB_PROXY_URL'] = 'ftp://ftp-user:ftp-secret@proxy.test:21'; + const fetchMock = mock(async () => new Response('[]')); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const { services, logs, batchUpsert } = createMockServices(); + + const result = await fetchSymbols(services); + + expect(result).toBeNull(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(batchUpsert).not.toHaveBeenCalled(); + expect(JSON.stringify(logs)).not.toContain('ftp-secret'); + }); + + test('fetchSymbols forwards the proxy on every paginated request and upserts once into ibSymbols', async () => { + const proxyUrl = buildProxyUrl('http', 'page-user', 'page-secret', 'proxy.test:8080'); + process.env['IB_PROXY_URL'] = proxyUrl; + const calls: Array<{ url: string; init: Record }> = []; + const totalCount = IB_CONFIG.PAGE_SIZE * 2 + 1; // forces 3 product pages + + globalThis.fetch = mock(async (url: string | URL | Request, init?: RequestInit) => { + const urlStr = String(url); + calls.push({ url: urlStr, init: (init ?? {}) as Record }); + if (urlStr.endsWith(IB_CONFIG.SUMMARY_API)) { + return new Response(JSON.stringify([{ totalCount }]), { status: 200 }); + } + const page = JSON.parse(String(init?.body)).pageNumber as number; + return new Response( + JSON.stringify({ products: [{ symbol: `SYM${page}`, exchangeId: 'NYSE' }] }), + { status: 200 } + ); + }) as unknown as typeof fetch; + + const { services, batchUpsert } = createMockServices(); + const symbols = await fetchSymbols(services); + + expect(calls).toHaveLength(4); + expect(calls.every(call => call.init['proxy'] === proxyUrl)).toBe(true); + expect(symbols).toHaveLength(3); + expect(batchUpsert).toHaveBeenCalledTimes(1); + const [collection, , keys] = batchUpsert.mock.calls[0] ?? []; + expect(collection).toBe('ibSymbols'); + expect(keys).toEqual(['symbol', 'exchangeId']); + }); +}); diff --git a/libs/services/browser/test/browser.test.ts b/libs/services/browser/test/browser.test.ts index b56e055a..e99c1d45 100644 --- a/libs/services/browser/test/browser.test.ts +++ b/libs/services/browser/test/browser.test.ts @@ -85,3 +85,39 @@ describe('Browser.createPageWithProxy', () => { expect(caught?.message).not.toContain('secret-token-xyz'); }); }); + +describe('Browser.createPageWithProxy edge cases (QA)', () => { + test('keeps non-special schemes, IPv6 hosts, and drops proxy paths/queries from the server', async () => { + const { browser, capturedContextOptions } = createBrowserWithMockPlaywright(); + + await browser.createPageWithProxy('https://example.test/a', `${'socks5'}://s-user:s-pass@proxy.test:1080`); + expect(capturedContextOptions[0]?.['proxy']).toEqual({ + server: 'socks5://proxy.test:1080', + username: 's-user', + password: 's-pass', + }); + + await browser.createPageWithProxy('https://example.test/b', 'http://[::1]:3128'); + expect(capturedContextOptions[1]?.['proxy']).toEqual({ server: 'http://[::1]:3128' }); + + await browser.createPageWithProxy('https://example.test/c', 'HTTP://PROXY.TEST:8080/some/path?x=1#frag'); + expect(capturedContextOptions[2]?.['proxy']).toEqual({ server: 'http://proxy.test:8080' }); + }); + + test('host-less proxy URLs carrying credentials are rejected before a context is created, without echoing them', async () => { + const { browser, newContext } = createBrowserWithMockPlaywright(); + + for (const bad of [`${'http'}://leak-user:leak-pass@`, `${'http'}://leak-user:leak-pass@bad host:80`]) { + let caught: Error | undefined; + try { + await browser.createPageWithProxy('https://example.test/page', bad); + } catch (error) { + caught = error as Error; + } + expect(caught?.message).toContain('Invalid proxy format'); + expect(caught?.message).not.toContain('leak-pass'); + expect(caught?.message).not.toContain('leak-user'); + } + expect(newContext).not.toHaveBeenCalled(); + }); +}); diff --git a/test/unit/audit-secrets-http-credentials.test.ts b/test/unit/audit-secrets-http-credentials.test.ts new file mode 100644 index 00000000..1274611d --- /dev/null +++ b/test/unit/audit-secrets-http-credentials.test.ts @@ -0,0 +1,119 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { findEmbeddedHttpCredentials } from '../../scripts/audit-secrets'; + +// Positive URLs are assembled at runtime so this file never trips the tracked-tree audit itself. +const credentialUrl = (scheme: string, host: string, user = 'qa-user', pass = 'qa-pass-123') => + `${scheme}://${user}:${pass}@${host}`; + +function isolatedGitEnv(): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(process.env)) { + if (value !== undefined && !key.startsWith('GIT_')) { + env[key] = value; + } + } + return env; +} + +function runAuditCliInTempRepo(files: Record) { + const tempDir = mkdtempSync(join(tmpdir(), 'audit-secrets-qa-')); + const auditScript = fileURLToPath(new URL('../../scripts/audit-secrets.ts', import.meta.url)); + const env = isolatedGitEnv(); + try { + expect(Bun.spawnSync(['git', 'init', '-q'], { cwd: tempDir, env }).exitCode).toBe(0); + for (const [name, content] of Object.entries(files)) { + writeFileSync(join(tempDir, name), content, 'utf8'); + } + const add = Bun.spawnSync(['git', 'add', '-f', ...Object.keys(files)], { cwd: tempDir, env }); + expect(add.exitCode).toBe(0); + const run = Bun.spawnSync([process.execPath, auditScript], { cwd: tempDir, env }); + return { + exitCode: run.exitCode, + stdout: new TextDecoder().decode(run.stdout), + stderr: new TextDecoder().decode(run.stderr), + }; + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +} + +describe('findEmbeddedHttpCredentials edge cases', () => { + test('flags the purged Webshare-style shape, upper-case schemes, private IPs and placeholder look-alike hosts', () => { + const flagged = [ + // Same shape as the removed IB_CONFIG.DEFAULT_PROXY, with fake values. + credentialUrl('http', 'p.vendor-proxy.io:80', 'abcdefgh-US-rotate', 'fakepass1234'), + credentialUrl('HTTPS', 'proxy.vendor.io'), + credentialUrl('http', 'example.com.attacker.io'), + credentialUrl('http', 'localhost.attacker.io:8080'), + credentialUrl('http', 'notexample.com'), + credentialUrl('http', 'host.vendor.io'), + credentialUrl('http', '10.0.0.51:3128'), + credentialUrl('http', '[2001:db8::1]:3128'), + ]; + + for (const literal of flagged) { + expect(findEmbeddedHttpCredentials(`const proxy = "${literal}";`)).toEqual([1]); + } + }); + + test('a placeholder URL earlier on a line does not hide a real credential later on the same line', () => { + const sideBySide = `a = "${credentialUrl('http', 'example.com')}"; b = "${credentialUrl('http', 'real.vendor.io')}";`; + const nested = `r = "https://example.com/redirect?to=${credentialUrl('http', 'real.vendor.io')}";`; + + expect(findEmbeddedHttpCredentials(sideBySide)).toEqual([1]); + expect(findEmbeddedHttpCredentials(nested)).toEqual([1]); + }); + + test('reports each line once with CRLF-accurate 1-based numbering', () => { + const leak = credentialUrl('http', 'proxy.vendor.io', 'crlf-user', 'crlf-pass'); + const content = ['first', `"${leak}" and "${leak}"`, 'third', `x=${leak}`, ''].join('\r\n'); + + expect(findEmbeddedHttpCredentials(content)).toEqual([2, 4]); + expect(findEmbeddedHttpCredentials('')).toEqual([]); + }); + + test('credential-free URLs and user-only URLs are not flagged', () => { + const content = [ + 'const a = "https://public.vendor.io/api?user=x&pass=y";', + 'const b = "mailto:user:pass@vendor.io";', + `const c = "${'http'}://token-only@vendor.io";`, + `const d = "${'http'}://user:@vendor.io";`, + ].join('\n'); + + expect(findEmbeddedHttpCredentials(content)).toEqual([]); + }); +}); + +describe('audit-secrets CLI', () => { + test('exits 0 with a pass message on a clean tracked tree', () => { + const result = runAuditCliInTempRepo({ + 'clean.ts': 'export const url = "https://public.vendor.io/api";\n', + '.env.example': 'IB_PROXY_URL=\n', + }); + + expect(result.exitCode).toBe(0); + expect(result.stderr).toBe(''); + expect(result.stdout).toContain('Secret audit passed'); + }); + + test('reports both a tracked env file and an embedded credential without echoing any value', () => { + const pass = 'combo-s3cr3t'; + const result = runAuditCliInTempRepo({ + '.env.production': 'TOKEN=never-printed\n', + 'proxy.ts': `\n\nexport const p = "${credentialUrl('https', 'proxy.vendor.io:443', 'combo-user', pass)}";\n`, + }); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Unexpected tracked environment files: .env.production'); + expect(result.stderr).toContain('proxy.ts:3'); + for (const output of [result.stdout, result.stderr]) { + expect(output).not.toContain(pass); + expect(output).not.toContain('combo-user'); + expect(output).not.toContain('never-printed'); + } + }); +});