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:55:19 -05:00
parent 5bbad5cced
commit a8c5fe2d4b
3 changed files with 121 additions and 17 deletions

View file

@ -138,7 +138,11 @@ export class ResearchEvidenceResolver {
database: BacktestResultQuery database: BacktestResultQuery
): Promise<ResearchEvidence[]> { ): Promise<ResearchEvidence[]> {
if (!source) { if (!source) {
return Promise.all(references.map(reference => this.resolve(reference, database))); const resolved: ResearchEvidence[] = [];
for (const reference of references) {
resolved.push(await this.resolve(reference, database));
}
return resolved;
} }
const results = await verifyResearchSource(source, references, database, (id, query) => const results = await verifyResearchSource(source, references, database, (id, query) =>
this.results.getRunResults(id, query) this.results.getRunResults(id, query)

View file

@ -419,7 +419,11 @@ export class ResearchService {
[projectId, includeArchived] [projectId, includeArchived]
) )
).rows; ).rows;
return Promise.all(rows.map(row => this.artifact(client, row, undefined, agentId))); const artifacts: ResearchArtifact[] = [];
for (const row of rows) {
artifacts.push(await this.artifact(client, row, undefined, agentId));
}
return artifacts;
}); });
} }
async createArtifact( async createArtifact(
@ -484,7 +488,11 @@ export class ResearchService {
[id] [id]
) )
).rows; ).rows;
return Promise.all(rows.map(row => this.artifactRevision(client, row, agentId))); const revisions: ResearchArtifactRevision[] = [];
for (const row of rows) {
revisions.push(await this.artifactRevision(client, row, agentId));
}
return revisions;
}); });
} }
async reviseArtifact( async reviseArtifact(

View file

@ -523,14 +523,49 @@ test('artifact reads check run ownership before resolving evidence for research
if (sql.includes('SELECT id, research_agent_id FROM runs WHERE id = ANY($1::uuid[])')) { if (sql.includes('SELECT id, research_agent_id FROM runs WHERE id = ANY($1::uuid[])')) {
return { rows: [{ id: foreignRunId, research_agent_id: null }] }; return { rows: [{ id: foreignRunId, research_agent_id: null }] };
} }
if (sql.includes('SELECT id,backtest_id,status FROM runs WHERE id=$1')) {
return {
rows: [
{
id: values?.[0],
backtest_id: '55555555-5555-4555-8555-555555555555',
status: 'completed',
},
],
};
}
throw new Error(`Unexpected SQL: ${sql}`); throw new Error(`Unexpected SQL: ${sql}`);
}); });
let queriesAfterRelease = 0;
const container = { const container = {
postgres: { postgres: {
query: clientQuery, query: clientQuery,
transaction: async <T>(fn: (client: { query: typeof clientQuery }) => Promise<T>) => transaction: async <T>(fn: (client: { query: typeof clientQuery }) => Promise<T>) => {
fn({ query: clientQuery }), let released = false;
let queue = Promise.resolve();
const txClient = {
query: ((sql: string, values?: unknown[]) => {
const run = queue.then(async () => {
if (released) {
queriesAfterRelease += 1;
throw new Error(`Query executed on released transaction client: ${sql}`);
}
return clientQuery(sql, values);
});
queue = run.then(
() => undefined,
() => undefined
);
return run;
}) as typeof clientQuery,
};
try {
return await fn(txClient);
} finally {
released = true;
}
},
}, },
logger: { error: mock(() => {}) }, logger: { error: mock(() => {}) },
} as unknown as IServiceContainer; } as unknown as IServiceContainer;
@ -574,6 +609,7 @@ test('artifact reads check run ownership before resolving evidence for research
}; };
expect(opBody.artifact.latestRevision.evidence[0]?.value).toBe(2.45); expect(opBody.artifact.latestRevision.evidence[0]?.value).toBe(2.45);
expect(resolveAll).toHaveBeenCalledTimes(1); expect(resolveAll).toHaveBeenCalledTimes(1);
expect(queriesAfterRelease).toBe(0);
}); });
test('mixed artifact revision history allows latest-revision list and item reads while blocking history reads of foreign evidence', async () => { test('mixed artifact revision history allows latest-revision list and item reads while blocking history reads of foreign evidence', async () => {
@ -584,15 +620,24 @@ test('mixed artifact revision history allows latest-revision list and item reads
const foreignRunId = '44444444-4444-4444-8444-444444444444'; const foreignRunId = '44444444-4444-4444-8444-444444444444';
const ownedRunId = '44444444-4444-4444-8444-444444444445'; const ownedRunId = '44444444-4444-4444-8444-444444444445';
const now = new Date('2026-01-01T00:00:00Z'); const now = new Date('2026-01-01T00:00:00Z');
const resolveAll = mock(async (refs: { runId: string }[]) => const resolveAll = mock(
refs.map(ref => ({ async (
refs: { runId: string }[],
_source: unknown,
db?: { query: (sql: string, values?: unknown[]) => Promise<{ rows: unknown[] }> }
) => {
if (db) {
await db.query('SELECT id,backtest_id,status FROM runs WHERE id=$1', [refs[0]?.runId]);
}
return refs.map(ref => ({
runId: ref.runId, runId: ref.runId,
datasetHash: 'a'.repeat(64), datasetHash: 'a'.repeat(64),
metricsVersion: 'canonical-analytics/v1', metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.sharpeRatio', metricPath: 'analytics.metrics.sharpeRatio',
value: ref.runId === foreignRunId ? 2.45 : 1.15, value: ref.runId === foreignRunId ? 2.45 : 1.15,
strategyVersionId: null, strategyVersionId: null,
})) }));
}
); );
const artifactRow = { const artifactRow = {
id: artifactId, id: artifactId,
@ -672,14 +717,49 @@ test('mixed artifact revision history allows latest-revision list and item reads
})), })),
}; };
} }
if (sql.includes('SELECT id,backtest_id,status FROM runs WHERE id=$1')) {
return {
rows: [
{
id: values?.[0],
backtest_id: '55555555-5555-4555-8555-555555555555',
status: 'completed',
},
],
};
}
throw new Error(`Unexpected SQL: ${sql}`); throw new Error(`Unexpected SQL: ${sql}`);
}); });
let queriesAfterRelease = 0;
const container = { const container = {
postgres: { postgres: {
query: clientQuery, query: clientQuery,
transaction: async <T>(fn: (client: { query: typeof clientQuery }) => Promise<T>) => transaction: async <T>(fn: (client: { query: typeof clientQuery }) => Promise<T>) => {
fn({ query: clientQuery }), let released = false;
let queue = Promise.resolve();
const txClient = {
query: ((sql: string, values?: unknown[]) => {
const run = queue.then(async () => {
if (released) {
queriesAfterRelease += 1;
throw new Error(`Query executed on released transaction client: ${sql}`);
}
return clientQuery(sql, values);
});
queue = run.then(
() => undefined,
() => undefined
);
return run;
}) as typeof clientQuery,
};
try {
return await fn(txClient);
} finally {
released = true;
}
},
}, },
logger: { error: mock(() => {}) }, logger: { error: mock(() => {}) },
} as unknown as IServiceContainer; } as unknown as IServiceContainer;
@ -710,10 +790,22 @@ test('mixed artifact revision history allows latest-revision list and item reads
.artifact.latestRevision.evidence[0]?.runId .artifact.latestRevision.evidence[0]?.runId
).toBe(ownedRunId); ).toBe(ownedRunId);
// History endpoint still fails closed with 403 because revision 1 references foreignRunId // History endpoint still fails closed with 403 because revision 1 references foreignRunId,
// and must not leak dangling queries onto the released transaction client.
const historyResp = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}/revisions`, { const historyResp = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}/revisions`, {
headers: { Authorization: `Bearer ${token}` }, headers: { Authorization: `Bearer ${token}` },
}); });
expect(historyResp.status).toBe(403); expect(historyResp.status).toBe(403);
expect(historyResp.headers.get('cache-control')).toBe('no-store'); expect(historyResp.headers.get('cache-control')).toBe('no-store');
await new Promise(resolve => setTimeout(resolve, 10));
expect(queriesAfterRelease).toBe(0);
// Subsequent operator history read succeeds cleanly on a fresh transaction
const opHistoryResp = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}/revisions`, {
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(opHistoryResp.status).toBe(200);
expect(
((await opHistoryResp.json()) as { revisions: { ordinal: number }[] }).revisions
).toHaveLength(2);
}); });