scim-server 0.5.3

A comprehensive SCIM 2.0 server library for Rust with multi-tenant support and type-safe operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! Test infrastructure and test cases for the SCIM server.
//!
//! This module contains all test-related code including the TestProvider
//! implementation and comprehensive test cases for the SCIM server functionality.

#[cfg(test)]
use super::core::ScimServer;
#[cfg(test)]
use crate::providers::ResourceProvider;
use crate::resource::version::RawVersion;
use crate::resource::versioned::VersionedResource;
use crate::resource::{ListQuery, RequestContext, Resource, SchemaResourceBuilder, ScimOperation};
#[cfg(test)]
use crate::schema::{Schema, SchemaRegistry};

#[cfg(test)]
use serde_json::{Value, json};
#[cfg(test)]
use std::collections::HashMap;
#[cfg(test)]
use std::future::Future;
#[cfg(test)]
use std::sync::{Arc, Mutex};

#[cfg(test)]
#[derive(Debug, thiserror::Error)]
pub enum TestError {
    #[error("Test error")]
    Test,
    #[error("Validation error: {0}")]
    ValidationError(String),
}

#[cfg(test)]
#[derive(Debug)]
pub struct TestProvider {
    resources: Arc<Mutex<HashMap<String, Vec<Resource>>>>,
}

#[cfg(test)]
impl TestProvider {
    pub fn new() -> Self {
        Self {
            resources: Arc::new(Mutex::new(HashMap::new())),
        }
    }
}

#[cfg(test)]
impl ResourceProvider for TestProvider {
    type Error = TestError;

    fn create_resource(
        &self,
        resource_type: &str,
        mut data: Value,
        _context: &RequestContext,
    ) -> impl Future<Output = Result<VersionedResource, Self::Error>> + Send {
        let resource_type = resource_type.to_string();
        let resources = Arc::clone(&self.resources);
        async move {
            let id = uuid::Uuid::new_v4().to_string();
            if let Some(obj) = data.as_object_mut() {
                obj.insert("id".to_string(), Value::String(id.clone()));
            }

            let resource = Resource::from_json(resource_type.clone(), data)
                .map_err(|e| TestError::ValidationError(e.to_string()))?;

            let mut resources = resources.lock().unwrap();
            resources
                .entry(resource_type)
                .or_insert_with(Vec::new)
                .push(resource.clone());

            Ok(VersionedResource::new(resource))
        }
    }

    fn get_resource(
        &self,
        resource_type: &str,
        id: &str,
        _context: &RequestContext,
    ) -> impl Future<Output = Result<Option<VersionedResource>, Self::Error>> + Send {
        let resource_type = resource_type.to_string();
        let id = id.to_string();
        let resources = Arc::clone(&self.resources);
        async move {
            let resources = resources.lock().unwrap();
            Ok(resources.get(&resource_type).and_then(|type_resources| {
                type_resources
                    .iter()
                    .find(|resource| resource.get_id() == Some(&id))
                    .map(|resource| VersionedResource::new(resource.clone()))
            }))
        }
    }

    fn update_resource(
        &self,
        resource_type: &str,
        id: &str,
        mut data: Value,
        _expected_version: Option<&RawVersion>,
        _context: &RequestContext,
    ) -> impl Future<Output = Result<VersionedResource, Self::Error>> + Send {
        let resource_type = resource_type.to_string();
        let id = id.to_string();
        let resources = Arc::clone(&self.resources);
        async move {
            if let Some(obj) = data.as_object_mut() {
                obj.insert("id".to_string(), Value::String(id.clone()));
            }

            let resource = Resource::from_json(resource_type.clone(), data)
                .map_err(|e| TestError::ValidationError(e.to_string()))?;

            let mut resources = resources.lock().unwrap();
            let type_resources = resources.entry(resource_type).or_insert_with(Vec::new);

            // Find and update existing resource, or add new one
            if let Some(existing) = type_resources.iter_mut().find(|r| r.get_id() == Some(&id)) {
                *existing = resource.clone();
            } else {
                type_resources.push(resource.clone());
            }

            Ok(VersionedResource::new(resource))
        }
    }

    fn delete_resource(
        &self,
        resource_type: &str,
        id: &str,
        _expected_version: Option<&RawVersion>,
        _context: &RequestContext,
    ) -> impl Future<Output = Result<(), Self::Error>> + Send {
        let resource_type = resource_type.to_string();
        let id = id.to_string();
        let resources = Arc::clone(&self.resources);
        async move {
            let mut resources = resources.lock().unwrap();
            if let Some(type_resources) = resources.get_mut(&resource_type) {
                type_resources.retain(|resource| resource.get_id() != Some(&id));
            }
            Ok(())
        }
    }

