//! Explicit Linux credential provisioning. Never return the secret or rotate a key. use std::path::Path; const USAGE: &str = "usage: strata-next api-key init --file ABSOLUTE_PATH"; fn parse(args: &[String]) -> Result<&Path, String> { let [action, flag, file] = args else { return Err(USAGE.into()); }; if action != "init" || flag != "--file" { return Err(USAGE.into()); } let path = Path::new(file); if !path.is_absolute() || path.file_name().is_none() || file.ends_with('/') || (cfg!(windows) && file.ends_with('\\')) || file .split(['/', '\\']) .any(|part| cfg!(windows) && matches!(part, "." | "..")) || (cfg!(not(windows)) && file.split('/').any(|part| matches!(part, "." | ".."))) || file.chars().any(char::is_control) { return Err( "key path must be an absolute file path without dot components or control characters" .into(), ); } Ok(path) } pub fn run(args: &[String]) -> Result { let path = parse(args)?; #[cfg(target_os = "linux")] { let created = linux::init(path)?; Ok(serde_json::json!({"created":created,"reused":!created})) } #[cfg(target_os = "windows")] { let created = windows::init(path)?; Ok(serde_json::json!({"created":created,"reused":!created})) } #[cfg(not(any(target_os = "linux", target_os = "windows")))] { let _ = path; Err("api-key init currently requires Linux or Windows".into()) } } /// Windows provisioning with the same contract as the Linux one: never rotate, never replace, publish a complete /// key atomically. There are no mode bits to check or set: the key is created next to an existing directory that is /// not a link and inherits that directory's access list, so put it under the user's profile /// (`%LOCALAPPDATA%\leleka\state`), which only the user, SYSTEM and administrators can read. #[cfg(target_os = "windows")] mod windows { use super::*; use std::{ fs::{File, OpenOptions}, io::{Read, Write}, }; fn random() -> Result<[u8; 32], String> { let mut bytes = [0u8; 32]; getrandom::fill(&mut bytes).map_err(|_| "OS random source failed; key not created")?; Ok(bytes) } fn existing(path: &Path) -> Result { match std::fs::symlink_metadata(path) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), Err(_) => { return Err("cannot open existing key safely; no replacement performed".into()); } Ok(m) if !m.is_file() => { return Err("existing key must be a regular file; no replacement performed".into()); } Ok(_) => (), } let file = File::open(path) .map_err(|_| "cannot open existing key safely; no replacement performed")?; let mut bytes = Vec::new(); file.take(515) .read_to_end(&mut bytes) .map_err(|_| "cannot read existing key")?; crate::auth::parse_token(&bytes) .map_err(|_| "existing key is invalid; no replacement performed")?; Ok(true) } struct Temporary(std::path::PathBuf); impl Drop for Temporary { fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } } pub(super) fn init(path: &Path) -> Result { let directory = path.parent().ok_or(USAGE)?; let m = std::fs::symlink_metadata(directory) .map_err(|_| "key parent must be an existing directory, not a link")?; if !m.is_dir() || m.file_type().is_symlink() { return Err("key parent must be an existing directory, not a link".into()); } if existing(path)? { return Ok(false); } let temporary = directory.join(format!(".strata-key-{}", hex::encode(random()?))); let mut file = OpenOptions::new() .write(true) .create_new(true) .open(&temporary) .map_err(|_| "cannot create temporary key; no replacement performed")?; let guard = Temporary(temporary); let token = hex::encode(random()?); file.write_all(token.as_bytes()) .and_then(|_| file.write_all(b"\n")) .and_then(|_| file.sync_all()) .map_err(|_| "key write failed; target not published")?; drop(file); // A hard link never replaces an existing target (NTFS); the temporary name is removed afterwards. let created = match std::fs::hard_link(&guard.0, path) { Ok(()) => true, Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { if !existing(path)? { return Err("concurrent key disappeared; retry init to reconcile".into()); } false } Err(_) => { return Err( "cannot publish key (the volume must be NTFS); no replacement performed".into(), ); } }; drop(guard); Ok(created) } } #[cfg(target_os = "linux")] mod linux { use super::*; use std::{ ffi::CString, fs::{File, OpenOptions}, io::{Read, Write}, os::{ fd::{AsRawFd, FromRawFd}, unix::{ ffi::OsStrExt, fs::{MetadataExt, OpenOptionsExt}, }, }, }; fn random() -> Result<[u8; 32], String> { let mut bytes = [0u8; 32]; let mut offset = 0; while offset < bytes.len() { // Linux OS CSPRNG; no clock/PID/user-provided seed or fallback. let n = unsafe { libc::getrandom(bytes[offset..].as_mut_ptr().cast(), bytes.len() - offset, 0) }; if n < 0 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted { continue; } if n <= 0 { return Err("OS random source failed; key not created".into()); } offset += n as usize; } Ok(bytes) } fn existing(directory: &File, name: &CString) -> Result { let fd = unsafe { libc::openat( directory.as_raw_fd(), name.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK, ) }; if fd < 0 { return if std::io::Error::last_os_error().kind() == std::io::ErrorKind::NotFound { Ok(false) } else { Err("cannot open existing key safely; no replacement performed".into()) }; } let file = unsafe { File::from_raw_fd(fd) }; let m = file.metadata().map_err(|_| "cannot inspect existing key")?; if !m.is_file() || m.uid() != unsafe { libc::geteuid() } || m.mode() & 0o077 != 0 { return Err( "existing key must be an owned private regular file; no replacement performed" .into(), ); } let mut bytes = Vec::new(); file.take(515) .read_to_end(&mut bytes) .map_err(|_| "cannot read existing key")?; crate::auth::parse_token(&bytes) .map_err(|_| "existing key is invalid; no replacement performed")?; Ok(true) } struct Temporary<'a> { directory: &'a File, name: CString, } impl Drop for Temporary<'_> { fn drop(&mut self) { unsafe { libc::unlinkat(self.directory.as_raw_fd(), self.name.as_ptr(), 0); } } } pub(super) fn init(path: &Path) -> Result { let directory = OpenOptions::new() .read(true) .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) .open(path.parent().ok_or(USAGE)?) .map_err(|_| "key parent must be an existing private directory, not a symlink")?; let m = directory .metadata() .map_err(|_| "cannot inspect key parent")?; if m.uid() != unsafe { libc::geteuid() } || m.mode() & 0o077 != 0 { return Err( "key parent must be owned and private (mode 700); no permissions changed".into(), ); } let name = CString::new(path.file_name().ok_or(USAGE)?.as_bytes()).map_err(|_| USAGE)?; if existing(&directory, &name)? { directory .sync_all() .map_err(|_| "key exists but directory synchronization failed")?; return Ok(false); } let temporary = CString::new(format!(".strata-key-{}", hex::encode(random()?))).unwrap(); let fd = unsafe { libc::openat( directory.as_raw_fd(), temporary.as_ptr(), libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0o600, ) }; if fd < 0 { return Err("cannot create private temporary key; no replacement performed".into()); } let guard = Temporary { directory: &directory, name: temporary, }; let mut file = unsafe { File::from_raw_fd(fd) }; // Only the newly created temporary inode; never change existing keys. if unsafe { libc::fchmod(file.as_raw_fd(), 0o600) } != 0 { return Err("cannot set private temporary key mode; target not published".into()); } let token = hex::encode(random()?); file.write_all(token.as_bytes()) .and_then(|_| file.write_all(b"\n")) .and_then(|_| file.sync_all()) .map_err(|_| "private key write failed; target not published")?; // linkat never replaces an existing target. Both names are scoped to the // opened directory, including when an ancestor path is renamed. let linked = unsafe { libc::linkat( directory.as_raw_fd(), guard.name.as_ptr(), directory.as_raw_fd(), name.as_ptr(), 0, ) }; let created = if linked == 0 { true } else if std::io::Error::last_os_error().kind() == std::io::ErrorKind::AlreadyExists { if !existing(&directory, &name)? { return Err("concurrent key disappeared; retry init to reconcile".into()); } false } else { return Err("cannot publish private key; no replacement performed".into()); }; drop(file); drop(guard); directory.sync_all().map_err( |_| "key published but directory synchronization failed; retry init to reconcile", )?; Ok(created) } } #[cfg(test)] mod tests { use super::*; #[test] fn only_explicit_absolute_init() { let args = |s: &[&str]| s.iter().map(|s| s.to_string()).collect::>(); let good = if cfg!(windows) { "C:\\private\\api.key" } else { "/private/api.key" }; assert!(parse(&args(&["init", "--file", good])).is_ok()); for parts in [ vec![], vec!["rotate", "--file", "/a"], vec!["init", "--file", "relative"], vec!["init", "--file", "/a/../b"], vec!["init", "--file", "/a/."], vec!["init", "--file", "/a/"], vec!["init", "--file", "/a\nb"], vec!["init", "--file", "/a", "--force"], ] { assert!(parse(&args(&parts)).is_err()); } } } #[cfg(all(test, target_os = "windows"))] mod windows_tests { use super::*; #[test] fn init_creates_once_and_reuses_without_rotating() { let dir = std::env::temp_dir().join(format!("strata-key-win-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let key = dir.join("api-key"); let args = vec![ "init".to_owned(), "--file".to_owned(), key.display().to_string(), ]; let first = run(&args).unwrap(); assert_eq!(first["created"], true); let text = std::fs::read_to_string(&key).unwrap(); assert_eq!(text.len(), 65); assert!(text.ends_with('\n') && text[..64].bytes().all(|b| b.is_ascii_hexdigit())); let second = run(&args).unwrap(); assert_eq!( (second["created"].clone(), second["reused"].clone()), (false.into(), true.into()) ); assert_eq!(std::fs::read_to_string(&key).unwrap(), text); // no temporary name is left behind assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); // an existing invalid key is never replaced std::fs::write(&key, "short").unwrap(); assert!(run(&args).is_err()); assert_eq!(std::fs::read_to_string(&key).unwrap(), "short"); std::fs::remove_dir_all(&dir).unwrap(); } #[test] fn dot_components_and_trailing_separators_are_refused_with_either_separator() { let args = |p: &str| vec!["init".to_owned(), "--file".to_owned(), p.to_owned()]; for bad in [ r"C:\a\..\b", r"C:\a\.\b", r"C:\a\", "C:/a/../b", r"relative\key", ] { assert!(parse(&args(bad)).is_err(), "{bad}"); } } }