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
//! Stage 1: Core Multi-Tenant Foundation Tests
//!
//! This module contains the foundational tests for multi-tenant functionality.
//! These tests drive the development of:
//! - Enhanced RequestContext with tenant information
//! - TenantResolver trait and implementations
//! - Basic tenant validation in ScimServer
//! - Tenant-related error types and handling
//! - Cross-tenant access prevention at the core level
//!
//! ## Test Strategy
//!
//! These tests follow a test-driven development approach where we:
//! 1. Define the expected behavior through tests
//! 2. Watch tests fail (Red)
//! 3. Implement minimal code to make tests pass (Green)
//! 4. Refactor for quality (Refactor)
//!
//! ## Security Focus
//!
//! Every test in this module focuses on ensuring tenant isolation and preventing
//! cross-tenant data access, which is critical for SaaS applications.

use scim_server::{IsolationLevel, RequestContext, TenantContext, TenantPermissions};
use std::collections::HashMap;

// ============================================================================
// Test Data Structures and Builders
// ============================================================================

/// Builder for creating tenant context test data
#[derive(Debug, Clone)]
pub struct TenantContextBuilder {
    tenant_id: String,
    client_id: String,
    isolation_level: IsolationLevel,
    permissions: Vec<String>,
}

impl TenantContextBuilder {
    pub fn new(tenant_id: &str) -> Self {
        Self {
            tenant_id: tenant_id.to_string(),
            client_id: format!("{}_client", tenant_id),
            isolation_level: IsolationLevel::Standard,
            permissions: vec!["read".to_string(), "write".to_string()],
        }
    }

    pub fn with_client_id(mut self, client_id: &str) -> Self {
        self.client_id = client_id.to_string();
        self
    }

    pub fn with_isolation_level(mut self, level: IsolationLevel) -> Self {
        self.isolation_level = level;
        self
    }

    pub fn with_permissions(mut self, permissions: Vec<&str>) -> Self {
        self.permissions = permissions.into_iter().map(String::from).collect();
        self
    }

    pub fn build(self) -> TenantContext {
        let mut permissions = TenantPermissions::default();
        permissions.can_create = self.permissions.contains(&"create".to_string())
            || self.permissions.contains(&"write".to_string());
        permissions.can_read = self.permissions.contains(&"read".to_string());
        permissions.can_update = self.permissions.contains(&"update".to_string())
            || self.permissions.contains(&"write".to_string());
        permissions.can_delete = self.permissions.contains(&"delete".to_string())
            || self.permissions.contains(&"write".to_string());
        permissions.can_list = self.permissions.contains(&"list".to_string())
            || self.permissions.contains(&"read".to_string());

        TenantContext::new(self.tenant_id, self.client_id)
            .with_isolation_level(self.isolation_level)
            .with_permissions(permissions)
    }
}

/// Builder for creating authentication information
#[derive(Debug, Clone)]
pub struct AuthInfoBuilder {
    api_key: Option<String>,
    bearer_token: Option<String>,
    client_certificate: Option<Vec<u8>>,
}

impl AuthInfoBuilder {
    pub fn new() -> Self {
        Self {
            api_key: None,
            bearer_token: None,
            client_certificate: None,
        }
    }

    pub fn with_api_key(mut self, key: &str) -> Self {
        self.api_key = Some(key.to_string());
        self
    }

    pub fn with_bearer_token(mut self, token: &str) -> Self {
        self.bearer_token = Some(token.to_string());
        self
    }

    pub fn build(self) -> AuthInfo {
        AuthInfo {
            api_key: self.api_key,
            bearer_token: self.bearer_token,
            client_certificate: self.client_certificate,
        }
    }
}

// ============================================================================
// Data Structures (These will be implemented in src/)
// ============================================================================

// Use main crate types - no local definitions needed

/// Authentication information from client requests
#[derive(Debug, Clone)]
pub struct AuthInfo {
    pub api_key: Option<String>,
    pub bearer_token: Option<String>,
    pub client_certificate: Option<Vec<u8>>,
}

/// Trait for resolving authentication to tenant context
pub trait TenantResolver: Send + Sync {
    type Error: std::error::Error + Send + Sync + 'static;

    fn resolve_tenant(&self, auth_info: &AuthInfo) -> Result<TenantContext, Self::Error>;
}

/// Simple tenant resolver for testing
pub struct TestTenantResolver {
    tenant_mappings: HashMap<String, TenantContext>,
}

