Skip to main content

tracevault_cli/
credentials.rs

1use serde::{Deserialize, Serialize};
2use std::fs;
3use std::path::PathBuf;
4
5#[derive(Debug, Serialize, Deserialize)]
6pub struct Credentials {
7    pub server_url: String,
8    pub token: String,
9    pub email: String,
10}
11
12impl Credentials {
13    pub fn path() -> PathBuf {
14        dirs::config_dir()
15            .unwrap_or_else(|| PathBuf::from("~/.config"))
16            .join("tracevault")
17            .join("credentials.json")
18    }
19
20    pub fn load() -> Option<Self> {
21        let path = Self::path();
22        let content = fs::read_to_string(&path).ok()?;
23        serde_json::from_str(&content).ok()
24    }
25
26    pub fn save(&self) -> Result<(), std::io::Error> {
27        let path = Self::path();
28        if let Some(parent) = path.parent() {
29            fs::create_dir_all(parent)?;
30        }
31        let json = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
32        fs::write(&path, json)
33    }
34
35    pub fn delete() -> Result<(), std::io::Error> {
36        let path = Self::path();
37        if path.exists() {
38            fs::remove_file(&path)?;
39        }
40        Ok(())
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    /// Old on-disk `credentials.json` files may still contain `org_slug`
49    /// from before the single-tenant org removal (mirrors config.rs's
50    /// `load_old_config_with_org_slug_still_parses`). serde must silently
51    /// ignore the unknown field rather than fail to parse (no
52    /// `deny_unknown_fields` on `Credentials`), so `Credentials::load()` keeps
53    /// working on an un-migrated credentials file.
54    ///
55    /// `XDG_CONFIG_HOME` is redirected to a tempdir so this reads a fixture
56    /// file rather than the developer's real
57    /// `~/.config/tracevault/credentials.json`; `_env_lock` serializes this
58    /// against other tests in the crate that mutate the same env var (see
59    /// `test_helpers::lock_env_mutation_sync`).
60    #[test]
61    fn load_old_credentials_with_org_slug_still_parses() {
62        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
63        let dir = tempfile::tempdir().unwrap();
64        let mut _guard = crate::test_helpers::EnvVarGuard::new();
65        _guard.set("XDG_CONFIG_HOME", dir.path());
66
67        let creds_dir = dir.path().join("tracevault");
68        fs::create_dir_all(&creds_dir).unwrap();
69        fs::write(
70            creds_dir.join("credentials.json"),
71            r#"{"server_url":"https://example.com","token":"tok","email":"a@b.com","org_slug":"x"}"#,
72        )
73        .unwrap();
74
75        let creds =
76            Credentials::load().expect("old credentials.json with org_slug must still parse");
77        assert_eq!(creds.server_url, "https://example.com");
78        assert_eq!(creds.token, "tok");
79        assert_eq!(creds.email, "a@b.com");
80    }
81}