Files
stack/packages/bus/src/interpreter.mjs

78 lines
4.3 KiB
JavaScript

import { realpathSync, statSync, readFileSync, openSync, fstatSync, writeSync, fsyncSync, closeSync, constants } from 'node:fs';
import { dirname, join, sep } from 'node:path';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
const systemPython = '/usr/bin/python3';
const defaultIO = { realpath: realpathSync, stat: statSync, readFile: readFileSync, exec: execFileSync };
const below = (path, parent) => path === parent || path.startsWith(parent + sep);
// Trusted dependency injection is for offline tests, never a CLI/env interpreter override.
export function inspectInterpreter({ io = defaultIO } = {}) {
let probeTimedOut = false;
try {
const path = io.realpath(systemPython);
const homes = ['/home', '/root', ...String(io.readFile('/etc/passwd', 'utf8')).split('\n')
.map(line => line.split(':')[5]).filter(p => p?.startsWith('/') && p !== '/')];
if (!path.startsWith('/') || homes.some(home => below(path, home))) throw Error();
// Check both the system entry's parent and every resolved component. /usr/bin/python3
// may be a system symlink; its containing directory and resolved target must be safe.
for (const start of [dirname(systemPython), path]) {
for (let at = start;; at = dirname(at)) {
const s = io.stat(at);
if (s.uid !== 0 || (s.mode & 0o022) || (at === path ? !s.isFile() : !s.isDirectory())) throw Error();
if (at === '/') break;
}
}
const data = io.readFile(path);
if (!Buffer.isBuffer(data) || !data.subarray(0, 4).equals(Buffer.from([127, 69, 76, 70]))) throw Error();
let output;
try {
output = io.exec(path, ['-I', '-S', '-c', 'import json,sys,socket;assert hasattr(socket,"SO_PEERCRED");print(json.dumps(list(sys.version_info[:3])))'],
{ env: {}, timeout: 1000, maxBuffer: 256, encoding: 'utf8' });
} catch (e) {
// Timeout establishes no interpreter result. Keep the same fail-closed bound,
// but distinguish unavailable probe evidence from a failed safety check.
probeTimedOut = e?.code === 'ETIMEDOUT';
throw e;
}
const version = JSON.parse(String(output));
if (!Array.isArray(version) || version.length !== 3 || !version.every(Number.isSafeInteger) ||
version[0] < 3 || (version[0] === 3 && version[1] < 10)) throw Error();
const s = io.stat(path);
return Object.freeze({ path, version: Object.freeze(version), dev: s.dev, ino: s.ino,
sha256: createHash('sha256').update(data).digest('hex') });
} catch { throw Error(probeTimedOut ? 'interpreter-probe-timeout' : 'interpreter-unsafe'); }
}
export function verifyInterpreterReceipt(directory, expected, since) {
let fd;
try {
fd = openSync(join(directory, 'peercred-starts.jsonl'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
const s = fstatSync(fd);
if (!s.isFile() || s.uid !== process.getuid() || (s.mode & 0o077) || s.nlink !== 1) throw Error();
const text = readFileSync(fd, 'utf8');
if (!text.endsWith('\n')) throw Error();
const actual = JSON.parse(text.trimEnd().split('\n').at(-1));
if (actual.copy !== new URL('../../../', import.meta.url).pathname || !(Date.parse(actual.at) >= Number(since)) ||
Date.parse(actual.at) > Date.now() + 1000 || ['path', 'sha256', 'dev', 'ino', 'version'].some(k => JSON.stringify(actual[k]) !== JSON.stringify(expected[k]))) throw Error();
return true;
} catch { throw Error('interpreter-receipt-mismatch'); }
finally { if (fd !== undefined) closeSync(fd); }
}
export function recordInterpreterStart(directory, record) {
let fd;
try {
const dir = statSync(directory);
if (!dir.isDirectory() || dir.uid !== process.getuid() || (dir.mode & 0o077)) throw Error();
fd = openSync(join(directory, 'peercred-starts.jsonl'),
constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
const s = fstatSync(fd);
if (!s.isFile() || s.uid !== process.getuid() || (s.mode & 0o077) || s.nlink !== 1) throw Error();
const line = Buffer.from(JSON.stringify({ at: new Date().toISOString(), copy: new URL('../../../', import.meta.url).pathname, ...record }) + '\n');
if (writeSync(fd, line) !== line.length) throw Error();
fsyncSync(fd);
} catch { throw Error('interpreter-receipt-unsafe'); }
finally { if (fd !== undefined) closeSync(fd); }
}