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};
const RESUME_SUFFIX: &str = ".setup-resume";
impl Session {
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)
}
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,
}
})?;
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)
}
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)
}
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
))?;
Ok(json!({
"administrator": claimed.administrator,
"node_did": claimed.node_did,
"revision": claimed.revision,
"public_config_hash": claimed.public_config_hash,
}))
}
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()
))
}
}
const SEED_REVISION: u64 = 0;
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))
}
fn discard(resume_path: &Path) -> Result<(), CliError> {
private_file::remove(resume_path).map_err(|source| CliError::File {
path: resume_path.to_owned(),
source,
})
}
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)
}
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)
}