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 denies all dataset operations including canonical dataset exports', async () => { const query = mock(async () => ({ rows: [{ id: agent, enabled: true, policy: {} }] })); const service = new ResearchAgentsService({ postgres: { query }, } as unknown as IServiceContainer); const hash = 'a'.repeat(64); const check = (path: string, method = 'GET') => service.authenticate( new Request(`http://localhost${path}`, { method, headers: { Authorization: `Bearer ${token}` }, }) ); for (const [path, method] of [ [`/api/v2/datasets/canonical/${hash}/export`, 'GET'], [`/api/v2/datasets/canonical/${hash}/export`, 'HEAD'], ['/api/v2/datasets/canonical', 'GET'], [`/api/v2/datasets/canonical/${hash}`, 'GET'], [`/api/v2/datasets/canonical/${hash}/export/extra`, 'GET'], [`/api/v2/datasets/canonical/${hash.toUpperCase()}/export`, 'GET'], ['/api/v2/datasets/canonical/invalid/export', 'GET'], ['/api/v2/datasets/stored-eod/coverage', 'GET'], ['/api/v2/datasets/canonical/preview', 'POST'], ['/api/v2/datasets/canonical/retain', 'POST'], ['/api/v2/datasets/canonical/stored-source', 'POST'], ['/api/v2/datasets/stored-eod/inspect', 'POST'], [`/api/v2/datasets/canonical/${hash}/export`, 'POST'], ]) { const response = (await check(path!, method)) as Response; expect(response).toBeInstanceOf(Response); expect(response.status).toBe(403); expect(response.headers.get('cache-control')).toBe('no-store'); } }); 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')) as Response).status).toBe( 403 ); expect(await check('/api/v2/research-agents', 'GET')).toBeInstanceOf(Response); }); test('resolver scopes GET and HEAD reads to granted projects, templates and owned resources', async () => { const grantedProject = randomUUID(), ungrantedProject = randomUUID(), grantedBacktest = randomUUID(), ungrantedBacktest = randomUUID(), grantedHypothesis = randomUUID(), ungrantedHypothesis = randomUUID(), missingHypothesis = randomUUID(), grantedArtifact = randomUUID(), ungrantedArtifact = randomUUID(), ownedExperiment = randomUUID(), ownedExperiment2 = randomUUID(), foreignExperiment = randomUUID(), ownedWalkForward = randomUUID(), foreignWalkForward = randomUUID(), ownedRun = randomUUID(), foreignRun = randomUUID(), permittedStrategy = randomUUID(), unpermittedStrategy = randomUUID(), permittedVersion = randomUUID(), unpermittedVersion = randomUUID(); const query = mock(async (sql: string, values?: unknown[]) => { if (sql.includes('FROM research_agents WHERE token_hash=')) { return { rows: [ { id: agent, enabled: true, policy: { allowedProjectIds: [grantedProject], grants: [{ backtestId: grantedBacktest }], }, }, ], }; } if (sql.startsWith('SELECT project_id FROM research_hypotheses')) { if (values?.[0] === grantedHypothesis) return { rows: [{ project_id: grantedProject }] }; if (values?.[0] === ungrantedHypothesis) return { rows: [{ project_id: ungrantedProject }] }; return { rows: [] }; } if (sql.startsWith('SELECT project_id FROM analysis_artifacts')) { if (values?.[0] === grantedArtifact) return { rows: [{ project_id: grantedProject }] }; if (values?.[0] === ungrantedArtifact) return { rows: [{ project_id: ungrantedProject }] }; return { rows: [] }; } if (sql.startsWith('SELECT id,submission_principal FROM research_experiments')) { const ids = (values?.[0] as string[]) ?? []; return { rows: ids .filter(id => [ownedExperiment, ownedExperiment2, foreignExperiment].includes(id)) .map(id => ({ id, submission_principal: id === foreignExperiment ? 'operator' : agent, })), }; } if (sql.startsWith('SELECT submission_principal FROM research_experiments')) { if (values?.[0] === ownedExperiment) return { rows: [{ submission_principal: agent }] }; if (values?.[0] === foreignExperiment) return { rows: [{ submission_principal: 'operator' }] }; return { rows: [] }; } if (sql.startsWith('SELECT submission_principal FROM research_walk_forwards')) { if (values?.[0] === ownedWalkForward) return { rows: [{ submission_principal: agent }] }; if (values?.[0] === foreignWalkForward) return { rows: [{ submission_principal: 'operator' }] }; return { rows: [] }; } if (sql.startsWith('SELECT research_agent_id FROM runs')) { if (values?.[0] === ownedRun) return { rows: [{ research_agent_id: agent }] }; if (values?.[0] === foreignRun) return { rows: [{ research_agent_id: null }] }; return { rows: [] }; } if (sql.includes('FROM strategies s')) { return { rows: values?.[0] === permittedStrategy ? [{ '?column?': 1 }] : [] }; } if (sql.includes('FROM strategy_versions sv')) { return { rows: values?.[0] === permittedVersion ? [{ '?column?': 1 }] : [] }; } throw new Error(`Unexpected SQL: ${sql}`); }); const service = new ResearchAgentsService({ postgres: { query }, } as unknown as IServiceContainer); const check = (path: string, method: 'GET' | 'HEAD' = 'GET') => service.authenticate( new Request(`http://localhost${path}`, { method, headers: { Authorization: `Bearer ${token}` }, }) ); for (const method of ['GET', 'HEAD'] as const) { for (const allowedPath of [ '/api/v2/research-projects', `/api/v2/research-projects/${grantedProject}`, `/api/v2/research-projects/${grantedProject}/strategies`, `/api/v2/research-projects/${grantedProject}/hypotheses`, `/api/v2/research-projects/${grantedProject}/analysis-artifacts`, `/api/v2/hypotheses/${grantedHypothesis}`, `/api/v2/hypotheses/${grantedHypothesis}/revisions`, `/api/v2/analysis-artifacts/${grantedArtifact}`, `/api/v2/analysis-artifacts/${grantedArtifact}/revisions`, '/api/v2/backtests', `/api/v2/backtests/${grantedBacktest}`, `/api/v2/backtests/${grantedBacktest}/canonical-capability`, `/api/v2/backtests/${grantedBacktest}/runs`, '/api/v2/experiments', `/api/v2/experiments?backtestId=${grantedBacktest}`, '/api/v2/experiments/validation', `/api/v2/experiments/validation?backtestId=${grantedBacktest}`, '/api/v2/experiments/walk-forward', `/api/v2/experiments/walk-forward?backtestId=${grantedBacktest}`, `/api/v2/experiments/${ownedExperiment}`, `/api/v2/experiments/${ownedExperiment}/trials/${ownedRun}/retries`, `/api/v2/experiments/validation/${ownedExperiment}`, `/api/v2/experiments/walk-forward/${ownedWalkForward}`, `/api/v2/experiments/compare?leftId=${ownedExperiment}&rightId=${ownedExperiment2}`, `/api/v2/runs/${ownedRun}`, `/api/v2/runs/${ownedRun}/results`, '/api/v2/strategies', `/api/v2/strategies/${permittedStrategy}`, `/api/v2/strategies/${permittedStrategy}/versions`, `/api/v2/strategy-versions/${permittedVersion}`, `/api/v2/strategy-versions/${permittedVersion}/artifact`, ]) { expect(await check(allowedPath, method)).toEqual({ principal: agent }); } for (const deniedPath of [ `/api/v2/research-projects/${ungrantedProject}`, `/api/v2/research-projects/${ungrantedProject}/strategies`, `/api/v2/research-projects/${ungrantedProject}/hypotheses`, `/api/v2/research-projects/${ungrantedProject}/analysis-artifacts`, '/api/v2/research-projects/not-a-uuid', `/api/v2/hypotheses/${ungrantedHypothesis}`, `/api/v2/hypotheses/${ungrantedHypothesis}/revisions`, `/api/v2/hypotheses/${missingHypothesis}`, '/api/v2/hypotheses/not-a-uuid', `/api/v2/analysis-artifacts/${ungrantedArtifact}`, `/api/v2/analysis-artifacts/${ungrantedArtifact}/revisions`, '/api/v2/analysis-artifacts/not-a-uuid', `/api/v2/backtests/${ungrantedBacktest}`, `/api/v2/backtests/${ungrantedBacktest}/canonical-capability`, `/api/v2/backtests/${ungrantedBacktest}/runs`, '/api/v2/backtests/not-a-uuid', `/api/v2/experiments?backtestId=${ungrantedBacktest}`, `/api/v2/experiments/validation?backtestId=${ungrantedBacktest}`, `/api/v2/experiments/walk-forward?backtestId=${ungrantedBacktest}`, `/api/v2/experiments/${foreignExperiment}`, `/api/v2/experiments/${foreignExperiment}/trials/${foreignRun}/retries`, `/api/v2/experiments/validation/${foreignExperiment}`, `/api/v2/experiments/walk-forward/${foreignWalkForward}`, '/api/v2/experiments/not-a-uuid', '/api/v2/experiments/validation/not-a-uuid', '/api/v2/experiments/walk-forward/not-a-uuid', `/api/v2/experiments/compare?leftId=${ownedExperiment}&rightId=${foreignExperiment}`, `/api/v2/experiments/compare?leftId=${ownedExperiment}`, `/api/v2/experiments/compare?leftId=${ownedExperiment}&leftId=${ownedExperiment2}&rightId=${ownedExperiment2}`, '/api/v2/experiments/compare?leftId=not-a-uuid&rightId=not-a-uuid', `/api/v2/runs/${foreignRun}`, `/api/v2/runs/${foreignRun}/results`, '/api/v2/runs/not-a-uuid', `/api/v2/strategies/${unpermittedStrategy}`, `/api/v2/strategies/${unpermittedStrategy}/versions`, '/api/v2/strategies/not-a-uuid', `/api/v2/strategy-versions/${unpermittedVersion}`, `/api/v2/strategy-versions/${unpermittedVersion}/artifact`, '/api/v2/strategy-versions/not-a-uuid', ]) { const response = (await check(deniedPath, method)) as Response; expect(response).toBeInstanceOf(Response); expect(response.status).toBe(403); } } }); 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); });