stock-bot/test/integration/web-api-security.test.ts

257 lines
8.7 KiB
TypeScript

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 grantedProjectId = '11111111-1111-4111-8111-111111111111';
const ungrantedProjectId = '22222222-2222-4222-8222-222222222222';
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: [grantedProjectId] } }]
: [],
};
}
if (sql === 'SELECT * FROM research_projects WHERE id=$1' && values?.[0] === grantedProjectId) {
return {
rows: [
{
id: grantedProjectId,
title: 'Granted project',
description: '',
revision: 1,
owner_principal: 'operator',
updated_by: 'operator',
archived_at: null,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
},
],
};
}
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();
});
test('web security denies agent dataset export and ungranted project reads before touching storage', async () => {
const f = fixture();
const hash = 'a'.repeat(64);
for (const method of ['GET', 'HEAD']) {
const exported = await f.app.request(`/api/v2/datasets/canonical/${hash}/export`, {
method,
headers: bearer(),
});
expect(exported.status).toBe(403);
expect(exported.headers.get('cache-control')).toBe('no-store');
const ungranted = await f.app.request(`/api/v2/research-projects/${ungrantedProjectId}`, {
method,
headers: bearer(),
});
expect(ungranted.status).toBe(403);
expect(ungranted.headers.get('cache-control')).toBe('no-store');
}
expect(
f.query.mock.calls.every(call =>
String(call[0]).startsWith('SELECT id,enabled,policy FROM research_agents WHERE token_hash=')
)
).toBe(true);
const granted = await f.app.request(`/api/v2/research-projects/${grantedProjectId}`, {
headers: bearer(),
});
expect(granted.status).toBe(200);
expect(await granted.json()).toMatchObject({ project: { id: grantedProjectId } });
});