From b37d1d1f87e68446c7a7b0ebe24f4a092e401006 Mon Sep 17 00:00:00 2001 From: "M. Wulff" Date: Tue, 1 Dec 2026 22:37:32 +1100 Subject: [PATCH 1/5] Add yarn sandbox to run the checks of a pull request without network or access to the machine --- package.json | 1 + test/sandbox/profile.sb | 21 ++++ test/sandbox/run.js | 250 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 272 insertions(+) create mode 100644 test/sandbox/profile.sb create mode 100644 test/sandbox/run.js diff --git a/package.json b/package.json index 9c9d4e2fcd..39160d8b83 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "test-parity": "yarn build-only && BASE=$(git merge-base origin/main HEAD | cut -c1-12) && bun test/parity/run.js record ref-$BASE --ref $BASE --if-missing && bun test/parity/run.js record new --once && bun test/parity/run.js compare ref-$BASE new", "test-bind": "yarn build-only && bun test/bind/run.js", "test-runstate": "yarn build-only && bun test/runstate/run.js", + "sandbox": "node test/sandbox/run.js", "test-parity-smoke": "node test/parity/smoke.js --node=$(which node) --pack", "test-cover": "# istanbul cover -x 'lib/zt/zt.js' --dir test/coverage _mocha", "build": "yarn format && yarn build-only", diff --git a/test/sandbox/profile.sb b/test/sandbox/profile.sb new file mode 100644 index 0000000000..4dc2e8116d --- /dev/null +++ b/test/sandbox/profile.sb @@ -0,0 +1,21 @@ +(version 1) +; What code from a pull request may do. Used by run.js, checked by its self-test on every run. +(allow default) +(deny network*) +; The one port the tests may serve files on. No other server on this machine can be reached. +(allow network-bind network-inbound (local ip (param "LOCAL"))) +(allow network-outbound (remote ip (param "LOCAL"))) +(deny file-write*) +(allow file-write* (subpath (param "DIR")) (literal "/dev/null") (literal "/dev/tty") (literal "/dev/dtracehelper")) +(deny file-read-data (subpath "/Users") (subpath "/Volumes") (subpath "/private/tmp") (subpath "/private/var/folders")) +(allow file-read-data (subpath (param "DIR")) (subpath (param "MODULES")) (subpath (param "NODE")) (literal (param "BUN"))) +(deny file-write* (subpath (param "MODULES"))) +(deny mach-lookup) +(deny mach-register) +(deny appleevent-send) +(deny lsopen) +(deny job-creation) +(deny process-exec) +(allow process-exec (literal (param "BUN")) (subpath (param "NODE")) (literal "/bin/sh") (literal "/bin/bash") (literal "/usr/bin/env") (subpath (param "MODULES")) (subpath (param "DIR"))) +(deny signal) +(allow signal (target same-sandbox)) diff --git a/test/sandbox/run.js b/test/sandbox/run.js new file mode 100644 index 0000000000..87e1ba8613 --- /dev/null +++ b/test/sandbox/run.js @@ -0,0 +1,250 @@ +/* + Runs the checks of a pull request, merged with origin/main, without network, secrets or + write access to anything but a temporary folder. macOS only. + + yarn sandbox 3184 # what to read before running: the head and the files to look at + yarn sandbox 3184 8cae9b96 # runs the checks, only when this is still the head + + Run it from a checkout of main. A pull request can change this file too. + The result is what the code under test printed. It says that the code did not break the tests, + not that the code is safe: read the diff first. +*/ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const net = require('net'); +const {spawnSync, execFileSync} = require('child_process'); + +const root = path.join(__dirname, '..', '..'); +const [pr, reviewed] = process.argv.slice(2); +const git = (...a) => + execFileSync('git', a, {cwd: root, encoding: 'utf8', maxBuffer: 1 << 28}).trim(); +const stop = message => { + console.error(message); + process.exit(2); +}; +if (process.platform !== 'darwin') stop('The sandbox uses sandbox-exec, which is macOS only'); +if (!/^\d+$/.test(pr || '')) stop('Usage: yarn sandbox [reviewed sha]'); + +const ref = 'refs/sandbox/' + pr; +git('fetch', '-q', '--no-tags', 'origin', 'main', '+refs/pull/' + pr + '/head:' + ref); +const head = git('rev-parse', ref); +git('update-ref', '-d', ref); +const base = git('merge-base', 'origin/main', head); + +// Files that run on their own, decide what is run, or cannot be read in a diff +const RUNS = + /^(package\.json|yarn\.lock|build\.js|\.github\/|\.husky\/|\.git|\.?(npm|yarn|bun)|bunfig|bin\/|modules\/|test\/(bun-setup\.js|lib\/|sandbox\/|parity\/|bind\/|runstate\/|dialect\/))/; +const HIDDEN = /[\u{200b}-\u{200f}\u{202a}-\u{202e}\u{2060}-\u{2069}]/u; +const lines = (...a) => + git(...a) + .split('\n') + .filter(Boolean); +const binary = new Set( + lines('diff', '--numstat', '--no-renames', base, head) + .filter(l => l.startsWith('-\t-\t')) + .map(l => l.split('\t')[2]) +); +console.log('Pull request ' + pr + ' is at ' + head); +for (const line of lines('diff', '--raw', '--no-renames', '--abbrev=40', base, head)) { + const [info, file] = line.split('\t'); + const [was, mode] = info.slice(1).split(' '); + const notes = []; + if (RUNS.test(file)) notes.push('runs or decides what is run'); + if (mode === '120000') notes.push('symlink'); + if (mode === '160000') notes.push('submodule'); + if (mode === '100755' && was !== mode) notes.push('executable'); + if (binary.has(file)) notes.push('binary'); + if (file === 'src/alasqlparser.js') notes.push('not used, generated from the grammar'); + if (mode.startsWith('100') && HIDDEN.test(git('show', head + ':' + file))) + notes.push('hidden characters'); + console.log(' ' + file + (notes.length ? ' <- ' + notes.join(', ') : '')); +} +if (!reviewed) + stop('Read the diff (gh pr diff ' + pr + '), then: yarn sandbox ' + pr + ' ' + head.slice(0, 8)); +if (reviewed.length < 7 || !head.startsWith(reviewed)) + stop('The head is not ' + reviewed + '. Nothing was run.'); + +// The merged files, with no .git folder +const merge = spawnSync('git', ['merge-tree', '--write-tree', '--name-only', 'origin/main', head], { + cwd: root, + encoding: 'utf8', +}); +const [tree, ...rest] = merge.stdout.split('\n'); +const conflicts = merge.status + ? rest.slice(0, rest.indexOf('')).filter(f => f !== 'src/alasqlparser.js') + : []; +if (conflicts.length || !tree) stop('Conflicts with main: ' + conflicts.join(', ') + merge.stderr); +const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'alasql-sandbox-'))); +const work = path.join(dir, 'work'); +const tmp = path.join(dir, 'tmp'); +[work, tmp].forEach(d => fs.mkdirSync(d)); +const tar = path.join(dir, 'a.tar'); +git('archive', '-o', tar, tree); +execFileSync('tar', ['-xf', tar, '-C', work]); +// A clone of our own packages (no disk space on APFS), which the code can read and not write +const modules = path.join(work, 'node_modules'); +execFileSync('cp', ['-Rc', fs.realpathSync(path.join(root, 'node_modules')), modules]); + +const which = name => + fs.realpathSync(execFileSync('/usr/bin/which', [name], {encoding: 'utf8'}).trim()); +const bun = which('bun'); +const node = path.dirname(path.dirname(which('node'))); +const bin = name => fs.realpathSync(path.join(modules, '.bin', name)); + +const server = net.createServer().listen(0, '127.0.0.1', () => { + const port = server.address().port; + server.close(() => main(port)); +}); + +function main(port) { + const params = {DIR: dir, MODULES: modules, NODE: node, BUN: bun, LOCAL: 'localhost:' + port}; + const prefix = ['-f', path.join(__dirname, 'profile.sb')]; + for (const k in params) prefix.unshift('-D', k + '=' + params[k]); + const env = { + PATH: [path.dirname(bun), node + '/bin', '/usr/bin', '/bin'].join(':'), + HOME: tmp, + TMPDIR: tmp, + LANG: 'en_US.UTF-8', + ALASQL_TEST_PORT: String(port), + }; + const run = (cmd, args) => + spawnSync('/usr/bin/sandbox-exec', [...prefix, cmd, ...args], { + cwd: work, + env, + encoding: 'utf8', + timeout: 5 * 60000, + maxBuffer: 1 << 28, + stdio: ['ignore', 'pipe', 'pipe'], + }); + + // Self-test. Each of these must be refused, or nothing of the pull request is run. + const q = JSON.stringify; + const probes = { + 'read the home folder': "require('fs').readdirSync(" + q(os.homedir()) + ')', + 'read the repository': "require('fs').readFileSync(" + q(path.join(root, 'package.json')) + ')', + 'write outside': + "require('fs').writeFileSync(" + q(path.join(modules, '.sandbox-probe')) + ",'')", + 'start a program': + "require('child_process').execFileSync('/usr/bin/open',['-h'],{stdio:'ignore'})", + }; + for (const name in probes) { + const p = run(node + '/bin/node', [ + '-e', + 'try{' + probes[name] + "}catch(e){process.exit(e.code==='EPERM'?42:1)}", + ]); + if (p.status !== 42) + stop('The sandbox does not refuse to ' + name + '. Nothing was run. ' + p.stderr); + } + const online = run(node + '/bin/node', [ + '-e', + "require('net').connect(443,'1.1.1.1').on('error',e=>process.exit(e.code==='EPERM'?42:1)).on('connect',()=>process.exit(0))", + ]); + if (online.status !== 42) stop('The sandbox does not refuse the network. Nothing was run.'); + console.log('\nThe sandbox refuses files, programs, writes and network. Running the checks.'); + + const tests = fs + .readdirSync(path.join(work, 'test')) + .filter(f => /^test[0-9-].*\.js$/.test(f)) + .sort() + .map(f => './test/' + f); + // The system log has whole seconds, and the refusals of the self-test are not of interest + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1500); + const started = new Date(); + const results = []; + const step = (name, cmd, args) => { + const r = run(cmd, args); + const text = (r.stdout || '') + (r.stderr || ''); + fs.writeFileSync(path.join(dir, name.replace(/\W+/g, '-') + '.log'), text); + results.push([ + name, + r.status, + (text.match(/^ ?\d+ (pass|skip|fail)$/gm) || []).map(s => s.trim()).join(', '), + ]); + if (r.status !== 0) + console.log( + text + .split('\n') + .filter(l => /^\(fail\)|rror/.test(l)) + .slice(0, 25) + .join('\n') + ); + return r.status === 0; + }; + const ok = + step('parser', node + '/bin/node', [ + bin('jison'), + './src/alasqlparser.jison', + '-o', + './src/alasqlparser.js', + ]) && + step('build', bun, ['build.js']) && + step('version', node + '/bin/node', [ + bin('rexreplace'), + 'PACKAGE_VERSION', + require(path.join(root, 'package.json')).version, + '-Iq', + 'dist/**/*.js', + ]); + if (ok) { + step('tests', bun, ['test', '--dots', '--preload', './test/bun-setup.js', ...tests]); + step('dialect test', bun, ['test/dialect/run.js']); + step('binding check', bun, ['test/bind/run.js']); + step('run-state check', bun, ['test/runstate/run.js']); + } + + // What the kernel refused while the checks ran + const when = d => + new Date(d - d.getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace('T', ' '); + const log = spawnSync( + '/usr/bin/log', + [ + 'show', + '--style', + 'compact', + '--start', + when(started), + '--predicate', + 'sender == "Sandbox" AND eventMessage CONTAINS "deny"', + ], + {encoding: 'utf8', maxBuffer: 1 << 28, timeout: 120000} + ); + if (log.status !== 0) + console.log('\nThe system log could not be read, so refused attempts are not known.'); + const denied = {}; + // Refused on every run of main too + const NOISE = + /^(mach-lookup com\.apple\.(system\.(opendirectoryd|notification_center)|logd|bsd\.dirhelper)|network-outbound \/private\/var\/run\/syslog)/; + for (const m of (log.stdout || '').matchAll( + /Sandbox: (bun|node|sh|bash|env)\(\d+\) deny\(\d+\) (.*)/g + )) { + const what = m[1] + ' ' + m[2]; + if (NOISE.test(m[2]) || dir.startsWith(m[2].replace('file-read-data ', ''))) continue; + denied[what] = (denied[what] || 0) + 1; + } + + console.log( + '\n' + + pr + + ' at ' + + head.slice(0, 8) + + ' merged with main ' + + git('rev-parse', '--short=8', 'origin/main') + ); + for (const [name, status, counts] of results) + console.log( + ' ' + + (status === 0 ? 'ok ' : 'FAILED') + + ' ' + + name + + (counts ? ' ' + counts : '') + + (status === null ? ' (timeout)' : '') + ); + const list = Object.entries(denied).sort((a, b) => b[1] - a[1]); + console.log('\nRefused by the sandbox: ' + (list.length ? '' : 'nothing')); + for (const [what, n] of list.slice(0, 40)) console.log(' ' + n + 'x ' + what); + console.log('\nLogs: ' + dir); + // 3 is for code that passes and tried something it may not do + if (!ok || results.some(r => r[1] !== 0) || log.status !== 0) process.exit(1); + process.exit(list.length ? 3 : 0); +} From 4c4e038e0c5e84d2cff2d7549585ba872dda1cfb Mon Sep 17 00:00:00 2001 From: "M. Wulff" Date: Wed, 2 Dec 2026 22:00:42 +1100 Subject: [PATCH 2/5] Add yarn test-safe to run all checks of a checkout in the sandbox and list what it refused --- package.json | 1 + test/sandbox/sandboxed.sh | 107 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100755 test/sandbox/sandboxed.sh diff --git a/package.json b/package.json index 39160d8b83..f204b394c3 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "test-bind": "yarn build-only && bun test/bind/run.js", "test-runstate": "yarn build-only && bun test/runstate/run.js", "sandbox": "node test/sandbox/run.js", + "test-safe": "bash test/sandbox/sandboxed.sh", "test-parity-smoke": "node test/parity/smoke.js --node=$(which node) --pack", "test-cover": "# istanbul cover -x 'lib/zt/zt.js' --dir test/coverage _mocha", "build": "yarn format && yarn build-only", diff --git a/test/sandbox/sandboxed.sh b/test/sandbox/sandboxed.sh new file mode 100755 index 0000000000..7651a0d740 --- /dev/null +++ b/test/sandbox/sandboxed.sh @@ -0,0 +1,107 @@ +#!/bin/bash +# Runs all checks of this checkout without network, secrets or write access to anything but a +# temporary folder, and lists what the code tried that the sandbox refused. macOS only. +# +# yarn test-safe +# +# Run it from a copy you trust. The code under test can change this file and package.json too. +# Exit 0 when the checks pass and nothing was refused, 3 when they pass and something was refused, +# 1 when a check fails, 2 when the sandbox does not work. + +set -u +stop() { + echo "$1" + exit 2 +} +[ "$(uname)" = Darwin ] || stop 'The sandbox uses sandbox-exec, which is macOS only' +here=$(cd "$(dirname "$0")" && pwd -P) +root=$(cd "$here/../.." && pwd -P) +dir=$(cd "$(mktemp -d "${TMPDIR:-/tmp}/alasql-safe-XXXXXX")" && pwd -P) +work=$dir/work +tmp=$dir/tmp +mkdir "$work" "$tmp" + +# A copy of the checkout without .git, and a clone of the packages (no disk space on APFS) +rsync -a --exclude=/.git --exclude=/node_modules "$root/" "$work/" +cp -Rc "$(cd "$root/node_modules" && pwd -P)" "$work/node_modules" +modules=$work/node_modules +bun=$(realpath "$(which bun)") +# Not the node of PATH, which yarn replaces with a script in a temporary folder +node=$(dirname "$(dirname "$(node -p 'require("fs").realpathSync(process.execPath)')")") +version=$(node -p "require('$work/package.json').version") +port=$(node -e "const s=require('net').createServer().listen(0,'127.0.0.1',()=>{console.log(s.address().port);s.close()})") + +run() { + (cd "$work" && env -i PATH="$(dirname "$bun"):$node/bin:/usr/bin:/bin" HOME="$tmp" TMPDIR="$tmp" \ + LANG=en_US.UTF-8 ALASQL_TEST_PORT="$port" /usr/bin/sandbox-exec -D DIR="$dir" \ + -D MODULES="$modules" -D NODE="$node" -D BUN="$bun" -D LOCAL="localhost:$port" \ + -f "$here/profile.sb" "$@") +} + +# Self-test. Each of these must be refused, or nothing is run. +probe() { + run "$node/bin/node" -e "try{$2}catch(e){process.exit(e.code==='EPERM'?42:1)}" "$3" >/dev/null 2>&1 + [ $? = 42 ] || stop "The sandbox does not refuse to $1. Nothing was run." +} +probe 'read the home folder' "require('fs').readdirSync(process.argv[1])" "$HOME" +probe 'read the repository' "require('fs').readFileSync(process.argv[1])" "$root/package.json" +probe 'write outside' "require('fs').writeFileSync(process.argv[1],'')" "$modules/.sandbox-probe" +probe 'start a program' "require('child_process').execFileSync('/usr/bin/open',['-h'],{stdio:'ignore'})" '' +run "$node/bin/node" -e "require('net').connect(443,'1.1.1.1').on('error',e=>process.exit(e.code==='EPERM'?42:1)).on('connect',()=>process.exit(0))" >/dev/null 2>&1 +[ $? = 42 ] || stop 'The sandbox does not refuse the network. Nothing was run.' +echo 'The sandbox refuses files, programs, writes and network. Running the checks.' + +# The system log has whole seconds, and the refusals of the self-test are not of interest +sleep 2 +started=$(date '+%Y-%m-%d %H:%M:%S') +summary='' +failed=0 +step() { + local name=$1 log="$dir/$1.log" + shift + run "$@" >"$log" 2>&1 + local status=$? + local counts=$(grep -oE '^ ?[0-9]+ (pass|skip|fail)$' "$log" | sed 's/^ //' | paste -sd, - | sed 's/,/, /g') + if [ $status = 0 ]; then summary+=" ok $name $counts"$'\n'; else + summary+=" FAILED $name $counts"$'\n' + failed=1 + grep -E '^\(fail\)|rror' "$log" | head -25 + fi + return $status +} +tests=($(cd "$work" && ls test | grep -E '^test[0-9-].*\.js$' | sort | sed 's|^|./test/|')) +step parser "$node/bin/node" "$(realpath "$modules/.bin/jison")" ./src/alasqlparser.jison -o ./src/alasqlparser.js && + step build "$bun" build.js && + step version "$node/bin/node" "$(realpath "$modules/.bin/rexreplace")" PACKAGE_VERSION "$version" -Iq 'dist/**/*.js' && + { + step tests "$bun" test --dots --preload ./test/bun-setup.js "${tests[@]}" + step dialect "$bun" test/dialect/run.js + step bind "$bun" test/bind/run.js + step runstate "$bun" test/runstate/run.js + } + +# What the kernel refused while the checks ran, without what every run of main is refused +/usr/bin/log show --style compact --start "$started" \ + --predicate 'sender == "Sandbox" AND eventMessage CONTAINS "deny"' >"$dir/refused.log" 2>&1 || + { + echo 'The system log could not be read, so refused attempts are not known.' + failed=1 + } +refused=$(grep -oE 'Sandbox: (bun|node|sh|bash|env)\([0-9]+\) deny\([0-9]+\) .*' "$dir/refused.log" | + sed -E 's/^Sandbox: ([a-z]+)\([0-9]+\) deny\([0-9]+\) /\1 /' | + grep -vE '^[a-z]+ (mach-lookup com\.apple\.(system\.(opendirectoryd|notification_center)|logd|bsd\.dirhelper)|network-outbound /private/var/run/syslog)' | + awk -v d="$dir" 'match($0, /^[a-z]+ file-read-data /) { if (index(d, substr($0, RLENGTH + 1)) == 1) next } { print }' | + sort | uniq -c | sort -rn | head -40) + +echo +echo "$root at $(git -C "$root" rev-parse --short=8 HEAD 2>/dev/null)$(git -C "$root" diff --quiet HEAD 2>/dev/null || echo ' with changes')" +printf '%s' "$summary" +echo +if [ -z "$refused" ]; then echo 'Refused by the sandbox: nothing'; else + echo 'Refused by the sandbox. Read this before you trust the code.' + echo "$refused" +fi +echo +echo "Logs: $dir" +[ $failed = 0 ] || exit 1 +[ -z "$refused" ] || exit 3 From bfbfd7598d39ba9364596f3c8cf6011238bc4c2e Mon Sep 17 00:00:00 2001 From: "M. Wulff" Date: Wed, 2 Dec 2026 22:06:45 +1100 Subject: [PATCH 3/5] Read the sandbox profile of yarn test-safe from main and list changed files that run --- package.json | 2 +- test/sandbox/sandboxed.sh | 32 ++++++++++++++++++++++++-------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index f204b394c3..ce60caeb74 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "test-bind": "yarn build-only && bun test/bind/run.js", "test-runstate": "yarn build-only && bun test/runstate/run.js", "sandbox": "node test/sandbox/run.js", - "test-safe": "bash test/sandbox/sandboxed.sh", + "test-safe": "git fetch -q origin main && bash -c \"$(git show ${SANDBOX_REF:-origin/main}:test/sandbox/sandboxed.sh)\" sandboxed", "test-parity-smoke": "node test/parity/smoke.js --node=$(which node) --pack", "test-cover": "# istanbul cover -x 'lib/zt/zt.js' --dir test/coverage _mocha", "build": "yarn format && yarn build-only", diff --git a/test/sandbox/sandboxed.sh b/test/sandbox/sandboxed.sh index 7651a0d740..735cc3b73f 100755 --- a/test/sandbox/sandboxed.sh +++ b/test/sandbox/sandboxed.sh @@ -4,7 +4,12 @@ # # yarn test-safe # -# Run it from a copy you trust. The code under test can change this file and package.json too. +# The code under test can change package.json and this file, so for code you have not written start +# the copy of main with a command that is not in the checkout, like this alias in ~/.zshrc. +# +# alias test-safe='git fetch -q origin main && bash -c "$(git show origin/main:test/sandbox/sandboxed.sh)" sandboxed' +# +# The profile is read from main too (SANDBOX_REF), and is kept where the code under test cannot write. # Exit 0 when the checks pass and nothing was refused, 3 when they pass and something was refused, # 1 when a check fails, 2 when the sandbox does not work. @@ -14,12 +19,23 @@ stop() { exit 2 } [ "$(uname)" = Darwin ] || stop 'The sandbox uses sandbox-exec, which is macOS only' -here=$(cd "$(dirname "$0")" && pwd -P) -root=$(cd "$here/../.." && pwd -P) +root=$(git rev-parse --show-toplevel) || stop 'Run it in a checkout of alasql' +ref=${SANDBOX_REF:-origin/main} dir=$(cd "$(mktemp -d "${TMPDIR:-/tmp}/alasql-safe-XXXXXX")" && pwd -P) work=$dir/work tmp=$dir/tmp -mkdir "$work" "$tmp" +safe=$dir.safe +mkdir "$work" "$tmp" "$safe" +git -C "$root" show "$ref:test/sandbox/profile.sb" >"$safe/profile.sb" || stop "No profile on $ref" + +# Files that run on their own or decide what is run. Read their diff before you trust the result. +changed=$( + { + git -C "$root" diff --name-only "$ref" + git -C "$root" ls-files --others --exclude-standard + } | sort -u | grep -E '^(package\.json|yarn\.lock|build\.js|\.github/|\.husky/|\.?(npm|yarn|bun)|bunfig|bin/|modules/|test/(bun-setup\.js|lib/|sandbox/|parity/|bind/|runstate/|dialect/))' +) +[ -z "$changed" ] || printf 'Changed from %s, and runs or decides what is run\n%s\n\n' "$ref" "$(echo "$changed" | sed 's/^/ /')" # A copy of the checkout without .git, and a clone of the packages (no disk space on APFS) rsync -a --exclude=/.git --exclude=/node_modules "$root/" "$work/" @@ -35,7 +51,7 @@ run() { (cd "$work" && env -i PATH="$(dirname "$bun"):$node/bin:/usr/bin:/bin" HOME="$tmp" TMPDIR="$tmp" \ LANG=en_US.UTF-8 ALASQL_TEST_PORT="$port" /usr/bin/sandbox-exec -D DIR="$dir" \ -D MODULES="$modules" -D NODE="$node" -D BUN="$bun" -D LOCAL="localhost:$port" \ - -f "$here/profile.sb" "$@") + -f "$safe/profile.sb" "$@") } # Self-test. Each of these must be refused, or nothing is run. @@ -82,12 +98,12 @@ step parser "$node/bin/node" "$(realpath "$modules/.bin/jison")" ./src/alasqlpar # What the kernel refused while the checks ran, without what every run of main is refused /usr/bin/log show --style compact --start "$started" \ - --predicate 'sender == "Sandbox" AND eventMessage CONTAINS "deny"' >"$dir/refused.log" 2>&1 || + --predicate 'sender == "Sandbox" AND eventMessage CONTAINS "deny"' >"$safe/refused.log" 2>&1 || { echo 'The system log could not be read, so refused attempts are not known.' failed=1 } -refused=$(grep -oE 'Sandbox: (bun|node|sh|bash|env)\([0-9]+\) deny\([0-9]+\) .*' "$dir/refused.log" | +refused=$(grep -oE 'Sandbox: (bun|node|sh|bash|env)\([0-9]+\) deny\([0-9]+\) .*' "$safe/refused.log" | sed -E 's/^Sandbox: ([a-z]+)\([0-9]+\) deny\([0-9]+\) /\1 /' | grep -vE '^[a-z]+ (mach-lookup com\.apple\.(system\.(opendirectoryd|notification_center)|logd|bsd\.dirhelper)|network-outbound /private/var/run/syslog)' | awk -v d="$dir" 'match($0, /^[a-z]+ file-read-data /) { if (index(d, substr($0, RLENGTH + 1)) == 1) next } { print }' | @@ -102,6 +118,6 @@ if [ -z "$refused" ]; then echo 'Refused by the sandbox: nothing'; else echo "$refused" fi echo -echo "Logs: $dir" +echo "Logs: $dir and $safe" [ $failed = 0 ] || exit 1 [ -z "$refused" ] || exit 3 From c2f9fdf9079f10d55c744f91585c0a854a669831 Mon Sep 17 00:00:00 2001 From: "M. Wulff" Date: Thu, 3 Dec 2026 14:36:21 +1100 Subject: [PATCH 4/5] Allow nothing in the sandbox profile unless a rule allows it --- test/sandbox/profile.sb | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/test/sandbox/profile.sb b/test/sandbox/profile.sb index 4dc2e8116d..335d3151f0 100644 --- a/test/sandbox/profile.sb +++ b/test/sandbox/profile.sb @@ -1,21 +1,21 @@ (version 1) -; What code from a pull request may do. Used by run.js, checked by its self-test on every run. -(allow default) -(deny network*) +; What code under test may do. Used by run.js and sandboxed.sh, checked by their self-test on every run. +; Nothing is allowed unless a rule below allows it. +(deny default) +; What every program on macOS needs to start (dyld, system libraries) +(import "system.sb") +; Names, sizes and dates of files, so paths can be resolved, but not their content +(allow file-read-metadata) +; Read by system libraries, the shells and Bun on every start +(allow file-read-data (literal "/bin/sh") (literal "/bin/bash") (literal "/dev/tty") (regex #"/\.CFUserTextEncoding$") (subpath "/private/etc/ssl")) +(allow sysctl-read) +(allow process-fork) +(allow process-exec (literal (param "BUN")) (subpath (param "NODE")) (literal "/bin/sh") (literal "/bin/bash") (literal "/usr/bin/env") (subpath (param "MODULES")) (subpath (param "DIR"))) +(allow signal (target same-sandbox)) +; The temporary folder of the run, with the checkout and its test files, and the programs that run them +(allow file-read* (subpath (param "DIR")) (subpath (param "MODULES")) (subpath (param "NODE")) (literal (param "BUN"))) +(allow file-write* (subpath (param "DIR")) (literal "/dev/null") (literal "/dev/tty") (literal "/dev/dtracehelper")) +(deny file-write* (subpath (param "MODULES"))) ; The one port the tests may serve files on. No other server on this machine can be reached. (allow network-bind network-inbound (local ip (param "LOCAL"))) (allow network-outbound (remote ip (param "LOCAL"))) -(deny file-write*) -(allow file-write* (subpath (param "DIR")) (literal "/dev/null") (literal "/dev/tty") (literal "/dev/dtracehelper")) -(deny file-read-data (subpath "/Users") (subpath "/Volumes") (subpath "/private/tmp") (subpath "/private/var/folders")) -(allow file-read-data (subpath (param "DIR")) (subpath (param "MODULES")) (subpath (param "NODE")) (literal (param "BUN"))) -(deny file-write* (subpath (param "MODULES"))) -(deny mach-lookup) -(deny mach-register) -(deny appleevent-send) -(deny lsopen) -(deny job-creation) -(deny process-exec) -(allow process-exec (literal (param "BUN")) (subpath (param "NODE")) (literal "/bin/sh") (literal "/bin/bash") (literal "/usr/bin/env") (subpath (param "MODULES")) (subpath (param "DIR"))) -(deny signal) -(allow signal (target same-sandbox)) From bf447467f55c0af4ef4c627a94c28d23ee07bc7f Mon Sep 17 00:00:00 2001 From: "M. Wulff" Date: Thu, 3 Dec 2026 15:03:48 +1100 Subject: [PATCH 5/5] Run only Bun in the sandbox with access to its own folder, and fold yarn sandbox into yarn test-safe --- package.json | 1 - test/sandbox/profile.sb | 25 ++-- test/sandbox/run.js | 250 -------------------------------------- test/sandbox/sandboxed.sh | 140 +++++++++++++-------- 4 files changed, 100 insertions(+), 316 deletions(-) delete mode 100644 test/sandbox/run.js diff --git a/package.json b/package.json index ce60caeb74..21fc8a3b4e 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,6 @@ "test-parity": "yarn build-only && BASE=$(git merge-base origin/main HEAD | cut -c1-12) && bun test/parity/run.js record ref-$BASE --ref $BASE --if-missing && bun test/parity/run.js record new --once && bun test/parity/run.js compare ref-$BASE new", "test-bind": "yarn build-only && bun test/bind/run.js", "test-runstate": "yarn build-only && bun test/runstate/run.js", - "sandbox": "node test/sandbox/run.js", "test-safe": "git fetch -q origin main && bash -c \"$(git show ${SANDBOX_REF:-origin/main}:test/sandbox/sandboxed.sh)\" sandboxed", "test-parity-smoke": "node test/parity/smoke.js --node=$(which node) --pack", "test-cover": "# istanbul cover -x 'lib/zt/zt.js' --dir test/coverage _mocha", diff --git a/test/sandbox/profile.sb b/test/sandbox/profile.sb index 335d3151f0..bb346f0a94 100644 --- a/test/sandbox/profile.sb +++ b/test/sandbox/profile.sb @@ -1,21 +1,14 @@ (version 1) -; What code under test may do. Used by run.js and sandboxed.sh, checked by their self-test on every run. -; Nothing is allowed unless a rule below allows it. +; What code under test may do in yarn test-safe. Nothing is allowed unless a rule below allows it. (deny default) -; What every program on macOS needs to start (dyld, system libraries) +; What every program on macOS needs to start (dyld and the system libraries) (import "system.sb") -; Names, sizes and dates of files, so paths can be resolved, but not their content -(allow file-read-metadata) -; Read by system libraries, the shells and Bun on every start -(allow file-read-data (literal "/bin/sh") (literal "/bin/bash") (literal "/dev/tty") (regex #"/\.CFUserTextEncoding$") (subpath "/private/etc/ssl")) -(allow sysctl-read) +; Bun, from a copy in the temporary folder of the run, and the processes it starts (allow process-fork) -(allow process-exec (literal (param "BUN")) (subpath (param "NODE")) (literal "/bin/sh") (literal "/bin/bash") (literal "/usr/bin/env") (subpath (param "MODULES")) (subpath (param "DIR"))) +(allow process-exec (literal (param "BUN"))) +; The binary of esbuild from our packages, which build.js runs +(allow process-exec (literal (param "ESBUILD"))) (allow signal (target same-sandbox)) -; The temporary folder of the run, with the checkout and its test files, and the programs that run them -(allow file-read* (subpath (param "DIR")) (subpath (param "MODULES")) (subpath (param "NODE")) (literal (param "BUN"))) -(allow file-write* (subpath (param "DIR")) (literal "/dev/null") (literal "/dev/tty") (literal "/dev/dtracehelper")) -(deny file-write* (subpath (param "MODULES"))) -; The one port the tests may serve files on. No other server on this machine can be reached. -(allow network-bind network-inbound (local ip (param "LOCAL"))) -(allow network-outbound (remote ip (param "LOCAL"))) +; The temporary folder of the run, with the checkout and its test files. Nothing else. +(allow file-read* file-write* (subpath (param "DIR"))) +(deny file-write* (subpath (param "MODULES")) (literal (param "BUN"))) diff --git a/test/sandbox/run.js b/test/sandbox/run.js deleted file mode 100644 index 87e1ba8613..0000000000 --- a/test/sandbox/run.js +++ /dev/null @@ -1,250 +0,0 @@ -/* - Runs the checks of a pull request, merged with origin/main, without network, secrets or - write access to anything but a temporary folder. macOS only. - - yarn sandbox 3184 # what to read before running: the head and the files to look at - yarn sandbox 3184 8cae9b96 # runs the checks, only when this is still the head - - Run it from a checkout of main. A pull request can change this file too. - The result is what the code under test printed. It says that the code did not break the tests, - not that the code is safe: read the diff first. -*/ -const fs = require('fs'); -const os = require('os'); -const path = require('path'); -const net = require('net'); -const {spawnSync, execFileSync} = require('child_process'); - -const root = path.join(__dirname, '..', '..'); -const [pr, reviewed] = process.argv.slice(2); -const git = (...a) => - execFileSync('git', a, {cwd: root, encoding: 'utf8', maxBuffer: 1 << 28}).trim(); -const stop = message => { - console.error(message); - process.exit(2); -}; -if (process.platform !== 'darwin') stop('The sandbox uses sandbox-exec, which is macOS only'); -if (!/^\d+$/.test(pr || '')) stop('Usage: yarn sandbox [reviewed sha]'); - -const ref = 'refs/sandbox/' + pr; -git('fetch', '-q', '--no-tags', 'origin', 'main', '+refs/pull/' + pr + '/head:' + ref); -const head = git('rev-parse', ref); -git('update-ref', '-d', ref); -const base = git('merge-base', 'origin/main', head); - -// Files that run on their own, decide what is run, or cannot be read in a diff -const RUNS = - /^(package\.json|yarn\.lock|build\.js|\.github\/|\.husky\/|\.git|\.?(npm|yarn|bun)|bunfig|bin\/|modules\/|test\/(bun-setup\.js|lib\/|sandbox\/|parity\/|bind\/|runstate\/|dialect\/))/; -const HIDDEN = /[\u{200b}-\u{200f}\u{202a}-\u{202e}\u{2060}-\u{2069}]/u; -const lines = (...a) => - git(...a) - .split('\n') - .filter(Boolean); -const binary = new Set( - lines('diff', '--numstat', '--no-renames', base, head) - .filter(l => l.startsWith('-\t-\t')) - .map(l => l.split('\t')[2]) -); -console.log('Pull request ' + pr + ' is at ' + head); -for (const line of lines('diff', '--raw', '--no-renames', '--abbrev=40', base, head)) { - const [info, file] = line.split('\t'); - const [was, mode] = info.slice(1).split(' '); - const notes = []; - if (RUNS.test(file)) notes.push('runs or decides what is run'); - if (mode === '120000') notes.push('symlink'); - if (mode === '160000') notes.push('submodule'); - if (mode === '100755' && was !== mode) notes.push('executable'); - if (binary.has(file)) notes.push('binary'); - if (file === 'src/alasqlparser.js') notes.push('not used, generated from the grammar'); - if (mode.startsWith('100') && HIDDEN.test(git('show', head + ':' + file))) - notes.push('hidden characters'); - console.log(' ' + file + (notes.length ? ' <- ' + notes.join(', ') : '')); -} -if (!reviewed) - stop('Read the diff (gh pr diff ' + pr + '), then: yarn sandbox ' + pr + ' ' + head.slice(0, 8)); -if (reviewed.length < 7 || !head.startsWith(reviewed)) - stop('The head is not ' + reviewed + '. Nothing was run.'); - -// The merged files, with no .git folder -const merge = spawnSync('git', ['merge-tree', '--write-tree', '--name-only', 'origin/main', head], { - cwd: root, - encoding: 'utf8', -}); -const [tree, ...rest] = merge.stdout.split('\n'); -const conflicts = merge.status - ? rest.slice(0, rest.indexOf('')).filter(f => f !== 'src/alasqlparser.js') - : []; -if (conflicts.length || !tree) stop('Conflicts with main: ' + conflicts.join(', ') + merge.stderr); -const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'alasql-sandbox-'))); -const work = path.join(dir, 'work'); -const tmp = path.join(dir, 'tmp'); -[work, tmp].forEach(d => fs.mkdirSync(d)); -const tar = path.join(dir, 'a.tar'); -git('archive', '-o', tar, tree); -execFileSync('tar', ['-xf', tar, '-C', work]); -// A clone of our own packages (no disk space on APFS), which the code can read and not write -const modules = path.join(work, 'node_modules'); -execFileSync('cp', ['-Rc', fs.realpathSync(path.join(root, 'node_modules')), modules]); - -const which = name => - fs.realpathSync(execFileSync('/usr/bin/which', [name], {encoding: 'utf8'}).trim()); -const bun = which('bun'); -const node = path.dirname(path.dirname(which('node'))); -const bin = name => fs.realpathSync(path.join(modules, '.bin', name)); - -const server = net.createServer().listen(0, '127.0.0.1', () => { - const port = server.address().port; - server.close(() => main(port)); -}); - -function main(port) { - const params = {DIR: dir, MODULES: modules, NODE: node, BUN: bun, LOCAL: 'localhost:' + port}; - const prefix = ['-f', path.join(__dirname, 'profile.sb')]; - for (const k in params) prefix.unshift('-D', k + '=' + params[k]); - const env = { - PATH: [path.dirname(bun), node + '/bin', '/usr/bin', '/bin'].join(':'), - HOME: tmp, - TMPDIR: tmp, - LANG: 'en_US.UTF-8', - ALASQL_TEST_PORT: String(port), - }; - const run = (cmd, args) => - spawnSync('/usr/bin/sandbox-exec', [...prefix, cmd, ...args], { - cwd: work, - env, - encoding: 'utf8', - timeout: 5 * 60000, - maxBuffer: 1 << 28, - stdio: ['ignore', 'pipe', 'pipe'], - }); - - // Self-test. Each of these must be refused, or nothing of the pull request is run. - const q = JSON.stringify; - const probes = { - 'read the home folder': "require('fs').readdirSync(" + q(os.homedir()) + ')', - 'read the repository': "require('fs').readFileSync(" + q(path.join(root, 'package.json')) + ')', - 'write outside': - "require('fs').writeFileSync(" + q(path.join(modules, '.sandbox-probe')) + ",'')", - 'start a program': - "require('child_process').execFileSync('/usr/bin/open',['-h'],{stdio:'ignore'})", - }; - for (const name in probes) { - const p = run(node + '/bin/node', [ - '-e', - 'try{' + probes[name] + "}catch(e){process.exit(e.code==='EPERM'?42:1)}", - ]); - if (p.status !== 42) - stop('The sandbox does not refuse to ' + name + '. Nothing was run. ' + p.stderr); - } - const online = run(node + '/bin/node', [ - '-e', - "require('net').connect(443,'1.1.1.1').on('error',e=>process.exit(e.code==='EPERM'?42:1)).on('connect',()=>process.exit(0))", - ]); - if (online.status !== 42) stop('The sandbox does not refuse the network. Nothing was run.'); - console.log('\nThe sandbox refuses files, programs, writes and network. Running the checks.'); - - const tests = fs - .readdirSync(path.join(work, 'test')) - .filter(f => /^test[0-9-].*\.js$/.test(f)) - .sort() - .map(f => './test/' + f); - // The system log has whole seconds, and the refusals of the self-test are not of interest - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1500); - const started = new Date(); - const results = []; - const step = (name, cmd, args) => { - const r = run(cmd, args); - const text = (r.stdout || '') + (r.stderr || ''); - fs.writeFileSync(path.join(dir, name.replace(/\W+/g, '-') + '.log'), text); - results.push([ - name, - r.status, - (text.match(/^ ?\d+ (pass|skip|fail)$/gm) || []).map(s => s.trim()).join(', '), - ]); - if (r.status !== 0) - console.log( - text - .split('\n') - .filter(l => /^\(fail\)|rror/.test(l)) - .slice(0, 25) - .join('\n') - ); - return r.status === 0; - }; - const ok = - step('parser', node + '/bin/node', [ - bin('jison'), - './src/alasqlparser.jison', - '-o', - './src/alasqlparser.js', - ]) && - step('build', bun, ['build.js']) && - step('version', node + '/bin/node', [ - bin('rexreplace'), - 'PACKAGE_VERSION', - require(path.join(root, 'package.json')).version, - '-Iq', - 'dist/**/*.js', - ]); - if (ok) { - step('tests', bun, ['test', '--dots', '--preload', './test/bun-setup.js', ...tests]); - step('dialect test', bun, ['test/dialect/run.js']); - step('binding check', bun, ['test/bind/run.js']); - step('run-state check', bun, ['test/runstate/run.js']); - } - - // What the kernel refused while the checks ran - const when = d => - new Date(d - d.getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace('T', ' '); - const log = spawnSync( - '/usr/bin/log', - [ - 'show', - '--style', - 'compact', - '--start', - when(started), - '--predicate', - 'sender == "Sandbox" AND eventMessage CONTAINS "deny"', - ], - {encoding: 'utf8', maxBuffer: 1 << 28, timeout: 120000} - ); - if (log.status !== 0) - console.log('\nThe system log could not be read, so refused attempts are not known.'); - const denied = {}; - // Refused on every run of main too - const NOISE = - /^(mach-lookup com\.apple\.(system\.(opendirectoryd|notification_center)|logd|bsd\.dirhelper)|network-outbound \/private\/var\/run\/syslog)/; - for (const m of (log.stdout || '').matchAll( - /Sandbox: (bun|node|sh|bash|env)\(\d+\) deny\(\d+\) (.*)/g - )) { - const what = m[1] + ' ' + m[2]; - if (NOISE.test(m[2]) || dir.startsWith(m[2].replace('file-read-data ', ''))) continue; - denied[what] = (denied[what] || 0) + 1; - } - - console.log( - '\n' + - pr + - ' at ' + - head.slice(0, 8) + - ' merged with main ' + - git('rev-parse', '--short=8', 'origin/main') - ); - for (const [name, status, counts] of results) - console.log( - ' ' + - (status === 0 ? 'ok ' : 'FAILED') + - ' ' + - name + - (counts ? ' ' + counts : '') + - (status === null ? ' (timeout)' : '') - ); - const list = Object.entries(denied).sort((a, b) => b[1] - a[1]); - console.log('\nRefused by the sandbox: ' + (list.length ? '' : 'nothing')); - for (const [what, n] of list.slice(0, 40)) console.log(' ' + n + 'x ' + what); - console.log('\nLogs: ' + dir); - // 3 is for code that passes and tried something it may not do - if (!ok || results.some(r => r[1] !== 0) || log.status !== 0) process.exit(1); - process.exit(list.length ? 3 : 0); -} diff --git a/test/sandbox/sandboxed.sh b/test/sandbox/sandboxed.sh index 735cc3b73f..fd4eabe26b 100755 --- a/test/sandbox/sandboxed.sh +++ b/test/sandbox/sandboxed.sh @@ -1,17 +1,20 @@ #!/bin/bash -# Runs all checks of this checkout without network, secrets or write access to anything but a -# temporary folder, and lists what the code tried that the sandbox refused. macOS only. +# Runs the checks of code we did not write in a sandbox, and lists what the code tried that the +# sandbox refused. Only Bun runs. It reads and writes only its own temporary folder and has no +# network. macOS only. # -# yarn test-safe +# yarn test-safe # this checkout +# yarn test-safe 3184 # pull request 3184: its head and the files to read, runs nothing +# yarn test-safe 3184 8cae9b96 # pull request 3184 merged with main, only when its head is 8cae9b96 # -# The code under test can change package.json and this file, so for code you have not written start -# the copy of main with a command that is not in the checkout, like this alias in ~/.zshrc. +# A pull request is never checked out, so its git hooks and its package.json do not run. To check a +# checkout of code from others, start main's copy with a command that is not in the checkout. # # alias test-safe='git fetch -q origin main && bash -c "$(git show origin/main:test/sandbox/sandboxed.sh)" sandboxed' # -# The profile is read from main too (SANDBOX_REF), and is kept where the code under test cannot write. +# The result says that the code did not break the checks, not that it is safe to merge. # Exit 0 when the checks pass and nothing was refused, 3 when they pass and something was refused, -# 1 when a check fails, 2 when the sandbox does not work. +# 1 when a check fails, 2 when nothing was run. set -u stop() { @@ -19,52 +22,93 @@ stop() { exit 2 } [ "$(uname)" = Darwin ] || stop 'The sandbox uses sandbox-exec, which is macOS only' -root=$(git rev-parse --show-toplevel) || stop 'Run it in a checkout of alasql' +root=$(git rev-parse --show-toplevel 2>/dev/null) || stop 'Run it in a checkout of alasql' +g() { git -C "$root" "$@"; } ref=${SANDBOX_REF:-origin/main} +pr=${1:-} +reviewed=${2:-} +[ -z "$pr" ] || [[ $pr =~ ^[0-9]+$ ]] || stop 'Usage: yarn test-safe [pull request] [reviewed sha]' + +# The files to read, and why +if [ -n "$pr" ]; then + g fetch -q --no-tags origin main "+refs/pull/$pr/head:refs/sandbox/$pr" || stop "Could not fetch $pr" + head=$(g rev-parse "refs/sandbox/$pr") + g update-ref -d "refs/sandbox/$pr" + base=$(g merge-base origin/main "$head") + echo "Pull request $pr is at $head" + files=$(g diff --name-only --no-renames "$base" "$head") + binary=$(g diff --numstat --no-renames "$base" "$head" | awk -F'\t' '$1 == "-" { print $3 }') + content() { g show "$head:$1" 2>/dev/null; } +else + echo "$root, changed from $ref" + files=$({ + g diff --name-only --no-renames "$ref" + g ls-files --others --exclude-standard + } | sort -u) + binary=$(g diff --numstat --no-renames "$ref" | awk -F'\t' '$1 == "-" { print $3 }') + content() { cat "$root/$1" 2>/dev/null; } +fi +RUNS='^(package\.json|yarn\.lock|build\.js|\.github/|\.husky/|\.git|\.?(npm|yarn|bun)|bunfig|bin/|modules/|test/(bun-setup\.js|lib/|sandbox/|parity/|bind/|runstate/|dialect/))' +while IFS= read -r f; do + [ -n "$f" ] || continue + notes='' + [[ $f =~ $RUNS ]] && notes+=', runs or decides what is run' + [ "$f" = src/alasqlparser.js ] && notes+=', not used, generated from the grammar' + grep -qxF "$f" <<<"$binary" && notes+=', binary' + content "$f" | perl -CSD -ne 'exit 1 if /[\x{200b}-\x{200f}\x{202a}-\x{202e}\x{2060}-\x{2069}]/' 2>/dev/null || + notes+=', hidden characters' + echo " $f${notes:+ <- ${notes:2}}" +done <<<"$files" +if [ -n "$pr" ]; then + [ -n "$reviewed" ] || stop "Read the diff (gh pr diff $pr), then: yarn test-safe $pr ${head:0:8}" + [ ${#reviewed} -ge 7 ] && [[ $head == "$reviewed"* ]] || stop "The head is not $reviewed. Nothing was run." +fi + +# A temporary folder with the code, a clone of our packages and a copy of Bun (no disk space on APFS). +# The profile and the log are kept next to it, where the code cannot write. dir=$(cd "$(mktemp -d "${TMPDIR:-/tmp}/alasql-safe-XXXXXX")" && pwd -P) work=$dir/work tmp=$dir/tmp +bin=$dir/bin safe=$dir.safe -mkdir "$work" "$tmp" "$safe" -git -C "$root" show "$ref:test/sandbox/profile.sb" >"$safe/profile.sb" || stop "No profile on $ref" - -# Files that run on their own or decide what is run. Read their diff before you trust the result. -changed=$( - { - git -C "$root" diff --name-only "$ref" - git -C "$root" ls-files --others --exclude-standard - } | sort -u | grep -E '^(package\.json|yarn\.lock|build\.js|\.github/|\.husky/|\.?(npm|yarn|bun)|bunfig|bin/|modules/|test/(bun-setup\.js|lib/|sandbox/|parity/|bind/|runstate/|dialect/))' -) -[ -z "$changed" ] || printf 'Changed from %s, and runs or decides what is run\n%s\n\n' "$ref" "$(echo "$changed" | sed 's/^/ /')" - -# A copy of the checkout without .git, and a clone of the packages (no disk space on APFS) -rsync -a --exclude=/.git --exclude=/node_modules "$root/" "$work/" +mkdir "$work" "$tmp" "$bin" "$safe" +g show "$ref:test/sandbox/profile.sb" >"$safe/profile.sb" || stop "No profile on $ref" +if [ -n "$pr" ]; then + merged=$(g merge-tree --write-tree --name-only origin/main "$head") + if [ $? != 0 ]; then + conflicts=$(sed -n '2,/^$/p' <<<"$merged" | grep -v -e '^$' -e '^src/alasqlparser.js$') + [ -z "$conflicts" ] || stop "Conflicts with main: $conflicts" + fi + g archive "$(head -1 <<<"$merged")" | tar -x -C "$work" +else + rsync -a --exclude=/.git --exclude=/node_modules "$root/" "$work/" +fi +# Not run here, also not by the binding and run-state checks: test2149 starts the command line tool +# and test418 serves files over HTTP +rm -f "$work/test/test2149.js" "$work/test/test418.js" cp -Rc "$(cd "$root/node_modules" && pwd -P)" "$work/node_modules" +cp -c "$(realpath "$(which bun)")" "$bin/bun" modules=$work/node_modules -bun=$(realpath "$(which bun)") -# Not the node of PATH, which yarn replaces with a script in a temporary folder -node=$(dirname "$(dirname "$(node -p 'require("fs").realpathSync(process.execPath)')")") -version=$(node -p "require('$work/package.json').version") -port=$(node -e "const s=require('net').createServer().listen(0,'127.0.0.1',()=>{console.log(s.address().port);s.close()})") +esbuild=$(realpath "$modules"/@esbuild/*/bin/esbuild | head -1) +version=$(sed -n 's/^[[:space:]]*"version": "\(.*\)",$/\1/p' "$work/package.json" | head -1) run() { - (cd "$work" && env -i PATH="$(dirname "$bun"):$node/bin:/usr/bin:/bin" HOME="$tmp" TMPDIR="$tmp" \ - LANG=en_US.UTF-8 ALASQL_TEST_PORT="$port" /usr/bin/sandbox-exec -D DIR="$dir" \ - -D MODULES="$modules" -D NODE="$node" -D BUN="$bun" -D LOCAL="localhost:$port" \ - -f "$safe/profile.sb" "$@") + (cd "$work" && env -i PATH="$bin" HOME="$tmp" TMPDIR="$tmp" LANG=en_US.UTF-8 /usr/bin/sandbox-exec \ + -D DIR="$dir" -D MODULES="$modules" -D BUN="$bin/bun" -D ESBUILD="$esbuild" -f "$safe/profile.sb" "$@") } # Self-test. Each of these must be refused, or nothing is run. probe() { - run "$node/bin/node" -e "try{$2}catch(e){process.exit(e.code==='EPERM'?42:1)}" "$3" >/dev/null 2>&1 + run "$bin/bun" -e "try{$2}catch(e){process.exit(42)}" "$3" >/dev/null 2>&1 [ $? = 42 ] || stop "The sandbox does not refuse to $1. Nothing was run." } probe 'read the home folder' "require('fs').readdirSync(process.argv[1])" "$HOME" probe 'read the repository' "require('fs').readFileSync(process.argv[1])" "$root/package.json" -probe 'write outside' "require('fs').writeFileSync(process.argv[1],'')" "$modules/.sandbox-probe" -probe 'start a program' "require('child_process').execFileSync('/usr/bin/open',['-h'],{stdio:'ignore'})" '' -run "$node/bin/node" -e "require('net').connect(443,'1.1.1.1').on('error',e=>process.exit(e.code==='EPERM'?42:1)).on('connect',()=>process.exit(0))" >/dev/null 2>&1 +probe 'write to the packages' "require('fs').writeFileSync(process.argv[1],'')" "$modules/.sandbox-probe" +probe 'start a program' "require('child_process').execFileSync('/bin/ls',{stdio:'ignore'})" '' +run "$bin/bun" -e "require('net').connect(443,'1.1.1.1').on('error',()=>process.exit(42)).on('connect',()=>process.exit(0))" >/dev/null 2>&1 [ $? = 42 ] || stop 'The sandbox does not refuse the network. Nothing was run.' +echo echo 'The sandbox refuses files, programs, writes and network. Running the checks.' # The system log has whole seconds, and the refusals of the self-test are not of interest @@ -86,32 +130,30 @@ step() { return $status } tests=($(cd "$work" && ls test | grep -E '^test[0-9-].*\.js$' | sort | sed 's|^|./test/|')) -step parser "$node/bin/node" "$(realpath "$modules/.bin/jison")" ./src/alasqlparser.jison -o ./src/alasqlparser.js && - step build "$bun" build.js && - step version "$node/bin/node" "$(realpath "$modules/.bin/rexreplace")" PACKAGE_VERSION "$version" -Iq 'dist/**/*.js' && +step parser "$bin/bun" "$(realpath "$modules/.bin/jison")" ./src/alasqlparser.jison -o ./src/alasqlparser.js && + step build "$bin/bun" build.js && + step version "$bin/bun" "$(realpath "$modules/.bin/rexreplace")" PACKAGE_VERSION "$version" -Iq 'dist/**/*.js' && { - step tests "$bun" test --dots --preload ./test/bun-setup.js "${tests[@]}" - step dialect "$bun" test/dialect/run.js - step bind "$bun" test/bind/run.js - step runstate "$bun" test/runstate/run.js + step tests "$bin/bun" test --dots --preload ./test/bun-setup.js "${tests[@]}" + step dialect "$bin/bun" test/dialect/run.js + step bind "$bin/bun" test/bind/run.js + step runstate "$bin/bun" test/runstate/run.js } -# What the kernel refused while the checks ran, without what every run of main is refused +# What the kernel refused while the checks ran, without Bun looking at the folders above the run folder /usr/bin/log show --style compact --start "$started" \ --predicate 'sender == "Sandbox" AND eventMessage CONTAINS "deny"' >"$safe/refused.log" 2>&1 || { echo 'The system log could not be read, so refused attempts are not known.' failed=1 } -refused=$(grep -oE 'Sandbox: (bun|node|sh|bash|env)\([0-9]+\) deny\([0-9]+\) .*' "$safe/refused.log" | - sed -E 's/^Sandbox: ([a-z]+)\([0-9]+\) deny\([0-9]+\) /\1 /' | - grep -vE '^[a-z]+ (mach-lookup com\.apple\.(system\.(opendirectoryd|notification_center)|logd|bsd\.dirhelper)|network-outbound /private/var/run/syslog)' | - awk -v d="$dir" 'match($0, /^[a-z]+ file-read-data /) { if (index(d, substr($0, RLENGTH + 1)) == 1) next } { print }' | - sort | uniq -c | sort -rn | head -40) +refused=$(grep -oE 'Sandbox: bun\([0-9]+\) deny\([0-9]+\) .*' "$safe/refused.log" | + sed -E 's/^Sandbox: bun\([0-9]+\) deny\([0-9]+\) //' | + awk -v d="$dir" 'match($0, /^file-read-(data|metadata) /) { if (index(d "/", substr($0, RLENGTH + 1) "/") == 1) next } { print }' | sort | uniq -c | sort -rn | head -40) echo -echo "$root at $(git -C "$root" rev-parse --short=8 HEAD 2>/dev/null)$(git -C "$root" diff --quiet HEAD 2>/dev/null || echo ' with changes')" printf '%s' "$summary" +echo ' (test2149 and test418 are not run in the sandbox)' echo if [ -z "$refused" ]; then echo 'Refused by the sandbox: nothing'; else echo 'Refused by the sandbox. Read this before you trust the code.'