Skip to main content

auth_framework/api/
auth.rs

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