: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): make filesystem sandbox opt-out by default (#64392)
Tom Piccirello3ca88b11d814
diff --git a/.env.local.example b/.env.local.exampleindex c1c19e9670b8..50cf410187e5 100644--- a/.env.local.example+++ b/.env.local.example@@ -28,10 +28,11 @@# 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+# macOS only: Python/Node dev services run under a Seatbelt sandbox by default so+# a malicious dependency can't read credentials (~/.ssh, ~/.aws, ...) outside the+# repo. See bin/dev-sandbox. No-op on Linux. Uncomment to disable; restart hogli+# start to apply.+# POSTHOG_DEV_SANDBOX=0# 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 dc6e81e1e971..ae72f6f06852 100755--- a/.flox/env/on-activate.sh+++ b/.flox/env/on-activate.sh@@ -302,15 +302,19 @@ _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.+# 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.+# 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=0if [[ "$(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+ _DEV_SANDBOX_INSTALLS=1+ if [[ "${POSTHOG_DEV_SANDBOX:-}" == "0" ]]; then+ _DEV_SANDBOX_INSTALLS=0+ elif [[ -z "${POSTHOG_DEV_SANDBOX:-}" ]] && grep -qE "^[[:space:]]*POSTHOG_DEV_SANDBOX=0[[:space:]]*$" "$FLOX_ENV_PROJECT/.env.local" 2>/dev/null; then+ _DEV_SANDBOX_INSTALLS=0fifidiff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex e5f48582a059..417995e27494 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -53,3 +53,6 @@ ee/api/scim/auth.py @PostHog/team-security# v1 data-modeling workflow is frozen during the v1 → v2 migration.# this will be removed from CODEOWNERS by June 1posthog/temporal/data_modeling/run_workflow.py @PostHog/team-data-modeling++# Dev sandbox provides important protection in local dev+bin/dev-sandbox* @PostHog/team-securitydiff --git a/bin/dev-sandbox b/bin/dev-sandboxindex 68eca87abee1..6c289d9f8897 100755--- a/bin/dev-sandbox+++ b/bin/dev-sandbox@@ -4,9 +4,9 @@# 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.+# argument and run via `bash -c`. On by default; opt out by setting+# POSTHOG_DEV_SANDBOX=0 in .env.local. The generator (hogli dev:generate) wraps+# Python/Node service commands with this script unless opted out.## The base profile denies all reads under $HOME. Because the repo lives under# $HOME, the OS / node module resolver / getcwd must still lstat+readdir thediff --git a/hogli.yaml b/hogli.yamlindex f4cedc7142dc..50f3be558237 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -1041,7 +1041,7 @@ environment:description: 'Expose local agent-ingress on a public cloudflared URL and wire AGENT_INGRESS_PUBLIC_URL into .env.local so Slack/webhooks can reach your dev box'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)'+ description: 'Run a command inside the dev filesystem sandbox (internal; used by hogli dev:generate by default unless POSTHOG_DEV_SANDBOX=0)'hidden: truedev:sandbox:selftest:bin_script: dev-sandbox-selftestdiff --git a/products/tasks/backend/services/docker_sandbox.py b/products/tasks/backend/services/docker_sandbox.pyindex 930fcbd342c2..3c3ac590bbeb 100644--- a/products/tasks/backend/services/docker_sandbox.py+++ b/products/tasks/backend/services/docker_sandbox.py@@ -103,10 +103,11 @@ class DockerSandbox(SandboxBase):Local dev requirements (set in .env.local, then restart ./bin/start so thesupervisor re-reads them — a per-process restart inherits the old env):- SANDBOX_PROVIDER=docker — route sandboxes here instead of Modal.- - POSTHOG_DEV_SANDBOX=0 — REQUIRED. The dev Seatbelt sandbox- (bin/dev-sandbox.sb) deliberately denies the Docker socket as an escape- vector, so with it enabled the worker can't reach the daemon and every- create() fails with a generic "Failed to create Docker sandbox".++ The dev Seatbelt sandbox (bin/dev-sandbox.sb, on by default) deliberately+ denies the Docker socket as an escape vector, so the temporal-worker — which+ needs that socket to create() containers — runs unsandboxed by default (see+ _SANDBOX_DEFAULT_EXCLUDES in the devenv generator). No extra config needed."""id: strdiff --git a/tools/hogli-commands/hogli_commands/devenv/generator.py b/tools/hogli-commands/hogli_commands/devenv/generator.pyindex 6b488d4f8cf2..58be94a3b6ee 100644--- a/tools/hogli-commands/hogli_commands/devenv/generator.py+++ b/tools/hogli-commands/hogli_commands/devenv/generator.py@@ -23,6 +23,11 @@ if TYPE_CHECKING:from .resolver import ResolvedEnvironment+def _dev_sandbox_enabled() -> bool:+ """Dev filesystem sandbox is on by default; opt out with POSTHOG_DEV_SANDBOX=0 (strict)."""+ return os.getenv("POSTHOG_DEV_SANDBOX") != "0"++class DevenvConfig(BaseModel):"""Source configuration for dev environment (what the user selected).@@ -229,18 +234,18 @@ class MprocsGenerator(ConfigGenerator):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"+ # Reflect the *effective* dependency-sandbox state: on by default (opt out+ # with POSTHOG_DEV_SANDBOX=0) 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_enabled = _dev_sandbox_enabled()sandbox_supported = sys.platform == "darwin" and shutil.which("sandbox-exec") is not None- if sandbox_opted_in and sandbox_supported:+ if sandbox_enabled 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}"+ elif sandbox_enabled:+ sandbox_status = f"{gray}off — unsupported on this platform{reset}"else:- sandbox_status = f"{gray}off{reset} {gray}(set POSTHOG_DEV_SANDBOX=1 in .env.local){reset}"+ sandbox_status = f"{gray}off{reset} {gray}(POSTHOG_DEV_SANDBOX=0; unset to re-enable){reset}"news_url = "https://raw.githubusercontent.com/posthog/posthog/master/devenv/news.txt"news_local = "devenv/news.txt"@@ -391,23 +396,29 @@ printf ' {gray}Run {reset}{blue}hogli dev:setup{reset}{gray} to tailor this to# code, so running them unsandboxed doesn't widen the untrusted attack surface._SANDBOX_DOCKER_GATES = ("bin/wait-for-docker", "bin/wait-for-postgres-tables")+ # Procs excluded from the sandbox by default: they need the docker socket the+ # profile denies (e.g. temporal-worker running PostHog Code tasks with+ # SANDBOX_PROVIDER=docker). POSTHOG_DEV_SANDBOX_EXCLUDE adds more on top.+ _SANDBOX_DEFAULT_EXCLUDES = frozenset({"temporal-worker"})+def _add_sandbox_wrapper(self, proc_config: dict[str, Any], name: str = "") -> 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.-- POSTHOG_DEV_SANDBOX_EXCLUDE (comma-separated proc names) opts individual- procs back out. Use sparingly — it exists for procs whose feature set- requires the docker socket the profile denies, e.g. temporal-worker running- PostHog Code tasks with SANDBOX_PROVIDER=docker. Excluded procs run fully- unsandboxed, so the dependency-isolation guarantee no longer covers them.+ """Wrap a service command in bin/dev-sandbox (macOS Seatbelt) by default.++ On by default; opt out globally with POSTHOG_DEV_SANDBOX=0 (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.++ Some procs are excluded by default (``_SANDBOX_DEFAULT_EXCLUDES``) because+ they need the docker socket the profile denies, e.g. temporal-worker running+ PostHog Code tasks with SANDBOX_PROVIDER=docker. POSTHOG_DEV_SANDBOX_EXCLUDE+ (comma-separated proc names) opts additional procs back out. Excluded procs+ run fully unsandboxed, so the dependency-isolation guarantee no longer covers+ them.The docker-gate preamble (bin/wait-for-docker) is peeled out to rununsandboxed, since it needs the very socket the sandbox denies; the actual@@ -417,8 +428,9 @@ printf ' {gray}Run {reset}{blue}hogli dev:setup{reset}{gray} to tailor this to# `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))- excluded = {p.strip() for p in os.getenv("POSTHOG_DEV_SANDBOX_EXCLUDE", "").split(",") if p.strip()}- if os.getenv("POSTHOG_DEV_SANDBOX") != "1" or not should_sandbox or (name and name in excluded):+ excluded = set(self._SANDBOX_DEFAULT_EXCLUDES)+ excluded |= {p.strip() for p in os.getenv("POSTHOG_DEV_SANDBOX_EXCLUDE", "").split(",") if p.strip()}+ if not _dev_sandbox_enabled() or not should_sandbox or (name and name in excluded):return proc_configshell = proc_config.get("shell", "")diff --git a/tools/hogli-commands/hogli_commands/tests/test_devenv.py b/tools/hogli-commands/hogli_commands/tests/test_devenv.pyindex dd56cd6acc1c..29d78ee808e5 100644--- a/tools/hogli-commands/hogli_commands/tests/test_devenv.py+++ b/tools/hogli-commands/hogli_commands/tests/test_devenv.py@@ -132,27 +132,27 @@ class TestSandboxWrapper: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:+ def test_wraps_by_default(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 result["shell"] == "bin/dev-sandbox ./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"+ def test_disabled_leaves_command_unwrapped(self, monkeypatch: Any) -> None:+ monkeypatch.setenv("POSTHOG_DEV_SANDBOX", "0")+ result = self._wrap({"shell": "./bin/start-backend", "sandbox": True})+ assert result["shell"] == "./bin/start-backend"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"+ def test_proc_without_sandbox_flag_not_wrapped(self, monkeypatch: Any) -> None:+ monkeypatch.delenv("POSTHOG_DEV_SANDBOX", raising=False)+ result = self._wrap({"shell": "cargo run --bin x"})+ assert result["shell"] == "cargo run --bin x"assert "sandbox" not in result- def test_excluded_proc_left_unwrapped(self, monkeypatch: Any) -> None:- monkeypatch.setenv("POSTHOG_DEV_SANDBOX", "1")- monkeypatch.setenv("POSTHOG_DEV_SANDBOX_EXCLUDE", "temporal-worker, other-proc")+ def test_temporal_worker_excluded_by_default(self, monkeypatch: Any) -> None:+ monkeypatch.delenv("POSTHOG_DEV_SANDBOX", raising=False)+ monkeypatch.delenv("POSTHOG_DEV_SANDBOX_EXCLUDE", raising=False)generator = MprocsGenerator(MockRegistry({}))excluded = generator._add_sandbox_wrapper({"shell": "./run-worker", "sandbox": True}, "temporal-worker")assert excluded["shell"] == "./run-worker"@@ -160,22 +160,33 @@ class TestSandboxWrapper:wrapped = generator._add_sandbox_wrapper({"shell": "./bin/start-backend", "sandbox": True}, "backend")assert wrapped["shell"] == "bin/dev-sandbox ./bin/start-backend"+ def test_excluded_proc_left_unwrapped(self, monkeypatch: Any) -> None:+ # POSTHOG_DEV_SANDBOX_EXCLUDE is additive on top of the default excludes.+ monkeypatch.delenv("POSTHOG_DEV_SANDBOX", raising=False)+ monkeypatch.setenv("POSTHOG_DEV_SANDBOX_EXCLUDE", "other-proc")+ generator = MprocsGenerator(MockRegistry({}))+ excluded = generator._add_sandbox_wrapper({"shell": "./run-other", "sandbox": True}, "other-proc")+ assert excluded["shell"] == "./run-other"+ assert "sandbox" not in excluded+ wrapped = generator._add_sandbox_wrapper({"shell": "./bin/start-backend", "sandbox": True}, "backend")+ assert wrapped["shell"] == "bin/dev-sandbox ./bin/start-backend"+def test_docker_gate_runs_outside_sandbox(self, monkeypatch: Any) -> None:- monkeypatch.setenv("POSTHOG_DEV_SANDBOX", "1")+ monkeypatch.delenv("POSTHOG_DEV_SANDBOX", raising=False)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")+ monkeypatch.delenv("POSTHOG_DEV_SANDBOX", raising=False)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")+ monkeypatch.delenv("POSTHOG_DEV_SANDBOX", raising=False)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"@@ -594,9 +605,10 @@ class TestInfoProcess:@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"),+ ("default_macos", {}, "darwin", True, r"\033[32mon"),+ ("explicit_enabled_macos", {"POSTHOG_DEV_SANDBOX": "1"}, "darwin", True, r"\033[32mon"),+ ("disabled_explicit", {"POSTHOG_DEV_SANDBOX": "0"}, "darwin", True, "POSTHOG_DEV_SANDBOX=0"),+ ("default_unsupported", {}, "linux", False, "unsupported"),])def test_info_process_shows_sandbox_status(