207 lines
6.9 KiB
TypeScript
207 lines
6.9 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 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();
|
|
});
|