This commit is contained in:
Boki 2026-10-20 18:36:19 -04:00
parent 879e9b4228
commit c3cb36c8d6
51 changed files with 2290 additions and 1467 deletions

32
scripts/audit-secrets.ts Normal file
View file

@ -0,0 +1,32 @@
// Explicit private local-development exceptions, not a general permission to track secrets.
const localDevelopmentEnvironmentFiles = new Set(['.env', 'apps/stock/web-app/.env']);
/** Refuse unexpected tracked environment files without printing contents or values. */
export function unexpectedTrackedEnvironmentFiles(paths: readonly string[]): string[] {
return paths.filter(path => {
if (path.startsWith('apps/wcag-ada/') || localDevelopmentEnvironmentFiles.has(path))
return false;
const name = path.split('/').at(-1) ?? '';
return (
(name === '.env' || name.startsWith('.env.')) &&
name !== '.env.example' &&
!name.endsWith('.example')
);
});
}
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`);
process.exitCode = 1;
} else {
process.stdout.write(
'Tracked environment-file audit passed (two local-development exceptions; WCAG excluded).\n'
);
}
}

View file

@ -2,11 +2,13 @@
import { fileURLToPath } from 'node:url';
export const checks = [
'audit:secrets',
'build',
'typecheck',
'test:contracts',
'test:tooling',
'test:integration',
'test:native',
'lint:check',
] as const;

12
scripts/test-postgres.ts Normal file
View file

@ -0,0 +1,12 @@
const url = process.env.PIPELINE_TEST_DATABASE_URL;
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error(
'Set PIPELINE_TEST_DATABASE_URL to a disposable stock_bot_safety database; tests create/drop isolated schemas'
);
}
const child = Bun.spawn([process.execPath, 'test', 'test/postgres/'], {
stdin: 'inherit',
stdout: 'inherit',
stderr: 'inherit',
});
process.exitCode = await child.exited;

View file

@ -0,0 +1,318 @@
import { readFileSync } from 'node:fs';
import { expect, test } from 'bun:test';
import { Hono } from 'hono';
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 { createWebSocketRoute } from '../../apps/stock/web-api/src/routes/websocket.routes';
import { createHttpSecurity, 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 { 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('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);
}
});