T-3: M0.4 Purge hardcoded proxy credential + fix IB collection typo
This commit is contained in:
commit
8fc0cdf766
12 changed files with 859 additions and 31 deletions
|
|
@ -14,3 +14,4 @@ EOD_API_KEY=
|
|||
QM_USERNAME=
|
||||
QM_PASSWORD=
|
||||
IB_ACCOUNT=
|
||||
IB_PROXY_URL=
|
||||
|
|
|
|||
|
|
@ -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<unknown[] | null> {
|
||||
|
|
@ -33,11 +33,13 @@ export async function fetchExchanges(services: IServiceContainer): Promise<unkno
|
|||
headerCount: Object.keys(requestHeaders).length,
|
||||
});
|
||||
|
||||
// Use fetch with proxy configuration
|
||||
const proxy = getIbProxyUrl();
|
||||
|
||||
// Use fetch with optional proxy configuration
|
||||
const response = await fetch(exchangeUrl, {
|
||||
method: 'GET',
|
||||
headers: requestHeaders,
|
||||
proxy: IB_CONFIG.DEFAULT_PROXY,
|
||||
...(proxy ? { proxy } : {}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
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';
|
||||
|
||||
export async function fetchSession(
|
||||
services: IServiceContainer
|
||||
): Promise<Record<string, string> | 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<Record<string, string> | undefined>(resolve => {
|
||||
let resolved = false;
|
||||
|
|
|
|||
|
|
@ -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<unknown[] | null> {
|
||||
|
|
@ -38,11 +38,13 @@ export async function fetchSymbols(services: IServiceContainer): Promise<unknown
|
|||
sortField: 'symbol',
|
||||
};
|
||||
|
||||
const proxy = getIbProxyUrl();
|
||||
|
||||
// Get Summary
|
||||
const summaryResponse = await fetch(IB_CONFIG.BASE_URL + IB_CONFIG.SUMMARY_API, {
|
||||
method: 'POST',
|
||||
headers: requestHeaders,
|
||||
proxy: IB_CONFIG.DEFAULT_PROXY,
|
||||
...(proxy ? { proxy } : {}),
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
|
|
@ -72,7 +74,7 @@ export async function fetchSymbols(services: IServiceContainer): Promise<unknown
|
|||
const symbolsResponse = fetch(IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_API, {
|
||||
method: 'POST',
|
||||
headers: requestHeaders,
|
||||
proxy: IB_CONFIG.DEFAULT_PROXY,
|
||||
...(proxy ? { proxy } : {}),
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
symbolPromises.push(symbolsResponse);
|
||||
|
|
@ -105,7 +107,7 @@ export async function fetchSymbols(services: IServiceContainer): Promise<unknown
|
|||
services.logger.info('✅ IB symbols fetched successfully, saving to DB...', {
|
||||
totalSymbols: symbols.length,
|
||||
});
|
||||
await requireServices(services, 'mongodb').mongodb.batchUpsert('ib_symbols', symbols, [
|
||||
await requireServices(services, 'mongodb').mongodb.batchUpsert('ibSymbols', symbols, [
|
||||
'symbol',
|
||||
'exchangeId',
|
||||
]);
|
||||
|
|
|
|||
285
apps/stock/data-ingestion/src/handlers/ib/ib.test.ts
Normal file
285
apps/stock/data-ingestion/src/handlers/ib/ib.test.ts
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
import { afterEach, describe, expect, mock, test } from 'bun:test';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { fetchExchanges } from './actions/fetch-exchanges.action';
|
||||
import { fetchSession } from './actions/fetch-session.action';
|
||||
import { fetchSymbols } from './actions/fetch-symbols.action';
|
||||
import { IB_CONFIG, getIbProxyUrl } from './shared/config';
|
||||
|
||||
const buildProxyUrl = (scheme = 'http', user = 'ib-user', pass = 'ib-secret', host = 'proxy.test:8080') =>
|
||||
`${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<string, string> }) => 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<string, string> }) => 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<Record<string, unknown>> = [];
|
||||
|
||||
globalThis.fetch = mock(async (_url: string | URL | Request, init?: RequestInit) => {
|
||||
capturedOptions.push((init ?? {}) as Record<string, unknown>);
|
||||
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<Record<string, unknown>> = [];
|
||||
const sampleSymbols = [{ symbol: 'AAPL', exchangeId: 'NASDAQ' }];
|
||||
|
||||
globalThis.fetch = mock(async (url: string | URL | Request, init?: RequestInit) => {
|
||||
capturedOptions.push((init ?? {}) as Record<string, unknown>);
|
||||
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',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
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<typeof mock> } })
|
||||
.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<string, unknown> }> = [];
|
||||
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<string, unknown> });
|
||||
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']);
|
||||
});
|
||||
});
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
123
libs/services/browser/test/browser.test.ts
Normal file
123
libs/services/browser/test/browser.test.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
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<Record<string, unknown>> = [];
|
||||
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<string, unknown>) => {
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,98 @@
|
|||
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().replace(/\.$/, '');
|
||||
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] ?? '';
|
||||
const normalizedHost = host.replace(/\.$/, '');
|
||||
if (
|
||||
fullMatch.includes('${') ||
|
||||
!normalizedHost ||
|
||||
normalizedHost.startsWith('.') ||
|
||||
isPlaceholderHost(normalizedHost)
|
||||
) {
|
||||
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 +110,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'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
@ -11,7 +14,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 +364,150 @@ 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 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";',
|
||||
'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://<user>:<pass>@proxy.vendor.io:80";',
|
||||
'const angleHost = "http://user:pass@<host>:80";',
|
||||
'const mongo = "mongodb://admin:secret@prod-db.internal:27017/stock";',
|
||||
`const leakedHttps = '${httpsCred}';`,
|
||||
`const leakedFqdn = "${fqdnCred}";`,
|
||||
].join('\n');
|
||||
|
||||
expect(findEmbeddedHttpCredentials(sample)).toEqual([2, 18, 19]);
|
||||
|
||||
const files = new Map<string, Buffer>([
|
||||
['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');
|
||||
});
|
||||
|
||||
function isolatedGitEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record<string, string> {
|
||||
const env: Record<string, string> = {};
|
||||
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, 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, 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),
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
]) {
|
||||
|
|
|
|||
119
test/unit/audit-secrets-http-credentials.test.ts
Normal file
119
test/unit/audit-secrets-http-credentials.test.ts
Normal file
|
|
@ -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<string, string> {
|
||||
const env: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (value !== undefined && !key.startsWith('GIT_')) {
|
||||
env[key] = value;
|
||||
}
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
function runAuditCliInTempRepo(files: Record<string, string>) {
|
||||
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');
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue