T-3: M0.4 Purge hardcoded proxy credential + fix IB collection typo
This commit is contained in:
parent
36489a1e91
commit
316607b3c2
4 changed files with 159 additions and 16 deletions
|
|
@ -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);
|
||||
|
|
|
|||
87
libs/services/browser/test/browser.test.ts
Normal file
87
libs/services/browser/test/browser.test.ts
Normal file
|
|
@ -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<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');
|
||||
});
|
||||
});
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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@<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, 16]);
|
||||
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')],
|
||||
|
|
@ -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 });
|
||||
}
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue