Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
"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",
Expand Down
14 changes: 14 additions & 0 deletions test/sandbox/profile.sb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
(version 1)
; 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 and the system libraries)
(import "system.sb")
; 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")))
; 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. Nothing else.
(allow file-read* file-write* (subpath (param "DIR")))
(deny file-write* (subpath (param "MODULES")) (literal (param "BUN")))
165 changes: 165 additions & 0 deletions test/sandbox/sandboxed.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
#!/bin/bash
# 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 # 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
#
# 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 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 nothing was run.

set -u
stop() {
echo "$1"
exit 2
}
[ "$(uname)" = Darwin ] || stop 'The sandbox uses sandbox-exec, which is macOS only'
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" "$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
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="$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 "$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 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
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 "$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 "$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 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\([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
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.'
echo "$refused"
fi
echo
echo "Logs: $dir and $safe"
[ $failed = 0 ] || exit 1
[ -z "$refused" ] || exit 3
Loading