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
//! `stratum setup`: the bootstrap claim flow.

use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize as _;
use serde_json::{json, Value as Json};
use stratum_node_config::{schema, Change};
use stratum_node_core::{ClaimBody, DidNostr, Sha256Digest};

use crate::changes::parse_changes;
use crate::client::{self, Client};
use crate::error::CliError;
use crate::exit;
use crate::output::sanitize;
use crate::private_file;
use crate::resume::ResumeRecord;
use crate::session::{
    check_expected_node, claim_json, invalid_preview, readyz, request_preview, to_body, Session,
    SetupOptions, CHALLENGE, CLAIM,
};
use crate::token::BootstrapToken;
use crate::wire::{ChallengeRequest, ChallengeResponse, ClaimResponse, PreviewResponse};

/// The suffix appended to the key file path for the default resume file.
const RESUME_SUFFIX: &str = ".setup-resume";

impl Session {
    /// `stratum setup --token-file <path> [--set path=value …]`: claims an
    /// unconfigured node for the operator key and commits the initial
    /// configuration. With no `--set`, the node is claimed with its seed
    /// configuration unchanged.
    ///
    /// The flow:
    ///
    /// 1. Read the bootstrap token and `/readyz`, which must report
    ///    `unconfigured` at revision 0, and take the node DID from it. With
    ///    [`SetupOptions::expect_node`], that DID must be the expected one,
    ///    or setup stops before anything else is sent.
    /// 2. Derive the initial configuration locally: the seed text of
    ///    `stratum-node-config` (the text of revision 0) with the changes
    ///    applied. Preview the same changes on the node; its `text` and
    ///    `diff` must equal the local ones byte for byte. Show the local
    ///    diff and change list (and with [`SetupOptions::show_text`] the
    ///    whole text); stop if the result is invalid.
    /// 3. Request a challenge for this key's DID and the same changes.
    /// 4. Check the returned claim body locally: it must name this
    ///    claimant and the node from `/readyz`, must not have expired, must
    ///    answer the challenge ID and base revision, its `config_sha256` must
    ///    be the SHA-256 of the locally derived text (so the hash covers
    ///    exactly the text shown), and the claim URL must be this client's
    ///    own `/api/v1/bootstrap/claim` URL with method `POST`.
    /// 5. Show the claim fields and ask for confirmation (or `--yes`).
    /// 6. Sign the body verbatim, save the signed request with the token to
    ///    the resume file (`0600`, created exclusively), then send it with
    ///    the token in `Stratum-Bootstrap-Token`.
    /// 7. Check that the response names this administrator and node, print
    ///    the administrator DID, revision and public-config hash, and delete
    ///    the resume file.
    ///
    /// If a resume file exists, steps 1 to 6 are skipped and the saved
    /// request is resent byte for byte, so that a node which committed the
    /// claim but lost the response returns its stored result. With
    /// [`SetupOptions::expect_node`], the saved body must name that node and
    /// `/readyz` must report it before the saved request is resent. The resume
    /// file is kept after a transport failure, a protocol error or a 5xx
    /// response, and deleted after success or any 4xx, which the identical
    /// request can never turn into a success.
    ///
    /// # Errors
    ///
    /// [`CliError::Refused`] for any failed local check (including a node
    /// other than the expected one, or a node preview that differs from
    /// the local derivation),
    /// [`CliError::NotConfirmed`], [`CliError::InvalidPreview`], token, key
    /// and resume-file errors, and transport, protocol and server errors.
    pub fn setup(&self, options: &SetupOptions) -> Result<u8, CliError> {
        let key_path = self.key_path()?;
        let resume_path = options
            .resume_file
            .clone()
            .unwrap_or_else(|| default_resume_path(key_path));
        let client = self.client()?;
        if fs::symlink_metadata(&resume_path).is_ok() {
            return self.resume_setup(&client, &resume_path, options);
        }
        self.fresh_setup(&client, &resume_path, options)
    }

