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