: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(infra): guide toolbox access setup (#76630)
Sven Lange84ef89865ba0
diff --git a/tools/infra-scripts/clitools/README.md b/tools/infra-scripts/clitools/README.mdindex 0f686e942975..6adfa5ab6ced 100644--- a/tools/infra-scripts/clitools/README.md+++ b/tools/infra-scripts/clitools/README.md@@ -23,7 +23,7 @@ The primary function is to help manage and connect to PostHog toolbox pods in a- Python 3.x- kubectl installed and configured- the PostHog Python SDK (`pip install -r requirements.txt`) — telemetry is skipped gracefully if it's missing-- your current settings and k8s context let you access the cluster that you want your toolbox to be claimed in+- a Fleet-managed kubeconfig with the standard PostHog contexts## Usage@@ -43,11 +43,14 @@ Or directly (Unix-based systems):The toolbox CLI:-1. Authenticates your AWS identity-2. Finds an available PostHog toolbox pod or connects to one you've already claimed-3. Claims the pod for a specified duration (default 12 hours)-4. Provides an interactive shell session to the pod-5. Offers to delete the pod when you exit the shell+1. Asks whether you need `dev`, `prod-eu`, or `prod-us`+2. Selects the least-privileged usable `-eks`, `-write`, or `-admin` context+3. Guides you through requesting `k8s + toolbox access` in `#aws-access` when needed,+ waits up to 10 minutes for approval, and continues automatically+4. Finds an available PostHog toolbox pod or connects to one you've already claimed+5. Claims the pod for a specified duration (default 12 hours)+6. Provides an interactive shell session to the pod+7. Offers to delete the pod when you exit the shell### Available Flags@@ -56,6 +59,9 @@ The toolbox CLI:| `--claim-duration HOURS` | Number of hours to claim the pod for | 12 || `--update-claim` | Update the termination time of your existing pod | False |+Set `KUBE_CONTEXT` to bypass environment selection for expert workflows. The context is scoped to this process and+must have the pod permissions required by the toolbox; the CLI never changes your global current context.+### Examples1. Connect to a pod with default 12-hour claim:@@ -80,4 +86,8 @@ python toolbox.py --update-claim --claim-duration 24- If no pods are available, the script will wait up to 5 minutes for a pod to become available- When you exit the pod shell, you'll be prompted whether to delete the pod+- If access is not approved within 10 minutes, the script exits with the profile-specific login command to use+ before retrying+- If Kubernetes rejects stale cached credentials after access is renewed, the script first logs in again with the+ selected profile. If Kubernetes still rejects it, the script resets AWS SSO, logs in again, and continues- If something doesn't work as expected, reach out to #team-infrastructure for assistancediff --git a/tools/infra-scripts/clitools/test_toolbox.py b/tools/infra-scripts/clitools/test_toolbox.pyindex 424386371d83..a3dc00be24a3 100644--- a/tools/infra-scripts/clitools/test_toolbox.py+++ b/tools/infra-scripts/clitools/test_toolbox.py@@ -11,12 +11,18 @@ import unittestfrom unittest.mock import MagicMock, patchfrom toolbox.kubernetes import (+ check_context_access,get_available_contexts,+ get_context_profile,get_current_context,kubectl_cmd,+ reset_sso,select_context,+ select_environment,+ summarize_diagnostic,switch_context,validate_context,+ wait_for_context_access,)from toolbox.pod import ClaimRaceError, claim_pod, delete_pod, get_toolbox_podfrom toolbox.user import get_current_user, parse_arn, sanitize_label@@ -700,7 +706,11 @@ class TestToolbox(unittest.TestCase):self.assertEqual(contexts, ["context1", "context2", "context3"])mock_run.assert_called_once_with(- ["kubectl", "config", "get-contexts", "-o", "name"], capture_output=True, text=True, check=True+ ["kubectl", "config", "get-contexts", "-o", "name"],+ capture_output=True,+ text=True,+ check=True,+ timeout=15,)@patch("subprocess.run")@@ -736,7 +746,11 @@ class TestToolbox(unittest.TestCase):self.assertEqual(context, "current-context")mock_run.assert_called_once_with(- ["kubectl", "config", "current-context"], capture_output=True, text=True, check=True+ ["kubectl", "config", "current-context"],+ capture_output=True,+ text=True,+ check=True,+ timeout=15,)@patch("subprocess.run")@@ -781,48 +795,94 @@ class TestToolbox(unittest.TestCase):mock_get.return_value = ["posthog-dev", "posthog-prod"]self.assertFalse(validate_context("posthog-bogus"))- @patch("toolbox.kubernetes.get_available_contexts")- @patch("toolbox.kubernetes.get_current_context")@patch("builtins.input")- def test_select_context(self, mock_input, mock_get_current, mock_get_available):- """Test selecting kubernetes context."""- # Setup mocks- mock_get_available.return_value = ["context1", "context2", "context3"]- mock_get_current.return_value = "context1"- mock_input.return_value = "" # User just presses Enter to use current context-- # Call function- result = select_context()-- # Verify result- self.assertEqual(result, "context1")- mock_get_available.assert_called_once()- mock_get_current.assert_called_once()- mock_input.assert_called_once()+ def test_select_environment_only_offers_toolbox_environments(self, mock_input):+ mock_input.side_effect = ["40", "0", "-1", "2"]+ self.assertEqual(select_environment(), "prod-eu")+ self.assertEqual(mock_input.call_count, 4)+ @patch("toolbox.kubernetes.check_context_access")@patch("toolbox.kubernetes.get_available_contexts")- @patch("toolbox.kubernetes.get_current_context")- @patch("builtins.input")- def test_select_context_picks_index_without_switching(self, mock_input, mock_get_current, mock_get_available):- """Picking a context returns the chosen name without calling kubectl config use-context."""- mock_get_available.return_value = ["context1", "context2", "context3"]- mock_get_current.return_value = "context1"- mock_input.return_value = "2"+ @patch("toolbox.kubernetes.select_environment", return_value="dev")+ def test_select_context_uses_least_privileged_working_context(self, mock_environment, mock_get, mock_access):+ mock_get.return_value = ["unrelated", "dev-eks", "dev-write", "dev-admin"]+ mock_access.side_effect = [(False, "no"), (True, "")]++ self.assertEqual(select_context("posthog"), "dev-write")+ self.assertEqual(+ mock_access.call_args_list,+ [unittest.mock.call("dev-eks", "posthog"), unittest.mock.call("dev-write", "posthog")],+ )++ @patch("subprocess.run")+ def test_check_context_access_uses_kubernetes_identity(self, mock_run):+ mock_run.return_value = MagicMock(returncode=0, stdout='{"status": {}}\n', stderr="")+ self.assertEqual(check_context_access("dev-eks", "posthog"), (True, ""))+ mock_run.assert_called_once_with(+ ["kubectl", "--context=dev-eks", "auth", "whoami", "-o", "json"],+ capture_output=True,+ text=True,+ check=False,+ timeout=15,+ )- with patch("toolbox.kubernetes.switch_context") as mock_switch:- result = select_context()+ @patch("subprocess.run")+ def test_get_context_profile_reads_local_kubeconfig(self, mock_run):+ mock_run.return_value = MagicMock(+ stdout=json.dumps(+ {+ "contexts": [{"name": "dev-eks", "context": {"user": "dev-eks-user"}}],+ "users": [+ {+ "name": "dev-eks-user",+ "user": {"exec": {"env": [{"name": "AWS_PROFILE", "value": "dev-eks"}]}},+ }+ ],+ }+ )+ )+ self.assertEqual(get_context_profile("dev-eks"), "dev-eks")++ @patch("toolbox.kubernetes.check_context_access", return_value=(True, ""))+ @patch("toolbox.kubernetes.get_context_profile", return_value="dev-eks")+ @patch("toolbox.kubernetes.time.monotonic", side_effect=[0, 1])+ def test_wait_for_context_access_continues_when_grant_appears(self, mock_time, mock_profile, mock_access):+ self.assertTrue(wait_for_context_access("dev-eks", "posthog"))+ mock_access.assert_called_once_with("dev-eks", "posthog")++ @patch("toolbox.kubernetes.login_to_sso", return_value=False)+ @patch("toolbox.kubernetes.get_context_profile", return_value="dev-eks")+ def test_wait_for_context_access_stops_when_required_sso_login_fails(self, mock_profile, mock_login):+ self.assertFalse(+ wait_for_context_access("dev-eks", "posthog", initial_diagnostic="Token has expired and refresh failed")+ )+ mock_login.assert_called_once_with("dev-eks", timeout=unittest.mock.ANY)- self.assertEqual(result, "context2")- mock_switch.assert_not_called()+ def test_summarize_diagnostic_surfaces_aws_no_access(self):+ diagnostic = "aws: [ERROR]: ForbiddenException when calling GetRoleCredentials: No access\nUnable to connect"+ self.assertEqual(summarize_diagnostic(diagnostic), "AWS reports that this profile currently has no access")- @patch("toolbox.kubernetes.get_available_contexts")- @patch("toolbox.kubernetes.get_current_context")- def test_select_context_current_none(self, mock_get_current, mock_get_available):- """Test select_context exits if current context is None."""- mock_get_available.return_value = ["context1", "context2"]- mock_get_current.return_value = None- with self.assertRaises(SystemExit):- select_context()+ def test_summarize_diagnostic_recognizes_whoami_unauthorized(self):+ diagnostic = "error: You must be logged in to the server (Unauthorized)"+ self.assertEqual(summarize_diagnostic(diagnostic), "Kubernetes rejected the cached AWS SSO credentials")++ @patch("toolbox.kubernetes.login_to_sso", return_value=True)+ @patch("toolbox.kubernetes.time.monotonic", return_value=10)+ @patch("subprocess.run")+ def test_reset_sso_logs_out_before_logging_back_in(self, mock_run, mock_time, mock_login):+ mock_run.return_value = MagicMock(returncode=0)+ self.assertTrue(reset_sso("prod-eu-eks", deadline=610))+ mock_run.assert_called_once_with(["aws", "sso", "logout"], check=False, timeout=600)+ mock_login.assert_called_once_with("prod-eu-eks", timeout=600)++ @patch("toolbox.kubernetes.login_to_sso", return_value=True)+ @patch("toolbox.kubernetes.check_context_access", return_value=(True, ""))+ @patch("toolbox.kubernetes.get_context_profile", return_value="prod-eu-eks")+ @patch("toolbox.kubernetes.time.monotonic", side_effect=[0, 1, 2])+ def test_wait_refreshes_rejected_cached_credentials(self, mock_time, mock_profile, mock_access, mock_login):+ diagnostic = "error: You must be logged in to the server (Unauthorized)"+ self.assertTrue(wait_for_context_access("prod-eu-eks", "posthog", initial_diagnostic=diagnostic))+ mock_login.assert_called_once_with("prod-eu-eks", timeout=599)@patch("subprocess.run")def test_claim_pod_wait_timeout(self, mock_run):@@ -1263,6 +1323,7 @@ class TestToolbox(unittest.TestCase):patches["delete_pod"],patches["select_context"] as m_select,patches["validate_context"] as m_validate,+ patch.object(toolbox_script, "ensure_context_access", return_value=True) as m_access,patch.object(toolbox_script.sys, "argv", ["toolbox.py"]),patch.dict(os.environ, {"KUBE_CONTEXT": "posthog-dev"}, clear=False),):@@ -1272,6 +1333,7 @@ class TestToolbox(unittest.TestCase):toolbox_script.main()m_validate.assert_called_once_with("posthog-dev")+ m_access.assert_called_once_with("posthog-dev", "posthog-toolbox-django")m_select.assert_not_called()# And the resolved context is threaded into get_toolbox_pod.self.assertEqual(m_get_pod.call_args.kwargs["context"], "posthog-dev")@@ -1295,7 +1357,7 @@ class TestToolbox(unittest.TestCase):with self.assertRaises(SystemExit):toolbox_script.main()- m_select.assert_called_once_with()+ m_select.assert_called_once_with("posthog-toolbox-django")m_validate.assert_not_called()self.assertEqual(m_get_pod.call_args.kwargs["context"], "posthog-dev")diff --git a/tools/infra-scripts/clitools/toolbox.py b/tools/infra-scripts/clitools/toolbox.pyindex ed1d472e6fa0..09a91460dc46 100755--- a/tools/infra-scripts/clitools/toolbox.py+++ b/tools/infra-scripts/clitools/toolbox.py@@ -14,7 +14,7 @@ from datetime import datetime, timedeltasys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))# Import functions from the modular package-from toolbox.kubernetes import select_context, validate_context+from toolbox.kubernetes import ensure_context_access, select_context, validate_contextfrom toolbox.pod import ClaimRaceError, claim_pod, connect_to_pod, delete_pod, get_toolbox_podfrom toolbox.telemetry import capture_invocation, prompt_for_reasonfrom toolbox.user import get_current_user@@ -122,9 +122,11 @@ def main():if not validate_context(kube_context):print(f"❌ KUBE_CONTEXT='{kube_context}' is not a known kubernetes context.") # noqa: T201sys.exit(1)+ if not ensure_context_access(kube_context, namespace):+ sys.exit(1)selected_context = kube_contextelse:- selected_context = select_context()+ selected_context = select_context(namespace)print(f"🔄 Using kubernetes context: {selected_context}") # noqa: T201# Get current user labelsdiff --git a/tools/infra-scripts/clitools/toolbox/kubernetes.py b/tools/infra-scripts/clitools/toolbox/kubernetes.pyindex d7e2ca1737ed..74961eff6986 100644--- a/tools/infra-scripts/clitools/toolbox/kubernetes.py+++ b/tools/infra-scripts/clitools/toolbox/kubernetes.py@@ -1,19 +1,21 @@#!/usr/bin/env python3-"""Kubernetes context management functions."""+"""Kubernetes context discovery and access management for the toolbox CLI."""import sys+import json+import timeimport subprocess+TOOLBOX_ENVIRONMENTS = ("dev", "prod-eu", "prod-us")+ACCESS_SUFFIXES = ("eks", "write", "admin")+ACCESS_WAIT_SECONDS = 10 * 60+ACCESS_POLL_SECONDS = 5+COMMAND_TIMEOUT_SECONDS = 15+AWS_ACCESS_CHANNEL = "https://posthog.slack.com/archives/C09ULM0E6SW"+def kubectl_cmd(*args: str, context: str | None = None) -> list[str]:- """Build a kubectl command with --context if `context` is set.-- Threading the context through every kubectl invocation lets us scope all- operations to one cluster without ever mutating the user's global kubeconfig- via `kubectl config use-context`. That matters because a wrapper that- silently flips the default context can redirect later operational commands- (kubectl delete, helm upgrade, …) to the wrong cluster.- """+ """Build a kubectl command scoped to a context without changing kubeconfig."""cmd = ["kubectl"]if context:cmd.append(f"--context={context}")@@ -21,92 +23,309 @@ def kubectl_cmd(*args: str, context: str | None = None) -> list[str]:return cmd-def get_available_contexts() -> list:- """Get available kubernetes contexts."""+def get_available_contexts() -> list[str]:+ """Return the context names in the user's active kubeconfig."""try:result = subprocess.run(- ["kubectl", "config", "get-contexts", "-o", "name"], capture_output=True, text=True, check=True+ ["kubectl", "config", "get-contexts", "-o", "name"],+ capture_output=True,+ text=True,+ check=True,+ timeout=COMMAND_TIMEOUT_SECONDS,)- contexts = [context.strip() for context in result.stdout.strip().split("\n") if context.strip()]- return contexts- except subprocess.CalledProcessError as e:- print(f"Error getting kubernetes contexts: {e}") # noqa: T201+ except FileNotFoundError:+ print("❌ kubectl is not installed or is not on PATH.") # noqa: T201+ sys.exit(1)+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:+ print(f"❌ Could not read kubernetes contexts: {error}") # noqa: T201sys.exit(1)+ return [context.strip() for context in result.stdout.splitlines() if context.strip()]def get_current_context() -> str | None:- """Get current kubernetes context."""+ """Return the current context, retained for backwards-compatible callers."""try:- result = subprocess.run(["kubectl", "config", "current-context"], capture_output=True, text=True, check=True)+ result = subprocess.run(+ ["kubectl", "config", "current-context"],+ capture_output=True,+ text=True,+ check=True,+ timeout=COMMAND_TIMEOUT_SECONDS,+ )return result.stdout.strip()- except subprocess.CalledProcessError as e:- print(f"Error getting current kubernetes context: {e}") # noqa: T201+ except (FileNotFoundError, subprocess.CalledProcessError, subprocess.TimeoutExpired):return Nonedef switch_context(context: str) -> bool:- """Switch to specified kubernetes context.-- Mutates kubeconfig globally. Prefer ``validate_context`` plus passing- ``--context`` per invocation via ``kubectl_cmd``; this function is kept- for callers that explicitly want a persistent switch.- """+ """Persistently switch context for legacy callers; the toolbox never uses this."""try:subprocess.run(["kubectl", "config", "use-context", context], check=True)print(f"✅ Switched to context: {context}") # noqa: T201return True- except subprocess.CalledProcessError as e:- print(f"Error switching kubernetes context: {e}") # noqa: T201+ except subprocess.CalledProcessError as error:+ print(f"Error switching kubernetes context: {error}") # noqa: T201return Falsedef validate_context(context: str) -> bool:- """Return True if ``context`` is a known kubernetes context.-- Use this when you want to scope a single invocation to a context without- mutating kubeconfig via ``switch_context``.- """+ """Return whether a context exists in the active kubeconfig."""return context in get_available_contexts()-def select_context() -> str:- """List available contexts and let the user pick one. Returns the chosen name.+def select_environment() -> str:+ """Prompt for one of the environments that actually hosts toolbox pools."""+ print("\n🌍 Choose an environment:") # noqa: T201+ for index, environment in enumerate(TOOLBOX_ENVIRONMENTS, 1):+ print(f" {index}. {environment}") # noqa: T201- Does **not** call ``kubectl config use-context``; the caller is expected to- pass the returned name as ``--context`` to subsequent kubectl invocations- via ``kubectl_cmd``. Pressing Enter keeps the current context.- """- contexts = get_available_contexts()- current = get_current_context()- if current is None:- print("❌ Could not determine current kubernetes context.") # noqa: T201- sys.exit(1)+ while True:+ response = input("Environment number: ").strip()+ try:+ choice = int(response)+ if 1 <= choice <= len(TOOLBOX_ENVIRONMENTS):+ return TOOLBOX_ENVIRONMENTS[choice - 1]+ except ValueError:+ pass+ print(f"⚠️ Please enter a number from 1 to {len(TOOLBOX_ENVIRONMENTS)}.") # noqa: T201- if not contexts:- print("❌ No kubernetes contexts found.") # noqa: T201- sys.exit(1)- print("\n🔍 Available kubernetes contexts:") # noqa: T201- for i, context in enumerate(contexts, 1):- if context == current:- print(f" {i}. {context} (current)") # noqa: T201- else:- print(f" {i}. {context}") # noqa: T201+def check_context_access(context: str, _namespace: str) -> tuple[bool, str]:+ """Return whether a context can authenticate to its Kubernetes cluster."""+ try:+ result = subprocess.run(+ kubectl_cmd("auth", "whoami", "-o", "json", context=context),+ capture_output=True,+ text=True,+ check=False,+ timeout=COMMAND_TIMEOUT_SECONDS,+ )+ except FileNotFoundError:+ return False, "kubectl is not installed or is not on PATH"+ except subprocess.TimeoutExpired:+ return False, "kubectl authentication check timed out"- print(f"\nCurrently using: {current}") # noqa: T201- response = input("Enter context number to switch or press Enter to continue with current context: ").strip()+ diagnostic = "\n".join(part for part in (result.stdout.strip(), result.stderr.strip()) if part)+ if result.returncode == 0:+ return True, ""+ return False, diagnostic- if not response:- return current+def get_context_profile(context: str) -> str:+ """Derive the AWS profile from a context's local kubeconfig user entry."""try:- index = int(response) - 1- except ValueError:- print("⚠️ Invalid input, continuing with current context.") # noqa: T201- return current+ result = subprocess.run(+ ["kubectl", "config", "view", "-o", "json"],+ capture_output=True,+ text=True,+ check=True,+ timeout=COMMAND_TIMEOUT_SECONDS,+ )+ config = json.loads(result.stdout)+ context_entry = next(item for item in config.get("contexts", []) if item.get("name") == context)+ user_name = context_entry["context"]["user"]+ user_entry = next(item for item in config.get("users", []) if item.get("name") == user_name)+ env = user_entry.get("user", {}).get("exec", {}).get("env", [])+ profile = next(item["value"] for item in env if item.get("name") == "AWS_PROFILE")+ if not profile:+ raise ValueError("empty AWS_PROFILE")+ return profile+ except (+ subprocess.CalledProcessError,+ subprocess.TimeoutExpired,+ json.JSONDecodeError,+ KeyError,+ StopIteration,+ ValueError,+ ) as error:+ raise RuntimeError(f"could not derive an AWS profile for context '{context}'") from error- if 0 <= index < len(contexts):- return contexts[index]- print("⚠️ Invalid selection, continuing with current context.") # noqa: T201- return current+def _needs_sso_login(diagnostic: str) -> bool:+ diagnostic = diagnostic.lower()+ return any(+ marker in diagnostic+ for marker in (+ "token has expired",+ "sso session",+ "sso token",+ "unauthorizedssotokenerror",+ "error loading sso",+ )+ )+++def _needs_sso_reset(diagnostic: str) -> bool:+ """Return whether Kubernetes rejected credentials from an otherwise active SSO grant."""+ diagnostic = diagnostic.lower()+ return any(+ marker in diagnostic+ for marker in (+ "the server has asked for the client to provide credentials",+ "you must be logged in to the server (unauthorized)",+ )+ )+++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()]+ for line in lines:+ if "No access" in line:+ return "AWS reports that this profile currently has no access"+ if _needs_sso_reset(line):+ return "Kubernetes rejected the cached AWS SSO credentials"+ for line in reversed(lines):+ if not line.startswith(("E", "Unable to connect to the server")):+ return line+ return lines[-1] if lines else "authentication failed"+++def login_to_sso(profile: str, *, timeout: float) -> bool:+ """Run the AWS CLI's interactive SSO login for a kubeconfig-derived profile."""+ print(f"🔐 Your AWS SSO session needs refreshing. Logging in with profile '{profile}'...") # noqa: T201+ try:+ return (+ subprocess.run(+ ["aws", "sso", "login", "--profile", profile],+ check=False,+ timeout=max(1, timeout),+ ).returncode+ == 0+ )+ except FileNotFoundError:+ print("❌ aws is not installed or is not on PATH.") # noqa: T201+ return False+ except subprocess.TimeoutExpired:+ print("❌ AWS SSO login did not finish before the access wait timed out.") # noqa: T201+ return False+++def reset_sso(profile: str, *, deadline: float) -> bool:+ """Clear stale AWS SSO credentials and log back in with the selected profile."""+ print("🔄 Kubernetes rejected the refreshed credentials. Resetting AWS SSO and logging in again...") # noqa: T201+ try:+ logout = subprocess.run(+ ["aws", "sso", "logout"],+ check=False,+ timeout=max(1, deadline - time.monotonic()),+ )+ except FileNotFoundError:+ print("❌ aws is not installed or is not on PATH.") # noqa: T201+ return False+ except subprocess.TimeoutExpired:+ print("❌ AWS SSO logout did not finish before the access wait timed out.") # noqa: T201+ return False+ if logout.returncode != 0:+ print("❌ AWS SSO logout failed.") # noqa: T201+ return False+ return login_to_sso(profile, timeout=deadline - time.monotonic())+++def wait_for_context_access(context: str, namespace: str, *, initial_diagnostic: str = "") -> bool:+ """Wait up to ten minutes for an AWS Access grant to become usable."""+ deadline = time.monotonic() + ACCESS_WAIT_SECONDS+ try:+ profile = get_context_profile(context)+ except RuntimeError as error:+ print(f"❌ {error}.") # noqa: T201+ return False++ sso_login_attempted = False+ sso_reset_attempted = False+ if _needs_sso_reset(initial_diagnostic):+ sso_login_attempted = True+ if not login_to_sso(profile, timeout=deadline - time.monotonic()):+ return False+ elif _needs_sso_login(initial_diagnostic):+ sso_login_attempted = True+ if not login_to_sso(profile, timeout=deadline - time.monotonic()):+ print( # noqa: T201+ f"❌ AWS SSO login failed. Try `aws sso login --profile {profile}` and rerun the toolbox."+ )+ return False++ print("\n🔒 No active toolbox-capable access was found.") # noqa: T201+ print(f"Request `k8s + toolbox access` (eks-developer) in #aws-access: {AWS_ACCESS_CHANNEL}") # noqa: T201+ print("⏳ Waiting up to 10 minutes for access. Press Ctrl-C to stop.") # noqa: T201++ next_status = 0.0+ last_reason = ""+ while time.monotonic() < deadline:+ print(f" Checking whether '{context}' can authenticate...") # noqa: T201+ usable, diagnostic = check_context_access(context, namespace)+ if usable:+ print("✅ Access is active. Continuing...") # noqa: T201+ return True+ if _needs_sso_reset(diagnostic):+ if not sso_login_attempted:+ sso_login_attempted = True+ if not login_to_sso(profile, timeout=deadline - time.monotonic()):+ return False+ elif not sso_reset_attempted:+ sso_reset_attempted = True+ if not reset_sso(profile, deadline=deadline):+ return False+ elif _needs_sso_login(diagnostic) and not sso_login_attempted:+ sso_login_attempted = True+ if not login_to_sso(profile, timeout=deadline - time.monotonic()):+ return False+ reason = summarize_diagnostic(diagnostic)+ if reason != last_reason:+ print(f" Not ready: {reason}.") # noqa: T201+ last_reason = reason+ now = time.monotonic()+ if now >= next_status:+ remaining = max(0, int((deadline - now) / 60) + 1)+ print(f" Still waiting for access ({remaining} min remaining)...") # noqa: T201+ next_status = now + 30+ time.sleep(ACCESS_POLL_SECONDS)++ print( # noqa: T201+ "❌ Access was not available after 10 minutes. "+ f"After approval, rerun or use `aws sso login --profile {profile}`."+ )+ return False+++def select_context(namespace: str) -> str:+ """Select the least-privileged usable managed context for a toolbox environment."""+ environment = select_environment()+ available = set(get_available_contexts())+ candidates = [f"{environment}-{suffix}" for suffix in ACCESS_SUFFIXES]+ configured = [context for context in candidates if context in available]+ if not configured:+ print(f"❌ No managed toolbox contexts were found for '{environment}'.") # noqa: T201+ print("Your managed kubeconfig may be missing or out of date; contact #team-infrastructure.") # noqa: T201+ sys.exit(1)++ diagnostics: dict[str, str] = {}+ for context in configured:+ print(f"🔎 Checking kubernetes access with '{context}'...") # noqa: T201+ usable, diagnostic = check_context_access(context, namespace)+ diagnostics[context] = diagnostic+ if usable:+ return context++ least_privileged = f"{environment}-eks"+ if least_privileged not in available:+ print(f"❌ Expected managed context '{least_privileged}' is missing from kubeconfig.") # noqa: T201+ sys.exit(1)+ if wait_for_context_access(+ least_privileged,+ namespace,+ initial_diagnostic=diagnostics.get(least_privileged, ""),+ ):+ return least_privileged+ sys.exit(1)+++def ensure_context_access(context: str, namespace: str) -> bool:+ """Validate an explicit expert override and explain failures."""+ usable, diagnostic = check_context_access(context, namespace)+ if usable:+ return True+ print(f"❌ KUBE_CONTEXT='{context}' cannot perform the toolbox pod operations.") # noqa: T201+ if diagnostic:+ print(diagnostic) # noqa: T201+ return False