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                        user_json["email"] = serde_json::json!(new_email);
226                    }
227                    let name = match (&req.first_name, &req.last_name) {
228                        (Some(f), Some(l)) => Some(format!("{} {}", f, l)),
229                        (Some(f), None) => Some(f.clone()),
230                        (None, Some(l)) => Some(l.clone()),
231                        (None, None) => None,
232                    };
233                    if let Some(ref n) = name {
234                        user_json["name"] = serde_json::json!(n);
235                    }
236                    user_json["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
237
238                    if let Ok(serialized) = serde_json::to_vec(&user_json) {
239                        let _ = storage.store_kv(&user_key, &serialized, None).await;
240                    }
241
242                    tracing::info!("Profile updated for user: {}", auth_token.user_id);
243
244                    // Read back the stored values to build an accurate response.
245                    let (stored_username, stored_email, stored_created_at) = {
246                        let fresh = storage.get_kv(&user_key).await.ok().flatten();
247                        let j: serde_json::Value = fresh
248                            .and_then(|b| serde_json::from_slice(&b).ok())
249                            .unwrap_or_default();
250                        (
251                            j["username"].as_str().map(|s| s.to_string()),
252                            j["email"].as_str().unwrap_or("").to_string(),
253                            j["created_at"].as_str().unwrap_or("").to_string(),
254                        )
255                    };
256
257                    // Return updated profile response
258                    let updated_profile = UserProfile {
259                        id: auth_token.user_id.clone(),
260                        username: stored_username
261                            .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
262                        email: stored_email,
263                        first_name: req.first_name,
264                        last_name: req.last_name,
265                        roles: auth_token.roles,
266                        permissions: auth_token.permissions,
267                        mfa_enabled: check_user_mfa_status(
268                            &state.auth_framework,
269                            &auth_token.user_id,
270                        )
271                        .await,
272                        email_verified: user_json["email_verified"].as_bool().unwrap_or(false),
273                        created_at: stored_created_at,
274                        updated_at: user_json["updated_at"].as_str().unwrap_or("").to_string(),
275                    };
276
277                    ApiResponse::success(updated_profile)
278                }
279                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
280            }
281        }
282        None => ApiResponse::<UserProfile>::unauthorized_typed(),
283    }
284}
285
286/// `POST /users/change-password` — change the authenticated user's password.
287///
288/// The current password must be verified before the new one is accepted.
289pub async fn change_password(
290    State(state): State<ApiState>,
291    headers: HeaderMap,
292    Json(req): Json<ChangePasswordRequest>,
293) -> ApiResponse<()> {
294    if req.current_password.is_empty() || req.new_password.is_empty() {
295        return ApiResponse::validation_error("Current password and new password are required");
296    }
297
298    // Enforce the same password complexity requirements as registration.
299    if let Err(e) = crate::utils::validation::validate_password(&req.new_password) {
300        return ApiResponse::validation_error_typed(format!("{e}"));
301    }
302
303    // Check new password against known data breaches (HIBP k-anonymity API)
304    match crate::utils::breach_check::is_password_breached(&req.new_password).await {
305        Ok(true) => {
306            return ApiResponse::validation_error(
307                "This password has appeared in a known data breach. Please choose a different password.",
308            );
309        }
310        Ok(false) => {}
311        Err(_) => {} // HIBP API unreachable; fail open
312    }
313
314    match extract_bearer_token(&headers) {
315        Some(token) => {
316            match validate_api_token(&state.auth_framework, &token).await {
317                Ok(auth_token) => {
318                    // Verify current password against stored hash
319                    match state
320                        .auth_framework
321                        .verify_user_password(&auth_token.user_id, &req.current_password)
322                        .await
323                    {
324                        Ok(true) => {}
325                        Ok(false) => {
326                            return ApiResponse::validation_error("Current password is incorrect");
327                        }
328                        Err(_) => {
329                            // Return the same generic message regardless of error type
330                            // to avoid distinguishing wrong-password from storage errors.
331                            return ApiResponse::validation_error("Current password is incorrect");
332                        }
333                    }
334
335                    // Get the username (update_user_password takes username)
336                    let username = match state
337                        .auth_framework
338                        .get_username_by_id(&auth_token.user_id)
339                        .await
340                    {
341                        Ok(u) => u,
342                        Err(e) => return ApiResponse::<()>::from(e),
343                    };
344
345                    match state
346                        .auth_framework
347                        .update_user_password(&username, &req.new_password)
348                        .await
349                    {
350                        Ok(()) => {
351                            tracing::info!("Password changed for user: {}", auth_token.user_id);
352                            ApiResponse::<()>::ok_with_message("Password changed successfully")
353                        }
354                        Err(e) => ApiResponse::<()>::from(e),
355                    }
356                }
357                Err(e) => ApiResponse::<()>::from(e),
358            }
359        }
360        None => ApiResponse::<()>::unauthorized(),
361    }
362}
363
364/// `GET /users/{user_id}/profile` — fetch another user's profile (admin only).
365pub async fn get_user_profile(
366    State(state): State<ApiState>,
367    headers: HeaderMap,
368    Path(user_id): Path<String>,
369) -> ApiResponse<UserProfile> {
370    match extract_bearer_token(&headers) {
371        Some(token) => {
372            match validate_api_token(&state.auth_framework, &token).await {
373                Ok(auth_token) => {
374                    if !auth_token.roles.contains("admin") {
375                        return ApiResponse::<UserProfile>::forbidden_typed();
376                    }
377
378                    match state.auth_framework.get_user_profile(&user_id).await {
379                        Ok(user_profile) => {
380                            // Load roles from the canonical user record (same
381                            // pattern as validate_api_token) rather than hard-coding [].
382                            // Load both roles and permissions from the canonical user
383                            // record so the admin profile view stays consistent with
384                            // what validate_api_token returns for the user's own token.
385                            let user_kv_bytes = {
386                                let uk = format!("user:{}", user_id);
387                                state
388                                    .auth_framework
389                                    .storage()
390                                    .get_kv(&uk)
391                                    .await
392                                    .ok()
393                                    .flatten()
394                            };
395                            let user_kv_json: serde_json::Value = user_kv_bytes
396                                .as_deref()
397                                .and_then(|b| serde_json::from_slice(b).ok())
398                                .unwrap_or_default();
399
400                            let profile_roles: Vec<String> = user_kv_json["roles"]
401                                .as_array()
402                                .map(|a| {
403                                    a.iter()
404                                        .filter_map(|v| v.as_str().map(String::from))
405                                        .collect()
406                                })
407                                .unwrap_or_default();
408
409                            let profile_permissions: Vec<String> = user_kv_json["permissions"]
410                                .as_array()
411                                .map(|a| {
412                                    a.iter()
413                                        .filter_map(|v| v.as_str().map(String::from))
414                                        .collect()
415                                })
416                                .unwrap_or_default();
417
418                            let (first_name, last_name) = if let Some(name) = &user_profile.name {
419                                let parts: Vec<&str> = name.split_whitespace().collect();
420                                if parts.len() >= 2 {
421                                    (Some(parts[0].to_string()), Some(parts[1..].join(" ")))
422                                } else if parts.len() == 1 {
423                                    (Some(parts[0].to_string()), None)
424                                } else {
425                                    (None, None)
426                                }
427                            } else {
428                                (None, None)
429                            };
430
431                            let profile = UserProfile {
432                                id: user_id.clone(),
433                                username: user_profile
434                                    .username
435                                    .unwrap_or_else(|| format!("user_{}", user_id)),
436                                email: user_profile.email.unwrap_or_default(),
437                                first_name,
438                                last_name,
439                                roles: profile_roles.into(),
440                                permissions: profile_permissions.into(),
441                                mfa_enabled: user_profile
442                                    .additional_data
443                                    .get("mfa_enabled")
444                                    .and_then(|v| v.as_bool())
445                                    .unwrap_or(false),
446                                email_verified: user_kv_json["email_verified"]
447                                    .as_bool()
448                                    .unwrap_or(false),
449                                created_at: user_profile
450                                    .additional_data
451                                    .get("created_at")
452                                    .and_then(|v| v.as_str())
453                                    .unwrap_or("")
454                                    .to_string(),
455                                updated_at: user_profile
456                                    .additional_data
457                                    .get("updated_at")
458                                    .and_then(|v| v.as_str())
459                                    .unwrap_or("")
460                                    .to_string(),
461                            };
462                            ApiResponse::success(profile)
463                        }
464                        Err(e) => {
465                            let error_response = ApiResponse::<()>::from(e);
466                            ApiResponse::<UserProfile> {
467                                success: error_response.success,
468                                data: None,
469                                error: error_response.error,
470                                message: error_response.message,
471                            }
472                        }
473                    }
474                }
475                Err(_e) => ApiResponse::error_typed("USER_ERROR", "User operation failed"),
476            }
477        }
478        None => ApiResponse::<UserProfile>::unauthorized_typed(),
479    }
480}
481
482/// `GET /users/sessions` — list the authenticated user's active sessions.
483pub async fn get_sessions(
484    State(state): State<ApiState>,
485    headers: HeaderMap,
486) -> ApiResponse<Vec<SessionInfo>> {
487    match extract_bearer_token(&headers) {
488        Some(token) => match validate_api_token(&state.auth_framework, &token).await {
489            Ok(auth_token) => {
490                let storage = state.auth_framework.storage();
491                match storage.list_user_sessions(&auth_token.user_id).await {
492                    Ok(sessions) => {
493                        let session_list: Vec<SessionInfo> = sessions
494                            .into_iter()
495                            .filter(|s| !s.is_expired())
496                            .map(|s| SessionInfo {
497                                id: s.session_id.clone(),
498                                device: s.user_agent.unwrap_or_default(),
499                                location: String::new(),
500                                ip_address: s.ip_address.unwrap_or_default(),
501                                created_at: s.created_at.to_rfc3339(),
502                                last_active: s.last_activity.to_rfc3339(),
503                                is_current: false,
504                            })
505                            .collect();
506                        ApiResponse::success(session_list)
507                    }
508                    Err(_e) => {
509                        ApiResponse::error_typed("SESSION_ERROR", "Failed to retrieve sessions")
510                    }
511                }
512            }
513            Err(_e) => ApiResponse::error_typed("USER_ERROR", "Session operation failed"),
514        },
515        None => ApiResponse::<Vec<SessionInfo>>::unauthorized_typed(),
516    }
517}
518
519/// Summary of an active browser/device session.
520#[derive(Debug, Serialize)]
521pub struct SessionInfo {
522    /// Unique session identifier.
523    pub id: String,
524    /// User-Agent string from the session’s originating request.
525    pub device: String,
526    /// Approximate geo-location derived from the client IP (may be empty).
527    pub location: String,
528    /// Client IP address recorded at session creation.
529    pub ip_address: String,
530    /// ISO-8601 timestamp of session creation.
531    pub created_at: String,
532    /// ISO-8601 timestamp of the most recent request in this session.
533    pub last_active: String,
534    /// `true` if this session belongs to the current request.
535    pub is_current: bool,
536}
537
538/// `DELETE /users/sessions/{session_id}` — revoke a specific session.
539///
540/// Only the session owner can revoke it; attempting to revoke another user's
541/// session returns `FORBIDDEN`.
542pub async fn revoke_session(
543    State(state): State<ApiState>,
544    headers: HeaderMap,
545    Path(session_id): Path<String>,
546) -> ApiResponse<()> {
547    match extract_bearer_token(&headers) {
548        Some(token) => {
549            match validate_api_token(&state.auth_framework, &token).await {
550                Ok(auth_token) => {
551                    let storage = state.auth_framework.storage();
552
553                    // SECURITY: Verify that the session belongs to the authenticated user
554                    // before deleting it; without this check any authenticated user can
555                    // terminate any other user's session by guessing the session_id.
556                    match storage.get_session(&session_id).await {
557                        Ok(Some(ref session)) if session.user_id == auth_token.user_id => {}
558                        Ok(Some(_)) => {
559                            return ApiResponse::<()>::error_typed(
560                                "FORBIDDEN",
561                                "You do not have permission to revoke this session",
562                            );
563                        }
564                        Ok(None) => {
565                            return ApiResponse::<()>::error_typed(
566                                "NOT_FOUND",
567                                "Session not found",
568                            );
569                        }
570                        Err(e) => return ApiResponse::<()>::from(e),
571                    }
572
573                    match storage.delete_session(&session_id).await {
574                        Ok(()) => {
575                            tracing::info!(
576                                "Revoked session: {}",
577                                crate::utils::redact::fingerprint(&session_id)
578                            );
579                            ApiResponse::<()>::ok_with_message("Session revoked successfully")
580                        }
581                        Err(e) => ApiResponse::<()>::from(e),
582                    }
583                }
584                Err(e) => ApiResponse::<()>::from(e),
585            }
586        }
587        None => ApiResponse::<()>::unauthorized(),
588    }
589}
590
591/// Helper function for MFA status integration.
592///
593/// Delegates to the canonical implementation in [`crate::api::mfa`] which
594/// checks the `mfa_enabled:{user_id}` KV key written by the MFA verification
595/// flow.
596async fn check_user_mfa_status(
597    auth_framework: &std::sync::Arc<crate::AuthFramework>,
598    user_id: &str,
599) -> bool {
600    crate::api::mfa::check_user_mfa_status(auth_framework, user_id).await
601}