Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/api_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool, FlooApiError> {
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<DeviceAuthorizeResponse, FlooApiError> {
let resp = self.post_json("/v1/auth/device", &serde_json::json!({}))?;
self.handle_response(resp)
Expand Down
2 changes: 1 addition & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
26 changes: 25 additions & 1 deletion src/commands/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"),
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -272,8 +277,27 @@ pub fn update_profile(name: &str) {
}

pub fn logout() {
let config = load_config();
// 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() {
Expand Down
22 changes: 20 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};
Expand All @@ -18,6 +19,10 @@ pub struct FlooConfig {
pub skill_paths: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_org: Option<String>,
/// 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 {
Expand All @@ -38,6 +43,7 @@ impl Default for FlooConfig {
user_email: None,
skill_paths: Vec::new(),
default_org: None,
browser_login: false,
}
}
}
Expand Down Expand Up @@ -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(())
}

Expand Down Expand Up @@ -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();
Expand Down
160 changes: 160 additions & 0 deletions tests/mock_api_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9690,3 +9690,163 @@ 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"));
}

#[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"#));
}