Something went wrong. Try again.
A human-friendly DSL for ATProto Lexicons forked from stavola.xyz/mlf
Something went wrong. Try again.
Rust
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287//! 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.<plugin>]` section shows up as a `DnsEntry`/// keyed by `<plugin>` 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<PdsEntry>,
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub dns: std::collections::BTreeMap<String, DnsEntry>,}
/// 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<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub app_password: Option<String>, /// 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<String, serde_json::Value>,}
/// 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<String, serde_json::Value>,}
impl DnsEntry { pub fn from_object(obj: serde_json::Map<String, serde_json::Value>) -> 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<Self, CredentialsError> { 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, /// `<project>/.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<PathBuf, CredentialsError> { match self { Scope::Global => Ok(global_credentials_path()?), Scope::Project => Ok(project_root.join(".mlf").join("credentials.toml")), } }}
pub fn global_credentials_path() -> Result<PathBuf, CredentialsError> { 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<PdsEntry>, pub dns: std::collections::BTreeMap<String, DnsEntry>,}
impl Merged { pub fn load(project_root: &Path) -> Result<Self, CredentialsError> { 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"), ); }}