reinhardt-auth 0.1.1

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
//! HTTP Basic Authentication
//!
//! Passwords are hashed with Argon2id on storage and verified using
//! constant-time comparison provided by the `argon2` crate.

// This module uses the deprecated User trait for backward compatibility.
// BasicAuthentication returns Box<dyn User> to preserve existing authentication APIs.
#![allow(deprecated)]
use crate::core::hasher::PasswordHasher;
use crate::rest_authentication::RestAuthentication;
use crate::{AuthenticationBackend, AuthenticationError, SimpleUser, User};
use base64::{Engine, engine::general_purpose::STANDARD};
use reinhardt_http::Request;
use std::collections::HashMap;
use uuid::Uuid;

/// Argon2-based password hasher used internally by `BasicAuthentication`.
///
/// This is intentionally a thin wrapper so the module stays self-contained
/// without requiring the `argon2-hasher` feature flag.
struct InternalArgon2Hasher;

impl PasswordHasher for InternalArgon2Hasher {
	fn hash(&self, password: &str) -> Result<String, reinhardt_core::exception::Error> {
		use argon2::Argon2;
		use password_hash::{PasswordHasher as _, SaltString, rand_core::OsRng};

		let salt = SaltString::generate(&mut OsRng);
		let argon2 = Argon2::default();

		argon2
			.hash_password(password.as_bytes(), &salt)
			.map(|hash| hash.to_string())
			.map_err(|e| reinhardt_core::exception::Error::Authentication(e.to_string()))
	}

	fn verify(&self, password: &str, hash: &str) -> Result<bool, reinhardt_core::exception::Error> {
		use argon2::Argon2;
		use password_hash::{PasswordHash, PasswordVerifier};

		let parsed_hash = PasswordHash::new(hash)
			.map_err(|e| reinhardt_core::exception::Error::Authentication(e.to_string()))?;

		// Argon2 verify_password uses constant-time comparison internally
		Ok(Argon2::default()
			.verify_password(password.as_bytes(), &parsed_hash)
			.is_ok())
	}
}

/// Basic Authentication backend
///
/// Passwords are hashed with Argon2id before storage.
/// Verification uses the constant-time comparison built into Argon2.
pub struct BasicAuthentication {
	/// username -> argon2 password hash
	users: HashMap<String, String>,
	hasher: InternalArgon2Hasher,
}

impl BasicAuthentication {
	/// Creates a new BasicAuthentication backend with no users.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_auth::{HttpBasicAuth, AuthenticationBackend};
	/// use bytes::Bytes;
	/// use hyper::{HeaderMap, Method, Uri, Version};
	/// use reinhardt_http::Request;
	///
	/// # async fn example() {
	/// let auth = HttpBasicAuth::new();
	///
	/// // Create a request without authentication header
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// // Since no users are registered, authentication should return None
	/// let result = auth.authenticate(&request).await.unwrap();
	/// assert!(result.is_none());
	/// # }
	/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
	/// ```
	pub fn new() -> Self {
		Self {
			users: HashMap::new(),
			hasher: InternalArgon2Hasher,
		}
	}

	/// Adds a user with the given username and password.
	///
	/// The password is hashed with Argon2id before storage.
	///
	/// # Panics
	///
	/// Panics if password hashing fails (should not happen in practice).
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_auth::{HttpBasicAuth, AuthenticationBackend};
	/// use bytes::Bytes;
	/// use hyper::{HeaderMap, Method, Uri, Version};
	/// use reinhardt_http::Request;
	///
	/// # async fn example() {
	/// let mut auth = HttpBasicAuth::new();
	/// auth.add_user("alice", "secret123");
	/// auth.add_user("bob", "password456");
	///
	/// // Create a request with valid Basic auth credentials
	/// // "alice:secret123" in base64 is "YWxpY2U6c2VjcmV0MTIz"
	/// let mut headers = HeaderMap::new();
	/// headers.insert("Authorization", "Basic YWxpY2U6c2VjcmV0MTIz".parse().unwrap());
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/")
	///     .headers(headers)
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// // Authentication should succeed
	/// let result = auth.authenticate(&request).await.unwrap();
	/// assert!(result.is_some());
	/// assert_eq!(result.unwrap().get_username(), "alice");
	/// # }
	/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
	/// ```
	pub fn add_user(&mut self, username: impl Into<String>, password: impl Into<String>) {
		let hash = self
			.hasher
			.hash(&password.into())
			.expect("Argon2 hashing should not fail");
		self.users.insert(username.into(), hash);
	}

