: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
chore(dev): add opt-in filesystem sandbox for dev services (#61789)
Tom Piccirello1e07c76249c4
diff --git a/.env.local.example b/.env.local.exampleindex 0dd12b1c6202..467a6eda618c 100644--- a/.env.local.example+++ b/.env.local.example@@ -23,5 +23,10 @@# Auto-login as a specific user (skips the login flow)+# macOS only: run Python/Node dev services under a Seatbelt sandbox so a+# malicious dependency can't read credentials (~/.ssh, ~/.aws, ...) outside the+# repo. See bin/dev-sandbox. No-op on Linux. Restart hogli start to apply.+# POSTHOG_DEV_SANDBOX=1+# Use your own API keys instead of 1Password# OPENAI_API_KEY=sk-...diff --git a/.flox/env/on-activate.sh b/.flox/env/on-activate.shindex 4ed59b693745..dc6e81e1e971 100755--- a/.flox/env/on-activate.sh+++ b/.flox/env/on-activate.sh@@ -302,10 +302,26 @@ _UV_SKIP=0_PHROCS_SKIP=0[[ -n "$_PHROCS_BAKED" && -n "$_PHROCS_CURRENT" && "$_PHROCS_BAKED" == "$_PHROCS_CURRENT" ]] && _PHROCS_SKIP=1+# Sandbox the automatic installs below when opted in (POSTHOG_DEV_SANDBOX=1,+# macOS). .env.local isn't loaded at flox-activate time, so check it directly+# alongside the live env. The build scripts that run during install (uv sdist+# hooks, allowlisted pnpm builds, cargo build.rs) then execute inside the+# sandbox, like the runtime path. See bin/dev-sandbox.+_DEV_SANDBOX_INSTALLS=0+if [[ "$(uname -s)" == "Darwin" && -x "$FLOX_ENV_PROJECT/bin/dev-sandbox" ]]; then+ if [[ "${POSTHOG_DEV_SANDBOX:-}" == "1" ]] || grep -qE "^[[:space:]]*POSTHOG_DEV_SANDBOX=1[[:space:]]*$" "$FLOX_ENV_PROJECT/.env.local" 2>/dev/null; then+ _DEV_SANDBOX_INSTALLS=1+ fi+fi+if [[ "$_PNPM_SKIP" -eq 0 ]]; then_BG_PNPM_LOG=$(mktemp)_ACTIVATION_TMPFILES+=("$_BG_PNPM_LOG")- ( pnpm install ) >"$_BG_PNPM_LOG" 2>&1 &+ if [[ "$_DEV_SANDBOX_INSTALLS" -eq 1 ]]; then+ ( "$FLOX_ENV_PROJECT/bin/dev-sandbox" "pnpm install" ) >"$_BG_PNPM_LOG" 2>&1 &+ else+ ( pnpm install ) >"$_BG_PNPM_LOG" 2>&1 &+ fi_BG_PNPM_PID=$!_BG_PNPM_START=$(date +%s)fi@@ -321,6 +337,8 @@ fi# ── Step 1: Python packages (must run before hogli — it needs Click) ─if [[ "$_UV_SKIP" -eq 1 ]]; thendone_step "Python packages (cached)"+elif [[ "$_DEV_SANDBOX_INSTALLS" -eq 1 ]]; then+ run_step "Python packages" "$FLOX_ENV_PROJECT/bin/dev-sandbox" "uv sync"elserun_step "Python packages" uv syncfidiff --git a/.github/workflows/dev-sandbox-selftest.yml b/.github/workflows/dev-sandbox-selftest.ymlnew file mode 100644index 000000000000..13f41a4a1f58--- /dev/null+++ b/.github/workflows/dev-sandbox-selftest.yml@@ -0,0 +1,37 @@+# Guards the local dev sandbox profile (bin/dev-sandbox*) against regressions.+# Path-filtered, so it only runs when the sandbox files themselves change.+name: Dev sandbox self-test++on:+ push:+ branches:+ - master+ paths:+ - bin/dev-sandbox+ - bin/dev-sandbox.sb+ - bin/dev-sandbox-selftest+ - .github/workflows/dev-sandbox-selftest.yml+ pull_request:+ paths:+ - bin/dev-sandbox+ - bin/dev-sandbox.sb+ - bin/dev-sandbox-selftest+ - .github/workflows/dev-sandbox-selftest.yml++concurrency:+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++jobs:+ selftest:+ name: Verify dev sandbox profile+ # sandbox-exec (Seatbelt) is macOS-only. Depot macOS is a fixed FIFO pool+ # (Startup+ plan); if it's unavailable, swap runs-on for `macos-14`.+ runs-on: depot-macos-latest+ timeout-minutes: 15+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ - name: Run dev sandbox self-test+ run: bin/dev-sandbox-selftestdiff --git a/bin/dev-sandbox b/bin/dev-sandboxnew file mode 100755index 000000000000..68eca87abee1--- /dev/null+++ b/bin/dev-sandbox@@ -0,0 +1,159 @@+#!/usr/bin/env bash+# Run a dev-stack command inside a macOS Seatbelt sandbox (see bin/dev-sandbox.sb).+#+# Usage: bin/dev-sandbox '<shell command>'+#+# The whole original shell command (operators and all) is passed as a single+# argument and run via `bash -c`. Opt in by setting POSTHOG_DEV_SANDBOX=1 in+# .env.local; the generator (hogli dev:generate) then wraps Python/Node service+# commands with this script.+#+# The base profile denies all reads under $HOME. Because the repo lives under+# $HOME, the OS / node module resolver / getcwd must still lstat+readdir the+# directory chain between $HOME and the repo to reach it. We compute that chain+# at runtime (it depends where each dev cloned the repo) and append read-allows+# for those specific dir nodes to a rendered copy of the profile — their non-repo+# contents (~/.ssh, ~/.aws, ...) stay denied.+#+# Failure policy:+# - non-macOS / sandbox-exec missing / profile missing / render fails -> passthrough+# - sandbox-exec cannot initialize the profile -> fail OPEN, loud warning+# (a working sandbox that merely *denies* a path is left to surface normally)++set -euo pipefail++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"; }++if [[ "$(uname -s)" != "Darwin" ]] || ! command -v sandbox-exec >/dev/null 2>&1 || [[ ! -f "$base_profile" ]]; then+ run_unsandboxed+fi++# When run from a git worktree, the main repo's .git lives outside $project; allow+# reads there too so git-aware tooling keeps working. Defaults to $project.+mainrepo="$project"+gitfile="$project/.git"+if [[ -f "$gitfile" ]]; then+ gitdir="$(sed -n 's/^gitdir: //p' "$gitfile")"+ [[ -n "$gitdir" && "$gitdir" != /* ]] && gitdir="$project/$gitdir"+ case "$gitdir" in+ */.git/worktrees/*) mainrepo="$(cd "${gitdir%/.git/worktrees/*}" 2>/dev/null && pwd -P || echo "$project")" ;;+ esac+fi++# Effective-profile path, keyed on every input that affects its contents: the+# base profile + this wrapper (via the mtime checks below) and the ancestor chain+# + SSH socket (via this hash). Any change yields a new path or fails a freshness+# check, so a cache hit is never stale. Keying lets the ~13 services phrocs starts+# concurrently reuse one render instead of each re-rendering identical bytes.+# TMPDIR is canonicalized so the profile's self-write-deny (rendered below) matches+# the physical path Seatbelt enforces against (/var/folders -> /private/var/...).+tmpdir="$(cd "${TMPDIR:-/tmp}" 2>/dev/null && pwd -P || echo "${TMPDIR:-/tmp}")"+cache_key="$(printf '%s\0' "$project" "$mainrepo" "$HOME" "${SSH_AUTH_SOCK:-}" | /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++# 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.+# Written to a unique temp and atomically renamed in (concurrent launches share+# the path; a half-written profile would make sandbox-exec fail open).+render_profile() {+ local -a ancestors=()+ local r p _a tmp sock_dir+ local _dq='"' _bs=$'\\'+ for r in "$project" "$mainrepo"; do+ p="${r%/*}"+ while [[ "$p" != "$HOME" && "$p" != "/" && -n "$p" ]]; do+ ancestors+=("$p")+ p="${p%/*}"+ done+ done+ ancestors+=("$HOME")+ # Paths are emitted as SBPL string literals; a " or \ would corrupt the+ # profile (quoted expansions match literally, dodging glob/escape ambiguity).+ for _a in "${ancestors[@]}" "$rendered" "$stamp"; do+ case "$_a" in+ *"$_dq"* | *"$_bs"*)+ echo "⚠️ dev sandbox: path contains a quote/backslash, running WITHOUT sandbox: $_a" >&2+ return 1+ ;;+ esac+ done+ tmp="$(mktemp "$tmpdir/posthog-dev-sandbox.XXXXXX")" || return 1+ if {+ cat "$base_profile"+ printf '(allow file-read*'+ printf ' (literal "%s")' "${ancestors[@]}"+ printf ')\n'+ # 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.+ if [[ "${SSH_AUTH_SOCK:-}" == /* ]]; then+ sock_dir="$(cd "${SSH_AUTH_SOCK%/*}" 2>/dev/null && pwd -P || true)"+ if [[ -n "$sock_dir" ]]; then+ printf '(deny network-outbound (literal "%s/%s"))\n' "$sock_dir" "${SSH_AUTH_SOCK##*/}"+ else+ printf '(deny network-outbound (literal "%s"))\n' "$SSH_AUTH_SOCK"+ fi+ fi+ # Deny the sandboxed process from rewriting its own cached profile + stamp.+ # They sit in TMPDIR (outside $HOME, hence writable by default); poisoning+ # 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"+ } >"$tmp" 2>/dev/null && mv -f "$tmp" "$rendered"; then+ rm -f "$stamp" # new contents: force a fresh init preflight+ return 0+ fi+ rm -f "$tmp"+ return 1+}++# Render on a cache miss: no rendered file, or the base profile / this wrapper is+# newer than the cache. The wrapper check means a render-logic change (e.g. on git+# pull) self-invalidates every stale profile — no version token to bump.+if [[ ! -f "$rendered" || "$base_profile" -nt "$rendered" || "$project/bin/dev-sandbox" -nt "$rendered" ]]; then+ render_profile || run_unsandboxed+fi++sandbox=(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).+if [[ "$rendered" -nt "$stamp" ]]; then+ if "${sandbox[@]}" /usr/bin/true >/dev/null 2>&1; then+ touch "$stamp" 2>/dev/null || true+ else+ echo "⚠️ dev sandbox failed to initialize — running WITHOUT sandbox. Set POSTHOG_DEV_SANDBOX=0 to silence." >&2+ run_unsandboxed+ fi+fi++# Strip ambient personal tokens the dev stack doesn't need from the child env.+# The application's own config env (DB URLs, OBJECT_STORAGE_* keys, 1Password-+# injected API keys) is left intact — only credentials that happen to live in the+# shell are removed. AWS_* is stripped because the dev stack reaches local object+# storage via OBJECT_STORAGE_*, not the AWS chain; DOCKER_HOST is stripped so the+# docker CLI can't be pointed at an endpoint the socket deny doesn't cover.+exec env \+ -u GITHUB_TOKEN \+ -u GH_TOKEN \+ -u NPM_TOKEN \+ -u NPM_AUTH_TOKEN \+ -u OP_SERVICE_ACCOUNT_TOKEN \+ -u SSH_AUTH_SOCK \+ -u DOCKER_HOST \+ -u AWS_ACCESS_KEY_ID \+ -u AWS_SECRET_ACCESS_KEY \+ -u AWS_SESSION_TOKEN \+ -u VAULT_TOKEN \+ -u GITLAB_TOKEN \+ -u CARGO_REGISTRY_TOKEN \+ -u HUGGING_FACE_HUB_TOKEN \+ -u HF_TOKEN \+ "${sandbox[@]}" /bin/bash -c "$cmd"diff --git a/bin/dev-sandbox-selftest b/bin/dev-sandbox-selftestnew file mode 100755index 000000000000..323eabe34409--- /dev/null+++ b/bin/dev-sandbox-selftest@@ -0,0 +1,199 @@+#!/usr/bin/env bash+# Self-test for the dev sandbox (bin/dev-sandbox + bin/dev-sandbox.sb).+#+# Regression guard: asserts the profile compiles, credential contents are+# blocked, persistence writes are blocked, the $HOME->repo ancestor chain is+# traversable (getcwd/realpath), env tokens are stripped, and the allowlisted+# toolchain dirs are readable. Run locally (`bin/dev-sandbox-selftest`) or in CI+# (.github/workflows/dev-sandbox-selftest.yml).+#+# Interpreters under $HOME (nvm/pyenv/hostedtoolcache) can't be exec'd inside the+# sandbox by design, so the path-traversal check uses /usr/bin/python3, which+# lives outside $HOME on macOS.++set -uo pipefail # intentionally not -e: run every check, then report++cd "$(dirname "$0")/.." || exit 1+SANDBOX="bin/dev-sandbox"+fail=0+pass() { printf ' \033[32mok\033[0m %s\n' "$1"; }+die() {+ printf ' \033[31mFAIL\033[0m %s\n' "$1"+ fail=1+}++if [[ "$(uname -s)" != "Darwin" ]] || ! command -v sandbox-exec >/dev/null 2>&1; then+ echo "Sandbox is a no-op on this platform — nothing to test."+ exit 0+fi++echo "dev-sandbox self-test"++# 1. Profile compiles and the sandbox is actually enforcing (not failing open).+err="$($SANDBOX 'echo SANDBOX_MARKER' 2>&1 >/dev/null)"+out="$($SANDBOX 'echo SANDBOX_MARKER' 2>/dev/null)"+if [[ "$out" == "SANDBOX_MARKER" && "$err" != *"failed to initialize"* ]]; then+ pass "profile compiles, sandbox active"+else+ die "sandbox not active (fail-open or broken profile): ${err:-no stderr}"+fi++# 2. Repo is readable.+if $SANDBOX 'head -1 package.json >/dev/null' 2>/dev/null; then+ pass "repo readable"+else+ die "repo not readable"+fi++# 3. Credential file CONTENTS are blocked. Probe a file in $HOME root (always+# exists); never create credential dirs as a side effect.+secret="$HOME/.dev_sandbox_selftest_secret"+echo secret >"$secret"+if $SANDBOX "cat '$secret'" >/dev/null 2>&1; then+ die "HOME file content readable (must be blocked)"+else+ pass "HOME file content blocked"+fi+rm -f "$secret"+if [[ -d "$HOME/.aws" ]]; then+ aws_probe="$HOME/.aws/.dev_sandbox_selftest"+ echo secret >"$aws_probe" 2>/dev/null || true+ if [[ -f "$aws_probe" ]]; then+ if $SANDBOX "cat '$aws_probe'" >/dev/null 2>&1; then die ".aws content readable"; else pass ".aws content blocked"; fi+ rm -f "$aws_probe"+ fi+fi++# 4. Writes that enable persistence are blocked. Only if ~/.ssh already exists —+# never create it (default umask 0755 would break the user's real ssh).+if [[ -d "$HOME/.ssh" ]]; then+ if $SANDBOX "echo x > '$HOME/.ssh/.dev_sandbox_selftest'" >/dev/null 2>&1; then+ die ".ssh write allowed (must be blocked)"+ rm -f "$HOME/.ssh/.dev_sandbox_selftest"+ else+ pass ".ssh write blocked"+ fi+else+ echo " -- ~/.ssh absent, skipping write-deny check"+fi++# 5. $HOME->repo ancestor chain is traversable: getcwd + realpath of a repo file.+# /usr/bin/python3 lives outside $HOME so it is exec'able inside the sandbox.+if [[ -x /usr/bin/python3 ]]; then+ if $SANDBOX "/usr/bin/python3 -c 'import os,sys; sys.exit(0 if os.path.isfile(os.path.realpath(\"package.json\")) else 1)'" 2>/dev/null; then+ pass "getcwd + realpath through HOME ancestors"+ else+ die "path traversal into repo blocked (ancestor-chain allow missing?)"+ fi+else+ echo " -- /usr/bin/python3 absent, skipping traversal check"+fi++# 6. Ambient tokens are stripped from the child environment.+# Single quotes below are intentional: $GITHUB_TOKEN must be expanded by the+# sandboxed shell, not by this one.+# shellcheck disable=SC2016+token_seen="$(GITHUB_TOKEN=should-vanish $SANDBOX 'printf %s "${GITHUB_TOKEN:-}"' 2>/dev/null)"+if [[ -z "$token_seen" ]]; then+ pass "GITHUB_TOKEN stripped"+else+ die "GITHUB_TOKEN not stripped"+fi++# 7. Allowlisted toolchain dirs are readable. Only the ones that already exist —+# never create dirs in $HOME as a side effect.+for d in .cache .npm .cargo "Library/Caches/node-gyp"; do+ if [[ ! -d "$HOME/$d" ]]; then+ echo " -- \$HOME/$d absent, skipping"+ continue+ fi+ if $SANDBOX "ls -d '$HOME/$d' >/dev/null" 2>/dev/null; then+ pass "readable: \$HOME/$d"+ else+ die "allowlisted dir not readable: \$HOME/$d"+ fi+done++# 8. cargo publish token stays blocked even though ~/.cargo is allowed (only if+# ~/.cargo already exists — don't create it).+if [[ -d "$HOME/.cargo" ]]; then+ cred="$HOME/.cargo/credentials.toml"+ created=0+ if [[ ! -f "$cred" ]]; then+ printf '[registry]\ntoken="x"\n' >"$cred" 2>/dev/null && created=1+ fi+ if [[ -f "$cred" ]]; then+ if $SANDBOX "cat '$cred'" >/dev/null 2>&1; then+ die "cargo credentials readable"+ else+ pass "cargo credentials blocked"+ fi+ [[ "$created" == 1 ]] && rm -f "$cred"+ fi+else+ echo " -- ~/.cargo absent, skipping cargo-credentials check"+fi++# 9. The docker daemon socket is unreachable inside the sandbox — otherwise a+# dependency could escape via `docker run -v $HOME:/host ...`. Only meaningful+# when a daemon is actually reachable from outside the sandbox.+if command -v docker >/dev/null 2>&1 && docker version --format '{{.Server.Version}}' >/dev/null 2>&1; then+ if $SANDBOX "docker version --format '{{.Server.Version}}'" >/dev/null 2>&1; then+ die "docker daemon reachable inside sandbox (container-mount escape possible)"+ else+ pass "docker daemon socket blocked (no container escape)"+ fi+else+ echo " -- no reachable docker daemon, skipping escape check"+fi++# 10. SSH agent unreachable inside the sandbox — otherwise a dep could use your+# keys (auth/sign) without reading ~/.ssh. Only meaningful with a live agent.+if [[ -n "${SSH_AUTH_SOCK:-}" ]] && ssh-add -l >/dev/null 2>&1; then+ if $SANDBOX 'ssh-add -l' >/dev/null 2>&1; then+ die "ssh agent reachable inside sandbox (keys usable)"+ else+ pass "ssh agent unreachable"+ fi+else+ echo " -- no usable ssh agent, skipping"+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+ die "writable, should be blocked: $2"+ rm -f "$1"+ else+ pass "write blocked: $2"+ fi+}+check_write_blocked "bin/.dev_sandbox_selftest_probe" "repo bin/"+mkdir -p .git/hooks 2>/dev/null || true+check_write_blocked ".git/hooks/.dev_sandbox_selftest_probe" ".git/hooks"+if [[ -d "$HOME/.cargo/bin" ]]; then+ check_write_blocked "$HOME/.cargo/bin/.dev_sandbox_selftest_probe" "cargo bin"+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)+rendered_profile="${rendered_profiles[0]}" # literal glob if none matched -> -f false below+if [[ -f "$rendered_profile" ]]; then+ check_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)"+fi++echo+if [[ $fail -eq 0 ]]; then+ echo "PASS — all dev-sandbox self-tests passed"+ exit 0+else+ echo "FAIL — dev-sandbox self-tests failed"+ exit 1+fidiff --git a/bin/dev-sandbox.sb b/bin/dev-sandbox.sbnew file mode 100644index 000000000000..57d8e721e1f3--- /dev/null+++ b/bin/dev-sandbox.sb@@ -0,0 +1,96 @@+;; macOS Seatbelt profile for the dev stack (see bin/dev-sandbox).+;;+;; Goal: a malicious npm/pip dependency running inside a dev service must not be+;; able to read credentials or other personal files from the developer's home+;; directory. Strategy: deny-by-default for $HOME, then re-allow only the repo ++;; the toolchain caches that legitimately live under $HOME. Everything outside+;; $HOME (system libraries, the flox/nix store at /nix/store, /tmp) stays+;; readable so the stack can actually run.+;;+;; Parameters are injected by bin/dev-sandbox via -D:+;; HOME absolute path to the developer's home directory+;; PROJECT canonical (physical) path to the repository root+;; MAINREPO main repo root when PROJECT is a git worktree, else == PROJECT+;;+;; SBPL is last-match-wins, so the re-allows below override the broad denies.+;;+;; bin/dev-sandbox appends `(allow file-read* (literal ...))` for the directory+;; chain between $HOME and the repo at runtime — the OS / node / getcwd must+;; lstat+readdir those dir nodes to reach the repo. Only those specific nodes+;; become readable; their non-repo contents stay denied by the rule below.++(version 1)++;; Broad base: process exec/fork, network, mach, sysctl, signals, etc.+;; We only tighten filesystem reads/writes and the docker socket below.+(allow default)++;; ── Docker daemon socket ──────────────────────────────────────────────+;; Reaching the docker daemon is a full sandbox escape: a dependency could run+;; `docker run -v $HOME:/host ...` and the daemon (which runs outside Seatbelt)+;; would mount the home dir into a container. bin/wait-for-docker runs OUTSIDE+;; the sandbox instead (see the generator), so sandboxed code never needs this+;; socket. Covers OrbStack and Docker Desktop.+(deny network-outbound+ (subpath (string-append (param "HOME") "/.orbstack/run"))+ (subpath (string-append (param "HOME") "/.docker/run"))+ (literal "/var/run/docker.sock")+ (literal "/private/var/run/docker.sock"))++;; ── Key/secret agent sockets ──────────────────────────────────────────+;; Reaching an agent lets a dep USE credentials without reading the key files+;; (sign SSH/GPG challenges, request 1Password secrets) — bypassing the read+;; block's intent. The SSH agent ($SSH_AUTH_SOCK) is denied at runtime by+;; bin/dev-sandbox (its path varies per agent); gpg and 1Password are static.+(deny network-outbound+ (subpath (string-append (param "HOME") "/.gnupg"))+ (subpath (string-append (param "HOME") "/Library/Group Containers/2BUA8C4S2C.com.1password")))++;; ── Reads ─────────────────────────────────────────────────────────────+;; Block every read under $HOME, then re-allow the repo and toolchain caches.+;; ~/.ssh, ~/.aws, ~/.config/{gcloud,gh,op}, ~/.gnupg, ~/Library/Keychains,+;; other repos, browser data — none are re-allowed, so all stay unreadable.+(deny file-read* (subpath (param "HOME")))+(allow file-read*+ (subpath (param "PROJECT")) ; repo (incl. .flox/cache/venv, node_modules)+ (subpath (param "MAINREPO")) ; main repo's .git when PROJECT is a worktree+ (subpath (string-append (param "HOME") "/.cache")) ; uv, node, flox caches+ (subpath (string-append (param "HOME") "/.npm")) ; npm cache+ (subpath (string-append (param "HOME") "/Library/Caches/node-gyp")) ; node headers for native builds+ (subpath (string-append (param "HOME") "/.local/share/uv")) ; uv-managed Python interpreters (venv links here)+ (subpath (string-append (param "HOME") "/.local/share/flox")) ; flox metadata+ (subpath (string-append (param "HOME") "/Library/pnpm")) ; pnpm content-addressed store+ ;; git global config (read by version-detection / git-aware tooling). Config+ ;; only, by exact path — credentials (~/.git-credentials, keychain) stay blocked.+ (literal (string-append (param "HOME") "/.gitconfig"))+ (literal (string-append (param "HOME") "/.config/git/config"))+ ;; cargo registry/git cache — the cyclotron-node native module is built with+ ;; cargo during the nodejs service prestart. (crates.io token re-denied below.)+ (subpath (string-append (param "HOME") "/.cargo")))++;; Keep the crates.io publish token blocked even though ~/.cargo is allowed above.+(deny file-read*+ (literal (string-append (param "HOME") "/.cargo/credentials"))+ (literal (string-append (param "HOME") "/.cargo/credentials.toml")))++;; ── Writes ────────────────────────────────────────────────────────────+;; Writes stay broadly allowed (the stack writes caches, build output, /tmp),+;; but block the obvious persistence vectors so a dependency can't plant a+;; login hook or background agent.+(deny file-write*+ (subpath (string-append (param "HOME") "/.ssh"))+ (subpath (string-append (param "HOME") "/Library/LaunchAgents"))+ (literal (string-append (param "HOME") "/.zshrc"))+ (literal (string-append (param "HOME") "/.zprofile"))+ (literal (string-append (param "HOME") "/.zshenv"))+ (literal (string-append (param "HOME") "/.bashrc"))+ (literal (string-append (param "HOME") "/.bash_profile"))+ (literal (string-append (param "HOME") "/.profile"))+ ;; 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 "PROJECT") "/.git/hooks")) ; git hooks run unsandboxed+ (subpath (string-append (param "MAINREPO") "/.git/hooks")) ; worktree main-repo hooks+ (literal (string-append (param "HOME") "/.gitconfig")) ; core.hooksPath / credential.helper = !cmd+ (subpath (string-append (param "HOME") "/.config/git")) ; XDG git config — same hooksPath/helper escape+ (subpath (string-append (param "HOME") "/.cargo/bin"))) ; binaries on PATHdiff --git a/bin/mprocs.yaml b/bin/mprocs.yamlindex 793103832e99..bdd186d0857f 100755--- a/bin/mprocs.yaml+++ b/bin/mprocs.yaml@@ -35,6 +35,7 @@ procs:capability: pinnedbackend:+ sandbox: trueshell: 'bin/wait-for-docker && ./bin/start-backend'ready_pattern: 'Listening at'groups:@@ -43,6 +44,7 @@ procs:# no capability: always_required via intent-map.yamlcelery-worker:+ sandbox: trueshell: 'bin/wait-for-docker && ./bin/start-celery worker'capability: celery_workersready_pattern: 'celery@'@@ -51,6 +53,7 @@ procs:tech: Pythoncelery-beat:+ sandbox: trueshell: 'bin/wait-for-docker && ./bin/start-celery beat'capability: celery_schedulerready_pattern: 'celery beat'@@ -59,6 +62,7 @@ procs:tech: Pythonnodejs:+ sandbox: trueshell: 'bin/wait-for-docker && ./bin/posthog-node'capability: event_ingestionready_pattern: 'All systems go'@@ -71,6 +75,7 @@ procs:# Example: NODEJS_CAPABILITY_GROUPS=cdp_workflows,session_replayingestion-errortracking:+ sandbox: trueshell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=ingestion-errortracking HTTP_SERVER_PORT=6742 ./bin/posthog-node'capability: nodejs_error_trackingready_pattern: 'All systems go'@@ -79,6 +84,7 @@ procs:tech: Nodeingestion-logs:+ sandbox: trueshell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=ingestion-logs HTTP_SERVER_PORT=6743 ./bin/posthog-node'capability: nodejs_logsready_pattern: 'All systems go'@@ -87,11 +93,13 @@ procs:tech: Nodeingestion-metrics:+ sandbox: trueshell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=ingestion-metrics HTTP_SERVER_PORT=6744 ./bin/posthog-node'capability: nodejs_metricsready_pattern: 'All systems go'ingestion-traces:+ sandbox: trueshell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=ingestion-traces HTTP_SERVER_PORT=6745 ./bin/posthog-node'capability: nodejs_tracesready_pattern: 'All systems go'@@ -100,6 +108,7 @@ procs:tech: Nodeingestion:+ sandbox: trueshell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=ingestion-v2-combined HTTP_SERVER_PORT=6739 ./bin/posthog-node'capability: event_ingestionready_pattern: 'All systems go'@@ -108,6 +117,7 @@ procs:tech: Nodeingestion-sessionreplay:+ sandbox: trueshell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=recordings-blob-ingestion-v2 HTTP_SERVER_PORT=6740 ./bin/posthog-node'capability: nodejs_session_replayready_pattern: 'All systems go'@@ -116,6 +126,7 @@ procs:tech: Noderecording-api:+ sandbox: trueshell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=recording-api HTTP_SERVER_PORT=6741 ./bin/posthog-node'capability: nodejs_session_replayready_pattern: 'All systems go'@@ -124,6 +135,7 @@ procs:tech: Nodefrontend:+ sandbox: trueshell: './bin/start-frontend'autorestart: trueready_pattern: 'VITE.*ready in'@@ -133,6 +145,7 @@ procs:# no capability: always_required via intent-map.yamltypegen:+ sandbox: trueshell: 'cd frontend && pnpm run typegen:watch'autostart: falseask_skip: true # wizard asks if user wants to skip this@@ -142,6 +155,7 @@ procs:tech: Frontendtemporal-worker:+ sandbox: trueshell: |-bin/wait-for-docker temporal && \bin/check_ducklake_up && \@@ -157,6 +171,7 @@ procs:tech: Pythonwebhook-s3-sink:+ sandbox: trueshell: |-bin/wait-for-docker && \python manage.py run_webhook_s3_sink --consumer-group dwh-webhook-sink-dev --health-port 8091@@ -167,6 +182,7 @@ procs:tech: Pythonstripe-mock:+ sandbox: trueshell: 'bin/start-stripe-mock'capability: stripe_mockready_pattern: 'Application startup complete'@@ -191,6 +207,7 @@ procs:SECRET_KEY: '<randomly generated secret key>'dagster:+ sandbox: trueshell: |-bin/wait-for-docker && \bin/check_ducklake_up && \@@ -409,6 +426,7 @@ procs:ready_pattern: 'Metrics server listening on *'llm-gateway:+ sandbox: trueshell: 'bin/wait-for-docker && bin/start-llm-gateway'capability: llm_gatewayready_pattern: 'Application startup complete'@@ -422,6 +440,7 @@ procs:LLM_GATEWAY_POSTHOG_HOST: 'http://localhost:8010'mcp:+ sandbox: trueshell: 'bin/start-mcp-server'capability: mcp_serverready_pattern: 'Server started on'@@ -430,6 +449,7 @@ procs:tech: Nodemcp-ui-apps:+ sandbox: trueshell: 'cd services/mcp && pnpm run build:ui-apps -- --watch'capability: mcp_serverready_pattern: 'Initial build complete'@@ -438,6 +458,7 @@ procs:tech: Frontendmcp-inspector:+ sandbox: trueshell: 'cd services/mcp && pnpm run inspector'capability: mcp_serverautostart: false@@ -447,6 +468,7 @@ procs:tech: Frontendstripe-app:+ sandbox: trueshell: 'bin/start-stripe-app'capability: stripe_appgroups:@@ -508,6 +530,7 @@ procs:# no capability - optional migrationgenerate-demo-data:+ sandbox: trueshell: |-bin/wait-for-docker && \./manage.py generate_demo_data@@ -519,6 +542,7 @@ procs:# no capability - manual startsync-feature-flags:+ sandbox: trueshell: |-bin/wait-for-docker && \./manage.py sync_feature_flags@@ -530,6 +554,7 @@ procs:# no capability - manual startsync-hog-function-templates:+ sandbox: trueshell: |-bin/wait-for-docker && \./manage.py sync_hog_function_templates@@ -541,6 +566,7 @@ procs:# no capability - manual startstorybook:+ sandbox: trueshell: 'pnpm --filter=@posthog/storybook install && pnpm run storybook'autostart: falseready_pattern: 'Storybook *'@@ -550,6 +576,7 @@ procs:# no capability - manual starthedgebox-dummy:+ sandbox: trueshell: 'bin/wait-for-docker && cd tools/hedgebox-dummy && pnpm install && pnpm run dev'autostart: falseready_pattern: 'Ready in *'@@ -559,6 +586,7 @@ procs:# no capability - manual startwarehouse-sources-load:+ sandbox: trueshell: |-bin/wait-for-docker && \python manage.py run_warehouse_sources_loaddiff --git a/hogli.yaml b/hogli.yamlindex ffed24df94ad..3a27b0658b83 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -999,3 +999,11 @@ environment:bin_script: wait-for-postgres-tablesdescription: 'Block until the named Postgres tables exist'hidden: true+ dev:sandbox:+ bin_script: dev-sandbox+ description: 'Run a command inside the dev filesystem sandbox (internal; used by hogli dev:generate when POSTHOG_DEV_SANDBOX=1)'+ hidden: true+ dev:sandbox:selftest:+ bin_script: dev-sandbox-selftest+ description: 'Verify the dev sandbox profile: blocks credentials/escapes, allows the toolchain'+ hidden: truediff --git a/tools/hogli-commands/hogli_commands/devenv/generator.py b/tools/hogli-commands/hogli_commands/devenv/generator.pyindex 8f8cc8d961c8..1394a0c2f94a 100644--- a/tools/hogli-commands/hogli_commands/devenv/generator.py+++ b/tools/hogli-commands/hogli_commands/devenv/generator.py@@ -7,6 +7,10 @@ The system is designed to be process-manager agnostic - mprocs is just one outpufrom __future__ import annotationsimport os+import re+import sys+import shlex+import shutilfrom abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -188,6 +192,9 @@ class MprocsGenerator(ConfigGenerator):if name == "temporal-worker":proc_config = self._add_uv_groups(proc_config, resolved)+ # Wrap Python/Node service commands in the dev sandbox when opted in+ proc_config = self._add_sandbox_wrapper(proc_config)+# Add logging wrapper if enabledif source_config and source_config.log_to_files:proc_config = self._add_logging(proc_config, name)@@ -218,9 +225,23 @@ class MprocsGenerator(ConfigGenerator):orange = r"\033[38;2;245;78;0m" # #F54E00blue = r"\033[38;2;29;74;255m" # #1D4AFFgray = r"\033[38;5;245m"+ green = r"\033[32m"bold = r"\033[1m"reset = r"\033[0m"+ # Reflect the *effective* dependency-sandbox state: opted in via+ # POSTHOG_DEV_SANDBOX=1 AND on macOS with sandbox-exec (the wrapper no-ops+ # elsewhere). Mirrors the gate in _add_sandbox_wrapper, so the banner can't+ # claim isolation the platform won't deliver.+ sandbox_opted_in = os.getenv("POSTHOG_DEV_SANDBOX") == "1"+ sandbox_supported = sys.platform == "darwin" and shutil.which("sandbox-exec") is not None+ if sandbox_opted_in and sandbox_supported:+ sandbox_status = f"{green}on{reset}"+ elif sandbox_opted_in:+ sandbox_status = f"{gray}off — POSTHOG_DEV_SANDBOX set but unsupported on this platform{reset}"+ else:+ sandbox_status = f"{gray}off{reset} {gray}(set POSTHOG_DEV_SANDBOX=1 in .env.local){reset}"+news_url = "https://raw.githubusercontent.com/posthog/posthog/master/devenv/news.txt"news_local = "devenv/news.txt"@@ -248,6 +269,7 @@ if [ -n "${{_POSTHOG_OP_RESOLVED:-}}" ]; thenelseprintf ' {bold}Secrets:{reset} {gray}local .env files{reset}\\n'fi+printf ' {bold}Sandbox:{reset} {sandbox_status}\\n'echo ''printf ' {bold}Log in with:{reset} [email protected] - {blue}12345678{reset}\\n'printf ' {gray}Run {reset}{blue}hogli dev:setup{reset}{gray} to tailor this to your workflow.{reset}\\n'@@ -363,6 +385,72 @@ printf ' {gray}Run {reset}{blue}hogli dev:setup{reset}{gray} to tailor this toproc_config["shell"] = f"{prefix} && {original_shell}"return proc_config+ # Trusted infra-wait scripts that need the docker daemon socket. They run+ # OUTSIDE the sandbox (the socket is denied inside it — reaching the daemon is+ # a full escape via `docker run -v $HOME:/host`). They contain no dependency+ # code, so running them unsandboxed doesn't widen the untrusted attack surface.+ _SANDBOX_DOCKER_GATES = ("bin/wait-for-docker", "bin/wait-for-postgres-tables")++ def _add_sandbox_wrapper(self, proc_config: dict[str, Any]) -> dict[str, Any]:+ """Wrap a service command in bin/dev-sandbox (macOS Seatbelt) when opted in.++ Opt in globally with POSTHOG_DEV_SANDBOX=1 (e.g. in .env.local). A proc is+ wrapped only if it declares ``sandbox: true`` in the registry — an explicit,+ reviewable per-proc boundary rather than one inferred from the cosmetic+ ``groups.tech`` field (which is optional, so a forgotten annotation silently+ dropped a service out of the sandbox). Rust/Docker/migration procs simply+ omit the flag. The sandbox restricts reads to the repo + toolchain caches so+ a malicious dependency can't read credentials (~/.ssh, ~/.aws, ...) and denies+ the docker/agent sockets so it can't escape via a container mount.++ The docker-gate preamble (bin/wait-for-docker) is peeled out to run+ unsandboxed, since it needs the very socket the sandbox denies; the actual+ server (which reaches infra over TCP) is what gets sandboxed. bin/dev-sandbox+ is a no-op passthrough on non-macOS, so the generated config stays portable.+ """+ # `sandbox` is a registry-only selector; pop it so it never leaks into the+ # emitted proc config (which phrocs/mprocs would otherwise see).+ should_sandbox = bool(proc_config.pop("sandbox", False))+ if os.getenv("POSTHOG_DEV_SANDBOX") != "1" or not should_sandbox:+ return proc_config++ shell = proc_config.get("shell", "")+ if not shell:+ return proc_config++ # Split into docker-gate segments (run unsandboxed) and the rest (sandboxed).+ # Collapse `\`-newline continuations first; splitting on && is safe here+ # because the generated commands keep branching inside if/;-blocks, not &&.+ #+ # Gates are matched anywhere in the chain and hoisted to the front, not kept+ # in place: _add_startup_message and _add_uv_groups prepend echo/uv-sync+ # preambles, so a gate is never the leading segment (a leading-run scan would+ # wrongly sandbox it). Hoisting reorders segments, which is safe because the+ # only gates (wait-for-docker, wait-for-postgres-tables) just block until+ # infra is ready and are order-independent w.r.t. install/echo/server steps.+ # A future order-sensitive gate would need interleaving instead of hoisting.+ normalized = re.sub(r"\\\n\s*", " ", shell)+ gates: list[str] = []+ rest: list[str] = []+ for segment in normalized.split("&&"):+ stripped = segment.strip()+ if not stripped:+ continue+ first_token = stripped.split(maxsplit=1)[0]+ (gates if first_token in self._SANDBOX_DOCKER_GATES else rest).append(stripped)++ rest_cmd = " && ".join(rest)+ if not rest_cmd:+ # Command is only gate scripts (trusted, need the docker socket) — there+ # is nothing to sandbox, so run them as-is. Avoids `bin/dev-sandbox ''`,+ # which the wrapper rejects (its ${1:?} fires on an empty argument).+ proc_config["shell"] = " && ".join(gates)+ elif not gates:+ proc_config["shell"] = f"bin/dev-sandbox {shlex.quote(rest_cmd)}"+ else:+ proc_config["shell"] = f"{' && '.join(gates)} && bin/dev-sandbox {shlex.quote(rest_cmd)}"+ return proc_config+def _add_logging(self, proc_config: dict[str, Any], process_name: str) -> dict[str, Any]:"""Wrap shell command to log output to /tmp/posthog-{name}.log.diff --git a/tools/hogli-commands/hogli_commands/tests/test_devenv.py b/tools/hogli-commands/hogli_commands/tests/test_devenv.pyindex 2dae29e0aa9f..aa939ba226fe 100644--- a/tools/hogli-commands/hogli_commands/tests/test_devenv.py+++ b/tools/hogli-commands/hogli_commands/tests/test_devenv.py@@ -2,11 +2,16 @@from __future__ import annotations+import os+import sys+import shlex+import shutilimport tempfilefrom pathlib import Pathfrom typing import Anyimport pytest+from unittest import mockimport yamlfrom hogli_commands.devenv.generator import DevenvConfig, MprocsGenerator, load_devenv_config@@ -122,6 +127,50 @@ def create_test_registry() -> MockRegistry:)+class TestSandboxWrapper:+ @staticmethod+ def _wrap(proc: dict[str, Any]) -> dict[str, Any]:+ return MprocsGenerator(MockRegistry({}))._add_sandbox_wrapper(proc)++ def test_flag_off_leaves_command_unwrapped(self, monkeypatch: Any) -> None:+ monkeypatch.delenv("POSTHOG_DEV_SANDBOX", raising=False)+ result = self._wrap({"shell": "./bin/start-backend", "sandbox": True})+ assert result["shell"] == "./bin/start-backend"+ assert "sandbox" not in result # registry-only selector must never leak to phrocs++ def test_opted_in_proc_without_flag_not_wrapped(self, monkeypatch: Any) -> None:+ monkeypatch.setenv("POSTHOG_DEV_SANDBOX", "1")+ result = self._wrap({"shell": "cargo run --bin x"})+ assert result["shell"] == "cargo run --bin x"+ assert "sandbox" not in result++ def test_wraps_when_opted_in(self, monkeypatch: Any) -> None:+ monkeypatch.setenv("POSTHOG_DEV_SANDBOX", "1")+ result = self._wrap({"shell": "./bin/start-frontend", "sandbox": True})+ assert result["shell"] == "bin/dev-sandbox ./bin/start-frontend"+ assert "sandbox" not in result++ def test_docker_gate_runs_outside_sandbox(self, monkeypatch: Any) -> None:+ monkeypatch.setenv("POSTHOG_DEV_SANDBOX", "1")+ result = self._wrap({"shell": "bin/wait-for-docker && ./bin/start-backend", "sandbox": True})+ assert result["shell"] == "bin/wait-for-docker && bin/dev-sandbox ./bin/start-backend"++ def test_gate_hoisted_from_middle_of_chain(self, monkeypatch: Any) -> None:+ # echo/uv-sync preambles are prepended before the gate, so it is never the+ # leading segment; it must still be peeled out to run unsandboxed.+ monkeypatch.setenv("POSTHOG_DEV_SANDBOX", "1")+ result = self._wrap({"shell": "echo hi && bin/wait-for-docker && ./server", "sandbox": True})+ assert result["shell"] == "bin/wait-for-docker && bin/dev-sandbox " + shlex.quote("echo hi && ./server")++ def test_gates_only_command_not_wrapped(self, monkeypatch: Any) -> None:+ # Nothing untrusted to sandbox -> must not emit `bin/dev-sandbox ''` (the+ # wrapper's ${1:?} would reject the empty argument and the service would die).+ monkeypatch.setenv("POSTHOG_DEV_SANDBOX", "1")+ result = self._wrap({"shell": "bin/wait-for-docker && bin/wait-for-postgres-tables x", "sandbox": True})+ assert "bin/dev-sandbox" not in result["shell"]+ assert result["shell"] == "bin/wait-for-docker && bin/wait-for-postgres-tables x"++class TestIntentResolver:"""Test intent resolution logic."""@@ -533,6 +582,33 @@ class TestInfoProcess:for product in expected_products:assert product in shell+ @parameterized.expand(+ [+ ("disabled", {}, "linux", False, "POSTHOG_DEV_SANDBOX=1"),+ ("enabled_macos", {"POSTHOG_DEV_SANDBOX": "1"}, "darwin", True, r"\033[32mon"),+ ("enabled_unsupported", {"POSTHOG_DEV_SANDBOX": "1"}, "linux", False, "unsupported"),+ ]+ )+ def test_info_process_shows_sandbox_status(+ self,+ _name: str,+ env: dict[str, str],+ platform: str,+ has_sandbox_exec: bool,+ expected_substring: str,+ ) -> None:+ which_result = "/usr/bin/sandbox-exec" if has_sandbox_exec else None+ with (+ mock.patch.dict(os.environ, env),+ mock.patch.object(sys, "platform", platform),+ mock.patch.object(shutil, "which", return_value=which_result),+ ):+ if "POSTHOG_DEV_SANDBOX" not in env:+ os.environ.pop("POSTHOG_DEV_SANDBOX", None)+ shell = self._generate_with_intents(["feature_flags"])["info"]["shell"]+ assert "Sandbox:" in shell+ assert expected_substring in shell+def test_info_process_includes_process_count(self) -> None:"""Info process shell includes the active process count."""intent_map = create_test_intent_map()