Skip to main content

appstruct_core/
query.rs

1// Shared list-query bounds and LIKE pattern escaping.
2
3use serde::{Deserialize, Serialize};
4
5/// A bounded, field-based filter tree. Values use the same textual codecs as query parameters.
6#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
7#[serde(untagged, deny_unknown_fields)]
8pub enum FilterExpression {
9    All {
10        all: Vec<Self>,
11    },
12    Any {
13        any: Vec<Self>,
14    },
15    Condition {
16        field: String,
17        op: FilterOperator,
18        #[serde(default)]
19        values: Vec<String>,
20    },
21}
22
23/// Operators exposed by generated resource queries.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum FilterOperator {
27    Eq,
28    Ne,
29    Gt,
30    Gte,
31    Lt,
32    Lte,
33    In,
34    NotIn,
35    IsNull,
36    NotNull,
37    Contains,
38    StartsWith,
39    EndsWith,
40    JsonContains,
41    JsonContainedBy,
42    JsonKey,
43}
44
45impl FilterOperator {
46    /// The corresponding sift-query operator name.
47    #[must_use]
48    pub const fn sift_name(self) -> &'static str {
49        match self {
50            Self::Eq => "eq",
51            Self::Ne => "ne",
52            Self::Gt => "gt",
53            Self::Gte => "ge",
54            Self::Lt => "lt",
55            Self::Lte => "le",
56            Self::In => "il",
57            Self::NotIn => "ni",
58            Self::IsNull => "nl",
59            Self::NotNull => "nn",
60            Self::Contains => "ct",
61            Self::StartsWith => "sw",
62            Self::EndsWith => "ew",
63            Self::JsonContains => "json_contains",
64            Self::JsonContainedBy => "json_contained_by",
65            Self::JsonKey => "json_key",
66        }
67    }
68}
69
70impl FilterExpression {
71    /// Parses and validates depth, node, value and byte budgets before building SQL.
72    ///
73    /// # Errors
74    /// Returns a diagnostic for malformed or overly complex filter trees.
75    pub fn parse(source: &str) -> Result<Self, String> {
76        if source.len() > 16_384 {
77            return Err("`where` must not exceed 16384 bytes".to_owned());
78        }
79        let expression: Self = serde_json::from_str(source)
80            .map_err(|_| "invalid `where` filter expression".to_owned())?;
81        let mut nodes = 0;
82        let mut values = 0;
83        expression.validate(1, &mut nodes, &mut values)?;
84        Ok(expression)
85    }
86
87    fn validate(&self, depth: usize, nodes: &mut usize, values: &mut usize) -> Result<(), String> {
88        *nodes += 1;
89        if depth > 8 || *nodes > 64 {
90            return Err("filter tree exceeds its depth or node budget".to_owned());
91        }
92        match self {
93            Self::All { all: children } | Self::Any { any: children } => {
94                if children.is_empty() {
95                    return Err("filter groups must not be empty".to_owned());
96                }
97                for child in children {
98                    child.validate(depth + 1, nodes, values)?;
99                }
100            }
101            Self::Condition {
102                field,
103                op,
104                values: inputs,
105            } => {
106                if field.is_empty() || field.len() > 64 || !crate::is_rust_field_name(field) {
107                    return Err("filter field must be a public scalar field name".to_owned());
108                }
109                let valid = match op {
110                    FilterOperator::IsNull | FilterOperator::NotNull => inputs.is_empty(),
111                    FilterOperator::In | FilterOperator::NotIn => {
112                        !inputs.is_empty() && inputs.len() <= 100
113                    }
114                    _ => inputs.len() == 1,
115                };
116                *values += inputs.len();
117                if !valid || *values > 100 {
118                    return Err(
119                        "filter operator has invalid values or exceeds the value budget".to_owned(),
120                    );
121                }
122            }
123        }
124        Ok(())
125    }
126}
127
128/// Maximum accepted offset-pagination page number.
129pub const MAX_LIST_PAGE: u64 = 10_000;
130/// Maximum accepted offset-pagination page size.
131pub const MAX_LIST_PAGE_SIZE: u64 = 100;
132/// Maximum Unicode scalar values accepted for a resource search term.
133pub const MAX_SEARCH_CHARS: usize = 200;
134
135/// Returns whether offset pagination arguments are within the generated API bounds.
136#[must_use]
137pub const fn list_page_is_valid(page: u64, page_size: u64) -> bool {
138    page >= 1 && page <= MAX_LIST_PAGE && page_size >= 1 && page_size <= MAX_LIST_PAGE_SIZE
139}
140
141/// Returns whether a resource search term fits the generated API bound.
142#[must_use]
143pub fn search_term_is_valid(term: &str) -> bool {
144    term.chars().count() <= MAX_SEARCH_CHARS
145}
146
147/// Builds a SQL `LIKE` pattern for substring search with `%`, `_`, and `\` escaped.
148#[must_use]
149pub fn like_contains_pattern(term: &str) -> String {
150    let mut pattern = String::from("%");
151    for character in term.chars() {
152        if matches!(character, '\\' | '%' | '_') {
153            pattern.push('\\');
154        }
155        pattern.push(character);
156    }
157    pattern.push('%');
158    pattern
159}
160
161#[cfg(test)]
162mod tests {
163    use super::FilterExpression;
164    use super::{
165        MAX_LIST_PAGE, MAX_LIST_PAGE_SIZE, MAX_SEARCH_CHARS, like_contains_pattern,
166        list_page_is_valid, search_term_is_valid,
167    };
168
169    #[test]
170    fn filter_trees_are_bounded_and_reject_ambiguous_inputs() {
171        let valid = r#"{"all":[{"field":"status","op":"in","values":["todo","active"]},{"any":[{"field":"owner","op":"is_null"},{"field":"priority","op":"gte","values":["3"]}]}]}"#;
172        assert!(FilterExpression::parse(valid).is_ok());
173        for invalid in [
174            r#"{"all":[]}"#,
175            r#"{"field":"x","op":"in","values":[]}"#,
176            r#"{"field":"x","op":"is_null","values":["null"]}"#,
177            r#"{"field":"x","op":"eq","values":["1"],"sql":"TRUE"}"#,
178            r#"{"field":"project.secret","op":"eq","values":["1"]}"#,
179            r#"{"all":[],"any":[]}"#,
180        ] {
181            assert!(FilterExpression::parse(invalid).is_err(), "{invalid}");
182        }
183        let mut deep = r#"{"field":"x","op":"is_null"}"#.to_owned();
184        for _ in 0..8 {
185            deep = format!("{{\"all\":[{deep}]}}");
186        }
187        assert!(FilterExpression::parse(&deep).is_err());
188        let wide = format!(
189            "{{\"all\":[{}]}}",
190            std::iter::repeat_n(r#"{"field":"x","op":"is_null"}"#, 64)
191                .collect::<Vec<_>>()
192                .join(",")
193        );
194        assert!(FilterExpression::parse(&wide).is_err());
195        assert!(FilterExpression::parse(&" ".repeat(16_385)).is_err());
196    }
197
198    #[test]
199    fn list_pages_are_bounded() {
200        assert!(list_page_is_valid(1, 25));
201        assert!(list_page_is_valid(MAX_LIST_PAGE, MAX_LIST_PAGE_SIZE));
202        assert!(!list_page_is_valid(0, 25));
203        assert!(!list_page_is_valid(MAX_LIST_PAGE + 1, 25));
204        assert!(!list_page_is_valid(1, 0));
205        assert!(!list_page_is_valid(1, MAX_LIST_PAGE_SIZE + 1));
206    }
207
208    #[test]
209    fn like_contains_escapes_wildcards_and_backslashes() {
210        assert_eq!(like_contains_pattern("ab"), "%ab%");
211        assert_eq!(like_contains_pattern(""), "%%");
212        assert_eq!(like_contains_pattern(r"a%b_c\d"), r"%a\%b\_c\\d%");
213    }
214
215    #[test]
216    fn search_terms_are_bounded_by_unicode_characters() {
217        assert!(search_term_is_valid(&"a".repeat(MAX_SEARCH_CHARS)));
218        assert!(!search_term_is_valid(&"a".repeat(MAX_SEARCH_CHARS + 1)));
219        assert!(search_term_is_valid(&"界".repeat(MAX_SEARCH_CHARS)));
220        assert!(!search_term_is_valid(&"界".repeat(MAX_SEARCH_CHARS + 1)));
221    }
222}