stock-bot/test/integration/candidate-sandbox.test.ts

497 lines
21 KiB
TypeScript

import { execFile, fork, type ChildProcessWithoutNullStreams } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { readlinkSync } from 'node:fs';
import { access, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import { describe, expect, test } from 'bun:test';
import { canonicalRunRequestSchema } from '../../apps/stock/config/src/contracts/canonical-research';
import {
candidateDescriptorPath,
IsolatedCandidateController,
readCandidateExecution,
removeCandidateContainer,
} from '../../apps/stock/orchestrator/src/backtest/candidate-sandbox';
import {
canonicalWorkerUrl,
readCanonicalBuildIdentity,
} from '../../apps/stock/orchestrator/src/backtest/canonical-build';
import {
NativeReplaySession,
prepareReplayLoad,
runReplaySessionAsync,
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { packageCandidateStrategy } from '../../scripts/package-candidate-strategy';
import { canonicalRunnerFixture } from '../fixtures/canonical-runner';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
const suite = process.env.CANDIDATE_SANDBOX_TESTS === '1' ? describe : describe.skip;
const hash = (s: string) => createHash('sha256').update(s).digest('hex');
const runFile = promisify(execFile);
const hostPidNamespace = readlinkSync('/proc/self/ns/pid');
const program = (
decision = "return {nextState:c.state,intent:{mode:'target',targets:[]}}",
prefix = ''
) =>
`${prefix}\nexport function createStrategy(s) { return {ownerId:s.ownerId,strategyId:s.strategyId,strategyVersion:s.strategyVersion,seed:s.seed,mode:'target',initialState:null,decide(c){${decision}}}; }`;
async function fixture(content: string) {
const f = canonicalRunnerFixture();
const pkg = {
...f.request.strategy.package,
execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
program: {
strategyId: 'isolated-probe',
strategyVersion: 'v1',
apiVersion: 'canonical-ts/v1',
checkpointVersion: '1',
},
parameterSchema: {
version: 1,
type: 'object',
properties: {},
required: [],
additionalProperties: false,
},
artifact: {
format: 'esm-bundle/v1',
entryExport: 'createStrategy',
content,
sha256: hash(content),
},
dependencyLock: { format: 'bun-lock/v1', content: '{}', sha256: hash('{}') },
};
const request = canonicalRunRequestSchema.parse({
...f.request,
strategy: {
...f.request.strategy,
origin: 'candidate',
baselineVersionId: f.request.strategy.versionId,
reviewId: null,
execution: await readCandidateExecution(),
package: pkg,
selection: {
...f.request.strategy.selection,
strategyId: 'isolated-probe',
strategyVersion: 'v1',
parameters: {},
},
},
});
return { ...f, request, name: `stock-bot-candidate-${randomUUID()}` };
}
async function absent(name: string) {
expect(
(
await runFile('/usr/bin/docker', [
'--host',
'unix:///var/run/docker.sock',
'ps',
'-a',
'-q',
'--filter',
`name=^/${name}$`,
])
).stdout.trim()
).toBe('');
}
suite('actual OS-isolated candidate runtime', () => {
test('host environment/files/network/process spawning denied; ordinary prefix-only computation completes under native finance', async () => {
const f = await fixture(
program(
"if(c.observations.some(o=>o.available_at>c.now))throw Error('future observation'); if('dataset' in c || 'history' in c)throw Error('unexpected dataset'); return {nextState:null,intent:{mode:'target',targets:[]}}",
`
if(Object.keys(process.env).length!==0)throw Error('inherited environment');
if(process.getuid()!==65534)throw Error('privileged child');
const fs=await import('node:fs');
try{fs.readFileSync('/home/boki/repos/stock-bot/.env');throw Error('host file visible')}catch(e){if(e.code!=='ENOENT')throw e}
try{fs.writeFileSync('/app/forbidden','x');throw Error('root writable')}catch(e){if(!['EROFS','EACCES'].includes(e.code))throw e}
const cp=await import('node:child_process');
const spawned=cp.spawnSync('/usr/bin/bun',['--version']); if(!spawned.error)throw Error('process spawn allowed');
try{await fetch('http://127.0.0.1:5432');throw Error('network allowed')}catch(e){if(e.message==='network allowed')throw e}
if(fs.readlinkSync('/proc/self/ns/pid')===${JSON.stringify(hostPidNamespace)})throw Error('host PID namespace');
const ffi=await import('bun:ffi'); const libc=ffi.dlopen('/lib/x86_64-linux-gnu/libc.so.6',{unshare:{args:['i32'],returns:'i32'}}); if(libc.symbols.unshare(0x10000000)!==-1)throw Error('namespace creation allowed');libc.close();
try{fs.writeFileSync('/tmp/overflow',Buffer.alloc(20*1024*1024));throw Error('tmp quota absent')}catch(e){if(e.code!=='ENOSPC')throw e}
const status=fs.readFileSync('/proc/self/status','utf8'); if(!/NoNewPrivs:\\s+1/.test(status)||!/Seccomp:\\s+2/.test(status))throw Error('seccomp missing');
`
)
);
const c = await IsolatedCandidateController.start(f.request, f.name);
try {
const result = await runReplaySessionAsync(
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
c,
{ resultFormat: 'report' }
);
await c.finish();
if (!('format' in result.result) || result.result.format !== 'report') {
throw new Error('Expected native report');
}
expect(result.result.projection.fills).toEqual([]);
expect(String(result.result.view.equity)).toBe('10000.00000000');
} finally {
await c.dispose();
}
await absent(f.name);
}, 30000);
test('native financial risk rejects malicious huge targets without treating ownerBudget as an allocation constraint', async () => {
const f = await fixture(
program(
"return {nextState:null,intent:{mode:'target',targets:[{instrumentId:'X0.US',quantity:'999999999'}]}}"
)
);
const c = await IsolatedCandidateController.start(f.request, f.name);
try {
const admissions: unknown[] = [];
const result = await runReplaySessionAsync(
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
{
stage: c.stage.bind(c),
async committed(outcome) {
admissions.push(outcome);
await c.committed(outcome);
},
},
{ resultFormat: 'report' }
);
await c.finish();
if (!('format' in result.result) || result.result.format !== 'report') {
throw new Error('Expected native report');
}
expect(result.result.projection.fills).toEqual([]);
expect(String(result.result.view.equity)).toBe('10000.00000000');
expect(JSON.stringify(admissions)).toContain('OrderSize');
} finally {
await c.dispose();
}
await absent(f.name);
}, 30000);
test('infinite callback deadline fails and disposal confirms no surviving container', async () => {
const f = await fixture(program('for(;;){}'));
const c = await IsolatedCandidateController.start(f.request, f.name, Date.now() + 2500);
const start = performance.now();
try {
await expect(
runReplaySessionAsync(
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
c
)
).rejects.toThrow();
} finally {
await c.dispose();
}
expect(performance.now() - start).toBeLessThan(8000);
await absent(f.name);
}, 15000);
test('process exit between ready and first callback rejects promptly instead of waiting for the wall budget', async () => {
const f = await fixture(program(undefined, 'setTimeout(()=>process.exit(0),50);'));
const c = await IsolatedCandidateController.start(f.request, f.name);
await Bun.sleep(150);
const start = performance.now();
try {
await expect(
runReplaySessionAsync(
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
c
)
).rejects.toThrow(/closed|exited/);
} finally {
await c.dispose();
}
expect(performance.now() - start).toBeLessThan(3000);
await absent(f.name);
}, 15000);
test('unsolicited stdout frames, oversized frames and stderr flood cannot create a valid financial result', async () => {
for (const attack of [
"const b=Buffer.from(JSON.stringify({version:1,type:'ready',sequence:999}));const h=Buffer.alloc(4);h.writeUInt32BE(b.length);process.stdout.write(Buffer.concat([h,b]));",
'process.stdout.write(Buffer.from([255,255,255,255]));',
"process.stderr.write('x'.repeat(200000));throw Error('bounded diagnostic');",
]) {
const f = await fixture(program(undefined, attack));
await expect(IsolatedCandidateController.start(f.request, f.name)).rejects.toThrow();
await absent(f.name);
}
}, 30000);
test('isolated TS packaging transforms types without evaluating top-level code and refuses dependency edges', async () => {
const f = await fixture(program());
const metadata = {
program: f.request.strategy.package.program,
parameterSchema: f.request.strategy.package.parameterSchema,
execution: f.request.strategy.package.execution,
source: f.request.strategy.package.source,
entryExport: 'createStrategy',
};
const pkg = await packageCandidateStrategy(
metadata,
`const typed: number = 1; ${program()}\nfor(;;){}`
);
expect(pkg.artifact.content).not.toContain(': number');
expect(pkg.artifact.sha256).toBe(hash(pkg.artifact.content));
expect(pkg.build.version).toBe(Bun.version);
for (const source of [
"import x from 'node:fs'; export {x};",
"const x = import('node:fs');",
'const x:number = ;',
]) {
await expect(packageCandidateStrategy(metadata, source)).rejects.toThrow();
}
}, 30000);
test('Docker client SIGKILL and stdin EOF independently trigger guardian cleanup during infinite callback', async () => {
for (const disconnect of ['kill', 'stdin'] as const) {
const f = await fixture(program('for(;;){}'));
const c = await IsolatedCandidateController.start(f.request, f.name);
const pending = runReplaySessionAsync(
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
c
);
void pending.catch(() => undefined);
await Bun.sleep(100);
const child = Reflect.get(c, 'child') as ChildProcessWithoutNullStreams;
const started = performance.now();
if (disconnect === 'kill') {
child.kill('SIGKILL');
} else {
child.stdin.destroy();
}
await expect(pending).rejects.toThrow();
// Verify the independent guardian has removed the namespace BEFORE explicit cleanup.
for (let i = 0; i < 80; i++) {
const present = (
await runFile('/usr/bin/docker', ['ps', '-a', '-q', '--filter', `name=^/${f.name}$`])
).stdout.trim();
if (!present) {
break;
}
await Bun.sleep(25);
}
await absent(f.name);
expect(performance.now() - started).toBeLessThan(5000);
await c.dispose();
}
}, 20000);
test('memory allocation failure cannot produce a successful result or leave the container running', async () => {
const f = await fixture(
program('const blocks=[];for(;;)blocks.push(new Uint8Array(16*1024*1024).fill(1));')
);
const c = await IsolatedCandidateController.start(f.request, f.name, Date.now() + 10000);
try {
await expect(
runReplaySessionAsync(
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
c
)
).rejects.toThrow();
} finally {
await c.dispose();
}
await absent(f.name);
}, 20000);
test('forged owner/decision identity on raw stdout is rejected before native admission', async () => {
const attack = `const d={version:1,sessionId:c.portfolio.portfolio.sessionId,barrierId:c.barrier.barrier_id,revision:c.barrier.revision,decision:{ownerId:'forged',decisionId:JSON.stringify(['strategy','forged',c.strategyId,c.strategyVersion,0]),sequence:0},intent:{mode:'target',targets:[]}};const b=Buffer.from(JSON.stringify({version:1,type:'decisions',sequence:1,decisions:[d]}));const h=Buffer.alloc(4);h.writeUInt32BE(b.length);process.stdout.write(Buffer.concat([h,b]));for(;;){}`;
const f = await fixture(program(attack));
const c = await IsolatedCandidateController.start(f.request, f.name);
try {
await expect(
runReplaySessionAsync(
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
c
)
).rejects.toThrow('forged decision');
} finally {
await c.dispose();
}
await absent(f.name);
}, 15000);
test('changing a future suffix cannot alter the earlier published prefix or candidate decisions', async () => {
const content = program(
"const last=c.observations.at(-1);return {nextState:null,intent:{mode:'target',targets:last?[{instrumentId:'X0.US',quantity:Number(last.close)>2?'1':'0'}]:[]}}"
);
const first = await fixture(content);
const changed = canonicalSmaFixture([first.request.strategy.selection.ownerId], {
closes: [3, 2, 1, 4, 5, 90, 100],
}).dataset;
const cutoff = changed.bars[5]!.availableAt;
const prefixes: unknown[][] = [];
for (const dataset of [first.dataset, changed]) {
const request = canonicalRunRequestSchema.parse({
...first.request,
datasetHash: dataset.manifest.hash,
});
const name = `stock-bot-candidate-${randomUUID()}`,
c = await IsolatedCandidateController.start(request, name),
seen: unknown[] = [];
try {
await runReplaySessionAsync(
new NativeReplaySession(prepareReplayLoad(dataset, request.policy)),
{
async stage(context, observations) {
const decisions = await c.stage(context, observations);
if (context.barrier.at < cutoff) {
seen.push({
at: context.barrier.at,
observations,
intents: decisions.map(d => d.intent),
});
}
return decisions;
},
committed: c.committed.bind(c),
}
);
await c.finish();
} finally {
await c.dispose();
}
prefixes.push(seen);
await absent(name);
}
const [original, changedPrefix] = prefixes;
if (!original || !changedPrefix) {
throw new Error('Missing prefix comparisons');
}
expect(original.length).toBeGreaterThan(1);
expect(changedPrefix).toEqual(original);
}, 20000);
test('killing the actual native worker or its parent leaves no isolated candidate descendant', async () => {
for (const target of ['worker', 'parent'] as const) {
const f = await fixture(program('for(;;){}'));
f.request.build = await readCanonicalBuildIdentity();
const input = {
type: 'runRetainedStrategy',
request: f.request,
dataset: f.dataset,
candidateContainerName: f.name,
executionDeadlineAt: Date.now() + 30000,
};
const directory = await mkdtemp(join(tmpdir(), 'stock-bot-candidate-parent-'));
const parentPath = join(directory, 'parent.mjs');
// The candidate artifact remains inert JSON in this trusted supervisor fixture.
await writeFile(
parentPath,
`import {fork} from 'node:child_process';const child=fork(${JSON.stringify(fileURLToPath(canonicalWorkerUrl))},[],{execPath:process.execPath,execArgv:[],serialization:'json',stdio:['ignore','ignore','pipe','ipc']});child.stderr?.resume();child.send(${JSON.stringify(input)});`
);
const child = fork(target === 'worker' ? fileURLToPath(canonicalWorkerUrl) : parentPath, [], {
execPath: process.execPath,
execArgv: [],
serialization: 'json',
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
});
child.stderr?.resume();
const closed = new Promise<void>(resolve => child.once('close', () => resolve()));
if (target === 'worker') {
child.send(input);
}
try {
let running = false;
for (let i = 0; i < 100; i++) {
if (
(
await runFile('/usr/bin/docker', ['ps', '-q', '--filter', `name=^/${f.name}$`])
).stdout.trim()
) {
running = true;
break;
}
await Bun.sleep(25);
}
expect(running).toBeTrue();
const started = performance.now();
child.kill('SIGKILL');
await closed;
for (let i = 0; i < 100; i++) {
if (
!(
await runFile('/usr/bin/docker', ['ps', '-a', '-q', '--filter', `name=^/${f.name}$`])
).stdout.trim()
) {
break;
}
await Bun.sleep(25);
}
await absent(f.name);
expect(performance.now() - started).toBeLessThan(6000);
} finally {
child.kill('SIGKILL');
await closed;
await removeCandidateContainer(f.name);
await rm(directory, { recursive: true, force: true });
}
}
}, 20000);
test('cleanup still closes the client and removes private configuration when explicit removal fails', async () => {
const f = await fixture(program());
const c = await IsolatedCandidateController.start(f.request, f.name);
const directory = Reflect.get(c, 'dockerConfig') as string;
const child = Reflect.get(c, 'child') as ChildProcessWithoutNullStreams;
// Fault injection at the exact-name validation seam; never disables the daemon or another container.
Reflect.set(c, 'name', 'invalid-owned-container-name');
await expect(c.dispose()).rejects.toThrow('Candidate cleanup failed');
expect(child.exitCode !== null || child.signalCode !== null).toBeTrue();
await expect(access(directory)).rejects.toThrow();
for (let i = 0; i < 80; i++) {
if (
!(
await runFile('/usr/bin/docker', ['ps', '-a', '-q', '--filter', `name=^/${f.name}$`])
).stdout.trim()
) {
break;
}
await Bun.sleep(25);
}
await absent(f.name);
}, 15000);
test('missing installed descriptor and altered retained runtime fail closed before candidate launch', async () => {
const f = await fixture(program());
const altered = structuredClone(f.request);
if (altered.strategy.origin !== 'candidate') {
throw Error('candidate fixture');
}
altered.strategy.execution.imageId = `sha256:${'0'.repeat(64)}`;
await expect(IsolatedCandidateController.start(altered, f.name)).rejects.toThrow(
'not installed'
);
await absent(f.name);
const hidden = candidateDescriptorPath + '.missing-test-' + randomUUID();
await rename(candidateDescriptorPath, hidden);
try {
await expect(IsolatedCandidateController.start(f.request, f.name)).rejects.toThrow(
'unavailable'
);
} finally {
await rename(hidden, candidateDescriptorPath);
}
await absent(f.name);
if (f.request.strategy.origin !== 'candidate') {
throw new Error('Expected candidate fixture');
}
expect(await readCandidateExecution()).toEqual(f.request.strategy.execution);
}, 15000);
test('closing stdout while continuing an infinite callback fails promptly before the wall deadline', async () => {
const f = await fixture(
program(
"const pipe=fs.readlinkSync('/proc/self/fd/1');for(const name of fs.readdirSync('/proc/self/fd')){try{if(fs.readlinkSync('/proc/self/fd/'+name)===pipe){libc.symbols.close(Number(name));}}catch{}}const remaining=fs.readdirSync('/proc/self/fd').filter(name=>{try{return fs.readlinkSync('/proc/self/fd/'+name)===pipe}catch{return false}});if(remaining.length)throw Error('stdout still open');process.stderr.write('candidate-test:stdout-eof-confirmed');for(;;){}",
"const fs=await import('node:fs');const ffi=await import('bun:ffi');const libc=ffi.dlopen('/lib/x86_64-linux-gnu/libc.so.6',{close:{args:['i32'],returns:'i32'}});"
)
);
const c = await IsolatedCandidateController.start(f.request, f.name, Date.now() + 5000);
const started = performance.now();
try {
await expect(
runReplaySessionAsync(
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
c
)
).rejects.toThrow();
} finally {
await c.dispose();
}
expect((Reflect.get(c, 'stderr') as Buffer).toString()).toContain(
'candidate-test:stdout-eof-confirmed'
);
expect(performance.now() - started).toBeLessThan(3000);
await absent(f.name);
}, 10000);
});