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
//! `stratum`: the operator's client for a Stratum node's loopback API.
//!
//! This file only parses the command line; the commands live in the
//! `stratum_node_cli` library.

use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Args, Parser, Subcommand};
use stratum_node_cli::{
    exit, ApplyOptions, Confirmation, LoopbackUrl, Output, OutputFormat, Session, SetupOptions,
    DEFAULT_URL,
};
use stratum_node_core::DidNostr;

/// The exit-code table shown at the end of `--help`.
const EXIT_CODES: &str = "\
Exit codes:
   0  success; for `status`, the node is ready
   1  local failure (key, token or resume file, clock, output)
   2  the node could not be reached
   3  status: the node is unconfigured
   4  status: the node is degraded
   5  the node's response does not follow the API contract
   6  previewed but not applied: no confirmation (pass --yes)
   7  a local check refused the node's answer (claim body, backup manifest)
  10  bad_request            11  unauthorized          12  forbidden
  13  not_found              14  conflict              15  payload_too_large
  16  unsupported_media_type 17  invalid (also an invalid preview)
  18  too_many_challenges    19  backup_refused        20  internal
  21  unknown server error code
  64  invalid command line

Server errors are printed as `code: message`.";

/// The operator's client for a Stratum node.
///
/// Talks to the node's loopback API over plain HTTP and signs requests with
/// the operator's Nostr key. PRE-RELEASE (0.1.0-alpha): commands and output
/// may change.
#[derive(Debug, Parser)]
#[command(name = "stratum", version, after_help = EXIT_CODES)]
struct Cli {
    /// Node API URL; the host must be an address in 127.0.0.0/8 (such as
    /// 127.0.0.1), `[::1]` or localhost, which is dialled as 127.0.0.1
    /// without a name lookup (no TLS in Step 1). For sign-challenge: the
    /// claim URL.
    #[arg(long, global = true, env = "STRATUM_URL", default_value = DEFAULT_URL)]
    url: LoopbackUrl,

    /// Operator key file (one nsec line, mode 0600).
    #[arg(long, global = true, env = "STRATUM_KEY_FILE", value_name = "FILE")]
    key_file: Option<PathBuf>,

    /// Write machine-readable JSON to standard output.
    #[arg(long, global = true)]
    json: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Create or inspect an operator key file.
    Key {
        #[command(subcommand)]
        command: KeyCommand,
    },
    /// Show the node's readiness (exit 0 ready, 3 unconfigured, 4 degraded,
    /// 2 unreachable).
    Status,
    /// Read, preview and apply configuration.
    Config {
        #[command(subcommand)]
        command: ConfigCommand,
    },
    /// Claim an unconfigured node with the bootstrap token and this key.
    Setup(SetupArgs),
    /// Sign a claim body offline and print the Authorization header value.
    ///
    /// Refuses a body that names another claimant, another node than
    /// --expect-node, or has expired. The configuration hash in the body
    /// cannot be checked offline and is signed as issued; `stratum setup`
    /// checks it. Uses --url as the claim URL: a bare origin gets
    /// /api/v1/bootstrap/claim appended, and a URL with a path must end in
    /// exactly that path. It must equal the `url` in the challenge
    /// response. No network access.
    SignChallenge {
        /// File holding the claim body bytes exactly as the node issued them.
        #[arg(long, value_name = "FILE")]
        claim_body_file: PathBuf,

        /// The node DID the claim must name, as stratumd printed it at start
        /// (never taken from the claim file).
        #[arg(long, value_name = "DID")]
        expect_node: DidNostr,
    },
    /// Audit log operations.
    Audit {
        #[command(subcommand)]
        command: AuditCommand,
    },
    /// Ask the node for a backup and verify its signed manifest.
    Backup {
        /// Operation ID to reuse when retrying; random when omitted.
        #[arg(long, value_name = "ID")]
        operation_id: Option<String>,

        /// Refuse unless /readyz reports this node DID.
        #[arg(long, value_name = "DID")]
        expect_node: Option<DidNostr>,
    },
}

#[derive(Debug, Subcommand)]
enum KeyCommand {
    /// Generate a new operator key into a new 0600 file; prints its DID and
    /// npub only.
    Generate {
        /// The key file to create; an existing file is never overwritten.
        #[arg(long, value_name = "FILE")]
        out: PathBuf,
    },
    /// Print the DID and npub of the key in --key-file.
    Show,
}

#[derive(Debug, Subcommand)]
enum ConfigCommand {
    /// Print the configuration schema.
    Schema,
    /// Print the effective configuration and revisions.
    Show,
    /// Show what a change would do, without applying it.
    Preview(PreviewArgs),
    /// Preview a change, confirm, then apply it.
    Apply(ApplyArgs),
}