    /// Steps 1 to 7 of [`setup`](Self::setup).
    fn fresh_setup(
        &self,
        client: &Client,
        resume_path: &Path,
        options: &SetupOptions,
    ) -> Result<u8, CliError> {
        let key = self.key()?;
        let claimant = key.public();
        let token = BootstrapToken::read_file(&options.token_file).map_err(|source| {
            CliError::TokenFile {
                path: options.token_file.clone(),
                source,
            }
        })?;
        // No --set is allowed: the node is then claimed with its seed
        // configuration, and the change list is sent as `[]`.
        let changes =
            parse_changes(&options.sets).map_err(|err| CliError::Usage(err.to_string()))?;

        let ready = readyz(client)?;
        check_expected_node(ready.node_did, options.expect_node.as_ref())?;
        if ready.status != "unconfigured" {
            return Err(CliError::Refused(format!(
                "the node reports status {:?}, not \"unconfigured\": it has already been set up",
                sanitize(&ready.status)
            )));
        }
        if ready.head_revision != SEED_REVISION {
            return Err(CliError::Refused(format!(
                "the node reports itself unconfigured at revision {}, not {SEED_REVISION}",
                ready.head_revision
            )));
        }
        let node = ready.node_did;
        let base = SEED_REVISION;

        let (preview, preview_raw) = derive_initial(&changes)?;
        let (remote, _remote_raw) = request_preview(client, base, &changes, None)?;
        if remote.text != preview.text || remote.diff != preview.diff {
            return Err(CliError::Refused(
                "the node's preview of the initial configuration differs from the one this client \
                 derives from its own stratum-node-config seed; the node and the client may be \
                 built on different versions; nothing was signed"
                    .to_owned(),
            ));
        }
        self.show_preview(&preview)?;
        if options.show_text {
            self.output().line(&format!(
                "configuration text (sha256 {}), exactly as the claim binds it:",
                Sha256Digest::of(preview.text.as_bytes())
            ))?;
            self.output().line(sanitize(&preview.text).trim_end())?;
        }
        if !preview.errors.is_empty() {
            self.output()
                .json(&json!({ "preview": preview_raw, "claimed": false }))?;
            return Err(invalid_preview(&preview));
        }

        let request = to_body(&ChallengeRequest {
            did: claimant,
            base_revision: base,
            changes: &changes,
        })?;
        let (challenge, _raw): (ChallengeResponse, Json) =
            client.post(CHALLENGE, &request, None)?.into_json()?;
        let claim_url = client.url(CLAIM);
        let body = check_challenge(&challenge, &claim_url, node, claimant, base, &preview.text)?;
        self.show_claim(&body)?;
        self.output().note(&format!(
            "the claim binds {claimant} as the administrator of {node}"
        ))?;
        let mut report = json!({
            "preview": preview_raw,
            "claim": claim_json(&body),
            "claimed": false,
        });
        if !self.confirmed("claim this node?", options.confirmation)? {
            self.output().json(&report)?;
            return Err(CliError::NotConfirmed);
        }

        let authorization = client::sign(&key, "POST", &claim_url, Some(body.as_bytes()))?;
        let record = ResumeRecord {
            url: claim_url,
            authorization,
            token,
            claim_body: challenge.claim_body,
        };
        record.save(resume_path)?;
        self.output().note(&format!(
            "saved the signed claim to {}; if the response is lost, rerun the same command to resend it",
            resume_path.display()
        ))?;
        let result = self.send_claim(client, &record, resume_path, node, claimant)?;
        report["claimed"] = Json::Bool(true);
        report["result"] = result;
        self.output().json(&report)?;
        Ok(exit::OK)
    }

    /// Resends a saved claim request.
    fn resume_setup(
        &self,
        client: &Client,
        resume_path: &Path,
        options: &SetupOptions,
    ) -> Result<u8, CliError> {
        let key = self.key()?;
        let record = ResumeRecord::load(resume_path)?;
        let claim_url = client.url(CLAIM);
        if record.url != claim_url {
            return Err(CliError::Usage(format!(
                "the saved claim in {} is for {}, not {claim_url}; pass the matching --url",
                resume_path.display(),
                sanitize(&record.url)
            )));
        }
        let body = ClaimBody::parse(record.claim_body.as_bytes()).map_err(|err| {
            CliError::FileContents {
                path: resume_path.to_owned(),
                message: format!("the saved claim body is malformed: {err}"),
            }
        })?;
        if body.claimant() != key.public() {
            return Err(CliError::Refused(format!(
                "the saved claim names claimant {}, but this key is {}",
                body.claimant(),
                key.public()
            )));
        }
        if let Some(expected) = &options.expect_node {
            if body.node() != *expected {
                return Err(CliError::Refused(format!(
                    "the saved claim is for node {}, not the expected {expected}",
                    body.node()
                )));
            }
            check_expected_node(readyz(client)?.node_did, Some(expected))?;
        }
        if !options.sets.is_empty() {
            self.output().note(
                "note: --set is ignored: resending the saved claim, whose configuration is already fixed",
            )?;
        }
        self.output().note(&format!(
            "resending the saved claim from {}",
            resume_path.display()
        ))?;
        self.show_claim(&body)?;
        let result = self.send_claim(client, &record, resume_path, body.node(), body.claimant())?;
        self.output().json(&json!({
            "claim": claim_json(&body),
            "claimed": true,
            "resumed": true,
            "result": result,
        }))?;
        Ok(exit::OK)
    }

