//! Protected atomic OAuth profile storage (`SMH-SPEC-SPEC0001`). use super::{Profile, ProfileMetadata}; use serde::{Deserialize, Serialize}; use std::fmt::Write as _; use std::fs::{self, File, OpenOptions}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; const STORE_VERSION: u8 = 2; const STORE_BYTES_MAX: u64 = 512 * 1024; const PROFILES_MAX: usize = 16; /// Separate OAuth profile namespace; API-key files are never read or modified. #[derive(Clone)] pub struct ProfileStore { root: PathBuf, } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct Store { version: u8, host_id: String, profiles: Vec, } impl ProfileStore { /// Select the trusted store directory explicitly. #[must_use] pub const fn at(root: PathBuf) -> Self { Self { root } } pub(super) fn host_id(&self) -> Result { let _lock = self.lock()?; if let Some(store) = self.read()? { return Ok(store.host_id); } let mut bytes = smith::entropy::bytes::<16>().map_err(|_| "OAuth host entropy unavailable")?; bytes[6] = (bytes[6] & 15) | 64; bytes[8] = (bytes[8] & 63) | 128; let mut host_id = String::with_capacity(45); host_id.push_str("urn:uuid:"); for (index, byte) in bytes.iter().enumerate() { if matches!(index, 4 | 6 | 8 | 10) { host_id.push('-'); } write!(host_id, "{byte:02x}").map_err(|_| "OAuth host identity encoding failed")?; } self.write(&Store { version: STORE_VERSION, host_id: host_id.clone(), profiles: Vec::new(), })?; Ok(host_id) } pub(super) fn save(&self, profile: Profile) -> Result { let _lock = self.lock()?; let mut store = self.read()?.ok_or("OAuth host identity missing")?; let index = match store .profiles .binary_search_by(|existing| existing.metadata.id.cmp(&profile.metadata.id)) { Ok(index) => { let existing = &store.profiles[index].metadata; if existing.flow != profile.metadata.flow || existing.connection_id != profile.metadata.connection_id || existing.issuer != profile.metadata.issuer || existing.subject != profile.metadata.subject || existing.client_id != profile.metadata.client_id || existing.workspace != profile.metadata.workspace || existing.code_assist_project != profile.metadata.code_assist_project { return Err("OAuth profile identity collision"); } store.profiles[index] = profile; index } Err(index) => { if store.profiles.len() == PROFILES_MAX { return Err("OAuth profile count bound exceeded"); } store.profiles.insert(index, profile); index } }; self.write(&store)?; // Move the acknowledgement out of temporary resident state after publication. Ok(store.profiles.remove(index).metadata) } /// Reject unusable renewable state without exposing or consuming credentials. pub(super) fn renewable_profile_available( &self, id: &str, ) -> Result<(), super::AuthorizationFault> { use super::AuthorizationFault; let _lock = self.lock().map_err(AuthorizationFault::Storage)?; let store = self .read() .map_err(AuthorizationFault::Storage)? .ok_or(AuthorizationFault::ReauthenticationRequired)?; let profile = store .profiles .iter() .find(|profile| profile.metadata.id == id) .ok_or(AuthorizationFault::ReauthenticationRequired)?; if profile.refresh_pending || profile.tokens.is_none() { return Err(AuthorizationFault::ReauthenticationRequired); } Ok(()) } pub(super) fn end_session( &self, id: &str, policy: &super::LoginPolicy, cancel: &smith::tool::CancelHandle, ) -> Result { use super::AuthorizationFault; let _lock = self.lock().map_err(AuthorizationFault::Storage)?; let mut store = self .read() .map_err(AuthorizationFault::Storage)? .ok_or(AuthorizationFault::ReauthenticationRequired)?; let index = store .profiles .iter() .position(|profile| profile.metadata.id == id) .ok_or(AuthorizationFault::ReauthenticationRequired)?; if !store.profiles[index].metadata.matches_policy(policy) { return Err(AuthorizationFault::Authority); } let uncertain = store.profiles[index].refresh_pending; store.profiles[index].refresh_pending = true; self.write(&store).map_err(AuthorizationFault::Storage)?; let confirmed = store.profiles[index].tokens.as_ref().is_some_and(|tokens| { super::revoke_session( policy, &store.profiles[index].metadata.client_id, &tokens.refresh, cancel, ) .is_ok() && !uncertain }); store.profiles[index].tokens = None; store.profiles[index].refresh_pending = false; self.write(&store).map_err(AuthorizationFault::Storage)?; Ok(confirmed) } pub(super) fn renew( &self, id: &str, policy: &super::LoginPolicy, cancel: &smith::tool::CancelHandle, ) -> Result { use super::AuthorizationFault; let _lock = self.lock().map_err(AuthorizationFault::Storage)?; let mut store = self .read() .map_err(AuthorizationFault::Storage)? .ok_or(AuthorizationFault::ReauthenticationRequired)?; let index = store .profiles .iter() .position(|profile| profile.metadata.id == id) .ok_or(AuthorizationFault::ReauthenticationRequired)?; let profile = &store.profiles[index]; if !profile.metadata.matches_policy(policy) { return Err(AuthorizationFault::Authority); } if profile.refresh_pending || profile.tokens.is_none() || policy .required_scopes .iter() .any(|scope| !profile.metadata.scopes.contains(scope)) { return Err(AuthorizationFault::ReauthenticationRequired); } let now = super::now()?; if profile.metadata.expires_at > now.saturating_add(60) { return store .profiles .remove(index) .tokens .ok_or(AuthorizationFault::ReauthenticationRequired); } if cancel.is_cancelled() { return Err(AuthorizationFault::Cancelled); } // Publication precedes dispatch: a crash or lost response must never replay rotation. store.profiles[index].refresh_pending = true; self.write(&store).map_err(AuthorizationFault::Storage)?; let result = super::refresh_profile(policy, &store.profiles[index], cancel); match result { Ok(profile) => { if cancel.is_cancelled() { return Err(AuthorizationFault::ExchangeUncertain); } if profile.metadata.id != id { return Err(AuthorizationFault::Rejected( "OAuth refresh identity mismatch", )); } store.profiles[index] = profile; self.write(&store).map_err(AuthorizationFault::Storage)?; store .profiles .remove(index) .tokens .ok_or(AuthorizationFault::ReauthenticationRequired) } Err(AuthorizationFault::ReauthenticationRequired) => { store.profiles[index].tokens = None; self.write(&store).map_err(AuthorizationFault::Storage)?; Err(AuthorizationFault::ReauthenticationRequired) } Err(fault) => Err(fault), } } /// Read only metadata for local profile listing. /// # Errors /// Rejects malformed, oversized, or insecure stores. pub fn list(&self) -> Result, &'static str> { if !self .root .try_exists() .map_err(|_| "OAuth store status failed")? { return Ok(Vec::new()); } let _lock = self.lock()?; Ok(self.read()?.map_or_else(Vec::new, |store| { store .profiles .into_iter() .map(|profile| profile.metadata) .collect() })) } fn lock(&self) -> Result { #[cfg(unix)] { use std::os::unix::fs::DirBuilderExt; fs::DirBuilder::new() .recursive(true) .mode(0o700) .create(&self.root) .map_err(|_| "OAuth store directory creation failed")?; } #[cfg(not(unix))] fs::create_dir_all(&self.root).map_err(|_| "OAuth store directory creation failed")?; let metadata = fs::symlink_metadata(&self.root).map_err(|_| "OAuth store directory status failed")?; if !metadata.is_dir() || metadata.file_type().is_symlink() { return Err("OAuth store requires a regular directory"); } #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; if metadata.permissions().mode() & 0o077 != 0 { return Err("OAuth store directory must be owner-only"); } } let lock_path = self.root.join("lock"); let mut options = OpenOptions::new(); options.read(true).write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } let file = match options.open(&lock_path) { Ok(file) => file, Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { protected_open(&lock_path)? } Err(_) => return Err("OAuth store lock creation failed"), }; file.try_lock() .map_err(|_| "OAuth profile store busy; no exchange started")?; Ok(file) } fn read(&self) -> Result, &'static str> { let path = self.root.join("profiles.json"); if !path.try_exists().map_err(|_| "OAuth store status failed")? { if fs::symlink_metadata(&path).is_ok() { return Err("OAuth store cannot be a dangling link"); } return Ok(None); } let file = protected_open(&path)?; let mut bytes = Vec::new(); #[expect( clippy::disallowed_methods, reason = "Take caps OAuth store bytes before checking overflow" )] file.take(STORE_BYTES_MAX + 1) .read_to_end(&mut bytes) .map_err(|_| "OAuth store read failed")?; if bytes.len() as u64 > STORE_BYTES_MAX { return Err("OAuth profile store exceeds byte bound"); } let store: Store = serde_json::from_slice(&bytes).map_err(|_| "corrupt OAuth profile store")?; if !valid_host_id(&store.host_id) { return Err( "invalid OAuth host UUID URI; restore the original store or explicitly remove this prototype store to register a new host", ); } if store.version != STORE_VERSION || store.profiles.len() > PROFILES_MAX || store .profiles .windows(2) .any(|pair| pair[0].metadata.id >= pair[1].metadata.id) || store.profiles.iter().any(|profile| { profile.metadata.id.len() != 64 || !profile .metadata .id .bytes() .all(|byte| byte.is_ascii_hexdigit()) }) { return Err("invalid OAuth profile store schema"); } for profile in &store.profiles { super::validate_metadata_secrecy(profile)?; } Ok(Some(store)) } fn write(&self, store: &Store) -> Result<(), &'static str> { let bytes = serde_json::to_vec(store).map_err(|_| "OAuth store serialization failed")?; if bytes.len() as u64 > STORE_BYTES_MAX { return Err("OAuth profile store exceeds byte bound"); } let suffix = super::encode( &smith::entropy::bytes::<16>().map_err(|_| "OAuth storage entropy unavailable")?, ); let temporary = self.root.join(format!("pending-{suffix}")); let mut options = OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } let result = (|| { let mut file = options .open(&temporary) .map_err(|_| "OAuth atomic store creation failed")?; file.write_all(&bytes) .and_then(|()| file.sync_all()) .map_err(|_| "OAuth atomic store write failed")?; publish(&temporary, &self.root.join("profiles.json"), &self.root) })(); if result.is_err() { let _cleanup = fs::remove_file(temporary); } result } } fn publish(temporary: &Path, profile: &Path, root: &Path) -> Result<(), &'static str> { publish_with( temporary, profile, root, |from, to| fs::rename(from, to), |directory| File::open(directory).and_then(|file| file.sync_all()), ) } fn publish_with( temporary: &Path, profile: &Path, root: &Path, rename: Rename, sync: Sync, ) -> Result<(), &'static str> where Rename: FnOnce(&Path, &Path) -> std::io::Result<()>, Sync: FnOnce(&Path) -> std::io::Result<()>, { rename(temporary, profile).map_err(|_| "OAuth atomic store publication failed")?; sync(root).map_err(|_| "OAuth directory sync failed; publication uncertain") } fn valid_host_id(identity: &str) -> bool { let Some(uuid) = identity.strip_prefix("urn:uuid:") else { return false; }; uuid.len() == 36 && uuid.bytes().enumerate().all(|(index, byte)| { if matches!(index, 8 | 13 | 18 | 23) { byte == b'-' } else { byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte) } }) && uuid.as_bytes()[14] == b'4' && matches!(uuid.as_bytes()[19], b'8' | b'9' | b'a' | b'b') } fn protected_open(path: &Path) -> Result { let before = fs::symlink_metadata(path).map_err(|_| "OAuth protected file status failed")?; if !before.is_file() || before.file_type().is_symlink() { return Err("OAuth store requires regular files"); } #[cfg(unix)] { use std::os::unix::fs::{MetadataExt, PermissionsExt}; if before.permissions().mode() & 0o777 != 0o600 || before.nlink() != 1 { return Err("OAuth store file must be private and unlinked elsewhere"); } } let file = OpenOptions::new() .read(true) .write(true) .open(path) .map_err(|_| "OAuth protected file open failed")?; let after = file .metadata() .map_err(|_| "OAuth protected file status failed")?; #[cfg(unix)] { use std::os::unix::fs::MetadataExt; if before.dev() != after.dev() || before.ino() != after.ino() { return Err("OAuth protected file changed during open"); } } if !after.is_file() { return Err("OAuth store requires regular files"); } Ok(file) } #[cfg(test)] mod publication_tests { use super::publish_with; use std::fs; use std::io; fn fixture_root() -> std::path::PathBuf { let root = std::env::temp_dir().join(format!("oauth-publication-{}", smith::id::SessionId::new())); fs::create_dir(&root).unwrap(); root } #[test] fn rename_failure_retains_canonical_profile_and_temporary_generation() { let root = fixture_root(); let profile = root.join("profiles.json"); let temporary = root.join("pending"); fs::write(&profile, b"canonical").unwrap(); fs::write(&temporary, b"verified-next").unwrap(); let error = publish_with( &temporary, &profile, &root, |_, _| Err(io::Error::other("fixture rename failure")), |_| Ok(()), ) .unwrap_err(); assert_eq!(error, "OAuth atomic store publication failed"); assert_eq!(fs::read(&profile).unwrap(), b"canonical"); assert_eq!(fs::read(&temporary).unwrap(), b"verified-next"); fs::remove_dir_all(root).unwrap(); } #[test] fn directory_sync_failure_after_rename_leaves_complete_new_generation() { let root = fixture_root(); let profile = root.join("profiles.json"); let temporary = root.join("pending"); fs::write(&profile, b"old-access\nold-refresh").unwrap(); fs::write(&temporary, b"new-access\nnew-refresh").unwrap(); let error = publish_with( &temporary, &profile, &root, |from, to| fs::rename(from, to), |_| Err(io::Error::other("fixture directory sync failure")), ) .unwrap_err(); assert_eq!(error, "OAuth directory sync failed; publication uncertain"); assert_eq!(fs::read(&profile).unwrap(), b"new-access\nnew-refresh"); assert!(!temporary.exists()); fs::remove_dir_all(root).unwrap(); } }