feat(research): retain immutable strategy versions and review history
This commit is contained in:
parent
b106c1ca85
commit
4a2e5ad362
36 changed files with 3236 additions and 148 deletions
207
test/integration/strategy-catalog-api.test.ts
Normal file
207
test/integration/strategy-catalog-api.test.ts
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes';
|
||||
|
||||
const tokens = {
|
||||
operator: 'catalog-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'catalog-service-fixture-not-a-real-secret-1234',
|
||||
read: 'catalog-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
function fixture(security: 'enabled' | 'disabled' | 'absent' = 'enabled') {
|
||||
const database = {
|
||||
query: mock(async () => {
|
||||
throw new Error('Rejected request reached storage');
|
||||
}),
|
||||
transaction: mock(async () => {
|
||||
throw new Error('Rejected request reached transaction');
|
||||
}),
|
||||
};
|
||||
const logger = { error: mock(() => {}) };
|
||||
const app = new Hono();
|
||||
if (security !== 'absent') {
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
disabled: security === 'disabled',
|
||||
}).mount(app);
|
||||
}
|
||||
app.route(
|
||||
'/',
|
||||
createStrategyRoutes({ postgres: database, logger } as unknown as IServiceContainer)
|
||||
);
|
||||
app.post('/api/v2/unrelated', c => c.json({ ok: true }));
|
||||
return {
|
||||
database,
|
||||
app,
|
||||
request(
|
||||
path: string,
|
||||
body: unknown,
|
||||
role?: keyof typeof tokens,
|
||||
extra: Record<string, string> = {},
|
||||
method = 'POST'
|
||||
) {
|
||||
return app.request(`/api/v2/${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
||||
'Content-Type': 'application/json',
|
||||
...extra,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
const strategyId = randomUUID();
|
||||
const versionId = randomUUID();
|
||||
const writes = [
|
||||
{ path: 'strategies', body: { name: 'Candidate' } },
|
||||
{ path: `strategies/${strategyId}`, body: { archived: true }, method: 'PATCH' },
|
||||
{ path: `strategies/${strategyId}/versions`, body: { package: {} } },
|
||||
{ path: `strategy-versions/${versionId}/clone`, body: { name: 'Clone' } },
|
||||
{
|
||||
path: `strategy-versions/${versionId}/reviews`,
|
||||
body: { decision: 'approve', reason: 'Review' },
|
||||
},
|
||||
{ path: `strategy-versions/${versionId}/validate`, body: { parameters: {} } },
|
||||
];
|
||||
|
||||
describe('strategy catalog HTTP credential boundary', () => {
|
||||
test('NUL and unpaired Unicode surrogates reject before storage instead of failing JSONB persistence', async () => {
|
||||
const f = fixture();
|
||||
for (const text of ['bad\u0000text', 'bad\ud800text', 'bad\udc00text']) {
|
||||
const cases = [
|
||||
{ path: 'strategies', body: { name: text } },
|
||||
{ path: `strategies/${strategyId}`, body: { description: text }, method: 'PATCH' },
|
||||
{
|
||||
path: `strategies/${strategyId}/versions`,
|
||||
body: { package: { artifact: { content: text } } },
|
||||
},
|
||||
{ path: `strategy-versions/${versionId}/clone`, body: { name: text } },
|
||||
{
|
||||
path: `strategy-versions/${versionId}/reviews`,
|
||||
body: { decision: 'approve', reason: text },
|
||||
},
|
||||
];
|
||||
for (const item of cases) {
|
||||
expect(
|
||||
(
|
||||
await f.request(
|
||||
item.path,
|
||||
item.body,
|
||||
'operator',
|
||||
{ 'Idempotency-Key': 'unicode' },
|
||||
item.method
|
||||
)
|
||||
).status
|
||||
).toBe(400);
|
||||
}
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('catalog middleware does not alter unrelated routes on a shared listener', async () => {
|
||||
const f = fixture('disabled');
|
||||
const result = await f.request('unrelated', {});
|
||||
expect(result.status).toBe(200);
|
||||
expect(result.headers.get('Cache-Control')).toBeNull();
|
||||
});
|
||||
test('every mutation requires verified credentials even with loopback auth bypass or no middleware', async () => {
|
||||
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
||||
const f = fixture(mode);
|
||||
for (const item of writes) {
|
||||
const result = await f.request(
|
||||
item.path,
|
||||
item.body,
|
||||
undefined,
|
||||
{ 'X-Actor': 'operator', 'X-Principal': 'operator', 'Idempotency-Key': 'forged' },
|
||||
item.method
|
||||
);
|
||||
expect(result.status).toBe(401);
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('read credentials cannot mutate and service credentials cannot append human review', async () => {
|
||||
const f = fixture();
|
||||
for (const item of writes) {
|
||||
expect((await f.request(item.path, item.body, 'read', {}, item.method)).status).toBe(403);
|
||||
}
|
||||
const review = await f.request(
|
||||
`strategy-versions/${versionId}/reviews?actor=operator`,
|
||||
{ decision: 'approve', reason: 'forged', actor: 'operator' },
|
||||
'service',
|
||||
{ 'X-Principal': 'operator' }
|
||||
);
|
||||
expect(review.status).toBe(403);
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('strict transport bodies reject privilege fields and missing or malformed receipt keys before storage', async () => {
|
||||
const f = fixture();
|
||||
const cases = [
|
||||
{ path: 'strategies', body: { name: 'Candidate', ownerPrincipal: 'operator' } },
|
||||
{
|
||||
path: `strategies/${strategyId}`,
|
||||
body: { name: 'Rename', origin: 'builtin' },
|
||||
method: 'PATCH',
|
||||
},
|
||||
{
|
||||
path: `strategies/${strategyId}/versions`,
|
||||
body: { package: {}, origin: 'builtin' },
|
||||
key: 'key',
|
||||
},
|
||||
{ path: `strategies/${strategyId}/versions`, body: { package: {} } },
|
||||
{ path: `strategies/${strategyId}/versions`, body: { package: {} }, key: 'has spaces' },
|
||||
{
|
||||
path: `strategy-versions/${versionId}/clone`,
|
||||
body: { name: 'Copy', reviewed: true },
|
||||
key: 'key',
|
||||
},
|
||||
{
|
||||
path: `strategy-versions/${versionId}/reviews`,
|
||||
body: { decision: 'approve', reason: 'Review', actor: 'operator' },
|
||||
},
|
||||
{ path: `strategy-versions/${versionId}/validate`, body: { parameters: {}, execute: true } },
|
||||
];
|
||||
for (const item of cases) {
|
||||
expect(
|
||||
(
|
||||
await f.request(
|
||||
item.path,
|
||||
item.body,
|
||||
'operator',
|
||||
item.key ? { 'Idempotency-Key': item.key } : {},
|
||||
item.method
|
||||
)
|
||||
).status
|
||||
).toBe(400);
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('malformed JSON is a client error and no seed or execution endpoint exists', async () => {
|
||||
const f = fixture();
|
||||
const response = await f.app.request('/api/v2/strategies', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${tokens.operator}` },
|
||||
body: '{',
|
||||
});
|
||||
expect(response.status).toBe(400);
|
||||
for (const path of [
|
||||
'strategies/seed',
|
||||
`strategy-versions/${versionId}/execute`,
|
||||
`strategy-versions/${versionId}/deploy`,
|
||||
]) {
|
||||
expect((await f.request(path, {}, 'operator')).status).toBe(404);
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
236
test/integration/strategy-version-contract.test.ts
Normal file
236
test/integration/strategy-version-contract.test.ts
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
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',
|
||||
});
|
||||
});
|
||||
|
|
@ -18,6 +18,7 @@ const migrations = [
|
|||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'15-canonical-paper-intents.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
116
test/postgres/strategy-catalog-seed.test.ts
Normal file
116
test/postgres/strategy-catalog-seed.test.ts
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { seedBuiltinCatalog } from '../../scripts/seed-builtin-strategies';
|
||||
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
test('trusted local seed retains real bundles and exposes only reviewed catalog operations over HTTP', async () => {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable stock_bot_safety database required');
|
||||
}
|
||||
const schema = `stock_bot_safety_seed_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: url });
|
||||
let pool: Pool | undefined;
|
||||
try {
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
|
||||
await pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/16-strategy-catalog.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
getLogger('seed-fixture')
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const container = { postgres, logger: getLogger('catalog-seed') };
|
||||
const service = new StrategyCatalogService(container);
|
||||
const versions = await seedBuiltinCatalog(service);
|
||||
expect(versions).toHaveLength(2);
|
||||
expect(
|
||||
versions.every(v => v.origin === 'builtin' && v.reviewStatus === 'pending' && !v.runnable)
|
||||
).toBe(true);
|
||||
expect((await seedBuiltinCatalog(service)).map(v => v.id)).toEqual(versions.map(v => v.id));
|
||||
expect((await pool.query('SELECT count(*) FROM strategies')).rows[0].count).toBe('2');
|
||||
expect((await pool.query('SELECT count(*) FROM strategy_versions')).rows[0].count).toBe('2');
|
||||
const security = {
|
||||
adminToken: 'operator-catalog-fixture-not-real-123456',
|
||||
serviceToken: 'service-catalog-fixture-not-real-123456',
|
||||
environment: 'test',
|
||||
};
|
||||
const app = createRoutes(container, createHttpSecurity(security));
|
||||
const request = (path: string, body?: unknown, operator = false, key?: string) =>
|
||||
app.request(path, {
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${operator ? security.adminToken : security.serviceToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
...(key ? { 'Idempotency-Key': key } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
const selected = versions.find(v => v.package.program.strategyId === 'sma_crossover')!;
|
||||
const path = `/api/v2/strategy-versions/${selected.id}`;
|
||||
const detail = await (await request(path)).json();
|
||||
expect(detail.version.package.artifact.content).toBeUndefined();
|
||||
expect(detail.version.package.dependencyLock.content).toBeUndefined();
|
||||
expect(detail.version.runnable).toBe(false);
|
||||
const artifact = await (await request(`${path}/artifact`)).json();
|
||||
expect(createHash('sha256').update(artifact.package.artifact.content).digest('hex')).toBe(
|
||||
artifact.package.artifact.sha256
|
||||
);
|
||||
const invalid = await request(`${path}/validate`, {
|
||||
parameters: { fastPeriod: 20, slowPeriod: 10 },
|
||||
});
|
||||
expect(invalid.status).toBe(400);
|
||||
const valid = await request(`${path}/validate`, { parameters: {} });
|
||||
expect(valid.status).toBe(200);
|
||||
expect((await valid.json()).parameters).toEqual({ fastPeriod: 5, slowPeriod: 15 });
|
||||
expect(
|
||||
(await request(`${path}/reviews`, { decision: 'approve', reason: 'service cannot approve' }))
|
||||
.status
|
||||
).toBe(403);
|
||||
const approved = await request(
|
||||
`${path}/reviews`,
|
||||
{ decision: 'approve', reason: 'fixture operator reviewed bundle' },
|
||||
true
|
||||
);
|
||||
expect(approved.status).toBe(201);
|
||||
const reviewed = await approved.json();
|
||||
expect(reviewed.version.reviewStatus).toBe('approved');
|
||||
expect(reviewed.version.runnable).toBe(false);
|
||||
// Even exact built-in bytes uploaded through HTTP do not self-register as trusted code.
|
||||
const upload = await request(
|
||||
`/api/v2/strategies/${selected.strategyId}/versions`,
|
||||
{ package: artifact.package },
|
||||
false,
|
||||
'candidate-copy'
|
||||
);
|
||||
expect(upload.status).toBe(201);
|
||||
const candidate = await upload.json();
|
||||
expect(candidate.version.origin).toBe('candidate');
|
||||
expect(candidate.version.parentVersionId).toBe(selected.id);
|
||||
expect(candidate.version.reviewStatus).toBe('pending');
|
||||
expect(candidate.version.runnable).toBe(false);
|
||||
const replay = await request(
|
||||
`/api/v2/strategies/${selected.strategyId}/versions`,
|
||||
{ package: artifact.package },
|
||||
false,
|
||||
'candidate-copy'
|
||||
);
|
||||
expect((await replay.json()).version.id).toBe(candidate.version.id);
|
||||
} finally {
|
||||
await pool?.end();
|
||||
await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
}
|
||||
}, 30000);
|
||||
532
test/postgres/strategy-catalog.test.ts
Normal file
532
test/postgres/strategy-catalog.test.ts
Normal file
|
|
@ -0,0 +1,532 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import {
|
||||
builtinCatalogDescriptors,
|
||||
parseStrategyVersionPackage,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('strategy-catalog-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
const migration = readFileSync(
|
||||
new URL('../../database/postgres/init/16-strategy-catalog.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const tokens = {
|
||||
operator: 'catalog-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'catalog-service-fixture-not-a-real-secret-1234',
|
||||
read: 'catalog-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
const hash = (text: string) => createHash('sha256').update(text).digest('hex');
|
||||
function candidate(
|
||||
content = 'throw new Error("ARTIFACT_MUST_NEVER_EXECUTE");'
|
||||
): StrategyVersionPackage {
|
||||
const lock = '{"lockfileVersion":1,"workspaces":{}}';
|
||||
return {
|
||||
version: 1,
|
||||
program: {
|
||||
strategyId: 'candidate-fixture',
|
||||
strategyVersion: 'v1',
|
||||
apiVersion: 'canonical-ts/v1',
|
||||
checkpointVersion: 'v1',
|
||||
},
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: 'createStrategy',
|
||||
content,
|
||||
sha256: hash(content),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: lock, sha256: hash(lock) },
|
||||
parameterSchema: {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
lookback: { type: 'integer', minimum: 1, default: 3 },
|
||||
mode: { type: 'string', enum: ['long', 'flat'] },
|
||||
},
|
||||
required: ['mode'],
|
||||
},
|
||||
source: { revision: 'a'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
};
|
||||
}
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_catalog_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
await pool.query(migration);
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { configurable: true, value: pool.query.bind(pool) });
|
||||
const api = new StrategyCatalogService({ postgres, logger });
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
}).mount(app);
|
||||
app.route('/', createStrategyRoutes({ postgres, logger }));
|
||||
return {
|
||||
pool,
|
||||
postgres,
|
||||
api,
|
||||
app,
|
||||
request(
|
||||
path: string,
|
||||
role: keyof typeof tokens,
|
||||
body?: unknown,
|
||||
key?: string,
|
||||
method = body === undefined ? 'GET' : 'POST'
|
||||
) {
|
||||
return app.request(`/api/v2/${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens[role]}`,
|
||||
'Content-Type': 'application/json',
|
||||
...(key ? { 'Idempotency-Key': key } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('immutable strategy catalog on real PostgreSQL', () => {
|
||||
test('valid UTF-8 metadata and artifact content retain exact bytes and hashes', async () => {
|
||||
const f = await fixture();
|
||||
const name = 'Research 🚀 東京';
|
||||
const s = await f.api.createStrategy({ name }, 'service');
|
||||
const pkg = candidate('export const label = "📈 café";');
|
||||
const v = await f.api.publishVersion(s.id, pkg, null, 'service', 'unicode');
|
||||
expect((await f.api.getStrategy(s.id)).name).toBe(name);
|
||||
expect(await f.api.getVersionArtifact(v.id)).toEqual(pkg);
|
||||
expect(
|
||||
(await f.api.reviewVersion(v.id, { decision: 'approve', reason: 'Reviewed 📈' }, 'operator'))
|
||||
.reviewStatus
|
||||
).toBe('approved');
|
||||
expect((await f.api.getVersionReviews(v.id))[0]!.reason).toBe('Reviewed 📈');
|
||||
});
|
||||
test('retains exact artifact bytes without execution, projects lightweight metadata and validates parameters only', async () => {
|
||||
const f = await fixture();
|
||||
const s = await f.api.createStrategy({ name: 'Candidate' }, 'service');
|
||||
const pkg = candidate();
|
||||
const v = await f.api.publishVersion(s.id, pkg, null, 'service', 'publish-1');
|
||||
expect(s).toMatchObject({ ownerPrincipal: 'service', updatedBy: 'service' });
|
||||
expect(
|
||||
await f.api.updateStrategy(s.id, { description: 'Operator note' }, 'operator')
|
||||
).toMatchObject({ ownerPrincipal: 'service', updatedBy: 'operator' });
|
||||
expect(v).toMatchObject({
|
||||
ordinal: 1,
|
||||
createdBy: 'service',
|
||||
origin: 'candidate',
|
||||
reviewStatus: 'pending',
|
||||
runnable: false,
|
||||
});
|
||||
expect(v.reason).toContain('A02');
|
||||
expect(v.package.artifact).not.toHaveProperty('content');
|
||||
expect(v.package.dependencyLock).not.toHaveProperty('content');
|
||||
expect(await f.api.getVersionArtifact(v.id)).toEqual(pkg);
|
||||
expect(await f.api.validateVersionParameters(v.id, { mode: 'long' })).toMatchObject({
|
||||
parameters: { mode: 'long', lookback: 3 },
|
||||
runnable: false,
|
||||
});
|
||||
for (const invalid of [
|
||||
{},
|
||||
{ mode: 'short' },
|
||||
{ mode: 'long', lookback: 0 },
|
||||
{ mode: 'long', extra: true },
|
||||
{ mode: 'long', lookback: 1.5 },
|
||||
]) {
|
||||
await expect(f.api.validateVersionParameters(v.id, invalid)).rejects.toMatchObject({
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
const metadataQueries: string[] = [];
|
||||
const realQuery = f.pool.query.bind(f.pool);
|
||||
Object.defineProperty(f.postgres, 'query', {
|
||||
configurable: true,
|
||||
value: async (text: string, values: unknown[]) => {
|
||||
metadataQueries.push(text);
|
||||
const result = await realQuery(text, values);
|
||||
for (const row of result.rows) {
|
||||
expect(row).not.toHaveProperty('envelope');
|
||||
if (row.package) {
|
||||
expect(row.package.artifact).not.toHaveProperty('content');
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
await f.api.listVersions(s.id);
|
||||
await f.api.getVersion(v.id);
|
||||
expect(
|
||||
metadataQueries
|
||||
.filter(text => text.includes('FROM strategy_versions'))
|
||||
.every(text => text.includes("#- '{artifact,content}'"))
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test('hash and schema failures are atomic, and missing references do not leave versions', async () => {
|
||||
const f = await fixture();
|
||||
const s = await f.api.createStrategy({ name: 'Invalid submissions' }, 'operator');
|
||||
const badHash = candidate();
|
||||
badHash.artifact.content += '\nchanged';
|
||||
const badLock = candidate();
|
||||
badLock.dependencyLock.content += 'changed';
|
||||
const badSchema = candidate();
|
||||
badSchema.parameterSchema.required.push('missing');
|
||||
for (const [index, pkg] of [badHash, badLock, badSchema].entries()) {
|
||||
await expect(
|
||||
f.api.publishVersion(s.id, pkg, null, 'operator', `bad-${index}`)
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
}
|
||||
await expect(
|
||||
f.api.publishVersion(s.id, candidate(), randomUUID(), 'operator', 'missing-parent')
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
expect(await f.api.listVersions(s.id)).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('receipt replay is key-order independent, survives archive, and rejects changed intent', async () => {
|
||||
const f = await fixture();
|
||||
const s = await f.api.createStrategy({ name: 'Receipts' }, 'operator');
|
||||
const pkg = candidate();
|
||||
const v = await f.api.publishVersion(s.id, pkg, null, 'operator', 'same');
|
||||
const reordered = {
|
||||
...pkg,
|
||||
program: {
|
||||
checkpointVersion: pkg.program.checkpointVersion,
|
||||
apiVersion: pkg.program.apiVersion,
|
||||
strategyVersion: pkg.program.strategyVersion,
|
||||
strategyId: pkg.program.strategyId,
|
||||
},
|
||||
};
|
||||
expect((await f.api.publishVersion(s.id, reordered, null, 'operator', 'same')).id).toBe(v.id);
|
||||
const next = await f.api.publishVersion(s.id, pkg, null, 'operator', 'intentional-new');
|
||||
expect(next).toMatchObject({ ordinal: 2, parentVersionId: v.id });
|
||||
const fork = await f.api.publishVersion(s.id, pkg, v.id, 'operator', 'older-parent');
|
||||
expect(fork).toMatchObject({ ordinal: 3, parentVersionId: v.id });
|
||||
const foreign = await f.api.createStrategy({ name: 'Foreign parent' }, 'operator');
|
||||
await expect(
|
||||
f.api.publishVersion(foreign.id, pkg, v.id, 'operator', 'cross-parent-invalid')
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
await f.api.updateStrategy(s.id, { archived: true }, 'operator');
|
||||
expect((await f.api.publishVersion(s.id, pkg, null, 'operator', 'same')).id).toBe(v.id);
|
||||
await expect(
|
||||
f.api.publishVersion(s.id, candidate('different'), null, 'operator', 'same')
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
await expect(
|
||||
f.api.publishVersion(s.id, pkg, null, 'operator', 'new-after-archive')
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(await f.api.listVersions(s.id)).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('parallel publication serializes ordinals and global actor receipts across strategies', async () => {
|
||||
const f = await fixture();
|
||||
const s = await f.api.createStrategy({ name: 'Parallel' }, 'operator');
|
||||
const pkg = candidate();
|
||||
const repeated = await Promise.all(
|
||||
Array.from({ length: 5 }, () => f.api.publishVersion(s.id, pkg, null, 'operator', 'repeat'))
|
||||
);
|
||||
expect(new Set(repeated.map(v => v.id)).size).toBe(1);
|
||||
const unique = await Promise.all(
|
||||
Array.from({ length: 4 }, (_, index) =>
|
||||
f.api.publishVersion(s.id, pkg, null, 'operator', `unique-${index}`)
|
||||
)
|
||||
);
|
||||
expect(unique.map(v => v.ordinal).sort()).toEqual([2, 3, 4, 5]);
|
||||
const other = await f.api.createStrategy({ name: 'Other' }, 'operator');
|
||||
const conflict = await Promise.allSettled(
|
||||
[s, other].map(target =>
|
||||
f.api.publishVersion(target.id, pkg, null, 'operator', 'cross-parent')
|
||||
)
|
||||
);
|
||||
expect(conflict.filter(item => item.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(conflict.find(item => item.status === 'rejected')).toMatchObject({
|
||||
reason: { status: 409 },
|
||||
});
|
||||
// Different credential cohorts have independent receipt namespaces.
|
||||
expect((await f.api.publishVersion(other.id, pkg, null, 'service', 'repeat')).createdBy).toBe(
|
||||
'service'
|
||||
);
|
||||
});
|
||||
|
||||
test('archive row lock prevents a blocked publication from entering an archived strategy', async () => {
|
||||
const f = await fixture();
|
||||
const s = await f.api.createStrategy({ name: 'Archive race' }, 'operator');
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [s.id]);
|
||||
const attempt = f.api.publishVersion(s.id, candidate(), null, 'operator', 'archive-race').then(
|
||||
() => null,
|
||||
error => error
|
||||
);
|
||||
await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [s.id]);
|
||||
await blocker.query('COMMIT');
|
||||
blocker.release();
|
||||
expect(await attempt).toMatchObject({ status: 409 });
|
||||
expect(await f.api.listVersions(s.id)).toEqual([]);
|
||||
});
|
||||
|
||||
test('reviews are explicit human-only append-only evidence, with immutable version and lineage storage', async () => {
|
||||
const f = await fixture();
|
||||
const s = await f.api.createStrategy({ name: 'Audit' }, 'operator');
|
||||
const v = await f.api.publishVersion(s.id, candidate(), null, 'operator', 'audit-version');
|
||||
await expect(
|
||||
f.api.reviewVersion(v.id, { decision: 'approve', reason: 'pretend human' }, 'service')
|
||||
).rejects.toMatchObject({ status: 403 });
|
||||
expect(await f.api.getVersionReviews(v.id)).toHaveLength(0);
|
||||
expect(
|
||||
await f.api.reviewVersion(
|
||||
v.id,
|
||||
{ decision: 'approve', reason: 'Reviewed retained artifact' },
|
||||
'operator'
|
||||
)
|
||||
).toMatchObject({ reviewStatus: 'approved', runnable: false });
|
||||
expect(
|
||||
await f.api.reviewVersion(
|
||||
v.id,
|
||||
{ decision: 'revoke', reason: 'Needs further validation' },
|
||||
'operator'
|
||||
)
|
||||
).toMatchObject({ reviewStatus: 'revoked', runnable: false });
|
||||
expect(
|
||||
(await f.api.getVersionReviews(v.id)).map(event => [
|
||||
event.ordinal,
|
||||
event.decision,
|
||||
event.actor,
|
||||
])
|
||||
).toEqual([
|
||||
[1, 'approve', 'operator'],
|
||||
[2, 'revoke', 'operator'],
|
||||
]);
|
||||
for (const query of [
|
||||
'UPDATE strategy_versions SET ordinal=99',
|
||||
'DELETE FROM strategy_versions',
|
||||
"UPDATE strategy_review_events SET reason='rewrite'",
|
||||
'DELETE FROM strategy_review_events',
|
||||
'DELETE FROM strategies',
|
||||
]) {
|
||||
await expect(f.pool.query(query)).rejects.toThrow('immutable');
|
||||
}
|
||||
await poolMigrationAgain(f.pool);
|
||||
expect(await f.api.getVersionReviews(v.id)).toHaveLength(2);
|
||||
expect(await f.api.getVersionArtifact(v.id)).toEqual(candidate());
|
||||
});
|
||||
|
||||
test('clones retain parent lineage, do not inherit approval, and retry without orphan strategies', async () => {
|
||||
const f = await fixture();
|
||||
const s = await f.api.createStrategy({ name: 'Original' }, 'operator');
|
||||
const v = await f.api.publishVersion(s.id, candidate(), null, 'operator', 'source');
|
||||
await f.api.reviewVersion(v.id, { decision: 'approve', reason: 'Source reviewed' }, 'operator');
|
||||
const clones = await Promise.all(
|
||||
Array.from({ length: 4 }, () =>
|
||||
f.api.cloneVersion(v.id, { name: 'Copy' }, 'service', 'clone')
|
||||
)
|
||||
);
|
||||
expect(new Set(clones.map(item => item.strategy.id)).size).toBe(1);
|
||||
expect(clones[0]!.version).toMatchObject({
|
||||
parentVersionId: v.id,
|
||||
ordinal: 1,
|
||||
origin: 'candidate',
|
||||
reviewStatus: 'pending',
|
||||
runnable: false,
|
||||
});
|
||||
expect(clones[0]!.strategy.ownerPrincipal).toBe('service');
|
||||
expect(await f.api.getVersionReviews(clones[0]!.version.id)).toHaveLength(0);
|
||||
expect(await f.api.listStrategies()).toHaveLength(2);
|
||||
await expect(
|
||||
f.api.cloneVersion(v.id, { name: 'Different copy' }, 'service', 'clone')
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
const revision = await f.api.publishVersion(
|
||||
s.id,
|
||||
candidate('revision'),
|
||||
v.id,
|
||||
'operator',
|
||||
'revision'
|
||||
);
|
||||
expect(revision.parentVersionId).toBe(v.id);
|
||||
expect(revision.reviewStatus).toBe('pending');
|
||||
});
|
||||
|
||||
test('trusted builtin seeding is idempotent and never grants review or execution', async () => {
|
||||
const f = await fixture();
|
||||
const descriptor = builtinCatalogDescriptors[0]!;
|
||||
const base = candidate();
|
||||
const pkg = parseStrategyVersionPackage({
|
||||
...base,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: { ...base.artifact, entryExport: descriptor.entryExport },
|
||||
});
|
||||
const seeded = await Promise.all(
|
||||
Array.from({ length: 3 }, () => f.api.seedBuiltin(descriptor.name, pkg, 'builtin-seed'))
|
||||
);
|
||||
expect(new Set(seeded.map(v => v.id)).size).toBe(1);
|
||||
expect(seeded[0]).toMatchObject({
|
||||
origin: 'builtin',
|
||||
createdBy: 'operator',
|
||||
reviewStatus: 'pending',
|
||||
runnable: false,
|
||||
});
|
||||
expect(seeded[0]!.reason).toContain('R05');
|
||||
expect(await f.api.listStrategies()).toHaveLength(1);
|
||||
await expect(f.api.seedBuiltin('Fake builtin', candidate(), 'fake')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
});
|
||||
expect((await f.api.validateVersionParameters(seeded[0]!.id, {})).parameters).toMatchObject({
|
||||
fastPeriod: 5,
|
||||
slowPeriod: 15,
|
||||
});
|
||||
await expect(
|
||||
f.api.validateVersionParameters(seeded[0]!.id, { fastPeriod: 15, slowPeriod: 5 })
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
const first = seeded[0]!;
|
||||
await f.api.reviewVersion(
|
||||
first.id,
|
||||
{ decision: 'approve', reason: 'Reviewed first build' },
|
||||
'operator'
|
||||
);
|
||||
await f.api.updateStrategy(
|
||||
first.strategyId,
|
||||
{ name: 'Personal SMA', description: 'Retained note' },
|
||||
'service'
|
||||
);
|
||||
const changed = structuredClone(pkg);
|
||||
changed.source.revision = 'b'.repeat(40);
|
||||
const updates = await Promise.all(
|
||||
Array.from({ length: 3 }, () =>
|
||||
f.api.seedBuiltin(descriptor.name, changed, 'builtin-revision')
|
||||
)
|
||||
);
|
||||
expect(new Set(updates.map(v => v.id)).size).toBe(1);
|
||||
expect(updates[0]).toMatchObject({
|
||||
strategyId: first.strategyId,
|
||||
ordinal: 2,
|
||||
parentVersionId: first.id,
|
||||
reviewStatus: 'pending',
|
||||
runnable: false,
|
||||
});
|
||||
expect(await f.api.getStrategy(first.strategyId)).toMatchObject({
|
||||
name: 'Personal SMA',
|
||||
description: 'Retained note',
|
||||
updatedBy: 'service',
|
||||
});
|
||||
expect(await f.api.listStrategies()).toHaveLength(1);
|
||||
await f.api.updateStrategy(first.strategyId, { archived: true }, 'operator');
|
||||
expect((await f.api.seedBuiltin(descriptor.name, pkg, 'builtin-seed')).id).toBe(first.id);
|
||||
await expect(
|
||||
f.api.seedBuiltin(descriptor.name, changed, 'new-after-archive')
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
});
|
||||
|
||||
test('HTTP service candidates cannot impersonate builtin authors or reviewers; readers retain artifact access', async () => {
|
||||
const f = await fixture();
|
||||
const created = await f.request('strategies', 'service', { name: 'HTTP candidate' });
|
||||
expect(created.status).toBe(201);
|
||||
const s = (await created.json()).strategy;
|
||||
const published = await f.request(
|
||||
`strategies/${s.id}/versions`,
|
||||
'service',
|
||||
{ package: candidate() },
|
||||
'http-publish'
|
||||
);
|
||||
expect(published.status).toBe(201);
|
||||
const v = (await published.json()).version;
|
||||
expect(v).toMatchObject({
|
||||
origin: 'candidate',
|
||||
createdBy: 'service',
|
||||
reviewStatus: 'pending',
|
||||
runnable: false,
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await f.request(
|
||||
`strategies/${s.id}/versions`,
|
||||
'service',
|
||||
{ package: candidate(), origin: 'builtin' },
|
||||
'forgery'
|
||||
)
|
||||
).status
|
||||
).toBe(400);
|
||||
expect(
|
||||
(
|
||||
await f.request(`strategy-versions/${v.id}/reviews`, 'service', {
|
||||
decision: 'approve',
|
||||
reason: 'forged',
|
||||
actor: 'operator',
|
||||
})
|
||||
).status
|
||||
).toBe(403);
|
||||
expect(
|
||||
(
|
||||
await f.request(`strategy-versions/${v.id}/reviews`, 'operator', {
|
||||
decision: 'approve',
|
||||
reason: 'checked',
|
||||
})
|
||||
).status
|
||||
).toBe(201);
|
||||
const detail = await f.request(`strategy-versions/${v.id}`, 'read');
|
||||
expect(await detail.json()).toMatchObject({
|
||||
version: { reviewStatus: 'approved', runnable: false },
|
||||
reviews: [{ ordinal: 1, actor: 'operator' }],
|
||||
});
|
||||
const artifact = await f.request(`strategy-versions/${v.id}/artifact`, 'read');
|
||||
expect(await artifact.json()).toEqual({ package: candidate() });
|
||||
expect(
|
||||
(
|
||||
await f.request(`strategy-versions/${v.id}/validate`, 'service', {
|
||||
parameters: { mode: 'flat' },
|
||||
})
|
||||
).status
|
||||
).toBe(200);
|
||||
expect(
|
||||
(
|
||||
await f.request(`strategy-versions/${v.id}/validate`, 'service', {
|
||||
parameters: { mode: 'invalid' },
|
||||
})
|
||||
).status
|
||||
).toBe(400);
|
||||
expect(
|
||||
(await f.request(`strategy-versions/${v.id}/artifact`, 'read')).headers.get('Cache-Control')
|
||||
).toBe('no-store');
|
||||
expect((await f.request('strategies/seed', 'operator', {})).status).toBe(404);
|
||||
expect((await f.request(`strategy-versions/${randomUUID()}`, 'read')).status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
async function poolMigrationAgain(pool: Pool) {
|
||||
await pool.query(migration);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue