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(hogli): use personal credentials for pr evidence uploads (#117129)

Adam Bowker3870307cbf78
diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.md
index 554f6eb92c6f..3d0a0a859ffd 100644
--- a/docs/published/handbook/engineering/developing-locally.md
+++ b/docs/published/handbook/engineering/developing-locally.md
@@ -68,6 +68,8 @@ This is the recommended option for most developers.
Before your first push, set up an [SSH key and commit signing](https://posthog.com/handbook/engineering/security#github) using Secretive or 1Password.
Signing is required: an org-wide ruleset rejects unsigned commits in every PostHog repository, so an unsigned push fails with `GH013: Commits must have verified signatures`.
+PR evidence uploads (`hogli pr:upload-image` and `hogli pr:upload-video`) prefer your stored GitHub CLI login over `GITHUB_TOKEN` from `.env.local`. Set `GH_TOKEN` to override the account; `GITHUB_TOKEN` remains the fallback when no CLI login exists.
+
#### macOS
1. Install Xcode Command Line Tools if you haven't already: `xcode-select --install`.
diff --git a/tools/hogli-commands/hogli_commands/github_auth.py b/tools/hogli-commands/hogli_commands/github_auth.py
index 5afcb332951c..c90bcfbaef64 100644
--- a/tools/hogli-commands/hogli_commands/github_auth.py
+++ b/tools/hogli-commands/hogli_commands/github_auth.py
@@ -11,18 +11,21 @@ import shutil
import subprocess
-def github_token() -> str | None:
- """A github.com token from GH_TOKEN/GITHUB_TOKEN, else `gh auth token`, else None.
+def github_token(*, prefer_cli: bool = False) -> str | None:
+ """Use GH_TOKEN as an explicit override, then choose between GITHUB_TOKEN and gh.
- Env vars win so CI and explicit overrides work without gh; otherwise fall back to the
- caller's gh login. Pinned to github.com so the result is independent of the cwd's repo.
+ Personal uploads prefer the stored gh login because hogli also loads application
+ credentials from .env.local. GITHUB_TOKEN remains the fallback without a gh login.
+ Other callers retain environment-first selection for CI and service credentials.
"""
- for env_var in ("GH_TOKEN", "GITHUB_TOKEN"):
- if token := os.environ.get(env_var):
- return token
+ if token := os.environ.get("GH_TOKEN"):
+ return token
+ fallback_token = os.environ.get("GITHUB_TOKEN") or None
+ if fallback_token and not prefer_cli:
+ return fallback_token
gh = shutil.which("gh")
if gh is None:
- return None
+ return fallback_token
try:
result = subprocess.run(
[gh, "auth", "token", "--hostname", "github.com"],
@@ -30,11 +33,12 @@ def github_token() -> str | None:
text=True,
timeout=10,
check=False,
+ env={key: value for key, value in os.environ.items() if key not in ("GH_TOKEN", "GITHUB_TOKEN")},
)
except (OSError, subprocess.TimeoutExpired):
- return None
+ return fallback_token
token = result.stdout.strip()
- return token if result.returncode == 0 and token else None
+ return token if result.returncode == 0 and token else fallback_token
def github_headers(token: str | None) -> dict[str, str]:
diff --git a/tools/hogli-commands/hogli_commands/pr_assets.py b/tools/hogli-commands/hogli_commands/pr_assets.py
index 2f7f0d1f3189..43aeb5293c46 100644
--- a/tools/hogli-commands/hogli_commands/pr_assets.py
+++ b/tools/hogli-commands/hogli_commands/pr_assets.py
@@ -99,7 +99,7 @@ def publish(paths: Sequence[Path], *, message: str) -> list[str]:
URLs are pinned to the created commit, so they keep serving even after the file is
moved or deleted.
"""
- token = github_token()
+ token = github_token(prefer_cli=True)
if token is None:
raise click.ClickException(
"no GitHub token found. Set GH_TOKEN or GITHUB_TOKEN, or install gh "
@@ -134,16 +134,18 @@ def _graphql(session: requests.Session, token: str, query: str, variables: dict[
except requests.RequestException as exc:
raise click.ClickException(f"GitHub request failed: {exc}")
- if resp.status_code in (401, 403):
- raise click.ClickException(_denied_message())
- if not resp.ok:
- raise click.ClickException(f"GitHub returned HTTP {resp.status_code}")
-
try:
body = resp.json()
except ValueError as exc:
+ if not resp.ok:
+ raise click.ClickException(f"GitHub returned HTTP {resp.status_code}") from exc
raise click.ClickException(f"GitHub returned a non-JSON response: {exc}")
+ if not resp.ok:
+ message = body.get("message", "")
+ detail = f": {message}" if message else ""
+ raise click.ClickException(f"GitHub returned HTTP {resp.status_code}{detail}")
+
if errors := body.get("errors"):
raise _OperationFailed(errors)
data = body.get("data")
@@ -188,10 +190,6 @@ def _commit(session: requests.Session, token: str, additions: list[dict[str, str
if "STALE_DATA" in exc.types:
head = _read_head(session, token)
continue
- # The head read above resolved this branch, so GitHub calling it missing here
- # means the token can read the repo but not write to it.
- if any("Branch not found" in reported for reported in exc.messages):
- raise click.ClickException(_denied_message())
raise click.ClickException(f"upload failed: {exc}")
oid = ((data.get("createCommitOnBranch") or {}).get("commit") or {}).get("oid")
@@ -202,12 +200,3 @@ def _commit(session: requests.Session, token: str, additions: list[dict[str, str
raise click.ClickException(
f"{REPO} moved under the upload {_MAX_ATTEMPTS} times in a row; nothing was published, so try again"
)
-
-
-def _denied_message() -> str:
- """Explain a rejected write: the token can't write to pr-assets (not an org member, or missing scope)."""
- return (
- f"upload denied. Writing to {REPO} needs write access to a public PostHog repo: "
- "confirm your token is a PostHog org account with the `repo` scope "
- "(gh users: `gh auth refresh -s repo`; or set GH_TOKEN to a PAT with the repo scope)."
- )
diff --git a/tools/hogli-commands/hogli_commands/tests/test_github_auth.py b/tools/hogli-commands/hogli_commands/tests/test_github_auth.py
index f37ccb2cb834..19fc0d56a254 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_github_auth.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_github_auth.py
@@ -8,27 +8,42 @@ from unittest.mock import patch
from hogli_commands import github_auth
-def test_env_token_wins_over_gh(monkeypatch: pytest.MonkeyPatch) -> None:
- # Env vars must take precedence so CI and explicit overrides work without gh.
- monkeypatch.setenv("GH_TOKEN", "env-tok")
[email protected](("env_var", "prefer_cli"), [("GH_TOKEN", False), ("GH_TOKEN", True), ("GITHUB_TOKEN", False)])
+def test_env_token_wins_over_gh(monkeypatch: pytest.MonkeyPatch, env_var: str, prefer_cli: bool) -> None:
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ monkeypatch.setenv(env_var, "env-tok")
with patch.object(github_auth.subprocess, "run") as run:
- assert github_auth.github_token() == "env-tok"
+ assert github_auth.github_token(prefer_cli=prefer_cli) == "env-tok"
run.assert_not_called()
-def test_falls_back_to_gh_cli(monkeypatch: pytest.MonkeyPatch) -> None:
[email protected]("application_token", [None, "app-tok"])
+def test_falls_back_to_gh_cli(monkeypatch: pytest.MonkeyPatch, application_token: str | None) -> None:
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ if application_token:
+ monkeypatch.setenv("GITHUB_TOKEN", application_token)
monkeypatch.setattr(github_auth.shutil, "which", lambda _: "/usr/bin/gh")
- with patch.object(github_auth.subprocess, "run", return_value=SimpleNamespace(returncode=0, stdout="gh-tok\n")):
- assert github_auth.github_token() == "gh-tok"
-
-
-def test_none_when_no_env_and_no_gh(monkeypatch: pytest.MonkeyPatch) -> None:
+ with patch.object(
+ github_auth.subprocess, "run", return_value=SimpleNamespace(returncode=0, stdout="gh-tok\n")
+ ) as run:
+ assert github_auth.github_token(prefer_cli=bool(application_token)) == "gh-tok"
+ assert "GITHUB_TOKEN" not in run.call_args.kwargs["env"]
+
+
[email protected]("application_token", [None, "app-tok"])
[email protected]("cli_available", [False, True])
+def test_fallback_without_cli_login(
+ monkeypatch: pytest.MonkeyPatch, application_token: str | None, cli_available: bool
+) -> None:
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
- monkeypatch.setattr(github_auth.shutil, "which", lambda _: None)
- assert github_auth.github_token() is None
+ if application_token:
+ monkeypatch.setenv("GITHUB_TOKEN", application_token)
+ monkeypatch.setattr(github_auth.shutil, "which", lambda _: "/usr/bin/gh" if cli_available else None)
+ with patch.object(github_auth.subprocess, "run", return_value=SimpleNamespace(returncode=1, stdout="")):
+ assert github_auth.github_token(prefer_cli=True) == application_token
def test_headers_carry_bearer_only_with_a_token() -> None:
diff --git a/tools/hogli-commands/hogli_commands/tests/test_pr_assets.py b/tools/hogli-commands/hogli_commands/tests/test_pr_assets.py
index 893b40dcf79f..bb08e009e62c 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_pr_assets.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_pr_assets.py
@@ -102,11 +102,29 @@ def test_sends_newline_free_base64_under_a_dated_key(png: Path, token: None) ->
assert re.fullmatch(_KEY_RE + r"\.png", addition["path"])
-def test_operation_failure_is_surfaced_even_though_http_is_200(png: Path, token: None) -> None:
- # GraphQL answers 200 with an errors array. Deciding on the status code would treat this
- # as a success and print markdown pointing at a commit that was never created.
- with _session(_head(), _failed(type="FORBIDDEN", message="nope")):
- with pytest.raises(click.ClickException, match="upload failed"):
+def test_upload_uses_cli_login_instead_of_application_token(png: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ monkeypatch.setenv("GITHUB_TOKEN", "app-tok")
+ monkeypatch.setattr(github_auth.shutil, "which", lambda _: "/usr/bin/gh")
+ with (
+ patch.object(github_auth.subprocess, "run", return_value=SimpleNamespace(returncode=0, stdout="user-tok\n")),
+ _session(_head(), _committed("c0ffee")) as session,
+ ):
+ urls = pr_assets.publish([png], message="add screenshot")
+
+ assert "/c0ffee/" in urls[0]
+ assert session.post.call_args.kwargs["headers"]["Authorization"] == "Bearer user-tok"
+
+
+ ("error_type", "message"),
+ [("FORBIDDEN", "nope"), ("NOT_FOUND", "Branch not found"), ("INTERNAL", "Something went wrong")],
+)
+def test_operation_failure_is_surfaced_even_though_http_is_200(
+ png: Path, token: None, error_type: str, message: str
+) -> None:
+ with _session(_head(), _failed(type=error_type, message=message)):
+ with pytest.raises(click.ClickException, match=f"upload failed: {message}"):
pr_assets.publish([png], message="add screenshot")
@@ -142,11 +160,25 @@ def test_gives_up_after_repeated_stale_heads(png: Path, token: None) -> None:
pr_assets.publish([png], message="add screenshot")
-def test_branch_not_found_after_a_successful_head_read_reports_write_access(png: Path, token: None) -> None:
- # GitHub returns "Branch not found" both for a missing branch and for a token that cannot
- # write. The head read already resolved this branch, so it can only be permissions.
- with _session(_head(), _failed(type="NOT_FOUND", message="Branch not found")):
- with pytest.raises(click.ClickException, match="write access"):
+ ("status", "message"),
+ [
+ (401, "Bad credentials"),
+ (403, "API rate limit exceeded"),
+ (403, "Resource not accessible by personal access token"),
+ (502, "Service unavailable"),
+ (502, None),
+ ],
+)
+def test_http_failure_preserves_status_and_github_reason(
+ png: Path, token: None, status: int, message: str | None
+) -> None:
+ response = _resp({"message": message}, status)
+ if message is None:
+ response.json = Mock(side_effect=ValueError("HTML error page"))
+ expected = f"HTTP {status}: {message}" if message else f"HTTP {status}"
+ with _session(_head(), response):
+ with pytest.raises(click.ClickException, match=expected):
pr_assets.publish([png], message="add screenshot")