scim-server 0.4.0

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
//! Dynamic value object factory for schema-driven construction.
//!
//! This module provides a factory system that can dynamically create value objects
//! based on SCIM schema definitions and JSON values. It supports both core SCIM
//! attributes and extension attributes, enabling flexible resource construction
//! while maintaining type safety and validation.
//!
//! ## Design Principles
//!
//! - **Schema-Driven**: Factory decisions based on attribute definitions
//! - **Extensible**: Support for registering new value object types
//! - **Type-Safe**: Compile-time guarantees where possible
//! - **Performance**: Efficient lookup and construction mechanisms

use super::extension::ExtensionAttributeValue;
use super::value_object_trait::{ValueObject, ValueObjectConstructor, ValueObjectRegistry};
use super::{EmailAddress, ExternalId, Name, ResourceId, SchemaUri, UserName};
use crate::error::{ValidationError, ValidationResult};
use crate::schema::types::{AttributeDefinition, AttributeType};
use serde_json::Value;
use std::collections::HashMap;

/// Factory for creating value objects from schema definitions and JSON values.
///
/// The factory maintains a registry of constructors and can dynamically
/// create appropriate value objects based on attribute definitions.
pub struct ValueObjectFactory {
    registry: ValueObjectRegistry,
    type_mappings: HashMap<String, AttributeType>,
}

impl ValueObjectFactory {
    /// Create a new factory with default constructors registered.
    pub fn new() -> Self {
        let mut factory = Self {
            registry: ValueObjectRegistry::new(),
            type_mappings: HashMap::new(),
        };

        factory.register_default_constructors();
        factory.setup_type_mappings();
        factory
    }

    /// Create a value object from a schema definition and JSON value.
    pub fn create_value_object(
        &self,
        definition: &AttributeDefinition,
        value: &Value,
    ) -> ValidationResult<Box<dyn ValueObject>> {
        // Handle null values for optional attributes
        if matches!(value, Value::Null) && !definition.required {
            return Err(ValidationError::NullValueForOptionalAttribute(
                definition.name.clone(),
            ));
        }

        // Handle multi-valued attributes
        if definition.multi_valued {
            return self.create_multi_valued_object(definition, value);
        }

        // Try registered constructors first
        match self.registry.create_value_object(definition, value) {
            Ok(obj) => Ok(obj),
            Err(_) => {
                // Fall back to extension attribute if no specific constructor found
                self.create_extension_attribute(definition, value)
            }
        }
    }

    /// Create a multi-valued attribute object.
    fn create_multi_valued_object(
        &self,
        definition: &AttributeDefinition,
        value: &Value,
    ) -> ValidationResult<Box<dyn ValueObject>> {
        let array = value
            .as_array()
            .ok_or_else(|| ValidationError::ExpectedArray(definition.name.clone()))?;

        // Create individual value objects for each array element
        let mut objects = Vec::new();
        for item_value in array {
            // Create a single-valued definition for each item
            let item_definition = AttributeDefinition {
                multi_valued: false,
                ..definition.clone()
            };

            let obj = self.create_value_object(&item_definition, item_value)?;
            objects.push(obj);
        }

        // For now, we'll create a generic multi-valued container
        // In a more sophisticated implementation, we could have specific
        // multi-valued types for different attribute types
        Ok(Box::new(GenericMultiValuedAttribute::new(
            definition.name.clone(),
            objects,
        )))
    }

    /// Create an extension attribute value object.
    fn create_extension_attribute(
        &self,
        definition: &AttributeDefinition,
        value: &Value,
    ) -> ValidationResult<Box<dyn ValueObject>> {
        // Create a default schema URI for unknown extensions
        let schema_uri = SchemaUri::new(format!(
            "urn:ietf:params:scim:schemas:extension:unknown:{}",
            definition.name
        ))?;

        let ext_attr = ExtensionAttributeValue::new(
            schema_uri,
            definition.name.clone(),
            value.clone(),
            Some(definition.clone()),
        )?;

        Ok(Box::new(ext_attr))
    }

