109 lines
3.8 KiB
TypeScript
109 lines
3.8 KiB
TypeScript
/** Installed candidate metadata and isolation inspection. Never launches or imports a strategy. */
|
|
import { execFile } from 'node:child_process';
|
|
import { createHash } from 'node:crypto';
|
|
import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join, resolve } from 'node:path';
|
|
import { promisify } from 'node:util';
|
|
import {
|
|
candidateExecutionSchema,
|
|
type CandidateExecution,
|
|
} from '@stock-bot/stock-config/candidate-execution';
|
|
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
|
import { localBuildArtifacts } from './artifacts';
|
|
|
|
const runFile = promisify(execFile);
|
|
export const docker = '/usr/bin/docker';
|
|
export const daemon = ['--host', 'unix:///var/run/docker.sock'];
|
|
export const environment = (config: string) => ({ PATH: '/usr/bin:/bin', DOCKER_CONFIG: config });
|
|
export const candidateDescriptorPath = () =>
|
|
resolve(
|
|
localBuildArtifacts().repositoryRoot,
|
|
'apps/stock/orchestrator/dist/candidate-sandbox.json'
|
|
);
|
|
export class CandidateSandboxUnavailable extends Error {
|
|
readonly code = 'candidate_sandbox_unavailable';
|
|
}
|
|
|
|
export async function dockerRead(args: string[]) {
|
|
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
|
|
try {
|
|
return (
|
|
await runFile(docker, [...daemon, ...args], {
|
|
env: environment(config),
|
|
timeout: 10000,
|
|
maxBuffer: 65536,
|
|
})
|
|
).stdout.trim();
|
|
} finally {
|
|
await rm(config, { recursive: true, force: true });
|
|
}
|
|
}
|
|
export async function readCandidateExecution(): Promise<CandidateExecution> {
|
|
try {
|
|
if (process.platform !== 'linux' || process.arch !== 'x64') {
|
|
throw new Error('Unsupported candidate platform');
|
|
}
|
|
const root = localBuildArtifacts().repositoryRoot;
|
|
const execution = candidateExecutionSchema.parse(
|
|
JSON.parse(await readFile(candidateDescriptorPath(), 'utf8'))
|
|
);
|
|
const files = [
|
|
resolve(root, 'apps/stock/orchestrator/dist/candidate-host.js'),
|
|
resolve(root, 'apps/stock/orchestrator/dist/candidate-guardian'),
|
|
await realpath(process.execPath),
|
|
];
|
|
const hashes = await Promise.all(
|
|
files.map(async path =>
|
|
createHash('sha256')
|
|
.update(await readFile(path))
|
|
.digest('hex')
|
|
)
|
|
);
|
|
if (
|
|
hashes[0] !== execution.profile.hostSha256 ||
|
|
hashes[1] !== execution.profile.guardianSha256 ||
|
|
hashes[2] !== execution.profile.bunSha256
|
|
) {
|
|
throw new Error('Candidate installed host/runtime bytes differ');
|
|
}
|
|
const info = JSON.parse(await dockerRead(['info', '--format', '{{json .}}'])) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
if (
|
|
info.OSType !== 'linux' ||
|
|
info.CgroupVersion !== '2' ||
|
|
info.MemoryLimit !== true ||
|
|
info.SwapLimit !== true ||
|
|
info.CpuCfsQuota !== true ||
|
|
info.PidsLimit !== true ||
|
|
!Array.isArray(info.SecurityOptions) ||
|
|
!info.SecurityOptions.some(v => String(v).startsWith('name=seccomp')) ||
|
|
!info.SecurityOptions.some(v => String(v).startsWith('name=apparmor'))
|
|
) {
|
|
throw new Error('Candidate cgroup/seccomp/AppArmor isolation is unavailable');
|
|
}
|
|
if (
|
|
(await dockerRead(['image', 'inspect', execution.imageId, '--format', '{{.Id}}'])) !==
|
|
execution.imageId
|
|
) {
|
|
throw new Error('Candidate exact image is unavailable');
|
|
}
|
|
return execution;
|
|
} catch (cause) {
|
|
throw new CandidateSandboxUnavailable('The exact isolated candidate runtime is unavailable', {
|
|
cause,
|
|
});
|
|
}
|
|
}
|
|
export async function verifyCandidateExecution(expected: CandidateExecution): Promise<void> {
|
|
if (
|
|
canonicalStrategyJson(await readCandidateExecution()) !==
|
|
canonicalStrategyJson(candidateExecutionSchema.parse(expected))
|
|
) {
|
|
throw new CandidateSandboxUnavailable(
|
|
'The retained isolated candidate runtime is not installed'
|
|
);
|
|
}
|
|
}
|