stock-bot/scripts/test/security.test.ts

513 lines
20 KiB
TypeScript

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';
import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/services';
import { createPipelineRoutes } from '../../apps/stock/web-api/src/routes/pipeline.routes';
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes';
import { createWebSocketRoute } from '../../apps/stock/web-api/src/routes/websocket.routes';
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 {
findEmbeddedHttpCredentials,
scanTrackedFilesForHttpCredentials,
unexpectedTrackedEnvironmentFiles,
} from '../audit-secrets';
import { checks } from '../check';
const options: HttpSecurityOptions = {
readToken: 'read-fixture-token-not-a-real-credential-123456',
adminToken: 'admin-fixture-token-not-a-real-credential-123456',
serviceToken: 'service-fixture-token-not-a-real-credential-123456',
origins: ['http://ui.test'],
browserSessions: true,
};
const bearer = (token = options.adminToken!) => ({ Authorization: `Bearer ${token}` });
function fixture() {
const security = createHttpSecurity(options);
const app = new Hono();
security.mount(app);
let writes = 0;
app.get('/health', context => context.json({ status: 'ok' }));
app.get('/api/data', context => context.json({ data: [] }));
app.post('/api/write', context => {
writes++;
return context.json({ ok: true });
});
return { app, security, writes: () => writes };
}
async function login(app: Hono, token = options.adminToken!) {
const response = await app.request('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: 'http://ui.test' },
body: JSON.stringify({ token }),
});
expect(response.status).toBe(200);
return response;
}
test('HTTP security fails closed and insecure mode is loopback-development only', () => {
expect(() => createHttpSecurity({})).toThrow('STOCK_BOT_ADMIN_TOKEN');
expect(() => createHttpSecurity({ ...options, readToken: options.adminToken })).toThrow(
'distinct'
);
expect(() => createHttpSecurity({ ...options, adminToken: 'weak' })).toThrow('32');
expect(() => createHttpSecurity({ disabled: true, environment: 'production' })).toThrow(
'loopback'
);
expect(() => createHttpSecurity({ disabled: true, hostname: '0.0.0.0' })).toThrow('loopback');
expect(() => createHttpSecurity({ ...options, origins: ['*'] })).toThrow('trusted');
expect(createHttpSecurity({ disabled: true }).hostname).toBe('127.0.0.1');
});
test('submission principals are stable server identities across bearer/cookie renewal and ignore spoofed headers', async () => {
const f = fixture();
f.app.post('/api/principal', context => context.json({ principal: getVerifiedHttpPrincipal(context.req.raw) }));
const post = (headers: HeadersInit) => f.app.request('/api/principal', { method: 'POST', headers });
expect(await (await post({ ...bearer(), 'X-Principal': 'service' })).json()).toEqual({ principal: 'operator' });
expect(await (await post(bearer(options.serviceToken))).json()).toEqual({ principal: 'service' });
const cookies: string[] = [];
for (let i = 0; i < 2; i++) {
const session = await login(f.app);
const Cookie = session.headers.get('set-cookie')!.split(';')[0]!;
cookies.push(Cookie);
expect(await (await post({ Cookie, Origin: 'http://ui.test', 'X-Principal': 'attacker' })).json()).toEqual({ principal: 'operator' });
}
expect(cookies[0]).not.toBe(cookies[1]);
expect((await post(bearer(options.readToken))).status).toBe(403);
expect((await post({ 'X-Principal': 'operator' })).status).toBe(401);
expect(getVerifiedHttpPrincipal(new Request('http://api.test', { headers: { 'X-Principal': 'operator' } }))).toBeUndefined();
});
test('keyed run routes fail closed without verified security and support trusted CORS preflight', async () => {
const services = { logger: getLogger('submission-security'), postgres: {} } as IServiceContainer;
const path = '/api/v2/backtests/00000000-0000-4000-8000-000000000001/runs';
const request = { method: 'POST', headers: { 'Idempotency-Key': 'key', 'X-Principal': 'operator' }, body: '{}' };
const bare = createBacktestV2Routes(services);
expect((await bare.request(path, request)).status).toBe(401);
const app = createRoutes(services, createApiSecurity(options));
expect((await app.request(path, request)).status).toBe(401);
expect((await app.request(path, { ...request, headers: { ...request.headers, ...bearer(options.readToken) } })).status).toBe(403);
expect((await app.request(path, { ...request, headers: { ...bearer(), 'Idempotency-Key': '' } })).status).toBe(400);
const preflight = await app.request(path, { method: 'OPTIONS', headers: {
Origin: 'http://ui.test', 'Access-Control-Request-Method': 'POST',
'Access-Control-Request-Headers': 'content-type,idempotency-key',
} });
expect(preflight.status).toBe(204);
expect(preflight.headers.get('Access-Control-Allow-Headers')?.toLowerCase()).toContain('idempotency-key');
expect(preflight.headers.get('Access-Control-Allow-Origin')).toBe('http://ui.test');
});
test('anonymous/invalid access is rejected; readers cannot mutate; service/admin can', async () => {
const f = fixture();
expect((await f.app.request('/health')).status).toBe(200);
expect((await f.app.request('/api/data')).status).toBe(401);
expect((await f.app.request('/api/data', { headers: bearer('invalid') })).status).toBe(401);
expect((await f.app.request('/api/data', { headers: bearer(options.readToken) })).status).toBe(
200
);
expect(
(await f.app.request('/api/write', { method: 'POST', headers: bearer(options.readToken) }))
.status
).toBe(403);
expect(f.writes()).toBe(0);
for (const token of [options.adminToken, options.serviceToken]) {
expect(
(await f.app.request('/api/write', { method: 'POST', headers: bearer(token) })).status
).toBe(200);
}
expect(f.writes()).toBe(2);
});
test('browser login uses a signed HttpOnly cookie, with no raw credential in the response', async () => {
const f = fixture();
const response = await login(f.app);
const cookie = response.headers.get('set-cookie')!;
expect(cookie).toContain('HttpOnly');
expect(cookie).toContain('SameSite=Strict');
expect(cookie).not.toContain(options.adminToken!);
expect(await response.text()).not.toContain(options.adminToken!);
const headers = { Cookie: cookie.split(';')[0]! };
expect((await f.app.request('/api/data', { headers })).status).toBe(200);
expect((await f.app.request('/api/write', { method: 'POST', headers })).status).toBe(403);
expect(
(
await f.app.request('/api/write', {
method: 'POST',
headers: { ...headers, Origin: 'http://evil.test' },
})
).status
).toBe(403);
expect(
(
await f.app.request('/api/write', {
method: 'POST',
headers: { ...headers, Origin: 'http://ui.test' },
})
).status
).toBe(200);
expect(
(await f.app.request('/api/data', { headers: { Cookie: headers.Cookie + 'tampered' } })).status
).toBe(401);
const logout = await f.app.request('/api/auth/session', {
method: 'DELETE',
headers: { ...headers, Origin: 'http://ui.test' },
});
expect(logout.headers.get('set-cookie')).toContain('Max-Age=0');
});
test('read sessions cannot escalate, internal tokens cannot sign into the browser, and login rejects hostile origins', async () => {
const f = fixture();
const response = await login(f.app, options.readToken);
const Cookie = response.headers.get('set-cookie')!.split(';')[0]!;
expect(
(
await f.app.request('/api/write', {
method: 'POST',
headers: { Cookie, Origin: 'http://ui.test' },
})
).status
).toBe(403);
expect(
(await f.app.request('/api/data', { headers: { Cookie: Cookie.replace('read.', 'admin.') } }))
.status
).toBe(401);
for (const token of [options.serviceToken, 'wrong']) {
expect(
(
await f.app.request('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
})
).status
).toBe(401);
}
expect(
(
await f.app.request('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: 'http://evil.test' },
body: JSON.stringify({ token: options.adminToken }),
})
).status
).toBe(403);
});
test('production sessions are Secure and token rotation invalidates existing sessions', async () => {
const old = fixture();
const response = await login(old.app);
const Cookie = response.headers.get('set-cookie')!.split(';')[0]!;
const production = new Hono();
createHttpSecurity({ ...options, environment: 'production' }).mount(production);
const fresh = await login(production);
expect(fresh.headers.get('set-cookie')).toContain('; Secure');
const rotated = new Hono();
createHttpSecurity({
...options,
adminToken: 'rotated-fixture-credential-not-real-1234567890',
}).mount(rotated);
rotated.get('/api/data', context => context.json({}));
expect((await rotated.request('/api/data', { headers: { Cookie } })).status).toBe(401);
});
test('expired browser sessions are rejected', async () => {
const f = fixture();
const response = await login(f.app);
const Cookie = response.headers.get('set-cookie')!.split(';')[0]!;
const expiresAt = Number(Cookie.split('.')[1]);
const now = Date.now;
try {
Date.now = () => (expiresAt + 1) * 1000;
expect(
f.security.authorize(new Request('http://api.test/api/data', { headers: { Cookie } }))?.status
).toBe(401);
} finally {
Date.now = now;
}
});
test('WebSocket upgrade authenticates and validates browser origin before upgrading', async () => {
const f = fixture();
let upgraded = 0;
const route = createWebSocketRoute({ logger: getLogger('security-test') }, f.security);
const server = {
upgrade() {
upgraded++;
return true;
},
};
expect(
route(
new Request('http://api.test/ws?runId=one&token=ignored', {
headers: { Upgrade: 'websocket' },
}),
server
)?.status
).toBe(401);
const response = await login(f.app);
const Cookie = response.headers.get('set-cookie')!.split(';')[0]!;
expect(
route(
new Request('http://api.test/ws?runId=one', {
headers: { Upgrade: 'websocket', Cookie, Origin: 'http://evil.test' },
}),
server
)?.status
).toBe(403);
expect(upgraded).toBe(0);
expect(
route(
new Request('http://api.test/ws?runId=one', {
headers: { Upgrade: 'websocket', Cookie, Origin: 'http://ui.test' },
}),
server
)
).toBeUndefined();
expect(upgraded).toBe(1);
});
test('real pipeline reset route authenticates, requires admin and exact confirmation before queueing', async () => {
const jobs: unknown[] = [];
const services = {
logger: getLogger('reset-test'),
queueManager: {
getQueue() {
return {
async add(_name: string, data: unknown) {
jobs.push(data);
return { id: 'fixture' };
},
};
},
},
} as unknown as IServiceContainer;
const f = fixture();
f.app.route('/api/pipeline', createPipelineRoutes(services));
const url = '/api/pipeline/clear/postgresql';
const reset = { type: 'all', confirmation: 'DELETE STOCK REFERENCE DATA:all' };
expect((await f.app.request(url, { method: 'POST' })).status).toBe(401);
expect(
(await f.app.request(url, { method: 'POST', headers: bearer(options.readToken) })).status
).toBe(403);
expect((await f.app.request(url, { method: 'POST', headers: bearer(), body: '{}' })).status).toBe(
400
);
expect(
(
await f.app.request('/api/pipeline/exchanges/all?clear=true', {
method: 'POST',
headers: bearer(),
})
).status
).toBe(400);
expect(jobs).toHaveLength(0);
expect(
(await f.app.request(url, { method: 'POST', headers: bearer(), body: JSON.stringify(reset) }))
.status
).toBe(200);
expect(jobs).toEqual([
{ handler: 'exchanges', operation: 'clear-postgresql-data', payload: reset },
]);
expect(() =>
parseReferenceDataResetRequest({
type: 'all',
confirmation: 'DELETE STOCK REFERENCE DATA:exchanges',
})
).toThrow();
});
test('log redaction covers nested configuration, errors, cookies, bearer tokens and authenticated URLs without mutation', () => {
const source = {
password: 'private-pass',
nested: { apiKey: 'private-key', safe: 'hello' },
rows: [{ token: 'private-token' }],
error: new Error('GET https://user:private-pass@example.test/api?api_token=private-key failed'),
header: 'Bearer private-token',
cookie: 'private-cookie',
};
const output = JSON.stringify(redactLogValue(source));
for (const value of ['private-pass', 'private-key', 'private-token', 'private-cookie'])
expect(output).not.toContain(value);
expect(output).toContain('hello');
expect(source.password).toBe('private-pass');
const circular: Record<string, unknown> = {};
circular.self = circular;
expect(JSON.stringify(redactLogValue(circular))).toContain('[Circular]');
});
test('native tests and credential-file audit remain mandatory repository gates', () => {
expect(checks).toContain('test:native');
expect(checks).toContain('audit:secrets');
expect(
unexpectedTrackedEnvironmentFiles([
'.env',
'apps/stock/web-app/.env',
'.env.production',
'apps/stock/web-api/.env',
'apps/stock/web-app/.env.local',
'.env.example',
'libs/core/config/.env.example',
'apps/wcag-ada/.env',
])
).toEqual(['.env.production', 'apps/stock/web-api/.env', 'apps/stock/web-app/.env.local']);
const ci = readFileSync(new URL('../../.gitlab-ci.yml', import.meta.url), 'utf8');
expect(ci).toContain('bun run test:postgres');
for (const file of ['docker-compose.yml', 'docker-compose.dev.yml']) {
const compose = readFileSync(new URL(`../../${file}`, import.meta.url), 'utf8');
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 });
}
});