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 { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; import { ResearchError } from '../../apps/stock/web-api/src/services/research-errors'; 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 () => { throw new Error('Rejected request reached transaction'); }), }; 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(); const hypothesisId = randomUUID(); const artifactId = randomUUID(); const strategyId = randomUUID(); const hypothesis = { title: 'Research hypothesis', proposition: 'A testable proposition' }; const note = { kind: 'note', title: 'Research note', body: 'Unvalidated narrative' }; const writes = [ { path: 'research-projects', body: { title: 'Project' }, method: 'POST' }, { path: `research-projects/${projectId}`, body: { expectedRevision: 1, archived: true }, method: 'PATCH', }, { path: `research-projects/${projectId}/strategies/${strategyId}`, method: 'PUT' }, { path: `research-projects/${projectId}/strategies/${strategyId}`, method: 'DELETE' }, { path: `research-projects/${projectId}/hypotheses`, body: hypothesis, method: 'POST' }, { path: `hypotheses/${hypothesisId}/revisions`, body: { ...hypothesis, expectedRevision: 1 }, method: 'POST', }, { path: `hypotheses/${hypothesisId}`, body: { archived: true }, method: 'PATCH' }, { path: `research-projects/${projectId}/analysis-artifacts`, body: note, method: 'POST' }, { path: `analysis-artifacts/${artifactId}/revisions`, body: { title: 'Changed', body: '', expectedRevision: 1 }, method: 'POST', }, { path: `analysis-artifacts/${artifactId}`, body: { archived: true }, method: 'PATCH' }, ]; const readPaths = [ 'research-projects', `research-projects/${projectId}`, `research-projects/${projectId}/strategies`, `research-projects/${projectId}/hypotheses`, `research-projects/${projectId}/analysis-artifacts`, `hypotheses/${hypothesisId}`, `hypotheses/${hypothesisId}/revisions`, `analysis-artifacts/${artifactId}`, `analysis-artifacts/${artifactId}/revisions`, ]; function noStorage(f: ReturnType) { expect(f.database.query.mock.calls).toHaveLength(0); expect(f.database.transaction.mock.calls).toHaveLength(0); } describe('research HTTP credential and transport boundary', () => { test('every mutation rejects absent credentials, forged actors and the development bypass', async () => { for (const mode of ['enabled', 'disabled', 'absent'] as const) { const f = fixture(mode); for (const write of writes) { const response = await f.request(write.path, write.body, undefined, write.method, { 'X-Actor': 'operator', 'X-Principal': 'operator', }); expect(response.status).toBe(401); } noStorage(f); } }); test('the mounted read role may read but cannot mutate; anonymous reads reject', async () => { const f = fixture('enabled', async () => ({ rows: [] })); for (const path of readPaths) { expect((await f.request(path)).status).toBe(401); } for (const write of writes) { expect((await f.request(write.path, write.body, 'read', write.method)).status).toBe(403); } noStorage(f); const response = await f.request('research-projects', undefined, 'read'); expect(response.status).toBe(200); expect(await response.json()).toEqual({ projects: [] }); expect(response.headers.get('Cache-Control')).toBe('no-store'); }); test('service credentials cannot claim human authorship before storage', async () => { const f = fixture(); const cases = [ { path: `research-projects/${projectId}/hypotheses`, body: hypothesis }, { path: `hypotheses/${hypothesisId}/revisions`, body: { ...hypothesis, expectedRevision: 1 }, }, { path: `research-projects/${projectId}/analysis-artifacts`, body: note }, { path: `analysis-artifacts/${artifactId}/revisions`, body: { title: 'Finding', body: '', expectedRevision: 1 }, }, ]; for (const item of cases) { const response = await f.request( `${item.path}?actor=operator`, { ...item.body, contentOrigin: 'human' }, 'service', 'POST', { 'X-Actor': 'operator' } ); expect(response.status).toBe(403); } noStorage(f); }); test('strict metadata bodies reject submitted actor, approval and validation claims', async () => { const f = fixture(); for (const write of writes) { for (const field of ['submittedBy', 'ownerPrincipal', 'validationState', 'approved']) { const response = await f.request( write.path, { ...(write.body ?? {}), [field]: field === 'approved' ? true : 'operator' }, 'operator', write.method ); expect(response.status).toBe(400); } } noStorage(f); }); test('invalid revision, text and metric references reject before database access', async () => { const f = fixture(); const invalidBodies = [ { path: 'research-projects', body: { title: '' }, method: 'POST' }, { path: `research-projects/${projectId}`, body: { title: 'No revision' }, method: 'PATCH' }, { path: `hypotheses/${hypothesisId}/revisions`, body: { ...hypothesis, expectedRevision: 0 }, method: 'POST', }, { path: `analysis-artifacts/${artifactId}`, body: { archived: 'true' }, method: 'PATCH' }, ]; for (const item of invalidBodies) { expect((await f.request(item.path, item.body, 'operator', item.method)).status).toBe(400); } for (const badText of ['bad\u0000text', 'bad\ud800text', 'bad\udc00text']) { expect((await f.request('research-projects', { title: badText }, 'operator')).status).toBe( 400 ); expect( ( await f.request( `research-projects/${projectId}/hypotheses`, { ...hypothesis, proposition: badText }, 'operator' ) ).status ).toBe(400); expect( ( await f.request( `research-projects/${projectId}/analysis-artifacts`, { ...note, body: badText }, 'operator' ) ).status ).toBe(400); } const reference = { runId: randomUUID(), metricsVersion: 'canonical-analytics/v1', metricPath: 'analytics.metrics.totalReturn', }; for (const evidence of [ [{ ...reference, metricsVersion: 'invented/v1' }], [{ ...reference, metricPath: '__proto__.totalReturn' }], [{ ...reference, value: 10 }], [reference, reference], ]) { const response = await f.request( `research-projects/${projectId}/analysis-artifacts`, { ...note, evidence }, 'operator' ); expect(response.status).toBe(400); } noStorage(f); }); test('list archive filters and path IDs are strict; unrelated API middleware is unaffected', async () => { const f = fixture(); for (const path of [ 'research-projects', `research-projects/${projectId}/hypotheses`, `research-projects/${projectId}/analysis-artifacts`, ]) { for (const value of ['', '1', 'TRUE', 'maybe']) { expect( (await f.request(`${path}?includeArchived=${value}`, undefined, 'read')).status ).toBe(400); } } for (const path of [ 'research-projects/not-a-uuid', 'hypotheses/not-a-uuid', 'analysis-artifacts/not-a-uuid', `research-projects/not-a-uuid/strategies`, ]) { expect((await f.request(path, undefined, 'read')).status).toBe(400); } noStorage(f); const unrelated = await f.request('unrelated', {}, 'operator'); expect(unrelated.status).toBe(200); expect(unrelated.headers.get('Cache-Control')).toBeNull(); }); test('malformed JSON rejects and metadata APIs do not expose deletion, approval or execution', async () => { const f = fixture(); for (const write of writes) { const response = await f.app.request(`/api/v2/${write.path}`, { method: write.method, headers: { Authorization: `Bearer ${tokens.operator}`, 'Content-Type': 'application/json' }, body: '{', }); expect(response.status).toBe(400); } for (const path of [ `research-projects/${projectId}`, `hypotheses/${hypothesisId}`, `analysis-artifacts/${artifactId}`, ]) { expect((await f.request(path, undefined, 'operator', 'DELETE')).status).toBe(404); for (const action of ['approve', 'execute', 'deploy']) { expect((await f.request(`${path}/${action}`, {}, 'operator')).status).toBe(404); } } noStorage(f); }); test('missing resources and typed conflicts retain their statuses; internal details do not leak', async () => { const missing = fixture('enabled', async () => ({ rows: [] })); expect( (await missing.request(`research-projects/${projectId}`, undefined, 'read')).status ).toBe(404); for (const status of [409, 422] as const) { const f = fixture('enabled', async () => { throw new ResearchError(status, 'Retained research reference rejected'); }); const response = await f.request(`research-projects/${projectId}`, undefined, 'read'); expect(response.status).toBe(status); expect(await response.json()).toEqual({ error: 'Retained research reference rejected' }); } const internal = fixture('enabled', async () => { throw new Error('private-database-connection-and-query-detail'); }); const response = await internal.request('research-projects', undefined, 'read'); expect(response.status).toBe(500); expect(await response.json()).toEqual({ error: 'Research workspace unavailable' }); expect(internal.logger.error.mock.calls).toHaveLength(1); }); test('project creation records verified principal instead of forged identity headers', async () => { for (const role of ['operator', 'service'] as const) { const f = fixture('enabled', async (_sql, values) => ({ rows: [ { id: projectId, title: 'Project', description: '', revision: 1, owner_principal: values?.includes('service') ? 'service' : 'operator', updated_by: values?.includes('service') ? 'service' : 'operator', archived_at: null, created_at: new Date('2026-01-01'), updated_at: new Date('2026-01-01'), }, ], })); const response = await f.request('research-projects', { title: 'Project' }, role, 'POST', { 'X-Actor': role === 'service' ? 'operator' : 'service', }); expect(response.status).toBe(201); const body = await response.json(); expect(body.project.ownerPrincipal).toBe(role); expect(body.project.updatedBy).toBe(role); expect(f.database.query.mock.calls[0]?.[1]).toContain(role); expect(response.headers.get('Cache-Control')).toBe('no-store'); } }); test('a valid artifact citation with a corrupt retained request returns a sanitized server error', async () => { const revisionId = randomUUID(); const runId = randomUUID(); const backtestId = randomUUID(); const stamp = new Date('2026-01-01'); const f = fixture('enabled', async sql => { if (sql.includes('FROM analysis_artifacts WHERE')) { return { rows: [ { id: artifactId, project_id: projectId, hypothesis_revision_id: null, kind: 'finding', owner_principal: 'operator', updated_by: 'operator', archived_at: null, created_at: stamp, updated_at: stamp, }, ], }; } if (sql.includes('FROM analysis_artifact_revisions WHERE')) { return { rows: [ { id: revisionId, artifact_id: artifactId, ordinal: 1, title: 'Retained finding', body: 'Narrative is not a metric', submitted_by: 'operator', content_origin: 'human', created_at: stamp, }, ], }; } if (sql.includes('FROM analysis_evidence WHERE')) { return { rows: [ { revision_id: revisionId, ordinal: 1, run_id: runId, metrics_version: 'canonical-analytics/v1', metric_path: 'analytics.metrics.totalReturn', strategy_version_id: null, }, ], }; } if (sql.includes('FROM runs WHERE')) { return { rows: [{ id: runId, backtest_id: backtestId, status: 'completed' }] }; } if (sql.includes('FROM backtest_results br')) { // The reference is valid. This damage is in retained server evidence, // and must not be classified as a malformed client request. return { rows: [ { run_id: runId, backtest_id: backtestId, run_status: 'completed', canonical_result: { kind: 'canonical-result/v1' }, request_snapshot: { kind: 'canonical-research/v1', 'private-retained-marker': true }, }, ], }; } throw new Error(`Unexpected evidence query: ${sql}`); }); const response = await f.request(`analysis-artifacts/${artifactId}`, undefined, 'read'); expect(response.status).toBe(500); expect(await response.json()).toEqual({ error: 'Research workspace unavailable' }); expect(response.headers.get('Cache-Control')).toBe('no-store'); expect(f.database.query.mock.calls).toHaveLength(5); expect(f.logger.error.mock.calls).toHaveLength(1); const diagnostic = f.logger.error.mock.calls[0]?.[1] as { error?: unknown } | undefined; expect(diagnostic?.error).toBeInstanceOf(Error); if (!(diagnostic?.error instanceof Error)) { throw new Error('Missing retained-read diagnostic'); } expect(diagnostic.error.message).toBe('Retained research result could not be read'); expect(diagnostic.error.cause).toBeInstanceOf(z.ZodError); }); });