    /// Register default constructors for built-in value objects.
    fn register_default_constructors(&mut self) {
        // Register constructors for core value objects
        self.registry
            .register_constructor(Box::new(ResourceIdConstructor::new()));
        self.registry
            .register_constructor(Box::new(UserNameConstructor::new()));
        self.registry
            .register_constructor(Box::new(ExternalIdConstructor::new()));
        self.registry
            .register_constructor(Box::new(EmailAddressConstructor::new()));
        self.registry
            .register_constructor(Box::new(SchemaUriConstructor::new()));
        self.registry
            .register_constructor(Box::new(NameConstructor::new()));
        // TODO: Add constructors for Address, PhoneNumber, and Meta when from_json methods are implemented
    }

    /// Setup mappings from attribute names to expected types.
    fn setup_type_mappings(&mut self) {
        self.type_mappings
            .insert("id".to_string(), AttributeType::String);
        self.type_mappings
            .insert("userName".to_string(), AttributeType::String);
        self.type_mappings
            .insert("externalId".to_string(), AttributeType::String);
        self.type_mappings
            .insert("schemas".to_string(), AttributeType::Reference);
        self.type_mappings
            .insert("name".to_string(), AttributeType::Complex);
        self.type_mappings
            .insert("emails".to_string(), AttributeType::Complex);
        self.type_mappings
            .insert("phoneNumbers".to_string(), AttributeType::Complex);
        self.type_mappings
            .insert("addresses".to_string(), AttributeType::Complex);
        self.type_mappings
            .insert("meta".to_string(), AttributeType::Complex);
    }

    /// Get the expected attribute type for a given attribute name.
    pub fn get_expected_type(&self, attribute_name: &str) -> Option<AttributeType> {
        self.type_mappings.get(attribute_name).cloned()
    }

    /// Register a custom constructor.
    pub fn register_constructor(&mut self, constructor: Box<dyn ValueObjectConstructor>) {
        self.registry.register_constructor(constructor);
    }

    /// Validate composite rules across multiple value objects.
    pub fn validate_composite_rules(
        &self,
        objects: &[Box<dyn ValueObject>],
    ) -> ValidationResult<()> {
        self.registry.validate_composite_rules(objects)
    }

    /// Check if the factory has any constructors registered.
    pub fn has_constructors(&self) -> bool {
        self.registry.has_constructors()
    }

    /// Create a collection of value objects from a JSON object.
    pub fn create_value_objects_from_json(
        &self,
        definitions: &[AttributeDefinition],
        json_obj: &serde_json::Map<String, Value>,
    ) -> ValidationResult<Vec<Box<dyn ValueObject>>> {
        let mut objects = Vec::new();

        for definition in definitions {
            if let Some(value) = json_obj.get(&definition.name) {
                let obj = self.create_value_object(definition, value)?;
                objects.push(obj);
            } else if definition.required {
                return Err(ValidationError::RequiredAttributeMissing(
                    definition.name.clone(),
                ));
            }
        }

        Ok(objects)
    }
}

impl Default for ValueObjectFactory {
    fn default() -> Self {
        Self::new()
    }
}

/// Generic multi-valued attribute container for factory-created objects.
#[derive(Debug)]
pub struct GenericMultiValuedAttribute {
    attribute_name: String,
    values: Vec<Box<dyn ValueObject>>,
    primary_index: Option<usize>,
}

impl GenericMultiValuedAttribute {
    pub fn new(attribute_name: String, values: Vec<Box<dyn ValueObject>>) -> Self {
        Self {
            attribute_name,
            values,
            primary_index: None,
        }
    }

    pub fn values(&self) -> &[Box<dyn ValueObject>] {
        &self.values
    }

    pub fn primary(&self) -> Option<&Box<dyn ValueObject>> {
        self.primary_index.map(|idx| &self.values[idx])
    }

    pub fn set_primary(&mut self, index: usize) -> ValidationResult<()> {
        if index >= self.values.len() {
            return Err(ValidationError::InvalidPrimaryIndex {
                attribute: self.attribute_name.clone(),
                index,
                length: self.values.len(),
            });
        }
        self.primary_index = Some(index);
        Ok(())
    }
}

impl ValueObject for GenericMultiValuedAttribute {
    fn attribute_type(&self) -> AttributeType {
        AttributeType::Complex // Multi-valued attributes are complex
    }

