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
//! Schema structure validation tests.
//!
//! This module tests validation errors related to the structure and format
//! of SCIM schema attributes in resources (Errors 1-8).

use serde_json::json;

// Import test utilities
use crate::common::{ValidationErrorCode, builders::UserBuilder, fixtures::rfc_examples};

// Import SCIM server types
use scim_server::error::ValidationError;
use scim_server::schema::{SchemaRegistry, validation::OperationContext};

/// Test Error #1: Missing required `schemas` attribute in resource
#[test]
fn test_missing_schemas_attribute() {
    let registry = SchemaRegistry::new().expect("Failed to create registry");

    // Create a User resource without the schemas attribute
    let invalid_user = UserBuilder::new().without_schemas().build();

    // Verify the test data is constructed correctly
    assert!(!invalid_user.as_object().unwrap().contains_key("schemas"));

    // Actually validate the resource
    let result = registry.validate_json_resource_with_context(
        "User",
        &invalid_user,
        OperationContext::Update,
    );

    // Assert that validation fails with the expected error
    assert!(result.is_err());
    match result {
        Err(ValidationError::MissingSchemas) => {
            // Expected error occurred
        }
        Err(other) => panic!("Expected MissingSchemas error, got {:?}", other),
        Ok(_) => panic!("Expected validation to fail, but it passed"),
    }
}

/// Test Error #2: Empty `schemas` array in resource
#[test]
fn test_empty_schemas_array() {
    let registry = SchemaRegistry::new().expect("Failed to create registry");

    // Create a User resource with empty schemas array
    let invalid_user = UserBuilder::new().with_empty_schemas().build();

    // Verify schemas array is empty
    assert_eq!(invalid_user["schemas"], json!([]));

    // Actually validate the resource
    let result = registry.validate_json_resource_with_context(
        "User",
        &invalid_user,
        OperationContext::Update,
    );

    // Assert that validation fails with the expected error
    assert!(result.is_err());
    match result {
        Err(ValidationError::EmptySchemas) => {
            // Expected error occurred
        }
        Err(other) => panic!("Expected EmptySchemas error, got {:?}", other),
        Ok(_) => panic!("Expected validation to fail, but it passed"),
    }
}

/// Test Error #3: Invalid schema URI format in `schemas` attribute
#[test]
fn test_invalid_schema_uri_format() {
    let registry = SchemaRegistry::new().expect("Failed to create registry");

    // Create a User resource with malformed schema URI
    let invalid_user = UserBuilder::new().with_invalid_schema_uri().build();

    // Verify the invalid URI is present
    assert_eq!(invalid_user["schemas"][0], "not-a-valid-uri");

    // Actually validate the resource
    let result = registry.validate_json_resource_with_context(
        "User",
        &invalid_user,
        OperationContext::Update,
    );

    // Assert that validation fails with the expected error
    assert!(result.is_err());
    match result {
        Err(ValidationError::InvalidSchemaUri { uri }) => {
            assert_eq!(uri, "not-a-valid-uri");
        }
        Err(other) => panic!("Expected InvalidSchemaUri error, got {:?}", other),
        Ok(_) => panic!("Expected validation to fail, but it passed"),
    }
}

/// Test Error #4: Unknown/unregistered schema URI referenced
#[test]
fn test_unknown_schema_uri() {
    let registry = SchemaRegistry::new().expect("Failed to create registry");

    // Create a User resource with unknown schema URI
    let invalid_user = UserBuilder::new().with_unknown_schema_uri().build();

    // Verify the unknown URI is present
    assert_eq!(
        invalid_user["schemas"][0],
        "urn:ietf:params:scim:schemas:core:2.0:UnknownResource"
    );

    // Actually validate the resource
    let result = registry.validate_json_resource_with_context(
        "User",
        &invalid_user,
        OperationContext::Update,
    );

    // Assert that validation fails with the expected error
    assert!(result.is_err());
    match result {
        Err(ValidationError::UnknownSchemaUri { uri }) => {
            assert_eq!(uri, "urn:ietf:params:scim:schemas:core:2.0:UnknownResource");
        }
        Err(other) => panic!("Expected UnknownSchemaUri error, got {:?}", other),
        Ok(_) => panic!("Expected validation to fail, but it passed"),
    }
}

