jmap_types/query.rs
1//! RFC 8620 §5.5 generic filter types for JMAP `/query` methods.
2//!
3//! Provides [`Filter`], [`FilterOperator`], and [`Operator`].
4//! Object-specific filter conditions (e.g. `EmailFilterCondition`) are
5//! defined in their respective type crates.
6//!
7//! # Filter algebra is excluded from extras preservation
8//!
9//! The filter algebra defined in this module is **intentionally not extensible**
10//! via the workspace "extras preservation" policy. See [`Filter`],
11//! [`FilterOperator`], and [`Operator`] for details. The same exclusion applies
12//! to every per-object `FilterCondition` / `Comparator` / `ComparatorProperty`
13//! type in the downstream `jmap-*-types` crates (see workspace `AGENTS.md`,
14//! bd JMAP-lbdy "Decision: filter algebra excluded").
15
16use serde::{Deserialize, Serialize};
17
18/// Logical operator for combining filter conditions (RFC 8620 §5.5).
19///
20/// # Excluded from extras preservation
21///
22/// This enum is **out of scope** for the workspace extras-preservation policy:
23/// it carries no `Other(String)` catch-all variant, and backends must
24/// dispatch on its known variants (`AND`, `OR`, `NOT`) to evaluate a filter
25/// tree. An `Other` operator would be meaningless — a server that cannot
26/// interpret the operator cannot evaluate the filter, and silently round-
27/// tripping it back to the client would yield wrong query results.
28///
29/// More broadly, filter algebra (this enum and the per-object
30/// `FilterCondition` / `Comparator` types) is excluded because unrecognised
31/// filter clauses are a query-correctness hazard: silently dropping or
32/// round-tripping a clause the server does not understand can return the
33/// wrong set of records to the client without any error signal.
34///
35/// ## What to do instead
36///
37/// **IETF-track path.** Vendors who need both capability-level declaration
38/// and filterability for custom fields should use
39/// `draft-ietf-jmap-metadata` (capability URI
40/// `urn:ietf:params:jmap:metadata`), which adds namespace-keyed
41/// `metadata` / `privateMetadata` properties to each listed data type,
42/// with per-type schema discovery via the capability's `dataTypes`
43/// (`namespaces` / `supportsVendorNamespaces` / `maxDepth`) and
44/// `metadataExists` / `metadataTextContains` / `metadataTextEquals`
45/// conditions on that type's own `/query` filter
46/// (draft-ietf-jmap-metadata-04 §1.2.1, §3.6). Helpers live in
47/// `jmap-metadata-types`, `jmap-metadata-server`, and
48/// `jmap-metadata-client`.
49///
50/// **Pre-IETF escape.** Vendors who cannot wait for the metadata draft can
51/// either escape the filter tree to `serde_json::Value` or fork the
52/// per-crate `FilterCondition` type. See
53/// `crate-jmap-calendars-types/PLAN.md` for the hybrid sloppy-value
54/// pattern.
55///
56/// Cross-reference: bd JMAP-lbdy "Decision: filter algebra excluded".
57#[non_exhaustive]
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
60pub enum Operator {
61 /// Logical AND: all sub-filters must match (RFC 8620 §5.5).
62 And,
63 /// Logical OR: at least one sub-filter must match (RFC 8620 §5.5).
64 Or,
65 /// Logical NOT: none of the sub-filters may match (RFC 8620 §5.5).
66 Not,
67}
68
69/// A filter node: either a logical operator combining sub-filters, or a
70/// type-specific condition object (RFC 8620 §5.5).
71///
72/// Serializes as an untagged union. The presence of the `"operator"` key
73/// distinguishes `Filter::Operator` from `Filter::Condition`.
74///
75/// **Variant ordering is critical**: `Operator` is listed before `Condition`
76/// because serde untagged tries variants in declaration order.
77/// `FilterOperator<T>` requires an `"operator"` field and fails fast without
78/// it, allowing the deserializer to fall through to `Condition(T)`.
79///
80/// # Unknown keys are rejected, not dropped
81///
82/// [`FilterOperator`] and every in-tree per-crate `FilterCondition` type
83/// carry `#[serde(deny_unknown_fields)]`, which composes correctly with
84/// `#[serde(untagged)]`: a node that fails both variants fails the whole
85/// decode. A misspelt `operator` key (`{"opperator":"AND","conditions":[]}`),
86/// an extra key on an operator node, or an unknown condition property at
87/// any depth is therefore a deserialization error, which servers map to
88/// RFC 8620 §5.5 `unsupportedFilter`. Without the attribute, such a node
89/// would decode as `T::default()` (all fields `None`), which matches every
90/// record.
91///
92/// A condition type `T` defined outside this workspace must carry
93/// `#[serde(deny_unknown_fields)]` too, or it reintroduces that silent
94/// match-all (pinned by
95/// `filter_with_typoed_operator_silently_decodes_as_match_all_condition`).
96/// Object types whose `Filter` is `serde_json::Value` get no such check.
97///
98/// # Excluded from extras preservation
99///
100/// This type is **out of scope** for the workspace extras-preservation
101/// policy: it carries no flatten-extras `extra` field, and the per-object
102/// condition type `T` is also expected to be non-extensible. Filter clauses
103/// the server does not understand are a query-correctness hazard — silently
104/// preserving an unrecognised clause and round-tripping it back to the
105/// client can return the wrong set of records with no error signal.
106///
107/// ## What to do instead
108///
109/// **IETF-track path.** Vendors who need both capability-level declaration
110/// and filterability for custom fields should use
111/// `draft-ietf-jmap-metadata` (capability URI
112/// `urn:ietf:params:jmap:metadata`), which adds namespace-keyed
113/// `metadata` / `privateMetadata` properties to each listed data type,
114/// filterable through `metadata*` conditions on that type's own `/query`
115/// (draft-ietf-jmap-metadata-04 §2, §3.6). Helpers live in
116/// `jmap-metadata-types`, `jmap-metadata-server`, and
117/// `jmap-metadata-client`.
118///
119/// **Pre-IETF escape.** Vendors who cannot wait for the metadata draft can
120/// either escape the filter tree to `serde_json::Value` or fork the
121/// per-crate `FilterCondition` type. See
122/// `crate-jmap-calendars-types/PLAN.md` for the hybrid sloppy-value
123/// pattern.
124///
125/// Cross-reference: bd JMAP-lbdy "Decision: filter algebra excluded".
126#[non_exhaustive]
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(untagged)]
129pub enum Filter<T> {
130 /// A logical combination of sub-filters.
131 Operator(FilterOperator<T>),
132 /// A type-specific condition object.
133 Condition(T),
134}
135
136/// Logical combination of filters (RFC 8620 §5.5).
137///
138/// # Excluded from extras preservation
139///
140/// This type is **out of scope** for the workspace extras-preservation
141/// policy: it carries no flatten-extras `extra` field, and its
142/// [`Operator`] field is a closed control enum that backends must dispatch
143/// on. See [`Operator`] and [`Filter`] for the rationale and for the two
144/// recommended paths (`draft-ietf-jmap-metadata`, bd JMAP-ua37; or the
145/// pre-IETF sloppy-value escape).
146///
147/// Cross-reference: bd JMAP-lbdy "Decision: filter algebra excluded".
148#[non_exhaustive]
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(deny_unknown_fields)]
151pub struct FilterOperator<T> {
152 /// Logical operator: AND, OR, or NOT.
153 pub operator: Operator,
154 /// Sub-conditions to evaluate.
155 pub conditions: Vec<Filter<T>>,
156}
157
158impl<T> Filter<T> {
159 /// `true` if a record matches this filter tree, where `condition`
160 /// decides whether the record matches one [`Filter::Condition`]
161 /// (RFC 8620 §5.5): "AND": all of the conditions must match; "OR": at
162 /// least one must match; "NOT": none of the conditions must match.
163 ///
164 /// Over an empty `conditions` list, `AND` and `NOT` match and `OR`
165 /// does not ("all" and "none" hold vacuously, "at least one" fails).
166 pub fn matches(&self, condition: &impl Fn(&T) -> bool) -> bool {
167 match self {
168 Filter::Condition(cond) => condition(cond),
169 Filter::Operator(op) => {
170 let mut each = op.conditions.iter().map(|f| f.matches(condition));
171 match op.operator {
172 Operator::And => each.all(|m| m),
173 Operator::Or => each.any(|m| m),
174 Operator::Not => !each.any(|m| m),
175 }
176 }
177 }
178 }
179}
180
181impl<T> FilterOperator<T> {
182 /// Create a new [`FilterOperator`] with the given logical operator and conditions.
183 pub fn new(operator: Operator, conditions: Vec<Filter<T>>) -> Self {
184 Self {
185 operator,
186 conditions,
187 }
188 }
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 // FilterCondition stub used only within this test module.
196 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197 struct Cond {
198 #[serde(skip_serializing_if = "Option::is_none")]
199 pub has_keyword: Option<String>,
200 }
201
202 /// Oracle: exercises the Filter<T> generic with a local stub type.
203 /// Adapted from the RFC 8620 §5.5 Todo/query example; `has_keyword` uses
204 /// Rust snake_case because `Cond` is a test stub, not a real JMAP type.
205 #[test]
206 fn filter_operator_or_roundtrip() {
207 let json =
208 r#"{"operator":"OR","conditions":[{"has_keyword":"music"},{"has_keyword":"video"}]}"#;
209 let f: Filter<Cond> = serde_json::from_str(json).expect("must parse");
210 match &f {
211 Filter::Operator(op) => {
212 assert_eq!(op.operator, Operator::Or);
213 assert_eq!(op.conditions.len(), 2);
214 }
215 other => panic!("expected Operator, got {other:?}"),
216 }
217 let back = serde_json::to_string(&f).expect("must serialize");
218 let f2: Filter<Cond> = serde_json::from_str(&back).expect("roundtrip");
219 assert_eq!(f, f2);
220 }
221
222 /// Oracle: a bare condition object (no "operator" key) deserializes as
223 /// Filter::Condition.
224 #[test]
225 fn filter_condition_deserialization() {
226 let json = r#"{"has_keyword":"$seen"}"#;
227 let f: Filter<Cond> = serde_json::from_str(json).expect("must parse");
228 match &f {
229 Filter::Condition(c) => assert_eq!(c.has_keyword.as_deref(), Some("$seen")),
230 other => panic!("expected Condition, got {other:?}"),
231 }
232 }
233
234 /// Oracle: Operator enum serializes as SCREAMING_SNAKE_CASE per RFC 8620 §5.5.
235 #[test]
236 fn operator_serialization() {
237 assert_eq!(serde_json::to_string(&Operator::And).unwrap(), r#""AND""#);
238 assert_eq!(serde_json::to_string(&Operator::Or).unwrap(), r#""OR""#);
239 assert_eq!(serde_json::to_string(&Operator::Not).unwrap(), r#""NOT""#);
240 }
241
242 /// Oracle: pins the malformed-operator silent-fallthrough hazard
243 /// documented on [`Filter`]. A client clause with a misspelled
244 /// `operator` field key (here `opperator`) fails to deserialize as
245 /// `Filter::Operator(FilterOperator)` (the key does not match the
246 /// typed field name) and falls through to `Filter::Condition(T)`.
247 /// Because `Cond` is a struct of all-`Option` fields without
248 /// `#[serde(deny_unknown_fields)]`, serde silently drops the
249 /// unknown `opperator` and `conditions` keys and deserializes the
250 /// clause as `Cond { has_keyword: None }` — semantically "match
251 /// any record".
252 ///
253 /// This test is a regression marker for `bd:JMAP-6xs8.7`: it pins
254 /// why every condition type must carry `deny_unknown_fields` (see
255 /// "Unknown keys are rejected, not dropped" on [`Filter`]);
256 /// `filter_with_strict_condition_rejects_unknown_keys` is the
257 /// counterpart with a strict condition type.
258 #[test]
259 fn filter_with_typoed_operator_silently_decodes_as_match_all_condition() {
260 // Variant 1: lower-case `o` typoed as `opperator`.
261 let raw = r#"{"opperator":"AND","conditions":[]}"#;
262 let f: Filter<Cond> = serde_json::from_str(raw).expect(
263 "untagged enum must accept the typo as Filter::Condition — \
264 this is the silent-fallthrough hazard",
265 );
266 match f {
267 Filter::Condition(c) => assert!(
268 c.has_keyword.is_none(),
269 "fallthrough Condition must be the all-None default \
270 'match-all' shape; got: {c:?}"
271 ),
272 Filter::Operator(_) => panic!(
273 "expected silent fallthrough to Condition, got Operator \
274 — serde untagged behavior changed?"
275 ),
276 }
277
278 // Variant 2: capitalised `O` typoed as `Operator`.
279 let raw_capitalised = r#"{"Operator":"AND","conditions":[]}"#;
280 let f2: Filter<Cond> =
281 serde_json::from_str(raw_capitalised).expect("capitalised typo must also fall through");
282 match f2 {
283 Filter::Condition(c) => assert!(c.has_keyword.is_none()),
284 Filter::Operator(_) => panic!("expected silent fallthrough to Condition, got Operator"),
285 }
286 }
287
288 // Condition stub with the same strictness as the in-tree condition types.
289 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290 #[serde(rename_all = "camelCase", deny_unknown_fields)]
291 struct StrictCond {
292 #[serde(skip_serializing_if = "Option::is_none")]
293 has_keyword: Option<String>,
294 }
295
296 /// Oracle: RFC 8620 §5.5 defines a FilterOperator as exactly
297 /// `operator` ("AND" | "OR" | "NOT") plus `conditions`, and
298 /// `unsupportedFilter` as "The "filter" is syntactically valid, but the
299 /// server cannot process it." Hand-written JSON: well-formed trees
300 /// must decode; trees with an unknown key at any node must fail.
301 #[test]
302 fn filter_with_strict_condition_rejects_unknown_keys() {
303 let accepted = [
304 r#"{"hasKeyword":"$seen"}"#,
305 "{}",
306 r#"{"operator":"AND","conditions":[{"hasKeyword":"a"}]}"#,
307 r#"{"operator":"OR","conditions":[]}"#,
308 r#"{"operator":"AND","conditions":[{"operator":"NOT","conditions":[{"hasKeyword":"b"}]}]}"#,
309 ];
310 for raw in accepted {
311 serde_json::from_str::<Filter<StrictCond>>(raw)
312 .unwrap_or_else(|e| panic!("{raw} must decode: {e}"));
313 }
314 let rejected = [
315 // snake_case typo of a known property
316 r#"{"has_keyword":"$seen"}"#,
317 // unknown leaf key next to a known one
318 r#"{"hasKeyword":"$seen","bogus":1}"#,
319 // misspelt operator key
320 r#"{"opperator":"AND","conditions":[]}"#,
321 // unknown key on an operator node
322 r#"{"operator":"AND","conditions":[],"extra":true}"#,
323 // operator value outside AND/OR/NOT
324 r#"{"operator":"XOR","conditions":[]}"#,
325 // unknown leaf key nested two levels down
326 r#"{"operator":"AND","conditions":[{"operator":"OR","conditions":[{"bogus":1}]}]}"#,
327 ];
328 for raw in rejected {
329 assert!(
330 serde_json::from_str::<Filter<StrictCond>>(raw).is_err(),
331 "{raw} must be rejected"
332 );
333 }
334 }
335
336 /// Oracle: nested AND(OR(...)) structure roundtrips correctly.
337 #[test]
338 fn nested_filter_roundtrip() {
339 let filter = Filter::Operator(FilterOperator {
340 operator: Operator::And,
341 conditions: vec![
342 Filter::Operator(FilterOperator {
343 operator: Operator::Or,
344 conditions: vec![
345 Filter::Condition(Cond {
346 has_keyword: Some("a".to_owned()),
347 }),
348 Filter::Condition(Cond {
349 has_keyword: Some("b".to_owned()),
350 }),
351 ],
352 }),
353 Filter::Condition(Cond {
354 has_keyword: Some("c".to_owned()),
355 }),
356 ],
357 });
358 let json = serde_json::to_string(&filter).expect("serialize");
359 let back: Filter<Cond> = serde_json::from_str(&json).expect("deserialize");
360 assert_eq!(filter, back);
361 }
362
363 /// Oracle: RFC 8620 §5.5 (line 2378-2385), quoted:
364 ///
365 /// > "AND": All of the conditions must match for the filter to match.
366 /// > "OR": At least one of the conditions must match for the filter to
367 /// > match.
368 /// > "NOT": None of the conditions must match for the filter to match.
369 ///
370 /// The condition predicate here is "has_keyword is `$seen`", applied to
371 /// a hand-written tree over the record's keyword `$seen`.
372 #[test]
373 fn matches_follows_rfc8620_operator_semantics() {
374 let seen = |c: &Cond| c.has_keyword.as_deref() == Some("$seen");
375 let tree = |json: &str| -> Filter<Cond> { serde_json::from_str(json).expect("must parse") };
376 let hit = r#"{"has_keyword":"$seen"}"#;
377 let miss = r#"{"has_keyword":"$flagged"}"#;
378 let op =
379 |o: &str, a: &str, b: &str| format!(r#"{{"operator":"{o}","conditions":[{a},{b}]}}"#);
380
381 assert!(tree(hit).matches(&seen));
382 assert!(!tree(miss).matches(&seen));
383 assert!(tree(&op("AND", hit, hit)).matches(&seen));
384 assert!(!tree(&op("AND", hit, miss)).matches(&seen));
385 assert!(tree(&op("OR", miss, hit)).matches(&seen));
386 assert!(!tree(&op("OR", miss, miss)).matches(&seen));
387 assert!(tree(&op("NOT", miss, miss)).matches(&seen));
388 assert!(!tree(&op("NOT", miss, hit)).matches(&seen));
389 // Nested: NOT(OR(miss, AND(hit, hit))) — the inner AND matches, so
390 // the OR matches, so the NOT does not.
391 let nested = op("NOT", &op("OR", miss, &op("AND", hit, hit)), miss);
392 assert!(!tree(&nested).matches(&seen));
393 }
394}