From 664ecfde33523ef5afaa34dec34edb0a4d2b3f60 Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 10:12:54 +0100 Subject: [PATCH 01/12] feat(rust): add delete account endpoint --- ...41e59c56a0dbd6a1cb436c5a92e53062505ab2.json | 14 ++++++++++++++ .../keygo-server/src/api/authenticated.rs | 6 ------ rust/crates/keygo-server/src/api/mod.rs | 1 + .../keygo-server/src/api/routes/account.rs | 18 ++++++++++++++++++ rust/crates/keygo-server/src/api/routes/mod.rs | 1 + rust/crates/keygo-server/src/db/users.rs | 8 ++++++++ .../crates/keygo-server/src/service/account.rs | 8 ++++++++ rust/crates/keygo-server/src/service/mod.rs | 1 + 8 files changed, 51 insertions(+), 6 deletions(-) create mode 100644 rust/crates/keygo-server/.sqlx/query-b0539523e23773e7d01ac00be741e59c56a0dbd6a1cb436c5a92e53062505ab2.json create mode 100644 rust/crates/keygo-server/src/api/routes/account.rs create mode 100644 rust/crates/keygo-server/src/service/account.rs diff --git a/rust/crates/keygo-server/.sqlx/query-b0539523e23773e7d01ac00be741e59c56a0dbd6a1cb436c5a92e53062505ab2.json b/rust/crates/keygo-server/.sqlx/query-b0539523e23773e7d01ac00be741e59c56a0dbd6a1cb436c5a92e53062505ab2.json new file mode 100644 index 000000000..f60705b69 --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-b0539523e23773e7d01ac00be741e59c56a0dbd6a1cb436c5a92e53062505ab2.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "delete from users where id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "b0539523e23773e7d01ac00be741e59c56a0dbd6a1cb436c5a92e53062505ab2" +} diff --git a/rust/crates/keygo-server/src/api/authenticated.rs b/rust/crates/keygo-server/src/api/authenticated.rs index f1f735f31..2e27653b7 100644 --- a/rust/crates/keygo-server/src/api/authenticated.rs +++ b/rust/crates/keygo-server/src/api/authenticated.rs @@ -113,10 +113,6 @@ impl FromRequestParts for Authenticated { } } -#[cfg_attr( - not(test), - expect(dead_code, reason = "no route requires a fresh sign-in yet") -)] #[derive(Debug, Error)] #[error("recent sign-in required")] pub struct FreshAuthRequired; @@ -127,10 +123,8 @@ impl HttpError for FreshAuthRequired { } } -#[expect(dead_code, reason = "no route requires a fresh sign-in yet")] pub struct FreshAuthenticated(Authenticated); -#[expect(dead_code, reason = "no route requires a fresh sign-in yet")] impl FreshAuthenticated { pub fn claims(&self) -> &Claims { self.0.claims() diff --git a/rust/crates/keygo-server/src/api/mod.rs b/rust/crates/keygo-server/src/api/mod.rs index 0a7b7d695..be8323658 100644 --- a/rust/crates/keygo-server/src/api/mod.rs +++ b/rust/crates/keygo-server/src/api/mod.rs @@ -34,6 +34,7 @@ fn v1() -> Router { .nest("/meta", routes::meta::router()) .nest("/auth", routes::auth::router()) .nest("/devices", routes::devices::router()) + .nest("/account", routes::account::router()) } async fn not_found() -> ServerError { diff --git a/rust/crates/keygo-server/src/api/routes/account.rs b/rust/crates/keygo-server/src/api/routes/account.rs new file mode 100644 index 000000000..031714702 --- /dev/null +++ b/rust/crates/keygo-server/src/api/routes/account.rs @@ -0,0 +1,18 @@ +use crate::api::authenticated::FreshAuthenticated; +use crate::api::{AppState, ServerResult}; +use crate::service::account; +use axum::Router; +use axum::extract::State; +use axum::routing::delete; + +pub fn router() -> Router { + Router::new().route("/", delete(delete_account)) +} + +async fn delete_account( + State(state): State, + authenticated: FreshAuthenticated, +) -> ServerResult<()> { + account::delete(&state.db, authenticated.claims().user_id()).await?; + Ok(()) +} diff --git a/rust/crates/keygo-server/src/api/routes/mod.rs b/rust/crates/keygo-server/src/api/routes/mod.rs index 8d63b5fa7..156466575 100644 --- a/rust/crates/keygo-server/src/api/routes/mod.rs +++ b/rust/crates/keygo-server/src/api/routes/mod.rs @@ -1,3 +1,4 @@ +pub mod account; pub mod auth; pub mod devices; pub mod health; diff --git a/rust/crates/keygo-server/src/db/users.rs b/rust/crates/keygo-server/src/db/users.rs index 6ae91cc92..374a01532 100644 --- a/rust/crates/keygo-server/src/db/users.rs +++ b/rust/crates/keygo-server/src/db/users.rs @@ -53,6 +53,14 @@ pub async fn find_username( Username::parse(&username).map(Some).map_err(corrupt) } +pub async fn delete(conn: &mut PgConnection, user_id: UserId) -> sqlx::Result<()> { + sqlx::query!("delete from users where id = $1", user_id.as_uuid()) + .execute(conn) + .await?; + + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/rust/crates/keygo-server/src/service/account.rs b/rust/crates/keygo-server/src/service/account.rs new file mode 100644 index 000000000..33099c4e1 --- /dev/null +++ b/rust/crates/keygo-server/src/service/account.rs @@ -0,0 +1,8 @@ +use crate::db::users; +use keygo_core::UserId; +use sqlx::PgPool; + +pub async fn delete(db: &PgPool, user_id: UserId) -> sqlx::Result<()> { + let mut conn = db.acquire().await?; + users::delete(&mut conn, user_id).await +} diff --git a/rust/crates/keygo-server/src/service/mod.rs b/rust/crates/keygo-server/src/service/mod.rs index 35e6d1172..5e5a0fae8 100644 --- a/rust/crates/keygo-server/src/service/mod.rs +++ b/rust/crates/keygo-server/src/service/mod.rs @@ -1,3 +1,4 @@ +pub mod account; pub mod device; pub mod handshake; pub mod invite; From be88b8fe93a963fcc72dccdf2a8d1ffa4d747508 Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 10:17:39 +0100 Subject: [PATCH 02/12] feat(rust): add delete account to sync client --- rust/crates/keygo-api/src/endpoints.rs | 1 + rust/crates/keygo-client/src/sync/client.rs | 12 ++++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/rust/crates/keygo-api/src/endpoints.rs b/rust/crates/keygo-api/src/endpoints.rs index f6d4d1a5f..ed8394e8c 100644 --- a/rust/crates/keygo-api/src/endpoints.rs +++ b/rust/crates/keygo-api/src/endpoints.rs @@ -44,6 +44,7 @@ endpoints! { Token: Post "/api/v1/auth/token", Proof, auth::token::TokenRequest => auth::Session; Logout: Post "/api/v1/auth/logout", AccessToken, () => (); ListDevices: Get "/api/v1/devices", AccessToken, () => devices::Devices; + DeleteAccount: Delete "/api/v1/account", AccessToken, () => (); } pub struct DeleteDevice { diff --git a/rust/crates/keygo-client/src/sync/client.rs b/rust/crates/keygo-client/src/sync/client.rs index b82efa546..045c59747 100644 --- a/rust/crates/keygo-client/src/sync/client.rs +++ b/rust/crates/keygo-client/src/sync/client.rs @@ -9,8 +9,8 @@ use keygo_api::Endpoint; use keygo_api::auth::{Session, login, register, step_up}; use keygo_api::domain::{Device, DeviceClaim, DeviceInfo, KeyBundle, Username}; use keygo_api::endpoints::{ - DeleteDevice, ListDevices, LoginFinish, LoginStart, Logout, Meta, RegisterFinish, - RegisterStart, StepUpFinish, StepUpStart, + DeleteAccount, DeleteDevice, ListDevices, LoginFinish, LoginStart, Logout, Meta, + RegisterFinish, RegisterStart, StepUpFinish, StepUpStart, }; use keygo_api::meta::ServerInfo; use keygo_core::{CryptoError, DeviceId, UserId}; @@ -340,6 +340,14 @@ impl SyncClient { (sent, _) => sent, } } + + /// Deletes the account. The client must have a fresh session in order to delete the account. + /// This will delete all account related data, such as vaults, keys, sessions, devices, etc. + /// **A user will _not_ be able to sign in again with this account. All data are lost + /// permanently and can _not_ be retrieved.** + pub async fn delete_account(&self) -> SyncResult<()> { + self.call(&DeleteAccount, &()).await + } } fn is_reattached(session: &Session, claimed: Option) -> bool { From 132b66c5cadf79d15d43eb45bfad07919c365374 Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 10:23:23 +0100 Subject: [PATCH 03/12] feat(rust): add delet account uniffi bindings --- rust/crates/keygo-uniffi/src/sync.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rust/crates/keygo-uniffi/src/sync.rs b/rust/crates/keygo-uniffi/src/sync.rs index 52e8512a9..8b1a11ab6 100644 --- a/rust/crates/keygo-uniffi/src/sync.rs +++ b/rust/crates/keygo-uniffi/src/sync.rs @@ -471,6 +471,10 @@ impl SyncClient { pub async fn logout(self: Arc) -> Result<(), SyncError> { detached(async move { self.inner.logout().await }).await } + + pub async fn delete_account(self: Arc) -> Result<(), SyncError> { + detached(async move { self.inner.delete_account().await }).await + } } #[cfg(test)] From 2cd0c5be43bc9565a0d4743a018be7126af9a4be Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 10:48:52 +0100 Subject: [PATCH 04/12] feat(rust): clear session upon account deletion --- rust/crates/keygo-client/src/sync/client.rs | 15 +++++++---- rust/crates/keygo-client/src/sync/pipeline.rs | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/rust/crates/keygo-client/src/sync/client.rs b/rust/crates/keygo-client/src/sync/client.rs index 045c59747..cd85c7a95 100644 --- a/rust/crates/keygo-client/src/sync/client.rs +++ b/rust/crates/keygo-client/src/sync/client.rs @@ -341,12 +341,17 @@ impl SyncClient { } } - /// Deletes the account. The client must have a fresh session in order to delete the account. - /// This will delete all account related data, such as vaults, keys, sessions, devices, etc. - /// **A user will _not_ be able to sign in again with this account. All data are lost - /// permanently and can _not_ be retrieved.** + /// Permanently deletes the account and all its server data; the local vault is kept. + /// **This cannot be undone: the account can never be signed in to again, and its server + /// data is lost and can _not_ be recovered.** + /// Needs a fresh sign-in, else [`SyncError::FreshAuthRequired`] (see [`Self::step_up`]). + /// Ends the local session on success. pub async fn delete_account(&self) -> SyncResult<()> { - self.call(&DeleteAccount, &()).await + self.call(&DeleteAccount, &()).await?; + let mut state = self.auth.lock().await; + // Best effort: the token is dead on the server, so one the store keeps is only rejected. + let _ = self.end_session(&mut state).await; + Ok(()) } } diff --git a/rust/crates/keygo-client/src/sync/pipeline.rs b/rust/crates/keygo-client/src/sync/pipeline.rs index c87e058f0..fa4366f45 100644 --- a/rust/crates/keygo-client/src/sync/pipeline.rs +++ b/rust/crates/keygo-client/src/sync/pipeline.rs @@ -1277,6 +1277,32 @@ mod tests { h.assert_signed_out_locally().await; } + #[tokio::test] + async fn delete_account_ends_the_session() { + let h = fresh().await; + h.transport.push(204, &[], b""); + + h.client.delete_account().await.unwrap(); + + let request = &h.transport.requests()[FRESH]; + assert_eq!(request.url, "https://kg.example/api/v1/account"); + assert_eq!(header(request, "authorization"), Some("DPoP a.b.c")); + h.assert_signed_out_locally().await; + } + + #[tokio::test] + async fn failed_delete_account_keeps_the_session() { + let h = fresh().await; + h.transport + .push(403, &[], &error_body("fresh_auth_required")); + + let error = h.client.delete_account().await.unwrap_err(); + + assert_eq!(error, SyncError::FreshAuthRequired); + assert!(h.client.auth.lock().await.access().is_some()); + assert!(h.store.current_refresh_token().is_some()); + } + #[tokio::test] async fn logout_clears_local_state_when_offline() { let h = fresh().await; From 913d7d279da3c811190a7ec0dee1b16b3c3ebf1a Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 11:12:23 +0100 Subject: [PATCH 05/12] fix(rust): delete account returns 204 --- rust/crates/keygo-server/src/api/routes/account.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/rust/crates/keygo-server/src/api/routes/account.rs b/rust/crates/keygo-server/src/api/routes/account.rs index 031714702..d80fc8082 100644 --- a/rust/crates/keygo-server/src/api/routes/account.rs +++ b/rust/crates/keygo-server/src/api/routes/account.rs @@ -3,6 +3,7 @@ use crate::api::{AppState, ServerResult}; use crate::service::account; use axum::Router; use axum::extract::State; +use axum::http::StatusCode; use axum::routing::delete; pub fn router() -> Router { @@ -12,7 +13,7 @@ pub fn router() -> Router { async fn delete_account( State(state): State, authenticated: FreshAuthenticated, -) -> ServerResult<()> { +) -> ServerResult { account::delete(&state.db, authenticated.claims().user_id()).await?; - Ok(()) + Ok(StatusCode::NO_CONTENT) } From d03455f0ebc2d3e1e4e95a61ea5a1e2e85d93b6d Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 11:12:54 +0100 Subject: [PATCH 06/12] tests(rust): add delete account tests --- rust/crates/keygo-e2e/tests/sync.rs | 52 +++++++++++++++++ .../keygo-server/src/api/routes/account.rs | 58 +++++++++++++++++++ .../keygo-server/src/service/account.rs | 55 ++++++++++++++++++ rust/crates/keygo-server/src/testing.rs | 28 ++++++++- 4 files changed, 190 insertions(+), 3 deletions(-) diff --git a/rust/crates/keygo-e2e/tests/sync.rs b/rust/crates/keygo-e2e/tests/sync.rs index 4dbb62dcc..b6e71f8cf 100644 --- a/rust/crates/keygo-e2e/tests/sync.rs +++ b/rust/crates/keygo-e2e/tests/sync.rs @@ -310,6 +310,58 @@ async fn client_logout_ends_the_session_on_the_server(db: PgPool) { assert!(!status.is_success(), "{status}"); } +#[sqlx::test(migrations = "../keygo-server/migrations")] +async fn delete_account_needs_a_fresh_sign_in(db: PgPool) { + let h = harness(&db).await; + sqlx::query("update sessions set auth_time = to_timestamp($1) where device_id = $2") + .bind((SystemClock.now_secs() - 301) as f64) + .bind(h.device_id.as_uuid()) + .execute(&db) + .await + .unwrap(); + + assert_eq!( + h.client.delete_account().await.unwrap_err(), + SyncError::FreshAuthRequired, + ); + assert_eq!(testing::count(&db, "users").await, 1); + + h.client.step_up(password()).await.unwrap(); + h.client.delete_account().await.unwrap(); + + assert_eq!(testing::count(&db, "users").await, 0); + assert_eq!(h.store.current_refresh_token(), None); + assert_eq!( + h.client.devices().await.unwrap_err(), + SyncError::SignedOut { reason: None }, + ); +} + +#[sqlx::test(migrations = "../keygo-server/migrations")] +async fn deleted_account_cannot_sign_in_and_frees_the_username(db: PgPool) { + let (client, _, state) = signed_out(&db); + let (ark_session, user_id) = local_account(); + register(&client, &ark_session, user_id, "ada").await; + + // Registration counts as a fresh sign-in. + client.delete_account().await.unwrap(); + + let error = client + .login( + &ark_session, + "ada".into(), + password(), + testing::device_info(), + ) + .await + .unwrap_err(); + assert_eq!(error, SyncError::InvalidCredentials); + + let (newcomer, _) = client_of(&state); + let (ark_session, user_id) = local_account(); + register(&newcomer, &ark_session, user_id, "ada").await; +} + #[sqlx::test(migrations = "../keygo-server/migrations")] async fn register_signs_the_device_in(db: PgPool) { let (client, store, _) = signed_out(&db); diff --git a/rust/crates/keygo-server/src/api/routes/account.rs b/rust/crates/keygo-server/src/api/routes/account.rs index d80fc8082..2e4c06982 100644 --- a/rust/crates/keygo-server/src/api/routes/account.rs +++ b/rust/crates/keygo-server/src/api/routes/account.rs @@ -17,3 +17,61 @@ async fn delete_account( account::delete(&state.db, authenticated.claims().user_id()).await?; Ok(StatusCode::NO_CONTENT) } + +#[cfg(test)] +mod tests { + use crate::domain::{FRESH_AUTH_WINDOW, unix_now}; + use crate::testing::{count, delete_with_token, prover, signed_in, token_issuer}; + use axum::http::StatusCode; + use sqlx::PgPool; + + const URI: &str = "/api/v1/account"; + + #[sqlx::test] + async fn fresh_session_deletes_the_account(db: PgPool) { + let prover = prover(); + let (state, issued) = signed_in(&db, &prover).await; + let token = issued.access_token.expose(); + + let (status, body) = delete_with_token(&state, &prover, URI, token).await; + + assert_eq!(status, StatusCode::NO_CONTENT); + assert!(body.is_null()); + assert_eq!(count(&db, "users").await, 0); + } + + #[sqlx::test] + async fn deleted_account_revokes_its_tokens(db: PgPool) { + let prover = prover(); + let (state, issued) = signed_in(&db, &prover).await; + let token = issued.access_token.expose(); + delete_with_token(&state, &prover, URI, token).await; + + let (status, body) = delete_with_token(&state, &prover, URI, token).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "session_revoked"); + assert!(body.get("reason").is_none()); + } + + #[sqlx::test] + async fn stale_session_cannot_delete_the_account(db: PgPool) { + let prover = prover(); + let (state, issued) = signed_in(&db, &prover).await; + let issuer = token_issuer(); + let claims = issuer.verify(issued.access_token.expose()).unwrap(); + let auth_time = unix_now() - FRESH_AUTH_WINDOW.as_secs() - 1; + let stale = issuer.issue( + claims.user_id(), + claims.session_id(), + auth_time, + prover.jkt(), + ); + + let (status, body) = delete_with_token(&state, &prover, URI, stale.expose()).await; + + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(body["code"], "fresh_auth_required"); + assert_eq!(count(&db, "users").await, 1); + } +} diff --git a/rust/crates/keygo-server/src/service/account.rs b/rust/crates/keygo-server/src/service/account.rs index 33099c4e1..9324a26cf 100644 --- a/rust/crates/keygo-server/src/service/account.rs +++ b/rust/crates/keygo-server/src/service/account.rs @@ -6,3 +6,58 @@ pub async fn delete(db: &PgPool, user_id: UserId) -> sqlx::Result<()> { let mut conn = db.acquire().await?; users::delete(&mut conn, user_id).await } + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{count, register}; + use keygo_opaque::server::ServerSetup; + + /// Every table that holds rows for a user, directly or through its devices. + const OWNED: [&str; 6] = [ + "users", + "opaque_records", + "key_bundles", + "devices", + "sessions", + "refresh_tokens", + ]; + + #[sqlx::test] + async fn delete_removes_everything_the_account_owns(db: PgPool) { + let user_id = register(&db, &ServerSetup::generate(), "ada").await; + for table in OWNED { + assert_eq!(count(&db, table).await, 1, "{table}"); + } + + delete(&db, user_id).await.unwrap(); + + for table in OWNED { + assert_eq!(count(&db, table).await, 0, "{table}"); + } + } + + #[sqlx::test] + async fn delete_keeps_other_accounts(db: PgPool) { + let setup = ServerSetup::generate(); + let ada = register(&db, &setup, "ada").await; + register(&db, &setup, "bob").await; + + delete(&db, ada).await.unwrap(); + + for table in OWNED { + assert_eq!(count(&db, table).await, 1, "{table}"); + } + } + + #[sqlx::test] + async fn delete_frees_the_username(db: PgPool) { + let setup = ServerSetup::generate(); + let ada = register(&db, &setup, "ada").await; + + delete(&db, ada).await.unwrap(); + + // `register` unwraps every step, so a taken name would panic here. + register(&db, &setup, "ada").await; + } +} diff --git a/rust/crates/keygo-server/src/testing.rs b/rust/crates/keygo-server/src/testing.rs index 86dd242b8..86ed234b2 100644 --- a/rust/crates/keygo-server/src/testing.rs +++ b/rust/crates/keygo-server/src/testing.rs @@ -11,7 +11,7 @@ use crate::service::session::{self, Issued}; use crate::service::{handshake, invite}; use axum::body::Body; use axum::http::header::AUTHORIZATION; -use axum::http::{HeaderMap, Request, StatusCode}; +use axum::http::{HeaderMap, Method, Request, StatusCode}; use http_body_util::BodyExt; use keygo_core::{AccountRootKey, Sealed}; use keygo_dpop::DpopVerifier; @@ -303,7 +303,20 @@ pub fn proof_post( ) -> Request { with_proof(state, prover, json_post(uri, body), None, nonce) } -/// Signs a proof for the POST `request` makes and attaches it, with the access token it is bound +/// Deletes as the session behind `access_token`. +pub async fn delete_with_token( + state: &AppState, + prover: &DpopProver, + uri: &str, + access_token: &str, +) -> (StatusCode, Value) { + send_with_nonce(state, |nonce| { + let request = Request::delete(uri).body(Body::empty()).unwrap(); + with_proof(state, prover, request, Some(access_token), nonce) + }) + .await +} +/// Signs a proof for the `request` it is given and attaches it, with the access token it is bound /// to when one is given. pub fn with_proof( state: &AppState, @@ -315,7 +328,7 @@ pub fn with_proof( let htu = state.public_url.join(request.uri().path()).unwrap(); let proof = prover .proof(&ProofRequest { - htm: Htm::Post, + htm: htm(request.method()), htu: htu.as_str(), access_token, nonce, @@ -332,6 +345,15 @@ pub fn with_proof( request } +fn htm(method: &Method) -> Htm { + match *method { + Method::GET => Htm::Get, + Method::POST => Htm::Post, + Method::DELETE => Htm::Delete, + ref other => panic!("no DPoP htm for {other}"), + } +} + /// Signs one proof carrying the verifier's nonce and builds identical requests around it, the way /// an attacker replays a captured request. Fetching the nonce takes a challenge, which keeps state. pub async fn replayable_post( From 74252c1bd55c24c3ed6309fe51f71971ffc36b5c Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 11:19:41 +0100 Subject: [PATCH 07/12] feat(rust): always step-up for account deletion --- rust/crates/keygo-client/src/sync/client.rs | 7 +++-- rust/crates/keygo-client/src/sync/pipeline.rs | 28 +++++++------------ rust/crates/keygo-e2e/tests/sync.rs | 27 ++++++++++-------- rust/crates/keygo-uniffi/src/sync.rs | 5 ++-- 4 files changed, 33 insertions(+), 34 deletions(-) diff --git a/rust/crates/keygo-client/src/sync/client.rs b/rust/crates/keygo-client/src/sync/client.rs index cd85c7a95..5439a8b9c 100644 --- a/rust/crates/keygo-client/src/sync/client.rs +++ b/rust/crates/keygo-client/src/sync/client.rs @@ -344,9 +344,10 @@ impl SyncClient { /// Permanently deletes the account and all its server data; the local vault is kept. /// **This cannot be undone: the account can never be signed in to again, and its server /// data is lost and can _not_ be recovered.** - /// Needs a fresh sign-in, else [`SyncError::FreshAuthRequired`] (see [`Self::step_up`]). - /// Ends the local session on success. - pub async fn delete_account(&self) -> SyncResult<()> { + /// Always proves `password` first (see [`Self::step_up`]), even on a fresh session: typing + /// it is the confirmation. Ends the local session on success. + pub async fn delete_account(&self, password: &str) -> SyncResult<()> { + self.step_up(password).await?; self.call(&DeleteAccount, &()).await?; let mut state = self.auth.lock().await; // Best effort: the token is dead on the server, so one the store keeps is only rejected. diff --git a/rust/crates/keygo-client/src/sync/pipeline.rs b/rust/crates/keygo-client/src/sync/pipeline.rs index fa4366f45..4fd99f22b 100644 --- a/rust/crates/keygo-client/src/sync/pipeline.rs +++ b/rust/crates/keygo-client/src/sync/pipeline.rs @@ -1278,27 +1278,19 @@ mod tests { } #[tokio::test] - async fn delete_account_ends_the_session() { + async fn delete_account_steps_up_first_and_keeps_the_session_on_failure() { let h = fresh().await; - h.transport.push(204, &[], b""); - - h.client.delete_account().await.unwrap(); - - let request = &h.transport.requests()[FRESH]; - assert_eq!(request.url, "https://kg.example/api/v1/account"); - assert_eq!(header(request, "authorization"), Some("DPoP a.b.c")); - h.assert_signed_out_locally().await; - } - - #[tokio::test] - async fn failed_delete_account_keeps_the_session() { - let h = fresh().await; - h.transport - .push(403, &[], &error_body("fresh_auth_required")); + h.transport.push_network_failure(NetworkError::Other); - let error = h.client.delete_account().await.unwrap_err(); + let error = h.client.delete_account("password").await.unwrap_err(); - assert_eq!(error, SyncError::FreshAuthRequired); + assert!(matches!(error, SyncError::Network(_)), "{error:?}"); + let requests = h.transport.requests(); + assert_eq!(requests.len(), FRESH + 1); + assert_eq!( + requests[FRESH].url, + "https://kg.example/api/v1/auth/step-up/start" + ); assert!(h.client.auth.lock().await.access().is_some()); assert!(h.store.current_refresh_token().is_some()); } diff --git a/rust/crates/keygo-e2e/tests/sync.rs b/rust/crates/keygo-e2e/tests/sync.rs index b6e71f8cf..1a520f2b5 100644 --- a/rust/crates/keygo-e2e/tests/sync.rs +++ b/rust/crates/keygo-e2e/tests/sync.rs @@ -311,7 +311,7 @@ async fn client_logout_ends_the_session_on_the_server(db: PgPool) { } #[sqlx::test(migrations = "../keygo-server/migrations")] -async fn delete_account_needs_a_fresh_sign_in(db: PgPool) { +async fn delete_account_steps_up_a_stale_session(db: PgPool) { let h = harness(&db).await; sqlx::query("update sessions set auth_time = to_timestamp($1) where device_id = $2") .bind((SystemClock.now_secs() - 301) as f64) @@ -320,14 +320,7 @@ async fn delete_account_needs_a_fresh_sign_in(db: PgPool) { .await .unwrap(); - assert_eq!( - h.client.delete_account().await.unwrap_err(), - SyncError::FreshAuthRequired, - ); - assert_eq!(testing::count(&db, "users").await, 1); - - h.client.step_up(password()).await.unwrap(); - h.client.delete_account().await.unwrap(); + h.client.delete_account(password()).await.unwrap(); assert_eq!(testing::count(&db, "users").await, 0); assert_eq!(h.store.current_refresh_token(), None); @@ -337,14 +330,26 @@ async fn delete_account_needs_a_fresh_sign_in(db: PgPool) { ); } +#[sqlx::test(migrations = "../keygo-server/migrations")] +async fn delete_account_with_a_wrong_password_keeps_the_account(db: PgPool) { + let h = harness(&db).await; + + assert_eq!( + h.client.delete_account("wrong").await.unwrap_err(), + SyncError::InvalidCredentials, + ); + + assert_eq!(testing::count(&db, "users").await, 1); + h.client.devices().await.unwrap(); +} + #[sqlx::test(migrations = "../keygo-server/migrations")] async fn deleted_account_cannot_sign_in_and_frees_the_username(db: PgPool) { let (client, _, state) = signed_out(&db); let (ark_session, user_id) = local_account(); register(&client, &ark_session, user_id, "ada").await; - // Registration counts as a fresh sign-in. - client.delete_account().await.unwrap(); + client.delete_account(password()).await.unwrap(); let error = client .login( diff --git a/rust/crates/keygo-uniffi/src/sync.rs b/rust/crates/keygo-uniffi/src/sync.rs index 8b1a11ab6..e4259971c 100644 --- a/rust/crates/keygo-uniffi/src/sync.rs +++ b/rust/crates/keygo-uniffi/src/sync.rs @@ -472,8 +472,9 @@ impl SyncClient { detached(async move { self.inner.logout().await }).await } - pub async fn delete_account(self: Arc) -> Result<(), SyncError> { - detached(async move { self.inner.delete_account().await }).await + pub async fn delete_account(self: Arc, password: String) -> Result<(), SyncError> { + let password = Zeroizing::new(password); + detached(async move { self.inner.delete_account(&password).await }).await } } From b5bc68592cb8a70c3f0c41fcd0cc9039fb479557 Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 12:51:01 +0100 Subject: [PATCH 08/12] feat(feature-account): add account delete function in repo --- .../keygo/core/sync/data/repository/SyncRepositoryImpl.kt | 5 +++++ .../keygo/core/sync/domain/repository/SyncRepository.kt | 2 ++ 2 files changed, 7 insertions(+) diff --git a/core/sync/src/main/kotlin/de/davis/keygo/core/sync/data/repository/SyncRepositoryImpl.kt b/core/sync/src/main/kotlin/de/davis/keygo/core/sync/data/repository/SyncRepositoryImpl.kt index 48096ce50..c1002f41a 100644 --- a/core/sync/src/main/kotlin/de/davis/keygo/core/sync/data/repository/SyncRepositoryImpl.kt +++ b/core/sync/src/main/kotlin/de/davis/keygo/core/sync/data/repository/SyncRepositoryImpl.kt @@ -92,6 +92,11 @@ internal class SyncRepositoryImpl( override suspend fun stepUp(password: String): Result = withSessionClient { client, _ -> client.stepUp(password) } + override suspend fun deleteAccount(password: String): Result = + withSessionClient { client, _ -> + client.deleteAccount(password) + } + private suspend fun clientFor(serverUrl: String): SyncClient = clientLock.withLock { // Rust stores the origin as `Url` prints it, with a trailing slash; ServerAddress has none. val origin = serverUrl.trimEnd('/') diff --git a/core/sync/src/main/kotlin/de/davis/keygo/core/sync/domain/repository/SyncRepository.kt b/core/sync/src/main/kotlin/de/davis/keygo/core/sync/domain/repository/SyncRepository.kt index 02566492e..cb09f47a3 100644 --- a/core/sync/src/main/kotlin/de/davis/keygo/core/sync/domain/repository/SyncRepository.kt +++ b/core/sync/src/main/kotlin/de/davis/keygo/core/sync/domain/repository/SyncRepository.kt @@ -33,4 +33,6 @@ interface SyncRepository { suspend fun deleteDevice(deviceId: UUID): Result suspend fun stepUp(password: String): Result + + suspend fun deleteAccount(password: String): Result } From 0c69e7baaafe6ec28bb3b9608201e626c3e43a96 Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 13:01:35 +0100 Subject: [PATCH 09/12] feat(feature-account): add account deleted on click event --- .../davis/keygo/feature/account/presentation/AccountContent.kt | 2 +- .../keygo/feature/account/presentation/AccountViewModel.kt | 2 ++ .../keygo/feature/account/presentation/models/AccountUiEvent.kt | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountContent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountContent.kt index ac2b126de..91a748516 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountContent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountContent.kt @@ -172,7 +172,7 @@ private fun SettingsScope.connectedSection( title = R.string.delete_account, icon = Icons.Default.Delete, colors = deleteAccountColors, - onClick = {}, + onClick = { onEvent(AccountUiEvent.OnDeleteAccountClicked) }, ) } } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt index 16b84044d..d6ced3c6d 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt @@ -83,6 +83,8 @@ internal class AccountViewModel( if (_logoutDialog.value != LogoutDialogState.LoggingOut) _logoutDialog.update { LogoutDialogState.Hidden } + AccountUiEvent.OnDeleteAccountClicked -> {} + AccountUiEvent.ResetPassword -> _event.trySend(AccountEvent.NavigateToChangePassword) } } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt index 4ac5d6aae..5cc7d3a3b 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt @@ -9,5 +9,7 @@ internal sealed interface AccountUiEvent { data object OnLogoutConfirmed : AccountUiEvent data object OnLogoutDismissed : AccountUiEvent + data object OnDeleteAccountClicked : AccountUiEvent + data object ResetPassword : AccountUiEvent } From b3875f2c046032b56672b1d66443115559536e2b Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 27 Nov 2026 13:33:09 +0100 Subject: [PATCH 10/12] feat(feature-account): add delete account dialog --- .../de/davis/keygo/rust/FakeSyncClient.kt | 3 + .../password/PasswordConfirmDialog.kt | 131 ++++++++++++++++++ .../sync/presentation/stepup/StepUpDialog.kt | 93 ++----------- .../keygo/core/sync/FakeSyncRepository.kt | 9 ++ .../account/presentation/AccountContent.kt | 13 ++ .../account/presentation/AccountScreen.kt | 3 +- .../account/presentation/AccountViewModel.kt | 43 +++++- .../components/DeleteAccountDialog.kt | 85 ++++++++++++ .../presentation/models/AccountUiEvent.kt | 2 + .../presentation/models/AccountUiState.kt | 1 + .../models/DeleteAccountDialogState.kt | 10 ++ .../src/main/res/values-de/strings.xml | 3 + .../account/src/main/res/values/strings.xml | 3 + .../presentation/AccountViewModelTest.kt | 110 +++++++++++++++ .../setup/ConnectServerViewModelTest.kt | 3 + 15 files changed, 430 insertions(+), 82 deletions(-) create mode 100644 core/sync/src/main/kotlin/de/davis/keygo/core/sync/presentation/password/PasswordConfirmDialog.kt create mode 100644 feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/components/DeleteAccountDialog.kt create mode 100644 feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/DeleteAccountDialogState.kt diff --git a/core/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakeSyncClient.kt b/core/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakeSyncClient.kt index 62dc8a99a..47cdd3124 100644 --- a/core/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakeSyncClient.kt +++ b/core/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakeSyncClient.kt @@ -11,6 +11,7 @@ import de.davisalessandro.keygo.rust.UserId class FakeSyncClient : SyncClientInterface { + var deleteAccountResult: Result = Result.success(Unit) var deleteDeviceResult: Result = Result.success(Unit) var devicesResult: Result> = Result.success(emptyList()) var loginResult: Result? = null @@ -19,6 +20,8 @@ class FakeSyncClient : SyncClientInterface { var registerResult: Result? = null var stepUpResult: Result = Result.success(Unit) + override suspend fun deleteAccount(password: String) = deleteAccountResult.getOrThrow() + override suspend fun deleteDevice(id: DeviceId) = deleteDeviceResult.getOrThrow() override suspend fun devices(): List = devicesResult.getOrThrow() diff --git a/core/sync/src/main/kotlin/de/davis/keygo/core/sync/presentation/password/PasswordConfirmDialog.kt b/core/sync/src/main/kotlin/de/davis/keygo/core/sync/presentation/password/PasswordConfirmDialog.kt new file mode 100644 index 000000000..49dda906b --- /dev/null +++ b/core/sync/src/main/kotlin/de/davis/keygo/core/sync/presentation/password/PasswordConfirmDialog.kt @@ -0,0 +1,131 @@ +package de.davis.keygo.core.sync.presentation.password + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.TextObfuscationMode +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Lock +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedSecureTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.DialogProperties +import de.davis.keygo.core.sync.R +import de.davis.keygo.core.sync.domain.model.SyncError +import de.davis.keygo.core.sync.presentation.messageRes +import de.davis.keygo.core.ui.components.VisibilityButton + +@Composable +fun PasswordConfirmDialog( + password: TextFieldState, + busy: Boolean, + error: SyncError?, + onSubmit: () -> Unit, + onCancel: () -> Unit, + icon: @Composable () -> Unit, + title: @Composable () -> Unit, + message: @Composable () -> Unit, + confirmButton: @Composable (enabled: Boolean, onClick: () -> Unit) -> Unit, +) { + val hasText by remember(password) { derivedStateOf { password.text.isNotEmpty() } } + val canSubmit = !busy && hasText + val submit = { + if (canSubmit) onSubmit() + } + + AlertDialog( + onDismissRequest = onCancel, + properties = DialogProperties( + dismissOnBackPress = !busy, + dismissOnClickOutside = !busy, + ), + confirmButton = { confirmButton(canSubmit, submit) }, + dismissButton = { + TextButton(onClick = onCancel, enabled = !busy) { + Text(text = stringResource(android.R.string.cancel)) + } + }, + icon = icon, + title = title, + text = { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + message() + + var hidden by rememberSaveable { mutableStateOf(true) } + OutlinedSecureTextField( + state = password, + modifier = Modifier.fillMaxWidth(), + enabled = !busy, + label = { Text(text = stringResource(R.string.step_up_password)) }, + isError = error != null, + textObfuscationMode = + if (hidden) TextObfuscationMode.RevealLastTyped + else TextObfuscationMode.Visible, + trailingIcon = { + VisibilityButton(isHidden = hidden, onClick = { hidden = !hidden }) + }, + keyboardOptions = KeyboardOptions( + autoCorrectEnabled = false, + keyboardType = KeyboardType.Password, + imeAction = ImeAction.Done, + ), + onKeyboardAction = { submit() }, + ) + + if (busy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + + error?.let { + Text( + text = stringResource(it.messageRes), + color = MaterialTheme.colorScheme.error, + ) + } + } + }, + ) +} + +@Preview +@Composable +private fun PasswordConfirmDialogPreview() { + MaterialTheme { + Surface(modifier = Modifier.fillMaxSize()) { + PasswordConfirmDialog( + password = TextFieldState(), + busy = false, + error = SyncError.InvalidCredentials, + onSubmit = {}, + onCancel = {}, + icon = { Icon(imageVector = Icons.Default.Lock, contentDescription = null) }, + title = { Text(text = "Confirm it's you") }, + message = { Text(text = "Enter your account password to continue.") }, + confirmButton = { enabled, onClick -> + TextButton(onClick = onClick, enabled = enabled) { + Text(text = "Confirm") + } + }, + ) + } + } +} diff --git a/core/sync/src/main/kotlin/de/davis/keygo/core/sync/presentation/stepup/StepUpDialog.kt b/core/sync/src/main/kotlin/de/davis/keygo/core/sync/presentation/stepup/StepUpDialog.kt index dc852e226..675e99dc0 100644 --- a/core/sync/src/main/kotlin/de/davis/keygo/core/sync/presentation/stepup/StepUpDialog.kt +++ b/core/sync/src/main/kotlin/de/davis/keygo/core/sync/presentation/stepup/StepUpDialog.kt @@ -1,44 +1,26 @@ package de.davis.keygo.core.sync.presentation.stepup -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.TextObfuscationMode import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Lock -import androidx.compose.material3.AlertDialog import androidx.compose.material3.Icon -import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedSecureTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable -import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.tooling.preview.PreviewParameterProvider -import androidx.compose.ui.unit.dp -import androidx.compose.ui.window.DialogProperties import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.davis.keygo.core.sync.R import de.davis.keygo.core.sync.domain.model.SyncError import de.davis.keygo.core.sync.domain.stepup.StepUpPrompt -import de.davis.keygo.core.sync.presentation.messageRes -import de.davis.keygo.core.ui.components.VisibilityButton -import de.davis.keygo.core.sync.R +import de.davis.keygo.core.sync.presentation.password.PasswordConfirmDialog import org.koin.androidx.compose.koinViewModel @Composable @@ -63,69 +45,20 @@ internal fun StepUpDialog( onSubmit: () -> Unit, onCancel: () -> Unit, ) { - val busy = prompt.busy - val hasText by remember(password) { derivedStateOf { password.text.isNotEmpty() } } - val canSubmit = !busy && hasText - val submit = { - if (canSubmit) onSubmit() - } - - AlertDialog( - onDismissRequest = onCancel, - properties = DialogProperties( - dismissOnBackPress = !busy, - dismissOnClickOutside = !busy, - ), - confirmButton = { - TextButton(onClick = submit, enabled = canSubmit) { + PasswordConfirmDialog( + password = password, + busy = prompt.busy, + error = prompt.error, + onSubmit = onSubmit, + onCancel = onCancel, + icon = { Icon(imageVector = Icons.Default.Lock, contentDescription = null) }, + title = { Text(text = stringResource(R.string.step_up_title)) }, + message = { Text(text = stringResource(R.string.step_up_message)) }, + confirmButton = { enabled, onClick -> + TextButton(onClick = onClick, enabled = enabled) { Text(text = stringResource(R.string.step_up_confirm)) } }, - dismissButton = { - TextButton(onClick = onCancel, enabled = !busy) { - Text(text = stringResource(android.R.string.cancel)) - } - }, - icon = { - Icon(imageVector = Icons.Default.Lock, contentDescription = null) - }, - title = { - Text(text = stringResource(R.string.step_up_title)) - }, - text = { - Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text(text = stringResource(R.string.step_up_message)) - - var hidden by rememberSaveable { mutableStateOf(true) } - OutlinedSecureTextField( - state = password, - modifier = Modifier.fillMaxWidth(), - enabled = !busy, - label = { Text(text = stringResource(R.string.step_up_password)) }, - isError = prompt.error != null, - textObfuscationMode = - if (hidden) TextObfuscationMode.RevealLastTyped - else TextObfuscationMode.Visible, - trailingIcon = { - VisibilityButton(isHidden = hidden, onClick = { hidden = !hidden }) - }, - keyboardOptions = KeyboardOptions( - keyboardType = KeyboardType.Password, - imeAction = ImeAction.Done, - ), - onKeyboardAction = { submit() }, - ) - - if (busy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) - - prompt.error?.let { - Text( - text = stringResource(it.messageRes), - color = MaterialTheme.colorScheme.error, - ) - } - } - }, ) } diff --git a/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt b/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt index bfe7197da..e86504c32 100644 --- a/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt +++ b/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt @@ -29,6 +29,9 @@ class FakeSyncRepository : SyncRepository { var stepUpGate: CompletableDeferred? = null + var deleteAccountResults: List> = listOf(Result.Success(Unit)) + val deleteAccountPasswords = mutableListOf() + override suspend fun checkServer(serverUrl: String): Result = error("checkServer is not faked") @@ -70,5 +73,11 @@ class FakeSyncRepository : SyncRepository { return result } + override suspend fun deleteAccount(password: String): Result { + val result = deleteAccountResults.answerFor(deleteAccountPasswords.size) + deleteAccountPasswords += password + return result + } + private fun List.answerFor(call: Int): T = getOrElse(call) { last() } } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountContent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountContent.kt index 91a748516..f975392aa 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountContent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountContent.kt @@ -3,6 +3,7 @@ package de.davis.keygo.feature.account.presentation import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.Logout @@ -36,9 +37,11 @@ import de.davis.keygo.core.util.presentation.UIText.Companion.ResourceString import de.davis.keygo.feature.account.R import de.davis.keygo.feature.account.presentation.components.AccountBanner import de.davis.keygo.feature.account.presentation.components.ConnectToServerCard +import de.davis.keygo.feature.account.presentation.components.DeleteAccountDialog import de.davis.keygo.feature.account.presentation.components.LogoutDialog import de.davis.keygo.feature.account.presentation.models.AccountUiEvent import de.davis.keygo.feature.account.presentation.models.AccountUiState +import de.davis.keygo.feature.account.presentation.models.DeleteAccountDialogState import de.davis.keygo.feature.account.presentation.models.DevicesSummary import de.davis.keygo.feature.account.presentation.models.LogoutDialogState import de.davis.keygo.feature.account.presentation.preview.ServerLinkProvider @@ -46,6 +49,7 @@ import de.davis.keygo.feature.account.presentation.preview.ServerLinkProvider @Composable internal fun AccountContent( state: AccountUiState, + deleteAccountPassword: TextFieldState, onEvent: (AccountUiEvent) -> Unit, ) { val link = state.link @@ -63,6 +67,14 @@ internal fun AccountContent( onDismiss = { onEvent(AccountUiEvent.OnLogoutDismissed) }, ) + if (link is ServerLink.Connected && state.deleteAccountDialog != DeleteAccountDialogState.Hidden) + DeleteAccountDialog( + state = state.deleteAccountDialog, + password = deleteAccountPassword, + onConfirm = { onEvent(AccountUiEvent.OnDeleteAccountConfirmed) }, + onDismiss = { onEvent(AccountUiEvent.OnDeleteAccountDismissed) }, + ) + Scaffold( modifier = Modifier .fillMaxSize() @@ -191,6 +203,7 @@ private fun AccountContentPreview( link = link, devices = DevicesSummary.Loaded(total = 3, signedIn = 2), ), + deleteAccountPassword = TextFieldState(), onEvent = {}, ) } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountScreen.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountScreen.kt index 603bb8eec..5ac28767a 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountScreen.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountScreen.kt @@ -28,6 +28,7 @@ internal fun AccountScreen( AccountContent( state = state, - onEvent = viewModel::onEvent + deleteAccountPassword = viewModel.deleteAccountPassword, + onEvent = viewModel::onEvent, ) } \ No newline at end of file diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt index d6ced3c6d..e7842666a 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt @@ -1,15 +1,20 @@ package de.davis.keygo.feature.account.presentation +import androidx.compose.foundation.text.input.TextFieldState import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import de.davis.keygo.core.sync.domain.model.Device import de.davis.keygo.core.sync.domain.model.ServerLink import de.davis.keygo.core.sync.domain.repository.ServerLinkRepository import de.davis.keygo.core.sync.domain.repository.SyncRepository +import de.davis.keygo.core.ui.text.clearSecret import de.davis.keygo.core.util.fold +import de.davis.keygo.core.util.onFailure +import de.davis.keygo.core.util.onSuccess import de.davis.keygo.feature.account.presentation.models.AccountEvent import de.davis.keygo.feature.account.presentation.models.AccountUiEvent import de.davis.keygo.feature.account.presentation.models.AccountUiState +import de.davis.keygo.feature.account.presentation.models.DeleteAccountDialogState import de.davis.keygo.feature.account.presentation.models.DevicesSummary import de.davis.keygo.feature.account.presentation.models.LogoutDialogState import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -32,6 +37,10 @@ internal class AccountViewModel( ) : ViewModel() { private val _logoutDialog = MutableStateFlow(LogoutDialogState.Hidden) + private val _deleteAccountDialog = + MutableStateFlow(DeleteAccountDialogState.Hidden) + + val deleteAccountPassword = TextFieldState() @OptIn(ExperimentalCoroutinesApi::class) private val devices = serverLinkRepository.observeLink() @@ -56,6 +65,7 @@ internal class AccountViewModel( serverLinkRepository.observeLink(), _logoutDialog, devices, + _deleteAccountDialog, ::AccountUiState, ).stateIn( scope = viewModelScope, @@ -83,12 +93,43 @@ internal class AccountViewModel( if (_logoutDialog.value != LogoutDialogState.LoggingOut) _logoutDialog.update { LogoutDialogState.Hidden } - AccountUiEvent.OnDeleteAccountClicked -> {} + AccountUiEvent.OnDeleteAccountClicked -> + _deleteAccountDialog.update { DeleteAccountDialogState.Confirming() } + + AccountUiEvent.OnDeleteAccountConfirmed -> deleteAccount() + AccountUiEvent.OnDeleteAccountDismissed -> dismissDeleteAccount() AccountUiEvent.ResetPassword -> _event.trySend(AccountEvent.NavigateToChangePassword) } } + private fun deleteAccount() { + if (_deleteAccountDialog.value !is DeleteAccountDialogState.Confirming) return + val password = deleteAccountPassword.text.toString() + if (password.isEmpty()) return + deleteAccountPassword.clearSecret() + + _deleteAccountDialog.update { DeleteAccountDialogState.Deleting } + viewModelScope.launch { + syncRepository.deleteAccount(password) + .onSuccess { _deleteAccountDialog.update { DeleteAccountDialogState.Hidden } } + .onFailure { error -> + _deleteAccountDialog.update { DeleteAccountDialogState.Confirming(error) } + } + } + } + + private fun dismissDeleteAccount() { + if (_deleteAccountDialog.value == DeleteAccountDialogState.Deleting) return + + deleteAccountPassword.clearSecret() + _deleteAccountDialog.update { DeleteAccountDialogState.Hidden } + } + + override fun onCleared() { + deleteAccountPassword.clearSecret() + } + private fun logout() { if (_logoutDialog.value == LogoutDialogState.LoggingOut) return diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/components/DeleteAccountDialog.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/components/DeleteAccountDialog.kt new file mode 100644 index 000000000..693268cd3 --- /dev/null +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/components/DeleteAccountDialog.kt @@ -0,0 +1,85 @@ +package de.davis.keygo.feature.account.presentation.components + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.tooling.preview.PreviewParameter +import androidx.compose.ui.tooling.preview.PreviewParameterProvider +import de.davis.keygo.core.sync.domain.model.SyncError +import de.davis.keygo.core.sync.presentation.password.PasswordConfirmDialog +import de.davis.keygo.feature.account.R +import de.davis.keygo.feature.account.presentation.models.DeleteAccountDialogState + +@Composable +internal fun DeleteAccountDialog( + state: DeleteAccountDialogState, + password: TextFieldState, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + PasswordConfirmDialog( + password = password, + busy = state == DeleteAccountDialogState.Deleting, + error = (state as? DeleteAccountDialogState.Confirming)?.error, + onSubmit = onConfirm, + onCancel = onDismiss, + icon = { + Icon( + imageVector = Icons.Default.Delete, + contentDescription = null, + tint = MaterialTheme.colorScheme.error, + ) + }, + title = { Text(text = stringResource(R.string.delete_account_title)) }, + message = { Text(text = stringResource(R.string.delete_account_message)) }, + confirmButton = { enabled, onClick -> + Button( + onClick = onClick, + enabled = enabled, + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.error, + ), + ) { + Text(text = stringResource(R.string.delete_account_confirm)) + } + }, + ) +} + +private class DeleteAccountDialogStateProvider : + PreviewParameterProvider { + + override val values = sequenceOf( + DeleteAccountDialogState.Confirming(), + DeleteAccountDialogState.Confirming(error = SyncError.InvalidCredentials), + DeleteAccountDialogState.Deleting, + ) +} + +@Preview +@Composable +private fun DeleteAccountDialogPreview( + @PreviewParameter(DeleteAccountDialogStateProvider::class) state: DeleteAccountDialogState, +) { + MaterialTheme { + Surface(modifier = Modifier.fillMaxSize()) { + DeleteAccountDialog( + state = state, + password = TextFieldState(), + onConfirm = {}, + onDismiss = {}, + ) + } + } +} diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt index 5cc7d3a3b..745ba6d72 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt @@ -10,6 +10,8 @@ internal sealed interface AccountUiEvent { data object OnLogoutDismissed : AccountUiEvent data object OnDeleteAccountClicked : AccountUiEvent + data object OnDeleteAccountConfirmed : AccountUiEvent + data object OnDeleteAccountDismissed : AccountUiEvent data object ResetPassword : AccountUiEvent } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiState.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiState.kt index aeacd92ac..76d483789 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiState.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiState.kt @@ -6,4 +6,5 @@ internal data class AccountUiState( val link: ServerLink = ServerLink.None, val logoutDialog: LogoutDialogState = LogoutDialogState.Hidden, val devices: DevicesSummary = DevicesSummary.Loading, + val deleteAccountDialog: DeleteAccountDialogState = DeleteAccountDialogState.Hidden, ) diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/DeleteAccountDialogState.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/DeleteAccountDialogState.kt new file mode 100644 index 000000000..838e093f3 --- /dev/null +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/DeleteAccountDialogState.kt @@ -0,0 +1,10 @@ +package de.davis.keygo.feature.account.presentation.models + +import de.davis.keygo.core.sync.domain.model.SyncError + +internal sealed interface DeleteAccountDialogState { + + data object Hidden : DeleteAccountDialogState + data class Confirming(val error: SyncError? = null) : DeleteAccountDialogState + data object Deleting : DeleteAccountDialogState +} diff --git a/feature/account/src/main/res/values-de/strings.xml b/feature/account/src/main/res/values-de/strings.xml index 06544d111..9983bb34d 100644 --- a/feature/account/src/main/res/values-de/strings.xml +++ b/feature/account/src/main/res/values-de/strings.xml @@ -32,6 +32,9 @@ Recovery Key Account löschen + Account löschen? + Dein Account und alles, was auf dem Server synchronisiert ist, werden endgültig gelöscht und alle deine Geräte abgemeldet. Das lässt sich nicht rückgängig machen. Deine Einträge bleiben auf diesem Gerät und funktionieren weiter offline. Gib zur Bestätigung dein Kontopasswort ein. + Account löschen Deine Geräte diff --git a/feature/account/src/main/res/values/strings.xml b/feature/account/src/main/res/values/strings.xml index a8a2415d9..a009aa617 100644 --- a/feature/account/src/main/res/values/strings.xml +++ b/feature/account/src/main/res/values/strings.xml @@ -32,6 +32,9 @@ Recovery Key Delete account + Delete account? + This permanently deletes your account and everything synced to the server, and signs out all your devices. It can\'t be undone. Your items remain on this device and keep working offline. Enter your account password to confirm. + Delete account Your devices diff --git a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt index 816d96bc9..cd5cb0a9c 100644 --- a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt +++ b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt @@ -9,7 +9,9 @@ import de.davis.keygo.core.sync.domain.model.SyncAccount import de.davis.keygo.core.sync.domain.model.SyncError import de.davis.keygo.core.sync.domain.repository.SyncRepository import de.davis.keygo.core.util.Result +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import de.davis.keygo.feature.account.presentation.models.AccountUiEvent +import de.davis.keygo.feature.account.presentation.models.DeleteAccountDialogState import de.davis.keygo.feature.account.presentation.models.DevicesSummary import de.davis.keygo.feature.account.presentation.models.LogoutDialogState import kotlinx.coroutines.CompletableDeferred @@ -203,6 +205,103 @@ class AccountViewModelTest { ) } + @Test + fun `delete account asks for the password first`() = runTest(dispatcher) { + repository.link.value = connected + val vm = viewModel() + vm.uiState.launchIn(backgroundScope) + + vm.onEvent(AccountUiEvent.OnDeleteAccountClicked) + + assertEquals(DeleteAccountDialogState.Confirming(), vm.uiState.value.deleteAccountDialog) + assertEquals(emptyList(), syncRepository.deleteAccountPasswords) + } + + @Test + fun `confirming deletes with the typed password and clears the field`() = + runTest(dispatcher) { + repository.link.value = connected + val vm = viewModel() + vm.uiState.launchIn(backgroundScope) + + vm.onEvent(AccountUiEvent.OnDeleteAccountClicked) + vm.deleteAccountPassword.setTextAndPlaceCursorAtEnd("hunter2") + vm.onEvent(AccountUiEvent.OnDeleteAccountConfirmed) + + assertEquals(listOf("hunter2"), syncRepository.deleteAccountPasswords) + assertEquals("", vm.deleteAccountPassword.text.toString()) + assertEquals(DeleteAccountDialogState.Hidden, vm.uiState.value.deleteAccountDialog) + assertEquals(ServerLink.None, vm.uiState.value.link) + } + + @Test + fun `confirming without a password does nothing`() = runTest(dispatcher) { + repository.link.value = connected + val vm = viewModel() + vm.uiState.launchIn(backgroundScope) + + vm.onEvent(AccountUiEvent.OnDeleteAccountClicked) + vm.onEvent(AccountUiEvent.OnDeleteAccountConfirmed) + + assertEquals(emptyList(), syncRepository.deleteAccountPasswords) + assertEquals(DeleteAccountDialogState.Confirming(), vm.uiState.value.deleteAccountDialog) + } + + @Test + fun `a wrong password keeps the dialog open with the error`() = runTest(dispatcher) { + repository.link.value = connected + syncRepository.deleteAccountResult = Result.Failure(SyncError.InvalidCredentials) + val vm = viewModel() + vm.uiState.launchIn(backgroundScope) + + vm.onEvent(AccountUiEvent.OnDeleteAccountClicked) + vm.deleteAccountPassword.setTextAndPlaceCursorAtEnd("wrong") + vm.onEvent(AccountUiEvent.OnDeleteAccountConfirmed) + + assertEquals( + DeleteAccountDialogState.Confirming(SyncError.InvalidCredentials), + vm.uiState.value.deleteAccountDialog, + ) + assertEquals("", vm.deleteAccountPassword.text.toString()) + assertEquals(connected, vm.uiState.value.link) + } + + @Test + fun `dismissing the delete dialog clears the password`() = runTest(dispatcher) { + repository.link.value = connected + val vm = viewModel() + vm.uiState.launchIn(backgroundScope) + + vm.onEvent(AccountUiEvent.OnDeleteAccountClicked) + vm.deleteAccountPassword.setTextAndPlaceCursorAtEnd("hunter2") + vm.onEvent(AccountUiEvent.OnDeleteAccountDismissed) + + assertEquals(DeleteAccountDialogState.Hidden, vm.uiState.value.deleteAccountDialog) + assertEquals("", vm.deleteAccountPassword.text.toString()) + assertEquals(emptyList(), syncRepository.deleteAccountPasswords) + } + + @Test + fun `deleting cannot be dismissed or started twice`() = runTest(dispatcher) { + repository.link.value = connected + val gate = CompletableDeferred() + syncRepository.deleteAccountGate = gate + val vm = viewModel() + vm.uiState.launchIn(backgroundScope) + + vm.onEvent(AccountUiEvent.OnDeleteAccountClicked) + vm.deleteAccountPassword.setTextAndPlaceCursorAtEnd("hunter2") + vm.onEvent(AccountUiEvent.OnDeleteAccountConfirmed) + vm.deleteAccountPassword.setTextAndPlaceCursorAtEnd("hunter2") + vm.onEvent(AccountUiEvent.OnDeleteAccountConfirmed) + vm.onEvent(AccountUiEvent.OnDeleteAccountDismissed) + + assertEquals(DeleteAccountDialogState.Deleting, vm.uiState.value.deleteAccountDialog) + gate.complete(Unit) + assertEquals(listOf("hunter2"), syncRepository.deleteAccountPasswords) + assertEquals(DeleteAccountDialogState.Hidden, vm.uiState.value.deleteAccountDialog) + } + private class FakeSyncRepository(private val links: FakeServerLinkRepository) : SyncRepository { var result: Result = Result.Success(Unit) var clearsLink = true @@ -245,6 +344,17 @@ class AccountViewModelTest { error("not used") override suspend fun stepUp(password: String): Result = error("not used") + + var deleteAccountResult: Result = Result.Success(Unit) + var deleteAccountGate: CompletableDeferred? = null + val deleteAccountPasswords = mutableListOf() + + override suspend fun deleteAccount(password: String): Result { + deleteAccountPasswords += password + deleteAccountGate?.await() + if (deleteAccountResult is Result.Success) links.link.value = ServerLink.None + return deleteAccountResult + } } private companion object { diff --git a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModelTest.kt b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModelTest.kt index 5fc7cc220..9fb19d55d 100644 --- a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModelTest.kt +++ b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModelTest.kt @@ -105,6 +105,9 @@ class ConnectServerViewModelTest { error("not used") override suspend fun stepUp(password: String): Result = error("not used") + + override suspend fun deleteAccount(password: String): Result = + error("not used") } private val dispatcher = StandardTestDispatcher() From 95841bb50345c4019d6611b7b3f17e9f804f4100 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 11:19:12 +0100 Subject: [PATCH 11/12] tests: enhance account tests --- .../keygo/core/sync/FakeSyncRepository.kt | 22 +++++- .../presentation/AccountViewModelTest.kt | 73 ++----------------- 2 files changed, 28 insertions(+), 67 deletions(-) diff --git a/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt b/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt index e86504c32..197a98e80 100644 --- a/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt +++ b/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt @@ -2,6 +2,7 @@ package de.davis.keygo.core.sync import de.davis.keygo.core.sync.domain.model.Device import de.davis.keygo.core.sync.domain.model.ServerInfo +import de.davis.keygo.core.sync.domain.model.ServerLink import de.davis.keygo.core.sync.domain.model.SyncAccount import de.davis.keygo.core.sync.domain.model.SyncError import de.davis.keygo.core.sync.domain.repository.SyncRepository @@ -9,7 +10,9 @@ import de.davis.keygo.core.util.Result import kotlinx.coroutines.CompletableDeferred import java.util.UUID -class FakeSyncRepository : SyncRepository { +class FakeSyncRepository( + private val links: FakeServerLinkRepository? = null, +) : SyncRepository { var devices: Result, SyncError> = Result.Success(emptyList()) @@ -29,9 +32,17 @@ class FakeSyncRepository : SyncRepository { var stepUpGate: CompletableDeferred? = null + var logoutResult: Result = Result.Success(Unit) + var logoutClearsLink = true + var logoutGate: CompletableDeferred? = null + var logouts = 0 + private set + var deleteAccountResults: List> = listOf(Result.Success(Unit)) val deleteAccountPasswords = mutableListOf() + var deleteAccountGate: CompletableDeferred? = null + override suspend fun checkServer(serverUrl: String): Result = error("checkServer is not faked") @@ -49,7 +60,12 @@ class FakeSyncRepository : SyncRepository { password: String, ): Result = error("login is not faked") - override suspend fun logout(): Result = Result.Success(Unit) + override suspend fun logout(): Result { + logouts++ + logoutGate?.await() + if (logoutClearsLink) links?.link?.value = ServerLink.None + return logoutResult + } override suspend fun devices(): Result, SyncError> { loads++ @@ -76,6 +92,8 @@ class FakeSyncRepository : SyncRepository { override suspend fun deleteAccount(password: String): Result { val result = deleteAccountResults.answerFor(deleteAccountPasswords.size) deleteAccountPasswords += password + deleteAccountGate?.await() + if (result is Result.Success) links?.link?.value = ServerLink.None return result } diff --git a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt index cd5cb0a9c..cc4978764 100644 --- a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt +++ b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt @@ -1,15 +1,13 @@ package de.davis.keygo.feature.account.presentation +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import de.davis.keygo.core.sync.FakeServerLinkRepository +import de.davis.keygo.core.sync.FakeSyncRepository import de.davis.keygo.core.sync.domain.model.Device import de.davis.keygo.core.sync.domain.model.NetworkFailure -import de.davis.keygo.core.sync.domain.model.ServerInfo import de.davis.keygo.core.sync.domain.model.ServerLink -import de.davis.keygo.core.sync.domain.model.SyncAccount import de.davis.keygo.core.sync.domain.model.SyncError -import de.davis.keygo.core.sync.domain.repository.SyncRepository import de.davis.keygo.core.util.Result -import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import de.davis.keygo.feature.account.presentation.models.AccountUiEvent import de.davis.keygo.feature.account.presentation.models.DeleteAccountDialogState import de.davis.keygo.feature.account.presentation.models.DevicesSummary @@ -118,7 +116,7 @@ class AccountViewModelTest { @Test fun `an unreachable server still counts as logged out`() = runTest(dispatcher) { repository.link.value = connected - syncRepository.result = Result.Failure(SyncError.Network(NetworkFailure.Timeout)) + syncRepository.logoutResult = Result.Failure(SyncError.Network(NetworkFailure.Timeout)) val vm = viewModel() vm.uiState.launchIn(backgroundScope) @@ -131,8 +129,8 @@ class AccountViewModelTest { @Test fun `a session that could not be cleared shows the failure`() = runTest(dispatcher) { repository.link.value = connected - syncRepository.clearsLink = false - syncRepository.result = Result.Failure(SyncError.Internal("store refused")) + syncRepository.logoutClearsLink = false + syncRepository.logoutResult = Result.Failure(SyncError.Internal("store refused")) val vm = viewModel() vm.uiState.launchIn(backgroundScope) @@ -146,7 +144,7 @@ class AccountViewModelTest { fun `logging out cannot be dismissed or started twice`() = runTest(dispatcher) { repository.link.value = connected val gate = CompletableDeferred() - syncRepository.gate = gate + syncRepository.logoutGate = gate val vm = viewModel() vm.uiState.launchIn(backgroundScope) @@ -191,7 +189,7 @@ class AccountViewModelTest { repository.link.value = connected syncRepository.devices = Result.Success(listOf(device(), device())) val gate = CompletableDeferred() - syncRepository.devicesGate = gate + syncRepository.gate = gate val vm = viewModel() vm.uiState.launchIn(backgroundScope) @@ -250,7 +248,7 @@ class AccountViewModelTest { @Test fun `a wrong password keeps the dialog open with the error`() = runTest(dispatcher) { repository.link.value = connected - syncRepository.deleteAccountResult = Result.Failure(SyncError.InvalidCredentials) + syncRepository.deleteAccountResults = listOf(Result.Failure(SyncError.InvalidCredentials)) val vm = viewModel() vm.uiState.launchIn(backgroundScope) @@ -302,61 +300,6 @@ class AccountViewModelTest { assertEquals(DeleteAccountDialogState.Hidden, vm.uiState.value.deleteAccountDialog) } - private class FakeSyncRepository(private val links: FakeServerLinkRepository) : SyncRepository { - var result: Result = Result.Success(Unit) - var clearsLink = true - var gate: CompletableDeferred? = null - var logouts = 0 - - override suspend fun checkServer(serverUrl: String): Result = - error("not used") - - override suspend fun register( - serverUrl: String, - userId: UUID, - username: String, - password: String, - invite: String?, - ): Result = error("not used") - - override suspend fun login( - serverUrl: String, - username: String, - password: String, - ): Result = error("not used") - - var devices: Result, SyncError> = Result.Success(emptyList()) - var devicesGate: CompletableDeferred? = null - - override suspend fun devices(): Result, SyncError> { - devicesGate?.await() - return devices - } - - override suspend fun logout(): Result { - logouts++ - gate?.await() - if (clearsLink) links.link.value = ServerLink.None - return result - } - - override suspend fun deleteDevice(deviceId: UUID): Result = - error("not used") - - override suspend fun stepUp(password: String): Result = error("not used") - - var deleteAccountResult: Result = Result.Success(Unit) - var deleteAccountGate: CompletableDeferred? = null - val deleteAccountPasswords = mutableListOf() - - override suspend fun deleteAccount(password: String): Result { - deleteAccountPasswords += password - deleteAccountGate?.await() - if (deleteAccountResult is Result.Success) links.link.value = ServerLink.None - return deleteAccountResult - } - } - private companion object { val connected = ServerLink.Connected(UUID.randomUUID(), "https://vault.example.org/", "ada") From 9d2beda2c4d4729c8f4d76dfd50d46a340408e19 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 11:19:58 +0100 Subject: [PATCH 12/12] docs(claude): add account endpoints Co-authored-by: Claude Opus 5.5 --- CLAUDE.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 79d560dd7..bbf103d29 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -166,8 +166,13 @@ Caddy as TLS proxy; `.env.example` sets `DOMAIN` and signups). option has a `KEYGO_*` env var. Secrets are one file each in `KEYGO_SECRETS_DIR` (`/run/secrets`): `db_password`, `opaque_setup`, `invite_pepper`, read through typed decoders in `secrets.rs`. `init` creates missing ones and never overwrites. -- **API** — `/health/live`, `/api/v1/meta`, `/api/v1/auth/{register,login}/{start,finish}`. - JSON is snake_case. Auth bodies are capped at `MAX_BODY_BYTES` (16 KiB). +- **API** — `/health/live`, `/api/v1/meta`, `/api/v1/auth/{register,login,step-up}/{start,finish}`, + `/api/v1/auth/{token,logout}`, `GET /api/v1/devices`, `DELETE /api/v1/devices/{id}`, + `DELETE /api/v1/account`. JSON is snake_case. Auth bodies are capped at `MAX_BODY_BYTES` (16 KiB). +- **Account deletion** — `DELETE /api/v1/account` requires a fresh sign-in (`FreshAuthenticated`); + one `delete from users` cascades to every table the account owns. The client always steps up + first (typing the password is the confirmation) and ends the local session; the local vault is + kept. Other devices learn of it only as a plain `session_revoked` on their next call. - **Registration** — two-step OPAQUE; `start` reserves username/user_id in the unlogged `pending_registrations` table (5 min TTL). `user_id` is client-generated (UUID v4) and equals the local user id. Unless `KEYGO_ALLOW_SIGNUPS`, an invite is required; invite codes are stored only