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