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
//! Multi-Factor Authentication (MFA)
//!
//! Provides TOTP (Time-based One-Time Password) support for MFA.

// This module uses the deprecated User trait for backward compatibility.
// MFAAuthentication returns Box<dyn User> to preserve existing authentication APIs.
#![allow(deprecated)]
use crate::{AuthenticationBackend, AuthenticationError, SimpleUser, User};
use reinhardt_http::Request;
use std::collections::HashMap;
use std::sync::Arc;
use subtle::ConstantTimeEq;
use tokio::sync::Mutex;
use uuid::Uuid;

use crate::USER_ID_NAMESPACE;

/// MFA authentication backend
///
/// Provides Time-based One-Time Password (TOTP) authentication.
///
/// # Examples
///
/// ```
/// use reinhardt_auth::MfaManager;
///
/// let mfa = MfaManager::new("MyApp");
/// ```
pub struct MFAAuthentication {
	/// TOTP issuer name
	issuer: String,
	/// User secrets (username -> secret)
	secrets: Arc<Mutex<HashMap<String, String>>>,
	/// Time window for TOTP validation (in seconds)
	time_window: u64,
}

impl MFAAuthentication {
	/// Create a new MFA authentication backend
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_auth::MfaManager;
	///
	/// let mfa = MfaManager::new("MyApp");
	/// ```
	pub fn new(issuer: impl Into<String>) -> Self {
		Self {
			issuer: issuer.into(),
			secrets: Arc::new(Mutex::new(HashMap::new())),
			time_window: 30,
		}
	}

	/// Set time window for TOTP validation
	pub fn time_window(mut self, seconds: u64) -> Self {
		self.time_window = seconds;
		self
	}

	/// Register a user with a secret
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_auth::MfaManager;
	///
	/// # async fn example() {
	/// let mfa = MfaManager::new("MyApp");
	/// mfa.register_user("alice", "SECRET_BASE32").await;
	/// # }
	/// ```
	pub async fn register_user(&self, username: impl Into<String>, secret: impl Into<String>) {
		let mut secrets = self.secrets.lock().await;
		secrets.insert(username.into(), secret.into());
	}

	/// Generate TOTP URL for QR code
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_auth::MfaManager;
	///
	/// let mfa = MfaManager::new("MyApp");
	/// let url = mfa.generate_totp_url("alice", "SECRET_BASE32");
	/// assert!(url.starts_with("otpauth://totp/"));
	/// ```
	pub fn generate_totp_url(&self, username: &str, secret: &str) -> String {
		format!(
			"otpauth://totp/{}:{}?secret={}&issuer={}",
			self.issuer, username, secret, self.issuer
		)
	}

	/// Verify TOTP code
	///
	/// Verifies a TOTP code using the RFC 6238 algorithm with SHA-256.
	/// Checks current time step and adjacent steps (±1) to tolerate
	/// minor clock skew between client and server.
	/// The secret must be a valid base32-encoded string.
	pub async fn verify_totp(
		&self,
		username: &str,
		code: &str,
	) -> Result<bool, AuthenticationError> {
		let secrets = self.secrets.lock().await;

		if let Some(secret) = secrets.get(username) {
			// Decode base32 secret
			let secret_bytes = match data_encoding::BASE32_NOPAD.decode(secret.as_bytes()) {
				Ok(bytes) => bytes,
				Err(_) => return Err(AuthenticationError::InvalidCredentials),
			};

			// Get current timestamp
			let current_time = std::time::SystemTime::now()
				.duration_since(std::time::UNIX_EPOCH)
				.unwrap_or_default()
				.as_secs();

			// Calculate time step
			let time_step = current_time / self.time_window;

			// Check current and adjacent time steps (±1) for clock skew tolerance
			for offset in [-1i64, 0, 1] {
				let adjusted_step = match (time_step as i64).checked_add(offset) {
					Some(s) if s >= 0 => s as u64,
					_ => continue,
				};

				let expected = totp_lite::totp_custom::<totp_lite::Sha256>(
					self.time_window,
					6,
					&secret_bytes,
					adjusted_step,
				);

				// Use constant-time comparison to prevent timing attacks
				if expected.as_bytes().ct_eq(code.as_bytes()).into() {
					return Ok(true);
				}
			}

			Ok(false)
		} else {
			Err(AuthenticationError::UserNotFound)
		}
	}

	/// Get the secret for a user (for testing purposes)
	///
	/// Returns the stored TOTP secret for the given user, or None if not registered.
	pub async fn get_secret(&self, username: &str) -> Option<String> {
		let secrets = self.secrets.lock().await;
		secrets.get(username).cloned()
	}
}

impl Default for MFAAuthentication {
	fn default() -> Self {
		Self::new("Reinhardt")
	}
}

