: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
feat(toolbox): check for the posthog.com tailnet and offer to switch (#117536)
Michi16a036b6a5f1
diff --git a/tools/infra-scripts/clitools/test_toolbox.py b/tools/infra-scripts/clitools/test_toolbox.pyindex 7c8c7a005e10..3789c6e73261 100644--- a/tools/infra-scripts/clitools/test_toolbox.py+++ b/tools/infra-scripts/clitools/test_toolbox.py@@ -917,12 +917,49 @@ class TestToolbox(unittest.TestCase):@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"})+ mock_run.return_value = self._tailscale_status_result(+ {"BackendState": "Running", "CurrentTailnet": {"Name": "posthog.com"}}+ )exit_code, output = self._run_tailscale_check()self.assertIsNone(exit_code)self.assertEqual(output, "")+ @patch("builtins.input", return_value="n")+ @patch("toolbox.tailscale.sys.stdin")+ @patch("toolbox.tailscale.subprocess.run")+ @patch("toolbox.tailscale.shutil.which", return_value="/usr/bin/tailscale")+ def test_ensure_tailscale_connected_exits_when_switch_declined(self, mock_which, mock_run, mock_stdin, mock_input):+ mock_stdin.isatty.return_value = True+ mock_run.return_value = self._tailscale_status_result(+ {"BackendState": "Running", "CurrentTailnet": {"Name": "[email protected]"}}+ )+ exit_code, output = self._run_tailscale_check()++ self.assertEqual(exit_code, 1)+ self.assertIn("'[email protected]' tailnet", output)+ self.assertIn("tailscale switch posthog.com", output)+ self.assertEqual(mock_run.call_count, 1)++ @patch("builtins.input", return_value="")+ @patch("toolbox.tailscale.sys.stdin")+ @patch("toolbox.tailscale.subprocess.run")+ @patch("toolbox.tailscale.shutil.which", return_value="/usr/bin/tailscale")+ def test_ensure_tailscale_connected_switches_tailnet_by_default(self, mock_which, mock_run, mock_stdin, mock_input):+ mock_stdin.isatty.return_value = True+ mock_run.side_effect = [+ self._tailscale_status_result(+ {"BackendState": "Running", "CurrentTailnet": {"Name": "[email protected]"}}+ ),+ MagicMock(returncode=0),+ self._tailscale_status_result({"BackendState": "Running", "CurrentTailnet": {"Name": "posthog.com"}}),+ ]+ exit_code, output = self._run_tailscale_check()++ self.assertIsNone(exit_code)+ self.assertEqual(mock_run.call_args_list[1].args[0], ["/usr/bin/tailscale", "switch", "posthog.com"])+ self.assertIn("Connected to the posthog.com tailnet", 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):diff --git a/tools/infra-scripts/clitools/toolbox.py b/tools/infra-scripts/clitools/toolbox.pyindex f2039745e6d5..23a44241594f 100755--- a/tools/infra-scripts/clitools/toolbox.py+++ b/tools/infra-scripts/clitools/toolbox.py@@ -288,7 +288,7 @@ def main():delete_pod(pod_name, namespace=namespace, context=selected_context)sys.exit(rc)except KeyboardInterrupt:- print("\n👋 Goodbye! \n \n Did something not work as expected? Ask in #team-infrastructure") # noqa: T201+ print("\n👋 Goodbye! \n \n Did something not work as expected? Ask in #support-infrastructure") # noqa: T201# POSIX convention: SIGINT exits 128 + signum (130). sys.exit(0) here# would mask Ctrl-C as a clean success to any wrapper checking $?, and# is inconsistent with the SIGTERM/SIGHUP handlers which already use 128 + signum.diff --git a/tools/infra-scripts/clitools/toolbox/tailscale.py b/tools/infra-scripts/clitools/toolbox/tailscale.pyindex 61b9eed82a83..ddadf1ca388b 100644--- a/tools/infra-scripts/clitools/toolbox/tailscale.py+++ b/tools/infra-scripts/clitools/toolbox/tailscale.py@@ -21,6 +21,7 @@ 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+POSTHOG_TAILNET = "posthog.com"# Health warning emitted by `tailscale status` when peers advertise subnet# routes but the local node has `--accept-routes` disabled. The cluster@@ -96,19 +97,95 @@ def warn_if_subnet_routes_rejected(status: dict[str, Any] | None) -> None:print(f" Fix it with: {fix}") # noqa: T201+def _current_tailnet(status: dict[str, Any] | None) -> str | None:+ return ((status or {}).get("CurrentTailnet") or {}).get("Name")+++def _confirm_switch(tailnet: str) -> bool:+ """Ask before switching tailnets, defaulting to yes; a non-TTY stdin never switches so automation does not block."""+ if not sys.stdin.isatty():+ return False+ try:+ response = input(f"❓ Tailscale is connected to the '{tailnet}' tailnet. Switch to {POSTHOG_TAILNET}? [Y/n]: ")+ except (EOFError, KeyboardInterrupt):+ return False+ return response.strip().lower() not in ("n", "no")+++def switch_to_posthog_tailnet() -> dict[str, Any] | None:+ """Run `tailscale switch` and return the new status, or None when the node is not on the PostHog tailnet after it.++ `tailscale switch` only selects an account that is already logged in on this+ device, so it fails when the user never logged into the PostHog tailnet here.+ """+ tailscale_path = resolve_tailscale()+ if not tailscale_path:+ return None+ try:+ result = subprocess.run(+ [tailscale_path, "switch", POSTHOG_TAILNET],+ env=_tailscale_env(tailscale_path),+ timeout=STATUS_TIMEOUT_SECONDS,+ )+ except (subprocess.TimeoutExpired, OSError):+ return None+ if result.returncode != 0:+ return None+ status = get_tailscale_status()+ if not status or status.get("BackendState") != "Running" or _current_tailnet(status) != POSTHOG_TAILNET:+ return None+ return status+++def ensure_posthog_tailnet(status: dict[str, Any]) -> dict[str, Any]:+ """Exit unless the node is on the PostHog tailnet, offering to switch first.++ Another tailnet (for example a personal one) still reports a running+ backend, but it has no routes to the cluster, so kubectl times out and the+ toolbox reports missing access instead. Older Tailscale clients do not+ report CurrentTailnet, so an absent name passes. Returns the status to use+ for the remaining checks, which is a fresh one after a switch.+ """+ tailnet = _current_tailnet(status)+ if not tailnet or tailnet == POSTHOG_TAILNET:+ return status++ if _confirm_switch(tailnet):+ print(f"🔄 Switching Tailscale to the {POSTHOG_TAILNET} tailnet...") # noqa: T201+ if switched_status := switch_to_posthog_tailnet():+ print(f"✅ Connected to the {POSTHOG_TAILNET} tailnet.") # noqa: T201+ return switched_status+ login = "tailscale login" if sys.platform == "darwin" else "sudo tailscale login"+ print(f"❌ Could not switch to the {POSTHOG_TAILNET} tailnet.") # noqa: T201+ print(f" If this device has never joined it, run `{login}` with your PostHog Google account.") # noqa: T201+ else:+ print( # noqa: T201+ f"❌ Tailscale is connected to the '{tailnet}' tailnet, but the toolbox needs the {POSTHOG_TAILNET} tailnet."+ )+ print( # noqa: T201+ f" Switch with: tailscale switch {POSTHOG_TAILNET} (or pick the {POSTHOG_TAILNET} account in the Tailscale app)."+ )+ 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)++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.+ Distinguishes not-installed from installed-but-not-running and from+ connected-to-another-tailnet (with an offer to switch), 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):returnstatus = get_tailscale_status()if status and status.get("BackendState") == "Running":+ status = ensure_posthog_tailnet(status)warn_if_subnet_routes_rejected(status)return