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.

feat(hogli): add gateway:token for AI gateway developer mode (#120755)

Brandone108a1c91b04
diff --git a/hogli.yaml b/hogli.yaml
index 96f9230b33b3..b49672a05ec6 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -912,6 +912,9 @@ auth:
metabase:cookie:
click: hogli_commands.metabase:metabase_cookie
description: Print the cached Metabase cookie header
+ gateway:token:
+ click: hogli_commands.gateway:gateway_token
+ description: Get a short-lived AI gateway token for PostHog staff, approved in your browser
tools:
metabase:databases:
click: hogli_commands.metabase:metabase_databases
diff --git a/tools/hogli-commands/hogli_commands/gateway.py b/tools/hogli-commands/hogli_commands/gateway.py
new file mode 100644
index 000000000000..8b52680ea78d
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/gateway.py
@@ -0,0 +1,113 @@
+"""`hogli gateway:token`, a short-lived AI gateway token for PostHog staff.
+
+hogli holds no PostHog credential for this. The staff member approves a PKCE challenge on the
+developer mode settings page, the page hands a one-time code to a loopback port, and hogli
+exchanges the code and its verifier for a token attributed to that staff member.
+"""
+
+from __future__ import annotations
+
+import json
+import base64
+import hashlib
+import secrets
+from typing import Any
+from urllib.parse import urlencode, urlsplit
+
+import click
+import requests
+
+from hogli_commands import posthog_auth
+
+_SETTINGS_PATH = "/settings/user-ai-gateway-dev-mode"
+_EXCHANGE_PATH = "/api/ai_gateway/dev_tokens/cli_exchange/"
+_HTTP_TIMEOUT_SECONDS = 30.0
+# An approved code plus its verifier is a token, so the CLI only sends them to hosts staff
+# actually approve on. Local dev hosts match on any port.
+_ALLOWED_HOSTS = ("https://us.posthog.com", "https://eu.posthog.com")
+_LOCAL_HOSTNAMES = ("localhost", "127.0.0.1")
+
+
[email protected](name="gateway:token", help="Get a short-lived AI gateway token after you approve it in your browser.")
+ "--host",
+ default=posthog_auth.DEFAULT_HOST,
+ show_default=True,
+ help="PostHog host that mints the token (e.g. https://eu.posthog.com).",
+)
+ "--allow-any-host",
+ is_flag=True,
+ help="Skip the --host allowlist. Only use this for a host you run yourself.",
+)
[email protected]("--json", "as_json", is_flag=True, help="Print the full token response as JSON.")
+def gateway_token(host: str, allow_any_host: bool, as_json: bool) -> None:
+ host = host.rstrip("/") if allow_any_host else _allowed_host(host)
+ verifier = secrets.token_urlsafe(64)
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
+ state = secrets.token_urlsafe(24)
+
+ def approval_url(port: int) -> str:
+ return f"{host}{_SETTINGS_PATH}?" + urlencode(
+ {"cli_challenge": challenge, "cli_port": port, "cli_state": state}
+ )
+
+ try:
+ code = posthog_auth.approve_in_browser(approval_url, state=state)
+ except posthog_auth.AuthError as error:
+ click.secho(error.message, fg="red", err=True)
+ raise SystemExit(error.exit_code)
+
+ minted = _exchange(host, code=code, verifier=verifier)
+ if as_json:
+ click.echo(json.dumps(minted))
+ return
+ # Only the token goes to stdout, so `$(hogli gateway:token)` captures it alone.
+ click.echo(minted["token"])
+ click.echo(
+ f"\nThe token expires at {minted['expires_at']} and can spend up to ${minted['cap_usd']}.",
+ err=True,
+ )
+
+
+def _allowed_host(host: str) -> str:
+ try:
+ parts = urlsplit(host.strip())
+ port = parts.port
+ except ValueError:
+ parts, port = None, None
+ if parts is not None and parts.hostname:
+ hostname = parts.hostname.lower()
+ if parts.scheme == "http" and hostname in _LOCAL_HOSTNAMES:
+ return f"http://{hostname}" + (f":{port}" if port else "")
+ if parts.scheme == "https" and port in (None, 443):
+ origin = f"https://{hostname}"
+ if origin in _ALLOWED_HOSTS:
+ return origin
+ allowed = ", ".join([*_ALLOWED_HOSTS, "http://localhost:<port>", "http://127.0.0.1:<port>"])
+ raise click.BadParameter(
+ f"{host} is not an allowed host. Allowed values: {allowed}. Pass --allow-any-host to use another host.",
+ param_hint="'--host'",
+ )
+
+
+def _exchange(host: str, *, code: str, verifier: str) -> dict[str, Any]:
+ try:
+ response = requests.post(
+ f"{host}{_EXCHANGE_PATH}",
+ json={"code": code, "code_verifier": verifier},
+ timeout=_HTTP_TIMEOUT_SECONDS,
+ allow_redirects=False,
+ )
+ except requests.RequestException as error:
+ raise click.ClickException(f"Could not reach {host}: {error}")
+ try:
+ body = response.json()
+ except ValueError:
+ body = None
+ if response.status_code != 201 or not isinstance(body, dict):
+ detail = body.get("detail") if isinstance(body, dict) else None
+ raise click.ClickException(
+ f"{host} refused the token exchange ({response.status_code}): {detail or response.text}"
+ )
+ return body
diff --git a/tools/hogli-commands/hogli_commands/posthog_auth.py b/tools/hogli-commands/hogli_commands/posthog_auth.py
index 2080acf4e0a7..1b99a3aa6783 100644
--- a/tools/hogli-commands/hogli_commands/posthog_auth.py
+++ b/tools/hogli-commands/hogli_commands/posthog_auth.py
@@ -43,7 +43,7 @@ import secrets
import threading
import webbrowser
import http.server
-from collections.abc import Iterable, Sequence
+from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any
@@ -401,6 +401,15 @@ def login(*, scopes: Sequence[str], host: str = DEFAULT_HOST) -> Credential:
return credential
+def approve_in_browser(url_for_port: Callable[[int], str], *, state: str) -> str:
+ """Open the page `url_for_port` builds and return the code it redirects back to the loopback `/callback`.
+
+ For PostHog flows other than this OAuth login that hand a code back the same way.
+ """
+ with _CallbackServer() as server:
+ return server.collect(url_for_port(server.port), state=state)
+
+
def _client() -> ClientMetadata:
"""The client PostHog publishes for hogli.
@@ -612,7 +621,8 @@ class _CallbackServer:
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}"
+ self.port = self._server.server_port
+ self.redirect_uri = f"http://127.0.0.1:{self.port}{_REDIRECT_PATH}"
def __enter__(self) -> _CallbackServer:
return self
diff --git a/tools/hogli-commands/hogli_commands/tests/test_gateway.py b/tools/hogli-commands/hogli_commands/tests/test_gateway.py
new file mode 100644
index 000000000000..0db89de2f9aa
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_gateway.py
@@ -0,0 +1,106 @@
+from __future__ import annotations
+
+import base64
+import hashlib
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from click.testing import CliRunner
+from hogli_commands import gateway, posthog_auth
+
+_HOST = "https://us.posthog.com"
+_MINTED = {
+ "id": "0190c0de-0000-7000-8000-000000000000",
+ "token": "phe_minted",
+ "expires_at": "2026-10-22T08:00:00Z",
+ "cap_usd": "25.00",
+ "gateway_url": "https://gateway.us.posthog.com",
+ "product": "dev",
+}
+
+
+def _response(status_code: int, payload: Any) -> MagicMock:
+ # `text` differs from the payload so an assertion on `detail` can't pass on the raw body.
+ response = MagicMock(status_code=status_code, text="<html>proxy page</html>")
+ response.json.return_value = payload
+ return response
+
+
+def _run(post: MagicMock, *args: str, host: str = f"{_HOST}/") -> tuple[Any, list[str]]:
+ opened: list[str] = []
+
+ def browser(url: str) -> bool:
+ # Plays the settings page approving the request.
+ opened.append(url)
+ query = parse_qs(urlparse(url).query)
+ params = {"code": "one-time-code", "state": query["cli_state"][0]}
+ requests.get(f"http://127.0.0.1:{query['cli_port'][0]}/callback", params=params, timeout=5)
+ return True
+
+ with (
+ patch.object(posthog_auth.webbrowser, "open", browser),
+ patch.object(posthog_auth, "_readable_terminal", lambda: False),
+ # A broken port fails the test at this deadline instead of hanging it.
+ patch.object(posthog_auth, "_LOGIN_TIMEOUT_SECONDS", 5.0),
+ patch.object(gateway.requests, "post", post),
+ ):
+ result = CliRunner(mix_stderr=False).invoke(gateway.gateway_token, ["--host", host, *args])
+ return result, opened
+
+
+def test_the_exchanged_verifier_matches_the_approved_challenge_and_stdout_holds_only_the_token() -> None:
+ post = MagicMock(return_value=_response(201, _MINTED))
+
+ result, opened = _run(post)
+
+ assert result.exit_code == 0, result.output
+ assert result.stdout == "phe_minted\n"
+ approval = urlparse(opened[0])
+ assert f"{approval.scheme}://{approval.netloc}{approval.path}" == f"{_HOST}/settings/user-ai-gateway-dev-mode"
+ assert post.call_args.args[0] == f"{_HOST}/api/ai_gateway/dev_tokens/cli_exchange/"
+ sent = post.call_args.kwargs["json"]
+ assert sent["code"] == "one-time-code"
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(sent["code_verifier"].encode()).digest()).rstrip(b"=")
+ assert parse_qs(approval.query)["cli_challenge"] == [challenge.decode()]
+
+
+def test_a_refused_exchange_reports_the_server_detail_and_prints_no_token() -> None:
+ post = MagicMock(return_value=_response(400, {"code": "invalid_code", "detail": "code is expired or used"}))
+
+ result, _ = _run(post)
+
+ assert result.exit_code == 1
+ assert result.stdout == ""
+ assert "code is expired or used" in result.stderr
+
+
+ "host,args,expected_origin",
+ [
+ ("https://EU.posthog.com/", (), "https://eu.posthog.com"),
+ ("http://localhost:8010", (), "http://localhost:8010"),
+ ("https://attacker.example", (), None),
+ ("https://us.posthog.com.attacker.example", (), None),
+ ("http://us.posthog.com", (), None),
+ ("https://attacker.example", ("--allow-any-host",), "https://attacker.example"),
+ ],
+)
+def test_host_allowlist(host: str, args: tuple[str, ...], expected_origin: str | None) -> None:
+ post = MagicMock(return_value=_response(201, _MINTED))
+
+ result, opened = _run(post, *args, host=host)
+
+ if expected_origin is None:
+ assert result.exit_code == 2
+ assert opened == []
+ post.assert_not_called()
+ assert "--host" in result.stderr and "--allow-any-host" in result.stderr
+ else:
+ assert result.exit_code == 0, result.output
+ assert opened[0].startswith(f"{expected_origin}/settings/")
+ assert post.call_args.args[0].startswith(f"{expected_origin}/api/")
+ assert post.call_args.kwargs["allow_redirects"] is False