#[async_trait::async_trait]
impl AuthenticationBackend for MFAAuthentication {
	async fn authenticate(
		&self,
		request: &Request,
	) -> Result<Option<Box<dyn User>>, AuthenticationError> {
		// Extract username and MFA code from request headers
		let username = request
			.headers
			.get("X-Username")
			.and_then(|v| v.to_str().ok());
		let code = request
			.headers
			.get("X-MFA-Code")
			.and_then(|v| v.to_str().ok());

		match (username, code) {
			(Some(user), Some(mfa_code)) => {
				if self.verify_totp(user, mfa_code).await? {
					Ok(Some(Box::new(SimpleUser {
						id: Uuid::new_v5(&USER_ID_NAMESPACE, user.as_bytes()),
						username: user.to_string(),
						email: String::new(),
						// Security defaults: privilege flags are set to restrictive values
						// since MFA authentication alone cannot determine user privileges.
						// Use UserRepository integration for accurate privilege data.
						is_active: true,
						is_admin: false,
						is_staff: false,
						is_superuser: false,
					})))
				} else {
					Err(AuthenticationError::InvalidCredentials)
				}
			}
			_ => Ok(None),
		}
	}

	async fn get_user(&self, user_id: &str) -> Result<Option<Box<dyn User>>, AuthenticationError> {
		// Check if user exists in our secrets store
		let secrets = self.secrets.lock().await;
		if secrets.contains_key(user_id) {
			Ok(Some(Box::new(SimpleUser {
				id: Uuid::new_v5(&USER_ID_NAMESPACE, user_id.as_bytes()),
				username: user_id.to_string(),
				email: String::new(),
				// Security defaults: privilege flags are set to restrictive values
				// since MFA authentication alone cannot determine user privileges.
				// Use UserRepository integration for accurate privilege data.
				is_active: true,
				is_admin: false,
				is_staff: false,
				is_superuser: false,
			})))
		} else {
			Ok(None)
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use bytes::Bytes;
	use hyper::{HeaderMap, Method};
	use rstest::rstest;

	#[rstest]
	#[tokio::test]
	async fn test_mfa_registration() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");

		// Act
		mfa.register_user("alice", "JBSWY3DPEHPK3PXP").await;

		// Assert
		let secrets = mfa.secrets.lock().await;
		assert!(secrets.contains_key("alice"));
	}

	#[rstest]
	fn test_generate_totp_url() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");

		// Act
		let url = mfa.generate_totp_url("alice", "SECRET");

		// Assert
		assert!(url.contains("otpauth://totp/"));
		assert!(url.contains("alice"));
		assert!(url.contains("SECRET"));
		assert!(url.contains("TestApp"));
	}

	#[rstest]
	#[tokio::test]
	async fn test_verify_totp_uses_sha256() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");
		let secret = "JBSWY3DPEHPK3PXP";
		mfa.register_user("alice", secret).await;

		let current_time = std::time::SystemTime::now()
			.duration_since(std::time::UNIX_EPOCH)
			.unwrap_or_default()
			.as_secs();
		let time_step = current_time / 30;
		let secret_bytes = data_encoding::BASE32_NOPAD
			.decode(secret.as_bytes())
			.unwrap();

		// Act - generate SHA-256 TOTP and verify it matches
		let totp_sha256 =
			totp_lite::totp_custom::<totp_lite::Sha256>(30, 6, &secret_bytes, time_step);
		let result = mfa.verify_totp("alice", &totp_sha256).await;

