Files
leleka/control-plane/src/key_init.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

219 lines
7.5 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 !path.is_absolute()
|| path.file_name().is_none()
|| file.ends_with('/')
|| 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<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(not(target_os = "linux"))]
{
let _ = path;
Err("api-key init currently requires Linux".into())
}
}
#[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<bool, String> {
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<bool, String> {
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::<Vec<_>>();
assert!(parse(&args(&["init", "--file", "/private/api.key"])).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());
}
}
}