BIT-1565: Approve and decline login requests (#818)

This commit is contained in:
Caleb Derosier
2024-06-20 17:08:07 +01:00
committed by Álison Fernandes
parent 3be37766e2
commit a187fbb0d1
19 changed files with 726 additions and 71 deletions
@@ -1,12 +1,15 @@
package com.x8bit.bitwarden.data.auth.datasource.network.service
import com.x8bit.bitwarden.data.auth.datasource.network.api.AuthRequestsApi
import com.x8bit.bitwarden.data.auth.datasource.network.model.AuthRequestsResponseJson
import com.x8bit.bitwarden.data.platform.base.BaseServiceTest
import kotlinx.coroutines.test.runTest
import okhttp3.mockwebserver.MockResponse
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import retrofit2.create
import java.time.ZonedDateTime
class AuthRequestsServiceTest : BaseServiceTest() {
@@ -45,4 +48,57 @@ class AuthRequestsServiceTest : BaseServiceTest() {
val actual = service.getAuthRequests()
assertTrue(actual.isSuccess)
}
@Test
fun `updateAuthRequest when request response is Failure should return Failure`() = runTest {
val response = MockResponse().setResponseCode(400)
server.enqueue(response)
val actual = service.updateAuthRequest(
requestId = "userId",
deviceId = "deviceId",
key = "secureKey",
masterPasswordHash = null,
isApproved = true,
)
assertTrue(actual.isFailure)
}
@Test
fun `updateAuthRequest when request response is Success should return Success`() = runTest {
val json = """
{
"id": "1",
"publicKey": "2",
"requestDeviceType": "Android",
"requestIpAddress": "1.0.0.1",
"key": "key",
"masterPasswordHash": "verySecureHash",
"creationDate": "2024-09-13T01:00:00.00Z",
"requestApproved": true,
"origin": "www.bitwarden.com"
}
"""
val expected = AuthRequestsResponseJson.AuthRequest(
id = "1",
publicKey = "2",
platform = "Android",
ipAddress = "1.0.0.1",
key = "key",
masterPasswordHash = "verySecureHash",
creationDate = ZonedDateTime.parse("2024-09-13T01:00:00.00Z"),
responseDate = null,
requestApproved = true,
originUrl = "www.bitwarden.com",
)
val response = MockResponse().setBody(json).setResponseCode(200)
server.enqueue(response)
val actual = service.updateAuthRequest(
requestId = "userId",
deviceId = "deviceId",
key = "secureKey",
masterPasswordHash = "verySecureHash",
isApproved = true,
)
assertEquals(Result.success(expected), actual)
}
}
@@ -70,6 +70,7 @@ import com.x8bit.bitwarden.data.platform.repository.util.FakeEnvironmentReposito
import com.x8bit.bitwarden.data.platform.util.asFailure
import com.x8bit.bitwarden.data.platform.util.asSuccess
import com.x8bit.bitwarden.data.vault.datasource.network.model.createMockOrganization
import com.x8bit.bitwarden.data.vault.datasource.sdk.VaultSdkSource
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
import com.x8bit.bitwarden.data.vault.repository.model.VaultState
import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockResult
@@ -158,6 +159,14 @@ class AuthRepositoryTest {
),
)
}
private val vaultSdkSource = mockk<VaultSdkSource> {
coEvery {
getAuthRequestKey(
publicKey = PUBLIC_KEY,
userId = USER_ID_1,
)
} returns "AsymmetricEncString".asSuccess()
}
private val userLogoutManager: UserLogoutManager = mockk {
every { logout(any()) } just runs
}
@@ -173,6 +182,7 @@ class AuthRepositoryTest {
newAuthRequestService = newAuthRequestService,
organizationService = organizationService,
authSdkSource = authSdkSource,
vaultSdkSource = vaultSdkSource,
authDiskSource = fakeAuthDiskSource,
environmentRepository = fakeEnvironmentRepository,
settingsRepository = settingsRepository,
@@ -2413,6 +2423,143 @@ class AuthRepositoryTest {
assertEquals(expected, result)
}
@Test
fun `updateAuthRequest should return failure when sdk returns failure`() = runTest {
coEvery {
vaultSdkSource.getAuthRequestKey(
publicKey = PUBLIC_KEY,
userId = USER_ID_1,
)
} returns Throwable("Fail").asFailure()
fakeAuthDiskSource.userState = SINGLE_USER_STATE_1
val result = repository.updateAuthRequest(
requestId = "requestId",
masterPasswordHash = "masterPasswordHash",
publicKey = PUBLIC_KEY,
isApproved = false,
)
coVerify(exactly = 1) {
vaultSdkSource.getAuthRequestKey(
publicKey = PUBLIC_KEY,
userId = USER_ID_1,
)
}
assertEquals(AuthRequestResult.Error, result)
}
@Test
fun `updateAuthRequest should return failure when service returns failure`() = runTest {
val requestId = "requestId"
val passwordHash = "masterPasswordHash"
val encodedKey = "encodedKey"
coEvery {
vaultSdkSource.getAuthRequestKey(
publicKey = PUBLIC_KEY,
userId = USER_ID_1,
)
} returns encodedKey.asSuccess()
coEvery {
authRequestsService.updateAuthRequest(
requestId = requestId,
masterPasswordHash = passwordHash,
key = encodedKey,
deviceId = UNIQUE_APP_ID,
isApproved = false,
)
} returns Throwable("Mission failed").asFailure()
fakeAuthDiskSource.userState = SINGLE_USER_STATE_1
val result = repository.updateAuthRequest(
requestId = "requestId",
masterPasswordHash = "masterPasswordHash",
publicKey = PUBLIC_KEY,
isApproved = false,
)
coVerify(exactly = 1) {
vaultSdkSource.getAuthRequestKey(
publicKey = PUBLIC_KEY,
userId = USER_ID_1,
)
}
assertEquals(AuthRequestResult.Error, result)
}
@Suppress("LongMethod")
@Test
fun `updateAuthRequest should return success when service & sdk return success`() = runTest {
val requestId = "requestId"
val passwordHash = "masterPasswordHash"
val encodedKey = "encodedKey"
val responseJson = AuthRequestsResponseJson.AuthRequest(
id = requestId,
publicKey = PUBLIC_KEY,
platform = "Android",
ipAddress = "192.168.0.1",
key = "key",
masterPasswordHash = passwordHash,
creationDate = ZonedDateTime.parse("2024-09-13T00:00Z"),
responseDate = null,
requestApproved = true,
originUrl = "www.bitwarden.com",
)
val expected = AuthRequestResult.Success(
authRequest = AuthRequest(
id = requestId,
publicKey = PUBLIC_KEY,
platform = "Android",
ipAddress = "192.168.0.1",
key = "key",
masterPasswordHash = passwordHash,
creationDate = ZonedDateTime.parse("2024-09-13T00:00Z"),
responseDate = null,
requestApproved = true,
originUrl = "www.bitwarden.com",
fingerprint = "",
),
)
coEvery {
vaultSdkSource.getAuthRequestKey(
publicKey = PUBLIC_KEY,
userId = USER_ID_1,
)
} returns encodedKey.asSuccess()
coEvery {
authRequestsService.updateAuthRequest(
requestId = requestId,
masterPasswordHash = passwordHash,
key = encodedKey,
deviceId = UNIQUE_APP_ID,
isApproved = false,
)
} returns responseJson.asSuccess()
fakeAuthDiskSource.userState = SINGLE_USER_STATE_1
val result = repository.updateAuthRequest(
requestId = requestId,
masterPasswordHash = passwordHash,
publicKey = PUBLIC_KEY,
isApproved = false,
)
coVerify(exactly = 1) {
vaultSdkSource.getAuthRequestKey(
publicKey = PUBLIC_KEY,
userId = USER_ID_1,
)
authRequestsService.updateAuthRequest(
requestId = requestId,
masterPasswordHash = passwordHash,
key = encodedKey,
deviceId = UNIQUE_APP_ID,
isApproved = false,
)
}
assertEquals(expected, result)
}
@Test
fun `getIsKnownDevice should return failure when service returns failure`() = runTest {
coEvery {
@@ -1,5 +1,9 @@
package com.x8bit.bitwarden.ui.platform.feature.settings.accountsecurity.loginapproval
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasAnyAncestor
import androidx.compose.ui.test.isDialog
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollTo
@@ -43,20 +47,6 @@ class LoginApprovalScreenTest : BaseComposeTest() {
@Test
fun `on Confirm login should send ApproveRequestClick`() = runTest {
// Set to content state to show appropriate buttons
mutableStateFlow.tryEmit(
LoginApprovalState(
fingerprint = FINGERPRINT,
viewState = LoginApprovalState.ViewState.Content(
deviceType = "Android",
domainUrl = "bitwarden.com",
email = "test@bitwarden.com",
fingerprint = FINGERPRINT,
ipAddress = "1.0.0.1",
time = "now",
),
),
)
composeTestRule
.onNodeWithText("Confirm login")
.performScrollTo()
@@ -69,20 +59,6 @@ class LoginApprovalScreenTest : BaseComposeTest() {
@Test
fun `on Deny login should send DeclineRequestClick`() = runTest {
// Set to content state to show appropriate buttons
mutableStateFlow.tryEmit(
LoginApprovalState(
fingerprint = FINGERPRINT,
viewState = LoginApprovalState.ViewState.Content(
deviceType = "Android",
domainUrl = "bitwarden.com",
email = "test@bitwarden.com",
fingerprint = FINGERPRINT,
ipAddress = "1.0.0.1",
time = "now",
),
),
)
composeTestRule
.onNodeWithText("Deny login")
.performScrollTo()
@@ -91,10 +67,43 @@ class LoginApprovalScreenTest : BaseComposeTest() {
viewModel.trySendAction(LoginApprovalAction.DeclineRequestClick)
}
}
@Test
fun `on error dialog dismiss click should send ErrorDialogDismiss`() = runTest {
mutableStateFlow.tryEmit(
DEFAULT_STATE.copy(
shouldShowErrorDialog = true,
),
)
composeTestRule
.onNodeWithText("An error has occurred.")
.assert(hasAnyAncestor(isDialog()))
.assertIsDisplayed()
composeTestRule
.onNodeWithText("Ok")
.performClick()
verify {
viewModel.trySendAction(LoginApprovalAction.ErrorDialogDismiss)
}
}
}
private const val FINGERPRINT = "fingerprint"
private val DEFAULT_STATE: LoginApprovalState = LoginApprovalState(
fingerprint = FINGERPRINT,
viewState = LoginApprovalState.ViewState.Loading,
masterPasswordHash = null,
publicKey = "publicKey",
requestId = "",
shouldShowErrorDialog = false,
viewState = LoginApprovalState.ViewState.Content(
deviceType = "Android",
domainUrl = "bitwarden.com",
email = "test@bitwarden.com",
fingerprint = FINGERPRINT,
ipAddress = "1.0.0.1",
time = "now",
),
)
@@ -8,7 +8,6 @@ import com.x8bit.bitwarden.data.auth.repository.model.AuthRequestResult
import com.x8bit.bitwarden.data.auth.repository.model.UserState
import com.x8bit.bitwarden.data.platform.repository.model.Environment
import com.x8bit.bitwarden.ui.platform.base.BaseViewModelTest
import com.x8bit.bitwarden.ui.platform.base.util.asText
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
@@ -82,23 +81,72 @@ class LoginApprovalViewModelTest : BaseViewModelTest() {
}
@Test
fun `on ApproveRequestClick should emit ShowToast`() = runTest {
fun `on ApproveRequestClick should approve auth request`() = runTest {
val viewModel = createViewModel()
viewModel.eventFlow.test {
viewModel.trySendAction(LoginApprovalAction.ApproveRequestClick)
assertEquals(LoginApprovalEvent.ShowToast("Not yet implemented".asText()), awaitItem())
coEvery {
mockAuthRepository.updateAuthRequest(
requestId = REQUEST_ID,
masterPasswordHash = PASSWORD_HASH,
publicKey = PUBLIC_KEY,
isApproved = true,
)
} returns AuthRequestResult.Success(AUTH_REQUEST)
viewModel.trySendAction(LoginApprovalAction.ApproveRequestClick)
coVerify {
mockAuthRepository.updateAuthRequest(
requestId = REQUEST_ID,
masterPasswordHash = PASSWORD_HASH,
publicKey = PUBLIC_KEY,
isApproved = true,
)
}
}
@Test
fun `on DeclineRequestClick should emit ShowToast`() = runTest {
fun `on DeclineRequestClick should deny auth request`() = runTest {
val viewModel = createViewModel()
viewModel.eventFlow.test {
viewModel.trySendAction(LoginApprovalAction.ApproveRequestClick)
assertEquals(LoginApprovalEvent.ShowToast("Not yet implemented".asText()), awaitItem())
coEvery {
mockAuthRepository.updateAuthRequest(
requestId = REQUEST_ID,
masterPasswordHash = PASSWORD_HASH,
publicKey = PUBLIC_KEY,
isApproved = false,
)
} returns AuthRequestResult.Success(AUTH_REQUEST)
viewModel.trySendAction(LoginApprovalAction.DeclineRequestClick)
coVerify {
mockAuthRepository.updateAuthRequest(
requestId = REQUEST_ID,
masterPasswordHash = PASSWORD_HASH,
publicKey = PUBLIC_KEY,
isApproved = false,
)
}
}
@Test
fun `on ErrorDialogDismiss should update state`() = runTest {
val viewModel = createViewModel()
coEvery {
mockAuthRepository.updateAuthRequest(
requestId = REQUEST_ID,
masterPasswordHash = PASSWORD_HASH,
publicKey = PUBLIC_KEY,
isApproved = false,
)
} returns AuthRequestResult.Error
viewModel.trySendAction(LoginApprovalAction.DeclineRequestClick)
assertEquals(viewModel.stateFlow.value, DEFAULT_STATE.copy(shouldShowErrorDialog = true))
viewModel.trySendAction(LoginApprovalAction.ErrorDialogDismiss)
assertEquals(viewModel.stateFlow.value, DEFAULT_STATE.copy(shouldShowErrorDialog = false))
}
private fun createViewModel(
authRepository: AuthRepository = mockAuthRepository,
state: LoginApprovalState? = DEFAULT_STATE,
@@ -112,8 +160,15 @@ class LoginApprovalViewModelTest : BaseViewModelTest() {
private const val EMAIL = "test@bitwarden.com"
private const val FINGERPRINT = "fingerprint"
private const val PASSWORD_HASH = "verySecureHash"
private const val PUBLIC_KEY = "publicKey"
private const val REQUEST_ID = "requestId"
private val DEFAULT_STATE: LoginApprovalState = LoginApprovalState(
fingerprint = FINGERPRINT,
masterPasswordHash = PASSWORD_HASH,
publicKey = PUBLIC_KEY,
requestId = REQUEST_ID,
shouldShowErrorDialog = false,
viewState = LoginApprovalState.ViewState.Content(
deviceType = "Android",
domainUrl = "www.bitwarden.com",
@@ -142,12 +197,12 @@ private val DEFAULT_USER_STATE = UserState(
),
)
private val AUTH_REQUEST = AuthRequest(
id = "1",
publicKey = "2",
id = REQUEST_ID,
publicKey = PUBLIC_KEY,
platform = "Android",
ipAddress = "1.0.0.1",
key = "public",
masterPasswordHash = "verySecureHash",
masterPasswordHash = PASSWORD_HASH,
creationDate = ZonedDateTime.parse("2024-09-13T00:00Z"),
responseDate = null,
requestApproved = true,
@@ -177,6 +177,75 @@ class PendingRequestsViewModelTest : BaseViewModelTest() {
}
}
@Suppress("LongMethod")
@Test
fun `on LifecycleResume should update state`() = runTest {
coEvery {
authRepository.getAuthRequests()
} returns AuthRequestsResult.Success(emptyList())
val viewModel = createViewModel()
assertEquals(
DEFAULT_STATE,
viewModel.stateFlow.value,
)
coEvery {
authRepository.getAuthRequests()
} returns AuthRequestsResult.Success(
authRequests = listOf(
AuthRequest(
id = "1",
publicKey = "publicKey-1",
platform = "Android",
ipAddress = "192.168.0.1",
key = "publicKey",
masterPasswordHash = "verySecureHash",
creationDate = ZonedDateTime.parse("2023-08-24T17:11Z"),
responseDate = null,
requestApproved = true,
originUrl = "www.bitwarden.com",
fingerprint = "pantry-overdue-survive-sleep-jab",
),
AuthRequest(
id = "2",
publicKey = "publicKey-2",
platform = "iOS",
ipAddress = "192.168.0.2",
key = "publicKey",
masterPasswordHash = "verySecureHash",
creationDate = ZonedDateTime.parse("2023-08-21T15:43Z"),
responseDate = null,
requestApproved = false,
originUrl = "www.bitwarden.com",
fingerprint = "erupt-anew-matchbook-disk-student",
),
),
)
val expected = DEFAULT_STATE.copy(
viewState = PendingRequestsState.ViewState.Content(
requests = listOf(
PendingRequestsState.ViewState.Content.PendingLoginRequest(
fingerprintPhrase = "pantry-overdue-survive-sleep-jab",
platform = "Android",
timestamp = "8/24/23 05:11 PM",
),
PendingRequestsState.ViewState.Content.PendingLoginRequest(
fingerprintPhrase = "erupt-anew-matchbook-disk-student",
platform = "iOS",
timestamp = "8/21/23 03:43 PM",
),
),
),
)
viewModel.trySendAction(PendingRequestsAction.LifecycleResume)
assertEquals(expected, viewModel.stateFlow.value)
coVerify(exactly = 2) {
authRepository.getAuthRequests()
}
}
private fun createViewModel(
state: PendingRequestsState? = DEFAULT_STATE,
): PendingRequestsViewModel = PendingRequestsViewModel(