/// Test Error #5: Duplicate schema URIs in `schemas` array
#[test]
fn test_duplicate_schema_uris() {
    let registry = SchemaRegistry::new().expect("Failed to create registry");

    // Create a User resource with duplicate schema URIs
    let invalid_user = UserBuilder::new().with_duplicate_schema_uris().build();

    // Verify duplicates are present
    let schemas = invalid_user["schemas"].as_array().unwrap();
    assert_eq!(schemas.len(), 2);
    assert_eq!(schemas[0], schemas[1]);
    assert_eq!(schemas[0], "urn:ietf:params:scim:schemas:core:2.0:User");

    // Actually validate the resource
    let result = registry.validate_json_resource_with_context(
        "User",
        &invalid_user,
        OperationContext::Update,
    );

    // Assert that validation fails with the expected error
    assert!(result.is_err());
    match result {
        Err(ValidationError::DuplicateSchemaUri { uri }) => {
            assert_eq!(uri, "urn:ietf:params:scim:schemas:core:2.0:User");
        }
        Err(other) => panic!("Expected DuplicateSchemaUri error, got {:?}", other),
        Ok(_) => panic!("Expected validation to fail, but it passed"),
    }
}

/// Test Error #6: Missing base/core schema URI for resource type
#[test]
fn test_missing_base_schema() {
    // Create a User resource with only extension schema, missing base User schema
    let invalid_user = json!({
        "schemas": ["urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"],
        "id": "123",
        "userName": "test@example.com",
        "meta": {
            "resourceType": "User"
        }
    });

    // Verify base schema is missing
    let schemas = invalid_user["schemas"].as_array().unwrap();
    assert_eq!(schemas.len(), 1);
    assert!(!schemas.contains(&json!("urn:ietf:params:scim:schemas:core:2.0:User")));
    assert!(schemas.contains(&json!(
        "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
    )));

    // This would trigger ValidationErrorCode::MissingBaseSchema in real validation
}

/// Test Error #7: Schema extension URI present without base schema
#[test]
fn test_extension_without_base_schema() {
    // Similar to above but more explicit about the extension-without-base error
    let invalid_user = json!({
        "schemas": [
            "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User",
            "urn:example:params:scim:schemas:extension:custom:2.0:User"
        ],
        "id": "123",
        "userName": "test@example.com",
        "meta": {
            "resourceType": "User"
        }
    });

    // Verify only extensions are present, no base schema
    let schemas = invalid_user["schemas"].as_array().unwrap();
    assert_eq!(schemas.len(), 2);
    assert!(!schemas.contains(&json!("urn:ietf:params:scim:schemas:core:2.0:User")));

    // All schemas are extensions
    for schema in schemas {
        assert!(schema.as_str().unwrap().contains("extension"));
    }
}

/// Test Error #8: Required schema extension missing when resource type mandates it
#[test]
fn test_missing_required_extension() {
    // Simulate a scenario where a ResourceType configuration requires an extension
    // but the resource doesn't include it
    let user_without_required_extension = json!({
        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
        "id": "123",
        "userName": "test@example.com",
        "meta": {
            "resourceType": "User"
        }
    });

    // Verify base schema is present but required extension is missing
    let schemas = user_without_required_extension["schemas"]
        .as_array()
        .unwrap();
    assert_eq!(schemas.len(), 1);
    assert!(schemas.contains(&json!("urn:ietf:params:scim:schemas:core:2.0:User")));
    assert!(!schemas.contains(&json!(
        "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
    )));
}

/// Test valid schema configurations to ensure we don't have false positives
#[test]
fn test_valid_schema_configurations() {
    let registry = SchemaRegistry::new().expect("Failed to create registry");

    // Test 1: Valid minimal User with just core schema
    let valid_minimal = rfc_examples::user_minimal();
    let schemas = valid_minimal["schemas"].as_array().unwrap();
    assert_eq!(schemas.len(), 1);
    assert_eq!(schemas[0], "urn:ietf:params:scim:schemas:core:2.0:User");

    // This should pass validation
    let result = registry.validate_json_resource_with_context(
        "User",
        &valid_minimal,
        OperationContext::Update,
    );
    assert!(result.is_ok(), "Valid minimal user should pass validation");

    // Test 2: Valid User with extension (this will fail until we add Group schema support)
    let valid_enterprise = rfc_examples::user_enterprise();
    let schemas = valid_enterprise["schemas"].as_array().unwrap();
    assert_eq!(schemas.len(), 2);
    assert!(schemas.contains(&json!("urn:ietf:params:scim:schemas:core:2.0:User")));
    assert!(schemas.contains(&json!(
        "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
    )));

    // Test 3: Valid Group (this will fail until we add Group schema support)
    let valid_group = rfc_examples::group_basic();
    let schemas = valid_group["schemas"].as_array().unwrap();
    assert_eq!(schemas.len(), 1);
    assert_eq!(schemas[0], "urn:ietf:params:scim:schemas:core:2.0:Group");
}

/// Test multiple schema structure errors in a single resource
#[test]
fn test_multiple_schema_structure_errors() {
    // Create a resource with multiple schema-related issues
    let invalid_resource = json!({
        "schemas": [], // Empty schemas (Error #2)
        "userName": "test@example.com"
        // Also missing id, meta, etc. but focusing on schema errors
    });

    // Verify multiple issues are present
    assert_eq!(invalid_resource["schemas"], json!([]));
    assert!(!invalid_resource.as_object().unwrap().contains_key("id"));
    assert!(!invalid_resource.as_object().unwrap().contains_key("meta"));
}