#[derive(Debug, Subcommand)]
enum AuditCommand {
    /// Print the audit checkpoint `<seq>:<hex>` and the node DID.
    Checkpoint,
}

/// `--set` and `--base-revision`, shared by preview and apply.
#[derive(Debug, Args)]
struct ChangeArgs {
    /// A change, typed by the schema: booleans `true`/`false`, integers in
    /// decimal, strings as given; lists comma-separated or by repeating
    /// --set for the same path (`path=` is the empty list).
    #[arg(long = "set", value_name = "PATH=VALUE")]
    sets: Vec<String>,

    /// The revision the change is based on; the node's head when omitted.
    #[arg(long, value_name = "N")]
    base_revision: Option<u64>,
}

#[derive(Debug, Args)]
struct PreviewArgs {
    #[command(flatten)]
    changes: ChangeArgs,
}

#[derive(Debug, Args)]
struct ApplyArgs {
    #[command(flatten)]
    changes: ChangeArgs,

    /// Operation ID to reuse when retrying; random (and printed) when
    /// omitted.
    #[arg(long, value_name = "ID")]
    operation_id: Option<String>,

    /// Apply without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

#[derive(Debug, Args)]
struct SetupArgs {
    /// The node's bootstrap token file, STATE_DIR/bootstrap-token.
    #[arg(long, value_name = "FILE")]
    token_file: PathBuf,

    /// An initial configuration change (as for `config apply`); optional:
    /// with none, the node is claimed with its seed configuration.
    #[arg(long = "set", value_name = "PATH=VALUE")]
    sets: Vec<String>,

    /// The node DID stratumd printed at start. The bootstrap token is sent
    /// only if /readyz reports it. Without it, setup trusts whatever answers
    /// on the loopback port.
    #[arg(long, value_name = "DID")]
    expect_node: Option<DidNostr>,

    /// Also print the full configuration text whose SHA-256 the claim binds.
    #[arg(long)]
    show_text: bool,

    /// Where the signed claim is saved before sending (0600); defaults to
    /// KEY_FILE.setup-resume. If it exists, it is resent unchanged.
    #[arg(long, value_name = "FILE")]
    resume_file: Option<PathBuf>,

    /// Claim without asking.
    #[arg(long, short = 'y')]
    yes: bool,
}

/// Maps the `--yes` flag of a command that changes the node.
trait YesFlag {
    /// Returns the flag's value.
    fn yes(&self) -> bool;

    /// Returns [`Confirmation::Assumed`] under `--yes`, else
    /// [`Confirmation::Prompt`].
    fn confirmation(&self) -> Confirmation {
        if self.yes() {
            Confirmation::Assumed
        } else {
            Confirmation::Prompt
        }
    }
}

impl YesFlag for ApplyArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

impl YesFlag for SetupArgs {
    fn yes(&self) -> bool {
        self.yes
    }
}

fn main() -> ExitCode {
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(err) => {
            let code = if err.use_stderr() {
                exit::USAGE
            } else {
                exit::OK
            };
            // Nothing useful can be done if printing the usage message fails.
            let _printed = err.print();
            return ExitCode::from(code);
        }
    };
    let output = Output::new(if cli.json {
        OutputFormat::Json
    } else {
        OutputFormat::Human
    });
    let session = Session::new(cli.url, cli.key_file, output);
    let result = match cli.command {
        Command::Key {
            command: KeyCommand::Generate { out },
        } => session.key_generate(&out),
        Command::Key {
            command: KeyCommand::Show,
        } => session.key_show(),
        Command::Status => session.status(),
        Command::Config { command } => match command {
            ConfigCommand::Schema => session.config_schema(),
            ConfigCommand::Show => session.config_show(),
            ConfigCommand::Preview(args) => {
                session.config_preview(&args.changes.sets, args.changes.base_revision)
            }
            ConfigCommand::Apply(args) => session.config_apply(&ApplyOptions {
                confirmation: args.confirmation(),
                sets: args.changes.sets,
                base_revision: args.changes.base_revision,
                operation_id: args.operation_id,
            }),
        },
        Command::Setup(args) => session.setup(&SetupOptions {
            confirmation: args.confirmation(),
            token_file: args.token_file,
            sets: args.sets,
            resume_file: args.resume_file,
            expect_node: args.expect_node,
            show_text: args.show_text,
        }),
        Command::SignChallenge {
            claim_body_file,
            expect_node,
        } => session.sign_challenge(&claim_body_file, &expect_node),
        Command::Audit {
            command: AuditCommand::Checkpoint,
        } => session.audit_checkpoint(),
        Command::Backup {
            operation_id,
            expect_node,
        } => session.backup(operation_id.as_deref(), expect_node.as_ref()),
    };
    match result {
        Ok(code) => ExitCode::from(code),
        Err(err) => {
            output.error(&err);
            ExitCode::from(err.exit_code())
        }
    }
}