Something went wrong. Try again.
A terminal UI for Libby libbui.vinnymac.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372//! Storage for the Libby credential (the bearer token and the chip id it//! belongs to).//!//! v1 keeps it in `identity.json` in the config directory, mode `0600`//! inside a `0700` directory, written atomically. A file other users can//! read is refused rather than used, because the token is a full login to//! someone's library card. Storing it in the OS keyring is a planned//! follow-up behind the same [`SecretStore`] trait.
use std::path::{Path, PathBuf};use std::sync::Mutex;
use jiff::Timestamp;use secrecy::{ExposeSecret, SecretString};use serde::{Deserialize, Serialize};
/// The persisted credential.////// `Debug` never shows the token.#[derive(Clone)]pub struct StoredIdentity { /// The Libby bearer token. pub token: SecretString, /// The chip (device) id the token was issued to. pub chip: String, /// When the credential was saved. pub saved_at: Timestamp,}
impl std::fmt::Debug for StoredIdentity { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("StoredIdentity") .field("token", &"[REDACTED]") .field("chip", &self.chip) .field("saved_at", &self.saved_at) .finish() }}
/// On-disk shape. Kept private so the plain-text token never escapes this/// module in anything but a [`SecretString`].#[derive(Serialize, Deserialize)]#[serde(deny_unknown_fields)]struct OnDisk { version: u32, token: String, chip: String, saved_at: Timestamp,}
const FORMAT_VERSION: u32 = 1;
/// Why the credential could not be loaded, saved or cleared.#[derive(Debug, thiserror::Error)]pub enum IdentityError { /// Reading, writing or removing the file failed. #[error("{}: {source}", path.display())] Io { /// The identity file or its directory. path: PathBuf, /// The underlying error. #[source] source: std::io::Error, }, /// The file is readable by other users, so it is not used. #[error( "{} is accessible by other users (mode {mode:o}); run `chmod 600 '{}'` and try again", path.display(), path.display() )] InsecurePermissions { /// The identity file. path: PathBuf, /// Its permission bits. mode: u32, }, /// The file exists but is not a valid identity. #[error("{} is not a valid identity file: {message}", path.display())] Malformed { /// The identity file. path: PathBuf, /// What is wrong. message: String, },}
/// Somewhere a credential can be kept.pub trait SecretStore: Send + Sync + std::fmt::Debug { /// Returns the stored credential, or `None` if there is none. /// /// # Errors /// Any problem other than "nothing stored" is an error. fn load(&self) -> Result<Option<StoredIdentity>, IdentityError>;
/// Replaces the stored credential. /// /// # Errors /// When the credential could not be persisted. fn save(&self, identity: &StoredIdentity) -> Result<(), IdentityError>;
/// Forgets the stored credential. Clearing an empty store succeeds. /// /// # Errors /// When an existing credential could not be removed. fn clear(&self) -> Result<(), IdentityError>;}
/// Keeps the credential in a `0600` JSON file.////// The interface and `libbui account` may both write it, but every write/// replaces the whole credential atomically (there is nothing to merge), so/// it needs no lock: the last sign-in or sign-out wins, as it would by hand.#[derive(Debug, Clone)]pub struct FileStore { path: PathBuf,}
impl FileStore { /// A store backed by `path` (normally [`crate::paths::Paths::identity_file`]). pub fn new(path: impl Into<PathBuf>) -> Self { Self { path: path.into() } }
/// The backing file. pub fn path(&self) -> &Path { &self.path }
fn io(&self, source: std::io::Error) -> IdentityError { IdentityError::Io { path: self.path.clone(), source, } }
#[cfg(unix)] fn check_mode(&self, meta: &std::fs::Metadata) -> Result<(), IdentityError> { use std::os::unix::fs::PermissionsExt; let mode = meta.permissions().mode() & 0o777; if mode & 0o077 != 0 { return Err(IdentityError::InsecurePermissions { path: self.path.clone(), mode, }); } Ok(()) }
#[cfg(not(unix))] fn check_mode(&self, _meta: &std::fs::Metadata) -> Result<(), IdentityError> { // Windows profile directories are already private to the user. Ok(()) }
/// Creates the parent directory as `0700`, tightening it if it exists /// with looser permissions. fn prepare_dir(&self) -> Result<(), IdentityError> { let dir = crate::fsutil::parent_dir(&self.path).map_err(|e| self.io(e))?; let mut builder = std::fs::DirBuilder::new(); builder.recursive(true); #[cfg(unix)] { use std::os::unix::fs::DirBuilderExt; builder.mode(0o700); } builder.create(dir).map_err(|source| IdentityError::Io { path: dir.to_path_buf(), source, })?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let meta = std::fs::metadata(dir).map_err(|source| IdentityError::Io { path: dir.to_path_buf(), source, })?; if meta.permissions().mode() & 0o077 != 0 { tracing::info!(dir = %dir.display(), "tightening config directory to 0700"); std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).map_err( |source| IdentityError::Io { path: dir.to_path_buf(), source, }, )?; } } Ok(()) }}
impl SecretStore for FileStore { fn load(&self) -> Result<Option<StoredIdentity>, IdentityError> { let meta = match std::fs::metadata(&self.path) { Ok(m) => m, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(self.io(e)), }; self.check_mode(&meta)?; let bytes = std::fs::read(&self.path).map_err(|e| self.io(e))?; let disk: OnDisk = serde_json::from_slice(&bytes).map_err(|e| IdentityError::Malformed { path: self.path.clone(), message: e.to_string(), })?; if disk.version != FORMAT_VERSION { return Err(IdentityError::Malformed { path: self.path.clone(), message: format!("unsupported version {}", disk.version), }); } if disk.token.is_empty() || disk.chip.is_empty() { return Err(IdentityError::Malformed { path: self.path.clone(), message: "token and chip must not be empty".to_owned(), }); } Ok(Some(StoredIdentity { token: SecretString::from(disk.token), chip: disk.chip, saved_at: disk.saved_at, })) }
fn save(&self, identity: &StoredIdentity) -> Result<(), IdentityError> { self.prepare_dir()?; let disk = OnDisk { version: FORMAT_VERSION, token: identity.token.expose_secret().to_owned(), chip: identity.chip.clone(), saved_at: identity.saved_at, }; let bytes = serde_json::to_vec_pretty(&disk).map_err(|e| IdentityError::Malformed { path: self.path.clone(), message: e.to_string(), })?; crate::fsutil::write_atomic(&self.path, &bytes, Some(0o600)).map_err(|e| self.io(e)) }
fn clear(&self) -> Result<(), IdentityError> { match std::fs::remove_file(&self.path) { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(e) => Err(self.io(e)), } }}
/// An in-memory store for tests and for running without persistence.#[derive(Debug, Default)]pub struct MemoryStore { inner: Mutex<Option<StoredIdentity>>,}
impl MemoryStore { /// An empty store. pub fn new() -> Self { Self::default() }
fn lock(&self) -> std::sync::MutexGuard<'_, Option<StoredIdentity>> { // A panic while holding this lock cannot leave the Option torn, so a // poisoned lock is still safe to use. self.inner .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) }}
impl SecretStore for MemoryStore { fn load(&self) -> Result<Option<StoredIdentity>, IdentityError> { Ok(self.lock().clone()) }
fn save(&self, identity: &StoredIdentity) -> Result<(), IdentityError> { *self.lock() = Some(identity.clone()); Ok(()) }
fn clear(&self) -> Result<(), IdentityError> { *self.lock() = None; Ok(()) }}
#[cfg(test)]mod tests { #![allow(clippy::unwrap_used, reason = "a failing test should panic")] use super::*;
fn identity() -> StoredIdentity { StoredIdentity { token: SecretString::from("super-secret-token"), chip: "chip-1".to_owned(), saved_at: Timestamp::from_second(1_700_000_000).unwrap(), } }
#[test] fn debug_redacts_token() { let s = format!("{:?}", identity()); assert!(!s.contains("super-secret-token"), "{s}"); assert!(s.contains("chip-1")); }
#[test] fn file_round_trip() { let dir = tempfile::tempdir().unwrap(); let store = FileStore::new(dir.path().join("cfg/identity.json")); assert!(store.load().unwrap().is_none()); store.save(&identity()).unwrap(); let back = store.load().unwrap().unwrap(); assert_eq!(back.token.expose_secret(), "super-secret-token"); assert_eq!(back.chip, "chip-1"); assert_eq!(back.saved_at, identity().saved_at); store.clear().unwrap(); assert!(store.load().unwrap().is_none()); store.clear().unwrap(); }
#[cfg(unix)] #[test] fn file_and_dir_modes() { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); let cfg = dir.path().join("cfg"); std::fs::create_dir(&cfg).unwrap(); std::fs::set_permissions(&cfg, std::fs::Permissions::from_mode(0o755)).unwrap(); let store = FileStore::new(cfg.join("identity.json")); store.save(&identity()).unwrap(); let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; assert_eq!(mode(store.path()), 0o600); assert_eq!(mode(&cfg), 0o700); }
#[cfg(unix)] #[test] fn refuses_loose_permissions() { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); let store = FileStore::new(dir.path().join("identity.json")); store.save(&identity()).unwrap(); std::fs::set_permissions(store.path(), std::fs::Permissions::from_mode(0o644)).unwrap(); let err = store.load().unwrap_err(); assert!( matches!(err, IdentityError::InsecurePermissions { mode: 0o644, .. }), "{err:?}" ); assert!(err.to_string().contains("chmod 600")); }
#[test] fn malformed_file_is_an_error() { let dir = tempfile::tempdir().unwrap(); let store = FileStore::new(dir.path().join("identity.json")); crate::fsutil::write_atomic(store.path(), b"{not json", Some(0o600)).unwrap(); assert!(matches!( store.load().unwrap_err(), IdentityError::Malformed { .. } )); }
#[test] fn memory_store() { let store = MemoryStore::new(); assert!(store.load().unwrap().is_none()); store.save(&identity()).unwrap(); assert_eq!(store.load().unwrap().unwrap().chip, "chip-1"); store.clear().unwrap(); assert!(store.load().unwrap().is_none()); }}