diff --git a/crates/adapters/http-axum/src/api/mod.rs b/crates/adapters/http-axum/src/api/mod.rs index 95440c08..5ab3d146 100644 --- a/crates/adapters/http-axum/src/api/mod.rs +++ b/crates/adapters/http-axum/src/api/mod.rs @@ -48,7 +48,11 @@ pub fn router() -> Router { .route("/diary/export", routing::get(diary::export_diary)) .route("/activity-feed", routing::get(diary::get_activity_feed)) .route("/users", routing::get(users::list_users)) - .route("/users/{id}", routing::get(user_profile::get_user_profile)) + .route("/users/me", routing::delete(users::delete_me)) + .route( + "/users/{id}", + routing::get(user_profile::get_user_profile).delete(users::delete_user), + ) .route("/import/sessions", routing::post(import::api_post_session)) .route( "/import/sessions/{id}", diff --git a/crates/adapters/http-axum/src/api/users.rs b/crates/adapters/http-axum/src/api/users.rs index bbf4d737..f7d7df1e 100644 --- a/crates/adapters/http-axum/src/api/users.rs +++ b/crates/adapters/http-axum/src/api/users.rs @@ -1,10 +1,12 @@ -use crate::extractors::{Body, Upload}; +use crate::extractors::{Body, PathId, Upload}; use crate::{errors::ApiError, extractors::AuthenticatedUser, state::AppState}; -use api_types::{ProfileResponse, UserSummaryDto, UsersResponse}; +use api_types::{DeleteAccountRequest, ProfileResponse, UserSummaryDto, UsersResponse}; use application::users::{ - get_users, queries::GetUsersQuery, update_profile, update_profile_fields, + get_users, queries::GetUsersQuery, request_account_deletion, update_profile, + update_profile_fields, }; use axum::{Json, extract::State, http::StatusCode, response::IntoResponse}; +use domain::value_objects::UserId; #[utoipa::path( get, path = "/api/v1/profile", @@ -155,3 +157,61 @@ pub async fn list_users(State(state): State) -> Result Result { + request_account_deletion::execute( + &state.app_ctx.deps.users.request_account_deletion, + actor, + target, + password, + ) + .await?; + Ok(StatusCode::NO_CONTENT) +} + +#[utoipa::path( + delete, path = "/api/v1/users/me", + request_body = DeleteAccountRequest, + responses( + (status = 204, description = "Account deleted"), + (status = 400, description = "Invalid input", body = api_types::ErrorResponse), + (status = 401, description = "Unauthorized or incorrect password", body = api_types::ErrorResponse), + (status = 409, description = "The last admin cannot be deleted", body = api_types::ErrorResponse), + ), + security(("bearer_auth" = [])) +)] +pub async fn delete_me( + State(state): State, + AuthenticatedUser(user_id): AuthenticatedUser, + Body(req): Body, +) -> Result { + delete_account(&state, user_id.clone(), user_id, &req.password).await +} + +#[utoipa::path( + delete, path = "/api/v1/users/{id}", + params(("id" = uuid::Uuid, Path, description = "User ID")), + request_body = DeleteAccountRequest, + responses( + (status = 204, description = "Account deleted"), + (status = 400, description = "Invalid input", body = api_types::ErrorResponse), + (status = 401, description = "Unauthorized or incorrect password", body = api_types::ErrorResponse), + (status = 403, description = "Admin only", body = api_types::ErrorResponse), + (status = 404, description = "User not found", body = api_types::ErrorResponse), + (status = 409, description = "The last admin cannot be deleted", body = api_types::ErrorResponse), + ), + security(("bearer_auth" = [])) +)] +pub async fn delete_user( + State(state): State, + AuthenticatedUser(actor): AuthenticatedUser, + PathId(target): PathId, + Body(req): Body, +) -> Result { + delete_account(&state, actor, UserId::from_uuid(target), &req.password).await +} diff --git a/crates/adapters/http-axum/src/html/auth.rs b/crates/adapters/http-axum/src/html/auth.rs index b3f02252..fcc82622 100644 --- a/crates/adapters/http-axum/src/html/auth.rs +++ b/crates/adapters/http-axum/src/html/auth.rs @@ -82,7 +82,7 @@ pub async fn post_login( } } -pub async fn get_logout(State(state): State) -> impl IntoResponse { +pub(super) async fn get_logout(State(state): State) -> impl IntoResponse { let val = format!( "token=; HttpOnly; Path=/; SameSite=Strict; Max-Age=0{}", secure_flag(state.app_ctx.config.secure_cookies) diff --git a/crates/adapters/http-axum/src/html/forms.rs b/crates/adapters/http-axum/src/html/forms.rs index 835b18e9..7cb8b8d5 100644 --- a/crates/adapters/http-axum/src/html/forms.rs +++ b/crates/adapters/http-axum/src/html/forms.rs @@ -62,6 +62,13 @@ pub struct RegisterForm { pub csrf_token: String, } +#[derive(Deserialize)] +pub struct DeleteAccountForm { + pub password: String, + #[serde(rename = "_csrf", default)] + pub csrf_token: String, +} + #[derive(Deserialize)] pub struct ErrorQuery { pub error: Option, diff --git a/crates/adapters/http-axum/src/html/mod.rs b/crates/adapters/http-axum/src/html/mod.rs index e735855e..52e40020 100644 --- a/crates/adapters/http-axum/src/html/mod.rs +++ b/crates/adapters/http-axum/src/html/mod.rs @@ -73,6 +73,11 @@ pub fn router() -> Router { "/settings/profile", routing::get(users::get_profile_settings).post(users::post_profile_settings), ) + .route( + "/settings/account/delete", + routing::post(users::post_delete_own_account), + ) + .route("/users/{id}/delete", routing::post(users::post_delete_user)) .route("/tags/{tag}", routing::get(tags::get_tag)) .route( "/users/{id}/watchlist", diff --git a/crates/adapters/http-axum/src/html/templates/users.rs b/crates/adapters/http-axum/src/html/templates/users.rs index 0e514ea9..cd7fbf15 100644 --- a/crates/adapters/http-axum/src/html/templates/users.rs +++ b/crates/adapters/http-axum/src/html/templates/users.rs @@ -189,5 +189,6 @@ pub struct ProfileSettingsTemplate<'a> { pub also_known_as: Option<&'a str>, pub profile_fields: &'a [(String, String)], pub saved: bool, + pub error: Option<&'a str>, pub embed_url: String, } diff --git a/crates/adapters/http-axum/src/html/users.rs b/crates/adapters/http-axum/src/html/users.rs index b6621b70..a2950f1b 100644 --- a/crates/adapters/http-axum/src/html/users.rs +++ b/crates/adapters/http-axum/src/html/users.rs @@ -1,3 +1,4 @@ +use crate::html::forms::DeleteAccountForm; use crate::html::helpers::build_page_context; use crate::html::templates::{ ProfileSettingsTemplate, RemoteActorDisplay, UserSummaryView, UsersTemplate, @@ -13,11 +14,16 @@ use application::users::{ update_profile_fields, }; use axum::{ + Form, extract::{Extension, Multipart, Path, Query, State}, http::StatusCode, response::IntoResponse, }; -use domain::{errors::DomainError, value_objects::Username}; +use domain::{ + errors::DomainError, + value_objects::{UserId, Username}, +}; +use uuid::Uuid; pub async fn get_users_list( OptionalCookieUser(user_id): OptionalCookieUser, @@ -76,6 +82,7 @@ pub async fn get_user_by_username( #[derive(serde::Deserialize, Default)] pub struct SavedQuery { pub saved: Option, + pub error: Option, } pub async fn get_profile_settings( @@ -109,6 +116,7 @@ pub async fn get_profile_settings( also_known_as: settings.also_known_as.as_deref(), profile_fields: &settings.fields, saved, + error: params.error.as_deref(), embed_url: format!( "{}/users/{}?embed=true", state.app_ctx.config.base_url, @@ -177,3 +185,61 @@ pub async fn post_profile_settings( axum::response::Redirect::to("/settings/profile?saved=1").into_response() } + +async fn delete_account( + state: &AppState, + actor: UserId, + target: UserId, + password: &str, +) -> Result<(), DomainError> { + application::users::request_account_deletion::execute( + &state.app_ctx.deps.users.request_account_deletion, + actor, + target, + password, + ) + .await +} + +pub async fn post_delete_own_account( + RequiredCookieUser(user_id): RequiredCookieUser, + State(state): State, + Extension(csrf): Extension, + Form(form): Form, +) -> impl IntoResponse { + if crate::html::csrf::mismatch(&csrf, &form.csrf_token) { + return StatusCode::FORBIDDEN.into_response(); + } + match delete_account(&state, user_id.clone(), user_id, &form.password).await { + Ok(()) => super::auth::get_logout(State(state)).await.into_response(), + Err(e) => axum::response::Redirect::to(&format!( + "/settings/profile?error={}", + crate::html::helpers::encode_domain_error(&e) + )) + .into_response(), + } +} + +pub async fn post_delete_user( + RequiredCookieUser(actor): RequiredCookieUser, + State(state): State, + Extension(csrf): Extension, + Path(target): Path, + Form(form): Form, +) -> impl IntoResponse { + if crate::html::csrf::mismatch(&csrf, &form.csrf_token) { + return StatusCode::FORBIDDEN.into_response(); + } + let target_id = UserId::from_uuid(target); + let own = actor == target_id; + match delete_account(&state, actor, target_id, &form.password).await { + // An admin removing their own account ends their own session too. + Ok(()) if own => super::auth::get_logout(State(state)).await.into_response(), + Ok(()) => axum::response::Redirect::to("/users").into_response(), + Err(e) => axum::response::Redirect::to(&format!( + "/users/{target}?error={}", + crate::html::helpers::encode_domain_error(&e) + )) + .into_response(), + } +} diff --git a/crates/adapters/http-axum/src/openapi/users.rs b/crates/adapters/http-axum/src/openapi/users.rs index 6bbd4961..7c297909 100644 --- a/crates/adapters/http-axum/src/openapi/users.rs +++ b/crates/adapters/http-axum/src/openapi/users.rs @@ -1,6 +1,7 @@ use api_types::{ - ProfileFieldDto, ProfileResponse, ProfileViewData, UpdateProfileFieldsRequest, UserProfileBase, - UserProfileResponse, UserStatsDto, UserSummaryDto, UsersResponse, + DeleteAccountRequest, ProfileFieldDto, ProfileResponse, ProfileViewData, + UpdateProfileFieldsRequest, UserProfileBase, UserProfileResponse, UserStatsDto, UserSummaryDto, + UsersResponse, }; use utoipa::OpenApi; @@ -12,6 +13,8 @@ use utoipa::OpenApi; crate::api::users::get_profile, crate::api::users::update_profile_handler, crate::api::users::update_profile_fields_handler, + crate::api::users::delete_me, + crate::api::users::delete_user, ), components(schemas( UsersResponse, @@ -23,6 +26,7 @@ use utoipa::OpenApi; ProfileResponse, UpdateProfileFieldsRequest, ProfileFieldDto, + DeleteAccountRequest, )) )] pub struct UsersDoc; diff --git a/crates/adapters/http-axum/templates/profile.html b/crates/adapters/http-axum/templates/profile.html index a4111264..bfbbd4fd 100644 --- a/crates/adapters/http-axum/templates/profile.html +++ b/crates/adapters/http-axum/templates/profile.html @@ -97,6 +97,20 @@ {% endif %} + {% if ctx.is_admin && !is_own_profile %} +
+

Admin

+ {% if let Some(err) = error %} +

{{ err }}

+ {% endif %} +
+ + + +
+
+ {% endif %} +
Recent Top Rated diff --git a/crates/adapters/http-axum/templates/profile_settings.html b/crates/adapters/http-axum/templates/profile_settings.html index 86be4691..6d24c2f2 100644 --- a/crates/adapters/http-axum/templates/profile_settings.html +++ b/crates/adapters/http-axum/templates/profile_settings.html @@ -7,6 +7,9 @@ {% if saved %}

Saved.

{% endif %} +{% if let Some(err) = error %} +

{{ err }}

+{% endif %}
@@ -62,4 +65,19 @@

Add your diary to your blog or website:

<iframe src="{{ embed_url }}" width="100%" height="600" style="border:none;border-radius:8px" loading="lazy"></iframe>
+ +
+

Delete account

+

+ Permanently removes your account and everything on it: reviews, watchlist, goals, follows and uploaded images. This cannot be undone. +

+ + + + + +
{% endblock %} diff --git a/crates/api-types/src/users.rs b/crates/api-types/src/users.rs index 17f783c5..5e8fbe8a 100644 --- a/crates/api-types/src/users.rs +++ b/crates/api-types/src/users.rs @@ -153,6 +153,12 @@ pub struct UpdateProfileFieldsRequest { pub fields: Vec, } +/// Proof of intent for account deletion: the acting user's own password. +#[derive(Debug, Clone, Deserialize, utoipa::ToSchema)] +pub struct DeleteAccountRequest { + pub password: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)] pub struct UserSettingsDto { pub federate_goals: bool, diff --git a/crates/bootstrap/tests/account_deletion_test.rs b/crates/bootstrap/tests/account_deletion_test.rs new file mode 100644 index 00000000..d87ab695 --- /dev/null +++ b/crates/bootstrap/tests/account_deletion_test.rs @@ -0,0 +1,223 @@ +//! Account deletion over HTTP: JSON and classic endpoints on the real wiring. + +mod support; + +use axum::{ + body::Body, + http::{Method, Request, header}, +}; +use support::{PASSWORD, Session, get, json_request, send}; + +async fn promote(pool: &sqlx::SqlitePool, user_id: &str) { + sqlx::query("UPDATE users SET role = 'admin' WHERE id = ?") + .bind(user_id) + .execute(pool) + .await + .unwrap(); +} + +fn delete_json(uri: &str, token: &str, password: &str) -> Request { + json_request( + Method::DELETE, + uri, + Some(token), + serde_json::json!({ "password": password }), + ) +} + +fn classic_post(uri: &str, cookie: &str, password: &str) -> Request { + let csrf = cookie + .split(';') + .find_map(|c| c.trim().strip_prefix("csrf=")) + .unwrap(); + Request::builder() + .method(Method::POST) + .uri(uri) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .header(header::COOKIE, cookie) + .body(Body::from(format!("password={password}&_csrf={csrf}"))) + .unwrap() +} + +fn location(headers: &axum::http::HeaderMap) -> String { + headers + .get(header::LOCATION) + .map(|v| v.to_str().unwrap().to_string()) + .unwrap_or_default() +} + +async fn two_users() -> (axum::Router, sqlx::SqlitePool, Session, Session) { + let (router, pool) = support::server().await; + let alice = support::register(&router, "alice", "alice@example.com").await; + let bob = support::register(&router, "bob", "bob@example.com").await; + (router, pool, alice, bob) +} + +#[tokio::test] +async fn self_delete_with_a_wrong_password_is_refused_and_keeps_the_account() { + let (router, _pool, alice, _bob) = two_users().await; + let (status, _, body) = send( + &router, + delete_json("/api/v1/users/me", &alice.token, "nope"), + ) + .await; + assert_eq!(status, 401, "{body}"); + let (status, _, _) = send(&router, get(&format!("/users/{}", alice.user_id), None)).await; + assert_eq!(status, 200); +} + +#[tokio::test] +async fn self_delete_removes_the_account_and_revokes_the_token() { + let (router, _pool, alice, _bob) = two_users().await; + let (status, _, body) = send( + &router, + delete_json("/api/v1/users/me", &alice.token, PASSWORD), + ) + .await; + assert_eq!(status, 204, "{body}"); + + let req = Request::builder() + .uri("/api/v1/profile") + .header(header::AUTHORIZATION, format!("Bearer {}", alice.token)) + .body(Body::empty()) + .unwrap(); + let (status, _, _) = send(&router, req).await; + assert_eq!(status, 401, "token of a deleted account"); + + for uri in [ + format!("/users/{}", alice.user_id), + format!("/users/{}?embed=true", alice.user_id), + ] { + let (status, _, _) = send(&router, get(&uri, None)).await; + assert_eq!(status, 404, "{uri}"); + } +} + +#[tokio::test] +async fn a_standard_user_cannot_delete_someone_else() { + let (router, _pool, alice, bob) = two_users().await; + let uri = format!("/api/v1/users/{}", bob.user_id); + let (status, _, body) = send(&router, delete_json(&uri, &alice.token, PASSWORD)).await; + assert_eq!(status, 403, "{body}"); + let (status, _, _) = send(&router, get(&format!("/users/{}", bob.user_id), None)).await; + assert_eq!(status, 200); +} + +#[tokio::test] +async fn an_admin_deletes_another_account() { + let (router, pool, alice, bob) = two_users().await; + promote(&pool, &alice.user_id).await; + let uri = format!("/api/v1/users/{}", bob.user_id); + + let (status, _, _) = send(&router, delete_json(&uri, &alice.token, "nope")).await; + assert_eq!(status, 401, "wrong admin password"); + + let (status, _, body) = send(&router, delete_json(&uri, &alice.token, PASSWORD)).await; + assert_eq!(status, 204, "{body}"); + + for uri in [ + format!("/users/{}", bob.user_id), + format!("/users/{}?embed=true", bob.user_id), + ] { + let (status, _, _) = send(&router, get(&uri, None)).await; + assert_eq!(status, 404, "{uri}"); + } + let (status, _, _) = send(&router, delete_json(&uri, &alice.token, PASSWORD)).await; + assert_eq!(status, 404, "already deleted"); + + #[cfg(feature = "federation")] + { + let req = Request::builder() + .uri(format!("/users/{}", bob.user_id)) + .header(header::ACCEPT, "application/activity+json") + .body(Body::empty()) + .unwrap(); + let (status, _, _) = send(&router, req).await; + assert_eq!(status, 410, "actor endpoint of a deleted account"); + } +} + +#[tokio::test] +async fn the_last_admin_cannot_be_deleted() { + let (router, pool, alice, _bob) = two_users().await; + promote(&pool, &alice.user_id).await; + let (status, _, body) = send( + &router, + delete_json("/api/v1/users/me", &alice.token, PASSWORD), + ) + .await; + assert_eq!(status, 409, "{body}"); + let (status, _, _) = send(&router, get(&format!("/users/{}", alice.user_id), None)).await; + assert_eq!(status, 200); +} + +#[tokio::test] +async fn classic_self_delete_logs_out_and_redirects_home() { + let (router, _pool, alice, _bob) = two_users().await; + + let (status, headers, _) = send( + &router, + classic_post("/settings/account/delete", &alice.cookie, "nope"), + ) + .await; + assert_eq!(status, 303); + assert!( + location(&headers).starts_with("/settings/profile?error="), + "{headers:?}" + ); + assert!( + support::cookie_value(&headers, "token").is_none(), + "a wrong password must not log out" + ); + + let (status, headers, _) = send( + &router, + classic_post("/settings/account/delete", &alice.cookie, PASSWORD), + ) + .await; + assert_eq!(status, 303); + assert_eq!(location(&headers), "/"); + assert_eq!( + support::cookie_value(&headers, "token").as_deref(), + Some("") + ); + + let (status, _, _) = send(&router, get(&format!("/users/{}", alice.user_id), None)).await; + assert_eq!(status, 404); +} + +#[tokio::test] +async fn classic_self_delete_requires_the_csrf_token() { + let (router, _pool, alice, _bob) = two_users().await; + let req = Request::builder() + .method(Method::POST) + .uri("/settings/account/delete") + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .header(header::COOKIE, &alice.cookie) + .body(Body::from(format!("password={PASSWORD}&_csrf=wrong"))) + .unwrap(); + let (status, _, _) = send(&router, req).await; + assert_eq!(status, 403); +} + +#[tokio::test] +async fn classic_admin_delete_redirects_to_the_member_list() { + let (router, pool, alice, bob) = two_users().await; + let uri = format!("/users/{}/delete", bob.user_id); + + let (status, headers, _) = send(&router, classic_post(&uri, &alice.cookie, PASSWORD)).await; + assert_eq!(status, 303); + assert!( + location(&headers).contains("error="), + "non-admin: {headers:?}" + ); + + promote(&pool, &alice.user_id).await; + let (status, headers, _) = send(&router, classic_post(&uri, &alice.cookie, PASSWORD)).await; + assert_eq!(status, 303); + assert_eq!(location(&headers), "/users"); + assert!(support::cookie_value(&headers, "token").is_none()); + + let (status, _, _) = send(&router, get(&format!("/users/{}", bob.user_id), None)).await; + assert_eq!(status, 404); +} diff --git a/crates/bootstrap/tests/fixtures/openapi_paths.txt b/crates/bootstrap/tests/fixtures/openapi_paths.txt index 851c39a0..4d8d7a84 100644 --- a/crates/bootstrap/tests/fixtures/openapi_paths.txt +++ b/crates/bootstrap/tests/fixtures/openapi_paths.txt @@ -3,6 +3,8 @@ DELETE /api/v1/goals/{year} DELETE /api/v1/import/profiles/{id} DELETE /api/v1/reviews/{id} DELETE /api/v1/settings/webhook-tokens/{id} +DELETE /api/v1/users/me +DELETE /api/v1/users/{id} DELETE /api/v1/watchlist/{movie_id} DELETE /api/v1/wrapups/{id} GET /api/v1/activity-feed diff --git a/crates/bootstrap/tests/fixtures/openapi_paths_federation_off.txt b/crates/bootstrap/tests/fixtures/openapi_paths_federation_off.txt index ea1b1b54..6687aaab 100644 --- a/crates/bootstrap/tests/fixtures/openapi_paths_federation_off.txt +++ b/crates/bootstrap/tests/fixtures/openapi_paths_federation_off.txt @@ -2,6 +2,8 @@ DELETE /api/v1/goals/{year} DELETE /api/v1/import/profiles/{id} DELETE /api/v1/reviews/{id} DELETE /api/v1/settings/webhook-tokens/{id} +DELETE /api/v1/users/me +DELETE /api/v1/users/{id} DELETE /api/v1/watchlist/{movie_id} DELETE /api/v1/wrapups/{id} GET /api/v1/activity-feed