ifc_lite_diff/
sidecar_validation.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4//! Structural validation of untrusted sidecar JSON. The host supplies its date
5//! parser predicate: the JS facade uses Date.parse, including legacy formats.
6use std::collections::{HashMap, HashSet};
7use crate::sidecar_value::{DocumentValue as Value, JsString};
8
9fn string_list(v: &Value) -> bool {
10    v.as_array().is_some_and(|a| a.iter().all(|v| v.as_string().is_some_and(|s| !s.is_empty())))
11}
12fn common(value: &Value, lineage: bool, valid_date: &impl Fn(&str) -> bool) -> Vec<JsString> {
13    let mut errors = vec![];
14    let format = if lineage { "ifc-lite/lineage" } else { "ifc-lite/identity-map" };
15    if value["format"].as_str() != Some(format) { errors.push(format!("format must be \"{format}\"").into()); }
16    let version = value["version"].as_f64();
17    if version != Some(1.0) && version != Some(2.0) { errors.push("version must be 1 or 2".into()); }
18    else if lineage {
19        if version == Some(2.0) && value.get("keyProperty").is_none() { errors.push("version 2 requires keyProperty".into()); }
20    } else if value.get("keyProperty").is_some() != (version == Some(2.0)) {
21        errors.push("version 2 requires keyProperty and version 1 forbids it".into());
22    }
23    for side in ["base","head"] {
24        let v = &value[side];
25        if !v.is_object() { errors.push(format!("{side} must be {{ hash, path? }}").into()); continue; }
26        if v["hash"].as_string().is_none_or(|s| s.is_empty()) { errors.push(format!("{side}.hash must be a non-empty content digest").into()); }
27        if v.get("path").is_some_and(|v| !v.is_string()) { errors.push(format!("{side}.path must be a string when present").into()); }
28    }
29    if let Some(created) = value.get("created") {
30        if !created.as_str().is_some_and(valid_date) { errors.push("created must be an ISO 8601 timestamp when present".into()); }
31    }
32    if let Some(key) = value.get("keyProperty") {
33        if key.as_string().is_none_or(|s| s.is_blank()) {
34            errors.push("keyProperty must be a non-empty string when present".into());
35        }
36    }
37    errors
38}
39pub(crate) fn validate_identity_document(value: &Value, valid_date: impl Fn(&str) -> bool) -> Vec<JsString> {
40    if !value.is_object() { return vec!["sidecar must be an object".into()]; }
41    let mut errors = common(value, false, &valid_date);
42    let Some(entries) = value["entries"].as_array() else { errors.push("entries must be an array".into()); return errors; };
43    let mut claimed = HashMap::new();
44    let mut conflicts = HashSet::new();
45    for entry in entries {
46        if !entry.is_object() || !["base","here","reason"].iter().all(|k| entry[*k].is_string()) {
47            errors.push("entries must be { base, here, reason } with string fields".into());
48            return errors;
49        }
50        let base = entry["base"].as_string().unwrap();
51        let here = entry["here"].as_string().unwrap();
52        if let Some(previous) = claimed.get(here) {
53            if *previous != base { conflicts.insert(here); }
54        } else { claimed.insert(here,base); }
55    }
56    let mut conflicts: Vec<_> = conflicts.into_iter().collect();
57    conflicts.sort();
58    errors.extend(conflicts.into_iter().map(|here| JsString::surround("entries claim two different base identities for here \"", here, "\"")));
59    errors
60}
61fn validate_lineage_entry(entry: &Value) -> Option<JsString> {
62    let error = if !entry.is_object() { "entries must be { base[], head[], relation, reason, shares? } objects" }
63    else if !string_list(&entry["base"]) || !string_list(&entry["head"]) { "entries must carry non-empty string lists for base and head" }
64    else if entry["base"].as_array().unwrap().is_empty() || entry["head"].as_array().unwrap().is_empty() { "an entry must name at least one key on each side" }
65    else if !matches!(entry["relation"].as_str(), Some("identity"|"split"|"merge"|"replaced")) { "entries must carry a relation of identity | split | merge | replaced" }
66    else if !entry["reason"].is_string() { "entries must carry a string reason" }
67    else {
68        let base = entry["base"].as_array().unwrap().len();
69        let head = entry["head"].as_array().unwrap().len();
70        let relation = entry["relation"].as_str().unwrap();
71        if matches!(relation,"identity"|"replaced") && (base != 1 || head != 1) { return Some(format!("a {relation} entry must be 1:1").into()); }
72        if relation == "split" && base != 1 { return Some("a split entry must have exactly one base key".into()); }
73        if relation == "merge" && head != 1 { return Some("a merge entry must have exactly one head key".into()); }
74        if let Some(shares) = entry.get("shares") {
75            let expected = match relation { "split"=>Some(head),"merge"=>Some(base),_=>None };
76            if !shares.as_array().is_some_and(|a| Some(a.len()) == expected && a.iter().all(|v| v.as_f64().is_some_and(|n| n.is_finite() && n >= 0.0))) {
77                return Some("shares must be one finite non-negative number per key on the k side of a split or merge".into());
78            }
79        }
80        return None;
81    };
82    Some(error.into())
83}
84pub(crate) fn validate_lineage_document(value: &Value, valid_date: impl Fn(&str) -> bool) -> Vec<JsString> {
85    if !value.is_object() { return vec!["sidecar must be an object".into()]; }
86    let mut errors = common(value,true,&valid_date);
87    if let Some(entries) = value["entries"].as_array() {
88        if let Some(problem) = entries.iter().find_map(validate_lineage_entry) { errors.push(problem); }
89        else {
90            for side in ["base","head"] {
91                let mut seen = HashSet::new(); let mut repeated = HashSet::new();
92                for entry in entries { for key in entry[side].as_array().unwrap() {
93                    let key = key.as_string().unwrap(); if !seen.insert(key) { repeated.insert(key); }
94                } }
95                let mut repeated: Vec<_> = repeated.into_iter().collect(); repeated.sort();
96                errors.extend(repeated.into_iter().map(|key| JsString::surround(&format!("{side} key \""), key, "\" appears in more than one lineage entry")));
97            }
98        }
99    } else { errors.push("entries must be an array".into()); }
100    if !string_list(&value["deleted"]) { errors.push("deleted must be a list of non-empty strings".into()); }
101    else if let Some(entries) = value["entries"].as_array() {
102        let keys: HashSet<_> = entries.iter().flat_map(|e| e.get("base").and_then(Value::as_array).into_iter().flatten()).filter_map(Value::as_string).collect();
103        let mut both: Vec<_> = value["deleted"].as_array().unwrap().iter().filter_map(Value::as_string).filter(|key|keys.contains(key)).collect();
104        both.sort();
105        errors.extend(both.into_iter().map(|key| JsString::surround("deleted key \"", key, "\" also appears in a lineage entry")));
106    }
107    errors
108}
109
110/// Validate a scalar-only JSON value supplied by a native caller.
111pub fn validate_identity_sidecar(value: &serde_json::Value, valid_date: impl Fn(&str) -> bool) -> Vec<String> {
112    validate_identity_document(&value.into(), valid_date).into_iter().map(|s| s.to_string()).collect()
113}
114/// Validate a scalar-only JSON value supplied by a native caller.
115pub fn validate_lineage_sidecar(value: &serde_json::Value, valid_date: impl Fn(&str) -> bool) -> Vec<String> {
116    validate_lineage_document(&value.into(), valid_date).into_iter().map(|s| s.to_string()).collect()
117}