: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(toolbox): fail fast when tailscale is not connected (#80522)
Thomas Obermüller3ca3f96e35dc
diff --git a/tools/infra-scripts/clitools/README.md b/tools/infra-scripts/clitools/README.mdindex 6adfa5ab6ced..131676483d52 100644--- a/tools/infra-scripts/clitools/README.md+++ b/tools/infra-scripts/clitools/README.md@@ -24,6 +24,9 @@ The primary function is to help manage and connect to PostHog toolbox pods in a- kubectl installed and configured- the PostHog Python SDK (`pip install -r requirements.txt`) — telemetry is skipped gracefully if it's missing- a Fleet-managed kubeconfig with the standard PostHog contexts+- Tailscale installed and connected to the PostHog tailnet — the cluster endpoints are only reachable over it.+ The CLI checks this before doing anything else and tells you how to fix it.+ Set `TOOLBOX_SKIP_TAILSCALE_CHECK=1` to skip the check on hosts that reach the cluster some other way## Usagediff --git a/tools/infra-scripts/clitools/test_toolbox.py b/tools/infra-scripts/clitools/test_toolbox.pyindex a3dc00be24a3..e8aa782950fe 100644--- a/tools/infra-scripts/clitools/test_toolbox.py+++ b/tools/infra-scripts/clitools/test_toolbox.py@@ -1,9 +1,11 @@#!/usr/bin/env python3+import ioimport osimport jsonimport timeimport signal+import contextlibimport subprocessimport importlib.util@@ -25,6 +27,7 @@ from toolbox.kubernetes import (wait_for_context_access,)from toolbox.pod import ClaimRaceError, claim_pod, delete_pod, get_toolbox_pod+from toolbox.tailscale import SKIP_CHECK_ENV_VAR, TAILSCALE_RUNBOOK_URL, ensure_tailscale_connectedfrom toolbox.user import get_current_user, parse_arn, sanitize_label# Load toolbox.py (the script with main() and POOLS) by file path, since the@@ -36,6 +39,14 @@ _spec.loader.exec_module(toolbox_script)class TestToolbox(unittest.TestCase):+ def setUp(self):+ # main() checks Tailscale before anything else; the real check would+ # exit on hosts without a connected tailnet (CI), so neutralize it here+ # and exercise the real function via the toolbox.tailscale tests below.+ ensure_patcher = patch.object(toolbox_script, "ensure_tailscale_connected")+ self.m_ensure_tailscale = ensure_patcher.start()+ self.addCleanup(ensure_patcher.stop)+def test_kubectl_cmd_without_context(self):"""kubectl_cmd with context=None returns the same shape as a bare kubectl call."""self.assertEqual(kubectl_cmd("get", "pods"), ["kubectl", "get", "pods"])@@ -866,6 +877,93 @@ class TestToolbox(unittest.TestCase):diagnostic = "error: You must be logged in to the server (Unauthorized)"self.assertEqual(summarize_diagnostic(diagnostic), "Kubernetes rejected the cached AWS SSO credentials")+ def test_summarize_diagnostic_flags_unreachable_cluster(self):+ cases = [+ "E0810 memcache.go:265 Unable to connect to the server: dial tcp: lookup abc.eks.amazonaws.com: no such host",+ "Unable to connect to the server: dial tcp 10.1.2.3:443: i/o timeout",+ "Unable to connect to the server: connect: no route to host",+ ]+ for diagnostic in cases:+ with self.subTest(diagnostic=diagnostic):+ self.assertEqual(+ summarize_diagnostic(diagnostic),+ "cannot reach the cluster endpoint (check that Tailscale is connected)",+ )++ def test_summarize_diagnostic_keeps_credential_plugin_transport_errors(self):+ aws_error = 'Could not connect to the endpoint URL: "https://portal.sso.us-east-1.amazonaws.com/token": connection refused'+ diagnostic = (+ "Unable to connect to the server: getting credentials: exec: executable aws failed with exit code 255\n"+ + aws_error+ )+ self.assertEqual(summarize_diagnostic(diagnostic), aws_error)++ def _tailscale_status_result(self, payload):+ return MagicMock(returncode=0, stdout=json.dumps(payload))++ def _run_tailscale_check(self):+ """Run the preflight with the skip var unset; return (exit_code or None, stdout)."""+ exit_code = None+ output = io.StringIO()+ with patch.dict(os.environ, {}, clear=False):+ os.environ.pop(SKIP_CHECK_ENV_VAR, None)+ with contextlib.redirect_stdout(output):+ try:+ ensure_tailscale_connected()+ except SystemExit as exc:+ exit_code = exc.code+ return exit_code, output.getvalue()++ @patch("toolbox.tailscale.subprocess.run")+ @patch("toolbox.tailscale.shutil.which", return_value="/usr/bin/tailscale")+ def test_ensure_tailscale_connected_passes_silently_when_running(self, mock_which, mock_run):+ mock_run.return_value = self._tailscale_status_result({"BackendState": "Running"})+ exit_code, output = self._run_tailscale_check()++ self.assertIsNone(exit_code)+ self.assertEqual(output, "")++ @patch("toolbox.tailscale.os.path.isfile", return_value=False)+ @patch("toolbox.tailscale.shutil.which", return_value=None)+ def test_ensure_tailscale_connected_exits_when_not_installed(self, mock_which, mock_isfile):+ exit_code, output = self._run_tailscale_check()++ self.assertEqual(exit_code, 1)+ self.assertIn("Tailscale is not installed", output)+ self.assertIn(TAILSCALE_RUNBOOK_URL, output)++ @patch("toolbox.tailscale.os.path.isfile", return_value=False)+ @patch("toolbox.tailscale.subprocess.run")+ @patch("toolbox.tailscale.shutil.which", return_value="/usr/bin/tailscale")+ def test_ensure_tailscale_connected_exits_when_not_running(self, mock_which, mock_run, mock_isfile):+ mock_run.return_value = self._tailscale_status_result({"BackendState": "Stopped"})+ exit_code, output = self._run_tailscale_check()++ self.assertEqual(exit_code, 1)+ self.assertIn("Tailscale is not connected", output)+ self.assertIn(TAILSCALE_RUNBOOK_URL, output)++ @patch("toolbox.tailscale.subprocess.run")+ @patch("toolbox.tailscale.shutil.which", return_value="/usr/bin/tailscale")+ def test_ensure_tailscale_connected_warns_when_subnet_routes_rejected(self, mock_which, mock_run):+ mock_run.return_value = self._tailscale_status_result(+ {+ "BackendState": "Running",+ "Health": ["some peers are advertising routes but --accept-routes is false"],+ }+ )+ exit_code, output = self._run_tailscale_check()++ self.assertIsNone(exit_code)+ self.assertIn("not accepting subnet routes", output)+ self.assertIn("--accept-routes", output)++ @patch("toolbox.tailscale.shutil.which")+ def test_ensure_tailscale_connected_skipped_via_env_var(self, mock_which):+ with patch.dict(os.environ, {SKIP_CHECK_ENV_VAR: "1"}, clear=False):+ ensure_tailscale_connected()+ mock_which.assert_not_called()+@patch("toolbox.kubernetes.login_to_sso", return_value=True)@patch("toolbox.kubernetes.time.monotonic", return_value=10)@patch("subprocess.run")@@ -1361,6 +1459,31 @@ class TestToolbox(unittest.TestCase):m_validate.assert_not_called()self.assertEqual(m_get_pod.call_args.kwargs["context"], "posthog-dev")+ def test_main_checks_tailscale_before_selecting_context(self):+ patches = self._patch_main_collaborators()+ parent = MagicMock()++ with (+ patches["get_current_user"],+ patches["get_toolbox_pod"],+ patches["claim_pod"],+ patches["connect_to_pod"],+ patches["delete_pod"],+ patches["select_context"] as m_select,+ patches["validate_context"],+ patch.object(toolbox_script.sys, "argv", ["toolbox.py"]),+ patch.dict(os.environ, {}, clear=False),+ ):+ self._clean_env()+ parent.attach_mock(self.m_ensure_tailscale, "ensure_tailscale")+ parent.attach_mock(m_select, "select_context")+ with self.assertRaises(SystemExit):+ toolbox_script.main()++ call_names = [name for name, _, _ in parent.mock_calls]+ self.assertIn("ensure_tailscale", call_names)+ self.assertLess(call_names.index("ensure_tailscale"), call_names.index("select_context"))+def test_main_kube_context_validate_failure_exits(self):"""When validate_context returns False, main() exits with status 1."""patches = self._patch_main_collaborators()diff --git a/tools/infra-scripts/clitools/toolbox.py b/tools/infra-scripts/clitools/toolbox.pyindex 09a91460dc46..8de103f7dcbb 100755--- a/tools/infra-scripts/clitools/toolbox.py+++ b/tools/infra-scripts/clitools/toolbox.py@@ -16,6 +16,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))# Import functions from the modular packagefrom toolbox.kubernetes import ensure_context_access, select_context, validate_contextfrom toolbox.pod import ClaimRaceError, claim_pod, connect_to_pod, delete_pod, get_toolbox_pod+from toolbox.tailscale import ensure_tailscale_connectedfrom toolbox.telemetry import capture_invocation, prompt_for_reasonfrom toolbox.user import get_current_user@@ -95,6 +96,10 @@ def main():)args = parser.parse_args()+ # The cluster endpoints are only reachable over the tailnet; without this+ # check a disconnected Tailscale surfaces as opaque kubectl timeouts.+ ensure_tailscale_connected()+# Ask up front (before the kubectl waits) what this session is for; skipped# automatically on non-interactive stdin so automation never blocks.usage_reason = prompt_for_reason()diff --git a/tools/infra-scripts/clitools/toolbox/kubernetes.py b/tools/infra-scripts/clitools/toolbox/kubernetes.pyindex 74961eff6986..22d85fb69d25 100644--- a/tools/infra-scripts/clitools/toolbox/kubernetes.py+++ b/tools/infra-scripts/clitools/toolbox/kubernetes.py@@ -103,7 +103,7 @@ def check_context_access(context: str, _namespace: str) -> tuple[bool, str]:except FileNotFoundError:return False, "kubectl is not installed or is not on PATH"except subprocess.TimeoutExpired:- return False, "kubectl authentication check timed out"+ return False, "kubectl authentication check timed out (check that Tailscale is connected)"diagnostic = "\n".join(part for part in (result.stdout.strip(), result.stderr.strip()) if part)if result.returncode == 0:@@ -167,6 +167,36 @@ def _needs_sso_reset(diagnostic: str) -> bool:)+# Transport-level fragments in kubectl output. They only count as cluster+# unreachability (which for the tailnet-gated clusters almost always means+# Tailscale is down) on lines about the API server connection; the same+# fragments coming from the AWS credential exec plugin must keep their own+# diagnostic instead of a misleading Tailscale hint.+_NETWORK_FAILURE_MARKERS = (+ "no such host",+ "no route to host",+ "i/o timeout",+ "network is unreachable",+ "connection refused",+ "dial tcp",+ "tls handshake timeout",+)+# kubectl's own dialer produces these; the AWS CLI phrases its errors differently.+_CLUSTER_CONNECTION_CONTEXTS = ("unable to connect to the server", "dial tcp")+_CREDENTIAL_PLUGIN_FRAGMENTS = ("getting credentials", "executable aws")+++def _looks_like_network_failure(diagnostic: str) -> bool:+ for line in diagnostic.lower().splitlines():+ if any(fragment in line for fragment in _CREDENTIAL_PLUGIN_FRAGMENTS):+ continue+ if not any(marker in line for marker in _NETWORK_FAILURE_MARKERS):+ continue+ if any(context in line for context in _CLUSTER_CONNECTION_CONTEXTS):+ return True+ return False++def summarize_diagnostic(diagnostic: str) -> str:"""Extract a concise, useful reason from noisy kubectl/AWS output."""lines = [line.strip() for line in diagnostic.splitlines() if line.strip()]@@ -175,6 +205,8 @@ def summarize_diagnostic(diagnostic: str) -> str:return "AWS reports that this profile currently has no access"if _needs_sso_reset(line):return "Kubernetes rejected the cached AWS SSO credentials"+ if _looks_like_network_failure(diagnostic):+ return "cannot reach the cluster endpoint (check that Tailscale is connected)"for line in reversed(lines):if not line.startswith(("E", "Unable to connect to the server")):return linediff --git a/tools/infra-scripts/clitools/toolbox/tailscale.py b/tools/infra-scripts/clitools/toolbox/tailscale.pynew file mode 100644index 000000000000..61b9eed82a83--- /dev/null+++ b/tools/infra-scripts/clitools/toolbox/tailscale.py@@ -0,0 +1,129 @@+#!/usr/bin/env python3+"""Tailscale connectivity preflight for the toolbox CLI.++The toolbox-capable Kubernetes API endpoints are only reachable over the+PostHog tailnet, so a disconnected Tailscale surfaces as opaque kubectl+timeouts. Checking up front turns that into an actionable message.++Adapted from hogli's devbox preflight (hogli_commands/devbox/coder.py); this+script is standalone and stdlib-only, so it cannot import that package.+"""++import os+import sys+import json+import shutil+import subprocess+from typing import Any++# macOS ships the CLI inside the app bundle, so it is often not on PATH.+MACOS_TAILSCALE_CLI = "/Applications/Tailscale.app/Contents/MacOS/Tailscale"+TAILSCALE_RUNBOOK_URL = "https://runbooks.posthog.com/vpn/#tailscale"+SKIP_CHECK_ENV_VAR = "TOOLBOX_SKIP_TAILSCALE_CHECK"+STATUS_TIMEOUT_SECONDS = 10++# Health warning emitted by `tailscale status` when peers advertise subnet+# routes but the local node has `--accept-routes` disabled. The cluster+# endpoints sit behind subnet routers, so DNS resolves but traffic blackholes.+ACCEPT_ROUTES_HEALTH_FRAGMENT = "--accept-routes is false"+++def resolve_tailscale() -> str | None:+ """Return the path to the tailscale CLI, checking PATH then the macOS app bundle."""+ if path := shutil.which("tailscale"):+ return path+ if sys.platform == "darwin" and os.path.isfile(MACOS_TAILSCALE_CLI):+ return MACOS_TAILSCALE_CLI+ return None+++def _tailscale_env(tailscale_path: str) -> dict[str, str] | None:+ """Return extra env vars needed when invoking the macOS app bundle CLI."""+ if tailscale_path == MACOS_TAILSCALE_CLI:+ return {**os.environ, "TAILSCALE_BE_CLI": "1"}+ return None+++def get_tailscale_status() -> dict[str, Any] | None:+ """Return parsed `tailscale status --json` output, or None when unavailable."""+ tailscale_path = resolve_tailscale()+ if not tailscale_path:+ return None+ try:+ result = subprocess.run(+ [tailscale_path, "status", "--json"],+ capture_output=True,+ text=True,+ env=_tailscale_env(tailscale_path),+ timeout=STATUS_TIMEOUT_SECONDS,+ )+ except (subprocess.TimeoutExpired, OSError):+ return None+ if result.returncode != 0:+ return None+ try:+ return json.loads(result.stdout)+ except json.JSONDecodeError:+ return None+++def _install_hint() -> str:+ if sys.platform == "darwin":+ return "Install it: brew install --cask tailscale (or via the Mac App Store)."+ if sys.platform.startswith("linux"):+ return "Install it: curl -fsSL https://tailscale.com/install.sh | sh"+ return "Install it from https://tailscale.com/download."+++def _connect_hint() -> str:+ if sys.platform == "darwin":+ return "Open the Tailscale app and sign in with your PostHog Google account."+ return "Run `sudo tailscale up` and complete the SSO flow with your PostHog Google account."+++def _cli_missing_on_macos() -> bool:+ """Return whether macOS has the Tailscale app but no CLI on PATH."""+ return sys.platform == "darwin" and shutil.which("tailscale") is None and os.path.isfile(MACOS_TAILSCALE_CLI)+++def warn_if_subnet_routes_rejected(status: dict[str, Any] | None) -> None:+ """Warn when the node rejects advertised subnet routes; cluster traffic needs them."""+ health = (status or {}).get("Health") or []+ if not any(ACCEPT_ROUTES_HEALTH_FRAGMENT in (message or "") for message in health):+ return+ fix = "tailscale set --accept-routes" if sys.platform == "darwin" else "sudo tailscale set --accept-routes"+ print("⚠️ Tailscale is not accepting subnet routes, so the cluster may be unreachable.") # noqa: T201+ print(f" Fix it with: {fix}") # noqa: T201+++def ensure_tailscale_connected() -> None:+ """Exit with guidance when the host is not connected to the PostHog tailnet.++ Distinguishes not-installed from installed-but-not-running, with the fix+ for each, plus a symlink hint on macOS when the CLI only exists inside the+ app bundle. Set TOOLBOX_SKIP_TAILSCALE_CHECK=1 to skip the check entirely,+ for hosts that reach the cluster some other way.+ """+ if os.environ.get(SKIP_CHECK_ENV_VAR):+ return++ status = get_tailscale_status()+ if status and status.get("BackendState") == "Running":+ warn_if_subnet_routes_rejected(status)+ return++ if not resolve_tailscale():+ print("❌ Tailscale is not installed, and the toolbox needs the PostHog tailnet to reach the cluster.") # noqa: T201+ print(f" {_install_hint()}") # noqa: T201+ print(f" See {TAILSCALE_RUNBOOK_URL} for joining the PostHog tailnet, then rerun the toolbox.") # noqa: T201+ print(f" Connected through something else? Set {SKIP_CHECK_ENV_VAR}=1 to skip this check.") # noqa: T201+ sys.exit(1)++ print("❌ Tailscale is not connected, and the toolbox needs the PostHog tailnet to reach the cluster.") # noqa: T201+ print(f" {_connect_hint()}") # noqa: T201+ if _cli_missing_on_macos():+ print(" To use the tailscale CLI from your shell, symlink it once:") # noqa: T201+ print(f" sudo ln -sfn {MACOS_TAILSCALE_CLI} /usr/local/bin/tailscale") # noqa: T201+ print(f" See {TAILSCALE_RUNBOOK_URL} if you have not yet joined the PostHog tailnet, then rerun the toolbox.") # noqa: T201+ print(f" Connected through something else? Set {SKIP_CHECK_ENV_VAR}=1 to skip this check.") # noqa: T201+ sys.exit(1)