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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
//! ETag Concurrency Control Example
//!
//! This example demonstrates the built-in ETag concurrency control features
//! of the SCIM server library. It shows how to use conditional operations
//! to prevent lost updates and handle version conflicts.

use scim_server::{
    ResourceProvider, ScimServer,
    multi_tenant::ScimOperation,
    operation_handler::{ScimOperationHandler, ScimOperationRequest},
    providers::{StandardResourceProvider, helpers::conditional::ConditionalOperations},
    resource::{
        RequestContext,
        version::{ConditionalResult, HttpVersion, RawVersion},
    },
    resource_handlers::create_user_resource_handler,
    storage::InMemoryStorage,
};
use serde_json::json;

use tokio::time::{Duration, sleep};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    env_logger::init();

    println!("🏷️  SCIM ETag Concurrency Control Example");
    println!("=========================================\n");

    // 1. Setup server with StandardResourceProvider
    let storage = InMemoryStorage::new();
    let provider = StandardResourceProvider::new(storage);
    let mut server = ScimServer::new(provider)?;

    // Register User resource type
    let user_schema = server
        .get_schema_by_id("urn:ietf:params:scim:schemas:core:2.0:User")
        .expect("User schema should be available")
        .clone();

    let user_handler = create_user_resource_handler(user_schema);
    server.register_resource_type(
        "User",
        user_handler,
        vec![
            ScimOperation::Create,
            ScimOperation::Read,
            ScimOperation::Update,
            ScimOperation::Delete,
        ],
    )?;

    let handler = ScimOperationHandler::new(server);
    let _context = RequestContext::with_generated_id();

    println!("✅ Server initialized with ETag support\n");

    // === BASIC VERSION MANAGEMENT ===
    println!("📋 BASIC VERSION MANAGEMENT");
    println!("===========================");

    // Create a user
    let create_request = ScimOperationRequest::create(
        "User",
        json!({
            "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
            "userName": "alice.smith",
            "name": {
                "familyName": "Smith",
                "givenName": "Alice",
                "formatted": "Alice Smith"
            },
            "emails": [
                {
                    "value": "alice.smith@example.com",
                    "type": "work",
                    "primary": true
                }
            ],
            "active": true
        }),
    );

    let create_response = handler.handle_operation(create_request).await;
    let user_id = if create_response.success {
        let user_id = create_response.metadata.resource_id.clone().unwrap();
        let etag = create_response.metadata.additional.get("etag").unwrap();

        println!("✅ Created user with ID: {}", user_id);
        println!("   ETag (weak): {}", etag.as_str().unwrap());
        user_id
    } else {
        panic!("Failed to create user: {:?}", create_response.error);
    };

    // Get user to see version information
    let get_request = ScimOperationRequest::get("User", &user_id);
    let get_response = handler.handle_operation(get_request).await;

    let current_version = if get_response.success {
        let etag = get_response.metadata.additional.get("etag").unwrap();

        println!("✅ Retrieved user successfully");
        println!("   Current ETag (weak): {}", etag.as_str().unwrap());

        etag.as_str().unwrap().parse::<HttpVersion>()?
    } else {
        panic!("Failed to retrieve user: {:?}", get_response.error);
    };

    println!();

    // === CONDITIONAL UPDATE SUCCESS ===
    println!("✅ CONDITIONAL UPDATE SUCCESS");
    println!("=============================");

    // Update with correct version (should succeed)
    let conditional_update_request = ScimOperationRequest::update(
        "User",
        &user_id,
        json!({
            "id": user_id,
            "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
            "userName": "alice.smith",
            "name": {
                "familyName": "Smith",
                "givenName": "Alice",
                "formatted": "Alice M. Smith" // Changed middle initial
            },
            "emails": [
                {
                    "value": "alice.smith@newcompany.com", // Changed email
                    "type": "work",
                    "primary": true
                }
            ],
            "active": true
        }),
    )
    .with_expected_version(current_version.clone());

    let conditional_update_response = handler.handle_operation(conditional_update_request).await;

    let _new_version = if conditional_update_response.success {
        let old_etag = current_version.to_string();
        let new_etag = conditional_update_response
            .metadata
            .additional
            .get("etag")
            .unwrap();

        println!("✅ Conditional update succeeded!");
        println!("   Old ETag (weak): {}", old_etag);
        println!("   New ETag (weak): {}", new_etag.as_str().unwrap());

        new_etag.as_str().unwrap().parse::<HttpVersion>()?
    } else {
        panic!(
            "Conditional update should have succeeded: {:?}",
            conditional_update_response.error
        );
    };

    println!();

    // === CONDITIONAL UPDATE CONFLICT ===
    println!("⚠️  CONDITIONAL UPDATE CONFLICT");
    println!("==============================");

    // Try to update with old version (should fail)
    let conflicting_update_request = ScimOperationRequest::update(
        "User",
        &user_id,
        json!({
            "id": user_id,
            "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
            "userName": "alice.smith",
            "name": {
                "familyName": "Smith-Jones", // Different change
                "givenName": "Alice",
                "formatted": "Alice Smith-Jones"
            },
            "active": false // Different change
        }),
    )
    .with_expected_version(current_version); // Using old version

    let conflicting_response = handler.handle_operation(conflicting_update_request).await;

    if !conflicting_response.success {
        println!("✅ Version conflict detected correctly!");
        println!("   Error: {}", conflicting_response.error.unwrap());
        println!(
            "   Error Code: {}",
            conflicting_response.error_code.unwrap()
        );
    } else {
        panic!("Conditional update should have failed due to version mismatch");
    }

    println!();

    // === PROVIDER-LEVEL CONDITIONAL OPERATIONS ===
    println!("🔧 PROVIDER-LEVEL CONDITIONAL OPERATIONS");
    println!("=========================================");

    // Create a new provider instance to demonstrate provider-level operations
    let storage = InMemoryStorage::new();
    let provider = StandardResourceProvider::new(storage);
    let mut provider_server = ScimServer::new(provider.clone())?;

    // Register User resource type for the provider demo
    let user_schema = provider_server
        .get_schema_by_id("urn:ietf:params:scim:schemas:core:2.0:User")
        .expect("User schema should be available")
        .clone();
    let user_handler = create_user_resource_handler(user_schema);
    provider_server.register_resource_type(
        "User",
        user_handler,
        vec![
            ScimOperation::Create,
            ScimOperation::Read,
            ScimOperation::Update,
            ScimOperation::Delete,
        ],
    )?;

    // Create a user for provider-level testing
    let provider_user_data = json!({
        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
        "userName": "provider.test",
        "active": true
    });

    let provider_context = RequestContext::with_generated_id();
    let created_resource = provider
        .create_resource("User", provider_user_data, &provider_context)
        .await?;
    let provider_user_id = created_resource.get_id().unwrap();

    // Get current resource
    let versioned_current = provider
        .get_resource("User", &provider_user_id, &provider_context)
        .await?
        .expect("User should exist");
    println!(
        "✅ Current resource ETag (weak): {}",
        HttpVersion::from(versioned_current.version().clone()).to_string()
    );

    // Successful conditional update
    let update_data = json!({
        "id": provider_user_id,
        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
        "userName": "provider.test",
        "name": {
            "familyName": "Test",
            "givenName": "Provider",
            "formatted": "Dr. Provider Test" // Added title
        },
        "active": true
    });

    match provider
        .conditional_update_resource(
            "User",
            &provider_user_id,
            update_data,
            versioned_current.version(),
            &provider_context,
        )
        .await?
    {
        ConditionalResult::Success(updated_versioned) => {
            println!("✅ Provider conditional update succeeded!");
            println!(
                "   New ETag (weak): {}",
                HttpVersion::from(updated_versioned.version().clone()).to_string()
            );
        }
        ConditionalResult::VersionMismatch(conflict) => {
            println!("❌ Unexpected version conflict: {}", conflict.message);
        }
        ConditionalResult::NotFound => {
            println!("❌ Resource not found");
        }
    }

    // Try update with wrong version
    let wrong_version = RawVersion::from_hash("wrong-version");
    let failing_update_data = json!({
        "id": provider_user_id,
        "userName": "should.fail",
        "active": false
    });

    match provider
        .conditional_update_resource(
            "User",
            &provider_user_id,
            failing_update_data,
            &wrong_version,
            &provider_context,
        )
        .await?
    {
        ConditionalResult::Success(_) => {
            println!("❌ Update should have failed!");
        }
        ConditionalResult::VersionMismatch(conflict) => {
            println!("✅ Provider correctly detected version mismatch!");
            println!("   Expected: {}", conflict.expected);
            println!("   Current: {}", conflict.current);
            println!("   Message: {}", conflict.message);
        }
        ConditionalResult::NotFound => {
            println!("❌ Resource not found");
        }
    }

    println!();

    // === CONDITIONAL DELETE ===
    println!("🗑️  CONDITIONAL DELETE");
    println!("======================");

    // Get current version for delete
    let current_resource = provider
        .get_resource("User", &provider_user_id, &provider_context)
        .await?
        .expect("User should exist");

    let versioned_for_delete = current_resource;
    println!(
        "✅ Resource ETag for delete (weak): {}",
        HttpVersion::from(versioned_for_delete.version().clone()).to_string()
    );

    // Try delete with wrong version first
    let wrong_delete_version = RawVersion::from_hash("wrong-delete-version");

    match provider
        .conditional_delete_resource(
            "User",
            &provider_user_id,
            &wrong_delete_version,
            &provider_context,
        )
        .await?
    {
        ConditionalResult::Success(()) => {
            println!("❌ Delete should have failed!");
        }
        ConditionalResult::VersionMismatch(conflict) => {
            println!("✅ Delete correctly rejected due to version mismatch!");
            println!("   Conflict: {}", conflict.message);
        }
        ConditionalResult::NotFound => {
            println!("❌ Resource not found");
        }
    }

    // Now delete with correct version
    match provider
        .conditional_delete_resource(
            "User",
            &provider_user_id,
            versioned_for_delete.version(),
            &provider_context,
        )
        .await?
    {
        ConditionalResult::Success(()) => {
            println!("✅ Conditional delete succeeded!");
        }
        ConditionalResult::VersionMismatch(conflict) => {
            println!("❌ Unexpected version conflict: {}", conflict.message);
        }
        ConditionalResult::NotFound => {
            println!("❌ Resource not found");
        }
    }

    // Verify deletion
    let verify_resource = provider
        .get_resource("User", &provider_user_id, &provider_context)
        .await?;
    if verify_resource.is_none() {
        println!("✅ Resource successfully deleted");
    } else {
        println!("❌ Resource still exists after delete");
    }

    println!();

    // === VERSION COMPUTATION EXAMPLES ===
    println!("🔢 VERSION COMPUTATION EXAMPLES");
    println!("===============================");

    // Show how versions are computed from content
    let test_resource1 = json!({
        "id": "test-123",
        "userName": "test.user",
        "active": true
    });

    let test_resource2 = json!({
        "id": "test-123",
        "userName": "test.user",
        "active": false  // Only this field changed
    });

    let version1 = RawVersion::from_content(test_resource1.to_string().as_bytes());
    let version2 = RawVersion::from_content(test_resource2.to_string().as_bytes());

    println!("✅ Content-based version computation:");
    println!(
        "   Resource 1 ETag (weak): {}",
        HttpVersion::from(version1.clone()).to_string()
    );
    println!(
        "   Resource 2 ETag (weak): {}",
        HttpVersion::from(version2.clone()).to_string()
    );
    println!("   Versions match: {}", version1 == version2);

    // Show identical content produces identical versions
    let test_resource1_copy = json!({
        "id": "test-123",
        "userName": "test.user",
        "active": true
    });

    let version1_copy = RawVersion::from_content(test_resource1_copy.to_string().as_bytes());
    println!(
        "   Identical content versions match: {}",
        version1 == version1_copy
    );

    println!();

    // === CONCURRENT MODIFICATION SIMULATION ===
    println!("🏃 CONCURRENT MODIFICATION SIMULATION");
    println!("====================================");

    // Create a new user for this demo
    let create_request = ScimOperationRequest::create(
        "User",
        json!({
            "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
            "userName": "concurrent.test",
            "active": true
        }),
    );

    let create_response = handler.handle_operation(create_request).await;
    let concurrent_user_id = create_response.metadata.resource_id.clone().unwrap();

    // Get initial version
    let get_request = ScimOperationRequest::get("User", &concurrent_user_id);
    let get_response = handler.handle_operation(get_request).await;
    let initial_etag = get_response
        .metadata
        .additional
        .get("etag")
        .unwrap()
        .as_str()
        .unwrap();
    let initial_version: HttpVersion = initial_etag.parse()?;

    println!(
        "✅ Created user for concurrent test: {}",
        concurrent_user_id
    );
    println!("   Initial ETag (weak): {}", initial_etag);

    // Simulate Client A getting the resource
    let client_a_version = initial_version.clone();
    println!(
        "👤 Client A has ETag (weak): {}",
        client_a_version.to_string()
    );

    // Simulate Client B getting the resource
    let client_b_version = initial_version.clone();
    println!(
        "👤 Client B has ETag (weak): {}",
        client_b_version.to_string()
    );

    // Client A successfully updates
    let client_a_update = ScimOperationRequest::update(
        "User",
        &concurrent_user_id,
        json!({
            "id": concurrent_user_id,
            "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
            "userName": "concurrent.test",
            "name": {
                "givenName": "Client",
                "familyName": "A"
            },
            "active": true
        }),
    )
    .with_expected_version(client_a_version);

    let client_a_response = handler.handle_operation(client_a_update).await;

    if client_a_response.success {
        let new_etag = client_a_response.metadata.additional.get("etag").unwrap();
        println!("✅ Client A update succeeded!");
        println!("   New ETag (weak): {}", new_etag.as_str().unwrap());
    }

    // Client B tries to update with stale version (should fail)
    sleep(Duration::from_millis(100)).await; // Small delay to simulate real timing

    let client_b_update = ScimOperationRequest::update(
        "User",
        &concurrent_user_id,
        json!({
            "id": concurrent_user_id,
            "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
            "userName": "concurrent.test",
            "name": {
                "givenName": "Client",
                "familyName": "B"
            },
            "active": false
        }),
    )
    .with_expected_version(client_b_version); // Using stale version

    let client_b_response = handler.handle_operation(client_b_update).await;

    if !client_b_response.success {
        println!("✅ Client B update correctly rejected!");
        println!("   Error: {}", client_b_response.error.unwrap());
        println!("   Prevented lost update scenario!");
    } else {
        println!("❌ Client B update should have failed!");
    }

    // Client B retrieves current version and retries
    let get_current_request = ScimOperationRequest::get("User", &concurrent_user_id);
    let get_current_response = handler.handle_operation(get_current_request).await;
    let current_etag = get_current_response
        .metadata
        .additional
        .get("etag")
        .unwrap()
        .as_str()
        .unwrap();
    let current_version: HttpVersion = current_etag.parse()?;

    println!(
        "👤 Client B retrieves current ETag (weak): {}",
        current_etag
    );

    let client_b_retry = ScimOperationRequest::update(
        "User",
        &concurrent_user_id,
        json!({
            "id": concurrent_user_id,
            "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
            "userName": "concurrent.test",
            "name": {
                "givenName": "Client A and B", // Merge changes
                "familyName": "Combined"
            },
            "active": false
        }),
    )
    .with_expected_version(current_version);

    let client_b_retry_response = handler.handle_operation(client_b_retry).await;

    if client_b_retry_response.success {
        println!("✅ Client B retry succeeded with current version!");
        let final_etag = client_b_retry_response
            .metadata
            .additional
            .get("etag")
            .unwrap();
        println!("   Final ETag (weak): {}", final_etag.as_str().unwrap());
    }

    println!();

    // === SUMMARY ===
    println!("🎉 ETAG CONCURRENCY CONTROL EXAMPLE COMPLETED!");
    println!("==============================================");
    println!("✅ Demonstrated automatic version management");
    println!("✅ Showed conditional update success and failure");
    println!("✅ Verified conditional delete operations");
    println!("✅ Illustrated content-based version computation");
    println!("✅ Simulated concurrent modification protection");
    println!("✅ Prevented lost update scenarios");
    println!();
    println!("🔧 KEY BENEFITS:");
    println!("   • Automatic weak ETag generation from resource content");
    println!("   • Built-in optimistic concurrency control");
    println!("   • RFC 7232 compliant HTTP weak ETag support");
    println!("   • Zero-configuration versioning for all providers");
    println!("   • Comprehensive conflict detection and handling");
    println!("   • Provider-agnostic implementation");

    Ok(())
}