reinhardt-auth 0.1.2

Authentication and authorization system
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Multi-tenant session isolation
//!
//! This module provides session isolation for multi-tenant applications.
//! Each tenant gets its own session namespace using prefix-based keying.
//!
//! ## Isolation Strategy
//!
//! Uses prefix-based keying with the pattern: `tenant:{tenant_id}:session:{session_id}`
//!
//! This approach provides:
//! - **Simple implementation**: Easy to understand and maintain
//! - **Efficient**: No additional infrastructure required
//! - **Scalable**: Works with any backend
//! - **Secure**: Strong isolation between tenants
//!
//! ## Example
//!
//! ```rust,no_run
//! use reinhardt_auth::sessions::tenant::{TenantSessionBackend, TenantConfig};
//! use reinhardt_auth::sessions::backends::InMemorySessionBackend;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let backend = InMemorySessionBackend::new();
//!
//! // Create tenant-specific session backend
//! let tenant_backend = TenantSessionBackend::new(
//!     backend,
//!     "tenant_123".to_string(),
//!     TenantConfig::default(),
//! );
//!
//! // All sessions are isolated to this tenant
//! # Ok(())
//! # }
//! ```

use super::backends::{SessionBackend, SessionError};
use super::cleanup::CleanupableBackend;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Tenant configuration
///
/// # Example
///
/// ```rust
/// use reinhardt_auth::sessions::tenant::TenantConfig;
///
/// let config = TenantConfig {
///     key_prefix: "tenant:{tenant_id}:session:".to_string(),
///     strict_isolation: true,
///     max_sessions: Some(10000),
/// };
/// ```
#[derive(Debug, Clone)]
pub struct TenantConfig {
	/// Key prefix pattern for tenant sessions
	///
	/// Default: `tenant:{tenant_id}:session:`
	///
	/// The `{tenant_id}` placeholder will be replaced with the actual tenant ID.
	pub key_prefix: String,

	/// Enable strict isolation (prevents cross-tenant access)
	///
	/// When enabled, operations that don't match the tenant prefix will fail.
	pub strict_isolation: bool,

	/// Maximum number of sessions per tenant
	///
	/// If set, operations that would exceed this limit will fail.
	pub max_sessions: Option<usize>,
}

impl Default for TenantConfig {
	fn default() -> Self {
		Self {
			key_prefix: "tenant:{tenant_id}:session:".to_string(),
			strict_isolation: true,
			max_sessions: None,
		}
	}
}

impl TenantConfig {
	/// Create a new tenant configuration with custom prefix
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_auth::sessions::tenant::TenantConfig;
	///
	/// let config = TenantConfig::with_prefix("app:tenant:{tenant_id}:sess:");
	/// ```
	pub fn with_prefix(prefix: &str) -> Self {
		Self {
			key_prefix: prefix.to_string(),
			..Default::default()
		}
	}

	/// Set maximum sessions per tenant
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_auth::sessions::tenant::TenantConfig;
	///
	/// let config = TenantConfig::default().with_max_sessions(5000);
	/// ```
	pub fn with_max_sessions(mut self, max: usize) -> Self {
		self.max_sessions = Some(max);
		self
	}

	/// Set strict isolation mode
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_auth::sessions::tenant::TenantConfig;
	///
	/// let config = TenantConfig::default().with_strict_isolation(false);
	/// ```
	pub fn with_strict_isolation(mut self, strict: bool) -> Self {
		self.strict_isolation = strict;
		self
	}
}

/// Tenant session backend
///
/// Provides session isolation for multi-tenant applications using prefix-based keying.
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_auth::sessions::tenant::{TenantSessionBackend, TenantConfig};
/// use reinhardt_auth::sessions::backends::InMemorySessionBackend;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let backend = InMemorySessionBackend::new();
///
/// let tenant_backend = TenantSessionBackend::new(
///     backend,
///     "tenant_123".to_string(),
///     TenantConfig::default(),
/// );
///
/// // Sessions are prefixed with "tenant:tenant_123:session:"
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct TenantSessionBackend<B> {
	backend: Arc<B>,
	tenant_id: String,
	config: TenantConfig,
}

