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

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