impl TestTenantResolver {
    pub fn new() -> Self {
        let mut mappings = HashMap::new();

        // Set up test tenants
        mappings.insert(
            "api_key_tenant_a".to_string(),
            TenantContextBuilder::new("tenant_a")
                .with_client_id("client_a")
                .build(),
        );

        mappings.insert(
            "api_key_tenant_b".to_string(),
            TenantContextBuilder::new("tenant_b")
                .with_client_id("client_b")
                .build(),
        );

        Self {
            tenant_mappings: mappings,
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum TenantError {
    #[error("Invalid authentication credentials")]
    InvalidCredentials,
    #[error("Tenant not found for credentials")]
    TenantNotFound,
    #[error("Unauthorized access to tenant {tenant_id}")]
    UnauthorizedAccess { tenant_id: String },
}

impl TenantResolver for TestTenantResolver {
    type Error = TenantError;

    fn resolve_tenant(&self, auth_info: &AuthInfo) -> Result<TenantContext, Self::Error> {
        if let Some(api_key) = &auth_info.api_key {
            self.tenant_mappings
                .get(api_key)
                .cloned()
                .ok_or(TenantError::TenantNotFound)
        } else {
            Err(TenantError::InvalidCredentials)
        }
    }
}

// ============================================================================
// Stage 1 Tests: Core Multi-Tenant Foundation
// ============================================================================

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

    // ------------------------------------------------------------------------
    // Test Group 1: TenantContext and RequestContext
    // ------------------------------------------------------------------------

    #[test]
    fn test_tenant_context_creation() {
        let tenant_context = TenantContextBuilder::new("tenant_123")
            .with_client_id("client_abc")
            .with_isolation_level(IsolationLevel::Strict)
            .with_permissions(vec!["read", "write", "delete"])
            .build();

        assert_eq!(tenant_context.tenant_id, "tenant_123");
        assert_eq!(tenant_context.client_id, "client_abc");
        assert_eq!(tenant_context.isolation_level, IsolationLevel::Strict);
        assert!(tenant_context.permissions.can_read);
        assert!(tenant_context.permissions.can_create);
        assert!(tenant_context.permissions.can_update);
        assert!(tenant_context.permissions.can_delete);
    }

    #[test]
    fn test_request_context_with_tenant() {
        let tenant_context = TenantContextBuilder::new("tenant_456").build();

        let request_context =
            scim_server::RequestContext::with_tenant("req_123".to_string(), tenant_context.clone());

        assert_eq!(request_context.request_id, "req_123");
        assert_eq!(request_context.tenant_id(), Some("tenant_456"));
    }

    #[test]
    fn test_isolation_level_variants() {
        let strict = IsolationLevel::Strict;
        let standard = IsolationLevel::Standard;
        let shared = IsolationLevel::Shared;

        // Test that isolation levels can be compared
        assert_ne!(strict, standard);
        assert_ne!(standard, shared);
        assert_ne!(strict, shared);
    }

    // ------------------------------------------------------------------------
    // Test Group 2: TenantResolver Implementation
    // ------------------------------------------------------------------------

    #[test]
    fn test_tenant_resolver_successful_resolution() {
        let resolver = TestTenantResolver::new();
        let auth_info = AuthInfoBuilder::new()
            .with_api_key("api_key_tenant_a")
            .build();

        let result = resolver.resolve_tenant(&auth_info);
        assert!(result.is_ok());

        let tenant_context = result.unwrap();
        assert_eq!(tenant_context.tenant_id, "tenant_a");
        assert_eq!(tenant_context.client_id, "client_a");
    }

    #[test]
    fn test_tenant_resolver_invalid_api_key() {
        let resolver = TestTenantResolver::new();
        let auth_info = AuthInfoBuilder::new()
            .with_api_key("invalid_api_key")
            .build();

        let result = resolver.resolve_tenant(&auth_info);
        assert!(result.is_err());

        match result.unwrap_err() {
            TenantError::TenantNotFound => {}
            other => panic!("Expected TenantNotFound, got {:?}", other),
        }
    }

    #[test]
    fn test_tenant_resolver_missing_credentials() {
        let resolver = TestTenantResolver::new();
        let auth_info = AuthInfoBuilder::new().build(); // No credentials

        let result = resolver.resolve_tenant(&auth_info);
        assert!(result.is_err());

        match result.unwrap_err() {
            TenantError::InvalidCredentials => {}
            other => panic!("Expected InvalidCredentials, got {:?}", other),
        }
    }

    #[test]
    fn test_tenant_resolver_different_tenants() {
        let resolver = TestTenantResolver::new();

        let auth_a = AuthInfoBuilder::new()
            .with_api_key("api_key_tenant_a")
            .build();
        let auth_b = AuthInfoBuilder::new()
            .with_api_key("api_key_tenant_b")
            .build();

        let tenant_a = resolver.resolve_tenant(&auth_a).unwrap();
        let tenant_b = resolver.resolve_tenant(&auth_b).unwrap();

        assert_eq!(tenant_a.tenant_id, "tenant_a");
        assert_eq!(tenant_b.tenant_id, "tenant_b");
        assert_ne!(tenant_a.tenant_id, tenant_b.tenant_id);
        assert_ne!(tenant_a.client_id, tenant_b.client_id);
    }

    // ------------------------------------------------------------------------
    // Test Group 3: Tenant Error Handling
    // ------------------------------------------------------------------------

    #[test]
    fn test_tenant_error_types() {
        let invalid_creds = TenantError::InvalidCredentials;
        let tenant_not_found = TenantError::TenantNotFound;
        let unauthorized = TenantError::UnauthorizedAccess {
            tenant_id: "tenant_123".to_string(),
        };

        // Test error messages
        assert!(invalid_creds.to_string().contains("Invalid authentication"));
        assert!(tenant_not_found.to_string().contains("Tenant not found"));
        assert!(
            unauthorized
                .to_string()
                .contains("Unauthorized access to tenant tenant_123")
        );
    }

    // ------------------------------------------------------------------------
    // Test Group 4: Cross-Tenant Isolation Verification
    // ------------------------------------------------------------------------

    #[test]
    fn test_tenant_contexts_are_isolated() {
        let tenant_a = TenantContextBuilder::new("tenant_a").build();
        let tenant_b = TenantContextBuilder::new("tenant_b").build();

        // Verify different tenants have different IDs
        assert_ne!(tenant_a.tenant_id, tenant_b.tenant_id);
        assert_ne!(tenant_a.client_id, tenant_b.client_id);

        // Verify tenant contexts are not equal
        assert_ne!(tenant_a.tenant_id, tenant_b.tenant_id);
    }

    #[test]
    fn test_tenant_context_immutability() {
        let tenant_context = TenantContextBuilder::new("tenant_123")
            .with_client_id("client_abc")
            .build();

        // Verify that cloning creates independent instances
        let cloned_context = tenant_context.clone();
        assert_eq!(tenant_context.tenant_id, cloned_context.tenant_id);
        assert_eq!(tenant_context.client_id, cloned_context.client_id);
    }

    // ------------------------------------------------------------------------
    // Test Group 5: Integration with Current RequestContext
    // ------------------------------------------------------------------------

    #[test]
    fn test_migration_from_current_request_context() {
        // This test documents how we use the unified RequestContext
        // for both single-tenant and multi-tenant scenarios

        // Single-tenant RequestContext
        let single_tenant_context = RequestContext::new("req_123".to_string());
        assert_eq!(single_tenant_context.request_id, "req_123");
        assert!(!single_tenant_context.is_multi_tenant());
        assert_eq!(single_tenant_context.tenant_id(), None);

        // Multi-tenant RequestContext
        let tenant_context = TenantContextBuilder::new("tenant_456").build();
        let multi_tenant_context =
            scim_server::RequestContext::with_tenant("req_456".to_string(), tenant_context);

        assert_eq!(multi_tenant_context.request_id, "req_456");
        assert!(multi_tenant_context.is_multi_tenant());
        assert_eq!(multi_tenant_context.tenant_id(), Some("tenant_456"));
    }

    // ------------------------------------------------------------------------
    // Test Group 6: Tenant Security Requirements
    // ------------------------------------------------------------------------

    #[test]
    fn test_tenant_permission_validation() {
        let read_only_tenant = TenantContextBuilder::new("readonly_tenant")
            .with_permissions(vec!["read"])
            .build();

        let full_access_tenant = TenantContextBuilder::new("full_access_tenant")
            .with_permissions(vec!["read", "write", "delete"])
            .build();

        assert!(read_only_tenant.permissions.can_read);
        assert!(!read_only_tenant.permissions.can_create);
        assert!(!read_only_tenant.permissions.can_update);
        assert!(!read_only_tenant.permissions.can_delete);

        assert!(full_access_tenant.permissions.can_read);
        assert!(full_access_tenant.permissions.can_create);
        assert!(full_access_tenant.permissions.can_update);
        assert!(full_access_tenant.permissions.can_delete);
    }

    #[test]
    fn test_strict_isolation_requirements() {
        let strict_tenant = TenantContextBuilder::new("strict_tenant")
            .with_isolation_level(IsolationLevel::Strict)
            .build();

        // Strict isolation should be used for highly sensitive tenants
        assert_eq!(strict_tenant.isolation_level, IsolationLevel::Strict);

        // Document the behavior expected from strict isolation
        println!("Strict isolation tenant: {}", strict_tenant.tenant_id);
        println!("Expected behavior: Complete database/schema separation");
    }

    // ------------------------------------------------------------------------
    // Test Group 7: Documentation and Examples
    // ------------------------------------------------------------------------

    #[test]
    fn test_multi_tenant_usage_examples() {
        println!("\n🏢 Multi-Tenant Usage Examples");
        println!("===============================");

        // Example 1: SaaS Application with Multiple Organizations
        let org_a = TenantContextBuilder::new("org_acme")
            .with_client_id("acme_client")
            .with_isolation_level(IsolationLevel::Standard)
            .build();

        let org_b = TenantContextBuilder::new("org_beta")
            .with_client_id("beta_client")
            .with_isolation_level(IsolationLevel::Strict)
            .build();

        println!(
            "Organization A: {} (isolation: {:?})",
            org_a.tenant_id, org_a.isolation_level
        );
        println!(
            "Organization B: {} (isolation: {:?})",
            org_b.tenant_id, org_b.isolation_level
        );

        // Example 2: Different Permission Levels
        let admin_tenant = TenantContextBuilder::new("admin_tenant")
            .with_permissions(vec!["read", "write", "delete", "admin"])
            .build();

        let viewer_tenant = TenantContextBuilder::new("viewer_tenant")
            .with_permissions(vec!["read"])
            .build();

        println!("Admin tenant permissions: {:?}", admin_tenant.permissions);
        println!("Viewer tenant permissions: {:?}", viewer_tenant.permissions);

        // Verify isolation
        assert_ne!(org_a.tenant_id, org_b.tenant_id);
        assert_ne!(admin_tenant.tenant_id, viewer_tenant.tenant_id);
    }
}

// ============================================================================
// Test Fixtures and Utilities
// ============================================================================

/// Test fixtures for multi-tenant scenarios
pub struct TenantFixtures;

impl TenantFixtures {
    /// Create a standard SaaS tenant for testing
    pub fn standard_saas_tenant(tenant_id: &str) -> TenantContext {
        TenantContextBuilder::new(tenant_id)
            .with_isolation_level(IsolationLevel::Standard)
            .with_permissions(vec!["read", "write"])
            .build()
    }

    /// Create a high-security tenant with strict isolation
    pub fn high_security_tenant(tenant_id: &str) -> TenantContext {
        TenantContextBuilder::new(tenant_id)
            .with_isolation_level(IsolationLevel::Strict)
            .with_permissions(vec!["read", "write", "delete"])
            .build()
    }

    /// Create a read-only tenant
    pub fn read_only_tenant(tenant_id: &str) -> TenantContext {
        TenantContextBuilder::new(tenant_id)
            .with_permissions(vec!["read"])
            .build()
    }
}

/// Test harness for multi-tenant integration testing
pub struct MultiTenantTestContext {
    pub resolver: TestTenantResolver,
    pub tenant_a: TenantContext,
    pub tenant_b: TenantContext,
}

impl MultiTenantTestContext {
    pub fn new() -> Self {
        Self {
            resolver: TestTenantResolver::new(),
            tenant_a: TenantFixtures::standard_saas_tenant("tenant_a"),
            tenant_b: TenantFixtures::standard_saas_tenant("tenant_b"),
        }
    }

    pub fn create_auth_for_tenant_a(&self) -> AuthInfo {
        AuthInfoBuilder::new()
            .with_api_key("api_key_tenant_a")
            .build()
    }

    pub fn create_auth_for_tenant_b(&self) -> AuthInfo {
        AuthInfoBuilder::new()
            .with_api_key("api_key_tenant_b")
            .build()
    }
}