crossexamdev 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/bin/crossexam.js +88 -4
- package/package.json +1 -1
- package/src/claims.js +138 -120
- package/src/github.js +93 -69
- package/src/mcp.js +198 -109
- package/src/mutate.js +443 -0
- package/src/report.js +194 -99
- package/src/sandbox.js +627 -0
- package/src/strength.js +628 -0
package/src/sandbox.js
ADDED
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
// Where mutants run: never in the user's working tree, and never with the
|
|
2
|
+
// user's full permissions unless the user explicitly says so.
|
|
3
|
+
//
|
|
4
|
+
// Two layers, kept separate on purpose:
|
|
5
|
+
//
|
|
6
|
+
// 1. A disposable copy of the checkout, next to the repo, that crossexam
|
|
7
|
+
// writes and deletes. This protects the working tree and git state.
|
|
8
|
+
// A copy is NOT a security boundary.
|
|
9
|
+
// 2. An isolation backend that runs the test command against that copy:
|
|
10
|
+
// bwrap Linux: read-only system, hidden homes, no network
|
|
11
|
+
// sandbox-exec macOS: writes confined to the copy, home unreadable, no network
|
|
12
|
+
// docker any OS with a Linux container engine: no network, limits, read-only root
|
|
13
|
+
// none explicit opt-in only: a scrubbed environment and a timeout, nothing more
|
|
14
|
+
//
|
|
15
|
+
// `auto` picks the first backend that passes a live probe. If none does,
|
|
16
|
+
// crossexam refuses to run mutants rather than silently running them unsandboxed.
|
|
17
|
+
// See docs/mutation-security.md for the threat model.
|
|
18
|
+
|
|
19
|
+
import { execFileSync, spawn, spawnSync } from 'node:child_process';
|
|
20
|
+
import crypto from 'node:crypto';
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import os from 'node:os';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
|
|
25
|
+
const DEP_DIRS = new Set(['node_modules', '.venv', 'venv', '.yarn', '.pnpm-store']);
|
|
26
|
+
const OUTPUT_CAP = 200000;
|
|
27
|
+
const COPY_TAG = '.crossexam-mut-';
|
|
28
|
+
const MANIFEST = '.crossexam-copy.json';
|
|
29
|
+
|
|
30
|
+
export const sha = (s) => crypto.createHash('sha256').update(s).digest('hex');
|
|
31
|
+
|
|
32
|
+
// ---------- environment ----------
|
|
33
|
+
|
|
34
|
+
// Anything that looks like a credential stays out of the test process.
|
|
35
|
+
const SECRET_ENV = /(?:TOKEN|SECRET|PASSW(?:OR)?D|API_?KEY|ACCESS_?KEY|PRIVATE|CREDENTIAL|AUTH|SESSION|COOKIE|SIGNING|WEBHOOK|DSN|CONNECTION_STRING|DATABASE_URL)/i;
|
|
36
|
+
const SECRET_PREFIX = /^(?:AWS_|AZURE_|GCP_|GOOGLE_APPLICATION|GH_|GITHUB_TOKEN|NPM_CONFIG__AUTH|NODE_AUTH|ANTHROPIC_|OPENAI_|STRIPE_|SUPABASE_|VERCEL_|NETLIFY_|HEROKU_|DIGITALOCEAN_|CLOUDFLARE_|TWILIO_|SENDGRID_|SLACK_|SSH_AUTH_SOCK|GPG_AGENT)/i;
|
|
37
|
+
// State a parent test runner leaves behind. NODE_TEST_CONTEXT makes a nested
|
|
38
|
+
// `node --test` report to a parent that isn't listening and always exit 0.
|
|
39
|
+
const RUNNER_STATE = /^(?:NODE_TEST_CONTEXT|NODE_TEST_|VITEST|VITEST_|JEST_WORKER_ID|NODE_UNIQUE_ID|NODE_CHANNEL_FD|NODE_CHANNEL_SERIALIZATION_MODE)/;
|
|
40
|
+
const FIXED = { CI: '1', FORCE_COLOR: '0', NO_COLOR: '1', CROSSEXAM_MUTATION: '1', GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' };
|
|
41
|
+
|
|
42
|
+
/** Unsandboxed runs: the user's environment minus anything credential-like. */
|
|
43
|
+
export function scrubbedEnv(base = process.env) {
|
|
44
|
+
const env = {};
|
|
45
|
+
const removed = [];
|
|
46
|
+
for (const [k, v] of Object.entries(base)) {
|
|
47
|
+
if (SECRET_ENV.test(k) || SECRET_PREFIX.test(k)) removed.push(k);
|
|
48
|
+
else if (!RUNNER_STATE.test(k)) env[k] = v;
|
|
49
|
+
}
|
|
50
|
+
Object.assign(env, FIXED);
|
|
51
|
+
return { env, removed };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Sandboxed runs get a short allowlist and nothing else.
|
|
55
|
+
const ALLOW_ENV = ['PATH', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM', 'TZ', 'SHELL', 'USER', 'LOGNAME', 'SystemRoot', 'PATHEXT', 'COMSPEC', 'WINDIR'];
|
|
56
|
+
export function allowlistedEnv(base = process.env, extra = {}) {
|
|
57
|
+
const env = {};
|
|
58
|
+
for (const k of ALLOW_ENV) if (base[k] != null) env[k] = base[k];
|
|
59
|
+
const removed = Object.keys(base).filter((k) => !(k in env));
|
|
60
|
+
return { env: { ...env, ...FIXED, ...extra }, removed };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---------- git (read-only, lock-free) ----------
|
|
64
|
+
|
|
65
|
+
const GIT_ENV = { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' };
|
|
66
|
+
export function git(cwd, args) {
|
|
67
|
+
return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 << 20, env: GIT_ENV });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Files that make up the project: tracked plus untracked-but-not-ignored. */
|
|
71
|
+
export function projectFiles(cwd) {
|
|
72
|
+
try {
|
|
73
|
+
return git(cwd, ['ls-files', '-co', '--exclude-standard', '-z']).split('\0').filter(Boolean);
|
|
74
|
+
} catch {
|
|
75
|
+
// Not a git repo: walk it without following links, skipping heavy folders.
|
|
76
|
+
const out = [];
|
|
77
|
+
const walk = (dir, rel) => {
|
|
78
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
79
|
+
if (e.name === '.git' || DEP_DIRS.has(e.name) || /^(?:dist|build|coverage|\.next)$/.test(e.name)) continue;
|
|
80
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
81
|
+
if (e.isDirectory()) walk(path.join(dir, e.name), r);
|
|
82
|
+
else if (e.isFile() || e.isSymbolicLink()) out.push(r);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
walk(cwd, '');
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Ignored dependency folders (node_modules, .venv…) at any depth, not nested inside each other. */
|
|
91
|
+
function dependencyDirs(cwd) {
|
|
92
|
+
let dirs = [];
|
|
93
|
+
try {
|
|
94
|
+
dirs = git(cwd, ['ls-files', '-o', '-i', '--exclude-standard', '--directory', '-z']).split('\0').filter(Boolean);
|
|
95
|
+
} catch {
|
|
96
|
+
dirs = fs.readdirSync(cwd).map((n) => n + '/');
|
|
97
|
+
}
|
|
98
|
+
return dirs
|
|
99
|
+
.map((d) => d.replace(/\/$/, ''))
|
|
100
|
+
.filter((d) => DEP_DIRS.has(d.split('/').pop()) && !d.split('/').slice(0, -1).some((p) => DEP_DIRS.has(p)))
|
|
101
|
+
.filter((d) => {
|
|
102
|
+
try {
|
|
103
|
+
// A real directory only: a dependency "folder" that is itself a link
|
|
104
|
+
// could point anywhere.
|
|
105
|
+
return fs.lstatSync(path.join(cwd, d)).isDirectory();
|
|
106
|
+
} catch {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Is `p` (after resolving links) inside `root`? */
|
|
113
|
+
export function isInside(root, p) {
|
|
114
|
+
let real;
|
|
115
|
+
try {
|
|
116
|
+
real = fs.realpathSync(p);
|
|
117
|
+
} catch {
|
|
118
|
+
real = path.resolve(p);
|
|
119
|
+
}
|
|
120
|
+
let r = root;
|
|
121
|
+
try {
|
|
122
|
+
r = fs.realpathSync(root);
|
|
123
|
+
} catch {}
|
|
124
|
+
const rel = path.relative(r, real);
|
|
125
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ---------- the copy ----------
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Make a disposable copy of the whole checkout (tests import across packages,
|
|
132
|
+
* configs extend the root, workspaces hoist dependencies), next to the repo so
|
|
133
|
+
* config lookups walk up through the same parents the real repo has.
|
|
134
|
+
* @returns {{dir: string, root: string, rel: string, top: string, depDirs: string[], skippedLinks: string[], files: number, dispose: () => {removed: boolean, path: string}}}
|
|
135
|
+
*/
|
|
136
|
+
function realPath(p) {
|
|
137
|
+
try {
|
|
138
|
+
return fs.realpathSync.native(path.resolve(p));
|
|
139
|
+
} catch {
|
|
140
|
+
return path.resolve(p);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function createCopy(cwd, { linkDeps = true, copyDir } = {}) {
|
|
145
|
+
// Resolve both ends fully: git reports the real path (macOS /private/var,
|
|
146
|
+
// Windows long names), and a relative path between a real and an aliased
|
|
147
|
+
// form would climb out of the copy and land back in the user's repo.
|
|
148
|
+
cwd = realPath(cwd);
|
|
149
|
+
let top = cwd;
|
|
150
|
+
try {
|
|
151
|
+
top = realPath(git(cwd, ['rev-parse', '--show-toplevel']).trim());
|
|
152
|
+
} catch {
|
|
153
|
+
/* not a git repo: the folder itself is the root */
|
|
154
|
+
}
|
|
155
|
+
const rel = path.relative(top, cwd);
|
|
156
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) throw new Error(`Cannot place ${cwd} inside its checkout ${top}; refusing to make a copy.`);
|
|
157
|
+
const root = makeCopyDir(top, copyDir);
|
|
158
|
+
fs.writeFileSync(path.join(root, MANIFEST), JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString(), source: top }));
|
|
159
|
+
let result = null;
|
|
160
|
+
const dispose = () => {
|
|
161
|
+
if (result) return result;
|
|
162
|
+
process.removeListener('exit', dispose);
|
|
163
|
+
result = safeRemove(root);
|
|
164
|
+
return result;
|
|
165
|
+
};
|
|
166
|
+
process.once('exit', dispose);
|
|
167
|
+
|
|
168
|
+
const depDirs = [];
|
|
169
|
+
const skippedLinks = [];
|
|
170
|
+
try {
|
|
171
|
+
const files = projectFiles(top);
|
|
172
|
+
for (const f of files) {
|
|
173
|
+
const from = path.join(top, f);
|
|
174
|
+
const to = path.join(root, f);
|
|
175
|
+
const back = path.relative(root, to);
|
|
176
|
+
if (!back || back.startsWith('..') || path.isAbsolute(back)) continue; // never write outside the copy
|
|
177
|
+
let st;
|
|
178
|
+
try {
|
|
179
|
+
st = fs.lstatSync(from);
|
|
180
|
+
} catch {
|
|
181
|
+
continue; // deleted while we were copying
|
|
182
|
+
}
|
|
183
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
184
|
+
if (st.isSymbolicLink()) {
|
|
185
|
+
// Recreate a tracked link only if it stays inside the repo; a link to
|
|
186
|
+
// ~/.ssh/id_rsa must not become readable from the copy.
|
|
187
|
+
const target = fs.readlinkSync(from);
|
|
188
|
+
const resolved = path.resolve(path.dirname(from), target);
|
|
189
|
+
if (!path.isAbsolute(target) && isInside(top, resolved)) {
|
|
190
|
+
try {
|
|
191
|
+
fs.symlinkSync(target, to);
|
|
192
|
+
} catch {
|
|
193
|
+
skippedLinks.push(f); // e.g. Windows without symlink privilege
|
|
194
|
+
}
|
|
195
|
+
} else skippedLinks.push(f);
|
|
196
|
+
} else if (st.isFile()) fs.copyFileSync(from, to);
|
|
197
|
+
}
|
|
198
|
+
if (linkDeps) {
|
|
199
|
+
for (const d of dependencyDirs(top)) {
|
|
200
|
+
const to = path.join(root, d);
|
|
201
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
202
|
+
fs.symlinkSync(path.join(top, d), to, process.platform === 'win32' ? 'junction' : 'dir');
|
|
203
|
+
depDirs.push(d);
|
|
204
|
+
}
|
|
205
|
+
} else depDirs.push(...dependencyDirs(top));
|
|
206
|
+
// An empty home and temp dir for the tests, inside the copy.
|
|
207
|
+
fs.mkdirSync(path.join(root, '.crossexam-home'), { recursive: true });
|
|
208
|
+
fs.mkdirSync(path.join(root, '.crossexam-tmp'), { recursive: true });
|
|
209
|
+
return { dir: path.join(root, rel), root, rel, top, depDirs, skippedLinks, files: files.length, dispose };
|
|
210
|
+
} catch (e) {
|
|
211
|
+
dispose();
|
|
212
|
+
throw e;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// The copy sits next to the repo, not in the system temp folder: tools walk up
|
|
217
|
+
// the directory tree for config (package.json, tsconfig, babel, vite…), and a
|
|
218
|
+
// copy under ~/AppData/Local/Temp would see the home directory's files instead
|
|
219
|
+
// of the ones the real repo sees. Hidden, uniquely named, removed afterwards.
|
|
220
|
+
function makeCopyDir(top, copyDir) {
|
|
221
|
+
const parents = copyDir ? [path.resolve(copyDir)] : [path.dirname(top), os.tmpdir()];
|
|
222
|
+
for (const parent of parents) {
|
|
223
|
+
try {
|
|
224
|
+
return fs.mkdtempSync(path.join(parent, `.${path.basename(top)}${COPY_TAG}`));
|
|
225
|
+
} catch {
|
|
226
|
+
/* not writable: try the next place */
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
throw new Error('Could not create an isolated copy next to the repository or in the temp directory.');
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Delete a copy without ever following a link out of it: every symlink and
|
|
234
|
+
* junction is unlinked first (lstat sees junctions as links), then the rest
|
|
235
|
+
* is removed. If any link refuses to go, nothing else is deleted.
|
|
236
|
+
*/
|
|
237
|
+
export function safeRemove(root) {
|
|
238
|
+
const links = [];
|
|
239
|
+
const walk = (d) => {
|
|
240
|
+
let entries;
|
|
241
|
+
try {
|
|
242
|
+
entries = fs.readdirSync(d, { withFileTypes: true });
|
|
243
|
+
} catch {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
for (const e of entries) {
|
|
247
|
+
const p = path.join(d, e.name);
|
|
248
|
+
let st;
|
|
249
|
+
try {
|
|
250
|
+
st = fs.lstatSync(p);
|
|
251
|
+
} catch {
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (st.isSymbolicLink()) links.push(p);
|
|
255
|
+
else if (st.isDirectory()) walk(p);
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
walk(root);
|
|
259
|
+
for (const l of links) {
|
|
260
|
+
try {
|
|
261
|
+
fs.unlinkSync(l);
|
|
262
|
+
} catch {
|
|
263
|
+
try {
|
|
264
|
+
fs.rmdirSync(l); // a junction on some Windows versions
|
|
265
|
+
} catch {
|
|
266
|
+
/* checked below */
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (links.some((l) => exists(l))) return { removed: false, path: root, reason: 'a link inside the copy could not be removed safely' };
|
|
271
|
+
try {
|
|
272
|
+
fs.rmSync(root, { recursive: true, force: true, maxRetries: 3 });
|
|
273
|
+
} catch (e) {
|
|
274
|
+
return { removed: false, path: root, reason: e.message };
|
|
275
|
+
}
|
|
276
|
+
return { removed: !exists(root), path: root };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Remove copies left by runs that crashed or were killed (their owner process is gone). */
|
|
280
|
+
export function sweepStaleCopies(cwd) {
|
|
281
|
+
let top = realPath(cwd);
|
|
282
|
+
try {
|
|
283
|
+
top = realPath(git(cwd, ['rev-parse', '--show-toplevel']).trim());
|
|
284
|
+
} catch {}
|
|
285
|
+
const prefix = `.${path.basename(top)}${COPY_TAG}`;
|
|
286
|
+
const removed = [];
|
|
287
|
+
for (const parent of new Set([path.dirname(top), os.tmpdir()])) {
|
|
288
|
+
let names = [];
|
|
289
|
+
try {
|
|
290
|
+
names = fs.readdirSync(parent).filter((n) => n.startsWith(prefix));
|
|
291
|
+
} catch {
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
for (const n of names) {
|
|
295
|
+
const root = path.join(parent, n);
|
|
296
|
+
let stale = false;
|
|
297
|
+
try {
|
|
298
|
+
const m = JSON.parse(fs.readFileSync(path.join(root, MANIFEST), 'utf8'));
|
|
299
|
+
stale = !alive(m.pid) || Date.now() - Date.parse(m.createdAt) > 24 * 3600e3;
|
|
300
|
+
if (stale) stopOrphans(m);
|
|
301
|
+
} catch {
|
|
302
|
+
// No manifest: created by a run that died before writing it, if it's old enough.
|
|
303
|
+
try {
|
|
304
|
+
stale = Date.now() - fs.statSync(root).mtimeMs > 3600e3;
|
|
305
|
+
} catch {}
|
|
306
|
+
}
|
|
307
|
+
if (stale && safeRemove(root).removed) removed.push(root);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return removed;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function updateManifest(root, patch) {
|
|
314
|
+
try {
|
|
315
|
+
const f = path.join(root, MANIFEST);
|
|
316
|
+
fs.writeFileSync(f, JSON.stringify({ ...JSON.parse(fs.readFileSync(f, 'utf8')), ...patch }));
|
|
317
|
+
} catch {
|
|
318
|
+
/* best effort */
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Stop test processes a crashed run left behind. Only where it can be done
|
|
324
|
+
* without risking someone else's process: a uniquely named container, or a
|
|
325
|
+
* POSIX process group crossexam created. On Windows a bare pid may already
|
|
326
|
+
* belong to another program, so the copy is left for a later sweep instead.
|
|
327
|
+
*/
|
|
328
|
+
function stopOrphans(m) {
|
|
329
|
+
if (m.container) spawnSync(containerEngine() || 'docker', ['kill', m.container], { stdio: 'ignore', windowsHide: true, timeout: 10000 });
|
|
330
|
+
if (m.child && m.posixGroup && process.platform !== 'win32' && Date.now() - Date.parse(m.startedAt || 0) < 24 * 3600e3) {
|
|
331
|
+
try {
|
|
332
|
+
process.kill(-m.child, 'SIGKILL');
|
|
333
|
+
} catch {
|
|
334
|
+
/* already gone */
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function alive(pid) {
|
|
340
|
+
if (!pid) return false;
|
|
341
|
+
try {
|
|
342
|
+
process.kill(pid, 0);
|
|
343
|
+
return true;
|
|
344
|
+
} catch (e) {
|
|
345
|
+
return e.code === 'EPERM';
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const exists = (p) => {
|
|
350
|
+
try {
|
|
351
|
+
fs.lstatSync(p);
|
|
352
|
+
return true;
|
|
353
|
+
} catch {
|
|
354
|
+
return false;
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
// ---------- isolation backends ----------
|
|
359
|
+
|
|
360
|
+
const probeCache = new Map();
|
|
361
|
+
const probe = (name, fn) => {
|
|
362
|
+
if (!probeCache.has(name)) {
|
|
363
|
+
let ok = false;
|
|
364
|
+
try {
|
|
365
|
+
ok = fn();
|
|
366
|
+
} catch {
|
|
367
|
+
ok = false;
|
|
368
|
+
}
|
|
369
|
+
probeCache.set(name, ok);
|
|
370
|
+
}
|
|
371
|
+
return probeCache.get(name);
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
/** Which backends actually work here, checked by running them, not by looking for binaries. */
|
|
375
|
+
export function availableBackends() {
|
|
376
|
+
const out = [];
|
|
377
|
+
if (process.platform === 'linux' && probe('bwrap', () => spawnSync('bwrap', ['--ro-bind', '/', '/', '--unshare-all', '--die-with-parent', '--dev', '/dev', '--proc', '/proc', 'true'], { timeout: 10000, stdio: 'ignore' }).status === 0)) out.push('bwrap');
|
|
378
|
+
if (process.platform === 'darwin' && probe('sandbox-exec', () => spawnSync('/usr/bin/sandbox-exec', ['-p', '(version 1)(allow default)(deny network*)', '/usr/bin/true'], { timeout: 10000, stdio: 'ignore' }).status === 0)) out.push('sandbox-exec');
|
|
379
|
+
const engine = containerEngine();
|
|
380
|
+
if (engine) out.push('docker');
|
|
381
|
+
return out;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function containerEngine() {
|
|
385
|
+
return probe('container', () => {
|
|
386
|
+
for (const bin of ['docker', 'podman']) {
|
|
387
|
+
const r = spawnSync(bin, ['info', '--format', '{{.OSType}}'], { encoding: 'utf8', timeout: 10000, windowsHide: true });
|
|
388
|
+
if (r.status === 0 && /linux/i.test(r.stdout)) return bin;
|
|
389
|
+
}
|
|
390
|
+
return false;
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export const BACKENDS = ['auto', 'bwrap', 'sandbox-exec', 'docker', 'none'];
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Decide how to isolate. A repository's own config may ask for a stronger
|
|
398
|
+
* backend but can never turn isolation off: only the human can, with
|
|
399
|
+
* --unsandboxed or CROSSEXAM_ALLOW_UNSANDBOXED=1.
|
|
400
|
+
* @returns {{method: string|null, sandboxed: boolean, refused?: string, notes: string[]}}
|
|
401
|
+
*/
|
|
402
|
+
export function chooseIsolation({ requested = 'auto', allowUnsandboxed = false, fromRepoConfig = false } = {}) {
|
|
403
|
+
const notes = [];
|
|
404
|
+
if (!BACKENDS.includes(requested)) return { method: null, sandboxed: false, refused: `Unknown isolation "${requested}". Use one of: ${BACKENDS.join(', ')}.`, notes };
|
|
405
|
+
if (requested === 'none' && fromRepoConfig) {
|
|
406
|
+
notes.push('crossexam.json asked for isolation "none"; a repository cannot turn the sandbox off, so it was ignored.');
|
|
407
|
+
requested = 'auto';
|
|
408
|
+
}
|
|
409
|
+
if (requested === 'none') {
|
|
410
|
+
if (!allowUnsandboxed) return { method: null, sandboxed: false, refused: 'Unsandboxed runs need --unsandboxed (or CROSSEXAM_ALLOW_UNSANDBOXED=1).', notes };
|
|
411
|
+
return { method: 'none', sandboxed: false, notes };
|
|
412
|
+
}
|
|
413
|
+
const have = availableBackends();
|
|
414
|
+
if (requested !== 'auto') {
|
|
415
|
+
if (have.includes(requested)) return { method: requested, sandboxed: true, notes };
|
|
416
|
+
return { method: null, sandboxed: false, refused: `Isolation "${requested}" is not available on this machine (its probe failed).${hint()}`, notes };
|
|
417
|
+
}
|
|
418
|
+
if (have.length) return { method: have[0], sandboxed: true, notes };
|
|
419
|
+
if (allowUnsandboxed) {
|
|
420
|
+
notes.push('No sandbox is available here; running unsandboxed because you allowed it.');
|
|
421
|
+
return { method: 'none', sandboxed: false, notes };
|
|
422
|
+
}
|
|
423
|
+
return { method: null, sandboxed: false, refused: `No sandbox is available on this machine, so no mutant was run.${hint()} To run anyway with your own permissions (only for code you trust as much as running its tests yourself), pass --unsandboxed.`, notes };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function hint() {
|
|
427
|
+
if (process.platform === 'linux') return ' Install bubblewrap (apt install bubblewrap); on Ubuntu 24.04+ unprivileged user namespaces must be allowed for it. Or use Docker/Podman.';
|
|
428
|
+
if (process.platform === 'darwin') return ' /usr/bin/sandbox-exec did not work; Docker or Podman also works.';
|
|
429
|
+
if (process.platform === 'win32') return ' Windows has no sandbox crossexam can drive without native code; Docker Desktop with Linux containers works.';
|
|
430
|
+
return ' Docker or Podman works on any platform.';
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** Plain-language description of what a backend does and doesn't protect. */
|
|
434
|
+
export function describeIsolation(method, limits) {
|
|
435
|
+
const d = {
|
|
436
|
+
bwrap: { filesystem: 'system read-only; home, /run and /tmp hidden; only the copy is writable', network: 'none (separate network namespace)', processes: 'own pid namespace, killed with crossexam' },
|
|
437
|
+
'sandbox-exec': { filesystem: 'writes only inside the copy; your home folder is unreadable except the copy, dependencies and toolchain', network: 'denied', processes: 'killed with crossexam' },
|
|
438
|
+
docker: { filesystem: 'only the copy is mounted; dependencies read-only; read-only root', network: 'none (--network none)', processes: `pid limit ${limits.pids}, no capabilities, no new privileges` },
|
|
439
|
+
none: { filesystem: 'NOT SANDBOXED: tests can read and write anything your user can', network: 'NOT SANDBOXED: your network', processes: 'killed on timeout' },
|
|
440
|
+
}[method];
|
|
441
|
+
return {
|
|
442
|
+
method,
|
|
443
|
+
sandboxed: method !== 'none',
|
|
444
|
+
...d,
|
|
445
|
+
environment: method === 'none' ? 'your environment minus credential-like variables' : 'allowlist only (PATH, locale, CI flags); HOME is an empty folder',
|
|
446
|
+
limits: {
|
|
447
|
+
timeoutSeconds: Math.round(limits.timeoutMs / 1000),
|
|
448
|
+
memoryMb: method === 'docker' || method === 'bwrap' ? limits.memoryMb : null,
|
|
449
|
+
cpuSeconds: method === 'none' ? null : limits.cpuSeconds,
|
|
450
|
+
cpus: method === 'docker' ? limits.cpus : null,
|
|
451
|
+
},
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
export const DEFAULT_LIMITS = { memoryMb: 4096, cpus: 2, pids: 512, cpuSeconds: 600 };
|
|
456
|
+
const clampLimits = (l = {}) => ({
|
|
457
|
+
memoryMb: Math.min(Math.max(Number(l.memoryMb) || DEFAULT_LIMITS.memoryMb, 256), 16384),
|
|
458
|
+
cpus: Math.min(Math.max(Number(l.cpus) || DEFAULT_LIMITS.cpus, 0.5), 16),
|
|
459
|
+
pids: Math.min(Math.max(Number(l.pids) || DEFAULT_LIMITS.pids, 64), 4096),
|
|
460
|
+
cpuSeconds: Math.min(Math.max(Number(l.cpuSeconds) || DEFAULT_LIMITS.cpuSeconds, 10), 3600),
|
|
461
|
+
});
|
|
462
|
+
export { clampLimits };
|
|
463
|
+
|
|
464
|
+
/** Toolchain folders that must stay readable in a sandbox (node from nvm, PATH entries under home). */
|
|
465
|
+
function toolchainDirs() {
|
|
466
|
+
const home = os.homedir();
|
|
467
|
+
const dirs = new Set([path.dirname(path.dirname(process.execPath))]);
|
|
468
|
+
for (const p of (process.env.PATH || '').split(path.delimiter)) if (p && p.startsWith(home) && exists(p)) dirs.add(p);
|
|
469
|
+
return [...dirs].filter((d) => d.startsWith(home));
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Run a shell command against the copy with a hard timeout that kills the
|
|
474
|
+
* whole process tree.
|
|
475
|
+
* @returns {Promise<{exitCode: number, output: string, ms: number, timedOut: boolean, spawnError?: string}>}
|
|
476
|
+
*/
|
|
477
|
+
export function runIsolated(command, { copy, cwd, timeoutMs, method, limits = DEFAULT_LIMITS, docker = {} }) {
|
|
478
|
+
const lim = clampLimits(limits);
|
|
479
|
+
const home = path.join(copy.root, '.crossexam-home');
|
|
480
|
+
const tmp = path.join(copy.root, '.crossexam-tmp');
|
|
481
|
+
const ulimits = `ulimit -t ${lim.cpuSeconds} 2>/dev/null; ${method === 'bwrap' ? `ulimit -d ${lim.memoryMb * 1024} 2>/dev/null; ` : ''}`;
|
|
482
|
+
let file;
|
|
483
|
+
let args;
|
|
484
|
+
let env;
|
|
485
|
+
let shell = false;
|
|
486
|
+
let cleanup = () => {};
|
|
487
|
+
|
|
488
|
+
if (method === 'none') {
|
|
489
|
+
env = { ...scrubbedEnv().env, GIT_CEILING_DIRECTORIES: path.dirname(copy.root) };
|
|
490
|
+
file = command;
|
|
491
|
+
shell = true;
|
|
492
|
+
} else if (method === 'bwrap') {
|
|
493
|
+
env = allowlistedEnv(process.env, { HOME: home, TMPDIR: '/tmp', GIT_CEILING_DIRECTORIES: path.dirname(copy.root) }).env;
|
|
494
|
+
const hide = ['/home', '/root', '/run', '/var/run', '/tmp', '/mnt', '/media', '/srv'].filter((p) => exists(p) && !fs.lstatSync(p).isSymbolicLink());
|
|
495
|
+
const homeDir = os.homedir();
|
|
496
|
+
args = ['--die-with-parent', '--new-session', '--unshare-all', '--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc'];
|
|
497
|
+
for (const h of hide) args.push('--tmpfs', h);
|
|
498
|
+
if (!hide.some((h) => homeDir.startsWith(h + '/'))) args.push('--tmpfs', homeDir);
|
|
499
|
+
for (const t of toolchainDirs()) args.push('--ro-bind', t, t);
|
|
500
|
+
for (const d of copy.depDirs) args.push('--ro-bind', path.join(copy.top, d), path.join(copy.top, d));
|
|
501
|
+
args.push('--bind', copy.root, copy.root, '--chdir', cwd, '--', '/bin/sh', '-c', ulimits + command);
|
|
502
|
+
file = 'bwrap';
|
|
503
|
+
} else if (method === 'sandbox-exec') {
|
|
504
|
+
const real = (p) => {
|
|
505
|
+
try {
|
|
506
|
+
return fs.realpathSync(p);
|
|
507
|
+
} catch {
|
|
508
|
+
return p;
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
const q = (p) => JSON.stringify(real(p));
|
|
512
|
+
const readable = [copy.root, ...copy.depDirs.map((d) => path.join(copy.top, d)), ...toolchainDirs()];
|
|
513
|
+
// Resolving a path (node's realpath, module lookup) stats every parent
|
|
514
|
+
// folder. Parents inside the home folder get metadata only: they can be
|
|
515
|
+
// stat'ed, not listed or read, so the names of your files stay hidden.
|
|
516
|
+
const homeReal = real(os.homedir());
|
|
517
|
+
const parents = new Set([homeReal]);
|
|
518
|
+
for (const p of readable) {
|
|
519
|
+
for (let d = path.dirname(real(p)); d.startsWith(homeReal + path.sep); d = path.dirname(d)) parents.add(d);
|
|
520
|
+
}
|
|
521
|
+
const profile = [
|
|
522
|
+
'(version 1)',
|
|
523
|
+
'(allow default)',
|
|
524
|
+
'(deny network*)',
|
|
525
|
+
'(allow network* (remote unix-socket))',
|
|
526
|
+
'(deny file-write*)',
|
|
527
|
+
`(allow file-write* (subpath ${q(copy.root)}) (literal "/dev/null") (literal "/dev/zero") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,
|
|
528
|
+
`(deny file-read* (subpath ${q(os.homedir())}) (subpath "/Volumes") (literal "/var/run/docker.sock") (literal "/private/var/run/docker.sock"))`,
|
|
529
|
+
`(allow file-read* ${readable.map((p) => `(subpath ${q(p)})`).join(' ')})`,
|
|
530
|
+
`(allow file-read-metadata ${[...parents].map((p) => `(literal ${JSON.stringify(p)})`).join(' ')})`,
|
|
531
|
+
].join('\n');
|
|
532
|
+
env = allowlistedEnv(process.env, { HOME: home, TMPDIR: tmp, GIT_CEILING_DIRECTORIES: path.dirname(copy.root) }).env;
|
|
533
|
+
file = '/usr/bin/sandbox-exec';
|
|
534
|
+
args = ['-p', profile, '/bin/sh', '-c', ulimits + command];
|
|
535
|
+
} else if (method === 'docker') {
|
|
536
|
+
const engine = containerEngine() || 'docker';
|
|
537
|
+
const name = `crossexam-mut-${crypto.randomBytes(6).toString('hex')}`;
|
|
538
|
+
const work = ['/work', ...(copy.rel ? copy.rel.split(path.sep) : [])].join('/');
|
|
539
|
+
args = ['run', '--rm', '--name', name, '--network', 'none', '--memory', `${lim.memoryMb}m`, '--memory-swap', `${lim.memoryMb}m`, '--cpus', String(lim.cpus), '--pids-limit', String(lim.pids), '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--read-only', '--tmpfs', '/tmp:rw,exec,size=512m', '-v', `${copy.root}:/work`, '-w', work, '-e', 'HOME=/work/.crossexam-home', '-e', 'TMPDIR=/tmp'];
|
|
540
|
+
if (process.platform === 'linux' && process.getuid) args.push('--user', `${process.getuid()}:${process.getgid()}`);
|
|
541
|
+
for (const d of copy.depDirs) args.push('-v', `${path.join(copy.top, d)}:/work/${d.split(path.sep).join('/')}:ro`);
|
|
542
|
+
for (const [k, v] of Object.entries(FIXED)) args.push('-e', `${k}=${v}`);
|
|
543
|
+
args.push(docker.image || 'node:22-bookworm-slim', 'sh', '-c', `ulimit -t ${lim.cpuSeconds} 2>/dev/null; ${command}`);
|
|
544
|
+
file = engine;
|
|
545
|
+
env = process.env; // the engine client's own environment; nothing is forwarded into the container
|
|
546
|
+
cleanup = () => spawnSync(engine, ['kill', name], { stdio: 'ignore', windowsHide: true });
|
|
547
|
+
} else {
|
|
548
|
+
return Promise.resolve({ exitCode: 127, output: `unknown isolation ${method}`, ms: 0, timedOut: false, spawnError: `unknown isolation ${method}` });
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
return new Promise((resolve) => {
|
|
552
|
+
const t0 = Date.now();
|
|
553
|
+
const posix = process.platform !== 'win32';
|
|
554
|
+
let child;
|
|
555
|
+
try {
|
|
556
|
+
child = spawn(file, args || [], { cwd, shell, env, windowsHide: true, detached: posix });
|
|
557
|
+
} catch (e) {
|
|
558
|
+
return resolve({ exitCode: 127, output: String(e.message), ms: 0, timedOut: false, spawnError: String(e.message) });
|
|
559
|
+
}
|
|
560
|
+
// If crossexam itself is killed mid-run, the next run's sweep needs to know
|
|
561
|
+
// what was still running against this copy.
|
|
562
|
+
const container = method === 'docker' ? args[args.indexOf('--name') + 1] : null;
|
|
563
|
+
updateManifest(copy.root, { child: child.pid, posixGroup: posix, container, startedAt: new Date().toISOString() });
|
|
564
|
+
let output = '';
|
|
565
|
+
const keep = (d) => {
|
|
566
|
+
output += d;
|
|
567
|
+
if (output.length > OUTPUT_CAP * 2) output = output.slice(-OUTPUT_CAP);
|
|
568
|
+
};
|
|
569
|
+
child.stdout.on('data', keep);
|
|
570
|
+
child.stderr.on('data', keep);
|
|
571
|
+
let timedOut = false;
|
|
572
|
+
const timer = setTimeout(() => {
|
|
573
|
+
timedOut = true;
|
|
574
|
+
cleanup();
|
|
575
|
+
killTree(child.pid, posix);
|
|
576
|
+
}, timeoutMs);
|
|
577
|
+
child.on('close', (code, signal) => {
|
|
578
|
+
clearTimeout(timer);
|
|
579
|
+
if (signal && !timedOut) output += `\n[crossexam] the test process was killed by ${signal} (a resource limit was probably hit)`;
|
|
580
|
+
resolve({ exitCode: code ?? 1, output, ms: Date.now() - t0, timedOut, signal: signal || null });
|
|
581
|
+
});
|
|
582
|
+
child.on('error', (e) => {
|
|
583
|
+
clearTimeout(timer);
|
|
584
|
+
resolve({ exitCode: 127, output: String(e.message), ms: Date.now() - t0, timedOut: false, spawnError: String(e.message) });
|
|
585
|
+
});
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function killTree(pid, posix) {
|
|
590
|
+
if (!pid) return;
|
|
591
|
+
try {
|
|
592
|
+
if (posix) process.kill(-pid, 'SIGKILL');
|
|
593
|
+
else spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
594
|
+
} catch {
|
|
595
|
+
/* already gone */
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** Hash files so we can prove the working tree came through untouched. */
|
|
600
|
+
export function fingerprint(cwd, files) {
|
|
601
|
+
const out = {};
|
|
602
|
+
for (const f of files) {
|
|
603
|
+
try {
|
|
604
|
+
out[f] = sha(fs.readFileSync(path.join(cwd, f)));
|
|
605
|
+
} catch {
|
|
606
|
+
out[f] = null;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
return out;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** Git state that must not change: HEAD, every ref, the stash, the index. */
|
|
613
|
+
export function gitState(cwd) {
|
|
614
|
+
const g = (args) => {
|
|
615
|
+
try {
|
|
616
|
+
return git(cwd, args);
|
|
617
|
+
} catch {
|
|
618
|
+
return null;
|
|
619
|
+
}
|
|
620
|
+
};
|
|
621
|
+
const dir = g(['rev-parse', '--absolute-git-dir']);
|
|
622
|
+
let index = null;
|
|
623
|
+
try {
|
|
624
|
+
index = dir ? sha(fs.readFileSync(path.join(dir.trim(), 'index'))) : null;
|
|
625
|
+
} catch {}
|
|
626
|
+
return { head: g(['rev-parse', 'HEAD']), refs: g(['for-each-ref', '--format=%(refname) %(objectname)']), stash: g(['stash', 'list']), status: g(['status', '--porcelain=v1', '-uall']), index };
|
|
627
|
+
}
|