    /// Sends the claim request held in `record` and handles the resume file.
    fn send_claim(
        &self,
        client: &Client,
        record: &ResumeRecord,
        resume_path: &Path,
        node: DidNostr,
        claimant: DidNostr,
    ) -> Result<Json, CliError> {
        let sent = client.post_raw(
            &record.url,
            record.claim_body.as_bytes(),
            Some(&record.authorization),
            Some(record.token.expose()),
        );
        let response = match sent {
            Ok(response) => response,
            Err(err) => {
                self.keep_note(resume_path)?;
                return Err(err);
            }
        };
        if (400..500).contains(&response.status) {
            discard(resume_path)?;
            return Err(response.into_error());
        }
        let parsed = response.into_json::<ClaimResponse>();
        let (claimed, _raw) = match parsed {
            Ok(ok) => ok,
            Err(err) => {
                self.keep_note(resume_path)?;
                return Err(err);
            }
        };
        discard(resume_path)?;
        if claimed.administrator != claimant || claimed.node_did != node {
            return Err(CliError::Refused(format!(
                "the node reports administrator {} of {}, not {claimant} of {node}",
                claimed.administrator, claimed.node_did
            )));
        }
        self.output()
            .line(&format!("administrator: {}", claimed.administrator))?;
        self.output().line(&format!("node: {}", claimed.node_did))?;
        self.output()
            .line(&format!("revision: {}", claimed.revision))?;
        self.output().line(&format!(
            "public config hash: {}",
            claimed.public_config_hash
        ))?;
        // Built from the checked fields only: anything else the node put in
        // the response (such as an echo of the token) is not repeated.
        Ok(json!({
            "administrator": claimed.administrator,
            "node_did": claimed.node_did,
            "revision": claimed.revision,
            "public_config_hash": claimed.public_config_hash,
        }))
    }

    /// Tells the operator the resume file was kept for a retry.
    fn keep_note(&self, resume_path: &Path) -> Result<(), CliError> {
        self.output().note(&format!(
            "the signed claim is kept in {}; rerun the same command to resend it",
            resume_path.display()
        ))
    }
}

/// The revision an unconfigured node reports: none committed, so its text
/// is the seed configuration.
const SEED_REVISION: u64 = 0;

/// Derives the initial configuration locally: the seed text of
/// `stratum-node-config` with `changes` applied, in the preview wire shape
/// (and as JSON for `--json` output).
fn derive_initial(changes: &[Change]) -> Result<(PreviewResponse, Json), CliError> {
    let preview = stratum_node_config::preview(&schema().seed_text(), changes)
        .map_err(|err| CliError::Usage(format!("the initial configuration: {err}")))?;
    let mut value = serde_json::to_value(&preview)
        .map_err(|err| CliError::Local(format!("encoding the preview failed: {err}")))?;
    value["base_revision"] = json!(SEED_REVISION);
    let typed = PreviewResponse::deserialize(&value)
        .map_err(|err| CliError::Local(format!("reading the local preview failed: {err}")))?;
    Ok((typed, value))
}

/// Deletes the resume file.
fn discard(resume_path: &Path) -> Result<(), CliError> {
    private_file::remove(resume_path).map_err(|source| CliError::File {
        path: resume_path.to_owned(),
        source,
    })
}

/// Returns `<key file>.setup-resume`.
fn default_resume_path(key_path: &Path) -> PathBuf {
    let mut path = key_path.as_os_str().to_owned();
    path.push(RESUME_SUFFIX);
    PathBuf::from(path)
}

/// Checks a challenge response against what this client asked for and
/// expects, and returns the parsed claim body.
fn check_challenge(
    challenge: &ChallengeResponse,
    claim_url: &str,
    node: DidNostr,
    claimant: DidNostr,
    base_revision: u64,
    previewed_text: &str,
) -> Result<ClaimBody, CliError> {
    if challenge.method != "POST" {
        return Err(CliError::Refused(
            "the challenge names a claim method other than POST".to_owned(),
        ));
    }
    if challenge.url != claim_url {
        return Err(CliError::Refused(format!(
            "the challenge names claim url {}, not {claim_url}",
            sanitize(&challenge.url)
        )));
    }
    let body = ClaimBody::parse(challenge.claim_body.as_bytes())
        .map_err(|err| CliError::Refused(format!("the claim body is not acceptable: {err}")))?;
    body.check(client::now()?, &node, &claimant)
        .map_err(|err| CliError::Refused(err.to_string()))?;
    if body.nonce() != challenge.challenge_id {
        return Err(CliError::Refused(
            "the claim body's nonce is not the challenge id".to_owned(),
        ));
    }
    if body.expires_at() != challenge.expires_at {
        return Err(CliError::Refused(
            "the claim body's expiry differs from the challenge's".to_owned(),
        ));
    }
    if body.base_revision().get() != base_revision {
        return Err(CliError::Refused(format!(
            "the claim body is based on revision {}, not {base_revision}",
            body.base_revision()
        )));
    }
    if body.config_sha256() != Sha256Digest::of(previewed_text.as_bytes()) {
        return Err(CliError::Refused(
            "the claim body's config_sha256 is not the hash of the previewed configuration"
                .to_owned(),
        ));
    }
    Ok(body)
}