forked from Txio-labs/txio-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_service.rs
More file actions
631 lines (541 loc) · 22.6 KB
/
Copy pathauth_service.rs
File metadata and controls
631 lines (541 loc) · 22.6 KB
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
use crate::dtos::admin_dtos::RpcLogRequest;
use crate::dtos::request::{LoginRequest, RegisterUserRequest};
use crate::dtos::response::{AuthResponse, SessionResponse, UserResponse};
use crate::model::rpc::RpcLog;
use crate::model::session::Session;
use crate::model::user::{NotificationPreferences, User};
use crate::repositories::rpc_repository::RpcRepository;
use crate::repositories::session_repository::SessionRepository;
use crate::repositories::user_repository::UserRepository;
use crate::services::email_service::EmailService;
use crate::services::otp_service::OTPService;
use crate::utils::auth_jwt::{Claims, JwtHelper};
use crate::utils::config::is_reserved_admin_email;
use crate::utils::error::AppError;
use chrono::Utc;
#[derive(Clone)]
pub struct AuthService {
repo: UserRepository,
rpc_repo: RpcRepository,
session_repo: SessionRepository,
jwt_helper: JwtHelper,
otp_service: OTPService,
email_service: EmailService,
/// Emails listed in ADMIN_EMAILS — reserved from self-service account creation.
reserved_admin_emails: Vec<String>,
}
impl AuthService {
fn to_user_response(user: &User) -> UserResponse {
let name = user.email.split('@').next().unwrap_or("user").to_string();
UserResponse {
id: user
.id
.as_ref()
.map(|id| id.to_string())
.unwrap_or_default(),
name,
email: user.email.clone(),
created_at: user.created_at.to_string(),
notification_preferences: user.notification_preferences.clone(),
github_account: user.github_account.clone(),
}
}
pub fn new(
repo: UserRepository,
rpc_repo: RpcRepository,
session_repo: SessionRepository,
jwt_helper: JwtHelper,
otp_service: OTPService,
email_service: EmailService,
reserved_admin_emails: Vec<String>,
) -> Self {
Self {
repo,
rpc_repo,
session_repo,
jwt_helper,
otp_service,
email_service,
reserved_admin_emails,
}
}
/// Case-normalizes an email address so two requests differing only in
/// casing (`User@Example.com` vs `user@example.com`) always resolve to
/// the same account. Matches the normalization already used for the
/// `ADMIN_EMAILS` roster in `utils::config`.
fn normalize_email(email: &str) -> String {
email.trim().to_ascii_lowercase()
}
fn reject_reserved_email(&self, email: &str) -> Result<(), AppError> {
if is_reserved_admin_email(email, &self.reserved_admin_emails) {
return Err(AppError::BadRequest(
"This email is reserved for administrator provisioning and cannot be registered or claimed via self-service. Use the bootstrap_admin tool instead."
.into(),
));
}
Ok(())
}
/// Verify a JWT and return its claims.
/// Used by handlers that need to read the `jti` from a just-issued token.
pub fn verify_token(&self, token: &str) -> Result<Claims, AppError> {
self.jwt_helper.verify_token(token)
}
// ── Session helpers ──────────────────────────────────────────────────────
/// Record a new login session. Called by handlers after a successful
/// login or registration, using device info extracted from the HTTP request.
pub async fn create_session(
&self,
user_id: &str,
jti: &str,
device_label: &str,
ip_address: &str,
) -> Result<Session, AppError> {
use mongodb::bson::oid::ObjectId;
use std::str::FromStr;
let oid = ObjectId::from_str(user_id)
.map_err(|_| AppError::InternalError("Invalid user ID".into()))?;
let session = Session::new(
oid,
jti.to_string(),
device_label.to_string(),
ip_address.to_string(),
);
self.session_repo.save(&session).await
}
/// Return all sessions belonging to the authenticated user.
/// The session whose `jti` matches `current_jti` is flagged `is_current`.
pub async fn list_sessions(
&self,
user_id: &str,
current_jti: Option<&str>,
) -> Result<Vec<SessionResponse>, AppError> {
use mongodb::bson::oid::ObjectId;
use std::str::FromStr;
let oid = ObjectId::from_str(user_id)
.map_err(|_| AppError::InternalError("Invalid user ID".into()))?;
let sessions = self.session_repo.find_by_user_id(&oid).await?;
let responses = sessions
.into_iter()
.map(|s| {
let is_current = current_jti.is_some_and(|jti| s.jti == jti);
SessionResponse {
id: s.id.map(|id| id.to_string()).unwrap_or_default(),
device_label: s.device_label,
ip_address: s.ip_address,
created_at: s.created_at.to_rfc3339(),
last_active_at: s.last_active_at.to_rfc3339(),
is_current,
}
})
.collect();
Ok(responses)
}
/// Revoke (delete) a session by its document ID.
/// Only sessions owned by `user_id` can be deleted.
pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), AppError> {
use mongodb::bson::oid::ObjectId;
use std::str::FromStr;
let user_oid = ObjectId::from_str(user_id)
.map_err(|_| AppError::InternalError("Invalid user ID".into()))?;
let session_oid = ObjectId::from_str(session_id)
.map_err(|_| AppError::BadRequest("Invalid session ID".into()))?;
self.session_repo
.delete_by_id_and_user(&session_oid, &user_oid)
.await
}
// ── OTP ──────────────────────────────────────────────────────────────────
pub async fn request_otp(&self, email: String) -> Result<(), AppError> {
let email = Self::normalize_email(&email);
let otp = self.otp_service.generate_otp(&email).await?;
self.email_service.send_otp_email(&email, &otp).await?;
Ok(())
}
pub async fn verify_otp(&self, email: String, code: String) -> Result<bool, AppError> {
let email = Self::normalize_email(&email);
self.otp_service.verify_otp(&email, &code).await
}
// ── Auth ─────────────────────────────────────────────────────────────────
pub async fn register_user(&self, req: RegisterUserRequest) -> Result<AuthResponse, AppError> {
let email = Self::normalize_email(&req.email);
self.reject_reserved_email(&email)?;
match self.repo.find_by_email(&email).await {
Ok(_) => return Err(AppError::BadRequest("Email already registered".into())),
Err(AppError::NotFound(_)) => (),
Err(e) => return Err(e),
};
let password_hash = bcrypt::hash(req.password.as_bytes(), bcrypt::DEFAULT_COST)
.map_err(|_| AppError::InternalError("Failed to hash password".into()))?;
let new_user = User::new(email, password_hash);
let saved_user = self.repo.save(&new_user).await?;
let user_id = saved_user.id.map(|id| id.to_string()).unwrap_or_default();
let (token, _jti) = self
.jwt_helper
.generate_token(&user_id, &saved_user.email)?;
Ok(AuthResponse {
token,
user: Self::to_user_response(&saved_user),
})
}
pub async fn login_user(&self, req: LoginRequest) -> Result<AuthResponse, AppError> {
const DUMMY_HASH: &str = "$2b$12$K4IzU6d5TqmqRKFLJZdqOeVLqZJ3mJHvJZdqOeVLqZJ3mJHvJZdq.";
const MAX_FAILED_ATTEMPTS: i32 = 5;
const LOCKOUT_MINUTES: i64 = 15;
let email = Self::normalize_email(&req.email);
let user_result = self.repo.find_by_email(&email).await;
if let Err(e) = &user_result {
if !matches!(e, AppError::NotFound(_)) {
return Err(user_result.unwrap_err());
}
}
let (hash_to_verify, user_found, is_locked) = match &user_result {
Ok(user) => {
let locked = user
.locked_until
.map(|locked_until| Utc::now() < locked_until)
.unwrap_or(false);
(user.password_hash.as_str(), true, locked)
}
Err(_) => (DUMMY_HASH, false, false),
};
// Always run password verification against real hash or constant-time dummy hash to avoid timing leaks.
let is_valid = bcrypt::verify(req.password.as_bytes(), hash_to_verify).unwrap_or(false);
// If account is currently locked out, reject login with uniform error without recording new attempts.
if is_locked {
return Err(AppError::Unauthorized("Invalid credentials".into()));
}
if !user_found || !is_valid {
// Only track attempts for real accounts — don't create a user-enumeration
// oracle by behaving differently, but also don't write to a nonexistent doc.
if user_found {
let _ = self
.repo
.record_failed_login_attempt(
&email,
MAX_FAILED_ATTEMPTS,
chrono::Duration::minutes(LOCKOUT_MINUTES),
)
.await;
}
return Err(AppError::Unauthorized("Invalid credentials".into()));
}
let user = user_result.unwrap();
// Reset counter on successful login.
if user.failed_login_attempts > 0 || user.locked_until.is_some() {
let _ = self.repo.reset_login_attempts(&user.email).await;
}
let user_id = user.id.map(|id| id.to_string()).unwrap_or_default();
let (token, _jti) = self.jwt_helper.generate_token(&user_id, &user.email)?;
Ok(AuthResponse {
token,
user: Self::to_user_response(&user),
})
}
pub async fn get_user_profile_by_email(&self, email: &str) -> Result<UserResponse, AppError> {
let user = self.repo.find_by_email(email).await?;
Ok(Self::to_user_response(&user))
}
pub async fn delete_user_by_email(&self, email: &str) -> Result<UserResponse, AppError> {
let user = self.repo.find_by_email(email).await?;
let user_id = user
.id
.map(|id| id.to_string())
.ok_or(AppError::InternalError("User ID missing".into()))?;
// Clean up all sessions before deleting the account. If either step
// fails the error is propagated — a partial deletion (account gone but
// sessions still live) is worse than leaving everything intact.
let oid = user_id
.parse::<mongodb::bson::oid::ObjectId>()
.map_err(|_| AppError::InternalError("Invalid user ID".into()))?;
self.session_repo.delete_all_by_user_id(&oid).await?;
let deleted_user = self.repo.delete_by_id(&user_id).await?;
Ok(Self::to_user_response(&deleted_user))
}
pub async fn update_user_email_by_email(
&self,
old_email: &str,
new_email: &str,
) -> Result<UserResponse, AppError> {
let old_email = Self::normalize_email(old_email);
let new_email = Self::normalize_email(new_email);
let mut user = self.repo.find_by_email(&old_email).await?;
if new_email != old_email {
self.reject_reserved_email(&new_email)?;
match self.repo.find_by_email(&new_email).await {
Ok(_) => return Err(AppError::BadRequest("Email already in use".into())),
Err(AppError::NotFound(_)) => (),
Err(e) => return Err(e),
};
}
user.email = new_email;
let updated_user = self.repo.update(&user).await?;
Ok(Self::to_user_response(&updated_user))
}
pub async fn update_notification_preferences_by_email(
&self,
email: &str,
preferences: NotificationPreferences,
) -> Result<UserResponse, AppError> {
let mut user = self.repo.find_by_email(email).await?;
user.notification_preferences = preferences;
let updated_user = self.repo.update(&user).await?;
Ok(Self::to_user_response(&updated_user))
}
pub async fn update_user_password_by_email(
&self,
email: &str,
current_password: &str,
new_password: &str,
) -> Result<UserResponse, AppError> {
let mut user = self.repo.find_by_email(email).await?;
verify_current_password(current_password, &user.password_hash)?;
let password_hash = bcrypt::hash(new_password.as_bytes(), bcrypt::DEFAULT_COST)
.map_err(|_| AppError::InternalError("Failed to hash password".into()))?;
user.password_hash = password_hash;
let updated_user = self.repo.update(&user).await?;
Ok(Self::to_user_response(&updated_user))
}
pub async fn reset_password_with_otp(
&self,
email: &str,
otp: &str,
new_password: &str,
) -> Result<(), AppError> {
let email = Self::normalize_email(email);
let is_valid = self.otp_service.verify_otp(&email, otp).await?;
if !is_valid {
return Err(AppError::BadRequest("Invalid or expired OTP".into()));
}
let mut user = self.repo.find_by_email(&email).await?;
let password_hash = bcrypt::hash(new_password.as_bytes(), bcrypt::DEFAULT_COST)
.map_err(|_| AppError::InternalError("Failed to hash password".into()))?;
user.password_hash = password_hash;
user.failed_login_attempts = 0;
user.locked_until = None;
self.repo.update(&user).await?;
Ok(())
}
pub async fn log_rpc_call(
&self,
user_id: mongodb::bson::oid::ObjectId,
req: RpcLogRequest,
) -> Result<(), AppError> {
let log = RpcLog::new(user_id, req.method, req.params, req.success, req.error);
self.rpc_repo.save(&log).await
}
pub async fn get_rpc_history(&self, email: &str) -> Result<Vec<RpcLog>, AppError> {
let user = self.repo.find_by_email(email).await?;
if let Some(user_id) = user.id {
let logs = self.rpc_repo.find_by_user_id(user_id, 100).await?;
Ok(logs)
} else {
Ok(vec![])
}
}
pub async fn update_user_network(
&self,
user_id: mongodb::bson::oid::ObjectId,
network: crate::model::network::Network,
) -> Result<UserResponse, AppError> {
let mut user = self.repo.find_by_id(&user_id).await?;
user.network = network;
let updated_user = self.repo.update(&user).await?;
Ok(Self::to_user_response(&updated_user))
}
pub async fn update_user_github_account(
&self,
email: &str,
github_account: Option<crate::model::user::GitHubAccount>,
) -> Result<User, AppError> {
let mut user = self.repo.find_by_email(email).await?;
user.github_account = github_account;
self.repo.update(&user).await
}
pub async fn oauth_login_or_register(
&self,
google_sub: String,
email: String,
) -> Result<AuthResponse, AppError> {
// Normalize casing here too: the provider's casing for the same
// mailbox can vary between the account that originally registered
// with a password and the one returned by a later OAuth login, and
// an exact-match lookup below would otherwise miss the existing
// account (the same class of bug as issue #359, just via OAuth).
let email = Self::normalize_email(&email);
// Treat NotFound as absence but propagate every other error.
// .ok() would silently turn a database outage into "user not found",
// causing an existing account to be re-registered under a new record.
let user_by_sub = match self.repo.find_by_google_sub(&google_sub).await {
Ok(u) => Some(u),
Err(AppError::NotFound(_)) => None,
Err(e) => return Err(e),
};
let user_by_email = match self.repo.find_by_email(&email).await {
Ok(u) => Some(u),
Err(AppError::NotFound(_)) => None,
Err(e) => return Err(e),
};
let user = resolve_oauth_account(google_sub, email, user_by_sub, user_by_email)?;
let user = match user {
OAuthAccountResolution::Login(existing) => existing,
OAuthAccountResolution::Register { email, google_sub } => {
self.reject_reserved_email(&email)?;
let random_password = uuid::Uuid::new_v4().to_string();
let password_hash = bcrypt::hash(random_password.as_bytes(), bcrypt::DEFAULT_COST)
.map_err(|_| AppError::InternalError("Failed to hash password".into()))?;
let new_user = User::new_oauth(email, password_hash, google_sub);
self.repo.save(&new_user).await?
}
};
let user_id = user.id.map(|id| id.to_string()).unwrap_or_default();
let (token, _jti) = self.jwt_helper.generate_token(&user_id, &user.email)?;
Ok(AuthResponse {
token,
user: Self::to_user_response(&user),
})
}
}
fn verify_current_password(current_password: &str, password_hash: &str) -> Result<(), AppError> {
let is_valid = bcrypt::verify(current_password.as_bytes(), password_hash).unwrap_or(false);
if !is_valid {
return Err(AppError::Unauthorized(
"Current password is incorrect".into(),
));
}
Ok(())
}
enum OAuthAccountResolution {
Login(User),
Register { email: String, google_sub: String },
}
fn resolve_oauth_account(
google_sub: String,
email: String,
user_by_sub: Option<User>,
user_by_email: Option<User>,
) -> Result<OAuthAccountResolution, AppError> {
if let Some(user) = user_by_sub {
return Ok(OAuthAccountResolution::Login(user));
}
if let Some(user) = user_by_email {
match user.google_sub.as_deref() {
Some(existing) if existing == google_sub => Ok(OAuthAccountResolution::Login(user)),
Some(_) => Err(AppError::Unauthorized(
"This Google account is not linked to the existing user".into(),
)),
None => Err(AppError::Forbidden(
"An account with this email already exists. Sign in with your password to link Google.".into(),
)),
}
} else {
Ok(OAuthAccountResolution::Register { email, google_sub })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_email_lowercases_and_trims() {
assert_eq!(
AuthService::normalize_email("User@Example.com"),
"user@example.com"
);
assert_eq!(
AuthService::normalize_email(" Mixed.Case@Domain.IO "),
"mixed.case@domain.io"
);
}
#[test]
fn normalize_email_is_idempotent() {
let once = AuthService::normalize_email("User@Example.com");
let twice = AuthService::normalize_email(&once);
assert_eq!(once, twice);
}
#[test]
fn verify_current_password_rejects_mismatched_password() {
let password_hash = bcrypt::hash(b"correct-password", bcrypt::DEFAULT_COST).unwrap();
let result = verify_current_password("wrong-password", &password_hash);
assert!(matches!(result, Err(AppError::Unauthorized(_))));
}
#[test]
fn verify_current_password_accepts_matching_password() {
let password_hash = bcrypt::hash(b"correct-password", bcrypt::DEFAULT_COST).unwrap();
let result = verify_current_password("correct-password", &password_hash);
assert!(result.is_ok());
}
}
#[cfg(test)]
mod oauth_tests {
use super::*;
use chrono::Utc;
use mongodb::bson::oid::ObjectId;
fn sample_user(email: &str, google_sub: Option<&str>) -> User {
User {
id: Some(ObjectId::new()),
email: email.to_string(),
password_hash: "hash".to_string(),
google_sub: google_sub.map(str::to_string),
tier: crate::model::user::PlanTier::Free,
network: crate::model::network::Network::Mainnet,
created_at: Utc::now(),
github_account: None,
notification_preferences: crate::model::user::NotificationPreferences::default(),
failed_login_attempts: 0,
locked_until: None,
is_admin: false,
}
}
#[test]
fn logs_in_when_google_sub_matches() {
let user = sample_user("user@example.com", Some("google-sub-123"));
let result = resolve_oauth_account(
"google-sub-123".to_string(),
"user@example.com".to_string(),
Some(user.clone()),
None,
)
.unwrap();
match result {
OAuthAccountResolution::Login(found) => assert_eq!(found.email, user.email),
OAuthAccountResolution::Register { .. } => panic!("expected login"),
}
}
#[test]
fn rejects_unlinked_password_account_with_matching_email() {
let user = sample_user("victim@example.com", None);
let result = resolve_oauth_account(
"attacker-sub".to_string(),
"victim@example.com".to_string(),
None,
Some(user),
);
assert!(matches!(result, Err(AppError::Forbidden(_))));
}
#[test]
fn registers_new_oauth_user_when_email_is_unknown() {
let result = resolve_oauth_account(
"new-sub".to_string(),
"new@example.com".to_string(),
None,
None,
)
.unwrap();
match result {
OAuthAccountResolution::Register { email, google_sub } => {
assert_eq!(email, "new@example.com");
assert_eq!(google_sub, "new-sub");
}
OAuthAccountResolution::Login(_) => panic!("expected register"),
}
}
#[test]
fn rejects_conflicting_google_sub_for_existing_email() {
let user = sample_user("user@example.com", Some("linked-sub"));
let result = resolve_oauth_account(
"different-sub".to_string(),
"user@example.com".to_string(),
None,
Some(user),
);
assert!(matches!(result, Err(AppError::Unauthorized(_))));
}
}