118 lines
4.5 KiB
TypeScript
118 lines
4.5 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';
|
|
|
|
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',
|
|
scenarios: [{ feeRate: '0', slippageRate: '0' }],
|
|
};
|
|
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' + 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);
|
|
|
|
const actions = [
|
|
['/cost-sensitivity/preview', JSON.stringify(input)],
|
|
['/cost-sensitivity', JSON.stringify({ ...input, previewHash })],
|
|
];
|
|
describe('cost-sensitivity HTTP gates', () => {
|
|
test('cost mutation requires verified operator/service even in disabled auth mode', 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);
|
|
});
|
|
test('strict mixed modes, costs, malformed JSON and missing receipt fail before storage', async () => {
|
|
for (const [path, body, key] of [
|
|
['/cost-sensitivity/preview', '{', 'key'],
|
|
['/cost-sensitivity/preview', JSON.stringify({ ...input, grid: {} }), 'key'],
|
|
[
|
|
'/cost-sensitivity/preview',
|
|
JSON.stringify({ ...input, scenarios: [{ feeRate: '0', slippageRate: '1' }] }),
|
|
'key',
|
|
],
|
|
['/cost-sensitivity', JSON.stringify({ ...input, previewHash }), undefined],
|
|
['/cost-sensitivity', JSON.stringify({ ...input, previewHash, mode: 'ordinary' }), 'key'],
|
|
]) {
|
|
const f = fixture();
|
|
expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400);
|
|
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
|
}
|
|
});
|
|
test('correct operation routes return404 or sanitized500; existing detail/cancel routes stay shared', 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);
|
|
}
|
|
expect((await f.request(`/${id}`, 'GET', undefined, role)).status).toBe(404);
|
|
}
|
|
for (const error of [new Error('private database failure'), new z.ZodError([])]) {
|
|
const f = fixture('enabled', async () => {
|
|
throw error;
|
|
});
|
|
const response = await f.request(
|
|
'/cost-sensitivity/preview',
|
|
'POST',
|
|
JSON.stringify(input),
|
|
'operator'
|
|
);
|
|
expect(response.status).toBe(500);
|
|
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
|
}
|
|
});
|
|
});
|