normogen/backend/src/handlers/users.rs
goose eb2c2aa546
Some checks failed
Lint and Build / format (pull_request) Successful in 39s
Lint and Build / clippy (pull_request) Successful in 1m40s
Lint and Build / build (pull_request) Successful in 3m45s
Lint and Build / test (pull_request) Failing after 2m55s
feat: per-profile DEKs + multi-profile (Phase A2, #3)
Implements the 3-tier key model from the multi-person sharing ADR:
each account owns multiple profiles (a person or pet — a 'subject of
care'), and each profile has its own random AES-256-GCM DEK. All
health data is now encrypted under the active profile's DEK, not the
account-wide DEK. The account DEK wraps each profile DEK; the server
stores only opaque wrapped blobs.

Per the ADR: DB wipe, no migration (no real user data). This unblocks
Phase B (sharing) — there is now a per-profile key to wrap to a
recipient's X25519 public key.

Backend:
- Profile model: owner_account_id, kind (human/pet), relationship,
  wrapped_profile_dek + iv. ProfileRepository gains find_all_by_owner,
  find_by_profile_id_owned, update_profile, delete_profile — all
  ownership-scoped.
- Profile handlers: GET/POST /api/profiles, GET/PUT/DELETE
  /api/profiles/:id. Removed /api/profiles/me. Renamed users.rs
  get_profile/update_profile (the /api/users/me handlers) to
  get_account/update_account to resolve a name collision.
- Register accepts default_profile_* fields and auto-creates the self
  profile when the client provides a wrapped profile DEK.
- HealthStatistic + Appointment gain profile_id and ?profile_id=
  filtering (health stats previously had no profile binding).
- New profile_tests.rs: multi-profile CRUD + ownership isolation +
  register-with-default-profile. Fixed the zk health-stat test to
  send the now-required profile_id.

Frontend:
- crypto/keys.ts: generateProfileDek, wrapProfileDek, unwrapProfileDek
  + in-memory per-profile DEK store with an active-profile concept.
- useProfileStore rewritten: holds profiles[], activeProfileId;
  loadProfiles unwraps each profile DEK; create/update/delete. All 11
  encrypt/decrypt sites switched from getEncKey() to
  getActiveProfileDek(). load actions pass ?profile_id= so only the
  active profile's rows come back.
- ProfileEditor rewritten for the new store (edit active profile,
  create/delete). New ProfileSwitcher in the Dashboard AppBar.
- MedicationManager / AppointmentsManager use the active profile id
  instead of the hardcoded profile_<user_id>.
- 2 new crypto tests for per-profile DEK isolation; updated store +
  component tests for the active-profile-DEK model.

Verification: backend cargo build/clippy/fmt green, tests compile
(integration tests run in CI — Mongo is fixed there). Frontend
tsc clean, 30/30 tests pass.

Closes nothing yet (Phase B/C/D remain). Refs #3.
2026-07-18 23:45:01 -03:00

455 lines
13 KiB
Rust

use axum::{extract::State, http::StatusCode, response::IntoResponse, Extension, Json};
use mongodb::bson::oid::ObjectId;
use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::{
auth::jwt::Claims, config::AppState, middleware::ClientIp, models::audit_log::AuditEventType,
models::user::User,
};
#[derive(Debug, Serialize)]
pub struct UserProfileResponse {
pub id: String,
pub email: String,
pub username: String,
pub created_at: i64,
pub last_active: i64,
pub email_verified: bool,
}
impl TryFrom<User> for UserProfileResponse {
type Error = anyhow::Error;
fn try_from(user: User) -> Result<Self, Self::Error> {
Ok(Self {
id: user.id.map(|id| id.to_string()).unwrap_or_default(),
email: user.email,
username: user.username,
created_at: user.created_at.timestamp_millis(),
last_active: user.last_active.timestamp_millis(),
email_verified: user.email_verified,
})
}
}
#[derive(Debug, Deserialize, Validate)]
pub struct UpdateProfileRequest {
#[validate(length(min = 1))]
pub username: Option<String>,
}
pub async fn get_account(
State(state): State<AppState>,
Extension(claims): Extension<Claims>,
) -> impl IntoResponse {
let user_id = match ObjectId::parse_str(&claims.sub) {
Ok(oid) => oid,
Err(_) => {
return (
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({ "error": "invalid token" })),
)
.into_response()
}
};
match state.db.find_user_by_id(&user_id).await {
Ok(Some(user)) => {
let response: UserProfileResponse = user.try_into().unwrap();
(StatusCode::OK, Json(response)).into_response()
}
Ok(None) => (
StatusCode::NOT_FOUND,
Json(serde_json::json!({
"error": "user not found"
})),
)
.into_response(),
Err(e) => {
tracing::error!("Failed to get user profile: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "failed to get profile"
})),
)
.into_response()
}
}
}
pub async fn update_account(
State(state): State<AppState>,
Extension(claims): Extension<Claims>,
Json(req): Json<UpdateProfileRequest>,
) -> impl IntoResponse {
if let Err(errors) = req.validate() {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"error": "validation failed",
"details": errors.to_string()
})),
)
.into_response();
}
let user_id = match ObjectId::parse_str(&claims.sub) {
Ok(oid) => oid,
Err(_) => {
return (
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({ "error": "invalid token" })),
)
.into_response()
}
};
let mut user = match state.db.find_user_by_id(&user_id).await {
Ok(Some(u)) => u,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(serde_json::json!({
"error": "user not found"
})),
)
.into_response()
}
Err(e) => {
tracing::error!("Failed to get user: {}", e);
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "database error"
})),
)
.into_response();
}
};
if let Some(username) = req.username {
user.username = username;
}
match state.db.update_user(&user).await {
Ok(_) => {
let response: UserProfileResponse = user.try_into().unwrap();
(StatusCode::OK, Json(response)).into_response()
}
Err(e) => {
tracing::error!("Failed to update user: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "failed to update profile"
})),
)
.into_response()
}
}
}
pub async fn delete_account(
State(state): State<AppState>,
Extension(claims): Extension<Claims>,
) -> impl IntoResponse {
let user_id = match ObjectId::parse_str(&claims.sub) {
Ok(oid) => oid,
Err(_) => {
return (
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({ "error": "invalid token" })),
)
.into_response()
}
};
match state.db.delete_user(&user_id).await {
Ok(_) => (StatusCode::NO_CONTENT, ()).into_response(),
Err(e) => {
tracing::error!("Failed to delete user: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "failed to delete account"
})),
)
.into_response()
}
}
}
#[derive(Debug, Deserialize, Validate)]
pub struct ChangePasswordRequest {
#[validate(length(min = 8))]
pub current_password: String,
#[validate(length(min = 8))]
pub new_password: String,
/// Re-wrapped DEK under the new password KEK (zero-knowledge: the client
/// re-wraps the DEK before sending).
pub new_wrapped_dek: Option<String>,
pub new_wrapped_dek_iv: Option<String>,
}
pub async fn change_password(
State(state): State<AppState>,
Extension(claims): Extension<Claims>,
Extension(client_ip): Extension<ClientIp>,
Json(req): Json<ChangePasswordRequest>,
) -> impl IntoResponse {
if let Err(errors) = req.validate() {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"error": "validation failed",
"details": errors.to_string()
})),
)
.into_response();
}
// The middleware already validated this against a real user, but guard
// against a malformed subject anyway rather than panicking.
let user_id = match ObjectId::parse_str(&claims.sub) {
Ok(oid) => oid,
Err(_) => {
return (
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({ "error": "invalid token" })),
)
.into_response()
}
};
let mut user = match state.db.find_user_by_id(&user_id).await {
Ok(Some(u)) => u,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(serde_json::json!({
"error": "user not found"
})),
)
.into_response()
}
Err(e) => {
tracing::error!("Failed to get user: {}", e);
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "database error"
})),
)
.into_response();
}
};
// Verify current password
match user.verify_password(&req.current_password) {
Ok(true) => {}
Ok(false) => {
return (
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({
"error": "current password is incorrect"
})),
)
.into_response()
}
Err(e) => {
tracing::error!("Failed to verify password: {}", e);
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "failed to verify password"
})),
)
.into_response();
}
}
// Update password (this also bumps token_version in memory)
match user.update_password(req.new_password) {
Ok(_) => {
// Store the re-wrapped DEK (zero-knowledge: client re-wrapped it).
user.wrapped_dek = req.new_wrapped_dek;
user.wrapped_dek_iv = req.new_wrapped_dek_iv;
}
Err(e) => {
tracing::error!("Failed to hash new password: {}", e);
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "failed to update password"
})),
)
.into_response();
}
}
match state.db.update_user(&user).await {
Ok(_) => {
// Invalidate all sessions: the bumped token_version rejects existing
// access tokens, and we revoke every refresh token immediately so
// they can't mint new access tokens.
if let Some(ref repo) = state.refresh_token_repo {
if let Err(e) = repo.revoke_all_by_user(&user_id.to_string()).await {
tracing::warn!("Failed to revoke refresh tokens on password change: {}", e);
}
}
state.token_version_cache.invalidate(&user_id).await;
// Audit the credential change.
if let Some(ref audit) = state.audit_logger {
let _ = audit
.log_event(
AuditEventType::PasswordChanged,
Some(user_id),
Some(user.email.clone()),
client_ip.as_str().to_string(),
None,
None,
)
.await;
}
(StatusCode::NO_CONTENT, ()).into_response()
}
Err(e) => {
tracing::error!("Failed to update user: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "failed to update password"
})),
)
.into_response()
}
}
}
#[derive(Debug, Serialize)]
pub struct UserSettingsResponse {
pub recovery_enabled: bool,
pub email_verified: bool,
}
impl From<User> for UserSettingsResponse {
fn from(user: User) -> Self {
Self {
recovery_enabled: user.recovery_enabled,
email_verified: user.email_verified,
}
}
}
pub async fn get_settings(
State(state): State<AppState>,
Extension(claims): Extension<Claims>,
) -> impl IntoResponse {
let user_id = match ObjectId::parse_str(&claims.sub) {
Ok(oid) => oid,
Err(_) => {
return (
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({ "error": "invalid token" })),
)
.into_response()
}
};
match state.db.find_user_by_id(&user_id).await {
Ok(Some(user)) => {
let response: UserSettingsResponse = user.into();
(StatusCode::OK, Json(response)).into_response()
}
Ok(None) => (
StatusCode::NOT_FOUND,
Json(serde_json::json!({
"error": "user not found"
})),
)
.into_response(),
Err(e) => {
tracing::error!("Failed to get user: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "failed to get settings"
})),
)
.into_response()
}
}
}
#[derive(Debug, Deserialize, Validate)]
pub struct UpdateSettingsRequest {
pub recovery_enabled: Option<bool>,
}
pub async fn update_settings(
State(state): State<AppState>,
Extension(claims): Extension<Claims>,
Json(req): Json<UpdateSettingsRequest>,
) -> impl IntoResponse {
let user_id = match ObjectId::parse_str(&claims.sub) {
Ok(oid) => oid,
Err(_) => {
return (
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({ "error": "invalid token" })),
)
.into_response()
}
};
let mut user = match state.db.find_user_by_id(&user_id).await {
Ok(Some(u)) => u,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(serde_json::json!({
"error": "user not found"
})),
)
.into_response()
}
Err(e) => {
tracing::error!("Failed to get user: {}", e);
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "database error"
})),
)
.into_response();
}
};
if let Some(recovery_enabled) = req.recovery_enabled {
if !recovery_enabled {
user.remove_recovery_phrase();
}
// Note: Enabling recovery requires a separate endpoint to set the phrase
}
match state.db.update_user(&user).await {
Ok(_) => {
let response: UserSettingsResponse = user.into();
(StatusCode::OK, Json(response)).into_response()
}
Err(e) => {
tracing::error!("Failed to update user: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": "failed to update settings"
})),
)
.into_response()
}
}
}