/// Test schema URI format validation specifics
#[test]
fn test_schema_uri_format_validation() {
    // Test various invalid URI formats
    let test_cases = vec![
        "not-a-uri",                    // No scheme
        "urn:",                         // Incomplete URN
        "http://example.com",           // Wrong scheme (should be URN)
        "urn:invalid",                  // Malformed URN
        "",                             // Empty string
        "urn:ietf:params:scim:schemas", // Incomplete SCIM URN
    ];

    for invalid_uri in test_cases {
        let invalid_user = json!({
            "schemas": [invalid_uri],
            "id": "123",
            "userName": "test@example.com",
            "meta": {
                "resourceType": "User"
            }
        });

        // Each should be considered an invalid schema URI
        assert_eq!(invalid_user["schemas"][0], invalid_uri);
    }
}

/// Test valid schema URI formats
#[test]
fn test_valid_schema_uri_formats() {
    let valid_uris = vec![
        "urn:ietf:params:scim:schemas:core:2.0:User",
        "urn:ietf:params:scim:schemas:core:2.0:Group",
        "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User",
        "urn:example:params:scim:schemas:extension:custom:2.0:User",
    ];

    for valid_uri in valid_uris {
        let valid_user = json!({
            "schemas": [valid_uri],
            "id": "123",
            "userName": "test@example.com",
            "meta": {
                "resourceType": "User"
            }
        });

        // Should be considered valid URIs
        assert_eq!(valid_user["schemas"][0], valid_uri);
        assert!(valid_uri.starts_with("urn:"));
        assert!(valid_uri.contains("scim:schemas"));
    }
}

/// Test schema-to-resource-type consistency
#[test]
fn test_schema_resource_type_consistency() {
    // User resource should have User schemas
    let valid_user = json!({
        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
        "id": "123",
        "userName": "test@example.com",
        "meta": {
            "resourceType": "User"
        }
    });
    assert_eq!(valid_user["meta"]["resourceType"], "User");
    assert!(valid_user["schemas"][0].as_str().unwrap().contains("User"));

    // Group resource should have Group schemas
    let valid_group = json!({
        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"],
        "id": "123",
        "displayName": "Test Group",
        "meta": {
            "resourceType": "Group"
        }
    });
    assert_eq!(valid_group["meta"]["resourceType"], "Group");
    assert!(
        valid_group["schemas"][0]
            .as_str()
            .unwrap()
            .contains("Group")
    );

    // Inconsistent case: User resource with Group schema (should be invalid)
    let inconsistent_resource = json!({
        "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"],
        "id": "123",
        "userName": "test@example.com", // User attribute
        "meta": {
            "resourceType": "User" // User type
        }
    });
    // This shows inconsistency between schema and resource type
    assert_eq!(inconsistent_resource["meta"]["resourceType"], "User");
    assert!(
        inconsistent_resource["schemas"][0]
            .as_str()
            .unwrap()
            .contains("Group")
    );
}

#[cfg(test)]
mod coverage_tests {
    use super::*;
    use crate::common::TestCoverage;

    #[test]
    fn test_schema_structure_error_coverage() {
        // Verify all schema structure errors (1-8) are covered by our tests
        let mut coverage = TestCoverage::new();

        // Mark errors as tested based on our test functions
        coverage.mark_tested(ValidationErrorCode::MissingSchemas); // Error #1
        coverage.mark_tested(ValidationErrorCode::EmptySchemas); // Error #2
        coverage.mark_tested(ValidationErrorCode::InvalidSchemaUri); // Error #3
        coverage.mark_tested(ValidationErrorCode::UnknownSchemaUri); // Error #4
        coverage.mark_tested(ValidationErrorCode::DuplicateSchemaUri); // Error #5
        coverage.mark_tested(ValidationErrorCode::MissingBaseSchema); // Error #6
        coverage.mark_tested(ValidationErrorCode::ExtensionWithoutBase); // Error #7
        coverage.mark_tested(ValidationErrorCode::MissingRequiredExtension); // Error #8

        // Verify we've covered all schema structure errors
        let schema_structure_errors = [
            ValidationErrorCode::MissingSchemas,
            ValidationErrorCode::EmptySchemas,
            ValidationErrorCode::InvalidSchemaUri,
            ValidationErrorCode::UnknownSchemaUri,
            ValidationErrorCode::DuplicateSchemaUri,
            ValidationErrorCode::MissingBaseSchema,
            ValidationErrorCode::ExtensionWithoutBase,
            ValidationErrorCode::MissingRequiredExtension,
        ];

        for error in &schema_structure_errors {
            assert!(
                coverage.is_tested(error),
                "Error {:?} not covered by tests",
                error
            );
        }
    }
}