Skip to main content

astrs_cli/
runtime_dir.rs

1//! The on-disk state `astrs up` creates and `astrs down`/`astrs status`
2//! read: the runtime directory, the cluster token file, and one pidfile
3//! per background process (blueprint §16, §24.2).
4//!
5//! ```text
6//!   <working dir>/.astrs-token          64 hex, mode 0600      §16
7//!   <runtime dir>/coordinator.pid       "<pid>\n<addr>\n"      §24.2
8//!   <runtime dir>/daemon.pid            "<pid>\n<addr>\n"      §24.2
9//!   <runtime dir>/daemon.sock           the node listener      §4.2
10//!   <runtime dir>/build/<node>.log      `astrs build` capture  §17
11//! ```
12//!
13//! # Why the token is not in the runtime directory
14//!
15//! Blueprint §16 is specific: *"64-hex cluster token
16//! (`<working_dir>/.astrs-token`, 0600), generated by `astrs up`"*. The
17//! runtime directory (§24.2) is per-*machine* and shared by every cluster
18//! a user runs on it; the token is per-*cluster*. Putting it beside the
19//! manifest is what lets a second cluster in a second directory have a
20//! second token without either clobbering the other, and it is what makes
21//! "check the token into your deployment directory, not your home" the
22//! natural thing to do. Pidfiles go the other way for the same reason:
23//! they describe *this machine's* processes, so they live in the runtime
24//! directory and survive a user changing directories.
25//!
26//! # Everything here is inspectable without a cluster
27//!
28//! Each function takes explicit paths rather than reading the environment
29//! for itself, so a test drives the whole lifecycle inside
30//! [`std::env::temp_dir`] with no ambient state at all — see this module's
31//! own tests.
32
33use std::io::Write as _;
34use std::path::{Path, PathBuf};
35
36use astrs_wire::AuthToken;
37
38use crate::error::CliError;
39
40/// The file name blueprint §16 gives the cluster token.
41pub const TOKEN_FILE: &str = ".astrs-token";
42
43/// The environment variable that supplies a token when no file does.
44pub const ENV_TOKEN: &str = "ASTRS_TOKEN";
45
46/// The environment variable naming the coordinator's address.
47pub const ENV_COORDINATOR_ADDR: &str = "ASTRS_COORDINATOR_ADDR";
48
49/// The coordinator's pidfile, inside the runtime directory.
50pub const COORDINATOR_PIDFILE: &str = "coordinator.pid";
51
52/// The daemon's pidfile, inside the runtime directory.
53pub const DAEMON_PIDFILE: &str = "daemon.pid";
54
55/// The subdirectory `astrs build` captures per-node build logs into.
56pub const BUILD_LOG_DIR: &str = "build";
57
58/// The mode blueprint §16 requires on the token file: owner read/write,
59/// nothing for anybody else.
60///
61/// Spelled as [`rustix::fs::Mode`] flags rather than an octal literal
62/// because `mode_t` is `u16` on some targets and `u32` on others; the
63/// flags carry their own width.
64const TOKEN_MODE: rustix::fs::Mode = rustix::fs::Mode::RUSR.union(rustix::fs::Mode::WUSR);
65
66/// The token file's mode as the octal a human reads in `ls -l`, for tests
67/// and messages — the same bits the private `TOKEN_MODE` flags spell.
68pub const TOKEN_MODE_OCTAL: u32 = 0o600;
69
70/// The runtime directory to use, honoring an explicit override first.
71///
72/// Falls back to `astrs-daemon`'s own resolution — `ASTRS_RUNTIME_DIR`,
73/// then `$XDG_RUNTIME_DIR/astrs`, then a per-uid temp directory (§24.2) —
74/// so the CLI, the daemon it spawns and the daemon it embeds all agree on
75/// one answer without the CLI re-deriving it.
76#[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/// The working directory a `.astrs-token` is looked up in.
85///
86/// The process's current directory when no override is given; a failure to
87/// read it (a deleted cwd) degrades to `.` rather than aborting a verb
88/// that may not need the token at all.
89#[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
97/// Creates `dir` if it does not exist.
98///
99/// # Errors
100///
101/// [`CliError::Io`] if the directory cannot be created.
102pub fn ensure_dir(dir: &Path) -> Result<(), CliError> {
103    std::fs::create_dir_all(dir).map_err(|source| CliError::io(dir, source))
104}
105
106/// The conventional token path for a working directory (§16).
107#[must_use]
108pub fn token_path(working_dir: &Path) -> PathBuf {
109    working_dir.join(TOKEN_FILE)
110}
111
112/// Where a token came from, so an error can name it.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum TokenSource {
115    /// A `--token` argument.
116    Argument,
117    /// The [`ENV_TOKEN`] environment variable.
118    Environment,
119    /// A file on disk.
120    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
133/// Finds the cluster token, in the order a user expects: the explicit
134/// argument, then an explicit file, then [`ENV_TOKEN`], then
135/// `<working_dir>/.astrs-token`.
136///
137/// Returns `Ok(None)` when nothing supplied one — a caller that can work
138/// without authentication (probing a token-less development coordinator)
139/// treats that as [`AuthToken::ZERO`], and one that cannot raises
140/// [`CliError::NoToken`] itself, naming what it wanted.
141///
142/// # Errors
143///
144/// - [`CliError::Io`] if an explicitly named token file cannot be read.
145/// - [`CliError::BadToken`] if what was found is not 64 hex digits.
146pub 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        // An explicitly named file that is missing is an error, unlike the
156        // conventional one below: the user said where to look.
157        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
173/// Parses one 64-hex token, trimming the trailing newline a file has.
174fn 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
183/// Writes a freshly generated token to `<working_dir>/.astrs-token` at mode
184/// `0600`, returning it and the path (§16).
185///
186/// Reuses the file that is already there when it holds a valid token, so a
187/// second `astrs up` in the same directory keeps the token every daemon and
188/// CLI on the machine has already been told.
189///
190/// # Errors
191///
192/// - [`CliError::Io`] if the file cannot be written or its mode set.
193/// - [`CliError::BadToken`] if an existing file holds something unusable —
194///   deliberately *not* overwritten, because silently replacing a token
195///   would lock out every process still holding the old one.
196pub 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        // The mode is re-applied even for an existing file: a token that
201        // became world-readable (a careless `cp`, a permissive umask on an
202        // earlier release) is exactly what §16 exists to prevent.
203        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
215/// Writes `token` to `path` at mode `0600` — the same private-write dance
216/// [`ensure_token_file`] uses for the root token, exposed for callers that
217/// already have a specific value to persist rather than one to generate or
218/// reuse.
219///
220/// `astrs token mint --out` is the reason this exists: minting a read-scope
221/// credential ([`astrs_coordinator::auth::derive_read_token`]) produces an
222/// exact value the caller wants written down, which is a different contract
223/// from [`ensure_token_file`]'s "generate a fresh one, or keep whatever is
224/// already there" (§16) — reusing that function here would either silently
225/// ignore the derived value or overwrite a root token a running coordinator
226/// still depends on.
227///
228/// # Errors
229///
230/// [`CliError::Io`] if the directory cannot be created, or the file cannot
231/// be written or its mode set.
232pub 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
241/// Writes `bytes` to `path`, owner-only from the moment it exists.
242///
243/// The mode is applied to the temporary name *before* the rename, so the
244/// token is never visible to another user even for the instant between
245/// `create` and `set_permissions`.
246fn 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
260/// Applies mode `0600` to an existing file (§16).
261fn 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/// What a pidfile records: the process, and where it listens.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct PidFile {
273    /// The process id.
274    pub pid: u32,
275    /// The address it bound, when it announced one.
276    pub addr: Option<String>,
277}
278
279impl PidFile {
280    /// A record for a process that has not announced an address.
281    #[must_use]
282    pub const fn new(pid: u32) -> Self {
283        Self { pid, addr: None }
284    }
285
286    /// A record for a process listening on `addr`.
287    #[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    /// The two-line text form: the pid, then the address (when known).
296    ///
297    /// Deliberately not JSON: `cat coordinator.pid` and `kill $(head -1 …)`
298    /// are things operators do, and a pidfile that needs a parser to read
299    /// is a pidfile that stops being useful the moment the CLI is what is
300    /// broken.
301    #[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    /// Parses the text form, ignoring anything past the second line.
310    #[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    /// Whether the recorded process is still alive.
323    ///
324    /// A `kill(pid, 0)` probe: it answers "is there a process with this id
325    /// that I could signal", which is exactly the question `astrs status`
326    /// and `astrs down` ask. It cannot tell a recycled pid apart from the
327    /// original, which is why [`crate::command::cluster`] confirms a
328    /// *coordinator* by greeting it rather than by this alone.
329    #[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
338/// Writes a pidfile, creating its directory if needed.
339///
340/// # Errors
341///
342/// [`CliError::Io`] if the directory or the file cannot be written.
343pub 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/// Reads a pidfile, treating a missing or malformed one as "no process".
351///
352/// A malformed pidfile is *not* an error: a truncated write from a machine
353/// that lost power should read as "nothing is running", which is the truth,
354/// rather than as a failure that stops `astrs status` from reporting on the
355/// other half of the cluster.
356#[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
362/// Deletes a pidfile, succeeding when it is already gone.
363///
364/// # Errors
365///
366/// [`CliError::Io`] for any failure other than "not found".
367pub 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/// The directory `astrs build` writes per-node logs into.
376#[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    /// A file's `rwx` bits, as [`rustix::fs::Mode`] flags.
398    ///
399    /// Compared as flags rather than as an octal number for the reason
400    /// [`TOKEN_MODE`] is spelled as flags in the first place: `mode_t` is
401    /// `u16` on some targets and `u32` on others, so any octal comparison
402    /// needs a width conversion that is load-bearing on one half of the
403    /// platforms and a no-op on the other. The mask drops the setuid,
404    /// setgid and sticky bits `from_raw_mode` also carries, which
405    /// [`TOKEN_MODE`] does not claim anything about.
406    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    /// [`TOKEN_MODE_OCTAL`] documents itself as "the same bits the private
414    /// `TOKEN_MODE` flags spell", and the two are declared apart — so
415    /// nothing but this pins them together. Compared as octal *text*
416    /// rather than as numbers on purpose: `bits()` is `mode_t`, whose width
417    /// differs by target, and that is the whole reason the two spellings
418    /// exist.
419    #[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        // Pid 0 addresses "every process in my group" to `kill(2)`, so it is
572        // never a live *process*; `Pid::from_raw` rejects it outright, which
573        // is the path this asserts.
574        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}