186 lines
7.3 KiB
TypeScript
186 lines
7.3 KiB
TypeScript
import { createHash, 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 { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
|
|
|
const tokens = {
|
|
operator: 'reproduction-admin-fixture-not-a-real-secret-1234',
|
|
service: 'reproduction-service-fixture-not-a-real-secret-1234',
|
|
read: 'reproduction-read-fixture-not-a-real-secret-1234',
|
|
};
|
|
const originalRunId = randomUUID();
|
|
const runId = randomUUID();
|
|
const backtestId = randomUUID();
|
|
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>): 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('/', createBacktestV2Routes({ postgres: database } as unknown as IServiceContainer));
|
|
return {
|
|
database,
|
|
request(path: string, method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
|
|
return app.request(`/api/v2/runs/${path}`, {
|
|
method,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
|
...(key !== undefined ? { 'Idempotency-Key': key } : {}),
|
|
},
|
|
...(body === undefined ? {} : { body }),
|
|
});
|
|
},
|
|
};
|
|
}
|
|
function row(extra: Record<string, unknown> = {}) {
|
|
return {
|
|
id: runId,
|
|
backtest_id: backtestId,
|
|
original_run_id: originalRunId,
|
|
run_number: 2,
|
|
status: 'pending',
|
|
speed_multiplier: null,
|
|
progress: '0',
|
|
attempt_number: 0,
|
|
created_at: '2026-10-24T00:00:00Z',
|
|
updated_at: '2026-10-24T00:00:00Z',
|
|
...extra,
|
|
};
|
|
}
|
|
|
|
describe('original reproduction HTTP contract', () => {
|
|
test('mutation requires credential proof even with development bypass or forged actor', async () => {
|
|
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
|
const f = fixture(mode);
|
|
const response = await f.request(
|
|
`${originalRunId}/reproduce?actor=operator`,
|
|
'POST',
|
|
'{}',
|
|
undefined,
|
|
'receipt'
|
|
);
|
|
expect(response.status).toBe(401);
|
|
expect(f.database.query.mock.calls).toHaveLength(0);
|
|
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
|
}
|
|
});
|
|
test('read-only role may inspect but cannot submit and anonymous reads reject', async () => {
|
|
const f = fixture();
|
|
expect((await f.request(`${runId}/reproduction`)).status).toBe(401);
|
|
expect((await f.request(`${runId}/reproduction-comparison`)).status).toBe(401);
|
|
expect((await f.request(`${runId}/reproduce`, 'POST', '{}', 'read', 'key')).status).toBe(403);
|
|
expect((await f.request(`${runId}/reproduction`, 'GET', undefined, 'read')).status).toBe(404);
|
|
});
|
|
test('strict original-run IDs, body and required keys reject financial overrides before storage', async () => {
|
|
for (const [id, body, key] of [
|
|
[originalRunId, '{}', undefined],
|
|
[originalRunId, '{}', 'contains space'],
|
|
[originalRunId, '{}', 'x'.repeat(201)],
|
|
[originalRunId, '{', 'key'],
|
|
[originalRunId, 'null', 'key'],
|
|
[originalRunId, '[]', 'key'],
|
|
[originalRunId, '{"feeRate":"0"}', 'key'],
|
|
[originalRunId, '{"originalRunId":"other"}', 'key'],
|
|
['not-uuid', '{}', 'key'],
|
|
]) {
|
|
const f = fixture();
|
|
expect((await f.request(`${id}/reproduce`, 'POST', body, 'operator', key)).status).toBe(400);
|
|
expect(f.database.query.mock.calls).toHaveLength(0);
|
|
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
|
}
|
|
const f = fixture();
|
|
expect((await f.request('bad/reproduction', 'GET', undefined, 'read')).status).toBe(400);
|
|
expect((await f.request('bad/reproduction-comparison', 'GET', undefined, 'read')).status).toBe(
|
|
400
|
|
);
|
|
});
|
|
test('an accepted receipt returns its original run and Location before eligibility checks', async () => {
|
|
const key = 'already-admitted';
|
|
const hash = createHash('sha256')
|
|
.update(JSON.stringify({ version: 1, operation: 'reproduce-original', originalRunId }))
|
|
.digest('hex');
|
|
for (const principal of ['operator', 'service'] as const) {
|
|
const f = fixture('enabled', async (sql, values) => {
|
|
expect(sql).toContain('submission_principal=$1');
|
|
expect(values).toEqual([principal, key]);
|
|
return { rows: [row({ submission_hash: hash })] };
|
|
});
|
|
const reply = await f.request(`${originalRunId}/reproduce`, 'POST', '{}', principal, key);
|
|
expect(reply.status).toBe(202);
|
|
expect(reply.headers.get('Location')).toBe(`/api/v2/runs/${runId}`);
|
|
expect(reply.headers.get('Cache-Control')).toBe('no-store');
|
|
expect(await reply.json()).toMatchObject({ id: runId, originalRunId, backtestId });
|
|
expect(f.database.query.mock.calls).toHaveLength(1);
|
|
}
|
|
});
|
|
test('receipt intent conflict is409, missing source404, incomplete preview is unavailable', async () => {
|
|
const conflict = fixture('enabled', async () => ({
|
|
rows: [row({ submission_hash: 'different' })],
|
|
}));
|
|
expect(
|
|
(await conflict.request(`${originalRunId}/reproduce`, 'POST', '{}', 'operator', 'key')).status
|
|
).toBe(409);
|
|
const missing = fixture();
|
|
expect(
|
|
(await missing.request(`${originalRunId}/reproduce`, 'POST', '{}', 'operator', 'key')).status
|
|
).toBe(404);
|
|
const pending = fixture('enabled', async () => ({ rows: [row()] }));
|
|
const preview = await pending.request(`${runId}/reproduction`, 'GET', undefined, 'read');
|
|
expect(preview.status).toBe(200);
|
|
expect(await preview.json()).toMatchObject({
|
|
originalRunId: runId,
|
|
backtestId,
|
|
available: false,
|
|
request: null,
|
|
});
|
|
const compare = await pending.request(
|
|
`${runId}/reproduction-comparison`,
|
|
'GET',
|
|
undefined,
|
|
'read'
|
|
);
|
|
expect(await compare.json()).toMatchObject({
|
|
runId,
|
|
originalRunId,
|
|
status: 'pending',
|
|
originalHash: null,
|
|
});
|
|
});
|
|
test('unexpected database and retained schema failures remain sanitized500, never input400 or available', async () => {
|
|
for (const failure of [new Error('private connection info'), new z.ZodError([])]) {
|
|
const f = fixture('enabled', async () => {
|
|
throw failure;
|
|
});
|
|
for (const [path, method, body, key] of [
|
|
[`${runId}/reproduction`, 'GET', undefined, undefined],
|
|
[`${runId}/reproduction-comparison`, 'GET', undefined, undefined],
|
|
[`${runId}/reproduce`, 'POST', '{}', 'key'],
|
|
] as const) {
|
|
const response = await f.request(path, method, body, 'operator', key);
|
|
expect(response.status).toBe(500);
|
|
expect(await response.text()).not.toContain('private connection');
|
|
}
|
|
}
|
|
});
|
|
});
|