use datumesh_core::json::{self, Value};
use datumesh_core::{key_document_from_response, ErrorCode};
use datumesh_store::{Error as StoreError, Store};
use crate::client::Client;
const MAX_DOC: u64 = 256 << 10;
pub const SUSPEND_AFTER: u32 = 2;
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Outcome {
Valid,
Invalid {
code: ErrorCode,
detail: String,
},
Skipped,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Validation {
pub host: String,
pub outcome: Outcome,
pub failures: u32,
pub suspended: bool,
pub suspended_now: bool,
pub reinstated: bool,
pub rotated: bool,
}
impl Validation {
fn new(host: &str, outcome: Outcome) -> Validation {
Validation {
host: host.to_string(),
outcome,
failures: 0,
suspended: false,
suspended_now: false,
reinstated: false,
rotated: false,
}
}
pub fn failed(&self) -> bool {
matches!(self.outcome, Outcome::Invalid { .. })
}
pub fn to_json(&self) -> Vec<u8> {
let b = |v: bool| Value::Bool(v);
let mut m = vec![
("failures".to_string(), json::parse(self.failures.to_string().as_bytes()).unwrap_or(Value::Null)),
("host".to_string(), Value::String(self.host.clone())),
("reinstated".to_string(), b(self.reinstated)),
("rotated".to_string(), b(self.rotated)),
("suspended".to_string(), b(self.suspended)),
("suspended_now".to_string(), b(self.suspended_now)),
];
let outcome = match &self.outcome {
Outcome::Valid => "valid",
Outcome::Skipped => "skipped",
Outcome::Invalid { code, detail } => {
m.push(("code".to_string(), Value::String(code.as_str().to_string())));
m.push(("detail".to_string(), Value::String(detail.clone())));
"invalid"
}
};
m.push(("outcome".to_string(), Value::String(outcome.to_string())));
Value::Object(m).to_jcs()
}
}
#[derive(Debug)]
pub struct Validator {
client: Client,
own: Vec<String>,
}
impl Validator {
pub fn new(client: Client, own: Vec<String>) -> Validator {
Validator { client, own }
}
fn fetch(&self, host: &str) -> Result<Vec<u8>, (ErrorCode, String)> {
let url = format!("https://{host}/.well-known/datumesh.json");
let (status, body) = self.client.get(&url, MAX_DOC).map_err(|e| (ErrorCode::KeyUnavailable, e))?;
key_document_from_response(host, status, if status == 200 { Some(&body) } else { None })
.map_err(|e| (e.code(), e.to_string()))?;
Ok(body)
}
pub fn validate(&self, store: &dyn Store, host: &str, now: &str) -> Result<Validation, StoreError> {
datumesh_core::lexical::check_dns_name(host, "host")?;
if self.own.iter().any(|h| h == host) {
return Ok(Validation::new(host, Outcome::Skipped));
}
let before = store.namespace(host)?;
match self.fetch(host) {
Ok(body) => {
let canonical = json::parse(&body)?.to_jcs();
let rotated = before.as_ref().is_some_and(|n| n.keydoc != canonical);
store.put_namespace(host, &body, now)?;
store.record_namespace_success(host, now)?;
let mut v = Validation::new(host, Outcome::Valid);
v.rotated = rotated;
v.reinstated = before.as_ref().is_some_and(|n| n.suspended_at.is_some());
Ok(v)
}
Err((code, detail)) => {
let mut v = Validation::new(host, Outcome::Invalid { code, detail });
if let Some(after) = store.record_namespace_failure(host, now, SUSPEND_AFTER)? {
v.failures = after.consecutive_failures;
v.suspended = after.suspended_at.is_some();
v.suspended_now = v.suspended && before.as_ref().is_some_and(|n| n.suspended_at.is_none());
}
Ok(v)
}
}
}
pub fn validate_all(&self, store: &dyn Store, now: &str) -> Result<Vec<Validation>, StoreError> {
store.namespaces()?.iter().map(|n| self.validate(store, &n.host, now)).collect()
}
}