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", &crate::utils::redact::redacted(&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.auth_framework.token_manager().create_jwt_token(
139        user_id,
140        vec!["refresh".to_string()],
141        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}
192
193impl std::fmt::Debug for RefreshResponse {
194    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195        let mut d = f.debug_struct("RefreshResponse");
196        d.field(
197            "access_token",
198            &crate::utils::redact::redacted(&self.access_token),
199        );
200        d.field("token_type", &self.token_type);
201        d.field("expires_in", &self.expires_in);
202        d.finish()
203    }
204}
205
206/// Logout request.
207#[derive(Deserialize)]
208pub struct LogoutRequest {
209    /// Optional refresh token to revoke alongside the access token.
210    #[serde(default)]
211    pub refresh_token: Option<String>,
212}
213
214impl std::fmt::Debug for LogoutRequest {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        let mut d = f.debug_struct("LogoutRequest");
217        d.field(
218            "refresh_token",
219            &crate::utils::redact::redacted(&self.refresh_token),
220        );
221        d.finish()
222    }
223}
224
225/// Compute a login risk level string from request headers.
226///
227/// This is a lightweight, header-only heuristic used to populate the
228/// `login_risk_level` field in the login response and to trigger security
229/// warnings when MFA is not enrolled.  It does **not** replace a full
230/// risk-engine evaluation — for that, see `AuthorizationContextBuilder`.
231pub(crate) fn login_risk_level(headers: &HeaderMap) -> (&'static str, Vec<String>) {
232    let user_agent = headers
233        .get("user-agent")
234        .and_then(|v| v.to_str().ok())
235        .unwrap_or("");
236
237    let forwarded_for = headers
238        .get("x-forwarded-for")
239        .and_then(|v| v.to_str().ok())
240        .unwrap_or("");
241
242    let mut risk_points: u8 = 0;
243    let mut warnings: Vec<String> = Vec::new();
244
245    if user_agent.is_empty() {
246        risk_points = risk_points.saturating_add(30);
247        warnings.push(
248            "No browser User-Agent detected; this request may originate from an automated script."
249                .to_string(),
250        );
251    }
252
253    // Detect Tor exit nodes by well-known header patterns.  This is a best-effort
254    // check and can be defeated; a proper geo-IP database lookup is more reliable.
255    if user_agent.to_lowercase().contains("tor browser") {
256        risk_points = risk_points.saturating_add(40);
257        warnings.push("Login originated from the Tor Browser.".to_string());
258    }
259
260    // Multiple IPs in X-Forwarded-For typically indicate a proxy or VPN hop.
261    let hop_count = forwarded_for.split(',').count();
262    if hop_count >= 2 {
263        risk_points = risk_points.saturating_add(15);
264        warnings.push(format!(
265            "Request passed through {} proxy hops (X-Forwarded-For).",
266            hop_count
267        ));
268    }
269
270    let level = match risk_points {
271        0..=9 => "low",
272        10..=29 => "medium",
273        30..=59 => "high",
274        _ => "critical",
275    };
276    (level, warnings)
277}
278
279/// Increment the per-username failed login counter with a sliding TTL window.
280async fn increment_login_failure(state: &ApiState, lockout_key: &str, window_secs: u64) {
281    let current: u64 = match state.auth_framework.storage().get_kv(lockout_key).await {
282        Ok(Some(bytes)) => std::str::from_utf8(&bytes)
283            .ok()
284            .and_then(|s| s.parse().ok())
285            .unwrap_or(0),
286        _ => 0,
287    };
288    let new_count = current.saturating_add(1);
289    let _ = state
290        .auth_framework
291        .storage()
292        .store_kv(
293            lockout_key,
294            new_count.to_string().as_bytes(),
295            Some(std::time::Duration::from_secs(window_secs)),
296        )
297        .await;
298}
299
300/// Step-up for a sensitive change: the caller proves knowledge of their own password, through
301/// the same per-username failure counter and lockout as `/auth/login`, so a bearer token alone
302/// cannot be used to guess it. Returns the error code and message to answer with.
303pub(crate) async fn require_password_step_up(
304    state: &ApiState,
305    user_id: &str,
306    password: Option<&str>,
307    mfa_code: Option<&str>,
308) -> Result<(), (&'static str, &'static str)> {
309    const WINDOW_SECS: u64 = 900;
310    const MAX_FAILED_ATTEMPTS: u64 = 5; // the login limit
311    const REQUIRED: (&str, &str) = (
312        "STEP_UP_REQUIRED",
313        "Confirm your current password to make this change",
314    );
315    // An account with no local password (it signs in through another method) cannot answer a
316    // password step-up: it confirms with the current code of its enrolled authenticator app, or,
317    // with none enrolled, is told what to enrol.
318    if let Ok(Some(bytes)) = state
319        .auth_framework
320        .storage()
321        .get_kv(&format!("user:{user_id}"))
322        .await
323        && let Ok(record) = serde_json::from_slice::<serde_json::Value>(&bytes)
324        && record["password_hash"].as_str().is_none()
325    {
326        return authenticator_step_up(state, user_id, mfa_code).await;
327    }
328    let Some(password) = password.filter(|p| !p.is_empty()) else {
329        return Err(REQUIRED);
330    };
331    let Ok(username) = state.auth_framework.get_username_by_id(user_id).await else {
332        return Err(REQUIRED);
333    };
334    let lockout_key = format!("login_failures:{username}");
335    if let Ok(Some(bytes)) = state.auth_framework.storage().get_kv(&lockout_key).await
336        && let Ok(text) = std::str::from_utf8(&bytes)
337        && let Ok(count) = text.parse::<u64>()
338        && count >= MAX_FAILED_ATTEMPTS
339    {
340        return Err((
341            "ACCOUNT_LOCKED",
342            "Too many failed attempts. Please try again later.",
343        ));
344    }
345    match state
346        .auth_framework
347        .verify_user_password(user_id, password)
348        .await
349    {
350        Ok(true) => {
351            let _ = state.auth_framework.storage().delete_kv(&lockout_key).await;
352            Ok(())
353        }
354        _ => {
355            increment_login_failure(state, &lockout_key, WINDOW_SECS).await;
356            Err(("STEP_UP_FAILED", "The password is not correct"))
357        }
358    }
359}
360
361/// Step-up for an account with no local password: the current code of its enrolled
362/// authenticator app (`current_mfa_code`), with the same failure counter and lockout as the
363/// password step-up. A code is accepted once.
364async fn authenticator_step_up(
365    state: &ApiState,
366    user_id: &str,
367    mfa_code: Option<&str>,
368) -> Result<(), (&'static str, &'static str)> {
369    const WINDOW_SECS: u64 = 900;
370    const MAX_FAILED_ATTEMPTS: u64 = 5; // the login limit
371    let storage = state.auth_framework.storage();
372    let Some(secret) = super::mfa::active_totp_secret(storage.as_ref(), user_id).await else {
373        return Err((
374            "STEP_UP_UNAVAILABLE",
375            "This account has no local password and no authenticator app; enrol one (POST /mfa/setup) to register passkeys",
376        ));
377    };
378    let Some(code) = mfa_code.filter(|c| !c.is_empty()) else {
379        return Err((
380            "STEP_UP_REQUIRED",
381            "Send the current code of your authenticator app as current_mfa_code",
382        ));
383    };
384    let lockout_key = format!("login_failures:{user_id}");
385    if let Ok(Some(bytes)) = storage.get_kv(&lockout_key).await
386        && let Ok(text) = std::str::from_utf8(&bytes)
387        && let Ok(count) = text.parse::<u64>()
388        && count >= MAX_FAILED_ATTEMPTS
389    {
390        return Err((
391            "ACCOUNT_LOCKED",
392            "Too many failed attempts. Please try again later.",
393        ));
394    }
395    let now = chrono::Utc::now().timestamp() as u64;
396    let valid = code.len() == 6
397        && code.chars().all(|c| c.is_ascii_digit())
398        && super::mfa::verify_totp_code(code, &secret, now);
399    // A code that was already used for a step-up is not accepted again.
400    let fresh = valid
401        && storage
402            .store_kv_if_absent(
403                &format!("stepup_totp_used:{user_id}:{code}"),
404                b"1",
405                Some(std::time::Duration::from_secs(120)),
406            )
407            .await
408            .unwrap_or(false);
409    if fresh {
410        let _ = storage.delete_kv(&lockout_key).await;
411        Ok(())
412    } else {
413        increment_login_failure(state, &lockout_key, WINDOW_SECS).await;
414        Err(("STEP_UP_FAILED", "The authenticator code is not correct"))
415    }
416}
417
418/// `POST /auth/login` — authenticate a user with username/password.
419///
420/// On success returns access + refresh tokens, user metadata, and adaptive
421/// risk information.  Returns `ACCOUNT_LOCKED` after 5 consecutive failures
422/// within 15 minutes.
423pub async fn login(
424    State(state): State<ApiState>,
425    headers: HeaderMap,
426    Json(req): Json<LoginRequest>,
427) -> ApiResponse<LoginResponse> {
428    // Validate required fields
429    if req.username.is_empty() || req.password.is_empty() {
430        return ApiResponse::validation_error_typed("Username and password are required");
431    }
432
433    if req.challenge_id.is_some() ^ req.mfa_code.is_some() {
434        return ApiResponse::validation_error_typed(
435            "challenge_id and mfa_code must be provided together",
436        );
437    }
438
439    if let (Some(challenge_id), Some(mfa_code)) =
440        (req.challenge_id.clone(), req.mfa_code.as_deref())
441    {
442        return match state
443            .auth_framework
444            .complete_mfa_by_id(&challenge_id, mfa_code)
445            .await
446        {
447            Ok(token) => {
448                let mut response = build_login_response(
449                    &state,
450                    &token.user_id,
451                    req.username,
452                    token.permissions.to_vec(),
453                )
454                .await;
455                // MFA completion means the step-up was satisfied — mark as low risk.
456                if let Some(data) = response.data.as_mut() {
457                    data.login_risk_level = "low".to_string();
458                }
459                response
460            }
461            Err(e) => {
462                tracing::debug!("MFA completion failed during login: {}", e);
463                ApiResponse::error_typed(
464                    "MFA_INVALID_CODE",
465                    "Invalid or expired MFA challenge or code",
466                )
467            }
468        };
469    }
470
471    // Compute adaptive risk from request headers before touching the auth core
472    // so the risk assessment can influence the response even on success.
473    let (risk_level, mut risk_warnings) = login_risk_level(&headers);
474
475    // SEC-M1/L1: Per-username failed login rate limiting / account lockout.
476    // Key: "login_failures:{username}" — stores the current failure count as a
477    // decimal string with a 15-minute TTL (auto-resets after 15 min of no attempts).
478    let lockout_key = format!("login_failures:{}", req.username);
479    const MAX_FAILED_ATTEMPTS: u64 = 5;
480    const LOCKOUT_WINDOW_SECS: u64 = 900; // 15 minutes
481    if let Ok(Some(count_bytes)) = state.auth_framework.storage().get_kv(&lockout_key).await
482        && let Ok(count_str) = std::str::from_utf8(&count_bytes)
483        && let Ok(count) = count_str.parse::<u64>()
484        && count >= MAX_FAILED_ATTEMPTS
485    {
486        tracing::warn!(
487            username = %req.username,
488            failed_attempts = count,
489            "Login rejected — account temporarily locked due to repeated failures"
490        );
491        return ApiResponse::error_typed(
492            "ACCOUNT_LOCKED",
493            "Too many failed login attempts. Please try again later.",
494        );
495    }
496
497    // Create credential for authentication
498    let credential = crate::authentication::credentials::Credential::Password {
499        username: req.username.clone(),
500        password: req.password.clone(),
501    };
502
503    // Attempt authentication
504    match state
505        .auth_framework
506        .authenticate("password", credential)
507        .await
508    {
509        Ok(auth_result) => match auth_result {
510            crate::auth::AuthResult::Success(token) => {
511                // Check if the user has MFA enrolled.  If not and the risk level is
512                // elevated, add a security advisory recommending MFA enrollment.
513                let mfa_enrolled =
514                    crate::api::mfa::check_user_mfa_status(&state.auth_framework, &token.user_id)
515                        .await;
516
517                if !mfa_enrolled && matches!(risk_level, "high" | "critical") {
518                    risk_warnings.push(
519                        "Your account does not have multi-factor authentication enabled. \
520                         Enable MFA to protect this account from high-risk login contexts."
521                            .to_string(),
522                    );
523                    tracing::warn!(
524                        user_id = %token.user_id,
525                        risk_level = %risk_level,
526                        "High-risk login without MFA enrolled"
527                    );
528                } else {
529                    tracing::info!(
530                        user_id = %token.user_id,
531                        risk_level = %risk_level,
532                        mfa_enrolled = %mfa_enrolled,
533                        "Successful login"
534                    );
535                }
536
537                let mut response = build_login_response(
538                    &state,
539                    &token.user_id,
540                    req.username,
541                    token.permissions.to_vec(),
542                )
543                .await;
544
545                // Reset failed login counter on successful authentication
546                let _ = state.auth_framework.storage().delete_kv(&lockout_key).await;
547
548                if let Some(data) = response.data.as_mut() {
549                    data.login_risk_level = risk_level.to_string();
550                    data.security_warnings = risk_warnings;
551                }
552                response
553            }
554            crate::auth::AuthResult::MfaRequired(challenge) => {
555                // Return the challenge data so the client knows how to fulfill MFA.
556                // The client should prompt for the appropriate second factor and then
557                // re-submit the login request with both challenge_id and mfa_code.
558                let mfa_type_str = match &challenge.mfa_type {
559                    crate::methods::MfaType::Totp => "totp",
560                    crate::methods::MfaType::Sms { .. } => "sms",
561                    crate::methods::MfaType::Email { .. } => "email",
562                    crate::methods::MfaType::Push { .. } => "push",
563                    crate::methods::MfaType::SecurityKey => "security_key",
564                    crate::methods::MfaType::BackupCode => "backup_code",
565                    crate::methods::MfaType::MultiMethod => "totp_or_backup_code",
566                };
567                ApiResponse::<()>::error_with_details(
568                    "MFA_REQUIRED",
569                    "Multi-factor authentication required",
570                    serde_json::json!({
571                        "challenge_id": challenge.id,
572                        "mfa_type": mfa_type_str,
573                        "expires_at": challenge.expires_at.to_rfc3339(),
574                        "message": challenge.message,
575                    }),
576                )
577                .cast()
578            }
579            crate::auth::AuthResult::Failure(reason) => {
580                // Increment failed login counter
581                increment_login_failure(&state, &lockout_key, LOCKOUT_WINDOW_SECS).await;
582                ApiResponse::error_typed("AUTHENTICATION_FAILED", reason)
583            }
584        },
585        Err(e) => {
586            // Increment failed login counter
587            increment_login_failure(&state, &lockout_key, LOCKOUT_WINDOW_SECS).await;
588            // Always return the same error code/message regardless of *why* auth failed.
589            // This prevents timing and enumeration attacks that could distinguish
590            // "user not found" from "wrong password".
591            tracing::debug!(
592                "Authentication error (reported as INVALID_CREDENTIALS): {}",
593                e
594            );
595            ApiResponse::error_typed("INVALID_CREDENTIALS", "Invalid username or password")
596        }
597    }
598}
599
600/// `POST /auth/refresh` — exchange a valid refresh token for a new access token.
601pub async fn refresh_token(
602    State(state): State<ApiState>,
603    Json(req): Json<RefreshRequest>,
604) -> ApiResponse<RefreshResponse> {
605    if req.refresh_token.is_empty() {
606        return ApiResponse::validation_error_typed("Invalid request");
607    }
608
609    // Validate the refresh token
610    match state
611        .auth_framework
612        .token_manager()
613        .validate_jwt_token(&req.refresh_token)
614    {
615        Ok(claims) => {
616            // Check if this is actually a refresh token
617            if !claims.scope.contains("refresh") {
618                return ApiResponse::error_typed(
619                    "INVALID_TOKEN",
620                    "Expected a refresh token, but received an access token",
621                );
622            }
623
624            // SECURITY: Reject revoked refresh tokens (e.g. those already passed to /auth/logout).
625            let revocation_key = format!("revoked_token:{}", claims.jti);
626            match state.auth_framework.storage().get_kv(&revocation_key).await {
627                Ok(Some(_)) => {
628                    return ApiResponse::error_typed(
629                        "INVALID_TOKEN",
630                        "Refresh token has been revoked",
631                    );
632                }
633                Ok(None) => {} // Not revoked — proceed
634                Err(e) => {
635                    tracing::error!("Refresh token revocation check failed: {}", e);
636                    return ApiResponse::error_typed(
637                        "INTERNAL_ERROR",
638                        "Unable to verify token status",
639                    );
640                }
641            }
642
643            // Create new access token, preserving the user's actual permissions from storage.
644            // H-1 fix: do NOT hard-code ["read","write"] — load the real permission set.
645
646            // SECURITY: Reject refresh if the user's account has been deactivated
647            // since the refresh token was issued.  Without this check a deactivated
648            // user can indefinitely obtain new access tokens.
649            {
650                let user_key = format!("user:{}", claims.sub);
651                if let Ok(Some(user_bytes)) = state.auth_framework.storage().get_kv(&user_key).await
652                {
653                    let user_json: serde_json::Value =
654                        serde_json::from_slice(&user_bytes).unwrap_or_default();
655                    let active = user_json["active"].as_bool().unwrap_or(true);
656                    if !active {
657                        return ApiResponse::error_typed(
658                            "ACCOUNT_DEACTIVATED",
659                            "Account has been deactivated",
660                        );
661                    }
662                }
663            }
664
665            // A refresh token issued before the account's credentials were reset is refused.
666            if crate::account_state::ensure_issued_after_revocation(
667                state.auth_framework.storage().as_ref(),
668                &claims.sub,
669                claims.iat.saturating_mul(1000),
670            )
671            .await
672            .is_err()
673            {
674                return ApiResponse::error_typed(
675                    "INVALID_TOKEN",
676                    "Refresh token is no longer valid",
677                );
678            }
679
680            let permissions: Vec<String> = match state
681                .auth_framework
682                .storage()
683                .get_kv(&format!("user_permissions:{}", claims.sub))
684                .await
685            {
686                Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
687                _ => vec![],
688            };
689
690            let token_lifetime = state.auth_framework.config().token_lifetime;
691            let new_access_token = match state.auth_framework.token_manager().create_jwt_token(
692                &claims.sub,
693                permissions,
694                Some(token_lifetime),
695            ) {
696                Ok(jwt) => jwt,
697                Err(e) => {
698                    tracing::error!("Failed to create new access token: {}", e);
699                    return ApiResponse::error_typed(
700                        "TOKEN_CREATION_FAILED",
701                        "Failed to create new access token",
702                    );
703                }
704            };
705
706            let response = RefreshResponse {
707                access_token: new_access_token,
708                token_type: "Bearer".to_string(),
709                expires_in: token_lifetime.as_secs(),
710            };
711
712            ApiResponse::success(response)
713        }
714        Err(e) => {
715            tracing::warn!("Invalid refresh token: {}", e);
716            ApiResponse::error_typed("INVALID_TOKEN", "Invalid or expired refresh token")
717        }
718    }
719}
720
721/// `POST /auth/logout` — revoke access and (optionally) refresh tokens.
722pub async fn logout(
723    State(state): State<ApiState>,
724    headers: HeaderMap,
725    Json(req): Json<LogoutRequest>,
726) -> ApiResponse<()> {
727    // Revoke the access token by storing it in the blocklist keyed by JTI
728    if let Some(token) = extract_bearer_token(&headers) {
729        match state
730            .auth_framework
731            .token_manager()
732            .validate_jwt_token(&token)
733        {
734            Ok(claims) => {
735                let revocation_key = format!("revoked_token:{}", claims.jti);
736                // TTL: longer of token's remaining lifetime or 1 hour; cap at 7 days
737                let ttl = std::time::Duration::from_secs(7 * 86400);
738                if let Err(e) = state
739                    .auth_framework
740                    .storage()
741                    .store_kv(revocation_key.as_str(), b"revoked", Some(ttl))
742                    .await
743                {
744                    tracing::error!("Failed to revoke access token JTI {}: {}", claims.jti, e);
745                } else {
746                    tracing::info!("Access token revoked (JTI: {})", claims.jti);
747                }
748            }
749            Err(_) => {
750                // Token was already invalid; no action needed
751                tracing::debug!("Logout called with invalid/expired access token");
752            }
753        }
754    }
755
756    // If refresh token provided, revoke it too
757    if let Some(ref refresh_token) = req.refresh_token {
758        match state
759            .auth_framework
760            .token_manager()
761            .validate_jwt_token(refresh_token)
762        {
763            Ok(claims) => {
764                let revocation_key = format!("revoked_token:{}", claims.jti);
765                let ttl = std::time::Duration::from_secs(7 * 86400);
766                if let Err(e) = state
767                    .auth_framework
768                    .storage()
769                    .store_kv(revocation_key.as_str(), b"revoked", Some(ttl))
770                    .await
771                {
772                    tracing::error!("Failed to revoke refresh token JTI {}: {}", claims.jti, e);
773                } else {
774                    tracing::info!("Refresh token revoked (JTI: {})", claims.jti);
775                }
776            }
777            Err(_) => {
778                tracing::debug!("Logout called with invalid/expired refresh token");
779            }
780        }
781    }
782
783    ApiResponse::<()>::ok_with_message("Successfully logged out")
784}
785
786/// GET /auth/validate
787/// Validate current token and return user information
788pub async fn validate_token(
789    State(state): State<ApiState>,
790    headers: HeaderMap,
791) -> ApiResponse<LoginUserInfo> {
792    match extract_bearer_token(&headers) {
793        Some(token) => {
794            match crate::api::validate_api_token(&state.auth_framework, &token).await {
795                Ok(auth_token) => {
796                    // Fetch actual user information from storage
797                    let username = match state
798                        .auth_framework
799                        .get_user_profile(&auth_token.user_id)
800                        .await
801                    {
802                        Ok(profile) => profile
803                            .username
804                            .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
805                        Err(_) => format!("user_{}", auth_token.user_id), // Fallback if profile fetch fails
806                    };
807
808                    let user_info = LoginUserInfo {
809                        id: auth_token.user_id,
810                        username,
811                        roles: auth_token.roles.to_vec(),
812                        permissions: auth_token.permissions.to_vec(),
813                    };
814                    ApiResponse::success(user_info)
815                }
816                Err(_e) => ApiResponse::error_typed("AUTH_ERROR", "Token validation failed"),
817            }
818        }
819        None => ApiResponse::unauthorized_typed(),
820    }
821}
822
823/// `GET /auth/providers` — list available OAuth providers and their authorize URLs.
824pub async fn list_providers(State(_state): State<ApiState>) -> ApiResponse<Vec<ProviderInfo>> {
825    let providers = vec![
826        ProviderInfo {
827            name: "google".to_string(),
828            display_name: "Google".to_string(),
829            auth_url: "/oauth/google".to_string(),
830        },
831        ProviderInfo {
832            name: "github".to_string(),
833            display_name: "GitHub".to_string(),
834            auth_url: "/oauth/github".to_string(),
835        },
836        ProviderInfo {
837            name: "microsoft".to_string(),
838            display_name: "Microsoft".to_string(),
839            auth_url: "/oauth/microsoft".to_string(),
840        },
841    ];
842
843    ApiResponse::success(providers)
844}
845
846/// Summary of an available OAuth login provider.
847#[derive(Debug, Serialize)]
848pub struct ProviderInfo {
849    /// Machine-readable identifier (e.g. `"google"`).
850    pub name: String,
851    /// Human-readable label.
852    pub display_name: String,
853    /// Relative URL to initiate the OAuth flow.
854    pub auth_url: String,
855}
856
857/// User registration request.
858#[derive(Deserialize)]
859pub struct RegisterRequest {
860    /// Desired username (validated for length, characters, must start with a letter).
861    pub username: String,
862    /// Email address for the new account.
863    pub email: String,
864    /// Password (validated against minimum complexity rules).
865    pub password: String,
866}
867
868impl std::fmt::Debug for RegisterRequest {
869    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
870        let mut d = f.debug_struct("RegisterRequest");
871        d.field("username", &self.username);
872        d.field("email", &self.email);
873        d.field("password", &crate::utils::redact::redacted(&self.password));
874        d.finish()
875    }
876}
877
878/// User registration response.
879#[derive(Debug, Serialize)]
880pub struct RegisterResponse {
881    /// System-generated unique user identifier.
882    pub user_id: String,
883    /// The registered username.
884    pub username: String,
885    /// The registered email.
886    pub email: String,
887}
888
889/// `POST /auth/register` — create a new user account.
890///
891/// Validates username format, password complexity, and email uniqueness
892/// before persisting the new user.
893pub async fn register(
894    State(state): State<ApiState>,
895    Json(req): Json<RegisterRequest>,
896) -> ApiResponse<RegisterResponse> {
897    // Validate required fields
898    if req.username.is_empty() || req.password.is_empty() || req.email.is_empty() {
899        return ApiResponse::validation_error_typed("Username, password, and email are required");
900    }
901
902    // Validate username format (length, allowed characters, must start with letter).
903    if let Err(e) = crate::utils::validation::validate_username(&req.username) {
904        return ApiResponse::validation_error_typed(format!("{e}"));
905    }
906
907    // Validate password strength (min 8 characters with complexity)
908    if let Err(e) = crate::utils::validation::validate_password(&req.password) {
909        return ApiResponse::validation_error_typed(format!("{e}"));
910    }
911
912    // Check password against known data breaches (HIBP k-anonymity API)
913    match crate::utils::breach_check::is_password_breached(&req.password).await {
914        Ok(true) => {
915            return ApiResponse::validation_error_typed(
916                "This password has appeared in a known data breach. Please choose a different password.",
917            );
918        }
919        Ok(false) => {} // Password not breached, continue
920        Err(_) => {}    // HIBP API unreachable; fail open to avoid blocking registration
921    }
922
923    // Validate email format
924    if let Err(e) = crate::utils::validation::validate_email(&req.email) {
925        return ApiResponse::validation_error_typed(format!("{e}"));
926    }
927
928    // Check if username already exists
929    let username_key = format!("user:credentials:{}", req.username);
930    match state.auth_framework.storage().get_kv(&username_key).await {
931        Ok(Some(_)) => {
932            // Use a generic message for both username and email conflicts to prevent
933            // enumeration of existing accounts via the public registration endpoint.
934            return ApiResponse::error_typed(
935                "CONFLICT",
936                "An account with the provided details already exists",
937            );
938        }
939        Err(e) => {
940            tracing::error!("Storage error checking username: {}", e);
941            return ApiResponse::internal_error_typed();
942        }
943        Ok(None) => {}
944    }
945
946    // Check if email already exists
947    let email_key = format!("user:email:{}", req.email);
948    match state.auth_framework.storage().get_kv(&email_key).await {
949        Ok(Some(_)) => {
950            return ApiResponse::error_typed(
951                "CONFLICT",
952                "An account with the provided details already exists",
953            );
954        }
955        Err(e) => {
956            tracing::error!("Storage error checking email: {}", e);
957            return ApiResponse::internal_error_typed();
958        }
959        Ok(None) => {}
960    }
961
962    // Hash the password
963    let password_hash = match crate::utils::password::hash_password_argon2id(&req.password) {
964        Ok(hash) => hash,
965        Err(e) => {
966            tracing::error!("Password hashing failed: {:?}", e);
967            return ApiResponse::error_typed("REGISTRATION_FAILED", "Failed to process password");
968        }
969    };
970
971    // Generate user ID
972    let user_id = format!("user_{}", uuid::Uuid::new_v4().as_simple());
973    let created_at = chrono::Utc::now().to_rfc3339();
974
975    // Build user record
976    let user_data = serde_json::json!({
977        "user_id": user_id,
978        "username": req.username,
979        "email": req.email,
980        "password_hash": password_hash,
981        "created_at": created_at,
982    });
983    let user_data_bytes = user_data.to_string().into_bytes();
984
985    // Store main user record
986    if let Err(e) = state
987        .auth_framework
988        .storage()
989        .store_kv(&username_key, &user_data_bytes, None)
990        .await
991    {
992        tracing::error!("User registration storage failed: {:?}", e);
993        return ApiResponse::error_typed("REGISTRATION_FAILED", "Failed to create user account");
994    }
995
996    // Store email → user_id mapping for duplicate checking
997    if let Err(e) = state
998        .auth_framework
999        .storage()
1000        .store_kv(&email_key, user_id.as_bytes(), None)
1001        .await
1002    {
1003        tracing::error!("Email mapping storage failed: {:?}", e);
1004        // Best-effort rollback
1005        let _ = state
1006            .auth_framework
1007            .storage()
1008            .delete_kv(&username_key)
1009            .await;
1010        return ApiResponse::error_typed("REGISTRATION_FAILED", "Failed to create user account");
1011    }
1012
1013    // Store the canonical user record used by admin operations (set_user_active,
1014    // update_user_password, delete_user, etc.) which all key on user:{user_id}.
1015    let canonical_user_data = serde_json::json!({
1016        "user_id": user_id,
1017        "username": req.username,
1018        "email": req.email,
1019        "password_hash": password_hash,
1020        "roles": ["user"],
1021        "active": true,
1022        "created_at": created_at,
1023    });
1024    let canonical_key = format!("user:{}", user_id);
1025    if let Err(e) = state
1026        .auth_framework
1027        .storage()
1028        .store_kv(
1029            &canonical_key,
1030            canonical_user_data.to_string().as_bytes(),
1031            None,
1032        )
1033        .await
1034    {
1035        tracing::error!("Canonical user record storage failed: {:?}", e);
1036        let _ = state
1037            .auth_framework
1038            .storage()
1039            .delete_kv(&username_key)
1040            .await;
1041        let _ = state.auth_framework.storage().delete_kv(&email_key).await;
1042        return ApiResponse::error_typed("REGISTRATION_FAILED", "Failed to create user account");
1043    }
1044
1045    // Store username → user_id mapping (used by get_username_by_id reverse-lookup).
1046    let username_id_key = format!("user:username:{}", req.username);
1047    if let Err(e) = state
1048        .auth_framework
1049        .storage()
1050        .store_kv(&username_id_key, user_id.as_bytes(), None)
1051        .await
1052    {
1053        tracing::error!("Username-id mapping storage failed: {:?}", e);
1054        let _ = state
1055            .auth_framework
1056            .storage()
1057            .delete_kv(&username_key)
1058            .await;
1059        let _ = state.auth_framework.storage().delete_kv(&email_key).await;
1060        let _ = state
1061            .auth_framework
1062            .storage()
1063            .delete_kv(&canonical_key)
1064            .await;
1065        return ApiResponse::error_typed("REGISTRATION_FAILED", "Failed to create user account");
1066    }
1067
1068    // Add user to the global users:index so admin list endpoints include self-registered users.
1069    let index_key = "users:index";
1070    let mut ids: Vec<String> = match state.auth_framework.storage().get_kv(index_key).await {
1071        Ok(Some(bytes)) => serde_json::from_slice(&bytes).unwrap_or_default(),
1072        _ => vec![],
1073    };
1074    ids.push(user_id.clone());
1075    if let Ok(idx_json) = serde_json::to_vec(&ids)
1076        && let Err(e) = state
1077            .auth_framework
1078            .storage()
1079            .store_kv(index_key, &idx_json, None)
1080            .await
1081    {
1082        tracing::warn!("Failed to update user index after registration: {}", e);
1083    }
1084
1085    tracing::info!("New user registered: {} ({})", req.username, user_id);
1086
1087    ApiResponse::success(RegisterResponse {
1088        user_id,
1089        username: req.username,
1090        email: req.email,
1091    })
1092}
1093
1094/// Response returned when an API key is successfully created.
1095#[derive(Serialize)]
1096pub struct CreateApiKeyResponse {
1097    /// The new API key – treat as a secret and display only once.
1098    pub api_key: String,
1099    /// Always `"ApiKey"`.
1100    pub token_type: String,
1101}
1102
1103impl std::fmt::Debug for CreateApiKeyResponse {
1104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1105        let mut d = f.debug_struct("CreateApiKeyResponse");
1106        d.field("api_key", &crate::utils::redact::redacted(&self.api_key));
1107        d.field("token_type", &self.token_type);
1108        d.finish()
1109    }
1110}
1111
1112/// POST /api-keys – create an API key (requires authentication)
1113pub async fn create_api_key(
1114    State(state): State<ApiState>,
1115    headers: HeaderMap,
1116) -> ApiResponse<CreateApiKeyResponse> {
1117    // Require a valid Bearer token; reject unauthenticated requests with 401.
1118    let token = match crate::api::extract_bearer_token(&headers) {
1119        Some(t) => t,
1120        None => return ApiResponse::unauthorized_typed(),
1121    };
1122
1123    // Validate the token and extract the caller's identity.
1124    let auth_token = match crate::api::validate_api_token(&state.auth_framework, &token).await {
1125        Ok(t) => t,
1126        Err(_) => return ApiResponse::unauthorized_typed(),
1127    };
1128
1129    // Create an API key scoped to the authenticated user.
1130    match state
1131        .auth_framework
1132        .create_api_key(&auth_token.user_id, None)
1133        .await
1134    {
1135        Ok(api_key) => ApiResponse::success(CreateApiKeyResponse {
1136            api_key,
1137            token_type: "ApiKey".to_string(),
1138        }),
1139        Err(e) => {
1140            tracing::error!(
1141                "Failed to create API key for user {}: {}",
1142                auth_token.user_id,
1143                e
1144            );
1145            ApiResponse::internal_error_typed()
1146        }
1147    }
1148}
1149
1150#[cfg(test)]
1151mod tests {
1152    use super::*;
1153    use axum::http::HeaderMap;
1154
1155    #[test]
1156    fn test_login_risk_low_normal_request() {
1157        let mut headers = HeaderMap::new();
1158        headers.insert(
1159            "user-agent",
1160            "Mozilla/5.0 (Windows NT 10.0; Win64; x64)".parse().unwrap(),
1161        );
1162        let (level, warnings) = login_risk_level(&headers);
1163        assert_eq!(level, "low");
1164        assert!(warnings.is_empty());
1165    }
1166
1167    #[test]
1168    fn test_login_risk_high_no_user_agent() {
1169        let headers = HeaderMap::new();
1170        let (level, warnings) = login_risk_level(&headers);
1171        assert_eq!(level, "high");
1172        assert!(!warnings.is_empty());
1173    }
1174
1175    #[test]
1176    fn test_login_risk_tor_browser() {
1177        let mut headers = HeaderMap::new();
1178        headers.insert("user-agent", "Mozilla/5.0 (Tor Browser)".parse().unwrap());
1179        let (level, warnings) = login_risk_level(&headers);
1180        // Tor alone is 40 points → "high"
1181        assert!(level == "high" || level == "critical");
1182        assert!(warnings.iter().any(|w| w.contains("Tor")));
1183    }
1184
1185    #[test]
1186    fn test_login_risk_proxy_hops() {
1187        let mut headers = HeaderMap::new();
1188        headers.insert("user-agent", "Mozilla/5.0".parse().unwrap());
1189        headers.insert("x-forwarded-for", "1.2.3.4, 5.6.7.8".parse().unwrap());
1190        let (level, warnings) = login_risk_level(&headers);
1191        assert_eq!(level, "medium");
1192        assert!(warnings.iter().any(|w| w.contains("proxy")));
1193    }
1194
1195    #[test]
1196    fn test_login_request_deserialization() {
1197        let json = r#"{"username":"alice","password":"secret"}"#;
1198        let req: LoginRequest = serde_json::from_str(json).unwrap();
1199        assert_eq!(req.username, "alice");
1200        assert_eq!(req.password, "secret");
1201        assert!(!req.remember_me);
1202        assert!(req.challenge_id.is_none());
1203        assert!(req.mfa_code.is_none());
1204    }
1205
1206    #[test]
1207    fn test_login_response_serialization() {
1208        let resp = LoginResponse {
1209            access_token: "at".into(),
1210            refresh_token: "rt".into(),
1211            token_type: "Bearer".into(),
1212            expires_in: 3600,
1213            user: LoginUserInfo {
1214                id: "uid".into(),
1215                username: "alice".into(),
1216                roles: vec!["user".into()],
1217                permissions: vec![],
1218            },
1219            login_risk_level: "low".into(),
1220            security_warnings: vec![],
1221        };
1222        let json = serde_json::to_value(&resp).unwrap();
1223        assert_eq!(json["token_type"], "Bearer");
1224        assert_eq!(json["expires_in"], 3600);
1225        assert_eq!(json["user"]["username"], "alice");
1226    }
1227
1228    #[test]
1229    fn test_register_request_deserialization() {
1230        let json = r#"{"username":"bob","password":"StrongP@ss1","email":"bob@example.com"}"#;
1231        let req: RegisterRequest = serde_json::from_str(json).unwrap();
1232        assert_eq!(req.username, "bob");
1233        assert_eq!(req.email, "bob@example.com");
1234    }
1235
1236    #[test]
1237    fn test_refresh_request_deserialization() {
1238        let json = r#"{"refresh_token":"some_token"}"#;
1239        let req: RefreshRequest = serde_json::from_str(json).unwrap();
1240        assert_eq!(req.refresh_token, "some_token");
1241    }
1242}