use std::io::Write as _;
use std::path::{Path, PathBuf};
use astrs_wire::AuthToken;
use crate::error::CliError;
pub const TOKEN_FILE: &str = ".astrs-token";
pub const ENV_TOKEN: &str = "ASTRS_TOKEN";
pub const ENV_COORDINATOR_ADDR: &str = "ASTRS_COORDINATOR_ADDR";
pub const COORDINATOR_PIDFILE: &str = "coordinator.pid";
pub const DAEMON_PIDFILE: &str = "daemon.pid";
pub const BUILD_LOG_DIR: &str = "build";
const TOKEN_MODE: rustix::fs::Mode = rustix::fs::Mode::RUSR.union(rustix::fs::Mode::WUSR);
pub const TOKEN_MODE_OCTAL: u32 = 0o600;
#[must_use]
pub fn runtime_dir(explicit: Option<&Path>) -> PathBuf {
explicit.map_or_else(
astrs_daemon::config::paths::default_runtime_dir,
Path::to_path_buf,
)
}
#[must_use]
pub fn working_dir(explicit: Option<&Path>) -> PathBuf {
explicit.map_or_else(
|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
Path::to_path_buf,
)
}
pub fn ensure_dir(dir: &Path) -> Result<(), CliError> {
std::fs::create_dir_all(dir).map_err(|source| CliError::io(dir, source))
}
#[must_use]
pub fn token_path(working_dir: &Path) -> PathBuf {
working_dir.join(TOKEN_FILE)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenSource {
Argument,
Environment,
File(PathBuf),
}
impl std::fmt::Display for TokenSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Argument => f.write_str("--token"),
Self::Environment => f.write_str(ENV_TOKEN),
Self::File(path) => write!(f, "{}", path.display()),
}
}
}
pub fn find_token(
argument: Option<&str>,
file: Option<&Path>,
working_dir: &Path,
) -> Result<Option<(AuthToken, TokenSource)>, CliError> {
if let Some(text) = argument {
return parse_token(text, TokenSource::Argument).map(Some);
}
if let Some(path) = file {
let text = std::fs::read_to_string(path).map_err(|source| CliError::io(path, source))?;
return parse_token(&text, TokenSource::File(path.to_path_buf())).map(Some);
}
if let Ok(text) = std::env::var(ENV_TOKEN)
&& !text.trim().is_empty()
{
return parse_token(&text, TokenSource::Environment).map(Some);
}
let conventional = token_path(working_dir);
match std::fs::read_to_string(&conventional) {
Ok(text) => parse_token(&text, TokenSource::File(conventional)).map(Some),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(source) => Err(CliError::io(&conventional, source)),
}
}
fn parse_token(text: &str, source: TokenSource) -> Result<(AuthToken, TokenSource), CliError> {
AuthToken::parse_hex(text.trim())
.map(|token| (token, source.clone()))
.map_err(|error| CliError::BadToken {
path: source.to_string(),
source: error,
})
}
pub fn ensure_token_file(working_dir: &Path) -> Result<(AuthToken, PathBuf), CliError> {
let path = token_path(working_dir);
if let Ok(text) = std::fs::read_to_string(&path) {
let (token, _) = parse_token(&text, TokenSource::File(path.clone()))?;
set_owner_only(&path)?;
return Ok((token, path));
}
ensure_dir(working_dir)?;
let token = AuthToken::generate().map_err(|error| CliError::BadToken {
path: path.display().to_string(),
source: error,
})?;
write_private(&path, format!("{}\n", token.reveal_hex()).as_bytes())?;
Ok((token, path))
}
pub fn write_token_file(path: &Path, token: &AuthToken) -> Result<(), CliError> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
ensure_dir(parent)?;
}
write_private(path, format!("{}\n", token.reveal_hex()).as_bytes())
}
fn write_private(path: &Path, bytes: &[u8]) -> Result<(), CliError> {
let temporary = path.with_extension("tmp");
{
let mut file =
std::fs::File::create(&temporary).map_err(|source| CliError::io(&temporary, source))?;
set_owner_only(&temporary)?;
file.write_all(bytes)
.map_err(|source| CliError::io(&temporary, source))?;
file.sync_all()
.map_err(|source| CliError::io(&temporary, source))?;
}
std::fs::rename(&temporary, path).map_err(|source| CliError::io(path, source))
}
fn set_owner_only(path: &Path) -> Result<(), CliError> {
rustix::fs::chmod(path, TOKEN_MODE).map_err(|error| {
CliError::io(
path,
std::io::Error::from_raw_os_error(error.raw_os_error()),
)
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PidFile {
pub pid: u32,
pub addr: Option<String>,
}
impl PidFile {
#[must_use]
pub const fn new(pid: u32) -> Self {
Self { pid, addr: None }
}
#[must_use]
pub fn listening(pid: u32, addr: impl Into<String>) -> Self {
Self {
pid,
addr: Some(addr.into()),
}
}
#[must_use]
pub fn to_text(&self) -> String {
match &self.addr {
Some(addr) => format!("{}\n{addr}\n", self.pid),
None => format!("{}\n", self.pid),
}
}
#[must_use]
pub fn parse(text: &str) -> Option<Self> {
let mut lines = text.lines();
let pid: u32 = lines.next()?.trim().parse().ok()?;
let addr = lines
.next()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(ToOwned::to_owned);
Some(Self { pid, addr })
}
#[must_use]
pub fn is_alive(&self) -> bool {
let Ok(pid) = rustix::process::Pid::from_raw(self.pid.cast_signed()).ok_or(()) else {
return false;
};
matches!(rustix::process::test_kill_process(pid), Ok(()))
}
}
pub fn write_pidfile(path: &Path, record: &PidFile) -> Result<(), CliError> {
if let Some(parent) = path.parent() {
ensure_dir(parent)?;
}
std::fs::write(path, record.to_text()).map_err(|source| CliError::io(path, source))
}
#[must_use]
pub fn read_pidfile(path: &Path) -> Option<PidFile> {
let text = std::fs::read_to_string(path).ok()?;
PidFile::parse(&text)
}
pub fn remove_pidfile(path: &Path) -> Result<(), CliError> {
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(source) => Err(CliError::io(path, source)),
}
}
#[must_use]
pub fn build_log_dir(runtime_dir: &Path) -> PathBuf {
runtime_dir.join(BUILD_LOG_DIR)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"astrs-cli-runtime-dir-{}-{name}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn permission_flags(path: &Path) -> rustix::fs::Mode {
use rustix::fs::Mode;
let stat = rustix::fs::stat(path).unwrap();
Mode::from_raw_mode(stat.st_mode)
.intersection(Mode::RWXU.union(Mode::RWXG).union(Mode::RWXO))
}
#[test]
fn the_documented_octal_spells_the_mode_that_gets_set() {
assert_eq!(
format!("{:o}", TOKEN_MODE.bits()),
format!("{TOKEN_MODE_OCTAL:o}")
);
}
#[test]
fn an_explicit_runtime_dir_wins_over_the_environment() {
let explicit = PathBuf::from("/tmp/somewhere");
assert_eq!(runtime_dir(Some(&explicit)), explicit);
}
#[test]
fn the_default_runtime_dir_is_the_daemons_own() {
assert_eq!(
runtime_dir(None),
astrs_daemon::config::paths::default_runtime_dir()
);
}
#[test]
fn a_generated_token_round_trips_and_is_owner_only() {
let dir = scratch("token");
let (token, path) = ensure_token_file(&dir).unwrap();
assert_eq!(path, dir.join(TOKEN_FILE));
assert_eq!(token.reveal_hex().len(), 64);
let found = find_token(None, None, &dir).unwrap().unwrap();
assert_eq!(found.0, token);
assert_eq!(found.1, TokenSource::File(path.clone()));
assert_eq!(permission_flags(&path), TOKEN_MODE);
}
#[test]
fn write_token_file_persists_the_exact_value_given() {
let dir = scratch("token-write-exact");
let path = dir.join("read.token");
let token = AuthToken::from_bytes([0x5A; 32]);
write_token_file(&path, &token).unwrap();
let (found, source) = find_token(None, Some(&path), &dir).unwrap().unwrap();
assert_eq!(found, token);
assert_eq!(source, TokenSource::File(path.clone()));
assert_eq!(permission_flags(&path), TOKEN_MODE);
}
#[test]
fn write_token_file_creates_a_missing_parent_directory() {
let dir = scratch("token-write-nested");
let path = dir.join("nested").join("deeper").join("read.token");
let token = AuthToken::from_bytes([0x5B; 32]);
write_token_file(&path, &token).unwrap();
let (found, _) = find_token(None, Some(&path), &dir).unwrap().unwrap();
assert_eq!(found, token);
}
#[test]
fn a_second_up_reuses_the_token_already_on_disk() {
let dir = scratch("token-reuse");
let (first, _) = ensure_token_file(&dir).unwrap();
let (second, _) = ensure_token_file(&dir).unwrap();
assert_eq!(
first, second,
"regenerating would lock out every process holding the old one"
);
}
#[test]
fn a_corrupt_token_file_is_refused_rather_than_replaced() {
let dir = scratch("token-corrupt");
std::fs::write(token_path(&dir), "not a token").unwrap();
let error = ensure_token_file(&dir).unwrap_err();
assert!(matches!(error, CliError::BadToken { .. }), "{error}");
}
#[test]
fn an_argument_beats_a_file() {
let dir = scratch("token-argument");
let (on_disk, _) = ensure_token_file(&dir).unwrap();
let other = AuthToken::from_bytes([9; 32]);
let found = find_token(Some(&other.reveal_hex()), None, &dir)
.unwrap()
.unwrap();
assert_eq!(found.0, other);
assert_ne!(found.0, on_disk);
assert_eq!(found.1, TokenSource::Argument);
}
#[test]
fn a_missing_conventional_token_is_not_an_error() {
let dir = scratch("token-absent");
assert!(find_token(None, None, &dir).unwrap().is_none());
}
#[test]
fn a_missing_explicit_token_file_is_an_error() {
let dir = scratch("token-explicit-absent");
let path = dir.join("nowhere.token");
let error = find_token(None, Some(&path), &dir).unwrap_err();
assert!(matches!(error, CliError::Io { .. }), "{error}");
}
#[test]
fn a_bad_argument_token_names_the_argument() {
let dir = scratch("token-bad-argument");
let error = find_token(Some("zz"), None, &dir).unwrap_err();
match error {
CliError::BadToken { path, .. } => assert_eq!(path, "--token"),
other => panic!("expected BadToken, got {other}"),
}
}
#[test]
fn a_pidfile_round_trips_through_its_text_form() {
let record = PidFile::listening(4242, "127.0.0.1:7407");
let parsed = PidFile::parse(&record.to_text()).unwrap();
assert_eq!(parsed, record);
let bare = PidFile::new(7);
assert_eq!(PidFile::parse(&bare.to_text()).unwrap(), bare);
}
#[test]
fn a_malformed_pidfile_reads_as_nothing_running() {
let dir = scratch("pidfile-malformed");
let path = dir.join(COORDINATOR_PIDFILE);
std::fs::write(&path, "\u{0}not a pid").unwrap();
assert!(read_pidfile(&path).is_none());
}
#[test]
fn writing_then_removing_a_pidfile_leaves_nothing_behind() {
let dir = scratch("pidfile-lifecycle");
let path = dir.join(DAEMON_PIDFILE);
write_pidfile(&path, &PidFile::listening(std::process::id(), "uds")).unwrap();
let read = read_pidfile(&path).unwrap();
assert_eq!(read.pid, std::process::id());
assert!(read.is_alive(), "this very process is alive");
remove_pidfile(&path).unwrap();
assert!(read_pidfile(&path).is_none());
remove_pidfile(&path).expect("removing a gone pidfile is not an error");
}
#[test]
fn a_pid_that_cannot_exist_is_not_alive() {
assert!(!PidFile::new(0).is_alive());
}
#[test]
fn the_build_log_directory_hangs_off_the_runtime_directory() {
let dir = PathBuf::from("/run/astrs");
assert_eq!(build_log_dir(&dir), dir.join(BUILD_LOG_DIR));
}
}