use std::path::{Path, PathBuf};
use std::time::Duration;
use serde::{Deserialize as _, Serialize};
use serde_json::{json, Value as Json};
use stratum_node_config::Change;
use stratum_node_core::{ClaimBody, DidNostr, NostrSecretKey, OperationId, SignedEvent};
use crate::changes::parse_changes;
use crate::client::{self, Client, Response};
use crate::error::CliError;
use crate::exit;
use crate::key::{generate_key_file, load_key_file};
use crate::output::{sanitize, Output};
use crate::private_file::{self, ModePolicy};
use crate::url::LoopbackUrl;
use crate::wire::{
ApplyRequest, ApplyResponse, BackupManifest, BackupRequest, BackupResponse, CheckpointResponse,
ConfigResponse, PreviewRequest, PreviewResponse, Readyz, BACKUP_FILES, BACKUP_FORMAT,
BACKUP_FORMAT_VERSION, BACKUP_FORMAT_VERSION_PODS, BACKUP_POD_ARCHIVE,
};
pub(crate) const READYZ: &str = "/readyz";
const SCHEMA: &str = "/api/v1/config/schema";
const CONFIG: &str = "/api/v1/config";
pub(crate) const PREVIEW: &str = "/api/v1/config/preview";
const APPLY: &str = "/api/v1/config/apply";
const CHECKPOINT: &str = "/api/v1/audit/checkpoint";
const BACKUP: &str = "/api/v1/backup";
const BACKUP_TIMEOUT: Duration = Duration::from_secs(15 * 60);
pub(crate) const CHALLENGE: &str = "/api/v1/bootstrap/challenge";
pub(crate) const CLAIM: &str = "/api/v1/bootstrap/claim";
const API_VERSION: u64 = 1;
const MANIFEST_KIND: u16 = 30078;
const CLAIM_BODY_FILE_LIMIT: usize = 64 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Confirmation {
#[default]
Prompt,
Assumed,
}
#[derive(Debug, Clone, Default)]
pub struct ApplyOptions {
pub sets: Vec<String>,
pub base_revision: Option<u64>,
pub operation_id: Option<String>,
pub confirmation: Confirmation,
}
#[derive(Debug, Clone, Default)]
pub struct SetupOptions {
pub token_file: PathBuf,
pub sets: Vec<String>,
pub resume_file: Option<PathBuf>,
pub confirmation: Confirmation,
pub expect_node: Option<DidNostr>,
pub show_text: bool,
}
#[derive(Debug, Clone)]
pub struct Session {
url: LoopbackUrl,
key_file: Option<PathBuf>,
output: Output,
}
impl Session {
pub fn new(url: LoopbackUrl, key_file: Option<PathBuf>, output: Output) -> Self {
Self {
url,
key_file,
output,
}
}
pub fn key_generate(&self, out: &Path) -> Result<u8, CliError> {
let key = generate_key_file(out).map_err(|source| CliError::KeyFile {
path: out.to_owned(),
source,
})?;
self.print_identity(&key.public(), out)
}
pub fn key_show(&self) -> Result<u8, CliError> {
let path = self.key_path()?;
let key = self.key()?;
self.print_identity(&key.public(), path)
}
pub fn status(&self) -> Result<u8, CliError> {
let client = self.client()?;
let response = client.get(READYZ, None)?;
let status = response.status;
let (readyz, raw): (Readyz, Json) = response.parse()?;
let code = match (status, readyz.status.as_str()) {
(200, "ready") => exit::OK,
(200, "unconfigured") => exit::UNCONFIGURED,
(503, "degraded") => exit::DEGRADED,
_ => {
return Err(CliError::Protocol(format!(
"readyz answered HTTP {status} with status {:?}",
sanitize(&readyz.status)
)))
}
};
self.output.json(&raw)?;
self.output.line(&format!("status: {}", readyz.status))?;
self.output.line(&format!("node: {}", readyz.node_did))?;
self.output
.line(&format!("version: {}", sanitize(&readyz.version)))?;
self.output
.line(&format!("api version: {}", readyz.api_version))?;
self.output.line(&format!(
"revision: head {}, active {}",
readyz.head_revision, readyz.active_revision
))?;
self.output.line(&format!(
"public config hash: {}",
readyz
.public_config_hash
.as_deref()
.map_or_else(|| "none".to_owned(), sanitize)
))?;
Ok(code)
}
pub fn config_schema(&self) -> Result<u8, CliError> {
let client = self.client()?;
let (schema, raw): (Json, Json) = client.get(SCHEMA, None)?.into_json()?;
self.output.json(&raw)?;
if let Some(version) = schema.get("schema_version") {
self.output.line(&format!("schema version {version}"))?;
}
let fields = schema
.get("fields")
.and_then(Json::as_array)
.ok_or_else(|| CliError::Protocol("schema has no fields list".to_owned()))?;
for field in fields {
let text = |name: &str| field.get(name).map_or_else(String::new, compact);
let kind = field
.get("type")
.and_then(|t| t.get("kind"))
.map_or_else(String::new, compact);
self.output.line(&sanitize(&format!(
"\n{} ({kind}, {}, default {})\n {}",
text("path").trim_matches('"'),
text("apply_class").trim_matches('"'),
text("default"),
text("description").trim_matches('"'),
)))?;
}
Ok(exit::OK)
}
pub fn config_show(&self) -> Result<u8, CliError> {
let key = self.key()?;
let client = self.client()?;
let (config, raw): (ConfigResponse, Json) = client.get(CONFIG, Some(&key))?.into_json()?;
self.output.json(&raw)?;
self.output.line(&format!(
"revision: head {}, active {}",
config.head_revision, config.active_revision
))?;
self.output.line(&format!(
"public config hash: {}",
config.public_config_hash
))?;
self.output.line("")?;
self.output.line(sanitize(&config.text).trim_end())?;
Ok(exit::OK)
}
pub fn config_preview(
&self,
sets: &[String],
base_revision: Option<u64>,
) -> Result<u8, CliError> {
let changes = changes_from(sets)?;
let key = match self.key_file {
Some(_) => Some(self.key()?),
None => None,
};
let client = self.client()?;
let base = match base_revision {
Some(base) => base,
None => readyz(&client)?.head_revision,
};
let (preview, raw) = request_preview(&client, base, &changes, key.as_ref())?;
self.output.json(&raw)?;
self.show_preview(&preview)?;
if preview.errors.is_empty() {
Ok(exit::OK)
} else {
Err(invalid_preview(&preview))
}
}
pub fn config_apply(&self, options: &ApplyOptions) -> Result<u8, CliError> {
let changes = changes_from(&options.sets)?;
let operation_id = operation_id(options.operation_id.as_deref())?;
let key = self.key()?;
let client = self.client()?;
let ready = readyz(&client)?;
let base = options.base_revision.unwrap_or(ready.head_revision);
let (preview, preview_raw) = request_preview(&client, base, &changes, Some(&key))?;
self.show_preview(&preview)?;
let mut report = json!({
"operation_id": operation_id.as_str(),
"base_revision": base,
"preview": preview_raw,
"applied": false,
});
if !preview.errors.is_empty() {
self.output.json(&report)?;
return Err(invalid_preview(&preview));
}
if preview.changes.is_empty() {
self.output.json(&report)?;
self.output
.line("nothing to apply: the change leaves the configuration as it is")?;
return Ok(exit::OK);
}
if !self.confirmed("apply these changes?", options.confirmation)? {
self.output.json(&report)?;
return Err(CliError::NotConfirmed);
}
self.output.note(&format!(
"operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
))?;
let body = to_body(&ApplyRequest {
node: ready.node_did,
operation_id: &operation_id,
base_revision: base,
changes: &changes,
})?;
let (applied, applied_raw): (ApplyResponse, Json) =
client.post(APPLY, &body, Some(&key))?.into_json()?;
report["applied"] = Json::Bool(true);
report["result"] = applied_raw;
self.output.json(&report)?;
self.output
.line(&format!("applied: revision {}", applied.revision))?;
self.output.line(&format!(
"public config hash: {}",
applied.public_config_hash
))?;
self.output.line(&format!(
"strictest apply class: {}",
applied
.strictest_apply_class
.as_deref()
.map_or_else(|| "none".to_owned(), sanitize)
))?;
if applied.restart_required {
self.output
.line("restart required: the change takes effect after the controller restarts")?;
}
Ok(exit::OK)
}
pub fn audit_checkpoint(&self) -> Result<u8, CliError> {
let key = self.key()?;
let client = self.client()?;
let (checkpoint, raw): (CheckpointResponse, Json) =
client.get(CHECKPOINT, Some(&key))?.into_json()?;
let expected = format!("{}:{}", checkpoint.sequence, checkpoint.tail_hash);
if checkpoint.checkpoint != expected {
return Err(CliError::Protocol(
"checkpoint text does not match its sequence and tail hash".to_owned(),
));
}
self.output.json(&raw)?;
self.output.line(&expected)?;
self.output
.line(&format!("node: {}", checkpoint.node_did))?;
Ok(exit::OK)
}
pub fn backup(
&self,
operation_id_arg: Option<&str>,
expect_node: Option<&DidNostr>,
) -> Result<u8, CliError> {
let operation_id = operation_id(operation_id_arg)?;
let key = self.key()?;
let client = self.client()?;
let ready = readyz(&client)?;
check_expected_node(ready.node_did, expect_node)?;
self.output.note(&format!(
"operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
))?;
let body = to_body(&BackupRequest {
node: ready.node_did,
operation_id: &operation_id,
})?;
let (backup, raw): (BackupResponse, Json) = client
.post_with_timeout(BACKUP, &body, &key, BACKUP_TIMEOUT)?
.into_json()?;
let manifest = SignedEvent::deserialize(&backup.manifest).map_err(|_| {
CliError::Refused("the backup manifest is not a validly signed nostr event".to_owned())
})?;
if manifest.author() != ready.node_did {
return Err(CliError::Refused(format!(
"the backup manifest is signed by {}, not by the node {}",
manifest.author(),
ready.node_did
)));
}
if manifest.kind() != MANIFEST_KIND {
return Err(CliError::Refused(format!(
"the backup manifest is kind {}, not the NIP-78 kind {MANIFEST_KIND}",
manifest.kind()
)));
}
if !is_checkpoint(&backup.checkpoint) {
return Err(CliError::Protocol(
"backup checkpoint is not of the form <seq>:<64 hex>".to_owned(),
));
}
let content =
check_manifest_content(manifest.content(), ready.node_did, &backup.checkpoint)?;
let report = json!({
"operation_id": operation_id.as_str(),
"node_did": ready.node_did,
"config_revision": content.config_revision,
"created_at": content.created_at,
"pod_archive": content.pod_archive,
"backup": raw,
});
self.output.json(&report)?;
self.output
.line(&format!("directory: {}", sanitize(&backup.directory)))?;
self.output
.line(&format!("checkpoint: {}", backup.checkpoint))?;
self.output
.line(&format!("config revision: {}", content.config_revision))?;
if let Some(pods) = content.pod_archive {
self.output.line(&format!(
"pod archive: {} entries, {} bytes",
pods.entries, pods.bytes
))?;
}
self.output.line(&format!(
"manifest: event {} signed by the node {}",
manifest.id(),
manifest.author()
))?;
Ok(exit::OK)
}
pub fn sign_challenge(
&self,
claim_body_file: &Path,
expect_node: &DidNostr,
) -> Result<u8, CliError> {
let key = self.key()?;
let url = if self.url.is_origin() {
self.url.join(CLAIM)
} else if self.url.path() == CLAIM {
self.url.to_url_string()
} else {
return Err(CliError::Usage(format!(
"sign-challenge signs only for the claim route: --url must be an origin or end in {CLAIM}"
)));
};
let bytes = private_file::read(claim_body_file, CLAIM_BODY_FILE_LIMIT, ModePolicy::Any)
.map_err(|source| CliError::File {
path: claim_body_file.to_owned(),
source,
})?;
let body = ClaimBody::parse(&bytes).map_err(|err| CliError::FileContents {
path: claim_body_file.to_owned(),
message: format!("not a claim body: {err}"),
})?;
if bytes.last().is_some_and(u8::is_ascii_whitespace) {
self.output.note(
"warning: the claim body file ends in whitespace; the node compares the exact bytes it issued",
)?;
}
if body.claimant() != key.public() {
return Err(CliError::Refused(format!(
"the claim body names claimant {}, but this key is {}",
body.claimant(),
key.public()
)));
}
body.check(client::now()?, expect_node, &key.public())
.map_err(|err| CliError::Refused(err.to_string()))?;
let authorization = client::sign(&key, "POST", &url, Some(body.as_bytes()))?;
if self.output.is_json() {
self.output.json(&json!({
"url": url,
"method": "POST",
"authorization": authorization,
"claim": claim_json(&body),
}))?;
} else {
self.show_claim(&body)?;
self.output.note(&format!("signed for POST {url}"))?;
self.output.value_line(&authorization)?;
}
Ok(exit::OK)
}
pub(crate) fn client(&self) -> Result<Client, CliError> {
if !self.url.is_origin() {
return Err(CliError::Usage(
"--url must be an origin such as http://127.0.0.1:7460 for this command".to_owned(),
));
}
Ok(Client::new(self.url.clone()))
}
pub(crate) fn key_path(&self) -> Result<&Path, CliError> {
self.key_file.as_deref().ok_or(CliError::MissingKeyFile)
}
pub(crate) fn key(&self) -> Result<NostrSecretKey, CliError> {
let path = self.key_path()?;
load_key_file(path).map_err(|source| CliError::KeyFile {
path: path.to_owned(),
source,
})
}
pub(crate) fn output(&self) -> &Output {
&self.output
}
pub(crate) fn confirmed(
&self,
question: &str,
confirmation: Confirmation,
) -> Result<bool, CliError> {
match confirmation {
Confirmation::Assumed => Ok(true),
Confirmation::Prompt => {
if let Some(answer) = self.output.confirm(question)? {
return Ok(answer);
}
self.output
.note("standard input is not a terminal: pass --yes to confirm")?;
Ok(false)
}
}
}
pub(crate) fn show_preview(&self, preview: &PreviewResponse) -> Result<(), CliError> {
self.output.line(&format!(
"preview against revision {}:",
preview.base_revision
))?;
if preview.diff.is_empty() {
self.output.line("(no textual change)")?;
} else {
self.output.line(sanitize(&preview.diff).trim_end())?;
}
if !preview.changes.is_empty() {
self.output.line("changes:")?;
for change in &preview.changes {
let old = change
.old
.as_ref()
.map_or_else(|| "unset".to_owned(), compact);
self.output.line(&sanitize(&format!(
" {}: {old} -> {} ({})",
change.path,
compact(&change.new),
change.apply_class
)))?;
}
}
self.output.line(&format!(
"strictest apply class: {}",
preview
.strictest_apply_class
.as_deref()
.map_or_else(|| "none".to_owned(), sanitize)
))?;
for error in &preview.errors {
self.output
.line(&format!("invalid: {}", validation_line(error)))?;
}
Ok(())
}
pub(crate) fn show_claim(&self, body: &ClaimBody) -> Result<(), CliError> {
let fields = [
("node", body.node().to_string()),
("claimant", body.claimant().to_string()),
("nonce", body.nonce().to_string()),
("expires at", body.expires_at().to_string()),
("base revision", body.base_revision().to_string()),
("config sha256", body.config_sha256().to_string()),
];
self.output.note("claim body:")?;
for (name, value) in fields {
self.output.note(&format!(" {name}: {value}"))?;
}
Ok(())
}
fn print_identity(&self, did: &DidNostr, path: &Path) -> Result<u8, CliError> {
self.output.json(&json!({
"did": did,
"npub": did.to_npub(),
"key_file": path.display().to_string(),
}))?;
self.output.line(&did.to_string())?;
self.output.line(&did.to_npub())?;
Ok(exit::OK)
}
}
pub(crate) fn readyz(client: &Client) -> Result<Readyz, CliError> {
let response: Response = client.get(READYZ, None)?;
let (ready, _raw): (Readyz, Json) = match response.status {
200 | 503 => response.parse()?,
_ => return Err(response.into_error()),
};
if ready.api_version != API_VERSION {
return Err(CliError::Protocol(format!(
"the node speaks API version {}; this client speaks {API_VERSION}",
ready.api_version
)));
}
Ok(ready)
}
pub(crate) fn check_expected_node(
actual: DidNostr,
expected: Option<&DidNostr>,
) -> Result<(), CliError> {
match expected {
Some(expected) if *expected != actual => Err(CliError::Refused(format!(
"the node at this url reports {actual}, not the expected {expected}"
))),
_ => Ok(()),
}
}
fn check_manifest_content(
content: &str,
node: DidNostr,
checkpoint: &str,
) -> Result<BackupManifest, CliError> {
let not_manifest =
|| CliError::Refused("the signed event is not a stratum backup manifest".to_owned());
let value: Json = serde_json::from_str(content).map_err(|_| not_manifest())?;
if value.get("format").and_then(Json::as_str) != Some(BACKUP_FORMAT) {
return Err(not_manifest());
}
let version = value.get("format_version").and_then(Json::as_u64);
let pods = match version {
Some(BACKUP_FORMAT_VERSION) => false,
Some(BACKUP_FORMAT_VERSION_PODS) => true,
_ => {
return Err(CliError::Refused(format!(
"the backup manifest has format version {}; this client reads versions \
{BACKUP_FORMAT_VERSION} and {BACKUP_FORMAT_VERSION_PODS}",
version.map_or_else(|| "none".to_owned(), |v| v.to_string())
)));
}
};
let manifest = BackupManifest::deserialize(&value).map_err(|_| not_manifest())?;
if manifest.format != BACKUP_FORMAT
|| Some(manifest.format_version) != version
|| manifest.pod_archive.is_some() != pods
{
return Err(not_manifest());
}
if manifest.node_did != node {
return Err(CliError::Refused(format!(
"the backup manifest is for node {}, not {node}",
manifest.node_did
)));
}
if manifest.audit_checkpoint != checkpoint {
return Err(CliError::Refused(format!(
"the signed manifest's audit checkpoint {} differs from the reported {checkpoint}",
sanitize(&manifest.audit_checkpoint)
)));
}
let mut expected = BACKUP_FILES.to_vec();
if pods {
expected.push(BACKUP_POD_ARCHIVE);
}
if !manifest
.files
.iter()
.map(|file| file.name.as_str())
.eq(expected.iter().copied())
{
return Err(CliError::Refused(format!(
"the backup manifest does not list exactly {}",
expected.join(", ")
)));
}
Ok(manifest)
}
pub(crate) fn request_preview(
client: &Client,
base_revision: u64,
changes: &[Change],
key: Option<&NostrSecretKey>,
) -> Result<(PreviewResponse, Json), CliError> {
let body = to_body(&PreviewRequest {
base_revision,
changes,
})?;
let (preview, raw): (PreviewResponse, Json) = client.post(PREVIEW, &body, key)?.into_json()?;
if preview.base_revision != base_revision {
return Err(CliError::Protocol(format!(
"preview is against revision {}, not the requested {base_revision}",
preview.base_revision
)));
}
Ok((preview, raw))
}
pub(crate) fn changes_from(sets: &[String]) -> Result<Vec<Change>, CliError> {
let changes = parse_changes(sets).map_err(|err| CliError::Usage(err.to_string()))?;
if changes.is_empty() {
return Err(CliError::Usage(
"give at least one --set path=value".to_owned(),
));
}
Ok(changes)
}
pub(crate) fn to_body<T: Serialize>(request: &T) -> Result<Vec<u8>, CliError> {
serde_json::to_vec(request)
.map_err(|err| CliError::Local(format!("encoding the request failed: {err}")))
}
pub(crate) fn operation_id(given: Option<&str>) -> Result<OperationId, CliError> {
if let Some(text) = given {
return text
.parse()
.map_err(|err| CliError::Usage(format!("--operation-id: {err}")));
}
let random = client::random_32()?;
let text = format!("op-{}", hex::encode(&random[..16]));
text.parse()
.map_err(|err| CliError::Local(format!("generated operation id: {err}")))
}
pub(crate) fn invalid_preview(preview: &PreviewResponse) -> CliError {
CliError::InvalidPreview {
details: preview.errors.iter().map(validation_line).collect(),
}
}
fn validation_line(error: &crate::wire::ValidationEntry) -> String {
match &error.path {
Some(path) => sanitize(&format!("{path}: {}", error.message)),
None => sanitize(&error.message),
}
}
fn compact(value: &Json) -> String {
value.to_string()
}
pub(crate) fn claim_json(body: &ClaimBody) -> Json {
json!({
"nonce": body.nonce(),
"node": body.node(),
"claimant": body.claimant(),
"expires_at": body.expires_at(),
"base_revision": body.base_revision(),
"config_sha256": body.config_sha256(),
})
}
fn is_checkpoint(text: &str) -> bool {
text.split_once(':').is_some_and(|(seq, hash)| {
!seq.is_empty()
&& seq.bytes().all(|b| b.is_ascii_digit())
&& hash.len() == 64
&& hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
})
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::BACKUP_TIMEOUT;
#[test]
fn backup_outwaits_the_nodes_drain_bound() {
assert!(
BACKUP_TIMEOUT > Duration::from_secs(90 + 60),
"the drain bound plus time to snapshot and archive"
);
}
}