    fn list_resources(
        &self,
        resource_type: &str,
        _query: Option<&ListQuery>,
        _context: &RequestContext,
    ) -> impl Future<Output = Result<Vec<VersionedResource>, Self::Error>> + Send {
        let resource_type = resource_type.to_string();
        let resources = Arc::clone(&self.resources);
        async move {
            let resources = resources.lock().unwrap();
            Ok(resources
                .get(&resource_type)
                .map(|type_resources| {
                    type_resources
                        .iter()
                        .map(|resource| VersionedResource::new(resource.clone()))
                        .collect()
                })
                .unwrap_or_default())
        }
    }

    fn find_resources_by_attribute(
        &self,
        resource_type: &str,
        attribute: &str,
        value: &str,
        _context: &RequestContext,
    ) -> impl Future<Output = Result<Vec<VersionedResource>, Self::Error>> + Send {
        let resource_type = resource_type.to_string();
        let attribute = attribute.to_string();
        let value = Value::String(value.to_string());
        let resources = Arc::clone(&self.resources);
        async move {
            let resources = resources.lock().unwrap();
            Ok(resources
                .get(&resource_type)
                .map(|type_resources| {
                    type_resources
                        .iter()
                        .filter(|resource| resource.get_attribute(&attribute) == Some(&value))
                        .map(|resource| VersionedResource::new(resource.clone()))
                        .collect()
                })
                .unwrap_or_default())
        }
    }

    fn patch_resource(
        &self,
        resource_type: &str,
        id: &str,
        _patch_request: &Value,
        _expected_version: Option<&RawVersion>,
        _context: &RequestContext,
    ) -> impl Future<Output = Result<VersionedResource, Self::Error>> + Send {
        let resource_type = resource_type.to_string();
        let id = id.to_string();
        let resources = Arc::clone(&self.resources);
        async move {
            // Simple patch implementation - just return the existing resource
            let resources = resources.lock().unwrap();
            if let Some(type_resources) = resources.get(&resource_type) {
                if let Some(resource) = type_resources.iter().find(|r| r.get_id() == Some(&id)) {
                    return Ok(VersionedResource::new(resource.clone()));
                }
            }
            Err(TestError::ValidationError("Resource not found".to_string()))
        }
    }

    fn resource_exists(
        &self,
        resource_type: &str,
        id: &str,
        _context: &RequestContext,
    ) -> impl Future<Output = Result<bool, Self::Error>> + Send {
        let resource_type = resource_type.to_string();
        let id = id.to_string();
        let resources = Arc::clone(&self.resources);
        async move {
            let resources = resources.lock().unwrap();
            Ok(resources
                .get(&resource_type)
                .map(|type_resources| type_resources.iter().any(|r| r.get_id() == Some(&id)))
                .unwrap_or(false))
        }
    }
}

#[cfg(test)]
pub fn create_test_user_schema() -> Schema {
    let registry = SchemaRegistry::new().expect("Failed to create registry");
    registry.get_user_schema().clone()
}

