stock-bot/test/integration/paper-deployments-api.test.ts

226 lines
8 KiB
TypeScript

import { expect, test } from 'bun:test';
import { Hono } from 'hono';
import { createHttpSecurity } from '@stock-bot/di';
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
import { createPaperDeploymentHostRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper-deployments';
import {
PaperDeploymentHost,
unboundPaperReadiness,
} from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost';
import {
createPaperDeploymentRoutes,
forwardPaperCommand,
} from '../../apps/stock/web-api/src/routes/paper-deployments.routes';
import type { PaperDeploymentsService } from '../../apps/stock/web-api/src/services/paper-deployments.service';
import { logger } from '../fixtures/execution';
const id = 'abcdefab-1234-4234-8234-123456789abc',
admin = 'paper-admin-fixture-only-01234567890123456789',
serviceToken = 'paper-service-fixture-only-01234567890123456789',
origin = 'http://localhost:5173';
const status = { deploymentId: id, boundDeploymentId: null, readiness: unboundPaperReadiness() };
const security = (disabled = false) =>
createHttpSecurity({
adminToken: admin,
serviceToken,
environment: 'test',
hostname: '127.0.0.1',
origins: [origin],
browserSessions: true,
disabled,
});
const json = (token = admin, extra: Record<string, string> = {}) => ({
method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', ...extra },
body: '{}',
});
function fixture(disabled = false) {
const events: string[] = [],
host = {
async bind(value: string) {
events.push('bind:' + value);
return status;
},
async activate(value: string) {
events.push('activate:' + value);
return status;
},
async halt(value: string) {
events.push('halt:' + value);
return status;
},
async status() {
return status;
},
} as unknown as PaperDeploymentHost;
const orchestrator = new Hono();
security(disabled).mount(orchestrator);
orchestrator.route('/api/paper/deployments', createPaperDeploymentHostRoutes(host, [origin]));
orchestrator.route(
'/api/paper',
createPaperRoutes({ logger, custom: {} }, { origins: [origin] })
);
const api = new Hono();
security(disabled).mount(api);
const custody = {
async authorizeCommand(value: string) {
events.push('authorize:' + value);
},
async get() {
return {};
},
async list() {
return [];
},
} as unknown as PaperDeploymentsService;
let forwarded: Request | undefined;
let forwardedInit: RequestInit | undefined;
const transport = async (url: string | URL | Request, init?: RequestInit) => {
forwardedInit = init;
forwarded = new Request(url, init);
return orchestrator.fetch(forwarded);
};
api.route(
'/',
createPaperDeploymentRoutes(
{ logger },
{
service: custody,
origin: 'http://paper.internal',
origins: [origin],
request: transport as typeof fetch,
}
)
);
return {
api,
orchestrator,
events,
forwarded: () => forwarded,
forwardedInit: () => forwardedInit,
};
}
test('original human bearer is verified by both endpoints, normalizes IDs, and never substitutes service credentials', async () => {
const f = fixture(),
response = await f.api.request(`/api/v2/paper-deployments/${id.toUpperCase()}/bind`, json());
expect(response.status).toBe(200);
expect(response.headers.get('cache-control')).toBe('no-store');
expect(await response.json()).toEqual(status);
expect(f.events).toEqual(['authorize:' + id, 'bind:' + id]);
expect(f.forwarded()?.headers.get('authorization')).toBe('Bearer ' + admin);
expect(f.forwardedInit()?.redirect).toBe('error');
for (const token of [serviceToken, 'sb-research.' + id + '.untrusted']) {
expect((await f.api.request(`/api/v2/paper-deployments/${id}/bind`, json(token))).status).toBe(
403
);
expect(
(await f.orchestrator.request(`/api/paper/deployments/${id}/bind`, json(token))).status
).toBe(403);
}
expect(f.events).toHaveLength(2);
});
test('signed browser session keeps original Origin and is independently verified upstream', async () => {
const f = fixture(),
login = await f.api.request('/api/auth/session', {
method: 'POST',
headers: { Origin: origin, 'Content-Type': 'application/json' },
body: JSON.stringify({ token: admin }),
});
expect(login.status).toBe(200);
const cookie = login.headers.get('set-cookie')?.split(';')[0];
expect(cookie).toBeDefined();
const response = await f.api.request(`/api/v2/paper-deployments/${id}/activate`, {
method: 'POST',
headers: { Cookie: cookie!, Origin: origin, 'Content-Type': 'application/json' },
body: '{}',
});
expect(response.status).toBe(200);
expect(f.forwarded()?.headers.get('cookie')).toBe(cookie!);
expect(f.forwarded()?.headers.get('origin')).toBe(origin);
expect(f.forwarded()?.headers.has('authorization')).toBe(false);
for (const app of [f.api, f.orchestrator]) {
const prefix = app === f.api ? '/api/v2/paper-deployments' : '/api/paper/deployments';
expect(
(
await app.request(
`${prefix}/${id}/bind`,
json(admin, { Origin: 'https://untrusted.invalid' })
)
).status
).toBe(403);
}
expect(f.events).toHaveLength(2);
});
test('auth-disabled development bypass cannot promote or activate through either endpoint or old direct activation', async () => {
const f = fixture(true);
expect((await f.api.request(`/api/v2/paper-deployments/${id}/bind`, json())).status).toBe(403);
expect(
(await f.orchestrator.request(`/api/paper/deployments/${id}/activate`, json())).status
).toBe(403);
expect((await f.orchestrator.request('/api/paper/activate', json())).status).toBe(403);
expect(f.events).toEqual([]);
});
test('unconfigured fixed origin and mismatched upstream identity fail honestly without arbitrary routing', async () => {
const request = new Request('http://web/api', { headers: { Authorization: 'Bearer ' + admin } });
await expect(forwardPaperCommand(request, id, 'bind', {}, {})).rejects.toThrow('not configured');
for (const origin of [
'file:///tmp/private',
'http://user:pass@paper.test',
'http://paper/other',
'http://paper?token=x',
]) {
await expect(forwardPaperCommand(request, id, 'bind', {}, { origin })).rejects.toThrow(
'fixed HTTP origin'
);
}
await expect(
forwardPaperCommand(
request,
id,
'bind',
{},
{
origin: 'http://paper',
request: async () =>
Response.json({ ...status, deploymentId: '11111111-1111-4111-8111-111111111111' }),
}
)
).rejects.toThrow('another deployment');
});
test('missing upstream origin policy rejects browser command even with valid operator token', async () => {
const app = new Hono();
security().mount(app);
app.route('/api/paper/deployments', createPaperDeploymentHostRoutes(undefined, []));
const response = await app.request(
`/api/paper/deployments/${id}/bind`,
json(admin, { Origin: origin })
);
expect(response.status).toBe(403);
expect(await response.json()).toEqual({
error: 'Paper commands require an explicitly configured trusted Origin',
});
});
test('unbound legacy readiness remains truthful and never creates an account or imports a program', async () => {
let calls = 0;
const unexpected = async () => {
calls++;
throw new Error('No persistence on unbound readiness');
};
const host = new PaperDeploymentHost({
database: { transaction: unexpected },
repository: { initialize: unexpected, transact: unexpected },
});
const app = new Hono();
security().mount(app);
app.route(
'/api/paper',
createPaperRoutes({ logger, custom: {} }, { deploymentHost: host, origins: [origin] })
);
const response = await app.request('/api/paper/readiness', {
headers: { Authorization: `Bearer ${admin}` },
});
expect(response.status).toBe(200);
expect(await response.json()).toEqual(unboundPaperReadiness());
expect(calls).toBe(0);
});