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 { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; const tokens = { operator: 'research-admin-fixture-not-a-real-secret-1234', service: 'research-service-fixture-not-a-real-secret-1234', read: 'research-read-fixture-not-a-real-secret-1234', }; type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record[] }>; function fixture( security: 'enabled' | 'disabled' | 'absent' = 'enabled', query: Query = async () => { throw new Error('Rejected request reached storage'); } ) { const database = { query: mock(query), transaction: mock(async (work: (client: { query: Query }) => Promise) => work({ query })), }; const logger = { error: mock((_message: string, _details?: unknown) => {}) }; const app = new Hono(); if (security !== 'absent') { createHttpSecurity({ adminToken: tokens.operator, serviceToken: tokens.service, readToken: tokens.read, environment: 'test', hostname: '127.0.0.1', disabled: security === 'disabled', }).mount(app); } app.route( '/', createResearchRoutes({ postgres: database, logger } as unknown as IServiceContainer) ); app.post('/api/v2/unrelated', c => c.json({ ok: true })); return { database, logger, app, request( path: string, body?: unknown, role?: keyof typeof tokens, method = body === undefined ? 'GET' : 'POST', extra: Record = {} ) { return app.request(`/api/v2/${path}`, { method, headers: { ...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}), 'Content-Type': 'application/json', ...extra, }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); }, }; } const projectId = randomUUID(), runId = randomUUID(); const source = { kind: 'experiment/v1', experimentId: randomUUID(), previewHash: 'a'.repeat(64) }; const body = { kind: 'finding', title: 'Evidence', body: 'Claim', source, evidence: [ { runId, metricsVersion: 'canonical-analytics/v1', metricPath: 'analytics.metrics.totalReturn', }, ], }; describe('source findings HTTP boundary', () => { test('malformed source metadata rejects before storage and write credentials remain mandatory', async () => { for (const change of [ { ...source, extra: true }, { ...source, previewHash: null }, { ...source, experimentId: 'bad' }, { ...source, kind: 'chronological-report/v1' }, ]) { const f = fixture(); expect( ( await f.request( `research-projects/${projectId}/analysis-artifacts`, { ...body, source: change }, 'operator' ) ).status ).toBe(400); expect(f.database.transaction.mock.calls).toHaveLength(0); } const f = fixture(); expect( (await f.request(`research-projects/${projectId}/analysis-artifacts`, body)).status ).toBe(401); expect( (await f.request(`research-projects/${projectId}/analysis-artifacts`, body, 'read')).status ).toBe(403); expect(f.database.transaction.mock.calls).toHaveLength(0); }); test('missing source is422 without exposing storage details; unexpected errors remain sanitized500', async () => { for (const broken of [false, true]) { const f = fixture('enabled', async sql => { if (sql.includes('FROM research_projects')) { return { rows: [{ id: projectId, archived_at: null }] }; } if (sql.startsWith('INSERT INTO analysis_artifacts(')) { return { rows: [{ id: randomUUID() }] }; } if (broken) { throw new Error('private database details'); } return { rows: [] }; }); const response = await f.request( `research-projects/${projectId}/analysis-artifacts`, body, 'operator' ); expect(response.status).toBe(broken ? 500 : 422); expect(response.headers.get('Cache-Control')).toBe('no-store'); if (broken) { expect(await response.json()).toEqual({ error: 'Research workspace unavailable' }); } } }); test('artifact reads select repeatable read-only mode before storage and do not require mutation credentials', async () => { const calls: string[] = []; const f = fixture('enabled', async sql => { calls.push(sql); return { rows: [] }; }); const response = await f.request(`analysis-artifacts/${randomUUID()}`, undefined, 'read'); expect(response.status).toBe(404); expect(calls[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); expect(calls.every(sql => !sql.includes('FOR UPDATE') && !sql.includes('FOR SHARE'))).toBe( true ); }); });