stock-bot/test/integration/chronological-validation-durable-api.test.ts

133 lines
5.1 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { describe, expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import { z } from 'zod';
import { createHttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
import { chronologicalDataset } from '../fixtures/chronological-validation';
const tokens = {
operator: 'validation-admin-fixture-not-a-real-secret-1234',
service: 'validation-service-fixture-not-a-real-secret-1234',
read: 'validation-read-fixture-not-a-real-secret-1234',
};
const input = {
backtestId: randomUUID(),
name: 'Validation preview',
grid: { fastPeriod: [1, 2] },
recipe: chronologicalDataset().recipe,
};
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
function fixture(
mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
query: Query = async () => ({ rows: [] })
) {
const client = { query: mock(query) };
const database = {
...client,
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work(client)),
};
const app = new Hono();
if (mode !== 'absent') {
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
readToken: tokens.read,
environment: 'test',
hostname: '127.0.0.1',
disabled: mode === 'disabled',
}).mount(app);
}
app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer));
return {
database,
request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
return app.request('/api/v2/experiments/validation' + path, {
method,
headers: {
'Content-Type': 'application/json',
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
...(key ? { 'Idempotency-Key': key } : {}),
},
...(body === undefined ? {} : { body }),
});
},
};
}
const id = randomUUID(),
previewHash = 'a'.repeat(64),
selectionHash = 'b'.repeat(64);
const actions = [
['', JSON.stringify({ ...input, previewHash })],
[`/${id}/select`, JSON.stringify({ previewHash })],
[`/${id}/finalize`, JSON.stringify({ previewHash, selectionHash })],
[`/${id}/cancel`, '{}'],
];
describe('durable validation HTTP gates', () => {
test('all writes require real operator/service proof including disabled development auth; readers only inspect', async () => {
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
const f = fixture(mode);
for (const [path, body] of actions) {
expect((await f.request(path, 'POST', body, undefined, 'key')).status).toBe(401);
}
expect(f.database.transaction.mock.calls).toHaveLength(0);
}
const f = fixture();
for (const [path, body] of actions) {
expect((await f.request(path, 'POST', body, 'read', 'key')).status).toBe(403);
}
expect((await f.request('', 'GET', undefined, 'read')).status).toBe(200);
expect((await f.request(`/${id}`, 'GET', undefined, 'read')).status).toBe(404);
expect((await f.request()).status).toBe(401);
});
test('strict bodies, unknown winners/actions, raw reserved grids and missing receipts reject before any transaction', async () => {
for (const [path, body, key] of [
['', '{', 'key'],
['', JSON.stringify({ ...input, previewHash, winner: 1 }), 'key'],
[
'',
JSON.stringify({ ...input, previewHash }).replace('"fastPeriod":[1,2]', '"__proto__":[1]'),
'key',
],
[`/${id}/select`, JSON.stringify({ previewHash, winner: 0 }), 'key'],
[`/${id}/select`, JSON.stringify({ previewHash }), undefined],
[`/${id}/finalize`, JSON.stringify({ previewHash }), 'key'],
[
`/${id}/finalize`,
JSON.stringify({ previewHash, selectionHash, operation: 'select' }),
'key',
],
[`/${id}/cancel`, '{"restart":true}', undefined],
['/bad/select', JSON.stringify({ previewHash }), 'key'],
]) {
const f = fixture();
expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400);
expect(f.database.transaction.mock.calls).toHaveLength(0);
expect(f.database.query.mock.calls).toHaveLength(0);
}
});
test('correct operation routes return missing404 and sanitize unexpected database/schema errors500', async () => {
for (const role of ['operator', 'service'] as const) {
const f = fixture();
for (const [path, body] of actions) {
expect((await f.request(path, 'POST', body, role, 'key')).status).toBe(404);
}
}
for (const error of [new Error('private storage failure'), new z.ZodError([])]) {
const f = fixture('enabled', async () => {
throw error;
});
const response = await f.request(
`/${id}/select`,
'POST',
JSON.stringify({ previewHash }),
'operator',
'key'
);
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
}
});
});