safety
This commit is contained in:
parent
879e9b4228
commit
c3cb36c8d6
51 changed files with 2290 additions and 1467 deletions
318
scripts/test/security.test.ts
Normal file
318
scripts/test/security.test.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue