236 lines
8.3 KiB
TypeScript
236 lines
8.3 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
import { getLogger } from '@stock-bot/logger';
|
|
import { PostgreSQLClient } from '@stock-bot/postgres';
|
|
import {
|
|
backtestRequestFromDefinition,
|
|
parseBacktestRequest,
|
|
} from '@stock-bot/stock-config/backtest';
|
|
import type { StrategyVersionPackage } from '@stock-bot/types';
|
|
import {
|
|
builtinCatalogDescriptors,
|
|
builtinStrategy,
|
|
canonicalStrategyJson,
|
|
parseStrategyVersionPackage,
|
|
validateStrategyParameters,
|
|
} from '../../apps/stock/config/src/contracts/strategy';
|
|
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
|
import {
|
|
createHttpSecurity,
|
|
getCredentialHttpPrincipal,
|
|
getVerifiedHttpPrincipal,
|
|
} from '../../libs/core/di/src/http/security';
|
|
|
|
function packageFor(index = 0): StrategyVersionPackage {
|
|
const descriptor = builtinCatalogDescriptors[index]!;
|
|
return {
|
|
version: 1,
|
|
program: structuredClone(descriptor.program),
|
|
artifact: {
|
|
format: 'esm-bundle/v1',
|
|
entryExport: descriptor.entryExport,
|
|
content: 'throw new Error("must never execute")',
|
|
sha256: 'a'.repeat(64),
|
|
},
|
|
dependencyLock: { format: 'bun-lock/v1', content: 'lock-bytes', sha256: 'b'.repeat(64) },
|
|
parameterSchema: structuredClone(descriptor.parameterSchema),
|
|
source: { revision: 'c'.repeat(40), dirty: true },
|
|
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
|
};
|
|
}
|
|
const mean = {
|
|
lookbackPeriod: 3,
|
|
trendPeriod: 5,
|
|
momentumPeriod: 1,
|
|
volatilityPeriod: 2,
|
|
entryZScore: 1,
|
|
exitZScore: 0.5,
|
|
minTrendReturn: -0.1,
|
|
minMomentumReturn: 0,
|
|
maxVolatility: 0.01,
|
|
minNotionalVolume: '0',
|
|
regimeFilter: 'volatility',
|
|
};
|
|
|
|
describe('retained strategy contracts', () => {
|
|
test('schema_validation retains exact builtin defaults, strict keys and cross-field rules', () => {
|
|
const sma = parseStrategyVersionPackage(packageFor());
|
|
expect(validateStrategyParameters(sma, {})).toEqual({ fastPeriod: 5, slowPeriod: 15 });
|
|
for (const params of [
|
|
{ fastPeriod: 15, slowPeriod: 5 },
|
|
{ fastPeriod: 0 },
|
|
{ slowPeriod: 10001 },
|
|
{ typo: 1 },
|
|
]) {
|
|
expect(() => validateStrategyParameters(sma, params)).toThrow();
|
|
}
|
|
const mr = parseStrategyVersionPackage(packageFor(1));
|
|
expect(validateStrategyParameters(mr, mean).minNotionalVolume).toBe('0.00000000');
|
|
for (const params of [
|
|
{ ...mean, trendPeriod: 3 },
|
|
{ ...mean, exitZScore: 2 },
|
|
{ ...mean, minNotionalVolume: '-1' },
|
|
{ ...mean, regimeFilter: 'learned' },
|
|
]) {
|
|
expect(() => validateStrategyParameters(mr, params)).toThrow();
|
|
}
|
|
expect(() =>
|
|
parseStrategyVersionPackage({
|
|
...sma,
|
|
parameterSchema: { ...sma.parameterSchema, required: ['fastPeriod'] },
|
|
})
|
|
).toThrow('cannot be overridden');
|
|
expect(() =>
|
|
parseStrategyVersionPackage({
|
|
...sma,
|
|
program: { ...sma.program, checkpointVersion: 'other' },
|
|
})
|
|
).toThrow('cannot be overridden');
|
|
expect(() => parseStrategyVersionPackage({ ...sma, reviewStatus: 'approved' })).toThrow();
|
|
const reserved = JSON.parse('{"__proto__":{"type":"number"}}');
|
|
expect(() =>
|
|
parseStrategyVersionPackage({
|
|
...sma,
|
|
parameterSchema: { ...sma.parameterSchema, properties: reserved },
|
|
})
|
|
).toThrow('Unsupported strategy metadata key');
|
|
});
|
|
test('candidate scalar schema validates without executing code or arbitrary validators', () => {
|
|
const pkg = {
|
|
...packageFor(),
|
|
program: {
|
|
strategyId: 'candidate',
|
|
strategyVersion: 'v1',
|
|
apiVersion: 'candidate/v1',
|
|
checkpointVersion: 'v1',
|
|
},
|
|
parameterSchema: {
|
|
version: 1 as const,
|
|
type: 'object' as const,
|
|
additionalProperties: false as const,
|
|
properties: {
|
|
window: { type: 'integer' as const, minimum: 2, default: 3 },
|
|
enabled: { type: 'boolean' as const },
|
|
mode: { type: 'string' as const, enum: ['a', 'b'] },
|
|
},
|
|
required: ['enabled', 'mode'],
|
|
},
|
|
};
|
|
const parsed = parseStrategyVersionPackage(pkg);
|
|
expect(validateStrategyParameters(parsed, { enabled: true, mode: 'a' })).toEqual({
|
|
window: 3,
|
|
enabled: true,
|
|
mode: 'a',
|
|
});
|
|
for (const input of [
|
|
{ enabled: 1, mode: 'a' },
|
|
{ enabled: true, mode: 'c' },
|
|
{ enabled: true },
|
|
{ enabled: true, mode: 'a', window: 1.5 },
|
|
{ enabled: true, mode: 'a', extra: 0 },
|
|
]) {
|
|
expect(() => validateStrategyParameters(parsed, input)).toThrow();
|
|
}
|
|
for (const schema of [
|
|
{ ...pkg.parameterSchema, required: ['missing'] },
|
|
{ ...pkg.parameterSchema, properties: { x: { type: 'number', minimum: 5, maximum: 1 } } },
|
|
{ ...pkg.parameterSchema, properties: { x: { type: 'string', pattern: '(.*)*' } } },
|
|
{ ...pkg.parameterSchema, properties: { x: { type: 'number', default: 'oops' } } },
|
|
]) {
|
|
expect(() => parseStrategyVersionPackage({ ...pkg, parameterSchema: schema })).toThrow();
|
|
}
|
|
});
|
|
test('metadata fingerprints are stable across object key order; arrays and bytes remain significant', () => {
|
|
expect(canonicalStrategyJson({ b: 2, a: { d: 4, c: 3 } })).toBe(
|
|
canonicalStrategyJson({ a: { c: 3, d: 4 }, b: 2 })
|
|
);
|
|
expect(canonicalStrategyJson({ a: ['a', 'b'] })).not.toBe(
|
|
canonicalStrategyJson({ a: ['b', 'a'] })
|
|
);
|
|
expect(builtinStrategy('Moving Average')).toBe('sma_crossover');
|
|
expect(builtinStrategy('mean-reversion')).toBe('mean_reversion');
|
|
});
|
|
});
|
|
|
|
test('catalog credentials exclude loopback bypass while preserving prior route identities', async () => {
|
|
const options = {
|
|
adminToken: 'operator-test-credential-not-real-123456',
|
|
serviceToken: 'service-test-credential-not-real-123456',
|
|
};
|
|
const app = new Hono();
|
|
createHttpSecurity(options).mount(app);
|
|
// Explicit route callbacks keep the Hono context type local to this router.
|
|
app.post('/api/identity', c =>
|
|
c.json({
|
|
credential: getCredentialHttpPrincipal(c.req.raw),
|
|
legacy: getVerifiedHttpPrincipal(c.req.raw),
|
|
})
|
|
);
|
|
for (const [token, principal] of [
|
|
[options.adminToken, 'operator'],
|
|
[options.serviceToken, 'service'],
|
|
]) {
|
|
const response = await app.request('/api/identity', {
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${token}`, 'X-Principal': 'operator' },
|
|
});
|
|
expect(await response.json()).toEqual({ credential: principal, legacy: principal });
|
|
}
|
|
const bypass = new Hono();
|
|
createHttpSecurity({ disabled: true }).mount(bypass);
|
|
bypass.post('/api/identity', c =>
|
|
c.json({
|
|
credential: getCredentialHttpPrincipal(c.req.raw),
|
|
legacy: getVerifiedHttpPrincipal(c.req.raw),
|
|
})
|
|
);
|
|
expect(await (await bypass.request('/api/identity', { method: 'POST' })).json()).toEqual({
|
|
legacy: 'operator',
|
|
});
|
|
expect(
|
|
getCredentialHttpPrincipal(
|
|
new Request('http://localhost', { headers: { 'X-Principal': 'operator' } })
|
|
)
|
|
).toBeUndefined();
|
|
});
|
|
|
|
const definition = {
|
|
name: 'legacy',
|
|
strategy: 'moving-average',
|
|
symbols: ['A.US'],
|
|
startDate: '2024-01-01T00:00:00Z',
|
|
endDate: '2024-02-01T00:00:00Z',
|
|
initialCapital: 1000,
|
|
};
|
|
test('legacy requests reject catalog references before parsers or routes discard them', async () => {
|
|
for (const extra of [
|
|
{ strategyVersionId: 'retained' },
|
|
{ config: { strategyVersionId: 'retained' } },
|
|
{ strategies: [{ name: 'sma', config: { strategyVersionId: 'retained' } }] },
|
|
]) {
|
|
expect(() => backtestRequestFromDefinition({ ...definition, ...extra })).toThrow(
|
|
'not supported'
|
|
);
|
|
expect(() =>
|
|
parseBacktestRequest({ ...definition, mode: 'backtest', dataFrequency: '1d', ...extra })
|
|
).toThrow('not supported');
|
|
}
|
|
const app = createBacktestV2Routes({
|
|
postgres: new PostgreSQLClient({
|
|
host: 'unused',
|
|
port: 5432,
|
|
database: 'unused',
|
|
username: 'unused',
|
|
password: 'unused',
|
|
}),
|
|
logger: getLogger('catalog-contract'),
|
|
});
|
|
const response = await app.request(
|
|
'/api/v2/backtests/00000000-0000-4000-8000-000000000001/runs',
|
|
{ method: 'POST', body: JSON.stringify({ strategyVersionId: 'retained' }) }
|
|
);
|
|
expect(response.status).toBe(400);
|
|
expect(await response.json()).toEqual({
|
|
error: 'Retained strategy versions are not supported by the current backtest runner',
|
|
});
|
|
});
|