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 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/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 } 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..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,6 +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") @@ -46,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++ @@ -70,5 +89,13 @@ class FakeSyncRepository : SyncRepository { return result } + 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 + } + 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 ac2b126de..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() @@ -172,7 +184,7 @@ private fun SettingsScope.connectedSection( title = R.string.delete_account, icon = Icons.Default.Delete, colors = deleteAccountColors, - onClick = {}, + onClick = { onEvent(AccountUiEvent.OnDeleteAccountClicked) }, ) } } @@ -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 16b84044d..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,10 +93,43 @@ internal class AccountViewModel( if (_logoutDialog.value != LogoutDialogState.LoggingOut) _logoutDialog.update { LogoutDialogState.Hidden } + 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 4ac5d6aae..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 @@ -9,5 +9,9 @@ internal sealed interface AccountUiEvent { data object OnLogoutConfirmed : 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..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,15 @@ 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 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 @@ -116,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) @@ -129,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) @@ -144,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) @@ -189,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) @@ -203,48 +203,101 @@ class AccountViewModelTest { ) } - 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 - } + @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) + } - override suspend fun logout(): Result { - logouts++ - gate?.await() - if (clearsLink) links.link.value = ServerLink.None - return result + @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) } - override suspend fun deleteDevice(deviceId: UUID): Result = - error("not used") + @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.deleteAccountResults = listOf(Result.Failure(SyncError.InvalidCredentials)) + val vm = viewModel() + vm.uiState.launchIn(backgroundScope) - override suspend fun stepUp(password: String): Result = error("not used") + 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 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() 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..5439a8b9c 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,20 @@ impl SyncClient { (sent, _) => sent, } } + + /// 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.** + /// 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. + let _ = self.end_session(&mut state).await; + Ok(()) + } } fn is_reattached(session: &Session, claimed: Option) -> bool { diff --git a/rust/crates/keygo-client/src/sync/pipeline.rs b/rust/crates/keygo-client/src/sync/pipeline.rs index c87e058f0..4fd99f22b 100644 --- a/rust/crates/keygo-client/src/sync/pipeline.rs +++ b/rust/crates/keygo-client/src/sync/pipeline.rs @@ -1277,6 +1277,24 @@ mod tests { h.assert_signed_out_locally().await; } + #[tokio::test] + async fn delete_account_steps_up_first_and_keeps_the_session_on_failure() { + let h = fresh().await; + h.transport.push_network_failure(NetworkError::Other); + + let error = h.client.delete_account("password").await.unwrap_err(); + + 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()); + } + #[tokio::test] async fn logout_clears_local_state_when_offline() { let h = fresh().await; diff --git a/rust/crates/keygo-e2e/tests/sync.rs b/rust/crates/keygo-e2e/tests/sync.rs index 4dbb62dcc..1a520f2b5 100644 --- a/rust/crates/keygo-e2e/tests/sync.rs +++ b/rust/crates/keygo-e2e/tests/sync.rs @@ -310,6 +310,63 @@ 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_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) + .bind(h.device_id.as_uuid()) + .execute(&db) + .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); + assert_eq!( + h.client.devices().await.unwrap_err(), + SyncError::SignedOut { reason: None }, + ); +} + +#[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; + + client.delete_account(password()).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/.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..2e4c06982 --- /dev/null +++ b/rust/crates/keygo-server/src/api/routes/account.rs @@ -0,0 +1,77 @@ +use crate::api::authenticated::FreshAuthenticated; +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 { + 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(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/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..9324a26cf --- /dev/null +++ b/rust/crates/keygo-server/src/service/account.rs @@ -0,0 +1,63 @@ +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 +} + +#[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/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; 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( diff --git a/rust/crates/keygo-uniffi/src/sync.rs b/rust/crates/keygo-uniffi/src/sync.rs index 52e8512a9..e4259971c 100644 --- a/rust/crates/keygo-uniffi/src/sync.rs +++ b/rust/crates/keygo-uniffi/src/sync.rs @@ -471,6 +471,11 @@ 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, password: String) -> Result<(), SyncError> { + let password = Zeroizing::new(password); + detached(async move { self.inner.delete_account(&password).await }).await + } } #[cfg(test)]