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