T-3: M0.4 Purge hardcoded proxy credential + fix IB collection typo

This commit is contained in:
Studio 2026-11-27 10:51:13 -05:00
parent 39f6f1fdfe
commit 36489a1e91
9 changed files with 415 additions and 20 deletions

View file

@ -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'
);
}
}

View file

@ -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://<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}';`,
].join('\n');
expect(findEmbeddedHttpCredentials(sample)).toEqual([2, 16]);
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');
});