//! Plaintext credential storage — same shape as cargo's //! `~/.cargo/credentials.toml` and npm's `.npmrc`. A global file under //! `~/.config/mlf/credentials.toml` holds defaults; an optional //! project-local `.mlf/credentials.toml` (gitignored) shadows entries //! per field. //! //! All files are written with mode `0o600` on Unix. use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; use thiserror::Error; #[derive(Error, Debug)] pub enum CredentialsError { #[error("Failed to read credentials file {path}: {source}")] Read { path: PathBuf, #[source] source: std::io::Error, }, #[error("Failed to write credentials file {path}: {source}")] Write { path: PathBuf, #[source] source: std::io::Error, }, #[error("Failed to parse credentials file {path}: {source}")] Parse { path: PathBuf, #[source] source: toml::de::Error, }, #[error("Home directory not available (set HOME)")] NoHomeDir, } /// On-disk shape. Any `[dns.]` section shows up as a `DnsEntry` /// keyed by `` in `dns`. Unknown top-level or per-plugin fields /// are preserved on round-trip so we don't clobber anything an older /// (or newer) MLF wrote. #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct CredentialsFile { #[serde(default, skip_serializing_if = "Option::is_none")] pub pds: Option, #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub dns: std::collections::BTreeMap, } /// One PDS credential entry. Fields match the publishing account. #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct PdsEntry { #[serde(default, skip_serializing_if = "Option::is_none")] pub handle: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub app_password: Option, /// Extra fields (e.g. did or pds URL the login resolved to) are /// preserved; the cli uses them as a cache. #[serde(flatten)] pub extra: serde_json::Map, } /// One DNS plugin's credential entry. Arbitrary key/value because each /// plugin declares its own schema; we store whatever the plugin's `login` /// op returned. #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct DnsEntry { #[serde(flatten)] pub fields: serde_json::Map, } impl DnsEntry { pub fn from_object(obj: serde_json::Map) -> Self { Self { fields: obj } } pub fn is_empty(&self) -> bool { self.fields.is_empty() } pub fn get_str(&self, key: &str) -> Option<&str> { self.fields.get(key).and_then(|v| v.as_str()) } } impl CredentialsFile { pub fn load(path: &Path) -> Result { if !path.exists() { return Ok(Self::default()); } let content = std::fs::read_to_string(path).map_err(|source| CredentialsError::Read { path: path.to_path_buf(), source, })?; toml::from_str(&content).map_err(|source| CredentialsError::Parse { path: path.to_path_buf(), source, }) } pub fn save(&self, path: &Path) -> Result<(), CredentialsError> { if let Some(parent) = path.parent() && !parent.as_os_str().is_empty() { std::fs::create_dir_all(parent).map_err(|source| CredentialsError::Write { path: path.to_path_buf(), source, })?; } let content = toml::to_string_pretty(self).map_err(|e| CredentialsError::Write { path: path.to_path_buf(), source: std::io::Error::other(e.to_string()), })?; write_private(path, content.as_bytes())?; Ok(()) } } fn write_private(path: &Path, bytes: &[u8]) -> Result<(), CredentialsError> { std::fs::write(path, bytes).map_err(|source| CredentialsError::Write { path: path.to_path_buf(), source, })?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let perms = std::fs::Permissions::from_mode(0o600); std::fs::set_permissions(path, perms).map_err(|source| CredentialsError::Write { path: path.to_path_buf(), source, })?; } Ok(()) } // --------------------------------------------------------------------------- // Scope resolution // --------------------------------------------------------------------------- /// Which file `mlf login` reads and writes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Scope { /// `~/.config/mlf/credentials.toml`. The default for local dev. Global, /// `/.mlf/credentials.toml`. The choice for CI, monorepos, /// and anywhere you want creds to live alongside the project. Project, } impl Scope { pub fn path(&self, project_root: &Path) -> Result { match self { Scope::Global => Ok(global_credentials_path()?), Scope::Project => Ok(project_root.join(".mlf").join("credentials.toml")), } } } pub fn global_credentials_path() -> Result { let home = std::env::var_os("HOME") .or_else(|| std::env::var_os("USERPROFILE")) .ok_or(CredentialsError::NoHomeDir)?; Ok(PathBuf::from(home) .join(".config") .join("mlf") .join("credentials.toml")) } /// Merge a global and project file into a single effective view. /// Project entries override global ones at the section level. #[derive(Debug, Default)] pub struct Merged { pub pds: Option, pub dns: std::collections::BTreeMap, } impl Merged { pub fn load(project_root: &Path) -> Result { let global = match global_credentials_path() { Ok(p) => CredentialsFile::load(&p)?, Err(CredentialsError::NoHomeDir) => CredentialsFile::default(), Err(e) => return Err(e), }; let project_path = project_root.join(".mlf").join("credentials.toml"); let project = CredentialsFile::load(&project_path)?; let mut merged = Merged::default(); merged.pds = project.pds.or(global.pds); merged.dns = global.dns; for (k, v) in project.dns { merged.dns.insert(k, v); } Ok(merged) } } #[cfg(test)] mod tests { use super::*; use tempfile::TempDir; #[test] fn round_trip_preserves_fields() { let dir = TempDir::new().unwrap(); let path = dir.path().join("creds.toml"); let mut file = CredentialsFile::default(); file.pds = Some(PdsEntry { handle: Some("matt.example.com".into()), app_password: Some("xxxx".into()), ..Default::default() }); file.dns.insert( "cloudflare".into(), DnsEntry::from_object( serde_json::json!({"api_token": "tkn"}) .as_object() .unwrap() .clone(), ), ); file.save(&path).unwrap(); let loaded = CredentialsFile::load(&path).unwrap(); assert_eq!( loaded.pds.as_ref().unwrap().handle.as_deref(), Some("matt.example.com") ); assert_eq!( loaded.dns.get("cloudflare").unwrap().get_str("api_token"), Some("tkn") ); } #[test] fn load_missing_file_returns_default() { let dir = TempDir::new().unwrap(); let path = dir.path().join("nope.toml"); let loaded = CredentialsFile::load(&path).unwrap(); assert!(loaded.pds.is_none()); assert!(loaded.dns.is_empty()); } #[cfg(unix)] #[test] fn save_sets_0600_permissions() { use std::os::unix::fs::PermissionsExt; let dir = TempDir::new().unwrap(); let path = dir.path().join("creds.toml"); CredentialsFile::default().save(&path).unwrap(); let perms = std::fs::metadata(&path).unwrap().permissions(); assert_eq!(perms.mode() & 0o777, 0o600); } #[test] fn merged_project_shadows_global() { let dir = TempDir::new().unwrap(); let project_root = dir.path(); std::fs::create_dir_all(project_root.join(".mlf")).unwrap(); // Seed project. let mut project_file = CredentialsFile::default(); project_file.dns.insert( "cloudflare".into(), DnsEntry::from_object( serde_json::json!({"api_token": "project-token"}) .as_object() .unwrap() .clone(), ), ); project_file .save(&project_root.join(".mlf").join("credentials.toml")) .unwrap(); // We don't have a writable $HOME in the test sandbox, so just // check project-only loading works. let merged = Merged::load(project_root).unwrap(); assert_eq!( merged.dns.get("cloudflare").unwrap().get_str("api_token"), Some("project-token"), ); } }