stratum-node-cli 0.1.0-alpha.1

The `stratum` operator client for Stratum pod nodes: operator key files, bootstrap claim, signed config apply, audit checkpoint and backup over the loopback API
Documentation
//! The setup resume file: a signed claim request saved before it is sent.

use std::path::Path;

use serde::Deserialize;
use zeroize::{Zeroize as _, Zeroizing};

use crate::error::CliError;
use crate::private_file::{self, ModePolicy};
use crate::token::BootstrapToken;

/// The resume-file format version.
const RESUME_VERSION: u32 = 1;

/// The largest resume file read: a claim body is a few hundred bytes and an
/// `Authorization` value well under 2 KiB.
const RESUME_FILE_LIMIT: usize = 64 * 1024;

/// Everything needed to resend the identical claim request.
///
/// The bootstrap token is included because the node deletes its token file
/// once the claim commits: after a lost response, the file the operator
/// pointed at may no longer exist, yet the identical request must carry the
/// same header to receive the stored result.
#[derive(Debug)]
pub(crate) struct ResumeRecord {
    pub(crate) url: String,
    pub(crate) authorization: String,
    pub(crate) token: BootstrapToken,
    pub(crate) claim_body: String,
}

/// The on-disk JSON shape.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Stored {
    version: u32,
    url: String,
    authorization: String,
    bootstrap_token: String,
    claim_body: String,
}

impl ResumeRecord {
    /// Writes the record to a new `0600` file; an existing file is never
    /// overwritten.
    pub(crate) fn save(&self, path: &Path) -> Result<(), CliError> {
        let mut value = serde_json::json!({
            "version": RESUME_VERSION,
            "url": self.url,
            "authorization": self.authorization,
            "bootstrap_token": self.token.expose(),
            "claim_body": self.claim_body,
        });
        let bytes =
            Zeroizing::new(serde_json::to_vec(&value).map_err(|err| {
                CliError::Local(format!("encoding the resume file failed: {err}"))
            })?);
        if let Some(serde_json::Value::String(text)) = value.get_mut("bootstrap_token") {
            text.zeroize();
        }
        private_file::create(path, &bytes).map_err(|source| CliError::File {
            path: path.to_owned(),
            source,
        })
    }

    /// Reads a record written by [`save`](Self::save). The file must be a
    /// regular file with a mode no wider than `0600`.
    pub(crate) fn load(path: &Path) -> Result<Self, CliError> {
        let bytes = private_file::read(path, RESUME_FILE_LIMIT, ModePolicy::OwnerOnly).map_err(
            |source| CliError::File {
                path: path.to_owned(),
                source,
            },
        )?;
        let malformed = |message: &str| CliError::FileContents {
            path: path.to_owned(),
            message: message.to_owned(),
        };
        let mut stored: Stored = serde_json::from_slice(&bytes)
            .map_err(|_| malformed("not a stratum setup resume file"))?;
        let token = BootstrapToken::parse(&stored.bootstrap_token);
        stored.bootstrap_token.zeroize();
        if stored.version != RESUME_VERSION {
            return Err(malformed("unsupported resume file version"));
        }
        let token = token.ok_or_else(|| malformed("the saved bootstrap token is malformed"))?;
        Ok(Self {
            url: stored.url,
            authorization: stored.authorization,
            token,
            claim_body: stored.claim_body,
        })
    }
}