1use std::io::Write as _;
34use std::path::{Path, PathBuf};
35
36use astrs_wire::AuthToken;
37
38use crate::error::CliError;
39
40pub const TOKEN_FILE: &str = ".astrs-token";
42
43pub const ENV_TOKEN: &str = "ASTRS_TOKEN";
45
46pub const ENV_COORDINATOR_ADDR: &str = "ASTRS_COORDINATOR_ADDR";
48
49pub const COORDINATOR_PIDFILE: &str = "coordinator.pid";
51
52pub const DAEMON_PIDFILE: &str = "daemon.pid";
54
55pub const BUILD_LOG_DIR: &str = "build";
57
58const TOKEN_MODE: rustix::fs::Mode = rustix::fs::Mode::RUSR.union(rustix::fs::Mode::WUSR);
65
66pub const TOKEN_MODE_OCTAL: u32 = 0o600;
69
70#[must_use]
77pub fn runtime_dir(explicit: Option<&Path>) -> PathBuf {
78 explicit.map_or_else(
79 astrs_daemon::config::paths::default_runtime_dir,
80 Path::to_path_buf,
81 )
82}
83
84#[must_use]
90pub fn working_dir(explicit: Option<&Path>) -> PathBuf {
91 explicit.map_or_else(
92 || std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
93 Path::to_path_buf,
94 )
95}
96
97pub fn ensure_dir(dir: &Path) -> Result<(), CliError> {
103 std::fs::create_dir_all(dir).map_err(|source| CliError::io(dir, source))
104}
105
106#[must_use]
108pub fn token_path(working_dir: &Path) -> PathBuf {
109 working_dir.join(TOKEN_FILE)
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum TokenSource {
115 Argument,
117 Environment,
119 File(PathBuf),
121}
122
123impl std::fmt::Display for TokenSource {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 match self {
126 Self::Argument => f.write_str("--token"),
127 Self::Environment => f.write_str(ENV_TOKEN),
128 Self::File(path) => write!(f, "{}", path.display()),
129 }
130 }
131}
132
133pub fn find_token(
147 argument: Option<&str>,
148 file: Option<&Path>,
149 working_dir: &Path,
150) -> Result<Option<(AuthToken, TokenSource)>, CliError> {
151 if let Some(text) = argument {
152 return parse_token(text, TokenSource::Argument).map(Some);
153 }
154 if let Some(path) = file {
155 let text = std::fs::read_to_string(path).map_err(|source| CliError::io(path, source))?;
158 return parse_token(&text, TokenSource::File(path.to_path_buf())).map(Some);
159 }
160 if let Ok(text) = std::env::var(ENV_TOKEN)
161 && !text.trim().is_empty()
162 {
163 return parse_token(&text, TokenSource::Environment).map(Some);
164 }
165 let conventional = token_path(working_dir);
166 match std::fs::read_to_string(&conventional) {
167 Ok(text) => parse_token(&text, TokenSource::File(conventional)).map(Some),
168 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
169 Err(source) => Err(CliError::io(&conventional, source)),
170 }
171}
172
173fn parse_token(text: &str, source: TokenSource) -> Result<(AuthToken, TokenSource), CliError> {
175 AuthToken::parse_hex(text.trim())
176 .map(|token| (token, source.clone()))
177 .map_err(|error| CliError::BadToken {
178 path: source.to_string(),
179 source: error,
180 })
181}
182
183pub fn ensure_token_file(working_dir: &Path) -> Result<(AuthToken, PathBuf), CliError> {
197 let path = token_path(working_dir);
198 if let Ok(text) = std::fs::read_to_string(&path) {
199 let (token, _) = parse_token(&text, TokenSource::File(path.clone()))?;
200 set_owner_only(&path)?;
204 return Ok((token, path));
205 }
206 ensure_dir(working_dir)?;
207 let token = AuthToken::generate().map_err(|error| CliError::BadToken {
208 path: path.display().to_string(),
209 source: error,
210 })?;
211 write_private(&path, format!("{}\n", token.reveal_hex()).as_bytes())?;
212 Ok((token, path))
213}
214
215pub fn write_token_file(path: &Path, token: &AuthToken) -> Result<(), CliError> {
233 if let Some(parent) = path.parent()
234 && !parent.as_os_str().is_empty()
235 {
236 ensure_dir(parent)?;
237 }
238 write_private(path, format!("{}\n", token.reveal_hex()).as_bytes())
239}
240
241fn write_private(path: &Path, bytes: &[u8]) -> Result<(), CliError> {
247 let temporary = path.with_extension("tmp");
248 {
249 let mut file =
250 std::fs::File::create(&temporary).map_err(|source| CliError::io(&temporary, source))?;
251 set_owner_only(&temporary)?;
252 file.write_all(bytes)
253 .map_err(|source| CliError::io(&temporary, source))?;
254 file.sync_all()
255 .map_err(|source| CliError::io(&temporary, source))?;
256 }
257 std::fs::rename(&temporary, path).map_err(|source| CliError::io(path, source))
258}
259
260fn set_owner_only(path: &Path) -> Result<(), CliError> {
262 rustix::fs::chmod(path, TOKEN_MODE).map_err(|error| {
263 CliError::io(
264 path,
265 std::io::Error::from_raw_os_error(error.raw_os_error()),
266 )
267 })
268}
269
270#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct PidFile {
273 pub pid: u32,
275 pub addr: Option<String>,
277}
278
279impl PidFile {
280 #[must_use]
282 pub const fn new(pid: u32) -> Self {
283 Self { pid, addr: None }
284 }
285
286 #[must_use]
288 pub fn listening(pid: u32, addr: impl Into<String>) -> Self {
289 Self {
290 pid,
291 addr: Some(addr.into()),
292 }
293 }
294
295 #[must_use]
302 pub fn to_text(&self) -> String {
303 match &self.addr {
304 Some(addr) => format!("{}\n{addr}\n", self.pid),
305 None => format!("{}\n", self.pid),
306 }
307 }
308
309 #[must_use]
311 pub fn parse(text: &str) -> Option<Self> {
312 let mut lines = text.lines();
313 let pid: u32 = lines.next()?.trim().parse().ok()?;
314 let addr = lines
315 .next()
316 .map(str::trim)
317 .filter(|line| !line.is_empty())
318 .map(ToOwned::to_owned);
319 Some(Self { pid, addr })
320 }
321
322 #[must_use]
330 pub fn is_alive(&self) -> bool {
331 let Ok(pid) = rustix::process::Pid::from_raw(self.pid.cast_signed()).ok_or(()) else {
332 return false;
333 };
334 matches!(rustix::process::test_kill_process(pid), Ok(()))
335 }
336}
337
338pub fn write_pidfile(path: &Path, record: &PidFile) -> Result<(), CliError> {
344 if let Some(parent) = path.parent() {
345 ensure_dir(parent)?;
346 }
347 std::fs::write(path, record.to_text()).map_err(|source| CliError::io(path, source))
348}
349
350#[must_use]
357pub fn read_pidfile(path: &Path) -> Option<PidFile> {
358 let text = std::fs::read_to_string(path).ok()?;
359 PidFile::parse(&text)
360}
361
362pub fn remove_pidfile(path: &Path) -> Result<(), CliError> {
368 match std::fs::remove_file(path) {
369 Ok(()) => Ok(()),
370 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
371 Err(source) => Err(CliError::io(path, source)),
372 }
373}
374
375#[must_use]
377pub fn build_log_dir(runtime_dir: &Path) -> PathBuf {
378 runtime_dir.join(BUILD_LOG_DIR)
379}
380
381#[cfg(test)]
382mod tests {
383 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
384
385 use super::*;
386
387 fn scratch(name: &str) -> PathBuf {
388 let dir = std::env::temp_dir().join(format!(
389 "astrs-cli-runtime-dir-{}-{name}",
390 std::process::id()
391 ));
392 let _ = std::fs::remove_dir_all(&dir);
393 std::fs::create_dir_all(&dir).unwrap();
394 dir
395 }
396
397 fn permission_flags(path: &Path) -> rustix::fs::Mode {
407 use rustix::fs::Mode;
408 let stat = rustix::fs::stat(path).unwrap();
409 Mode::from_raw_mode(stat.st_mode)
410 .intersection(Mode::RWXU.union(Mode::RWXG).union(Mode::RWXO))
411 }
412
413 #[test]
420 fn the_documented_octal_spells_the_mode_that_gets_set() {
421 assert_eq!(
422 format!("{:o}", TOKEN_MODE.bits()),
423 format!("{TOKEN_MODE_OCTAL:o}")
424 );
425 }
426
427 #[test]
428 fn an_explicit_runtime_dir_wins_over_the_environment() {
429 let explicit = PathBuf::from("/tmp/somewhere");
430 assert_eq!(runtime_dir(Some(&explicit)), explicit);
431 }
432
433 #[test]
434 fn the_default_runtime_dir_is_the_daemons_own() {
435 assert_eq!(
436 runtime_dir(None),
437 astrs_daemon::config::paths::default_runtime_dir()
438 );
439 }
440
441 #[test]
442 fn a_generated_token_round_trips_and_is_owner_only() {
443 let dir = scratch("token");
444 let (token, path) = ensure_token_file(&dir).unwrap();
445 assert_eq!(path, dir.join(TOKEN_FILE));
446 assert_eq!(token.reveal_hex().len(), 64);
447
448 let found = find_token(None, None, &dir).unwrap().unwrap();
449 assert_eq!(found.0, token);
450 assert_eq!(found.1, TokenSource::File(path.clone()));
451
452 assert_eq!(permission_flags(&path), TOKEN_MODE);
453 }
454
455 #[test]
456 fn write_token_file_persists_the_exact_value_given() {
457 let dir = scratch("token-write-exact");
458 let path = dir.join("read.token");
459 let token = AuthToken::from_bytes([0x5A; 32]);
460
461 write_token_file(&path, &token).unwrap();
462
463 let (found, source) = find_token(None, Some(&path), &dir).unwrap().unwrap();
464 assert_eq!(found, token);
465 assert_eq!(source, TokenSource::File(path.clone()));
466 assert_eq!(permission_flags(&path), TOKEN_MODE);
467 }
468
469 #[test]
470 fn write_token_file_creates_a_missing_parent_directory() {
471 let dir = scratch("token-write-nested");
472 let path = dir.join("nested").join("deeper").join("read.token");
473 let token = AuthToken::from_bytes([0x5B; 32]);
474
475 write_token_file(&path, &token).unwrap();
476
477 let (found, _) = find_token(None, Some(&path), &dir).unwrap().unwrap();
478 assert_eq!(found, token);
479 }
480
481 #[test]
482 fn a_second_up_reuses_the_token_already_on_disk() {
483 let dir = scratch("token-reuse");
484 let (first, _) = ensure_token_file(&dir).unwrap();
485 let (second, _) = ensure_token_file(&dir).unwrap();
486 assert_eq!(
487 first, second,
488 "regenerating would lock out every process holding the old one"
489 );
490 }
491
492 #[test]
493 fn a_corrupt_token_file_is_refused_rather_than_replaced() {
494 let dir = scratch("token-corrupt");
495 std::fs::write(token_path(&dir), "not a token").unwrap();
496 let error = ensure_token_file(&dir).unwrap_err();
497 assert!(matches!(error, CliError::BadToken { .. }), "{error}");
498 }
499
500 #[test]
501 fn an_argument_beats_a_file() {
502 let dir = scratch("token-argument");
503 let (on_disk, _) = ensure_token_file(&dir).unwrap();
504 let other = AuthToken::from_bytes([9; 32]);
505 let found = find_token(Some(&other.reveal_hex()), None, &dir)
506 .unwrap()
507 .unwrap();
508 assert_eq!(found.0, other);
509 assert_ne!(found.0, on_disk);
510 assert_eq!(found.1, TokenSource::Argument);
511 }
512
513 #[test]
514 fn a_missing_conventional_token_is_not_an_error() {
515 let dir = scratch("token-absent");
516 assert!(find_token(None, None, &dir).unwrap().is_none());
517 }
518
519 #[test]
520 fn a_missing_explicit_token_file_is_an_error() {
521 let dir = scratch("token-explicit-absent");
522 let path = dir.join("nowhere.token");
523 let error = find_token(None, Some(&path), &dir).unwrap_err();
524 assert!(matches!(error, CliError::Io { .. }), "{error}");
525 }
526
527 #[test]
528 fn a_bad_argument_token_names_the_argument() {
529 let dir = scratch("token-bad-argument");
530 let error = find_token(Some("zz"), None, &dir).unwrap_err();
531 match error {
532 CliError::BadToken { path, .. } => assert_eq!(path, "--token"),
533 other => panic!("expected BadToken, got {other}"),
534 }
535 }
536
537 #[test]
538 fn a_pidfile_round_trips_through_its_text_form() {
539 let record = PidFile::listening(4242, "127.0.0.1:7407");
540 let parsed = PidFile::parse(&record.to_text()).unwrap();
541 assert_eq!(parsed, record);
542
543 let bare = PidFile::new(7);
544 assert_eq!(PidFile::parse(&bare.to_text()).unwrap(), bare);
545 }
546
547 #[test]
548 fn a_malformed_pidfile_reads_as_nothing_running() {
549 let dir = scratch("pidfile-malformed");
550 let path = dir.join(COORDINATOR_PIDFILE);
551 std::fs::write(&path, "\u{0}not a pid").unwrap();
552 assert!(read_pidfile(&path).is_none());
553 }
554
555 #[test]
556 fn writing_then_removing_a_pidfile_leaves_nothing_behind() {
557 let dir = scratch("pidfile-lifecycle");
558 let path = dir.join(DAEMON_PIDFILE);
559 write_pidfile(&path, &PidFile::listening(std::process::id(), "uds")).unwrap();
560 let read = read_pidfile(&path).unwrap();
561 assert_eq!(read.pid, std::process::id());
562 assert!(read.is_alive(), "this very process is alive");
563
564 remove_pidfile(&path).unwrap();
565 assert!(read_pidfile(&path).is_none());
566 remove_pidfile(&path).expect("removing a gone pidfile is not an error");
567 }
568
569 #[test]
570 fn a_pid_that_cannot_exist_is_not_alive() {
571 assert!(!PidFile::new(0).is_alive());
575 }
576
577 #[test]
578 fn the_build_log_directory_hangs_off_the_runtime_directory() {
579 let dir = PathBuf::from("/run/astrs");
580 assert_eq!(build_log_dir(&dir), dir.join(BUILD_LOG_DIR));
581 }
582}