143 lines
4.8 KiB
Rust
143 lines
4.8 KiB
Rust
//! 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 !acceptable_key_path(path, file) {
|
|
return Err(
|
|
"key path must be an absolute file path without dot components or control characters"
|
|
.into(),
|
|
);
|
|
}
|
|
Ok(path)
|
|
}
|
|
|
|
fn acceptable_key_path(path: &Path, file: &str) -> bool {
|
|
path.is_absolute()
|
|
&& path.file_name().is_some()
|
|
&& !file.ends_with('/')
|
|
&& !(cfg!(windows) && file.ends_with('\\'))
|
|
&& !has_dot_component(file)
|
|
&& !file.chars().any(char::is_control)
|
|
}
|
|
|
|
fn has_dot_component(file: &str) -> bool {
|
|
file.split(['/', '\\'])
|
|
.any(|part| cfg!(windows) && matches!(part, "." | ".."))
|
|
|| (cfg!(not(windows)) && file.split('/').any(|part| matches!(part, "." | "..")))
|
|
}
|
|
|
|
pub fn run(args: &[String]) -> Result<serde_json::Value, String> {
|
|
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;
|
|
|
|
#[cfg(target_os = "linux")]
|
|
mod linux;
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn only_explicit_absolute_init() {
|
|
let args = |s: &[&str]| s.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
|
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}");
|
|
}
|
|
}
|
|
}
|