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
//! Multi-Tenant Integration Tests
//!
//! This test suite validates the successful integration of multi-tenant functionality
//! into the main SCIM server application. It tests the complete flow from tenant
//! resolution through resource operations to ensure all components work together.

use scim_server::{
    IsolationLevel, RequestContext, ResourceProvider, StaticTenantResolver, TenantContext,
    TenantPermissions, TenantResolver, providers::StandardResourceProvider,
    storage::InMemoryStorage,
};
use serde_json::json;

// MockSingleTenantProvider removed - was unused after transitioning to StandardResourceProvider

/// Test basic multi-tenant context creation and usage
#[tokio::test]
async fn test_enhanced_request_context_creation() {
    let tenant_context = TenantContext::new("test-tenant".to_string(), "test-client".to_string());
    let enhanced_context = RequestContext::with_tenant_generated_id(tenant_context.clone());

    assert_eq!(enhanced_context.tenant_id(), Some("test-tenant"));
    assert_eq!(enhanced_context.client_id(), Some("test-client"));
    assert!(!enhanced_context.request_id.is_empty());

    // Test that this is a multi-tenant context
    assert!(enhanced_context.is_multi_tenant());
    assert_eq!(enhanced_context.tenant_id(), Some("test-tenant"));
}

/// Test tenant resolver functionality
#[tokio::test]
async fn test_tenant_resolver() {
    let resolver = StaticTenantResolver::new();

    let tenant_a = TenantContext::new("tenant-a".to_string(), "client-a".to_string())
        .with_isolation_level(IsolationLevel::Strict);
    let tenant_b = TenantContext::new("tenant-b".to_string(), "client-b".to_string());

    resolver.add_tenant("api-key-a", tenant_a.clone()).await;
    resolver.add_tenant("api-key-b", tenant_b.clone()).await;

    // Test successful resolution
    let resolved_a = resolver.resolve_tenant("api-key-a").await.unwrap();
    assert_eq!(resolved_a.tenant_id, "tenant-a");
    assert_eq!(resolved_a.isolation_level, IsolationLevel::Strict);

    let resolved_b = resolver.resolve_tenant("api-key-b").await.unwrap();
    assert_eq!(resolved_b.tenant_id, "tenant-b");
    assert_eq!(resolved_b.isolation_level, IsolationLevel::Standard);

    // Test invalid credential
    let invalid_result = resolver.resolve_tenant("invalid-key").await;
    assert!(invalid_result.is_err());

    // Test tenant validation
    assert!(resolver.validate_tenant("tenant-a").await.unwrap());
    assert!(!resolver.validate_tenant("nonexistent").await.unwrap());
}

/// Test single-tenant adapter with multi-tenant context
/// Test single-tenant to multi-tenant adapter
/// TODO: Fix adapter test - currently disabled due to compilation issues
/*
#[tokio::test]
async fn test_single_tenant_adapter() {
    let mock_provider = Arc::new(MockSingleTenantProvider::new());
    let adapter = SingleTenantAdapter::new(mock_provider);

    let tenant_context = TenantContext::new("adapter-test".to_string(), "client".to_string());
    let context = RequestContext::with_tenant_generated_id(tenant_context);

    // Test create operation
    let user_data = json!({
        "userName": "adapteruser",
        "displayName": "Adapter User"
    });

    let created_user = adapter
        .create_resource("User", user_data, &context)
        .await
        .unwrap();

    assert_eq!(created_user.get_username(), Some("adapteruser"));
    assert!(created_user.get_id().is_some());

    // Test get operation
    let user_id = created_user.get_id().unwrap();
    let retrieved_user = adapter
        .get_resource("User", user_id, &context)
        .await
        .unwrap();

    assert!(retrieved_user.is_some());
    let retrieved_user = retrieved_user.unwrap();
    assert_eq!(retrieved_user.get_username(), Some("adapteruser"));

    // Test tenant validation - should fail with wrong tenant
    let wrong_tenant_context = TenantContext::new("wrong-tenant".to_string(), "client".to_string());
    let wrong_context = RequestContext::with_tenant_generated_id(wrong_tenant_context);

    let result = adapter.get_resource("User", user_id, &wrong_context).await;
    assert!(result.is_err());
}
*/

