: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
feat(cli): load credentials from .env (#60465)
Aleksander Błaszkiewicz02c62915fd01
diff --git a/cli/CHANGELOG.md b/cli/CHANGELOG.mdindex a80790ab70c0..ee15be32de21 100644--- a/cli/CHANGELOG.md+++ b/cli/CHANGELOG.md@@ -1,5 +1,9 @@# posthog-cli+# 0.7.14++- feat: add `--env-file <PATH>` to load `POSTHOG_CLI_HOST`, `POSTHOG_CLI_API_KEY`, and `POSTHOG_CLI_PROJECT_ID` (and their legacy aliases) from a dotenv-style file when not set in the process environment. Credentials are resolved atomically from a single source (process env first, then the file), so `POSTHOG_CLI_HOST` from the file cannot redirect a key supplied by the process env.+# 0.7.13- chore: bump `cargo-dist` to 0.32.0; the new npm installer drops the bundled transitive deps that were carrying open CVEs (`axios`, `follow-redirects`, `minimatch`, `brace-expansion`)diff --git a/cli/Cargo.lock b/cli/Cargo.lockindex fd65c1e4152a..2dcd79f4ad10 100644--- a/cli/Cargo.lock+++ b/cli/Cargo.lock@@ -1851,7 +1851,7 @@ dependencies = [[[package]]name = "posthog-cli"-version = "0.7.13"+version = "0.7.14"dependencies = ["anyhow","chrono",diff --git a/cli/Cargo.toml b/cli/Cargo.tomlindex 1e819a6900a7..e3e70881d088 100644--- a/cli/Cargo.toml+++ b/cli/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-cli"-version = "0.7.13"+version = "0.7.14"authors = ["David <[email protected]>","Olly <[email protected]>",diff --git a/cli/README.md b/cli/README.mdindex 2e151dadb1d6..d2af5efa053b 100644--- a/cli/README.md+++ b/cli/README.md@@ -27,6 +27,10 @@ You can authenticate with PostHog interactively for using the CLI locally, but i- `POSTHOG_CLI_API_KEY`: [A posthog personal API key.](https://posthog.com/docs/api#private-endpoint-authentication) (also accepts `POSTHOG_CLI_TOKEN` for backward compatibility)- `POSTHOG_CLI_PROJECT_ID`: The ID number of the project/environment to connect to. E.g. the "2" in `https://us.posthog.com/project/2` (also accepts `POSTHOG_CLI_ENV_ID` for backward compatibility)+These variables can also be loaded from a dotenv-style file via `--env-file <PATH>` (e.g. `posthog-cli --env-file .env query ...`). The process environment always wins; the file is only consulted if the required variables aren't set. `POSTHOG_CLI_HOST` is only read from the same source that supplied the rest, so a stray host in the file cannot redirect a key supplied by the process env.++Full precedence: CLI args → process env → `--env-file` → `~/.posthog/credentials.json` (from `posthog-cli login`).+### Personal API key scopesCommands require different API scopes. Make sure to set these scopes on your personal API key:diff --git a/cli/src/commands.rs b/cli/src/commands.rsindex 6b613690a4c2..2c978b1cc85b 100644--- a/cli/src/commands.rs+++ b/cli/src/commands.rs@@ -1,3 +1,5 @@+use std::path::PathBuf;+use anyhow::Context;use clap::{Parser, Subcommand};use tracing::error;@@ -30,6 +32,10 @@ pub struct Cli {#[arg(long, env = "POSTHOG_CLIENT_RATE_LIMIT")]rate_limit: Option<usize>,+ /// Load PostHog credentials from this dotenv-style file when not present in the process environment.+ #[arg(long, value_name = "PATH")]+ env_file: Option<PathBuf>,+#[command(subcommand)]command: Commands,}@@ -174,6 +180,7 @@ impl Cli {self.host.clone(),self.skip_ssl_verification,self.rate_limit,+ self.env_file.clone(),)?;}diff --git a/cli/src/invocation_context.rs b/cli/src/invocation_context.rsindex 9b541823b192..ab2c5284aabf 100644--- a/cli/src/invocation_context.rs+++ b/cli/src/invocation_context.rs@@ -8,6 +8,7 @@ use reqwest::blocking::Client;use serde_json::json;use std::{io::{self, IsTerminal},+ path::PathBuf,sync::{Mutex, OnceLock},thread::JoinHandle,};@@ -33,8 +34,13 @@ pub fn context() -> &'static InvocationContext {INVOCATION_CONTEXT.get().expect("Context has been set up")}-pub fn init_context(host: Option<String>, skip_ssl: bool, rate_limit: Option<usize>) -> Result<()> {- let token = get_token()?;+pub fn init_context(+ host: Option<String>,+ skip_ssl: bool,+ rate_limit: Option<usize>,+ env_file: Option<PathBuf>,+) -> Result<()> {+ let token = get_token(env_file)?;let config = InvocationConfig {api_key: token.token.clone(),host: host.unwrap_or(token.host.unwrap_or("https://us.i.posthog.com".into())),diff --git a/cli/src/login.rs b/cli/src/login.rsindex 11cf5cd6f231..4b7ce5c022c2 100644--- a/cli/src/login.rs+++ b/cli/src/login.rs@@ -249,7 +249,7 @@ fn poll_for_authorization(fn complete_login(provider: &HomeDirProvider, command_name: &str) -> Result<(), Error> {// Login is the only command that doesn't have a context coming in - because it modifies the context- init_context(None, false, None)?;+ init_context(None, false, None, None)?;context().capture_command_invoked(command_name);println!();diff --git a/cli/src/utils/auth.rs b/cli/src/utils/auth.rsindex b835da66463b..93dade4f3339 100644--- a/cli/src/utils/auth.rs+++ b/cli/src/utils/auth.rs@@ -1,7 +1,9 @@+use super::dotenv::load_dotenv;use super::homedir::{ensure_homedir_exists, posthog_home_dir};use anyhow::{Context, Error};use inquire::{validator::Validation, CustomUserError};use reqwest::Url;+use std::path::PathBuf;use tracing::info;use serde::{Deserialize, Serialize};@@ -59,25 +61,40 @@ impl CredentialProvider for HomeDirProvider {}}-/// Tries to read the token from the env var `POSTHOG_CLI_API_KEY`-pub struct EnvVarProvider;+/// Reads credentials atomically from a single source. Tries the process env first; if the+/// required variables aren't there and an explicit `--env-file` path was supplied, tries that+/// file next. `host` is optional and is only read from the same source that supplied the rest.+pub struct EnvVarProvider {+ pub env_file: Option<PathBuf>,+}++fn try_source<F: Fn(&str) -> Option<String>>(lookup: F) -> Option<Token> {+ let token = lookup("POSTHOG_CLI_API_KEY").or_else(|| lookup("POSTHOG_CLI_TOKEN"))?;+ let env_id = lookup("POSTHOG_CLI_PROJECT_ID").or_else(|| lookup("POSTHOG_CLI_ENV_ID"))?;+ let host = lookup("POSTHOG_CLI_HOST");+ Some(Token {+ host,+ token,+ env_id,+ })+}impl CredentialProvider for EnvVarProvider {fn get_credentials(&self) -> Result<Token, Error> {- let host = std::env::var("POSTHOG_CLI_HOST").ok();- // Try POSTHOG_CLI_API_KEY first, fall back to POSTHOG_CLI_TOKEN for backward compatibility- let token = std::env::var("POSTHOG_CLI_API_KEY")- .or_else(|_| std::env::var("POSTHOG_CLI_TOKEN"))- .context("While trying to read env var POSTHOG_CLI_API_KEY")?;- // Try POSTHOG_CLI_PROJECT_ID first, fall back to POSTHOG_CLI_ENV_ID for backward compatibility- let env_id = std::env::var("POSTHOG_CLI_PROJECT_ID")- .or_else(|_| std::env::var("POSTHOG_CLI_ENV_ID"))- .context("While trying to read env var POSTHOG_CLI_PROJECT_ID")?;- Ok(Token {- host,- token,- env_id,- })+ if let Some(t) = try_source(|n| std::env::var(n).ok()) {+ return Ok(t);+ }+ if let Some(path) = &self.env_file {+ let file = load_dotenv(path)?;+ if let Some(t) = try_source(|n| file.get(n).cloned()) {+ return Ok(t);+ }+ anyhow::bail!(+ "Couldn't find POSTHOG_CLI_API_KEY and POSTHOG_CLI_PROJECT_ID in process env or {}",+ path.display()+ )+ }+ anyhow::bail!("Couldn't find POSTHOG_CLI_API_KEY and POSTHOG_CLI_PROJECT_ID in process env")}fn store_credentials(&self, _token: Token) -> Result<(), Error> {@@ -127,11 +144,14 @@ pub fn env_id_validator(env_id: &str) -> Result<Validation, CustomUserError> {Ok(Validation::Valid)}-pub fn get_token() -> Result<Token, Error> {- let env = EnvVarProvider;+pub fn get_token(env_file: Option<PathBuf>) -> Result<Token, Error> {+ let env = EnvVarProvider { env_file };let env_err = match env.get_credentials() {Ok(token) => {- info!("Using token from env var, for environment {}", token.env_id);+ info!(+ "Using token from environment or --env-file, for environment {}",+ token.env_id+ );return Ok(token);}Err(e) => e,@@ -155,3 +175,160 @@ pub fn get_token() -> Result<Token, Error> {.context(dir_err),)}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::HashMap;+ use std::io::Write;++ fn lookup<'a>(map: &'a HashMap<&'a str, &'a str>) -> impl Fn(&str) -> Option<String> + 'a {+ move |k| map.get(k).map(|v| v.to_string())+ }++ #[test]+ fn try_source_returns_none_when_required_missing() {+ let map = HashMap::new();+ assert!(try_source(lookup(&map)).is_none());+ }++ #[test]+ fn try_source_requires_both_api_key_and_project_id() {+ let mut only_key = HashMap::new();+ only_key.insert("POSTHOG_CLI_API_KEY", "phx_abc");+ assert!(try_source(lookup(&only_key)).is_none());++ let mut only_id = HashMap::new();+ only_id.insert("POSTHOG_CLI_PROJECT_ID", "1");+ assert!(try_source(lookup(&only_id)).is_none());+ }++ #[test]+ fn try_source_accepts_legacy_aliases() {+ let mut map = HashMap::new();+ map.insert("POSTHOG_CLI_TOKEN", "phx_legacy");+ map.insert("POSTHOG_CLI_ENV_ID", "42");+ let token = try_source(lookup(&map)).expect("should resolve");+ assert_eq!(token.token, "phx_legacy");+ assert_eq!(token.env_id, "42");+ assert!(token.host.is_none());+ }++ #[test]+ fn try_source_prefers_canonical_over_legacy() {+ let mut map = HashMap::new();+ map.insert("POSTHOG_CLI_API_KEY", "phx_new");+ map.insert("POSTHOG_CLI_TOKEN", "phx_old");+ map.insert("POSTHOG_CLI_PROJECT_ID", "1");+ map.insert("POSTHOG_CLI_ENV_ID", "2");+ let token = try_source(lookup(&map)).unwrap();+ assert_eq!(token.token, "phx_new");+ assert_eq!(token.env_id, "1");+ }++ #[test]+ fn try_source_host_is_optional() {+ let mut map = HashMap::new();+ map.insert("POSTHOG_CLI_API_KEY", "phx_abc");+ map.insert("POSTHOG_CLI_PROJECT_ID", "1");+ let token = try_source(lookup(&map)).unwrap();+ assert!(token.host.is_none());+ }++ #[test]+ fn try_source_picks_up_host_from_same_source() {+ let mut map = HashMap::new();+ map.insert("POSTHOG_CLI_API_KEY", "phx_abc");+ map.insert("POSTHOG_CLI_PROJECT_ID", "1");+ map.insert("POSTHOG_CLI_HOST", "https://eu.posthog.com");+ let token = try_source(lookup(&map)).unwrap();+ assert_eq!(token.host.as_deref(), Some("https://eu.posthog.com"));+ }++ #[test]+ fn try_source_ignores_host_when_required_missing() {+ // Host alone is not enough to count as a valid source — it must not leak through.+ let mut map = HashMap::new();+ map.insert("POSTHOG_CLI_HOST", "https://attacker.example");+ assert!(try_source(lookup(&map)).is_none());+ }++ // Tests below mutate the real process env. Serialize them against each other so parallel+ // test execution doesn't cause one test's setup to leak into another's assertion.+ static ENV_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++ const ENV_VARS: &[&str] = &[+ "POSTHOG_CLI_API_KEY",+ "POSTHOG_CLI_TOKEN",+ "POSTHOG_CLI_PROJECT_ID",+ "POSTHOG_CLI_ENV_ID",+ "POSTHOG_CLI_HOST",+ ];++ fn clear_env() {+ for v in ENV_VARS {+ std::env::remove_var(v);+ }+ }++ #[test]+ fn provider_prefers_process_env_over_env_file() {+ let _guard = ENV_TEST_LOCK.lock().unwrap();+ clear_env();+ std::env::set_var("POSTHOG_CLI_API_KEY", "phx_from_env");+ std::env::set_var("POSTHOG_CLI_PROJECT_ID", "111");++ let mut f = tempfile::NamedTempFile::new().unwrap();+ writeln!(f, "POSTHOG_CLI_API_KEY=phx_from_file").unwrap();+ writeln!(f, "POSTHOG_CLI_PROJECT_ID=222").unwrap();++ let provider = EnvVarProvider {+ env_file: Some(f.path().to_path_buf()),+ };+ let token = provider.get_credentials().unwrap();+ assert_eq!(token.token, "phx_from_env");+ assert_eq!(token.env_id, "111");++ clear_env();+ }++ #[test]+ fn env_file_cannot_exfiltrate_process_api_key_via_interpolation() {+ let _guard = ENV_TEST_LOCK.lock().unwrap();+ clear_env();+ // Real key in the process env, but no project id — so the env-file fallback runs.+ std::env::set_var("POSTHOG_CLI_API_KEY", "phx_process_secret");++ let mut f = tempfile::NamedTempFile::new().unwrap();+ writeln!(f, "POSTHOG_CLI_API_KEY=${{POSTHOG_CLI_API_KEY}}").unwrap();+ writeln!(f, "POSTHOG_CLI_PROJECT_ID=42").unwrap();+ writeln!(f, "POSTHOG_CLI_HOST=https://attacker.example").unwrap();++ let provider = EnvVarProvider {+ env_file: Some(f.path().to_path_buf()),+ };+ let token = provider.get_credentials().unwrap();+ assert_ne!(token.token, "phx_process_secret");+ assert_eq!(token.token, "${POSTHOG_CLI_API_KEY}");+ assert_eq!(token.host.as_deref(), Some("https://attacker.example"));++ clear_env();+ }++ #[test]+ fn provider_falls_back_to_env_file_when_process_env_missing() {+ let _guard = ENV_TEST_LOCK.lock().unwrap();+ clear_env();++ let mut f = tempfile::NamedTempFile::new().unwrap();+ writeln!(f, "POSTHOG_CLI_API_KEY=phx_from_file").unwrap();+ writeln!(f, "POSTHOG_CLI_PROJECT_ID=222").unwrap();++ let provider = EnvVarProvider {+ env_file: Some(f.path().to_path_buf()),+ };+ let token = provider.get_credentials().unwrap();+ assert_eq!(token.token, "phx_from_file");+ assert_eq!(token.env_id, "222");+ }+}diff --git a/cli/src/utils/dotenv.rs b/cli/src/utils/dotenv.rsnew file mode 100644index 000000000000..a3f54c28ac98--- /dev/null+++ b/cli/src/utils/dotenv.rs@@ -0,0 +1,95 @@+use anyhow::{Context, Error};+use std::collections::HashMap;+use std::path::Path;++// Credential values are read literally — no $VAR/${VAR} interpolation — so a credentials file+// can't pull a secret out of the process environment and pair it with a host of its choosing.+pub(crate) fn load_dotenv(path: &Path) -> Result<HashMap<String, String>, Error> {+ let contents = std::fs::read_to_string(path)+ .with_context(|| format!("While trying to read env file {}", path.display()))?;+ let mut map = HashMap::new();+ for (i, raw) in contents.lines().enumerate() {+ let line = raw.trim();+ if line.is_empty() || line.starts_with('#') {+ continue;+ }+ let (key, value) = line.split_once('=').with_context(|| {+ format!(+ "Malformed line {} in env file {}: expected KEY=VALUE",+ i + 1,+ path.display()+ )+ })?;+ let key = key.trim();+ if key.is_empty() {+ anyhow::bail!(+ "Malformed line {} in env file {}: empty key",+ i + 1,+ path.display()+ );+ }+ map.insert(key.to_string(), unquote(value.trim()).to_string());+ }+ Ok(map)+}++fn unquote(value: &str) -> &str {+ let bytes = value.as_bytes();+ if bytes.len() >= 2 {+ let quote = bytes[0];+ if (quote == b'"' || quote == b'\'') && bytes[bytes.len() - 1] == quote {+ return &value[1..value.len() - 1];+ }+ }+ value+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;++ #[test]+ fn load_dotenv_parses_file() {+ let mut f = tempfile::NamedTempFile::new().unwrap();+ writeln!(f, "POSTHOG_CLI_API_KEY=phx_from_file").unwrap();+ writeln!(f, "POSTHOG_CLI_PROJECT_ID=99").unwrap();+ let map = load_dotenv(f.path()).unwrap();+ assert_eq!(map.get("POSTHOG_CLI_API_KEY").unwrap(), "phx_from_file");+ assert_eq!(map.get("POSTHOG_CLI_PROJECT_ID").unwrap(), "99");+ }++ #[test]+ fn load_dotenv_errors_when_missing() {+ let err = load_dotenv(Path::new("/definitely/not/a/real/path/.env")).unwrap_err();+ assert!(err.to_string().contains("env file"));+ }++ #[test]+ fn load_dotenv_strips_quotes_and_comments() {+ let mut f = tempfile::NamedTempFile::new().unwrap();+ writeln!(f, "# a comment").unwrap();+ writeln!(f).unwrap();+ writeln!(f, "POSTHOG_CLI_API_KEY=\"phx_quoted\"").unwrap();+ writeln!(f, "POSTHOG_CLI_HOST='https://eu.posthog.com'").unwrap();+ let map = load_dotenv(f.path()).unwrap();+ assert_eq!(map.get("POSTHOG_CLI_API_KEY").unwrap(), "phx_quoted");+ assert_eq!(+ map.get("POSTHOG_CLI_HOST").unwrap(),+ "https://eu.posthog.com"+ );+ }++ #[test]+ fn load_dotenv_does_not_interpolate_process_env() {+ let key = "POSTHOG_CLI_DOTENV_TEST_INTERP";+ std::env::set_var(key, "secret_from_process");++ let mut f = tempfile::NamedTempFile::new().unwrap();+ writeln!(f, "VALUE=${{{key}}}").unwrap();+ let map = load_dotenv(f.path()).unwrap();+ assert_eq!(map.get("VALUE").unwrap(), &format!("${{{key}}}"));++ std::env::remove_var(key);+ }+}diff --git a/cli/src/utils/mod.rs b/cli/src/utils/mod.rsindex c33244c6014d..4d3b37f45352 100644--- a/cli/src/utils/mod.rs+++ b/cli/src/utils/mod.rs@@ -3,6 +3,7 @@ use reqwest::blocking::Response;use tracing::error;pub mod auth;+pub mod dotenv;pub mod files;pub mod git;pub mod homedir;