stock-bot/test/integration/paper-routes.test.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
2026-11-27 00:11:50 -05:00

377 lines
15 KiB
TypeScript

import { describe, expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import { createHttpSecurity } from '@stock-bot/di/http-security';
import {
PaperRuntimeError,
type PaperConfigurationInput,
type PaperConnection,
type PaperFrameInput,
type PaperReadiness,
type PaperRuntime,
} from '@stock-bot/stock-config/paper-runtime';
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/canonical-paper';
import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { paperFeedFrame } from '../fixtures/paper-feed';
const tokens = {
operator: 'paper-routes-admin-fixture-not-a-real-secret-1234',
service: 'paper-routes-service-fixture-not-a-real-secret-1234',
read: 'paper-routes-read-fixture-not-a-real-secret-1234',
};
type Role = keyof typeof tokens;
const connection = { sourceId: 'trusted-fixture', connectionId: 'connection-1' };
const readiness = (): PaperReadiness => ({
configured: true,
accountId: 'paper-account',
sourceId: 'trusted-fixture',
active: false,
ready: true,
operatorHalted: true,
connected: true,
reasons: [],
lastReceivedAt: 1000,
lastAvailableAt: 1000,
requiresHistoricalRecovery: false,
pendingInput: null,
pendingBatch: null,
pendingDecisionSequence: null,
nativeStatus: 'Running',
risk: { dailyHalted: false, drawdownHalted: false },
});
function runtimeFixture() {
return {
initialize: mock(async (_input: PaperConfigurationInput) => {}),
status: mock(async () => readiness()),
connect: mock(async (_input: PaperConnection) => readiness()),
disconnect: mock(async (_input: PaperConnection) => readiness()),
ingest: mock(async (_input: PaperFrameInput) => ({
duplicate: false,
disposition: 'admitted' as const,
readiness: readiness(),
})),
activate: mock(async (_input: { recoverPending: boolean }) => readiness()),
halt: mock(async (_reason: string) => readiness()),
shutdown: mock(async () => {}),
} satisfies PaperRuntime;
}
function fixture(runtime: PaperRuntime | null = runtimeFixture(), allRoutes = false) {
const logger = {
info: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
error: mock(() => {}),
};
const legacy = {
submitOrder: mock(async () => {
throw new Error('Legacy submit must be unreachable');
}),
cancelOrder: mock(async () => {
throw new Error('Legacy cancel must be unreachable');
}),
getPositions: mock(async () => {
throw new Error('Legacy positions must be unreachable');
}),
getRecoveryStatus: mock(async () => {
throw new Error('Legacy recovery must be unreachable');
}),
on: mock(() => {}),
};
const services = {
logger,
custom: {
...(runtime ? { CanonicalPaperRuntime: runtime } : {}),
ExecutionService: legacy,
BacktestRunner: {},
ModeManager: { getCurrentMode: mock(() => 'live') },
},
} as unknown as OrchestratorServices;
const io = { on: mock(() => {}) };
const app = new Hono();
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
readToken: tokens.read,
environment: 'test',
}).mount(app);
if (allRoutes) {
app.route('/', createRoutes(services, io as unknown as SocketIOServer));
} else {
app.route('/api/paper', createPaperRoutes(services));
}
return {
app,
logger,
legacy,
io,
request(path: string, role?: Role, body?: unknown, headers?: Record<string, string>) {
return app.request(`/api/paper${path}`, {
method: body === undefined ? 'GET' : 'POST',
headers: {
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
'Content-Type': 'application/json',
...headers,
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
},
};
}
const mutations = [
{ path: '/activate', method: 'activate', body: {}, feed: false },
{ path: '/halt', method: 'halt', body: { reason: 'operator-request' }, feed: false },
{ path: '/feed/connect', method: 'connect', body: connection, feed: true },
{ path: '/feed/disconnect', method: 'disconnect', body: connection, feed: true },
{ path: '/feed/frames', method: 'ingest', body: paperFeedFrame(), feed: true },
] as const;
describe('canonical paper HTTP authorization', () => {
test('real security distinguishes operator, service producer, reader and anonymous callers', async () => {
for (const role of ['operator', 'service', 'read', undefined] as const) {
const runtime = runtimeFixture();
const f = fixture(runtime);
const response = await f.request('/readiness', role);
expect(response.status).toBe(role ? 200 : 401);
expect(runtime.status.mock.calls).toHaveLength(role ? 1 : 0);
for (const endpoint of mutations) {
const allowed = role === 'operator' || (role === 'service' && endpoint.feed);
const mutation = await f.request(endpoint.path, role, endpoint.body);
expect(mutation.status).toBe(allowed ? 200 : role ? 403 : 401);
expect(runtime[endpoint.method].mock.calls).toHaveLength(allowed ? 1 : 0);
}
}
});
test('caller actor headers, query strings and body fields cannot manufacture operator authority', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
const forged = { 'X-Actor': 'operator', 'X-Principal': 'operator', 'X-Role': 'admin' };
for (const role of ['service', 'read', undefined] as const) {
const response = await f.request(
'/activate?principal=operator&actor=admin',
role,
{},
forged
);
expect(response.status).toBe(role ? 403 : 401);
}
expect((await f.request('/activate', 'operator', { actor: 'operator' }, forged)).status).toBe(
400
);
expect(runtime.activate.mock.calls).toHaveLength(0);
expect((await f.request('/feed/connect', undefined, connection, forged)).status).toBe(401);
expect(runtime.connect.mock.calls).toHaveLength(0);
});
});
describe('canonical paper HTTP input and readiness contracts', () => {
test('activation defaults to no historical recovery and accepts only the explicit strict option', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
expect((await f.request('/activate', 'operator', {})).status).toBe(200);
expect((await f.request('/activate', 'operator', { recoverPending: true })).status).toBe(200);
expect(runtime.activate.mock.calls).toEqual([
[{ recoverPending: false }],
[{ recoverPending: true }],
]);
for (const body of [
{ recoverPending: 'true' },
{ recoverPending: true, resetCapital: true },
null,
[],
]) {
expect((await f.request('/activate', 'operator', body)).status).toBe(400);
}
const malformed = await f.app.request('/api/paper/activate', {
method: 'POST',
headers: { Authorization: `Bearer ${tokens.operator}` },
body: '{',
});
expect(malformed.status).toBe(400);
expect(runtime.activate.mock.calls).toHaveLength(2);
});
test('halt and feed endpoints pass only validated normalized arguments to the runtime', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
expect((await f.request('/halt', 'operator', { reason: ' stop requested ' })).status).toBe(
200
);
expect(runtime.halt.mock.calls).toEqual([['stop requested']]);
for (const body of [{ reason: '' }, { reason: ' ' }, { reason: 'stop', resetRisk: true }]) {
expect((await f.request('/halt', 'operator', body)).status).toBe(400);
}
for (const path of ['/feed/connect', '/feed/disconnect']) {
expect((await f.request(path, 'service', connection)).status).toBe(200);
expect((await f.request(path, 'service', { sourceId: connection.sourceId })).status).toBe(
400
);
expect((await f.request(path, 'service', { ...connection, actor: 'operator' })).status).toBe(
400
);
}
expect(runtime.connect.mock.calls).toEqual([[connection]]);
expect(runtime.disconnect.mock.calls).toEqual([[connection]]);
const frame = paperFeedFrame();
const admitted = await f.request('/feed/frames', 'service', frame);
expect(admitted.status).toBe(200);
expect(await admitted.json()).toEqual({
duplicate: false,
disposition: 'admitted',
readiness: readiness(),
});
expect(runtime.ingest.mock.calls[0]![0].quotes[0]!.bid).toBe('10.00000000');
for (const body of [
{ ...frame, unexpected: true },
{ ...frame, quotes: [] },
{ ...frame, quotes: [{ ...frame.quotes[0], brokerOrderId: 'forbidden' }] },
{ ...frame, observations: [{ ...frame.observations[0], futureFeature: 'forbidden' }] },
]) {
expect((await f.request('/feed/frames', 'service', body)).status).toBe(400);
}
expect(runtime.ingest.mock.calls).toHaveLength(1);
expect(runtime.initialize.mock.calls).toHaveLength(0);
});
test('malformed quote and observation decimals return400 before runtime admission', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
for (const malformed of ['bad', 'NaN', '1e5', '1.000000001']) {
const quote = paperFeedFrame();
quote.quotes[0]!.bid = malformed;
expect((await f.request('/feed/frames', 'service', quote)).status).toBe(400);
const observation = paperFeedFrame();
const body = {
...observation,
observations: [{ ...observation.observations[0], close: malformed }],
};
expect((await f.request('/feed/frames', 'service', body)).status).toBe(400);
}
expect(runtime.ingest.mock.calls).toHaveLength(0);
});
test('unconfigured readiness reports explicit unavailable state and never invents an account', async () => {
const f = fixture(null);
const response = await f.request('/readiness', 'read');
expect(response.status).toBe(200);
expect(response.headers.get('Cache-Control')).toBe('no-store');
expect(await response.json()).toEqual({
configured: false,
accountId: null,
sourceId: null,
active: false,
ready: false,
operatorHalted: true,
connected: false,
reasons: ['not-configured'],
lastReceivedAt: null,
lastAvailableAt: null,
requiresHistoricalRecovery: false,
pendingInput: null,
pendingBatch: null,
pendingDecisionSequence: null,
nativeStatus: null,
risk: null,
});
const activate = await f.request('/activate', 'operator', {});
expect(activate.status).toBe(409);
expect(await activate.json()).toMatchObject({ code: 'not-ready' });
});
test('configured readiness preserves recovery and risk diagnostics without claiming activation', async () => {
const runtime = runtimeFixture();
const blocked: PaperReadiness = {
...readiness(),
ready: false,
active: false,
connected: false,
reasons: ['disconnected', 'pending-financial-work'],
requiresHistoricalRecovery: true,
pendingInput: 'input-7',
pendingBatch: 'batch-3',
pendingDecisionSequence: 8,
risk: { dailyHalted: true, drawdownHalted: false },
};
runtime.status.mockImplementation(async () => blocked);
const response = await fixture(runtime).request('/readiness', 'read');
expect(response.status).toBe(200);
expect(await response.json()).toEqual(blocked);
expect(response.headers.get('Cache-Control')).toBe('no-store');
});
});
describe('canonical paper HTTP failure and legacy gateway isolation', () => {
test('typed validation/readiness/conflict failures keep their public status classification', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
for (const [error, expectedStatus, code] of [
[new PaperRuntimeError('invalid-input', 'Invalid physical quote'), 400, 'invalid-input'],
[new PaperRuntimeError('not-ready', 'Feed disconnected'), 409, 'not-ready'],
[new PaperRuntimeError('conflict', 'Frame conflicts'), 409, 'conflict'],
[new ExecutionConflictError('Account conflicts'), 409, 'conflict'],
] as const) {
runtime.activate.mockImplementation(async () => {
throw error;
});
const response = await f.request('/activate', 'operator', {});
expect(response.status).toBe(expectedStatus);
expect(await response.json()).toEqual({ error: error.message, code });
}
expect(f.logger.error.mock.calls).toHaveLength(0);
});
test('runtime failures return503 and never leak internal database or transport details', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime);
const failure = new Error('sensitive database driver details');
runtime.status.mockImplementation(async () => {
throw failure;
});
const failedStatus = await f.request('/readiness', 'read');
expect(failedStatus.status).toBe(503);
expect(await failedStatus.json()).toEqual({ error: 'Canonical paper runtime unavailable' });
for (const endpoint of mutations) {
runtime[endpoint.method].mockImplementation(async () => {
throw failure;
});
const response = await f.request(endpoint.path, 'operator', endpoint.body);
expect(response.status).toBe(503);
expect(await response.json()).toEqual({ error: 'Canonical paper runtime unavailable' });
expect(response.headers.get('Cache-Control')).toBe('no-store');
}
expect(f.logger.error.mock.calls).toHaveLength(6);
});
test('canonical createRoutes blocks legacy account REST paths and does not register legacy WebSocket handlers', async () => {
const runtime = runtimeFixture();
const f = fixture(runtime, true);
const headers = { Authorization: `Bearer ${tokens.operator}` };
for (const path of [
'/api/orders',
'/api/orders/order-1',
'/api/positions',
'/api/positions/X',
]) {
for (const method of ['GET', 'POST', 'DELETE']) {
const response = await f.app.request(path, { method, headers });
expect(response.status).toBe(409);
expect(await response.json()).toEqual({
error:
'Legacy account execution is retired; use the explicitly configured canonical paper runtime',
});
}
}
const recovery = await f.app.request('/api/recovery', { headers });
expect(await recovery.json()).toEqual({ engine: 'canonical-paper', ...readiness() });
const health = await f.app.request('/health');
expect(await health.json()).toMatchObject({ mode: 'paper', execution: 'canonical-paper' });
expect(f.io.on.mock.calls).toHaveLength(0);
for (const call of Object.values(f.legacy)) {
expect(call.mock.calls).toHaveLength(0);
}
});
});