1use crate::attribute::{Attribute, SubAttribute};
20use serde::{Deserialize, Serialize};
21use serde_with::{
22 formats::CommaSeparator, serde_as, skip_serializing_none, DisplayFromStr, StringWithSeparator,
23};
24use sshkey_attest::proto::PublicKey as SshPublicKey;
25use std::{collections::BTreeMap, fmt, num::NonZeroU64, ops::Not, str::FromStr};
26use utoipa::ToSchema;
27use uuid::Uuid;
28
29pub use self::synch::*;
30pub use scim_proto::prelude::*;
31pub use serde_json::Value as JsonValue;
32
33pub mod client;
34pub mod server;
35mod synch;
36
37#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
41pub struct ScimEntryGeneric {
42 #[serde(flatten)]
43 pub header: ScimEntryHeader,
44 #[serde(flatten)]
45 pub attrs: BTreeMap<Attribute, JsonValue>,
46}
47
48#[derive(Serialize, Deserialize, Clone, Debug, Default, ToSchema)]
49#[serde(rename_all = "lowercase")]
50pub enum ScimSortOrder {
51 #[default]
52 Ascending,
53 Descending,
54}
55
56#[serde_as]
58#[skip_serializing_none]
59#[derive(Serialize, Deserialize, Clone, Debug, Default, ToSchema)]
60#[serde(rename_all = "camelCase")]
61pub struct ScimEntryGetQuery {
62 #[serde_as(as = "Option<StringWithSeparator::<CommaSeparator, Attribute>>")]
63 pub attributes: Option<Vec<Attribute>>,
64 #[serde(default, skip_serializing_if = "<&bool>::not")]
65 pub ext_access_check: bool,
66
67 #[serde(default)]
69 pub sort_by: Option<Attribute>,
70 #[serde(default)]
71 pub sort_order: Option<ScimSortOrder>,
72
73 #[schema(value_type = u64)]
75 pub start_index: Option<NonZeroU64>,
76 #[schema(value_type = u64)]
77 pub count: Option<NonZeroU64>,
78
79 #[serde_as(as = "Option<DisplayFromStr>")]
81 #[schema(value_type = JsonValue)]
82 pub filter: Option<ScimFilter>,
83}
84
85#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
86pub enum ScimSchema {
87 #[serde(rename = "urn:ietf:params:scim:schemas:kanidm:sync:1:account")]
88 SyncAccountV1,
89 #[serde(rename = "urn:ietf:params:scim:schemas:kanidm:sync:1:group")]
90 SyncV1GroupV1,
91 #[serde(rename = "urn:ietf:params:scim:schemas:kanidm:sync:1:person")]
92 SyncV1PersonV1,
93 #[serde(rename = "urn:ietf:params:scim:schemas:kanidm:sync:1:posixaccount")]
94 SyncV1PosixAccountV1,
95 #[serde(rename = "urn:ietf:params:scim:schemas:kanidm:sync:1:posixgroup")]
96 SyncV1PosixGroupV1,
97}
98
99#[serde_as]
100#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, ToSchema)]
101#[serde(deny_unknown_fields, rename_all = "camelCase")]
102pub struct ScimMail {
103 #[serde(default)]
104 pub primary: bool,
105 pub value: String,
106}
107
108#[derive(Deserialize, Serialize, Debug, Clone, ToSchema)]
109#[serde(rename_all = "camelCase")]
110pub struct ScimSshPublicKey {
111 pub label: String,
112
113 #[schema(value_type = String)]
114 pub value: SshPublicKey,
115}
116
117#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, ToSchema)]
118#[serde(rename_all = "camelCase")]
119pub struct ScimReference {
120 pub uuid: Uuid,
121 pub value: String,
122}
123
124#[derive(Deserialize, Serialize, Debug, Clone, ToSchema)]
125pub enum ScimOauth2ClaimMapJoinChar {
126 #[serde(rename = ",", alias = "csv")]
127 CommaSeparatedValue,
128 #[serde(rename = " ", alias = "ssv")]
129 SpaceSeparatedValue,
130 #[serde(rename = ";", alias = "json_array")]
131 JsonArray,
132}
133
134#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, ToSchema)]
135#[serde(rename_all = "camelCase")]
136pub struct ScimApplicationPassword {
137 pub uuid: Uuid,
138 pub label: String,
139 pub secret: String,
140}
141
142#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, ToSchema)]
143#[serde(rename_all = "camelCase")]
144pub struct ScimApplicationPasswordCreate {
145 pub application_uuid: Uuid,
146 pub label: String,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Deserialize, ToSchema)]
150pub struct AttrPath {
151 pub a: Attribute,
152 pub s: Option<SubAttribute>,
153}
154
155impl fmt::Display for AttrPath {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 if let Some(subattr) = self.s.as_ref() {
158 write!(f, "{}.{}", self.a, subattr)
159 } else {
160 write!(f, "{}", self.a)
161 }
162 }
163}
164
165impl From<Attribute> for AttrPath {
166 fn from(a: Attribute) -> Self {
167 Self { a, s: None }
168 }
169}
170
171impl From<(Attribute, SubAttribute)> for AttrPath {
172 fn from((a, s): (Attribute, SubAttribute)) -> Self {
173 Self { a, s: Some(s) }
174 }
175}
176
177#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
178pub enum ScimFilter {
179 Or(Box<ScimFilter>, Box<ScimFilter>),
180 And(Box<ScimFilter>, Box<ScimFilter>),
181 Not(Box<ScimFilter>),
182
183 Present(AttrPath),
184 Equal(AttrPath, JsonValue),
185 NotEqual(AttrPath, JsonValue),
186 Contains(AttrPath, JsonValue),
187 StartsWith(AttrPath, JsonValue),
188 EndsWith(AttrPath, JsonValue),
189 Greater(AttrPath, JsonValue),
190 Less(AttrPath, JsonValue),
191 GreaterOrEqual(AttrPath, JsonValue),
192 LessOrEqual(AttrPath, JsonValue),
193
194 Complex(Attribute, Box<ScimComplexFilter>),
195}
196
197impl fmt::Display for ScimFilter {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 match self {
200 Self::Equal(attrpath, value) => write!(f, "({attrpath} eq {value})"),
201 Self::Contains(attrpath, value) => write!(f, "({attrpath} co {value})"),
202 Self::Not(expr) => write!(f, "(not ({expr}))"),
203 Self::Or(this, that) => write!(f, "({this} or {that})"),
204 Self::And(this, that) => write!(f, "({this} and {that})"),
205 Self::EndsWith(attrpath, value) => write!(f, "({attrpath} ew {value})"),
206 Self::Greater(attrpath, value) => write!(f, "({attrpath} gt {value})"),
207 Self::GreaterOrEqual(attrpath, value) => {
208 write!(f, "({attrpath} ge {value})")
209 }
210 Self::Less(attrpath, value) => write!(f, "({attrpath} lt {value})"),
211 Self::LessOrEqual(attrpath, value) => write!(f, "({attrpath} le {value})"),
212 Self::NotEqual(attrpath, value) => write!(f, "({attrpath} ne {value})"),
213 Self::Present(attrpath) => write!(f, "({attrpath} pr)"),
214 Self::StartsWith(attrpath, value) => write!(f, "({attrpath} sw {value})"),
215 Self::Complex(attrname, expr) => write!(f, "{attrname}[{expr}]"),
216 }
217 }
218}
219
220#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
221pub enum ScimComplexFilter {
222 Or(Box<ScimComplexFilter>, Box<ScimComplexFilter>),
223 And(Box<ScimComplexFilter>, Box<ScimComplexFilter>),
224 Not(Box<ScimComplexFilter>),
225
226 Present(SubAttribute),
227 Equal(SubAttribute, JsonValue),
228 NotEqual(SubAttribute, JsonValue),
229 Contains(SubAttribute, JsonValue),
230 StartsWith(SubAttribute, JsonValue),
231 EndsWith(SubAttribute, JsonValue),
232 Greater(SubAttribute, JsonValue),
233 Less(SubAttribute, JsonValue),
234 GreaterOrEqual(SubAttribute, JsonValue),
235 LessOrEqual(SubAttribute, JsonValue),
236}
237
238impl fmt::Display for ScimComplexFilter {
239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240 match self {
241 Self::Equal(subattr, value) => write!(f, "({subattr} eq {value})"),
242 Self::Contains(subattr, value) => write!(f, "({subattr} co {value})"),
243 Self::Not(expr) => write!(f, "(not ({expr}))"),
244 Self::Or(this, that) => write!(f, "({this} or {that})"),
245 Self::And(this, that) => write!(f, "({this} and {that})"),
246 Self::EndsWith(subattr, value) => write!(f, "({subattr} ew {value})"),
247 Self::Greater(subattr, value) => write!(f, "({subattr} gt {value})"),
248 Self::GreaterOrEqual(subattr, value) => {
249 write!(f, "({subattr} ge {value})")
250 }
251 Self::Less(subattr, value) => write!(f, "({subattr} lt {value})"),
252 Self::LessOrEqual(subattr, value) => write!(f, "({subattr} le {value})"),
253 Self::NotEqual(subattr, value) => write!(f, "({subattr} ne {value})"),
254 Self::Present(subattr) => write!(f, "({subattr} pr)"),
255 Self::StartsWith(subattr, value) => write!(f, "({subattr} sw {value})"),
256 }
257 }
258}
259
260const SCIM_FILTER_MAX_DEPTH: usize = 128;
261
262peg::parser! {
263 grammar scimfilter() for str {
264
265 pub rule parse() -> ScimFilter =
266 f:parse_depth(SCIM_FILTER_MAX_DEPTH) { f }
267
268 pub(crate) rule parse_depth(max_depth: usize) -> ScimFilter =
269 limiter(max_depth) a:parse_inner(max_depth.saturating_sub(1)) { a }
270
271 rule limiter(max_depth: usize) -> () =
272 {? if max_depth == 0 { Err("too deeply nested") } else { Ok(()) } }
273
274 rule parse_inner(max_depth: usize) -> ScimFilter = precedence!{
277 "not" separator()+ "(" e:parse_depth(max_depth) ")" {
278 ScimFilter::Not(Box::new(e))
279 }
280 --
281 a:parse_inner_attr(max_depth) separator()+ "or" separator()+ b:parse_depth(max_depth) {
282 ScimFilter::Or(
283 Box::new(a),
284 Box::new(b)
285 )
286 }
287 --
288 a:parse_inner_attr(max_depth) separator()+ "and" separator()+ b:parse_depth(max_depth) {
289 ScimFilter::And(
290 Box::new(a),
291 Box::new(b)
292 )
293 }
294 --
295 "(" e:parse_depth(max_depth) ")" { e }
296 --
297 a:attrname()"[" e:parse_complex_depth(max_depth) "]" {
298 ScimFilter::Complex(
299 a,
300 Box::new(e)
301 )
302 }
303 --
304 a:parse_inner_attr(max_depth) { a }
305 }
306
307 rule parse_inner_attr(max_depth: usize) -> ScimFilter = precedence!{
308 a:attrname()"[" e:parse_complex_depth(max_depth) "]" {
309 ScimFilter::Complex(
310 a,
311 Box::new(e)
312 )
313 }
314 --
315 a:attrexp() { a }
316 }
317
318 pub rule parse_complex() -> ScimComplexFilter =
319 f:parse_complex_depth(SCIM_FILTER_MAX_DEPTH) { f }
320
321 pub(crate) rule parse_complex_depth(max_depth: usize) -> ScimComplexFilter =
322 limiter(max_depth) a:parse_complex_inner(max_depth.saturating_sub(1)) { a }
323
324 rule parse_complex_inner(max_depth: usize) -> ScimComplexFilter = precedence!{
325 a:complex_attrexp() separator()+ "or" separator()+ b:parse_complex_depth(max_depth) {
326 ScimComplexFilter::Or(
327 Box::new(a),
328 Box::new(b)
329 )
330 }
331 --
332 a:complex_attrexp() separator()+ "and" separator()+ b:parse_complex_depth(max_depth) {
333 ScimComplexFilter::And(
334 Box::new(a),
335 Box::new(b)
336 )
337 }
338 --
339 "not" separator()+ "(" e:parse_complex_depth(max_depth) ")" {
340 ScimComplexFilter::Not(Box::new(e))
341 }
342 --
343 "(" e:parse_complex_depth(max_depth) ")" { e }
344 a:complex_attrexp() { a }
345 }
346
347 pub(crate) rule attrexp() -> ScimFilter =
348 pres()
349 / eq()
350 / ne()
351 / co()
352 / sw()
353 / ew()
354 / gt()
355 / lt()
356 / ge()
357 / le()
358
359 pub(crate) rule pres() -> ScimFilter =
360 a:attrpath() separator()+ "pr" { ScimFilter::Present(a) }
361
362 pub(crate) rule eq() -> ScimFilter =
363 a:attrpath() separator()+ "eq" separator()+ v:value() { ScimFilter::Equal(a, v) }
364
365 pub(crate) rule ne() -> ScimFilter =
366 a:attrpath() separator()+ "ne" separator()+ v:value() { ScimFilter::NotEqual(a, v) }
367
368 pub(crate) rule co() -> ScimFilter =
369 a:attrpath() separator()+ "co" separator()+ v:value() { ScimFilter::Contains(a, v) }
370
371 pub(crate) rule sw() -> ScimFilter =
372 a:attrpath() separator()+ "sw" separator()+ v:value() { ScimFilter::StartsWith(a, v) }
373
374 pub(crate) rule ew() -> ScimFilter =
375 a:attrpath() separator()+ "ew" separator()+ v:value() { ScimFilter::EndsWith(a, v) }
376
377 pub(crate) rule gt() -> ScimFilter =
378 a:attrpath() separator()+ "gt" separator()+ v:value() { ScimFilter::Greater(a, v) }
379
380 pub(crate) rule lt() -> ScimFilter =
381 a:attrpath() separator()+ "lt" separator()+ v:value() { ScimFilter::Less(a, v) }
382
383 pub(crate) rule ge() -> ScimFilter =
384 a:attrpath() separator()+ "ge" separator()+ v:value() { ScimFilter::GreaterOrEqual(a, v) }
385
386 pub(crate) rule le() -> ScimFilter =
387 a:attrpath() separator()+ "le" separator()+ v:value() { ScimFilter::LessOrEqual(a, v) }
388
389 pub(crate) rule complex_attrexp() -> ScimComplexFilter =
390 c_pres()
391 / c_eq()
392 / c_ne()
393 / c_co()
394 / c_sw()
395 / c_ew()
396 / c_gt()
397 / c_lt()
398 / c_ge()
399 / c_le()
400
401 pub(crate) rule c_pres() -> ScimComplexFilter =
402 a:subattr() separator()+ "pr" { ScimComplexFilter::Present(a) }
403
404 pub(crate) rule c_eq() -> ScimComplexFilter =
405 a:subattr() separator()+ "eq" separator()+ v:value() { ScimComplexFilter::Equal(a, v) }
406
407 pub(crate) rule c_ne() -> ScimComplexFilter =
408 a:subattr() separator()+ "ne" separator()+ v:value() { ScimComplexFilter::NotEqual(a, v) }
409
410 pub(crate) rule c_co() -> ScimComplexFilter =
411 a:subattr() separator()+ "co" separator()+ v:value() { ScimComplexFilter::Contains(a, v) }
412
413 pub(crate) rule c_sw() -> ScimComplexFilter =
414 a:subattr() separator()+ "sw" separator()+ v:value() { ScimComplexFilter::StartsWith(a, v) }
415
416 pub(crate) rule c_ew() -> ScimComplexFilter =
417 a:subattr() separator()+ "ew" separator()+ v:value() { ScimComplexFilter::EndsWith(a, v) }
418
419 pub(crate) rule c_gt() -> ScimComplexFilter =
420 a:subattr() separator()+ "gt" separator()+ v:value() { ScimComplexFilter::Greater(a, v) }
421
422 pub(crate) rule c_lt() -> ScimComplexFilter =
423 a:subattr() separator()+ "lt" separator()+ v:value() { ScimComplexFilter::Less(a, v) }
424
425 pub(crate) rule c_ge() -> ScimComplexFilter =
426 a:subattr() separator()+ "ge" separator()+ v:value() { ScimComplexFilter::GreaterOrEqual(a, v) }
427
428 pub(crate) rule c_le() -> ScimComplexFilter =
429 a:subattr() separator()+ "le" separator()+ v:value() { ScimComplexFilter::LessOrEqual(a, v) }
430
431 rule separator() =
432 ['\n' | ' ' | '\t' ]
433
434 rule operator() =
435 ['\n' | ' ' | '\t' | '(' | ')' | '[' | ']' ]
436
437 rule value() -> JsonValue =
438 quotedvalue() / unquotedvalue()
439
440 rule quotedvalue() -> JsonValue =
441 s:$(['"'] ((['\\'][_]) / (!['"'][_]))* ['"']) {? serde_json::from_str(s).map_err(|_| "invalid json value" ) }
442
443 rule unquotedvalue() -> JsonValue =
444 s:$((!operator()[_])*) {? serde_json::from_str(s).map_err(|_| "invalid json value" ) }
445
446 pub(crate) rule attrpath() -> AttrPath =
447 a:attrname() s:dot_subattr()? { AttrPath { a, s } }
448
449 rule dot_subattr() -> SubAttribute =
450 "." s:subattr() { s }
451
452 rule subattr() -> SubAttribute =
453 s:attrstring() { SubAttribute::from(s.as_str()) }
454
455 pub(crate) rule attrname() -> Attribute =
456 s:attrstring() { Attribute::from(s.as_str()) }
457
458 pub(crate) rule attrstring() -> String =
459 s:$([ 'a'..='z' | 'A'..='Z']['a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' ]*) { s.to_string() }
460 }
461}
462
463impl FromStr for AttrPath {
464 type Err = peg::error::ParseError<peg::str::LineCol>;
465 fn from_str(input: &str) -> Result<Self, Self::Err> {
466 scimfilter::attrpath(input)
467 }
468}
469
470impl FromStr for ScimFilter {
471 type Err = peg::error::ParseError<peg::str::LineCol>;
472 fn from_str(input: &str) -> Result<Self, Self::Err> {
473 scimfilter::parse(input)
474 }
475}
476
477impl FromStr for ScimComplexFilter {
478 type Err = peg::error::ParseError<peg::str::LineCol>;
479 fn from_str(input: &str) -> Result<Self, Self::Err> {
480 scimfilter::parse_complex(input)
481 }
482}
483
484#[cfg(test)]
485mod tests {
486 use super::*;
487
488 #[test]
489 fn scim_rfc_to_generic() {
490 }
493
494 #[test]
495 fn scim_kani_to_generic() {
496 }
498
499 #[test]
500 fn scim_kani_to_rfc() {
501 }
503
504 #[test]
505 fn scim_sync_kani_to_rfc() {
506 use super::*;
507
508 let group_uuid = uuid::uuid!("2d0a9e7c-cc08-4ca2-8d7f-114f9abcfc8a");
510
511 let group = ScimSyncGroup::builder(
512 group_uuid,
513 "cn=testgroup".to_string(),
514 "testgroup".to_string(),
515 )
516 .set_description(Some("test desc".to_string()))
517 .set_gidnumber(Some(12345))
518 .set_members(vec!["member_a".to_string(), "member_a".to_string()].into_iter())
519 .build();
520
521 let entry: Result<ScimEntry, _> = group.try_into();
522
523 assert!(entry.is_ok());
524
525 let user_uuid = uuid::uuid!("cb3de098-33fd-4565-9d80-4f7ed6a664e9");
527
528 let user_sshkey = "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBENubZikrb8hu+HeVRdZ0pp/VAk2qv4JDbuJhvD0yNdWDL2e3cBbERiDeNPkWx58Q4rVnxkbV1fa8E2waRtT91wAAAAEc3NoOg== testuser@fidokey";
529
530 let person = ScimSyncPerson::builder(
531 user_uuid,
532 "cn=testuser".to_string(),
533 "testuser".to_string(),
534 "Test User".to_string(),
535 )
536 .set_password_import(Some("new_password".to_string()))
537 .set_unix_password_import(Some("new_password".to_string()))
538 .set_totp_import(vec![ScimTotp {
539 external_id: "Totp".to_string(),
540 secret: "abcd".to_string(),
541 algo: "SHA3".to_string(),
542 step: 60,
543 digits: 8,
544 }])
545 .set_mail(vec![MultiValueAttr {
546 primary: Some(true),
547 value: "testuser@example.com".to_string(),
548 ..Default::default()
549 }])
550 .set_ssh_publickey(vec![ScimSshPubKey {
551 label: "Key McKeyface".to_string(),
552 value: user_sshkey.to_string(),
553 }])
554 .set_login_shell(Some("/bin/false".to_string()))
555 .set_account_valid_from(Some("2023-11-28T04:57:55Z".to_string()))
556 .set_account_expire(Some("2023-11-28T04:57:55Z".to_string()))
557 .set_gidnumber(Some(54321))
558 .build();
559
560 let entry: Result<ScimEntry, _> = person.try_into();
561
562 assert!(entry.is_ok());
563 }
564
565 #[test]
566 fn scim_entry_get_query() {
567 use super::*;
568
569 let q = ScimEntryGetQuery {
570 attributes: None,
571 ..Default::default()
572 };
573
574 let txt = serde_urlencoded::to_string(&q).unwrap();
575
576 assert_eq!(txt, "");
577
578 let q = ScimEntryGetQuery {
579 attributes: Some(vec![Attribute::Name]),
580 ext_access_check: false,
581 ..Default::default()
582 };
583
584 let txt = serde_urlencoded::to_string(&q).unwrap();
585 assert_eq!(txt, "attributes=name");
586
587 let q = ScimEntryGetQuery {
588 attributes: Some(vec![Attribute::Name, Attribute::Spn]),
589 ext_access_check: true,
590 ..Default::default()
591 };
592
593 let txt = serde_urlencoded::to_string(&q).unwrap();
594 assert_eq!(txt, "attributes=name%2Cspn&extAccessCheck=true");
595 }
596
597 #[test]
598 fn test_scimfilter_attrname() {
599 assert_eq!(scimfilter::attrstring("abcd-_"), Ok("abcd-_".to_string()));
600 assert_eq!(scimfilter::attrstring("aB-_CD"), Ok("aB-_CD".to_string()));
601 assert_eq!(scimfilter::attrstring("a1-_23"), Ok("a1-_23".to_string()));
602 assert!(scimfilter::attrstring("-bcd").is_err());
603 assert!(scimfilter::attrstring("_bcd").is_err());
604 assert!(scimfilter::attrstring("0bcd").is_err());
605 }
606
607 #[test]
608 fn test_scimfilter_attrpath() {
609 assert_eq!(
610 scimfilter::attrpath("mail"),
611 Ok(AttrPath {
612 a: Attribute::from("mail"),
613 s: None
614 })
615 );
616
617 assert_eq!(
618 scimfilter::attrpath("mail.primary"),
619 Ok(AttrPath {
620 a: Attribute::from("mail"),
621 s: Some(SubAttribute::from("primary"))
622 })
623 );
624
625 assert!(scimfilter::attrname("mail.0").is_err());
626 assert!(scimfilter::attrname("mail._").is_err());
627 assert!(scimfilter::attrname("mail,0").is_err());
628 assert!(scimfilter::attrname(".primary").is_err());
629 }
630
631 #[test]
632 fn test_scimfilter_pres() {
633 assert!(
634 scimfilter::parse("mail pr")
635 == Ok(ScimFilter::Present(AttrPath {
636 a: Attribute::from("mail"),
637 s: None
638 }))
639 );
640 }
641
642 #[test]
643 fn test_scimfilter_eq() {
644 assert!(
645 scimfilter::parse("mail eq \"dcba\"")
646 == Ok(ScimFilter::Equal(
647 AttrPath {
648 a: Attribute::from("mail"),
649 s: None
650 },
651 JsonValue::String("dcba".to_string())
652 ))
653 );
654 }
655
656 #[test]
657 fn test_scimfilter_ne() {
658 assert!(
659 scimfilter::parse("mail ne \"dcba\"")
660 == Ok(ScimFilter::NotEqual(
661 AttrPath {
662 a: Attribute::from("mail"),
663 s: None
664 },
665 JsonValue::String("dcba".to_string())
666 ))
667 );
668 }
669
670 #[test]
671 fn test_scimfilter_co() {
672 assert!(
673 scimfilter::parse("mail co \"dcba\"")
674 == Ok(ScimFilter::Contains(
675 AttrPath {
676 a: Attribute::from("mail"),
677 s: None
678 },
679 JsonValue::String("dcba".to_string())
680 ))
681 );
682 }
683
684 #[test]
685 fn test_scimfilter_sw() {
686 assert!(
687 scimfilter::parse("mail sw \"dcba\"")
688 == Ok(ScimFilter::StartsWith(
689 AttrPath {
690 a: Attribute::from("mail"),
691 s: None
692 },
693 JsonValue::String("dcba".to_string())
694 ))
695 );
696 }
697
698 #[test]
699 fn test_scimfilter_ew() {
700 assert!(
701 scimfilter::parse("mail ew \"dcba\"")
702 == Ok(ScimFilter::EndsWith(
703 AttrPath {
704 a: Attribute::from("mail"),
705 s: None
706 },
707 JsonValue::String("dcba".to_string())
708 ))
709 );
710 }
711
712 #[test]
713 fn test_scimfilter_gt() {
714 assert!(
715 scimfilter::parse("mail gt \"dcba\"")
716 == Ok(ScimFilter::Greater(
717 AttrPath {
718 a: Attribute::from("mail"),
719 s: None
720 },
721 JsonValue::String("dcba".to_string())
722 ))
723 );
724 }
725
726 #[test]
727 fn test_scimfilter_lt() {
728 assert!(
729 scimfilter::parse("mail lt \"dcba\"")
730 == Ok(ScimFilter::Less(
731 AttrPath {
732 a: Attribute::from("mail"),
733 s: None
734 },
735 JsonValue::String("dcba".to_string())
736 ))
737 );
738 }
739
740 #[test]
741 fn test_scimfilter_ge() {
742 assert!(
743 scimfilter::parse("mail ge \"dcba\"")
744 == Ok(ScimFilter::GreaterOrEqual(
745 AttrPath {
746 a: Attribute::from("mail"),
747 s: None
748 },
749 JsonValue::String("dcba".to_string())
750 ))
751 );
752 }
753
754 #[test]
755 fn test_scimfilter_le() {
756 assert!(
757 scimfilter::parse("mail le \"dcba\"")
758 == Ok(ScimFilter::LessOrEqual(
759 AttrPath {
760 a: Attribute::from("mail"),
761 s: None
762 },
763 JsonValue::String("dcba".to_string())
764 ))
765 );
766 }
767
768 #[test]
769 fn test_scimfilter_group() {
770 let f = scimfilter::parse("(mail eq \"dcba\")");
771 eprintln!("{f:?}");
772 assert!(
773 f == Ok(ScimFilter::Equal(
774 AttrPath {
775 a: Attribute::from("mail"),
776 s: None
777 },
778 JsonValue::String("dcba".to_string())
779 ))
780 );
781 }
782
783 #[test]
784 fn test_scimfilter_not() {
785 let f = scimfilter::parse("not (mail eq \"dcba\")");
786 eprintln!("{f:?}");
787
788 assert!(
789 f == Ok(ScimFilter::Not(Box::new(ScimFilter::Equal(
790 AttrPath {
791 a: Attribute::from("mail"),
792 s: None
793 },
794 JsonValue::String("dcba".to_string())
795 ))))
796 );
797 }
798
799 #[test]
800 fn test_scimfilter_and() {
801 let f = scimfilter::parse("mail eq \"dcba\" and name ne \"1234\"");
802 eprintln!("{f:?}");
803
804 assert!(
805 f == Ok(ScimFilter::And(
806 Box::new(ScimFilter::Equal(
807 AttrPath {
808 a: Attribute::from("mail"),
809 s: None
810 },
811 JsonValue::String("dcba".to_string())
812 )),
813 Box::new(ScimFilter::NotEqual(
814 AttrPath {
815 a: Attribute::from("name"),
816 s: None
817 },
818 JsonValue::String("1234".to_string())
819 ))
820 ))
821 );
822 }
823
824 #[test]
825 fn test_scimfilter_or() {
826 let f = scimfilter::parse("mail eq \"dcba\" or name ne \"1234\"");
827 eprintln!("{f:?}");
828
829 assert!(
830 f == Ok(ScimFilter::Or(
831 Box::new(ScimFilter::Equal(
832 AttrPath {
833 a: Attribute::from("mail"),
834 s: None
835 },
836 JsonValue::String("dcba".to_string())
837 )),
838 Box::new(ScimFilter::NotEqual(
839 AttrPath {
840 a: Attribute::from("name"),
841 s: None
842 },
843 JsonValue::String("1234".to_string())
844 ))
845 ))
846 );
847 }
848
849 #[test]
850 fn test_scimfilter_complex() {
851 let f = scimfilter::parse("mail[type eq \"work\"]");
852 eprintln!("-- {f:?}");
853 assert!(f.is_ok());
854
855 let f = scimfilter::parse("mail[type eq \"work\" and value co \"@example.com\"] or testattr[type eq \"xmpp\" and value co \"@foo.com\"]");
856 eprintln!("{f:?}");
857
858 assert_eq!(
859 f,
860 Ok(ScimFilter::Or(
861 Box::new(ScimFilter::Complex(
862 Attribute::from("mail"),
863 Box::new(ScimComplexFilter::And(
864 Box::new(ScimComplexFilter::Equal(
865 SubAttribute::from("type"),
866 JsonValue::String("work".to_string())
867 )),
868 Box::new(ScimComplexFilter::Contains(
869 SubAttribute::from("value"),
870 JsonValue::String("@example.com".to_string())
871 ))
872 ))
873 )),
874 Box::new(ScimFilter::Complex(
875 Attribute::from("testattr"),
876 Box::new(ScimComplexFilter::And(
877 Box::new(ScimComplexFilter::Equal(
878 SubAttribute::from("type"),
879 JsonValue::String("xmpp".to_string())
880 )),
881 Box::new(ScimComplexFilter::Contains(
882 SubAttribute::from("value"),
883 JsonValue::String("@foo.com".to_string())
884 ))
885 ))
886 ))
887 ))
888 );
889 }
890
891 #[test]
1025 fn test_scimfilter_quoted_values() {
1026 assert_eq!(
1027 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""#),
1028 Ok(ScimFilter::Equal(
1029 AttrPath { a: Attribute::from("description"), s: None },
1030 JsonValue::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())
1031 ))
1032 );
1033 }
1034
1035 #[test]
1036 fn test_scimfilter_quoted_values_incomplete_escape() {
1037 let result = scimfilter::parse(r#"name eq "test\""#);
1038 assert!(result.is_err());
1039 }
1040
1041 #[test]
1042 fn test_scimfilter_quoted_values_empty() {
1043 assert_eq!(
1044 scimfilter::parse(r#"name eq """#),
1045 Ok(ScimFilter::Equal(
1046 AttrPath {
1047 a: Attribute::from("name"),
1048 s: None
1049 },
1050 JsonValue::String("".to_string())
1051 ))
1052 );
1053 }
1054
1055 #[test]
1056 fn test_scimfilter_recursion_limit() {
1057 scimfilter::parse_depth("name pr and (name pr and (name pr and name pr))", 0)
1058 .expect_err("Must fail");
1059
1060 scimfilter::parse_depth("name pr and (name pr and (name pr and name pr))", 1)
1061 .expect_err("Must fail");
1062
1063 scimfilter::parse_depth("name pr and (name pr and (name pr and name pr))", 5)
1064 .expect_err("Must fail");
1065
1066 scimfilter::parse_depth("name pr and (name pr and (name pr and name pr))", 6)
1067 .expect("Must pass");
1068
1069 scimfilter::parse_depth("((name pr and name pr))", 0).expect_err("Must fail");
1070
1071 scimfilter::parse_depth("((name pr and name pr))", 1).expect_err("Must fail");
1072
1073 scimfilter::parse_depth("((name pr and name pr))", 3).expect_err("Must fail");
1074
1075 scimfilter::parse_depth("((name pr and name pr))", 4).expect("Must pass");
1076
1077 scimfilter::parse_depth("name pr and name pr and name pr and name pr", 0)
1078 .expect_err("Must fail");
1079
1080 scimfilter::parse_depth("name pr and name pr and name pr and name pr", 1)
1081 .expect_err("Must fail");
1082
1083 scimfilter::parse_depth("name pr and name pr and name pr and name pr", 3)
1084 .expect_err("Must fail");
1085
1086 scimfilter::parse_depth("name pr and name pr and name pr and name pr", 4)
1087 .expect("Must pass");
1088 }
1089}