Skip to content

: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.

fix(devex): say why metabase:login finds no cookies when macOS blocks the terminal (#103862)

Julian Bezab96a550dc0c
diff --git a/.agents/skills/querying-production-databases-via-metabase/SKILL.md b/.agents/skills/querying-production-databases-via-metabase/SKILL.md
index 39e75fcbe199..f7f172972688 100644
--- a/.agents/skills/querying-production-databases-via-metabase/SKILL.md
+++ b/.agents/skills/querying-production-databases-via-metabase/SKILL.md
@@ -70,6 +70,11 @@ hogli metabase:login --region eu
blocks Keychain access from agent shells, so the user has to authenticate
interactively.
+On macOS, the terminal app needs Full Disk Access to read browser cookies —
+without it, `metabase:login` fails with an error naming which browsers it
+couldn't read. Several browsers installed and logged into the wrong one?
+Pass `--browser <name>` to target one directly.
+
### Agents: use `metabase:query`
`hogli metabase:query` reads the cached cookie internally and only emits
diff --git a/tools/hogli-commands/hogli_commands/metabase.py b/tools/hogli-commands/hogli_commands/metabase.py
index 605b35b5eeca..df45033abd98 100644
--- a/tools/hogli-commands/hogli_commands/metabase.py
+++ b/tools/hogli-commands/hogli_commands/metabase.py
@@ -23,8 +23,11 @@ import os
import sys
import json
import time
+import plistlib
+import functools
+import subprocess
import webbrowser
-from collections.abc import Iterable
+from collections.abc import Iterable, Iterator
from pathlib import Path
from typing import Any
@@ -43,6 +46,7 @@ _CHROMIUM_PROFILE_ROOTS: dict[str, list[Path]] = {
"arc": [_HOME / "Library/Application Support/Arc/User Data"],
"dia": [_HOME / "Library/Application Support/Dia/User Data"],
}
+_FIREFOX_ROOT: Path = _HOME / "Library/Application Support/Firefox"
REGIONS: dict[str, str] = {
"us": "metabase.prod-us.posthog.dev",
@@ -58,6 +62,15 @@ REQUIRED_COOKIES: tuple[str, ...] = (
SUPPORTED_BROWSERS: tuple[str, ...] = ("chrome", "chromium", "brave", "arc", "dia", "firefox", "safari")
CACHE_DIR: Path = Path.home() / ".config" / "posthog" / "metabase"
+_HTTPS_HANDLER_BUNDLE_IDS: dict[str, str] = {
+ "org.mozilla.firefox": "firefox",
+ "com.google.chrome": "chrome",
+ "org.chromium.chromium": "chromium",
+ "com.brave.browser": "brave",
+ "company.thebrowser.browser": "arc",
+ "com.apple.safari": "safari",
+}
+
def _cookie_path(region: str) -> Path:
return CACHE_DIR / f"cookie-{region}"
@@ -67,6 +80,53 @@ def _format_cookie_header(cookies: dict[str, str]) -> str:
return "; ".join(f"{name}={value}" for name, value in cookies.items())
[email protected]_cache(maxsize=1)
+def _default_https_browser() -> str | None:
+ """Return the supported browser name registered as the system's https handler.
+
+ Only implemented for macOS, via LaunchServices. Any failure to run or parse
+ `defaults export` — missing binary, unreadable plist, unknown bundle id — falls
+ back to `None` so the caller keeps today's fixed browser order. Getting the
+ default wrong only costs one extra decrypt; it never blocks login.
+ """
+ if sys.platform != "darwin":
+ return None
+ try:
+ result = subprocess.run(
+ ["defaults", "export", "com.apple.LaunchServices/com.apple.launchservices.secure", "-"],
+ capture_output=True,
+ check=True,
+ timeout=5.0,
+ )
+ handlers = plistlib.loads(result.stdout).get("LSHandlers", [])
+ except Exception:
+ return None
+
+ for handler in handlers:
+ if not isinstance(handler, dict) or handler.get("LSHandlerURLScheme") != "https":
+ continue
+ bundle_id = handler.get("LSHandlerRoleAll") or handler.get("LSHandlerRoleViewer")
+ if isinstance(bundle_id, str):
+ return _HTTPS_HANDLER_BUNDLE_IDS.get(bundle_id.lower())
+ return None
+
+
+def _ordered_browsers(browser: str | None) -> tuple[str, ...]:
+ """Browsers to scan for cookies, default https handler first when known.
+
+ Without this, a machine with several browsers installed decrypts (and
+ Keychain-prompts for) every one of them in a fixed order before reaching
+ whichever browser actually holds the Metabase session. Only reorders —
+ every supported browser is still tried if the default one comes up empty.
+ """
+ if browser is not None:
+ return (browser,)
+ default = _default_https_browser()
+ if default is None or default not in SUPPORTED_BROWSERS:
+ return SUPPORTED_BROWSERS
+ return (default, *(name for name in SUPPORTED_BROWSERS if name != default))
+
+
def _enumerate_cookie_files(browser: str | None) -> list[tuple[str, Path]]:
"""Return (loader_name, cookie_file_path) pairs for every browser profile to try.
@@ -78,8 +138,7 @@ def _enumerate_cookie_files(browser: str | None) -> list[tuple[str, Path]]:
Firefox and Safari fall back to the default `browser_cookie3` loader.
"""
targets: list[tuple[str, Path]] = []
- selected = SUPPORTED_BROWSERS if browser is None else (browser,)
- for name in selected:
+ for name in _ordered_browsers(browser):
if name in _CHROMIUM_PROFILE_ROOTS:
for root in _CHROMIUM_PROFILE_ROOTS[name]:
if not root.exists():
@@ -91,11 +150,24 @@ def _enumerate_cookie_files(browser: str | None) -> list[tuple[str, Path]]:
return targets
-def _load_cookies_from_browser(domain: str, browser: str | None) -> dict[str, str]:
- """Read cookies for `domain` from the user's system browser cookie store.
+def _iter_cookie_candidates(
+ domain: str,
+ browser: str | None,
+ seen_warnings: set[str] | None = None,
+) -> Iterator[dict[str, str]]:
+ """Yield one complete REQUIRED_COOKIES set per readable browser profile, in scan order.
+
+ A profile that doesn't hold every required cookie is skipped rather than
+ merged with another profile's set — cookie values from two different
+ logins don't add up to a valid session. This is a generator, so a caller
+ that stops once an earlier candidate validates never decrypts (or
+ Keychain-prompts for) a later profile.
Decrypting Chromium cookies on macOS triggers a one-time Keychain prompt
per profile; users who pick "Always allow" won't see it again.
+
+ `seen_warnings`, when passed, dedupes load errors across repeated calls
+ (a polling loop) so the same warning doesn't reprint every interval.
"""
try:
import browser_cookie3
@@ -120,7 +192,7 @@ def _load_cookies_from_browser(domain: str, browser: str | None) -> dict[str, st
).load()
targets = _enumerate_cookie_files(browser)
- found: dict[str, str] = {}
+ found_candidate = False
errors: list[str] = []
for loader_name, cookie_file in targets:
loader = dia if loader_name == "dia" else getattr(browser_cookie3, loader_name, None)
@@ -134,13 +206,50 @@ def _load_cookies_from_browser(domain: str, browser: str | None) -> dict[str, st
except Exception as exc:
errors.append(f"{loader_name} ({cookie_file or 'default'}): {exc}")
continue
+ source_cookies: dict[str, str] = {}
for cookie in jar:
if cookie.name in REQUIRED_COOKIES and cookie.value:
- found[cookie.name] = cookie.value
+ source_cookies[cookie.name] = cookie.value
+ if all(name in source_cookies for name in REQUIRED_COOKIES):
+ found_candidate = True
+ yield source_cookies
+
+ if not found_candidate and errors:
+ new_errors = errors if seen_warnings is None else [e for e in errors if e not in seen_warnings]
+ if seen_warnings is not None:
+ seen_warnings.update(errors)
+ if new_errors:
+ click.echo("\n".join(f" warn: {e}" for e in new_errors), err=True)
+
- if not found and errors:
- click.echo("\n".join(f" warn: {e}" for e in errors), err=True)
- return found
+def _find_valid_candidate(
+ domain: str,
+ browser: str | None,
+ seen_warnings: set[str] | None = None,
+ rejected_headers: set[str] | None = None,
+) -> tuple[str | None, bool]:
+ """Try each cookie candidate against Metabase in order; return (header, any_candidate).
+
+ `header` is the first candidate's cookie header the server accepts, or
+ `None` if none did. `rejected_headers`, when passed, skips re-checking a
+ header the server already outright rejected, without stopping the scan —
+ an expired session in an earlier profile must not block a valid one in a
+ later profile, on this call or a repeated one. A header the server hasn't
+ confirmed or rejected (a network blip, a 5xx from the load balancer) is
+ never added to `rejected_headers`, so it gets retried on the next call.
+ """
+ any_candidate = False
+ for candidate in _iter_cookie_candidates(domain, browser, seen_warnings):
+ any_candidate = True
+ header = _format_cookie_header(candidate)
+ if rejected_headers is not None and header in rejected_headers:
+ continue
+ result = _probe_cookie(domain, header)
+ if result is True:
+ return header, any_candidate
+ if result is False and rejected_headers is not None:
+ rejected_headers.add(header)
+ return None, any_candidate
def _secure_write(path: Path, content: str) -> None:
@@ -172,8 +281,15 @@ def _read_cookie_file(region: str) -> str | None:
return path.read_text().strip()
-def _check_cookie(domain: str, cookie_header: str, timeout: float = 5.0) -> bool:
- """Hit /api/user/current to confirm the cookie is still valid."""
+def _probe_cookie(domain: str, cookie_header: str, timeout: float = 5.0) -> bool | None:
+ """Hit /api/user/current and classify the response into three states.
+
+ `True`: the session is valid. `False`: the server rejected it outright (a
+ redirect back to SSO, 401, 403) — this cookie will not become valid
+ later. `None`: a transport failure or a transient status (5xx, 429,
+ anything else unexpected) — inconclusive, so a caller should retry
+ rather than treat the cookie as dead.
+ """
import requests
try:
@@ -184,8 +300,112 @@ def _check_cookie(domain: str, cookie_header: str, timeout: float = 5.0) -> bool
allow_redirects=False,
)
except requests.RequestException:
+ return None
+
+ if response.status_code == 200:
+ return True
+ if response.status_code in (401, 403) or 300 <= response.status_code < 400:
return False
- return response.status_code == 200
+ return None
+
+
+def _check_cookie(domain: str, cookie_header: str, timeout: float = 5.0) -> bool:
+ """Confirm the cookie is currently valid. `None` (inconclusive) reads as not valid."""
+ return _probe_cookie(domain, cookie_header, timeout) is True
+
+
+def _is_directory_blocked(root: Path) -> bool:
+ """True if `root` exists but this process can't read its contents.
+
+ macOS's Full Disk Access restriction doesn't clear a directory's unix
+ permission bits, so `os.access` alone can say "readable" while every real
+ read raises `PermissionError`. Check both: `os.access` catches the
+ ordinary case, the read attempt catches TCC's silent block.
+ """
+ if not root.exists():
+ return False
+ if not os.access(root, os.R_OK):
+ return True
+ try:
+ with os.scandir(root) as entries:
+ next(entries, None)
+ except PermissionError:
+ return True
+ return False
+
+
+def _detect_blocked_browsers(browser: str | None) -> list[str]:
+ """Browser names whose cookie-data directory exists but can't be read.
+
+ Covers the Chromium-family roots and the Firefox root — the two cases
+ where macOS blocks a directory listing outright before browser_cookie3
+ gets a chance to say anything useful. Safari doesn't scan a directory
+ (its cookie store is a single file), so its own load error covers it.
+ """
+ selected = SUPPORTED_BROWSERS if browser is None else (browser,)
+ blocked: list[str] = []
+ for name in selected:
+ if name in _CHROMIUM_PROFILE_ROOTS:
+ roots = _CHROMIUM_PROFILE_ROOTS[name]
+ elif name == "firefox":
+ roots = [_FIREFOX_ROOT]
+ else:
+ continue
+ if any(_is_directory_blocked(root) for root in roots):
+ blocked.append(name)
+ return blocked
+
+
+def _all_readable_browsers_blocked(browser: str | None, blocked: list[str]) -> bool:
+ """True when every installed, directory-checkable candidate is blocked.
+
+ An uninstalled browser is neither blocked nor a reason to keep polling, so
+ only an installed Chromium/Firefox root that isn't blocked counts as a
+ reason a valid session could still show up. Safari isn't directory-checked
+ at all, so a detected Safari default (or an explicit --browser safari)
+ always counts as a live candidate — this check otherwise has no way to
+ see it.
+ """
+ if browser == "safari" or (browser is None and _default_https_browser() == "safari"):
+ return False
+ selected = SUPPORTED_BROWSERS if browser is None else (browser,)
+ for name in selected:
+ if name in _CHROMIUM_PROFILE_ROOTS:
+ roots = _CHROMIUM_PROFILE_ROOTS[name]
+ elif name == "firefox":
+ roots = [_FIREFOX_ROOT]
+ else:
+ continue
+ if name not in blocked and any(root.exists() for root in roots):
+ return False
+ return True
+
+
+def _full_disk_access_hint() -> str:
+ """macOS-specific remediation text; empty string on every other platform."""
+ if sys.platform != "darwin":
+ return ""
+ return (
+ " On macOS: grant your terminal app Full Disk Access under System Settings > "
+ "Privacy & Security > Full Disk Access, restart the terminal, then run this command again."
+ )
+
+
+def _blocked_browser_note(blocked: list[str]) -> str:
+ """One-line, printed once, while polling continues because another browser worked."""
+ return f"note: {', '.join(blocked)} cookie data can't be read; skipping." + _full_disk_access_hint()
+
+
+def _blocked_browser_message(blocked: list[str]) -> str:
+ """`ClickException` text for when no cookies at all were found and a browser is blocked.
+
+ Waiting out the timeout wouldn't help here — the browser holding the
+ session may never become readable without the Full Disk Access grant.
+ """
+ return (
+ f"No cookies found, and {', '.join(blocked)} cookie data can't be read "
+ "(the OS is blocking this terminal from it)." + _full_disk_access_hint()
+ )
def _wait_for_valid_cookie(
@@ -197,26 +417,35 @@ def _wait_for_valid_cookie(
"""Poll the browser cookie store until a valid Metabase session appears.
Returns the cookie header on success. Raises `click.ClickException` after
- `timeout` seconds without finding a valid session.
+ `timeout` seconds without finding a valid session — or immediately if no
+ cookie candidate at all can be read and every installed candidate browser
+ is blocked, since waiting out the timeout would never help in that case.
+ A still-readable candidate might just need more time to complete SSO, so
+ that case keeps polling as before.
"""
+ blocked = _detect_blocked_browsers(browser)
+ hopeless = bool(blocked) and _all_readable_browsers_blocked(browser, blocked)
deadline = time.monotonic() + timeout
last_status = ""
- last_header: str | None = None
+ seen_warnings: set[str] = set()
+ rejected_headers: set[str] = set()
+ blocked_note_printed = False
while True:
- cookies = _load_cookies_from_browser(domain, browser)
- missing = [name for name in REQUIRED_COOKIES if name not in cookies]
- if not missing:
- cookie_header = _format_cookie_header(cookies)
- # Avoid pinging /api/user/current with the same header repeatedly
- # when the user already had a stale cookie set on disk.
- if cookie_header != last_header:
- last_header = cookie_header
- if _check_cookie(domain, cookie_header):
- return cookie_header
- status = "Cookies present but session not yet valid; still waiting..."
- else:
- status = f"Waiting for cookies: missing {missing}..."
-
+ header, any_candidate = _find_valid_candidate(domain, browser, seen_warnings, rejected_headers)
+ if header is not None:
+ return header
+
+ if not any_candidate and hopeless:
+ raise click.ClickException(_blocked_browser_message(blocked))
+ if blocked and not blocked_note_printed:
+ click.echo(_blocked_browser_note(blocked))
+ blocked_note_printed = True
+
+ status = (
+ "Cookies present but session not yet valid; still waiting..."
+ if any_candidate
+ else "Waiting for cookies: no browser profile has the full set yet..."
+ )
if status != last_status:
click.echo(status)
last_status = status
@@ -234,13 +463,11 @@ def _login_region(region: str, browser: str | None, no_open: bool, timeout: floa
"""Authenticate one region: fast-path if already logged in, else open browser and wait."""
domain = REGIONS[region]
- cookies = _load_cookies_from_browser(domain, browser)
- if all(name in cookies for name in REQUIRED_COOKIES):
- header = _format_cookie_header(cookies)
- if _check_cookie(domain, header):
- path = _write_cookie_file(region, header)
- click.echo(f"[{region}] already logged in; saved cookie to {path}")
- return
+ header, _ = _find_valid_candidate(domain, browser)
+ if header is not None:
+ path = _write_cookie_file(region, header)
+ click.echo(f"[{region}] already logged in; saved cookie to {path}")
+ return
if not no_open:
click.echo(f"[{region}] opening https://{domain} in your default browser.")
@@ -263,7 +490,7 @@ def _login_region(region: str, browser: str | None, no_open: bool, timeout: floa
"--browser",
type=click.Choice(SUPPORTED_BROWSERS),
default=None,
- help="Read cookies from this browser only (default: scan all supported browsers)",
+ help="Read cookies from this browser only (default: try the system default browser first, then scan the rest)",
)
@click.option("--no-open", is_flag=True, help="Skip opening the browser; just capture cookies")
@click.option(
diff --git a/tools/hogli-commands/hogli_commands/tests/test_metabase.py b/tools/hogli-commands/hogli_commands/tests/test_metabase.py
index 9b8d47d4813c..98427e1b00f6 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_metabase.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_metabase.py
@@ -1,8 +1,10 @@
from __future__ import annotations
import os
-from collections.abc import Iterator
+import plistlib
+from collections.abc import Callable, Iterator
from pathlib import Path
+from types import SimpleNamespace
import pytest
from unittest.mock import patch
@@ -75,24 +77,32 @@ def test_load_cookies_filters_to_required_names(monkeypatch: pytest.MonkeyPatch)
"_enumerate_cookie_files",
lambda browser: [("chrome", Path("/fake/profile/Cookies"))],
)
- cookies = metabase._load_cookies_from_browser("metabase.prod-us.posthog.dev", "chrome")
- assert cookies == {
- "metabase.SESSION": "s",
- "metabase.DEVICE": "d",
- "ph_int_auth-0": "a0",
- "ph_int_auth-1": "a1",
- }
+ candidates = list(metabase._iter_cookie_candidates("metabase.prod-us.posthog.dev", "chrome"))
+ assert candidates == [
+ {
+ "metabase.SESSION": "s",
+ "metabase.DEVICE": "d",
+ "ph_int_auth-0": "a0",
+ "ph_int_auth-1": "a1",
+ }
+ ]
def test_load_cookies_dia_uses_chromium_based_with_dia_keychain(monkeypatch: pytest.MonkeyPatch) -> None:
seen_kwargs: dict = {}
+ complete_jar = [
+ _FakeCookie("metabase.SESSION", "s"),
+ _FakeCookie("metabase.DEVICE", "d"),
+ _FakeCookie("ph_int_auth-0", "a0"),
+ _FakeCookie("ph_int_auth-1", "a1"),
+ ]
class FakeChromiumBased:
def __init__(self, **kwargs: object) -> None:
seen_kwargs.update(kwargs)
def load(self) -> list[_FakeCookie]:
- return [_FakeCookie("metabase.SESSION", "s")]
+ return complete_jar
class FakeBC3:
ChromiumBased = FakeChromiumBased
@@ -105,12 +115,186 @@ def test_load_cookies_dia_uses_chromium_based_with_dia_keychain(monkeypatch: pyt
"_enumerate_cookie_files",
lambda browser: [("dia", Path("/fake/dia/Default/Cookies"))],
)
- cookies = metabase._load_cookies_from_browser("metabase.prod-us.posthog.dev", "dia")
- assert cookies == {"metabase.SESSION": "s"}
+ candidates = list(metabase._iter_cookie_candidates("metabase.prod-us.posthog.dev", "dia"))
+ assert candidates == [
+ {"metabase.SESSION": "s", "metabase.DEVICE": "d", "ph_int_auth-0": "a0", "ph_int_auth-1": "a1"}
+ ]
assert seen_kwargs["osx_key_service"] == "Dia Safe Storage"
assert seen_kwargs["cookie_file"] == "/fake/dia/Default/Cookies"
+def test_iter_cookie_candidates_never_merges_partial_profiles(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Profiles A and B are each partial but jointly cover REQUIRED_COOKIES; profile C
+ # is complete on its own. Only C's set may appear — A and B are not candidates,
+ # merged or otherwise, since their cookies belong to two different logins.
+ jars_by_file = {
+ "/a/Cookies": [_FakeCookie("metabase.SESSION", "s-a"), _FakeCookie("metabase.DEVICE", "d-a")],
+ "/b/Cookies": [_FakeCookie("ph_int_auth-0", "a0-b"), _FakeCookie("ph_int_auth-1", "a1-b")],
+ "/c/Cookies": [
+ _FakeCookie("metabase.SESSION", "s-c"),
+ _FakeCookie("metabase.DEVICE", "d-c"),
+ _FakeCookie("ph_int_auth-0", "a0-c"),
+ _FakeCookie("ph_int_auth-1", "a1-c"),
+ ],
+ }
+
+ class FakeBC3:
+ @staticmethod
+ def chrome(domain_name: str, cookie_file: str | None = None) -> list[_FakeCookie]:
+ return jars_by_file[cookie_file]
+
+ import sys
+
+ monkeypatch.setitem(sys.modules, "browser_cookie3", FakeBC3)
+ monkeypatch.setattr(
+ metabase,
+ "_enumerate_cookie_files",
+ lambda browser: [
+ ("chrome", Path("/a/Cookies")),
+ ("chrome", Path("/b/Cookies")),
+ ("chrome", Path("/c/Cookies")),
+ ],
+ )
+
+ candidates = list(metabase._iter_cookie_candidates("metabase.prod-us.posthog.dev", "chrome"))
+ assert candidates == [
+ {
+ "metabase.SESSION": "s-c",
+ "metabase.DEVICE": "d-c",
+ "ph_int_auth-0": "a0-c",
+ "ph_int_auth-1": "a1-c",
+ }
+ ]
+
+
+def test_find_valid_candidate_ignores_partial_profiles_and_never_probes(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ jars_by_file = {
+ "/a/Cookies": [_FakeCookie("metabase.SESSION", "s-a"), _FakeCookie("metabase.DEVICE", "d-a")],
+ "/b/Cookies": [_FakeCookie("ph_int_auth-0", "a0-b"), _FakeCookie("ph_int_auth-1", "a1-b")],
+ }
+
+ class FakeBC3:
+ @staticmethod
+ def chrome(domain_name: str, cookie_file: str | None = None) -> list[_FakeCookie]:
+ return jars_by_file[cookie_file]
+
+ import sys
+
+ monkeypatch.setitem(sys.modules, "browser_cookie3", FakeBC3)
+ monkeypatch.setattr(
+ metabase,
+ "_enumerate_cookie_files",
+ lambda browser: [("chrome", Path("/a/Cookies")), ("chrome", Path("/b/Cookies"))],
+ )
+ probe_calls: list[str] = []
+ monkeypatch.setattr(metabase, "_probe_cookie", lambda domain, header: probe_calls.append(header) or True)
+
+ header, any_candidate = metabase._find_valid_candidate("metabase.prod-us.posthog.dev", "chrome")
+ assert header is None
+ assert any_candidate is False
+ assert probe_calls == []
+
+
+def test_find_valid_candidate_stops_after_first_valid_candidate(monkeypatch: pytest.MonkeyPatch) -> None:
+ complete = [
+ _FakeCookie("metabase.SESSION", "s"),
+ _FakeCookie("metabase.DEVICE", "d"),
+ _FakeCookie("ph_int_auth-0", "a0"),
+ _FakeCookie("ph_int_auth-1", "a1"),
+ ]
+ calls: list[str] = []
+
+ class FakeBC3:
+ @staticmethod
+ def chrome(domain_name: str, cookie_file: str | None = None) -> list[_FakeCookie]:
+ calls.append(cookie_file or "default")
+ if cookie_file == "/first/Cookies":
+ return complete
+ raise AssertionError("must not read a later profile once one validates")
+
+ import sys
+
+ monkeypatch.setitem(sys.modules, "browser_cookie3", FakeBC3)
+ monkeypatch.setattr(
+ metabase,
+ "_enumerate_cookie_files",
+ lambda browser: [("chrome", Path("/first/Cookies")), ("chrome", Path("/second/Cookies"))],
+ )
+ monkeypatch.setattr(metabase, "_probe_cookie", lambda domain, header: True)
+
+ header, any_candidate = metabase._find_valid_candidate("metabase.prod-us.posthog.dev", "chrome")
+ expected = metabase._format_cookie_header(
+ {"metabase.SESSION": "s", "metabase.DEVICE": "d", "ph_int_auth-0": "a0", "ph_int_auth-1": "a1"}
+ )
+ assert header == expected
+ assert any_candidate is True
+ assert calls == ["/first/Cookies"]
+
+
+ ("status_code", "expected"),
+ [
+ pytest.param(200, True, id="200-accepted"),
+ pytest.param(302, False, id="302-sso-redirect"),
+ pytest.param(303, False, id="303-sso-redirect"),
+ pytest.param(401, False, id="401-unauthorized"),
+ pytest.param(403, False, id="403-forbidden"),
+ pytest.param(429, None, id="429-rate-limited"),
+ pytest.param(502, None, id="502-bad-gateway"),
+ pytest.param(503, None, id="503-unavailable"),
+ ],
+)
+def test_probe_cookie_classifies_the_response(
+ monkeypatch: pytest.MonkeyPatch, status_code: int, expected: bool | None
+) -> None:
+ import requests
+
+ monkeypatch.setattr(requests, "get", lambda *a, **k: SimpleNamespace(status_code=status_code))
+ assert metabase._probe_cookie("metabase.example", "cookie=1") is expected
+
+
+def test_probe_cookie_returns_none_on_request_exception(monkeypatch: pytest.MonkeyPatch) -> None:
+ import requests
+
+ def raise_request_exception(*args: object, **kwargs: object) -> None:
+ raise requests.RequestException("boom")
+
+ monkeypatch.setattr(requests, "get", raise_request_exception)
+ assert metabase._probe_cookie("metabase.example", "cookie=1") is None
+
+
+def test_check_cookie_treats_inconclusive_the_same_as_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
+ # _check_cookie keeps its boolean contract for metabase:cookie --check,
+ # which has no retry loop to give a transient failure a second chance.
+ monkeypatch.setattr(metabase, "_probe_cookie", lambda domain, header, timeout=5.0: None)
+ assert metabase._check_cookie("metabase.example", "cookie=1") is False
+
+
+ ("probe_result", "remembered"),
+ [
+ pytest.param(False, True, id="rejected-is-remembered"),
+ pytest.param(None, False, id="inconclusive-is-not-remembered"),
+ ],
+)
+def test_find_valid_candidate_only_remembers_an_outright_rejection(
+ monkeypatch: pytest.MonkeyPatch, probe_result: bool | None, remembered: bool
+) -> None:
+ candidate = {"metabase.SESSION": "s", "metabase.DEVICE": "d", "ph_int_auth-0": "a0", "ph_int_auth-1": "a1"}
+ header = metabase._format_cookie_header(candidate)
+ monkeypatch.setattr(
+ metabase, "_iter_cookie_candidates", lambda domain, browser, seen_warnings=None: iter([candidate])
+ )
+ monkeypatch.setattr(metabase, "_probe_cookie", lambda domain, h: probe_result)
+
+ rejected_headers: set[str] = set()
+ result_header, _ = metabase._find_valid_candidate("metabase.example", None, rejected_headers=rejected_headers)
+ assert result_header is None
+ assert (header in rejected_headers) is remembered
+
+
def test_enumerate_cookie_files_globs_chromium_profiles(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
chrome_root = tmp_path / "Chrome"
(chrome_root / "Default").mkdir(parents=True)
@@ -125,6 +309,56 @@ def test_enumerate_cookie_files_globs_chromium_profiles(monkeypatch: pytest.Monk
assert any("Profile 1/Cookies" in p for p in cookie_files)
+def test_ordered_browsers_puts_default_first(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(metabase, "_default_https_browser", lambda: "firefox")
+ order = metabase._ordered_browsers(None)
+ assert order[0] == "firefox"
+ assert set(order) == set(metabase.SUPPORTED_BROWSERS), "reordering must never drop a browser"
+
+
+def test_ordered_browsers_falls_back_when_default_unknown(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(metabase, "_default_https_browser", lambda: None)
+ assert metabase._ordered_browsers(None) == metabase.SUPPORTED_BROWSERS
+
+
+def test_ordered_browsers_ignores_default_when_explicit_browser_given(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(metabase, "_default_https_browser", lambda: "firefox")
+ assert metabase._ordered_browsers("chrome") == ("chrome",)
+
+
+def _plist_stub(bundle_id: str) -> Callable[..., SimpleNamespace]:
+ plist = plistlib.dumps({"LSHandlers": [{"LSHandlerURLScheme": "https", "LSHandlerRoleAll": bundle_id}]})
+ return lambda *args, **kwargs: SimpleNamespace(stdout=plist)
+
+
+def _failing_subprocess_run(*args: object, **kwargs: object) -> SimpleNamespace:
+ raise OSError("no defaults binary")
+
+
+ ("platform", "run_stub", "expected"),
+ [
+ pytest.param("darwin", _plist_stub("org.mozilla.firefox"), "firefox", id="known-bundle-id"),
+ pytest.param("darwin", _plist_stub("com.example.unknownbrowser"), None, id="unknown-bundle-id"),
+ pytest.param("linux", _plist_stub("org.mozilla.firefox"), None, id="non-darwin"),
+ pytest.param("darwin", _failing_subprocess_run, None, id="subprocess-failure"),
+ ],
+)
+def test_default_https_browser(
+ monkeypatch: pytest.MonkeyPatch,
+ platform: str,
+ run_stub: Callable[..., SimpleNamespace],
+ expected: str | None,
+) -> None:
+ metabase._default_https_browser.cache_clear()
+ monkeypatch.setattr(metabase.sys, "platform", platform)
+ monkeypatch.setattr(metabase.subprocess, "run", run_stub)
+ try:
+ assert metabase._default_https_browser() == expected
+ finally:
+ metabase._default_https_browser.cache_clear()
+
+
def test_load_cookies_unsupported_browser_raises(monkeypatch: pytest.MonkeyPatch) -> None:
class FakeBC3:
pass
@@ -133,7 +367,141 @@ def test_load_cookies_unsupported_browser_raises(monkeypatch: pytest.MonkeyPatch
monkeypatch.setitem(sys.modules, "browser_cookie3", FakeBC3)
with pytest.raises(click.ClickException, match="Unsupported browser"):
- metabase._load_cookies_from_browser("metabase.prod-us.posthog.dev", "lynx")
+ # _iter_cookie_candidates is a generator, so the body (and its raise) only
+ # runs once iterated.
+ list(metabase._iter_cookie_candidates("metabase.prod-us.posthog.dev", "lynx"))
+
+
+def test_load_cookies_warning_printed_once_across_repeated_calls(
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ class FakeBC3:
+ @staticmethod
+ def firefox(domain_name: str, cookie_file: str | None = None) -> list[_FakeCookie]:
+ raise RuntimeError("Failed to find Firefox cookie file")
+
+ import sys
+
+ monkeypatch.setitem(sys.modules, "browser_cookie3", FakeBC3)
+ monkeypatch.setattr(metabase, "_enumerate_cookie_files", lambda browser: [("firefox", Path())])
+
+ seen_warnings: set[str] = set()
+ list(metabase._iter_cookie_candidates("metabase.prod-us.posthog.dev", "firefox", seen_warnings))
+ list(metabase._iter_cookie_candidates("metabase.prod-us.posthog.dev", "firefox", seen_warnings))
+
+ captured = capsys.readouterr()
+ assert captured.err.count("Failed to find Firefox cookie file") == 1
+
+
+def test_is_directory_blocked_false_for_missing_directory(tmp_path: Path) -> None:
+ assert metabase._is_directory_blocked(tmp_path / "does-not-exist") is False
+
+
+def test_is_directory_blocked_false_for_readable_directory(tmp_path: Path) -> None:
+ root = tmp_path / "readable"
+ root.mkdir()
+ assert metabase._is_directory_blocked(root) is False
+
+
+def test_is_directory_blocked_true_on_permission_error(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ root = tmp_path / "blocked"
+ root.mkdir()
+
+ def raise_permission_error(path: object) -> None:
+ raise PermissionError("Operation not permitted")
+
+ monkeypatch.setattr(metabase.os, "scandir", raise_permission_error)
+ assert metabase._is_directory_blocked(root) is True
+
+
+def test_is_directory_blocked_true_for_chmod_000(tmp_path: Path) -> None:
+ if os.geteuid() == 0:
+ pytest.skip("root bypasses unix permission bits")
+ root = tmp_path / "locked"
+ root.mkdir()
+ root.chmod(0o000)
+ try:
+ assert metabase._is_directory_blocked(root) is True
+ finally:
+ root.chmod(0o700)
+
+
+def test_detect_blocked_browsers_reports_chromium_and_firefox_roots(monkeypatch: pytest.MonkeyPatch) -> None:
+ chrome_root = Path("/fake/chrome")
+ firefox_root = Path("/fake/firefox")
+ monkeypatch.setattr(metabase, "_CHROMIUM_PROFILE_ROOTS", {"chrome": [chrome_root], "brave": [Path("/fake/brave")]})
+ monkeypatch.setattr(metabase, "_FIREFOX_ROOT", firefox_root)
+ monkeypatch.setattr(metabase, "_is_directory_blocked", lambda root: root in (chrome_root, firefox_root))
+
+ assert metabase._detect_blocked_browsers(None) == ["chrome", "firefox"]
+
+
+def test_detect_blocked_browsers_does_not_check_safari(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Safari's cookie store is a single binarycookies file, not a scanned directory,
+ # so it never shows up as "blocked" here — browser_cookie3's own load error covers it.
+ monkeypatch.setattr(metabase, "_is_directory_blocked", lambda root: True)
+ assert metabase._detect_blocked_browsers("safari") == []
+
+
+def test_detect_blocked_browsers_scoped_to_explicit_browser(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(metabase, "_is_directory_blocked", lambda root: True)
+ assert metabase._detect_blocked_browsers("chrome") == ["chrome"]
+ assert metabase._detect_blocked_browsers("firefox") == ["firefox"]
+
+
+def test_all_readable_browsers_blocked_true_when_only_installed_candidates_are_blocked(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ chrome_root = tmp_path / "chrome"
+ chrome_root.mkdir()
+ firefox_root = tmp_path / "firefox"
+ firefox_root.mkdir()
+ monkeypatch.setattr(metabase, "_CHROMIUM_PROFILE_ROOTS", {"chrome": [chrome_root]})
+ monkeypatch.setattr(metabase, "_FIREFOX_ROOT", firefox_root)
+ monkeypatch.setattr(metabase, "_default_https_browser", lambda: None)
+
+ assert metabase._all_readable_browsers_blocked(None, ["chrome", "firefox"]) is True
+
+
+def test_all_readable_browsers_blocked_false_when_an_installed_candidate_is_unblocked(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # Arc is blocked, but Chrome is installed and readable, so SSO could still land there.
+ chrome_root = tmp_path / "chrome"
+ chrome_root.mkdir()
+ arc_root = tmp_path / "arc"
+ arc_root.mkdir()
+ monkeypatch.setattr(metabase, "_CHROMIUM_PROFILE_ROOTS", {"chrome": [chrome_root], "arc": [arc_root]})
+ monkeypatch.setattr(metabase, "_FIREFOX_ROOT", tmp_path / "does-not-exist")
+ monkeypatch.setattr(metabase, "_default_https_browser", lambda: None)
+
+ assert metabase._all_readable_browsers_blocked(None, ["arc"]) is False
+
+
+def test_all_readable_browsers_blocked_true_when_no_candidate_is_installed(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr(metabase, "_CHROMIUM_PROFILE_ROOTS", {"chrome": [tmp_path / "does-not-exist"]})
+ monkeypatch.setattr(metabase, "_FIREFOX_ROOT", tmp_path / "also-missing")
+ monkeypatch.setattr(metabase, "_default_https_browser", lambda: None)
+
+ assert metabase._all_readable_browsers_blocked(None, []) is True
+
+
+ ("browser", "blocked"),
+ [
+ pytest.param(None, ["chrome", "firefox"], id="default-browser-is-safari"),
+ pytest.param("safari", [], id="explicit-safari"),
+ ],
+)
+def test_all_readable_browsers_blocked_false_for_safari(
+ monkeypatch: pytest.MonkeyPatch, browser: str | None, blocked: list[str]
+) -> None:
+ # Safari isn't directory-checked, so a blocked Chrome/Firefox must not read as
+ # "hopeless" when Safari is the browser actually in play.
+ monkeypatch.setattr(metabase, "_default_https_browser", lambda: "safari")
+ assert metabase._all_readable_browsers_blocked(browser, blocked) is False
def test_metabase_cookie_command_errors_when_no_cache(cache_dir: Path) -> None:
@@ -169,14 +537,10 @@ def test_metabase_cookie_requires_region_flag() -> None:
def test_metabase_login_writes_cookie_after_validation(cache_dir: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- captured = {
- "metabase.SESSION": "s",
- "metabase.DEVICE": "d",
- "ph_int_auth-0": "a0",
- "ph_int_auth-1": "a1",
- }
- monkeypatch.setattr(metabase, "_load_cookies_from_browser", lambda domain, browser: captured)
- monkeypatch.setattr(metabase, "_check_cookie", lambda domain, header: True)
+ expected = metabase._format_cookie_header(
+ {"metabase.SESSION": "s", "metabase.DEVICE": "d", "ph_int_auth-0": "a0", "ph_int_auth-1": "a1"}
+ )
+ monkeypatch.setattr(metabase, "_find_valid_candidate", lambda domain, browser: (expected, True))
monkeypatch.setattr(metabase.webbrowser, "open", lambda url: True)
monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
@@ -185,7 +549,7 @@ def test_metabase_login_writes_cookie_after_validation(cache_dir: Path, monkeypa
assert result.exit_code == 0, result.output
saved = (cache_dir / "cookie-eu").read_text()
- assert saved == "metabase.SESSION=s; metabase.DEVICE=d; ph_int_auth-0=a0; ph_int_auth-1=a1"
+ assert saved == expected
mode = os.stat(cache_dir / "cookie-eu").st_mode & 0o777
assert mode == 0o600
@@ -198,9 +562,8 @@ def test_metabase_login_requires_region_flag() -> None:
def test_metabase_login_fast_paths_already_valid_session(cache_dir: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- captured = {name: f"{name}-val" for name in metabase.REQUIRED_COOKIES}
- monkeypatch.setattr(metabase, "_load_cookies_from_browser", lambda domain, browser: captured)
- monkeypatch.setattr(metabase, "_check_cookie", lambda domain, header: True)
+ expected = metabase._format_cookie_header({name: f"{name}-val" for name in metabase.REQUIRED_COOKIES})
+ monkeypatch.setattr(metabase, "_find_valid_candidate", lambda domain, browser: (expected, True))
monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
opens: list[str] = []
@@ -218,24 +581,32 @@ def test_metabase_login_fast_paths_already_valid_session(cache_dir: Path, monkey
def test_wait_for_valid_cookie_returns_when_session_valid(monkeypatch: pytest.MonkeyPatch) -> None:
+ expected = metabase._format_cookie_header({name: name + "-val" for name in metabase.REQUIRED_COOKIES})
sequence = [
- {},
- {"metabase.SESSION": "s"},
- {name: name + "-val" for name in metabase.REQUIRED_COOKIES},
+ (None, False),
+ (None, True),
+ (expected, True),
]
calls = iter(sequence)
- monkeypatch.setattr(metabase, "_load_cookies_from_browser", lambda d, b: next(calls))
- monkeypatch.setattr(metabase, "_check_cookie", lambda d, h: True)
+ monkeypatch.setattr(metabase, "_detect_blocked_browsers", lambda browser: [])
+ monkeypatch.setattr(
+ metabase,
+ "_find_valid_candidate",
+ lambda d, b, seen_warnings=None, rejected_headers=None: next(calls),
+ )
monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
header = metabase._wait_for_valid_cookie("metabase.example", None, timeout=10.0, interval=0.0)
- expected = metabase._format_cookie_header({name: name + "-val" for name in metabase.REQUIRED_COOKIES})
assert header == expected
def test_wait_for_valid_cookie_times_out(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(metabase, "_load_cookies_from_browser", lambda d, b: {})
- monkeypatch.setattr(metabase, "_check_cookie", lambda d, h: False)
+ monkeypatch.setattr(metabase, "_detect_blocked_browsers", lambda browser: [])
+ monkeypatch.setattr(
+ metabase,
+ "_find_valid_candidate",
+ lambda d, b, seen_warnings=None, rejected_headers=None: (None, False),
+ )
monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
# Return 0.0 twice (start + flush-hint check), then saturate past the deadline.
@@ -253,6 +624,191 @@ def test_wait_for_valid_cookie_times_out(monkeypatch: pytest.MonkeyPatch) -> Non
metabase._wait_for_valid_cookie("metabase.example", None, timeout=10.0, interval=0.0)
+def test_wait_for_valid_cookie_raises_immediately_when_blocked_and_no_cookies(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(metabase, "_detect_blocked_browsers", lambda browser: ["chrome"])
+ monkeypatch.setattr(metabase, "_all_readable_browsers_blocked", lambda browser, blocked: True)
+ monkeypatch.setattr(
+ metabase,
+ "_find_valid_candidate",
+ lambda d, b, seen_warnings=None, rejected_headers=None: (None, False),
+ )
+ monkeypatch.setattr(metabase.sys, "platform", "darwin")
+ sleep_calls: list[float] = []
+ monkeypatch.setattr(metabase.time, "sleep", lambda s: sleep_calls.append(s))
+
+ with pytest.raises(click.ClickException, match="chrome") as exc_info:
+ metabase._wait_for_valid_cookie("metabase.example", None, timeout=180.0, interval=1.0)
+
+ assert sleep_calls == [], "must stop before waiting out the poll interval, let alone the timeout"
+ assert "Full Disk Access" in str(exc_info.value)
+
+
+def test_wait_for_valid_cookie_blocked_message_omits_macos_hint_off_darwin(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(metabase, "_detect_blocked_browsers", lambda browser: ["chrome"])
+ monkeypatch.setattr(metabase, "_all_readable_browsers_blocked", lambda browser, blocked: True)
+ monkeypatch.setattr(
+ metabase,
+ "_find_valid_candidate",
+ lambda d, b, seen_warnings=None, rejected_headers=None: (None, False),
+ )
+ monkeypatch.setattr(metabase.sys, "platform", "linux")
+ monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
+
+ with pytest.raises(click.ClickException) as exc_info:
+ metabase._wait_for_valid_cookie("metabase.example", None, timeout=180.0, interval=1.0)
+
+ assert "Full Disk Access" not in str(exc_info.value)
+
+
+def test_wait_for_valid_cookie_does_not_fail_fast_when_another_browser_might_work(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # An unrelated, unused browser being blocked (e.g. Arc, installed but never opened)
+ # must not cut off SSO in the browser the user is actually completing it in.
+ monkeypatch.setattr(metabase, "_detect_blocked_browsers", lambda browser: ["arc"])
+ monkeypatch.setattr(metabase, "_all_readable_browsers_blocked", lambda browser, blocked: False)
+ monkeypatch.setattr(
+ metabase,
+ "_find_valid_candidate",
+ lambda d, b, seen_warnings=None, rejected_headers=None: (None, False),
+ )
+ monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
+
+ call_count = {"n": 0}
+
+ def fake_monotonic() -> float:
+ call_count["n"] += 1
+ return 0.0 if call_count["n"] <= 2 else 100.0
+
+ monkeypatch.setattr(metabase.time, "monotonic", fake_monotonic)
+
+ with pytest.raises(click.ClickException, match="Timed out"):
+ metabase._wait_for_valid_cookie("metabase.example", None, timeout=10.0, interval=0.0)
+
+
+def test_wait_for_valid_cookie_keeps_polling_when_default_browser_is_safari(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Chrome is blocked, but Safari (the actual default) isn't directory-checked,
+ # so this must not fail fast on the first empty poll.
+ monkeypatch.setattr(metabase, "_detect_blocked_browsers", lambda browser: ["chrome"])
+ monkeypatch.setattr(metabase, "_default_https_browser", lambda: "safari")
+ monkeypatch.setattr(
+ metabase,
+ "_find_valid_candidate",
+ lambda d, b, seen_warnings=None, rejected_headers=None: (None, False),
+ )
+ monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
+
+ call_count = {"n": 0}
+
+ def fake_monotonic() -> float:
+ call_count["n"] += 1
+ return 0.0 if call_count["n"] <= 2 else 100.0
+
+ monkeypatch.setattr(metabase.time, "monotonic", fake_monotonic)
+
+ with pytest.raises(click.ClickException, match="Timed out"):
+ metabase._wait_for_valid_cookie("metabase.example", None, timeout=10.0, interval=0.0)
+
+
+def test_wait_for_valid_cookie_keeps_polling_and_notes_blocked_browser_once(
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ monkeypatch.setattr(metabase, "_detect_blocked_browsers", lambda browser: ["chrome"])
+ monkeypatch.setattr(metabase, "_all_readable_browsers_blocked", lambda browser, blocked: False)
+ monkeypatch.setattr(
+ metabase,
+ "_find_valid_candidate",
+ lambda d, b, seen_warnings=None, rejected_headers=None: (None, True),
+ )
+ monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
+
+ call_count = {"n": 0}
+
+ def fake_monotonic() -> float:
+ call_count["n"] += 1
+ return 0.0 if call_count["n"] <= 3 else 100.0
+
+ monkeypatch.setattr(metabase.time, "monotonic", fake_monotonic)
+
+ with pytest.raises(click.ClickException, match="Timed out"):
+ metabase._wait_for_valid_cookie("metabase.example", None, timeout=10.0, interval=0.0)
+
+ captured = capsys.readouterr()
+ assert captured.out.count("chrome") == 1
+
+
+def test_wait_for_valid_cookie_skips_expired_first_candidate_and_reaches_the_next_one(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ expired = {"metabase.SESSION": "old", "metabase.DEVICE": "old", "ph_int_auth-0": "old", "ph_int_auth-1": "old"}
+ valid = {"metabase.SESSION": "new", "metabase.DEVICE": "new", "ph_int_auth-0": "new", "ph_int_auth-1": "new"}
+ expired_header = metabase._format_cookie_header(expired)
+ valid_header = metabase._format_cookie_header(valid)
+ poll_count = {"n": 0}
+ check_calls: dict[str, int] = {}
+
+ def fake_iter_candidates(
+ domain: str, browser: str | None, seen_warnings: set[str] | None = None
+ ) -> Iterator[dict[str, str]]:
+ # A second profile with the real, valid session only shows up from the
+ # second poll onward (e.g. the user was still completing SSO there).
+ poll_count["n"] += 1
+ yield expired
+ if poll_count["n"] >= 2:
+ yield valid
+
+ def fake_probe_cookie(domain: str, header: str) -> bool:
+ # The expired header gets an outright rejection (a real backend would
+ # answer 401/302 for it), not a transient failure.
+ check_calls[header] = check_calls.get(header, 0) + 1
+ return header == valid_header
+
+ monkeypatch.setattr(metabase, "_detect_blocked_browsers", lambda browser: [])
+ monkeypatch.setattr(metabase, "_iter_cookie_candidates", fake_iter_candidates)
+ monkeypatch.setattr(metabase, "_probe_cookie", fake_probe_cookie)
+ monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
+
+ header = metabase._wait_for_valid_cookie("metabase.example", None, timeout=10.0, interval=0.0)
+
+ assert header == valid_header
+ # The expired header is checked once (poll 1), never rechecked on poll 2 once rejected.
+ assert check_calls[expired_header] == 1
+ assert check_calls[valid_header] == 1
+
+
+def test_wait_for_valid_cookie_retries_a_transient_probe_failure_and_then_succeeds(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ candidate = {"metabase.SESSION": "s", "metabase.DEVICE": "d", "ph_int_auth-0": "a0", "ph_int_auth-1": "a1"}
+ header = metabase._format_cookie_header(candidate)
+ monkeypatch.setattr(metabase, "_detect_blocked_browsers", lambda browser: [])
+ monkeypatch.setattr(
+ metabase, "_iter_cookie_candidates", lambda domain, browser, seen_warnings=None: iter([candidate])
+ )
+ # Poll 1: a network blip or a 5xx from the load balancer (None, inconclusive).
+ # Poll 2: the same header, now accepted.
+ probe_results = iter([None, True])
+ probe_calls: list[str] = []
+
+ def fake_probe(domain: str, h: str, timeout: float = 5.0) -> bool | None:
+ probe_calls.append(h)
+ return next(probe_results)
+
+ monkeypatch.setattr(metabase, "_probe_cookie", fake_probe)
+ monkeypatch.setattr(metabase.time, "sleep", lambda _: None)
+
+ result = metabase._wait_for_valid_cookie("metabase.example", None, timeout=10.0, interval=0.0)
+
+ assert result == header
+ assert probe_calls == [header, header]
+
+
def test_require_cookie_header_errors_when_missing(cache_dir: Path) -> None:
with pytest.raises(click.ClickException, match="No cached cookie"):
metabase._require_cookie_header("us")