this repo has no description
1use crate::api::EmptyResponse; 2use crate::api::error::ApiError; 3use crate::cache::Cache; 4use crate::plc::PlcClient; 5use crate::state::AppState; 6use crate::types::PlainPassword; 7use axum::{ 8 Json, 9 extract::State, 10 http::StatusCode, 11 response::{IntoResponse, Response}, 12}; 13use bcrypt::verify; 14use chrono::{Duration, Utc}; 15use cid::Cid; 16use jacquard_repo::commit::Commit; 17use jacquard_repo::storage::BlockStore; 18use k256::ecdsa::SigningKey; 19use serde::{Deserialize, Serialize}; 20use std::str::FromStr; 21use std::sync::Arc; 22use tracing::{error, info, warn}; 23use uuid::Uuid; 24 25#[derive(Serialize)] 26#[serde(rename_all = "camelCase")] 27pub struct CheckAccountStatusOutput { 28 pub activated: bool, 29 pub valid_did: bool, 30 pub repo_commit: String, 31 pub repo_rev: String, 32 pub repo_blocks: i64, 33 pub indexed_records: i64, 34 pub private_state_values: i64, 35 pub expected_blobs: i64, 36 pub imported_blobs: i64, 37} 38 39pub async fn check_account_status( 40 State(state): State<AppState>, 41 headers: axum::http::HeaderMap, 42) -> Response { 43 let extracted = match crate::auth::extract_auth_token_from_header( 44 headers.get("Authorization").and_then(|h| h.to_str().ok()), 45 ) { 46 Some(t) => t, 47 None => return ApiError::AuthenticationRequired.into_response(), 48 }; 49 let dpop_proof = headers.get("DPoP").and_then(|h| h.to_str().ok()); 50 let http_uri = format!( 51 "https://{}/xrpc/com.atproto.server.checkAccountStatus", 52 std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()) 53 ); 54 let did = match crate::auth::validate_token_with_dpop( 55 &state.db, 56 &extracted.token, 57 extracted.is_dpop, 58 dpop_proof, 59 "GET", 60 &http_uri, 61 true, 62 false, 63 ) 64 .await 65 { 66 Ok(user) => user.did, 67 Err(e) => return ApiError::from(e).into_response(), 68 }; 69 let user_id = match sqlx::query_scalar!("SELECT id FROM users WHERE did = $1", did.as_str()) 70 .fetch_optional(&state.db) 71 .await 72 { 73 Ok(Some(id)) => id, 74 _ => { 75 return ApiError::InternalError(None).into_response(); 76 } 77 }; 78 let user_status = sqlx::query!( 79 "SELECT deactivated_at FROM users WHERE did = $1", 80 did.as_str() 81 ) 82 .fetch_optional(&state.db) 83 .await; 84 let deactivated_at = match user_status { 85 Ok(Some(row)) => row.deactivated_at, 86 _ => None, 87 }; 88 let repo_result = sqlx::query!( 89 "SELECT repo_root_cid, repo_rev FROM repos WHERE user_id = $1", 90 user_id 91 ) 92 .fetch_optional(&state.db) 93 .await; 94 let (repo_commit, repo_rev_from_db) = match repo_result { 95 Ok(Some(row)) => (row.repo_root_cid, row.repo_rev), 96 _ => (String::new(), None), 97 }; 98 let block_count: i64 = sqlx::query_scalar!( 99 "SELECT COUNT(*) FROM user_blocks WHERE user_id = $1", 100 user_id 101 ) 102 .fetch_one(&state.db) 103 .await 104 .unwrap_or(Some(0)) 105 .unwrap_or(0); 106 let repo_rev = if let Some(rev) = repo_rev_from_db { 107 rev 108 } else if !repo_commit.is_empty() { 109 if let Ok(cid) = Cid::from_str(&repo_commit) { 110 if let Ok(Some(block)) = state.block_store.get(&cid).await { 111 Commit::from_cbor(&block) 112 .ok() 113 .map(|c| c.rev().to_string()) 114 .unwrap_or_default() 115 } else { 116 String::new() 117 } 118 } else { 119 String::new() 120 } 121 } else { 122 String::new() 123 }; 124 let record_count: i64 = 125 sqlx::query_scalar!("SELECT COUNT(*) FROM records WHERE repo_id = $1", user_id) 126 .fetch_one(&state.db) 127 .await 128 .unwrap_or(Some(0)) 129 .unwrap_or(0); 130 let imported_blobs: i64 = sqlx::query_scalar!( 131 "SELECT COUNT(*) FROM blobs WHERE created_by_user = $1", 132 user_id 133 ) 134 .fetch_one(&state.db) 135 .await 136 .unwrap_or(Some(0)) 137 .unwrap_or(0); 138 let expected_blobs: i64 = sqlx::query_scalar!( 139 "SELECT COUNT(DISTINCT blob_cid) FROM record_blobs WHERE repo_id = $1", 140 user_id 141 ) 142 .fetch_one(&state.db) 143 .await 144 .unwrap_or(Some(0)) 145 .unwrap_or(0); 146 let valid_did = is_valid_did_for_service(&state.db, state.cache.clone(), did.as_str()).await; 147 ( 148 StatusCode::OK, 149 Json(CheckAccountStatusOutput { 150 activated: deactivated_at.is_none(), 151 valid_did, 152 repo_commit: repo_commit.clone(), 153 repo_rev, 154 repo_blocks: block_count as i64, 155 indexed_records: record_count, 156 private_state_values: 0, 157 expected_blobs, 158 imported_blobs, 159 }), 160 ) 161 .into_response() 162} 163 164async fn is_valid_did_for_service(db: &sqlx::PgPool, cache: Arc<dyn Cache>, did: &str) -> bool { 165 assert_valid_did_document_for_service(db, cache, did, false) 166 .await 167 .is_ok() 168} 169 170async fn assert_valid_did_document_for_service( 171 db: &sqlx::PgPool, 172 cache: Arc<dyn Cache>, 173 did: &str, 174 with_retry: bool, 175) -> Result<(), ApiError> { 176 let hostname = std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()); 177 let expected_endpoint = format!("https://{}", hostname); 178 179 if did.starts_with("did:plc:") { 180 let plc_client = PlcClient::with_cache(None, Some(cache.clone())); 181 182 let max_attempts = if with_retry { 5 } else { 1 }; 183 let mut last_error = None; 184 let mut doc_data = None; 185 for attempt in 0..max_attempts { 186 if attempt > 0 { 187 let delay_ms = 500 * (1 << (attempt - 1)); 188 info!( 189 "Waiting {}ms before retry {} for DID document validation ({})", 190 delay_ms, attempt, did 191 ); 192 tokio::time::sleep(tokio::time::Duration::from_millis(delay_ms)).await; 193 } 194 195 match plc_client.get_document_data(did).await { 196 Ok(data) => { 197 let pds_endpoint = data 198 .get("services") 199 .and_then(|s| s.get("atproto_pds").or_else(|| s.get("atprotoPds"))) 200 .and_then(|p| p.get("endpoint")) 201 .and_then(|e| e.as_str()); 202 203 if pds_endpoint == Some(&expected_endpoint) { 204 doc_data = Some(data); 205 break; 206 } else { 207 info!( 208 "Attempt {}: DID {} has endpoint {:?}, expected {} - retrying", 209 attempt + 1, 210 did, 211 pds_endpoint, 212 expected_endpoint 213 ); 214 last_error = Some(format!( 215 "DID document endpoint {:?} does not match expected {}", 216 pds_endpoint, expected_endpoint 217 )); 218 } 219 } 220 Err(e) => { 221 warn!( 222 "Attempt {}: Failed to fetch PLC document for {}: {:?}", 223 attempt + 1, 224 did, 225 e 226 ); 227 last_error = Some(format!("Could not resolve DID document: {}", e)); 228 } 229 } 230 } 231 232 let Some(doc_data) = doc_data else { 233 return Err(ApiError::InvalidRequest( 234 last_error.unwrap_or_else(|| "DID document validation failed".to_string()), 235 )); 236 }; 237 238 let server_rotation_key = std::env::var("PLC_ROTATION_KEY").ok(); 239 if let Some(ref expected_rotation_key) = server_rotation_key { 240 let rotation_keys = doc_data 241 .get("rotationKeys") 242 .and_then(|v| v.as_array()) 243 .map(|arr| arr.iter().filter_map(|k| k.as_str()).collect::<Vec<_>>()) 244 .unwrap_or_default(); 245 if !rotation_keys.contains(&expected_rotation_key.as_str()) { 246 return Err(ApiError::InvalidRequest( 247 "Server rotation key not included in PLC DID data".into(), 248 )); 249 } 250 } 251 252 let doc_signing_key = doc_data 253 .get("verificationMethods") 254 .and_then(|v| v.get("atproto")) 255 .and_then(|k| k.as_str()); 256 257 let user_row = sqlx::query!( 258 "SELECT uk.key_bytes, uk.encryption_version FROM user_keys uk JOIN users u ON uk.user_id = u.id WHERE u.did = $1", 259 did 260 ) 261 .fetch_optional(db) 262 .await 263 .map_err(|e| { 264 error!("Failed to fetch user key: {:?}", e); 265 ApiError::InternalError(None) 266 })?; 267 268 if let Some(row) = user_row { 269 let key_bytes = crate::config::decrypt_key(&row.key_bytes, row.encryption_version) 270 .map_err(|e| { 271 error!("Failed to decrypt user key: {}", e); 272 ApiError::InternalError(None) 273 })?; 274 let signing_key = SigningKey::from_slice(&key_bytes).map_err(|e| { 275 error!("Failed to create signing key: {:?}", e); 276 ApiError::InternalError(None) 277 })?; 278 let expected_did_key = crate::plc::signing_key_to_did_key(&signing_key); 279 280 if doc_signing_key != Some(&expected_did_key) { 281 warn!( 282 "DID {} has signing key {:?}, expected {}", 283 did, doc_signing_key, expected_did_key 284 ); 285 return Err(ApiError::InvalidRequest( 286 "DID document verification method does not match expected signing key".into(), 287 )); 288 } 289 } 290 } else if let Some(host_and_path) = did.strip_prefix("did:web:") { 291 let client = crate::api::proxy_client::did_resolution_client(); 292 let decoded = host_and_path.replace("%3A", ":"); 293 let parts: Vec<&str> = decoded.split(':').collect(); 294 let (host, path_parts) = if parts.len() > 1 && parts[1].chars().all(|c| c.is_ascii_digit()) 295 { 296 (format!("{}:{}", parts[0], parts[1]), parts[2..].to_vec()) 297 } else { 298 (parts[0].to_string(), parts[1..].to_vec()) 299 }; 300 let scheme = 301 if host.starts_with("localhost") || host.starts_with("127.") || host.contains(':') { 302 "http" 303 } else { 304 "https" 305 }; 306 let url = if path_parts.is_empty() { 307 format!("{}://{}/.well-known/did.json", scheme, host) 308 } else { 309 format!("{}://{}/{}/did.json", scheme, host, path_parts.join("/")) 310 }; 311 let resp = client.get(&url).send().await.map_err(|e| { 312 warn!("Failed to fetch did:web document for {}: {:?}", did, e); 313 ApiError::InvalidRequest(format!("Could not resolve DID document: {}", e)) 314 })?; 315 let doc: serde_json::Value = resp.json().await.map_err(|e| { 316 warn!("Failed to parse did:web document for {}: {:?}", did, e); 317 ApiError::InvalidRequest(format!("Could not parse DID document: {}", e)) 318 })?; 319 320 let pds_endpoint = doc 321 .get("service") 322 .and_then(|s| s.as_array()) 323 .and_then(|arr| { 324 arr.iter().find(|svc| { 325 svc.get("id").and_then(|id| id.as_str()) == Some("#atproto_pds") 326 || svc.get("type").and_then(|t| t.as_str()) 327 == Some("AtprotoPersonalDataServer") 328 }) 329 }) 330 .and_then(|svc| svc.get("serviceEndpoint")) 331 .and_then(|e| e.as_str()); 332 333 if pds_endpoint != Some(&expected_endpoint) { 334 warn!( 335 "DID {} has endpoint {:?}, expected {}", 336 did, pds_endpoint, expected_endpoint 337 ); 338 return Err(ApiError::InvalidRequest( 339 "DID document atproto_pds service endpoint does not match PDS public url".into(), 340 )); 341 } 342 } 343 344 Ok(()) 345} 346 347pub async fn activate_account( 348 State(state): State<AppState>, 349 headers: axum::http::HeaderMap, 350) -> Response { 351 info!("[MIGRATION] activateAccount called"); 352 let extracted = match crate::auth::extract_auth_token_from_header( 353 headers.get("Authorization").and_then(|h| h.to_str().ok()), 354 ) { 355 Some(t) => t, 356 None => { 357 info!("[MIGRATION] activateAccount: No auth token"); 358 return ApiError::AuthenticationRequired.into_response(); 359 } 360 }; 361 let dpop_proof = headers.get("DPoP").and_then(|h| h.to_str().ok()); 362 let http_uri = format!( 363 "https://{}/xrpc/com.atproto.server.activateAccount", 364 std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()) 365 ); 366 let auth_user = match crate::auth::validate_token_with_dpop( 367 &state.db, 368 &extracted.token, 369 extracted.is_dpop, 370 dpop_proof, 371 "POST", 372 &http_uri, 373 true, 374 false, 375 ) 376 .await 377 { 378 Ok(user) => user, 379 Err(e) => { 380 info!("[MIGRATION] activateAccount: Auth failed: {:?}", e); 381 return ApiError::from(e).into_response(); 382 } 383 }; 384 info!( 385 "[MIGRATION] activateAccount: Authenticated user did={}", 386 auth_user.did 387 ); 388 389 if let Err(e) = crate::auth::scope_check::check_account_scope( 390 auth_user.is_oauth, 391 auth_user.scope.as_deref(), 392 crate::oauth::scopes::AccountAttr::Repo, 393 crate::oauth::scopes::AccountAction::Manage, 394 ) { 395 info!("[MIGRATION] activateAccount: Scope check failed"); 396 return e; 397 } 398 399 let did = auth_user.did; 400 401 info!( 402 "[MIGRATION] activateAccount: Validating DID document for did={}", 403 did 404 ); 405 let did_validation_start = std::time::Instant::now(); 406 if let Err(e) = 407 assert_valid_did_document_for_service(&state.db, state.cache.clone(), did.as_str(), true) 408 .await 409 { 410 info!( 411 "[MIGRATION] activateAccount: DID document validation FAILED for {} (took {:?})", 412 did, 413 did_validation_start.elapsed() 414 ); 415 return e.into_response(); 416 } 417 info!( 418 "[MIGRATION] activateAccount: DID document validation SUCCESS for {} (took {:?})", 419 did, 420 did_validation_start.elapsed() 421 ); 422 423 let handle = sqlx::query_scalar!("SELECT handle FROM users WHERE did = $1", did.as_str()) 424 .fetch_optional(&state.db) 425 .await 426 .ok() 427 .flatten(); 428 info!( 429 "[MIGRATION] activateAccount: Activating account did={} handle={:?}", 430 did, handle 431 ); 432 let result = sqlx::query!( 433 "UPDATE users SET deactivated_at = NULL WHERE did = $1", 434 did.as_str() 435 ) 436 .execute(&state.db) 437 .await; 438 match result { 439 Ok(_) => { 440 info!( 441 "[MIGRATION] activateAccount: DB update success for did={}", 442 did 443 ); 444 if let Some(ref h) = handle { 445 let _ = state.cache.delete(&format!("handle:{}", h)).await; 446 } 447 info!( 448 "[MIGRATION] activateAccount: Sequencing account event (active=true) for did={}", 449 did 450 ); 451 if let Err(e) = 452 crate::api::repo::record::sequence_account_event(&state, did.as_str(), true, None) 453 .await 454 { 455 warn!( 456 "[MIGRATION] activateAccount: Failed to sequence account activation event: {}", 457 e 458 ); 459 } else { 460 info!("[MIGRATION] activateAccount: Account event sequenced successfully"); 461 } 462 info!( 463 "[MIGRATION] activateAccount: Sequencing identity event for did={} handle={:?}", 464 did, handle 465 ); 466 if let Err(e) = crate::api::repo::record::sequence_identity_event( 467 &state, 468 did.as_str(), 469 handle.as_deref(), 470 ) 471 .await 472 { 473 warn!( 474 "[MIGRATION] activateAccount: Failed to sequence identity event for activation: {}", 475 e 476 ); 477 } else { 478 info!("[MIGRATION] activateAccount: Identity event sequenced successfully"); 479 } 480 let repo_root = sqlx::query_scalar!( 481 "SELECT r.repo_root_cid FROM repos r JOIN users u ON r.user_id = u.id WHERE u.did = $1", 482 did.as_str() 483 ) 484 .fetch_optional(&state.db) 485 .await 486 .ok() 487 .flatten(); 488 if let Some(root_cid) = repo_root { 489 info!( 490 "[MIGRATION] activateAccount: Sequencing sync event for did={} root_cid={}", 491 did, root_cid 492 ); 493 let rev = if let Ok(cid) = Cid::from_str(&root_cid) { 494 if let Ok(Some(block)) = state.block_store.get(&cid).await { 495 Commit::from_cbor(&block).ok().map(|c| c.rev().to_string()) 496 } else { 497 None 498 } 499 } else { 500 None 501 }; 502 if let Err(e) = crate::api::repo::record::sequence_sync_event( 503 &state, 504 did.as_str(), 505 &root_cid, 506 rev.as_deref(), 507 ) 508 .await 509 { 510 warn!( 511 "[MIGRATION] activateAccount: Failed to sequence sync event for activation: {}", 512 e 513 ); 514 } else { 515 info!("[MIGRATION] activateAccount: Sync event sequenced successfully"); 516 } 517 } else { 518 warn!( 519 "[MIGRATION] activateAccount: No repo root found for did={}", 520 did 521 ); 522 } 523 info!("[MIGRATION] activateAccount: SUCCESS for did={}", did); 524 EmptyResponse::ok().into_response() 525 } 526 Err(e) => { 527 error!( 528 "[MIGRATION] activateAccount: DB error activating account: {:?}", 529 e 530 ); 531 ApiError::InternalError(None).into_response() 532 } 533 } 534} 535 536#[derive(Deserialize)] 537#[serde(rename_all = "camelCase")] 538pub struct DeactivateAccountInput { 539 pub delete_after: Option<String>, 540} 541 542pub async fn deactivate_account( 543 State(state): State<AppState>, 544 headers: axum::http::HeaderMap, 545 Json(input): Json<DeactivateAccountInput>, 546) -> Response { 547 let extracted = match crate::auth::extract_auth_token_from_header( 548 headers.get("Authorization").and_then(|h| h.to_str().ok()), 549 ) { 550 Some(t) => t, 551 None => return ApiError::AuthenticationRequired.into_response(), 552 }; 553 let dpop_proof = headers.get("DPoP").and_then(|h| h.to_str().ok()); 554 let http_uri = format!( 555 "https://{}/xrpc/com.atproto.server.deactivateAccount", 556 std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()) 557 ); 558 let auth_user = match crate::auth::validate_token_with_dpop( 559 &state.db, 560 &extracted.token, 561 extracted.is_dpop, 562 dpop_proof, 563 "POST", 564 &http_uri, 565 false, 566 false, 567 ) 568 .await 569 { 570 Ok(user) => user, 571 Err(e) => return ApiError::from(e).into_response(), 572 }; 573 574 if let Err(e) = crate::auth::scope_check::check_account_scope( 575 auth_user.is_oauth, 576 auth_user.scope.as_deref(), 577 crate::oauth::scopes::AccountAttr::Repo, 578 crate::oauth::scopes::AccountAction::Manage, 579 ) { 580 return e; 581 } 582 583 let delete_after: Option<chrono::DateTime<chrono::Utc>> = input 584 .delete_after 585 .as_ref() 586 .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) 587 .map(|dt| dt.with_timezone(&chrono::Utc)); 588 589 let did = auth_user.did; 590 591 let handle = sqlx::query_scalar!("SELECT handle FROM users WHERE did = $1", did.as_str()) 592 .fetch_optional(&state.db) 593 .await 594 .ok() 595 .flatten(); 596 597 let result = sqlx::query!( 598 "UPDATE users SET deactivated_at = NOW(), delete_after = $2 WHERE did = $1", 599 did.as_str(), 600 delete_after 601 ) 602 .execute(&state.db) 603 .await; 604 605 match result { 606 Ok(_) => { 607 if let Some(ref h) = handle { 608 let _ = state.cache.delete(&format!("handle:{}", h)).await; 609 } 610 if let Err(e) = crate::api::repo::record::sequence_account_event( 611 &state, 612 did.as_str(), 613 false, 614 Some("deactivated"), 615 ) 616 .await 617 { 618 warn!("Failed to sequence account deactivated event: {}", e); 619 } 620 EmptyResponse::ok().into_response() 621 } 622 Err(e) => { 623 error!("DB error deactivating account: {:?}", e); 624 ApiError::InternalError(None).into_response() 625 } 626 } 627} 628 629pub async fn request_account_delete( 630 State(state): State<AppState>, 631 headers: axum::http::HeaderMap, 632) -> Response { 633 let extracted = match crate::auth::extract_auth_token_from_header( 634 headers.get("Authorization").and_then(|h| h.to_str().ok()), 635 ) { 636 Some(t) => t, 637 None => return ApiError::AuthenticationRequired.into_response(), 638 }; 639 let dpop_proof = headers.get("DPoP").and_then(|h| h.to_str().ok()); 640 let http_uri = format!( 641 "https://{}/xrpc/com.atproto.server.requestAccountDelete", 642 std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()) 643 ); 644 let validated = match crate::auth::validate_token_with_dpop( 645 &state.db, 646 &extracted.token, 647 extracted.is_dpop, 648 dpop_proof, 649 "POST", 650 &http_uri, 651 true, 652 false, 653 ) 654 .await 655 { 656 Ok(user) => user, 657 Err(e) => return ApiError::from(e).into_response(), 658 }; 659 let did = validated.did.clone(); 660 661 if !crate::api::server::reauth::check_legacy_session_mfa(&state.db, did.as_str()).await { 662 return crate::api::server::reauth::legacy_mfa_required_response(&state.db, did.as_str()) 663 .await; 664 } 665 666 let user_id = match sqlx::query_scalar!("SELECT id FROM users WHERE did = $1", did.as_str()) 667 .fetch_optional(&state.db) 668 .await 669 { 670 Ok(Some(id)) => id, 671 _ => { 672 return ApiError::InternalError(None).into_response(); 673 } 674 }; 675 let confirmation_token = Uuid::new_v4().to_string(); 676 let expires_at = Utc::now() + Duration::minutes(15); 677 let insert = sqlx::query!( 678 "INSERT INTO account_deletion_requests (token, did, expires_at) VALUES ($1, $2, $3)", 679 confirmation_token, 680 did.as_str(), 681 expires_at 682 ) 683 .execute(&state.db) 684 .await; 685 if let Err(e) = insert { 686 error!("DB error creating deletion token: {:?}", e); 687 return ApiError::InternalError(None).into_response(); 688 } 689 let hostname = std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()); 690 if let Err(e) = 691 crate::comms::enqueue_account_deletion(&state.db, user_id, &confirmation_token, &hostname) 692 .await 693 { 694 warn!("Failed to enqueue account deletion notification: {:?}", e); 695 } 696 info!("Account deletion requested for user {}", did); 697 EmptyResponse::ok().into_response() 698} 699 700#[derive(Deserialize)] 701pub struct DeleteAccountInput { 702 pub did: crate::types::Did, 703 pub password: PlainPassword, 704 pub token: String, 705} 706 707pub async fn delete_account( 708 State(state): State<AppState>, 709 Json(input): Json<DeleteAccountInput>, 710) -> Response { 711 let did = &input.did; 712 let password = &input.password; 713 let token = input.token.trim(); 714 if password.is_empty() { 715 return ApiError::InvalidRequest("password is required".into()).into_response(); 716 } 717 const OLD_PASSWORD_MAX_LENGTH: usize = 512; 718 if password.len() > OLD_PASSWORD_MAX_LENGTH { 719 return ApiError::InvalidRequest("Invalid password length".into()).into_response(); 720 } 721 if token.is_empty() { 722 return ApiError::InvalidToken(Some("token is required".into())).into_response(); 723 } 724 let user = sqlx::query!( 725 "SELECT id, password_hash, handle FROM users WHERE did = $1", 726 did.as_str() 727 ) 728 .fetch_optional(&state.db) 729 .await; 730 let (user_id, password_hash, handle) = match user { 731 Ok(Some(row)) => (row.id, row.password_hash, row.handle), 732 Ok(None) => { 733 return ApiError::InvalidRequest("account not found".into()).into_response(); 734 } 735 Err(e) => { 736 error!("DB error in delete_account: {:?}", e); 737 return ApiError::InternalError(None).into_response(); 738 } 739 }; 740 let password_valid = if password_hash 741 .as_ref() 742 .map(|h| verify(password, h).unwrap_or(false)) 743 .unwrap_or(false) 744 { 745 true 746 } else { 747 let app_pass_rows = sqlx::query!( 748 "SELECT password_hash FROM app_passwords WHERE user_id = $1", 749 user_id 750 ) 751 .fetch_all(&state.db) 752 .await 753 .unwrap_or_default(); 754 app_pass_rows 755 .iter() 756 .any(|row| verify(password, &row.password_hash).unwrap_or(false)) 757 }; 758 if !password_valid { 759 return ApiError::AuthenticationFailed(Some("Invalid password".into())).into_response(); 760 } 761 let deletion_request = sqlx::query!( 762 "SELECT did, expires_at FROM account_deletion_requests WHERE token = $1", 763 token 764 ) 765 .fetch_optional(&state.db) 766 .await; 767 let (token_did, expires_at) = match deletion_request { 768 Ok(Some(row)) => (row.did, row.expires_at), 769 Ok(None) => { 770 return ApiError::InvalidToken(Some("Invalid or expired token".into())).into_response(); 771 } 772 Err(e) => { 773 error!("DB error fetching deletion token: {:?}", e); 774 return ApiError::InternalError(None).into_response(); 775 } 776 }; 777 if token_did != did.as_str() { 778 return ApiError::InvalidToken(Some("Token does not match account".into())).into_response(); 779 } 780 if Utc::now() > expires_at { 781 let _ = sqlx::query!( 782 "DELETE FROM account_deletion_requests WHERE token = $1", 783 token 784 ) 785 .execute(&state.db) 786 .await; 787 return ApiError::ExpiredToken(None).into_response(); 788 } 789 let mut tx = match state.db.begin().await { 790 Ok(tx) => tx, 791 Err(e) => { 792 error!("Failed to begin transaction: {:?}", e); 793 return ApiError::InternalError(None).into_response(); 794 } 795 }; 796 let deletion_result: Result<(), sqlx::Error> = async { 797 sqlx::query!("DELETE FROM session_tokens WHERE did = $1", did) 798 .execute(&mut *tx) 799 .await?; 800 sqlx::query!("DELETE FROM records WHERE repo_id = $1", user_id) 801 .execute(&mut *tx) 802 .await?; 803 sqlx::query!("DELETE FROM repos WHERE user_id = $1", user_id) 804 .execute(&mut *tx) 805 .await?; 806 sqlx::query!("DELETE FROM blobs WHERE created_by_user = $1", user_id) 807 .execute(&mut *tx) 808 .await?; 809 sqlx::query!("DELETE FROM user_keys WHERE user_id = $1", user_id) 810 .execute(&mut *tx) 811 .await?; 812 sqlx::query!("DELETE FROM app_passwords WHERE user_id = $1", user_id) 813 .execute(&mut *tx) 814 .await?; 815 sqlx::query!("DELETE FROM account_deletion_requests WHERE did = $1", did) 816 .execute(&mut *tx) 817 .await?; 818 sqlx::query!("DELETE FROM users WHERE id = $1", user_id) 819 .execute(&mut *tx) 820 .await?; 821 Ok(()) 822 } 823 .await; 824 match deletion_result { 825 Ok(()) => { 826 if let Err(e) = tx.commit().await { 827 error!("Failed to commit account deletion transaction: {:?}", e); 828 return ApiError::InternalError(None).into_response(); 829 } 830 let account_seq = crate::api::repo::record::sequence_account_event( 831 &state, 832 did, 833 false, 834 Some("deleted"), 835 ) 836 .await; 837 match account_seq { 838 Ok(seq) => { 839 if let Err(e) = sqlx::query!( 840 "DELETE FROM repo_seq WHERE did = $1 AND seq != $2", 841 did, 842 seq 843 ) 844 .execute(&state.db) 845 .await 846 { 847 warn!( 848 "Failed to cleanup sequences for deleted account {}: {}", 849 did, e 850 ); 851 } 852 } 853 Err(e) => { 854 warn!( 855 "Failed to sequence account deletion event for {}: {}", 856 did, e 857 ); 858 } 859 } 860 let _ = state.cache.delete(&format!("handle:{}", handle)).await; 861 info!("Account {} deleted successfully", did); 862 EmptyResponse::ok().into_response() 863 } 864 Err(e) => { 865 error!("DB error deleting account, rolling back: {:?}", e); 866 ApiError::InternalError(None).into_response() 867 } 868 } 869}