:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(dev): deny writes to git config and pin the wrapper's PATH (#87021)
Phil Haacka69326769657
diff --git a/.flox/env/on-activate.sh b/.flox/env/on-activate.shindex a35479245d08..baf9e18b18c6 100755--- a/.flox/env/on-activate.sh+++ b/.flox/env/on-activate.sh@@ -312,6 +312,23 @@ _UV_SKIP=0_PHROCS_SKIP=0[[ -n "$_PHROCS_BAKED" && -n "$_PHROCS_CURRENT" && "$_PHROCS_BAKED" == "$_PHROCS_CURRENT" ]] && _PHROCS_SKIP=1+# Seed repo-local git settings here, because package.json's postinstall runs inside+# the sandbox below, which write-denies .git/config. The postinstall still tries+# blame.ignoreRevsFile for clones that never activate flox (.claude/hooks/setup-cloud.sh+# and friends); under the sandbox that attempt no-ops and this one is what lands.+# Idempotent — the --get short-circuits once the value is set.+git -C "$FLOX_ENV_PROJECT" config --get blame.ignoreRevsFile >/dev/null 2>&1 ||+ git -C "$FLOX_ENV_PROJECT" config blame.ignoreRevsFile .git-blame-ignore-revs >/dev/null 2>&1 ||+ true+# Same for husky's core.hooksPath, which `prepare` sets during the sandboxed pnpm+# install below. husky checks only whether git spawned, not how it exited, so the+# denied write leaves a fresh clone with no hooks and an install that claims success.+# --local, not --get: a global core.hooksPath would satisfy a merged --get and skip+# the seed, leaving the repo pointed at the developer's global hooks dir instead.+git -C "$FLOX_ENV_PROJECT" config --local --get core.hooksPath >/dev/null 2>&1 ||+ git -C "$FLOX_ENV_PROJECT" config core.hooksPath .husky >/dev/null 2>&1 ||+ true+# Sandbox the automatic installs below by default on macOS (opt out with# POSTHOG_DEV_SANDBOX=0). .env.local isn't loaded at flox-activate time, so check# it directly — but only when the live env is unset, so shell env keeps precedence.diff --git a/bin/dev-sandbox b/bin/dev-sandboxindex cea3b9fb4795..a482fea93d5f 100755--- a/bin/dev-sandbox+++ b/bin/dev-sandbox@@ -1,4 +1,4 @@-#!/usr/bin/env bash+#!/bin/bash# Run a dev-stack command inside a macOS Seatbelt sandbox (see bin/dev-sandbox.sb).## Usage: bin/dev-sandbox '<shell command>'@@ -22,13 +22,25 @@set -euo pipefail+# Everything below runs BEFORE the sandbox exists, with the developer's full+# privileges. The inherited $PATH is not trustworthy at that point: it keeps the+# repo's own node_modules/.bin (see the PATH sanitizing near the end, which+# deliberately preserves repo bins for the child), and sandboxed dependency code+# can write there. A bare `sed`/`mktemp` would then resolve to a binary a previous+# sandboxed run planted, and run unsandboxed as the developer. So pin PATH to the+# system directories for this script's own use and hand the inherited one to the+# child, which is the only consumer that needs it.+inherited_path="$PATH"+PATH="/usr/bin:/bin:/usr/sbin:/sbin"+cmd="${1:?bin/dev-sandbox: expected a command string as the first argument}"project="$(cd "$(dirname "$0")/.." && pwd -P)" # canonical repo root (Seatbelt matches physical paths)base_profile="$project/bin/dev-sandbox.sb"-run_unsandboxed() { exec /bin/bash -c "$cmd"; }+# Passthrough runs the developer's own command, so it gets the real PATH back.+run_unsandboxed() { PATH="$inherited_path" exec /bin/bash -c "$cmd"; }-if [[ "$(uname -s)" != "Darwin" ]] || ! command -v sandbox-exec >/dev/null 2>&1 || [[ ! -f "$base_profile" ]]; then+if [[ "$(uname -s)" != "Darwin" ]] || [[ ! -x /usr/bin/sandbox-exec ]] || [[ ! -f "$base_profile" ]]; thenrun_unsandboxedfi@@ -53,6 +65,23 @@ fi# the physical path Seatbelt enforces against (/var/folders -> /private/var/...).tmpdir="$(cd "${TMPDIR:-/tmp}" 2>/dev/null && pwd -P || echo "${TMPDIR:-/tmp}")"+# Held in variables because matching a literal backslash in a `case` pattern+# otherwise needs a shellcheck pragma (SC1003).+_dq='"' _bs=$'\\'++# Can this path be rendered inside an SBPL (literal "…")? One owner, so every+# emitter agrees on the answer. Quotes and backslashes are the cases that matter,+# for two different reasons: a double quote closes the literal early and fails the+# whole profile to parse (loud, but the wrapper then runs unsandboxed), while a+# backslash is eaten as an SBPL string escape, so the deny silently binds to a+# different path than intended and the real one stays writable. Tabs and newlines+# are legal in filenames and render correctly, so they are not rejected. Empty means+# a cd/pwd -P failed upstream, leaving nothing to protect.+unrenderable_path() { # $1 = path+ case "$1" in "" | *"$_dq"* | *"$_bs"*) return 0 ;; esac+ return 1+}+# The base profile allows the git config files by literal path, but Seatbelt# matches physical paths — when one is a symlink (dotfile managers), the read of# its target is still denied and cargo/libgit2 fails hard ("failed to stat@@ -65,10 +94,47 @@ for _cfg in "$HOME/.gitconfig" "$HOME/.gitconfig.local" "$HOME/.config/git/confi[[ -n "$_resolved" && "$_resolved" != "$_cfg" ]] && gitcfg_targets+=("$_resolved")done-cache_key="$(printf '%s\0' "$project" "$mainrepo" "$HOME" "${SSH_AUTH_SOCK:-}" ${gitcfg_targets[@]+"${gitcfg_targets[@]}"} | /usr/bin/shasum -a256 | cut -c1-16)"+# The profile write-denies the repo's own git config by PROJECT/MAINREPO literal,+# which reaches neither a worktree's real gitdir (it lives under the MAIN repo, at+# .git/worktrees/<name>/) nor a checkout whose .git is a symlink, since Seatbelt+# matches physical paths. Collect both config files there so the render can deny+# them too. Write-deny only: reads are already allowed via the MAINREPO subpath.+# $mainrepo is $project unless this is a worktree, where $project/.git is the+# redirect file (nothing to deny inside it) and $gitdir is the real git dir.+# commondir belongs to this surface too — git resolves it to the common git dir and+# then reads that directory's config AND hooks/, so rewriting it reaches the escape+# the .git/hooks denies close off. It is not worktree-only: git honors a commondir+# in any git dir, including a plain clone's.+gitcfg_wdeny=()+for _gd in "$mainrepo/.git" ${gitdir:+"$gitdir"}; do+ [[ -d "$_gd" ]] || continue+ _raw="$_gd"+ _gd="$(cd "$_gd" 2>/dev/null && pwd -P || true)" # physical path: Seatbelt matches that+ # Dropping the whole render over one git dir would leave the developer with no+ # sandbox at all, so skip just this deny — but say so, since the config it would+ # have protected stays writable.+ if unrenderable_path "$_gd"; then+ echo "⚠️ dev sandbox: cannot deny writes to $_raw/config (path unresolvable or unrenderable)" >&2+ continue+ fi+ gitcfg_wdeny+=("$_gd/config" "$_gd/config.worktree" "$_gd/commondir")+done++cache_key="$(printf '%s\0' "$project" "$mainrepo" "$HOME" "${SSH_AUTH_SOCK:-}" ${gitcfg_targets[@]+"${gitcfg_targets[@]}"} "--" ${gitcfg_wdeny[@]+"${gitcfg_wdeny[@]}"} | /usr/bin/shasum -a256 | cut -c1-16)"rendered="$tmpdir/posthog-dev-sandbox-$cache_key.sb"stamp="$rendered.ok" # touched once the rendered profile passes the init preflight+# One SBPL rule over N path literals. A rule with no filters matches EVERYTHING —+# a bare `(deny file-write*)` denies every write — so an empty list emits nothing.+emit_rule() { # emit_rule <operation> <path>...+ local op="$1"+ shift+ [[ $# -gt 0 ]] || return 0+ printf '(%s' "$op"+ printf ' (literal "%s")' "$@"+ printf ')\n'+}+# Render = base profile + ancestor read-allows ($HOME down to each repo root, so# the OS/node/getcwd can lstat+readdir into the repo) + the SSH-agent socket deny.# Parameter expansion (no dirname forks) since this is on the per-service path.@@ -77,7 +143,6 @@ stamp="$rendered.ok" # touched once the rendered profile passes the init prefligrender_profile() {local -a ancestors=()local r p _a tmp sock_dir- local _dq='"' _bs=$'\\'for r in "$project" "$mainrepo"; dop="${r%/*}"while [[ "$p" != "$HOME" && "$p" != "/" && -n "$p" ]]; do@@ -86,32 +151,26 @@ render_profile() {donedoneancestors+=("$HOME")- # Paths are emitted as SBPL string literals; a " or \ would corrupt the- # profile (quoted expansions match literally, dodging glob/escape ambiguity).+ # These paths carry the read-allows the stack needs, so unlike a single git-dir+ # deny they cannot be dropped individually — fail the render and run without a+ # sandbox, loudly, rather than emit a profile missing part of what it grants.for _a in "${ancestors[@]}" "$rendered" "$stamp" ${gitcfg_targets[@]+"${gitcfg_targets[@]}"}; do- case "$_a" in- *"$_dq"* | *"$_bs"*)- echo "⚠️ dev sandbox: path contains a quote/backslash, running WITHOUT sandbox: $_a" >&2+ if unrenderable_path "$_a"; then+ echo "⚠️ dev sandbox: path is unrenderable, running WITHOUT sandbox: $_a" >&2return 1- ;;- esac+ fidonetmp="$(mktemp "$tmpdir/posthog-dev-sandbox.XXXXXX")" || return 1if {cat "$base_profile"- printf '(allow file-read*'- printf ' (literal "%s")' "${ancestors[@]}"- printf ')\n'+ emit_rule 'allow file-read*' "${ancestors[@]}"# Physical targets of symlinked git configs (resolved above): readable like# the configs themselves, write-denied for the same hooksPath escape reason.- if [[ ${#gitcfg_targets[@]} -gt 0 ]]; then- printf '(allow file-read*'- printf ' (literal "%s")' "${gitcfg_targets[@]}"- printf ')\n'- printf '(deny file-write*'- printf ' (literal "%s")' "${gitcfg_targets[@]}"- printf ')\n'- fi+ emit_rule 'allow file-read*' ${gitcfg_targets[@]+"${gitcfg_targets[@]}"}+ emit_rule 'deny file-write*' ${gitcfg_targets[@]+"${gitcfg_targets[@]}"}+ # Physical git-dir config paths (collected above), which the profile's+ # PROJECT/MAINREPO literals miss for a worktree or a symlinked .git.+ emit_rule 'deny file-write*' ${gitcfg_wdeny[@]+"${gitcfg_wdeny[@]}"}# Deny the SSH agent socket (path varies per agent: Secretive, 1Password,# launchd, gpg). Canonicalize its dir — Seatbelt matches the kernel's# physical path (e.g. /tmp -> /private/tmp); fall back to the raw path.@@ -128,7 +187,7 @@ render_profile() {# them would bypass the sandbox on the next cache hit, which re-runs neither# render nor preflight. The legit render here runs outside the sandbox, so# it is unaffected. Literals are canonical (TMPDIR resolved above).- printf '(deny file-write* (literal "%s") (literal "%s"))\n' "$rendered" "$stamp"+ emit_rule 'deny file-write*' "$rendered" "$stamp"} >"$tmp" 2>/dev/null && mv -f "$tmp" "$rendered"; thenrm -f "$stamp" # new contents: force a fresh init preflightreturn 0@@ -144,7 +203,10 @@ if [[ ! -f "$rendered" || "$base_profile" -nt "$rendered" || "$project/bin/dev-srender_profile || run_unsandboxedfi-sandbox=(sandbox-exec -f "$rendered" -D HOME="$HOME" -D PROJECT="$project" -D MAINREPO="$mainrepo")+# Absolute path: the final exec below hands the child's PATH to `env`, and that PATH+# deliberately keeps the repo's own writable bins — so a bare name here would let+# sandboxed code plant the very binary that creates the sandbox.+sandbox=(/usr/bin/sandbox-exec -f "$rendered" -D HOME="$HOME" -D PROJECT="$project" -D MAINREPO="$mainrepo")# Init preflight, once per rendered profile (the stamp records that it passed).# Fail OPEN if it can't initialize (e.g. the profile won't compile on this OS).@@ -172,7 +234,7 @@ sandboxed_path=""_oldifs="$IFS"set -f # PATH entries are literal paths; never glob-expand themIFS=':'-for _pdir in $PATH; do+for _pdir in $inherited_path; do # the developer's real PATH, not this script's pinned onecase "$_pdir" in"$project"/* | "$mainrepo"/*) ;; # repo bins (node_modules/.bin) — keep"$HOME"/* | "") continue ;; # read-denied $HOME shim dir / empty — dropdiff --git a/bin/dev-sandbox-selftest b/bin/dev-sandbox-selftestindex adf490367ca2..0d4a60883201 100755--- a/bin/dev-sandbox-selftest+++ b/bin/dev-sandbox-selftest@@ -15,12 +15,18 @@ set -uo pipefail # intentionally not -e: run every check, then reportcd "$(dirname "$0")/.." || exit 1SANDBOX="bin/dev-sandbox"+repo="$(pwd -P)" # canonical repo root, as Seatbelt sees itfail=0pass() { printf ' \033[32mok\033[0m %s\n' "$1"; }die() {printf ' \033[31mFAIL\033[0m %s\n' "$1"fail=1}+# The checks below build throwaway repos at several different points. One trap owns+# all of them, so an interrupt mid-run doesn't strand a git worktree in TMPDIR.+_tmpdirs=()+cleanup_tmpdirs() { [[ ${#_tmpdirs[@]} -eq 0 ]] || rm -rf "${_tmpdirs[@]}"; }+trap cleanup_tmpdirs EXITif [[ "$(uname -s)" != "Darwin" ]] || ! command -v sandbox-exec >/dev/null 2>&1; thenecho "Sandbox is a no-op on this platform — nothing to test."@@ -161,13 +167,19 @@ fi# 11. Execute-later write targets are read-only inside the sandbox (poisoning# them would run code OUTSIDE the sandbox). Probe files only — never real ones.-check_write_blocked() {- if $SANDBOX "echo x > '$1'" >/dev/null 2>&1; then+# The probes differ in how they attempt the write; they share this verdict.+# Returns non-zero when the write got through, so a caller can clean up after+# whatever its probe just created.+report_write_blocked() { # $1 = probe exit status, $2 = label+ if [[ "$1" -eq 0 ]]; thendie "writable, should be blocked: $2"- rm -f "$1"- else- pass "write blocked: $2"+ return 1fi+ pass "write blocked: $2"+}+check_write_blocked() {+ $SANDBOX "echo x > '$1'" >/dev/null 2>&1+ report_write_blocked $? "$2" || rm -f "$1"}check_write_blocked "bin/.dev_sandbox_selftest_probe" "repo bin/"mkdir -p .git/hooks 2>/dev/null || true@@ -175,18 +187,157 @@ check_write_blocked ".git/hooks/.dev_sandbox_selftest_probe" ".git/hooks"if [[ -d "$HOME/.cargo/bin" ]]; thencheck_write_blocked "$HOME/.cargo/bin/.dev_sandbox_selftest_probe" "cargo bin"fi+# Homebrew's bin/sbin/Cellar: developer-owned and on PATH, same execute-later route+# as cargo bin above — no git-config indirection needed to reach it.+for hb_bin in /opt/homebrew/bin /usr/local/bin; do+ if [[ -d "$hb_bin" ]]; then+ check_write_blocked "$hb_bin/.dev_sandbox_selftest_probe" "Homebrew bin ($hb_bin)"+ fi+done+# For files that really exist and must not be damaged by the probe: opens for+# append and writes nothing, so Seatbelt still has to decide on write access while+# a missing deny cannot corrupt the file.+check_write_blocked_existing() {+ $SANDBOX ": >> '$1'" >/dev/null 2>&1+ report_write_blocked $? "$2"+}+# Repo-local git config reaches the same escape as .git/hooks above: core.hooksPath+# moves the hook directory elsewhere, and core.fsmonitor is a command git runs on+# ordinary read commands. --git-common-dir resolves to the main repo's .git in a+# worktree, which is the file git actually reads there.+gitcommon="$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)"+# Absolute, but not symlink-resolved — Seatbelt matches the physical path.+[[ -n "$gitcommon" ]] && gitcommon="$(cd "$gitcommon" 2>/dev/null && pwd -P || true)"+if [[ -n "$gitcommon" && -f "$gitcommon/config" ]]; then+ check_write_blocked_existing "$gitcommon/config" "repo .git/config (core.hooksPath / core.fsmonitor escape)"+else+ echo " -- repo .git/config not found, skipping"+fi+# The scripts that actually run outside the sandbox. core.hooksPath points git at+# .husky, so the .git/hooks deny above guards a directory git never reads once that+# is set; these are the real hooks. .flox/env holds the activation scripts, and+# on-activate.sh is what builds this sandbox in the first place.+# .husky/_/husky.sh is deliberately absent from this list — husky's installer+# rewrites it on every sandboxed install, so the profile re-allows it. See the note+# in bin/dev-sandbox.sb.+for unsandboxed_exec in .husky/pre-commit .husky/pre-push .husky/post-checkout .flox/env/on-activate.sh; do+ if [[ ! -f "$repo/$unsandboxed_exec" ]]; then+ echo " -- $unsandboxed_exec absent, skipping"+ continue+ fi+ check_write_blocked_existing "$repo/$unsandboxed_exec" "$unsandboxed_exec (runs unsandboxed)"+done+# Counterpart to the .husky checks above, so the suite does not read as if husky+# hooks were fully sealed. The checked-in hooks each source .husky/_/husky.sh, and+# that file stays writable BY DESIGN — husky's installer rewrites it on every+# sandboxed install and throws if it cannot. So the .husky denies stop tampering+# with the hook files, not execution through the sourced helper. This asserts the+# door is knowingly open; closing it (and breaking pnpm install) turns this red.+# See bin/dev-sandbox.sb and the follow-up in #79300.+if [[ -f "$repo/.husky/_/husky.sh" ]]; then+ if $SANDBOX ": >> '$repo/.husky/_/husky.sh'" >/dev/null 2>&1; then+ pass "known-open: .husky/_/husky.sh writable by design (husky reinstalls it)"+ else+ die ".husky/_/husky.sh is denied — this breaks the sandboxed pnpm install (husky throws)"+ fi+else+ echo " -- .husky/_/husky.sh absent, skipping known-open check"+fi+# Homebrew's system-scope gitconfig is owned by the developer, not root, and a brew+# git reads it on every invocation — the same escape from a file outside $HOME.+for sysgitcfg in /opt/homebrew/etc/gitconfig /usr/local/etc/gitconfig; do+ if [[ ! -f "$sysgitcfg" ]]; then+ echo " -- $sysgitcfg absent, skipping"+ continue+ fi+ check_write_blocked_existing "$sysgitcfg" "system gitconfig ($sysgitcfg)"+done+# The .git node itself: in a worktree it is a file holding `gitdir: <path>`, so+# rewriting it repoints git at an attacker-controlled directory that brings its own+# config. Build a throwaway worktree rather than probing this checkout's own .git —+# appending to a directory fails on its own, so on a plain clone that probe would+# report "blocked" without the sandbox having anything to do with it.+wt_root="$(cd "$(mktemp -d)" && pwd -P)"+_tmpdirs+=("$wt_root")+# Runs the throwaway worktree's own copy of the wrapper, so the deny under test is+# the one that copy renders. The cd matters: from the outer repo the child's cwd is+# read-denied, and a getcwd failure would look like the write being blocked.+wt_write_blocked() { # $1 = shell write expression, $2 = label+ (cd "$wt_root/wt" && TMPDIR="$wt_root/tmp" ./bin/dev-sandbox "$1") >/dev/null 2>&1+ report_write_blocked $? "$2"+}+# The counterpart: a write the dev stack depends on, which must NOT be blocked.+# Every other check here asserts something is refused, so an over-broad deny would+# land green — this is what catches one.+wt_write_allowed() { # $1 = shell write expression, $2 = label+ if (cd "$wt_root/wt" && TMPDIR="$wt_root/tmp" ./bin/dev-sandbox "$1") >/dev/null 2>&1; then+ pass "write allowed: $2"+ else+ die "write blocked, should be allowed: $2"+ fi+}+if git init -q "$wt_root/origin" 2>/dev/null &&+ git -C "$wt_root/origin" -c [email protected] -c user.name=t -c commit.gpgsign=false \+ commit -q --allow-empty -m init 2>/dev/null &&+ git -C "$wt_root/origin" worktree add -q "$wt_root/wt" 2>/dev/null &&+ [[ -f "$wt_root/wt/.git" ]]; then+ mkdir -p "$wt_root/wt/bin" "$wt_root/tmp"+ cp -p "$repo/bin/dev-sandbox" "$repo/bin/dev-sandbox.sb" "$wt_root/wt/bin/"+ wt_write_blocked ": >> .git" "worktree .git redirect file (gitdir redirect escape)"+ # The worktree's real git dir lives under the MAIN repo, which no+ # PROJECT-relative rule reaches; the wrapper denies it at runtime.+ wt_gitdir="$(cd "$wt_root/wt" && git rev-parse --path-format=absolute --git-dir 2>/dev/null || true)"+ if [[ -n "$wt_gitdir" ]]; then+ wt_write_blocked "echo x > '$wt_gitdir/config.worktree'" "per-worktree config.worktree"+ # commondir repoints git at another common git dir, which brings its own+ # config AND hooks/ — so it reaches the escape from a file the config denies+ # do not name. Append-only: the real one holds "../.." and must keep working.+ wt_write_blocked ": >> '$wt_gitdir/commondir'" "per-worktree commondir (common-dir repoint escape)"+ fi+ # Positive control: the .git node deny is a literal, not a subpath, so ordinary+ # entries inside a real .git directory must stay writable or the dev stack breaks.+ wt_write_allowed "echo x > '$wt_root/origin/.git/DEV_SANDBOX_PROBE'" \+ "entry inside a real .git dir (the deny is the node, not a subpath)"+else+ echo " -- could not build a throwaway worktree, skipping .git redirect checks"+fi+# A checkout whose .git is a symlink to a git dir elsewhere, which is what dotfile+# managers produce. Seatbelt matches the physical path, so the profile's+# PROJECT/.git/config literal cannot fire here and the wrapper's runtime+# canonicalization is the only thing denying the write. Without it this passes+# silently while the developer's config stays writable.+sym_root="$(cd "$(mktemp -d)" && pwd -P)"+_tmpdirs+=("$sym_root")+if git init -q "$sym_root/repo" 2>/dev/null &&+ mv "$sym_root/repo/.git" "$sym_root/realgit" 2>/dev/null &&+ ln -s "$sym_root/realgit" "$sym_root/repo/.git" 2>/dev/null; then+ mkdir -p "$sym_root/repo/bin" "$sym_root/tmp"+ cp -p "$repo/bin/dev-sandbox" "$repo/bin/dev-sandbox.sb" "$sym_root/repo/bin/"+ (cd "$sym_root/repo" && TMPDIR="$sym_root/tmp" ./bin/dev-sandbox ": >> '$sym_root/realgit/config'") >/dev/null 2>&1+ report_write_blocked $? "symlinked .git, config at the physical target"+else+ echo " -- could not build a symlinked-.git checkout, skipping"+fi# 12. The rendered profile + its preflight stamp are read-only inside the sandbox.# Otherwise a dependency could overwrite them and have a poisoned profile# loaded on the next cache hit (which re-runs neither render nor preflight),-# bypassing the sandbox entirely. Earlier checks have already rendered it.-rendered_profiles=("${TMPDIR:-/tmp}"/posthog-dev-sandbox-*.sb)+# bypassing the sandbox entirely.+# A profile write-denies only itself, so render into a private TMPDIR: the only+# profile there is the one these checks run under. Globbing the shared TMPDIR+# would also turn up profiles left by other worktrees — writable by this sandbox,+# and so read as a failure — and clearing those would evict their live cache.+prof_tmp="$(cd "$(mktemp -d)" && pwd -P)"+_tmpdirs+=("$prof_tmp")+export TMPDIR="$prof_tmp" # check 13 below reuses this same private profile+$SANDBOX 'true' >/dev/null 2>&1+rendered_profiles=("$prof_tmp"/posthog-dev-sandbox-*.sb)rendered_profile="${rendered_profiles[0]}" # literal glob if none matched -> -f false belowif [[ -f "$rendered_profile" ]]; thencheck_write_blocked "$rendered_profile" "rendered profile (cache poisoning)"check_write_blocked "$rendered_profile.ok" "rendered profile stamp (cache poisoning)"else- die "rendered profile not found (expected after earlier sandbox runs)"+ die "rendered profile not found in $prof_tmp (expected from the render just above)"fi# 13. PATH is sanitized: read-denied $HOME dirs are dropped from the child PATH so a@@ -196,7 +347,6 @@ fi# ahead of the real binary breaks every bare spawn (e.g. pnpm lifecycle scripts).# Assert a $HOME dir is dropped while system + repo bins survive. String-only, so# the probe dir need not exist.-repo="$(pwd -P)"shim="$HOME/.dev_sandbox_selftest_shim/bin"child_path="$(PATH="$shim:/usr/bin:/bin:$repo/bin" $SANDBOX 'printf %s "$PATH"' 2>/dev/null)"if [[ ":$child_path:" == *":$shim:"* ]]; then@@ -207,6 +357,47 @@ elsepass "PATH sanitized: denied \$HOME dir dropped, system + repo bins kept"fi+# 14. The passthrough hands the caller's real PATH back. On Linux that is the+# wrapper's entire job (there is no Seatbelt), and this suite exits before here+# on non-Darwin — so reach the same branch on macOS by running a copy of the+# wrapper with no profile beside it. If the restore breaks, every sandboxed+# service on a Linux dev box starts with only the four pinned system dirs.+pass_dir="$(cd "$(mktemp -d)" && pwd -P)"+_tmpdirs+=("$pass_dir")+mkdir -p "$pass_dir/bin"+cp -p "$repo/bin/dev-sandbox" "$pass_dir/bin/" # no dev-sandbox.sb -> passthrough branch+# $HOME-rooted so the marker also fails the sandboxed branch's PATH sanitizer: if+# passthrough ever handed back the pinned/sanitized PATH instead of the caller's,+# a system-dir marker would survive and hide the regression, but this one is dropped.+marker="$HOME/.dev_sandbox_selftest_pathmarker" # string-only, need not exist+child_path="$(PATH="$marker:$PATH" "$pass_dir/bin/dev-sandbox" 'printf %s "$PATH"' 2>/dev/null)"+if [[ ":$child_path:" == *":$marker:"* ]]; then+ pass "passthrough restores the caller's PATH"+else+ die "passthrough PATH left pinned to system dirs (got: $child_path)"+fi++# 15. The shebang resolves a fixed interpreter, not one found by searching the+# caller's PATH. `env bash` would let a bash planted by a prior sandboxed run+# (e.g. in node_modules/.bin or .flox/cache/venv/bin, both repo-writable) run+# BEFORE this script's own PATH pin — or any other line — has a chance to stop+# it. Plant a fake bash ahead of the real one and confirm it never runs.+fake_bin="$(cd "$(mktemp -d)" && pwd -P)"+_tmpdirs+=("$fake_bin")+marker="$fake_bin/ran"+cat >"$fake_bin/bash" <<SCRIPT+#!/bin/sh+touch "$marker"+exec /bin/bash "\$@"+SCRIPT+chmod +x "$fake_bin/bash"+PATH="$fake_bin:$PATH" $SANDBOX 'true' >/dev/null 2>&1+if [[ -f "$marker" ]]; then+ die "planted bash ahead on PATH ran via shebang resolution"+else+ pass "shebang ignores a PATH-planted bash"+fi+echoif [[ $fail -eq 0 ]]; thenecho "PASS — all dev-sandbox self-tests passed"diff --git a/bin/dev-sandbox.sb b/bin/dev-sandbox.sbindex ee3ce3b76a46..2ae4cc967d89 100644--- a/bin/dev-sandbox.sb+++ b/bin/dev-sandbox.sb@@ -110,9 +110,90 @@;; Execute-later targets that run OUTSIDE the sandbox if poisoned. The repo;; is otherwise writable (build output, caches); these specific paths are not.(subpath (string-append (param "PROJECT") "/bin")) ; sandbox files + scripts (bin/wait-for-docker runs unsandboxed)+ (subpath (string-append (param "MAINREPO") "/bin")) ; worktree main-repo scripts — same execute-later route+ ;; The flox activation scripts. They run unsandboxed on every `flox activate`,+ ;; and on-activate.sh is what builds this sandbox — poisoning it is a shortcut+ ;; past everything else here. Only .flox/env is denied: run/, cache/ and log/+ ;; are generated and stay writable.+ (subpath (string-append (param "PROJECT") "/.flox/env"))+ (subpath (string-append (param "MAINREPO") "/.flox/env"))+ ;; The husky hooks. core.hooksPath points git at .husky, so these are the hooks+ ;; that actually run — .git/hooks above is the directory git never reads once+ ;; that is set. Same unsandboxed execution, one step more direct.+ (subpath (string-append (param "PROJECT") "/.husky"))+ (subpath (string-append (param "MAINREPO") "/.husky"))(subpath (string-append (param "PROJECT") "/.git/hooks")) ; git hooks run unsandboxed(subpath (string-append (param "MAINREPO") "/.git/hooks")) ; worktree main-repo hooks+ ;; Repo-local git config, which reaches the same escape as the hook denies above+ ;; by another route: core.hooksPath relocates the hook directory they protect,+ ;; and core.fsmonitor is a command git runs on ordinary read commands. Either one+ ;; executes in the developer's own terminal, outside Seatbelt. config.worktree is+ ;; the same file for a repo with extensions.worktreeConfig set.+ ;; The repo seeds its own entries here (blame.ignoreRevsFile, and core.hooksPath+ ;; for husky) from the flox activation, which runs unsandboxed. package.json's+ ;; postinstall still attempts blame.ignoreRevsFile, for clones that never activate+ ;; flox; sandboxed, that attempt no-ops against these denies and the activation is+ ;; what lands. cargo's git-dependency writes go to ~/.cargo/git/db instead.+ ;; husky's `prepare` still retries the core.hooksPath write on every sandboxed+ ;; install and prints git's "Operation not permitted"; that is noise, because the+ ;; activation already seeded the value. Do not relax these to silence it — husky+ ;; ignores git's exit status, so the deny would fail silently rather than loudly.+ ;; bin/dev-sandbox appends more of these at render time: a worktree's real gitdir+ ;; lives under MAINREPO/.git/worktrees/<name>/, sibling worktrees have their own,+ ;; and a symlinked .git resolves elsewhere — Seatbelt matches physical paths.+ ;; Those runtime denies are not redundant with the literals below.+ (literal (string-append (param "PROJECT") "/.git/config"))+ (literal (string-append (param "PROJECT") "/.git/config.worktree"))+ (literal (string-append (param "MAINREPO") "/.git/config"))+ (literal (string-append (param "MAINREPO") "/.git/config.worktree"))+ ;; The .git node itself. In a worktree it is a file holding `gitdir: <path>`, and+ ;; rewriting it repoints git at a directory the attacker controls, which brings+ ;; its own config and so the same escape. Denying the literal does not affect+ ;; entries inside a real .git directory — those are their own paths, and the dev+ ;; stack writes them freely.+ (literal (string-append (param "PROJECT") "/.git"))+ (literal (string-append (param "MAINREPO") "/.git"))(literal (string-append (param "HOME") "/.gitconfig")) ; core.hooksPath / credential.helper = !cmd(literal (string-append (param "HOME") "/.gitconfig.local")) ; included by ~/.gitconfig — same escape if writable(subpath (string-append (param "HOME") "/.config/git")) ; XDG git config — same hooksPath/helper escape+ ;; Homebrew's system-scope gitconfig, read by a brew-installed git on every+ ;; invocation and owned by the developer's account — unlike the Xcode CLT one,+ ;; which is root-owned and so already out of reach. Same hooksPath/fsmonitor+ ;; escape. Both prefixes: Apple Silicon, then Intel.+ (literal "/opt/homebrew/etc/gitconfig")+ (literal "/usr/local/etc/gitconfig")+ ;; …and the directories holding them. Seatbelt matches the resolved path, so+ ;; renaming the parent and dropping a symlink in its place moves the file out+ ;; from under the two literals above while everything in it keeps working.+ ;; Denying the node blocks that swap; writes to files inside are unaffected,+ ;; same as the .git node denies above.+ (literal "/opt/homebrew/etc")+ (literal "/usr/local/etc")+ ;; The rest of the Homebrew prefix: developer-owned like the gitconfig above, and+ ;; on PATH ahead of the system dirs — no git indirection needed, a planted+ ;; git/node/rg here just runs on the developer's next shell command.+ ;; lib/ is covered because Seatbelt matches resolved paths: bin/npm is a symlink+ ;; chain into Cellar and out again to ../lib/node_modules/npm/bin/npm-cli.js,+ ;; so the Cellar deny alone never matches the file npm actually executes.+ (subpath "/opt/homebrew/bin")+ (subpath "/opt/homebrew/sbin")+ (subpath "/opt/homebrew/Cellar")+ (subpath "/opt/homebrew/lib")+ (subpath "/usr/local/bin")+ (subpath "/usr/local/sbin")+ (subpath "/usr/local/Cellar")+ (subpath "/usr/local/lib")(subpath (string-append (param "HOME") "/.cargo/bin"))) ; binaries on PATH++;; husky's installer writes .husky/_/ (a gitignored husky.sh plus a .gitignore) on+;; every sandboxed `pnpm install`, and it throws when that write fails, which would+;; fail the install. Re-allow just that directory: last match wins, so this reopens+;; _/ and nothing else inside the .husky deny above.+;; Known limit, deliberate: the checked-in hooks source _/husky.sh, so this leaves+;; one path to the same unsandboxed execution. Closing it means moving husky's+;; install out of the sandbox, and a fresh clone has no _/husky.sh until pnpm+;; install creates it — the same restructuring #79300 tracks for the config chain.+;; The three checked-in hooks are protected either way.+(allow file-write*+ (subpath (string-append (param "PROJECT") "/.husky/_"))+ (subpath (string-append (param "MAINREPO") "/.husky/_")))