Skip to main content

bitbucket_cli/auth/
file_store.rs

1use anyhow::{Context, Result};
2use std::fs;
3use std::path::PathBuf;
4
5use super::Credential;
6
7/// File-based credential storage (fallback when keyring is unavailable)
8pub struct FileStore {
9    path: PathBuf,
10}
11
12impl FileStore {
13    pub fn new() -> Result<Self> {
14        // NOTE: legacy directory — config.toml lives under "bitbucket-cli"
15        // (config::settings::APP_NAME). Existing credential files keep this
16        // path until a migration consolidates the two directories.
17        let config_dir = dirs::config_dir()
18            .context("Could not determine config directory")?
19            .join("bitbucket");
20
21        // Create config directory if it doesn't exist
22        fs::create_dir_all(&config_dir).context("Failed to create config directory")?;
23
24        let path = config_dir.join("credentials.json");
25
26        Ok(Self { path })
27    }
28
29    /// Store credentials in a file
30    pub fn store_credential(&self, credential: &Credential) -> Result<()> {
31        let json =
32            serde_json::to_string_pretty(credential).context("Failed to serialize credential")?;
33
34        // Write with restrictive permissions (0600 = read/write for owner only)
35        #[cfg(unix)]
36        {
37            use std::fs::OpenOptions;
38            use std::os::unix::fs::OpenOptionsExt;
39
40            OpenOptions::new()
41                .write(true)
42                .create(true)
43                .truncate(true)
44                .mode(0o600)
45                .open(&self.path)
46                .and_then(|mut file| {
47                    use std::io::Write;
48                    file.write_all(json.as_bytes())
49                })
50                .context("Failed to write credential file")?;
51        }
52
53        #[cfg(not(unix))]
54        {
55            fs::write(&self.path, json).context("Failed to write credential file")?;
56        }
57
58        Ok(())
59    }
60
61    /// Get credentials from the file
62    pub fn get_credential(&self) -> Result<Option<Credential>> {
63        if !self.path.exists() {
64            return Ok(None);
65        }
66
67        let json = fs::read_to_string(&self.path).context("Failed to read credential file")?;
68
69        let credential: Credential =
70            serde_json::from_str(&json).context("Failed to parse stored credential")?;
71
72        Ok(Some(credential))
73    }
74
75    /// Delete credentials from the file
76    pub fn delete_credential(&self) -> Result<()> {
77        if self.path.exists() {
78            fs::remove_file(&self.path).context("Failed to delete credential file")?;
79        }
80        Ok(())
81    }
82}