//! Stored secrets, `config/secrets.dat` (`app/src/admin.spec.md`): DPAPI-encrypted for the Windows //! user; plain JSON with owner-only permissions elsewhere (development only). use std::path::{Path, PathBuf}; use serde_json::{Map, Value}; use crate::datadir::write_atomic; /// The Discord bot token's name in the store. pub const DISCORD_TOKEN: &str = "discordToken"; #[derive(Debug)] pub struct SecretsError(pub String); impl std::fmt::Display for SecretsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) } } impl std::error::Error for SecretsError {} pub struct Secrets { file: PathBuf, } impl Secrets { pub fn new(file: &Path) -> Self { Self { file: file.to_path_buf() } } fn load(&self) -> Result, SecretsError> { let bytes = match std::fs::read(&self.file) { Ok(b) => b, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Map::new()), Err(e) => return Err(SecretsError(format!("could not read the secrets: {e}"))), }; let plain = unprotect(&bytes)?; match serde_json::from_slice(&plain) { Ok(Value::Object(m)) => Ok(m), _ => Err(SecretsError("the secrets file is damaged".into())), } } fn save(&self, m: &Map) -> Result<(), SecretsError> { let plain = serde_json::to_vec(m).expect("a map serialises"); let bytes = protect(&plain)?; write_atomic(&self.file, &bytes).map_err(|e| SecretsError(format!("could not write the secrets: {e}")))?; restrict(&self.file); Ok(()) } pub fn get(&self, name: &str) -> Result, SecretsError> { Ok(self.load()?.get(name).and_then(Value::as_str).map(str::to_owned)) } pub fn set(&self, name: &str, value: &str) -> Result<(), SecretsError> { let mut m = self.load()?; m.insert(name.into(), Value::String(value.into())); self.save(&m) } pub fn remove(&self, name: &str) -> Result<(), SecretsError> { let mut m = self.load()?; if m.remove(name).is_some() { self.save(&m)?; } Ok(()) } /// The names of the stored secrets. pub fn names(&self) -> Result, SecretsError> { Ok(self.load()?.keys().cloned().collect()) } /// Every stored value, for log redaction. pub fn values(&self) -> Vec { self.load().map(|m| m.values().filter_map(Value::as_str).map(str::to_owned).collect()).unwrap_or_default() } } /// Only the last 4 characters, for the screens: `••••abcd`. pub fn masked(value: &str) -> String { let chars: Vec = value.chars().collect(); let tail: String = chars[chars.len().saturating_sub(4)..].iter().collect(); format!("••••{tail}") } #[cfg(unix)] fn restrict(path: &Path) { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); } #[cfg(not(unix))] fn restrict(_: &Path) {} #[cfg(not(windows))] fn protect(plain: &[u8]) -> Result, SecretsError> { Ok(plain.to_vec()) } #[cfg(not(windows))] fn unprotect(bytes: &[u8]) -> Result, SecretsError> { Ok(bytes.to_vec()) } #[cfg(windows)] fn dpapi(input: &[u8], encrypt: bool) -> Result, SecretsError> { use windows_sys::Win32::Foundation::LocalFree; use windows_sys::Win32::Security::Cryptography::{ CryptProtectData, CryptUnprotectData, CRYPTPROTECT_UI_FORBIDDEN, CRYPT_INTEGER_BLOB, }; let data_in = CRYPT_INTEGER_BLOB { cbData: input.len() as u32, pbData: input.as_ptr() as *mut u8 }; let mut out = CRYPT_INTEGER_BLOB { cbData: 0, pbData: std::ptr::null_mut() }; // SAFETY: the input blob points at `input` for the call; the output is freed with LocalFree. let ok = unsafe { if encrypt { CryptProtectData(&data_in, std::ptr::null(), std::ptr::null(), std::ptr::null(), std::ptr::null(), CRYPTPROTECT_UI_FORBIDDEN, &mut out) } else { CryptUnprotectData(&data_in, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), std::ptr::null(), CRYPTPROTECT_UI_FORBIDDEN, &mut out) } }; if ok == 0 { return Err(SecretsError(if encrypt { "could not encrypt the secrets".into() } else { "could not decrypt the secrets (another Windows user or PC?)".into() })); } // SAFETY: DPAPI returned `cbData` bytes at `pbData`. let v = unsafe { std::slice::from_raw_parts(out.pbData, out.cbData as usize).to_vec() }; unsafe { LocalFree(out.pbData as _) }; Ok(v) } #[cfg(windows)] fn protect(plain: &[u8]) -> Result, SecretsError> { dpapi(plain, true) } #[cfg(windows)] fn unprotect(bytes: &[u8]) -> Result, SecretsError> { dpapi(bytes, false) } #[cfg(test)] mod tests { use super::*; use crate::datadir::temp_dir; #[test] fn secrets_round_trip_and_are_removed() { let s = Secrets::new(&temp_dir("sec").join("config").join("secrets.dat")); assert_eq!(s.get(DISCORD_TOKEN).unwrap(), None); s.set(DISCORD_TOKEN, "abc.def.ghij").unwrap(); s.set("other", "x").unwrap(); assert_eq!(s.get(DISCORD_TOKEN).unwrap().as_deref(), Some("abc.def.ghij")); let mut v = s.values(); v.sort(); assert_eq!(v, vec!["abc.def.ghij", "x"]); s.remove(DISCORD_TOKEN).unwrap(); assert_eq!(s.get(DISCORD_TOKEN).unwrap(), None); assert_eq!(s.get("other").unwrap().as_deref(), Some("x")); } #[cfg(unix)] #[test] fn the_file_is_readable_by_its_owner_only() { use std::os::unix::fs::PermissionsExt; let f = temp_dir("secp").join("secrets.dat"); Secrets::new(&f).set(DISCORD_TOKEN, "t").unwrap(); assert_eq!(std::fs::metadata(&f).unwrap().permissions().mode() & 0o777, 0o600); } #[test] fn a_damaged_file_is_reported_not_overwritten() { let f = temp_dir("secd").join("secrets.dat"); std::fs::write(&f, b"not json").unwrap(); let s = Secrets::new(&f); assert!(s.get(DISCORD_TOKEN).is_err()); assert!(s.set(DISCORD_TOKEN, "t").is_err()); assert_eq!(std::fs::read(&f).unwrap(), b"not json"); } #[test] fn masking_shows_only_the_last_four() { assert_eq!(masked("MTIz.abcd.wxyz"), "••••wxyz"); assert_eq!(masked("ab"), "••••ab"); } }