		// Assert - SHA-256 code should be accepted
		assert!(result.is_ok());
		assert!(result.unwrap());
	}

	#[rstest]
	#[tokio::test]
	async fn test_verify_totp_rejects_sha1_code() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");
		let secret = "JBSWY3DPEHPK3PXP";
		mfa.register_user("alice", secret).await;

		let current_time = std::time::SystemTime::now()
			.duration_since(std::time::UNIX_EPOCH)
			.unwrap_or_default()
			.as_secs();
		let time_step = current_time / 30;
		let secret_bytes = data_encoding::BASE32_NOPAD
			.decode(secret.as_bytes())
			.unwrap();

		// Act - generate SHA-1 TOTP (old algorithm)
		let totp_sha1 = totp_lite::totp_custom::<totp_lite::Sha1>(30, 6, &secret_bytes, time_step);

		// SHA-256 code for comparison
		let totp_sha256 =
			totp_lite::totp_custom::<totp_lite::Sha256>(30, 6, &secret_bytes, time_step);

		// Assert - SHA-1 and SHA-256 produce different codes (unless by coincidence)
		// If they happen to match, this test is still valid since both would be accepted
		if totp_sha1 != totp_sha256 {
			let result = mfa.verify_totp("alice", &totp_sha1).await;
			assert!(result.is_ok());
			assert!(!result.unwrap());
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_verify_totp_time_skew_tolerance() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");
		let secret = "JBSWY3DPEHPK3PXP";
		mfa.register_user("alice", secret).await;

		let current_time = std::time::SystemTime::now()
			.duration_since(std::time::UNIX_EPOCH)
			.unwrap_or_default()
			.as_secs();
		let time_step = current_time / 30;
		let secret_bytes = data_encoding::BASE32_NOPAD
			.decode(secret.as_bytes())
			.unwrap();

		// Act & Assert - previous time step should be accepted (clock skew tolerance)
		if time_step > 0 {
			let totp_prev =
				totp_lite::totp_custom::<totp_lite::Sha256>(30, 6, &secret_bytes, time_step - 1);
			let result = mfa.verify_totp("alice", &totp_prev).await;
			assert!(result.is_ok());
			assert!(
				result.unwrap(),
				"Previous time step TOTP should be accepted"
			);
		}

		// Act & Assert - next time step should be accepted
		let totp_next =
			totp_lite::totp_custom::<totp_lite::Sha256>(30, 6, &secret_bytes, time_step + 1);
		let result = mfa.verify_totp("alice", &totp_next).await;
		assert!(result.is_ok());
		assert!(result.unwrap(), "Next time step TOTP should be accepted");
	}

	#[rstest]
	#[tokio::test]
	async fn test_verify_totp_invalid_code() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");
		let secret = "JBSWY3DPEHPK3PXP";
		mfa.register_user("alice", secret).await;

		// Act
		let result = mfa.verify_totp("alice", "000000").await;

		// Assert
		assert!(result.is_ok());
		assert!(!result.unwrap());
	}

	#[rstest]
	#[tokio::test]
	async fn test_verify_totp_unregistered_user() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");

		// Act
		let result = mfa.verify_totp("alice", "123456").await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_mfa_authentication_with_valid_code() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");
		let secret = "JBSWY3DPEHPK3PXP";
		mfa.register_user("alice", secret).await;

		let current_time = std::time::SystemTime::now()
			.duration_since(std::time::UNIX_EPOCH)
			.unwrap_or_default()
			.as_secs();
		let time_step = current_time / 30;
		let secret_bytes = data_encoding::BASE32_NOPAD
			.decode(secret.as_bytes())
			.unwrap();
		let totp = totp_lite::totp_custom::<totp_lite::Sha256>(30, 6, &secret_bytes, time_step);

		let mut headers = HeaderMap::new();
		headers.insert("X-Username", "alice".parse().unwrap());
		headers.insert("X-MFA-Code", totp.parse().unwrap());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let result = mfa.authenticate(&request).await.unwrap();

		// Assert
		assert!(result.is_some());
		assert_eq!(result.unwrap().get_username(), "alice");
	}

	#[rstest]
	#[tokio::test]
	async fn test_mfa_authentication_without_headers() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");

		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let result = mfa.authenticate(&request).await.unwrap();

		// Assert
		assert!(result.is_none());
	}

	#[rstest]
	fn test_time_window_configuration() {
		// Arrange & Act
		let mfa = MFAAuthentication::new("TestApp").time_window(60);

		// Assert
		assert_eq!(mfa.time_window, 60);
	}

	#[rstest]
	#[tokio::test]
	async fn test_get_user_same_username_produces_same_id() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");
		mfa.register_user("alice", "JBSWY3DPEHPK3PXP").await;

		// Act
		let user1 = mfa.get_user("alice").await.unwrap().unwrap();
		let user2 = mfa.get_user("alice").await.unwrap().unwrap();

		// Assert
		assert_eq!(
			user1.id(),
			user2.id(),
			"same username must produce the same UUID"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_user_id_is_deterministic_uuidv5() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");
		mfa.register_user("alice", "JBSWY3DPEHPK3PXP").await;

		// Act
		let user = mfa.get_user("alice").await.unwrap().unwrap();
		let id = Uuid::parse_str(&user.id()).unwrap();

		// Assert - ID must be UUIDv5 (version 5, RFC 4122 variant)
		assert_eq!(id.get_version_num(), 5, "user ID must be UUIDv5");
		assert_eq!(
			id.get_variant(),
			uuid::Variant::RFC4122,
			"user ID must use RFC 4122 variant"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_get_user_unregistered_returns_none() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");

		// Act
		let result = mfa.get_user("nonexistent_user").await.unwrap();

		// Assert
		assert!(result.is_none());
	}

	#[rstest]
	#[tokio::test]
	async fn test_get_user_different_usernames_produce_different_ids() {
		// Arrange
		let mfa = MFAAuthentication::new("TestApp");
		mfa.register_user("alice", "JBSWY3DPEHPK3PXP").await;
		mfa.register_user("bob", "KRSXG5CTMVRXEZLUKN").await;

		// Act
		let user_a = mfa.get_user("alice").await.unwrap().unwrap();
		let user_b = mfa.get_user("bob").await.unwrap().unwrap();

		// Assert
		assert_ne!(
			user_a.id(),
			user_b.id(),
			"different usernames must produce different UUIDs"
		);
	}
}