Skip to main content

astrs_cli/command/
token.rs

1//! `astrs token mint` (blueprint §16, §22).
2//!
3//! ```text
4//!   astrs token mint --scope mutate   -> the root token itself (back-compat)
5//!   astrs token mint --scope read     -> the HKDF-derived read-scope token
6//! ```
7//!
8//! Purely local: unlike every other verb in `command/`, minting never dials
9//! a coordinator — it only needs the root secret already on this machine
10//! (resolved exactly like every coordinator-facing verb resolves one, via
11//! [`crate::runtime_dir::find_token`]), and the scope derivation is a pure
12//! function of it ([`astrs_coordinator::auth::derive_read_token`]). A
13//! coordinator configured from the same root token always reaches the
14//! identical 32 bytes (see that function's own docs), so minting needs
15//! neither a network round trip nor a coordinator restart — the credential
16//! it prints is already the one a running coordinator will recognise.
17
18use std::io::Write;
19use std::path::PathBuf;
20
21use astrs_wire::AuthToken;
22
23use crate::cli::TokenScopeArg;
24use crate::error::CliError;
25use crate::runtime_dir;
26
27/// `astrs token mint` arguments, independent of `clap`.
28#[derive(Debug, Clone)]
29pub struct MintArgs {
30    /// The scope to mint a credential for.
31    pub scope: TokenScopeArg,
32    /// An explicit root token, instead of resolving one.
33    pub token: Option<String>,
34    /// A file holding the root token.
35    pub token_file: Option<PathBuf>,
36    /// Where `.astrs-token` is looked up when neither of the above is
37    /// given.
38    pub working_dir: Option<PathBuf>,
39    /// Write the minted credential to this file (mode `0600`) instead of
40    /// printing it to stdout.
41    pub out: Option<PathBuf>,
42    /// Emit JSON rather than a bare hex line.
43    pub json: bool,
44}
45
46/// Mints (derives, or reveals) the credential for one scope from the
47/// cluster's root token.
48///
49/// # Errors
50///
51/// - [`CliError::NoToken`] if no root token can be found by any of the
52///   usual means (§16).
53/// - [`CliError::BadToken`] if what was found is not a 64-hex value.
54/// - [`CliError::Io`] if `--out` cannot be written.
55pub fn mint(out: &mut dyn Write, args: &MintArgs) -> Result<(), CliError> {
56    let working_dir = runtime_dir::working_dir(args.working_dir.as_deref());
57    let (root, source) = runtime_dir::find_token(
58        args.token.as_deref(),
59        args.token_file.as_deref(),
60        &working_dir,
61    )?
62    .ok_or(CliError::NoToken {
63        env: runtime_dir::ENV_TOKEN,
64        file: runtime_dir::TOKEN_FILE,
65    })?;
66
67    let minted = match args.scope {
68        TokenScopeArg::Mutate => root,
69        TokenScopeArg::Read => astrs_coordinator::auth::derive_read_token(&root),
70    };
71
72    if let Some(path) = &args.out {
73        runtime_dir::write_token_file(path, &minted)?;
74    }
75
76    report(out, args, &minted, &source);
77    Ok(())
78}
79
80/// A stable, lower-case scope name for output — mirrors
81/// [`astrs_wire::RequestScope::as_str`], which `TokenScopeArg` sits below in
82/// the layer stack and so cannot borrow directly.
83const fn scope_name(scope: TokenScopeArg) -> &'static str {
84    match scope {
85        TokenScopeArg::Read => "read",
86        TokenScopeArg::Mutate => "mutate",
87    }
88}
89
90/// Writes the result, in whichever form `args` asked for.
91fn report(
92    out: &mut dyn Write,
93    args: &MintArgs,
94    minted: &AuthToken,
95    source: &runtime_dir::TokenSource,
96) {
97    if args.json {
98        emit_json(
99            out,
100            &serde_json::json!({
101                "scope": scope_name(args.scope),
102                "token": minted.reveal_hex(),
103                "root_source": source.to_string(),
104                "written_to": args.out.as_ref().map(|p| p.display().to_string()),
105            }),
106        );
107    } else if let Some(path) = &args.out {
108        let _ = writeln!(
109            out,
110            "{} token written to {}",
111            scope_name(args.scope),
112            path.display()
113        );
114        let _ = out.flush();
115    } else {
116        let _ = writeln!(out, "{}", minted.reveal_hex());
117        let _ = out.flush();
118    }
119}
120
121/// Writes one JSON object.
122///
123/// Duplicated from `command::record`'s own copy rather than shared — see
124/// that module's docs on this crate's small-per-module-helper convention.
125fn emit_json(out: &mut dyn Write, value: &serde_json::Value) {
126    let _ = writeln!(
127        out,
128        "{}",
129        serde_json::to_string_pretty(value).unwrap_or_else(|_| "{}".to_owned())
130    );
131    let _ = out.flush();
132}
133
134#[cfg(test)]
135mod tests {
136    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
137
138    use super::*;
139
140    fn scratch(name: &str) -> PathBuf {
141        let dir = std::env::temp_dir().join(format!(
142            "astrs-cli-token-mint-{}-{name}",
143            std::process::id()
144        ));
145        let _ = std::fs::remove_dir_all(&dir);
146        std::fs::create_dir_all(&dir).unwrap();
147        dir
148    }
149
150    fn args(scope: TokenScopeArg, working_dir: &std::path::Path) -> MintArgs {
151        MintArgs {
152            scope,
153            token: None,
154            token_file: None,
155            working_dir: Some(working_dir.to_path_buf()),
156            out: None,
157            json: false,
158        }
159    }
160
161    #[test]
162    fn minting_mutate_reveals_the_root_token_unchanged() {
163        let dir = scratch("mutate");
164        let (root, _) = runtime_dir::ensure_token_file(&dir).unwrap();
165
166        let mut sink = Vec::new();
167        mint(&mut sink, &args(TokenScopeArg::Mutate, &dir)).unwrap();
168        let printed = String::from_utf8(sink).unwrap();
169        assert_eq!(printed.trim(), root.reveal_hex());
170    }
171
172    #[test]
173    fn minting_read_derives_a_different_value_than_the_root() {
174        let dir = scratch("read");
175        let (root, _) = runtime_dir::ensure_token_file(&dir).unwrap();
176
177        let mut sink = Vec::new();
178        mint(&mut sink, &args(TokenScopeArg::Read, &dir)).unwrap();
179        let printed = String::from_utf8(sink).unwrap().trim().to_owned();
180
181        assert_ne!(printed, root.reveal_hex());
182        assert_eq!(
183            printed,
184            astrs_coordinator::auth::derive_read_token(&root).reveal_hex(),
185            "the CLI and the coordinator must derive the identical value"
186        );
187    }
188
189    #[test]
190    fn minting_without_a_root_token_is_a_clear_error() {
191        let dir = scratch("no-root");
192        let error = mint(&mut Vec::new(), &args(TokenScopeArg::Read, &dir)).unwrap_err();
193        assert!(matches!(error, CliError::NoToken { .. }), "{error}");
194    }
195
196    #[test]
197    fn out_writes_the_minted_token_to_a_private_file() {
198        let dir = scratch("out-file");
199        let (root, _) = runtime_dir::ensure_token_file(&dir).unwrap();
200        let out_path = dir.join("read.token");
201
202        let mut a = args(TokenScopeArg::Read, &dir);
203        a.out = Some(out_path.clone());
204        mint(&mut Vec::new(), &a).unwrap();
205
206        let (found, _) = runtime_dir::find_token(None, Some(&out_path), &dir)
207            .unwrap()
208            .unwrap();
209        assert_eq!(found, astrs_coordinator::auth::derive_read_token(&root));
210    }
211
212    #[test]
213    fn json_output_names_the_scope_and_token() {
214        let dir = scratch("json");
215        runtime_dir::ensure_token_file(&dir).unwrap();
216
217        let mut a = args(TokenScopeArg::Read, &dir);
218        a.json = true;
219        let mut sink = Vec::new();
220        mint(&mut sink, &a).unwrap();
221
222        let value: serde_json::Value = serde_json::from_slice(&sink).unwrap();
223        assert_eq!(value["scope"], "read");
224        assert_eq!(value["token"].as_str().unwrap().len(), 64);
225    }
226}