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

@ -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 } });
});