Skip to main content

acl_core/
schema.rs

1//! Runtime schema validation (spec §19): validate incoming CL payloads
2//! against a compiled IDL schema BEFORE processing.
3//!
4//! Build time: `aclc gen schema vocab.acl` emits `<ns>.schema.json`.
5//! Runtime: `RuntimeSchema::from_json` loads it; `validate()` checks a
6//! `Body::Cl` payload against the declared vocabulary. This closes the
7//! loop started in §18 — types are enforced at build time AND on the wire.
8
9use crate::cl::ClExpr;
10use serde::{Deserialize, Serialize};
11use std::collections::BTreeMap;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct SchemaOp {
15    /// param name -> primitive or alias type
16    pub params: BTreeMap<String, String>,
17    pub ret: String,
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub doc: Option<String>,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct RuntimeSchema {
24    pub namespace: String,
25    pub version: u32,
26    /// alias -> primitive (resolved at compile time)
27    #[serde(default)]
28    pub aliases: BTreeMap<String, String>,
29    /// local name -> op (full name = namespace.local)
30    pub predicates: BTreeMap<String, SchemaOp>,
31    pub actions: BTreeMap<String, SchemaOp>,
32    /// §31: deprecated terms (full name -> reason)
33    #[serde(default)]
34    pub deprecated: BTreeMap<String, String>,
35}
36
37impl RuntimeSchema {
38    pub fn from_json(bytes: &[u8]) -> Result<Self, String> {
39        serde_json::from_slice(bytes).map_err(|e| format!("bad schema json: {e}"))
40    }
41
42    /// Resolve a type reference (alias or primitive) to its primitive.
43    fn resolve<'a>(&'a self, ty: &'a str) -> Result<&'a str, String> {
44        if crate::idl::PRIMITIVES.contains(&ty) {
45            Ok(ty)
46        } else {
47            self.aliases
48                .get(ty)
49                .map(|s| s.as_str())
50                .ok_or_else(|| format!("unknown type '{ty}'"))
51        }
52    }
53
54    /// Check one JSON value against a declared type. Rules:
55    /// - string  -> is_string
56    /// - int     -> integer (not float)
57    /// - float   -> any number
58    /// - bool    -> is_boolean
59    /// - bytes   -> base64/hex string or array (lenient: any string)
60    /// - timestamp / any -> int / anything
61    fn check_value(&self, ty: &str, v: &serde_json::Value) -> Result<(), String> {
62        let prim = self.resolve(ty)?;
63        let ok = match prim {
64            "string" => v.is_string(),
65            "int" | "timestamp" => v.as_i64().is_some() || v.as_u64().is_some(),
66            "float" => v.is_number(),
67            "bool" => v.is_boolean(),
68            "bytes" => v.is_string() || v.is_array(), // encoded form
69            "any" => true,
70            other => return Err(format!("unresolved primitive '{other}'")),
71        };
72        if ok {
73            Ok(())
74        } else {
75            Err(format!("expected {prim}, got {}", type_of(v)))
76        }
77    }
78
79    fn check_op(
80        &self,
81        kind: &str,
82        table: &BTreeMap<String, SchemaOp>,
83        full_name: &str,
84        params: &serde_json::Value,
85    ) -> Result<(), String> {
86        let local = full_name
87            .strip_prefix(&format!("{}.", self.namespace))
88            .ok_or_else(|| format!("{kind} '{full_name}' is not in namespace '{}'", self.namespace))?;
89        let op = table
90            .get(local)
91            .ok_or_else(|| format!("unknown {kind} '{full_name}'"))?;
92        let obj = params
93            .as_object()
94            .ok_or_else(|| format!("{kind} '{full_name}' params must be an object"))?;
95        // declared params: present + typed
96        for (pname, pty) in &op.params {
97            let v = obj
98                .get(pname)
99                .ok_or_else(|| format!("{kind} '{full_name}' missing param '{pname}'"))?;
100            self.check_value(pty, v).map_err(|e| format!("{kind} '{full_name}' param '{pname}': {e}"))?;
101        }
102        // strict: undeclared params rejected
103        for k in obj.keys() {
104            if !op.params.contains_key(k) {
105                return Err(format!("{kind} '{full_name}' has undeclared param '{k}'"));
106            }
107        }
108        Ok(())
109    }
110
111    /// Validate a CL expression (recursively, §6.3) against the schema.
112    /// `RefExpr` is skipped (it binds to another message's validation).
113    pub fn validate(&self, e: &ClExpr) -> Result<(), String> {
114        match e {
115            ClExpr::Fact { predicate, args, .. } => {
116                let args_val = serde_json::to_value(args).unwrap_or(serde_json::Value::Null);
117                self.check_op("predicate", &self.predicates, predicate, &args_val)
118            }
119            ClExpr::Action { name, params, .. } => {
120                self.check_op("action", &self.actions, name, params)
121            }
122            ClExpr::Query { predicate, args, .. } => {
123                self.check_op("predicate", &self.predicates, predicate, args)
124            }
125            ClExpr::Commitment { act, .. } => self.validate(&ClExpr::Action {
126                name: act.name.clone(),
127                params: act.params.clone(),
128                result_schema: act.result_schema.clone(),
129            }),
130            ClExpr::And { exprs } | ClExpr::Or { exprs } => {
131                for sub in exprs {
132                    self.validate(sub)?;
133                }
134                Ok(())
135            }
136            ClExpr::Not { expr } => self.validate(expr),
137            ClExpr::RefExpr { .. } => Ok(()), // validated where it was produced
138            ClExpr::Bind { expr, body, .. } => {
139                self.validate(expr)?;
140                self.validate(body)
141            }
142            ClExpr::ForAll { over, such_that, .. }
143            | ClExpr::Exists { over, such_that, .. } => {
144                self.validate(over)?;
145                self.validate(such_that)
146            }
147            ClExpr::Believes { fact, .. } => self.validate(fact),
148            // §29: renew targets a prior message — nothing to validate here
149            ClExpr::Renew { .. } => Ok(()),
150            // §32: conditional commitment validates its condition + act
151            ClExpr::ConditionalCommitment { condition, act, .. } => {
152                self.validate(condition)?;
153                self.validate(&ClExpr::Action {
154                    name: act.name.clone(),
155                    params: act.params.clone(),
156                    result_schema: act.result_schema.clone(),
157                })
158            }
159            // §32: preference criteria are policy facts — validated
160            ClExpr::Prefer { criteria } => {
161                for c in criteria {
162                    self.validate(c)?;
163                }
164                Ok(())
165            }
166        }
167    }
168
169    /// §31: validate and COLLECT deprecation warnings. Returns
170    /// (validation_result, warnings). Warnings don't fail validation —
171    /// deprecated terms still work until the vocabulary's major bump.
172    pub fn validate_with_warnings(
173        &self,
174        exprs: &[ClExpr],
175    ) -> (Result<(), Vec<String>>, Vec<String>) {
176        let result = self.validate_all(exprs);
177        let mut warnings = Vec::new();
178        for e in exprs {
179            collect_dep_warnings(e, &self.deprecated, &self.namespace, &mut warnings);
180        }
181        (result, warnings)
182    }
183
184    /// Validate every expression of a Cl body.
185    pub fn validate_all(&self, exprs: &[ClExpr]) -> Result<(), Vec<String>> {
186        let mut errors = Vec::new();
187        for e in exprs {
188            if let Err(msg) = self.validate(e) {
189                errors.push(msg);
190            }
191        }
192        if errors.is_empty() {
193            Ok(())
194        } else {
195            Err(errors)
196        }
197    }
198}
199
200/// Walk expressions collecting deprecation warnings for used terms.
201fn collect_dep_warnings(
202    e: &ClExpr,
203    deprecated: &BTreeMap<String, String>,
204    namespace: &str,
205    out: &mut Vec<String>,
206) {
207    fn check_term(term: &str, deprecated: &BTreeMap<String, String>, out: &mut Vec<String>) {
208        if let Some(reason) = deprecated.get(term) {
209            out.push(format!("{term} is deprecated: {reason}"));
210        }
211    }
212    match e {
213        ClExpr::Fact { predicate, .. } => check_term(predicate, deprecated, out),
214        ClExpr::Action { name, .. } => check_term(name, deprecated, out),
215        ClExpr::Query { predicate, .. } => check_term(predicate, deprecated, out),
216        ClExpr::Commitment { act, .. } => check_term(&act.name, deprecated, out),
217        ClExpr::And { exprs } | ClExpr::Or { exprs } => {
218            for sub in exprs {
219                collect_dep_warnings(sub, deprecated, namespace, out);
220            }
221        }
222        ClExpr::Not { expr } | ClExpr::Bind { body: expr, .. } => {
223            collect_dep_warnings(expr, deprecated, namespace, out)
224        }
225        ClExpr::ForAll { over, such_that, .. }
226        | ClExpr::Exists { over, such_that, .. } => {
227            collect_dep_warnings(over, deprecated, namespace, out);
228            collect_dep_warnings(such_that, deprecated, namespace, out);
229        }
230        ClExpr::Believes { fact, .. } => {
231            collect_dep_warnings(fact, deprecated, namespace, out)
232        }
233        ClExpr::ConditionalCommitment { condition, act, .. } => {
234            collect_dep_warnings(condition, deprecated, namespace, out);
235            check_term(&act.name, deprecated, out);
236        }
237        ClExpr::Prefer { criteria } => {
238            for c in criteria {
239                collect_dep_warnings(c, deprecated, namespace, out);
240            }
241        }
242        ClExpr::Renew { .. } | ClExpr::RefExpr { .. } => {}
243    }
244}
245
246fn type_of(v: &serde_json::Value) -> &'static str {
247    match v {
248        serde_json::Value::Null => "null",
249        serde_json::Value::Bool(_) => "bool",
250        serde_json::Value::Number(n) => {
251            if n.is_f64() {
252                "float"
253            } else {
254                "int"
255            }
256        }
257        serde_json::Value::String(_) => "string",
258        serde_json::Value::Array(_) => "array",
259        serde_json::Value::Object(_) => "object",
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use crate::cl::ClAction;
267    use std::collections::BTreeMap;
268
269    fn schema() -> RuntimeSchema {
270        RuntimeSchema {
271            namespace: "acl.std.fs".into(),
272            version: 1,
273            aliases: BTreeMap::from([("Path".to_string(), "string".to_string())]),
274            predicates: BTreeMap::from([(
275                "file_exists".to_string(),
276                SchemaOp {
277                    params: BTreeMap::from([("path".to_string(), "Path".to_string())]),
278                    ret: "bool".into(),
279                    doc: None,
280                },
281            )]),
282            actions: BTreeMap::from([(
283                "file_read".to_string(),
284                SchemaOp {
285                    params: BTreeMap::from([("path".to_string(), "Path".to_string())]),
286                    ret: "string".into(),
287                    doc: None,
288                },
289            )]),
290            deprecated: BTreeMap::new(),
291        }
292    }
293
294    #[test]
295    fn valid_fact_and_action() {
296        let s = schema();
297        assert!(s
298            .validate(&ClExpr::fact(
299                "acl.std.fs.file_exists",
300                serde_json::json!({"path": "/tmp/x"})
301            ))
302            .is_ok());
303        assert!(s
304            .validate(&ClExpr::Action {
305                name: "acl.std.fs.file_read".into(),
306                params: serde_json::json!({"path": "/tmp/x"}),
307                result_schema: None,
308            })
309            .is_ok());
310    }
311
312    #[test]
313    fn missing_param_wrong_type_extra_param() {
314        let s = schema();
315        // missing param
316        assert!(s.validate(&ClExpr::fact("acl.std.fs.file_exists", serde_json::json!({}))).is_err());
317        // wrong type (int for Path)
318        assert!(s
319            .validate(&ClExpr::fact("acl.std.fs.file_exists", serde_json::json!({"path": 42})))
320            .is_err());
321        // extra undeclared param
322        assert!(s
323            .validate(&ClExpr::fact(
324                "acl.std.fs.file_exists",
325                serde_json::json!({"path": "/x", "mode": "rw"})
326            ))
327            .is_err());
328        // unknown predicate
329        assert!(s.validate(&ClExpr::fact("acl.std.fs.nothing", serde_json::json!({}))).is_err());
330        // foreign namespace
331        assert!(s.validate(&ClExpr::fact("other.ns.f", serde_json::json!({}))).is_err());
332    }
333
334    #[test]
335    fn alias_and_composition_recursion() {
336        let s = schema();
337        // 'Path' alias resolves to string — value must be a string
338        assert!(s.validate(&ClExpr::fact("acl.std.fs.file_exists", serde_json::json!({"path": "ok"}))).is_ok());
339        // composition recursion: valid inside and()
340        assert!(s
341            .validate(&ClExpr::and(vec![
342                ClExpr::fact("acl.std.fs.file_exists", serde_json::json!({"path": "/x"})),
343                ClExpr::not(ClExpr::fact("acl.std.fs.file_exists", serde_json::json!({"path": "/y"}))),
344            ]))
345            .is_ok());
346        // invalid leaf inside and() surfaces
347        let errs = s
348            .validate_all(&[ClExpr::and(vec![ClExpr::fact(
349                "acl.std.fs.file_exists",
350                serde_json::json!({"path": 99}),
351            )])])
352            .unwrap_err();
353        assert!(errs[0].contains("expected string"));
354    }
355
356    #[test]
357    fn commitment_validates_its_act() {
358        let s = schema();
359        let c = ClExpr::Commitment {
360            debtor: "a".into(),
361            creditor: "b".into(),
362            act: ClAction {
363                name: "acl.std.fs.file_read".into(),
364                params: serde_json::json!({"path": "/x"}),
365                result_schema: None,
366                partial: None,
367            },
368            deadline_ms: None,
369            status: crate::cl::CommitmentStatus::Proposed,
370        };
371        assert!(s.validate(&c).is_ok());
372        let bad = ClExpr::Commitment {
373            debtor: "a".into(),
374            creditor: "b".into(),
375            act: ClAction {
376                name: "acl.std.fs.file_read".into(),
377                params: serde_json::json!({"path": 7}),
378                result_schema: None,
379                partial: None,
380            },
381            deadline_ms: None,
382            status: crate::cl::CommitmentStatus::Proposed,
383        };
384        assert!(s.validate(&bad).is_err());
385    }
386
387    #[test]
388    fn json_roundtrip() {
389        let s = schema();
390        let json = serde_json::to_vec(&s).unwrap();
391        let s2 = RuntimeSchema::from_json(&json).unwrap();
392        assert_eq!(s.namespace, s2.namespace);
393        assert!(s2.validate(&ClExpr::fact("acl.std.fs.file_exists", serde_json::json!({"path": "/x"}))).is_ok());
394    }
395}