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(cli-auth): keep an approved cli key until its code expires (#125179)

Rafael Audiberte789fe134410
diff --git a/hog/README.md b/hog/README.md
index 401f54489546..91cc96aebd9c 100644
--- a/hog/README.md
+++ b/hog/README.md
@@ -48,7 +48,6 @@ Then, once the commands above work:
Smaller follow-ups, none of them blocking:
-- [ ] PostHog: keep an approved CLI login key until its code expires, and let a repeated poll return it again. Then `hog auth login --wait` works however long the person takes to resume the agent, and a poll whose response is lost can retry. posthog-cli polls in one process, so only hog's agent flow needs this.
- [ ] `hog error-tracking upload --include-source`: read `DW_LNE_define_file` entries in the DWARF line program, so hog bundles the same source files as posthog-cli. Current compilers don't emit them, and DWARF 5 removed them.
- [ ] `hog error-tracking upload --include-source`: write ZIP64, so a binary that names more than 65,533 source files keeps its sources. hog uploads it without sources and warns.
diff --git a/posthog/api/cli_auth.py b/posthog/api/cli_auth.py
index 99f88be7c265..a652f9a0e17f 100644
--- a/posthog/api/cli_auth.py
+++ b/posthog/api/cli_auth.py
@@ -13,6 +13,7 @@ Flow:
import string
import secrets
+from datetime import datetime
from django.core.cache import cache
from django.utils import timezone
@@ -36,6 +37,10 @@ DEVICE_CODE_EXPIRY_SECONDS = 600
# CLI polling interval (5 seconds)
CLI_POLL_INTERVAL_SECONDS = 5
+# How long an approved key stays retrievable after the first poll that returns it, so a client
+# whose response was lost can poll again. Also the floor when a code is approved just before it expires.
+AUTHORIZED_RETRIEVAL_SECONDS = 60
+
# Scopes granted to CLI
CLI_SCOPES = [
"event_definition:read",
@@ -66,6 +71,14 @@ def get_user_code_cache_key(user_code: str) -> str:
return f"cli_user_code:{user_code}"
+def remaining_device_code_seconds(device_data: dict) -> int:
+ created_at = device_data.get("created_at")
+ if not created_at:
+ return AUTHORIZED_RETRIEVAL_SECONDS
+ elapsed = (timezone.now() - datetime.fromisoformat(created_at)).total_seconds()
+ return max(int(DEVICE_CODE_EXPIRY_SECONDS - elapsed), AUTHORIZED_RETRIEVAL_SECONDS)
+
+
def get_validation_error_description(error: serializers.ValidationError) -> str:
detail = error.detail
if isinstance(detail, list) and detail:
@@ -288,8 +301,9 @@ class CLIAuthViewSet(viewsets.ViewSet):
device_data["authorized_at"] = timezone.now().isoformat()
device_data["user_id"] = user.id
- # Update cache with longer TTL to ensure CLI can poll
- cache.set(device_cache_key, device_data, timeout=60) # 1 minute to retrieve
+ # An agent can resume `hog auth login --wait` long after the person approves, so the key
+ # stays until the code expires.
+ cache.set(device_cache_key, device_data, timeout=remaining_device_code_seconds(device_data))
return Response(
{
@@ -343,10 +357,10 @@ class CLIAuthViewSet(viewsets.ViewSet):
"scopes": device_data.get("scopes", []),
}
- # Clean up - key has been retrieved
- cache.delete(device_cache_key)
- user_code_cache_key = get_user_code_cache_key(device_data["user_code"])
- cache.delete(user_code_cache_key)
+ if "retrieved_at" not in device_data:
+ device_data["retrieved_at"] = timezone.now().isoformat()
+ cache.set(device_cache_key, device_data, timeout=AUTHORIZED_RETRIEVAL_SECONDS)
+ cache.delete(get_user_code_cache_key(device_data["user_code"]))
response_serializer = DevicePollResponseSerializer(response_data)
return Response(response_serializer.data, status=status.HTTP_200_OK)
diff --git a/posthog/api/test/test_cli_auth.py b/posthog/api/test/test_cli_auth.py
index 4ca53be2752f..41b6d75e75f6 100644
--- a/posthog/api/test/test_cli_auth.py
+++ b/posthog/api/test/test_cli_auth.py
@@ -10,7 +10,13 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
-from posthog.api.cli_auth import CLI_SCOPES, DEVICE_CODE_EXPIRY_SECONDS, get_device_cache_key, get_user_code_cache_key
+from posthog.api.cli_auth import (
+ AUTHORIZED_RETRIEVAL_SECONDS,
+ CLI_SCOPES,
+ DEVICE_CODE_EXPIRY_SECONDS,
+ get_device_cache_key,
+ get_user_code_cache_key,
+)
from posthog.constants import AvailableFeature
from posthog.models import PersonalAPIKey, Team, User
from posthog.models.organization import Organization, OrganizationMembership
@@ -416,24 +422,6 @@ class TestCLIAuthPollEndpoint(APIBaseTest):
data = response.json()
self.assertEqual(data["status"], "expired")
- def test_poll_cleans_up_cache_after_successful_retrieval(self):
- """Test that cache is cleaned up after API key is retrieved"""
- # Authorize the code
- self.client.post(
- "/api/cli-auth/authorize/",
- {"user_code": self.user_code, "project_id": self.team.id},
- )
-
- # Poll for the result
- self.client.post("/api/cli-auth/poll/", {"device_code": self.device_code})
-
- # Verify cache is cleaned up
- device_cache_key = get_device_cache_key(self.device_code)
- user_code_cache_key = get_user_code_cache_key(self.user_code)
-
- self.assertIsNone(cache.get(device_cache_key))
- self.assertIsNone(cache.get(user_code_cache_key))
-
def test_poll_can_be_called_multiple_times_before_authorization(self):
"""Test that poll can be called multiple times while pending"""
# Poll multiple times
@@ -448,22 +436,36 @@ class TestCLIAuthPollEndpoint(APIBaseTest):
response = self.client.post("/api/cli-auth/poll/", {"device_code": self.device_code})
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
- def test_poll_returns_api_key_only_once(self):
- """Test that API key can only be retrieved once"""
- # Authorize the code
- self.client.post(
- "/api/cli-auth/authorize/",
- {"user_code": self.user_code, "project_id": self.team.id},
- )
+ def test_poll_returns_the_key_again_until_the_retrieval_window_closes(self):
+ self.client.post("/api/cli-auth/authorize/", {"user_code": self.user_code, "project_id": self.team.id})
- # First poll succeeds
- response1 = self.client.post("/api/cli-auth/poll/", {"device_code": self.device_code})
- self.assertEqual(response1.status_code, status.HTTP_200_OK)
+ first = self.client.post("/api/cli-auth/poll/", {"device_code": self.device_code})
+ second = self.client.post("/api/cli-auth/poll/", {"device_code": self.device_code})
- # Second poll fails (cache cleaned up)
- response2 = self.client.post("/api/cli-auth/poll/", {"device_code": self.device_code})
- self.assertEqual(response2.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response2.json()["status"], "expired")
+ self.assertEqual(first.status_code, status.HTTP_200_OK)
+ self.assertEqual(second.status_code, status.HTTP_200_OK)
+ self.assertEqual(second.json()["personal_api_key"], first.json()["personal_api_key"])
+ self.assertIsNone(cache.get(get_user_code_cache_key(self.user_code)))
+ with time_machine.travel(timezone.now() + timedelta(seconds=AUTHORIZED_RETRIEVAL_SECONDS + 1), tick=False):
+ late = self.client.post("/api/cli-auth/poll/", {"device_code": self.device_code})
+ self.assertEqual(late.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(late.json()["status"], "expired")
+
+ @parameterized.expand(
+ [
+ ("long after approval", 300, status.HTTP_200_OK),
+ ("after the code expires", DEVICE_CODE_EXPIRY_SECONDS + 1, status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_an_approved_key_waits_for_the_first_poll_until_the_code_expires(
+ self, _name: str, seconds_later: int, expected_status: int
+ ):
+ self.client.post("/api/cli-auth/authorize/", {"user_code": self.user_code, "project_id": self.team.id})
+
+ with time_machine.travel(timezone.now() + timedelta(seconds=seconds_later), tick=False):
+ response = self.client.post("/api/cli-auth/poll/", {"device_code": self.device_code})
+
+ self.assertEqual(response.status_code, expected_status)
class TestCLIAuthEndToEnd(APIBaseTest):