Skip to main content

auth_framework/protocols/
scim.rs

1//! SCIM 2.0 (RFC 7643 / RFC 7644) — System for Cross-domain Identity Management
2//!
3//! Provides types and a client for provisioning and managing user/group
4//! identities across domains using the SCIM 2.0 protocol.
5//!
6//! # Supported Operations
7//!
8//! - **Users**: Create, Read, Replace, Patch, Delete, List (with filtering)
9//! - **Groups**: Create, Read, Replace, Patch, Delete, List
10//! - **Bulk**: Batch operations for efficient provisioning
11//! - **Service Provider Config**: Capability discovery
12//!
13//! # Security
14//!
15//! - All requests use Bearer token authentication
16//! - TLS is required (enforced by the client)
17//! - Attribute filtering prevents over-exposure of PII
18
19use crate::errors::{AuthError, Result};
20use serde::{Deserialize, Serialize};
21use std::collections::HashMap;
22
23// ─── SCIM Core Schema Types (RFC 7643) ───────────────────────────────────────
24
25/// SCIM 2.0 schema URN constants.
26pub 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/// Common SCIM metadata present on every resource.
41#[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/// SCIM multi-valued attribute with canonical type/primary flags.
52#[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/// SCIM Name component (RFC 7643 §4.1.1).
64#[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/// SCIM User resource (RFC 7643 §4.1).
82#[derive(Debug, Clone, Serialize, Deserialize)]
83#[serde(rename_all = "camelCase")]
84pub struct ScimUser {
85    /// Schema URNs.
86    pub schemas: Vec<String>,
87
88    /// Unique server-assigned identifier.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub id: Option<String>,
91
92    /// Unique identifier for the user (typically login name).
93    pub user_name: String,
94
95    /// User's name components.
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub name: Option<Name>,
98
99    /// Display name.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub display_name: Option<String>,
102
103    /// Email addresses.
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub emails: Option<Vec<MultiValuedAttr>>,
106
107    /// Phone numbers.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub phone_numbers: Option<Vec<MultiValuedAttr>>,
110
111    /// Whether the user account is active.
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub active: Option<bool>,
114
115    /// Resource metadata.
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub meta: Option<Meta>,
118
119    /// Groups the user belongs to (read-only).
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub groups: Option<Vec<MultiValuedAttr>>,
122
123    /// Additional extension attributes.
124    #[serde(flatten)]
125    pub extensions: HashMap<String, serde_json::Value>,
126}
127
128impl ScimUser {
129    /// Create a minimal SCIM User with only the required `userName`.
130    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/// SCIM Group resource (RFC 7643 §4.2).
148#[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// ─── SCIM Protocol Messages (RFC 7644) ───────────────────────────────────────
178
179/// SCIM ListResponse (RFC 7644 §3.4.2).
180#[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/// SCIM Patch operation (RFC 7644 §3.5.2).
194#[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/// A single patch operation entry.
202#[derive(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
211impl std::fmt::Debug for PatchOperation {
212    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213        let mut d = f.debug_struct("PatchOperation");
214        d.field("op", &self.op);
215        d.field("path", &self.path);
216        d.field("value", &crate::utils::redact::redacted(&self.value));
217        d.finish()
218    }
219}
220
221/// Patch operation type.
222#[derive(Debug, Clone, Serialize, Deserialize)]
223#[serde(rename_all = "lowercase")]
224pub enum PatchOpType {
225    Add,
226    Remove,
227    Replace,
228}
229
230/// SCIM Bulk request (RFC 7644 §3.7).
231#[derive(Debug, Clone, Serialize, Deserialize)]
232#[serde(rename_all = "camelCase")]
233pub struct BulkRequest {
234    pub schemas: Vec<String>,
235    #[serde(skip_serializing_if = "Option::is_none")]
236    pub fail_on_errors: Option<u32>,
237    #[serde(rename = "Operations")]
238    pub operations: Vec<BulkOperation>,
239}
240
241/// SCIM Bulk response.
242#[derive(Debug, Clone, Serialize, Deserialize)]
243#[serde(rename_all = "camelCase")]
244pub struct BulkResponse {
245    pub schemas: Vec<String>,
246    #[serde(rename = "Operations")]
247    pub operations: Vec<BulkOperationResponse>,
248}
249
250/// A single operation inside a bulk request.
251#[derive(Clone, Serialize, Deserialize)]
252#[serde(rename_all = "camelCase")]
253pub struct BulkOperation {
254    pub method: BulkMethod,
255    #[serde(skip_serializing_if = "Option::is_none")]
256    pub bulk_id: Option<String>,
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub path: Option<String>,
259    #[serde(skip_serializing_if = "Option::is_none")]
260    pub data: Option<serde_json::Value>,
261}
262
263impl std::fmt::Debug for BulkOperation {
264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        let mut d = f.debug_struct("BulkOperation");
266        d.field("method", &self.method);
267        d.field("bulk_id", &self.bulk_id);
268        d.field("path", &self.path);
269        d.field("data", &crate::utils::redact::redacted(&self.data));
270        d.finish()
271    }
272}
273
274/// A single operation response inside a bulk response.
275#[derive(Debug, Clone, Serialize, Deserialize)]
276#[serde(rename_all = "camelCase")]
277pub struct BulkOperationResponse {
278    pub method: BulkMethod,
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub bulk_id: Option<String>,
281    #[serde(skip_serializing_if = "Option::is_none")]
282    pub location: Option<String>,
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub status: Option<String>,
285    #[serde(skip_serializing_if = "Option::is_none")]
286    pub response: Option<serde_json::Value>,
287}
288
289#[derive(Debug, Clone, Serialize, Deserialize)]
290#[serde(rename_all = "UPPERCASE")]
291pub enum BulkMethod {
292    Post,
293    Put,
294    Patch,
295    Delete,
296}
297
298/// SCIM Error response (RFC 7644 §3.12).
299#[derive(Debug, Clone, Serialize, Deserialize)]
300#[serde(rename_all = "camelCase")]
301pub struct ScimError {
302    pub schemas: Vec<String>,
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub status: Option<String>,
305    #[serde(skip_serializing_if = "Option::is_none")]
306    pub scim_type: Option<String>,
307    #[serde(skip_serializing_if = "Option::is_none")]
308    pub detail: Option<String>,
309}
310
311/// SCIM Search request (RFC 7644 §3.4.3).
312#[derive(Debug, Clone, Serialize, Deserialize)]
313#[serde(rename_all = "camelCase")]
314pub struct SearchRequest {
315    pub schemas: Vec<String>,
316    #[serde(skip_serializing_if = "Option::is_none")]
317    pub filter: Option<String>,
318    #[serde(skip_serializing_if = "Option::is_none")]
319    pub sort_by: Option<String>,
320    #[serde(skip_serializing_if = "Option::is_none")]
321    pub sort_order: Option<String>,
322    #[serde(skip_serializing_if = "Option::is_none")]
323    pub start_index: Option<u64>,
324    #[serde(skip_serializing_if = "Option::is_none")]
325    pub count: Option<u64>,
326    #[serde(skip_serializing_if = "Option::is_none")]
327    pub attributes: Option<Vec<String>>,
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub excluded_attributes: Option<Vec<String>>,
330}
331
332/// Service provider configuration (RFC 7643 §5).
333#[derive(Debug, Clone, Serialize, Deserialize)]
334#[serde(rename_all = "camelCase")]
335pub struct ServiceProviderConfig {
336    pub schemas: Vec<String>,
337    pub patch: Supported,
338    pub bulk: BulkSupported,
339    pub filter: FilterSupported,
340    pub change_password: Supported,
341    pub sort: Supported,
342    pub etag: Supported,
343    pub authentication_schemes: Vec<AuthenticationScheme>,
344}
345
346#[derive(Debug, Clone, Serialize, Deserialize)]
347pub struct Supported {
348    pub supported: bool,
349}
350
351#[derive(Debug, Clone, Serialize, Deserialize)]
352#[serde(rename_all = "camelCase")]
353pub struct BulkSupported {
354    pub supported: bool,
355    pub max_operations: u32,
356    pub max_payload_size: u64,
357}
358
359#[derive(Debug, Clone, Serialize, Deserialize)]
360#[serde(rename_all = "camelCase")]
361pub struct FilterSupported {
362    pub supported: bool,
363    pub max_results: u32,
364}
365
366#[derive(Debug, Clone, Serialize, Deserialize)]
367#[serde(rename_all = "camelCase")]
368pub struct AuthenticationScheme {
369    pub name: String,
370    pub description: String,
371    #[serde(rename = "type")]
372    pub scheme_type: String,
373    #[serde(skip_serializing_if = "Option::is_none")]
374    pub spec_uri: Option<String>,
375    #[serde(skip_serializing_if = "Option::is_none")]
376    pub documentation_uri: Option<String>,
377    pub primary: bool,
378}
379
380// ─── SCIM Client ─────────────────────────────────────────────────────────────
381
382/// Configuration for the SCIM 2.0 client.
383#[derive(Clone)]
384pub struct ScimClientConfig {
385    /// Base URL of the SCIM service (e.g. `https://idp.example.com/scim/v2`).
386    pub base_url: String,
387
388    /// Bearer token for authentication.
389    pub bearer_token: String,
390
391    /// Request timeout in seconds.
392    pub timeout_secs: u64,
393}
394
395impl std::fmt::Debug for ScimClientConfig {
396    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
397        let mut d = f.debug_struct("ScimClientConfig");
398        d.field("base_url", &self.base_url);
399        d.field(
400            "bearer_token",
401            &crate::utils::redact::redacted(&self.bearer_token),
402        );
403        d.field("timeout_secs", &self.timeout_secs);
404        d.finish()
405    }
406}
407
408/// SCIM 2.0 client for provisioning users and groups.
409pub struct ScimClient {
410    config: ScimClientConfig,
411    http: reqwest::Client,
412}
413
414impl ScimClient {
415    /// Create a new SCIM client.
416    pub fn new(config: ScimClientConfig) -> Result<Self> {
417        if !config.base_url.starts_with("https://") {
418            return Err(AuthError::config(
419                "SCIM base URL must use HTTPS for security",
420            ));
421        }
422
423        let http = reqwest::Client::builder()
424            .timeout(std::time::Duration::from_secs(config.timeout_secs))
425            .build()
426            .map_err(|e| AuthError::internal(format!("Failed to build HTTP client: {e}")))?;
427
428        Ok(Self { config, http })
429    }
430
431    // ── Users ────────────────────────────────────────────────────────────
432
433    /// Create a user (POST /Users).
434    pub async fn create_user(&self, user: &ScimUser) -> Result<ScimUser> {
435        let url = format!("{}/Users", self.config.base_url);
436        let resp = self
437            .http
438            .post(&url)
439            .bearer_auth(&self.config.bearer_token)
440            .json(user)
441            .send()
442            .await
443            .map_err(|e| AuthError::internal(format!("SCIM create user request failed: {e}")))?;
444
445        if !resp.status().is_success() {
446            let status = resp.status();
447            let body = resp.text().await.unwrap_or_default();
448            return Err(AuthError::internal(format!(
449                "SCIM create user failed (HTTP {status}): {body}"
450            )));
451        }
452
453        resp.json::<ScimUser>()
454            .await
455            .map_err(|e| AuthError::internal(format!("SCIM create user parse error: {e}")))
456    }
457
458    /// Get a user by ID (GET /Users/{id}).
459    pub async fn get_user(&self, id: &str) -> Result<ScimUser> {
460        let url = format!("{}/Users/{}", self.config.base_url, id);
461        let resp = self
462            .http
463            .get(&url)
464            .bearer_auth(&self.config.bearer_token)
465            .send()
466            .await
467            .map_err(|e| AuthError::internal(format!("SCIM get user request failed: {e}")))?;
468
469        if !resp.status().is_success() {
470            let status = resp.status();
471            let body = resp.text().await.unwrap_or_default();
472            return Err(AuthError::internal(format!(
473                "SCIM get user failed (HTTP {status}): {body}"
474            )));
475        }
476
477        resp.json::<ScimUser>()
478            .await
479            .map_err(|e| AuthError::internal(format!("SCIM get user parse error: {e}")))
480    }
481
482    /// Replace a user (PUT /Users/{id}).
483    pub async fn replace_user(&self, id: &str, user: &ScimUser) -> Result<ScimUser> {
484        let url = format!("{}/Users/{}", self.config.base_url, id);
485        let resp = self
486            .http
487            .put(&url)
488            .bearer_auth(&self.config.bearer_token)
489            .json(user)
490            .send()
491            .await
492            .map_err(|e| AuthError::internal(format!("SCIM replace user request failed: {e}")))?;
493
494        if !resp.status().is_success() {
495            let status = resp.status();
496            let body = resp.text().await.unwrap_or_default();
497            return Err(AuthError::internal(format!(
498                "SCIM replace user failed (HTTP {status}): {body}"
499            )));
500        }
501
502        resp.json::<ScimUser>()
503            .await
504            .map_err(|e| AuthError::internal(format!("SCIM replace user parse error: {e}")))
505    }
506
507    /// Patch a user (PATCH /Users/{id}).
508    pub async fn patch_user(&self, id: &str, patch: &PatchOp) -> Result<ScimUser> {
509        let url = format!("{}/Users/{}", self.config.base_url, id);
510        let resp = self
511            .http
512            .patch(&url)
513            .bearer_auth(&self.config.bearer_token)
514            .json(patch)
515            .send()
516            .await
517            .map_err(|e| AuthError::internal(format!("SCIM patch user request failed: {e}")))?;
518
519        if !resp.status().is_success() {
520            let status = resp.status();
521            let body = resp.text().await.unwrap_or_default();
522            return Err(AuthError::internal(format!(
523                "SCIM patch user failed (HTTP {status}): {body}"
524            )));
525        }
526
527        resp.json::<ScimUser>()
528            .await
529            .map_err(|e| AuthError::internal(format!("SCIM patch user parse error: {e}")))
530    }
531
532    /// Delete a user (DELETE /Users/{id}).
533    pub async fn delete_user(&self, id: &str) -> Result<()> {
534        let url = format!("{}/Users/{}", self.config.base_url, id);
535        let resp = self
536            .http
537            .delete(&url)
538            .bearer_auth(&self.config.bearer_token)
539            .send()
540            .await
541            .map_err(|e| AuthError::internal(format!("SCIM delete user request failed: {e}")))?;
542
543        if !resp.status().is_success() {
544            let status = resp.status();
545            let body = resp.text().await.unwrap_or_default();
546            return Err(AuthError::internal(format!(
547                "SCIM delete user failed (HTTP {status}): {body}"
548            )));
549        }
550
551        Ok(())
552    }
553
554    /// List users with optional filter (GET /Users?filter=...).
555    pub async fn list_users(
556        &self,
557        filter: Option<&str>,
558        start_index: Option<u64>,
559        count: Option<u64>,
560    ) -> Result<ListResponse<ScimUser>> {
561        let mut url = format!("{}/Users", self.config.base_url);
562        let mut params = Vec::new();
563        if let Some(f) = filter {
564            params.push(format!("filter={}", urlencoding::encode(f)));
565        }
566        if let Some(si) = start_index {
567            params.push(format!("startIndex={si}"));
568        }
569        if let Some(c) = count {
570            params.push(format!("count={c}"));
571        }
572        if !params.is_empty() {
573            url = format!("{}?{}", url, params.join("&"));
574        }
575
576        let resp = self
577            .http
578            .get(&url)
579            .bearer_auth(&self.config.bearer_token)
580            .send()
581            .await
582            .map_err(|e| AuthError::internal(format!("SCIM list users request failed: {e}")))?;
583
584        if !resp.status().is_success() {
585            let status = resp.status();
586            let body = resp.text().await.unwrap_or_default();
587            return Err(AuthError::internal(format!(
588                "SCIM list users failed (HTTP {status}): {body}"
589            )));
590        }
591
592        resp.json::<ListResponse<ScimUser>>()
593            .await
594            .map_err(|e| AuthError::internal(format!("SCIM list users parse error: {e}")))
595    }
596
597    // ── Groups ───────────────────────────────────────────────────────────
598
599    /// Create a group (POST /Groups).
600    pub async fn create_group(&self, group: &ScimGroup) -> Result<ScimGroup> {
601        let url = format!("{}/Groups", self.config.base_url);
602        let resp = self
603            .http
604            .post(&url)
605            .bearer_auth(&self.config.bearer_token)
606            .json(group)
607            .send()
608            .await
609            .map_err(|e| AuthError::internal(format!("SCIM create group request failed: {e}")))?;
610
611        if !resp.status().is_success() {
612            let status = resp.status();
613            let body = resp.text().await.unwrap_or_default();
614            return Err(AuthError::internal(format!(
615                "SCIM create group failed (HTTP {status}): {body}"
616            )));
617        }
618
619        resp.json::<ScimGroup>()
620            .await
621            .map_err(|e| AuthError::internal(format!("SCIM create group parse error: {e}")))
622    }
623
624    /// Get a group by ID (GET /Groups/{id}).
625    pub async fn get_group(&self, id: &str) -> Result<ScimGroup> {
626        let url = format!("{}/Groups/{}", self.config.base_url, id);
627        let resp = self
628            .http
629            .get(&url)
630            .bearer_auth(&self.config.bearer_token)
631            .send()
632            .await
633            .map_err(|e| AuthError::internal(format!("SCIM get group request failed: {e}")))?;
634
635        if !resp.status().is_success() {
636            let status = resp.status();
637            let body = resp.text().await.unwrap_or_default();
638            return Err(AuthError::internal(format!(
639                "SCIM get group failed (HTTP {status}): {body}"
640            )));
641        }
642
643        resp.json::<ScimGroup>()
644            .await
645            .map_err(|e| AuthError::internal(format!("SCIM get group parse error: {e}")))
646    }
647
648    /// Delete a group (DELETE /Groups/{id}).
649    pub async fn delete_group(&self, id: &str) -> Result<()> {
650        let url = format!("{}/Groups/{}", self.config.base_url, id);
651        let resp = self
652            .http
653            .delete(&url)
654            .bearer_auth(&self.config.bearer_token)
655            .send()
656            .await
657            .map_err(|e| AuthError::internal(format!("SCIM delete group request failed: {e}")))?;
658
659        if !resp.status().is_success() {
660            let status = resp.status();
661            let body = resp.text().await.unwrap_or_default();
662            return Err(AuthError::internal(format!(
663                "SCIM delete group failed (HTTP {status}): {body}"
664            )));
665        }
666
667        Ok(())
668    }
669
670    /// List groups with optional filter (GET /Groups?filter=...).
671    pub async fn list_groups(
672        &self,
673        filter: Option<&str>,
674        start_index: Option<u64>,
675        count: Option<u64>,
676    ) -> Result<ListResponse<ScimGroup>> {
677        let mut url = format!("{}/Groups", self.config.base_url);
678        let mut params = Vec::new();
679        if let Some(f) = filter {
680            params.push(format!("filter={}", urlencoding::encode(f)));
681        }
682        if let Some(si) = start_index {
683            params.push(format!("startIndex={si}"));
684        }
685        if let Some(c) = count {
686            params.push(format!("count={c}"));
687        }
688        if !params.is_empty() {
689            url = format!("{}?{}", url, params.join("&"));
690        }
691
692        let resp = self
693            .http
694            .get(&url)
695            .bearer_auth(&self.config.bearer_token)
696            .send()
697            .await
698            .map_err(|e| AuthError::internal(format!("SCIM list groups request failed: {e}")))?;
699
700        if !resp.status().is_success() {
701            let status = resp.status();
702            let body = resp.text().await.unwrap_or_default();
703            return Err(AuthError::internal(format!(
704                "SCIM list groups failed (HTTP {status}): {body}"
705            )));
706        }
707
708        resp.json::<ListResponse<ScimGroup>>()
709            .await
710            .map_err(|e| AuthError::internal(format!("SCIM list groups parse error: {e}")))
711    }
712
713    // ── Bulk ─────────────────────────────────────────────────────────────
714
715    /// Execute a bulk request (POST /Bulk).
716    pub async fn bulk(&self, request: &BulkRequest) -> Result<BulkResponse> {
717        let url = format!("{}/Bulk", self.config.base_url);
718        let resp = self
719            .http
720            .post(&url)
721            .bearer_auth(&self.config.bearer_token)
722            .json(request)
723            .send()
724            .await
725            .map_err(|e| AuthError::internal(format!("SCIM bulk request failed: {e}")))?;
726
727        if !resp.status().is_success() {
728            let status = resp.status();
729            let body = resp.text().await.unwrap_or_default();
730            return Err(AuthError::internal(format!(
731                "SCIM bulk request failed (HTTP {status}): {body}"
732            )));
733        }
734
735        resp.json::<BulkResponse>()
736            .await
737            .map_err(|e| AuthError::internal(format!("SCIM bulk response parse error: {e}")))
738    }
739
740    // ── Service Provider Config ──────────────────────────────────────────
741
742    /// Retrieve the service provider configuration.
743    pub async fn get_service_provider_config(&self) -> Result<ServiceProviderConfig> {
744        let url = format!("{}/ServiceProviderConfig", self.config.base_url);
745        let resp = self
746            .http
747            .get(&url)
748            .bearer_auth(&self.config.bearer_token)
749            .send()
750            .await
751            .map_err(|e| {
752                AuthError::internal(format!("SCIM service provider config request failed: {e}"))
753            })?;
754
755        if !resp.status().is_success() {
756            let status = resp.status();
757            let body = resp.text().await.unwrap_or_default();
758            return Err(AuthError::internal(format!(
759                "SCIM service provider config failed (HTTP {status}): {body}"
760            )));
761        }
762
763        resp.json::<ServiceProviderConfig>().await.map_err(|e| {
764            AuthError::internal(format!("SCIM service provider config parse error: {e}"))
765        })
766    }
767}
768
769// ─── Helper constructors ─────────────────────────────────────────────────────
770
771impl PatchOp {
772    /// Create a new PatchOp with a list of operations.
773    pub fn new(operations: Vec<PatchOperation>) -> Self {
774        Self {
775            schemas: vec![schema::PATCH_OP.to_string()],
776            operations,
777        }
778    }
779}
780
781impl SearchRequest {
782    /// Create a search request with a filter.
783    pub fn with_filter(filter: impl Into<String>) -> Self {
784        Self {
785            schemas: vec![schema::SEARCH_REQUEST.to_string()],
786            filter: Some(filter.into()),
787            sort_by: None,
788            sort_order: None,
789            start_index: None,
790            count: None,
791            attributes: None,
792            excluded_attributes: None,
793        }
794    }
795}
796
797impl BulkRequest {
798    /// Create a new bulk request.
799    pub fn new(operations: Vec<BulkOperation>, fail_on_errors: Option<u32>) -> Self {
800        Self {
801            schemas: vec![schema::BULK_REQUEST.to_string()],
802            fail_on_errors,
803            operations,
804        }
805    }
806}
807
808#[cfg(test)]
809mod tests {
810    use super::*;
811
812    #[test]
813    fn test_scim_user_serialization() {
814        let mut user = ScimUser::new("jdoe");
815        user.name = Some(Name {
816            given_name: Some("John".into()),
817            family_name: Some("Doe".into()),
818            ..Default::default()
819        });
820        user.emails = Some(vec![MultiValuedAttr {
821            value: "jdoe@example.com".into(),
822            attr_type: Some("work".into()),
823            primary: Some(true),
824            display: None,
825        }]);
826
827        let json = serde_json::to_string(&user).expect("serialize");
828        assert!(json.contains("\"userName\":\"jdoe\""));
829        assert!(json.contains(schema::USER));
830    }
831
832    #[test]
833    fn test_scim_group_serialization() {
834        let group = ScimGroup::new("Engineering");
835        let json = serde_json::to_string(&group).expect("serialize");
836        assert!(json.contains("\"displayName\":\"Engineering\""));
837        assert!(json.contains(schema::GROUP));
838    }
839
840    #[test]
841    fn test_patch_op_construction() {
842        let patch = PatchOp::new(vec![PatchOperation {
843            op: PatchOpType::Replace,
844            path: Some("active".into()),
845            value: Some(serde_json::Value::Bool(false)),
846        }]);
847        assert_eq!(patch.schemas[0], schema::PATCH_OP);
848        assert_eq!(patch.operations.len(), 1);
849    }
850
851    #[test]
852    fn test_scim_user_roundtrip() {
853        let user = ScimUser::new("alice");
854        let json = serde_json::to_value(&user).expect("to value");
855        let parsed: ScimUser = serde_json::from_value(json).expect("from value");
856        assert_eq!(parsed.user_name, "alice");
857        assert_eq!(parsed.active, Some(true));
858    }
859
860    #[test]
861    fn test_bulk_request_construction() {
862        let bulk = BulkRequest::new(
863            vec![BulkOperation {
864                method: BulkMethod::Post,
865                bulk_id: Some("op1".into()),
866                path: Some("/Users".into()),
867                data: Some(serde_json::to_value(ScimUser::new("bulk_user")).expect("val")),
868            }],
869            Some(1),
870        );
871        assert_eq!(bulk.schemas[0], schema::BULK_REQUEST);
872        assert_eq!(bulk.fail_on_errors, Some(1));
873    }
874
875    #[test]
876    fn test_scim_user_empty_username() {
877        let user = ScimUser::new("");
878        assert_eq!(user.user_name, "");
879        // Roundtrip should preserve the empty string
880        let json = serde_json::to_value(&user).unwrap();
881        let parsed: ScimUser = serde_json::from_value(json).unwrap();
882        assert_eq!(parsed.user_name, "");
883    }
884
885    #[test]
886    fn test_scim_user_all_optional_fields() {
887        let mut user = ScimUser::new("fulluser");
888        user.id = Some("u-123".into());
889        user.display_name = Some("Full User".into());
890        user.name = Some(Name {
891            formatted: Some("Dr. Full A. User Jr.".into()),
892            family_name: Some("User".into()),
893            given_name: Some("Full".into()),
894            middle_name: Some("A".into()),
895            honorific_prefix: Some("Dr.".into()),
896            honorific_suffix: Some("Jr.".into()),
897        });
898        user.emails = Some(vec![
899            MultiValuedAttr {
900                value: "work@example.com".into(),
901                attr_type: Some("work".into()),
902                primary: Some(true),
903                display: Some("Work Email".into()),
904            },
905            MultiValuedAttr {
906                value: "home@example.com".into(),
907                attr_type: Some("home".into()),
908                primary: Some(false),
909                display: None,
910            },
911        ]);
912        user.phone_numbers = Some(vec![MultiValuedAttr {
913            value: "+1-555-0100".into(),
914            attr_type: Some("mobile".into()),
915            primary: Some(true),
916            display: None,
917        }]);
918        user.active = Some(false);
919        user.groups = Some(vec![MultiValuedAttr {
920            value: "g-eng".into(),
921            attr_type: None,
922            primary: None,
923            display: Some("Engineering".into()),
924        }]);
925
926        let json = serde_json::to_string(&user).unwrap();
927        let parsed: ScimUser =
928            serde_json::from_value(serde_json::from_str(&json).unwrap()).unwrap();
929        assert_eq!(parsed.id.as_deref(), Some("u-123"));
930        assert_eq!(parsed.display_name.as_deref(), Some("Full User"));
931        assert_eq!(parsed.active, Some(false));
932        assert_eq!(parsed.emails.as_ref().unwrap().len(), 2);
933        assert_eq!(parsed.phone_numbers.as_ref().unwrap().len(), 1);
934        assert_eq!(parsed.groups.as_ref().unwrap().len(), 1);
935        let name = parsed.name.as_ref().unwrap();
936        assert_eq!(name.honorific_prefix.as_deref(), Some("Dr."));
937        assert_eq!(name.honorific_suffix.as_deref(), Some("Jr."));
938    }
939
940    #[test]
941    fn test_scim_user_deserialization_from_json() {
942        let json_str = r#"{
943            "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
944            "id": "server-1",
945            "userName": "jdoe",
946            "displayName": "Jane Doe",
947            "active": true,
948            "meta": {
949                "resourceType": "User",
950                "created": "2024-01-01T00:00:00Z",
951                "lastModified": "2024-06-01T00:00:00Z",
952                "location": "https://scim.example.com/Users/server-1",
953                "version": "W/\"1\""
954            }
955        }"#;
956
957        let user: ScimUser = serde_json::from_str(json_str).unwrap();
958        assert_eq!(user.user_name, "jdoe");
959        assert_eq!(user.id.as_deref(), Some("server-1"));
960        assert_eq!(user.display_name.as_deref(), Some("Jane Doe"));
961        let meta = user.meta.as_ref().unwrap();
962        assert_eq!(meta.resource_type, "User");
963        assert_eq!(meta.version.as_deref(), Some("W/\"1\""));
964    }
965
966    #[test]
967    fn test_scim_group_with_members() {
968        let mut group = ScimGroup::new("DevOps");
969        group.members = Some(vec![
970            MultiValuedAttr {
971                value: "u-1".into(),
972                attr_type: Some("User".into()),
973                primary: None,
974                display: Some("Alice".into()),
975            },
976            MultiValuedAttr {
977                value: "u-2".into(),
978                attr_type: Some("User".into()),
979                primary: None,
980                display: Some("Bob".into()),
981            },
982        ]);
983
984        let json = serde_json::to_string(&group).unwrap();
985        let parsed: ScimGroup = serde_json::from_str(&json).unwrap();
986        assert_eq!(parsed.display_name, "DevOps");
987        let members = parsed.members.unwrap();
988        assert_eq!(members.len(), 2);
989        assert_eq!(members[0].display.as_deref(), Some("Alice"));
990    }
991
992    #[test]
993    fn test_patch_op_add_and_remove() {
994        let patch = PatchOp::new(vec![
995            PatchOperation {
996                op: PatchOpType::Add,
997                path: Some("emails".into()),
998                value: Some(serde_json::json!([{"value": "new@example.com", "type": "work"}])),
999            },
1000            PatchOperation {
1001                op: PatchOpType::Remove,
1002                path: Some("phoneNumbers".into()),
1003                value: None,
1004            },
1005        ]);
1006
1007        assert_eq!(patch.operations.len(), 2);
1008
1009        // Verify JSON serialization of patch ops
1010        let json = serde_json::to_string(&patch).unwrap();
1011        assert!(json.contains("\"add\""));
1012        assert!(json.contains("\"remove\""));
1013        assert!(json.contains("new@example.com"));
1014    }
1015
1016    #[test]
1017    fn test_bulk_request_multiple_operations() {
1018        let bulk = BulkRequest::new(
1019            vec![
1020                BulkOperation {
1021                    method: BulkMethod::Post,
1022                    bulk_id: Some("create-1".into()),
1023                    path: Some("/Users".into()),
1024                    data: Some(serde_json::to_value(ScimUser::new("user1")).unwrap()),
1025                },
1026                BulkOperation {
1027                    method: BulkMethod::Put,
1028                    bulk_id: Some("update-1".into()),
1029                    path: Some("/Users/existing-id".into()),
1030                    data: Some(serde_json::to_value(ScimUser::new("user1_updated")).unwrap()),
1031                },
1032                BulkOperation {
1033                    method: BulkMethod::Delete,
1034                    bulk_id: Some("delete-1".into()),
1035                    path: Some("/Users/old-id".into()),
1036                    data: None,
1037                },
1038            ],
1039            Some(2),
1040        );
1041
1042        assert_eq!(bulk.operations.len(), 3);
1043        assert_eq!(bulk.fail_on_errors, Some(2));
1044
1045        // Roundtrip
1046        let json = serde_json::to_string(&bulk).unwrap();
1047        let parsed: BulkRequest = serde_json::from_str(&json).unwrap();
1048        assert_eq!(parsed.operations.len(), 3);
1049    }
1050
1051    #[test]
1052    fn test_search_request_with_filter() {
1053        let search = SearchRequest::with_filter("userName eq \"jdoe\"");
1054        assert_eq!(search.filter.as_deref(), Some("userName eq \"jdoe\""));
1055        assert_eq!(search.schemas[0], schema::SEARCH_REQUEST);
1056        assert!(search.sort_by.is_none());
1057        assert!(search.count.is_none());
1058    }
1059
1060    #[test]
1061    fn test_scim_error_serialization() {
1062        let error = ScimError {
1063            schemas: vec![schema::ERROR.to_string()],
1064            status: Some("400".into()),
1065            scim_type: Some("invalidFilter".into()),
1066            detail: Some("The filter syntax is invalid".into()),
1067        };
1068
1069        let json = serde_json::to_string(&error).unwrap();
1070        let parsed: ScimError = serde_json::from_str(&json).unwrap();
1071        assert_eq!(parsed.status.as_deref(), Some("400"));
1072        assert_eq!(parsed.scim_type.as_deref(), Some("invalidFilter"));
1073    }
1074
1075    #[test]
1076    fn test_scim_user_active_defaults_to_true() {
1077        let user = ScimUser::new("defaultuser");
1078        assert_eq!(user.active, Some(true));
1079    }
1080
1081    #[test]
1082    fn test_scim_user_extensions_roundtrip() {
1083        let mut user = ScimUser::new("extuser");
1084        user.extensions.insert(
1085            "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User".to_string(),
1086            serde_json::json!({
1087                "employeeNumber": "12345",
1088                "department": "Engineering"
1089            }),
1090        );
1091
1092        let json = serde_json::to_string(&user).unwrap();
1093        let parsed: ScimUser = serde_json::from_str(&json).unwrap();
1094        let ext = &parsed.extensions["urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"];
1095        assert_eq!(ext["employeeNumber"], "12345");
1096        assert_eq!(ext["department"], "Engineering");
1097    }
1098
1099    #[test]
1100    fn test_scim_client_rejects_http_url() {
1101        let config = ScimClientConfig {
1102            base_url: "http://insecure.example.com/scim/v2".to_string(),
1103            bearer_token: "tok".to_string(),
1104            timeout_secs: 10,
1105        };
1106        match ScimClient::new(config) {
1107            Err(e) => {
1108                let msg = format!("{e}");
1109                assert!(msg.contains("HTTPS"), "got: {msg}");
1110            }
1111            Ok(_) => panic!("expected error for HTTP URL"),
1112        }
1113    }
1114
1115    #[test]
1116    fn test_list_response_deserialization() {
1117        let json_str = r#"{
1118            "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
1119            "totalResults": 2,
1120            "startIndex": 1,
1121            "itemsPerPage": 10,
1122            "Resources": [
1123                {
1124                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
1125                    "userName": "alice"
1126                },
1127                {
1128                    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
1129                    "userName": "bob"
1130                }
1131            ]
1132        }"#;
1133
1134        let list: ListResponse<ScimUser> = serde_json::from_str(json_str).unwrap();
1135        assert_eq!(list.total_results, 2);
1136        assert_eq!(list.resources.len(), 2);
1137        assert_eq!(list.resources[0].user_name, "alice");
1138        assert_eq!(list.resources[1].user_name, "bob");
1139    }
1140}