feat(research): read verified frozen datasets (RP28)
This commit is contained in:
parent
04892a59fe
commit
4b9c642817
9 changed files with 263 additions and 18 deletions
|
|
@ -32,10 +32,13 @@ const payloadSql = 'SELECT payload FROM backtest_datasets WHERE hash=$1';
|
|||
const baseline = createDatasetV2(datasetInput());
|
||||
const path = (hash = baseline.manifest.hash) => `/api/v2/datasets/canonical/${hash}/export`;
|
||||
function fixture(load: () => Promise<unknown> = async () => baseline) {
|
||||
let researchEnabled = true;
|
||||
const payloadRead = mock(load);
|
||||
const query = mock(async (sql: string, values?: unknown[]) => {
|
||||
if (sql === 'SELECT id,enabled,policy FROM research_agents WHERE token_hash=$1') {
|
||||
return { rows: [{ id: agentId, enabled: true, policy: { allowedProjectIds: [] } }] };
|
||||
return {
|
||||
rows: [{ id: agentId, enabled: researchEnabled, policy: { allowedProjectIds: [] } }],
|
||||
};
|
||||
}
|
||||
if (sql !== payloadSql || values?.length !== 1) {
|
||||
throw new Error('Unexpected query: export must not write or read other tables');
|
||||
|
|
@ -69,7 +72,18 @@ function fixture(load: () => Promise<unknown> = async () => baseline) {
|
|||
headers: Record<string, string> = { Authorization: `Bearer ${tokens.admin}` },
|
||||
signal?: AbortSignal
|
||||
) => app.request(path(hash), { headers, signal });
|
||||
return { app, request, database, query, payloadRead, sourceRead, research };
|
||||
return {
|
||||
app,
|
||||
request,
|
||||
database,
|
||||
query,
|
||||
payloadRead,
|
||||
sourceRead,
|
||||
research,
|
||||
revokeResearch: () => {
|
||||
researchEnabled = false;
|
||||
},
|
||||
};
|
||||
}
|
||||
function responseHeaders(response: Response) {
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
|
|
@ -268,11 +282,11 @@ describe('validated canonical dataset export', () => {
|
|||
).rejects.toThrow('cancelled after query');
|
||||
});
|
||||
|
||||
test('existing read, admin, service and browser credentials may export; anonymous and real research credentials may not', async () => {
|
||||
test('read, admin, service, browser and research credentials export; 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]) {
|
||||
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);
|
||||
|
|
@ -289,20 +303,13 @@ describe('validated canonical dataset export', () => {
|
|||
expect((await f.request(baseline.manifest.hash, { Cookie: cookie! })).status).toBe(200);
|
||||
}
|
||||
const before = f.payloadRead.mock.calls.length;
|
||||
f.revokeResearch();
|
||||
const denied = await f.request(baseline.manifest.hash, {
|
||||
Authorization: `Bearer ${tokens.research}`,
|
||||
});
|
||||
expect(denied.status).toBe(403);
|
||||
expect(denied.status).toBe(401);
|
||||
expect(denied.headers.get('Content-Disposition')).toBeNull();
|
||||
expect(f.payloadRead).toHaveBeenCalledTimes(before);
|
||||
// Positive control: this token is recognized by the real resolver for an allowed route.
|
||||
expect(
|
||||
await f.research.authenticate(
|
||||
new Request('http://localhost/api/v2/experiments', {
|
||||
headers: { Authorization: `Bearer ${tokens.research}` },
|
||||
})
|
||||
)
|
||||
).toEqual({ principal: agentId });
|
||||
expect(
|
||||
f.query.mock.calls.filter(call => call[0].includes('FROM research_agents'))
|
||||
).toHaveLength(2);
|
||||
|
|
|
|||
|
|
@ -118,6 +118,41 @@ 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 () => {
|
||||
const query = mock(async () => ({ rows: [{ id: agent, enabled: true, policy: {} }] }));
|
||||
const service = new ResearchAgentsService({
|
||||
postgres: { query },
|
||||
} as unknown as IServiceContainer);
|
||||
const hash = 'a'.repeat(64);
|
||||
const check = (path: string, method = 'GET') =>
|
||||
service.authenticate(
|
||||
new Request(`http://localhost${path}`, {
|
||||
method,
|
||||
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', 'GET'],
|
||||
[`/api/v2/datasets/canonical/${hash}`, 'GET'],
|
||||
[`/api/v2/datasets/canonical/${hash}/export/extra`, 'GET'],
|
||||
[`/api/v2/datasets/canonical/${hash.toUpperCase()}/export`, 'GET'],
|
||||
['/api/v2/datasets/canonical/invalid/export', 'GET'],
|
||||
['/api/v2/datasets/stored-eod/coverage', 'GET'],
|
||||
['/api/v2/datasets/canonical/preview', 'POST'],
|
||||
['/api/v2/datasets/canonical/retain', 'POST'],
|
||||
['/api/v2/datasets/canonical/stored-source', 'POST'],
|
||||
['/api/v2/datasets/stored-eod/inspect', 'POST'],
|
||||
[`/api/v2/datasets/canonical/${hash}/export`, 'POST'],
|
||||
]) {
|
||||
expect(((await check(path!, method)) as Response).status).toBe(403);
|
||||
}
|
||||
});
|
||||
|
||||
test('resolver exact write capabilities refuse trading, operators, foreign evidence and ownership impersonation', async () => {
|
||||
const projectId = randomUUID(),
|
||||
experimentId = randomUUID(),
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/Backt
|
|||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
|
||||
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
|
||||
|
|
@ -118,6 +119,7 @@ async function fixture() {
|
|||
app.route('/', createResearchRoutes(container));
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
app.route('/', createBacktestV2Routes(container));
|
||||
app.route('/', createDatasetRoutes(container));
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
});
|
||||
|
|
@ -258,6 +260,71 @@ async function fixture() {
|
|||
}
|
||||
|
||||
describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust', () => {
|
||||
test('research credentials export known immutable snapshots with exact read-only scope', async () => {
|
||||
const f = await fixture();
|
||||
const hash = f.dataset.manifest.hash;
|
||||
const totals = async () =>
|
||||
(
|
||||
await f.pool.query(`SELECT
|
||||
(SELECT count(*)::int FROM runs) AS runs,
|
||||
(SELECT count(*)::int FROM research_experiments) AS experiments,
|
||||
(SELECT count(*)::int FROM backtest_datasets) AS datasets`)
|
||||
).rows[0];
|
||||
const before = await totals();
|
||||
expect(await f.client.canonicalDataset(hash)).toEqual(f.dataset);
|
||||
const head = await f.transport(
|
||||
`http://127.0.0.1:2003/api/v2/datasets/canonical/${hash}/export`,
|
||||
{
|
||||
method: 'HEAD',
|
||||
headers: { Authorization: `Bearer ${f.provisioned.token}` },
|
||||
}
|
||||
);
|
||||
expect(head.status).toBe(200);
|
||||
expect(head.headers.get('cache-control')).toBe('no-store');
|
||||
expect(head.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
expect(head.headers.get('content-disposition')).toBe(
|
||||
`attachment; filename="dataset-${hash}.json"`
|
||||
);
|
||||
expect(await head.text()).toBe('');
|
||||
for (const [path, method] of [
|
||||
['/datasets/canonical', 'GET'],
|
||||
['/datasets/stored-eod/coverage', 'GET'],
|
||||
['/datasets/canonical/preview', 'POST'],
|
||||
['/datasets/canonical/retain', 'POST'],
|
||||
['/datasets/canonical/stored-source', 'POST'],
|
||||
['/datasets/stored-eod/inspect', 'POST'],
|
||||
[`/datasets/canonical/${hash}/export`, 'POST'],
|
||||
]) {
|
||||
const response = await f.transport(`http://127.0.0.1:2003/api/v2${path}`, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${f.provisioned.token}` },
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
}
|
||||
await expect(f.client.canonicalDataset('0'.repeat(64))).rejects.toMatchObject({
|
||||
status: 404,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(await totals()).toEqual(before);
|
||||
const badHash = 'f'.repeat(64);
|
||||
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb)', [
|
||||
badHash,
|
||||
f.dataset,
|
||||
]);
|
||||
const afterFixtureInsert = await totals();
|
||||
await expect(f.client.canonicalDataset(badHash)).rejects.toMatchObject({
|
||||
status: 409,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(await totals()).toEqual(afterFixtureInsert);
|
||||
await f.agents.update(f.provisioned.agent.id, { expectedRevision: 1, enabled: false });
|
||||
await expect(f.client.canonicalDataset(hash)).rejects.toMatchObject({
|
||||
status: 401,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(f.executionErrors).toEqual([]);
|
||||
});
|
||||
|
||||
test('defaulted candidate validation accepts, reopens and replays the exact original input', async () => {
|
||||
const f = await fixture();
|
||||
const plan = f.suggestions();
|
||||
|
|
@ -607,6 +674,34 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust'
|
|||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(
|
||||
before
|
||||
);
|
||||
const original = await f.client.canonicalRunResult(reference.runId);
|
||||
const snapshot = await f.client.canonicalDataset(original.request.datasetHash);
|
||||
expect(snapshot).toEqual(
|
||||
(
|
||||
await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
||||
original.request.datasetHash,
|
||||
])
|
||||
).rows[0].payload
|
||||
);
|
||||
const template = await f.api.getBacktest(original.backtestId);
|
||||
if (!template) {
|
||||
throw new Error('Missing original template');
|
||||
}
|
||||
await f.api.updateBacktest(original.backtestId, {
|
||||
startDate: new Date(f.dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(f.dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
symbols: f.dataset.manifest.executionSeries.map(series => series.instrumentId),
|
||||
config: {
|
||||
...template.config,
|
||||
datasetHash: f.dataset.manifest.hash,
|
||||
dataFrequency: f.dataset.manifest.series[0]!.interval,
|
||||
},
|
||||
});
|
||||
expect(await f.client.canonicalDataset(original.request.datasetHash)).toEqual(snapshot);
|
||||
expect(await f.client.canonicalRunResult(reference.runId)).toEqual(original);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(
|
||||
before
|
||||
);
|
||||
await f.agents.update(f.provisioned.agent.id, {
|
||||
expectedRevision: f.provisioned.agent.revision,
|
||||
enabled: false,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue