didbot_cli/lib.rs
1//! What every didbot command shares, so that verbs shipped as separate
2//! binaries read as one tool.
3//!
4//! `didbot <verb> …` is a dispatcher: it finds `didbot-<binary>` on `PATH`
5//! and hands it the rest of the command line. Each binary parses for itself,
6//! and this crate is how they all parse the same way: [`parse`] over the
7//! workspace's one `clap`, [`Server`] and [`Json`] for the two flags every
8//! verb takes, [`Exit`] for the three statuses a script can rely on, and
9//! [`finish`] for the one line an error is written as.
10//!
11//! [`FirstPartyVerb`] is the row type of the table the dispatcher carries.
12//! It lives here rather than in the dispatcher so a verb crate's tests can
13//! read the same type the dispatcher does.
14
15#![forbid(unsafe_code)]
16
17use std::fmt;
18use std::process::ExitCode;
19
20use clap::Args;
21use serde::Serialize;
22
23#[cfg(feature = "reference")]
24pub mod reference;
25
26/// The environment variables a didbot command reads a credential from.
27///
28/// The dispatcher removes every one of these before handing off to a verb,
29/// so nothing reached through `didbot <verb>` inherits a credential the
30/// caller's shell happened to hold. A verb authenticates for itself.
31pub mod env {
32 /// An agent account's own token, for a host with no daemon.
33 pub const ACCOUNT_TOKEN: &str = "DIDBOT_ACCOUNT_TOKEN";
34 /// A file holding [`ACCOUNT_TOKEN`]'s value.
35 pub const ACCOUNT_TOKEN_FILE: &str = "DIDBOT_ACCOUNT_TOKEN_FILE";
36 /// Every variable the dispatcher scrubs.
37 pub const CREDENTIALS: &[&str] = &[ACCOUNT_TOKEN, ACCOUNT_TOKEN_FILE];
38 /// The server's origin, such as `https://pds.example`, for a command
39 /// that names its server through the environment rather than
40 /// `--server`. Not a credential, so the dispatcher passes it through.
41 pub const PDS: &str = "DIDBOT_PDS";
42 /// The directory a host keeps its keys and account tokens in. A host
43 /// that leaves it unset gets a default under `$XDG_STATE_HOME`.
44 pub const STATE: &str = "DIDBOT_STATE";
45
46 /// The origin a server is reached at, from either spelling a person
47 /// uses: a URL as given, and `https://` before a hostname. Every server
48 /// this project runs terminates TLS, on a developer's machine as much
49 /// as anywhere else, so there is one scheme. `--server` and [`PDS`]
50 /// read the same way everywhere.
51 ///
52 /// A hostname with no port means 443, unless
53 /// [`didbot_identity::did::RESOLVE_PORTS`] says that zone answers
54 /// somewhere else — which is how several local servers run at once on
55 /// one machine.
56 #[must_use]
57 pub fn server_origin(server: &str) -> String {
58 let server = server.trim().trim_end_matches('/');
59 if server.contains("://") {
60 return server.to_owned();
61 }
62 if server != didbot_identity::did::host_without_port(server) {
63 return format!("https://{server}");
64 }
65 match didbot_identity::did::resolve_port(server) {
66 Some(port) => format!("https://{server}:{port}"),
67 None => format!("https://{server}"),
68 }
69 }
70
71 #[cfg(test)]
72 mod tests {
73 use super::server_origin;
74
75 /// A hostname, a loopback hostname with a port, and a URL each
76 /// reach the same server whichever a person typed.
77 #[test]
78 fn a_server_is_named_by_hostname_or_by_url() {
79 assert_eq!(server_origin("pds.example"), "https://pds.example");
80 assert_eq!(
81 server_origin("nc.localhost:3413"),
82 "https://nc.localhost:3413"
83 );
84 assert_eq!(
85 server_origin("https://nc.localhost:3413/"),
86 "https://nc.localhost:3413"
87 );
88 assert_eq!(server_origin("https://pds.example"), "https://pds.example");
89 }
90 }
91}
92
93/// Where an account token lands on the machine that will be the account.
94///
95/// `didbot register` and `didbot operate` both end with a session for the
96/// account they created, and `didbot-oauth` reads one back through
97/// [`env::ACCOUNT_TOKEN_FILE`]. One file per account, holding the token and
98/// nothing else, so the path is the whole hand-off.
99///
100/// Behind the `tokens` feature, which the crates that store one turn on.
101/// The `didbot` dispatcher links this crate for the flag grammar and the
102/// verb table, and a router that can reach a credential writer is a reach
103/// nothing asks it for.
104#[cfg(feature = "tokens")]
105pub mod tokens {
106 use std::io;
107 use std::path::{Path, PathBuf};
108
109 /// The directory under the state base that a host's daemon owns.
110 pub const SERVICE: &str = "agentd";
111
112 /// The state directory: [`super::env::STATE`] when set, else
113 /// `$XDG_STATE_HOME/didbot/agentd`, else `~/.local/state/didbot/agentd`,
114 /// and the current directory for a process with none of them.
115 #[must_use]
116 pub fn state_dir() -> PathBuf {
117 std::env::var_os(super::env::STATE)
118 .map(PathBuf::from)
119 .filter(|path| !path.as_os_str().is_empty())
120 .unwrap_or_else(default_state_dir)
121 }
122
123 /// The state directory a process with no [`super::env::STATE`] uses.
124 #[must_use]
125 pub fn default_state_dir() -> PathBuf {
126 std::env::var_os("XDG_STATE_HOME")
127 .map(PathBuf::from)
128 .filter(|path| !path.as_os_str().is_empty())
129 .or_else(|| {
130 std::env::var_os("HOME")
131 .map(PathBuf::from)
132 .filter(|path| !path.as_os_str().is_empty())
133 .map(|home| home.join(".local/state"))
134 })
135 .unwrap_or_else(|| PathBuf::from("."))
136 .join("didbot")
137 .join(SERVICE)
138 }
139
140 /// The file the token for the account named `name` is kept in, under
141 /// `state`.
142 #[must_use]
143 pub fn account_token_file(state: &Path, name: &str) -> PathBuf {
144 state.join("accounts").join(format!("{name}.token"))
145 }
146
147 /// The one line a command prints about a stored token: how to hand it
148 /// to `didbot-oauth`.
149 #[must_use]
150 pub fn hand_off(path: &Path) -> String {
151 format!(
152 "for didbot-oauth: export {}={}",
153 super::env::ACCOUNT_TOKEN_FILE,
154 path.display()
155 )
156 }
157
158 /// Writes `token` for `name` under `state`, readable by this user alone,
159 /// and returns the file's path.
160 pub fn store_account_token(state: &Path, name: &str, token: &str) -> io::Result<PathBuf> {
161 let path = account_token_file(state, name);
162 let dir = path.parent().expect("the token file has a directory");
163 std::fs::create_dir_all(dir)?;
164 #[cfg(unix)]
165 {
166 use std::os::unix::fs::PermissionsExt;
167 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
168 }
169 let mut body = token.to_owned();
170 body.push('\n');
171 std::fs::write(&path, body)?;
172 #[cfg(unix)]
173 {
174 use std::os::unix::fs::PermissionsExt;
175 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
176 }
177 Ok(path)
178 }
179
180 #[cfg(test)]
181 mod tests {
182 use super::*;
183
184 /// The file is what `DIDBOT_ACCOUNT_TOKEN_FILE` reads: the token, a
185 /// newline, nothing else, and nobody else's to read.
186 #[cfg(unix)]
187 #[test]
188 fn a_stored_token_is_the_file_didbot_oauth_reads() {
189 use std::os::unix::fs::PermissionsExt;
190 let state =
191 std::env::temp_dir().join(format!("didbot-cli-tokens-{}", std::process::id()));
192 let _ = std::fs::remove_dir_all(&state);
193
194 let path = store_account_token(&state, "kestrel.pds.example", "tok-1").unwrap();
195
196 assert_eq!(path, state.join("accounts/kestrel.pds.example.token"));
197 assert_eq!(std::fs::read_to_string(&path).unwrap(), "tok-1\n");
198 let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
199 assert_eq!(mode(&path), 0o600);
200 assert_eq!(mode(path.parent().unwrap()), 0o700);
201 std::fs::remove_dir_all(&state).ok();
202 }
203 }
204}
205
206/// `<binary> <version>`, as the binary this expands in answers `--version`.
207///
208/// A macro rather than a function because the version has to be the
209/// calling crate's: `didbot --list` shows one line per installed binary, and
210/// a line that reported this library's version would hide the skew it
211/// exists to show.
212#[macro_export]
213macro_rules! version {
214 () => {
215 concat!(env!("CARGO_BIN_NAME"), " ", env!("CARGO_PKG_VERSION"))
216 };
217}
218
219/// How a didbot command exits.
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221#[repr(u8)]
222pub enum Exit {
223 /// Did what was asked.
224 Ok = 0,
225 /// Understood the request and could not, or would not, do it.
226 Failed = 1,
227 /// Did not understand the request.
228 Usage = 2,
229}
230
231impl From<Exit> for ExitCode {
232 fn from(exit: Exit) -> Self {
233 ExitCode::from(exit as u8)
234 }
235}
236
237/// Why a command stopped, and how it exits.
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct Refusal {
240 /// The status to exit with.
241 pub exit: Exit,
242 /// One line for the person, without the program name.
243 pub message: String,
244}
245
246impl Refusal {
247 /// A request this command understood and did not carry out.
248 pub fn failed(message: impl fmt::Display) -> Self {
249 Self {
250 exit: Exit::Failed,
251 message: message.to_string(),
252 }
253 }
254
255 /// A request this command did not understand.
256 pub fn usage(message: impl fmt::Display) -> Self {
257 Self {
258 exit: Exit::Usage,
259 message: message.to_string(),
260 }
261 }
262}
263
264impl fmt::Display for Refusal {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 f.write_str(&self.message)
267 }
268}
269
270/// Renders an outcome the way every didbot command does.
271///
272/// Success is silent here — the verb printed its answer — and a refusal is
273/// one line on stderr, `<program>: <message>`, with the exit status
274/// [`Refusal::exit`] names. `program` is the spelling the person typed, so a
275/// verb reached as `didbot login` says `didbot login:`.
276pub fn finish(program: &str, result: Result<(), Refusal>) -> ExitCode {
277 match result {
278 Ok(()) => Exit::Ok.into(),
279 Err(refusal) => {
280 eprintln!("{program}: {refusal}");
281 refusal.exit.into()
282 }
283 }
284}
285
286/// Sends `tracing` to stderr, and only what `RUST_LOG` asks for.
287///
288/// A command's status is the lines it prints itself, so by default nothing
289/// is logged at all.
290pub fn logs() {
291 tracing_subscriber::fmt()
292 .with_env_filter(
293 tracing_subscriber::EnvFilter::try_from_default_env()
294 .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("off")),
295 )
296 .with_writer(std::io::stderr)
297 .init();
298}
299
300/// Parses the command line as `T`.
301///
302/// `--help` and `--version` answer on stdout and exit 0; a command line clap
303/// cannot read is reported on stderr and exits [`Exit::Usage`]. This is
304/// clap's own behaviour, wrapped so every verb goes through one call and a
305/// change to how a usage error reads is made once.
306pub fn parse<T: clap::Parser>() -> T {
307 match T::try_parse() {
308 Ok(parsed) => parsed,
309 Err(error) => error.exit(),
310 }
311}
312
313/// `--server <HOSTNAME>`: which deployment a verb acts on.
314///
315/// Global, so it reads the same before or after the verb. Optional at parse
316/// time because not every verb needs it; [`Server::hostname`] is the check
317/// for one that does.
318#[derive(Args, Debug, Clone, Default)]
319pub struct Server {
320 /// The deployment to act on, as its own hostname
321 #[arg(long, global = true, value_name = "HOSTNAME")]
322 pub server: Option<String>,
323}
324
325impl Server {
326 /// The hostname, or the usage refusal a verb that needs one gives.
327 pub fn hostname(&self) -> Result<&str, Refusal> {
328 self.server
329 .as_deref()
330 .ok_or_else(|| Refusal::usage("--server <HOSTNAME> is required"))
331 }
332}
333
334/// `--json`: the answer as one line of JSON on stdout, for a script.
335#[derive(Args, Debug, Clone, Copy, Default)]
336pub struct Json {
337 /// Print the answer as JSON
338 #[arg(long, global = true)]
339 pub json: bool,
340}
341
342impl Json {
343 /// Prints `value` as JSON, or the text `plain` renders from it.
344 pub fn print<T: Serialize>(self, value: &T, plain: impl FnOnce(&T) -> String) {
345 if self.json {
346 println!(
347 "{}",
348 serde_json::to_string(value).expect("an answer serializes")
349 );
350 } else {
351 println!("{}", plain(value));
352 }
353 }
354}
355
356/// A verb the dispatcher knows by name, whether or not its binary is
357/// installed.
358///
359/// `didbot <verb> …` runs `<binary> <argv…> …`: the binary found on `PATH`,
360/// then [`FirstPartyVerb::argv`], then what followed the verb on the
361/// command line. A binary that is not installed is named with the crate
362/// that ships it, so the answer is "install this" rather than "unknown
363/// command".
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub struct FirstPartyVerb {
366 /// What the person types after `didbot`.
367 pub verb: &'static str,
368 /// The binary that answers it.
369 pub binary: &'static str,
370 /// The crate `cargo install` takes to get the binary.
371 pub package: &'static str,
372 /// What precedes the caller's arguments when the binary is run.
373 pub argv: &'static [&'static str],
374 /// One line for `didbot --help`.
375 pub about: &'static str,
376}
377
378impl FirstPartyVerb {
379 /// The row for `verb` in `table`, if there is one.
380 pub fn lookup<'a>(table: &'a [Self], verb: &str) -> Option<&'a Self> {
381 table.iter().find(|row| row.verb == verb)
382 }
383}