stratum_node_cli/token.rs
1//! The node's single-use bootstrap token, read from the file the node wrote.
2
3use std::fmt;
4use std::path::Path;
5
6use zeroize::Zeroizing;
7
8use crate::private_file::{self, ModePolicy, PrivateFileError};
9
10/// The number of lowercase hex digits in a bootstrap token.
11const TOKEN_HEX_LEN: usize = 64;
12
13/// The largest token file read: the token, a newline and some slack.
14const TOKEN_FILE_LIMIT: usize = 256;
15
16/// The bootstrap token: 64 lowercase hex digits proving entitlement to claim
17/// a node.
18///
19/// The node writes it to `<state_dir>/bootstrap-token` at first boot and never
20/// serves it over HTTP; whoever can read that file is the owner. The value
21/// is held in zeroising memory, has a redacting `Debug`, and is neither
22/// `Clone`, `Display` nor `Serialize`. Reading a token also registers it
23/// for redaction: for the rest of the process, everything written through
24/// [`Output`](crate::Output) has the token (in either letter case, and its
25/// base64 forms) replaced by `<redacted>`, including text a node sends back.
26///
27/// # Examples
28///
29/// ```
30/// use stratum_node_cli::BootstrapToken;
31///
32/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
33/// let dir = std::env::temp_dir().join(format!("stratum-token-doc-{}", std::process::id()));
34/// std::fs::create_dir_all(&dir)?;
35/// let path = dir.join("bootstrap-token");
36/// std::fs::write(&path, format!("{}\n", "ab".repeat(32)))?;
37/// let token = BootstrapToken::read_file(&path)?;
38/// assert!(!format!("{token:?}").contains("abab"));
39/// # std::fs::remove_file(&path)?;
40/// # Ok(())
41/// # }
42/// ```
43pub struct BootstrapToken(Zeroizing<String>);
44
45impl BootstrapToken {
46 /// Reads the token from the node's token file.
47 ///
48 /// The file must be a regular file (not a symbolic link) holding 64
49 /// lowercase hex digits, optionally followed by a newline. Its mode is
50 /// not checked: the file belongs to the node, and reading it at all is
51 /// the proof of entitlement.
52 ///
53 /// # Errors
54 ///
55 /// Returns [`TokenFileError::File`] when the file cannot be read safely
56 /// and [`TokenFileError::Malformed`] when it does not hold a token. No
57 /// error carries any part of the file.
58 pub fn read_file(path: &Path) -> Result<Self, TokenFileError> {
59 let contents = private_file::read(path, TOKEN_FILE_LIMIT, ModePolicy::Any)
60 .map_err(TokenFileError::File)?;
61 let text = std::str::from_utf8(&contents).map_err(|_| TokenFileError::Malformed)?;
62 let line = text.strip_suffix('\n').unwrap_or(text);
63 Self::parse(line).ok_or(TokenFileError::Malformed)
64 }
65
66 /// Accepts exactly 64 lowercase hex digits.
67 pub(crate) fn parse(text: &str) -> Option<Self> {
68 let valid = text.len() == TOKEN_HEX_LEN
69 && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
70 if !valid {
71 return None;
72 }
73 // From here on, nothing this process writes can show the token.
74 crate::redact::register_hex_secret(text);
75 Some(Self(Zeroizing::new(text.to_owned())))
76 }
77
78 /// Returns the token text, for the request header and the resume file.
79 pub(crate) fn expose(&self) -> &str {
80 &self.0
81 }
82}
83
84impl fmt::Debug for BootstrapToken {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 f.write_str("BootstrapToken(<redacted>)")
87 }
88}
89
90/// Why the bootstrap token file could not be read.
91///
92/// No variant carries any part of the token.
93#[derive(Debug, thiserror::Error)]
94#[non_exhaustive]
95pub enum TokenFileError {
96 /// The file could not be opened or read safely.
97 #[error(transparent)]
98 File(PrivateFileError),
99 /// The file does not hold 64 lowercase hex digits and a newline.
100 #[error("token file does not hold a bootstrap token (64 lowercase hex digits)")]
101 Malformed,
102}