feat: zero-knowledge recovery (Phase 2) — wrapped-DEK model
Introduces a wrapped-DEK recovery model so a forgotten password doesn't lose all encrypted data. The encryption key becomes a random DEK (not derived from the password); the DEK is wrapped under both a password-derived KEK and a recovery-phrase-derived KEK, and both wrapped forms are stored on the server. Crypto (crypto/keys.ts): - DEK generation (random AES-256-GCM), KEK derivation (PBKDF2 password/recovery), wrapDek/unwrapDek/rewrapDek. - setupEncryption(password, recoveryPhrase?) — generates a DEK, wraps under both KEKs, returns wrapped forms + recovery proof. - unlockWithPassword(password, wrappedDek) — derives password KEK, unwraps DEK. - unlockWithRecovery(phrase, wrappedDek) — derives recovery KEK, unwraps DEK. Backend: - User model: wrapped_dek, wrapped_dek_iv, recovery_wrapped_dek, recovery_wrapped_dek_iv fields. - RegisterRequest accepts wrapped-DEK fields; stored verbatim. - AuthResponse returns wrapped_dek + wrapped_dek_iv (for login unwrapping). - New GET /api/auth/recovery-info?email= — returns recovery-wrapped DEK. - RecoverPasswordRequest gains new_wrapped_dek + new_wrapped_dek_iv. - change-password also accepts + stores re-wrapped DEK. Frontend: - Auth store: login unwraps DEK from response; new recover() action fetches recovery-wrapped DEK, unwraps with phrase, re-wraps under new password. - RecoveryPage (new): email + recovery phrase + new password flow. - LoginPage: 'Forgot password? Recover' link. App.tsx: /recover route. Verified: backend 21 tests, 0 warnings; frontend build clean, 20 tests.
This commit is contained in:
parent
62ef1abb84
commit
7a641dec00
13 changed files with 528 additions and 67 deletions
|
|
@ -34,7 +34,8 @@ pub fn build_app(state: AppState) -> Router {
|
|||
.route(
|
||||
"/api/auth/recover-password",
|
||||
post(handlers::recover_password),
|
||||
);
|
||||
)
|
||||
.route("/api/auth/recovery-info", get(handlers::recovery_info));
|
||||
|
||||
// Build protected routes (auth required)
|
||||
let protected_routes = Router::new()
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
use axum::{extract::Extension, extract::State, http::StatusCode, response::IntoResponse, Json};
|
||||
use axum::{
|
||||
extract::Extension, extract::Query, extract::State, http::StatusCode, response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use validator::Validate;
|
||||
|
|
@ -16,8 +19,14 @@ pub struct RegisterRequest {
|
|||
pub username: String,
|
||||
#[validate(length(min = 8))]
|
||||
pub password: String,
|
||||
/// Optional recovery phrase for password recovery
|
||||
/// Optional recovery phrase hash (for server-side verification)
|
||||
pub recovery_phrase: Option<String>,
|
||||
/// Wrapped DEK (base64 ciphertext) — encrypted under the password KEK
|
||||
pub wrapped_dek: Option<String>,
|
||||
pub wrapped_dek_iv: Option<String>,
|
||||
/// Wrapped DEK (base64 ciphertext) — encrypted under the recovery KEK
|
||||
pub recovery_wrapped_dek: Option<String>,
|
||||
pub recovery_wrapped_dek_iv: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
|
|
@ -27,6 +36,10 @@ pub struct AuthResponse {
|
|||
pub user_id: String,
|
||||
pub email: String,
|
||||
pub username: String,
|
||||
/// Wrapped DEK + IV (for the client to unwrap at login). Absent if the
|
||||
/// user has no wrapped DEK (legacy/pre-recovery accounts).
|
||||
pub wrapped_dek: Option<String>,
|
||||
pub wrapped_dek_iv: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn register(
|
||||
|
|
@ -70,11 +83,11 @@ pub async fn register(
|
|||
}
|
||||
|
||||
// Create new user
|
||||
let user = match User::new(
|
||||
let mut user = match User::new(
|
||||
req.email.clone(),
|
||||
req.username.clone(),
|
||||
req.password,
|
||||
req.recovery_phrase,
|
||||
req.recovery_phrase.clone(),
|
||||
) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
|
|
@ -89,6 +102,13 @@ pub async fn register(
|
|||
}
|
||||
};
|
||||
|
||||
// Store the wrapped-DEK fields (zero-knowledge: server stores verbatim).
|
||||
user.wrapped_dek = req.wrapped_dek;
|
||||
user.wrapped_dek_iv = req.wrapped_dek_iv;
|
||||
user.recovery_wrapped_dek = req.recovery_wrapped_dek.clone();
|
||||
user.recovery_wrapped_dek_iv = req.recovery_wrapped_dek_iv.clone();
|
||||
user.recovery_enabled = req.recovery_wrapped_dek.is_some();
|
||||
|
||||
// Get token_version before saving
|
||||
let token_version = user.token_version;
|
||||
|
||||
|
|
@ -179,8 +199,10 @@ pub async fn register(
|
|||
token,
|
||||
refresh_token,
|
||||
user_id: user_id.to_string(),
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
email: user.email.clone(),
|
||||
username: user.username.clone(),
|
||||
wrapped_dek: user.wrapped_dek.clone(),
|
||||
wrapped_dek_iv: user.wrapped_dek_iv.clone(),
|
||||
};
|
||||
|
||||
(StatusCode::CREATED, Json(response)).into_response()
|
||||
|
|
@ -387,8 +409,10 @@ pub async fn login(
|
|||
token,
|
||||
refresh_token,
|
||||
user_id: user_id.to_string(),
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
email: user.email.clone(),
|
||||
username: user.username.clone(),
|
||||
wrapped_dek: user.wrapped_dek.clone(),
|
||||
wrapped_dek_iv: user.wrapped_dek_iv.clone(),
|
||||
};
|
||||
|
||||
(StatusCode::OK, Json(response)).into_response()
|
||||
|
|
@ -398,10 +422,61 @@ pub async fn login(
|
|||
pub struct RecoverPasswordRequest {
|
||||
#[validate(email)]
|
||||
pub email: String,
|
||||
/// The recovery-phrase-derived proof (base64) — the server verifies it
|
||||
/// against the stored recovery_phrase_hash.
|
||||
#[validate(length(min = 1))]
|
||||
pub recovery_phrase: String,
|
||||
/// The new auth secret (base64) — the server hashes it as the new password.
|
||||
#[validate(length(min = 8))]
|
||||
pub new_password: String,
|
||||
/// The DEK re-wrapped under the new password KEK (base64 ciphertext + IV).
|
||||
pub new_wrapped_dek: Option<String>,
|
||||
pub new_wrapped_dek_iv: Option<String>,
|
||||
}
|
||||
|
||||
/// GET /api/auth/recovery-info?email=... — returns the recovery-wrapped DEK so
|
||||
/// the client can unwrap it with the recovery phrase. Public (the wrapped DEK
|
||||
/// is useless without the recovery phrase).
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct RecoveryInfoQuery {
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
pub async fn recovery_info(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<RecoveryInfoQuery>,
|
||||
) -> impl IntoResponse {
|
||||
let user = match state.db.find_user_by_email(&query.email).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => {
|
||||
// Don't reveal whether the email exists — return disabled.
|
||||
return (
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({
|
||||
"recovery_enabled": false,
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Recovery info lookup failed: {}", e);
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({ "error": "database error" })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({
|
||||
"recovery_enabled": user.recovery_enabled,
|
||||
"recovery_wrapped_dek": user.recovery_wrapped_dek,
|
||||
"recovery_wrapped_dek_iv": user.recovery_wrapped_dek_iv,
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub async fn recover_password(
|
||||
|
|
@ -468,9 +543,14 @@ pub async fn recover_password(
|
|||
}
|
||||
}
|
||||
|
||||
// Update password
|
||||
// Update password + store the new wrapped DEK (re-wrapped client-side under
|
||||
// the new password KEK). The server never sees the DEK itself.
|
||||
match user.update_password(req.new_password) {
|
||||
Ok(_) => {}
|
||||
Ok(_) => {
|
||||
// Store the re-wrapped DEK so the new password can unlock it.
|
||||
user.wrapped_dek = req.new_wrapped_dek;
|
||||
user.wrapped_dek_iv = req.new_wrapped_dek_iv;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to update password: {}", e);
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ pub mod users;
|
|||
pub use appointments::{
|
||||
create_appointment, delete_appointment, get_appointment, list_appointments, update_appointment,
|
||||
};
|
||||
pub use auth::{login, logout, recover_password, refresh, register};
|
||||
pub use auth::{login, logout, recover_password, recovery_info, refresh, register};
|
||||
pub use health::{health_check, ready_check};
|
||||
pub use health_stats::{
|
||||
create_health_stat, delete_health_stat, get_health_stat, get_health_trends, list_health_stats,
|
||||
|
|
|
|||
|
|
@ -187,6 +187,10 @@ pub struct ChangePasswordRequest {
|
|||
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(
|
||||
|
|
@ -268,7 +272,11 @@ pub async fn change_password(
|
|||
|
||||
// Update password (this also bumps token_version in memory)
|
||||
match user.update_password(req.new_password) {
|
||||
Ok(_) => {}
|
||||
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 (
|
||||
|
|
|
|||
|
|
@ -23,6 +23,20 @@ pub struct User {
|
|||
/// Whether password recovery is enabled for this user
|
||||
pub recovery_enabled: bool,
|
||||
|
||||
/// Wrapped DEK (data encryption key) — the DEK encrypted under the password
|
||||
/// KEK. Base64 ciphertext. The server stores this verbatim; only the client
|
||||
/// can unwrap it. (Phase 2 zero-knowledge recovery.)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub wrapped_dek: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub wrapped_dek_iv: Option<String>,
|
||||
|
||||
/// Wrapped DEK under the recovery KEK — for password recovery.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_wrapped_dek: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_wrapped_dek_iv: Option<String>,
|
||||
|
||||
/// Token version for invalidating all tokens on password change
|
||||
pub token_version: i32,
|
||||
|
||||
|
|
@ -75,6 +89,10 @@ impl User {
|
|||
password_hash,
|
||||
recovery_phrase_hash,
|
||||
recovery_enabled,
|
||||
wrapped_dek: None,
|
||||
wrapped_dek_iv: None,
|
||||
recovery_wrapped_dek: None,
|
||||
recovery_wrapped_dek_iv: None,
|
||||
token_version: 0,
|
||||
created_at: now,
|
||||
last_active: now,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue