import { randomUUID } from 'node:crypto'; import { expect, mock, test } from 'bun:test'; import { Hono } from 'hono'; import { createHttpSecurity, getCredentialHttpPrincipal, getResearchHttpPrincipal, } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/services'; import { createResearchAgentSchema } from '@stock-bot/stock-config/research-agents'; import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes'; import { researchAgentDatabaseError } from '../../apps/stock/web-api/src/services/research-agent-budget'; import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service'; const agent = `agent:${randomUUID()}` as const; const token = 'sb-research.fixture-token'; const adminToken = 'operator-test-secret-12345678901234567890'; const serviceToken = 'service-test-secret-123456789012345678901'; const limits = { maxActiveTrials: 2, maxTrialsPerExperiment: 4, maxBarEvaluationsPerExperiment: 1000, maxAttemptWallMs: 1000, maxAttempts: 2, }; function boundary(disabled = false, resolver = true) { const resolve = mock(async () => ({ principal: agent })); const security = createHttpSecurity({ adminToken, serviceToken, disabled, environment: 'test', browserSessions: true, ...(resolver ? { resolveResearchCredential: resolve } : {}), }); const app = new Hono(); security.mount(app); app.all('/api/v2/experiments', c => c.json({ principal: getResearchHttpPrincipal(c.req.raw), privileged: getCredentialHttpPrincipal(c.req.raw) ?? null, }) ); return { app, security, resolve }; } test('research HTTP identity is distinct; Origin and upgrades are fenced before asynchronous resolution', async () => { const f = boundary(); for (const headers of [{ Origin: 'https://evil.invalid' }, { Upgrade: 'websocket' }] as Record< string, string >[]) { const response = await f.app.request('/api/v2/experiments', { method: 'POST', headers: { Authorization: `Bearer ${token}`, ...headers }, }); expect(response.status).toBe(403); expect(response.headers.get('cache-control')).toBe('no-store'); } expect(f.resolve).toHaveBeenCalledTimes(0); const response = await f.app.request('/api/v2/experiments', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, }); expect(response.status).toBe(200); expect(await response.json()).toEqual({ principal: agent, privileged: null }); expect( f.security.authorize( new Request('http://localhost/api/v2/experiments', { headers: { Authorization: `Bearer ${token}` }, }) )?.status ).toBe(403); }); test('research credential never becomes a privileged session or bypasses disabled/unrelated authentication', async () => { for (const f of [boundary(true), boundary(false, false)]) { const response = await f.app.request('/api/v2/experiments', { headers: { Authorization: `Bearer ${token}` }, }); expect(response.status).toBe(403); expect(f.resolve).toHaveBeenCalledTimes(0); expect(f.security.researchEnabled).toBe(false); const login = await f.app.request('/api/auth/session', { method: 'POST', headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), }); expect(login.status).toBe(403); expect(login.headers.get('set-cookie')).toBeNull(); } const f = boundary(); const login = await f.app.request('/api/auth/session', { method: 'POST', headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), }); expect(login.status).toBe(403); expect(login.headers.get('set-cookie')).toBeNull(); }); test('operator-only provisioning fails closed without enabled research authentication before storage', async () => { const query = mock(async () => { throw new Error('denied operation touched storage'); }); const container = { postgres: { query }, logger: { error: mock(() => {}) }, } as unknown as IServiceContainer; for (const disabled of [false, true]) { const f = boundary(disabled); f.app.route('/', createResearchAgentRoutes(container, f.security.researchEnabled)); for (const bearer of [token, serviceToken, ...(disabled ? [adminToken] : [])]) { const response = await f.app.request('/api/v2/research-agents', { method: 'POST', headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' }, body: '{}', }); expect(response.status).toBe(403); } } expect(query).toHaveBeenCalledTimes(0); }); test('resolver exact write capabilities refuse trading, operators, foreign evidence and ownership impersonation', async () => { const projectId = randomUUID(), experimentId = randomUUID(), familyId = randomUUID(); const query = mock(async (sql: string) => ({ rows: sql.includes('token_hash') ? [{ id: agent, enabled: true, policy: { allowedProjectIds: [projectId] } }] : [{ submission_principal: 'operator', owner_principal: 'operator', project_id: projectId }], })); const service = new ResearchAgentsService({ postgres: { query }, } as unknown as IServiceContainer); const check = (path: string, method = 'POST') => service.authenticate( new Request(`http://localhost${path}`, { method, headers: { Authorization: `Bearer ${token}` }, }) ); for (const path of [ '/api/v2/research-agents', '/api/v2/backtests', '/api/v2/datasets/retain', '/api/v2/strategy-versions/' + familyId + '/review', '/api/operations/start', '/api/v2/runs/' + experimentId + '/reproduce', `/api/v2/experiments/${experimentId}/cancel`, `/api/v2/strategies/${familyId}/versions`, `/api/v2/research-projects/${randomUUID()}/hypotheses`, ]) { expect(await check(path)).toBeInstanceOf(Response); expect(((await check(path)) as Response).status).toBe(403); } expect(await check(`/api/v2/research-projects/${projectId}/hypotheses`)).toEqual({ principal: agent, }); expect(await check('/api/v2/experiments/preview')).toEqual({ principal: agent }); expect(await check(`/api/v2/experiments/${experimentId}`, 'GET')).toEqual({ principal: agent }); expect(await check('/api/v2/research-agents', 'GET')).toBeInstanceOf(Response); }); test('quota diagnostics remain distinguishable from arbitrary database failures; policy is strict and bounded', () => { expect( researchAgentDatabaseError({ code: 'P0001', message: 'research_budget:capacity' })?.status ).toBe(429); expect( researchAgentDatabaseError({ code: 'P0001', message: 'research_access:denied' })?.status ).toBe(403); expect(researchAgentDatabaseError(new Error('database unavailable'))).toBeNull(); expect( researchAgentDatabaseError({ code: '23514', message: 'research_budget:spoof' }) ).toBeNull(); expect( createResearchAgentSchema.parse({ name: 'Agent', allowedProjectIds: [], allowedBacktestIds: [], limits, }).limits ).toEqual(limits); for (const bad of [ { ...limits, maxAttempts: 4 }, { ...limits, maxActiveTrials: 0 }, { ...limits, maxAttemptWallMs: 2147483648 }, ]) { expect( createResearchAgentSchema.safeParse({ name: 'Agent', allowedProjectIds: [], allowedBacktestIds: [], limits: bad, }).success ).toBe(false); } expect( createResearchAgentSchema.safeParse({ name: 'Agent', allowedProjectIds: [], allowedBacktestIds: [], limits, ownerPrincipal: 'operator', }).success ).toBe(false); });