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): open only web URLs from the server, without cmd on Windows (#129930)

James Gilldcc1bd9fe4cc
diff --git a/cli/.sampo/changesets/plain-web-urls.md b/cli/.sampo/changesets/plain-web-urls.md
new file mode 100644
index 000000000000..8b32737876d7
--- /dev/null
+++ b/cli/.sampo/changesets/plain-web-urls.md
@@ -0,0 +1,5 @@
+---
+cargo/posthog-cli: patch
+---
+
+Open only http and https server URLs with expected characters, and open them on Windows without `cmd`
diff --git a/cli/Cargo.lock b/cli/Cargo.lock
index 0dd378c9f733..10a4fc618ef9 100644
--- a/cli/Cargo.lock
+++ b/cli/Cargo.lock
@@ -1939,6 +1939,7 @@ version = "5.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43bb73a7fa3799b198970490a51174027ba0d4ec504b03cd08caf513d40024bc"
dependencies = [
+ "dunce",
"is-wsl",
"libc",
"pathdiff",
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
index 22a3ce83025f..1f3dda3a1fa5 100644
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -74,7 +74,9 @@ urlencoding = "2.1.3"
url = "2"
rayon = "1.11.0"
similar = "2.7"
-open = "5"
+# With this feature, `open::that_detached` on Windows calls ShellExecuteExW. Without it, it runs
+# `cmd /c start` and cmd parses the URL. WebUrl::open_in_browser relies on the feature.
+open = { version = "5", features = ["shellexecute-on-windows"] }
zip = { version = "2.2", default-features = false, features = ["deflate", "deflate-zlib"] }
tempfile = "3"
symbolic = { version = "12.12", features = ["debuginfo"] }
diff --git a/cli/clippy.toml b/cli/clippy.toml
new file mode 100644
index 000000000000..fed169657f67
--- /dev/null
+++ b/cli/clippy.toml
@@ -0,0 +1,10 @@
+disallowed-methods = [
+ { path = "open::that", reason = "use WebUrl::open_in_browser" },
+ { path = "open::that_detached", reason = "use WebUrl::open_in_browser" },
+ { path = "open::that_in_background", reason = "use WebUrl::open_in_browser" },
+ { path = "open::with", reason = "use WebUrl::open_in_browser" },
+ { path = "open::with_detached", reason = "use WebUrl::open_in_browser" },
+ { path = "open::with_in_background", reason = "use WebUrl::open_in_browser" },
+ { path = "open::commands", reason = "use WebUrl::open_in_browser" },
+ { path = "open::with_command", reason = "use WebUrl::open_in_browser" },
+]
diff --git a/cli/src/experimental/endpoints/open.rs b/cli/src/experimental/endpoints/open.rs
index 77e9c3824998..93b301c17ff2 100644
--- a/cli/src/experimental/endpoints/open.rs
+++ b/cli/src/experimental/endpoints/open.rs
@@ -1,6 +1,6 @@
-use anyhow::{Context, Result};
+use anyhow::Result;
-use crate::invocation_context::context;
+use crate::{invocation_context::context, utils::web_url::WebUrl};
use super::{fetch_endpoint, OpenArgs};
@@ -12,9 +12,10 @@ pub fn open_endpoint(args: &OpenArgs) -> Result<()> {
let ui_url = endpoint
.ui_url
.ok_or_else(|| anyhow::anyhow!("Endpoint has no UI URL"))?;
+ let ui_url = WebUrl::try_from(ui_url)?;
crate::safe_println!("Opening {ui_url}...");
- open::that(&ui_url).context("Failed to open browser")?;
+ ui_url.open_in_browser()?;
Ok(())
}
diff --git a/cli/src/login.rs b/cli/src/login.rs
index 4c4c9440118d..ce584c7cf3fd 100644
--- a/cli/src/login.rs
+++ b/cli/src/login.rs
@@ -8,9 +8,12 @@ use tracing::info;
use crate::{
invocation_context::{context, init_context},
- utils::auth::{
- env_id_validator, host_validator, token_validator, CredentialProvider, HomeDirProvider,
- Token,
+ utils::{
+ auth::{
+ env_id_validator, host_validator, token_validator, CredentialProvider, HomeDirProvider,
+ Token,
+ },
+ web_url::WebUrl,
},
};
@@ -18,7 +21,7 @@ use crate::{
struct DeviceCodeResponse {
device_code: String,
user_code: String,
- verification_uri_complete: String,
+ verification_uri_complete: WebUrl,
expires_in: u64,
interval: u64,
}
@@ -80,19 +83,9 @@ pub fn login_with_use_cases(host_override: Option<String>, use_cases: Vec<&str>)
// Step 1: Request device code
let device_data = request_device_code(&host)?;
- // Add use_cases parameter to the verification URL
- let use_cases_param = use_cases.join(",");
- let verification_url = if device_data.verification_uri_complete.contains('?') {
- format!(
- "{}&use_cases={}",
- device_data.verification_uri_complete, use_cases_param
- )
- } else {
- format!(
- "{}?use_cases={}",
- device_data.verification_uri_complete, use_cases_param
- )
- };
+ let verification_url = device_data
+ .verification_uri_complete
+ .with_query_pair("use_cases", &use_cases.join(","))?;
crate::safe_println!();
crate::safe_println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
@@ -109,7 +102,7 @@ pub fn login_with_use_cases(host_override: Option<String>, use_cases: Vec<&str>)
crate::safe_println!();
// Step 2: Try to open browser
- if let Err(e) = open_browser(&verification_url) {
+ if let Err(e) = verification_url.open_in_browser() {
info!("Could not open browser automatically: {}", e);
info!("Please open the URL manually");
} else {
@@ -171,35 +164,6 @@ fn request_device_code(host: &str) -> Result<DeviceCodeResponse, Error> {
Ok(device_data)
}
-fn open_browser(url: &str) -> Result<(), Error> {
- // Try to open browser using platform-specific commands
- #[cfg(target_os = "macos")]
- {
- std::process::Command::new("open")
- .arg(url)
- .spawn()
- .context("Failed to open browser")?;
- }
-
- #[cfg(target_os = "linux")]
- {
- std::process::Command::new("xdg-open")
- .arg(url)
- .spawn()
- .context("Failed to open browser")?;
- }
-
- #[cfg(target_os = "windows")]
- {
- std::process::Command::new("cmd")
- .args(&["/C", "start", url])
- .spawn()
- .context("Failed to open browser")?;
- }
-
- Ok(())
-}
-
fn poll_for_authorization(
host: &str,
device_code: &str,
@@ -425,4 +389,48 @@ mod tests {
assert_eq!(recommended_next_command(&scopes, &[]), NEXT_COMMAND_SCHEMA);
}
+
+ #[test]
+ fn device_code_response_accepts_only_web_urls() {
+ let parse = |url: &str| {
+ serde_json::from_value::<DeviceCodeResponse>(serde_json::json!({
+ "device_code": "device",
+ "user_code": "ABCD-1234",
+ "verification_uri_complete": url,
+ "expires_in": 600,
+ "interval": 5,
+ }))
+ };
+
+ for url in [
+ "https://us.posthog.com/cli/authorize?code=ABCD-1234",
+ "http://localhost:8010/cli/authorize?code=ABCD-1234",
+ ] {
+ assert!(parse(url).is_ok(), "{url} should be accepted");
+ }
+
+ for url in [
+ "file:///etc/hosts",
+ "javascript:void(0)",
+ "custom-app://open",
+ "not a url",
+ "https://us.posthog.com/cli/authorize?code=ABCD$1234",
+ ] {
+ assert!(parse(url).is_err(), "{url} should be rejected");
+ }
+ }
+
+ #[test]
+ fn verification_url_keeps_the_server_code_and_adds_the_use_cases() {
+ let url =
+ WebUrl::try_from("https://us.posthog.com/cli/authorize?code=ABCD-1234".to_string())
+ .unwrap();
+
+ assert_eq!(
+ url.with_query_pair("use_cases", &DEFAULT_LOGIN_USE_CASES.join(","))
+ .unwrap()
+ .to_string(),
+ "https://us.posthog.com/cli/authorize?code=ABCD-1234&use_cases=agent-cli"
+ );
+ }
}
diff --git a/cli/src/utils/mod.rs b/cli/src/utils/mod.rs
index 9f6c03396c2c..b612e44d0f46 100644
--- a/cli/src/utils/mod.rs
+++ b/cli/src/utils/mod.rs
@@ -9,6 +9,7 @@ pub mod files;
pub mod git;
pub mod homedir;
pub mod throttler;
+pub mod web_url;
pub mod xcode;
pub fn raise_for_err(response: Response) -> Result<Response> {
diff --git a/cli/src/utils/web_url.rs b/cli/src/utils/web_url.rs
new file mode 100644
index 000000000000..e6268a0353b1
--- /dev/null
+++ b/cli/src/utils/web_url.rs
@@ -0,0 +1,57 @@
+use std::fmt;
+
+use anyhow::{ensure, Context, Error, Result};
+use serde::Deserialize;
+use url::Url;
+
+#[derive(Debug, Deserialize)]
+#[serde(try_from = "String")]
+pub struct WebUrl(Url);
+
+impl WebUrl {
+ fn new(url: Url) -> Result<Self> {
+ ensure!(
+ matches!(url.scheme(), "http" | "https"),
+ "The server returned a {} URL. The CLI only opens http and https URLs, so check that your PostHog host is correct",
+ url.scheme()
+ );
+ // On WSL, `wslview` puts the URL in a double-quoted PowerShell string, where none of
+ // these characters is syntax. PostHog URLs use no others.
+ ensure!(
+ url.as_str()
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || "-._~:/?#[]@&=+,%".contains(c)),
+ "The server returned a URL with characters that the CLI does not open, so check that your PostHog host is correct"
+ );
+ Ok(Self(url))
+ }
+
+ pub fn with_query_pair(mut self, name: &str, value: &str) -> Result<Self> {
+ self.0.query_pairs_mut().append_pair(name, value);
+ Self::new(self.0)
+ }
+
+ /// Only `that_detached` avoids `cmd` on Windows. Elsewhere `that` reports a failed opener.
+ #[allow(clippy::disallowed_methods)]
+ pub fn open_in_browser(&self) -> Result<()> {
+ #[cfg(windows)]
+ let opened = open::that_detached(self.0.as_str());
+ #[cfg(not(windows))]
+ let opened = open::that(self.0.as_str());
+ opened.context("Failed to open browser")
+ }
+}
+
+impl TryFrom<String> for WebUrl {
+ type Error = Error;
+
+ fn try_from(raw: String) -> Result<Self> {
+ Self::new(Url::parse(&raw).context("The server returned a URL that is not valid")?)
+ }
+}
+
+impl fmt::Display for WebUrl {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.0.fmt(f)
+ }
+}