T-4: M0.4b — Close sb-research.* holdout leak: 403 on dataset /export and ungranted project GETs

This commit is contained in:
Studio 2026-11-27 01:16:52 -05:00
parent 13eb8352f3
commit 420e77f837
17 changed files with 788 additions and 1123 deletions

View file

@ -1,12 +1,17 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { getCredentialHttpPrincipal, getVerifiedHttpPrincipal } from '@stock-bot/di';
import {
getCredentialHttpPrincipal,
getResearchHttpPrincipal,
getVerifiedHttpPrincipal,
} from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import {
isBacktestRequestError,
rejectCatalogVersionReferences,
} from '@stock-bot/stock-config/backtest';
import { isResearchAgent } from '@stock-bot/types';
import {
BacktestRetentionError,
BacktestServiceV2,
@ -21,6 +26,10 @@ const logger = getLogger('backtests-v2-routes');
export function createBacktestV2Routes(container: IServiceContainer) {
const app = new Hono();
const backtestService = new BacktestServiceV2(container);
const agentScope = (request: Request) => {
const principal = getResearchHttpPrincipal(request);
return principal && isResearchAgent(principal) ? principal : undefined;
};
// Backtest endpoints
app.get('/api/v2/backtests', async c => {
@ -31,10 +40,12 @@ export function createBacktestV2Routes(container: IServiceContainer) {
if (archiveQuery !== undefined && archiveQuery !== 'true' && archiveQuery !== 'false') {
return c.json({ error: 'includeArchived must be true or false' }, 400);
}
const agentId = agentScope(c.req.raw);
const backtests = await backtestService.listBacktests({
limit,
offset,
includeArchived: archiveQuery === 'true',
...(agentId ? { agentId } : {}),
});
return c.json(backtests);
} catch (error) {
@ -138,7 +149,10 @@ export function createBacktestV2Routes(container: IServiceContainer) {
// Run endpoints
app.get('/api/v2/backtests/:backtestId/runs', async c => {
try {
const runs = await backtestService.listRuns(c.req.param('backtestId'));
const runs = await backtestService.listRuns(
c.req.param('backtestId'),
agentScope(c.req.raw)
);
return c.json(runs);
} catch (error) {
logger.error('Failed to list runs', error);

View file

@ -3,6 +3,7 @@ import { z } from 'zod';
import { getResearchHttpPrincipal } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/services';
import { isResearchAgent } from '@stock-bot/types';
import {
parseCostSensitivityInput,
parseCostSensitivitySubmission,
@ -68,6 +69,10 @@ export function createExperimentRoutes(
logger.error('Experiment operation failed', error);
return c.json({ error: 'Experiment operation unavailable' }, 500);
});
const agentScope = (request: Request) => {
const principal = getResearchHttpPrincipal(request);
return principal && isResearchAgent(principal) ? principal : undefined;
};
const body = async (request: Request): Promise<unknown> => {
try {
return await request.json();
@ -116,7 +121,9 @@ export function createExperimentRoutes(
return c.json({ walkForward }, 202);
});
app.get('/api/v2/experiments/walk-forward', async c =>
c.json({ walkForwards: await walkForwards.list(c.req.query('backtestId')) })
c.json({
walkForwards: await walkForwards.list(c.req.query('backtestId'), agentScope(c.req.raw)),
})
);
app.get('/api/v2/experiments/walk-forward/:id', async c =>
c.json({ walkForward: await walkForwards.get(experimentId(c.req.param('id'))) })
@ -167,7 +174,9 @@ export function createExperimentRoutes(
return c.json({ validation }, 202);
});
app.get('/api/v2/experiments/validation', async c =>
c.json({ validations: await validations.list(c.req.query('backtestId')) })
c.json({
validations: await validations.list(c.req.query('backtestId'), agentScope(c.req.raw)),
})
);
app.get('/api/v2/experiments/validation/:id', async c =>
c.json({ validation: await validations.get(experimentId(c.req.param('id'))) })
@ -235,7 +244,7 @@ export function createExperimentRoutes(
if (filter !== undefined) {
experimentId(filter);
}
return c.json({ experiments: await service.list(filter) });
return c.json({ experiments: await service.list(filter, agentScope(c.req.raw)) });
});
app.get('/api/v2/experiments/compare', async c => {
const params = new URL(c.req.url).searchParams;

View file

@ -3,6 +3,7 @@ import { z } from 'zod';
import { getResearchHttpPrincipal } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { archiveResearchSchema, parseResearchInput } from '@stock-bot/stock-config/research';
import { isResearchAgent } from '@stock-bot/types';
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
import { ResearchError } from '../services/research-errors';
import { createResearchServices } from '../services/research-services';
@ -75,9 +76,17 @@ export function createResearchRoutes(
return principal;
};
const agentScope = (request: Request) => {
const principal = getResearchHttpPrincipal(request);
return principal && isResearchAgent(principal) ? principal : undefined;
};
app.get('/api/v2/research-projects', async c =>
c.json({
projects: await service.listProjects(includeArchived(c.req.query('includeArchived'))),
projects: await service.listProjects(
includeArchived(c.req.query('includeArchived')),
agentScope(c.req.raw)
),
})
);
app.post('/api/v2/research-projects', async c =>

View file

@ -2,6 +2,7 @@ import { Hono, type MiddlewareHandler } from 'hono';
import { z } from 'zod';
import { getResearchHttpPrincipal } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { isResearchAgent } from '@stock-bot/types';
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
import { StrategyCatalogError, StrategyCatalogService } from '../services/strategy-catalog.service';
@ -61,7 +62,13 @@ export function createStrategyRoutes(
}
return value;
};
app.get('/api/v2/strategies', async c => c.json({ strategies: await service.listStrategies() }));
const agentScope = (request: Request) => {
const principal = getResearchHttpPrincipal(request);
return principal && isResearchAgent(principal) ? principal : undefined;
};
app.get('/api/v2/strategies', async c =>
c.json({ strategies: await service.listStrategies(agentScope(c.req.raw)) })
);
app.post('/api/v2/strategies', async c =>
c.json({ strategy: await service.createStrategy(await c.req.json(), actor(c.req.raw)) }, 201)
);

View file

@ -142,13 +142,21 @@ export class BacktestRuns {
return mapRun(at(result.rows, 0));
}
async listRuns(backtestId: string): Promise<Run[]> {
const result = await this.container.postgres.query(
`SELECT * FROM runs
WHERE backtest_id = $1
ORDER BY run_number DESC`,
[backtestId]
);
async listRuns(backtestId: string, agentId?: string): Promise<Run[]> {
const result =
agentId !== undefined
? await this.container.postgres.query(
`SELECT * FROM runs
WHERE backtest_id = $1 AND research_agent_id = $2
ORDER BY run_number DESC`,
[backtestId, agentId]
)
: await this.container.postgres.query(
`SELECT * FROM runs
WHERE backtest_id = $1
ORDER BY run_number DESC`,
[backtestId]
);
return result.rows.map(row => mapRun(row));
}

View file

@ -191,7 +191,23 @@ export class BacktestTemplates {
limit: number;
offset: number;
includeArchived?: boolean;
agentId?: string;
}): Promise<Backtest[]> {
if (params.agentId !== undefined) {
const result = await this.container.postgres.query(
`SELECT b.* FROM backtests b
JOIN research_agents a ON a.id = $4
WHERE ($3::boolean OR b.archived_at IS NULL)
AND EXISTS (
SELECT 1 FROM jsonb_array_elements(a.policy->'grants') g
WHERE g->>'backtestId' = b.id::text
)
ORDER BY b.created_at DESC
LIMIT $1 OFFSET $2`,
[params.limit, params.offset, params.includeArchived === true, params.agentId]
);
return result.rows.map(row => mapBacktest(row));
}
const result = await this.container.postgres.query(
`SELECT * FROM backtests
WHERE ($3::boolean OR archived_at IS NULL)

View file

@ -198,13 +198,23 @@ export class ChronologicalValidationService {
await this.insertRuns(client, identity.id, train);
return true;
}
async list(backtestId?: string): Promise<ChronologicalValidationSummary[]> {
async list(backtestId?: string, agentId?: string): Promise<ChronologicalValidationSummary[]> {
if (backtestId !== undefined) {
experimentId(backtestId);
}
const conditions = ["validation_phase='train'"];
const values: unknown[] = [];
if (backtestId !== undefined) {
values.push(backtestId);
conditions.push(`backtest_id=$${values.length}`);
}
if (agentId !== undefined) {
values.push(agentId);
conditions.push(`submission_principal=$${values.length}`);
}
const rows = await this.database.query(
`SELECT * FROM research_experiments WHERE validation_phase='train' ${backtestId === undefined ? '' : 'AND backtest_id=$1'} ORDER BY created_at DESC,id DESC`,
backtestId === undefined ? [] : [backtestId]
`SELECT * FROM research_experiments WHERE ${conditions.join(' AND ')} ORDER BY created_at DESC,id DESC`,
values
);
return rows.rows.map(row => {
retainedValidationPreview(row.validation_manifest);

View file

@ -333,14 +333,24 @@ export class ExperimentsService {
return this.readDetail(client, experimentId);
});
}
async list(backtestId?: string): Promise<ExperimentSummary[]> {
async list(backtestId?: string, agentId?: string): Promise<ExperimentSummary[]> {
if (backtestId !== undefined) {
experimentId(backtestId);
}
const conditions = ['e.validation_phase IS NULL'];
const values: unknown[] = [];
if (backtestId !== undefined) {
values.push(backtestId);
conditions.push(`e.backtest_id=$${values.length}`);
}
if (agentId !== undefined) {
values.push(agentId);
conditions.push(`e.submission_principal=$${values.length}`);
}
const rows = await this.database.query(
`SELECT ${summaryColumns} FROM research_experiments e
WHERE e.validation_phase IS NULL ${backtestId === undefined ? '' : 'AND e.backtest_id=$1'} ORDER BY e.created_at DESC,e.id DESC`,
backtestId === undefined ? [] : [backtestId]
WHERE ${conditions.join(' AND ')} ORDER BY e.created_at DESC,e.id DESC`,
values
);
return rows.rows.map(summary);
}

View file

@ -39,7 +39,8 @@ function record(row: QueryResultRow): ResearchAgentRecord {
updatedAt: new Date(row.updated_at).toISOString(),
};
}
const uuid = '[0-9a-fA-F-]{36}';
const uuid = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
const strictUuid = new RegExp(`^${uuid}$`);
function permitted(request: Request): boolean {
const path = new URL(request.url).pathname,
method = request.method;
@ -47,9 +48,7 @@ function permitted(request: Request): boolean {
return (
/^\/api\/v2\/(research-projects|hypotheses|analysis-artifacts|strategies|strategy-versions|experiments|backtests|runs)(\/|$)/.test(
path
) ||
/^\/api\/v2\/datasets\/canonical\/[a-f0-9]{64}\/export$/.test(path) ||
path === '/api/v2/research-agent/budget'
) || path === '/api/v2/research-agent/budget'
);
}
if (method === 'PUT') {
@ -311,12 +310,156 @@ export class ResearchAgentsService {
if (!permitted(request)) {
return deny();
}
if (!['GET', 'HEAD'].includes(request.method)) {
const path = new URL(request.url).pathname;
const project = new RegExp(`^/api/v2/research-projects/(${uuid})/`).exec(path);
if (project && !row.policy.allowedProjectIds.includes(project[1]?.toLowerCase())) {
const allowedProjectIds = Array.isArray(row.policy?.allowedProjectIds)
? row.policy.allowedProjectIds
.filter((id: unknown): id is string => typeof id === 'string')
.map((id: string) => id.toLowerCase())
: [];
const grantedBacktestIds = Array.isArray(row.policy?.grants)
? row.policy.grants
.map((grant: unknown) =>
grant && typeof grant === 'object' && 'backtestId' in grant
? (grant as { backtestId?: unknown }).backtestId
: undefined
)
.filter((id: unknown): id is string => typeof id === 'string')
.map((id: string) => id.toLowerCase())
: [];
const url = new URL(request.url);
const path = url.pathname;
const project = /^\/api\/v2\/research-projects\/([^/]+)(?:\/|$)/.exec(path);
if (project && !allowedProjectIds.includes(project[1]!.toLowerCase())) {
return deny();
}
if (request.method === 'GET' || request.method === 'HEAD') {
const narrative = /^\/api\/v2\/(hypotheses|analysis-artifacts)\/([^/]+)(?:\/|$)/.exec(path);
if (narrative) {
const narrativeId = narrative[2]!;
if (!strictUuid.test(narrativeId)) {
return deny();
}
const table = narrative[1] === 'hypotheses' ? 'research_hypotheses' : 'analysis_artifacts';
const owned = (
await this.database.query(`SELECT project_id FROM ${table} WHERE id=$1`, [narrativeId])
).rows[0];
if (!owned || !allowedProjectIds.includes(String(owned.project_id).toLowerCase())) {
return deny();
}
}
const backtest = /^\/api\/v2\/backtests\/([^/]+)(?:\/|$)/.exec(path);
if (backtest && !grantedBacktestIds.includes(backtest[1]!.toLowerCase())) {
return deny();
}
if (path === '/api/v2/experiments/compare') {
const leftIds = url.searchParams.getAll('leftId');
const rightIds = url.searchParams.getAll('rightId');
if (
leftIds.length !== 1 ||
rightIds.length !== 1 ||
!strictUuid.test(leftIds[0]!) ||
!strictUuid.test(rightIds[0]!)
) {
return deny();
}
const uniqueIds = [...new Set([leftIds[0]!.toLowerCase(), rightIds[0]!.toLowerCase()])];
const rows = (
await this.database.query(
'SELECT id,submission_principal FROM research_experiments WHERE id=ANY($1::uuid[])',
[uniqueIds]
)
).rows;
if (
rows.length !== uniqueIds.length ||
rows.some(item => item.submission_principal !== row.id)
) {
return deny();
}
} else if (
path === '/api/v2/experiments' ||
path === '/api/v2/experiments/validation' ||
path === '/api/v2/experiments/walk-forward'
) {
const backtestIds = url.searchParams.getAll('backtestId');
if (backtestIds.some(id => !grantedBacktestIds.includes(id.toLowerCase()))) {
return deny();
}
} else {
const experiment =
/^\/api\/v2\/experiments\/(walk-forward\/|validation\/)?([^/]+)(?:\/|$)/.exec(path);
if (experiment) {
const experimentId = experiment[2]!;
if (!strictUuid.test(experimentId)) {
return deny();
}
const table =
experiment[1] === 'walk-forward/' ? 'research_walk_forwards' : 'research_experiments';
const owned = (
await this.database.query(`SELECT submission_principal FROM ${table} WHERE id=$1`, [
experimentId,
])
).rows[0];
if (owned?.submission_principal !== row.id) {
return deny();
}
}
}
const run = /^\/api\/v2\/runs\/([^/]+)(?:\/|$)/.exec(path);
if (run) {
const runId = run[1]!;
if (!strictUuid.test(runId)) {
return deny();
}
const owned = (
await this.database.query('SELECT research_agent_id FROM runs WHERE id=$1', [runId])
).rows[0];
if (owned?.research_agent_id !== row.id) {
return deny();
}
}
const strategy = /^\/api\/v2\/strategies\/([^/]+)(?:\/|$)/.exec(path);
if (strategy) {
const strategyId = strategy[1]!;
if (!strictUuid.test(strategyId)) {
return deny();
}
const permittedStrategy = (
await this.database.query(
`SELECT 1 FROM strategies s
WHERE s.id=$1 AND (
s.owner_principal=$2
OR EXISTS(SELECT 1 FROM research_project_strategies rps WHERE rps.strategy_id=s.id AND rps.project_id=ANY($3::uuid[]))
OR EXISTS(SELECT 1 FROM strategy_versions sv JOIN backtests b ON b.strategy_version_id=sv.id WHERE sv.strategy_id=s.id AND b.id=ANY($4::uuid[]))
)`,
[strategyId, row.id, allowedProjectIds, grantedBacktestIds]
)
).rows[0];
if (!permittedStrategy) {
return deny();
}
}
const strategyVersion = /^\/api\/v2\/strategy-versions\/([^/]+)(?:\/|$)/.exec(path);
if (strategyVersion) {
const versionId = strategyVersion[1]!;
if (!strictUuid.test(versionId)) {
return deny();
}
const permittedVersion = (
await this.database.query(
`SELECT 1 FROM strategy_versions sv
JOIN strategies s ON s.id=sv.strategy_id
WHERE sv.id=$1 AND (
s.owner_principal=$2
OR EXISTS(SELECT 1 FROM research_project_strategies rps WHERE rps.strategy_id=s.id AND rps.project_id=ANY($3::uuid[]))
OR EXISTS(SELECT 1 FROM strategy_versions sv2 JOIN backtests b ON b.strategy_version_id=sv2.id WHERE sv2.strategy_id=s.id AND b.id=ANY($4::uuid[]))
)`,
[versionId, row.id, allowedProjectIds, grantedBacktestIds]
)
).rows[0];
if (!permittedVersion) {
return deny();
}
}
} else {
const experiment = new RegExp(
`^/api/v2/experiments/(walk-forward/|validation/)?(${uuid})/`
).exec(path);
@ -355,7 +498,7 @@ export class ResearchAgentsService {
).rows[0];
if (
owned?.owner_principal !== row.id ||
!row.policy.allowedProjectIds.includes(owned.project_id)
!allowedProjectIds.includes(String(owned.project_id).toLowerCase())
) {
return deny();
}

View file

@ -146,7 +146,19 @@ export class ResearchService {
this.catalog = collaborators.catalog;
}
async listProjects(includeArchived = false): Promise<ResearchProject[]> {
async listProjects(includeArchived = false, agentId?: string): Promise<ResearchProject[]> {
if (agentId !== undefined) {
return (
await this.database.query(
`SELECT p.* FROM research_projects p
JOIN research_agents a ON a.id = $2
WHERE ($1::boolean OR p.archived_at IS NULL)
AND (a.policy->'allowedProjectIds' ? p.id::text)
ORDER BY p.created_at DESC, p.id`,
[includeArchived, agentId]
)
).rows.map(project);
}
return (
await this.database.query(
'SELECT * FROM research_projects WHERE ($1::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id',

View file

@ -175,7 +175,31 @@ export class StrategyCatalogService {
return strategy(row);
});
}
async listStrategies(): Promise<StrategyRecord[]> {
async listStrategies(agentId?: string): Promise<StrategyRecord[]> {
if (agentId !== undefined) {
return (
await this.database.query(
`SELECT s.* FROM strategies s
JOIN research_agents a ON a.id = $1
WHERE s.owner_principal = $1
OR EXISTS (
SELECT 1 FROM research_project_strategies rps
WHERE rps.strategy_id = s.id AND (a.policy->'allowedProjectIds' ? rps.project_id::text)
)
OR EXISTS (
SELECT 1 FROM strategy_versions sv
JOIN backtests b ON b.strategy_version_id = sv.id
WHERE sv.strategy_id = s.id
AND EXISTS (
SELECT 1 FROM jsonb_array_elements(a.policy->'grants') g
WHERE g->>'backtestId' = b.id::text
)
)
ORDER BY s.created_at DESC, s.id`,
[agentId]
)
).rows.map(strategy);
}
return (
await this.database.query('SELECT * FROM strategies ORDER BY created_at DESC,id')
).rows.map(strategy);

View file

@ -191,14 +191,25 @@ export class WalkForwardService {
return this.readDetail(client, id);
});
}
async list(backtestId?: string): Promise<WalkForwardSummary[]> {
async list(backtestId?: string, agentId?: string): Promise<WalkForwardSummary[]> {
if (backtestId !== undefined) {
experimentId(backtestId);
}
const conditions: string[] = [];
const values: unknown[] = [];
if (backtestId !== undefined) {
values.push(backtestId);
conditions.push(`w.backtest_id=$${values.length}`);
}
if (agentId !== undefined) {
values.push(agentId);
conditions.push(`w.submission_principal=$${values.length}`);
}
const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
const rows = await this.database.query(
`SELECT w.*,(SELECT count(*)::int FROM research_experiments e WHERE e.walk_forward_id=w.id AND e.validation_report IS NOT NULL) AS reported
FROM research_walk_forwards w ${backtestId === undefined ? '' : 'WHERE w.backtest_id=$1'} ORDER BY w.created_at DESC,w.id DESC`,
backtestId === undefined ? [] : [backtestId]
FROM research_walk_forwards w ${where} ORDER BY w.created_at DESC,w.id DESC`,
values
);
return rows.rows.map(row => {
checkedHeader(row);

1116
bun.lock

File diff suppressed because it is too large Load diff

View file

@ -282,14 +282,16 @@ describe('validated canonical dataset export', () => {
).rejects.toThrow('cancelled after query');
});
test('read, admin, service, browser and research credentials export; anonymous and revoked credentials do not', async () => {
test('read, admin, service and browser credentials export; research, anonymous and revoked credentials do not', async () => {
const f = fixture();
expect((await f.request(baseline.manifest.hash, {})).status).toBe(401);
expect(f.query).not.toHaveBeenCalled();
for (const token of [tokens.read, tokens.admin, tokens.service, tokens.research]) {
expect(
(await f.request(baseline.manifest.hash, { Authorization: `Bearer ${token}` })).status
).toBe(200);
for (const token of [tokens.read, tokens.admin, tokens.service]) {
const response = await f.request(baseline.manifest.hash, {
Authorization: `Bearer ${token}`,
});
expect(response.status).toBe(200);
expect(await response.json()).toEqual(baseline);
}
for (const token of [tokens.read, tokens.admin]) {
const login = await f.app.request('/api/auth/session', {
@ -300,19 +302,31 @@ describe('validated canonical dataset export', () => {
expect(login.status).toBe(200);
const cookie = login.headers.get('Set-Cookie')?.split(';')[0];
expect(cookie).toBeDefined();
expect((await f.request(baseline.manifest.hash, { Cookie: cookie! })).status).toBe(200);
const response = await f.request(baseline.manifest.hash, { Cookie: cookie! });
expect(response.status).toBe(200);
expect(await response.json()).toEqual(baseline);
}
const before = f.payloadRead.mock.calls.length;
const beforeResearch = f.payloadRead.mock.calls.length;
for (const method of ['GET', 'HEAD']) {
const forbidden = await f.app.request(path(baseline.manifest.hash), {
method,
headers: { Authorization: `Bearer ${tokens.research}` },
});
expect(forbidden.status).toBe(403);
expect(forbidden.headers.get('Cache-Control')).toBe('no-store');
expect(forbidden.headers.get('Content-Disposition')).toBeNull();
}
expect(f.payloadRead).toHaveBeenCalledTimes(beforeResearch);
f.revokeResearch();
const denied = await f.request(baseline.manifest.hash, {
Authorization: `Bearer ${tokens.research}`,
});
expect(denied.status).toBe(401);
expect(denied.headers.get('Content-Disposition')).toBeNull();
expect(f.payloadRead).toHaveBeenCalledTimes(before);
expect(f.payloadRead).toHaveBeenCalledTimes(beforeResearch);
expect(
f.query.mock.calls.filter(call => call[0].includes('FROM research_agents'))
).toHaveLength(2);
).toHaveLength(3);
expect(f.sourceRead).not.toHaveBeenCalled();
});
});

View file

@ -118,7 +118,7 @@ test('operator-only provisioning fails closed without enabled research authentic
}
expect(query).toHaveBeenCalledTimes(0);
});
test('resolver grants only exact immutable dataset exports among dataset operations', async () => {
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 },
@ -131,12 +131,9 @@ test('resolver grants only exact immutable dataset exports among dataset operati
headers: { Authorization: `Bearer ${token}` },
})
);
for (const method of ['GET', 'HEAD']) {
expect(await check(`/api/v2/datasets/canonical/${hash}/export`, method)).toEqual({
principal: agent,
});
}
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'],
@ -149,7 +146,10 @@ test('resolver grants only exact immutable dataset exports among dataset operati
['/api/v2/datasets/stored-eod/inspect', 'POST'],
[`/api/v2/datasets/canonical/${hash}/export`, 'POST'],
]) {
expect(((await check(path!, method)) as Response).status).toBe(403);
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');
}
});
@ -190,9 +190,189 @@ test('resolver exact write capabilities refuse trading, operators, foreign evide
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/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

View file

@ -18,6 +18,8 @@ const options = {
origins: ['http://ui.test'],
};
const agentId = 'agent:00000000-0000-4000-8000-000000000001';
const grantedProjectId = '11111111-1111-4111-8111-111111111111';
const ungrantedProjectId = '22222222-2222-4222-8222-222222222222';
const token = 'sb-research.server-composition-fixture';
const bearer = (value = token) => ({ Authorization: `Bearer ${value}` });
@ -28,10 +30,27 @@ function fixture(disabled = false, supplied = false) {
return {
rows:
values?.[0] === createHash('sha256').update(token).digest('hex')
? [{ id: agentId, enabled, policy: { allowedProjectIds: [] } }]
? [{ id: agentId, enabled, policy: { allowedProjectIds: [grantedProjectId] } }]
: [],
};
}
if (sql === 'SELECT * FROM research_projects WHERE id=$1' && values?.[0] === grantedProjectId) {
return {
rows: [
{
id: grantedProjectId,
title: 'Granted project',
description: '',
revision: 1,
owner_principal: 'operator',
updated_by: 'operator',
archived_at: null,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
},
],
};
}
if (sql.startsWith('SELECT a.*,(SELECT count(*)::integer FROM runs')) {
return {
rows: [
@ -205,3 +224,34 @@ test('web composition preserves token, environment, origin and browser-session v
expect(preflight.headers.get('access-control-allow-origin')).toBe('http://ui.test');
expect(f.query).not.toHaveBeenCalled();
});
test('web security denies agent dataset export and ungranted project reads before touching storage', async () => {
const f = fixture();
const hash = 'a'.repeat(64);
for (const method of ['GET', 'HEAD']) {
const exported = await f.app.request(`/api/v2/datasets/canonical/${hash}/export`, {
method,
headers: bearer(),
});
expect(exported.status).toBe(403);
expect(exported.headers.get('cache-control')).toBe('no-store');
const ungranted = await f.app.request(`/api/v2/research-projects/${ungrantedProjectId}`, {
method,
headers: bearer(),
});
expect(ungranted.status).toBe(403);
expect(ungranted.headers.get('cache-control')).toBe('no-store');
}
expect(
f.query.mock.calls.every(call =>
String(call[0]).startsWith('SELECT id,enabled,policy FROM research_agents WHERE token_hash=')
)
).toBe(true);
const granted = await f.app.request(`/api/v2/research-projects/${grantedProjectId}`, {
headers: bearer(),
});
expect(granted.status).toBe(200);
expect(await granted.json()).toMatchObject({ project: { id: grantedProjectId } });
});

View file

@ -1048,4 +1048,178 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
expect((await f.experiments.submit(changed, receipt(p.agent.id))).trials).toHaveLength(2);
});
test('HTTP read scoping blocks dataset export, ungranted projects/narratives/templates and foreign experiments/runs/strategies', 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' = 'GET') =>
app.request(path, { method, headers: { Authorization: `Bearer ${token}` } });
// 1. Dataset export: 403 for agent (GET/HEAD), 200 for operator
const exportPath = `/api/v2/datasets/canonical/${f.dataset.manifest.hash}/export`;
for (const method of ['GET', 'HEAD'] as const) {
const agentExport = await req(exportPath, p.token, method);
expect(agentExport.status).toBe(403);
expect(agentExport.headers.get('cache-control')).toBe('no-store');
expect(agentExport.headers.get('content-disposition')).toBeNull();
}
expect((await req(exportPath, operatorToken)).status).toBe(200);
// 2. Projects & narratives: granted vs ungranted
const ungrantedProject = await f.research.createProject(
{ title: 'Operator secret project' },
'operator'
);
const grantedHypothesis = await f.research.createHypothesis(
p.project.id,
{ title: 'Granted H', proposition: 'Visible to agent' },
'operator'
);
const ungrantedHypothesis = await f.research.createHypothesis(
ungrantedProject.id,
{ title: 'Secret H', proposition: 'Hidden from agent' },
'operator'
);
const grantedArtifact = await f.research.createArtifact(
p.project.id,
{ kind: 'note', title: 'Granted A', body: 'Visible note', evidence: [] },
'operator'
);
const ungrantedArtifact = await f.research.createArtifact(
ungrantedProject.id,
{ kind: 'note', title: 'Secret A', body: 'Hidden note', evidence: [] },
'operator'
);
const agentProjects = await req('/api/v2/research-projects', p.token);
expect(agentProjects.status).toBe(200);
expect(((await agentProjects.json()) as { projects: { id: string }[] }).projects.map(x => x.id)).toEqual([
p.project.id,
]);
const opProjects = await req('/api/v2/research-projects', operatorToken);
expect(opProjects.status).toBe(200);
expect(((await opProjects.json()) as { projects: { id: string }[] }).projects).toHaveLength(2);
for (const allowedPath of [
`/api/v2/research-projects/${p.project.id}`,
`/api/v2/research-projects/${p.project.id}/strategies`,
`/api/v2/research-projects/${p.project.id}/hypotheses`,
`/api/v2/research-projects/${p.project.id}/analysis-artifacts`,
`/api/v2/hypotheses/${grantedHypothesis.id}`,
`/api/v2/hypotheses/${grantedHypothesis.id}/revisions`,
`/api/v2/analysis-artifacts/${grantedArtifact.id}`,
`/api/v2/analysis-artifacts/${grantedArtifact.id}/revisions`,
]) {
expect((await req(allowedPath, p.token)).status).toBe(200);
}
for (const deniedPath of [
`/api/v2/research-projects/${ungrantedProject.id}`,
`/api/v2/research-projects/${ungrantedProject.id}/strategies`,
`/api/v2/research-projects/${ungrantedProject.id}/hypotheses`,
`/api/v2/research-projects/${ungrantedProject.id}/analysis-artifacts`,
`/api/v2/hypotheses/${ungrantedHypothesis.id}`,
`/api/v2/hypotheses/${ungrantedHypothesis.id}/revisions`,
`/api/v2/analysis-artifacts/${ungrantedArtifact.id}`,
`/api/v2/analysis-artifacts/${ungrantedArtifact.id}/revisions`,
'/api/v2/research-projects/not-a-uuid',
'/api/v2/hypotheses/not-a-uuid',
'/api/v2/analysis-artifacts/not-a-uuid',
]) {
expect((await req(deniedPath, p.token)).status).toBe(403);
}
// 3. Backtests, experiments & runs (including shared granted template)
const ungrantedBacktest = await f.api.createBacktest(
{ ...f.definition, name: 'Ungranted template' },
{ autoStart: false }
);
const agentBacktests = await req('/api/v2/backtests', p.token);
expect(agentBacktests.status).toBe(200);
expect(((await agentBacktests.json()) as { id: string }[]).map(b => b.id)).toEqual([
f.draft.id,
]);
expect((await req(`/api/v2/backtests/${f.draft.id}`, p.token)).status).toBe(200);
expect((await req(`/api/v2/backtests/${ungrantedBacktest.id}`, p.token)).status).toBe(403);
expect((await req(`/api/v2/backtests/${ungrantedBacktest.id}/runs`, p.token)).status).toBe(403);
const agentExp = await f.experiments.submit(
await preparation(f, 'Agent exp', f.draft.id, { fastPeriod: [1] }),
receipt(p.agent.id)
);
const opExp = await f.experiments.submit(
await preparation(f, 'Operator exp', f.draft.id, { fastPeriod: [2] }),
receipt('operator')
);
const agentRunId = required(agentExp.trials[0]!.runId);
const opRunId = required(opExp.trials[0]!.runId);
const agentExpList = await req('/api/v2/experiments', p.token);
expect(agentExpList.status).toBe(200);
expect(
((await agentExpList.json()) as { experiments: { id: string }[] }).experiments.map(e => e.id)
).toEqual([agentExp.id]);
expect((await req(`/api/v2/experiments?backtestId=${f.draft.id}`, p.token)).status).toBe(200);
expect(
(await req(`/api/v2/experiments?backtestId=${ungrantedBacktest.id}`, p.token)).status
).toBe(403);
expect((await req(`/api/v2/experiments/${agentExp.id}`, p.token)).status).toBe(200);
expect((await req(`/api/v2/experiments/${opExp.id}`, p.token)).status).toBe(403);
expect(
(
await req(
`/api/v2/experiments/compare?leftId=${agentExp.id}&rightId=${opExp.id}`,
p.token
)
).status
).toBe(403);
const agentRuns = await req(`/api/v2/backtests/${f.draft.id}/runs`, p.token);
expect(agentRuns.status).toBe(200);
expect(((await agentRuns.json()) as { id: string }[]).map(r => r.id)).toEqual([agentRunId]);
expect((await req(`/api/v2/runs/${agentRunId}`, p.token)).status).toBe(200);
expect((await req(`/api/v2/runs/${opRunId}`, p.token)).status).toBe(403);
expect((await req('/api/v2/runs/not-a-uuid', p.token)).status).toBe(403);
// 4. Strategies & strategy-versions: granted/owned vs unlinked foreign
const foreignStrategy = await f.catalog.cloneVersion(
f.version.id,
{ name: 'Foreign operator strategy' },
'operator',
randomUUID()
);
const ownedStrategy = await f.catalog.cloneVersion(
f.version.id,
{ name: 'Agent owned strategy' },
p.agent.id as `agent:${string}`,
randomUUID()
);
const agentStrategies = await req('/api/v2/strategies', p.token);
expect(agentStrategies.status).toBe(200);
const visibleStrategyIds = (
(await agentStrategies.json()) as { strategies: { id: string }[] }
).strategies.map(s => s.id);
expect(visibleStrategyIds).toContain(f.version.strategyId);
expect(visibleStrategyIds).toContain(ownedStrategy.strategy.id);
expect(visibleStrategyIds).not.toContain(foreignStrategy.strategy.id);
expect((await req(`/api/v2/strategies/${f.version.strategyId}`, p.token)).status).toBe(200);
expect((await req(`/api/v2/strategies/${ownedStrategy.strategy.id}`, p.token)).status).toBe(200);
expect((await req(`/api/v2/strategies/${foreignStrategy.strategy.id}`, p.token)).status).toBe(
403
);
expect((await req(`/api/v2/strategy-versions/${ownedStrategy.version.id}`, p.token)).status).toBe(
200
);
expect(
(await req(`/api/v2/strategy-versions/${foreignStrategy.version.id}`, p.token)).status
).toBe(403);
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);
});
});