stratum-node-cli 0.1.0-alpha.4

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
//! The node's single-use bootstrap token, read from the file the node wrote.

use std::fmt;
use std::path::Path;

use zeroize::Zeroizing;

use crate::private_file::{self, ModePolicy, PrivateFileError};

/// The number of lowercase hex digits in a bootstrap token.
const TOKEN_HEX_LEN: usize = 64;

/// The largest token file read: the token, a newline and some slack.
const TOKEN_FILE_LIMIT: usize = 256;

/// The bootstrap token: 64 lowercase hex digits proving entitlement to claim
/// a node.
///
/// The node writes it to `<state_dir>/bootstrap-token` at first boot and never
/// serves it over HTTP; whoever can read that file is the owner. The value
/// is held in zeroising memory, has a redacting `Debug`, and is neither
/// `Clone`, `Display` nor `Serialize`. Reading a token also registers it
/// for redaction: for the rest of the process, everything written through
/// [`Output`](crate::Output) has the token (in either letter case, and its
/// base64 forms) replaced by `<redacted>`, including text a node sends back.
///
/// # Examples
///
/// ```
/// use stratum_node_cli::BootstrapToken;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let dir = std::env::temp_dir().join(format!("stratum-token-doc-{}", std::process::id()));
/// std::fs::create_dir_all(&dir)?;
/// let path = dir.join("bootstrap-token");
/// std::fs::write(&path, format!("{}\n", "ab".repeat(32)))?;
/// let token = BootstrapToken::read_file(&path)?;
/// assert!(!format!("{token:?}").contains("abab"));
/// # std::fs::remove_file(&path)?;
/// # Ok(())
/// # }
/// ```
pub struct BootstrapToken(Zeroizing<String>);

impl BootstrapToken {
    /// Reads the token from the node's token file.
    ///
    /// The file must be a regular file (not a symbolic link) holding 64
    /// lowercase hex digits, optionally followed by a newline. Its mode is
    /// not checked: the file belongs to the node, and reading it at all is
    /// the proof of entitlement.
    ///
    /// # Errors
    ///
    /// Returns [`TokenFileError::File`] when the file cannot be read safely
    /// and [`TokenFileError::Malformed`] when it does not hold a token. No
    /// error carries any part of the file.
    pub fn read_file(path: &Path) -> Result<Self, TokenFileError> {
        let contents = private_file::read(path, TOKEN_FILE_LIMIT, ModePolicy::Any)
            .map_err(TokenFileError::File)?;
        let text = std::str::from_utf8(&contents).map_err(|_| TokenFileError::Malformed)?;
        let line = text.strip_suffix('\n').unwrap_or(text);
        Self::parse(line).ok_or(TokenFileError::Malformed)
    }

    /// Accepts exactly 64 lowercase hex digits.
    pub(crate) fn parse(text: &str) -> Option<Self> {
        let valid = text.len() == TOKEN_HEX_LEN
            && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
        if !valid {
            return None;
        }
        // From here on, nothing this process writes can show the token.
        crate::redact::register_hex_secret(text);
        Some(Self(Zeroizing::new(text.to_owned())))
    }

    /// Returns the token text, for the request header and the resume file.
    pub(crate) fn expose(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for BootstrapToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("BootstrapToken(<redacted>)")
    }
}

/// Why the bootstrap token file could not be read.
///
/// No variant carries any part of the token.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TokenFileError {
    /// The file could not be opened or read safely.
    #[error(transparent)]
    File(PrivateFileError),
    /// The file does not hold 64 lowercase hex digits and a newline.
    #[error("token file does not hold a bootstrap token (64 lowercase hex digits)")]
    Malformed,
}