1use crate::errors::{AuthError, Result};
20use serde::{Deserialize, Serialize};
21use std::collections::HashMap;
22
23pub mod schema {
27 pub const USER: &str = "urn:ietf:params:scim:schemas:core:2.0:User";
28 pub const GROUP: &str = "urn:ietf:params:scim:schemas:core:2.0:Group";
29 pub const ENTERPRISE_USER: &str = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User";
30 pub const LIST_RESPONSE: &str = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
31 pub const PATCH_OP: &str = "urn:ietf:params:scim:api:messages:2.0:PatchOp";
32 pub const BULK_REQUEST: &str = "urn:ietf:params:scim:api:messages:2.0:BulkRequest";
33 pub const BULK_RESPONSE: &str = "urn:ietf:params:scim:api:messages:2.0:BulkResponse";
34 pub const ERROR: &str = "urn:ietf:params:scim:api:messages:2.0:Error";
35 pub const SEARCH_REQUEST: &str = "urn:ietf:params:scim:api:messages:2.0:SearchRequest";
36 pub const SERVICE_PROVIDER_CONFIG: &str =
37 "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig";
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43pub struct Meta {
44 pub resource_type: String,
45 pub created: Option<String>,
46 pub last_modified: Option<String>,
47 pub location: Option<String>,
48 pub version: Option<String>,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct MultiValuedAttr {
54 pub value: String,
55 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
56 pub attr_type: Option<String>,
57 #[serde(skip_serializing_if = "Option::is_none")]
58 pub primary: Option<bool>,
59 #[serde(skip_serializing_if = "Option::is_none")]
60 pub display: Option<String>,
61}
62
63#[derive(Debug, Clone, Default, Serialize, Deserialize)]
65#[serde(rename_all = "camelCase")]
66pub struct Name {
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub formatted: Option<String>,
69 #[serde(skip_serializing_if = "Option::is_none")]
70 pub family_name: Option<String>,
71 #[serde(skip_serializing_if = "Option::is_none")]
72 pub given_name: Option<String>,
73 #[serde(skip_serializing_if = "Option::is_none")]
74 pub middle_name: Option<String>,
75 #[serde(skip_serializing_if = "Option::is_none")]
76 pub honorific_prefix: Option<String>,
77 #[serde(skip_serializing_if = "Option::is_none")]
78 pub honorific_suffix: Option<String>,
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize)]
83#[serde(rename_all = "camelCase")]
84pub struct ScimUser {
85 pub schemas: Vec<String>,
87
88 #[serde(skip_serializing_if = "Option::is_none")]
90 pub id: Option<String>,
91
92 pub user_name: String,
94
95 #[serde(skip_serializing_if = "Option::is_none")]
97 pub name: Option<Name>,
98
99 #[serde(skip_serializing_if = "Option::is_none")]
101 pub display_name: Option<String>,
102
103 #[serde(skip_serializing_if = "Option::is_none")]
105 pub emails: Option<Vec<MultiValuedAttr>>,
106
107 #[serde(skip_serializing_if = "Option::is_none")]
109 pub phone_numbers: Option<Vec<MultiValuedAttr>>,
110
111 #[serde(skip_serializing_if = "Option::is_none")]
113 pub active: Option<bool>,
114
115 #[serde(skip_serializing_if = "Option::is_none")]
117 pub meta: Option<Meta>,
118
119 #[serde(skip_serializing_if = "Option::is_none")]
121 pub groups: Option<Vec<MultiValuedAttr>>,
122
123 #[serde(flatten)]
125 pub extensions: HashMap<String, serde_json::Value>,
126}
127
128impl ScimUser {
129 pub fn new(user_name: impl Into<String>) -> Self {
131 Self {
132 schemas: vec![schema::USER.to_string()],
133 id: None,
134 user_name: user_name.into(),
135 name: None,
136 display_name: None,
137 emails: None,
138 phone_numbers: None,
139 active: Some(true),
140 meta: None,
141 groups: None,
142 extensions: HashMap::new(),
143 }
144 }
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize)]
149#[serde(rename_all = "camelCase")]
150pub struct ScimGroup {
151 pub schemas: Vec<String>,
152
153 #[serde(skip_serializing_if = "Option::is_none")]
154 pub id: Option<String>,
155
156 pub display_name: String,
157
158 #[serde(skip_serializing_if = "Option::is_none")]
159 pub members: Option<Vec<MultiValuedAttr>>,
160
161 #[serde(skip_serializing_if = "Option::is_none")]
162 pub meta: Option<Meta>,
163}
164
165impl ScimGroup {
166 pub fn new(display_name: impl Into<String>) -> Self {
167 Self {
168 schemas: vec![schema::GROUP.to_string()],
169 id: None,
170 display_name: display_name.into(),
171 members: None,
172 meta: None,
173 }
174 }
175}
176
177#[derive(Debug, Clone, Serialize, Deserialize)]
181#[serde(rename_all = "camelCase")]
182pub struct ListResponse<T> {
183 pub schemas: Vec<String>,
184 pub total_results: u64,
185 #[serde(skip_serializing_if = "Option::is_none")]
186 pub start_index: Option<u64>,
187 #[serde(skip_serializing_if = "Option::is_none")]
188 pub items_per_page: Option<u64>,
189 #[serde(rename = "Resources")]
190 pub resources: Vec<T>,
191}
192
193#[derive(Debug, Clone, Serialize, Deserialize)]
195pub struct PatchOp {
196 pub schemas: Vec<String>,
197 #[serde(rename = "Operations")]
198 pub operations: Vec<PatchOperation>,
199}
200
201#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct PatchOperation {
204 pub op: PatchOpType,
205 #[serde(skip_serializing_if = "Option::is_none")]
206 pub path: Option<String>,
207 #[serde(skip_serializing_if = "Option::is_none")]
208 pub value: Option<serde_json::Value>,
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
213#[serde(rename_all = "lowercase")]
214pub enum PatchOpType {
215 Add,
216 Remove,
217 Replace,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase")]
223pub struct BulkRequest {
224 pub schemas: Vec<String>,
225 #[serde(skip_serializing_if = "Option::is_none")]
226 pub fail_on_errors: Option<u32>,
227 #[serde(rename = "Operations")]
228 pub operations: Vec<BulkOperation>,
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize)]
233#[serde(rename_all = "camelCase")]
234pub struct BulkResponse {
235 pub schemas: Vec<String>,
236 #[serde(rename = "Operations")]
237 pub operations: Vec<BulkOperationResponse>,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize)]
242#[serde(rename_all = "camelCase")]
243pub struct BulkOperation {
244 pub method: BulkMethod,
245 #[serde(skip_serializing_if = "Option::is_none")]
246 pub bulk_id: Option<String>,
247 #[serde(skip_serializing_if = "Option::is_none")]
248 pub path: Option<String>,
249 #[serde(skip_serializing_if = "Option::is_none")]
250 pub data: Option<serde_json::Value>,
251}
252
253#[derive(Debug, Clone, Serialize, Deserialize)]
255#[serde(rename_all = "camelCase")]
256pub struct BulkOperationResponse {
257 pub method: BulkMethod,
258 #[serde(skip_serializing_if = "Option::is_none")]
259 pub bulk_id: Option<String>,
260 #[serde(skip_serializing_if = "Option::is_none")]
261 pub location: Option<String>,
262 #[serde(skip_serializing_if = "Option::is_none")]
263 pub status: Option<String>,
264 #[serde(skip_serializing_if = "Option::is_none")]
265 pub response: Option<serde_json::Value>,
266}
267
268#[derive(Debug, Clone, Serialize, Deserialize)]
269#[serde(rename_all = "UPPERCASE")]
270pub enum BulkMethod {
271 Post,
272 Put,
273 Patch,
274 Delete,
275}
276
277#[derive(Debug, Clone, Serialize, Deserialize)]
279#[serde(rename_all = "camelCase")]
280pub struct ScimError {
281 pub schemas: Vec<String>,
282 #[serde(skip_serializing_if = "Option::is_none")]
283 pub status: Option<String>,
284 #[serde(skip_serializing_if = "Option::is_none")]
285 pub scim_type: Option<String>,
286 #[serde(skip_serializing_if = "Option::is_none")]
287 pub detail: Option<String>,
288}
289
290#[derive(Debug, Clone, Serialize, Deserialize)]
292#[serde(rename_all = "camelCase")]
293pub struct SearchRequest {
294 pub schemas: Vec<String>,
295 #[serde(skip_serializing_if = "Option::is_none")]
296 pub filter: Option<String>,
297 #[serde(skip_serializing_if = "Option::is_none")]
298 pub sort_by: Option<String>,
299 #[serde(skip_serializing_if = "Option::is_none")]
300 pub sort_order: Option<String>,
301 #[serde(skip_serializing_if = "Option::is_none")]
302 pub start_index: Option<u64>,
303 #[serde(skip_serializing_if = "Option::is_none")]
304 pub count: Option<u64>,
305 #[serde(skip_serializing_if = "Option::is_none")]
306 pub attributes: Option<Vec<String>>,
307 #[serde(skip_serializing_if = "Option::is_none")]
308 pub excluded_attributes: Option<Vec<String>>,
309}
310
311#[derive(Debug, Clone, Serialize, Deserialize)]
313#[serde(rename_all = "camelCase")]
314pub struct ServiceProviderConfig {
315 pub schemas: Vec<String>,
316 pub patch: Supported,
317 pub bulk: BulkSupported,
318 pub filter: FilterSupported,
319 pub change_password: Supported,
320 pub sort: Supported,
321 pub etag: Supported,
322 pub authentication_schemes: Vec<AuthenticationScheme>,
323}
324
325#[derive(Debug, Clone, Serialize, Deserialize)]
326pub struct Supported {
327 pub supported: bool,
328}
329
330#[derive(Debug, Clone, Serialize, Deserialize)]
331#[serde(rename_all = "camelCase")]
332pub struct BulkSupported {
333 pub supported: bool,
334 pub max_operations: u32,
335 pub max_payload_size: u64,
336}
337
338#[derive(Debug, Clone, Serialize, Deserialize)]
339#[serde(rename_all = "camelCase")]
340pub struct FilterSupported {
341 pub supported: bool,
342 pub max_results: u32,
343}
344
345#[derive(Debug, Clone, Serialize, Deserialize)]
346#[serde(rename_all = "camelCase")]
347pub struct AuthenticationScheme {
348 pub name: String,
349 pub description: String,
350 #[serde(rename = "type")]
351 pub scheme_type: String,
352 #[serde(skip_serializing_if = "Option::is_none")]
353 pub spec_uri: Option<String>,
354 #[serde(skip_serializing_if = "Option::is_none")]
355 pub documentation_uri: Option<String>,
356 pub primary: bool,
357}
358
359#[derive(Clone)]
363pub struct ScimClientConfig {
364 pub base_url: String,
366
367 pub bearer_token: String,
369
370 pub timeout_secs: u64,
372}
373
374impl std::fmt::Debug for ScimClientConfig {
375 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376 let mut d = f.debug_struct("ScimClientConfig");
377 d.field("base_url", &self.base_url);
378 d.field(
379 "bearer_token",
380 &crate::utils::redact::redacted(&self.bearer_token),
381 );
382 d.field("timeout_secs", &self.timeout_secs);
383 d.finish()
384 }
385}
386
387pub struct ScimClient {
389 config: ScimClientConfig,
390 http: reqwest::Client,
391}
392
393impl ScimClient {
394 pub fn new(config: ScimClientConfig) -> Result<Self> {
396 if !config.base_url.starts_with("https://") {
397 return Err(AuthError::config(
398 "SCIM base URL must use HTTPS for security",
399 ));
400 }
401
402 let http = reqwest::Client::builder()
403 .timeout(std::time::Duration::from_secs(config.timeout_secs))
404 .build()
405 .map_err(|e| AuthError::internal(format!("Failed to build HTTP client: {e}")))?;
406
407 Ok(Self { config, http })
408 }
409
410 pub async fn create_user(&self, user: &ScimUser) -> Result<ScimUser> {
414 let url = format!("{}/Users", self.config.base_url);
415 let resp = self
416 .http
417 .post(&url)
418 .bearer_auth(&self.config.bearer_token)
419 .json(user)
420 .send()
421 .await
422 .map_err(|e| AuthError::internal(format!("SCIM create user request failed: {e}")))?;
423
424 if !resp.status().is_success() {
425 let status = resp.status();
426 let body = resp.text().await.unwrap_or_default();
427 return Err(AuthError::internal(format!(
428 "SCIM create user failed (HTTP {status}): {body}"
429 )));
430 }
431
432 resp.json::<ScimUser>()
433 .await
434 .map_err(|e| AuthError::internal(format!("SCIM create user parse error: {e}")))
435 }
436
437 pub async fn get_user(&self, id: &str) -> Result<ScimUser> {
439 let url = format!("{}/Users/{}", self.config.base_url, id);
440 let resp = self
441 .http
442 .get(&url)
443 .bearer_auth(&self.config.bearer_token)
444 .send()
445 .await
446 .map_err(|e| AuthError::internal(format!("SCIM get user request failed: {e}")))?;
447
448 if !resp.status().is_success() {
449 let status = resp.status();
450 let body = resp.text().await.unwrap_or_default();
451 return Err(AuthError::internal(format!(
452 "SCIM get user failed (HTTP {status}): {body}"
453 )));
454 }
455
456 resp.json::<ScimUser>()
457 .await
458 .map_err(|e| AuthError::internal(format!("SCIM get user parse error: {e}")))
459 }
460
461 pub async fn replace_user(&self, id: &str, user: &ScimUser) -> Result<ScimUser> {
463 let url = format!("{}/Users/{}", self.config.base_url, id);
464 let resp = self
465 .http
466 .put(&url)
467 .bearer_auth(&self.config.bearer_token)
468 .json(user)
469 .send()
470 .await
471 .map_err(|e| AuthError::internal(format!("SCIM replace user request failed: {e}")))?;
472
473 if !resp.status().is_success() {
474 let status = resp.status();
475 let body = resp.text().await.unwrap_or_default();
476 return Err(AuthError::internal(format!(
477 "SCIM replace user failed (HTTP {status}): {body}"
478 )));
479 }
480
481 resp.json::<ScimUser>()
482 .await
483 .map_err(|e| AuthError::internal(format!("SCIM replace user parse error: {e}")))
484 }
485
486 pub async fn patch_user(&self, id: &str, patch: &PatchOp) -> Result<ScimUser> {
488 let url = format!("{}/Users/{}", self.config.base_url, id);
489 let resp = self
490 .http
491 .patch(&url)
492 .bearer_auth(&self.config.bearer_token)
493 .json(patch)
494 .send()
495 .await
496 .map_err(|e| AuthError::internal(format!("SCIM patch user request failed: {e}")))?;
497
498 if !resp.status().is_success() {
499 let status = resp.status();
500 let body = resp.text().await.unwrap_or_default();
501 return Err(AuthError::internal(format!(
502 "SCIM patch user failed (HTTP {status}): {body}"
503 )));
504 }
505
506 resp.json::<ScimUser>()
507 .await
508 .map_err(|e| AuthError::internal(format!("SCIM patch user parse error: {e}")))
509 }
510
511 pub async fn delete_user(&self, id: &str) -> Result<()> {
513 let url = format!("{}/Users/{}", self.config.base_url, id);
514 let resp = self
515 .http
516 .delete(&url)
517 .bearer_auth(&self.config.bearer_token)
518 .send()
519 .await
520 .map_err(|e| AuthError::internal(format!("SCIM delete user request failed: {e}")))?;
521
522 if !resp.status().is_success() {
523 let status = resp.status();
524 let body = resp.text().await.unwrap_or_default();
525 return Err(AuthError::internal(format!(
526 "SCIM delete user failed (HTTP {status}): {body}"
527 )));
528 }
529
530 Ok(())
531 }
532
533 pub async fn list_users(
535 &self,
536 filter: Option<&str>,
537 start_index: Option<u64>,
538 count: Option<u64>,
539 ) -> Result<ListResponse<ScimUser>> {
540 let mut url = format!("{}/Users", self.config.base_url);
541 let mut params = Vec::new();
542 if let Some(f) = filter {
543 params.push(format!("filter={}", urlencoding::encode(f)));
544 }
545 if let Some(si) = start_index {
546 params.push(format!("startIndex={si}"));
547 }
548 if let Some(c) = count {
549 params.push(format!("count={c}"));
550 }
551 if !params.is_empty() {
552 url = format!("{}?{}", url, params.join("&"));
553 }
554
555 let resp = self
556 .http
557 .get(&url)
558 .bearer_auth(&self.config.bearer_token)
559 .send()
560 .await
561 .map_err(|e| AuthError::internal(format!("SCIM list users request failed: {e}")))?;
562
563 if !resp.status().is_success() {
564 let status = resp.status();
565 let body = resp.text().await.unwrap_or_default();
566 return Err(AuthError::internal(format!(
567 "SCIM list users failed (HTTP {status}): {body}"
568 )));
569 }
570
571 resp.json::<ListResponse<ScimUser>>()
572 .await
573 .map_err(|e| AuthError::internal(format!("SCIM list users parse error: {e}")))
574 }
575
576 pub async fn create_group(&self, group: &ScimGroup) -> Result<ScimGroup> {
580 let url = format!("{}/Groups", self.config.base_url);
581 let resp = self
582 .http
583 .post(&url)
584 .bearer_auth(&self.config.bearer_token)
585 .json(group)
586 .send()
587 .await
588 .map_err(|e| AuthError::internal(format!("SCIM create group request failed: {e}")))?;
589
590 if !resp.status().is_success() {
591 let status = resp.status();
592 let body = resp.text().await.unwrap_or_default();
593 return Err(AuthError::internal(format!(
594 "SCIM create group failed (HTTP {status}): {body}"
595 )));
596 }
597
598 resp.json::<ScimGroup>()
599 .await
600 .map_err(|e| AuthError::internal(format!("SCIM create group parse error: {e}")))
601 }
602
603 pub async fn get_group(&self, id: &str) -> Result<ScimGroup> {
605 let url = format!("{}/Groups/{}", self.config.base_url, id);
606 let resp = self
607 .http
608 .get(&url)
609 .bearer_auth(&self.config.bearer_token)
610 .send()
611 .await
612 .map_err(|e| AuthError::internal(format!("SCIM get group request failed: {e}")))?;
613
614 if !resp.status().is_success() {
615 let status = resp.status();
616 let body = resp.text().await.unwrap_or_default();
617 return Err(AuthError::internal(format!(
618 "SCIM get group failed (HTTP {status}): {body}"
619 )));
620 }
621
622 resp.json::<ScimGroup>()
623 .await
624 .map_err(|e| AuthError::internal(format!("SCIM get group parse error: {e}")))
625 }
626
627 pub async fn delete_group(&self, id: &str) -> Result<()> {
629 let url = format!("{}/Groups/{}", self.config.base_url, id);
630 let resp = self
631 .http
632 .delete(&url)
633 .bearer_auth(&self.config.bearer_token)
634 .send()
635 .await
636 .map_err(|e| AuthError::internal(format!("SCIM delete group request failed: {e}")))?;
637
638 if !resp.status().is_success() {
639 let status = resp.status();
640 let body = resp.text().await.unwrap_or_default();
641 return Err(AuthError::internal(format!(
642 "SCIM delete group failed (HTTP {status}): {body}"
643 )));
644 }
645
646 Ok(())
647 }
648
649 pub async fn list_groups(
651 &self,
652 filter: Option<&str>,
653 start_index: Option<u64>,
654 count: Option<u64>,
655 ) -> Result<ListResponse<ScimGroup>> {
656 let mut url = format!("{}/Groups", self.config.base_url);
657 let mut params = Vec::new();
658 if let Some(f) = filter {
659 params.push(format!("filter={}", urlencoding::encode(f)));
660 }
661 if let Some(si) = start_index {
662 params.push(format!("startIndex={si}"));
663 }
664 if let Some(c) = count {
665 params.push(format!("count={c}"));
666 }
667 if !params.is_empty() {
668 url = format!("{}?{}", url, params.join("&"));
669 }
670
671 let resp = self
672 .http
673 .get(&url)
674 .bearer_auth(&self.config.bearer_token)
675 .send()
676 .await
677 .map_err(|e| AuthError::internal(format!("SCIM list groups request failed: {e}")))?;
678
679 if !resp.status().is_success() {
680 let status = resp.status();
681 let body = resp.text().await.unwrap_or_default();
682 return Err(AuthError::internal(format!(
683 "SCIM list groups failed (HTTP {status}): {body}"
684 )));
685 }
686
687 resp.json::<ListResponse<ScimGroup>>()
688 .await
689 .map_err(|e| AuthError::internal(format!("SCIM list groups parse error: {e}")))
690 }
691
692 pub async fn bulk(&self, request: &BulkRequest) -> Result<BulkResponse> {
696 let url = format!("{}/Bulk", self.config.base_url);
697 let resp = self
698 .http
699 .post(&url)
700 .bearer_auth(&self.config.bearer_token)
701 .json(request)
702 .send()
703 .await
704 .map_err(|e| AuthError::internal(format!("SCIM bulk request failed: {e}")))?;
705
706 if !resp.status().is_success() {
707 let status = resp.status();
708 let body = resp.text().await.unwrap_or_default();
709 return Err(AuthError::internal(format!(
710 "SCIM bulk request failed (HTTP {status}): {body}"
711 )));
712 }
713
714 resp.json::<BulkResponse>()
715 .await
716 .map_err(|e| AuthError::internal(format!("SCIM bulk response parse error: {e}")))
717 }
718
719 pub async fn get_service_provider_config(&self) -> Result<ServiceProviderConfig> {
723 let url = format!("{}/ServiceProviderConfig", self.config.base_url);
724 let resp = self
725 .http
726 .get(&url)
727 .bearer_auth(&self.config.bearer_token)
728 .send()
729 .await
730 .map_err(|e| {
731 AuthError::internal(format!("SCIM service provider config request failed: {e}"))
732 })?;
733
734 if !resp.status().is_success() {
735 let status = resp.status();
736 let body = resp.text().await.unwrap_or_default();
737 return Err(AuthError::internal(format!(
738 "SCIM service provider config failed (HTTP {status}): {body}"
739 )));
740 }
741
742 resp.json::<ServiceProviderConfig>().await.map_err(|e| {
743 AuthError::internal(format!("SCIM service provider config parse error: {e}"))
744 })
745 }
746}
747
748impl PatchOp {
751 pub fn new(operations: Vec<PatchOperation>) -> Self {
753 Self {
754 schemas: vec![schema::PATCH_OP.to_string()],
755 operations,
756 }
757 }
758}
759
760impl SearchRequest {
761 pub fn with_filter(filter: impl Into<String>) -> Self {
763 Self {
764 schemas: vec![schema::SEARCH_REQUEST.to_string()],
765 filter: Some(filter.into()),
766 sort_by: None,
767 sort_order: None,
768 start_index: None,
769 count: None,
770 attributes: None,
771 excluded_attributes: None,
772 }
773 }
774}
775
776impl BulkRequest {
777 pub fn new(operations: Vec<BulkOperation>, fail_on_errors: Option<u32>) -> Self {
779 Self {
780 schemas: vec![schema::BULK_REQUEST.to_string()],
781 fail_on_errors,
782 operations,
783 }
784 }
785}
786
787#[cfg(test)]
788mod tests {
789 use super::*;
790
791 #[test]
792 fn test_scim_user_serialization() {
793 let mut user = ScimUser::new("jdoe");
794 user.name = Some(Name {
795 given_name: Some("John".into()),
796 family_name: Some("Doe".into()),
797 ..Default::default()
798 });
799 user.emails = Some(vec![MultiValuedAttr {
800 value: "jdoe@example.com".into(),
801 attr_type: Some("work".into()),
802 primary: Some(true),
803 display: None,
804 }]);
805
806 let json = serde_json::to_string(&user).expect("serialize");
807 assert!(json.contains("\"userName\":\"jdoe\""));
808 assert!(json.contains(schema::USER));
809 }
810
811 #[test]
812 fn test_scim_group_serialization() {
813 let group = ScimGroup::new("Engineering");
814 let json = serde_json::to_string(&group).expect("serialize");
815 assert!(json.contains("\"displayName\":\"Engineering\""));
816 assert!(json.contains(schema::GROUP));
817 }
818
819 #[test]
820 fn test_patch_op_construction() {
821 let patch = PatchOp::new(vec![PatchOperation {
822 op: PatchOpType::Replace,
823 path: Some("active".into()),
824 value: Some(serde_json::Value::Bool(false)),
825 }]);
826 assert_eq!(patch.schemas[0], schema::PATCH_OP);
827 assert_eq!(patch.operations.len(), 1);
828 }
829
830 #[test]
831 fn test_scim_user_roundtrip() {
832 let user = ScimUser::new("alice");
833 let json = serde_json::to_value(&user).expect("to value");
834 let parsed: ScimUser = serde_json::from_value(json).expect("from value");
835 assert_eq!(parsed.user_name, "alice");
836 assert_eq!(parsed.active, Some(true));
837 }
838
839 #[test]
840 fn test_bulk_request_construction() {
841 let bulk = BulkRequest::new(
842 vec![BulkOperation {
843 method: BulkMethod::Post,
844 bulk_id: Some("op1".into()),
845 path: Some("/Users".into()),
846 data: Some(serde_json::to_value(ScimUser::new("bulk_user")).expect("val")),
847 }],
848 Some(1),
849 );
850 assert_eq!(bulk.schemas[0], schema::BULK_REQUEST);
851 assert_eq!(bulk.fail_on_errors, Some(1));
852 }
853
854 #[test]
855 fn test_scim_user_empty_username() {
856 let user = ScimUser::new("");
857 assert_eq!(user.user_name, "");
858 let json = serde_json::to_value(&user).unwrap();
860 let parsed: ScimUser = serde_json::from_value(json).unwrap();
861 assert_eq!(parsed.user_name, "");
862 }
863
864 #[test]
865 fn test_scim_user_all_optional_fields() {
866 let mut user = ScimUser::new("fulluser");
867 user.id = Some("u-123".into());
868 user.display_name = Some("Full User".into());
869 user.name = Some(Name {
870 formatted: Some("Dr. Full A. User Jr.".into()),
871 family_name: Some("User".into()),
872 given_name: Some("Full".into()),
873 middle_name: Some("A".into()),
874 honorific_prefix: Some("Dr.".into()),
875 honorific_suffix: Some("Jr.".into()),
876 });
877 user.emails = Some(vec![
878 MultiValuedAttr {
879 value: "work@example.com".into(),
880 attr_type: Some("work".into()),
881 primary: Some(true),
882 display: Some("Work Email".into()),
883 },
884 MultiValuedAttr {
885 value: "home@example.com".into(),
886 attr_type: Some("home".into()),
887 primary: Some(false),
888 display: None,
889 },
890 ]);
891 user.phone_numbers = Some(vec![MultiValuedAttr {
892 value: "+1-555-0100".into(),
893 attr_type: Some("mobile".into()),
894 primary: Some(true),
895 display: None,
896 }]);
897 user.active = Some(false);
898 user.groups = Some(vec![MultiValuedAttr {
899 value: "g-eng".into(),
900 attr_type: None,
901 primary: None,
902 display: Some("Engineering".into()),
903 }]);
904
905 let json = serde_json::to_string(&user).unwrap();
906 let parsed: ScimUser =
907 serde_json::from_value(serde_json::from_str(&json).unwrap()).unwrap();
908 assert_eq!(parsed.id.as_deref(), Some("u-123"));
909 assert_eq!(parsed.display_name.as_deref(), Some("Full User"));
910 assert_eq!(parsed.active, Some(false));
911 assert_eq!(parsed.emails.as_ref().unwrap().len(), 2);
912 assert_eq!(parsed.phone_numbers.as_ref().unwrap().len(), 1);
913 assert_eq!(parsed.groups.as_ref().unwrap().len(), 1);
914 let name = parsed.name.as_ref().unwrap();
915 assert_eq!(name.honorific_prefix.as_deref(), Some("Dr."));
916 assert_eq!(name.honorific_suffix.as_deref(), Some("Jr."));
917 }
918
919 #[test]
920 fn test_scim_user_deserialization_from_json() {
921 let json_str = r#"{
922 "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
923 "id": "server-1",
924 "userName": "jdoe",
925 "displayName": "Jane Doe",
926 "active": true,
927 "meta": {
928 "resourceType": "User",
929 "created": "2024-01-01T00:00:00Z",
930 "lastModified": "2024-06-01T00:00:00Z",
931 "location": "https://scim.example.com/Users/server-1",
932 "version": "W/\"1\""
933 }
934 }"#;
935
936 let user: ScimUser = serde_json::from_str(json_str).unwrap();
937 assert_eq!(user.user_name, "jdoe");
938 assert_eq!(user.id.as_deref(), Some("server-1"));
939 assert_eq!(user.display_name.as_deref(), Some("Jane Doe"));
940 let meta = user.meta.as_ref().unwrap();
941 assert_eq!(meta.resource_type, "User");
942 assert_eq!(meta.version.as_deref(), Some("W/\"1\""));
943 }
944
945 #[test]
946 fn test_scim_group_with_members() {
947 let mut group = ScimGroup::new("DevOps");
948 group.members = Some(vec![
949 MultiValuedAttr {
950 value: "u-1".into(),
951 attr_type: Some("User".into()),
952 primary: None,
953 display: Some("Alice".into()),
954 },
955 MultiValuedAttr {
956 value: "u-2".into(),
957 attr_type: Some("User".into()),
958 primary: None,
959 display: Some("Bob".into()),
960 },
961 ]);
962
963 let json = serde_json::to_string(&group).unwrap();
964 let parsed: ScimGroup = serde_json::from_str(&json).unwrap();
965 assert_eq!(parsed.display_name, "DevOps");
966 let members = parsed.members.unwrap();
967 assert_eq!(members.len(), 2);
968 assert_eq!(members[0].display.as_deref(), Some("Alice"));
969 }
970
971 #[test]
972 fn test_patch_op_add_and_remove() {
973 let patch = PatchOp::new(vec![
974 PatchOperation {
975 op: PatchOpType::Add,
976 path: Some("emails".into()),
977 value: Some(serde_json::json!([{"value": "new@example.com", "type": "work"}])),
978 },
979 PatchOperation {
980 op: PatchOpType::Remove,
981 path: Some("phoneNumbers".into()),
982 value: None,
983 },
984 ]);
985
986 assert_eq!(patch.operations.len(), 2);
987
988 let json = serde_json::to_string(&patch).unwrap();
990 assert!(json.contains("\"add\""));
991 assert!(json.contains("\"remove\""));
992 assert!(json.contains("new@example.com"));
993 }
994
995 #[test]
996 fn test_bulk_request_multiple_operations() {
997 let bulk = BulkRequest::new(
998 vec![
999 BulkOperation {
1000 method: BulkMethod::Post,
1001 bulk_id: Some("create-1".into()),
1002 path: Some("/Users".into()),
1003 data: Some(serde_json::to_value(ScimUser::new("user1")).unwrap()),
1004 },
1005 BulkOperation {
1006 method: BulkMethod::Put,
1007 bulk_id: Some("update-1".into()),
1008 path: Some("/Users/existing-id".into()),
1009 data: Some(serde_json::to_value(ScimUser::new("user1_updated")).unwrap()),
1010 },
1011 BulkOperation {
1012 method: BulkMethod::Delete,
1013 bulk_id: Some("delete-1".into()),
1014 path: Some("/Users/old-id".into()),
1015 data: None,
1016 },
1017 ],
1018 Some(2),
1019 );
1020
1021 assert_eq!(bulk.operations.len(), 3);
1022 assert_eq!(bulk.fail_on_errors, Some(2));
1023
1024 let json = serde_json::to_string(&bulk).unwrap();
1026 let parsed: BulkRequest = serde_json::from_str(&json).unwrap();
1027 assert_eq!(parsed.operations.len(), 3);
1028 }
1029
1030 #[test]
1031 fn test_search_request_with_filter() {
1032 let search = SearchRequest::with_filter("userName eq \"jdoe\"");
1033 assert_eq!(search.filter.as_deref(), Some("userName eq \"jdoe\""));
1034 assert_eq!(search.schemas[0], schema::SEARCH_REQUEST);
1035 assert!(search.sort_by.is_none());
1036 assert!(search.count.is_none());
1037 }
1038
1039 #[test]
1040 fn test_scim_error_serialization() {
1041 let error = ScimError {
1042 schemas: vec![schema::ERROR.to_string()],
1043 status: Some("400".into()),
1044 scim_type: Some("invalidFilter".into()),
1045 detail: Some("The filter syntax is invalid".into()),
1046 };
1047
1048 let json = serde_json::to_string(&error).unwrap();
1049 let parsed: ScimError = serde_json::from_str(&json).unwrap();
1050 assert_eq!(parsed.status.as_deref(), Some("400"));
1051 assert_eq!(parsed.scim_type.as_deref(), Some("invalidFilter"));
1052 }
1053
1054 #[test]
1055 fn test_scim_user_active_defaults_to_true() {
1056 let user = ScimUser::new("defaultuser");
1057 assert_eq!(user.active, Some(true));
1058 }
1059
1060 #[test]
1061 fn test_scim_user_extensions_roundtrip() {
1062 let mut user = ScimUser::new("extuser");
1063 user.extensions.insert(
1064 "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User".to_string(),
1065 serde_json::json!({
1066 "employeeNumber": "12345",
1067 "department": "Engineering"
1068 }),
1069 );
1070
1071 let json = serde_json::to_string(&user).unwrap();
1072 let parsed: ScimUser = serde_json::from_str(&json).unwrap();
1073 let ext = &parsed.extensions["urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"];
1074 assert_eq!(ext["employeeNumber"], "12345");
1075 assert_eq!(ext["department"], "Engineering");
1076 }
1077
1078 #[test]
1079 fn test_scim_client_rejects_http_url() {
1080 let config = ScimClientConfig {
1081 base_url: "http://insecure.example.com/scim/v2".to_string(),
1082 bearer_token: "tok".to_string(),
1083 timeout_secs: 10,
1084 };
1085 match ScimClient::new(config) {
1086 Err(e) => {
1087 let msg = format!("{e}");
1088 assert!(msg.contains("HTTPS"), "got: {msg}");
1089 }
1090 Ok(_) => panic!("expected error for HTTP URL"),
1091 }
1092 }
1093
1094 #[test]
1095 fn test_list_response_deserialization() {
1096 let json_str = r#"{
1097 "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
1098 "totalResults": 2,
1099 "startIndex": 1,
1100 "itemsPerPage": 10,
1101 "Resources": [
1102 {
1103 "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
1104 "userName": "alice"
1105 },
1106 {
1107 "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
1108 "userName": "bob"
1109 }
1110 ]
1111 }"#;
1112
1113 let list: ListResponse<ScimUser> = serde_json::from_str(json_str).unwrap();
1114 assert_eq!(list.total_results, 2);
1115 assert_eq!(list.resources.len(), 2);
1116 assert_eq!(list.resources[0].user_name, "alice");
1117 assert_eq!(list.resources[1].user_name, "bob");
1118 }
1119}