From e88044e4b84d85a03010c25258852202ce95d42c Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:01:40 -0500 Subject: [PATCH] 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'); + } + }); +});