	/// Parse Authorization header
	fn parse_auth_header(&self, header: &str) -> Option<(String, String)> {
		if !header.starts_with("Basic ") {
			return None;
		}

		let encoded = header.strip_prefix("Basic ")?;
		let decoded = STANDARD.decode(encoded).ok()?;
		let decoded_str = String::from_utf8(decoded).ok()?;

		let parts: Vec<&str> = decoded_str.splitn(2, ':').collect();
		if parts.len() != 2 {
			return None;
		}

		Some((parts[0].to_string(), parts[1].to_string()))
	}
}

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

#[async_trait::async_trait]
impl AuthenticationBackend for BasicAuthentication {
	async fn authenticate(
		&self,
		request: &Request,
	) -> Result<Option<Box<dyn User>>, AuthenticationError> {
		let auth_header = request
			.headers
			.get("Authorization")
			.and_then(|h| h.to_str().ok());

		if let Some(header) = auth_header
			&& let Some((username, password)) = self.parse_auth_header(header)
		{
			if let Some(stored_hash) = self.users.get(&username) {
				// Argon2 verify uses constant-time comparison internally
				let is_valid = self.hasher.verify(&password, stored_hash).unwrap_or(false);
				if is_valid {
					return Ok(Some(Box::new(SimpleUser {
						id: Uuid::new_v5(&crate::USER_ID_NAMESPACE, username.as_bytes()),
						username: username.clone(),
						email: String::new(),
						is_active: true,
						is_admin: false,
						is_staff: false,
						is_superuser: false,
					})));
				}
			}
			return Err(AuthenticationError::InvalidCredentials);
		}

		Ok(None)
	}

	async fn get_user(&self, user_id: &str) -> Result<Option<Box<dyn User>>, AuthenticationError> {
		if self.users.contains_key(user_id) {
			Ok(Some(Box::new(SimpleUser {
				id: Uuid::new_v5(&crate::USER_ID_NAMESPACE, user_id.as_bytes()),
				username: user_id.to_string(),
				email: String::new(),
				is_active: true,
				is_admin: false,
				is_staff: false,
				is_superuser: false,
			})))
		} else {
			Ok(None)
		}
	}
}

