Skip to main content

zero_client/ast/
strict.rs

1//! `strictASTSchema` (`packages/zero-protocol/src/ast.ts`), for ASTs a client
2//! sends: nested at most [`MAX_DEPTH`] deep, and parsed in valita's `strict`
3//! mode even inside a lenient parse, so an AST with a key zero doesn't know
4//! is rejected rather than run as a different query.
5
6use super::Ast;
7use crate::decode::{DecodeError, JsonCodable, Result};
8use crate::json::{Object, Value};
9
10/// `MAX_AST_DEPTH`.
11pub const MAX_DEPTH: usize = 50;
12
13pub fn decode(v: &Value) -> Result<Ast> {
14    if exceeds_depth(v, MAX_DEPTH) {
15        return Err(DecodeError::new(format!(
16            "AST exceeds the maximum depth of {MAX_DEPTH}"
17        )));
18    }
19    check_ast(v)?;
20    Ast::from_json(v)
21}
22
23/// `isPlainObject` (`packages/shared/src/deep-merge.ts`) is true for arrays
24/// too; they have none of the keys looked at.
25fn plain_object(v: Option<&Value>) -> Option<Option<&Object>> {
26    match v {
27        Some(Value::Object(o)) => Some(Some(o)),
28        Some(Value::Array(_)) => Some(None),
29        _ => None,
30    }
31}
32
33/// `exceedsASTDepth`: every step down counts, except the one from an AST
34/// into its where clause.
35pub fn exceeds_depth(ast: &Value, max_depth: usize) -> bool {
36    ast_exceeds(Some(ast), 0, max_depth)
37}
38
39fn ast_exceeds(ast: Option<&Value>, depth: usize, max: usize) -> bool {
40    if depth > max {
41        return true;
42    }
43    let Some(o) = plain_object(ast) else {
44        return false;
45    };
46    let Some(o) = o else { return false };
47    if condition_exceeds(o.get("where"), depth, max) {
48        return true;
49    }
50    let Some(Value::Array(related)) = o.get("related") else {
51        return false;
52    };
53    related.iter().any(|r| match plain_object(Some(r)) {
54        Some(Some(r)) => ast_exceeds(r.get("subquery"), depth + 1, max),
55        _ => false,
56    })
57}
58
59fn condition_exceeds(cond: Option<&Value>, depth: usize, max: usize) -> bool {
60    if depth > max {
61        return true;
62    }
63    let Some(Some(o)) = plain_object(cond) else {
64        return false;
65    };
66    if let Some(Value::Array(conditions)) = o.get("conditions")
67        && conditions
68            .iter()
69            .any(|c| condition_exceeds(Some(c), depth + 1, max))
70    {
71        return true;
72    }
73    match plain_object(o.get("related")) {
74        Some(Some(r)) => ast_exceeds(r.get("subquery"), depth + 1, max),
75        _ => false,
76    }
77}
78
79// The keys each object of the AST may have. `Ast::from_json` checks the
80// values; this only rejects the keys `strict` mode would.
81
82fn only(o: &Object, keys: &[&str]) -> Result<()> {
83    match o.keys().find(|k| !keys.contains(&k.as_str())) {
84        Some(k) => Err(DecodeError::new("Unexpected key").at(k.clone())),
85        None => Ok(()),
86    }
87}
88
89fn check_ast(v: &Value) -> Result<()> {
90    let Value::Object(o) = v else { return Ok(()) };
91    only(
92        o,
93        &[
94            "schema",
95            "table",
96            "alias",
97            "where",
98            "related",
99            "limit",
100            "orderBy",
101            "start",
102            "aggregate",
103            "groupBy",
104        ],
105    )?;
106    if let Some(a) = o.get("aggregate") {
107        check_aggregate(a)?;
108    }
109    if let Some(w) = o.get("where") {
110        check_condition(w)?;
111    }
112    if let Some(Value::Array(related)) = o.get("related") {
113        for r in related {
114            check_correlated_subquery(r)?;
115        }
116    }
117    if let Some(Value::Object(start)) = o.get("start") {
118        only(start, &["row", "exclusive"])?;
119    }
120    Ok(())
121}
122
123fn check_correlated_subquery(v: &Value) -> Result<()> {
124    let Value::Object(o) = v else { return Ok(()) };
125    only(
126        o,
127        &["correlation", "hidden", "system", "subquery", "aggregate"],
128    )?;
129    if let Some(a) = o.get("aggregate") {
130        check_aggregate(a)?;
131    }
132    if let Some(Value::Object(c)) = o.get("correlation") {
133        only(c, &["parentField", "childField"])?;
134    }
135    if let Some(s) = o.get("subquery") {
136        check_ast(s)?;
137    }
138    Ok(())
139}
140
141fn check_aggregate(v: &Value) -> Result<()> {
142    match v {
143        Value::Object(o) => only(o, &["fn", "field", "path", "distinct"]),
144        _ => Ok(()),
145    }
146}
147
148fn check_condition(v: &Value) -> Result<()> {
149    let Value::Object(o) = v else { return Ok(()) };
150    match o.get("type").and_then(Value::as_str) {
151        Some("simple") => {
152            only(o, &["type", "op", "left", "right"])?;
153            if let Some(l) = o.get("left") {
154                check_value_position(l)?;
155            }
156            if let Some(r) = o.get("right") {
157                check_value_position(r)?;
158            }
159        }
160        Some("and" | "or") => {
161            only(o, &["type", "conditions"])?;
162            if let Some(Value::Array(conditions)) = o.get("conditions") {
163                for c in conditions {
164                    check_condition(c)?;
165                }
166            }
167        }
168        Some("correlatedSubquery") => {
169            only(o, &["type", "related", "op", "flip", "scalar"])?;
170            if let Some(r) = o.get("related") {
171                check_correlated_subquery(r)?;
172            }
173        }
174        _ => {}
175    }
176    Ok(())
177}
178
179fn check_value_position(v: &Value) -> Result<()> {
180    let Value::Object(o) = v else { return Ok(()) };
181    match o.get("type").and_then(Value::as_str) {
182        Some("literal") => only(o, &["type", "value"]),
183        Some("column") => only(o, &["type", "name"]),
184        Some("json") => {
185            only(o, &["type", "value", "path"])?;
186            match o.get("value") {
187                Some(c) => check_value_position(c),
188                None => Ok(()),
189            }
190        }
191        Some("static") => only(o, &["type", "anchor", "field"]),
192        _ => Ok(()),
193    }
194}