From 6ed6e3e8aea5c1076dd2156edebf8eb10525fd3f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 04:32:49 +0000 Subject: [PATCH 1/2] fix(auth): logout revokes the key browser sign-in made; credentials file is created owner-only `floo auth logout` only deleted the local file, so the key minted by browser sign-in stayed valid on the server. Logout now revokes that key first. A key pasted with --api-key is left alone, since it may also run in CI. If the revoke fails, logout still signs out here and says the key still works. The credentials file is created 0600 instead of written and then narrowed. Refs getfloo/floo#4711 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Eufw46LbCK8k4xKuhXxdYW --- src/api_client.rs | 28 +++++++++ src/cli.rs | 2 +- src/commands/auth.rs | 13 +++++ src/config.rs | 22 ++++++- tests/mock_api_tests.rs | 125 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 187 insertions(+), 3 deletions(-) diff --git a/src/api_client.rs b/src/api_client.rs index a3c8860..d042614 100644 --- a/src/api_client.rs +++ b/src/api_client.rs @@ -178,6 +178,34 @@ impl FlooClient { // --- Auth --- + /// Revoke the key this client signs in with. The API lists keys masked, so + /// the key is found by the two ends it shows; false when no single key matches. + pub fn revoke_own_api_key(&self) -> Result { + let key = self.api_key.as_deref().unwrap_or_default(); + let (Some(prefix), Some(suffix)) = ( + key.get(..9), + key.len().checked_sub(4).and_then(|at| key.get(at..)), + ) else { + return Ok(false); + }; + let listed: Value = self.handle_response(self.get("/v1/auth/api-keys")?)?; + let own: Vec<&str> = listed["api_keys"] + .as_array() + .into_iter() + .flatten() + .filter(|k| k["key_prefix"] == prefix && k["key_suffix"] == suffix) + .filter_map(|k| k["id"].as_str()) + .collect(); + let [id] = own.as_slice() else { + return Ok(false); + }; + let resp = self.delete(&format!("/v1/auth/api-keys/{id}"))?; + if !resp.status().is_success() { + self.handle_response_value(resp)?; + } + Ok(true) + } + pub fn device_authorize(&self) -> Result { let resp = self.post_json("/v1/auth/device", &serde_json::json!({}))?; self.handle_response(resp) diff --git a/src/cli.rs b/src/cli.rs index 74db439..756ab30 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -752,7 +752,7 @@ pub enum AuthCommands { #[arg(long)] force: bool, }, - /// Clear stored credentials. + /// Sign out on this machine, and revoke the key that browser sign-in made. Logout, /// Show the currently authenticated user. Whoami, diff --git a/src/commands/auth.rs b/src/commands/auth.rs index f0117b7..c512a4d 100644 --- a/src/commands/auth.rs +++ b/src/commands/auth.rs @@ -8,11 +8,15 @@ use crate::config::{clear_config, load_config, save_config}; use crate::errors::ErrorCode; use crate::output; +const KEY_STILL_WORKS: &str = + "Signed out on this machine, but its API key still works. Revoke it in the dashboard under API keys."; + pub fn login(api_key: Option<&str>, force: bool) { // Path 1: --api-key flag — save directly and validate if let Some(key) = api_key { let mut config = load_config(); config.api_key = Some(key.to_string()); + config.browser_login = false; if let Err(e) = save_config(&config) { output::error( &format!("Failed to save credentials: {e}"), @@ -157,6 +161,7 @@ pub fn login(api_key: Option<&str>, force: bool) { let email = &result.email; let mut config = load_config(); config.api_key = Some(api_key.to_string()); + config.browser_login = true; config.user_email = Some(email.to_string()); if let Err(e) = save_config(&config) { output::error( @@ -272,6 +277,14 @@ pub fn update_profile(name: &str) { } pub fn logout() { + let config = load_config(); + if config.browser_login && config.api_key.is_some() { + match super::init_client(Some(config)).revoke_own_api_key() { + Ok(true) => {} + Ok(false) => output::warn(KEY_STILL_WORKS), + Err(e) => output::warn(&format!("{KEY_STILL_WORKS} ({})", e.message)), + } + } clear_config(); output::success("Logged out.", None); } diff --git a/src/config.rs b/src/config.rs index 2878199..e9ca9e6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,5 +1,6 @@ use std::env; use std::fs; +use std::io::Write; use std::path::PathBuf; use serde::{Deserialize, Serialize}; @@ -18,6 +19,10 @@ pub struct FlooConfig { pub skill_paths: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub default_org: Option, + /// True when `api_key` came from browser sign-in, so it lives on this + /// machine alone and signing out revokes it. A pasted key may run elsewhere. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub browser_login: bool, } fn default_api_url() -> String { @@ -38,6 +43,7 @@ impl Default for FlooConfig { user_email: None, skill_paths: Vec::new(), default_org: None, + browser_login: false, } } } @@ -172,12 +178,23 @@ pub fn save_config(config: &FlooConfig) -> anyhow::Result<()> { fs::create_dir_all(parent)?; } let json = serde_json::to_string_pretty(config)?; - fs::write(&path, json)?; + // The file holds the API key: it is created owner-only, never readable by + // others even for the moment between a write and a chmod. + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); #[cfg(unix)] { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&path)?; + #[cfg(unix)] + { + // A file an older CLI left with wider permissions is narrowed too. use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?; + file.set_permissions(fs::Permissions::from_mode(0o600))?; } + file.write_all(json.as_bytes())?; Ok(()) } @@ -244,6 +261,7 @@ mod tests { user_email: Some("test@example.com".to_string()), skill_paths: vec!["/tmp/floo.md".to_string()], default_org: Some("org-123".to_string()), + browser_login: false, }; let json = serde_json::to_string(&config).unwrap(); let deserialized: FlooConfig = serde_json::from_str(&json).unwrap(); diff --git a/tests/mock_api_tests.rs b/tests/mock_api_tests.rs index f200b9c..c7684d2 100644 --- a/tests/mock_api_tests.rs +++ b/tests/mock_api_tests.rs @@ -9690,3 +9690,128 @@ fn test_db_dump_without_database_url_names_the_env() { .stdout(predicate::str::contains("no DATABASE_URL in dev")); assert!(!bin.path().join("pg_dump.log").exists()); } + +/// Config whose key came from `floo auth login` in the browser, or was pasted. +fn setup_signed_in_config(server: &Server, browser_login: bool) -> TempDir { + let home = TempDir::new().unwrap(); + let config_dir = home.path().join(".floo-local"); + std::fs::create_dir_all(&config_dir).unwrap(); + std::fs::write( + config_dir.join("config.json"), + format!( + r#"{{"api_key":"floo_abcd0123456789wxyz","api_url":"{}","browser_login":{browser_login}}}"#, + server.url() + ), + ) + .unwrap(); + home +} + +fn mock_own_keys(server: &mut Server) -> Mock { + server + .mock("GET", "/v1/auth/api-keys") + .with_status(200) + .with_header("content-type", "application/json") + .with_body( + r#"{"api_keys":[ + {"id":"key-other","name":"CI","key_prefix":"floo_zzzz","key_suffix":"wxyz"}, + {"id":"key-this-machine","name":"CLI login","key_prefix":"floo_abcd","key_suffix":"wxyz"} + ],"total":2}"#, + ) + .create() +} + +#[test] +fn logout_revokes_the_key_browser_sign_in_made() { + let mut server = Server::new(); + let home = setup_signed_in_config(&server, true); + let listed = mock_own_keys(&mut server); + let revoked = server + .mock("DELETE", "/v1/auth/api-keys/key-this-machine") + .with_status(204) + .create(); + + floo() + .args(["auth", "logout"]) + .env("HOME", home.path()) + .assert() + .success() + .stderr(predicate::str::contains("Logged out.")); + + listed.assert(); + revoked.assert(); + assert!(!home.path().join(".floo-local/config.json").exists()); +} + +#[test] +fn logout_leaves_a_pasted_key_working() { + let mut server = Server::new(); + let home = setup_signed_in_config(&server, false); + let revoked = server + .mock("DELETE", Matcher::Regex("^/v1/auth/api-keys/".to_string())) + .expect(0) + .create(); + + floo() + .args(["auth", "logout"]) + .env("HOME", home.path()) + .assert() + .success(); + + revoked.assert(); + assert!(!home.path().join(".floo-local/config.json").exists()); +} + +#[test] +fn logout_signs_out_here_and_says_so_when_the_key_cannot_be_revoked() { + let mut server = Server::new(); + let home = setup_signed_in_config(&server, true); + server + .mock("GET", "/v1/auth/api-keys") + .with_status(500) + .with_header("content-type", "application/json") + .with_body(r#"{"detail":{"code":"INTERNAL_ERROR","message":"boom"}}"#) + .create(); + + floo() + .args(["auth", "logout"]) + .env("HOME", home.path()) + .assert() + .success() + .stderr(predicate::str::contains("still works")); + + assert!(!home.path().join(".floo-local/config.json").exists()); +} + +#[cfg(unix)] +#[test] +fn the_credentials_file_is_readable_by_its_owner_alone() { + use std::os::unix::fs::PermissionsExt; + + let mut server = Server::new(); + // An older CLI, or a hand-made file, may have left it readable by everyone. + let home = setup_config(&server); + let config_file = home.path().join(".floo-local/config.json"); + std::fs::set_permissions(&config_file, std::fs::Permissions::from_mode(0o644)).unwrap(); + server + .mock("GET", "/v1/auth/whoami") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"email":"ada@example.com","name":null}"#) + .create(); + + floo() + .args(["auth", "login", "--api-key", "floo_pasted0123456789"]) + .env("HOME", home.path()) + .assert() + .success(); + + let mode = std::fs::metadata(&config_file) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + assert!(!std::fs::read_to_string(&config_file) + .unwrap() + .contains("browser_login")); +} From 7ae1dc0e4f979ec46320b1d719af75f3051d4863 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 04:36:43 +0000 Subject: [PATCH 2/2] fix(auth): logout --json reports whether the key was revoked The warning for a failed revoke is not printed in JSON mode, so a script could not tell a revoked key from one still valid. The logout result now carries key_revoked and the warning. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Eufw46LbCK8k4xKuhXxdYW --- src/commands/auth.rs | 27 +++++++++++++++++++-------- tests/mock_api_tests.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/src/commands/auth.rs b/src/commands/auth.rs index c512a4d..d2d89b0 100644 --- a/src/commands/auth.rs +++ b/src/commands/auth.rs @@ -278,15 +278,26 @@ pub fn update_profile(name: &str) { pub fn logout() { let config = load_config(); - if config.browser_login && config.api_key.is_some() { - match super::init_client(Some(config)).revoke_own_api_key() { - Ok(true) => {} - Ok(false) => output::warn(KEY_STILL_WORKS), - Err(e) => output::warn(&format!("{KEY_STILL_WORKS} ({})", e.message)), - } - } + // None when there is no key from browser sign-in to revoke. + let revoke = (config.browser_login && config.api_key.is_some()) + .then(|| super::init_client(Some(config)).revoke_own_api_key()); clear_config(); - output::success("Logged out.", None); + let warning = match &revoke { + None | Some(Ok(true)) => None, + Some(Ok(false)) => Some(KEY_STILL_WORKS.to_string()), + Some(Err(e)) => Some(format!("{KEY_STILL_WORKS} ({})", e.message)), + }; + if let Some(warning) = &warning { + output::warn(warning); + } + // A script reads here what a person reads in the warning: the key may still be live. + output::success( + "Logged out.", + Some(serde_json::json!({ + "key_revoked": matches!(revoke, Some(Ok(true))), + "warning": warning, + })), + ); } pub fn whoami() { diff --git a/tests/mock_api_tests.rs b/tests/mock_api_tests.rs index c7684d2..9299244 100644 --- a/tests/mock_api_tests.rs +++ b/tests/mock_api_tests.rs @@ -9815,3 +9815,38 @@ fn the_credentials_file_is_readable_by_its_owner_alone() { .unwrap() .contains("browser_login")); } + +#[test] +fn logout_json_says_whether_the_key_was_revoked() { + let mut server = Server::new(); + let home = setup_signed_in_config(&server, true); + server + .mock("GET", "/v1/auth/api-keys") + .with_status(500) + .with_header("content-type", "application/json") + .with_body(r#"{"detail":{"code":"INTERNAL_ERROR","message":"boom"}}"#) + .create(); + + floo() + .args(["--json", "auth", "logout"]) + .env("HOME", home.path()) + .assert() + .success() + .stdout(predicate::str::contains(r#""key_revoked":false"#)) + .stdout(predicate::str::contains("still works")); + + let home = setup_signed_in_config(&server, true); + mock_own_keys(&mut server); + server + .mock("DELETE", "/v1/auth/api-keys/key-this-machine") + .with_status(204) + .create(); + + floo() + .args(["--json", "auth", "logout"]) + .env("HOME", home.path()) + .assert() + .success() + .stdout(predicate::str::contains(r#""key_revoked":true"#)) + .stdout(predicate::str::contains(r#""warning":null"#)); +}