// Implement REST API Authentication trait by forwarding to AuthenticationBackend
#[async_trait::async_trait]
impl RestAuthentication for BasicAuthentication {
	async fn authenticate(
		&self,
		request: &Request,
	) -> Result<Option<Box<dyn User>>, AuthenticationError> {
		// Forward to AuthenticationBackend implementation
		AuthenticationBackend::authenticate(self, request).await
	}
}

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

	fn create_request_with_auth(auth: &str) -> Request {
		let mut headers = HeaderMap::new();
		headers.insert("Authorization", auth.parse().unwrap());
		Request::builder()
			.method(Method::GET)
			.uri("/")
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap()
	}

	#[rstest]
	#[tokio::test]
	async fn test_basic_auth_success() {
		// Arrange
		let mut backend = BasicAuthentication::new();
		backend.add_user("testuser", "testpass");

		// Base64 encode "testuser:testpass"
		let auth = "Basic dGVzdHVzZXI6dGVzdHBhc3M=";
		let request = create_request_with_auth(auth);

		// Act
		let result = AuthenticationBackend::authenticate(&backend, &request)
			.await
			.unwrap();

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

	#[rstest]
	#[tokio::test]
	async fn test_basic_auth_invalid_password() {
		// Arrange
		let mut backend = BasicAuthentication::new();
		backend.add_user("testuser", "correctpass");

		// Base64 encode "testuser:wrongpass"
		let auth = "Basic dGVzdHVzZXI6d3JvbmdwYXNz";
		let request = create_request_with_auth(auth);

		// Act
		let result = AuthenticationBackend::authenticate(&backend, &request).await;

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

	#[rstest]
	#[tokio::test]
	async fn test_basic_auth_no_header() {
		// Arrange
		let backend = BasicAuthentication::new();
		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let result = AuthenticationBackend::authenticate(&backend, &request)
			.await
			.unwrap();

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

	#[rstest]
	fn test_parse_auth_header() {
		// Arrange
		let backend = BasicAuthentication::new();

		// Act
		let (user, pass) = backend.parse_auth_header("Basic dGVzdDpwYXNz").unwrap();

		// Assert
		assert_eq!(user, "test");
		assert_eq!(pass, "pass");
	}

	#[rstest]
	#[tokio::test]
	async fn test_get_user() {
		// Arrange
		let mut backend = BasicAuthentication::new();
		backend.add_user("testuser", "testpass");

		// Act
		let user = backend.get_user("testuser").await.unwrap();
		let no_user = backend.get_user("nonexistent").await.unwrap();

		// Assert
		assert!(user.is_some());
		assert_eq!(user.unwrap().get_username(), "testuser");
		assert!(no_user.is_none());
	}

	#[rstest]
	fn test_password_is_hashed_on_storage() {
		// Arrange
		let mut backend = BasicAuthentication::new();

		// Act
		backend.add_user("testuser", "plaintext_password");

		// Assert
		let stored = backend.users.get("testuser").unwrap();
		// Argon2 hashes start with "$argon2"
		assert!(
			stored.starts_with("$argon2"),
			"Password should be stored as Argon2 hash, got: {}",
			stored
		);
		assert_ne!(stored, "plaintext_password");
	}

	#[rstest]
	#[tokio::test]
	async fn test_authenticate_same_username_produces_same_id() {
		// Arrange
		let mut backend = BasicAuthentication::new();
		backend.add_user("testuser", "testpass");

		let auth = "Basic dGVzdHVzZXI6dGVzdHBhc3M=";
		let request1 = create_request_with_auth(auth);
		let request2 = create_request_with_auth(auth);

		// Act
		let user1 = AuthenticationBackend::authenticate(&backend, &request1)
			.await
			.unwrap()
			.unwrap();
		let user2 = AuthenticationBackend::authenticate(&backend, &request2)
			.await
			.unwrap()
			.unwrap();

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

	#[rstest]
	#[tokio::test]
	async fn test_authenticated_user_id_is_deterministic_uuidv5() {
		// Arrange
		let mut backend = BasicAuthentication::new();
		backend.add_user("testuser", "testpass");

		let auth = "Basic dGVzdHVzZXI6dGVzdHBhc3M=";
		let request = create_request_with_auth(auth);

		// Act
		let user = AuthenticationBackend::authenticate(&backend, &request)
			.await
			.unwrap()
			.unwrap();
		let id = Uuid::parse_str(&user.id()).unwrap();

		// Assert
		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_authenticated_user_has_default_privilege_flags() {
		// Arrange
		let mut backend = BasicAuthentication::new();
		backend.add_user("testuser", "testpass");

		let auth = "Basic dGVzdHVzZXI6dGVzdHBhc3M=";
		let request = create_request_with_auth(auth);

		// Act
		let user = AuthenticationBackend::authenticate(&backend, &request)
			.await
			.unwrap()
			.unwrap();

		// Assert
		assert!(user.is_active());
		assert!(!user.is_admin());
		assert!(!user.is_staff());
		assert!(!user.is_superuser());
	}

	#[rstest]
	#[tokio::test]
	async fn test_get_user_same_username_produces_same_id() {
		// Arrange
		let mut backend = BasicAuthentication::new();
		backend.add_user("testuser", "testpass");

		// Act
		let user1 = backend.get_user("testuser").await.unwrap().unwrap();
		let user2 = backend.get_user("testuser").await.unwrap().unwrap();

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

	#[rstest]
	fn test_argon2_verification_works() {
		// Arrange
		let hasher = InternalArgon2Hasher;
		let password = "test_password_123";

		// Act
		let hash = hasher.hash(password).unwrap();
		let valid = hasher.verify(password, &hash).unwrap();
		let invalid = hasher.verify("wrong_password", &hash).unwrap();

		// Assert
		assert!(valid);
		assert!(!invalid);
	}
}