stratum-node-cli 0.1.0-alpha.3

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
//! Operator key files: one `nsec1…` line in a `0600` file.

use std::fmt::Write as _;
use std::path::Path;

use bech32::{Bech32, Hrp};
use stratum_node_core::{NostrSecretKey, ParseKeyError};
use zeroize::Zeroizing;

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

/// The NIP-19 prefix of a secret key.
const NSEC_HRP: &str = "nsec";

/// The length of an `nsec1…` string over 32 bytes.
const NSEC_LEN: usize = 63;

/// The largest key file read: one `nsec` line with room for a CRLF.
const KEY_FILE_LIMIT: usize = 128;

/// How many times generation retries when the random bytes are not a valid
/// secp256k1 scalar. The chance of even one retry is about 2^-128.
const MAX_GENERATE_ATTEMPTS: usize = 8;

/// Creates a new operator key file holding a freshly generated key.
///
/// The key is 32 bytes from the operating system's random source
/// (`getrandom`), written as one NIP-19 `nsec1…` line followed by a newline.
/// The file is created exclusively with mode `0600` set at creation, so an
/// existing file, or a symbolic link at `path`, is never overwritten or
/// followed. The returned key's [`public`](NostrSecretKey::public) principal
/// is the operator's DID; the secret is never returned in text form.
///
/// # Examples
///
/// ```
/// use stratum_node_cli::{generate_key_file, load_key_file};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let dir = std::env::temp_dir().join(format!("stratum-doc-{}", std::process::id()));
/// std::fs::create_dir_all(&dir)?;
/// let path = dir.join("operator.nsec");
/// # let _ = std::fs::remove_file(&path);
/// let key = generate_key_file(&path)?;
/// assert_eq!(load_key_file(&path)?.public(), key.public());
/// assert!(generate_key_file(&path).is_err(), "never overwrites");
/// # std::fs::remove_file(&path)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns [`KeyFileError::File`] with [`PrivateFileError::AlreadyExists`]
/// when anything exists at `path`, another [`KeyFileError::File`] for an
/// operating-system failure (nothing is left behind), and
/// [`KeyFileError::RandomUnavailable`] when the random source fails.
pub fn generate_key_file(path: &Path) -> Result<NostrSecretKey, KeyFileError> {
    let mut bytes = Zeroizing::new([0u8; 32]);
    let mut key = None;
    for _ in 0..MAX_GENERATE_ATTEMPTS {
        getrandom::fill(bytes.as_mut_slice()).map_err(|_| KeyFileError::RandomUnavailable)?;
        if let Ok(candidate) = NostrSecretKey::from_bytes(&bytes) {
            key = Some(candidate);
            break;
        }
    }
    let key = key.ok_or(KeyFileError::RandomUnavailable)?;
    let mut line = Zeroizing::new(String::with_capacity(NSEC_LEN + 1));
    let hrp = Hrp::parse_unchecked(NSEC_HRP);
    bech32::encode_lower_to_fmt::<Bech32, _>(&mut *line, hrp, bytes.as_slice())
        .map_err(|_| KeyFileError::Encoding)?;
    line.write_char('\n').map_err(|_| KeyFileError::Encoding)?;
    private_file::create(path, line.as_bytes()).map_err(KeyFileError::File)?;
    Ok(key)
}

/// Loads an operator key file written by [`generate_key_file`].
///
/// The file must be a regular file (not a symbolic link) with a mode not
/// open to group or others, holding one `nsec1…` string optionally followed by a
/// newline. The contents are read into memory that is zeroised afterwards.
///
/// # Errors
///
/// Returns [`KeyFileError::File`] for a symbolic link, a non-regular file, a
/// mode wider than `0600`, an over-long file or an operating-system
/// failure, [`KeyFileError::NotOneLine`] when the file is not one line of
/// text, and [`KeyFileError::InvalidKey`] when the line is not a valid
/// `nsec`. No error carries any part of the file.
pub fn load_key_file(path: &Path) -> Result<NostrSecretKey, KeyFileError> {
    let contents = private_file::read(path, KEY_FILE_LIMIT, ModePolicy::OwnerOnly)
        .map_err(KeyFileError::File)?;
    let text = std::str::from_utf8(&contents).map_err(|_| KeyFileError::NotOneLine)?;
    let line = text
        .strip_suffix("\r\n")
        .or_else(|| text.strip_suffix('\n'))
        .unwrap_or(text);
    if line.contains(['\n', '\r']) {
        return Err(KeyFileError::NotOneLine);
    }
    NostrSecretKey::from_nsec(line).map_err(KeyFileError::InvalidKey)
}

/// Why an operator key file could not be created or loaded.
///
/// No variant carries any part of the key.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum KeyFileError {
    /// The file could not be created, opened or read safely.
    #[error(transparent)]
    File(PrivateFileError),
    /// The file is not a single line of UTF-8 text.
    #[error("key file must hold exactly one nsec line")]
    NotOneLine,
    /// The line is not a valid NIP-19 secret key.
    #[error("key file does not hold a valid nsec key")]
    InvalidKey(#[source] ParseKeyError),
    /// The operating system's random source failed.
    #[error("the system random source is unavailable")]
    RandomUnavailable,
    /// The key could not be encoded as `nsec`.
    #[error("the key could not be encoded as nsec")]
    Encoding,
}