fix(api): wire research credentials into server security (RP20)
This commit is contained in:
parent
fd90d17214
commit
7de497e9b0
5 changed files with 274 additions and 26 deletions
207
test/integration/web-api-security.test.ts
Normal file
207
test/integration/web-api-security.test.ts
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { expect, mock, test } from 'bun:test';
|
||||
import {
|
||||
createHttpSecurity,
|
||||
getCredentialHttpPrincipal,
|
||||
getResearchHttpPrincipal,
|
||||
} from '@stock-bot/di';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { createWebApiSecurity } from '../../apps/stock/web-api/src/http-security';
|
||||
import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes';
|
||||
import { createWebSocketRoute } from '../../apps/stock/web-api/src/routes/websocket.routes';
|
||||
|
||||
const options = {
|
||||
adminToken: 'operator-fixture-not-a-secret-123456789012345',
|
||||
serviceToken: 'service-fixture-not-a-secret-123456789012345',
|
||||
environment: 'test',
|
||||
origins: ['http://ui.test'],
|
||||
};
|
||||
const agentId = 'agent:00000000-0000-4000-8000-000000000001';
|
||||
const token = 'sb-research.server-composition-fixture';
|
||||
const bearer = (value = token) => ({ Authorization: `Bearer ${value}` });
|
||||
|
||||
function fixture(disabled = false, supplied = false) {
|
||||
let enabled = true;
|
||||
const query = mock(async (sql: string, values?: unknown[]) => {
|
||||
if (sql.startsWith('SELECT id,enabled,policy FROM research_agents WHERE token_hash=')) {
|
||||
return {
|
||||
rows:
|
||||
values?.[0] === createHash('sha256').update(token).digest('hex')
|
||||
? [{ id: agentId, enabled, policy: { allowedProjectIds: [] } }]
|
||||
: [],
|
||||
};
|
||||
}
|
||||
if (sql.startsWith('SELECT a.*,(SELECT count(*)::integer FROM runs')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: agentId,
|
||||
name: 'Scoped researcher',
|
||||
enabled,
|
||||
revision: 1,
|
||||
policy: {
|
||||
allowedProjectIds: [],
|
||||
grants: [],
|
||||
limits: {
|
||||
maxActiveTrials: 2,
|
||||
maxTrialsPerExperiment: 4,
|
||||
maxBarEvaluationsPerExperiment: 1000,
|
||||
maxAttemptWallMs: 1000,
|
||||
maxAttempts: 1,
|
||||
},
|
||||
},
|
||||
active_trials: 1,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
throw new Error('Unexpected storage access');
|
||||
});
|
||||
const container = {
|
||||
postgres: { query },
|
||||
logger: getLogger('web-api-security-test'),
|
||||
} as unknown as IServiceContainer;
|
||||
const security = supplied
|
||||
? createHttpSecurity({ ...options, disabled, browserSessions: true })
|
||||
: createWebApiSecurity(container, { ...options, disabled });
|
||||
const app = createRoutes(container, security);
|
||||
return {
|
||||
app,
|
||||
container,
|
||||
security,
|
||||
query,
|
||||
revoke: () => {
|
||||
enabled = false;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('production web security enables operator provisioning and the real research resolver', async () => {
|
||||
const f = fixture();
|
||||
const provision = await f.app.request('/api/v2/research-agents', {
|
||||
method: 'POST',
|
||||
headers: { ...bearer(options.adminToken), 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
});
|
||||
// Reaching the existing policy validator proves provisioning passed the composition fence.
|
||||
expect(provision.status).toBe(400);
|
||||
expect(await provision.json()).toEqual({ error: 'Invalid research principal policy' });
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
const request = new Request('http://api.test/api/v2/research-agent/budget', {
|
||||
headers: bearer(),
|
||||
});
|
||||
const budget = await f.app.fetch(request);
|
||||
expect(budget.status).toBe(200);
|
||||
expect(getResearchHttpPrincipal(request)).toBe(agentId);
|
||||
expect(getCredentialHttpPrincipal(request)).toBeUndefined();
|
||||
expect(await budget.json()).toMatchObject({
|
||||
agent: { id: agentId },
|
||||
activeTrials: 1,
|
||||
remainingActiveTrials: 1,
|
||||
});
|
||||
f.revoke();
|
||||
expect((await f.app.request('/api/v2/research-agent/budget', { headers: bearer() })).status).toBe(
|
||||
401
|
||||
);
|
||||
expect(
|
||||
(await f.app.request('/api/v2/research-agent/budget', { headers: bearer('invalid') })).status
|
||||
).toBe(401);
|
||||
expect(
|
||||
(
|
||||
await f.app.request('/api/v2/research-agent/budget', {
|
||||
headers: bearer('sb-research.unknown'),
|
||||
})
|
||||
).status
|
||||
).toBe(401);
|
||||
});
|
||||
|
||||
test('shared web security denies agent administration, sessions and synchronous upgrades', async () => {
|
||||
const f = fixture();
|
||||
for (const path of [
|
||||
'/api/v2/research-agents',
|
||||
'/api/v2/paper-deployments',
|
||||
'/api/operations/start',
|
||||
]) {
|
||||
expect(
|
||||
(await f.app.request(path, { method: 'POST', headers: bearer(), body: '{}' })).status
|
||||
).toBe(403);
|
||||
}
|
||||
expect(
|
||||
(
|
||||
await f.app.request('/api/v2/research-agents', {
|
||||
method: 'POST',
|
||||
headers: bearer(options.serviceToken),
|
||||
body: '{}',
|
||||
})
|
||||
).status
|
||||
).toBe(403);
|
||||
expect(
|
||||
(
|
||||
await f.app.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { Origin: 'http://ui.test', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token }),
|
||||
})
|
||||
).status
|
||||
).toBe(403);
|
||||
f.query.mockClear();
|
||||
const upgrade = mock(() => true);
|
||||
const ws = createWebSocketRoute(f.container, f.security);
|
||||
const response = ws(
|
||||
new Request('http://api.test/ws?runId=fixture', {
|
||||
headers: { ...bearer(), Upgrade: 'websocket', Origin: 'http://ui.test' },
|
||||
}),
|
||||
{ upgrade }
|
||||
);
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect(response?.status).toBe(403);
|
||||
expect(upgrade).not.toHaveBeenCalled();
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('disabled authentication and explicitly supplied security do not gain research capabilities', async () => {
|
||||
for (const f of [fixture(true), fixture(false, true)]) {
|
||||
expect(f.security.researchEnabled).toBe(false);
|
||||
expect(
|
||||
(
|
||||
await f.app.request('/api/v2/research-agents', {
|
||||
method: 'POST',
|
||||
headers: bearer(options.adminToken),
|
||||
body: '{}',
|
||||
})
|
||||
).status
|
||||
).toBe(403);
|
||||
expect(
|
||||
(await f.app.request('/api/v2/research-agent/budget', { headers: bearer() })).status
|
||||
).toBe(403);
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
test('web composition preserves token, environment, origin and browser-session validation', async () => {
|
||||
const f = fixture();
|
||||
for (const invalid of [
|
||||
{ ...options, adminToken: 'short' },
|
||||
{ ...options, origins: ['*'] },
|
||||
{ ...options, disabled: true, environment: 'production' },
|
||||
]) {
|
||||
expect(() => createWebApiSecurity(f.container, invalid)).toThrow();
|
||||
}
|
||||
const login = await f.app.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { Origin: 'http://ui.test', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: options.adminToken }),
|
||||
});
|
||||
expect(login.status).toBe(200);
|
||||
expect(login.headers.get('set-cookie')).toContain('stock_bot_session=');
|
||||
const preflight = await f.app.request('/api/v2/research-agents', {
|
||||
method: 'OPTIONS',
|
||||
headers: { Origin: 'http://ui.test', 'Access-Control-Request-Method': 'POST' },
|
||||
});
|
||||
expect(preflight.status).toBe(204);
|
||||
expect(preflight.headers.get('access-control-allow-origin')).toBe('http://ui.test');
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
|
@ -3,7 +3,6 @@ import { readFileSync } from 'node:fs';
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type {
|
||||
|
|
@ -13,9 +12,9 @@ import type {
|
|||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { createWebApiSecurity } from '../../apps/stock/web-api/src/http-security';
|
||||
import { createRoutes } from '../../apps/stock/web-api/src/routes/create-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';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
|
||||
|
|
@ -206,18 +205,14 @@ async function totals(f: Fixture) {
|
|||
)
|
||||
).rows[0];
|
||||
}
|
||||
const operatorToken = 'operator-test-secret-12345678901234567890';
|
||||
function http(f: Fixture) {
|
||||
const app = new Hono();
|
||||
const security = createHttpSecurity({
|
||||
adminToken: 'operator-test-secret-12345678901234567890',
|
||||
const security = createWebApiSecurity(f.container, {
|
||||
adminToken: operatorToken,
|
||||
serviceToken: 'service-test-secret-123456789012345678901',
|
||||
environment: 'test',
|
||||
resolveResearchCredential: request => f.agents.authenticate(request),
|
||||
});
|
||||
security.mount(app);
|
||||
app.route('/', createResearchAgentRoutes(f.container, security.researchEnabled));
|
||||
app.route('/', createExperimentRoutes(f.container));
|
||||
app.route('/', createResearchRoutes(f.container));
|
||||
const app = createRoutes(f.container, security);
|
||||
return (path: string, token: string, body?: unknown, key?: string) =>
|
||||
app.request(path, {
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
|
|
@ -308,10 +303,20 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
|
|||
await expect(update('description=description')).rejects.toThrow('disabled');
|
||||
expect(await f.research.getProject(p.project.id)).toEqual(after);
|
||||
});
|
||||
test('operator provisioning stores only a hash; real mounted authentication, AI authorship and scoped writes', async () => {
|
||||
const f = await fixture(1),
|
||||
p = await provision(f);
|
||||
test('production security issues research credentials with scoped identity, durable budgets and revocation', async () => {
|
||||
const f = await fixture(1);
|
||||
await f.approve();
|
||||
const project = await f.research.createProject({ title: 'Agent research' }, 'operator');
|
||||
const request = http(f);
|
||||
const issued = await request('/api/v2/research-agents', operatorToken, {
|
||||
name: 'Bounded researcher',
|
||||
allowedProjectIds: [project.id],
|
||||
allowedBacktestIds: [f.draft.id],
|
||||
limits,
|
||||
});
|
||||
expect(issued.status).toBe(201);
|
||||
const created = (await issued.json()) as Awaited<ReturnType<ResearchAgentsService['create']>>;
|
||||
const p = { ...created, project };
|
||||
expect(p.token.startsWith('sb-research.')).toBe(true);
|
||||
const stored = (await f.pool.query('SELECT * FROM research_agents WHERE id=$1', [p.agent.id]))
|
||||
.rows[0];
|
||||
|
|
@ -372,6 +377,29 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
|
|||
f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [candidate.id] })
|
||||
).rejects.toThrow('approved canonical templates');
|
||||
expect((await totals(f)).runs).toBe(0);
|
||||
const admitted = await request(
|
||||
'/api/v2/experiments',
|
||||
p.token,
|
||||
await preparation(f),
|
||||
randomUUID()
|
||||
);
|
||||
expect(admitted.status).toBe(202);
|
||||
const beforeDenial = await totals(f);
|
||||
expect(beforeDenial.runs).toBe(limits.maxActiveTrials);
|
||||
const owners = await f.pool.query('SELECT DISTINCT research_agent_id FROM runs');
|
||||
expect(owners.rows).toEqual([{ research_agent_id: p.agent.id }]);
|
||||
const submitters = await f.pool.query(
|
||||
'SELECT DISTINCT submission_principal FROM research_experiments'
|
||||
);
|
||||
expect(submitters.rows).toEqual([{ submission_principal: p.agent.id }]);
|
||||
const exhausted = await request(
|
||||
'/api/v2/experiments',
|
||||
p.token,
|
||||
await preparation(f, 'Capacity exceeded', f.draft.id, { fastPeriod: [1] }),
|
||||
randomUUID()
|
||||
);
|
||||
expect(exhausted.status).toBe(429);
|
||||
expect(await totals(f)).toEqual(beforeDenial);
|
||||
await f.agents.update(p.agent.id, { expectedRevision: 1, enabled: false });
|
||||
expect((await request('/api/v2/research-agent/budget', p.token)).status).toBe(401);
|
||||
expect((await f.agents.budget(p.agent.id, true)).agent.enabled).toBe(false);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue