Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

feat(runners): a remote file denial is classified on the runner [I1,C7]

Corey Olson99e01d770297
diff --git a/src/gate.js b/src/gate.js
index bb2e99c5..136a1a66 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -6,8 +6,8 @@
*/
import { spawn, spawnSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
-import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
+import { dirname, isAbsolute, join, relative, sep } from 'node:path';
import { availableParallelism } from 'node:os';
import { fileURLToPath } from 'node:url';
import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked } from './git.js';
@@ -20,6 +20,10 @@ import { checkNeedsBrowser, testsNeedBrowser } from './browser-admission.js';
import { timingFromOutput, timingRunner } from './timing.js';
import { landingShardProfile } from './landing-shards.js';
import { RunnerDropped, runOnRunner, runOnRunnerAsync, runnerSource } from './runners.js';
+import { sandboxBlockedOperation, sandboxBlockedScanner } from './sandbox-denial.js';
+
+// Callers keep importing the classifier from the gate; the runner worker imports it directly.
+export { sandboxBlockedOperation, sandboxBlockedScanner };
const STAMP = 'pullboard-gate-green';
const LOG = 'pullboard-gate.log';
@@ -175,139 +179,6 @@ export function runShell(root, command, { pipefail = false, env = {} } = {}) {
sandboxBlocked: result.status === 0 ? null : sandboxBlockedOperation(root, output) };
}
-/** Resolve existing path prefixes so a symlink cannot hide an outside-worktree operation. */
-function diagnosticPath(path) {
- let current = resolve(path);
- const missing = [];
- for (;;) {
- try { return resolve(realpathSync(current), ...missing); }
- catch (error) {
- if (!['ENOENT', 'ENOTDIR'].includes(error.code)) return null;
- const parent = dirname(current);
- if (parent === current) return null;
- missing.unshift(relative(parent, current));
- current = parent;
- }
- }
-}
-
-/** Describe one OS permission message, resolving file targets against the command's worktree. */
-function permissionOperation(root, message, { includeFilePaths = true } = {}) {
- const network = /^(listen|bind) (EPERM|EACCES)\b/u.exec(message);
- if (network) return { code: network[2], syscall: network[1], operation: `${network[1]} (${network[2]})` };
- if (!includeFilePaths) return null;
- const file = /^(EPERM|EACCES): [^\n]*?, (open|mkdir|read|write|rename|unlink|scandir|access) (['"])([^\n]+?)\3(?= -> |$)/u.exec(message);
- const python = /^PermissionError: \[Errno (?:1|13)\] [^\n]*?: ['"]([^'"\n]+)['"]/u.exec(message);
- if (!file && !python) return null;
- const path = diagnosticPath(resolve(root, file ? file[4] : python[1]));
- const tree = diagnosticPath(root);
- if (!path || !tree) return null;
- const within = relative(tree, path);
- if (within !== '..' && !within.startsWith('../') && !isAbsolute(within)) return null;
- const code = file ? file[1] : 'EACCES';
- return { code, path, syscall: file ? file[2] : null,
- operation: `${file ? file[2] : 'file access'} ${JSON.stringify(path)} (${code})` };
-}
-
-/** Decode the single-line quoted YAML scalars emitted by Node's TAP reporter. */
-function tapScalar(value) {
- if (value.startsWith('"')) {
- try { return JSON.parse(value); } catch { return null; }
- }
- if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replace(/''/gu, "'");
- return /^[A-Z_]+$/u.test(value) ? value : null;
-}
-
-/** Scan complete lines with bounded TAP state so assertion messages cannot impersonate OS codes. */
-export function sandboxBlockedScanner(root, { includeFilePaths = true } = {}) {
- let failureIndent = null;
- let fieldIndent = null;
- let permission = null;
- let code = null;
- let comment = null;
- let startup = null;
- let failureMessage = null;
- let failureType = false;
- let exitCode = null;
- /** Retain one pending fatal diagnostic and the current failed TAP record. */
- return (raw) => {
- const line = raw.trim().replace(/^#\s*/u, '');
- const indent = raw.length - raw.trimStart().length;
- // Node's TAP reporter prints test-console output as comments and assertion details
- // as indented YAML. Neither is a standalone gate diagnostic, even when it contains
- // text that looks exactly like an operating-system denial.
- if (indent === 0 && !raw.startsWith('#') && /^(?:Error: |PermissionError: )/u.test(line)) {
- const direct = permissionOperation(root, line.replace(/^Error: /u, ''), { includeFilePaths });
- if (direct) return direct.operation;
- }
- if (/^TAP version \d+$/u.test(raw)) {
- comment = null; startup = null;
- failureIndent = null; fieldIndent = null; permission = null; code = null;
- failureMessage = null; failureType = false; exitCode = null;
- }
- // Uncaught module-load errors are comments too. Keep their complete Node fatal
- // diagnostic pending; it is evidence only if the following file record failed
- // to start. A test logging a caught error and then asserting is not that record.
- if (indent === 0 && raw.startsWith('#')) {
- if (line.startsWith('Error: ')) {
- const operation = permissionOperation(root, line.slice('Error: '.length), { includeFilePaths });
- comment = operation ? { operation, code: null, syscall: null, path: null, closed: false, fatal: false } : null;
- } else if (comment) {
- const field = /^(code|syscall|path): (.*)$/u.exec(line);
- if (field) comment[field[1]] = tapScalar(field[2].replace(/,$/u, ''));
- else if (line === '}') comment.closed = true;
- else if (/^Node\.js v\d+\./u.test(line)) comment.fatal = true;
- else if (line && !/^at |^errno: |^address: |^port: /u.test(line)
- && !(comment.closed && comment.fatal && line.startsWith('Subtest: '))) comment = null;
- }
- }
- if (/^(?:not )?ok \d+\b/u.test(line)) {
- failureIndent = /^not ok /u.test(line) ? indent : null;
- const operation = comment?.operation;
- startup = failureIndent !== null && comment?.closed && comment.fatal
- && comment.code === operation.code && comment.syscall === operation.syscall
- && (!operation.path || (typeof comment.path === 'string'
- && diagnosticPath(resolve(root, comment.path)) === operation.path)) ? operation : null;
- comment = null;
- fieldIndent = null; permission = null; code = null;
- failureMessage = null; failureType = false; exitCode = null;
- } else if (line === '---' && failureIndent !== null && indent === failureIndent + 2) {
- fieldIndent = indent;
- } else if (line === '...' && indent === fieldIndent) {
- failureIndent = null; fieldIndent = null; permission = null; code = null;
- startup = null; comment = null;
- failureMessage = null; failureType = false; exitCode = null;
- } else if (fieldIndent !== null && indent === fieldIndent) {
- const field = /^(error|code|failureType|exitCode): (.*)$/u.exec(line);
- if (field) {
- const value = tapScalar(field[2]);
- if (field[1] === 'error') {
- failureMessage = value;
- permission = typeof value === 'string' ? permissionOperation(root, value, { includeFilePaths }) : null;
- } else if (field[1] === 'code') {
- code = value;
- if (code !== 'ERR_TEST_FAILURE') startup = null;
- } else if (field[1] === 'failureType') failureType = value === 'testCodeFailure' || field[2] === 'testCodeFailure';
- else exitCode = /^[1-9]\d*$/u.test(field[2]) && Number.isSafeInteger(Number(field[2])) ? Number(field[2]) : null;
- if (permission && permission.code === code) return permission.operation;
- if (startup && code === 'ERR_TEST_FAILURE' && failureMessage === 'test failed'
- && failureType && exitCode !== null) return startup.operation;
- }
- }
- return null;
- };
-}
-
-/** Recognize concrete OS permission diagnostics, keeping ordinary assertion failures ordinary. */
-export function sandboxBlockedOperation(root, output, options) {
- const scan = sandboxBlockedScanner(root, options);
- for (const line of output.split('\n')) {
- const operation = scan(line);
- if (operation) return operation;
- }
- return null;
-}
-
/** Refuse an environment-blocked proof after its ordinary raw logs and timings are persisted. */
export function refuseSandboxBlocked(run) {
if (run.sandboxBlocked) throw new Refused('SANDBOX_BLOCKED',
diff --git a/src/runner-worker.js b/src/runner-worker.js
index 925143a6..04fe01df 100644
--- a/src/runner-worker.js
+++ b/src/runner-worker.js
@@ -7,6 +7,7 @@ import { delimiter, dirname, isAbsolute, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import * as resourceApi from './resources.js';
import { parseProcessCensus } from './process-census.js';
+import { fileDenialWatcher } from './sandbox-denial.js';
import { once } from 'node:events';
import { pipeline } from 'node:stream/promises';
@@ -131,7 +132,7 @@ async function readSpec() {
tagNames.add(tag.name);
if (tag.chain.length ? tag.chain[0] !== tag.object : tag.object !== tag.peeledCommit) throw new Error('invalid tag manifest');
}
- const runtimeNames = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js'];
+ const runtimeNames = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js'];
if (Object.keys(value.runtime.files).length !== runtimeNames.length
|| runtimeNames.some(name => typeof value.runtime.files[name] !== 'string')) throw new Error('invalid work specification');
if (createHash('sha256').update(JSON.stringify(value.runtime.files)).digest('hex') !== value.runtime.sha256) throw new Error('invalid trusted runtime');
@@ -1039,7 +1040,10 @@ async function stopOwnedGroup(pid, closed, tracker) {
await closed;
}
-/** Run the exact requested command in its isolated checkout, retaining raw output and real test exit status. */
+/**
+ * Run the exact requested command in its isolated checkout, retaining raw output and real test exit status.
+ * A failed command also carries any file denial's evidence, classified here against this checkout (#706).
+ */
async function runCommand(spec, root, env, sink, tracker) {
let shell = '/bin/sh';
let args = ['-c', spec.command];
@@ -1058,9 +1062,10 @@ async function runCommand(spec, root, env, sink, tracker) {
let writes = Promise.resolve();
const closed = owned.closed;
const onDrop = () => { sink.pipeFailed = true; transportDrop(); };
+ const denials = fileDenialWatcher(root);
const forward = stream => stream.on('data', part => {
stream.pause();
- if (!outputError) writes = writes.then(() => sink.write(part)).then(() => stream.resume()).catch(error => { outputError = error; onDrop(); });
+ if (!outputError) writes = writes.then(() => { denials.push(part); return sink.write(part); }).then(() => stream.resume()).catch(error => { outputError = error; onDrop(); });
});
forward(child.stdout); forward(child.stderr);
const result = await closed;
@@ -1075,7 +1080,9 @@ async function runCommand(spec, root, env, sink, tracker) {
if (outputError) throw outputError;
if (sink.pipeFailed) return { code: 1, signal: result.signal ?? 'SIGHUP' };
if (result.error) throw result.error;
- return { code: Number.isInteger(result.code) ? result.code : 1, signal: result.signal ?? null };
+ const code = Number.isInteger(result.code) ? result.code : 1;
+ const denial = code === 0 && !result.signal ? null : denials.end();
+ return { code, signal: result.signal ?? null, ...(denial ? { denial } : {}) };
}
/** Send the single nonce-bound result line after the complete merged output has drained. */
@@ -1083,7 +1090,7 @@ async function receipt(spec, fields, sink) {
await flushStdout();
const body = { id: spec.id, commit: spec.commit, tree: spec.tree, code: fields.code, signal: fields.signal,
runtimeSha256: spec.runtime.sha256, toolingSha256: spec.tooling.sha256, root: fields.root ?? '', outputSha256: sink.hash.digest('hex'), wallMs: Math.max(0, Date.now() - sink.wallStart),
- ...(fields.refused ? { refused: fields.refused } : {}) };
+ ...(fields.refused ? { refused: fields.refused } : {}), ...(fields.denial ? { denial: fields.denial } : {}) };
const encoded = Buffer.from(JSON.stringify(body)).toString('base64');
await new Promise((resolveWrite, rejectWrite) => process.stderr.write(`${RECEIPT} ${spec.id} ${encoded}\n`, error => error ? rejectWrite(error) : resolveWrite()));
}
diff --git a/src/runners.js b/src/runners.js
index 19e539d6..c5c04b2c 100644
--- a/src/runners.js
+++ b/src/runners.js
@@ -11,6 +11,7 @@ import { configFromSource, defaults } from './config.js';
import { blockedPaths, secretsIn } from './hooks.js';
import { cleanGitEnvironment, headCommit, headTree, isClean, repoInfo, untracked } from './git.js';
import { Refused } from './refused.js';
+import { remoteFileDenial } from './sandbox-denial.js';
// Budget: 64 MiB bounds worst-case JSON bridge escaping below Node string limits.
const MAX_OUTPUT_BYTES = 64 * 1024 ** 2;
@@ -18,7 +19,7 @@ const MAX_BLOB_BYTES = 8 * 1024 ** 2;
const MAX_HISTORY_TAGS = 1_024;
const MAX_TAG_CHAIN = 8;
const TOOL_ROOT = fileURLToPath(new URL('../', import.meta.url));
-const RUNTIME_NAMES = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js'];
+const RUNTIME_NAMES = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js'];
/** Validate an SSH destination as one argument, never a command or an SSH option. */
export function validateRunner(value) {
@@ -434,7 +435,10 @@ function resultFrom(request, result) {
// The runner answered, so this is a named failure, not a dropped transport to requeue.
throw new Refused('RUNNER_SETUP_REFUSED', `runner ${request.runner.host} refused this run before it started: [${receipt.refused}] from its own resource pool; run pullboard resources and pullboard settings on ${request.runner.host} to fix that pool, then run again`);
}
- return { isGreen: receipt.code === 0 && !receipt.signal, output: output.toString('utf8'),
+ // The runner classified any file denial against its own checkout; only its evidence is trusted here.
+ const sandboxBlocked = receipt.denial === undefined ? null : remoteFileDenial(receipt.denial, request.runner.host);
+ if (receipt.denial !== undefined && (!sandboxBlocked || receipt.code === 0)) throw new RunnerDropped(request.runner.host);
+ return { isGreen: receipt.code === 0 && !receipt.signal, output: output.toString('utf8'), sandboxBlocked,
seconds: Math.round(receipt.wallMs / 1000), exitCode: receipt.code,
executionRunner: request.runner.host, executionRoot: receipt.root, remoteWallMs: receipt.wallMs,
executionSource: { commit: receipt.commit, tree: receipt.tree, tooling: request.spec.tooling } };
diff --git a/src/sandbox-denial.js b/src/sandbox-denial.js
new file mode 100644
index 00000000..a44b7d40
--- /dev/null
+++ b/src/sandbox-denial.js
@@ -0,0 +1,198 @@
+/**
+ * Sandbox denials (I1, C7): the one classifier for an operating-system permission refusal in gate
+ * output, shared by the local gate and the remote runner worker. It ships to runners as a trusted
+ * runtime file, so a file denial is resolved against the worktree it happened in, on the machine
+ * it happened on, and only its evidence travels.
+ */
+import { realpathSync } from 'node:fs';
+import { dirname, isAbsolute, relative, resolve } from 'node:path';
+
+/** Resolve existing path prefixes so a symlink cannot hide an outside-worktree operation. */
+function diagnosticPath(path) {
+ let current = resolve(path);
+ const missing = [];
+ for (;;) {
+ try { return resolve(realpathSync(current), ...missing); }
+ catch (error) {
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) return null;
+ const parent = dirname(current);
+ if (parent === current) return null;
+ missing.unshift(relative(parent, current));
+ current = parent;
+ }
+ }
+}
+
+/** Describe one OS permission message, resolving file targets against the command's worktree. */
+function permissionOperation(root, message, { includeFilePaths = true } = {}) {
+ const network = /^(listen|bind) (EPERM|EACCES)\b/u.exec(message);
+ if (network) return { code: network[2], syscall: network[1], operation: `${network[1]} (${network[2]})` };
+ if (!includeFilePaths) return null;
+ const file = /^(EPERM|EACCES): [^\n]*?, (open|mkdir|read|write|rename|unlink|scandir|access) (['"])([^\n]+?)\3(?= -> |$)/u.exec(message);
+ const python = /^PermissionError: \[Errno (?:1|13)\] [^\n]*?: ['"]([^'"\n]+)['"]/u.exec(message);
+ if (!file && !python) return null;
+ const path = diagnosticPath(resolve(root, file ? file[4] : python[1]));
+ const tree = diagnosticPath(root);
+ if (!path || !tree) return null;
+ const within = relative(tree, path);
+ if (within !== '..' && !within.startsWith('../') && !isAbsolute(within)) return null;
+ const code = file ? file[1] : 'EACCES';
+ return { code, path, syscall: file ? file[2] : null,
+ operation: `${file ? file[2] : 'file access'} ${JSON.stringify(path)} (${code})` };
+}
+
+/** Decode the single-line quoted YAML scalars emitted by Node's TAP reporter. */
+function tapScalar(value) {
+ if (value.startsWith('"')) {
+ try { return JSON.parse(value); } catch { return null; }
+ }
+ if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replace(/''/gu, "'");
+ return /^[A-Z_]+$/u.test(value) ? value : null;
+}
+
+/**
+ * Scan complete lines with bounded TAP state so assertion messages cannot impersonate OS codes.
+ * With `evidence`, a hit is the whole denial (code, syscall, path, operation) rather than its words.
+ */
+export function sandboxBlockedScanner(root, { includeFilePaths = true, evidence = false } = {}) {
+ const hit = denial => evidence ? denial : denial.operation;
+ let failureIndent = null;
+ let fieldIndent = null;
+ let permission = null;
+ let code = null;
+ let comment = null;
+ let startup = null;
+ let failureMessage = null;
+ let failureType = false;
+ let exitCode = null;
+ /** Retain one pending fatal diagnostic and the current failed TAP record. */
+ return (raw) => {
+ const line = raw.trim().replace(/^#\s*/u, '');
+ const indent = raw.length - raw.trimStart().length;
+ // Node's TAP reporter prints test-console output as comments and assertion details
+ // as indented YAML. Neither is a standalone gate diagnostic, even when it contains
+ // text that looks exactly like an operating-system denial.
+ if (indent === 0 && !raw.startsWith('#') && /^(?:Error: |PermissionError: )/u.test(line)) {
+ const direct = permissionOperation(root, line.replace(/^Error: /u, ''), { includeFilePaths });
+ if (direct) return hit(direct);
+ }
+ if (/^TAP version \d+$/u.test(raw)) {
+ comment = null; startup = null;
+ failureIndent = null; fieldIndent = null; permission = null; code = null;
+ failureMessage = null; failureType = false; exitCode = null;
+ }
+ // Uncaught module-load errors are comments too. Keep their complete Node fatal
+ // diagnostic pending; it is evidence only if the following file record failed
+ // to start. A test logging a caught error and then asserting is not that record.
+ if (indent === 0 && raw.startsWith('#')) {
+ if (line.startsWith('Error: ')) {
+ const operation = permissionOperation(root, line.slice('Error: '.length), { includeFilePaths });
+ comment = operation ? { operation, code: null, syscall: null, path: null, closed: false, fatal: false } : null;
+ } else if (comment) {
+ const field = /^(code|syscall|path): (.*)$/u.exec(line);
+ if (field) comment[field[1]] = tapScalar(field[2].replace(/,$/u, ''));
+ else if (line === '}') comment.closed = true;
+ else if (/^Node\.js v\d+\./u.test(line)) comment.fatal = true;
+ else if (line && !/^at |^errno: |^address: |^port: /u.test(line)
+ && !(comment.closed && comment.fatal && line.startsWith('Subtest: '))) comment = null;
+ }
+ }
+ if (/^(?:not )?ok \d+\b/u.test(line)) {
+ failureIndent = /^not ok /u.test(line) ? indent : null;
+ const operation = comment?.operation;
+ startup = failureIndent !== null && comment?.closed && comment.fatal
+ && comment.code === operation.code && comment.syscall === operation.syscall
+ && (!operation.path || (typeof comment.path === 'string'
+ && diagnosticPath(resolve(root, comment.path)) === operation.path)) ? operation : null;
+ comment = null;
+ fieldIndent = null; permission = null; code = null;
+ failureMessage = null; failureType = false; exitCode = null;
+ } else if (line === '---' && failureIndent !== null && indent === failureIndent + 2) {
+ fieldIndent = indent;
+ } else if (line === '...' && indent === fieldIndent) {
+ failureIndent = null; fieldIndent = null; permission = null; code = null;
+ startup = null; comment = null;
+ failureMessage = null; failureType = false; exitCode = null;
+ } else if (fieldIndent !== null && indent === fieldIndent) {
+ const field = /^(error|code|failureType|exitCode): (.*)$/u.exec(line);
+ if (field) {
+ const value = tapScalar(field[2]);
+ if (field[1] === 'error') {
+ failureMessage = value;
+ permission = typeof value === 'string' ? permissionOperation(root, value, { includeFilePaths }) : null;
+ } else if (field[1] === 'code') {
+ code = value;
+ if (code !== 'ERR_TEST_FAILURE') startup = null;
+ } else if (field[1] === 'failureType') failureType = value === 'testCodeFailure' || field[2] === 'testCodeFailure';
+ else exitCode = /^[1-9]\d*$/u.test(field[2]) && Number.isSafeInteger(Number(field[2])) ? Number(field[2]) : null;
+ if (permission && permission.code === code) return hit(permission);
+ if (startup && code === 'ERR_TEST_FAILURE' && failureMessage === 'test failed'
+ && failureType && exitCode !== null) return hit(startup);
+ }
+ }
+ return null;
+ };
+}
+
+/** Recognize concrete OS permission diagnostics, keeping ordinary assertion failures ordinary. */
+export function sandboxBlockedOperation(root, output, options) {
+ const scan = sandboxBlockedScanner(root, options);
+ for (const line of output.split('\n')) {
+ const operation = scan(line);
+ if (operation) return operation;
+ }
+ return null;
+}
+
+const FILE_OPERATIONS = new Set(['open', 'mkdir', 'read', 'write', 'rename', 'unlink', 'scandir', 'access', 'file access']);
+const LINE_LIMIT = 64 * 1024;
+
+/**
+ * Watch streamed command output on the machine that ran it for a file denial outside `root`.
+ * Only the evidence leaves: the operation, that its path was outside the worktree, and the errno.
+ * Why here: a path can be resolved only on its own machine, so a controller never realpaths a
+ * remote path. An over-long line is skipped whole, as the local scanner never sees one either.
+ */
+export function fileDenialWatcher(root) {
+ const scan = sandboxBlockedScanner(root, { evidence: true });
+ const decoder = new TextDecoder();
+ let pending = '';
+ let skipping = false;
+ let found = null;
+ /** Classify one complete line unless a denial is already in hand. */
+ const take = line => {
+ const denial = found || skipping ? null : scan(line);
+ if (denial?.path) found = { operation: denial.syscall ?? 'file access', outside: true, errno: denial.code };
+ };
+ return {
+ /** Feed one raw output chunk. */
+ push(chunk) {
+ if (found) return;
+ pending += decoder.decode(chunk, { stream: true });
+ let newline;
+ while ((newline = pending.indexOf('\n')) >= 0) {
+ take(pending.slice(0, newline));
+ pending = pending.slice(newline + 1);
+ skipping = false;
+ }
+ if (pending.length > LINE_LIMIT) { pending = ''; skipping = true; }
+ },
+ /** Finish the stream and return the evidence, or null for an ordinary failure. */
+ end() {
+ pending += decoder.decode();
+ if (pending) take(pending);
+ pending = '';
+ return found;
+ },
+ };
+}
+
+/**
+ * Name a runner's file denial from its evidence alone, with the runner host; null when the
+ * evidence is not a well-formed denial, so a malformed receipt cannot pass as one.
+ */
+export function remoteFileDenial(denial, host) {
+ if (!denial || typeof denial !== 'object' || Object.keys(denial).sort().join() !== 'errno,operation,outside'
+ || !FILE_OPERATIONS.has(denial.operation) || !['EACCES', 'EPERM'].includes(denial.errno) || denial.outside !== true) return null;
+ return `${denial.operation} outside its worktree (${denial.errno}) on runner ${host}`;
+}
diff --git a/test/runners.test.js b/test/runners.test.js
index b222c892..f1196a9b 100644
--- a/test/runners.test.js
+++ b/test/runners.test.js
@@ -12,6 +12,7 @@ import { listResources, setResourceCapacity, takeResource } from '../src/resourc
import { parseProcessCensus } from '../src/process-census.js';
import { listResources as listPreRunnerResources, takeResource as takePreRunnerResource } from './fixtures/resources-pre-runners.js';
import { runFixtureChild, runFixtureChildAsync, startFixtureChild } from './fixture-child.js';
+import { refuseSandboxBlocked } from '../src/gate.js';
const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
const TEMP = [];
@@ -392,7 +393,7 @@ async function runThroughGate(repo, env, command, { browser = true, item = '663'
const result = await withGateSlot(${JSON.stringify(repo)}, lease => runProfiledShell(${JSON.stringify(repo)}, ${JSON.stringify(command)}, { gateLease: lease, landing: ${landing} }),
{ browser: ${browser}, item: ${JSON.stringify(item)}, kind: ${JSON.stringify(kind)}, landing: ${landing}, agent: 'runner-fixture' });
process.stdout.write(result.output);
-process.stdout.write('PULLBOARD_RUN_RESULT ' + JSON.stringify({ isGreen: result.isGreen, runner: result.profile.executionRunner, profile: result.profile }) + '\\n');
+process.stdout.write('PULLBOARD_RUN_RESULT ' + JSON.stringify({ isGreen: result.isGreen, runner: result.profile.executionRunner, sandboxBlocked: result.sandboxBlocked, profile: result.profile }) + '\\n');
process.exitCode = result.isGreen ? 0 : 1;
`;
try {
@@ -1543,6 +1544,74 @@ test('a refused remote setup fails the run by name [C7]', async (t) => {
}
});
+test('a remote file denial is classified on the runner [I1,C7]', { skip: process.getuid?.() === 0 && 'root reads any file' }, async (t) => {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-denial-')));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const [home, remoteHome, repo, worker, bin] = ['home', 'worker-home', 'repo', 'second-machine', 'bin'].map(name => join(dir, name));
+ const machineHome = join(home, '.pullboard');
+ const remoteMachineHome = join(remoteHome, '.pullboard');
+ const requests = join(dir, 'ssh-requests.jsonl');
+ const realpaths = join(dir, 'controller-realpaths.log');
+ const preload = join(dir, 'realpath-witness.mjs');
+ for (const folder of [repo, worker, bin, machineHome, remoteMachineHome]) mkdirSync(folder, { recursive: true });
+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));
+ // The controller logs every path it realpaths that lies on the runner, so resolving one is caught.
+ writeFileSync(preload, `import fs from 'node:fs'; import { syncBuiltinESMExports } from 'node:module';
+const real = fs.realpathSync; const native = real.native;
+const log = path => { if (String(path).includes(${JSON.stringify(remoteHome)})) fs.appendFileSync(${JSON.stringify(realpaths)}, String(path) + '\\n'); };
+fs.realpathSync = Object.assign((path, ...rest) => { log(path); return real(path, ...rest); }, { native: (path, ...rest) => { log(path); return native(path, ...rest); } });
+syncBuiltinESMExports();\n`);
+ const env = {
+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,
+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Runner Fixture', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Runner Fixture', GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ git(repo, env, 'init', '-q', '-b', 'main');
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));
+ git(repo, env, 'add', 'pullboard.json');
+ git(repo, env, 'commit', '-q', '-m', 'test: prepare remote denial fixture');
+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });
+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');
+ assert.equal(added.status, 0, added.context);
+ const controllerEnv = { ...env, NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=${pathToFileURL(preload).href}`.trim() };
+ // The unreadable file sits beside the runner's checkout, outside its worktree, on the runner only.
+ const denied = "mkdir ../denied && echo kept > ../denied/secret && chmod 000 ../denied/secret && node -e \"require('node:fs').readFileSync('../denied/secret')\"";
+ const ordinary = "node -e \"require('node:assert').strictEqual('open ../denied/secret (EACCES)', 'an ordinary assertion')\"";
+ const previous = [process.env.PULLBOARD_HOME, process.env.PULLBOARD_MACHINE_HOME];
+ process.env.PULLBOARD_HOME = home;
+ process.env.PULLBOARD_MACHINE_HOME = machineHome;
+ let held;
+ try {
+ // Fill the controller's own gate so each run goes to the runner.
+ held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,
+ agent: 'fixture-local-holder', item: 'local-holder', kind: 'force-registered-runner' });
+ const blocked = await runThroughGate(repo, controllerEnv, denied, { item: '706', requests });
+ const blockedResult = gateResult(blocked.stdout);
+ assert.equal(blockedResult.runner, HOST, fixtureResultContext(blocked));
+ assert.equal(blockedResult.isGreen, false);
+ assert.match(blocked.stdout, /EACCES: permission denied, open '\.\.\/denied\/secret'/u, 'the raw denial still comes back unchanged');
+ assert.equal(blockedResult.sandboxBlocked, `open outside its worktree (EACCES) on runner ${HOST}`,
+ `the controller names the operation and the runner host from the runner's evidence\n${fixtureResultContext(blocked)}`);
+ assert.throws(() => refuseSandboxBlocked(blockedResult), error => error.code === 'SANDBOX_BLOCKED'
+ && error.message.includes(`refused open outside its worktree (EACCES) on runner ${HOST}`), 'a remote denial asks the person');
+ const failed = await runThroughGate(repo, controllerEnv, ordinary, { item: '706', requests });
+ const failedResult = gateResult(failed.stdout);
+ assert.equal(failedResult.runner, HOST, fixtureResultContext(failed));
+ assert.equal(failedResult.isGreen, false);
+ assert.match(failed.stdout, /AssertionError/u);
+ assert.equal(failedResult.sandboxBlocked, null, 'an ordinary remote assertion failure stays ordinary');
+ assert.doesNotThrow(() => refuseSandboxBlocked(failedResult));
+ assert.equal(existsSync(realpaths) ? readFileSync(realpaths, 'utf8') : '', '', 'the controller never realpaths a runner path');
+ } finally {
+ held?.release();
+ for (const [key, value] of [['PULLBOARD_HOME', previous[0]], ['PULLBOARD_MACHINE_HOME', previous[1]]]) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ }
+});
+
test('a queued run executes on a registered runner and its result comes back [C7] (parent death drains a detached worker descendant before releasing its lease)', async (t) => {
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-parent-death-')));
t.after(() => rmSync(dir, { recursive: true, force: true }));