/// Test multi-tenant provider functionality
#[tokio::test]
async fn test_multi_tenant_provider_functionality() {
    let storage = InMemoryStorage::new();
    let provider = StandardResourceProvider::new(storage);

    let tenant_context = TenantContext::new("db-test".to_string(), "client".to_string());
    let context = RequestContext::with_tenant_generated_id(tenant_context);

    // Test create user
    let user_data = json!({
        "userName": "dbuser",
        "displayName": "Database User",
        "emails": [{"value": "db@example.com", "primary": true}]
    });

    let created_user = provider
        .create_resource("User", user_data, &context)
        .await
        .unwrap();

    assert_eq!(created_user.resource().get_username(), Some("dbuser"));
    assert!(created_user.resource().get_id().is_some());

    // Test list resources
    let users = provider
        .list_resources("User", None, &context)
        .await
        .unwrap();
    assert_eq!(users.len(), 1);
    assert_eq!(users[0].resource().get_username(), Some("dbuser"));

    // Test update
    let user_id = created_user.resource().get_id().unwrap();
    let updated_data = json!({
        "id": user_id,
        "userName": "dbuser",
        "displayName": "Updated Database User"
    });

    let updated_user = provider
        .update_resource("User", user_id, updated_data, None, &context)
        .await
        .unwrap();
    assert_eq!(
        updated_user.resource().get_attribute("displayName"),
        Some(&json!("Updated Database User"))
    );

    // Test delete
    provider
        .delete_resource("User", user_id, None, &context)
        .await
        .unwrap();

    let deleted_user = provider
        .get_resource("User", user_id, &context)
        .await
        .unwrap();
    assert!(deleted_user.is_none());
}

/// Test multi-tenant isolation between tenants
#[tokio::test]
async fn test_multi_tenant_isolation() {
    let storage = InMemoryStorage::new();
    let provider = StandardResourceProvider::new(storage);

    // Set up two different tenants
    let tenant_a_context = TenantContext::new("tenant-a".to_string(), "client-a".to_string());
    let context_a = RequestContext::with_tenant_generated_id(tenant_a_context);

    let tenant_b_context = TenantContext::new("tenant-b".to_string(), "client-b".to_string());
    let context_b = RequestContext::with_tenant_generated_id(tenant_b_context);

    // Create users in both tenants with same username
    let user_data_a = json!({"id": "user1", "userName": "john", "displayName": "John from A"});
    let user_data_b = json!({"id": "user1", "userName": "john", "displayName": "John from B"});

    provider
        .create_resource("User", user_data_a, &context_a)
        .await
        .unwrap();

    provider
        .create_resource("User", user_data_b, &context_b)
        .await
        .unwrap();

    // Each tenant should only see their own data
    let user_a = provider
        .get_resource("User", "user1", &context_a)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        user_a.resource().get_attribute("displayName"),
        Some(&json!("John from A"))
    );

    let user_b = provider
        .get_resource("User", "user1", &context_b)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        user_b.resource().get_attribute("displayName"),
        Some(&json!("John from B"))
    );

    // Cross-tenant access should return None (isolation via context)
    let _cross_access_result = provider
        .get_resource("User", "user1", &context_a)
        .await
        .unwrap();
    // Should not find tenant-b's resource when using tenant-a's context

    // Resource counts can be checked via list_resources
    let list_a = provider
        .list_resources("User", None, &context_a)
        .await
        .unwrap();
    let list_b = provider
        .list_resources("User", None, &context_b)
        .await
        .unwrap();
    assert_eq!(list_a.len(), 1);
    assert_eq!(list_b.len(), 1);
}

/// Test tenant permissions and limits
#[tokio::test]
async fn test_tenant_permissions_and_limits() {
    let storage = InMemoryStorage::new();
    let provider = StandardResourceProvider::new(storage);

    // Create tenant with restricted permissions
    let mut permissions = TenantPermissions::default();
    permissions.can_delete = false;
    permissions.max_users = Some(1);

    let tenant_context = TenantContext::new("restricted".to_string(), "client".to_string())
        .with_permissions(permissions);
    let context = RequestContext::with_tenant_generated_id(tenant_context);

    // Create first user should succeed
    let user1_data = json!({"id": "user1", "userName": "user1"});
    let result1 = provider.create_resource("User", user1_data, &context).await;
    assert!(result1.is_ok());

    // Create second user - should fail due to max_users limit of 1
    let user2_data = json!({"id": "user2", "userName": "user2"});
    let result2 = provider.create_resource("User", user2_data, &context).await;
    // Should fail because we've reached the user limit
    assert!(result2.is_err());

    // Delete should fail - tenant has can_delete = false
    let delete_result = provider
        .delete_resource("User", "user1", None, &context)
        .await;
    // Should fail because tenant doesn't have delete permission
    assert!(delete_result.is_err());
}

