Skip to main content

auth_framework/api/
auth.rs

1//! Authentication API Endpoints
2//!
3//! Handles login, logout, token refresh, and related authentication operations
4
5use crate::api::{ApiResponse, ApiState, extract_bearer_token};
6use axum::{Json, extract::State, http::HeaderMap};
7use serde::{Deserialize, Serialize};
8
9/// Login request payload.
10///
11/// When `challenge_id` and `mfa_code` are both present the login completes an
12/// in-progress MFA challenge instead of performing a fresh password check.
13/// The two fields must appear together — providing one without the other is
14/// rejected with a validation error.
15#[derive(Deserialize)]
16pub struct LoginRequest {
17    pub username: String,
18    pub password: String,
19    /// Identifier of a pending MFA challenge (returned by a prior login attempt).
20    #[serde(default)]
21    pub challenge_id: Option<String>,
22    /// The TOTP or backup code that answers the MFA challenge.
23    #[serde(default)]
24    pub mfa_code: Option<String>,
25    /// When `true`, the session lifetime is extended (e.g. "remember me" cookie).
26    #[serde(default)]
27    pub remember_me: bool,
28}
29
30impl std::fmt::Debug for LoginRequest {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        let mut d = f.debug_struct("LoginRequest");
33        d.field("username", &self.username);
34        d.field("password", &crate::utils::redact::redacted(&self.password));
35        d.field("challenge_id", &self.challenge_id);
36        d.field("mfa_code", &self.mfa_code);
37        d.field("remember_me", &self.remember_me);
38        d.finish()
39    }
40}
41
42/// Successful login response.
43///
44/// Contains access and refresh tokens plus user metadata and adaptive risk
45/// information.  Clients should inspect `login_risk_level` and
46/// `security_warnings` to decide whether to prompt for additional verification.
47#[derive(Serialize)]
48pub struct LoginResponse {
49    pub access_token: String,
50    pub refresh_token: String,
51    pub token_type: String,
52    pub expires_in: u64,
53    pub user: LoginUserInfo,
54    /// Risk level of this login attempt: "low", "medium", "high", or "critical".
55    /// Clients can use this to prompt the user to enable MFA or perform additional verification.
56    pub login_risk_level: String,
57    /// Non-blocking security advisories for the authenticated session.
58    /// Empty in the common case; populated when adaptive risk policy detects elevated risk.
59    pub security_warnings: Vec<String>,
60}
61
62impl std::fmt::Debug for LoginResponse {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        let mut d = f.debug_struct("LoginResponse");
65        d.field(
66            "access_token",
67            &crate::utils::redact::redacted(&self.access_token),
68        );
69        d.field(
70            "refresh_token",
71            &crate::utils::redact::redacted(&self.refresh_token),
72        );
73        d.field("token_type", &self.token_type);
74        d.field("expires_in", &self.expires_in);
75        d.field("user", &self.user);
76        d.field("login_risk_level", &self.login_risk_level);
77        d.field("security_warnings", &self.security_warnings);
78        d.finish()
79    }
80}
81
82/// User information embedded in login and validation responses.
83#[derive(Debug, Serialize)]
84pub struct LoginUserInfo {
85    pub id: String,
86    pub username: String,
87    pub roles: Vec<String>,
88    pub permissions: Vec<String>,
89}
90
91async fn build_login_response(
92    state: &ApiState,
93    user_id: &str,
94    username: String,
95    permissions: Vec<String>,
96) -> ApiResponse<LoginResponse> {
97    let user_key = format!("user:{}", user_id);
98    let roles: Vec<String> = match state.auth_framework.storage().get_kv(&user_key).await {
99        Ok(Some(bytes)) => {
100            let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or_default();
101            json["roles"]
102                .as_array()
103                .map(|arr| {
104                    arr.iter()
105                        .filter_map(|value| value.as_str())
106                        .map(|value| value.to_string())
107                        .collect()
108                })
109                .unwrap_or_default()
110        }
111        _ => vec![],
112    };
113
114    let user_info = LoginUserInfo {
115        id: user_id.to_string(),
116        username,
117        roles: roles.clone(),
118        permissions,
119    };
120
121    let token_lifetime = state.auth_framework.config().token_lifetime;
122    let access_token = match state.auth_framework.token_manager().create_jwt_token(
123        user_id,
124        roles,
125        Some(token_lifetime),
126    ) {
127        Ok(jwt) => jwt,
128        Err(e) => {
129            tracing::error!("Failed to create JWT token: {}", e);
130            return ApiResponse::error_typed(
131                "TOKEN_CREATION_FAILED",
132                "Failed to create access token",
133            );
134        }
135    };
136
137    let refresh_token_lifetime = state.auth_framework.config().refresh_token_lifetime;
138    let refresh_token = match state
139        .auth_framework
140        .token_manager()
141        .create_refresh_jwt_token(user_id, Some(refresh_token_lifetime))
142    {
143        Ok(jwt) => jwt,
144        Err(e) => {
145            tracing::error!("Failed to create refresh token: {}", e);
146            return ApiResponse::error_typed(
147                "TOKEN_CREATION_FAILED",
148                "Failed to create refresh token",
149            );
150        }
151    };
152
153    ApiResponse::success(LoginResponse {
154        access_token,
155        refresh_token,
156        token_type: "Bearer".to_string(),
157        expires_in: token_lifetime.as_secs(),
158        user: user_info,
159        login_risk_level: "low".to_string(), // Caller may override after build
160        security_warnings: Vec::new(),       // Caller may override after build
161    })
162}
163
164/// Token refresh request.
165#[derive(Deserialize)]
166pub struct RefreshRequest {
167    /// The refresh token issued during a previous login.
168    pub refresh_token: String,
169}
170
171impl std::fmt::Debug for RefreshRequest {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        let mut d = f.debug_struct("RefreshRequest");
174        d.field(
175            "refresh_token",
176            &crate::utils::redact::redacted(&self.refresh_token),
177        );
178        d.finish()
179    }
180}
181
182/// Token refresh response.
183#[derive(Serialize)]
184pub struct RefreshResponse {
185    /// The newly issued access token.
186    pub access_token: String,
187    /// Always `"Bearer"`.
188    pub token_type: String,
189    /// Seconds until the new access token expires.
190    pub expires_in: u64,
191    /// The next refresh token. The one just redeemed no longer works.
192    pub refresh_token: String,
193}
194
195impl std::fmt::Debug for RefreshResponse {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        let mut d = f.debug_struct("RefreshResponse");
198        d.field(
199            "access_token",
200            &crate::utils::redact::redacted(&self.access_token),
201        );
202        d.field("token_type", &self.token_type);
203        d.field("expires_in", &self.expires_in);
204        d.field(
205            "refresh_token",
206            &crate::utils::redact::redacted(&self.refresh_token),
207        );
208        d.finish()
209    }
210}
211
212/// Logout request.
213#[derive(Deserialize)]
214pub struct LogoutRequest {
215    /// Optional refresh token to revoke alongside the access token.
216    #[serde(default)]
217    pub refresh_token: Option<String>,
218}
219
220impl std::fmt::Debug for LogoutRequest {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        let mut d = f.debug_struct("LogoutRequest");
223        d.field(
224            "refresh_token",
225            &crate::utils::redact::redacted(&self.refresh_token),
226        );
227        d.finish()
228    }
229}
230
231/// Compute a login risk level string from request headers.
232///
233/// This is a lightweight, header-only heuristic used to populate the
234/// `login_risk_level` field in the login response and to trigger security
235/// warnings when MFA is not enrolled.  It does **not** replace a full
236/// risk-engine evaluation — for that, see `AuthorizationContextBuilder`.
237pub(crate) fn login_risk_level(headers: &HeaderMap) -> (&'static str, Vec<String>) {
238    let user_agent = headers
239        .get("user-agent")
240        .and_then(|v| v.to_str().ok())
241        .unwrap_or("");
242
243    let forwarded_for = headers
244        .get("x-forwarded-for")
245        .and_then(|v| v.to_str().ok())
246        .unwrap_or("");
247
248    let mut risk_points: u8 = 0;
249    let mut warnings: Vec<String> = Vec::new();
250
251    if user_agent.is_empty() {
252        risk_points = risk_points.saturating_add(30);
253        warnings.push(
254            "No browser User-Agent detected; this request may originate from an automated script."
255                .to_string(),
256        );
257    }
258
259    // Detect Tor exit nodes by well-known header patterns.  This is a best-effort
260    // check and can be defeated; a proper geo-IP database lookup is more reliable.
261    if user_agent.to_lowercase().contains("tor browser") {
262        risk_points = risk_points.saturating_add(40);
263        warnings.push("Login originated from the Tor Browser.".to_string());
264    }
265
266    // Multiple IPs in X-Forwarded-For typically indicate a proxy or VPN hop.
267    let hop_count = forwarded_for.split(',').count();
268    if hop_count >= 2 {
269        risk_points = risk_points.saturating_add(15);
270        warnings.push(format!(
271            "Request passed through {} proxy hops (X-Forwarded-For).",
272            hop_count
273        ));
274    }
275
276    let level = match risk_points {
277        0..=9 => "low",
278        10..=29 => "medium",
279        30..=59 => "high",
280        _ => "critical",
281    };
282    (level, warnings)
283}
284
285/// MFA code attempts allowed per account within the window (across all its challenges).
286const MAX_FAILED_ATTEMPTS: u64 = 5;
287/// How long MFA attempts are remembered.
288const MFA_LOCKOUT_WINDOW_SECS: u64 = 900;
289
290fn mfa_attempt_key(user_id: &str, slot: u64) -> String {
291    format!("mfa_attempt:{user_id}:{slot}")
292}
293
294/// Reserve one of the account's MFA attempts BEFORE a code is checked. Each of the
295/// `MAX_FAILED_ATTEMPTS` slots is claimed with an atomic set-if-absent, so any burst of
296/// parallel guesses gets at most that many checks in total, whatever challenge it uses.
297/// `false` means the account's budget is spent.
298async fn reserve_mfa_attempt(state: &ApiState, user_id: &str) -> bool {
299    let storage = state.auth_framework.storage();
300    for slot in 0..MAX_FAILED_ATTEMPTS {
301        match storage
302            .store_kv_if_absent(
303                &mfa_attempt_key(user_id, slot),
304                b"1",
305                Some(std::time::Duration::from_secs(MFA_LOCKOUT_WINDOW_SECS)),
306            )
307            .await
308        {
309            Ok(true) => return true,
310            Ok(false) => continue,
311            // An unreadable store gives no attempts (fail closed).
312            Err(_) => return false,
313        }
314    }
315    false
316}
317
318/// Is the account's MFA attempt budget spent?
319async fn mfa_attempts_exhausted(state: &ApiState, user_id: &str) -> bool {
320    for slot in 0..MAX_FAILED_ATTEMPTS {
321        match state
322            .auth_framework
323            .storage()
324            .get_kv(&mfa_attempt_key(user_id, slot))
325            .await
326        {
327            Ok(Some(_)) => continue,
328            // a free slot: not exhausted; an unreadable store counts as exhausted (fail closed)
329            Ok(None) => return false,
330            Err(_) => return true,
331        }
332    }
333    true
334}
335
336/// A successful MFA login gives the account its attempts back.
337async fn clear_mfa_attempts(state: &ApiState, user_id: &str) {
338    for slot in 0..MAX_FAILED_ATTEMPTS {
339        let _ = state
340            .auth_framework
341            .storage()
342            .delete_kv(&mfa_attempt_key(user_id, slot))
343            .await;
344    }
345}
346
347/// Increment the per-username failed login counter with a sliding TTL window.
348async fn increment_login_failure(state: &ApiState, lockout_key: &str, window_secs: u64) {
349    let current: u64 = match state.auth_framework.storage().get_kv(lockout_key).await {
350        Ok(Some(bytes)) => std::str::from_utf8(&bytes)
351            .ok()
352            .and_then(|s| s.parse().ok())
353            .unwrap_or(0),
354        _ => 0,
355    };
356    let new_count = current.saturating_add(1);
357    let _ = state
358        .auth_framework
359        .storage()
360        .store_kv(
361            lockout_key,
362            new_count.to_string().as_bytes(),
363            Some(std::time::Duration::from_secs(window_secs)),
364        )
365        .await;
366}
367
368/// `POST /auth/login` — authenticate a user with username/password.
369///
370/// On success returns access + refresh tokens, user metadata, and adaptive
371/// risk information.  Returns `ACCOUNT_LOCKED` after 5 consecutive failures
372/// within 15 minutes.
373pub async fn login(
374    State(state): State<ApiState>,
375    headers: HeaderMap,
376    Json(req): Json<LoginRequest>,
377) -> ApiResponse<LoginResponse> {
378    // Validate required fields
379    if req.username.is_empty() || req.password.is_empty() {
380        return ApiResponse::validation_error_typed("Username and password are required");
381    }
382
383    if req.challenge_id.is_some() ^ req.mfa_code.is_some() {
384        return ApiResponse::validation_error_typed(
385            "challenge_id and mfa_code must be provided together",
386        );
387    }
388
389    if let (Some(challenge_id), Some(mfa_code)) =
390        (req.challenge_id.clone(), req.mfa_code.as_deref())
391    {
392        // Wrong codes are counted against the account the challenge belongs to, whatever
393        // username the caller sends, and locked accounts get no further guesses.
394        let Some(owner_id) = state
395            .auth_framework
396            .mfa_challenge_owner(&challenge_id)
397            .await
398        else {
399            return ApiResponse::error_typed(
400                "MFA_INVALID_CODE",
401                "Invalid or expired MFA challenge or code",
402            );
403        };
404        if !reserve_mfa_attempt(&state, &owner_id).await {
405            return ApiResponse::error_typed(
406                "ACCOUNT_LOCKED",
407                "Too many failed login attempts. Please try again later.",
408            );
409        }
410        return match state
411            .auth_framework
412            .complete_mfa_by_id(&challenge_id, mfa_code)
413            .await
414        {
415            Ok(token) => {
416                clear_mfa_attempts(&state, &owner_id).await;
417                let mut response = build_login_response(
418                    &state,
419                    &token.user_id,
420                    req.username,
421                    token.permissions.to_vec(),
422                )
423                .await;
424                // MFA completion means the step-up was satisfied — mark as low risk.
425                if let Some(data) = response.data.as_mut() {
426                    data.login_risk_level = "low".to_string();
427                }
428                response
429            }
430            Err(e) => {
431                tracing::debug!("MFA completion failed during login: {}", e);
432                ApiResponse::error_typed(
433                    "MFA_INVALID_CODE",
434                    "Invalid or expired MFA challenge or code",
435                )
436            }
437        };
438    }
439
440    // Compute adaptive risk from request headers before touching the auth core
441    // so the risk assessment can influence the response even on success.
442    let (risk_level, mut risk_warnings) = login_risk_level(&headers);
443
444    // SEC-M1/L1: Per-username failed login rate limiting / account lockout.
445    // Key: "login_failures:{username}" — stores the current failure count as a
446    // decimal string with a 15-minute TTL (auto-resets after 15 min of no attempts).
447    let lockout_key = format!("login_failures:{}", req.username);
448    const LOCKOUT_WINDOW_SECS: u64 = 900; // 15 minutes
449    if let Ok(Some(count_bytes)) = state.auth_framework.storage().get_kv(&lockout_key).await
450        && let Ok(count_str) = std::str::from_utf8(&count_bytes)
451        && let Ok(count) = count_str.parse::<u64>()
452        && count >= MAX_FAILED_ATTEMPTS
453    {
454        tracing::warn!(
455            username = %req.username,
456            failed_attempts = count,
457            "Login rejected — account temporarily locked due to repeated failures"
458        );
459        return ApiResponse::error_typed(
460            "ACCOUNT_LOCKED",
461            "Too many failed login attempts. Please try again later.",
462        );
463    }
464
465    // Create credential for authentication
466    let credential = crate::authentication::credentials::Credential::Password {
467        username: req.username.clone(),
468        password: req.password.clone(),
469    };
470
471    // Attempt authentication
472    match state
473        .auth_framework
474        .authenticate("password", credential)
475        .await
476    {
477        Ok(auth_result) => match auth_result {
478            crate::auth::AuthResult::Success(token) => {
479                // Check if the user has MFA enrolled.  If not and the risk level is
480                // elevated, add a security advisory recommending MFA enrollment.
481                let mfa_enrolled =
482                    crate::api::mfa::check_user_mfa_status(&state.auth_framework, &token.user_id)
483                        .await;
484
485                if !mfa_enrolled && matches!(risk_level, "high" | "critical") {
486                    risk_warnings.push(
487                        "Your account does not have multi-factor authentication enabled. \
488                         Enable MFA to protect this account from high-risk login contexts."
489                            .to_string(),
490                    );
491                    tracing::warn!(
492                        user_id = %token.user_id,
493                        risk_level = %risk_level,
494                        "High-risk login without MFA enrolled"
495                    );
496                } else {
497                    tracing::info!(
498                        user_id = %token.user_id,
499                        risk_level = %risk_level,
500                        mfa_enrolled = %mfa_enrolled,
501                        "Successful login"
502                    );
503                }
504
505                let mut response = build_login_response(
506                    &state,
507                    &token.user_id,
508                    req.username,
509                    token.permissions.to_vec(),
510                )
511                .await;
512
513                // Reset failed login counter on successful authentication
514                let _ = state.auth_framework.storage().delete_kv(&lockout_key).await;
515
516                if let Some(data) = response.data.as_mut() {
517                    data.login_risk_level = risk_level.to_string();
518                    data.security_warnings = risk_warnings;
519                }
520                response
521            }
522            crate::auth::AuthResult::MfaRequired(challenge) => {
523                // An account whose MFA codes were guessed wrongly too often gets no new
524                // challenge until the lockout window passes.
525                if mfa_attempts_exhausted(&state, &challenge.user_id).await {
526                    state
527                        .auth_framework
528                        .discard_mfa_challenge(&challenge.id)
529                        .await;
530                    return ApiResponse::error_typed(
531                        "ACCOUNT_LOCKED",
532                        "Too many failed login attempts. Please try again later.",
533                    );
534                }
535                // Return the challenge data so the client knows how to fulfill MFA.
536                // The client should prompt for the appropriate second factor and then
537                // re-submit the login request with both challenge_id and mfa_code.
538                let mfa_type_str = match &challenge.mfa_type {
539                    crate::methods::MfaType::Totp => "totp",
540                    crate::methods::MfaType::Sms { .. } => "sms",
541                    crate::methods::MfaType::Email { .. } => "email",
542                    crate::methods::MfaType::Push { .. } => "push",
543                    crate::methods::MfaType::SecurityKey => "security_key",
544                    crate::methods::MfaType::BackupCode => "backup_code",
545                    crate::methods::MfaType::MultiMethod => "totp_or_backup_code",
546                };
547                ApiResponse::<()>::error_with_details(
548                    "MFA_REQUIRED",
549                    "Multi-factor authentication required",
550                    serde_json::json!({
551                        "challenge_id": challenge.id,
552                        "mfa_type": mfa_type_str,
553                        "expires_at": challenge.expires_at.to_rfc3339(),
554                        "message": challenge.message,
555                    }),
556                )
557                .cast()
558            }
559            crate::auth::AuthResult::Failure(reason) => {
560                // Increment failed login counter
561                increment_login_failure(&state, &lockout_key, LOCKOUT_WINDOW_SECS).await;
562                ApiResponse::error_typed("AUTHENTICATION_FAILED", reason)
563            }
564        },
565        Err(e) => {
566            // Increment failed login counter
567            increment_login_failure(&state, &lockout_key, LOCKOUT_WINDOW_SECS).await;
568            // Always return the same error code/message regardless of *why* auth failed.
569            // This prevents timing and enumeration attacks that could distinguish
570            // "user not found" from "wrong password".
571            tracing::debug!(
572                "Authentication error (reported as INVALID_CREDENTIALS): {}",
573                e
574            );
575            ApiResponse::error_typed("INVALID_CREDENTIALS", "Invalid username or password")
576        }
577    }
578}
579
580/// `POST /auth/refresh` — exchange a valid refresh token for a new access token.
581pub async fn refresh_token(
582    State(state): State<ApiState>,
583    Json(req): Json<RefreshRequest>,
584) -> ApiResponse<RefreshResponse> {
585    if req.refresh_token.is_empty() {
586        return ApiResponse::validation_error_typed("Invalid request");
587    }
588
589    // Redeem the refresh token: it must be a genuine, unrevoked, unspent refresh token of an
590    // active account; the next token of the chain is issued below.
591    let redemption = match state
592        .auth_framework
593        .redeem_refresh_jwt(&req.refresh_token)
594        .await
595    {
596        Ok(r) => r,
597        Err(e) => {
598            tracing::warn!("Refresh token refused: {}", e);
599            return ApiResponse::error_typed("INVALID_TOKEN", "Invalid or expired refresh token");
600        }
601    };
602    let claims = redemption.claims;
603
604    // Create new access token, preserving the user's actual permissions from storage.
605    let permissions: Vec<String> = match state
606        .auth_framework
607        .storage()
608        .get_kv(&format!("user_permissions:{}", claims.sub))
609        .await
610    {
611        Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
612        _ => vec![],
613    };
614
615    let token_lifetime = state.auth_framework.config().token_lifetime;
616    let new_access_token = match state.auth_framework.token_manager().create_jwt_token(
617        &claims.sub,
618        permissions,
619        Some(token_lifetime),
620    ) {
621        Ok(jwt) => jwt,
622        Err(e) => {
623            tracing::error!("Failed to create new access token: {}", e);
624            return ApiResponse::error_typed(
625                "TOKEN_CREATION_FAILED",
626                "Failed to create new access token",
627            );
628        }
629    };
630
631    ApiResponse::success(RefreshResponse {
632        access_token: new_access_token,
633        token_type: "Bearer".to_string(),
634        expires_in: token_lifetime.as_secs(),
635        refresh_token: redemption.new_refresh_token,
636    })
637}
638
639/// `POST /auth/logout` — revoke access and (optionally) refresh tokens.
640pub async fn logout(
641    State(state): State<ApiState>,
642    headers: HeaderMap,
643    Json(req): Json<LogoutRequest>,
644) -> ApiResponse<()> {
645    // Revoke the access token by storing it in the blocklist keyed by JTI
646    if let Some(token) = extract_bearer_token(&headers) {
647        match state
648            .auth_framework
649            .token_manager()
650            .validate_jwt_token(&token)
651        {
652            Ok(claims) => {
653                let revocation_key = format!("revoked_token:{}", claims.jti);
654                // TTL: longer of token's remaining lifetime or 1 hour; cap at 7 days
655                let ttl = std::time::Duration::from_secs(7 * 86400);
656                if let Err(e) = state
657                    .auth_framework
658                    .storage()
659                    .store_kv(revocation_key.as_str(), b"revoked", Some(ttl))
660                    .await
661                {
662                    tracing::error!("Failed to revoke access token JTI {}: {}", claims.jti, e);
663                } else {
664                    tracing::info!("Access token revoked (JTI: {})", claims.jti);
665                }
666            }
667            Err(_) => {
668                // Token was already invalid; no action needed
669                tracing::debug!("Logout called with invalid/expired access token");
670            }
671        }
672    }
673
674    // If refresh token provided, revoke it too
675    if let Some(ref refresh_token) = req.refresh_token {
676        match state
677            .auth_framework
678            .token_manager()
679            .validate_jwt_token(refresh_token)
680        {
681            Ok(claims) => {
682                // A logged-out refresh token ends its whole chain: a copy of a later token
683                // (e.g. one an attacker redeemed first) must not outlive the logout.
684                let family_ttl = state.auth_framework.config().refresh_token_lifetime
685                    + std::time::Duration::from_secs(60);
686                if let Err(e) = state
687                    .auth_framework
688                    .storage()
689                    .store_kv(
690                        &format!("revoked_family:{}", claims.refresh_family()),
691                        b"logout",
692                        Some(family_ttl),
693                    )
694                    .await
695                {
696                    tracing::error!(
697                        "Failed to revoke refresh chain {}: {}",
698                        claims.refresh_family(),
699                        e
700                    );
701                }
702                let revocation_key = format!("revoked_token:{}", claims.jti);
703                // as long as the token could still be presented
704                let ttl = std::time::Duration::from_secs(
705                    (claims.exp - chrono::Utc::now().timestamp()).max(60) as u64,
706                );
707                if let Err(e) = state
708                    .auth_framework
709                    .storage()
710                    .store_kv(revocation_key.as_str(), b"revoked", Some(ttl))
711                    .await
712                {
713                    tracing::error!("Failed to revoke refresh token JTI {}: {}", claims.jti, e);
714                } else {
715                    tracing::info!("Refresh token revoked (JTI: {})", claims.jti);
716                }
717            }
718            Err(_) => {
719                tracing::debug!("Logout called with invalid/expired refresh token");
720            }
721        }
722    }
723
724    ApiResponse::<()>::ok_with_message("Successfully logged out")
725}
726
727/// GET /auth/validate
728/// Validate current token and return user information
729pub async fn validate_token(
730    State(state): State<ApiState>,
731    headers: HeaderMap,
732) -> ApiResponse<LoginUserInfo> {
733    match extract_bearer_token(&headers) {
734        Some(token) => {
735            match crate::api::validate_api_token(&state.auth_framework, &token).await {
736                Ok(auth_token) => {
737                    // Fetch actual user information from storage
738                    let username = match state
739                        .auth_framework
740                        .get_user_profile(&auth_token.user_id)
741                        .await
742                    {
743                        Ok(profile) => profile
744                            .username
745                            .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
746                        Err(_) => format!("user_{}", auth_token.user_id), // Fallback if profile fetch fails
747                    };
748
749                    let user_info = LoginUserInfo {
750                        id: auth_token.user_id,
751                        username,
752                        roles: auth_token.roles.to_vec(),
753                        permissions: auth_token.permissions.to_vec(),
754                    };
755                    ApiResponse::success(user_info)
756                }
757                Err(_e) => ApiResponse::error_typed("AUTH_ERROR", "Token validation failed"),
758            }
759        }
760        None => ApiResponse::unauthorized_typed(),
761    }
762}
763
764/// `GET /auth/providers` — list available OAuth providers and their authorize URLs.
765pub async fn list_providers(State(_state): State<ApiState>) -> ApiResponse<Vec<ProviderInfo>> {
766    let providers = vec![
767        ProviderInfo {
768            name: "google".to_string(),
769            display_name: "Google".to_string(),
770            auth_url: "/oauth/google".to_string(),
771        },
772        ProviderInfo {
773            name: "github".to_string(),
774            display_name: "GitHub".to_string(),
775            auth_url: "/oauth/github".to_string(),
776        },
777        ProviderInfo {
778            name: "microsoft".to_string(),
779            display_name: "Microsoft".to_string(),
780            auth_url: "/oauth/microsoft".to_string(),
781        },
782    ];
783
784    ApiResponse::success(providers)
785}
786
787/// Summary of an available OAuth login provider.
788#[derive(Debug, Serialize)]
789pub struct ProviderInfo {
790    /// Machine-readable identifier (e.g. `"google"`).
791    pub name: String,
792    /// Human-readable label.
793    pub display_name: String,
794    /// Relative URL to initiate the OAuth flow.
795    pub auth_url: String,
796}
797
798/// User registration request.
799#[derive(Deserialize)]
800pub struct RegisterRequest {
801    /// Desired username (validated for length, characters, must start with a letter).
802    pub username: String,
803    /// Email address for the new account.
804    pub email: String,
805    /// Password (validated against minimum complexity rules).
806    pub password: String,
807}
808
809impl std::fmt::Debug for RegisterRequest {
810    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
811        let mut d = f.debug_struct("RegisterRequest");
812        d.field("username", &self.username);
813        d.field("email", &self.email);
814        d.field("password", &crate::utils::redact::redacted(&self.password));
815        d.finish()
816    }
817}
818
819/// User registration response.
820#[derive(Debug, Serialize)]
821pub struct RegisterResponse {
822    /// System-generated unique user identifier.
823    pub user_id: String,
824    /// The registered username.
825    pub username: String,
826    /// The registered email.
827    pub email: String,
828}
829
830/// `POST /auth/register` — create a new user account.
831///
832/// Validates username format, password complexity, and email uniqueness
833/// before persisting the new user.
834pub async fn register(
835    State(state): State<ApiState>,
836    Json(req): Json<RegisterRequest>,
837) -> ApiResponse<RegisterResponse> {
838    // Validate required fields
839    if req.username.is_empty() || req.password.is_empty() || req.email.is_empty() {
840        return ApiResponse::validation_error_typed("Username, password, and email are required");
841    }
842
843    // Validate username format (length, allowed characters, must start with letter).
844    if let Err(e) = crate::utils::validation::validate_username(&req.username) {
845        return ApiResponse::validation_error_typed(format!("{e}"));
846    }
847
848    // Validate password strength (min 8 characters with complexity)
849    if let Err(e) = crate::utils::validation::validate_password(&req.password) {
850        return ApiResponse::validation_error_typed(format!("{e}"));
851    }
852
853    // Check password against known data breaches (HIBP k-anonymity API)
854    match crate::utils::breach_check::is_password_breached(&req.password).await {
855        Ok(true) => {
856            return ApiResponse::validation_error_typed(
857                "This password has appeared in a known data breach. Please choose a different password.",
858            );
859        }
860        Ok(false) => {} // Password not breached, continue
861        Err(_) => {}    // HIBP API unreachable; fail open to avoid blocking registration
862    }
863
864    // Validate email format
865    if let Err(e) = crate::utils::validation::validate_email(&req.email) {
866        return ApiResponse::validation_error_typed(format!("{e}"));
867    }
868
869    // Check if username already exists
870    let username_key = format!("user:credentials:{}", req.username);
871    match state.auth_framework.storage().get_kv(&username_key).await {
872        Ok(Some(_)) => {
873            // Use a generic message for both username and email conflicts to prevent
874            // enumeration of existing accounts via the public registration endpoint.
875            return ApiResponse::error_typed(
876                "CONFLICT",
877                "An account with the provided details already exists",
878            );
879        }
880        Err(e) => {
881            tracing::error!("Storage error checking username: {}", e);
882            return ApiResponse::internal_error_typed();
883        }
884        Ok(None) => {}
885    }
886
887    // Check if email already exists
888    let email_key = format!("user:email:{}", req.email);
889    match state.auth_framework.storage().get_kv(&email_key).await {
890        Ok(Some(_)) => {
891            return ApiResponse::error_typed(
892                "CONFLICT",
893                "An account with the provided details already exists",
894            );
895        }
896        Err(e) => {
897            tracing::error!("Storage error checking email: {}", e);
898            return ApiResponse::internal_error_typed();
899        }
900        Ok(None) => {}
901    }
902
903    // Hash the password
904    let password_hash = match crate::utils::password::hash_password_argon2id(&req.password) {
905        Ok(hash) => hash,
906        Err(e) => {
907            tracing::error!("Password hashing failed: {:?}", e);
908            return ApiResponse::error_typed("REGISTRATION_FAILED", "Failed to process password");
909        }
910    };
911
912    // Generate user ID
913    let user_id = format!("user_{}", uuid::Uuid::new_v4().as_simple());
914    let created_at = chrono::Utc::now().to_rfc3339();
915
916    // Build user record
917    let user_data = serde_json::json!({
918        "user_id": user_id,
919        "username": req.username,
920        "email": req.email,
921        "password_hash": password_hash,
922        "created_at": created_at,
923    });
924    let user_data_bytes = user_data.to_string().into_bytes();
925
926    // Store main user record. This is the claim on the username: the existence checks above
927    // are only an early exit (two simultaneous registrations both pass them), so exactly one
928    // caller may create the key.
929    match state
930        .auth_framework
931        .storage()
932        .store_kv_if_absent(&username_key, &user_data_bytes, None)
933        .await
934    {
935        Ok(true) => {}
936        Ok(false) => {
937            return ApiResponse::error_typed(
938                "CONFLICT",
939                "An account with the provided details already exists",
940            );
941        }
942        Err(e) => {
943            tracing::error!("User registration storage failed: {:?}", e);
944            return ApiResponse::error_typed(
945                "REGISTRATION_FAILED",
946                "Failed to create user account",
947            );
948        }
949    }
950
951    // Store email → user_id mapping for duplicate checking (the claim on the email address)
952    let email_claim = state
953        .auth_framework
954        .storage()
955        .store_kv_if_absent(&email_key, user_id.as_bytes(), None)
956        .await;
957    if matches!(email_claim, Ok(false)) {
958        let _ = state
959            .auth_framework
960            .storage()
961            .delete_kv(&username_key)
962            .await;
963        return ApiResponse::error_typed(
964            "CONFLICT",
965            "An account with the provided details already exists",
966        );
967    }
968    if let Err(e) = email_claim {
969        tracing::error!("Email mapping storage failed: {:?}", e);
970        // Best-effort rollback
971        let _ = state
972            .auth_framework
973            .storage()
974            .delete_kv(&username_key)
975            .await;
976        return ApiResponse::error_typed("REGISTRATION_FAILED", "Failed to create user account");
977    }
978
979    // Store the canonical user record used by admin operations (set_user_active,
980    // update_user_password, delete_user, etc.) which all key on user:{user_id}.
981    let canonical_user_data = serde_json::json!({
982        "user_id": user_id,
983        "username": req.username,
984        "email": req.email,
985        "password_hash": password_hash,
986        "roles": ["user"],
987        "active": true,
988        "created_at": created_at,
989    });
990    let canonical_key = format!("user:{}", user_id);
991    if let Err(e) = state
992        .auth_framework
993        .storage()
994        .store_kv(
995            &canonical_key,
996            canonical_user_data.to_string().as_bytes(),
997            None,
998        )
999        .await
1000    {
1001        tracing::error!("Canonical user record storage failed: {:?}", e);
1002        let _ = state
1003            .auth_framework
1004            .storage()
1005            .delete_kv(&username_key)
1006            .await;
1007        let _ = state.auth_framework.storage().delete_kv(&email_key).await;
1008        return ApiResponse::error_typed("REGISTRATION_FAILED", "Failed to create user account");
1009    }
1010
1011    // Store username → user_id mapping (used by get_username_by_id reverse-lookup).
1012    let username_id_key = format!("user:username:{}", req.username);
1013    if let Err(e) = state
1014        .auth_framework
1015        .storage()
1016        .store_kv(&username_id_key, user_id.as_bytes(), None)
1017        .await
1018    {
1019        tracing::error!("Username-id mapping storage failed: {:?}", e);
1020        let _ = state
1021            .auth_framework
1022            .storage()
1023            .delete_kv(&username_key)
1024            .await;
1025        let _ = state.auth_framework.storage().delete_kv(&email_key).await;
1026        let _ = state
1027            .auth_framework
1028            .storage()
1029            .delete_kv(&canonical_key)
1030            .await;
1031        return ApiResponse::error_typed("REGISTRATION_FAILED", "Failed to create user account");
1032    }
1033
1034    // Add user to the global users:index so admin list endpoints include self-registered users.
1035    if let Err(e) = crate::auth_modular::user_manager::update_users_index(
1036        &*state.auth_framework.storage(),
1037        &user_id,
1038        true,
1039    )
1040    .await
1041    {
1042        tracing::warn!("Failed to update user index after registration: {}", e);
1043    }
1044
1045    tracing::info!("New user registered: {} ({})", req.username, user_id);
1046
1047    ApiResponse::success(RegisterResponse {
1048        user_id,
1049        username: req.username,
1050        email: req.email,
1051    })
1052}
1053
1054/// Response returned when an API key is successfully created.
1055#[derive(Serialize)]
1056pub struct CreateApiKeyResponse {
1057    /// The new API key – treat as a secret and display only once.
1058    pub api_key: String,
1059    /// Always `"ApiKey"`.
1060    pub token_type: String,
1061}
1062
1063impl std::fmt::Debug for CreateApiKeyResponse {
1064    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1065        let mut d = f.debug_struct("CreateApiKeyResponse");
1066        d.field("api_key", &crate::utils::redact::redacted(&self.api_key));
1067        d.field("token_type", &self.token_type);
1068        d.finish()
1069    }
1070}
1071
1072/// POST /api-keys – create an API key (requires authentication)
1073pub async fn create_api_key(
1074    State(state): State<ApiState>,
1075    headers: HeaderMap,
1076) -> ApiResponse<CreateApiKeyResponse> {
1077    // Require a valid Bearer token; reject unauthenticated requests with 401.
1078    let token = match crate::api::extract_bearer_token(&headers) {
1079        Some(t) => t,
1080        None => return ApiResponse::unauthorized_typed(),
1081    };
1082
1083    // Validate the token and extract the caller's identity.
1084    let auth_token = match crate::api::validate_api_token(&state.auth_framework, &token).await {
1085        Ok(t) => t,
1086        Err(_) => return ApiResponse::unauthorized_typed(),
1087    };
1088
1089    // Create an API key scoped to the authenticated user.
1090    match state
1091        .auth_framework
1092        .create_api_key(&auth_token.user_id, None)
1093        .await
1094    {
1095        Ok(api_key) => ApiResponse::success(CreateApiKeyResponse {
1096            api_key,
1097            token_type: "ApiKey".to_string(),
1098        }),
1099        Err(e) => {
1100            tracing::error!(
1101                "Failed to create API key for user {}: {}",
1102                auth_token.user_id,
1103                e
1104            );
1105            ApiResponse::internal_error_typed()
1106        }
1107    }
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112    use super::*;
1113    use axum::http::HeaderMap;
1114
1115    #[test]
1116    fn test_login_risk_low_normal_request() {
1117        let mut headers = HeaderMap::new();
1118        headers.insert(
1119            "user-agent",
1120            "Mozilla/5.0 (Windows NT 10.0; Win64; x64)".parse().unwrap(),
1121        );
1122        let (level, warnings) = login_risk_level(&headers);
1123        assert_eq!(level, "low");
1124        assert!(warnings.is_empty());
1125    }
1126
1127    #[test]
1128    fn test_login_risk_high_no_user_agent() {
1129        let headers = HeaderMap::new();
1130        let (level, warnings) = login_risk_level(&headers);
1131        assert_eq!(level, "high");
1132        assert!(!warnings.is_empty());
1133    }
1134
1135    #[test]
1136    fn test_login_risk_tor_browser() {
1137        let mut headers = HeaderMap::new();
1138        headers.insert("user-agent", "Mozilla/5.0 (Tor Browser)".parse().unwrap());
1139        let (level, warnings) = login_risk_level(&headers);
1140        // Tor alone is 40 points → "high"
1141        assert!(level == "high" || level == "critical");
1142        assert!(warnings.iter().any(|w| w.contains("Tor")));
1143    }
1144
1145    #[test]
1146    fn test_login_risk_proxy_hops() {
1147        let mut headers = HeaderMap::new();
1148        headers.insert("user-agent", "Mozilla/5.0".parse().unwrap());
1149        headers.insert("x-forwarded-for", "1.2.3.4, 5.6.7.8".parse().unwrap());
1150        let (level, warnings) = login_risk_level(&headers);
1151        assert_eq!(level, "medium");
1152        assert!(warnings.iter().any(|w| w.contains("proxy")));
1153    }
1154
1155    #[test]
1156    fn test_login_request_deserialization() {
1157        let json = r#"{"username":"alice","password":"secret"}"#;
1158        let req: LoginRequest = serde_json::from_str(json).unwrap();
1159        assert_eq!(req.username, "alice");
1160        assert_eq!(req.password, "secret");
1161        assert!(!req.remember_me);
1162        assert!(req.challenge_id.is_none());
1163        assert!(req.mfa_code.is_none());
1164    }
1165
1166    #[test]
1167    fn test_login_response_serialization() {
1168        let resp = LoginResponse {
1169            access_token: "at".into(),
1170            refresh_token: "rt".into(),
1171            token_type: "Bearer".into(),
1172            expires_in: 3600,
1173            user: LoginUserInfo {
1174                id: "uid".into(),
1175                username: "alice".into(),
1176                roles: vec!["user".into()],
1177                permissions: vec![],
1178            },
1179            login_risk_level: "low".into(),
1180            security_warnings: vec![],
1181        };
1182        let json = serde_json::to_value(&resp).unwrap();
1183        assert_eq!(json["token_type"], "Bearer");
1184        assert_eq!(json["expires_in"], 3600);
1185        assert_eq!(json["user"]["username"], "alice");
1186    }
1187
1188    #[test]
1189    fn test_register_request_deserialization() {
1190        let json = r#"{"username":"bob","password":"StrongP@ss1","email":"bob@example.com"}"#;
1191        let req: RegisterRequest = serde_json::from_str(json).unwrap();
1192        assert_eq!(req.username, "bob");
1193        assert_eq!(req.email, "bob@example.com");
1194    }
1195
1196    #[test]
1197    fn test_refresh_request_deserialization() {
1198        let json = r#"{"refresh_token":"some_token"}"#;
1199        let req: RefreshRequest = serde_json::from_str(json).unwrap();
1200        assert_eq!(req.refresh_token, "some_token");
1201    }
1202}