: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
fix(cli): show valid command after login (#64598)
Chris Volzer7be64cbe1e98
diff --git a/cli/.sampo/changesets/login-next-command-hint.md b/cli/.sampo/changesets/login-next-command-hint.mdnew file mode 100644index 000000000000..45511f96b6f6--- /dev/null+++ b/cli/.sampo/changesets/login-next-command-hint.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Fix the post-login hint so `posthog-cli login` suggests a valid next command based on the scopes authorized for the generated key.diff --git a/cli/src/login.rs b/cli/src/login.rsindex b5ca65b5046d..635b6281cb94 100644--- a/cli/src/login.rs+++ b/cli/src/login.rs@@ -33,12 +33,18 @@ struct PollResponse {status: String,personal_api_key: Option<String>,project_id: Option<String>,+ scopes: Option<Vec<String>>,}// The `agent-cli` use case grants the full MCP / `posthog-cli api` scope set// (a superset of schema + error_tracking + endpoints), so a freshly logged-in// CLI can run the agent interface without re-authorizing.const DEFAULT_LOGIN_USE_CASES: &[&str] = &["agent-cli"];+const NEXT_COMMAND_AGENT_CLI: &str = "posthog-cli api tools";+const NEXT_COMMAND_ERROR_TRACKING: &str = "posthog-cli sourcemap --help";+const NEXT_COMMAND_SCHEMA: &str = "posthog-cli exp schema pull";+const NEXT_COMMAND_ENDPOINTS: &str = "posthog-cli exp endpoints list";+const NEXT_COMMAND_DEFAULT: &str = "posthog-cli --help";pub fn login(host_override: Option<String>) -> Result<()> {if !io::stdout().is_terminal() {@@ -118,6 +124,7 @@ pub fn login_with_use_cases(host_override: Option<String>, use_cases: Vec<&str>)device_data.interval,device_data.expires_in,)?;+ let authorized_scopes = poll_response.scopes.clone().unwrap_or_default();info!("✓ Successfully authenticated!");@@ -132,7 +139,12 @@ pub fn login_with_use_cases(host_override: Option<String>, use_cases: Vec<&str>)info!("Token saved to: {}", provider.report_location());- complete_login(&provider, "interactive_login")+ complete_login(+ &provider,+ "interactive_login",+ &authorized_scopes,+ &use_cases,+ )}fn request_device_code(host: &str) -> Result<DeviceCodeResponse, Error> {@@ -252,17 +264,80 @@ fn poll_for_authorization())}-fn complete_login(provider: &HomeDirProvider, command_name: &str) -> Result<(), Error> {+fn has_scope_action(scopes: &[String], object: &str) -> bool {+ scopes.iter().any(|scope| {+ scope == "*" || scope == &format!("{object}:read") || scope == &format!("{object}:write")+ })+}++fn use_cases_include(use_cases: &[&str], candidates: &[&str]) -> bool {+ use_cases+ .iter()+ .any(|use_case| candidates.contains(use_case))+}++fn recommended_next_command(scopes: &[String], use_cases: &[&str]) -> &'static str {+ if !scopes.is_empty() {+ if has_scope_action(scopes, "user")+ && has_scope_action(scopes, "project")+ && has_scope_action(scopes, "query")+ {+ return NEXT_COMMAND_AGENT_CLI;+ }++ if has_scope_action(scopes, "error_tracking") {+ return NEXT_COMMAND_ERROR_TRACKING;+ }++ if has_scope_action(scopes, "event_definition")+ && has_scope_action(scopes, "property_definition")+ {+ return NEXT_COMMAND_SCHEMA;+ }++ if has_scope_action(scopes, "endpoint") {+ return NEXT_COMMAND_ENDPOINTS;+ }++ return NEXT_COMMAND_DEFAULT;+ }++ if use_cases_include(use_cases, &["agent-cli", "agent"]) {+ return NEXT_COMMAND_AGENT_CLI;+ }++ if use_cases_include(use_cases, &["error_tracking", "error-tracking"]) {+ return NEXT_COMMAND_ERROR_TRACKING;+ }++ if use_cases_include(use_cases, &["schema"]) {+ return NEXT_COMMAND_SCHEMA;+ }++ if use_cases_include(use_cases, &["endpoints"]) {+ return NEXT_COMMAND_ENDPOINTS;+ }++ NEXT_COMMAND_DEFAULT+}++fn complete_login(+ provider: &HomeDirProvider,+ command_name: &str,+ scopes: &[String],+ use_cases: &[&str],+) -> Result<(), Error> {// Login is the only command that doesn't have a context coming in - because it modifies the contextinit_context(None, false, None, None)?;context().capture_command_invoked(command_name);+ let next_command = recommended_next_command(scopes, use_cases);println!();println!("🎉 Authentication complete!");println!("Credentials saved to: {}", provider.report_location());println!();println!("You can now use the CLI:");- println!(" posthog-cli schema pull");+ println!(" {next_command}");println!();Ok(())@@ -295,7 +370,7 @@ fn manual_login() -> Result<(), Error> {info!("Token saved to: {}", provider.report_location());- complete_login(&provider, "manual_login")+ complete_login(&provider, "manual_login", &[], &[])}#[cfg(test)]@@ -308,4 +383,46 @@ mod tests {// scope set; narrowing it here would silently break agent commands.assert_eq!(DEFAULT_LOGIN_USE_CASES, &["agent-cli"]);}++ #[test]+ fn recommends_api_tools_for_agent_cli_use_case() {+ assert_eq!(+ recommended_next_command(&[], &["agent-cli"]),+ NEXT_COMMAND_AGENT_CLI+ );+ }++ #[test]+ fn recommends_api_tools_for_agent_capable_scopes() {+ let scopes = vec![+ "user:read".to_string(),+ "project:read".to_string(),+ "query:read".to_string(),+ ];++ assert_eq!(+ recommended_next_command(&scopes, &["error_tracking"]),+ NEXT_COMMAND_AGENT_CLI+ );+ }++ #[test]+ fn recommends_sourcemap_for_error_tracking_scopes() {+ let scopes = vec!["error_tracking:write".to_string()];++ assert_eq!(+ recommended_next_command(&scopes, &["agent-cli"]),+ NEXT_COMMAND_ERROR_TRACKING+ );+ }++ #[test]+ fn recommends_schema_for_schema_scopes() {+ let scopes = vec![+ "event_definition:read".to_string(),+ "property_definition:read".to_string(),+ ];++ assert_eq!(recommended_next_command(&scopes, &[]), NEXT_COMMAND_SCHEMA);+ }}diff --git a/posthog/api/cli_auth.py b/posthog/api/cli_auth.pyindex f1c0a309d4ee..fbb0b322c510 100644--- a/posthog/api/cli_auth.py+++ b/posthog/api/cli_auth.py@@ -17,6 +17,7 @@ import secretsfrom django.core.cache import cachefrom django.utils import timezone+from drf_spectacular.utils import extend_schemafrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.permissions import AllowAny, IsAuthenticated@@ -107,8 +108,14 @@ class DevicePollResponseSerializer(serializers.Serializer):personal_api_key = serializers.CharField(required=False, help_text="The API key (only if authorized)")label = serializers.CharField(required=False, help_text="Label of the created key") # type: ignore[assignment]project_id = serializers.CharField(required=False, help_text="The project ID (only if authorized)")+ scopes = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Scopes granted to the created API key (only if authorized)",+ )+@extend_schema(extensions={"x-product": "core"})class CLIAuthViewSet(viewsets.ViewSet):"""OAuth2 Device Authorization Flow for CLI authentication@@ -135,6 +142,7 @@ class CLIAuthViewSet(viewsets.ViewSet):return []+ @extend_schema(request=None, responses={200: DeviceCodeResponseSerializer})@action(methods=["POST"], detail=False, url_path="device-code")def device_code(self, request):"""@@ -177,6 +185,7 @@ class CLIAuthViewSet(viewsets.ViewSet):serializer = DeviceCodeResponseSerializer(response_data)return Response(serializer.data, status=status.HTTP_200_OK)+ @extend_schema(request=DeviceAuthorizationSerializer)@action(methods=["POST"], detail=False, url_path="authorize")def authorize(self, request):"""@@ -285,6 +294,7 @@ class CLIAuthViewSet(viewsets.ViewSet):device_data["personal_api_key"] = api_key_valuedevice_data["label"] = labeldevice_data["project_id"] = str(project_id)+ device_data["scopes"] = scopesdevice_data["authorized_at"] = timezone.now().isoformat()device_data["user_id"] = user.id@@ -300,6 +310,7 @@ class CLIAuthViewSet(viewsets.ViewSet):status=status.HTTP_200_OK,)+ @extend_schema(request=DevicePollSerializer, responses={200: DevicePollResponseSerializer})@action(methods=["POST"], detail=False, url_path="poll")def poll(self, request):"""@@ -339,6 +350,7 @@ class CLIAuthViewSet(viewsets.ViewSet):"personal_api_key": device_data["personal_api_key"],"label": device_data["label"],"project_id": device_data["project_id"],+ "scopes": device_data.get("scopes", []),}# Clean up - key has been retrieveddiff --git a/posthog/api/test/test_cli_auth.py b/posthog/api/test/test_cli_auth.pyindex 41cd5fcadb4b..682389672160 100644--- a/posthog/api/test/test_cli_auth.py+++ b/posthog/api/test/test_cli_auth.py@@ -254,9 +254,11 @@ class TestCLIAuthAuthorizeEndpoint(APIBaseTest):def test_authorization_updates_cache_with_api_key(self):"""Test that authorization updates the cache with the API key"""+ submitted_scopes = ["error_tracking:write"]+response = self.client.post("/api/cli-auth/authorize/",- {"user_code": self.user_code, "project_id": self.team.id},+ {"user_code": self.user_code, "project_id": self.team.id, "scopes": submitted_scopes},)self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -268,6 +270,7 @@ class TestCLIAuthAuthorizeEndpoint(APIBaseTest):self.assertEqual(device_data["status"], "authorized")self.assertIn("personal_api_key", device_data)self.assertEqual(device_data["project_id"], str(self.team.id))+ self.assertEqual(device_data["scopes"], submitted_scopes)self.assertEqual(device_data["user_id"], self.user.id)def test_multiple_users_can_authorize_different_codes(self):@@ -349,10 +352,12 @@ class TestCLIAuthPollEndpoint(APIBaseTest):def test_poll_returns_api_key_after_authorization(self):"""Test that polling returns API key after user authorizes"""+ submitted_scopes = ["error_tracking:write"]+# Authorize the codeself.client.post("/api/cli-auth/authorize/",- {"user_code": self.user_code, "project_id": self.team.id},+ {"user_code": self.user_code, "project_id": self.team.id, "scopes": submitted_scopes},)# Poll for the result@@ -364,6 +369,7 @@ class TestCLIAuthPollEndpoint(APIBaseTest):self.assertIn("personal_api_key", data)self.assertIn("label", data)self.assertEqual(data["project_id"], str(self.team.id))+ self.assertEqual(data["scopes"], submitted_scopes)# Verify the API key is validapi_key = data["personal_api_key"]