Skip to main content

logicaffeine_cli/project/
credentials.rs

1//! Phase 39: Credential Management
2//!
3//! Stores and retrieves API tokens for the package registry.
4//!
5//! Credentials are stored in a TOML file at `~/.config/logos/credentials.toml`
6//! with restrictive permissions (0600 on Unix) to protect sensitive tokens.
7//!
8//! # Token Resolution Order
9//!
10//! When retrieving a token via [`get_token`], the following order is used:
11//! 1. `LOGOS_TOKEN` environment variable (highest priority)
12//! 2. Credentials file entry for the registry URL
13//!
14//! # Security
15//!
16//! - Tokens are stored in plaintext (like cargo, npm, etc.)
17//! - File permissions are set to owner-only on Unix systems
18//! - The `LOGOS_CREDENTIALS_PATH` env var can override the default location
19
20use std::collections::HashMap;
21use std::fs;
22use std::path::PathBuf;
23
24/// Persistent storage for registry authentication tokens.
25///
26/// Tokens are stored per-registry URL, allowing authentication with
27/// multiple registries simultaneously.
28///
29/// # File Format
30///
31/// ```toml
32/// [registries]
33/// "https://registry.logicaffeine.com" = "tok_xxxxx"
34/// ```
35#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
36pub struct Credentials {
37    /// Map of registry URL to authentication token.
38    #[serde(default)]
39    pub registries: HashMap<String, String>,
40}
41
42impl Credentials {
43    /// Load credentials from the default location
44    pub fn load() -> Result<Self, CredentialsError> {
45        let path = credentials_path().ok_or(CredentialsError::NoConfigDir)?;
46
47        if !path.exists() {
48            return Ok(Self::default());
49        }
50
51        let content = fs::read_to_string(&path).map_err(|e| CredentialsError::Io(e.to_string()))?;
52
53        toml::from_str(&content).map_err(|e| CredentialsError::Parse(e.to_string()))
54    }
55
56    /// Save credentials to the default location
57    pub fn save(&self) -> Result<(), CredentialsError> {
58        let path = credentials_path().ok_or(CredentialsError::NoConfigDir)?;
59
60        // Create parent directory if needed
61        if let Some(parent) = path.parent() {
62            fs::create_dir_all(parent).map_err(|e| CredentialsError::Io(e.to_string()))?;
63        }
64
65        let content =
66            toml::to_string_pretty(self).map_err(|e| CredentialsError::Serialize(e.to_string()))?;
67
68        fs::write(&path, content).map_err(|e| CredentialsError::Io(e.to_string()))?;
69
70        // Set restrictive permissions on Unix
71        #[cfg(unix)]
72        {
73            use std::os::unix::fs::PermissionsExt;
74            let perms = std::fs::Permissions::from_mode(0o600);
75            fs::set_permissions(&path, perms).map_err(|e| CredentialsError::Io(e.to_string()))?;
76        }
77
78        Ok(())
79    }
80
81    /// Get token for a registry
82    pub fn get_token(&self, registry_url: &str) -> Option<&str> {
83        self.registries.get(registry_url).map(|s| s.as_str())
84    }
85
86    /// Set token for a registry
87    pub fn set_token(&mut self, registry_url: &str, token: &str) {
88        self.registries
89            .insert(registry_url.to_string(), token.to_string());
90    }
91
92    /// Remove token for a registry
93    pub fn remove_token(&mut self, registry_url: &str) {
94        self.registries.remove(registry_url);
95    }
96}
97
98/// Get the token for a registry, checking env var first then credentials file
99pub fn get_token(registry_url: &str) -> Option<String> {
100    // Check LOGOS_TOKEN env var first
101    if let Ok(token) = std::env::var("LOGOS_TOKEN") {
102        if !token.is_empty() {
103            return Some(token);
104        }
105    }
106
107    // Fall back to credentials file
108    Credentials::load()
109        .ok()
110        .and_then(|c| c.get_token(registry_url).map(String::from))
111}
112
113/// Get the path to the credentials file
114pub fn credentials_path() -> Option<PathBuf> {
115    // Check LOGOS_CREDENTIALS_PATH env var first
116    if let Ok(path) = std::env::var("LOGOS_CREDENTIALS_PATH") {
117        return Some(PathBuf::from(path));
118    }
119
120    // Use standard config directory
121    dirs::config_dir().map(|p| p.join("logos").join("credentials.toml"))
122}
123
124/// Errors that can occur when loading or saving credentials.
125#[derive(Debug)]
126pub enum CredentialsError {
127    /// Could not determine the config directory (e.g., `$HOME` not set).
128    NoConfigDir,
129    /// File system operation failed.
130    Io(String),
131    /// Failed to parse the credentials TOML file.
132    Parse(String),
133    /// Failed to serialize credentials to TOML.
134    Serialize(String),
135}
136
137impl std::fmt::Display for CredentialsError {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        match self {
140            Self::NoConfigDir => write!(f, "Could not determine config directory"),
141            Self::Io(e) => write!(f, "I/O error: {}", e),
142            Self::Parse(e) => write!(f, "Failed to parse credentials: {}", e),
143            Self::Serialize(e) => write!(f, "Failed to serialize credentials: {}", e),
144        }
145    }
146}
147
148impl std::error::Error for CredentialsError {}