1#![allow(warnings)]
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5use std::str::FromStr;
6
7const SCIM_FILTER_MAX_DEPTH: usize = 128;
8
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10pub struct AttrPath {
11 a: String,
13 s: Option<String>,
14}
15
16impl ToString for AttrPath {
17 fn to_string(&self) -> String {
18 match self {
19 Self {
20 a: attrname,
21 s: Some(subattr),
22 } => format!("{attrname}.{subattr}"),
23 Self {
24 a: attrname,
25 s: None,
26 } => attrname.to_owned(),
27 }
28 }
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub enum ScimFilter {
33 Or(Box<ScimFilter>, Box<ScimFilter>),
34 And(Box<ScimFilter>, Box<ScimFilter>),
35 Not(Box<ScimFilter>),
36
37 Present(AttrPath),
38 Equal(AttrPath, Value),
39 NotEqual(AttrPath, Value),
40 Contains(AttrPath, Value),
41 StartsWith(AttrPath, Value),
42 EndsWith(AttrPath, Value),
43 Greater(AttrPath, Value),
44 Less(AttrPath, Value),
45 GreaterOrEqual(AttrPath, Value),
46 LessOrEqual(AttrPath, Value),
47
48 Complex(String, Box<ScimComplexFilter>),
49}
50
51impl ToString for ScimFilter {
52 fn to_string(&self) -> String {
53 match self {
54 Self::And(this, that) => format!("({} and {})", this.to_string(), that.to_string()),
55 Self::Contains(attrpath, value) => format!("({} co {value})", attrpath.to_string()),
56 Self::EndsWith(attrpath, value) => format!("({} ew {value})", attrpath.to_string()),
57 Self::Equal(attrpath, value) => format!("({} eq {value})", attrpath.to_string()),
58 Self::Greater(attrpath, value) => format!("({} gt {value})", attrpath.to_string()),
59 Self::GreaterOrEqual(attrpath, value) => {
60 format!("({} ge {value})", attrpath.to_string())
61 }
62 Self::Less(attrpath, value) => format!("({} lt {value})", attrpath.to_string()),
63 Self::LessOrEqual(attrpath, value) => format!("({} le {value})", attrpath.to_string()),
64 Self::Not(expr) => format!("(not ({}))", expr.to_string()),
65 Self::NotEqual(attrpath, value) => format!("({} ne {value})", attrpath.to_string()),
66 Self::Or(this, that) => format!("({} or {})", this.to_string(), that.to_string()),
67 Self::Present(attrpath) => format!("({} pr)", attrpath.to_string()),
68 Self::StartsWith(attrpath, value) => format!("({} sw {value})", attrpath.to_string()),
69 Self::Complex(attrname, expr) => format!("{attrname}[{}]", expr.to_string()),
70 }
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub enum ScimComplexFilter {
76 Or(Box<ScimComplexFilter>, Box<ScimComplexFilter>),
77 And(Box<ScimComplexFilter>, Box<ScimComplexFilter>),
78 Not(Box<ScimComplexFilter>),
79
80 Present(String),
81 Equal(String, Value),
82 NotEqual(String, Value),
83 Contains(String, Value),
84 StartsWith(String, Value),
85 EndsWith(String, Value),
86 Greater(String, Value),
87 Less(String, Value),
88 GreaterOrEqual(String, Value),
89 LessOrEqual(String, Value),
90}
91
92impl ToString for ScimComplexFilter {
93 fn to_string(&self) -> String {
94 match self {
95 Self::And(this, that) => format!("({} and {})", this.to_string(), that.to_string()),
96 Self::Contains(attrname, value) => format!("({attrname} co {value})"),
97 Self::EndsWith(attrname, value) => format!("({attrname} ew {value})"),
98 Self::Equal(attrname, value) => format!("({attrname} eq {value})"),
99 Self::Greater(attrname, value) => format!("({attrname} gt {value})"),
100 Self::GreaterOrEqual(attrname, value) => format!("({attrname} ge {value})"),
101 Self::Less(attrname, value) => format!("({attrname} lt {value})"),
102 Self::LessOrEqual(attrname, value) => format!("({attrname} le {value})"),
103 Self::Not(expr) => format!("(not ({}))", expr.to_string()),
104 Self::NotEqual(attrname, value) => format!("({attrname} ne {value})"),
105 Self::Or(this, that) => format!("({} or {})", this.to_string(), that.to_string()),
106 Self::Present(attrname) => format!("({attrname} pr)"),
107 Self::StartsWith(attrname, value) => format!("({attrname} sw {value})"),
108 }
109 }
110}
111
112peg::parser! {
115 grammar scimfilter() for str {
116
117 pub rule parse() -> ScimFilter =
118 f:parse_depth(SCIM_FILTER_MAX_DEPTH) { f }
119
120 pub(crate) rule parse_depth(max_depth: usize) -> ScimFilter =
121 limiter(max_depth) a:parse_inner(max_depth.saturating_sub(1)) { a }
122
123 rule limiter(max_depth: usize) -> () =
124 {? if max_depth == 0 { Err("too deeply nested") } else { Ok(()) } }
125
126 rule parse_inner(max_depth: usize) -> ScimFilter = precedence!{
129 "not" separator()+ "(" e:parse_depth(max_depth) ")" {
130 ScimFilter::Not(Box::new(e))
131 }
132 --
133 a:parse_inner_attr(max_depth) separator()+ "or" separator()+ b:parse_depth(max_depth) {
134 ScimFilter::Or(
135 Box::new(a),
136 Box::new(b)
137 )
138 }
139 --
140 a:parse_inner_attr(max_depth) separator()+ "and" separator()+ b:parse_depth(max_depth) {
141 ScimFilter::And(
142 Box::new(a),
143 Box::new(b)
144 )
145 }
146 --
147 "(" e:parse_depth(max_depth) ")" { e }
148 --
149 a:parse_inner_attr(max_depth) { a }
150 }
151
152 rule parse_inner_attr(max_depth: usize) -> ScimFilter = precedence!{
153 a:attrname()"[" e:parse_complex_depth(max_depth) "]" {
154 ScimFilter::Complex(
155 a,
156 Box::new(e)
157 )
158 }
159 --
160 a:attrexp() { a }
161 }
162
163 pub rule parse_complex() -> ScimComplexFilter =
164 f:parse_complex_depth(SCIM_FILTER_MAX_DEPTH) { f }
165
166 pub(crate) rule parse_complex_depth(max_depth: usize) -> ScimComplexFilter =
167 limiter(max_depth) a:parse_complex_inner(max_depth.saturating_sub(1)) { a }
168
169 rule parse_complex_inner(max_depth: usize) -> ScimComplexFilter = precedence!{
170 a:complex_attrexp() separator()+ "or" separator()+ b:parse_complex_depth(max_depth) {
171 ScimComplexFilter::Or(
172 Box::new(a),
173 Box::new(b)
174 )
175 }
176 --
177 a:complex_attrexp() separator()+ "and" separator()+ b:parse_complex_depth(max_depth) {
178 ScimComplexFilter::And(
179 Box::new(a),
180 Box::new(b)
181 )
182 }
183 --
184 "not" separator()+ "(" e:parse_complex_depth(max_depth) ")" {
185 ScimComplexFilter::Not(Box::new(e))
186 }
187 --
188 "(" e:parse_complex_depth(max_depth) ")" { e }
189 a:complex_attrexp() { a }
190 }
191
192 pub(crate) rule attrexp() -> ScimFilter =
193 pres()
194 / eq()
195 / ne()
196 / co()
197 / sw()
198 / ew()
199 / gt()
200 / lt()
201 / ge()
202 / le()
203
204 pub(crate) rule pres() -> ScimFilter =
205 a:attrpath() separator()+ "pr" { ScimFilter::Present(a) }
206
207 pub(crate) rule eq() -> ScimFilter =
208 a:attrpath() separator()+ "eq" separator()+ v:value() { ScimFilter::Equal(a, v) }
209
210 pub(crate) rule ne() -> ScimFilter =
211 a:attrpath() separator()+ "ne" separator()+ v:value() { ScimFilter::NotEqual(a, v) }
212
213 pub(crate) rule co() -> ScimFilter =
214 a:attrpath() separator()+ "co" separator()+ v:value() { ScimFilter::Contains(a, v) }
215
216 pub(crate) rule sw() -> ScimFilter =
217 a:attrpath() separator()+ "sw" separator()+ v:value() { ScimFilter::StartsWith(a, v) }
218
219 pub(crate) rule ew() -> ScimFilter =
220 a:attrpath() separator()+ "ew" separator()+ v:value() { ScimFilter::EndsWith(a, v) }
221
222 pub(crate) rule gt() -> ScimFilter =
223 a:attrpath() separator()+ "gt" separator()+ v:value() { ScimFilter::Greater(a, v) }
224
225 pub(crate) rule lt() -> ScimFilter =
226 a:attrpath() separator()+ "lt" separator()+ v:value() { ScimFilter::Less(a, v) }
227
228 pub(crate) rule ge() -> ScimFilter =
229 a:attrpath() separator()+ "ge" separator()+ v:value() { ScimFilter::GreaterOrEqual(a, v) }
230
231 pub(crate) rule le() -> ScimFilter =
232 a:attrpath() separator()+ "le" separator()+ v:value() { ScimFilter::LessOrEqual(a, v) }
233
234 pub(crate) rule complex_attrexp() -> ScimComplexFilter =
235 c_pres()
236 / c_eq()
237 / c_ne()
238 / c_co()
239 / c_sw()
240 / c_ew()
241 / c_gt()
242 / c_lt()
243 / c_ge()
244 / c_le()
245
246 pub(crate) rule c_pres() -> ScimComplexFilter =
247 a:attrname() separator()+ "pr" { ScimComplexFilter::Present(a) }
248
249 pub(crate) rule c_eq() -> ScimComplexFilter =
250 a:attrname() separator()+ "eq" separator()+ v:value() { ScimComplexFilter::Equal(a, v) }
251
252 pub(crate) rule c_ne() -> ScimComplexFilter =
253 a:attrname() separator()+ "ne" separator()+ v:value() { ScimComplexFilter::NotEqual(a, v) }
254
255 pub(crate) rule c_co() -> ScimComplexFilter =
256 a:attrname() separator()+ "co" separator()+ v:value() { ScimComplexFilter::Contains(a, v) }
257
258 pub(crate) rule c_sw() -> ScimComplexFilter =
259 a:attrname() separator()+ "sw" separator()+ v:value() { ScimComplexFilter::StartsWith(a, v) }
260
261 pub(crate) rule c_ew() -> ScimComplexFilter =
262 a:attrname() separator()+ "ew" separator()+ v:value() { ScimComplexFilter::EndsWith(a, v) }
263
264 pub(crate) rule c_gt() -> ScimComplexFilter =
265 a:attrname() separator()+ "gt" separator()+ v:value() { ScimComplexFilter::Greater(a, v) }
266
267 pub(crate) rule c_lt() -> ScimComplexFilter =
268 a:attrname() separator()+ "lt" separator()+ v:value() { ScimComplexFilter::Less(a, v) }
269
270 pub(crate) rule c_ge() -> ScimComplexFilter =
271 a:attrname() separator()+ "ge" separator()+ v:value() { ScimComplexFilter::GreaterOrEqual(a, v) }
272
273 pub(crate) rule c_le() -> ScimComplexFilter =
274 a:attrname() separator()+ "le" separator()+ v:value() { ScimComplexFilter::LessOrEqual(a, v) }
275
276 rule separator() =
277 ['\n' | ' ' | '\t' ]
278
279 rule operator() =
280 ['\n' | ' ' | '\t' | '(' | ')' | '[' | ']' ]
281
282 rule value() -> Value =
283 quotedvalue() / unquotedvalue()
284
285 rule quotedvalue() -> Value =
286 s:$(['"'] ((['\\'][_]) / (!['"'][_]))* ['"']) {? serde_json::from_str(s).map_err(|_| "invalid json value" ) }
287
288 rule unquotedvalue() -> Value =
289 s:$((!operator()[_])*) {? serde_json::from_str(s).map_err(|_| "invalid json value" ) }
290
291 pub(crate) rule attrpath() -> AttrPath =
292 a:attrname() s:subattr()? { AttrPath { a, s } }
293
294 rule subattr() -> String =
295 "." s:attrname() { s.to_string() }
296
297 pub(crate) rule attrname() -> String =
298 s:$([ 'a'..='z' | 'A'..='Z']['a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' ]*) { s.to_string() }
299 }
300}
301
302impl FromStr for AttrPath {
303 type Err = peg::error::ParseError<peg::str::LineCol>;
304 fn from_str(input: &str) -> Result<Self, Self::Err> {
305 scimfilter::attrpath(input)
306 }
307}
308
309impl FromStr for ScimFilter {
310 type Err = peg::error::ParseError<peg::str::LineCol>;
311 fn from_str(input: &str) -> Result<Self, Self::Err> {
312 scimfilter::parse(input)
313 }
314}
315
316impl FromStr for ScimComplexFilter {
317 type Err = peg::error::ParseError<peg::str::LineCol>;
318 fn from_str(input: &str) -> Result<Self, Self::Err> {
319 scimfilter::parse_complex(input)
320 }
321}
322
323#[cfg(test)]
324mod test {
325 use super::*;
326 use crate::filter::{AttrPath, ScimFilter};
327 use serde_json::Value;
328
329 #[test]
330 fn test_scimfilter_attrname() {
331 assert_eq!(scimfilter::attrname("abcd-_"), Ok("abcd-_".to_string()));
332 assert_eq!(scimfilter::attrname("aB-_CD"), Ok("aB-_CD".to_string()));
333 assert_eq!(scimfilter::attrname("a1-_23"), Ok("a1-_23".to_string()));
334 assert!(scimfilter::attrname("-bcd").is_err());
335 assert!(scimfilter::attrname("_bcd").is_err());
336 assert!(scimfilter::attrname("0bcd").is_err());
337 }
338
339 #[test]
340 fn test_scimfilter_attrpath() {
341 assert_eq!(
342 scimfilter::attrpath("abcd"),
343 Ok(AttrPath {
344 a: "abcd".to_string(),
345 s: None
346 })
347 );
348
349 assert_eq!(
350 scimfilter::attrpath("abcd.abcd"),
351 Ok(AttrPath {
352 a: "abcd".to_string(),
353 s: Some("abcd".to_string())
354 })
355 );
356
357 assert!(scimfilter::attrname("abcd.0").is_err());
358 assert!(scimfilter::attrname("abcd._").is_err());
359 assert!(scimfilter::attrname("abcd,0").is_err());
360 assert!(scimfilter::attrname(".abcd").is_err());
361 }
362
363 #[test]
364 fn test_scimfilter_pres() {
365 assert!(
366 scimfilter::parse("abcd pr")
367 == Ok(ScimFilter::Present(AttrPath {
368 a: "abcd".to_string(),
369 s: None
370 }))
371 );
372 }
373
374 #[test]
375 fn test_scimfilter_eq() {
376 assert!(
377 scimfilter::parse("abcd eq \"dcba\"")
378 == Ok(ScimFilter::Equal(
379 AttrPath {
380 a: "abcd".to_string(),
381 s: None
382 },
383 Value::String("dcba".to_string())
384 ))
385 );
386 }
387
388 #[test]
389 fn test_scimfilter_ne() {
390 assert!(
391 scimfilter::parse("abcd ne \"dcba\"")
392 == Ok(ScimFilter::NotEqual(
393 AttrPath {
394 a: "abcd".to_string(),
395 s: None
396 },
397 Value::String("dcba".to_string())
398 ))
399 );
400 }
401
402 #[test]
403 fn test_scimfilter_co() {
404 assert!(
405 scimfilter::parse("abcd co \"dcba\"")
406 == Ok(ScimFilter::Contains(
407 AttrPath {
408 a: "abcd".to_string(),
409 s: None
410 },
411 Value::String("dcba".to_string())
412 ))
413 );
414 }
415
416 #[test]
417 fn test_scimfilter_sw() {
418 assert!(
419 scimfilter::parse("abcd sw \"dcba\"")
420 == Ok(ScimFilter::StartsWith(
421 AttrPath {
422 a: "abcd".to_string(),
423 s: None
424 },
425 Value::String("dcba".to_string())
426 ))
427 );
428 }
429
430 #[test]
431 fn test_scimfilter_ew() {
432 assert!(
433 scimfilter::parse("abcd ew \"dcba\"")
434 == Ok(ScimFilter::EndsWith(
435 AttrPath {
436 a: "abcd".to_string(),
437 s: None
438 },
439 Value::String("dcba".to_string())
440 ))
441 );
442 }
443
444 #[test]
445 fn test_scimfilter_gt() {
446 assert!(
447 scimfilter::parse("abcd gt \"dcba\"")
448 == Ok(ScimFilter::Greater(
449 AttrPath {
450 a: "abcd".to_string(),
451 s: None
452 },
453 Value::String("dcba".to_string())
454 ))
455 );
456 }
457
458 #[test]
459 fn test_scimfilter_lt() {
460 assert!(
461 scimfilter::parse("abcd lt \"dcba\"")
462 == Ok(ScimFilter::Less(
463 AttrPath {
464 a: "abcd".to_string(),
465 s: None
466 },
467 Value::String("dcba".to_string())
468 ))
469 );
470 }
471
472 #[test]
473 fn test_scimfilter_ge() {
474 assert!(
475 scimfilter::parse("abcd ge \"dcba\"")
476 == Ok(ScimFilter::GreaterOrEqual(
477 AttrPath {
478 a: "abcd".to_string(),
479 s: None
480 },
481 Value::String("dcba".to_string())
482 ))
483 );
484 }
485
486 #[test]
487 fn test_scimfilter_le() {
488 assert!(
489 scimfilter::parse("abcd le \"dcba\"")
490 == Ok(ScimFilter::LessOrEqual(
491 AttrPath {
492 a: "abcd".to_string(),
493 s: None
494 },
495 Value::String("dcba".to_string())
496 ))
497 );
498 }
499
500 #[test]
501 fn test_scimfilter_group() {
502 let f = scimfilter::parse("(abcd eq \"dcba\")");
503 eprintln!("{:?}", f);
504 assert!(
505 f == Ok(ScimFilter::Equal(
506 AttrPath {
507 a: "abcd".to_string(),
508 s: None
509 },
510 Value::String("dcba".to_string())
511 ))
512 );
513 }
514
515 #[test]
516 fn test_scimfilter_not() {
517 let f = scimfilter::parse("not (abcd eq \"dcba\")");
518 eprintln!("{:?}", f);
519
520 assert!(
521 f == Ok(ScimFilter::Not(Box::new(ScimFilter::Equal(
522 AttrPath {
523 a: "abcd".to_string(),
524 s: None
525 },
526 Value::String("dcba".to_string())
527 ))))
528 );
529 }
530
531 #[test]
532 fn test_scimfilter_and() {
533 let f = scimfilter::parse("abcd eq \"dcba\" and bcda ne \"1234\"");
534 eprintln!("{:?}", f);
535
536 assert!(
537 f == Ok(ScimFilter::And(
538 Box::new(ScimFilter::Equal(
539 AttrPath {
540 a: "abcd".to_string(),
541 s: None
542 },
543 Value::String("dcba".to_string())
544 )),
545 Box::new(ScimFilter::NotEqual(
546 AttrPath {
547 a: "bcda".to_string(),
548 s: None
549 },
550 Value::String("1234".to_string())
551 ))
552 ))
553 );
554 }
555
556 #[test]
557 fn test_scimfilter_or() {
558 let f = scimfilter::parse("abcd eq \"dcba\" or bcda ne \"1234\"");
559 eprintln!("{:?}", f);
560
561 assert!(
562 f == Ok(ScimFilter::Or(
563 Box::new(ScimFilter::Equal(
564 AttrPath {
565 a: "abcd".to_string(),
566 s: None
567 },
568 Value::String("dcba".to_string())
569 )),
570 Box::new(ScimFilter::NotEqual(
571 AttrPath {
572 a: "bcda".to_string(),
573 s: None
574 },
575 Value::String("1234".to_string())
576 ))
577 ))
578 );
579 }
580
581 #[test]
582 fn test_scimfilter_complex() {
583 let f = scimfilter::parse("emails[type eq \"work\"]");
584 eprintln!("-- {:?}", f);
585 assert!(f.is_ok());
586
587 let f = scimfilter::parse("emails[type eq \"work\" and value co \"@example.com\"] or ims[type eq \"xmpp\" and value co \"@foo.com\"]");
588 eprintln!("{:?}", f);
589
590 assert_eq!(
591 f,
592 Ok(ScimFilter::Or(
593 Box::new(ScimFilter::Complex(
594 "emails".to_string(),
595 Box::new(ScimComplexFilter::And(
596 Box::new(ScimComplexFilter::Equal(
597 "type".to_string(),
598 Value::String("work".to_string())
599 )),
600 Box::new(ScimComplexFilter::Contains(
601 "value".to_string(),
602 Value::String("@example.com".to_string())
603 ))
604 ))
605 )),
606 Box::new(ScimFilter::Complex(
607 "ims".to_string(),
608 Box::new(ScimComplexFilter::And(
609 Box::new(ScimComplexFilter::Equal(
610 "type".to_string(),
611 Value::String("xmpp".to_string())
612 )),
613 Box::new(ScimComplexFilter::Contains(
614 "value".to_string(),
615 Value::String("@foo.com".to_string())
616 ))
617 ))
618 ))
619 ))
620 );
621 }
622
623 #[test]
753 fn test_scimfilter_quoted_values() {
754 assert_eq!(
755 scimfilter::parse(r#"description eq "text ( ) [ ] 'single' \"escaped\" \\\\consecutive\\\\ \/slash\b\f\n\r\t\u0041 and or not eq ne co sw ew gt lt ge le pr true false""#),
756 Ok(ScimFilter::Equal(
757 AttrPath { a: "description".to_string(), s: None },
758 Value::String("text ( ) [ ] 'single' \"escaped\" \\\\consecutive\\\\ /slash\u{08}\u{0C}\n\r\tA and or not eq ne co sw ew gt lt ge le pr true false".to_string())
759 ))
760 );
761 }
762
763 #[test]
764 fn test_scimfilter_quoted_values_incomplete_escape() {
765 let result = scimfilter::parse(r#"name eq "test\""#);
766 assert!(result.is_err());
767 }
768
769 #[test]
770 fn test_scimfilter_quoted_values_empty() {
771 assert_eq!(
772 scimfilter::parse(r#"name eq """#),
773 Ok(ScimFilter::Equal(
774 AttrPath {
775 a: "name".to_string(),
776 s: None
777 },
778 Value::String("".to_string())
779 ))
780 );
781 }
782
783 #[test]
784 fn test_scimfilter_recursion_limit() {
785 scimfilter::parse_depth("a pr and (b pr and (c pr and d pr))", 0).expect_err("Must fail");
786
787 scimfilter::parse_depth("a pr and (b pr and (c pr and d pr))", 1).expect_err("Must fail");
788
789 scimfilter::parse_depth("a pr and (b pr and (c pr and d pr))", 5).expect_err("Must fail");
790
791 scimfilter::parse_depth("a pr and (b pr and (c pr and d pr))", 6).expect("Must pass");
792
793 scimfilter::parse_depth("((c pr and d pr))", 0).expect_err("Must fail");
794
795 scimfilter::parse_depth("((c pr and d pr))", 1).expect_err("Must fail");
796
797 scimfilter::parse_depth("((c pr and d pr))", 3).expect_err("Must fail");
798
799 scimfilter::parse_depth("((c pr and d pr))", 4).expect("Must pass");
800
801 scimfilter::parse_depth("a pr and b pr and c pr and d pr", 0).expect_err("Must fail");
802
803 scimfilter::parse_depth("a pr and b pr and c pr and d pr", 1).expect_err("Must fail");
804
805 scimfilter::parse_depth("a pr and b pr and c pr and d pr", 3).expect_err("Must fail");
806
807 scimfilter::parse_depth("a pr and b pr and c pr and d pr", 4).expect("Must pass");
808 }
809}