#[cfg(test)]
pub fn create_user_resource_handler(schema: Schema) -> crate::resource::ResourceHandler {
    SchemaResourceBuilder::new(schema).build()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_dynamic_server_registration() {
        let provider = TestProvider::new();
        let mut server = ScimServer::new(provider).expect("Failed to create server");

        // Create and register a User resource type
        let user_schema = create_test_user_schema();
        let user_handler = create_user_resource_handler(user_schema);

        let result = server.register_resource_type(
            "User",
            user_handler,
            vec![ScimOperation::Create, ScimOperation::Read],
        );

        assert!(result.is_ok(), "Should register User resource type");

        // Verify registration
        let resource_types = server.get_supported_resource_types();
        assert!(
            resource_types.contains(&"User"),
            "User should be in supported resource types"
        );

        let operations = server.get_supported_operations("User");
        assert!(operations.is_some(), "User operations should be defined");
        assert_eq!(operations.unwrap().len(), 2, "Should have 2 operations");
    }

    #[tokio::test]
    async fn test_dynamic_create_and_get() {
        let provider = TestProvider::new();
        let mut server = ScimServer::new(provider).expect("Failed to create server");

        // Register User resource type
        let user_schema = create_test_user_schema();
        let user_handler = create_user_resource_handler(user_schema);

        server
            .register_resource_type(
                "User",
                user_handler,
                vec![ScimOperation::Create, ScimOperation::Read],
            )
            .expect("Failed to register User resource type");

        let context = RequestContext::new("test-request".to_string());

        // Create a user
        let user_data = json!({
            "userName": "testuser"
        });

        let created_user = server
            .create_resource("User", user_data, &context)
            .await
            .expect("Failed to create user");

        assert_eq!(created_user.resource_type, "User");
        assert_eq!(created_user.get_username(), Some("testuser"));

        // Get the user back
        let user_id = created_user.get_id().expect("User should have an ID");
        let retrieved_user = server
            .get_resource("User", user_id, &context)
            .await
            .expect("Failed to get user")
            .expect("User should exist");

        assert_eq!(retrieved_user.get_id(), Some(user_id));
        assert_eq!(retrieved_user.get_username(), Some("testuser"));
    }

    #[tokio::test]
    async fn test_unsupported_operation() {
        let provider = TestProvider::new();
        let mut server = ScimServer::new(provider).expect("Failed to create server");

        // Register User with only Create operation
        let user_schema = create_test_user_schema();
        let user_handler = create_user_resource_handler(user_schema);

        server
            .register_resource_type("User", user_handler, vec![ScimOperation::Create])
            .expect("Failed to register User resource type");

        let context = RequestContext::new("test-request".to_string());

        // Try to read (unsupported operation)
        let result = server.get_resource("User", "123", &context).await;

        assert!(result.is_err(), "Should fail for unsupported operation");
    }

    /// Test full Group resource lifecycle with dynamic server
    #[tokio::test]
    async fn test_group_resource_operations() {
        let provider = TestProvider::new();
        let mut server = ScimServer::new(provider).expect("Failed to create server");

        // Get Group schema and create handler
        let registry = SchemaRegistry::new().expect("Failed to create registry");
        let group_schema = registry.get_group_schema().clone();
        let group_handler = crate::resource_handlers::create_group_resource_handler(group_schema);

        // Register Group resource type with all operations
        server
            .register_resource_type(
                "Group",
                group_handler,
                vec![
                    ScimOperation::Create,
                    ScimOperation::Read,
                    ScimOperation::Update,
                    ScimOperation::Delete,
                    ScimOperation::List,
                ],
            )
            .expect("Failed to register Group resource type");

        let context = RequestContext::new("test-group-ops".to_string());

        // Test Create Group
        let group_data = json!({
            "displayName": "Test Group",
            "members": []
        });

        let created_group = server
            .create_resource("Group", group_data, &context)
            .await
            .expect("Failed to create group");

        assert_eq!(created_group.resource_type, "Group");
        let group_id = created_group
            .get_id()
            .expect("Group should have an ID")
            .to_string();

        // Test Read Group
        let retrieved_group = server
            .get_resource("Group", &group_id, &context)
            .await
            .expect("Failed to get group")
            .expect("Group should exist");

        assert_eq!(retrieved_group.get_id(), Some(group_id.as_str()));

        // Test Update Group
        let updated_data = json!({
            "displayName": "Updated Test Group",
            "members": []
        });

        let updated_group = server
            .update_resource("Group", &group_id, updated_data, &context)
            .await
            .expect("Failed to update group");

        assert_eq!(
            updated_group.get_attribute("displayName"),
            Some(&json!("Updated Test Group"))
        );

        // Test List Groups
        let groups = server
            .list_resources("Group", &context)
            .await
            .expect("Failed to list groups");

        assert!(!groups.is_empty(), "Should have at least one group");
        assert!(
            groups.iter().any(|g| g.get_id() == Some(group_id.as_str())),
            "Should contain our created group"
        );

        // Test Delete Group
        server
            .delete_resource("Group", &group_id, &context)
            .await
            .expect("Failed to delete group");

        // Verify deletion - resource should return None
        let deleted_resource = server
            .get_resource("Group", &group_id, &context)
            .await
            .expect("Get operation should succeed even after deletion");

        assert!(
            deleted_resource.is_none(),
            "Resource should be None after deletion"
        );
    }

    /// Test Group schema validation in server context
    #[tokio::test]
    async fn test_group_validation_in_server() {
        let provider = TestProvider::new();
        let mut server = ScimServer::new(provider).expect("Failed to create server");

        let registry = SchemaRegistry::new().expect("Failed to create registry");
        let group_schema = registry.get_group_schema().clone();
        let group_handler = crate::resource_handlers::create_group_resource_handler(group_schema);

        server
            .register_resource_type("Group", group_handler, vec![ScimOperation::Create])
            .expect("Failed to register Group resource type");

        let context = RequestContext::new("test-req".to_string());

        // Test valid group creation
        let valid_group = json!({
            "displayName": "Valid Group",
            "members": []
        });

        let result = server.create_resource("Group", valid_group, &context).await;
        assert!(result.is_ok(), "Valid group should be created successfully");

        // Test invalid group creation (missing schemas will be added automatically)
        let minimal_group = json!({
            "displayName": "Minimal Group"
        });

        let result = server
            .create_resource("Group", minimal_group, &context)
            .await;
        assert!(
            result.is_ok(),
            "Minimal group should be created successfully"
        );
    }
}