diff --git a/apps/stock/web-api/src/routes/research.routes.ts b/apps/stock/web-api/src/routes/research.routes.ts index f5f465b6..dfb05b96 100644 --- a/apps/stock/web-api/src/routes/research.routes.ts +++ b/apps/stock/web-api/src/routes/research.routes.ts @@ -166,7 +166,8 @@ export function createResearchRoutes( c.json({ artifacts: await service.listArtifacts( c.req.param('id'), - includeArchived(c.req.query('includeArchived')) + includeArchived(c.req.query('includeArchived')), + agentScope(c.req.raw) ), }) ); @@ -183,10 +184,12 @@ export function createResearchRoutes( ) ); app.get('/api/v2/analysis-artifacts/:id', async c => - c.json({ artifact: await service.getArtifact(c.req.param('id')) }) + c.json({ artifact: await service.getArtifact(c.req.param('id'), agentScope(c.req.raw)) }) ); app.get('/api/v2/analysis-artifacts/:id/revisions', async c => - c.json({ revisions: await service.listArtifactRevisions(c.req.param('id')) }) + c.json({ + revisions: await service.listArtifactRevisions(c.req.param('id'), agentScope(c.req.raw)), + }) ); app.post('/api/v2/analysis-artifacts/:id/revisions', async c => c.json( diff --git a/apps/stock/web-api/src/services/research.service.ts b/apps/stock/web-api/src/services/research.service.ts index a740189f..d78d875a 100644 --- a/apps/stock/web-api/src/services/research.service.ts +++ b/apps/stock/web-api/src/services/research.service.ts @@ -14,21 +14,22 @@ import { reviseResearchHypothesisSchema, updateResearchProjectSchema, } from '@stock-bot/stock-config/research'; -import type { - ResearchActor, - ResearchArtifact, - ResearchArtifactRevision, - ResearchAuthorship, - ResearchContentOrigin, - ResearchEvidence, - ResearchEvidenceReference, - ResearchFindingSource, - ResearchHypothesis, - ResearchHypothesisRevision, - ResearchProject, - StrategyRecord, +import { + isResearchAgent, + type ResearchActor, + type ResearchArtifact, + type ResearchArtifactRevision, + type ResearchAuthorship, + type ResearchContentOrigin, + type ResearchEvidence, + type ResearchEvidenceReference, + type ResearchFindingSource, + type ResearchHypothesis, + type ResearchHypothesisRevision, + type ResearchProject, + type StrategyRecord, } from '@stock-bot/types'; -import { lockResearchAgent } from './research-agent-budget'; +import { lockResearchAgent, ResearchAgentError } from './research-agent-budget'; import { ResearchError } from './research-errors'; import type { ResearchEvidenceResolver } from './research-evidence'; import type { StrategyCatalogService } from './strategy-catalog.service'; @@ -382,18 +383,38 @@ export class ResearchService { }); } - async listArtifacts(projectId: string, includeArchived = false): Promise { + async listArtifacts( + projectId: string, + includeArchived = false, + agentId?: string + ): Promise { researchIdSchema.parse(projectId); return this.database.transaction(async client => { await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); await this.projectRow(client, projectId); const rows = ( - await client.query( - 'SELECT * FROM analysis_artifacts WHERE project_id=$1 AND ($2::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id', - [projectId, includeArchived] - ) + agentId !== undefined + ? await client.query( + `SELECT a.* FROM analysis_artifacts a + WHERE a.project_id=$1 + AND ($2::boolean OR a.archived_at IS NULL) + AND NOT EXISTS ( + SELECT 1 + FROM analysis_artifact_revisions rev + JOIN analysis_evidence ev ON ev.revision_id = rev.id + LEFT JOIN runs r ON r.id = ev.run_id + WHERE rev.artifact_id = a.id + AND r.research_agent_id IS DISTINCT FROM $3 + ) + ORDER BY a.created_at DESC, a.id`, + [projectId, includeArchived, agentId] + ) + : await client.query( + 'SELECT * FROM analysis_artifacts WHERE project_id=$1 AND ($2::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id', + [projectId, includeArchived] + ) ).rows; - return Promise.all(rows.map(row => this.artifact(client, row))); + return Promise.all(rows.map(row => this.artifact(client, row, undefined, agentId))); }); } async createArtifact( @@ -440,14 +461,14 @@ export class ResearchService { return this.artifact(client, row, revision); }); } - async getArtifact(id: string): Promise { + async getArtifact(id: string, agentId?: string): Promise { researchIdSchema.parse(id); return this.database.transaction(async client => { await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); - return this.artifact(client, await this.artifactRow(client, id)); + return this.artifact(client, await this.artifactRow(client, id), undefined, agentId); }); } - async listArtifactRevisions(id: string): Promise { + async listArtifactRevisions(id: string, agentId?: string): Promise { researchIdSchema.parse(id); return this.database.transaction(async client => { await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); @@ -458,7 +479,7 @@ export class ResearchService { [id] ) ).rows; - return Promise.all(rows.map(row => this.artifactRevision(client, row))); + return Promise.all(rows.map(row => this.artifactRevision(client, row, agentId))); }); } async reviseArtifact( @@ -621,7 +642,8 @@ export class ResearchService { private async artifact( database: Database, row: QueryResultRow, - resolved?: ResearchArtifactRevision + resolved?: ResearchArtifactRevision, + agentId?: string ): Promise { const latest = resolved ?? @@ -635,7 +657,8 @@ export class ResearchService { ) ).rows[0], 'Artifact revision' - ) + ), + agentId )); return { id: row.id, @@ -650,9 +673,35 @@ export class ResearchService { latestRevision: latest, }; } + private async assertAgentOwnsEvidenceRuns( + database: Database, + references: ResearchEvidenceReference[], + agentId: string + ): Promise { + const uniqueRunIds = [...new Set(references.map(ref => ref.runId))]; + if (uniqueRunIds.length === 0) { + return; + } + const rows = ( + await database.query<{ id: string; research_agent_id: string | null }>( + 'SELECT id, research_agent_id FROM runs WHERE id = ANY($1::uuid[])', + [uniqueRunIds] + ) + ).rows; + if ( + rows.length !== uniqueRunIds.length || + rows.some(item => item.research_agent_id !== agentId) + ) { + throw new ResearchAgentError( + 403, + 'Research credential does not permit accessing foreign run evidence' + ); + } + } private async artifactRevision( database: Database, - row: QueryResultRow + row: QueryResultRow, + agentId?: string ): Promise { const references: ResearchEvidenceReference[] = ( await database.query( @@ -665,6 +714,9 @@ export class ResearchService { metricPath: item.metric_path, strategyVersionId: item.strategy_version_id, })); + if (agentId !== undefined && references.length > 0) { + await this.assertAgentOwnsEvidenceRuns(database, references, agentId); + } const source = findingSource(row.source); let evidence; try { @@ -699,6 +751,9 @@ export class ResearchService { ...reference, strategyVersionId: reference.strategyVersionId ?? null, })); + if (isResearchAgent(author.submittedBy) && references.length > 0) { + await this.assertAgentOwnsEvidenceRuns(client, references, author.submittedBy); + } const evidence = await this.evidence.resolveAll(references, data.source, client); const revisionId = randomUUID(); const row = required( diff --git a/test/integration/research-agents-api.test.ts b/test/integration/research-agents-api.test.ts index abbfcff5..6c6cd5a5 100644 --- a/test/integration/research-agents-api.test.ts +++ b/test/integration/research-agents-api.test.ts @@ -8,9 +8,11 @@ import { } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/services'; import { createResearchAgentSchema } from '@stock-bot/stock-config/research-agents'; +import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; 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'; +import { ResearchService } from '../../apps/stock/web-api/src/services/research.service'; const agent = `agent:${randomUUID()}` as const; const token = 'sb-research.fixture-token'; @@ -416,3 +418,131 @@ test('quota diagnostics remain distinguishable from arbitrary database failures; }).success ).toBe(false); }); + +test('artifact reads check run ownership before resolving evidence for research agents while preserving operator access', async () => { + const projectId = randomUUID(), + artifactId = randomUUID(), + revisionId = randomUUID(), + foreignRunId = randomUUID(), + now = new Date().toISOString(); + + const resolveAll = mock(async () => [ + { + runId: foreignRunId, + backtestId: randomUUID(), + metricsVersion: 'canonical-analytics/v1' as const, + metricPath: 'analytics.metrics.sharpeRatio' as const, + strategyVersionId: null, + value: 2.45, + unit: 'ratio' as const, + availability: 'available' as const, + unavailableReason: null, + resultKind: 'canonical' as const, + financialEngine: 'rust' as const, + datasetHash: 'b'.repeat(64), + limitations: [], + }, + ]); + + const artifactRow = { + id: artifactId, + project_id: projectId, + hypothesis_revision_id: null, + kind: 'finding', + owner_principal: 'operator', + updated_by: 'operator', + archived_at: null, + created_at: now, + updated_at: now, + }; + const revisionRow = { + id: revisionId, + artifact_id: artifactId, + ordinal: 1, + title: 'Holdout finding', + body: 'Operator holdout sharpe', + submitted_by: 'operator', + content_origin: 'human', + source: null, + created_at: now, + }; + + const clientQuery = mock(async (sql: string, values?: unknown[]) => { + if (sql.startsWith('SET TRANSACTION')) return { rows: [] }; + if (sql.includes('FROM research_projects WHERE id=$1')) return { rows: [{ id: projectId }] }; + if (sql.includes('FROM analysis_artifacts WHERE id=$1')) return { rows: [artifactRow] }; + if (sql.includes('FROM analysis_artifacts a') && sql.includes('NOT EXISTS')) { + expect(values).toEqual([projectId, false, agent]); + return { rows: [] }; + } + if (sql.includes('FROM analysis_artifacts WHERE project_id=$1')) return { rows: [artifactRow] }; + if (sql.includes('FROM analysis_artifact_revisions WHERE artifact_id=$1')) { + return { rows: [revisionRow] }; + } + if (sql.includes('FROM analysis_evidence WHERE revision_id=$1')) { + return { + rows: [ + { + run_id: foreignRunId, + metrics_version: 'canonical-analytics/v1', + metric_path: 'analytics.metrics.sharpeRatio', + strategy_version_id: null, + }, + ], + }; + } + if (sql.includes('SELECT id, research_agent_id FROM runs WHERE id = ANY($1::uuid[])')) { + return { rows: [{ id: foreignRunId, research_agent_id: null }] }; + } + throw new Error(`Unexpected SQL: ${sql}`); + }); + + const container = { + postgres: { + query: clientQuery, + transaction: async (fn: (client: { query: typeof clientQuery }) => Promise) => + fn({ query: clientQuery }), + }, + logger: { error: mock(() => {}) }, + } as unknown as IServiceContainer; + + const service = new ResearchService(container, { + evidence: { resolveAll }, + catalog: { getStrategy: mock(async () => ({}) as never) }, + }); + const f = boundary(); + f.app.route('/', createResearchRoutes(container, service)); + + // Agent item and revision reads must fail closed with 403 before resolving evidence + for (const method of ['GET', 'HEAD'] as const) { + for (const path of [ + `/api/v2/analysis-artifacts/${artifactId}`, + `/api/v2/analysis-artifacts/${artifactId}/revisions`, + ]) { + const response = await f.app.request(path, { + method, + headers: { Authorization: `Bearer ${token}` }, + }); + expect(response.status).toBe(403); + expect(response.headers.get('cache-control')).toBe('no-store'); + } + } + // Agent project-list read omits artifacts referencing foreign runs without resolving evidence + const agentList = await f.app.request(`/api/v2/research-projects/${projectId}/analysis-artifacts`, { + headers: { Authorization: `Bearer ${token}` }, + }); + expect(agentList.status).toBe(200); + expect(await agentList.json()).toEqual({ artifacts: [] }); + expect(resolveAll).toHaveBeenCalledTimes(0); + + // Operator access remains intact and resolves evidence + const opItem = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}`, { + headers: { Authorization: `Bearer ${adminToken}` }, + }); + expect(opItem.status).toBe(200); + const opBody = (await opItem.json()) as { + artifact: { latestRevision: { evidence: { value: number }[] } }; + }; + expect(opBody.artifact.latestRevision.evidence[0]?.value).toBe(2.45); + expect(resolveAll).toHaveBeenCalledTimes(1); +}); diff --git a/test/postgres/research-agents.test.ts b/test/postgres/research-agents.test.ts index 0cb31b1d..0bb1f154 100644 --- a/test/postgres/research-agents.test.ts +++ b/test/postgres/research-agents.test.ts @@ -1222,4 +1222,169 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => { expect((await req('/api/v2/strategies/not-a-uuid', p.token)).status).toBe(403); expect((await req('/api/v2/strategy-versions/not-a-uuid', p.token)).status).toBe(403); }); + + test('granted project artifacts cannot leak foreign holdout run evidence to research agents while preserving operator access', async () => { + const f = await fixture(4), + p = await provision(f); + const security = createWebApiSecurity(f.container, { + adminToken: operatorToken, + serviceToken: 'service-test-secret-123456789012345678901', + environment: 'test', + }); + const app = createRoutes(f.container, security); + const req = ( + path: string, + token: string, + method: 'GET' | 'HEAD' | 'POST' = 'GET', + body?: unknown + ) => + app.request(path, { + method, + headers: { + Authorization: `Bearer ${token}`, + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + + // Execute an operator-owned holdout run and an agent-owned run on the shared template + const opExp = await f.experiments.submit( + await preparation(f, 'Operator holdout', f.draft.id, { fastPeriod: [2] }), + receipt('operator') + ); + const opRunId = required(opExp.trials[0]!.runId); + await f.execute(opRunId); + + const agentExp = await f.experiments.submit( + await preparation(f, 'Agent search', f.draft.id, { fastPeriod: [1] }), + receipt(p.agent.id) + ); + const agentRunId = required(agentExp.trials[0]!.runId); + await f.execute(agentRunId); + + // Operator attaches the holdout run's Sharpe ratio to a finding in the agent's granted project + const opFinding = await f.research.createArtifact( + p.project.id, + { + kind: 'finding', + title: 'Operator holdout finding', + body: 'Holdout Sharpe ratio from operator run', + evidence: [ + { + runId: opRunId, + metricsVersion: 'canonical-analytics/v1', + metricPath: 'analytics.metrics.sharpeRatio', + }, + ], + }, + 'operator' + ); + const agentFinding = await f.research.createArtifact( + p.project.id, + { + kind: 'finding', + title: 'Agent finding', + body: 'Sharpe ratio from agent-owned run', + evidence: [ + { + runId: agentRunId, + metricsVersion: 'canonical-analytics/v1', + metricPath: 'analytics.metrics.sharpeRatio', + }, + ], + }, + p.agent.id as `agent:${string}` + ); + const plainNote = await f.research.createArtifact( + p.project.id, + { kind: 'note', title: 'Shared note', body: 'No run evidence', evidence: [] }, + 'operator' + ); + + // Agent cannot read operator run results directly + expect((await req(`/api/v2/runs/${opRunId}/results`, p.token)).status).toBe(403); + + // Agent cannot read the operator finding or its revisions via GET or HEAD + for (const method of ['GET', 'HEAD'] as const) { + for (const path of [ + `/api/v2/analysis-artifacts/${opFinding.id}`, + `/api/v2/analysis-artifacts/${opFinding.id}/revisions`, + ]) { + const denied = await req(path, p.token, method); + expect(denied.status).toBe(403); + expect(denied.headers.get('cache-control')).toBe('no-store'); + if (method === 'GET') { + expect(await denied.text()).not.toContain(f.dataset.manifest.hash); + } + } + } + + // Agent project-list omits the operator holdout finding while keeping owned/non-evidence artifacts + const agentList = await req(`/api/v2/research-projects/${p.project.id}/analysis-artifacts`, p.token); + expect(agentList.status).toBe(200); + const agentArtifactIds = ( + (await agentList.json()) as { artifacts: { id: string }[] } + ).artifacts.map(a => a.id); + expect(agentArtifactIds).toContain(agentFinding.id); + expect(agentArtifactIds).toContain(plainNote.id); + expect(agentArtifactIds).not.toContain(opFinding.id); + + // Agent can still read its own finding and revisions + const ownItem = await req(`/api/v2/analysis-artifacts/${agentFinding.id}`, p.token); + expect(ownItem.status).toBe(200); + expect( + ( + (await ownItem.json()) as { + artifact: { latestRevision: { evidence: { runId: string }[] } }; + } + ).artifact.latestRevision.evidence[0]?.runId + ).toBe(agentRunId); + expect((await req(`/api/v2/analysis-artifacts/${agentFinding.id}/revisions`, p.token)).status).toBe( + 200 + ); + + // Agent cannot attach an operator-owned run as evidence when creating an artifact + const forged = await req( + `/api/v2/research-projects/${p.project.id}/analysis-artifacts`, + p.token, + 'POST', + { + kind: 'finding', + title: 'Attempted exfiltration', + body: 'Refers to operator run', + evidence: [ + { + runId: opRunId, + metricsVersion: 'canonical-analytics/v1', + metricPath: 'analytics.metrics.sharpeRatio', + }, + ], + } + ); + expect(forged.status).toBe(403); + + // Operator retains full read access to the holdout finding, its revisions, and the full list + const opItem = await req(`/api/v2/analysis-artifacts/${opFinding.id}`, operatorToken); + expect(opItem.status).toBe(200); + const opArtifact = ( + (await opItem.json()) as { + artifact: { latestRevision: { evidence: { runId: string; datasetHash: string }[] } }; + } + ).artifact; + expect(opArtifact.latestRevision.evidence[0]?.runId).toBe(opRunId); + expect(opArtifact.latestRevision.evidence[0]?.datasetHash).toBe(f.dataset.manifest.hash); + + expect( + (await req(`/api/v2/analysis-artifacts/${opFinding.id}/revisions`, operatorToken)).status + ).toBe(200); + + const opList = await req( + `/api/v2/research-projects/${p.project.id}/analysis-artifacts`, + operatorToken + ); + expect(opList.status).toBe(200); + expect( + ((await opList.json()) as { artifacts: { id: string }[] }).artifacts.map(a => a.id) + ).toEqual(expect.arrayContaining([opFinding.id, agentFinding.id, plainNote.id])); + }); });