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:30:17 -05:00
parent 7f4d3c7543
commit 48ae151260
3 changed files with 305 additions and 37 deletions

View file

@ -400,10 +400,15 @@ export class ResearchService {
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
FROM analysis_evidence ev
LEFT JOIN runs r ON r.id = ev.run_id
WHERE rev.artifact_id = a.id
WHERE ev.revision_id = (
SELECT rev.id
FROM analysis_artifact_revisions rev
WHERE rev.artifact_id = a.id
ORDER BY rev.ordinal DESC
LIMIT 1
)
AND r.research_agent_id IS DISTINCT FROM $3
)
ORDER BY a.created_at DESC, a.id`,

View file

@ -236,13 +236,21 @@ test('resolver scopes GET and HEAD reads to granted projects, templates and owne
};
}
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 }] };
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 }] };
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')) {
@ -257,19 +265,30 @@ test('resolver scopes GET and HEAD reads to granted projects, templates and owne
};
}
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' }] };
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)
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 }] };
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')) {
@ -468,14 +487,24 @@ test('artifact reads check run ownership before resolving evidence for research
};
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.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(sql).toContain('ORDER BY rev.ordinal DESC');
expect(sql).toContain('LIMIT 1');
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_artifacts WHERE project_id=$1')) {
return { rows: [artifactRow] };
}
if (sql.includes('FROM analysis_artifact_revisions WHERE artifact_id=$1')) {
return { rows: [revisionRow] };
}
@ -546,3 +575,145 @@ test('artifact reads check run ownership before resolving evidence for research
expect(opBody.artifact.latestRevision.evidence[0]?.value).toBe(2.45);
expect(resolveAll).toHaveBeenCalledTimes(1);
});
test('mixed artifact revision history allows latest-revision list and item reads while blocking history reads of foreign evidence', async () => {
const projectId = '11111111-1111-4111-8111-111111111111';
const artifactId = '22222222-2222-4222-8222-222222222222';
const rev1Id = '33333333-3333-4333-8333-333333333333';
const rev2Id = '33333333-3333-4333-8333-333333333334';
const foreignRunId = '44444444-4444-4444-8444-444444444444';
const ownedRunId = '44444444-4444-4444-8444-444444444445';
const now = new Date('2026-01-01T00:00:00Z');
const resolveAll = mock(async (refs: { runId: string }[]) =>
refs.map(ref => ({
runId: ref.runId,
datasetHash: 'a'.repeat(64),
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.sharpeRatio',
value: ref.runId === foreignRunId ? 2.45 : 1.15,
strategyVersionId: null,
}))
);
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 rev1Row = {
id: rev1Id,
artifact_id: artifactId,
ordinal: 1,
title: 'Initial holdout finding',
body: 'Operator holdout sharpe',
submitted_by: 'operator',
content_origin: 'human',
source: null,
created_at: now,
};
const rev2Row = {
id: rev2Id,
artifact_id: artifactId,
ordinal: 2,
title: 'Sanitized finding',
body: 'Agent-visible 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(sql).toContain('ORDER BY rev.ordinal DESC');
expect(sql).toContain('LIMIT 1');
expect(values).toEqual([projectId, false, agent]);
return { rows: [artifactRow] };
}
if (sql.includes('FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1')) {
return { rows: [rev2Row] };
}
if (sql.includes('FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal')) {
return { rows: [rev1Row, rev2Row] };
}
if (sql.includes('FROM analysis_evidence WHERE revision_id=$1')) {
const runId = values?.[0] === rev1Id ? foreignRunId : ownedRunId;
return {
rows: [
{
run_id: runId,
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[])')) {
const ids = (values?.[0] as string[]) ?? [];
return {
rows: ids.map(id => ({
id,
research_agent_id: id === ownedRunId ? agent : null,
})),
};
}
throw new Error(`Unexpected SQL: ${sql}`);
});
const container = {
postgres: {
query: clientQuery,
transaction: async <T>(fn: (client: { query: typeof clientQuery }) => Promise<T>) =>
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));
// Project list and item read succeed for the agent because latest revision (ordinal 2) uses ownedRunId
const listResp = await f.app.request(`/api/v2/research-projects/${projectId}/analysis-artifacts`, {
headers: { Authorization: `Bearer ${token}` },
});
expect(listResp.status).toBe(200);
expect(
((await listResp.json()) as { artifacts: { id: string; latestRevision: { ordinal: number } }[] })
.artifacts
).toMatchObject([{ id: artifactId, latestRevision: { ordinal: 2 } }]);
const itemResp = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}`, {
headers: { Authorization: `Bearer ${token}` },
});
expect(itemResp.status).toBe(200);
expect(
((await itemResp.json()) as { artifact: { latestRevision: { evidence: { runId: string }[] } } })
.artifact.latestRevision.evidence[0]?.runId
).toBe(ownedRunId);
// History endpoint still fails closed with 403 because revision 1 references foreignRunId
const historyResp = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}/revisions`, {
headers: { Authorization: `Bearer ${token}` },
});
expect(historyResp.status).toBe(403);
expect(historyResp.headers.get('cache-control')).toBe('no-store');
});

View file

@ -1224,8 +1224,9 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
});
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 data = walkForwardDataset(),
f = await fixture(4, true, data.dataset),
p = await provision(f, { maxActiveTrials: 4 });
const security = createWebApiSecurity(f.container, {
adminToken: operatorToken,
serviceToken: 'service-test-secret-123456789012345678901',
@ -1247,13 +1248,35 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
...(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] }),
// Execute a real operator-owned chronological validation and its test holdout phase
const { validations } = createResearchServices(f.container);
const validationInput = {
backtestId: f.draft.id,
name: 'Operator chronological holdout',
grid: { fastPeriod: [1, 2] },
recipe: data.windows[0]!,
};
const prepared = await f.experiments.previewValidation(validationInput);
const train = await validations.submit(
{ ...validationInput, previewHash: prepared.previewHash },
receipt('operator')
);
const opRunId = required(opExp.trials[0]!.runId);
for (const trial of required(train.phases[0]?.experiment).trials) {
await f.execute(required(trial.runId));
}
const selected = await validations.select(
train.id,
{ previewHash: prepared.previewHash },
receipt('operator')
);
const holdoutPhase = required(
selected.validation.phases.find(phase => phase.phase === 'test')
);
const opRunId = required(required(holdoutPhase.experiment).trials[0]?.runId);
await f.execute(opRunId);
const holdoutDatasetHash = required(
prepared.partitions.find(partition => partition.phase === 'test')?.dataset.hash
);
const agentExp = await f.experiments.submit(
await preparation(f, 'Agent search', f.draft.id, { fastPeriod: [1] }),
@ -1262,13 +1285,13 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
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
// Operator attaches the holdout phase 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',
body: 'Holdout Sharpe ratio from operator test phase',
evidence: [
{
runId: opRunId,
@ -1301,10 +1324,10 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
'operator'
);
// Agent cannot read operator run results directly
// Agent cannot read operator holdout 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
// Agent cannot read the operator holdout 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}`,
@ -1314,13 +1337,16 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
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);
expect(await denied.text()).not.toContain(holdoutDatasetHash);
}
}
}
// 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);
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 }[] }
@ -1339,11 +1365,11 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
}
).artifact.latestRevision.evidence[0]?.runId
).toBe(agentRunId);
expect((await req(`/api/v2/analysis-artifacts/${agentFinding.id}/revisions`, p.token)).status).toBe(
200
);
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
// Agent cannot attach an operator-owned holdout run as evidence when creating an artifact
const forged = await req(
`/api/v2/research-projects/${p.project.id}/analysis-artifacts`,
p.token,
@ -1351,7 +1377,7 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
{
kind: 'finding',
title: 'Attempted exfiltration',
body: 'Refers to operator run',
body: 'Refers to operator holdout run',
evidence: [
{
runId: opRunId,
@ -1363,16 +1389,21 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
);
expect(forged.status).toBe(403);
// Operator retains full read access to the holdout finding, its revisions, and the full list
// Operator retains full read access to the holdout finding, its retained metric, and holdout dataset hash
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: {
latestRevision: {
evidence: { runId: string; datasetHash: string; value: number }[];
};
};
}
).artifact;
expect(opArtifact.latestRevision.evidence[0]?.runId).toBe(opRunId);
expect(opArtifact.latestRevision.evidence[0]?.datasetHash).toBe(f.dataset.manifest.hash);
expect(opArtifact.latestRevision.evidence[0]?.datasetHash).toBe(holdoutDatasetHash);
expect(Number.isFinite(opArtifact.latestRevision.evidence[0]?.value)).toBe(true);
expect(
(await req(`/api/v2/analysis-artifacts/${opFinding.id}/revisions`, operatorToken)).status
@ -1386,5 +1417,66 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
expect(
((await opList.json()) as { artifacts: { id: string }[] }).artifacts.map(a => a.id)
).toEqual(expect.arrayContaining([opFinding.id, agentFinding.id, plainNote.id]));
// Mixed revision history: after operator revises the finding to reference only the agent's run,
// the latest revision becomes visible in the project list and by ID, while /revisions still fails closed (403)
await f.research.reviseArtifact(
opFinding.id,
{
title: 'Sanitized finding',
body: 'Replaced holdout reference with agent-owned run',
evidence: [
{
runId: agentRunId,
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.sharpeRatio',
},
],
},
'operator'
);
const agentListAfterRev = await req(
`/api/v2/research-projects/${p.project.id}/analysis-artifacts`,
p.token
);
expect(agentListAfterRev.status).toBe(200);
expect(
((await agentListAfterRev.json()) as { artifacts: { id: string }[] }).artifacts.map(a => a.id)
).toEqual(expect.arrayContaining([opFinding.id, agentFinding.id, plainNote.id]));
const agentItemAfterRev = await req(`/api/v2/analysis-artifacts/${opFinding.id}`, p.token);
expect(agentItemAfterRev.status).toBe(200);
const sanitizedText = await agentItemAfterRev.text();
expect(sanitizedText).not.toContain(holdoutDatasetHash);
expect(
(
JSON.parse(sanitizedText) as {
artifact: { latestRevision: { ordinal: number; evidence: { runId: string }[] } };
}
).artifact.latestRevision
).toMatchObject({ ordinal: 2, evidence: [{ runId: agentRunId }] });
const agentHistoryAfterRev = await req(
`/api/v2/analysis-artifacts/${opFinding.id}/revisions`,
p.token
);
expect(agentHistoryAfterRev.status).toBe(403);
expect(agentHistoryAfterRev.headers.get('cache-control')).toBe('no-store');
expect(await agentHistoryAfterRev.text()).not.toContain(holdoutDatasetHash);
const opHistoryAfterRev = await req(
`/api/v2/analysis-artifacts/${opFinding.id}/revisions`,
operatorToken
);
expect(opHistoryAfterRev.status).toBe(200);
const opRevisions = (
(await opHistoryAfterRev.json()) as {
revisions: { ordinal: number; evidence: { runId: string; datasetHash: string }[] }[];
}
).revisions;
expect(opRevisions).toHaveLength(2);
expect(opRevisions[0]?.evidence[0]?.datasetHash).toBe(holdoutDatasetHash);
expect(opRevisions[1]?.evidence[0]?.runId).toBe(agentRunId);
});
});