impl<B> TenantSessionBackend<B>
where
	B: SessionBackend + Clone,
{
	/// Create a new tenant session backend with default config
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_auth::sessions::tenant::{TenantSessionBackend, TenantConfig};
	/// use reinhardt_auth::sessions::backends::InMemorySessionBackend;
	///
	/// let backend = InMemorySessionBackend::new();
	/// let tenant_backend = TenantSessionBackend::new(
	///     backend,
	///     "tenant_123".to_string(),
	///     TenantConfig::default(),
	/// );
	/// ```
	pub fn new(backend: B, tenant_id: String, config: TenantConfig) -> Self {
		Self {
			backend: Arc::new(backend),
			tenant_id,
			config,
		}
	}

	/// Get the tenant ID
	pub fn tenant_id(&self) -> &str {
		&self.tenant_id
	}

	/// Get the tenant configuration
	pub fn config(&self) -> &TenantConfig {
		&self.config
	}

	/// Make a tenant-prefixed key
	///
	/// Converts a session ID to a tenant-specific key using the configured prefix.
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_auth::sessions::tenant::{TenantSessionBackend, TenantConfig};
	/// use reinhardt_auth::sessions::backends::InMemorySessionBackend;
	///
	/// let backend = InMemorySessionBackend::new();
	/// let tenant_backend = TenantSessionBackend::new(
	///     backend,
	///     "tenant_123".to_string(),
	///     TenantConfig::default(),
	/// );
	///
	/// let key = tenant_backend.make_key("session_abc");
	/// assert_eq!(key, "tenant:tenant_123:session:session_abc");
	/// ```
	pub fn make_key(&self, session_id: &str) -> String {
		let prefix = self
			.config
			.key_prefix
			.replace("{tenant_id}", &self.tenant_id);
		format!("{}{}", prefix, session_id)
	}

	/// Check if a key belongs to this tenant
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_auth::sessions::tenant::{TenantSessionBackend, TenantConfig};
	/// use reinhardt_auth::sessions::backends::InMemorySessionBackend;
	///
	/// let backend = InMemorySessionBackend::new();
	/// let tenant_backend = TenantSessionBackend::new(
	///     backend,
	///     "tenant_123".to_string(),
	///     TenantConfig::default(),
	/// );
	///
	/// assert!(tenant_backend.is_tenant_key("tenant:tenant_123:session:abc"));
	/// assert!(!tenant_backend.is_tenant_key("tenant:tenant_456:session:abc"));
	/// ```
	pub fn is_tenant_key(&self, key: &str) -> bool {
		let prefix = self
			.config
			.key_prefix
			.replace("{tenant_id}", &self.tenant_id);
		key.starts_with(&prefix)
	}

	/// Extract session ID from tenant key
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_auth::sessions::tenant::{TenantSessionBackend, TenantConfig};
	/// use reinhardt_auth::sessions::backends::InMemorySessionBackend;
	///
	/// let backend = InMemorySessionBackend::new();
	/// let tenant_backend = TenantSessionBackend::new(
	///     backend,
	///     "tenant_123".to_string(),
	///     TenantConfig::default(),
	/// );
	///
	/// let session_id = tenant_backend.extract_session_id("tenant:tenant_123:session:abc");
	/// assert_eq!(session_id, Some("abc"));
	/// ```
	pub fn extract_session_id<'a>(&self, key: &'a str) -> Option<&'a str> {
		let prefix = self
			.config
			.key_prefix
			.replace("{tenant_id}", &self.tenant_id);

		if key.starts_with(&prefix) {
			Some(&key[prefix.len()..])
		} else {
			None
		}
	}

	/// Get a reference to the underlying backend
	pub fn backend(&self) -> &B {
		&self.backend
	}
}