/// Test end-to-end workflow: resolver -> provider -> operations
#[tokio::test]
async fn test_end_to_end_workflow() {
    // Set up tenant resolver
    let resolver = StaticTenantResolver::new();
    let tenant_context = TenantContext::new("e2e-tenant".to_string(), "e2e-client".to_string());
    resolver
        .add_tenant("e2e-api-key", tenant_context.clone())
        .await;

    // Set up multi-tenant provider
    let storage = InMemoryStorage::new();
    let provider = StandardResourceProvider::new(storage);

    // Simulate authentication and tenant resolution
    let resolved_tenant = resolver.resolve_tenant("e2e-api-key").await.unwrap();
    assert_eq!(resolved_tenant.tenant_id, "e2e-tenant");

    // Create enhanced context from resolved tenant
    let context = RequestContext::with_tenant_generated_id(resolved_tenant);

    // Perform CRUD operations
    let user_data = json!({
        "userName": "e2euser",
        "displayName": "End-to-End User",
        "emails": [{"value": "e2e@example.com", "primary": true}]
    });

    // Create
    let created_user = provider
        .create_resource("User", user_data, &context)
        .await
        .unwrap();
    let user_id = created_user.resource().get_id().unwrap();

    // Read
    let retrieved_user = provider
        .get_resource("User", user_id, &context)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(retrieved_user.resource().get_username(), Some("e2euser"));

    // Update
    let updated_data = json!({
        "id": user_id,
        "userName": "e2euser",
        "displayName": "Updated E2E User"
    });
    let updated_user = provider
        .update_resource("User", user_id, updated_data, None, &context)
        .await
        .unwrap();
    assert_eq!(
        updated_user.resource().get_attribute("displayName"),
        Some(&json!("Updated E2E User"))
    );

    // List
    let users = provider
        .list_resources("User", None, &context)
        .await
        .unwrap();
    assert_eq!(users.len(), 1);

    // Search by attribute
    let found_users = provider
        .find_resources_by_attribute("User", "userName", "e2euser", &context)
        .await
        .unwrap();
    assert!(!found_users.is_empty());
    let found_user = &found_users[0];
    assert_eq!(found_user.resource().get_id(), Some(user_id));

    // Delete
    provider
        .delete_resource("User", user_id, None, &context)
        .await
        .unwrap();

    // Verify deletion
    let deleted_user = provider
        .get_resource("User", user_id, &context)
        .await
        .unwrap();
    assert!(deleted_user.is_none());
}

/// Test backward compatibility with existing single-tenant code
#[tokio::test]
async fn test_backward_compatibility() {
    // Test that existing RequestContext still works
    let context = RequestContext::new("test-request".to_string());
    assert_eq!(context.request_id, "test-request");
    assert!(!context.is_multi_tenant());
    assert!(context.tenant_id().is_none());

    // Test that we can add tenant information to existing context
    let tenant_context = TenantContext::new("compat-tenant".to_string(), "client".to_string());
    let enhanced_context = RequestContext::with_tenant("test-request".to_string(), tenant_context);

    assert!(enhanced_context.is_multi_tenant());
    assert_eq!(enhanced_context.tenant_id(), Some("compat-tenant"));

    // Test conversion from enhanced to regular context
    let converted = enhanced_context.clone();
    assert!(converted.is_multi_tenant());
    assert_eq!(converted.tenant_id(), Some("compat-tenant"));
}

/// Test performance with multiple tenants and resources
#[tokio::test]
async fn test_multi_tenant_performance() {
    let storage = InMemoryStorage::new();
    let provider = StandardResourceProvider::new(storage);

    let tenant_count = 5;
    let users_per_tenant = 10;

    // Create multiple tenants and users
    for tenant_idx in 0..tenant_count {
        let tenant_id = format!("perf-tenant-{}", tenant_idx);
        let tenant_context = TenantContext::new(tenant_id.clone(), "client".to_string());
        let context = RequestContext::with_tenant_generated_id(tenant_context);

        for user_idx in 0..users_per_tenant {
            let user_data = json!({
                "id": format!("user-{}", user_idx),
                "userName": format!("user{}_{}", tenant_idx, user_idx),
                "displayName": format!("User {} from Tenant {}", user_idx, tenant_idx)
            });

            provider
                .create_resource("User", user_data, &context)
                .await
                .unwrap();
        }
    }

    // Verify data isolation and correctness
    for tenant_idx in 0..tenant_count {
        let tenant_id = format!("perf-tenant-{}", tenant_idx);
        let tenant_context = TenantContext::new(tenant_id.clone(), "client".to_string());
        let context = RequestContext::with_tenant_generated_id(tenant_context);

        let users = provider
            .list_resources("User", None, &context)
            .await
            .unwrap();
        assert_eq!(users.len(), users_per_tenant);
    }

    // Get overall statistics
    let stats = provider.get_stats().await;
    assert_eq!(stats.tenant_count, tenant_count);
    assert_eq!(stats.total_resources, tenant_count * users_per_tenant);
}