import { randomUUID } from 'node:crypto'; import { describe, expect, mock, test } from 'bun:test'; import { Hono } from 'hono'; 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: 'retention-operator-fixture-not-secret-123456', service: 'retention-service-fixture-not-secret-123456', read: 'retention-reader-fixture-not-secret-123456', }; function fixture(secured = false) { const database = { query: mock(async (_query: string, _values?: unknown[]) => ({ rows: [] })), transaction: mock(async () => { throw new Error('Invalid archive request reached storage'); }), }; const app = new Hono(); if (secured) { createHttpSecurity({ adminToken: tokens.operator, serviceToken: tokens.service, readToken: tokens.read, environment: 'test', }).mount(app); } app.route( '/', createBacktestV2Routes({ postgres: database, logger: { info() {}, error() {} }, } as unknown as IServiceContainer) ); return { app, database }; } describe('research retention route validation', () => { test('archive requires exactly a boolean and rejects malformed JSON before a transaction', async () => { const f = fixture(); for (const body of [ {}, null, [], { archived: 'true' }, { archived: 1 }, { archived: true, purge: true }, { archived: false, runId: randomUUID() }, ]) { expect( ( await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, { method: 'POST', body: JSON.stringify(body), }) ).status ).toBe(400); } expect( ( await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, { method: 'POST', body: '{', }) ).status ).toBe(400); expect(f.database.transaction.mock.calls).toHaveLength(0); }); test('includeArchived accepts only literal query booleans and defaults to active templates', async () => { const f = fixture(); for (const value of ['1', 'yes', 'TRUE', '']) { expect((await f.app.request(`/api/v2/backtests?includeArchived=${value}`)).status).toBe(400); } expect(f.database.query.mock.calls).toHaveLength(0); for (const query of ['', '?includeArchived=false', '?includeArchived=true']) { expect((await f.app.request(`/api/v2/backtests${query}`)).status).toBe(200); } expect(f.database.query.mock.calls.map(call => call[1])).toEqual([ [50, 0, false], [50, 0, false], [50, 0, true], ]); }); test('the existing security boundary prevents anonymous and read-only archive mutations', async () => { const f = fixture(true); for (const token of [undefined, tokens.read]) { const response = await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, { method: 'POST', headers: token ? { Authorization: `Bearer ${token}` } : {}, body: '{"archived":true}', }); expect(response.status).toBe(token ? 403 : 401); } expect(f.database.transaction.mock.calls).toHaveLength(0); }); });