use serde_json::{json, Value};
use crate::error::{CoreError, Result};
pub const ENV_VAR: &str = "VOUCH_TRUSTED_ROOTS";
use crate::did_web::py_space;
fn py_line_break(c: char) -> bool {
matches!(
c,
'\n' | '\r'
| '\u{0b}'
| '\u{0c}'
| '\u{1c}'
| '\u{1d}'
| '\u{1e}'
| '\u{85}'
| '\u{2028}'
| '\u{2029}'
)
}
fn py_splitlines(text: &str) -> Vec<&str> {
let mut lines = Vec::new();
let mut start = 0;
let mut chars = text.char_indices().peekable();
while let Some((i, c)) = chars.next() {
if py_line_break(c) {
lines.push(&text[start..i]);
let mut end = i + c.len_utf8();
if c == '\r' {
if let Some(&(j, '\n')) = chars.peek() {
chars.next();
end = j + 1;
}
}
start = end;
}
}
if start < text.len() {
lines.push(&text[start..]);
}
lines
}
pub fn roots_from_text(text: &str) -> Vec<String> {
let mut roots: Vec<String> = Vec::new();
for line in py_splitlines(text) {
let entry = line.trim_matches(py_space);
if entry.is_empty() || entry.starts_with('#') {
continue;
}
if let Ok(root) = crate::did_web::normalize_root(entry) {
if !roots.contains(&root) {
roots.push(root);
}
}
}
roots
}
pub fn roots_from_env(value: &str) -> Vec<String> {
roots_from_text(&value.replace(',', "\n"))
}
pub fn default_roots(env: Option<&str>, saved: Option<&str>) -> Option<Vec<String>> {
let roots = match env {
Some(v) => roots_from_env(v),
None => saved.map(roots_from_text).unwrap_or_default(),
};
(!roots.is_empty()).then_some(roots)
}
pub fn default_roots_json(request: &Value) -> Result<Value> {
let obj = request
.as_object()
.ok_or_else(|| CoreError::Json("the request must be a JSON object".into()))?;
let text = |name: &str| match obj.get(name) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s.as_str())),
Some(_) => Err(CoreError::Json(format!("{name} must be text or null"))),
};
Ok(json!({"roots": default_roots(text("env")?, text("saved")?)}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splits_like_python() {
assert_eq!(py_splitlines("a\r\nb\rc\n"), vec!["a", "b", "c"]);
assert_eq!(py_splitlines("a\u{2028}b"), vec!["a", "b"]);
assert_eq!(py_splitlines(""), Vec::<&str>::new());
assert_eq!(py_splitlines("\n"), vec![""]);
}
#[test]
fn env_set_to_nothing_wins_over_saved() {
assert_eq!(default_roots(Some(""), Some("example.com")), None);
assert_eq!(
default_roots(None, Some("example.com\n# note\nexample.com")),
Some(vec!["did:web:example.com".to_string()])
);
}
}