Skip to main content

rcp/
filter.rs

1//! Build and validate RCP metadata filter trees (spec §8).
2//!
3//! Two jobs, one canonical implementation shared by every RCP peer:
4//!
5//! * **Builder** (client side): compose a filter tree with typed helpers instead
6//!   of hand-writing [`Json`], so a bad operator or shape is impossible to build.
7//!
8//!   ```
9//!   use rcp::filter;
10//!   let flt = filter::eq("lang", "en").and(filter::gte("year", 2015));
11//!   let _wire = flt.to_json();
12//!   ```
13//!
14//! * **Validator** (server side): turn an arbitrary incoming filter into either a
15//!   clean normalized tree or a precise [`RcpError`] `-32602` naming the offending
16//!   path — so no server hand-parses a tree and re-introduces a panic/`unwrap` leak.
17//!
18//!   ```
19//!   use rcp::{filter, Json};
20//!   let fields = [("year", "int"), ("lang", "keyword")];
21//!   let params_filter: Option<&Json> = None;
22//!   let _tree = filter::validate(params_filter, Some(&fields), None, 32)?;
23//!   # Ok::<(), rcp::RcpError>(())
24//!   ```
25//!
26//! Wire format is unchanged: a nested tree of `{and|or|not: …}` combinators over
27//! `{field, op, value}` leaves (spec §8).
28
29use crate::json::{obj, Json};
30use crate::types::{Errc, RcpError};
31
32/// Scalar comparison operators (spec §8).
33pub const SCALAR_OPS: [&str; 6] = ["eq", "ne", "gt", "gte", "lt", "lte"];
34/// Set-membership operators.
35pub const ARRAY_OPS: [&str; 2] = ["in", "nin"];
36/// Presence operator.
37pub const UNARY_OPS: [&str; 1] = ["exists"];
38/// Substring / element-membership operator.
39pub const STRING_OPS: [&str; 1] = ["contains"];
40
41const ORDERED_OPS: [&str; 4] = ["gt", "gte", "lt", "lte"];
42const ORDERED_TYPES: [&str; 3] = ["int", "float", "date"];
43
44fn is_known_op(op: &str) -> bool {
45    SCALAR_OPS.contains(&op)
46        || ARRAY_OPS.contains(&op)
47        || UNARY_OPS.contains(&op)
48        || STRING_OPS.contains(&op)
49}
50
51// ── Builder ──────────────────────────────────────────────────────────────────
52
53/// An immutable filter tree node. Combine with [`Filter::and`] / [`Filter::or`] /
54/// [`Filter::not`] and emit the wire form with [`Filter::to_json`].
55#[derive(Clone, Debug)]
56pub struct Filter(Json);
57
58impl Filter {
59    /// The spec §8 wire object. Always a fresh clone — safe to embed.
60    pub fn to_json(&self) -> Json {
61        self.0.clone()
62    }
63
64    /// Boolean AND of `self` and `other`.
65    pub fn and(self, other: Filter) -> Filter {
66        all([self, other])
67    }
68
69    /// Boolean OR of `self` and `other`.
70    pub fn or(self, other: Filter) -> Filter {
71        any([self, other])
72    }
73
74    /// Boolean NOT of `self`. Also available as `!filter` via [`std::ops::Not`].
75    pub fn negate(self) -> Filter {
76        Filter(obj(&[("not", self.0)]))
77    }
78}
79
80impl std::ops::Not for Filter {
81    type Output = Filter;
82    fn not(self) -> Filter {
83        self.negate()
84    }
85}
86
87impl std::ops::BitAnd for Filter {
88    type Output = Filter;
89    fn bitand(self, rhs: Filter) -> Filter {
90        self.and(rhs)
91    }
92}
93
94impl std::ops::BitOr for Filter {
95    type Output = Filter;
96    fn bitor(self, rhs: Filter) -> Filter {
97        self.or(rhs)
98    }
99}
100
101fn leaf(field: &str, op: &str, value: Json) -> Filter {
102    Filter(obj(&[
103        ("field", Json::from(field)),
104        ("op", Json::from(op)),
105        ("value", value),
106    ]))
107}
108
109/// `field == value`.
110pub fn eq(field: &str, value: impl Into<Json>) -> Filter {
111    leaf(field, "eq", value.into())
112}
113/// `field != value`.
114pub fn ne(field: &str, value: impl Into<Json>) -> Filter {
115    leaf(field, "ne", value.into())
116}
117/// `field > value`.
118pub fn gt(field: &str, value: impl Into<Json>) -> Filter {
119    leaf(field, "gt", value.into())
120}
121/// `field >= value`.
122pub fn gte(field: &str, value: impl Into<Json>) -> Filter {
123    leaf(field, "gte", value.into())
124}
125/// `field < value`.
126pub fn lt(field: &str, value: impl Into<Json>) -> Filter {
127    leaf(field, "lt", value.into())
128}
129/// `field <= value`.
130pub fn lte(field: &str, value: impl Into<Json>) -> Filter {
131    leaf(field, "lte", value.into())
132}
133
134/// `field ∈ values` (set membership).
135pub fn in_(field: &str, values: impl IntoIterator<Item = Json>) -> Filter {
136    leaf(field, "in", Json::Array(values.into_iter().collect()))
137}
138/// `field ∉ values` (set exclusion).
139pub fn nin(field: &str, values: impl IntoIterator<Item = Json>) -> Filter {
140    leaf(field, "nin", Json::Array(values.into_iter().collect()))
141}
142/// Substring on a `text` field, or element membership in an array field.
143pub fn contains(field: &str, value: impl Into<Json>) -> Filter {
144    leaf(field, "contains", value.into())
145}
146/// Whether `field` is present (`present = true`) or absent (`false`).
147pub fn exists(field: &str, present: bool) -> Filter {
148    leaf(field, "exists", Json::Bool(present))
149}
150
151/// Boolean AND of all `clauses`.
152pub fn all(clauses: impl IntoIterator<Item = Filter>) -> Filter {
153    combine("and", clauses)
154}
155/// Boolean OR of all `clauses`.
156pub fn any(clauses: impl IntoIterator<Item = Filter>) -> Filter {
157    combine("or", clauses)
158}
159/// Boolean NOT of `clause` (free-function form of the `!` operator).
160pub fn not(clause: Filter) -> Filter {
161    clause.negate()
162}
163
164fn combine(kind: &str, clauses: impl IntoIterator<Item = Filter>) -> Filter {
165    let arr = Json::Array(clauses.into_iter().map(|c| c.0).collect());
166    Filter(obj(&[(kind, arr)]))
167}
168
169// ── Validator ────────────────────────────────────────────────────────────────
170
171/// Validate + normalize an incoming filter (spec §8). Server-side entry point.
172///
173/// Returns `Ok(None)` for an absent/empty filter, else `Ok(Some(tree))` with a
174/// normalized wire object. Returns `Err(RcpError)` `-32602` with `data.field`
175/// naming the offending path for anything malformed, unauthorized, or
176/// type-mismatched — so a server never hand-parses and never panics on bad input.
177///
178/// * `fields` — advertised `filter.fields` as `(name, type)` pairs. `None` allows
179///   any field (no field gating). `type` may be `""` when only names are gated.
180/// * `operators` — advertised operator allow-list. `None` allows all spec ops.
181/// * `max_depth` — reject pathologically deep trees (DoS guard, spec §15.5).
182pub fn validate(
183    node: Option<&Json>,
184    fields: Option<&[(&str, &str)]>,
185    operators: Option<&[&str]>,
186    max_depth: i32,
187) -> Result<Option<Json>, RcpError> {
188    let node = match node {
189        None => return Ok(None),
190        Some(n) if n.is_null() => return Ok(None),
191        Some(Json::Object(o)) if o.is_empty() => return Ok(None),
192        Some(n) => n,
193    };
194    Ok(Some(validate_node(node, fields, operators, "filter", max_depth)?))
195}
196
197fn validate_node(
198    node: &Json,
199    fields: Option<&[(&str, &str)]>,
200    operators: Option<&[&str]>,
201    path: &str,
202    depth: i32,
203) -> Result<Json, RcpError> {
204    if depth < 0 {
205        return Err(bad(path, "filter nesting too deep"));
206    }
207    let obj_pairs = match node.as_object() {
208        Some(o) => o,
209        None => return Err(bad(path, "filter node must be an object")),
210    };
211
212    let has = |k: &str| obj_pairs.iter().any(|(kk, _)| kk == k);
213    let present: Vec<&str> = ["and", "or", "not"].into_iter().filter(|k| has(k)).collect();
214    let is_leaf = has("field") || has("op");
215    if present.len() > 1 {
216        return Err(bad(path, "filter node has multiple combinators"));
217    }
218    if !present.is_empty() && is_leaf {
219        return Err(bad(path, "filter node mixes a combinator with a leaf"));
220    }
221
222    if let Some(&comb) = present.first() {
223        if comb == "not" {
224            let child = node.get("not").unwrap();
225            let inner = validate_node(child, fields, operators, &format!("{path}.not"), depth - 1)?;
226            return Ok(obj(&[("not", inner)]));
227        }
228        let kids = match node.get(comb).and_then(|v| v.as_array()) {
229            Some(a) => a,
230            None => return Err(bad(&format!("{path}.{comb}"), "combinator must be an array")),
231        };
232        let mut out = Vec::with_capacity(kids.len());
233        for (i, c) in kids.iter().enumerate() {
234            out.push(validate_node(c, fields, operators, &format!("{path}.{comb}[{i}]"), depth - 1)?);
235        }
236        return Ok(obj(&[(comb, Json::Array(out))]));
237    }
238
239    if !is_leaf {
240        return Err(bad(path, "filter node is neither a combinator nor a leaf"));
241    }
242
243    // Leaf: {field, op, value?}
244    let field = match node.get_str("field") {
245        Some(f) if !f.is_empty() => f,
246        _ => return Err(bad(path, "leaf requires a non-empty string 'field'")),
247    };
248    let op = match node.get_str("op") {
249        Some(o) => o,
250        None => return Err(bad(&format!("{path}.op"), "leaf requires a string 'op'")),
251    };
252    if !is_known_op(op) {
253        return Err(bad(&format!("{path}.op"), &format!("unknown operator '{op}'")));
254    }
255    if let Some(ops) = operators {
256        if !ops.contains(&op) {
257            return Err(bad(&format!("{path}.op"), &format!("operator '{op}' not advertised")));
258        }
259    }
260    let ftype = match fields {
261        Some(fs) => match fs.iter().find(|(n, _)| *n == field) {
262            Some((_, t)) => Some(*t),
263            None => return Err(bad(&format!("{path}.{field}"), &format!("field '{field}' not advertised"))),
264        },
265        None => None,
266    };
267
268    check_value(op, node, ftype, path)?;
269
270    let value = if UNARY_OPS.contains(&op) {
271        Json::Bool(node.get("value").and_then(|v| v.as_bool()).unwrap_or(true))
272    } else {
273        node.get("value").cloned().unwrap()
274    };
275    Ok(obj(&[
276        ("field", Json::from(field)),
277        ("op", Json::from(op)),
278        ("value", value),
279    ]))
280}
281
282fn check_value(op: &str, node: &Json, ftype: Option<&str>, path: &str) -> Result<(), RcpError> {
283    if UNARY_OPS.contains(&op) {
284        return Ok(());
285    }
286    let value = match node.get("value") {
287        Some(v) => v,
288        None => return Err(bad(&format!("{path}.value"), &format!("operator '{op}' requires a 'value'"))),
289    };
290    if ARRAY_OPS.contains(&op) {
291        match value.as_array() {
292            Some(a) if !a.is_empty() => {
293                if a.iter().any(|v| matches!(v, Json::Array(_) | Json::Object(_))) {
294                    return Err(bad(&format!("{path}.value"), &format!("operator '{op}' array must hold scalars")));
295                }
296            }
297            _ => return Err(bad(&format!("{path}.value"), &format!("operator '{op}' requires a non-empty array"))),
298        }
299    } else if (SCALAR_OPS.contains(&op) || STRING_OPS.contains(&op))
300        && matches!(value, Json::Array(_) | Json::Object(_))
301    {
302        return Err(bad(&format!("{path}.value"), &format!("operator '{op}' requires a scalar value")));
303    }
304    if ORDERED_OPS.contains(&op) {
305        if let Some(t) = ftype {
306            if !t.is_empty() && !ORDERED_TYPES.contains(&t) {
307                return Err(bad(&format!("{path}.op"), &format!("operator '{op}' not valid on '{t}' field")));
308            }
309        }
310    }
311    Ok(())
312}
313
314fn bad(path: &str, message: &str) -> RcpError {
315    RcpError::with_data(
316        Errc::INVALID_PARAMS,
317        format!("{message} ({path})"),
318        obj(&[("field", Json::from(path))]),
319    )
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    const FIELDS: [(&str, &str); 2] = [("year", "int"), ("lang", "keyword")];
327    const OPS: [&str; 8] = ["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin"];
328
329    #[test]
330    fn builder_emits_spec_shape() {
331        let leaf = eq("lang", "fr").to_json();
332        assert_eq!(leaf.get_str("field"), Some("lang"));
333        assert_eq!(leaf.get_str("op"), Some("eq"));
334        assert_eq!(leaf.get("value").and_then(|v| v.as_str()), Some("fr"));
335
336        let tree = eq("lang", "en").and(gte("year", 2015i64)).to_json();
337        let arr = tree.get("and").and_then(|v| v.as_array()).unwrap();
338        assert_eq!(arr.len(), 2);
339    }
340
341    #[test]
342    fn validate_accepts_well_formed() {
343        let tree = all([eq("lang", "en"), gte("year", 2015i64)]).to_json();
344        let out = validate(Some(&tree), Some(&FIELDS), Some(&OPS), 32).unwrap();
345        assert!(out.is_some());
346        // empty / absent -> None
347        assert!(validate(None, Some(&FIELDS), None, 32).unwrap().is_none());
348        assert!(validate(Some(&Json::object()), Some(&FIELDS), None, 32).unwrap().is_none());
349    }
350
351    #[test]
352    fn validate_rejects_every_malformed_tree_with_32602() {
353        let cases = [
354            obj(&[("field", "author".into()), ("op", "eq".into()), ("value", "z".into())]),
355            obj(&[("field", "lang".into()), ("op", "equals".into()), ("value", "en".into())]),
356            obj(&[("and", "not-a-list".into())]),
357            obj(&[("field", "year".into()), ("op", "in".into()), ("value", Json::Int(2017))]),
358            obj(&[("or", Json::Array(vec![obj(&[("field", "lang".into())])]))]),
359            obj(&[("field", "lang".into()), ("op", "gt".into()), ("value", "en".into())]),
360        ];
361        for c in &cases {
362            let err = validate(Some(c), Some(&FIELDS), Some(&OPS), 32).unwrap_err();
363            assert_eq!(err.code, Errc::INVALID_PARAMS, "case: {}", c.dump());
364            assert!(err.data.as_ref().and_then(|d| d.get("field")).is_some());
365        }
366    }
367}