#[async_trait]
impl<B> SessionBackend for TenantSessionBackend<B>
where
	B: SessionBackend + CleanupableBackend + Clone,
{
	async fn load<T>(&self, session_id: &str) -> Result<Option<T>, SessionError>
	where
		T: for<'de> Deserialize<'de> + Serialize + Send + Sync,
	{
		let key = self.make_key(session_id);
		self.backend.load(&key).await
	}

	async fn save<T>(
		&self,
		session_id: &str,
		data: &T,
		ttl: Option<u64>,
	) -> Result<(), SessionError>
	where
		T: Serialize + Send + Sync,
	{
		// Check max sessions limit if configured
		if let Some(max) = self.config.max_sessions {
			let count = self.count_sessions().await?;
			if count >= max {
				return Err(SessionError::CacheError(format!(
					"Tenant {} has reached maximum session limit: {}",
					self.tenant_id, max
				)));
			}
		}

		let key = self.make_key(session_id);
		self.backend.save(&key, data, ttl).await
	}

	async fn delete(&self, session_id: &str) -> Result<(), SessionError> {
		let key = self.make_key(session_id);
		self.backend.delete(&key).await
	}

	async fn exists(&self, session_id: &str) -> Result<bool, SessionError> {
		let key = self.make_key(session_id);
		self.backend.exists(&key).await
	}
}

/// Extended tenant session operations
///
/// Provides additional operations for managing tenant-specific sessions.
#[async_trait]
pub trait TenantSessionOperations: SessionBackend {
	/// List all session IDs for a tenant
	///
	/// Note: This operation may be expensive for large session stores.
	async fn list_sessions(&self) -> Result<Vec<String>, SessionError>;

	/// Count sessions for a tenant
	async fn count_sessions(&self) -> Result<usize, SessionError>;

	/// Delete all sessions for a tenant
	///
	/// Returns the number of sessions deleted.
	async fn delete_all_sessions(&self) -> Result<usize, SessionError>;
}

#[async_trait]
impl<B> TenantSessionOperations for TenantSessionBackend<B>
where
	B: SessionBackend + CleanupableBackend + Clone,
{
	async fn list_sessions(&self) -> Result<Vec<String>, SessionError> {
		let prefix = self
			.config
			.key_prefix
			.replace("{tenant_id}", &self.tenant_id);
		let keys = self.backend.list_keys_with_prefix(&prefix).await?;

		// Remove prefix and return only session IDs
		Ok(keys
			.iter()
			.filter_map(|key| self.extract_session_id(key))
			.map(String::from)
			.collect())
	}

	async fn count_sessions(&self) -> Result<usize, SessionError> {
		let prefix = self
			.config
			.key_prefix
			.replace("{tenant_id}", &self.tenant_id);
		self.backend.count_keys_with_prefix(&prefix).await
	}

	async fn delete_all_sessions(&self) -> Result<usize, SessionError> {
		let prefix = self
			.config
			.key_prefix
			.replace("{tenant_id}", &self.tenant_id);
		self.backend.delete_keys_with_prefix(&prefix).await
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::sessions::InMemorySessionBackend;
	use rstest::rstest;

	#[rstest]
	#[tokio::test]
	async fn test_tenant_session_save_load() {
		let backend = InMemorySessionBackend::new();
		let tenant_backend =
			TenantSessionBackend::new(backend, "tenant_123".to_string(), TenantConfig::default());

		let data = serde_json::json!({"key": "value"});

		tenant_backend
			.save("session_abc", &data, None)
			.await
			.unwrap();

		let loaded: Option<serde_json::Value> = tenant_backend.load("session_abc").await.unwrap();
		assert_eq!(loaded.unwrap(), data);
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_session_isolation() {
		let backend = InMemorySessionBackend::new();

		let tenant1 = TenantSessionBackend::new(
			backend.clone(),
			"tenant_123".to_string(),
			TenantConfig::default(),
		);

		let tenant2 = TenantSessionBackend::new(
			backend.clone(),
			"tenant_456".to_string(),
			TenantConfig::default(),
		);

		let data1 = serde_json::json!({"tenant": "123"});
		let data2 = serde_json::json!({"tenant": "456"});

		// Save same session ID for different tenants
		tenant1.save("session_abc", &data1, None).await.unwrap();
		tenant2.save("session_abc", &data2, None).await.unwrap();

		// Each tenant should have its own data
		let loaded1: Option<serde_json::Value> = tenant1.load("session_abc").await.unwrap();
		let loaded2: Option<serde_json::Value> = tenant2.load("session_abc").await.unwrap();

		assert_eq!(loaded1.unwrap(), data1);
		assert_eq!(loaded2.unwrap(), data2);
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_session_delete() {
		let backend = InMemorySessionBackend::new();
		let tenant_backend =
			TenantSessionBackend::new(backend, "tenant_123".to_string(), TenantConfig::default());

		let data = serde_json::json!({"key": "value"});

		tenant_backend
			.save("session_abc", &data, None)
			.await
			.unwrap();
		assert!(tenant_backend.exists("session_abc").await.unwrap());

		tenant_backend.delete("session_abc").await.unwrap();
		assert!(!tenant_backend.exists("session_abc").await.unwrap());
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_make_key() {
		let backend = InMemorySessionBackend::new();
		let tenant_backend =
			TenantSessionBackend::new(backend, "tenant_123".to_string(), TenantConfig::default());

		let key = tenant_backend.make_key("session_abc");
		assert_eq!(key, "tenant:tenant_123:session:session_abc");
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_is_tenant_key() {
		let backend = InMemorySessionBackend::new();
		let tenant_backend =
			TenantSessionBackend::new(backend, "tenant_123".to_string(), TenantConfig::default());

		assert!(tenant_backend.is_tenant_key("tenant:tenant_123:session:abc"));
		assert!(!tenant_backend.is_tenant_key("tenant:tenant_456:session:abc"));
		assert!(!tenant_backend.is_tenant_key("other:prefix:abc"));
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_extract_session_id() {
		let backend = InMemorySessionBackend::new();
		let tenant_backend =
			TenantSessionBackend::new(backend, "tenant_123".to_string(), TenantConfig::default());

		let session_id = tenant_backend.extract_session_id("tenant:tenant_123:session:abc");
		assert_eq!(session_id, Some("abc"));

		let invalid = tenant_backend.extract_session_id("tenant:tenant_456:session:abc");
		assert_eq!(invalid, None);
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_config_with_prefix() {
		let config = TenantConfig::with_prefix("app:t:{tenant_id}:s:");

		let backend = InMemorySessionBackend::new();
		let tenant_backend = TenantSessionBackend::new(backend, "tenant_123".to_string(), config);

		let key = tenant_backend.make_key("session_abc");
		assert_eq!(key, "app:t:tenant_123:s:session_abc");
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_config_with_max_sessions() {
		let config = TenantConfig::default().with_max_sessions(1);

		let backend = InMemorySessionBackend::new();
		let tenant_backend = TenantSessionBackend::new(backend, "tenant_123".to_string(), config);

		let data = serde_json::json!({"key": "value"});

		// First session should succeed
		tenant_backend.save("session_1", &data, None).await.unwrap();

		// Second session should fail due to max_sessions=1 limit
		let result = tenant_backend.save("session_2", &data, None).await;
		assert!(result.is_err());

		// Verify error message
		if let Err(SessionError::CacheError(msg)) = result {
			assert!(msg.contains("maximum session limit"));
			assert!(msg.contains("tenant_123"));
		} else {
			panic!("Expected CacheError with maximum session limit message");
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_config_with_strict_isolation() {
		let config = TenantConfig::default().with_strict_isolation(true);

		let backend = InMemorySessionBackend::new();
		let tenant_backend = TenantSessionBackend::new(backend, "tenant_123".to_string(), config);

		assert!(tenant_backend.config.strict_isolation);
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_getters() {
		let backend = InMemorySessionBackend::new();
		let tenant_backend = TenantSessionBackend::new(
			backend.clone(),
			"tenant_123".to_string(),
			TenantConfig::default(),
		);

		assert_eq!(tenant_backend.tenant_id(), "tenant_123");
		assert_eq!(
			tenant_backend.config().key_prefix,
			"tenant:{tenant_id}:session:"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_count_sessions() {
		let backend = InMemorySessionBackend::new();
		let tenant_backend =
			TenantSessionBackend::new(backend, "tenant_123".to_string(), TenantConfig::default());

		// count_sessions returns 0 when no sessions exist
		let count = tenant_backend.count_sessions().await.unwrap();
		assert_eq!(count, 0);
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_list_sessions_returns_all() {
		// Arrange
		let backend = InMemorySessionBackend::new();
		let tenant_backend =
			TenantSessionBackend::new(backend, "tenant_a".to_string(), TenantConfig::default());
		let data = serde_json::json!({"key": "value"});

		tenant_backend.save("sess_1", &data, None).await.unwrap();
		tenant_backend.save("sess_2", &data, None).await.unwrap();
		tenant_backend.save("sess_3", &data, None).await.unwrap();

		// Act
		let sessions = tenant_backend.list_sessions().await.unwrap();

		// Assert
		assert_eq!(sessions.len(), 3);
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_delete_all_sessions() {
		// Arrange
		let backend = InMemorySessionBackend::new();
		let tenant_backend =
			TenantSessionBackend::new(backend, "tenant_a".to_string(), TenantConfig::default());
		let data = serde_json::json!({"key": "value"});

		tenant_backend.save("sess_1", &data, None).await.unwrap();
		tenant_backend.save("sess_2", &data, None).await.unwrap();
		tenant_backend.save("sess_3", &data, None).await.unwrap();

		// Act
		let deleted = tenant_backend.delete_all_sessions().await.unwrap();

		// Assert
		assert_eq!(deleted, 3);
		let remaining = tenant_backend.list_sessions().await.unwrap();
		assert_eq!(remaining.len(), 0);
	}

	#[rstest]
	#[tokio::test]
	async fn test_two_tenants_independent_counts() {
		// Arrange
		let backend = InMemorySessionBackend::new();
		let tenant_a = TenantSessionBackend::new(
			backend.clone(),
			"tenant_a".to_string(),
			TenantConfig::default(),
		);
		let tenant_b = TenantSessionBackend::new(
			backend.clone(),
			"tenant_b".to_string(),
			TenantConfig::default(),
		);
		let data = serde_json::json!({"key": "value"});

		tenant_a.save("sess_1", &data, None).await.unwrap();
		tenant_a.save("sess_2", &data, None).await.unwrap();

		tenant_b.save("sess_1", &data, None).await.unwrap();
		tenant_b.save("sess_2", &data, None).await.unwrap();
		tenant_b.save("sess_3", &data, None).await.unwrap();

		// Act
		let count_a = tenant_a.count_sessions().await.unwrap();
		let count_b = tenant_b.count_sessions().await.unwrap();

		// Assert
		assert_eq!(count_a, 2);
		assert_eq!(count_b, 3);
	}

	#[rstest]
	#[tokio::test]
	async fn test_tenant_max_sessions_after_delete() {
		// Arrange
		let config = TenantConfig::default().with_max_sessions(3);
		let backend = InMemorySessionBackend::new();
		let tenant_backend = TenantSessionBackend::new(backend, "tenant_a".to_string(), config);
		let data = serde_json::json!({"key": "value"});

		tenant_backend.save("sess_1", &data, None).await.unwrap();
		tenant_backend.save("sess_2", &data, None).await.unwrap();
		tenant_backend.save("sess_3", &data, None).await.unwrap();

		// Act
		tenant_backend.delete("sess_2").await.unwrap();
		let result = tenant_backend.save("sess_4", &data, None).await;

		// Assert
		assert!(result.is_ok());
		let count = tenant_backend.count_sessions().await.unwrap();
		assert_eq!(count, 3);
	}
}