use std::path::{Path, PathBuf};
use rustls::RootCertStore;
use serde_json::json;
use crate::channel::material::{self, Material};
use crate::cli::Verdict;
mod entry;
mod https;
mod key;
mod url;
pub use https::web_roots;
pub const WORD: &str = "register";
pub const WORD_LINE: &str = "Confirmation word";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Registered {
pub workspace: String,
pub name: String,
pub grade: String,
pub word: String,
pub entry: PathBuf,
pub addresses: Vec<String>,
pub proved: Result<(), String>,
}
impl Registered {
pub fn said(&self) -> String {
let proved = match &self.proved {
Ok(()) => "Waiting for approval: the server has heard this box and will refuse it \
until the offer is approved."
.to_owned(),
Err(why) => format!(
"The server has not heard this box yet, so the offer cannot be approved: {why}. \
The entry is filed; any `lernie` command that reaches that server will do it."
),
};
format!(
"Registered as {} ({}) in workspace {}. The entry is filed at {}.\n\
{WORD_LINE}: {}\n\
On a seat that is already connected, approve the offer whose row shows that word: \
`lernie approve {} {}`, or Settings › Servers › offers.\n\
{proved}",
self.name,
self.grade,
self.workspace,
self.entry.display(),
self.word,
self.workspace,
self.name
)
}
}
pub fn claim(data_root: &Path, url: &str, roots: RootCertStore) -> Result<Registered, String> {
let offer = url::parse(url)?;
let made = key::make()?;
let body = json!({ "public_key": key::pem("PUBLIC KEY", &made.spki) }).to_string();
let answer = https::post(&offer, &body, roots)?;
if answer.status != 200 {
return Err(format!(
"this offer cannot be claimed: {} answered {}. The code is unknown, expired or \
already used — a registration URL works once. Ask for a new offer.",
offer.authority(),
answer.status
));
}
let claimed = entry::read(&answer.body)?;
let word = key::word(&made.spki, &claimed.ca)?;
let dir = entry::file(data_root, &claimed, &key::pem("PRIVATE KEY", &made.pkcs8))?;
Ok(Registered {
proved: prove(&dir, &claimed.addresses),
workspace: claimed.workspace,
name: claimed.name,
grade: claimed.grade,
word,
entry: dir,
addresses: claimed.addresses,
})
}
fn prove(dir: &Path, addresses: &[String]) -> Result<(), String> {
let held = Material {
anchors: dir.join(material::ANCHORS),
chain: dir.join(material::CHAIN),
key: dir.join(material::KEY),
addresses: addresses.to_vec(),
};
crate::channel::Channel::open(&held)?
.ask(&crate::verbs::workspaces())
.map(|_| ())
.map_err(|reach| reach.said())
}
pub fn register(data_root: &Path, url: &str, roots: RootCertStore) -> Verdict {
match claim(data_root, url, roots) {
Ok(registered) => Verdict::ok(registered.said()),
Err(refusal) => Verdict::failed(refusal),
}
}
#[cfg(test)]
mod tests;