137 lines
5.4 KiB
TypeScript
137 lines
5.4 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(body: string, role?: keyof typeof tokens) {
|
|
return app.request('/api/v2/experiments/validation/preview', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
|
},
|
|
body,
|
|
});
|
|
},
|
|
};
|
|
}
|
|
|
|
describe('chronological validation HTTP boundary', () => {
|
|
test('verified credentials are mandatory even for disabled development auth; read roles cannot prepare', async () => {
|
|
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
|
const f = fixture(mode);
|
|
expect((await f.request(JSON.stringify(input))).status).toBe(401);
|
|
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
|
}
|
|
const f = fixture();
|
|
expect((await f.request(JSON.stringify(input), 'read')).status).toBe(403);
|
|
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
|
});
|
|
test('malformed bodies, raw reserved keys, nonzero labels, fitted models and implicit windows reject before storage', async () => {
|
|
for (const body of [
|
|
'{',
|
|
'[]',
|
|
'null',
|
|
JSON.stringify({ ...input, backtestId: 'invalid' }),
|
|
JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }),
|
|
JSON.stringify({ ...input, modelArtifacts: ['fit'] }),
|
|
JSON.stringify({ ...input, recipe: { ...input.recipe, labelHorizonMs: 1 } }),
|
|
JSON.stringify({ ...input, recipe: { ...input.recipe, embargoMs: 0 } }),
|
|
JSON.stringify({
|
|
...input,
|
|
recipe: {
|
|
...input.recipe,
|
|
train: { ...input.recipe.train, tradeStart: '2024-01-01T09:06:00Z' },
|
|
},
|
|
}),
|
|
JSON.stringify({
|
|
...input,
|
|
recipe: {
|
|
...input.recipe,
|
|
train: { ...input.recipe.train, warmupStart: input.recipe.train.tradeStart },
|
|
},
|
|
}),
|
|
JSON.stringify({
|
|
...input,
|
|
recipe: {
|
|
...input.recipe,
|
|
validation: { ...input.recipe.validation, tradeStart: input.recipe.train.tradeEnd - 1 },
|
|
},
|
|
}),
|
|
JSON.stringify(input).replace('"fastPeriod":[1,2]', '"__proto__":[1]'),
|
|
]) {
|
|
const f = fixture();
|
|
const response = await f.request(body, 'operator');
|
|
expect(response.status).toBe(400);
|
|
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
|
expect(f.database.query.mock.calls).toHaveLength(0);
|
|
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
|
}
|
|
});
|
|
test('operator and service requests bind the preview method without requiring a receipt; missing and archived are distinct', async () => {
|
|
for (const role of ['operator', 'service'] as const) {
|
|
const f = fixture('enabled', async (sql, values) => {
|
|
expect(sql).toBe('SELECT * FROM backtests WHERE id=$1 FOR UPDATE');
|
|
expect(values).toEqual([input.backtestId]);
|
|
return { rows: [] };
|
|
});
|
|
const response = await f.request(JSON.stringify(input), role);
|
|
expect(response.status).toBe(404);
|
|
expect(await response.json()).toEqual({ error: 'Backtest not found' });
|
|
expect(f.database.transaction.mock.calls).toHaveLength(1);
|
|
}
|
|
const f = fixture('enabled', async () => ({
|
|
rows: [{ id: input.backtestId, archived_at: new Date() }],
|
|
}));
|
|
expect((await f.request(JSON.stringify(input), 'operator')).status).toBe(409);
|
|
});
|
|
test('unexpected storage and internal schema failures remain sanitized server errors, never invalid user input', async () => {
|
|
for (const error of [new Error('secret database connection detail'), new z.ZodError([])]) {
|
|
const f = fixture('enabled', async () => {
|
|
throw error;
|
|
});
|
|
const response = await f.request(JSON.stringify(input), 'operator');
|
|
expect(response.status).toBe(500);
|
|
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
|
}
|
|
});
|
|
});
|