astrs_cli/command/
token.rs1use 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#[derive(Debug, Clone)]
29pub struct MintArgs {
30 pub scope: TokenScopeArg,
32 pub token: Option<String>,
34 pub token_file: Option<PathBuf>,
36 pub working_dir: Option<PathBuf>,
39 pub out: Option<PathBuf>,
42 pub json: bool,
44}
45
46pub 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
80const fn scope_name(scope: TokenScopeArg) -> &'static str {
84 match scope {
85 TokenScopeArg::Read => "read",
86 TokenScopeArg::Mutate => "mutate",
87 }
88}
89
90fn 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
121fn 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}