Skip to main content

auth_framework/api/
users.rs

1//! User Management API Endpoints
2//!
3//! Handles user profile, password changes, and related user operations
4
5use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
6use axum::{
7    Json,
8    extract::{Path, State},
9    http::HeaderMap,
10};
11use serde::{Deserialize, Serialize};
12
13/// Full user profile returned by the `/users/profile` and `/users/:id` endpoints.
14#[derive(Debug, Serialize)]
15pub struct UserProfile {
16    /// Unique user identifier.
17    pub id: String,
18    pub username: String,
19    pub email: String,
20    pub first_name: Option<String>,
21    pub last_name: Option<String>,
22    /// Role names assigned to this user.
23    pub roles: crate::types::Roles,
24    /// Effective permissions derived from roles and direct grants.
25    pub permissions: crate::types::Permissions,
26    /// Whether multi-factor authentication is enrolled.
27    pub mfa_enabled: bool,
28    /// Whether the user's email address has been verified.
29    pub email_verified: bool,
30    /// ISO-8601 creation timestamp.
31    pub created_at: String,
32    /// ISO-8601 last-modification timestamp.
33    pub updated_at: String,
34}
35
36/// Profile update request. Only the supplied fields are modified.
37#[derive(Debug, Deserialize)]
38pub struct UpdateProfileRequest {
39    #[serde(default)]
40    pub first_name: Option<String>,
41    #[serde(default)]
42    pub last_name: Option<String>,
43    /// New email address (must not already be registered to another user).
44    #[serde(default)]
45    pub email: Option<String>,
46}
47
48/// Password change request.
49///
50/// Both fields are required.  The server will verify `current_password` before
51/// applying the change, and will validate `new_password` against the same
52/// complexity rules used during registration.
53#[derive(Deserialize)]
54pub struct ChangePasswordRequest {
55    pub current_password: String,
56    pub new_password: String,
57}
58
59impl std::fmt::Debug for ChangePasswordRequest {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        let mut d = f.debug_struct("ChangePasswordRequest");
62        d.field(
63            "current_password",
64            &crate::utils::redact::redacted(&self.current_password),
65        );
66        d.field(
67            "new_password",
68            &crate::utils::redact::redacted(&self.new_password),
69        );
70        d.finish()
71    }
72}
73
74/// `GET /users/profile` — fetch the authenticated user's own profile.
75pub async fn get_profile(
76    State(state): State<ApiState>,
77    headers: HeaderMap,
78) -> ApiResponse<UserProfile> {
79    match extract_bearer_token(&headers) {
80        Some(token) => {
81            match validate_api_token(&state.auth_framework, &token).await {
82                Ok(auth_token) => {
83                    // Fetch actual user profile from storage
84                    match state
85                        .auth_framework
86                        .get_user_profile(&auth_token.user_id)
87                        .await
88                    {
89                        Ok(user_profile) => {
90                            // Check MFA status from AuthFramework
91                            let mfa_enabled =
92                                check_user_mfa_status(&state.auth_framework, &auth_token.user_id)
93                                    .await;
94
95                            // Extract first_name and last_name from the name field if available
96                            let (first_name, last_name) = if let Some(name) = &user_profile.name {
97                                let parts: Vec<&str> = name.split_whitespace().collect();
98                                if parts.len() >= 2 {
99                                    (Some(parts[0].to_string()), Some(parts[1..].join(" ")))
100                                } else if parts.len() == 1 {
101                                    (Some(parts[0].to_string()), None)
102                                } else {
103                                    (None, None)
104                                }
105                            } else {
106                                (None, None)
107                            };
108
109                            let profile = UserProfile {
110                                id: auth_token.user_id.clone(),
111                                username: user_profile
112                                    .username
113                                    .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
114                                email: user_profile.email.unwrap_or_default(),
115                                first_name,
116                                last_name,
117                                roles: auth_token.roles,
118                                permissions: auth_token.permissions,
119                                mfa_enabled,
120                                email_verified: user_profile.email_verified.unwrap_or(false),
121                                created_at: user_profile
122                                    .additional_data
123                                    .get("created_at")
124                                    .and_then(|v| v.as_str())
125                                    .unwrap_or("")
126                                    .to_string(),
127                                updated_at: user_profile
128                                    .additional_data
129                                    .get("updated_at")
130                                    .and_then(|v| v.as_str())
131                                    .unwrap_or("")
132                                    .to_string(),
133                            };
134
135                            ApiResponse::success(profile)
136                        }
137                        Err(e) => {
138                            tracing::warn!(
139                                "Failed to fetch user profile for user {}: {}",
140                                auth_token.user_id,
141                                e
142                            );
143                            // M-7: Return an error instead of a fabricated profile so callers
144                            // cannot mistake placeholder data for real user information.
145                            ApiResponse::error_typed(
146                                "PROFILE_UNAVAILABLE",
147                                "User profile could not be retrieved; please try again",
148                            )
149                        }
150                    }
151                }
152                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
153            }
154        }
155        None => ApiResponse::<UserProfile>::unauthorized_typed(),
156    }
157}
158
159/// `PUT /users/profile` — update the authenticated user's profile fields.
160pub async fn update_profile(
161    State(state): State<ApiState>,
162    headers: HeaderMap,
163    Json(req): Json<UpdateProfileRequest>,
164) -> ApiResponse<UserProfile> {
165    match extract_bearer_token(&headers) {
166        Some(token) => {
167            match validate_api_token(&state.auth_framework, &token).await {
168                Ok(auth_token) => {
169                    // Validate email format before storing to ensure consistency with
170                    // the public registration endpoint.
171                    if let Some(ref email) = req.email
172                        && crate::utils::validation::validate_email(email).is_err()
173                    {
174                        return ApiResponse::validation_error_typed("Invalid email format");
175                    }
176
177                    // Enforce length limits on name fields to prevent storage abuse.
178                    if req.first_name.as_deref().is_some_and(|n| n.len() > 100) {
179                        return ApiResponse::validation_error_typed(
180                            "First name must be 100 characters or fewer",
181                        );
182                    }
183                    if req.last_name.as_deref().is_some_and(|n| n.len() > 100) {
184                        return ApiResponse::validation_error_typed(
185                            "Last name must be 100 characters or fewer",
186                        );
187                    }
188
189                    // Persist updated profile to storage
190                    let storage = state.auth_framework.storage();
191                    let user_key = format!("user:{}", auth_token.user_id);
192                    let current_data = storage.get_kv(&user_key).await.ok().flatten();
193                    let mut user_json: serde_json::Value = current_data
194                        .and_then(|b| serde_json::from_slice(&b).ok())
195                        .unwrap_or_else(|| serde_json::json!({}));
196
197                    // Maintain the email reverse-lookup index so duplicate-email
198                    // detection at registration keeps working after an email change.
199                    if let Some(ref new_email) = req.email {
200                        let old_email = user_json["email"].as_str().unwrap_or("").to_string();
201                        if old_email != *new_email {
202                            // SECURITY: Verify the new email is not already claimed
203                            // by another user before updating the index.
204                            let new_email_key = format!("user:email:{}", new_email);
205                            if let Ok(Some(existing)) = storage.get_kv(&new_email_key).await {
206                                let owner = String::from_utf8_lossy(&existing).to_string();
207                                if owner != auth_token.user_id {
208                                    return ApiResponse::error_typed(
209                                        "CONFLICT",
210                                        "Email address is already in use",
211                                    );
212                                }
213                            }
214                            // Delete the old mapping.
215                            if !old_email.is_empty() {
216                                let _ = storage
217                                    .delete_kv(&format!("user:email:{}", old_email))
218                                    .await;
219                            }
220                            // Write the new email → user_id mapping.
221                            let _ = storage
222                                .store_kv(&new_email_key, auth_token.user_id.as_bytes(), None)
223                                .await;
224                        }
225                        if user_json["email"].as_str() != Some(new_email.as_str()) {
226                            // A new address has not been proven yet.
227                            user_json["email_verified"] = serde_json::json!(false);
228                        }
229                        user_json["email"] = serde_json::json!(new_email);
230                    }
231                    let name = match (&req.first_name, &req.last_name) {
232                        (Some(f), Some(l)) => Some(format!("{} {}", f, l)),
233                        (Some(f), None) => Some(f.clone()),
234                        (None, Some(l)) => Some(l.clone()),
235                        (None, None) => None,
236                    };
237                    if let Some(ref n) = name {
238                        user_json["name"] = serde_json::json!(n);
239                    }
240                    user_json["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
241
242                    if let Ok(serialized) = serde_json::to_vec(&user_json) {
243                        let _ = storage.store_kv(&user_key, &serialized, None).await;
244                    }
245
246                    tracing::info!("Profile updated for user: {}", auth_token.user_id);
247
248                    // Read back the stored values to build an accurate response.
249                    let (stored_username, stored_email, stored_created_at) = {
250                        let fresh = storage.get_kv(&user_key).await.ok().flatten();
251                        let j: serde_json::Value = fresh
252                            .and_then(|b| serde_json::from_slice(&b).ok())
253                            .unwrap_or_default();
254                        (
255                            j["username"].as_str().map(|s| s.to_string()),
256                            j["email"].as_str().unwrap_or("").to_string(),
257                            j["created_at"].as_str().unwrap_or("").to_string(),
258                        )
259                    };
260
261                    // Return updated profile response
262                    let updated_profile = UserProfile {
263                        id: auth_token.user_id.clone(),
264                        username: stored_username
265                            .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
266                        email: stored_email,
267                        first_name: req.first_name,
268                        last_name: req.last_name,
269                        roles: auth_token.roles,
270                        permissions: auth_token.permissions,
271                        mfa_enabled: check_user_mfa_status(
272                            &state.auth_framework,
273                            &auth_token.user_id,
274                        )
275                        .await,
276                        email_verified: user_json["email_verified"].as_bool().unwrap_or(false),
277                        created_at: stored_created_at,
278                        updated_at: user_json["updated_at"].as_str().unwrap_or("").to_string(),
279                    };
280
281                    ApiResponse::success(updated_profile)
282                }
283                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
284            }
285        }
286        None => ApiResponse::<UserProfile>::unauthorized_typed(),
287    }
288}
289
290/// `POST /users/change-password` — change the authenticated user's password.
291///
292/// The current password must be verified before the new one is accepted.
293pub async fn change_password(
294    State(state): State<ApiState>,
295    headers: HeaderMap,
296    Json(req): Json<ChangePasswordRequest>,
297) -> ApiResponse<()> {
298    if req.current_password.is_empty() || req.new_password.is_empty() {
299        return ApiResponse::validation_error("Current password and new password are required");
300    }
301
302    // Enforce the same password complexity requirements as registration.
303    if let Err(e) = crate::utils::validation::validate_password(&req.new_password) {
304        return ApiResponse::validation_error_typed(format!("{e}"));
305    }
306
307    // Check new password against known data breaches (HIBP k-anonymity API)
308    match crate::utils::breach_check::is_password_breached(&req.new_password).await {
309        Ok(true) => {
310            return ApiResponse::validation_error(
311                "This password has appeared in a known data breach. Please choose a different password.",
312            );
313        }
314        Ok(false) => {}
315        Err(_) => {} // HIBP API unreachable; fail open
316    }
317
318    match extract_bearer_token(&headers) {
319        Some(token) => {
320            match validate_api_token(&state.auth_framework, &token).await {
321                Ok(auth_token) => {
322                    // Verify current password against stored hash
323                    match state
324                        .auth_framework
325                        .verify_user_password(&auth_token.user_id, &req.current_password)
326                        .await
327                    {
328                        Ok(true) => {}
329                        Ok(false) => {
330                            return ApiResponse::validation_error("Current password is incorrect");
331                        }
332                        Err(_) => {
333                            // Return the same generic message regardless of error type
334                            // to avoid distinguishing wrong-password from storage errors.
335                            return ApiResponse::validation_error("Current password is incorrect");
336                        }
337                    }
338
339                    // Get the username (update_user_password takes username)
340                    let username = match state
341                        .auth_framework
342                        .get_username_by_id(&auth_token.user_id)
343                        .await
344                    {
345                        Ok(u) => u,
346                        Err(e) => return ApiResponse::<()>::from(e),
347                    };
348
349                    match state
350                        .auth_framework
351                        .update_user_password(&username, &req.new_password)
352                        .await
353                    {
354                        Ok(()) => {
355                            tracing::info!("Password changed for user: {}", auth_token.user_id);
356                            ApiResponse::<()>::ok_with_message("Password changed successfully")
357                        }
358                        Err(e) => ApiResponse::<()>::from(e),
359                    }
360                }
361                Err(e) => ApiResponse::<()>::from(e),
362            }
363        }
364        None => ApiResponse::<()>::unauthorized(),
365    }
366}
367
368/// `GET /users/{user_id}/profile` — fetch another user's profile (admin only).
369pub async fn get_user_profile(
370    State(state): State<ApiState>,
371    headers: HeaderMap,
372    Path(user_id): Path<String>,
373) -> ApiResponse<UserProfile> {
374    match extract_bearer_token(&headers) {
375        Some(token) => {
376            match validate_api_token(&state.auth_framework, &token).await {
377                Ok(auth_token) => {
378                    if !auth_token.roles.contains("admin") {
379                        return ApiResponse::<UserProfile>::forbidden_typed();
380                    }
381
382                    match state.auth_framework.get_user_profile(&user_id).await {
383                        Ok(user_profile) => {
384                            // Load roles from the canonical user record (same
385                            // pattern as validate_api_token) rather than hard-coding [].
386                            // Load both roles and permissions from the canonical user
387                            // record so the admin profile view stays consistent with
388                            // what validate_api_token returns for the user's own token.
389                            let user_kv_bytes = {
390                                let uk = format!("user:{}", user_id);
391                                state
392                                    .auth_framework
393                                    .storage()
394                                    .get_kv(&uk)
395                                    .await
396                                    .ok()
397                                    .flatten()
398                            };
399                            let user_kv_json: serde_json::Value = user_kv_bytes
400                                .as_deref()
401                                .and_then(|b| serde_json::from_slice(b).ok())
402                                .unwrap_or_default();
403
404                            let profile_roles: Vec<String> = user_kv_json["roles"]
405                                .as_array()
406                                .map(|a| {
407                                    a.iter()
408                                        .filter_map(|v| v.as_str().map(String::from))
409                                        .collect()
410                                })
411                                .unwrap_or_default();
412
413                            let profile_permissions: Vec<String> = user_kv_json["permissions"]
414                                .as_array()
415                                .map(|a| {
416                                    a.iter()
417                                        .filter_map(|v| v.as_str().map(String::from))
418                                        .collect()
419                                })
420                                .unwrap_or_default();
421
422                            let (first_name, last_name) = if let Some(name) = &user_profile.name {
423                                let parts: Vec<&str> = name.split_whitespace().collect();
424                                if parts.len() >= 2 {
425                                    (Some(parts[0].to_string()), Some(parts[1..].join(" ")))
426                                } else if parts.len() == 1 {
427                                    (Some(parts[0].to_string()), None)
428                                } else {
429                                    (None, None)
430                                }
431                            } else {
432                                (None, None)
433                            };
434
435                            let profile = UserProfile {
436                                id: user_id.clone(),
437                                username: user_profile
438                                    .username
439                                    .unwrap_or_else(|| format!("user_{}", user_id)),
440                                email: user_profile.email.unwrap_or_default(),
441                                first_name,
442                                last_name,
443                                roles: profile_roles.into(),
444                                permissions: profile_permissions.into(),
445                                mfa_enabled: user_profile
446                                    .additional_data
447                                    .get("mfa_enabled")
448                                    .and_then(|v| v.as_bool())
449                                    .unwrap_or(false),
450                                email_verified: user_kv_json["email_verified"]
451                                    .as_bool()
452                                    .unwrap_or(false),
453                                created_at: user_profile
454                                    .additional_data
455                                    .get("created_at")
456                                    .and_then(|v| v.as_str())
457                                    .unwrap_or("")
458                                    .to_string(),
459                                updated_at: user_profile
460                                    .additional_data
461                                    .get("updated_at")
462                                    .and_then(|v| v.as_str())
463                                    .unwrap_or("")
464                                    .to_string(),
465                            };
466                            ApiResponse::success(profile)
467                        }
468                        Err(e) => {
469                            let error_response = ApiResponse::<()>::from(e);
470                            ApiResponse::<UserProfile> {
471                                success: error_response.success,
472                                data: None,
473                                error: error_response.error,
474                                message: error_response.message,
475                            }
476                        }
477                    }
478                }
479                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
480            }
481        }
482        None => ApiResponse::<UserProfile>::unauthorized_typed(),
483    }
484}
485
486/// `GET /users/sessions` — list the authenticated user's active sessions.
487pub async fn get_sessions(
488    State(state): State<ApiState>,
489    headers: HeaderMap,
490) -> ApiResponse<Vec<SessionInfo>> {
491    match extract_bearer_token(&headers) {
492        Some(token) => match validate_api_token(&state.auth_framework, &token).await {
493            Ok(auth_token) => {
494                let storage = state.auth_framework.storage();
495                match storage.list_user_sessions(&auth_token.user_id).await {
496                    Ok(sessions) => {
497                        let session_list: Vec<SessionInfo> = sessions
498                            .into_iter()
499                            .filter(|s| !s.is_expired())
500                            .map(|s| SessionInfo {
501                                id: s.session_id.clone(),
502                                device: s.user_agent.unwrap_or_default(),
503                                location: String::new(),
504                                ip_address: s.ip_address.unwrap_or_default(),
505                                created_at: s.created_at.to_rfc3339(),
506                                last_active: s.last_activity.to_rfc3339(),
507                                is_current: false,
508                            })
509                            .collect();
510                        ApiResponse::success(session_list)
511                    }
512                    Err(_e) => {
513                        ApiResponse::error_typed("SESSION_ERROR", "Failed to retrieve sessions")
514                    }
515                }
516            }
517            Err(_e) => ApiResponse::error_typed("USER_ERROR", "Session operation failed"),
518        },
519        None => ApiResponse::<Vec<SessionInfo>>::unauthorized_typed(),
520    }
521}
522
523/// Summary of an active browser/device session.
524#[derive(Debug, Serialize)]
525pub struct SessionInfo {
526    /// Unique session identifier.
527    pub id: String,
528    /// User-Agent string from the session’s originating request.
529    pub device: String,
530    /// Approximate geo-location derived from the client IP (may be empty).
531    pub location: String,
532    /// Client IP address recorded at session creation.
533    pub ip_address: String,
534    /// ISO-8601 timestamp of session creation.
535    pub created_at: String,
536    /// ISO-8601 timestamp of the most recent request in this session.
537    pub last_active: String,
538    /// `true` if this session belongs to the current request.
539    pub is_current: bool,
540}
541
542/// `DELETE /users/sessions/{session_id}` — revoke a specific session.
543///
544/// Only the session owner can revoke it; attempting to revoke another user's
545/// session returns `FORBIDDEN`.
546pub async fn revoke_session(
547    State(state): State<ApiState>,
548    headers: HeaderMap,
549    Path(session_id): Path<String>,
550) -> ApiResponse<()> {
551    match extract_bearer_token(&headers) {
552        Some(token) => {
553            match validate_api_token(&state.auth_framework, &token).await {
554                Ok(auth_token) => {
555                    let storage = state.auth_framework.storage();
556
557                    // SECURITY: Verify that the session belongs to the authenticated user
558                    // before deleting it; without this check any authenticated user can
559                    // terminate any other user's session by guessing the session_id.
560                    match storage.get_session(&session_id).await {
561                        Ok(Some(ref session)) if session.user_id == auth_token.user_id => {}
562                        Ok(Some(_)) => {
563                            return ApiResponse::<()>::error_typed(
564                                "FORBIDDEN",
565                                "You do not have permission to revoke this session",
566                            );
567                        }
568                        Ok(None) => {
569                            return ApiResponse::<()>::error_typed(
570                                "NOT_FOUND",
571                                "Session not found",
572                            );
573                        }
574                        Err(e) => return ApiResponse::<()>::from(e),
575                    }
576
577                    match storage.delete_session(&session_id).await {
578                        Ok(()) => {
579                            tracing::info!("Revoked session: {}", session_id);
580                            ApiResponse::<()>::ok_with_message("Session revoked successfully")
581                        }
582                        Err(e) => ApiResponse::<()>::from(e),
583                    }
584                }
585                Err(e) => ApiResponse::<()>::from(e),
586            }
587        }
588        None => ApiResponse::<()>::unauthorized(),
589    }
590}
591
592/// Helper function for MFA status integration.
593///
594/// Delegates to the canonical implementation in [`crate::api::mfa`] which
595/// checks the `mfa_enabled:{user_id}` KV key written by the MFA verification
596/// flow.
597async fn check_user_mfa_status(
598    auth_framework: &std::sync::Arc<crate::AuthFramework>,
599    user_id: &str,
600) -> bool {
601    crate::api::mfa::check_user_mfa_status(auth_framework, user_id).await
602}