: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(hogli): add browser-based PostHog auth for commands (#78518)
Raúl Negrón-Otero59b4ee8acdcb
diff --git a/.env.local.example b/.env.local.exampleindex 585cf1ae9749..24fe906a0a2d 100644--- a/.env.local.example+++ b/.env.local.example@@ -36,3 +36,12 @@# Use your own API keys instead of 1Password# OPENAI_API_KEY=sk-...++# ── hogli reading from the PostHog API ─────────+# Not needed for the ordinary case: `hogli posthog:login` signs in through your+# browser and caches a scoped, revocable token, with no key to mint. Set one of these+# only for an unattended caller (CI, a container, an agent that can't reach a browser).+# Env always wins over the cached login, so leaving a stale key here makes a fresh+# login look like it did nothing.+# POSTHOG_PERSONAL_API_KEY=phx_...+# POSTHOG_AUTH_HEADER=Bearer phx_...diff --git a/hogli.yaml b/hogli.yamlindex cf68a656d4ad..f4403ebe9028 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -855,6 +855,15 @@ quality:cmd: pnpm run --filter @posthog/mcp formatdescription: Format MCP filesauth:+ posthog:login:+ click: hogli_commands.posthog_auth_cli:posthog_login+ description: Sign hogli in to PostHog in your browser (no API key to mint)+ posthog:status:+ click: hogli_commands.posthog_auth_cli:posthog_status+ description: Show hogli's cached PostHog credential (host, scopes, expiry)+ posthog:logout:+ click: hogli_commands.posthog_auth_cli:posthog_logout+ description: Revoke and forget hogli's cached PostHog credentialmetabase:login:click: hogli_commands.metabase:metabase_logindescription: Log in to Metabase via SSO and cache the session cookiediff --git a/tools/hogli-commands/hogli_commands/posthog_auth.py b/tools/hogli-commands/hogli_commands/posthog_auth.pynew file mode 100644index 000000000000..5b3bc9e46113--- /dev/null+++ b/tools/hogli-commands/hogli_commands/posthog_auth.py@@ -0,0 +1,730 @@+"""Shared PostHog API auth for hogli commands, the way `github_auth` does for github.com.++ from hogli_commands import posthog_auth++ token = posthog_auth.token(scopes=("engineering_analytics:read",))++Three sources, in order:++1. ``POSTHOG_PERSONAL_API_KEY``, then ``POSTHOG_AUTH_HEADER`` (the name ``services/mcp`` has you+ export for mcp-remote). Either can be a literal line in ``.env.local``, which hogli loads on+ every invocation. Env wins so CI, containers, and an existing key keep working untouched.+2. A cached OAuth credential for that host, refreshed silently when the access token has aged out.+3. An interactive browser login, on a tty only.++The browser path is the RFC 8252 native-app flow. The client_id is the URL of the client metadata+document PostHog serves for hogli, so there is nothing to register and every machine authorizes as+the same named client. The code comes back to an ephemeral port on 127.0.0.1 with PKCE.+RFC 8628 device flow is not used because PostHog does not advertise that grant. A login always+prints the URL as well as opening it, and accepts the redirect typed back in, so it also finishes+on a machine whose browser lives somewhere else.++Credentials are cached per host at ``~/.config/posthog/oauth/<host>.json`` with mode 0600,+alongside the client that minted them, so one login serves every hogli command on that host. Logging out+revokes at the server before deleting the file, since a deleted file leaves a refresh token that+still mints access tokens for anyone holding a copy.++Nothing here opens a browser off a tty. A piped or agent-driven caller with no cached credential+gets ``AuthError`` carrying exit code 78 (sysexits ``EX_CONFIG``), so it can branch on the code+rather than on message text.+"""++from __future__ import annotations++import os+import sys+import json+import time+import queue+import base64+import select+import hashlib+import secrets+import threading+import webbrowser+import http.server+from collections.abc import Iterable, Sequence+from dataclasses import dataclass, field, replace+from pathlib import Path+from typing import Any+from urllib.parse import parse_qs, urlencode, urlparse++import click+import requests++DEFAULT_HOST = "https://us.posthog.com"++# sysexits.h EX_CONFIG. Distinct from 1 so a caller can tell "you have not set this up" from+# "the command ran and the answer is bad" without parsing prose.+EXIT_NOT_CONFIGURED = 78++KEY_ENV_VARS = ("POSTHOG_PERSONAL_API_KEY", "POSTHOG_AUTH_HEADER")++_CACHE_ROOT = Path.home() / ".config" / "posthog" / "oauth"++# PostHog serves hogli's client metadata document here, and its own URL is the client_id.+_METADATA_PATH = "api/oauth/hogli/client-metadata"+# The document registers the redirect without a port: RFC 8252 §7.3 requires the server to allow+# any port on a loopback redirect, so one entry covers whichever ephemeral port we get. 127.0.0.1+# rather than localhost because django-oauth-toolkit's port exemption lists the literal addresses.+_REDIRECT_PATH = "/callback"++# Refresh this far before the access token actually expires, so a slow request can't start on a+# valid token and arrive on an expired one.+_EXPIRY_MARGIN_SECONDS = 120.0++_LOGIN_TIMEOUT_SECONDS = 300.0+_HTTP_TIMEOUT_SECONDS = 30.0++_DONE_PAGE = b"""<!doctype html><meta charset=utf-8><title>hogli</title>+<body style="font:14px -apple-system,sans-serif;padding:3rem;text-align:center">+<h1 style="font-size:1.1rem">You're signed in</h1><p>Close this tab and return to your terminal.</p>+"""+++class AuthError(Exception):+ def __init__(self, message: str, *, exit_code: int = EXIT_NOT_CONFIGURED) -> None:+ super().__init__(message)+ self.message = message+ self.exit_code = exit_code+++@dataclass(frozen=True, kw_only=True)+class Credential:+ """One host's cached OAuth state: the client that minted the tokens, and the tokens.++ ``granted`` is what the server said it issued, which can be narrower than the ask, so a+ caller checks it rather than assuming the request survived consent.+ """++ host: str+ client_id: str+ access_token: str = field(repr=False)+ refresh_token: str | None = field(default=None, repr=False)+ expires_at: float | None = None+ granted: tuple[str, ...] = ()++ def is_fresh(self, *, now: float | None = None) -> bool:+ if self.expires_at is None:+ return True+ return (now if now is not None else time.time()) < self.expires_at - _EXPIRY_MARGIN_SECONDS++ def covers(self, scopes: Iterable[str]) -> bool:+ granted = set(self.granted)+ # An empty `granted` means the server reported no scopes, which is "unknown" rather than+ # "none", so it satisfies any ask.+ return not granted or set(scopes) <= granted++ def as_json(self) -> dict[str, Any]:+ return {+ "host": self.host,+ "client_id": self.client_id,+ "access_token": self.access_token,+ "refresh_token": self.refresh_token,+ "expires_at": self.expires_at,+ "granted": list(self.granted),+ }+++@dataclass(frozen=True, kw_only=True)+class ClientMetadata:+ """The client PostHog publishes for hogli: its id, and the scope ceiling it may ask for."""++ client_id: str+ scopes: tuple[str, ...]+++@dataclass(frozen=True, kw_only=True)+class Logout:+ """What a logout did. ``forgotten`` without ``revoked`` means the token still works."""++ forgotten: bool+ revoked: bool+ error: str | None = None+++@dataclass(frozen=True, kw_only=True)+class EnvironmentKey:+ """A personal API key found in the environment, and the variable it came from."""++ variable: str+ key: str = field(repr=False)+++def _normalize_host(host: str) -> str:+ return host.rstrip("/")+++def _cache_path(host: str) -> Path:+ """One file per host, so us, eu and a local stack can hold credentials at once.++ Only unreserved characters survive into the name, since the host has to be a valid filename.+ The scheme is part of the name because http://host and https://host are different origins+ holding different grants, and a name built from the netloc alone would hand one's token to+ the other.+ """+ parsed = urlparse(host)+ origin = f"{parsed.scheme}-{parsed.netloc}" if parsed.netloc else host+ slug = "".join(char if char.isalnum() else "-" for char in origin)+ return _CACHE_ROOT / f"{slug}.json"+++def load(host: str = DEFAULT_HOST) -> Credential | None:+ """The cached credential for a host, or None when absent, unreadable, or for another host.++ An unparseable file, or one missing a field because an older hogli wrote a narrower shape, is+ treated as absent rather than fatal: it is derived state, and re-authorizing is always there.+ """+ host = _normalize_host(host)+ try:+ raw = json.loads(_cache_path(host).read_text())+ except (OSError, ValueError):+ return None+ if not isinstance(raw, dict) or raw.get("host") != host:+ # Hosts differing only by URL path share a filename, which the slug cannot carry. A miss+ # sends the caller to a login; serving the other host's token would send its credential+ # to the wrong server.+ return None+ try:+ return Credential(+ host=host,+ client_id=str(raw["client_id"]),+ access_token=str(raw["access_token"]),+ refresh_token=raw.get("refresh_token"),+ expires_at=raw.get("expires_at"),+ granted=tuple(raw.get("granted") or ()),+ )+ except (KeyError, TypeError):+ return None+++def save(credential: Credential) -> None:+ """Persist a credential, readable only by its owner.++ Written to a temp file and renamed so a concurrent reader sees either the old file or the new+ one, never a half-written one. Mode 0600 is set at open() rather than after, so the token is+ never briefly world-readable on disk.+ """+ path = _cache_path(credential.host)+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ temp = path.with_name(f"{path.name}.{os.getpid()}.tmp")+ descriptor = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ try:+ with os.fdopen(descriptor, "w") as handle:+ json.dump(credential.as_json(), handle)+ os.replace(temp, path)+ finally:+ temp.unlink(missing_ok=True)+++def logout(host: str = DEFAULT_HOST) -> Logout:+ """Revoke a host's credential at the server, then drop it locally.++ Revocation goes first because the file is the only record of the token: dropping it first+ strands a live refresh token nobody can name. A failed revocation still drops the file, and+ reports that the grant is live so the caller can say where to finish it off.+ """+ host = _normalize_host(host)+ credential = load(host)+ path = _cache_path(host)+ existed = credential is not None or path.exists()+ failure: str | None = None+ if credential is not None:+ try:+ revoke(credential)+ except AuthError as exc:+ failure = exc.message+ path.unlink(missing_ok=True)+ return Logout(forgotten=existed, revoked=credential is not None and failure is None, error=failure)+++def _revoke_superseded(credential: Credential) -> None:+ """Revoke a credential a fresh login replaced, warning rather than raising: the login worked."""+ try:+ revoke(credential)+ except AuthError as exc:+ click.secho(+ f"Could not revoke the previous credential for {credential.host}: {exc.message}", fg="yellow", err=True+ )+ click.secho("It is still live. Revoke it under Settings → Connected applications.", fg="yellow", err=True)+++def revoke(credential: Credential) -> None:+ """Tell the server to drop the grant, so a copy of the token stops working.++ The refresh token goes when there is one, since it outlives the access token and mints more.+ PostHog's `revoke_token` override then sweeps every token and grant for that user and client,+ not just the one presented, so this must only ever run against a client hogli is done with.+ """+ hint = "refresh_token" if credential.refresh_token else "access_token"+ revoked = credential.refresh_token or credential.access_token+ _send(+ f"{credential.host}/oauth/revoke/",+ # A public client authenticates on client_id alone, with no secret to present.+ form_body={"token": revoked, "token_type_hint": hint, "client_id": credential.client_id},+ action="Revoking the credential",+ )+++def key_in_env() -> EnvironmentKey | None:+ """The personal API key set in the environment, with its variable, or None when neither is set.++ Carries both so `status` does not re-derive which variable won, since a second scan could+ disagree with this one about whether a whitespace-only value counts. ``POSTHOG_AUTH_HEADER``+ holds a whole ``Bearer <key>`` header value, so the scheme is stripped rather than sent twice.+ """+ for var in KEY_ENV_VARS:+ raw = (os.environ.get(var) or "").strip()+ if not raw:+ continue+ # hogli's dotenv loader assigns the raw value, so a quoted `.env.local` line arrives with+ # its quotes attached and the `Bearer ` prefix no longer matches.+ if len(raw) > 1 and raw[0] == raw[-1] and raw[0] in "\"'":+ raw = raw[1:-1].strip()+ return EnvironmentKey(variable=var, key=raw.removeprefix("Bearer ").strip())+ return None+++def key_from_env() -> str | None:+ """Just the key, for callers that do not care which variable carried it."""+ found = key_in_env()+ return found.key if found else None+++def token(+ *,+ scopes: Sequence[str],+ host: str = DEFAULT_HOST,+ interactive: bool | None = None,+) -> str:+ """A bearer token for ``host``, good for ``scopes``. The one function callers need.++ ``interactive`` defaults to whether stdin is a tty. Off, a missing or scope-short credential+ raises rather than trying to open a browser: a piped caller cannot answer a consent screen,+ and blocking for five minutes on a login nobody can see is worse than failing fast.+ """+ host = _normalize_host(host)+ if key := key_from_env():+ return key++ credential = load(host)+ if credential is not None and credential.covers(scopes):+ if credential.is_fresh():+ return credential.access_token+ if refreshed := _refresh(credential):+ save(refreshed)+ return refreshed.access_token++ if interactive is None:+ interactive = sys.stdin.isatty()+ if not interactive:+ if credential is not None and not credential.covers(scopes):+ missing = " ".join(scope for scope in scopes if scope not in credential.granted)+ headline = f"hogli is signed in to {host} but not for {missing}."+ command = f"`hogli posthog:login --scope {missing}`"+ else:+ headline = f"hogli is not signed in to {host}."+ command = "`hogli posthog:login`"+ raise AuthError(+ f"{headline}\n"+ f" Run {command} once. It opens a browser and asks for no API key.\n"+ f" Or set {KEY_ENV_VARS[0]} for an unattended caller."+ )+ return login(scopes=scopes, host=host).access_token+++def login(*, scopes: Sequence[str], host: str = DEFAULT_HOST) -> Credential:+ """Run the browser authorization flow and cache the result."""+ host = _normalize_host(host)+ wanted = tuple(dict.fromkeys(scopes))+ if not wanted:+ raise AuthError("A login needs at least one scope to ask for.", exit_code=1)+ if not sys.stdin.isatty():+ # A browser opened here answers to nobody, and the login would sit out its whole timeout.+ raise AuthError(+ f"A login to {host} needs a terminal, and this one is not attached to any.\n"+ f" Run `hogli posthog:login` yourself, or set {KEY_ENV_VARS[0]} for this caller."+ )++ superseded = load(host)+ client = _client(host)+ refused = [scope for scope in wanted if scope not in client.scopes]+ if refused:+ # Checked before the browser opens, since /authorize clamps to the published ceiling and+ # consenting would mint a token missing these, failing only after the user's click.+ raise AuthError(+ f"{host} does not offer {' '.join(refused)} to hogli.\n"+ f" It publishes {' '.join(client.scopes)}. A new scope goes in the client metadata "+ "document PostHog serves, not here."+ )++ verifier = secrets.token_urlsafe(64)+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()+ state = secrets.token_urlsafe(24)++ with _CallbackServer() as server:+ redirect_uri = server.redirect_uri+ url = f"{host}/oauth/authorize/?" + urlencode(+ {+ "client_id": client.client_id,+ "response_type": "code",+ "redirect_uri": redirect_uri,+ "scope": " ".join(wanted),+ "state": state,+ "code_challenge": challenge,+ "code_challenge_method": "S256",+ }+ )+ code = server.collect(url, state=state)++ credential = _exchange(+ host,+ client_id=client.client_id,+ code=code,+ verifier=verifier,+ redirect_uri=redirect_uri,+ asked=wanted,+ )+ save(credential)+ if superseded is not None and superseded.client_id != credential.client_id:+ # A credential from another client, which the save above just made unreachable. Revoking+ # only when the client differs is the whole condition: the server sweeps every token for a+ # client, so revoking a same-client credential would take the token just minted with it.+ _revoke_superseded(superseded)+ if not credential.covers(wanted):+ # The ceiling check above cannot see a narrowing that happens at consent time, so this is+ # the backstop. Returning here would hand back a token quietly missing what was asked for,+ # and the failure would surface later as an unactionable 403 on a scope check.+ missing = " ".join(scope for scope in wanted if scope not in credential.granted)+ raise AuthError(f"{host} granted a token without {missing}.")+ return credential+++def _client(host: str) -> ClientMetadata:+ """The client PostHog publishes for hogli, fetched from the host itself.++ The document's own URL is the client_id, so there is nothing to register and every machine+ authorizes as the same named client. Fetched rather than hardcoded so the scope ceiling comes+ from the server that enforces it, and so a host too old to serve one says so before a browser+ opens on an /authorize that cannot resolve the client.+ """+ url = f"{host}/{_METADATA_PATH}"+ body = _get(url, action="Reading hogli's client metadata")+ if body.get("client_id") != url:+ raise AuthError(f"{host} published a client metadata document for a different client_id.")+ scopes = body.get("com.posthog", {}).get("scopes") if isinstance(body.get("com.posthog"), dict) else None+ if not scopes:+ raise AuthError(f"{host} published no scopes for hogli, so a login could ask for nothing.")+ return ClientMetadata(client_id=url, scopes=tuple(str(scope) for scope in scopes))+++def _exchange(+ host: str,+ *,+ client_id: str,+ code: str,+ verifier: str,+ redirect_uri: str,+ asked: tuple[str, ...],+) -> Credential:+ body = _post(+ f"{host}/oauth/token/",+ form_body={+ "grant_type": "authorization_code",+ "code": code,+ "redirect_uri": redirect_uri,+ "client_id": client_id,+ "code_verifier": verifier,+ },+ action="Exchanging the authorization code",+ )+ return _credential_from(+ body,+ host=host,+ client_id=client_id,+ # RFC 6749 §5.1 makes `scope` optional when it matches the request, so an omission means+ # the ask was granted whole. Recording nothing instead would read as "scopes unknown".+ fallback_granted=asked,+ )+++def _refresh(credential: Credential) -> Credential | None:+ """A renewed credential, or None when the refresh token is spent.++ None rather than raising: an expired or revoked grant is an ordinary end of life, and the+ caller's next step (log in again, or fail with the not-configured code) is the same as if+ nothing had been cached. A transient failure raises instead, because the grant may still be+ good and "not signed in" would be false.+ """+ if not credential.refresh_token:+ return None+ try:+ body = _post(+ f"{credential.host}/oauth/token/",+ form_body={+ "grant_type": "refresh_token",+ "refresh_token": credential.refresh_token,+ "client_id": credential.client_id,+ },+ action="Refreshing the access token",+ )+ except AuthError as exc:+ # Only a definitive OAuth refusal (a 4xx such as invalid_grant) proves the grant spent.+ # A network failure or a 5xx says nothing about it, so the error surfaces as itself+ # rather than sending the caller through a needless re-login.+ if exc.exit_code != EXIT_NOT_CONFIGURED:+ raise+ return None+ return _credential_from(+ body,+ host=credential.host,+ client_id=credential.client_id,+ # Refresh-token rotation is optional; keep the working one when the server reissues none.+ fallback_refresh=credential.refresh_token,+ fallback_granted=credential.granted,+ )+++def _credential_from(+ body: dict[str, Any],+ *,+ host: str,+ client_id: str,+ fallback_refresh: str | None = None,+ fallback_granted: tuple[str, ...] = (),+) -> Credential:+ access_token = body.get("access_token")+ if not access_token:+ raise AuthError(f"{host} returned no access token.")+ expires_in = body.get("expires_in")+ granted = tuple(str(body["scope"]).split()) if body.get("scope") else fallback_granted+ return Credential(+ host=host,+ client_id=client_id,+ access_token=str(access_token),+ refresh_token=str(body.get("refresh_token") or fallback_refresh or "") or None,+ expires_at=time.time() + float(expires_in) if expires_in else None,+ granted=granted,+ )+++def _post(+ url: str,+ *,+ action: str,+ json_body: dict[str, Any] | None = None,+ form_body: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """One unauthenticated POST to an OAuth endpoint whose answer is the object it returns."""+ body = _send(url, action=action, json_body=json_body, form_body=form_body)+ if not body:+ raise AuthError(f"{action} returned no object.")+ return body+++def _get(url: str, *, action: str) -> dict[str, Any]:+ """One unauthenticated GET, for the metadata document that names the client."""+ try:+ response = requests.get(url, timeout=_HTTP_TIMEOUT_SECONDS)+ except requests.RequestException as exc:+ raise AuthError(f"{action} could not reach {url}: {exc}", exit_code=1) from exc+ if response.status_code == 404:+ # Named rather than left as a bare 404, because the fix is a PostHog version, not anything+ # the user did wrong.+ raise AuthError(+ f"{url} is not served by this PostHog.\n"+ " A browser login needs a version that publishes hogli's client metadata document.\n"+ f" Set {KEY_ENV_VARS[0]} to use a personal API key against this host instead."+ )+ body = _body_of(response, action=action)+ if not body:+ raise AuthError(f"{action} returned no object.")+ return body+++def _send(+ url: str,+ *,+ action: str,+ json_body: dict[str, Any] | None = None,+ form_body: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """One unauthenticated POST to an OAuth endpoint. RFC 7009 revocation answers 200 with no body."""+ try:+ response = requests.post(url, json=json_body, data=form_body, timeout=_HTTP_TIMEOUT_SECONDS)+ except requests.RequestException as exc:+ raise AuthError(f"{action} could not reach {url}: {exc}", exit_code=1) from exc+ return _body_of(response, action=action)+++def _body_of(response: requests.Response, *, action: str) -> dict[str, Any]:+ """The JSON object a response carries, empty when it carries none, raising on a 4xx or 5xx."""+ try:+ body = response.json()+ except ValueError:+ body = {}+ # Before any .get(): a proxy or load balancer can answer with valid JSON that is not an object,+ # and an AttributeError here escapes the AuthError handling every caller relies on.+ if not isinstance(body, dict):+ body = {}+ if response.status_code >= 400:+ # OAuth errors are `error` / `error_description`; DRF's are `detail`.+ detail = body.get("error_description") or body.get("error") or body.get("detail") or response.text[:200]+ # A 5xx means the server or a proxy in front of it is unhealthy, not that anything here+ # is set up wrong, so it carries the plain failure code rather than EX_CONFIG.+ code = 1 if response.status_code >= 500 else EXIT_NOT_CONFIGURED+ raise AuthError(f"{action} failed ({response.status_code}): {detail}", exit_code=code)+ return body+++class _RedirectServer(http.server.HTTPServer):+ """Carries the redirect's query from the handler back to the waiting login."""++ query: dict[str, list[str]] | None = None+++class _Handler(http.server.BaseHTTPRequestHandler):+ """Captures the one redirect we are waiting for and ignores everything else.++ A browser also asks for /favicon.ico and may prefetch, so a handler that treated any request+ as the callback would end the wait on the wrong one. Only the registered path counts.+ """++ server: _RedirectServer++ # Without this the read blocks forever on a socket that connects and sends nothing, and the+ # single-threaded server never returns to check the login deadline.+ timeout = 10.0++ def do_GET(self) -> None:+ parsed = urlparse(self.path)+ if parsed.path != _REDIRECT_PATH:+ self.send_error(404)+ return+ self.server.query = parse_qs(parsed.query)+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.send_header("Content-Length", str(len(_DONE_PAGE)))+ self.end_headers()+ self.wfile.write(_DONE_PAGE)++ def log_message(self, *args: Any) -> None:+ """Silence the default stderr access log; it is noise around a browser handoff."""+++class _CallbackServer:+ """A loopback listener for one authorization redirect.++ Bound to port 0, so the OS picks a free port and two logins can never collide. RFC 8252 §7.3+ obliges the server to accept whichever port that is against the portless registered URI.+ """++ def __init__(self) -> None:+ self._server = _RedirectServer(("127.0.0.1", 0), _Handler)+ self.redirect_uri = f"http://127.0.0.1:{self._server.server_port}{_REDIRECT_PATH}"++ def __enter__(self) -> _CallbackServer:+ return self++ def __exit__(self, *exc: object) -> None:+ self._server.server_close()++ def collect(self, url: str, *, state: str) -> str:+ """Serve until the redirect arrives, then return its authorization code."""+ # Printed as well as opened, because a devbox over ssh is indistinguishable from a laptop+ # here, and there the open does nothing.+ click.echo(f"Approve hogli in your browser:\n {url}", err=True)+ # On a thread because `webbrowser.open` blocks until the browser exits for a terminal-mode+ # browser, or anything $BROWSER points at that doesn't detach. In the foreground it would+ # deadlock on the redirect only this listener can serve.+ threading.Thread(target=webbrowser.open, args=(url,), daemon=True).start()+ return self._await_code(state=state)++ def _await_code(self, *, state: str) -> str:+ deadline = time.monotonic() + _LOGIN_TIMEOUT_SECONDS+ self._server.timeout = 1.0+ done = threading.Event()+ pasted = _pasted_redirects(done)+ try:+ while self._server.query is None:+ if pasted is not None and not pasted.empty():+ return _code_from(pasted.get(), state=state)+ if time.monotonic() > deadline:+ raise AuthError("Timed out waiting for the browser to come back.", exit_code=1)+ self._server.handle_request()+ return _code_from(self._server.query, state=state)+ finally:+ # Releases the reader, which would otherwise hold stdin for the life of the process and+ # eat the next line a command prompts for.+ done.set()+++def _pasted_redirects(done: threading.Event) -> queue.Queue[dict[str, list[str]]] | None:+ """Redirects typed back in, or None when there is no terminal to read from.++ A browser on another machine cannot reach this listener, so its redirect fails and the code+ exists only in the address bar of a page that never loaded. Read alongside the listener rather+ than instead of it, because which one the redirect reaches cannot be detected from here.+ """+ if not _readable_terminal():+ return None+ click.echo("If your browser is on another machine, paste the address it lands on:", err=True)+ queued: queue.Queue[dict[str, list[str]]] = queue.Queue()+ threading.Thread(target=_read_redirect, args=(queued, done), daemon=True).start()+ return queued+++def _readable_terminal() -> bool:+ """Whether this process may read stdin, rather than only whether stdin is a terminal.++ Reading a terminal from a background process group raises SIGTTIN, which by default stops the+ whole process, so `hogli posthog:login &` would hang on the read instead of finishing on+ the listener the browser can still reach.+ """+ if not sys.stdin.isatty():+ return False+ try:+ return os.tcgetpgrp(sys.stdin.fileno()) == os.getpgrp()+ except (OSError, AttributeError):+ return False+++def _read_redirect(queued: queue.Queue[dict[str, list[str]]], done: threading.Event) -> None:+ """Read lines until one carries an authorization redirect, queueing its query."""+ while not done.is_set():+ # Polled rather than blocking outright, so the login ending releases stdin for whatever+ # the command does next.+ if not select.select([sys.stdin], [], [], 0.5)[0]:+ continue+ line = sys.stdin.readline()+ if not line:+ return+ pasted = line.strip()+ # The address may arrive whole or as the query alone, depending on what the user selected.+ query = parse_qs(urlparse(pasted).query or pasted)+ if query.get("code") or query.get("error"):+ queued.put(query)+ return+ if pasted:+ click.echo("That address carried no authorization code. Paste the whole thing, including ?code=.", err=True)+++def _code_from(query: dict[str, list[str]], *, state: str) -> str:+ """The authorization code from a redirect's query, once it proves it answers our request."""+ if error := query.get("error"):+ described = (query.get("error_description") or [""])[0]+ raise AuthError(f"Authorization was refused: {error[0]}{f' ({described})' if described else ''}")+ # Without this the flow would accept a code from an authorization request we never made.+ if not secrets.compare_digest((query.get("state") or [""])[0], state):+ raise AuthError("The redirect carried the wrong state. Start the login again.")+ code = (query.get("code") or [""])[0]+ if not code:+ raise AuthError("The redirect carried no authorization code.")+ return code+++def redact(credential: Credential) -> Credential:+ """A copy safe to print, so a caller rendering a credential need not track which fields are secret."""+ return replace(+ credential, access_token="<redacted>", refresh_token="<redacted>" if credential.refresh_token else None+ )diff --git a/tools/hogli-commands/hogli_commands/posthog_auth_cli.py b/tools/hogli-commands/hogli_commands/posthog_auth_cli.pynew file mode 100644index 000000000000..127e474ae889--- /dev/null+++ b/tools/hogli-commands/hogli_commands/posthog_auth_cli.py@@ -0,0 +1,132 @@+"""`hogli posthog:*`, which signs hogli in to a PostHog host once, for every command.++The commands live here so `posthog_auth` stays a plain helper: a command that just needs a token+imports that module and picks up none of these.++ hogli posthog:login # opens a browser; no API key to mint+ hogli posthog:status # which host, which scopes, how long the token has left+ hogli posthog:logout # revoke the grant, then drop the local credential+"""++from __future__ import annotations++import json+import time+from typing import NoReturn++import click++from hogli_commands import posthog_auth++# Enough to read CI health, which is what the first caller needs. A command wanting more passes its+# own scopes to `posthog_auth.token`, up to the ceiling the host publishes for hogli.+_DEFAULT_SCOPES = ("engineering_analytics:read",)++_HOST_OPTION = click.option(+ "--host",+ default=posthog_auth.DEFAULT_HOST,+ show_default=True,+ help="PostHog host to authenticate against (e.g. https://eu.posthog.com).",+)+++def _fail(error: posthog_auth.AuthError) -> NoReturn:+ click.secho(error.message, fg="red", err=True)+ raise SystemExit(error.exit_code)+++def _lifetime(expires_at: float | None) -> str:+ """What the access token has left, at the coarsest unit that still reads usefully.++ Tokens run to days, and minutes alone renders a week as "expires in 10079m", which a reader+ has to divide before it means anything.+ """+ if expires_at is None:+ return "no expiry reported"+ remaining = int(expires_at - time.time())+ if remaining <= 0:+ return "expired"+ for unit, size in (("d", 86400), ("h", 3600), ("m", 60)):+ if remaining >= size:+ return f"expires in {remaining // size}{unit}"+ return "expires in under a minute"++[email protected](name="posthog:login", help="Sign hogli in to PostHog in your browser.")+@_HOST_OPTION+ "--scope",+ "scopes",+ multiple=True,+ help=f"API scope to request; repeatable. Defaults to {' '.join(_DEFAULT_SCOPES)}.",+)+def posthog_login(host: str, scopes: tuple[str, ...]) -> None:+ try:+ credential = posthog_auth.login(scopes=scopes or _DEFAULT_SCOPES, host=host)+ except posthog_auth.AuthError as exc:+ _fail(exc)+ click.secho(f"Signed in to {credential.host}.", fg="green")+ click.echo(f" scopes {' '.join(credential.granted) or '(none reported)'}")+ if found := posthog_auth.key_in_env():+ # Otherwise the login appears to have done nothing: every command reads the env var first.+ click.secho(+ f"\nNote: {found.variable} is set in your environment, and it wins over this credential.\n"+ f"Unset {found.variable} to use the browser login.",+ fg="yellow",+ )++[email protected](name="posthog:status", help="Show hogli's cached PostHog credential.")+@_HOST_OPTION[email protected]("--json", "as_json", is_flag=True, help="Emit JSON instead of a table.")+def posthog_status(host: str, as_json: bool) -> None:+ host = host.rstrip("/")+ credential = posthog_auth.load(host)+ env_key = posthog_auth.key_from_env()+ # Both output shapes report the same verdict: a script gating on the exit code must not read+ # "configured" just because it asked for JSON.+ configured = bool(env_key or credential)+ if as_json:+ click.echo(+ json.dumps(+ {+ "host": host,+ "environment_key_set": bool(env_key),+ "credential": posthog_auth.redact(credential).as_json() if credential else None,+ },+ indent=2,+ )+ )+ raise SystemExit(0 if configured else posthog_auth.EXIT_NOT_CONFIGURED)++ if found := posthog_auth.key_in_env():+ click.echo(f"environment {found.variable} is set, and it wins over any cached credential")+ if credential is None:+ click.echo(f"credential none cached for {host}. Run `hogli posthog:login`")+ raise SystemExit(0 if env_key else posthog_auth.EXIT_NOT_CONFIGURED)++ lifetime = _lifetime(credential.expires_at)+ click.echo(f"host {credential.host}")+ click.echo(f"client {credential.client_id}")+ click.echo(f"scopes {' '.join(credential.granted) or '(none reported)'}")+ click.echo(f"access token {lifetime}" + (", refreshable" if credential.refresh_token else ", not refreshable"))++[email protected](name="posthog:logout", help="Revoke and forget hogli's cached PostHog credential.")+@_HOST_OPTION+def posthog_logout(host: str) -> None:+ host = host.rstrip("/")+ result = posthog_auth.logout(host)+ if found := posthog_auth.key_in_env():+ # This is the command where "signed out" is acted on, and the key keeps every command signed in.+ click.secho(f"Note: {found.variable} is still set, and hogli keeps using it.", fg="yellow")+ if not result.forgotten:+ click.echo(f"No cached credential for {host}.")+ return+ if result.revoked:+ click.echo(f"Signed out of {host}. The token it held no longer works.")+ return+ click.echo(f"Forgot the cached credential for {host}.")+ if result.error:+ click.secho(result.error, fg="yellow", err=True)+ click.secho("The token may still work. Revoke it under Settings → Connected applications.", fg="yellow", err=True)diff --git a/tools/hogli-commands/hogli_commands/tests/test_posthog_auth.py b/tools/hogli-commands/hogli_commands/tests/test_posthog_auth.pynew file mode 100644index 000000000000..d1097b53f82d--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_posthog_auth.py@@ -0,0 +1,644 @@+from __future__ import annotations++import os+import json+import stat+import time+import threading+from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path+from typing import Any++import pytest+from unittest.mock import patch++import requests+from click.testing import CliRunner+from hogli_commands import posthog_auth, posthog_auth_cli++_HOST = "https://us.posthog.com"+_SCOPE = "engineering_analytics:read"++[email protected](autouse=True)+def cache_dir(tmp_path: Path) -> Iterator[Path]:+ # Redirect the cache so no test reads or writes the developer's real ~/.config/posthog.+ with patch.object(posthog_auth, "_CACHE_ROOT", tmp_path / "oauth"):+ yield tmp_path / "oauth"++[email protected](autouse=True)+def no_env_key(monkeypatch: pytest.MonkeyPatch) -> None:+ for var in posthog_auth.KEY_ENV_VARS:+ monkeypatch.delenv(var, raising=False)+++def runner() -> CliRunner:+ return CliRunner()++[email protected](autouse=True)+def a_terminal() -> Iterator[None]:+ # `login` refuses off a tty, and pytest's stdin is not one. The paste path stays off regardless,+ # since `_readable_terminal` also needs a real fd.+ with patch.object(posthog_auth.sys.stdin, "isatty", lambda: True):+ yield+++_CLIENT_ID = f"{_HOST}/api/oauth/hogli/client-metadata"+++def _metadata(*scopes: str) -> Any:+ # Stands in for the client metadata document PostHog serves, which names hogli and its ceiling.+ document = {"client_id": _CLIENT_ID, "com.posthog": {"scopes": list(scopes or (_SCOPE,))}}+ return patch.object(posthog_auth.requests, "get", lambda url, timeout: _Response(200, document))+++def _credential(**overrides: Any) -> posthog_auth.Credential:+ fields: dict[str, Any] = {+ "host": _HOST,+ "client_id": "client-abc",+ "access_token": "pha_cached",+ "refresh_token": "phr_cached",+ "expires_at": time.time() + 3600,+ "granted": (_SCOPE,),+ }+ return posthog_auth.Credential(**{**fields, **overrides})+++def _endpoint_of(url: str) -> str:+ tail = url.rstrip("/").rsplit("/", 1)[-1]+ return tail if tail in ("register", "revoke") else "token"+++def _port_from(uri: str) -> int:+ return int(uri.rsplit(":", 1)[1].split("/")[0])+++@contextmanager+def _terminal(text: str) -> Iterator[None]:+ # A real pipe rather than a StringIO, because the reader polls with select() and needs an fd.+ # `_readable_terminal` is stubbed since a pipe is not a terminal and pytest's own stdin is not+ # one either, so without this the paste path never starts.+ read_fd, write_fd = os.pipe()+ os.write(write_fd, text.encode())+ try:+ with os.fdopen(read_fd) as stdin:+ with patch.object(posthog_auth.sys, "stdin", stdin), _paste_path(True):+ yield+ finally:+ os.close(write_fd)+++def _paste_path(available: bool) -> Any:+ return patch.object(posthog_auth, "_readable_terminal", lambda: available)+++# Stands in for `requests.post`, recording every call and replaying a canned response per endpoint,+# so a test can assert both on what was sent and on which endpoints were reached at all.+class _Poster:+ def __init__(self, **bodies: Any) -> None:+ self.calls: list[dict[str, Any]] = []+ self._bodies = bodies++ def __call__(self, url: str, *, json: Any = None, data: Any = None, timeout: float) -> Any:+ self.calls.append({"url": url, "json": json, "data": data})+ status, body = self._bodies.get(_endpoint_of(url), (200, {}))+ return _Response(status, body)++ def body_for(self, endpoint: str) -> dict[str, Any]:+ call = next(call for call in self.calls if _endpoint_of(call["url"]) == endpoint)+ return call["json"] or call["data"] or {}++ def reached(self, endpoint: str) -> bool:+ return any(_endpoint_of(call["url"]) == endpoint for call in self.calls)+++class _Response:+ def __init__(self, status_code: int, payload: Any) -> None:+ self.status_code = status_code+ self._payload = payload+ self.text = json.dumps(payload)++ def json(self) -> Any:+ # A None payload models a response that carries no JSON at all.+ if self._payload is None:+ raise ValueError("no body")+ return self._payload+++def _fake_browser(query: dict[str, list[str]] | None = None) -> Any:+ # Stands in for the browser, answering the pending authorization with a matching redirect.+ def collect(self: Any, url: str, *, state: str) -> str:+ return posthog_auth._code_from(query or {"code": ["auth-code"], "state": [state]}, state=state)++ return patch.object(posthog_auth._CallbackServer, "collect", collect)+++# --- env-var ladder: the path CI and unattended agents take -------------------------------------+++ "env, expected",+ [+ ({"POSTHOG_PERSONAL_API_KEY": "phx_direct"}, "phx_direct"),+ ({"POSTHOG_AUTH_HEADER": "Bearer phx_from_header"}, "phx_from_header"),+ ({"POSTHOG_AUTH_HEADER": "phx_bare_header"}, "phx_bare_header"),+ ({"POSTHOG_PERSONAL_API_KEY": "phx_wins", "POSTHOG_AUTH_HEADER": "Bearer phx_loses"}, "phx_wins"),+ ],+)+def test_environment_key_ladder(monkeypatch: pytest.MonkeyPatch, env: dict[str, str], expected: str) -> None:+ for var, value in env.items():+ monkeypatch.setenv(var, value)+ assert posthog_auth.token(scopes=[_SCOPE], host=_HOST) == expected++[email protected]("raw", ['"Bearer phx_quoted"', "'Bearer phx_quoted'", '"phx_quoted"', "Bearer phx_quoted"])+def test_a_quoted_environment_value_still_yields_the_bare_key(monkeypatch: pytest.MonkeyPatch, raw: str) -> None:+ # hogli's dotenv loader assigns the raw value, so a quoted `.env.local` line arrives with its+ # quotes attached, the `Bearer ` prefix stops matching, and the key goes out to PostHog quoted.+ monkeypatch.setenv("POSTHOG_AUTH_HEADER", raw)+ assert posthog_auth.key_from_env() == "phx_quoted"+++ "env, expected_source",+ [+ ({"POSTHOG_PERSONAL_API_KEY": "phx_a"}, "POSTHOG_PERSONAL_API_KEY"),+ ({"POSTHOG_AUTH_HEADER": "Bearer phx_b"}, "POSTHOG_AUTH_HEADER"),+ # Whitespace-only does not count as set. A second scan using bare truthiness reported this+ # as the source while the key actually came from the other variable.+ ({"POSTHOG_PERSONAL_API_KEY": " ", "POSTHOG_AUTH_HEADER": "phx_b"}, "POSTHOG_AUTH_HEADER"),+ ],+)+def test_the_reported_environment_source_is_the_one_the_key_came_from(+ monkeypatch: pytest.MonkeyPatch, env: dict[str, str], expected_source: str+) -> None:+ for var, value in env.items():+ monkeypatch.setenv(var, value)+ found = posthog_auth.key_in_env()+ assert found is not None and found.variable == expected_source+++def test_environment_key_wins_over_a_cached_credential(monkeypatch: pytest.MonkeyPatch) -> None:+ # An explicit key is an override, so a stale cache silently outranking it would be unexplainable.+ posthog_auth.save(_credential())+ monkeypatch.setenv("POSTHOG_PERSONAL_API_KEY", "phx_explicit")+ assert posthog_auth.token(scopes=[_SCOPE], host=_HOST) == "phx_explicit"+++# --- cache: the path every command after the first login takes ----------------------------------+++def test_a_fresh_cached_credential_is_reused_without_any_request() -> None:+ posthog_auth.save(_credential())+ with patch.object(posthog_auth.requests, "post", side_effect=AssertionError("must not call the network")):+ assert posthog_auth.token(scopes=[_SCOPE], host=_HOST) == "pha_cached"+++def test_the_credential_file_is_owner_only() -> None:+ posthog_auth.save(_credential())+ path = posthog_auth._cache_path(_HOST)+ # The file holds a bearer token, so a default-umask 0644 would expose it to every local process.+ assert stat.S_IMODE(path.stat().st_mode) == 0o600+++ "other_host",+ [+ # us and eu are different accounts, so one overwriting the other would log you out sideways.+ "https://eu.posthog.com",+ # http and https on one netloc are different origins, so a slug built from the netloc+ # alone would let one login overwrite and serve the other.+ "http://us.posthog.com",+ ],+)+def test_hosts_are_cached_separately(other_host: str) -> None:+ posthog_auth.save(_credential())+ posthog_auth.save(_credential(host=other_host, access_token="pha_other"))+ ours, theirs = posthog_auth.load(_HOST), posthog_auth.load(other_host)+ assert ours is not None and ours.access_token == "pha_cached"+ assert theirs is not None and theirs.access_token == "pha_other"+++def test_a_cache_file_recorded_for_another_host_reads_as_absent() -> None:+ # Hosts differing only by URL path slug to one filename. A miss costs a login; serving the+ # file anyway would send one host's token to the other.+ posthog_auth.save(_credential(host="https://proxy.example.com/us"))+ assert posthog_auth.load("https://proxy.example.com/eu") is None++[email protected]("content", ["not json at all", '["not", "an", "object"]', f'{{"host": "{_HOST}"}}'])+def test_an_unreadable_cache_reads_as_absent(content: str) -> None:+ # The cache is derived state, so a corrupt or older-shaped file must send you to a login rather+ # than crash the command that asked for a token.+ path = posthog_auth._cache_path(_HOST)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content)+ assert posthog_auth.load(_HOST) is None+++def test_an_expired_credential_refreshes_and_persists_the_new_tokens() -> None:+ posthog_auth.save(_credential(access_token="pha_old", expires_at=time.time() - 10))+ poster = _Poster(token=(200, {"access_token": "pha_new", "refresh_token": "phr_new", "expires_in": 3600}))+ with patch.object(posthog_auth.requests, "post", poster):+ assert posthog_auth.token(scopes=[_SCOPE], host=_HOST) == "pha_new"+ assert poster.body_for("token")["grant_type"] == "refresh_token"+ stored = posthog_auth.load(_HOST)+ assert stored is not None and stored.access_token == "pha_new" and stored.refresh_token == "phr_new"+++def test_a_refresh_that_reissues_no_refresh_token_keeps_the_working_one() -> None:+ # Rotation is optional, so dropping the old token against a non-rotating server would force a+ # re-login on every expiry.+ posthog_auth.save(_credential(expires_at=time.time() - 10))+ with patch.object(posthog_auth.requests, "post", _Poster(token=(200, {"access_token": "pha_new"}))):+ posthog_auth.token(scopes=[_SCOPE], host=_HOST)+ stored = posthog_auth.load(_HOST)+ assert stored is not None and stored.refresh_token == "phr_cached"+++def test_a_credential_expiring_within_the_margin_refreshes_early() -> None:+ # A token with seconds left would otherwise be handed to a request that outlives it.+ posthog_auth.save(_credential(access_token="pha_old", expires_at=time.time() + 30))+ with patch.object(posthog_auth.requests, "post", _Poster(token=(200, {"access_token": "pha_new"}))):+ assert posthog_auth.token(scopes=[_SCOPE], host=_HOST) == "pha_new"+++# --- non-interactive callers: agents and pipes ---------------------------------------------------+++def test_a_non_interactive_caller_never_opens_a_browser() -> None:+ # Agents run this piped. Blocking five minutes on a consent screen nobody can see is worse than+ # exiting with a code the caller can branch on.+ with patch.object(posthog_auth.webbrowser, "open", side_effect=AssertionError("must not open")):+ with pytest.raises(posthog_auth.AuthError) as caught:+ posthog_auth.token(scopes=[_SCOPE], host=_HOST, interactive=False)+ assert caught.value.exit_code == posthog_auth.EXIT_NOT_CONFIGURED+ assert "posthog:login" in caught.value.message+++def test_a_dead_refresh_token_reports_not_configured_rather_than_the_http_error() -> None:+ # The caller's next step is a login either way, so a spent grant must reach the same branch as no+ # cached credential at all.+ posthog_auth.save(_credential(expires_at=time.time() - 10))+ with patch.object(posthog_auth.requests, "post", _Poster(token=(400, {"error": "invalid_grant"}))):+ with pytest.raises(posthog_auth.AuthError) as caught:+ posthog_auth.token(scopes=[_SCOPE], host=_HOST, interactive=False)+ assert caught.value.exit_code == posthog_auth.EXIT_NOT_CONFIGURED++[email protected]("payload", [["gateway", "down"], None])+def test_a_non_object_error_body_reports_the_status_instead_of_crashing(payload: Any) -> None:+ # A proxy or load balancer can answer with valid JSON that is not an object, or with no JSON at+ # all. Reading `detail` off a list raises AttributeError, which escapes the AuthError handling+ # every caller relies on.+ posthog_auth.save(_credential(expires_at=time.time() - 10))+ with patch.object(posthog_auth.requests, "post", _Poster(token=(502, payload))):+ with pytest.raises(posthog_auth.AuthError) as caught:+ posthog_auth.token(scopes=[_SCOPE], host=_HOST, interactive=False)+ assert "502" in caught.value.message+++def _unreachable_post(*args: Any, **kwargs: Any) -> Any:+ raise requests.ConnectionError("connection refused")+++ "post, expected",+ [+ (_unreachable_post, "could not reach"),+ (_Poster(token=(503, {"detail": "unavailable"})), "503"),+ ],+)+def test_a_transient_refresh_failure_is_not_reported_as_signed_out(post: Any, expected: str) -> None:+ # A timeout or a proxy 5xx says nothing about the grant. Treating it as spent reports "not+ # signed in" and starts a needless re-login while the credential is still good.+ posthog_auth.save(_credential(expires_at=time.time() - 10))+ with patch.object(posthog_auth.requests, "post", post):+ with pytest.raises(posthog_auth.AuthError) as caught:+ posthog_auth.token(scopes=[_SCOPE], host=_HOST, interactive=False)+ assert expected in caught.value.message+ assert caught.value.exit_code == 1+ assert "not signed in" not in caught.value.message+++# --- scopes: the reason this is general rather than one command's helper -------------------------+++def test_a_credential_short_of_the_requested_scope_does_not_satisfy_it() -> None:+ # Returning it would send a request that 403s on a scope check, surfacing as a permission problem+ # the user cannot act on.+ posthog_auth.save(_credential(granted=("query:read",)))+ with pytest.raises(posthog_auth.AuthError):+ posthog_auth.token(scopes=[_SCOPE], host=_HOST, interactive=False)+++def test_the_client_id_is_the_document_the_host_publishes() -> None:+ # A self-registered client per machine is what this replaced: it left a dead OAuth app behind on+ # every scope change and showed the user an unverified-app consent screen.+ poster = _Poster(token=(200, {"access_token": "pha_new", "expires_in": 3600}))+ with patch.object(posthog_auth.requests, "post", poster), _metadata(), _fake_browser():+ credential = posthog_auth.login(scopes=[_SCOPE], host=_HOST)+ assert credential.client_id == _CLIENT_ID+ assert poster.body_for("token")["client_id"] == _CLIENT_ID+ assert not poster.reached("register")+++ "cached_client_id, revokes",+ [+ # The upgrade case: a credential minted by the self-registered client this replaced. Its+ # refresh token stays live for 30 days, and no later logout can name it once overwritten.+ ("client-abc", True),+ # The same client, so the server's sweep would take the token this login just minted.+ (_CLIENT_ID, False),+ ],+)+def test_a_login_revokes_a_replaced_credential_only_when_it_came_from_another_client(+ cached_client_id: str, revokes: bool+) -> None:+ posthog_auth.save(_credential(client_id=cached_client_id))+ poster = _Poster(token=(200, {"access_token": "pha_new", "refresh_token": "phr_new", "expires_in": 3600}))+ with patch.object(posthog_auth.requests, "post", poster), _metadata(), _fake_browser():+ credential = posthog_auth.login(scopes=[_SCOPE], host=_HOST)+ assert credential.access_token == "pha_new"+ assert poster.reached("revoke") is revokes+ if revokes:+ revoked = poster.body_for("revoke")+ assert revoked["token"] == "phr_cached" and revoked["client_id"] == "client-abc"+++def test_a_login_keeps_its_new_credential_when_revoking_the_replaced_one_fails() -> None:+ # The user is signed in either way, so failing here would report a working login as an error.+ posthog_auth.save(_credential(client_id="client-abc"))+ poster = _Poster(+ token=(200, {"access_token": "pha_new", "expires_in": 3600}),+ revoke=(503, {"error": "service_unavailable"}),+ )+ with patch.object(posthog_auth.requests, "post", poster), _metadata(), _fake_browser():+ credential = posthog_auth.login(scopes=[_SCOPE], host=_HOST)+ assert credential.access_token == "pha_new"+ cached = posthog_auth.load(_HOST)+ assert cached is not None and cached.access_token == "pha_new"+++def test_a_host_that_serves_no_client_document_names_the_way_out() -> None:+ # An older self-hosted PostHog would otherwise fail at /authorize, which cannot say what to do.+ with patch.object(posthog_auth.requests, "get", lambda url, timeout: _Response(404, {})):+ with patch.object(posthog_auth.webbrowser, "open", side_effect=AssertionError("must not open")):+ with pytest.raises(posthog_auth.AuthError) as caught:+ posthog_auth.login(scopes=[_SCOPE], host=_HOST)+ assert "POSTHOG_PERSONAL_API_KEY" in caught.value.message+++def test_a_login_off_a_tty_refuses_instead_of_opening_a_browser() -> None:+ # A browser opened for a piped caller answers to nobody, and the login would sit out its whole+ # five-minute timeout before failing.+ with patch.object(posthog_auth.sys.stdin, "isatty", lambda: False):+ with patch.object(posthog_auth.webbrowser, "open", side_effect=AssertionError("must not open")):+ with pytest.raises(posthog_auth.AuthError) as caught:+ posthog_auth.login(scopes=[_SCOPE], host=_HOST)+ assert caught.value.exit_code == posthog_auth.EXIT_NOT_CONFIGURED+++def test_a_scope_the_host_does_not_publish_is_reported_before_the_browser_opens() -> None:+ # /authorize clamps to the published ceiling, so consenting first would spend the user's click+ # to mint a token missing what was asked for, landing as an unactionable 403 later.+ poster = _Poster()+ with patch.object(posthog_auth.requests, "post", poster), _metadata(_SCOPE):+ with patch.object(posthog_auth.webbrowser, "open", side_effect=AssertionError("must not open")):+ with pytest.raises(posthog_auth.AuthError) as caught:+ posthog_auth.login(scopes=[_SCOPE, "llm_gateway:read"], host=_HOST)+ assert "llm_gateway:read" in caught.value.message+ assert not poster.reached("token")+++def test_retrying_a_refused_scope_mints_no_grant_and_leaves_the_cache_alone() -> None:+ # Refusing after the exchange rather than before it would leave a live grant behind on every+ # attempt, each needing its own revocation, and overwrite a working credential.+ posthog_auth.save(_credential())+ poster = _Poster()+ with patch.object(posthog_auth.requests, "post", poster), _metadata(_SCOPE):+ with patch.object(posthog_auth.webbrowser, "open", side_effect=AssertionError("must not open")):+ for _ in range(3):+ with pytest.raises(posthog_auth.AuthError):+ posthog_auth.login(scopes=[_SCOPE, "llm_gateway:read"], host=_HOST)+ assert not poster.reached("token")+ survivor = posthog_auth.load(_HOST)+ assert survivor is not None and survivor.access_token == "pha_cached"+++def test_the_granted_scopes_come_from_the_server_not_the_request() -> None:+ # PostHog widens some grants. Storing what we asked for would re-authorize forever, or claim a+ # scope the token does not carry.+ poster = _Poster(token=(200, {"access_token": "pha_new", "scope": f"{_SCOPE} engineering_analytics:write"}))+ with patch.object(posthog_auth.requests, "post", poster), _metadata(), _fake_browser():+ credential = posthog_auth.login(scopes=[_SCOPE], host=_HOST)+ assert credential.granted == (_SCOPE, "engineering_analytics:write")+++def test_a_token_response_without_a_scope_field_records_what_was_asked_for() -> None:+ # RFC 6749 §5.1 omits `scope` when it matches the request, so an omission means the whole ask was+ # granted. Recording nothing would read as "scopes unknown" and satisfy every later request.+ poster = _Poster(token=(200, {"access_token": "pha_new", "expires_in": 3600}))+ with patch.object(posthog_auth.requests, "post", poster), _metadata(), _fake_browser():+ credential = posthog_auth.login(scopes=[_SCOPE], host=_HOST)+ assert credential.granted == (_SCOPE,)+++# --- the browser handoff ------------------------------------------------------------------------+++def test_the_exchange_carries_the_port_the_listener_actually_bound() -> None:+ # RFC 8252 §7.3 exempts a loopback port from redirect matching, which is the whole reason one+ # portless entry in the published document covers whichever port the OS hands this login.+ poster = _Poster(token=(200, {"access_token": "pha_new", "expires_in": 3600}))+ with patch.object(posthog_auth.requests, "post", poster), _metadata(), _fake_browser():+ posthog_auth.login(scopes=[_SCOPE], host=_HOST)+ sent = poster.body_for("token")["redirect_uri"]+ assert sent.startswith("http://127.0.0.1:") and sent.endswith("/callback")+ assert _port_from(sent) > 0+++def test_the_code_exchange_proves_possession_of_the_pkce_verifier() -> None:+ # A public client has no secret, so the verifier is the only thing binding the code to us.+ poster = _Poster(token=(200, {"access_token": "pha_new", "expires_in": 3600}))+ with patch.object(posthog_auth.requests, "post", poster), _metadata(), _fake_browser():+ posthog_auth.login(scopes=[_SCOPE], host=_HOST)+ body = poster.body_for("token")+ assert body["grant_type"] == "authorization_code" and body["code_verifier"]+++ "query, expected",+ [+ ({"code": ["c"], "state": ["mismatched"]}, "wrong state"),+ ({"error": ["access_denied"], "state": ["expected"]}, "refused"),+ ({"state": ["expected"]}, "no authorization code"),+ ],+)+def test_a_redirect_that_does_not_answer_our_request_is_rejected(query: dict[str, list[str]], expected: str) -> None:+ # Without the state check the flow would accept a code from a request we never made.+ with pytest.raises(posthog_auth.AuthError) as caught:+ posthog_auth._code_from(query, state="expected")+ assert expected in caught.value.message+++def test_the_callback_listener_ignores_paths_that_are_not_the_redirect() -> None:+ # A browser also fetches /favicon.ico, so treating any request as the callback would end the wait+ # on the wrong one.+ with posthog_auth._CallbackServer() as server, _paste_path(False):+ with patch.object(posthog_auth.webbrowser, "open", lambda url: True):+ threading.Thread(+ target=lambda: (+ requests.get(f"http://127.0.0.1:{_port_from(server.redirect_uri)}/favicon.ico", timeout=5),+ requests.get(f"{server.redirect_uri}?code=real&state=s", timeout=5),+ ),+ daemon=True,+ ).start()+ assert server.collect("http://example.invalid", state="s") == "real"+++def test_a_browser_that_blocks_until_it_exits_does_not_deadlock_the_listener() -> None:+ # `webbrowser.open` blocks for a terminal-mode browser, and for anything $BROWSER points at that+ # doesn't detach. Opened in the foreground it would wait on the redirect only this listener can+ # serve, so the login would hang until its timeout.+ released = threading.Event()+ collected: dict[str, str] = {}+ with posthog_auth._CallbackServer() as server, _paste_path(False):++ def blocking_open(url: str) -> bool:+ # What a real blocking browser does: fetch the redirect, then stay open until dismissed.+ threading.Thread(+ target=lambda: requests.get(f"{server.redirect_uri}?code=blocked&state=s", timeout=5), daemon=True+ ).start()+ released.wait()+ return True++ with patch.object(posthog_auth.webbrowser, "open", blocking_open):+ # Run in a worker so a login that waits on the browser fails this test rather than+ # hanging it: the browser is never dismissed until the assertions are done.+ worker = threading.Thread(target=lambda: collected.update(code=server.collect("http://x", state="s")))+ worker.daemon = True+ worker.start()+ worker.join(10)+ released.set()+ assert collected.get("code") == "blocked", "the login did not return while the browser was still open"+++def test_a_login_prints_the_url_and_takes_the_redirect_back_by_hand(capsys: pytest.CaptureFixture[str]) -> None:+ # A browser on another machine never reaches this listener, so without the printed URL and the+ # redirect typed back, a devbox login waits out its timeout with the code already on screen.+ with posthog_auth._CallbackServer() as server:+ pasted = f"{server.redirect_uri}?code=pasted&state=s"+ with patch.object(posthog_auth.webbrowser, "open", lambda url: False), _terminal(f"{pasted}\n"):+ assert server.collect("https://us.posthog.com/oauth/authorize/?client_id=abc", state="s") == "pasted"+ assert "https://us.posthog.com/oauth/authorize/?client_id=abc" in capsys.readouterr().err+++# --- the CLI surface ----------------------------------------------------------------------------+++def test_status_exits_not_configured_when_nothing_is_cached(runner: CliRunner) -> None:+ # So a script can gate on the exit code instead of grepping the table.+ result = runner.invoke(posthog_auth_cli.posthog_status, [])+ assert result.exit_code == posthog_auth.EXIT_NOT_CONFIGURED+ assert "posthog:login" in result.output+++def test_status_reports_the_same_verdict_in_both_output_shapes(runner: CliRunner) -> None:+ # A script gating on the exit code must not read "configured" just because it asked for JSON.+ assert runner.invoke(posthog_auth_cli.posthog_status, []).exit_code == posthog_auth.EXIT_NOT_CONFIGURED+ assert runner.invoke(posthog_auth_cli.posthog_status, ["--json"]).exit_code == posthog_auth.EXIT_NOT_CONFIGURED+ posthog_auth.save(_credential())+ assert runner.invoke(posthog_auth_cli.posthog_status, []).exit_code == 0+ assert runner.invoke(posthog_auth_cli.posthog_status, ["--json"]).exit_code == 0+++# A token runs for days, so reporting only minutes prints "expires in 10079m" and leaves the reader+# dividing by hand. The absent case is here too because a server that issues no `expires_in` would+# otherwise reach the arithmetic with None and crash the whole status table.+ "seconds,expected",+ [+ (7 * 86400, "expires in 7d"),+ (90, "expires in 1m"),+ (30, "expires in under a minute"),+ (-1, "expired"),+ (None, "no expiry reported"),+ ],+)+def test_status_reports_a_lifetime_at_a_readable_unit(+ monkeypatch: pytest.MonkeyPatch, seconds: int | None, expected: str+) -> None:+ # Pinned, because flooring an exact multiple drops a unit as soon as the clock moves.+ monkeypatch.setattr(posthog_auth_cli.time, "time", lambda: 1_700_000_000.0)+ assert posthog_auth_cli._lifetime(None if seconds is None else 1_700_000_000.0 + seconds) == expected+++def test_status_never_prints_the_token(runner: CliRunner) -> None:+ # Status is run to diagnose auth, often with a terminal being shared or logged.+ posthog_auth.save(_credential())+ table = runner.invoke(posthog_auth_cli.posthog_status, [])+ rendered = runner.invoke(posthog_auth_cli.posthog_status, ["--json"])+ for result in (table, rendered):+ assert result.exit_code == 0+ assert "pha_cached" not in result.output and "phr_cached" not in result.output+ assert json.loads(rendered.output)["credential"]["access_token"] == "<redacted>"+++def test_status_warns_when_an_environment_key_outranks_the_cached_credential(+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch+) -> None:+ # Otherwise a stale exported key makes a fresh login look like it did nothing.+ posthog_auth.save(_credential())+ monkeypatch.setenv("POSTHOG_PERSONAL_API_KEY", "phx_exported")+ result = runner.invoke(posthog_auth_cli.posthog_status, [])+ assert result.exit_code == 0 and "wins over" in result.output+++def test_logout_reports_whether_there_was_anything_to_forget(runner: CliRunner) -> None:+ posthog_auth.save(_credential())+ with patch.object(posthog_auth.requests, "post", _Poster()):+ assert "Signed out" in runner.invoke(posthog_auth_cli.posthog_logout, []).output+ assert "No cached credential" in runner.invoke(posthog_auth_cli.posthog_logout, []).output+++ "refresh_token, expected_token, expected_hint",+ [+ # The refresh token is the one that matters: it outlives the access token and mints more.+ ("phr_cached", "phr_cached", "refresh_token"),+ # Without this branch the absent refresh token goes out as token=None, revoking nothing.+ (None, "pha_cached", "access_token"),+ ],+)+def test_logout_revokes_the_credential_before_dropping_the_file(+ refresh_token: str | None, expected_token: str, expected_hint: str+) -> None:+ # Deleting the file alone leaves the token live for anyone who copied it, with nothing local+ # left to name it by.+ posthog_auth.save(_credential(refresh_token=refresh_token))+ poster = _Poster()+ with patch.object(posthog_auth.requests, "post", poster):+ result = posthog_auth.logout(_HOST)+ revoked = poster.body_for("revoke")+ assert revoked["token"] == expected_token+ assert revoked["token_type_hint"] == expected_hint+ assert revoked["client_id"] == "client-abc"+ assert result.revoked and result.forgotten+ assert posthog_auth.load(_HOST) is None+++def test_logout_still_drops_the_credential_when_revocation_fails(runner: CliRunner) -> None:+ # A logout that leaves the token on disk because the server was unreachable is the worse+ # outcome, so the file goes and the user is told the grant is still live.+ posthog_auth.save(_credential())+ with patch.object(posthog_auth.requests, "post", side_effect=requests.ConnectionError("no route")):+ result = runner.invoke(posthog_auth_cli.posthog_logout, [])+ assert result.exit_code == 0+ assert "may still work" in result.output+ assert posthog_auth.load(_HOST) is None