    fn attribute_name(&self) -> &str {
        &self.attribute_name
    }

    fn to_json(&self) -> ValidationResult<Value> {
        let mut array = Vec::new();
        for value_obj in &self.values {
            array.push(value_obj.to_json()?);
        }
        Ok(Value::Array(array))
    }

    fn validate_against_schema(&self, definition: &AttributeDefinition) -> ValidationResult<()> {
        if !definition.multi_valued {
            return Err(ValidationError::NotMultiValued(definition.name.clone()));
        }

        // Validate each value object
        let single_def = AttributeDefinition {
            multi_valued: false,
            ..definition.clone()
        };

        for value_obj in &self.values {
            value_obj.validate_against_schema(&single_def)?;
        }

        Ok(())
    }

    fn as_json_value(&self) -> Value {
        self.to_json().unwrap_or(Value::Null)
    }

    fn supports_definition(&self, definition: &AttributeDefinition) -> bool {
        definition.multi_valued && definition.name == self.attribute_name
    }

    fn clone_boxed(&self) -> Box<dyn ValueObject> {
        Box::new(GenericMultiValuedAttribute {
            attribute_name: self.attribute_name.clone(),
            values: self.values.iter().map(|v| v.clone_boxed()).collect(),
            primary_index: self.primary_index,
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// Specific constructors for built-in value objects

pub struct ResourceIdConstructor;

impl ResourceIdConstructor {
    pub fn new() -> Self {
        Self
    }
}

impl ValueObjectConstructor for ResourceIdConstructor {
    fn try_construct(
        &self,
        definition: &AttributeDefinition,
        value: &Value,
    ) -> Option<ValidationResult<Box<dyn ValueObject>>> {
        if definition.name == "id" && definition.data_type == AttributeType::String {
            if let Some(id_str) = value.as_str() {
                Some(
                    ResourceId::new(id_str.to_string())
                        .map(|id| Box::new(id) as Box<dyn ValueObject>),
                )
            } else {
                Some(Err(ValidationError::InvalidAttributeType {
                    attribute: definition.name.clone(),
                    expected: "string".to_string(),
                    actual: "non-string".to_string(),
                }))
            }
        } else {
            None
        }
    }

    fn priority(&self) -> u8 {
        100 // High priority for exact matches
    }

    fn description(&self) -> &str {
        "ResourceId constructor for 'id' attributes"
    }
}

pub struct UserNameConstructor;

impl UserNameConstructor {
    pub fn new() -> Self {
        Self
    }
}

impl ValueObjectConstructor for UserNameConstructor {
    fn try_construct(
        &self,
        definition: &AttributeDefinition,
        value: &Value,
    ) -> Option<ValidationResult<Box<dyn ValueObject>>> {
        if definition.name == "userName" && definition.data_type == AttributeType::String {
            if let Some(username_str) = value.as_str() {
                Some(
                    UserName::new(username_str.to_string())
                        .map(|username| Box::new(username) as Box<dyn ValueObject>),
                )
            } else {
                Some(Err(ValidationError::InvalidAttributeType {
                    attribute: definition.name.clone(),
                    expected: "string".to_string(),
                    actual: "non-string".to_string(),
                }))
            }
        } else {
            None
        }
    }

    fn priority(&self) -> u8 {
        100
    }

    fn description(&self) -> &str {
        "UserName constructor for 'userName' attributes"
    }
}

pub struct ExternalIdConstructor;

impl ExternalIdConstructor {
    pub fn new() -> Self {
        Self
    }
}

impl ValueObjectConstructor for ExternalIdConstructor {
    fn try_construct(
        &self,
        definition: &AttributeDefinition,
        value: &Value,
    ) -> Option<ValidationResult<Box<dyn ValueObject>>> {
        if definition.name == "externalId" && definition.data_type == AttributeType::String {
            if let Some(ext_id_str) = value.as_str() {
                Some(
                    ExternalId::new(ext_id_str.to_string())
                        .map(|ext_id| Box::new(ext_id) as Box<dyn ValueObject>),
                )
            } else {
                Some(Err(ValidationError::InvalidAttributeType {
                    attribute: definition.name.clone(),
                    expected: "string".to_string(),
                    actual: "non-string".to_string(),
                }))
            }
        } else {
            None
        }
    }

    fn priority(&self) -> u8 {
        100
    }

    fn description(&self) -> &str {
        "ExternalId constructor for 'externalId' attributes"
    }
}

pub struct EmailAddressConstructor;

impl EmailAddressConstructor {
    pub fn new() -> Self {
        Self
    }
}

impl ValueObjectConstructor for EmailAddressConstructor {
    fn try_construct(
        &self,
        definition: &AttributeDefinition,
        value: &Value,
    ) -> Option<ValidationResult<Box<dyn ValueObject>>> {
        if (definition.name == "value" || definition.name.contains("email"))
            && definition.data_type == AttributeType::String
        {
            if let Some(email_str) = value.as_str() {
                Some(
                    EmailAddress::new(email_str.to_string(), None, None, None)
                        .map(|email| Box::new(email) as Box<dyn ValueObject>),
                )
            } else {
                Some(Err(ValidationError::InvalidAttributeType {
                    attribute: definition.name.clone(),
                    expected: "string".to_string(),
                    actual: "non-string".to_string(),
                }))
            }
        } else {
            None
        }
    }

    fn priority(&self) -> u8 {
        80 // Lower priority than exact name matches
    }

    fn description(&self) -> &str {
        "EmailAddress constructor for email-related attributes"
    }
}

pub struct SchemaUriConstructor;

impl SchemaUriConstructor {
    pub fn new() -> Self {
        Self
    }
}

impl ValueObjectConstructor for SchemaUriConstructor {
    fn try_construct(
        &self,
        _definition: &AttributeDefinition,
        _value: &Value,
    ) -> Option<ValidationResult<Box<dyn ValueObject>>> {
        // TODO: Implement when SchemaUri implements ValueObject trait
        None
    }

    fn priority(&self) -> u8 {
        100
    }

    fn description(&self) -> &str {
        "SchemaUri constructor for 'schemas' attributes"
    }
}

pub struct NameConstructor;

impl NameConstructor {
    pub fn new() -> Self {
        Self
    }
}

impl ValueObjectConstructor for NameConstructor {
    fn try_construct(
        &self,
        definition: &AttributeDefinition,
        value: &Value,
    ) -> Option<ValidationResult<Box<dyn ValueObject>>> {
        if definition.name == "name" && definition.data_type == AttributeType::Complex {
            Some(Name::from_json(value).map(|name| Box::new(name) as Box<dyn ValueObject>))
        } else {
            None
        }
    }

    fn priority(&self) -> u8 {
        100
    }

    fn description(&self) -> &str {
        "Name constructor for 'name' complex attributes"
    }
}

// TODO: Implement constructors for Address, PhoneNumber, and Meta when from_json methods are available

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::types::{Mutability, Uniqueness};

    fn create_string_definition(name: &str) -> AttributeDefinition {
        AttributeDefinition {
            name: name.to_string(),
            data_type: AttributeType::String,
            multi_valued: false,
            required: false,
            case_exact: false,
            mutability: Mutability::ReadWrite,
            uniqueness: Uniqueness::None,
            canonical_values: vec![],
            sub_attributes: vec![],
            returned: None,
        }
    }

    #[test]
    fn test_factory_creation() {
        let factory = ValueObjectFactory::new();
        assert!(factory.has_constructors());
    }

    #[test]
    fn test_resource_id_construction() {
        let factory = ValueObjectFactory::new();
        let definition = create_string_definition("id");
        let value = Value::String("test-id".to_string());

        let result = factory.create_value_object(&definition, &value);
        assert!(result.is_ok());

        let obj = result.unwrap();
        assert_eq!(obj.attribute_name(), "id");
        assert_eq!(obj.attribute_type(), AttributeType::String);
    }

    #[test]
    fn test_username_construction() {
        let factory = ValueObjectFactory::new();
        let definition = create_string_definition("userName");
        let value = Value::String("testuser".to_string());

        let result = factory.create_value_object(&definition, &value);
        assert!(result.is_ok());

        let obj = result.unwrap();
        assert_eq!(obj.attribute_name(), "userName");
    }
}