diff --git a/app/build.gradle.kts b/app/build.gradle.kts index e547a0b75..7c75b1e35 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -251,7 +251,10 @@ dependencies { testImplementation(libs.truth) testImplementation(libs.kotlin.coroutines.test) testImplementation(libs.androidx.navigation3.runtime) + testImplementation(libs.paging.compose) + testImplementation(libs.paging.runtime) testImplementation(project(":commontest")) + testImplementation(project(":dto")) androidTestImplementation(project(":testtags")) androidTestImplementation(project(":resourcetypes-domain")) diff --git a/app/src/main/java/com/passbolt/mobile/android/PassboltApplication.kt b/app/src/main/java/com/passbolt/mobile/android/PassboltApplication.kt index 5fd1033ad..1422b74a9 100644 --- a/app/src/main/java/com/passbolt/mobile/android/PassboltApplication.kt +++ b/app/src/main/java/com/passbolt/mobile/android/PassboltApplication.kt @@ -54,10 +54,52 @@ class PassboltApplication : override fun onCreate() { super.onCreate() + configureLeakCanary() applyAutomaticPageSizeUseCase.execute(Unit) registerAppForegroundListener() } + private fun configureLeakCanary() { + if (!BuildConfig.DEBUG) return + runCatching { + val leakCanaryClass = Class.forName("leakcanary.LeakCanary") + val getConfigMethod = leakCanaryClass.getMethod("getConfig") + val setConfigMethod = leakCanaryClass.getMethod("setConfig", Class.forName("leakcanary.LeakCanary\$Config")) + val matchersClass = Class.forName("shark.AndroidReferenceMatchers") + val ignoredFieldMethod = matchersClass.getMethod("ignoredInstanceField", String::class.java, String::class.java) + + val currentConfig = getConfigMethod.invoke(null) ?: return@runCatching + val builderMethod = currentConfig.javaClass.getMethod("newBuilder") + val builder = builderMethod.invoke(currentConfig) + val getMatchersMethod = currentConfig.javaClass.getMethod("getReferenceMatchers") + @Suppress("UNCHECKED_CAST") + val currentMatchers = getMatchersMethod.invoke(currentConfig) as? List ?: emptyList() + + val ignoredStubThis0 = ignoredFieldMethod.invoke( + null, + "android.service.credentials.CredentialProviderService\$1", + "this$0", + ) + val ignoredInterface = ignoredFieldMethod.invoke( + null, + "android.service.credentials.CredentialProviderService", + "mInterface", + ) + val ignoredAndroidxService = ignoredFieldMethod.invoke( + null, + "androidx.credentials.provider.CredentialProviderService", + "mInterface", + ) + + val newMatchers = currentMatchers + listOfNotNull(ignoredStubThis0, ignoredInterface, ignoredAndroidxService) + val referenceMatchersMethod = builder.javaClass.getMethod("referenceMatchers", List::class.java) + referenceMatchersMethod.invoke(builder, newMatchers) + val buildMethod = builder.javaClass.getMethod("build") + val newConfig = buildMethod.invoke(builder) + setConfigMethod.invoke(null, newConfig) + } + } + /** * Registers a listener detecting when application goes foreground. * Listening is done using the application coroutine scope. diff --git a/app/src/test/java/net/svaroh/passly/e2e/AuthenticationAndOfflineVaultE2ETest.kt b/app/src/test/java/net/svaroh/passly/e2e/AuthenticationAndOfflineVaultE2ETest.kt new file mode 100644 index 000000000..d09957891 --- /dev/null +++ b/app/src/test/java/net/svaroh/passly/e2e/AuthenticationAndOfflineVaultE2ETest.kt @@ -0,0 +1,442 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.e2e + +import app.cash.turbine.test +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.setMain +import org.mockito.kotlin.atLeastOnce +import net.svaroh.passly.common.usecase.UserIdInput +import net.svaroh.passly.core.idlingresource.SignInIdlingResource +import net.svaroh.passly.core.mvp.authentication.MfaProvidersHandler +import net.svaroh.passly.core.navigation.ActivityIntents.AuthConfig +import net.svaroh.passly.core.navigation.AppContext +import net.svaroh.passly.core.passphrasememorycache.PassphraseMemoryCache +import net.svaroh.passly.core.security.rootdetection.RootDetector +import net.svaroh.passly.core.security.runtimeauth.RuntimeAuthenticatedFlag +import net.svaroh.passly.database.usecase.HasLocalReplicaUseCase +import net.svaroh.passly.domain.accounts.AuthenticatedAccountFlow +import net.svaroh.passly.domain.accounts.usecase.GetAccountDataUseCase +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase +import net.svaroh.passly.domain.accounts.usecase.SaveSelectedAccountUseCase +import net.svaroh.passly.domain.accounts.usecase.SaveServerFingerprintUseCase +import net.svaroh.passly.domain.auth.model.ServerSignOutStatus +import net.svaroh.passly.domain.auth.usecase.GetPassphraseUseCase +import net.svaroh.passly.domain.auth.usecase.SaveMfaTokenUseCase +import net.svaroh.passly.domain.auth.usecase.SaveSessionUseCase +import net.svaroh.passly.domain.inappreview.usecase.InAppReviewInteractor +import net.svaroh.passly.domain.preferences.PreferencesDefaults +import net.svaroh.passly.domain.preferences.usecase.GetGlobalPreferencesUseCase +import net.svaroh.passly.domain.privatekey.model.PrivateKey +import net.svaroh.passly.domain.privatekey.usecase.GetPrivateKeyUseCase +import net.svaroh.passly.dto.response.ChallengeResponseDto +import net.svaroh.passly.encryptedstorage.biometric.BiometricCipher +import net.svaroh.passly.feature.authentication.auth.AuthIntent +import net.svaroh.passly.feature.authentication.auth.AuthSideEffect +import net.svaroh.passly.feature.authentication.auth.AuthViewModel +import net.svaroh.passly.feature.authentication.auth.challenge.MfaStatus +import net.svaroh.passly.feature.authentication.auth.challenge.MfaStatusProvider +import net.svaroh.passly.feature.authentication.auth.usecase.BackgroundSignInExecutor +import net.svaroh.passly.feature.authentication.auth.usecase.BiometryInteractor +import net.svaroh.passly.feature.authentication.auth.usecase.GetAndVerifyServerKeysAndTimeInteractor +import net.svaroh.passly.feature.authentication.auth.usecase.PostSignInActionsInteractor +import net.svaroh.passly.feature.authentication.auth.usecase.RefreshSessionUseCase +import net.svaroh.passly.feature.authentication.auth.usecase.ServerKeysWarmup +import net.svaroh.passly.feature.authentication.auth.usecase.SignInVerifyInteractor +import net.svaroh.passly.feature.authentication.auth.usecase.SignOutUseCase +import net.svaroh.passly.feature.authentication.auth.usecase.VerifyPassphraseUseCase +import net.svaroh.passly.ui.GlobalPreferencesUiModel +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.reset +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import kotlin.test.assertIs + +@OptIn(ExperimentalCoroutinesApi::class) +class AuthenticationAndOfflineVaultE2ETest { + private val testDispatcher = StandardTestDispatcher() + + private val mockGetAccountDataUseCase = mock() + private val mockGetPrivateKeyUseCase = mock() + private val mockVerifyPassphraseUseCase = mock() + private val mockBiometricCipher = mock() + private val mockGetPassphraseUseCase = mock() + private val mockPassphraseMemoryCache = mock() + private val mockRootDetector = mock() + private val mockBiometryInteractor = mock() + private val mockGetGlobalPreferencesUseCase = mock() + private val mockRuntimeAuthenticatedFlag = mock() + private val mockSaveSessionUseCase = mock() + private val mockSaveMfaTokenUseCase = mock() + private val mockSaveSelectedAccountUseCase = mock() + private val mockGetSelectedAccountUseCase = mock() + private val mockSignOutUseCase = mock() + private val mockSaveServerFingerprintUseCase = mock() + private val mockMfaStatusProvider = mock() + private val mockGetAndVerifyServerKeysInteractor = mock() + private val mockSignInVerifyInteractor = mock() + private val mockInAppReviewInteractor = mock() + private val mockSignInIdlingResource = mock() + private val mockPostSignInActionsInteractor = mock() + private val mockRefreshSessionUseCase = mock() + private val mockMfaProvidersHandler = mock() + private val mockServerKeysWarmup = mock() + private val mockHasLocalReplicaUseCase = mock() + private val mockBackgroundSignInExecutor = mock() + + private val authenticatedAccountFlow = + AuthenticatedAccountFlow( + mockGetSelectedAccountUseCase.apply { + whenever(execute(Unit)).thenReturn(GetSelectedAccountUseCase.Output(null)) + }, + ) + + @Before + fun setUp() { + Dispatchers.setMain(testDispatcher) + whenever(mockGetAccountDataUseCase.execute(any())).thenReturn( + GetAccountDataUseCase.Output( + firstName = "Ton", + lastName = "Tester", + email = "ton@passly.svaroh.net", + avatarUrl = null, + url = "https://passly.svaroh.net", + serverId = "server-user-id", + label = "Ton Tester", + role = "user", + ), + ) + whenever(mockGetPrivateKeyUseCase.execute(any())).thenReturn( + GetPrivateKeyUseCase.Output( + PrivateKey("-----BEGIN PGP PRIVATE KEY BLOCK-----\ntest\n-----END PGP PRIVATE KEY BLOCK-----"), + ), + ) + whenever(mockGetGlobalPreferencesUseCase.execute(Unit)).thenReturn( + GlobalPreferencesUiModel( + areDebugLogsEnabled = false, + debugLogFileCreationDateTime = null, + debugLogLastAppVersion = null, + isHideRootDialogEnabled = false, + isAuthRequiredOnEveryEntry = true, + apiFetchPageSize = PreferencesDefaults.API_FETCH_PAGE_SIZE, + isApiFetchPageSizeManuallySet = false, + accessibilityPoliciesConsentGiven = false, + deprecatedOsWarningHiddenForSdk = null, + ), + ) + whenever(mockRootDetector.isDeviceRooted()).thenReturn(false) + whenever(mockMfaStatusProvider.provideMfaStatus()).thenReturn(MfaStatus.NOT_REQUIRED) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + reset( + mockGetAccountDataUseCase, + mockGetPrivateKeyUseCase, + mockVerifyPassphraseUseCase, + mockPassphraseMemoryCache, + mockRuntimeAuthenticatedFlag, + mockSaveSessionUseCase, + mockSaveSelectedAccountUseCase, + mockGetAndVerifyServerKeysInteractor, + mockSignInVerifyInteractor, + mockHasLocalReplicaUseCase, + mockSignOutUseCase, + mockRefreshSessionUseCase, + ) + } + + private fun createViewModel( + authConfig: AuthConfig = AuthConfig.Startup, + ): AuthViewModel = + AuthViewModel( + authConfig = authConfig, + userId = TEST_USER_ID, + appContext = AppContext.APP, + getAccountDataUseCase = mockGetAccountDataUseCase, + getPrivateKeyUseCase = mockGetPrivateKeyUseCase, + verifyPassphraseUseCase = mockVerifyPassphraseUseCase, + biometricCipher = mockBiometricCipher, + getPassphraseUseCase = mockGetPassphraseUseCase, + passphraseMemoryCache = mockPassphraseMemoryCache, + rootDetector = mockRootDetector, + biometryInteractor = mockBiometryInteractor, + getGlobalPreferencesUseCase = mockGetGlobalPreferencesUseCase, + runtimeAuthenticatedFlag = mockRuntimeAuthenticatedFlag, + saveSessionUseCase = mockSaveSessionUseCase, + saveMfaTokenUseCase = mockSaveMfaTokenUseCase, + saveSelectedAccountUseCase = mockSaveSelectedAccountUseCase, + authenticatedAccountFlow = authenticatedAccountFlow, + signOutUseCase = mockSignOutUseCase, + saveServerFingerprintUseCase = mockSaveServerFingerprintUseCase, + mfaStatusProvider = mockMfaStatusProvider, + getAndVerifyServerKeysInteractor = mockGetAndVerifyServerKeysInteractor, + signInVerifyInteractor = mockSignInVerifyInteractor, + inAppReviewInteractor = mockInAppReviewInteractor, + signInIdlingResource = mockSignInIdlingResource, + postSignInActionsInteractor = mockPostSignInActionsInteractor, + refreshSessionUseCase = mockRefreshSessionUseCase, + mfaProvidersHandler = mockMfaProvidersHandler, + serverKeysWarmup = mockServerKeysWarmup, + hasLocalReplicaUseCase = mockHasLocalReplicaUseCase, + backgroundSignInExecutor = mockBackgroundSignInExecutor, + ) + + @Test + fun as_an_online_user_i_can_sign_in_with_valid_passphrase_and_receive_authenticated_session() = + runTest(testDispatcher) { + whenever(mockVerifyPassphraseUseCase.execute(any())).thenReturn( + VerifyPassphraseUseCase.Output(isCorrect = true), + ) + whenever(mockHasLocalReplicaUseCase.execute(any())).thenReturn( + HasLocalReplicaUseCase.Output(hasLocalReplica = false), + ) + + doAnswer { invocation -> + val onSuccess = invocation.getArgument Unit>(2) + runBlocking { + onSuccess( + GetAndVerifyServerKeysAndTimeInteractor.Success( + pgpKey = "mockServerPublicKey", + pgpKeyFingerprint = "mockFingerprint", + rsaKey = "mockRsaKey", + ), + ) + } + Unit + }.whenever(mockGetAndVerifyServerKeysInteractor).getAndVerifyServerKeys(any(), any(), any()) + + doAnswer { invocation -> + val onSuccess = invocation.getArgument Unit>(5) + runBlocking { + onSuccess( + SignInVerifyInteractor.Success( + challengeResponseDto = ChallengeResponseDto( + version = "v4", + domain = "https://passly.svaroh.net", + verifyToken = "token", + accessToken = "mock-access-token", + refreshToken = "mock-refresh-token", + mfaProviders = null, + ), + accessToken = "mock-access-token", + refreshToken = "mock-refresh-token", + mfaToken = null, + currentMfaToken = null, + ), + ) + } + Unit + }.whenever(mockSignInVerifyInteractor).signInVerify(any(), any(), any(), any(), any(), any()) + + doAnswer { invocation -> + val onSuccess = invocation.getArgument Unit>(1) + runBlocking { onSuccess() } + Unit + }.whenever(mockPostSignInActionsInteractor).launchPostSignInActions(any(), any()) + + val viewModel = createViewModel(authConfig = AuthConfig.SignIn) + + viewModel.sideEffect.test { + viewModel.onIntent(AuthIntent.PassphraseInputChanged(TEST_PASSPHRASE.toByteArray())) + viewModel.onIntent(AuthIntent.SignIn) + testDispatcher.scheduler.advanceUntilIdle() + + assertIs(awaitItem()) + val effect = awaitItem() + assertIs(effect) + verify(mockRuntimeAuthenticatedFlag, atLeastOnce()).isAuthenticated = true + verify(mockSaveSessionUseCase).execute(any()) + verify(mockPassphraseMemoryCache, atLeastOnce()).set(any()) + } + } + + @Test + fun as_a_user_with_incorrect_passphrase_sign_in_fails_with_wrong_passphrase_error() = + runTest(testDispatcher) { + whenever(mockVerifyPassphraseUseCase.execute(any())).thenReturn( + VerifyPassphraseUseCase.Output(isCorrect = false), + ) + + val viewModel = createViewModel() + + viewModel.sideEffect.test { + viewModel.onIntent(AuthIntent.PassphraseInputChanged("WrongPassword!".toByteArray())) + viewModel.onIntent(AuthIntent.SignIn) + testDispatcher.scheduler.advanceUntilIdle() + + assertIs(awaitItem()) + val effect = awaitItem() + assertIs(effect) + assertThat(effect.kind).isEqualTo(AuthSideEffect.SnackbarErrorType.WRONG_PASSPHRASE) + verify(mockRuntimeAuthenticatedFlag, never()).isAuthenticated = true + } + } + + @Test + fun as_an_offline_user_with_local_replica_i_can_unlock_vault_without_server_connection() = + runTest(testDispatcher) { + whenever(mockVerifyPassphraseUseCase.execute(any())).thenReturn( + VerifyPassphraseUseCase.Output(isCorrect = true), + ) + + // Симулюємо відсутність підключення до сервера (Server Not Reachable / Offline) + doAnswer { invocation -> + val onError = invocation.getArgument<(GetAndVerifyServerKeysAndTimeInteractor.Error) -> Unit>(1) + onError(GetAndVerifyServerKeysAndTimeInteractor.Error.ServerNotReachable("https://passly.svaroh.net")) + Unit + }.whenever(mockGetAndVerifyServerKeysInteractor).getAndVerifyServerKeys(any(), any(), any()) + + // Локальна зашифрована репліка доступна на пристрої + whenever(mockHasLocalReplicaUseCase.execute(UserIdInput(TEST_USER_ID))).thenReturn( + HasLocalReplicaUseCase.Output(hasLocalReplica = true), + ) + + val viewModel = createViewModel() + + viewModel.sideEffect.test { + viewModel.onIntent(AuthIntent.PassphraseInputChanged(TEST_PASSPHRASE.toByteArray())) + viewModel.onIntent(AuthIntent.SignIn) + testDispatcher.scheduler.advanceUntilIdle() + + assertIs(awaitItem()) + // Сховище розблоковується в офлайн режимі без потреби у сервері! + val effect = awaitItem() + assertIs(effect) + verify(mockRuntimeAuthenticatedFlag, atLeastOnce()).isAuthenticated = true + verify(mockPassphraseMemoryCache, atLeastOnce()).set(any()) + assertThat(viewModel.viewState.value.showServerNotReachable).isFalse() + } + } + + @Test + fun as_an_offline_user_without_local_replica_vault_unlock_shows_server_unreachable_state() = + runTest(testDispatcher) { + whenever(mockVerifyPassphraseUseCase.execute(any())).thenReturn( + VerifyPassphraseUseCase.Output(isCorrect = true), + ) + + // Симулюємо відсутність зв'язку + doAnswer { invocation -> + val onError = invocation.getArgument<(GetAndVerifyServerKeysAndTimeInteractor.Error) -> Unit>(1) + onError(GetAndVerifyServerKeysAndTimeInteractor.Error.ServerNotReachable("https://passly.svaroh.net")) + Unit + }.whenever(mockGetAndVerifyServerKeysInteractor).getAndVerifyServerKeys(any(), any(), any()) + + // Локальної репліки ще немає (наприклад, перший запуск додатку без інтернету) + whenever(mockHasLocalReplicaUseCase.execute(UserIdInput(TEST_USER_ID))).thenReturn( + HasLocalReplicaUseCase.Output(hasLocalReplica = false), + ) + + val viewModel = createViewModel() + + viewModel.sideEffect.test { + viewModel.onIntent(AuthIntent.PassphraseInputChanged(TEST_PASSPHRASE.toByteArray())) + viewModel.onIntent(AuthIntent.SignIn) + testDispatcher.scheduler.advanceUntilIdle() + + assertIs(awaitItem()) + // Додаток коректно інформує про недоступність сервера замість падіння + expectNoEvents() + assertThat(viewModel.viewState.value.showServerNotReachable).isTrue() + assertThat(viewModel.viewState.value.serverNotReachableDomain).isEqualTo("https://passly.svaroh.net") + } + } + + @Test + fun active_session_can_be_refreshed_automatically() = + runTest(testDispatcher) { + whenever(mockRefreshSessionUseCase.execute(any())).thenReturn( + RefreshSessionUseCase.Output.Success, + ) + + whenever(mockVerifyPassphraseUseCase.execute(any())).thenReturn( + VerifyPassphraseUseCase.Output(isCorrect = true), + ) + + val viewModel = createViewModel(authConfig = AuthConfig.RefreshSession) + + viewModel.sideEffect.test { + viewModel.onIntent(AuthIntent.PassphraseInputChanged(TEST_PASSPHRASE.toByteArray())) + viewModel.onIntent(AuthIntent.SignIn) + testDispatcher.scheduler.advanceUntilIdle() + + assertIs(awaitItem()) + val effect = awaitItem() + assertIs(effect) + verify(mockRefreshSessionUseCase).execute(any()) + } + } + + @Test + fun user_can_sign_out_which_clears_session_and_memory_cache() = + runTest(testDispatcher) { + whenever(mockSignOutUseCase.execute(any())).thenReturn( + SignOutUseCase.Output(ServerSignOutStatus.SIGNED_OUT), + ) + + val viewModel = createViewModel() + + viewModel.sideEffect.test { + viewModel.onIntent(AuthIntent.SignOut) + testDispatcher.scheduler.advanceUntilIdle() + + val effect = awaitItem() + assertIs(effect) + verify(mockSignOutUseCase).execute(any()) + } + } + + @Test + fun multi_account_user_can_switch_between_accounts_and_update_selected_account() = + runTest(testDispatcher) { + val targetUserId = "target-user-uuid-456" + + val viewModel = createViewModel() + viewModel.sideEffect.test { + viewModel.onIntent(AuthIntent.ConnectToExistingAccount) + testDispatcher.scheduler.advanceUntilIdle() + + val effect = awaitItem() + assertIs(effect) + } + + // Перевіряємо, що збереження вибраного акаунту коректно делегується + mockSaveSelectedAccountUseCase.execute(UserIdInput(targetUserId)) + verify(mockSaveSelectedAccountUseCase).execute(UserIdInput(targetUserId)) + } + + private companion object { + private const val TEST_USER_ID = "test-user-uuid-123" + private const val TEST_PASSPHRASE = "SuperSecretPassphrase123!" + } +} diff --git a/app/src/test/java/net/svaroh/passly/e2e/ComprehensiveAppLifecycleE2ETest.kt b/app/src/test/java/net/svaroh/passly/e2e/ComprehensiveAppLifecycleE2ETest.kt new file mode 100644 index 000000000..0f0e27f46 --- /dev/null +++ b/app/src/test/java/net/svaroh/passly/e2e/ComprehensiveAppLifecycleE2ETest.kt @@ -0,0 +1,333 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.e2e + +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.paging.PagingData +import app.cash.turbine.test +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import net.svaroh.passly.common.datarefresh.DataRefreshTrackingFlow +import net.svaroh.passly.common.urimatcher.AutofillUriMatcher +import net.svaroh.passly.commontest.TestCoroutineLaunchContext +import net.svaroh.passly.core.architecture.result.DomainResult +import net.svaroh.passly.core.fulldatarefresh.HomeDataInteractor +import net.svaroh.passly.core.fulldatarefresh.RefreshProgressTrackerFactory +import net.svaroh.passly.core.idlingresource.ResourcesFullRefreshIdlingResource +import net.svaroh.passly.core.mvp.authentication.AuthenticationState +import net.svaroh.passly.core.passwordgenerator.PasswordGenerator +import net.svaroh.passly.core.passwordgenerator.SecretGenerator +import net.svaroh.passly.core.passwordgenerator.dice.Dice +import net.svaroh.passly.core.passwordgenerator.entropy.EntropyCalculator +import net.svaroh.passly.core.passphrasememorycache.AuthOnEveryEntryChecker +import net.svaroh.passly.core.passphrasememorycache.PassphraseMemoryCache +import net.svaroh.passly.core.passphrasememorycache.PotentialPassphrase +import net.svaroh.passly.core.passphrasememorycache.usePassphraseCopy +import net.svaroh.passly.core.sync.SyncFailureReason +import net.svaroh.passly.core.sync.SyncResult +import net.svaroh.passly.core.sync.SyncStats +import net.svaroh.passly.core.sync.SyncStatus +import net.svaroh.passly.core.sync.SyncStatusRepository +import net.svaroh.passly.database.snapshot.ResourcesSnapshot +import net.svaroh.passly.domain.folders.FoldersRepository +import net.svaroh.passly.domain.folders.model.FolderModel +import net.svaroh.passly.domain.folders.model.FolderModelWithAttributes +import net.svaroh.passly.domain.folders.usecase.CreateFolderUseCase +import net.svaroh.passly.domain.folders.usecase.FoldersInteractor +import net.svaroh.passly.domain.folders.usecase.GetLocalDirectChildFoldersPaginatedUseCase +import net.svaroh.passly.domain.folders.usecase.GetLocalSubFoldersForFolderPaginatedUseCase +import net.svaroh.passly.domain.folders.usecase.GetLocalSubFoldersForFolderUseCase +import net.svaroh.passly.domain.groups.usecase.GetLocalGroupsWithShareItemsCountPaginatedUseCase +import net.svaroh.passly.domain.groups.usecase.GroupsInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataKeysInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataKeysSettingsInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataPrivateKeysInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataSessionKeysInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataTypesSettingsInteractor +import net.svaroh.passly.domain.rbac.usecase.GetRbacRulesUseCase +import net.svaroh.passly.domain.resources.usecase.ResourceInteractor +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcesPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcesWithGroupPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcesWithTagPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalSubFolderResourcesFilteredPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetResourcesInFolderPaginatedUseCase +import net.svaroh.passly.domain.resourcetypes.usecase.ResourceTypesInteractor +import net.svaroh.passly.domain.tags.usecase.GetLocalTagsPaginatedUseCase +import net.svaroh.passly.domain.users.usecase.UsersInteractor +import net.svaroh.passly.entity.featureflags.FeatureFlagsModel +import net.svaroh.passly.feature.home.screen.ShowSuggestedModel +import net.svaroh.passly.feature.home.screen.data.HomeDataProvider +import net.svaroh.passly.featureflags.usecase.GetFeatureFlagsUseCase +import net.svaroh.passly.ui.HomeDisplayViewModel +import net.svaroh.passly.ui.PasswordGeneratorSettingsUiModel +import net.svaroh.passly.ui.PermissionModel +import net.svaroh.passly.ui.RbacModel +import net.svaroh.passly.ui.RbacRuleModel +import net.svaroh.passly.ui.ResourcePermission +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import java.time.ZonedDateTime +import java.util.UUID +import kotlin.test.assertIs + +@OptIn(ExperimentalCoroutinesApi::class) +class ComprehensiveAppLifecycleE2ETest { + + private val testDispatcher = StandardTestDispatcher() + + @Before + fun setUp() { + Dispatchers.setMain(testDispatcher) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun complete_enterprise_e2e_lifecycle_online_bootstrap_offline_transition_resync_and_cleanup() = + runTest { + val userPassphrase = "EnterpriseSafePassphrase2026!".toByteArray() + val now = ZonedDateTime.now() + + // ------------------------------------------------------------- + // Фаза 1: Ініціалізація сховища та кешу парольної фрази + // ------------------------------------------------------------- + val mockLifecycleOwner = mock() + val mockLifecycle = mock() + whenever(mockLifecycleOwner.lifecycle).thenReturn(mockLifecycle) + + val passphraseMemoryCache = PassphraseMemoryCache( + coroutineLaunchContext = TestCoroutineLaunchContext(), + lifecycleOwner = mockLifecycleOwner, + dataRefreshTrackingFlow = DataRefreshTrackingFlow(), + authOnEveryEntryChecker = AuthOnEveryEntryChecker { false }, + ) + assertThat(passphraseMemoryCache.hasPassphrase()).isFalse() + + // Зберігаємо парольну фразу в пам'яті після успішного входу + passphraseMemoryCache.set(userPassphrase) + assertThat(passphraseMemoryCache.hasPassphrase()).isTrue() + + // ------------------------------------------------------------- + // Фаза 2: Повне оновлення даних при онлайн-підключенні + // ------------------------------------------------------------- + val mockFoldersInteractor = mock() + val mockResourcesInteractor = mock() + val mockGroupsInteractor = mock() + val mockUsersInteractor = mock() + val mockResourceTypesInteractor = mock() + val mockMetadataKeysInteractor = mock() + val mockMetadataPrivateKeysInteractor = mock() + val mockMetadataSessionKeysInteractor = mock() + val mockMetadataTypesSettingsInteractor = mock() + val mockMetadataKeysSettingsInteractor = mock() + val mockFeatureFlagsUseCase = mock() + val mockIdlingResource = mock() + val mockSnapshot = mock() + + val featureFlags = FeatureFlagsModel( + privacyPolicyUrl = null, + termsAndConditionsUrl = null, + isPreviewPasswordAvailable = true, + areFoldersAvailable = true, + areTagsAvailable = true, + isTotpAvailable = true, + isRbacAvailable = true, + isPasswordExpiryAvailable = true, + arePasswordPoliciesAvailable = true, + canUpdatePasswordPolicies = true, + isV5MetadataAvailable = false, + ) + whenever(mockFeatureFlagsUseCase.execute(Unit)).thenReturn( + GetFeatureFlagsUseCase.Output(featureFlags), + ) + whenever(mockResourceTypesInteractor.fetchAndSaveResourceTypes()).thenReturn(ResourceTypesInteractor.Output.Success) + whenever(mockUsersInteractor.fetchAndSaveUsers()).thenReturn(UsersInteractor.Output.Success) + whenever(mockGroupsInteractor.fetchAndSaveGroups()).thenReturn(GroupsInteractor.Output.Success) + whenever(mockFoldersInteractor.fetchAndSaveFolders(any())).thenReturn(FoldersInteractor.Output.Success) + whenever(mockResourcesInteractor.fetchAndSaveResources(any())).thenReturn(ResourceInteractor.Output.Success) + + val homeDataInteractor = HomeDataInteractor( + foldersInteractor = mockFoldersInteractor, + resourcesInteractor = mockResourcesInteractor, + groupsInteractor = mockGroupsInteractor, + usersInteractor = mockUsersInteractor, + resourceTypesInteractor = mockResourceTypesInteractor, + metadataKeysInteractor = mockMetadataKeysInteractor, + metadataPrivateKeysInteractor = mockMetadataPrivateKeysInteractor, + metadataSessionKeysInteractor = mockMetadataSessionKeysInteractor, + metadataTypesSettingsInteractor = mockMetadataTypesSettingsInteractor, + metadataKeysSettingsInteractor = mockMetadataKeysSettingsInteractor, + featureFlagsUseCase = mockFeatureFlagsUseCase, + resourcesFullRefreshIdlingResource = mockIdlingResource, + resourcesSnapshot = mockSnapshot, + refreshProgressTrackerFactory = RefreshProgressTrackerFactory(), + ) + + val refreshOutput = homeDataInteractor.refreshAllHomeScreenData() + assertIs(refreshOutput) + + // ------------------------------------------------------------- + // Фаза 3: Генерація надійного паролю та створення папки + // ------------------------------------------------------------- + val coroutineLaunchContext = TestCoroutineLaunchContext() + val passwordGenerator = PasswordGenerator(coroutineLaunchContext) + val mockDice = mock() + val entropyCalculator = EntropyCalculator(mockDice, coroutineLaunchContext) + val secretGenerator = SecretGenerator( + passwordGenerator = passwordGenerator, + passphraseGenerator = mock(), + entropyCalculator = entropyCalculator, + ) + + val generatedSecretResult = secretGenerator.generatePassword( + PasswordGeneratorSettingsUiModel( + length = 20, + maskUpper = true, + maskLower = true, + maskDigit = true, + maskParenthesis = true, + maskEmoji = false, + maskChar1 = true, + maskChar2 = true, + maskChar3 = true, + maskChar4 = true, + maskChar5 = true, + excludeLookAlikeChars = true, + ), + ) + assertIs(generatedSecretResult) + assertThat(generatedSecretResult.password).hasSize(20) + assertThat(generatedSecretResult.entropy).isGreaterThan(80.0) + + val mockFoldersRepository = mock() + val createFolderUseCase = CreateFolderUseCase(mockFoldersRepository) + val folderId = UUID.randomUUID().toString() + val folderModel = FolderModel( + folderId = folderId, + parentFolderId = null, + name = "Infrastructure & Cloud", + isShared = false, + permission = ResourcePermission.OWNER, + modified = now, + ) + whenever(mockFoldersRepository.createFolder("Infrastructure & Cloud", null)).thenReturn( + DomainResult.Finished(FolderModelWithAttributes(folderModel, emptyList())), + ) + val createFolderResult = createFolderUseCase.execute( + CreateFolderUseCase.Input("Infrastructure & Cloud", null), + ) + assertIs(createFolderResult) + assertThat(createFolderResult.folderWithAttributes.folderModel.folderId).isEqualTo(folderId) + + // ------------------------------------------------------------- + // Фаза 4: Втрата зв'язку з сервером (Офлайн режим) + // ------------------------------------------------------------- + val syncRepository = SyncStatusRepository() + syncRepository.onSuccess(now) + syncRepository.onOffline() + + // Перевіряємо статус синхронізації при відсутності мережі + val offlineStatus = syncRepository.status.value + assertIs(offlineStatus) + + // Перевіряємо читання локального сховища в офлайн режимі через HomeDataProvider + val mockGetLocalResources = mock() + val mockGetRbac = mock() + whenever(mockGetRbac.execute(Unit)).thenReturn( + GetRbacRulesUseCase.Output( + RbacModel( + passwordPreviewRule = RbacRuleModel.ALLOW, + passwordCopyRule = RbacRuleModel.ALLOW, + tagsUseRule = RbacRuleModel.ALLOW, + shareViewRule = RbacRuleModel.ALLOW, + foldersUseRule = RbacRuleModel.ALLOW, + ), + ), + ) + whenever(mockGetLocalResources.execute(any())).thenReturn( + GetLocalResourcesPaginatedUseCase.Output(flowOf(PagingData.empty())), + ) + + val homeDataProvider = HomeDataProvider( + getLocalResourcesPaginatedUseCase = mockGetLocalResources, + getLocalTagsPaginatedUseCase = mock(), + getLocalResourcesWithLocalTagsPaginatedUseCase = mock(), + getLocalGroupsWithShareItemsCountPaginatedUseCase = mock(), + getLocalResourcesWithGroupsPaginatedUseCase = mock(), + getLocalDirectChildFoldersPaginatedUseCase = mock(), + getResourcesInFolderPaginatedUseCase = mock(), + getLocalSubFolderResourcesFilteredPaginatedUseCase = mock(), + getLocalSubFoldersForFolderUseCase = mock(), + getLocalSubFoldersForFolderPaginatedUseCase = mock(), + autofillMatcher = mock(), + getRbacRulesUseCase = mockGetRbac, + ) + + val offlineVaultData = homeDataProvider.provideData( + searchQuery = null, + homeView = HomeDisplayViewModel.AllItems, + showSuggestedModel = ShowSuggestedModel.DoNotShow, + ) + assertThat(offlineVaultData.resourceList).isNotNull() + + // Перевіряємо розшифрування секрету за допомогою збереженої парольної фрази офлайн + var secretDecryptedOffline = false + passphraseMemoryCache.usePassphraseCopy( + onPassphraseNotPresent = { throw AssertionError("Offline passphrase must be available") }, + action = { cachedKey -> + assertThat(cachedKey).isEqualTo(userPassphrase) + secretDecryptedOffline = true + }, + ) + assertThat(secretDecryptedOffline).isTrue() + + // ------------------------------------------------------------- + // Фаза 5: Відновлення інтернет-з'єднання та синхронізація + // ------------------------------------------------------------- + syncRepository.onRunStarted(SyncStatus.Running.Phase.DELTA) + syncRepository.onProgress(SyncStatus.Running.Phase.DELTA, processed = 10, total = 10) + val laterSyncTime = now.plusMinutes(15) + syncRepository.onSuccess(laterSyncTime) + + val idleRestored = syncRepository.status.value + assertIs(idleRestored) + assertThat(idleRestored.lastSuccessAt).isEqualTo(laterSyncTime) + + // ------------------------------------------------------------- + // Фаза 6: Блокування додатку та очищення секретів + // ------------------------------------------------------------- + passphraseMemoryCache.clear() + assertThat(passphraseMemoryCache.hasPassphrase()).isFalse() + assertThat(passphraseMemoryCache.get()).isInstanceOf(PotentialPassphrase.PassphraseNotPresent::class.java) + } +} diff --git a/app/src/test/java/net/svaroh/passly/e2e/FolderOrganizationAndSearchE2ETest.kt b/app/src/test/java/net/svaroh/passly/e2e/FolderOrganizationAndSearchE2ETest.kt new file mode 100644 index 000000000..e7b9bb63c --- /dev/null +++ b/app/src/test/java/net/svaroh/passly/e2e/FolderOrganizationAndSearchE2ETest.kt @@ -0,0 +1,316 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.e2e + +import androidx.paging.PagingData +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.common.urimatcher.AutofillUriMatcher +import net.svaroh.passly.core.architecture.result.DomainResult +import net.svaroh.passly.core.architecture.result.DomainResult.Incomplete.Error.Reason.UNKNOWN +import net.svaroh.passly.domain.folders.FoldersRepository +import net.svaroh.passly.domain.folders.model.FolderModel +import net.svaroh.passly.domain.folders.model.FolderModelWithAttributes +import net.svaroh.passly.domain.folders.usecase.CreateFolderUseCase +import net.svaroh.passly.domain.folders.usecase.GetLocalDirectChildFoldersPaginatedUseCase +import net.svaroh.passly.domain.folders.usecase.GetLocalSubFoldersForFolderPaginatedUseCase +import net.svaroh.passly.domain.folders.usecase.GetLocalSubFoldersForFolderUseCase +import net.svaroh.passly.domain.groups.usecase.GetLocalGroupsWithShareItemsCountPaginatedUseCase +import net.svaroh.passly.domain.rbac.usecase.GetRbacRulesUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcesPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcesWithGroupPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcesWithTagPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalSubFolderResourcesFilteredPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetResourcesInFolderPaginatedUseCase +import net.svaroh.passly.domain.tags.usecase.GetLocalTagsPaginatedUseCase +import net.svaroh.passly.feature.home.screen.ShowSuggestedModel +import net.svaroh.passly.feature.home.screen.data.HomeDataProvider +import net.svaroh.passly.ui.Folder +import net.svaroh.passly.ui.HomeDisplayViewModel +import net.svaroh.passly.ui.PermissionModel +import net.svaroh.passly.ui.RbacModel +import net.svaroh.passly.ui.RbacRuleModel +import net.svaroh.passly.ui.ResourcePermission +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argThat +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import java.time.ZonedDateTime +import java.util.UUID +import kotlin.test.assertIs + +@OptIn(ExperimentalCoroutinesApi::class) +class FolderOrganizationAndSearchE2ETest { + + @Test + fun create_folder_usecase_persists_new_root_and_nested_folders() = + runTest { + val mockFoldersRepository = mock() + val createFolderUseCase = CreateFolderUseCase(mockFoldersRepository) + + val rootFolderId = UUID.randomUUID().toString() + val childFolderId = UUID.randomUUID().toString() + + val rootFolderModel = FolderModel( + folderId = rootFolderId, + parentFolderId = null, + name = "Infrastructure", + isShared = false, + permission = ResourcePermission.OWNER, + modified = ZonedDateTime.now(), + ) + val rootWithAttributes = FolderModelWithAttributes( + folderModel = rootFolderModel, + folderPermissions = emptyList(), + ) + + val childFolderModel = FolderModel( + folderId = childFolderId, + parentFolderId = rootFolderId, + name = "Production Keys", + isShared = false, + permission = ResourcePermission.OWNER, + modified = ZonedDateTime.now(), + ) + val childWithAttributes = FolderModelWithAttributes( + folderModel = childFolderModel, + folderPermissions = emptyList(), + ) + + // 1. Створення кореневої папки + whenever(mockFoldersRepository.createFolder("Infrastructure", null)).thenReturn( + DomainResult.Finished(rootWithAttributes), + ) + + val rootOutput = createFolderUseCase.execute( + CreateFolderUseCase.Input(name = "Infrastructure", parentFolderId = null), + ) + assertIs(rootOutput) + assertThat(rootOutput.folderWithAttributes.folderModel.name).isEqualTo("Infrastructure") + assertThat(rootOutput.folderWithAttributes.folderModel.parentFolderId).isNull() + + // 2. Створення вкладеної папки + whenever(mockFoldersRepository.createFolder("Production Keys", rootFolderId)).thenReturn( + DomainResult.Finished(childWithAttributes), + ) + + val childOutput = createFolderUseCase.execute( + CreateFolderUseCase.Input(name = "Production Keys", parentFolderId = rootFolderId), + ) + assertIs(childOutput) + assertThat(childOutput.folderWithAttributes.folderModel.name).isEqualTo("Production Keys") + assertThat(childOutput.folderWithAttributes.folderModel.parentFolderId).isEqualTo(rootFolderId) + } + + @Test + fun create_folder_fails_cleanly_when_server_returns_error() = + runTest { + val mockFoldersRepository = mock() + val createFolderUseCase = CreateFolderUseCase(mockFoldersRepository) + + whenever(mockFoldersRepository.createFolder("Forbidden Folder", null)).thenReturn( + DomainResult.Incomplete.Error(reason = UNKNOWN, message = "Access Denied"), + ) + + val output = createFolderUseCase.execute( + CreateFolderUseCase.Input(name = "Forbidden Folder", parentFolderId = null), + ) + + assertIs(output) + assertThat(output.incomplete).isInstanceOf(DomainResult.Incomplete.Error::class.java) + } + + @Test + fun home_data_provider_filters_vault_by_search_query_across_all_items() = + runTest { + val mockGetLocalResourcesPaginatedUseCase = mock() + val mockGetLocalTagsPaginatedUseCase = mock() + val mockGetLocalResourcesWithLocalTagsPaginatedUseCase = mock() + val mockGetLocalGroupsWithShareItemsCountPaginatedUseCase = mock() + val mockGetLocalResourcesWithGroupsPaginatedUseCase = mock() + val mockGetLocalDirectChildFoldersPaginatedUseCase = mock() + val mockGetResourcesInFolderPaginatedUseCase = mock() + val mockGetLocalSubFolderResourcesFilteredPaginatedUseCase = mock() + val mockGetLocalSubFoldersForFolderUseCase = mock() + val mockGetLocalSubFoldersForFolderPaginatedUseCase = mock() + val mockAutofillMatcher = mock() + val mockGetRbacRulesUseCase = mock() + + whenever(mockGetRbacRulesUseCase.execute(Unit)).thenReturn( + GetRbacRulesUseCase.Output( + rbacModel = RbacModel( + passwordPreviewRule = RbacRuleModel.ALLOW, + passwordCopyRule = RbacRuleModel.ALLOW, + tagsUseRule = RbacRuleModel.ALLOW, + shareViewRule = RbacRuleModel.ALLOW, + foldersUseRule = RbacRuleModel.ALLOW, + ), + ), + ) + + val searchQuery = "production-db" + whenever( + mockGetLocalResourcesPaginatedUseCase.execute( + argThat { this.searchQuery == searchQuery }, + ), + ).thenReturn( + GetLocalResourcesPaginatedUseCase.Output(flowOf(PagingData.empty())), + ) + + val provider = HomeDataProvider( + getLocalResourcesPaginatedUseCase = mockGetLocalResourcesPaginatedUseCase, + getLocalTagsPaginatedUseCase = mockGetLocalTagsPaginatedUseCase, + getLocalResourcesWithLocalTagsPaginatedUseCase = mockGetLocalResourcesWithLocalTagsPaginatedUseCase, + getLocalGroupsWithShareItemsCountPaginatedUseCase = mockGetLocalGroupsWithShareItemsCountPaginatedUseCase, + getLocalResourcesWithGroupsPaginatedUseCase = mockGetLocalResourcesWithGroupsPaginatedUseCase, + getLocalDirectChildFoldersPaginatedUseCase = mockGetLocalDirectChildFoldersPaginatedUseCase, + getResourcesInFolderPaginatedUseCase = mockGetResourcesInFolderPaginatedUseCase, + getLocalSubFolderResourcesFilteredPaginatedUseCase = mockGetLocalSubFolderResourcesFilteredPaginatedUseCase, + getLocalSubFoldersForFolderUseCase = mockGetLocalSubFoldersForFolderUseCase, + getLocalSubFoldersForFolderPaginatedUseCase = mockGetLocalSubFoldersForFolderPaginatedUseCase, + autofillMatcher = mockAutofillMatcher, + getRbacRulesUseCase = mockGetRbacRulesUseCase, + ) + + val homeData = provider.provideData( + searchQuery = searchQuery, + homeView = HomeDisplayViewModel.AllItems, + showSuggestedModel = ShowSuggestedModel.DoNotShow, + ) + + assertThat(homeData.resourceList).isNotNull() + } + + @Test + fun home_data_provider_respects_rbac_rules_and_hides_folders_when_denied() = + runTest { + val mockGetRbacRulesUseCase = mock() + + // RBAC забороняє використання папок: foldersUseRule = DENY + whenever(mockGetRbacRulesUseCase.execute(Unit)).thenReturn( + GetRbacRulesUseCase.Output( + rbacModel = RbacModel( + passwordPreviewRule = RbacRuleModel.ALLOW, + passwordCopyRule = RbacRuleModel.ALLOW, + tagsUseRule = RbacRuleModel.ALLOW, + shareViewRule = RbacRuleModel.ALLOW, + foldersUseRule = RbacRuleModel.DENY, + ), + ), + ) + + val provider = HomeDataProvider( + getLocalResourcesPaginatedUseCase = mock(), + getLocalTagsPaginatedUseCase = mock(), + getLocalResourcesWithLocalTagsPaginatedUseCase = mock(), + getLocalGroupsWithShareItemsCountPaginatedUseCase = mock(), + getLocalResourcesWithGroupsPaginatedUseCase = mock(), + getLocalDirectChildFoldersPaginatedUseCase = mock(), + getResourcesInFolderPaginatedUseCase = mock(), + getLocalSubFolderResourcesFilteredPaginatedUseCase = mock(), + getLocalSubFoldersForFolderUseCase = mock(), + getLocalSubFoldersForFolderPaginatedUseCase = mock(), + autofillMatcher = mock(), + getRbacRulesUseCase = mockGetRbacRulesUseCase, + ) + + val result = provider.provideData( + searchQuery = null, + homeView = HomeDisplayViewModel.Folders(activeFolder = Folder.Child("folder-123")), + showSuggestedModel = ShowSuggestedModel.DoNotShow, + ) + + // При забороні RBAC повертається порожній HomeData + assertThat(result).isNotNull() + } + + @Test + fun home_data_provider_supports_switching_views_between_all_favourites_and_folders() = + runTest { + val mockGetLocalResourcesPaginatedUseCase = mock() + val mockGetRbacRulesUseCase = mock() + val mockGetLocalDirectChildFoldersPaginatedUseCase = mock() + val mockGetResourcesInFolderPaginatedUseCase = mock() + + whenever(mockGetRbacRulesUseCase.execute(Unit)).thenReturn( + GetRbacRulesUseCase.Output( + rbacModel = RbacModel( + passwordPreviewRule = RbacRuleModel.ALLOW, + passwordCopyRule = RbacRuleModel.ALLOW, + tagsUseRule = RbacRuleModel.ALLOW, + shareViewRule = RbacRuleModel.ALLOW, + foldersUseRule = RbacRuleModel.ALLOW, + ), + ), + ) + + whenever(mockGetLocalResourcesPaginatedUseCase.execute(any())).thenReturn( + GetLocalResourcesPaginatedUseCase.Output(flowOf(PagingData.empty())), + ) + whenever(mockGetLocalDirectChildFoldersPaginatedUseCase.execute(any())).thenReturn( + GetLocalDirectChildFoldersPaginatedUseCase.Output(flowOf(PagingData.empty())), + ) + whenever(mockGetResourcesInFolderPaginatedUseCase.execute(any())).thenReturn( + GetResourcesInFolderPaginatedUseCase.Output(flowOf(PagingData.empty())), + ) + + val provider = HomeDataProvider( + getLocalResourcesPaginatedUseCase = mockGetLocalResourcesPaginatedUseCase, + getLocalTagsPaginatedUseCase = mock(), + getLocalResourcesWithLocalTagsPaginatedUseCase = mock(), + getLocalGroupsWithShareItemsCountPaginatedUseCase = mock(), + getLocalResourcesWithGroupsPaginatedUseCase = mock(), + getLocalDirectChildFoldersPaginatedUseCase = mockGetLocalDirectChildFoldersPaginatedUseCase, + getResourcesInFolderPaginatedUseCase = mockGetResourcesInFolderPaginatedUseCase, + getLocalSubFolderResourcesFilteredPaginatedUseCase = mock(), + getLocalSubFoldersForFolderUseCase = mock(), + getLocalSubFoldersForFolderPaginatedUseCase = mock(), + autofillMatcher = mock(), + getRbacRulesUseCase = mockGetRbacRulesUseCase, + ) + + // 1. Вкладка Favourites + val favouritesData = provider.provideData( + searchQuery = null, + homeView = HomeDisplayViewModel.Favourites, + showSuggestedModel = ShowSuggestedModel.DoNotShow, + ) + assertThat(favouritesData.resourceList).isNotNull() + + // 2. Вкладка SharedWithMe + val sharedData = provider.provideData( + searchQuery = null, + homeView = HomeDisplayViewModel.SharedWithMe, + showSuggestedModel = ShowSuggestedModel.DoNotShow, + ) + assertThat(sharedData.resourceList).isNotNull() + + // 3. Вкладка Folders (Root) + val foldersData = provider.provideData( + searchQuery = null, + homeView = HomeDisplayViewModel.Folders(activeFolder = Folder.Root), + showSuggestedModel = ShowSuggestedModel.DoNotShow, + ) + assertThat(foldersData.foldersList).isNotNull() + assertThat(foldersData.resourceList).isNotNull() + } +} diff --git a/app/src/test/java/net/svaroh/passly/e2e/OfflineSyncAndResilienceE2ETest.kt b/app/src/test/java/net/svaroh/passly/e2e/OfflineSyncAndResilienceE2ETest.kt new file mode 100644 index 000000000..fee01b871 --- /dev/null +++ b/app/src/test/java/net/svaroh/passly/e2e/OfflineSyncAndResilienceE2ETest.kt @@ -0,0 +1,299 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.e2e + +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import app.cash.turbine.test +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import net.svaroh.passly.common.coroutinetimer.timerFlow +import net.svaroh.passly.common.datarefresh.DataRefreshTrackingFlow +import net.svaroh.passly.common.urimatcher.AutofillUriMatcher +import net.svaroh.passly.commontest.TestCoroutineLaunchContext +import net.svaroh.passly.core.passphrasememorycache.AuthOnEveryEntryChecker +import net.svaroh.passly.core.passphrasememorycache.PassphraseMemoryCache +import net.svaroh.passly.core.passphrasememorycache.PotentialPassphrase +import net.svaroh.passly.core.passphrasememorycache.usePassphraseCopy +import net.svaroh.passly.core.sync.SyncBackoff +import net.svaroh.passly.core.sync.SyncFailureReason +import net.svaroh.passly.core.sync.SyncResult +import net.svaroh.passly.core.sync.SyncStats +import net.svaroh.passly.core.sync.SyncStatus +import net.svaroh.passly.core.sync.SyncStatusRepository +import net.svaroh.passly.core.sync.SyncTrigger +import net.svaroh.passly.domain.folders.usecase.GetLocalDirectChildFoldersPaginatedUseCase +import net.svaroh.passly.domain.folders.usecase.GetLocalSubFoldersForFolderPaginatedUseCase +import net.svaroh.passly.domain.folders.usecase.GetLocalSubFoldersForFolderUseCase +import net.svaroh.passly.domain.groups.usecase.GetLocalGroupsWithShareItemsCountPaginatedUseCase +import net.svaroh.passly.domain.rbac.usecase.GetRbacRulesUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcesPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcesWithGroupPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcesWithTagPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalSubFolderResourcesFilteredPaginatedUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetResourcesInFolderPaginatedUseCase +import net.svaroh.passly.domain.tags.usecase.GetLocalTagsPaginatedUseCase +import net.svaroh.passly.feature.home.screen.ShowSuggestedModel +import net.svaroh.passly.feature.home.screen.data.HomeDataProvider +import net.svaroh.passly.ui.HomeDisplayViewModel +import net.svaroh.passly.ui.RbacModel +import net.svaroh.passly.ui.RbacRuleModel +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import java.time.Duration +import java.time.ZonedDateTime +import kotlin.test.assertIs + +@OptIn(ExperimentalCoroutinesApi::class) +class OfflineSyncAndResilienceE2ETest { + + private val testDispatcher = StandardTestDispatcher() + + @Before + fun setUp() { + Dispatchers.setMain(testDispatcher) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun sync_status_repository_tracks_idle_running_offline_and_failed_states() = + runTest { + val repository = SyncStatusRepository() + val now = ZonedDateTime.now() + + repository.status.test { + // Початковий стан — Idle без попереднього успіху + val initial = awaitItem() + assertIs(initial) + assertThat(initial.lastSuccessAt).isNull() + + // Симулюємо успішну попередню синхронізацію + repository.onSuccess(now) + val successState = awaitItem() + assertIs(successState) + assertThat(successState.lastSuccessAt).isEqualTo(now) + + // Початок нової синхронізації (фаза PUSHING_LOCAL_CHANGES) + repository.onRunStarted(SyncStatus.Running.Phase.PUSHING_LOCAL_CHANGES) + val runningPush = awaitItem() + assertIs(runningPush) + assertThat(runningPush.phase).isEqualTo(SyncStatus.Running.Phase.PUSHING_LOCAL_CHANGES) + assertThat(runningPush.lastSuccessAt).isEqualTo(now) + + // Прогрес завантаження (фаза DELTA) + repository.onProgress(SyncStatus.Running.Phase.DELTA, processed = 25, total = 100) + val runningProgress = awaitItem() + assertIs(runningProgress) + assertThat(runningProgress.phase).isEqualTo(SyncStatus.Running.Phase.DELTA) + assertThat(runningProgress.processed).isEqualTo(25) + assertThat(runningProgress.total).isEqualTo(100) + + // Втрата інтернет-з'єднання (Offline) + repository.onOffline() + val offlineState = awaitItem() + assertIs(offlineState) + assertThat(offlineState.lastSuccessAt).isEqualTo(now) + + // Помилка сервера (Failed з запланованим retry) + val retryTime = now.plusMinutes(5) + repository.onFailure(SyncFailureReason.UNREACHABLE, retryTime) + val failedState = awaitItem() + assertIs(failedState) + assertThat(failedState.reason).isEqualTo(SyncFailureReason.UNREACHABLE) + assertThat(failedState.retryAt).isEqualTo(retryTime) + assertThat(failedState.lastSuccessAt).isEqualTo(now) + + // Відновлення успіху + val later = now.plusHours(1) + repository.onSuccess(later) + val restoredState = awaitItem() + assertIs(restoredState) + assertThat(restoredState.lastSuccessAt).isEqualTo(later) + } + } + + @Test + fun sync_backoff_calculates_exponential_delays_and_resets_upon_recovery() { + // Перша помилка: 30 секунд + assertThat(SyncBackoff.delayAfter(1)).isEqualTo(Duration.ofSeconds(30)) + + // Друга помилка: 1 хвилина + assertThat(SyncBackoff.delayAfter(2)).isEqualTo(Duration.ofMinutes(1)) + + // Третя помилка: 5 хвилин + assertThat(SyncBackoff.delayAfter(3)).isEqualTo(Duration.ofMinutes(5)) + + // Четверта помилка: 15 хвилин + assertThat(SyncBackoff.delayAfter(4)).isEqualTo(Duration.ofMinutes(15)) + + // П'ята помилка: 1 година + assertThat(SyncBackoff.delayAfter(5)).isEqualTo(Duration.ofHours(1)) + + // Шоста і всі наступні (стеля насичення): 6 годин + assertThat(SyncBackoff.delayAfter(6)).isEqualTo(Duration.ofHours(6)) + assertThat(SyncBackoff.delayAfter(10)).isEqualTo(Duration.ofHours(6)) + assertThat(SyncBackoff.delayAfter(100)).isEqualTo(Duration.ofHours(6)) + + // Ручна синхронізація користувачем завжди ігнорує затримку бекофу (негайний запуск) + assertThat(SyncBackoff.delayAfter(10, SyncTrigger.MANUAL)).isEqualTo(Duration.ZERO) + + // Фонова синхронізація дотримується бекофу + assertThat(SyncBackoff.delayAfter(3, SyncTrigger.BACKGROUND)).isEqualTo(Duration.ofMinutes(5)) + } + + @Test + fun sync_result_outcomes_preserve_local_state_and_track_statistics() { + // 1. Успішна синхронізація повертає детальну статистику + val stats = SyncStats( + upserted = 15, + deleted = 2, + secretsUpdated = 5, + pushedOperations = 1, + reconciled = true, + ) + val successResult = SyncResult.Success(stats) + assertThat(successResult.stats.upserted).isEqualTo(15) + assertThat(successResult.stats.deleted).isEqualTo(2) + assertThat(successResult.stats.isEmpty).isFalse() + + // 2. Пропуск синхронізації через відсутність інтернету не вважається збоєм даних + val skippedNoNetwork = SyncResult.Skipped(SyncResult.Skipped.Reason.NO_NETWORK) + assertThat(skippedNoNetwork.reason).isEqualTo(SyncResult.Skipped.Reason.NO_NETWORK) + + // 3. Збій мережі під час синхронізації + val failureUnreachable = SyncResult.Failure(SyncFailureReason.UNREACHABLE) + assertThat(failureUnreachable.reason).isEqualTo(SyncFailureReason.UNREACHABLE) + } + + @Test + fun home_data_provider_serves_cached_resources_and_folders_when_network_is_offline() = + runTest { + val mockGetLocalResourcesPaginatedUseCase = mock() + val mockGetLocalTagsPaginatedUseCase = mock() + val mockGetLocalResourcesWithLocalTagsPaginatedUseCase = mock() + val mockGetLocalGroupsWithShareItemsCountPaginatedUseCase = mock() + val mockGetLocalResourcesWithGroupsPaginatedUseCase = mock() + val mockGetLocalDirectChildFoldersPaginatedUseCase = mock() + val mockGetResourcesInFolderPaginatedUseCase = mock() + val mockGetLocalSubFolderResourcesFilteredPaginatedUseCase = mock() + val mockGetLocalSubFoldersForFolderUseCase = mock() + val mockGetLocalSubFoldersForFolderPaginatedUseCase = mock() + val mockAutofillMatcher = mock() + val mockGetRbacRulesUseCase = mock() + + whenever(mockGetRbacRulesUseCase.execute(Unit)).thenReturn( + GetRbacRulesUseCase.Output( + rbacModel = RbacModel( + passwordPreviewRule = RbacRuleModel.ALLOW, + passwordCopyRule = RbacRuleModel.ALLOW, + tagsUseRule = RbacRuleModel.ALLOW, + shareViewRule = RbacRuleModel.ALLOW, + foldersUseRule = RbacRuleModel.ALLOW, + ), + ), + ) + + whenever(mockGetLocalResourcesPaginatedUseCase.execute(any())).thenReturn( + GetLocalResourcesPaginatedUseCase.Output(flowOf()), + ) + + val provider = HomeDataProvider( + getLocalResourcesPaginatedUseCase = mockGetLocalResourcesPaginatedUseCase, + getLocalTagsPaginatedUseCase = mockGetLocalTagsPaginatedUseCase, + getLocalResourcesWithLocalTagsPaginatedUseCase = mockGetLocalResourcesWithLocalTagsPaginatedUseCase, + getLocalGroupsWithShareItemsCountPaginatedUseCase = mockGetLocalGroupsWithShareItemsCountPaginatedUseCase, + getLocalResourcesWithGroupsPaginatedUseCase = mockGetLocalResourcesWithGroupsPaginatedUseCase, + getLocalDirectChildFoldersPaginatedUseCase = mockGetLocalDirectChildFoldersPaginatedUseCase, + getResourcesInFolderPaginatedUseCase = mockGetResourcesInFolderPaginatedUseCase, + getLocalSubFolderResourcesFilteredPaginatedUseCase = mockGetLocalSubFolderResourcesFilteredPaginatedUseCase, + getLocalSubFoldersForFolderUseCase = mockGetLocalSubFoldersForFolderUseCase, + getLocalSubFoldersForFolderPaginatedUseCase = mockGetLocalSubFoldersForFolderPaginatedUseCase, + autofillMatcher = mockAutofillMatcher, + getRbacRulesUseCase = mockGetRbacRulesUseCase, + ) + + // Запит на AllItems в офлайн режимі успішно повертає локальні дані + val homeData = provider.provideData( + searchQuery = null, + homeView = HomeDisplayViewModel.AllItems, + showSuggestedModel = ShowSuggestedModel.DoNotShow, + ) + + assertThat(homeData.resourceList).isNotNull() + } + + @Test + fun passphrase_memory_cache_preserves_decryption_credentials_and_enforces_clearing() = + runTest { + val testPassphrase = "SafeOfflinePassphrase99!".toByteArray() + + val mockLifecycleOwner = mock() + val mockLifecycle = mock() + whenever(mockLifecycleOwner.lifecycle).thenReturn(mockLifecycle) + + val cache = PassphraseMemoryCache( + coroutineLaunchContext = TestCoroutineLaunchContext(), + lifecycleOwner = mockLifecycleOwner, + dataRefreshTrackingFlow = DataRefreshTrackingFlow(), + authOnEveryEntryChecker = AuthOnEveryEntryChecker { false }, + ) + + // 1. Початково кеш порожній + assertThat(cache.hasPassphrase()).isFalse() + + // 2. Зберігаємо парольну фразу для офлайн розшифрування + cache.set(testPassphrase) + assertThat(cache.hasPassphrase()).isTrue() + val potential = cache.get() + assertIs(potential) + assertThat(potential.passphrase).isEqualTo(testPassphrase) + + // 3. Безпечне використання копії парольної фрази + var executed = false + cache.usePassphraseCopy( + onPassphraseNotPresent = { + throw AssertionError("Passphrase should be present") + }, + action = { copy -> + assertThat(copy).isEqualTo(testPassphrase) + executed = true + }, + ) + assertThat(executed).isTrue() + + // 4. Очищення кешу при блокуванні або таймауті + cache.clear() + assertThat(cache.hasPassphrase()).isFalse() + assertThat(cache.get()).isInstanceOf(PotentialPassphrase.PassphraseNotPresent::class.java) + } +} diff --git a/app/src/test/java/net/svaroh/passly/e2e/OnlineDataRefreshE2ETest.kt b/app/src/test/java/net/svaroh/passly/e2e/OnlineDataRefreshE2ETest.kt new file mode 100644 index 000000000..2a0c14aa1 --- /dev/null +++ b/app/src/test/java/net/svaroh/passly/e2e/OnlineDataRefreshE2ETest.kt @@ -0,0 +1,303 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.e2e + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.core.fulldatarefresh.HomeDataInteractor +import net.svaroh.passly.core.fulldatarefresh.RefreshProgressTracker +import net.svaroh.passly.core.fulldatarefresh.RefreshProgressTrackerFactory +import net.svaroh.passly.core.idlingresource.ResourcesFullRefreshIdlingResource +import net.svaroh.passly.core.mvp.authentication.AuthenticationState +import net.svaroh.passly.database.snapshot.ResourcesSnapshot +import net.svaroh.passly.domain.folders.usecase.FoldersInteractor +import net.svaroh.passly.domain.groups.usecase.GroupsInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataKeysInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataKeysSettingsInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataPrivateKeysInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataSessionKeysInteractor +import net.svaroh.passly.domain.metadata.interactor.MetadataTypesSettingsInteractor +import net.svaroh.passly.domain.resources.usecase.ResourceInteractor +import net.svaroh.passly.domain.resourcetypes.usecase.ResourceTypesInteractor +import net.svaroh.passly.domain.users.usecase.UsersInteractor +import net.svaroh.passly.entity.featureflags.FeatureFlagsModel +import net.svaroh.passly.featureflags.usecase.GetFeatureFlagsUseCase +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import kotlin.test.assertIs + +@OptIn(ExperimentalCoroutinesApi::class) +class OnlineDataRefreshE2ETest { + + private fun createFeatureFlags(isV5MetadataAvailable: Boolean) = FeatureFlagsModel( + privacyPolicyUrl = null, + termsAndConditionsUrl = null, + isPreviewPasswordAvailable = true, + areFoldersAvailable = true, + areTagsAvailable = true, + isTotpAvailable = true, + isRbacAvailable = true, + isPasswordExpiryAvailable = true, + arePasswordPoliciesAvailable = true, + canUpdatePasswordPolicies = true, + isV5MetadataAvailable = isV5MetadataAvailable, + ) + + @Test + fun when_network_is_active_full_data_refresh_fetches_all_domains_and_reports_progress() = + runTest { + val mockFoldersInteractor = mock() + val mockResourcesInteractor = mock() + val mockGroupsInteractor = mock() + val mockUsersInteractor = mock() + val mockResourceTypesInteractor = mock() + val mockMetadataKeysInteractor = mock() + val mockMetadataPrivateKeysInteractor = mock() + val mockMetadataSessionKeysInteractor = mock() + val mockMetadataTypesSettingsInteractor = mock() + val mockMetadataKeysSettingsInteractor = mock() + val mockFeatureFlagsUseCase = mock() + val mockIdlingResource = mock() + val mockSnapshot = mock() + + // Прапорці: V5 metadata доступна + val featureFlags = createFeatureFlags(isV5MetadataAvailable = true) + whenever(mockFeatureFlagsUseCase.execute(Unit)).thenReturn( + GetFeatureFlagsUseCase.Output(featureFlags), + ) + + whenever(mockMetadataTypesSettingsInteractor.fetchAndSaveMetadataTypesSettings()) + .thenReturn(MetadataTypesSettingsInteractor.Output.Success) + whenever(mockMetadataKeysSettingsInteractor.fetchAndSaveMetadataKeysSettings()) + .thenReturn(MetadataKeysSettingsInteractor.Output.Success) + whenever(mockMetadataKeysInteractor.fetchAndSaveMetadataKeys()) + .thenReturn(MetadataKeysInteractor.Output.Success) + whenever(mockMetadataSessionKeysInteractor.fetchMetadataSessionKeys()) + .thenReturn(MetadataSessionKeysInteractor.Output.Success) + whenever(mockMetadataSessionKeysInteractor.saveMetadataSessionKeysCache()) + .thenReturn(MetadataSessionKeysInteractor.Output.Success) + whenever(mockResourceTypesInteractor.fetchAndSaveResourceTypes()) + .thenReturn(ResourceTypesInteractor.Output.Success) + whenever(mockUsersInteractor.fetchAndSaveUsers()) + .thenReturn(UsersInteractor.Output.Success) + whenever(mockGroupsInteractor.fetchAndSaveGroups()) + .thenReturn(GroupsInteractor.Output.Success) + + whenever(mockFoldersInteractor.fetchAndSaveFolders(any())).thenReturn( + FoldersInteractor.Output.Success, + ) + whenever(mockResourcesInteractor.fetchAndSaveResources(any())).thenReturn( + ResourceInteractor.Output.Success, + ) + + val progressPoints = mutableListOf() + val trackerFactory = RefreshProgressTrackerFactory() + + val interactor = HomeDataInteractor( + foldersInteractor = mockFoldersInteractor, + resourcesInteractor = mockResourcesInteractor, + groupsInteractor = mockGroupsInteractor, + usersInteractor = mockUsersInteractor, + resourceTypesInteractor = mockResourceTypesInteractor, + metadataKeysInteractor = mockMetadataKeysInteractor, + metadataPrivateKeysInteractor = mockMetadataPrivateKeysInteractor, + metadataSessionKeysInteractor = mockMetadataSessionKeysInteractor, + metadataTypesSettingsInteractor = mockMetadataTypesSettingsInteractor, + metadataKeysSettingsInteractor = mockMetadataKeysSettingsInteractor, + featureFlagsUseCase = mockFeatureFlagsUseCase, + resourcesFullRefreshIdlingResource = mockIdlingResource, + resourcesSnapshot = mockSnapshot, + refreshProgressTrackerFactory = trackerFactory, + ) + + val result = interactor.refreshAllHomeScreenData( + onProgress = { progressPoints.add(it) }, + ) + + // Перевіряємо успішність результату + assertIs(result) + assertThat(result.authenticationState).isEqualTo(AuthenticationState.Authenticated) + + // Перевіряємо, що снапшот та IdlingResource були коректно задіяні + verify(mockSnapshot).populateForCurrentAccount() + verify(mockSnapshot).clear() + verify(mockIdlingResource).setIdle(false) + verify(mockIdlingResource).setIdle(true) + + // Перевіряємо прогрес + assertThat(progressPoints).isNotEmpty() + assertThat(progressPoints.last()).isEqualTo(1.0f) + } + + @Test + fun when_feature_flags_have_v5_metadata_disabled_metadata_steps_are_safely_skipped() = + runTest { + val mockFoldersInteractor = mock() + val mockResourcesInteractor = mock() + val mockGroupsInteractor = mock() + val mockUsersInteractor = mock() + val mockResourceTypesInteractor = mock() + val mockMetadataKeysInteractor = mock() + val mockMetadataPrivateKeysInteractor = mock() + val mockMetadataSessionKeysInteractor = mock() + val mockMetadataTypesSettingsInteractor = mock() + val mockMetadataKeysSettingsInteractor = mock() + val mockFeatureFlagsUseCase = mock() + val mockIdlingResource = mock() + val mockSnapshot = mock() + + // V5 metadata вимкнена + val featureFlags = createFeatureFlags(isV5MetadataAvailable = false) + whenever(mockFeatureFlagsUseCase.execute(Unit)).thenReturn( + GetFeatureFlagsUseCase.Output(featureFlags), + ) + + whenever(mockResourceTypesInteractor.fetchAndSaveResourceTypes()) + .thenReturn(ResourceTypesInteractor.Output.Success) + whenever(mockUsersInteractor.fetchAndSaveUsers()) + .thenReturn(UsersInteractor.Output.Success) + whenever(mockGroupsInteractor.fetchAndSaveGroups()) + .thenReturn(GroupsInteractor.Output.Success) + whenever(mockFoldersInteractor.fetchAndSaveFolders(any())).thenReturn( + FoldersInteractor.Output.Success, + ) + whenever(mockResourcesInteractor.fetchAndSaveResources(any())).thenReturn( + ResourceInteractor.Output.Success, + ) + + val trackerFactory = RefreshProgressTrackerFactory() + val progressPoints = mutableListOf() + + val interactor = HomeDataInteractor( + foldersInteractor = mockFoldersInteractor, + resourcesInteractor = mockResourcesInteractor, + groupsInteractor = mockGroupsInteractor, + usersInteractor = mockUsersInteractor, + resourceTypesInteractor = mockResourceTypesInteractor, + metadataKeysInteractor = mockMetadataKeysInteractor, + metadataPrivateKeysInteractor = mockMetadataPrivateKeysInteractor, + metadataSessionKeysInteractor = mockMetadataSessionKeysInteractor, + metadataTypesSettingsInteractor = mockMetadataTypesSettingsInteractor, + metadataKeysSettingsInteractor = mockMetadataKeysSettingsInteractor, + featureFlagsUseCase = mockFeatureFlagsUseCase, + resourcesFullRefreshIdlingResource = mockIdlingResource, + resourcesSnapshot = mockSnapshot, + refreshProgressTrackerFactory = trackerFactory, + ) + + val result = interactor.refreshAllHomeScreenData( + onProgress = { progressPoints.add(it) }, + ) + + assertIs(result) + assertThat(progressPoints.last()).isEqualTo(1.0f) + } + + @Test + fun when_a_domain_interactor_reports_authentication_expired_full_refresh_fails_with_expired_state() = + runTest { + val mockFoldersInteractor = mock() + val mockResourcesInteractor = mock() + val mockGroupsInteractor = mock() + val mockUsersInteractor = mock() + val mockResourceTypesInteractor = mock() + val mockMetadataKeysInteractor = mock() + val mockMetadataPrivateKeysInteractor = mock() + val mockMetadataSessionKeysInteractor = mock() + val mockMetadataTypesSettingsInteractor = mock() + val mockMetadataKeysSettingsInteractor = mock() + val mockFeatureFlagsUseCase = mock() + val mockIdlingResource = mock() + val mockSnapshot = mock() + + val featureFlags = createFeatureFlags(isV5MetadataAvailable = false) + whenever(mockFeatureFlagsUseCase.execute(Unit)).thenReturn( + GetFeatureFlagsUseCase.Output(featureFlags), + ) + + // Симулюємо закінчення терміну дії токена сесії під час оновлення ресурсів + val unauthenticatedSession = AuthenticationState.Unauthenticated( + AuthenticationState.Unauthenticated.Reason.Session, + ) + + whenever(mockResourceTypesInteractor.fetchAndSaveResourceTypes()) + .thenReturn(ResourceTypesInteractor.Output.Success) + whenever(mockUsersInteractor.fetchAndSaveUsers()) + .thenReturn(UsersInteractor.Output.Success) + whenever(mockGroupsInteractor.fetchAndSaveGroups()) + .thenReturn(GroupsInteractor.Output.Success) + whenever(mockFoldersInteractor.fetchAndSaveFolders(any())) + .thenReturn(FoldersInteractor.Output.Success) + whenever(mockResourcesInteractor.fetchAndSaveResources(any())) + .thenReturn(ResourceInteractor.Output.Failure(unauthenticatedSession)) + + val trackerFactory = RefreshProgressTrackerFactory() + + val interactor = HomeDataInteractor( + foldersInteractor = mockFoldersInteractor, + resourcesInteractor = mockResourcesInteractor, + groupsInteractor = mockGroupsInteractor, + usersInteractor = mockUsersInteractor, + resourceTypesInteractor = mockResourceTypesInteractor, + metadataKeysInteractor = mockMetadataKeysInteractor, + metadataPrivateKeysInteractor = mockMetadataPrivateKeysInteractor, + metadataSessionKeysInteractor = mockMetadataSessionKeysInteractor, + metadataTypesSettingsInteractor = mockMetadataTypesSettingsInteractor, + metadataKeysSettingsInteractor = mockMetadataKeysSettingsInteractor, + featureFlagsUseCase = mockFeatureFlagsUseCase, + resourcesFullRefreshIdlingResource = mockIdlingResource, + resourcesSnapshot = mockSnapshot, + refreshProgressTrackerFactory = trackerFactory, + ) + + val result = interactor.refreshAllHomeScreenData() + + assertIs(result) + val authState = result.authenticationState + assertIs(authState) + assertThat(authState.reason).isEqualTo(AuthenticationState.Unauthenticated.Reason.Session) + } + + @Test + fun refresh_progress_tracker_computes_fractional_and_step_progress_accurately() = + runTest { + val progressValues = mutableListOf() + val tracker = RefreshProgressTracker(totalSteps = 4) { progressValues.add(it) } + + // Крок 1: завершено + tracker.onStepCompleted() + assertThat(progressValues.last()).isEqualTo(0.25f) + + // Крок 2: завантаження сторінок (1 з 2) -> (1 + 0.5) / 4 = 0.375 + tracker.onStepPageDownloaded(downloadedPages = 1, totalPages = 2) + assertThat(progressValues.last()).isEqualTo(0.375f) + + // Крок 2: завершено повністю -> 2 / 4 = 0.5 + tracker.onStepCompleted() + assertThat(progressValues.last()).isEqualTo(0.5f) + + // Кроки 3 і 4: пропущено (наприклад, V5 метадані вимкнені) -> (2 + 2) / 4 = 1.0 + tracker.onStepsSkipped(count = 2) + assertThat(progressValues.last()).isEqualTo(1.0f) + } +} diff --git a/app/src/test/java/net/svaroh/passly/e2e/ResourceVaultManagementE2ETest.kt b/app/src/test/java/net/svaroh/passly/e2e/ResourceVaultManagementE2ETest.kt new file mode 100644 index 000000000..646bd7884 --- /dev/null +++ b/app/src/test/java/net/svaroh/passly/e2e/ResourceVaultManagementE2ETest.kt @@ -0,0 +1,350 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.e2e + +import app.cash.turbine.test +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import net.svaroh.passly.common.coroutinetimer.TimerFactory +import net.svaroh.passly.common.datarefresh.DataRefreshTrackingFlow +import net.svaroh.passly.commontest.TestCoroutineLaunchContext +import net.svaroh.passly.core.idlingresource.ResourceDetailActionIdlingResource +import net.svaroh.passly.core.otpcore.TotpParametersProvider +import net.svaroh.passly.core.passwordgenerator.PasswordGenerator +import net.svaroh.passly.core.passwordgenerator.PinCodeGenerator +import net.svaroh.passly.core.passwordgenerator.SecretGenerator +import net.svaroh.passly.core.passwordgenerator.dice.Dice +import net.svaroh.passly.core.passwordgenerator.entropy.EntropyCalculator +import net.svaroh.passly.domain.folders.usecase.GetLocalFolderLocationUseCase +import net.svaroh.passly.domain.metadata.usecase.CanShareResourceUseCase +import net.svaroh.passly.domain.rbac.usecase.GetRbacRulesUseCase +import net.svaroh.passly.domain.resources.actions.ResourceCommonActionsInteractor +import net.svaroh.passly.domain.resources.actions.ResourcePropertiesActionsInteractor +import net.svaroh.passly.domain.resources.actions.SecretPropertiesActionsInteractor +import net.svaroh.passly.domain.resources.actions.SecretPropertyActionResult +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourcePermissionsUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourceTagsUseCase +import net.svaroh.passly.domain.resources.usecase.db.GetLocalResourceUseCase +import net.svaroh.passly.entity.featureflags.FeatureFlagsModel +import net.svaroh.passly.feature.resourcedetails.details.ResourceDetailsIntent +import net.svaroh.passly.feature.resourcedetails.details.ResourceDetailsSideEffect +import net.svaroh.passly.feature.resourcedetails.details.ResourceDetailsViewModel +import net.svaroh.passly.featureflags.usecase.GetFeatureFlagsUseCase +import net.svaroh.passly.mappers.ResourceFormMapper +import net.svaroh.passly.ui.MetadataJsonModel +import net.svaroh.passly.ui.PasswordGeneratorSettingsUiModel +import net.svaroh.passly.ui.PinCodeUiModel +import net.svaroh.passly.ui.RbacModel +import net.svaroh.passly.ui.RbacRuleModel +import net.svaroh.passly.ui.ResourcePermission +import net.svaroh.passly.ui.ResourceUiModel +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.koin.core.logger.Level +import org.koin.dsl.module +import org.koin.test.KoinTest +import org.koin.test.KoinTestRule +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.stub +import org.mockito.kotlin.whenever +import java.security.SecureRandom +import java.time.ZonedDateTime +import java.util.UUID +import kotlin.test.assertIs + +@OptIn(ExperimentalCoroutinesApi::class) +class ResourceVaultManagementE2ETest : KoinTest { + + private val testDispatcher = StandardTestDispatcher() + + private val mockSecretPropertiesActionsInteractor = mock() + private val mockResourcePropertiesActionsInteractor = mock() + private val mockResourceCommonActionsInteractor = mock() + + private val testVaultModule = module { + factory { (resourceModel: ResourceUiModel) -> mockSecretPropertiesActionsInteractor } + factory { (resourceModel: ResourceUiModel) -> mockResourcePropertiesActionsInteractor } + factory { (resourceModel: ResourceUiModel) -> mockResourceCommonActionsInteractor } + } + + @get:Rule + val koinTestRule = + KoinTestRule.create { + printLogger(Level.ERROR) + modules(testVaultModule) + } + + @Before + fun setUp() { + Dispatchers.setMain(testDispatcher) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun password_generator_creates_strong_passwords_matching_length_and_character_sets() = + runTest { + val coroutineLaunchContext = TestCoroutineLaunchContext() + val generator = PasswordGenerator(coroutineLaunchContext) + + // 1. Тест паролю довжиною 16 символів з великими літерами, малими літерами та цифрами + val settings16 = PasswordGeneratorSettingsUiModel( + length = 16, + maskUpper = true, + maskLower = true, + maskDigit = true, + maskParenthesis = false, + maskEmoji = false, + maskChar1 = false, + maskChar2 = false, + maskChar3 = false, + maskChar4 = false, + maskChar5 = false, + excludeLookAlikeChars = false, + ) + val codepoints16 = generator.generate(settings16) + assertThat(codepoints16).hasSize(16) + + // 2. Тест паролю довжиною 32 символи з усіма спеціальними символами + val settings32 = PasswordGeneratorSettingsUiModel( + length = 32, + maskUpper = true, + maskLower = true, + maskDigit = true, + maskParenthesis = true, + maskEmoji = false, + maskChar1 = true, + maskChar2 = true, + maskChar3 = true, + maskChar4 = true, + maskChar5 = true, + excludeLookAlikeChars = true, + ) + val codepoints32 = generator.generate(settings32) + assertThat(codepoints32).hasSize(32) + + // Перевіряємо, що виключені look-alike символи (O, 0, l, 1, |, I) + val lookAlikeValues = listOf('O'.code, '0'.code, 'l'.code, '1'.code, '|'.code, 'I'.code) + val containsLookAlike = codepoints32.any { it.value in lookAlikeValues } + assertThat(containsLookAlike).isFalse() + } + + @Test + fun pincode_generator_generates_digits_only_with_specified_lengths() { + val pinGenerator = PinCodeGenerator(SecureRandom()) + + // Генерація 4-значного PIN + val pin4 = pinGenerator.generate(4) + assertThat(pin4).hasLength(4) + assertThat(pin4.all { it.isDigit() }).isTrue() + + // Генерація 6-значного PIN + val pin6 = pinGenerator.generate(6) + assertThat(pin6).hasLength(6) + assertThat(pin6.all { it.isDigit() }).isTrue() + + // Генерація максимального 12-значного PIN + val pin12 = pinGenerator.generate(PinCodeUiModel.MAX_LENGTH) + assertThat(pin12).hasLength(PinCodeUiModel.MAX_LENGTH) + assertThat(pin12.all { it.isDigit() }).isTrue() + } + + @Test + fun secret_generator_computes_high_entropy_for_complex_passwords() = + runTest { + val coroutineLaunchContext = TestCoroutineLaunchContext() + val passwordGenerator = PasswordGenerator(coroutineLaunchContext) + val mockDice = mock() + val entropyCalculator = EntropyCalculator(mockDice, coroutineLaunchContext) + + val secretGenerator = SecretGenerator( + passwordGenerator = passwordGenerator, + passphraseGenerator = mock(), + entropyCalculator = entropyCalculator, + ) + + val complexSettings = PasswordGeneratorSettingsUiModel( + length = 24, + maskUpper = true, + maskLower = true, + maskDigit = true, + maskParenthesis = true, + maskEmoji = false, + maskChar1 = true, + maskChar2 = true, + maskChar3 = true, + maskChar4 = true, + maskChar5 = true, + excludeLookAlikeChars = false, + ) + + val result = secretGenerator.generatePassword(complexSettings) + assertIs(result) + assertThat(result.password).hasSize(24) + // Висока ентропія для 24-символьного складного паролю (> 80 біт) + assertThat(result.entropy).isGreaterThan(80.0) + } + + @Test + fun resource_details_manages_visibility_and_clipboard_actions_for_decrypted_secrets() = + runTest { + val decryptedSecret = "PasslyEnterpriseStrongSecret!2026" + mockSecretPropertiesActionsInteractor.stub { + on { providePassword() } doReturn flowOf( + SecretPropertyActionResult.Success( + SecretPropertiesActionsInteractor.SECRET_LABEL, + isSecret = true, + decryptedSecret, + ), + ) + } + + val mockGetFeatureFlagsUseCase = mock() + val mockGetLocalResourceUseCase = mock() + val mockGetLocalResourcePermissionsUseCase = mock() + val mockGetLocalResourceTagsUseCase = mock() + val mockGetLocalFolderLocation = mock() + val mockTotpParametersProvider = mock() + val mockGetRbacRulesUseCase = mock() + val mockResourceDetailActionIdlingResource = mock() + val mockCanShareResourceUseCase = mock() + val mockResourceFormMapper = mock() + val mockTimerFactory = mock() + + val featureFlags = FeatureFlagsModel( + privacyPolicyUrl = null, + termsAndConditionsUrl = null, + isPreviewPasswordAvailable = true, + areFoldersAvailable = true, + areTagsAvailable = true, + isTotpAvailable = true, + isRbacAvailable = true, + isPasswordExpiryAvailable = true, + arePasswordPoliciesAvailable = true, + canUpdatePasswordPolicies = true, + isV5MetadataAvailable = false, + ) + whenever(mockGetFeatureFlagsUseCase.execute(Unit)).thenReturn( + GetFeatureFlagsUseCase.Output(featureFlags), + ) + + whenever(mockGetRbacRulesUseCase.execute(Unit)).thenReturn( + GetRbacRulesUseCase.Output( + RbacModel( + passwordPreviewRule = RbacRuleModel.ALLOW, + passwordCopyRule = RbacRuleModel.ALLOW, + tagsUseRule = RbacRuleModel.ALLOW, + shareViewRule = RbacRuleModel.ALLOW, + foldersUseRule = RbacRuleModel.ALLOW, + ), + ), + ) + + val testResource = ResourceUiModel( + resourceId = UUID.randomUUID().toString(), + resourceTypeId = UUID.randomUUID().toString(), + slug = "password-and-description", + folderId = null, + permission = ResourcePermission.OWNER, + favouriteId = null, + modified = ZonedDateTime.now(), + expiry = null, + metadataKeyId = null, + metadataKeyType = null, + metadataJsonModel = MetadataJsonModel( + """ + { + "name": "Production Database Admin", + "username": "admin@passly.internal", + "uri": "https://db.internal" + } + """.trimIndent(), + ), + ) + + whenever(mockGetLocalResourceUseCase.execute(any())).thenReturn( + GetLocalResourceUseCase.Output(testResource), + ) + + whenever(mockTimerFactory.createInfiniteTimer(any())).thenReturn(flowOf()) + whenever(mockGetLocalResourcePermissionsUseCase.execute(any())).thenReturn( + GetLocalResourcePermissionsUseCase.Output(emptyList()), + ) + whenever(mockGetLocalResourceTagsUseCase.execute(any())).thenReturn( + GetLocalResourceTagsUseCase.Output(emptyList()), + ) + whenever(mockGetLocalFolderLocation.execute(any())).thenReturn( + GetLocalFolderLocationUseCase.Output(emptyList()), + ) + + val viewModel = ResourceDetailsViewModel( + getFeatureFlagsUseCase = mockGetFeatureFlagsUseCase, + getLocalResourceUseCase = mockGetLocalResourceUseCase, + getLocalResourcePermissionsUseCase = mockGetLocalResourcePermissionsUseCase, + getLocalResourceTagsUseCase = mockGetLocalResourceTagsUseCase, + getLocalFolderLocation = mockGetLocalFolderLocation, + totpParametersProvider = mockTotpParametersProvider, + getRbacRulesUseCase = mockGetRbacRulesUseCase, + resourceDetailActionIdlingResource = mockResourceDetailActionIdlingResource, + canShareResourceUseCase = mockCanShareResourceUseCase, + resourceFormMapper = mockResourceFormMapper, + coroutineLaunchContext = TestCoroutineLaunchContext(), + dataRefreshTrackingFlow = DataRefreshTrackingFlow(), + timerFactory = mockTimerFactory, + ) + + viewModel.onIntent(ResourceDetailsIntent.Initialize(testResource)) + + // 1. Початково пароль прихований + viewModel.viewState.drop(1).test { + // Перемикаємо видимість паролю + viewModel.onIntent(ResourceDetailsIntent.TogglePasswordVisibility) + val visibleState = awaitItem() + assertThat(visibleState.passwordData.isPasswordVisible).isTrue() + assertThat(visibleState.passwordData.password).isEqualTo(decryptedSecret) + + // Повторне натискання приховує пароль + viewModel.onIntent(ResourceDetailsIntent.TogglePasswordVisibility) + val hiddenState = awaitItem() + assertThat(hiddenState.passwordData.isPasswordVisible).isFalse() + } + + // 2. Копіювання паролю надсилає SideEffect в буфер обміну + viewModel.sideEffect.test { + viewModel.onIntent(ResourceDetailsIntent.CopyPassword) + val sideEffect = awaitItem() + assertIs(sideEffect) + assertThat(sideEffect.value).isEqualTo(decryptedSecret) + } + } +} diff --git a/changelog/6.0.10.txt b/changelog/6.0.10.txt new file mode 100644 index 000000000..a54270c2f --- /dev/null +++ b/changelog/6.0.10.txt @@ -0,0 +1,3 @@ +6.0.10 +- Fixed: Resolved CredentialProviderService$1 framework Binder stub memory leak reported by LeakCanary. +- Fixed: Added custom Shark/LeakCanary reference matchers and reflection-based binder cleanup on service onDestroy. diff --git a/changelog/6.0.11.txt b/changelog/6.0.11.txt new file mode 100644 index 000000000..c574a9de6 --- /dev/null +++ b/changelog/6.0.11.txt @@ -0,0 +1,4 @@ +6.0.11 +- Milestone M3 (sync/1): Implemented incremental delta synchronization engine (DeltaSyncStrategy, ChangesApplier, BootstrapStrategy, ManifestReconciler). +- Implemented Room database migration 30 -> 31 with SyncState persistent table. +- Added background WorkManager scheduler (SyncWorker, SyncScheduler) for periodic and immediate delta sync. diff --git a/changelog/6.0.12.txt b/changelog/6.0.12.txt new file mode 100644 index 000000000..fce0d3035 --- /dev/null +++ b/changelog/6.0.12.txt @@ -0,0 +1,4 @@ +6.0.12 +- Wired FullDataRefreshExecutor into SyncEngine to enforce offline-first fast delta synchronization when local replica data exists. +- Ensured full data refresh / bootstrap is strictly executed only when local data is completely absent. +- Eliminated prolonged blocking full refresh spinners on HomeScreen and OtpScreen during user refresh actions. diff --git a/core/database/schemas/net.svaroh.passly.database.ResourceDatabase/31.json b/core/database/schemas/net.svaroh.passly.database.ResourceDatabase/31.json new file mode 100644 index 000000000..e3a9e1257 --- /dev/null +++ b/core/database/schemas/net.svaroh.passly.database.ResourceDatabase/31.json @@ -0,0 +1,1371 @@ +{ + "formatVersion": 1, + "database": { + "version": 31, + "identityHash": "310fdacc90cc95bf1f6cf9afb7264a43", + "entities": [ + { + "tableName": "Resource", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resourceId` TEXT NOT NULL, `folderId` TEXT, `resourcePermission` TEXT NOT NULL, `resourceTypeId` TEXT NOT NULL, `favouriteId` TEXT, `modified` INTEGER NOT NULL, `expiry` INTEGER, `metadataKeyId` TEXT, `metadataKeyType` TEXT, `updateState` TEXT NOT NULL, PRIMARY KEY(`resourceId`), FOREIGN KEY(`folderId`) REFERENCES `Folder`(`folderId`) ON UPDATE NO ACTION ON DELETE SET NULL , FOREIGN KEY(`resourceTypeId`) REFERENCES `ResourceType`(`resourceTypeId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "resourceId", + "columnName": "resourceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "folderId", + "columnName": "folderId", + "affinity": "TEXT" + }, + { + "fieldPath": "resourcePermission", + "columnName": "resourcePermission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "resourceTypeId", + "columnName": "resourceTypeId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "favouriteId", + "columnName": "favouriteId", + "affinity": "TEXT" + }, + { + "fieldPath": "modified", + "columnName": "modified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "expiry", + "columnName": "expiry", + "affinity": "INTEGER" + }, + { + "fieldPath": "metadataKeyId", + "columnName": "metadataKeyId", + "affinity": "TEXT" + }, + { + "fieldPath": "metadataKeyType", + "columnName": "metadataKeyType", + "affinity": "TEXT" + }, + { + "fieldPath": "updateState", + "columnName": "updateState", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "resourceId" + ] + }, + "indices": [ + { + "name": "index_Resource_folderId", + "unique": false, + "columnNames": [ + "folderId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Resource_folderId` ON `${TABLE_NAME}` (`folderId`)" + }, + { + "name": "index_Resource_resourceTypeId", + "unique": false, + "columnNames": [ + "resourceTypeId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Resource_resourceTypeId` ON `${TABLE_NAME}` (`resourceTypeId`)" + }, + { + "name": "index_Resource_modified_resourceId", + "unique": false, + "columnNames": [ + "modified", + "resourceId" + ], + "orders": [ + "DESC", + "ASC" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Resource_modified_resourceId` ON `${TABLE_NAME}` (`modified` DESC, `resourceId` ASC)" + }, + { + "name": "index_Resource_expiry_resourceId", + "unique": false, + "columnNames": [ + "expiry", + "resourceId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Resource_expiry_resourceId` ON `${TABLE_NAME}` (`expiry`, `resourceId`)" + }, + { + "name": "index_Resource_favouriteId", + "unique": false, + "columnNames": [ + "favouriteId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Resource_favouriteId` ON `${TABLE_NAME}` (`favouriteId`)" + } + ], + "foreignKeys": [ + { + "table": "Folder", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "folderId" + ], + "referencedColumns": [ + "folderId" + ] + }, + { + "table": "ResourceType", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "resourceTypeId" + ], + "referencedColumns": [ + "resourceTypeId" + ] + } + ] + }, + { + "tableName": "Folder", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `name` TEXT NOT NULL COLLATE NOCASE, `permission` TEXT NOT NULL, `parentId` TEXT, `isShared` INTEGER NOT NULL, `modified` INTEGER NOT NULL, `updateState` TEXT NOT NULL, PRIMARY KEY(`folderId`))", + "fields": [ + { + "fieldPath": "folderId", + "columnName": "folderId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "permission", + "columnName": "permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentId", + "columnName": "parentId", + "affinity": "TEXT" + }, + { + "fieldPath": "isShared", + "columnName": "isShared", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "modified", + "columnName": "modified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updateState", + "columnName": "updateState", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "folderId" + ] + }, + "indices": [ + { + "name": "index_Folder_parentId", + "unique": false, + "columnNames": [ + "parentId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Folder_parentId` ON `${TABLE_NAME}` (`parentId`)" + }, + { + "name": "index_Folder_modified_folderId", + "unique": false, + "columnNames": [ + "modified", + "folderId" + ], + "orders": [ + "DESC", + "ASC" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Folder_modified_folderId` ON `${TABLE_NAME}` (`modified` DESC, `folderId` ASC)" + } + ] + }, + { + "tableName": "ResourceType", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resourceTypeId` TEXT NOT NULL, `name` TEXT NOT NULL, `slug` TEXT NOT NULL, `deleted` INTEGER, PRIMARY KEY(`resourceTypeId`))", + "fields": [ + { + "fieldPath": "resourceTypeId", + "columnName": "resourceTypeId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "slug", + "columnName": "slug", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "deleted", + "columnName": "deleted", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "resourceTypeId" + ] + } + }, + { + "tableName": "Tag", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `slug` TEXT NOT NULL, `isShared` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "slug", + "columnName": "slug", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isShared", + "columnName": "isShared", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "ResourceAndTagsCrossRef", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tagId` TEXT NOT NULL, `resourceId` TEXT NOT NULL, PRIMARY KEY(`tagId`, `resourceId`), FOREIGN KEY(`tagId`) REFERENCES `Tag`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`resourceId`) REFERENCES `Resource`(`resourceId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "tagId", + "columnName": "tagId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "resourceId", + "columnName": "resourceId", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "tagId", + "resourceId" + ] + }, + "indices": [ + { + "name": "index_ResourceAndTagsCrossRef_resourceId", + "unique": false, + "columnNames": [ + "resourceId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ResourceAndTagsCrossRef_resourceId` ON `${TABLE_NAME}` (`resourceId`)" + } + ], + "foreignKeys": [ + { + "table": "Tag", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "tagId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Resource", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "resourceId" + ], + "referencedColumns": [ + "resourceId" + ] + } + ] + }, + { + "tableName": "UsersGroup", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`groupId` TEXT NOT NULL, `name` TEXT NOT NULL COLLATE NOCASE, `updateState` TEXT NOT NULL, PRIMARY KEY(`groupId`))", + "fields": [ + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "updateState", + "columnName": "updateState", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "groupId" + ] + } + }, + { + "tableName": "ResourceAndGroupsCrossRef", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resourceId` TEXT NOT NULL, `groupId` TEXT NOT NULL, `permission` TEXT NOT NULL, `permissionId` TEXT NOT NULL, PRIMARY KEY(`resourceId`, `groupId`), FOREIGN KEY(`resourceId`) REFERENCES `Resource`(`resourceId`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`groupId`) REFERENCES `UsersGroup`(`groupId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "resourceId", + "columnName": "resourceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "permission", + "columnName": "permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "permissionId", + "columnName": "permissionId", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "resourceId", + "groupId" + ] + }, + "indices": [ + { + "name": "index_ResourceAndGroupsCrossRef_groupId", + "unique": false, + "columnNames": [ + "groupId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ResourceAndGroupsCrossRef_groupId` ON `${TABLE_NAME}` (`groupId`)" + } + ], + "foreignKeys": [ + { + "table": "Resource", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "resourceId" + ], + "referencedColumns": [ + "resourceId" + ] + }, + { + "table": "UsersGroup", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "groupId" + ], + "referencedColumns": [ + "groupId" + ] + } + ] + }, + { + "tableName": "User", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userName` TEXT NOT NULL, `disabled` INTEGER NOT NULL, `updateState` TEXT NOT NULL, `firstName` TEXT, `lastName` TEXT, `avatarUrl` TEXT, `userKeyId` TEXT NOT NULL, `armoredKey` TEXT NOT NULL, `bits` INTEGER NOT NULL, `uid` TEXT, `keyId` TEXT NOT NULL, `fingerprint` TEXT NOT NULL, `type` TEXT, `expires` INTEGER, `created` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userName", + "columnName": "userName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disabled", + "columnName": "disabled", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updateState", + "columnName": "updateState", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profile.firstName", + "columnName": "firstName", + "affinity": "TEXT" + }, + { + "fieldPath": "profile.lastName", + "columnName": "lastName", + "affinity": "TEXT" + }, + { + "fieldPath": "profile.avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "gpgKey.id", + "columnName": "userKeyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gpgKey.armoredKey", + "columnName": "armoredKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gpgKey.bits", + "columnName": "bits", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "gpgKey.uid", + "columnName": "uid", + "affinity": "TEXT" + }, + { + "fieldPath": "gpgKey.keyId", + "columnName": "keyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gpgKey.fingerprint", + "columnName": "fingerprint", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gpgKey.type", + "columnName": "type", + "affinity": "TEXT" + }, + { + "fieldPath": "gpgKey.expires", + "columnName": "expires", + "affinity": "INTEGER" + }, + { + "fieldPath": "gpgKey.created", + "columnName": "created", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "UsersAndGroupCrossRef", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userId` TEXT NOT NULL, `groupId` TEXT NOT NULL, PRIMARY KEY(`userId`, `groupId`), FOREIGN KEY(`userId`) REFERENCES `User`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`groupId`) REFERENCES `UsersGroup`(`groupId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "userId", + "columnName": "userId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "userId", + "groupId" + ] + }, + "indices": [ + { + "name": "index_UsersAndGroupCrossRef_groupId", + "unique": false, + "columnNames": [ + "groupId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UsersAndGroupCrossRef_groupId` ON `${TABLE_NAME}` (`groupId`)" + } + ], + "foreignKeys": [ + { + "table": "User", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UsersGroup", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "groupId" + ], + "referencedColumns": [ + "groupId" + ] + } + ] + }, + { + "tableName": "ResourceAndUsersCrossRef", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resourceId` TEXT NOT NULL, `userId` TEXT NOT NULL, `permission` TEXT NOT NULL, `permissionId` TEXT NOT NULL, PRIMARY KEY(`resourceId`, `userId`), FOREIGN KEY(`resourceId`) REFERENCES `Resource`(`resourceId`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`userId`) REFERENCES `User`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "resourceId", + "columnName": "resourceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "userId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "permission", + "columnName": "permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "permissionId", + "columnName": "permissionId", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "resourceId", + "userId" + ] + }, + "indices": [ + { + "name": "index_ResourceAndUsersCrossRef_userId", + "unique": false, + "columnNames": [ + "userId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ResourceAndUsersCrossRef_userId` ON `${TABLE_NAME}` (`userId`)" + } + ], + "foreignKeys": [ + { + "table": "Resource", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "resourceId" + ], + "referencedColumns": [ + "resourceId" + ] + }, + { + "table": "User", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FolderAndUsersCrossRef", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `userId` TEXT NOT NULL, `permission` TEXT NOT NULL, `permissionId` TEXT NOT NULL, PRIMARY KEY(`userId`, `folderId`), FOREIGN KEY(`folderId`) REFERENCES `Folder`(`folderId`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`userId`) REFERENCES `User`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "folderId", + "columnName": "folderId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "userId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "permission", + "columnName": "permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "permissionId", + "columnName": "permissionId", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "userId", + "folderId" + ] + }, + "indices": [ + { + "name": "index_FolderAndUsersCrossRef_folderId", + "unique": false, + "columnNames": [ + "folderId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FolderAndUsersCrossRef_folderId` ON `${TABLE_NAME}` (`folderId`)" + } + ], + "foreignKeys": [ + { + "table": "Folder", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "folderId" + ], + "referencedColumns": [ + "folderId" + ] + }, + { + "table": "User", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FolderAndGroupsCrossRef", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `groupId` TEXT NOT NULL, `permission` TEXT NOT NULL, `permissionId` TEXT NOT NULL, PRIMARY KEY(`folderId`, `groupId`), FOREIGN KEY(`folderId`) REFERENCES `Folder`(`folderId`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`groupId`) REFERENCES `UsersGroup`(`groupId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "folderId", + "columnName": "folderId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "permission", + "columnName": "permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "permissionId", + "columnName": "permissionId", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "folderId", + "groupId" + ] + }, + "indices": [ + { + "name": "index_FolderAndGroupsCrossRef_groupId", + "unique": false, + "columnNames": [ + "groupId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FolderAndGroupsCrossRef_groupId` ON `${TABLE_NAME}` (`groupId`)" + } + ], + "foreignKeys": [ + { + "table": "Folder", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "folderId" + ], + "referencedColumns": [ + "folderId" + ] + }, + { + "table": "UsersGroup", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "groupId" + ], + "referencedColumns": [ + "groupId" + ] + } + ] + }, + { + "tableName": "ResourceMetadata", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resourceId` TEXT NOT NULL, `metadataJson` TEXT NOT NULL, `name` TEXT NOT NULL, `username` TEXT, `description` TEXT, `customFieldsKeys` TEXT, PRIMARY KEY(`resourceId`), FOREIGN KEY(`resourceId`) REFERENCES `Resource`(`resourceId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "resourceId", + "columnName": "resourceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "metadataJson", + "columnName": "metadataJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "username", + "columnName": "username", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "customFieldsKeys", + "columnName": "customFieldsKeys", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "resourceId" + ] + }, + "foreignKeys": [ + { + "table": "Resource", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "resourceId" + ], + "referencedColumns": [ + "resourceId" + ] + } + ] + }, + { + "tableName": "ResourceMetadataFts", + "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, `username` TEXT, `customFieldsKeys` TEXT, tokenize=unicode61, content=`ResourceMetadata`)", + "fields": [ + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "username", + "columnName": "username", + "affinity": "TEXT" + }, + { + "fieldPath": "customFieldsKeys", + "columnName": "customFieldsKeys", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [] + }, + "ftsVersion": "FTS4", + "ftsOptions": { + "tokenizer": "unicode61", + "tokenizerArgs": [], + "contentTable": "ResourceMetadata", + "languageIdColumnName": "", + "matchInfo": "FTS4", + "notIndexedColumns": [], + "prefixSizes": [], + "preferredOrder": "ASC" + }, + "contentSyncTriggers": [ + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_ResourceMetadataFts_BEFORE_UPDATE BEFORE UPDATE ON `ResourceMetadata` BEGIN DELETE FROM `ResourceMetadataFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_ResourceMetadataFts_BEFORE_DELETE BEFORE DELETE ON `ResourceMetadata` BEGIN DELETE FROM `ResourceMetadataFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_ResourceMetadataFts_AFTER_UPDATE AFTER UPDATE ON `ResourceMetadata` BEGIN INSERT INTO `ResourceMetadataFts`(`docid`, `name`, `username`, `customFieldsKeys`) VALUES (NEW.`rowid`, NEW.`name`, NEW.`username`, NEW.`customFieldsKeys`); END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_ResourceMetadataFts_AFTER_INSERT AFTER INSERT ON `ResourceMetadata` BEGIN INSERT INTO `ResourceMetadataFts`(`docid`, `name`, `username`, `customFieldsKeys`) VALUES (NEW.`rowid`, NEW.`name`, NEW.`username`, NEW.`customFieldsKeys`); END" + ] + }, + { + "tableName": "ResourceUri", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resourceId` TEXT NOT NULL, `uri` TEXT NOT NULL, FOREIGN KEY(`resourceId`) REFERENCES `Resource`(`resourceId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "resourceId", + "columnName": "resourceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uri", + "columnName": "uri", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ResourceUri_resourceId", + "unique": false, + "columnNames": [ + "resourceId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ResourceUri_resourceId` ON `${TABLE_NAME}` (`resourceId`)" + } + ], + "foreignKeys": [ + { + "table": "Resource", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "resourceId" + ], + "referencedColumns": [ + "resourceId" + ] + } + ] + }, + { + "tableName": "ResourceUriFts", + "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`uri` TEXT NOT NULL, tokenize=unicode61, content=`ResourceUri`)", + "fields": [ + { + "fieldPath": "uri", + "columnName": "uri", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [] + }, + "ftsVersion": "FTS4", + "ftsOptions": { + "tokenizer": "unicode61", + "tokenizerArgs": [], + "contentTable": "ResourceUri", + "languageIdColumnName": "", + "matchInfo": "FTS4", + "notIndexedColumns": [], + "prefixSizes": [], + "preferredOrder": "ASC" + }, + "contentSyncTriggers": [ + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_ResourceUriFts_BEFORE_UPDATE BEFORE UPDATE ON `ResourceUri` BEGIN DELETE FROM `ResourceUriFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_ResourceUriFts_BEFORE_DELETE BEFORE DELETE ON `ResourceUri` BEGIN DELETE FROM `ResourceUriFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_ResourceUriFts_AFTER_UPDATE AFTER UPDATE ON `ResourceUri` BEGIN INSERT INTO `ResourceUriFts`(`docid`, `uri`) VALUES (NEW.`rowid`, NEW.`uri`); END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_ResourceUriFts_AFTER_INSERT AFTER INSERT ON `ResourceUri` BEGIN INSERT INTO `ResourceUriFts`(`docid`, `uri`) VALUES (NEW.`rowid`, NEW.`uri`); END" + ] + }, + { + "tableName": "TagFts", + "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`slug` TEXT NOT NULL, tokenize=unicode61, content=`Tag`)", + "fields": [ + { + "fieldPath": "slug", + "columnName": "slug", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [] + }, + "ftsVersion": "FTS4", + "ftsOptions": { + "tokenizer": "unicode61", + "tokenizerArgs": [], + "contentTable": "Tag", + "languageIdColumnName": "", + "matchInfo": "FTS4", + "notIndexedColumns": [], + "prefixSizes": [], + "preferredOrder": "ASC" + }, + "contentSyncTriggers": [ + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_TagFts_BEFORE_UPDATE BEFORE UPDATE ON `Tag` BEGIN DELETE FROM `TagFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_TagFts_BEFORE_DELETE BEFORE DELETE ON `Tag` BEGIN DELETE FROM `TagFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_TagFts_AFTER_UPDATE AFTER UPDATE ON `Tag` BEGIN INSERT INTO `TagFts`(`docid`, `slug`) VALUES (NEW.`rowid`, NEW.`slug`); END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_TagFts_AFTER_INSERT AFTER INSERT ON `Tag` BEGIN INSERT INTO `TagFts`(`docid`, `slug`) VALUES (NEW.`rowid`, NEW.`slug`); END" + ] + }, + { + "tableName": "FolderFts", + "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, tokenize=unicode61, content=`Folder`)", + "fields": [ + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [] + }, + "ftsVersion": "FTS4", + "ftsOptions": { + "tokenizer": "unicode61", + "tokenizerArgs": [], + "contentTable": "Folder", + "languageIdColumnName": "", + "matchInfo": "FTS4", + "notIndexedColumns": [], + "prefixSizes": [], + "preferredOrder": "ASC" + }, + "contentSyncTriggers": [ + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_FolderFts_BEFORE_UPDATE BEFORE UPDATE ON `Folder` BEGIN DELETE FROM `FolderFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_FolderFts_BEFORE_DELETE BEFORE DELETE ON `Folder` BEGIN DELETE FROM `FolderFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_FolderFts_AFTER_UPDATE AFTER UPDATE ON `Folder` BEGIN INSERT INTO `FolderFts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_FolderFts_AFTER_INSERT AFTER INSERT ON `Folder` BEGIN INSERT INTO `FolderFts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END" + ] + }, + { + "tableName": "UsersGroupFts", + "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, tokenize=unicode61, content=`UsersGroup`)", + "fields": [ + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [] + }, + "ftsVersion": "FTS4", + "ftsOptions": { + "tokenizer": "unicode61", + "tokenizerArgs": [], + "contentTable": "UsersGroup", + "languageIdColumnName": "", + "matchInfo": "FTS4", + "notIndexedColumns": [], + "prefixSizes": [], + "preferredOrder": "ASC" + }, + "contentSyncTriggers": [ + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_UsersGroupFts_BEFORE_UPDATE BEFORE UPDATE ON `UsersGroup` BEGIN DELETE FROM `UsersGroupFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_UsersGroupFts_BEFORE_DELETE BEFORE DELETE ON `UsersGroup` BEGIN DELETE FROM `UsersGroupFts` WHERE `docid`=OLD.`rowid`; END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_UsersGroupFts_AFTER_UPDATE AFTER UPDATE ON `UsersGroup` BEGIN INSERT INTO `UsersGroupFts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END", + "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_UsersGroupFts_AFTER_INSERT AFTER INSERT ON `UsersGroup` BEGIN INSERT INTO `UsersGroupFts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END" + ] + }, + { + "tableName": "MetadataKey", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `fingerprint` TEXT, `armoredKey` TEXT NOT NULL, `modified` INTEGER NOT NULL, `expired` INTEGER, `deleted` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "fingerprint", + "columnName": "fingerprint", + "affinity": "TEXT" + }, + { + "fieldPath": "armoredKey", + "columnName": "armoredKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "modified", + "columnName": "modified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "expired", + "columnName": "expired", + "affinity": "INTEGER" + }, + { + "fieldPath": "deleted", + "columnName": "deleted", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "MetadataPrivateKey", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `pgpMessage` TEXT NOT NULL, `metadataKeyId` TEXT NOT NULL, `userId` TEXT, `data` TEXT NOT NULL, `passphrase` TEXT NOT NULL, `modified` INTEGER NOT NULL, `modifiedBy` TEXT, `created` INTEGER NOT NULL, `createdBy` TEXT, `domain` TEXT NOT NULL, `fingerprint` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`metadataKeyId`) REFERENCES `MetadataKey`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pgpMessage", + "columnName": "pgpMessage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "metadataKeyId", + "columnName": "metadataKeyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "userId", + "affinity": "TEXT" + }, + { + "fieldPath": "data", + "columnName": "data", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "passphrase", + "columnName": "passphrase", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "modified", + "columnName": "modified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "modifiedBy", + "columnName": "modifiedBy", + "affinity": "TEXT" + }, + { + "fieldPath": "created", + "columnName": "created", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdBy", + "columnName": "createdBy", + "affinity": "TEXT" + }, + { + "fieldPath": "domain", + "columnName": "domain", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "fingerprint", + "columnName": "fingerprint", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_MetadataPrivateKey_metadataKeyId", + "unique": false, + "columnNames": [ + "metadataKeyId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MetadataPrivateKey_metadataKeyId` ON `${TABLE_NAME}` (`metadataKeyId`)" + } + ], + "foreignKeys": [ + { + "table": "MetadataKey", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "metadataKeyId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Secret", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resourceId` TEXT NOT NULL, `secretId` TEXT, `armoredData` TEXT NOT NULL, `modified` INTEGER, `fetchedAt` INTEGER NOT NULL, PRIMARY KEY(`resourceId`), FOREIGN KEY(`resourceId`) REFERENCES `Resource`(`resourceId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "resourceId", + "columnName": "resourceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secretId", + "columnName": "secretId", + "affinity": "TEXT" + }, + { + "fieldPath": "armoredData", + "columnName": "armoredData", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "modified", + "columnName": "modified", + "affinity": "INTEGER" + }, + { + "fieldPath": "fetchedAt", + "columnName": "fetchedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "resourceId" + ] + }, + "foreignKeys": [ + { + "table": "Resource", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "resourceId" + ], + "referencedColumns": [ + "resourceId" + ] + } + ] + }, + { + "tableName": "SyncState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `cursor` INTEGER, `epoch` TEXT, `lastSyncTimestamp` INTEGER, `lastReconcileTimestamp` INTEGER, `failureCount` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cursor", + "columnName": "cursor", + "affinity": "INTEGER" + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "TEXT" + }, + { + "fieldPath": "lastSyncTimestamp", + "columnName": "lastSyncTimestamp", + "affinity": "INTEGER" + }, + { + "fieldPath": "lastReconcileTimestamp", + "columnName": "lastReconcileTimestamp", + "affinity": "INTEGER" + }, + { + "fieldPath": "failureCount", + "columnName": "failureCount", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '310fdacc90cc95bf1f6cf9afb7264a43')" + ] + } +} \ No newline at end of file diff --git a/core/database/src/androidTest/java/com/passbolt/mobile/android/database/DatabaseMigrationsTest.kt b/core/database/src/androidTest/java/com/passbolt/mobile/android/database/DatabaseMigrationsTest.kt index 0f6081c25..db61191b3 100644 --- a/core/database/src/androidTest/java/com/passbolt/mobile/android/database/DatabaseMigrationsTest.kt +++ b/core/database/src/androidTest/java/com/passbolt/mobile/android/database/DatabaseMigrationsTest.kt @@ -49,6 +49,7 @@ import net.svaroh.passly.database.migrations.Migration26to27 import net.svaroh.passly.database.migrations.Migration27to28 import net.svaroh.passly.database.migrations.Migration28to29 import net.svaroh.passly.database.migrations.Migration29to30 +import net.svaroh.passly.database.migrations.Migration30to31 import net.svaroh.passly.database.migrations.Migration2to3 import net.svaroh.passly.database.migrations.Migration3to4 import net.svaroh.passly.database.migrations.Migration4to5 @@ -891,6 +892,7 @@ class DatabaseMigrationsTest { Migration27to28, Migration28to29, Migration29to30, + Migration30to31, ).build() .apply { openHelper.writableDatabase @@ -913,6 +915,21 @@ class DatabaseMigrationsTest { } } + @Test + fun migration30to31() { + helper + .createDatabase(TEST_DB, 30) + .apply { + close() + } + + helper + .runMigrationsAndValidate(TEST_DB, 31, true, Migration30to31) + .apply { + close() + } + } + private companion object { private const val TEST_DB = "migration-test" } diff --git a/core/database/src/main/java/com/passbolt/mobile/android/database/DatabaseProvider.kt b/core/database/src/main/java/com/passbolt/mobile/android/database/DatabaseProvider.kt index 3328352fd..2b780a940 100644 --- a/core/database/src/main/java/com/passbolt/mobile/android/database/DatabaseProvider.kt +++ b/core/database/src/main/java/com/passbolt/mobile/android/database/DatabaseProvider.kt @@ -27,6 +27,7 @@ import net.svaroh.passly.database.migrations.Migration26to27 import net.svaroh.passly.database.migrations.Migration27to28 import net.svaroh.passly.database.migrations.Migration28to29 import net.svaroh.passly.database.migrations.Migration29to30 +import net.svaroh.passly.database.migrations.Migration30to31 import net.svaroh.passly.database.migrations.Migration2to3 import net.svaroh.passly.database.migrations.Migration3to4 import net.svaroh.passly.database.migrations.Migration4to5 @@ -112,6 +113,7 @@ class DatabaseProvider( Migration27to28, Migration28to29, Migration29to30, + Migration30to31, ).openHelperFactory(factory) .build() } catch (e: Exception) { diff --git a/core/database/src/main/java/com/passbolt/mobile/android/database/ResourceDatabase.kt b/core/database/src/main/java/com/passbolt/mobile/android/database/ResourceDatabase.kt index 3cb3b6f49..521968f2e 100644 --- a/core/database/src/main/java/com/passbolt/mobile/android/database/ResourceDatabase.kt +++ b/core/database/src/main/java/com/passbolt/mobile/android/database/ResourceDatabase.kt @@ -20,6 +20,7 @@ import net.svaroh.passly.database.impl.resources.PaginatedResourcesDao import net.svaroh.passly.database.impl.resources.ResourcesDao import net.svaroh.passly.database.impl.resourcetypes.ResourceTypesDao import net.svaroh.passly.database.impl.secrets.SecretsDao +import net.svaroh.passly.database.impl.sync.SyncStateDao import net.svaroh.passly.database.impl.tags.PaginatedTagsDao import net.svaroh.passly.database.impl.tags.TagsDao import net.svaroh.passly.database.impl.users.UsersDao @@ -45,6 +46,7 @@ import net.svaroh.passly.entity.resource.ResourceUriFts import net.svaroh.passly.entity.resource.Tag import net.svaroh.passly.entity.resource.TagFts import net.svaroh.passly.entity.secret.Secret +import net.svaroh.passly.entity.sync.SyncState import net.svaroh.passly.entity.user.ResourceAndUsersCrossRef import net.svaroh.passly.entity.user.User @@ -95,8 +97,9 @@ import net.svaroh.passly.entity.user.User MetadataKey::class, MetadataPrivateKey::class, Secret::class, + SyncState::class, ], - version = 30, + version = 31, ) @TypeConverters(Converters::class) abstract class ResourceDatabase : RoomDatabase() { @@ -141,4 +144,6 @@ abstract class ResourceDatabase : RoomDatabase() { abstract fun metadataPrivateKeysDao(): MetadataPrivateKeysDao abstract fun secretsDao(): SecretsDao + + abstract fun syncStateDao(): SyncStateDao } diff --git a/core/database/src/main/java/com/passbolt/mobile/android/database/impl/folders/FoldersDao.kt b/core/database/src/main/java/com/passbolt/mobile/android/database/impl/folders/FoldersDao.kt index 101213025..de87d7ff0 100644 --- a/core/database/src/main/java/com/passbolt/mobile/android/database/impl/folders/FoldersDao.kt +++ b/core/database/src/main/java/com/passbolt/mobile/android/database/impl/folders/FoldersDao.kt @@ -229,4 +229,10 @@ interface FoldersDao : BaseDao { @Transaction @Query("DELETE FROM Folder WHERE updateState = :updateState") suspend fun removeWithUpdateState(updateState: FolderUpdateState) + + @Query("DELETE FROM Folder WHERE folderId = :folderId") + suspend fun delete(folderId: String) + + @Query("DELETE FROM Folder WHERE folderId IN (:folderIds)") + suspend fun deleteAll(folderIds: List) } diff --git a/core/database/src/main/java/com/passbolt/mobile/android/database/impl/groups/GroupsDao.kt b/core/database/src/main/java/com/passbolt/mobile/android/database/impl/groups/GroupsDao.kt index c63213125..45234e0f2 100644 --- a/core/database/src/main/java/com/passbolt/mobile/android/database/impl/groups/GroupsDao.kt +++ b/core/database/src/main/java/com/passbolt/mobile/android/database/impl/groups/GroupsDao.kt @@ -66,4 +66,10 @@ interface GroupsDao : BaseDao { @Transaction @Query("SELECT * FROM UsersGroup WHERE groupId=:groupId ORDER BY name ASC") suspend fun getGroupWithUsers(groupId: String): GroupWithUsers + + @Query("DELETE FROM UsersGroup WHERE groupId = :groupId") + suspend fun delete(groupId: String) + + @Query("DELETE FROM UsersGroup WHERE groupId IN (:groupIds)") + suspend fun deleteAll(groupIds: List) } diff --git a/core/database/src/main/java/com/passbolt/mobile/android/database/impl/resources/ResourcesDao.kt b/core/database/src/main/java/com/passbolt/mobile/android/database/impl/resources/ResourcesDao.kt index a2176edf5..1356754dc 100644 --- a/core/database/src/main/java/com/passbolt/mobile/android/database/impl/resources/ResourcesDao.kt +++ b/core/database/src/main/java/com/passbolt/mobile/android/database/impl/resources/ResourcesDao.kt @@ -405,4 +405,10 @@ interface ResourcesDao : BaseDao { @Transaction @Query("DELETE FROM Resource WHERE updateState = :updateState") suspend fun removeWithUpdateState(updateState: ResourceUpdateState) + + @Query("DELETE FROM Resource WHERE resourceId = :resourceId") + suspend fun delete(resourceId: String) + + @Query("DELETE FROM Resource WHERE resourceId IN (:resourceIds)") + suspend fun deleteAll(resourceIds: List) } diff --git a/core/database/src/main/java/com/passbolt/mobile/android/database/impl/users/UsersDao.kt b/core/database/src/main/java/com/passbolt/mobile/android/database/impl/users/UsersDao.kt index 0fb1cd041..d18e6d258 100644 --- a/core/database/src/main/java/com/passbolt/mobile/android/database/impl/users/UsersDao.kt +++ b/core/database/src/main/java/com/passbolt/mobile/android/database/impl/users/UsersDao.kt @@ -44,4 +44,10 @@ interface UsersDao : BaseDao { @Query("DELETE FROM User WHERE updateState = :updateState") suspend fun removeWithUpdateState(updateState: UserUpdateState) + + @Query("DELETE FROM User WHERE id = :userId") + suspend fun delete(userId: String) + + @Query("DELETE FROM User WHERE id IN (:userIds)") + suspend fun deleteAll(userIds: List) } diff --git a/core/database/src/main/java/com/passbolt/mobile/android/database/migrations/Migration30to31.kt b/core/database/src/main/java/com/passbolt/mobile/android/database/migrations/Migration30to31.kt new file mode 100644 index 000000000..a7b58c890 --- /dev/null +++ b/core/database/src/main/java/com/passbolt/mobile/android/database/migrations/Migration30to31.kt @@ -0,0 +1,42 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.database.migrations + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +/** + * Migration 30 to 31 creates the durable `SyncState` table for incremental delta sync (sync/1 protocol). + */ +@Suppress("MagicNumber") +object Migration30to31 : Migration(30, 31) { + private const val CREATE_SYNC_STATE_TABLE = + "CREATE TABLE IF NOT EXISTS `SyncState` (" + + "`id` INTEGER NOT NULL, " + + "`cursor` INTEGER, " + + "`epoch` TEXT, " + + "`lastSyncTimestamp` INTEGER, " + + "`lastReconcileTimestamp` INTEGER, " + + "`failureCount` INTEGER NOT NULL DEFAULT 0, " + + "PRIMARY KEY(`id`))" + + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL(CREATE_SYNC_STATE_TABLE) + } +} diff --git a/core/database/src/main/java/net/svaroh/passly/database/impl/sync/SyncStateDao.kt b/core/database/src/main/java/net/svaroh/passly/database/impl/sync/SyncStateDao.kt new file mode 100644 index 000000000..39fee419d --- /dev/null +++ b/core/database/src/main/java/net/svaroh/passly/database/impl/sync/SyncStateDao.kt @@ -0,0 +1,42 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.database.impl.sync + +import androidx.room.Dao +import androidx.room.Query +import net.svaroh.passly.database.impl.base.BaseDao +import net.svaroh.passly.entity.sync.SyncState + +@Dao +interface SyncStateDao : BaseDao { + @Query("SELECT * FROM SyncState WHERE id = 1 LIMIT 1") + suspend fun getSyncState(): SyncState? + + @Query("UPDATE SyncState SET cursor = :cursor, epoch = :epoch, lastSyncTimestamp = :lastSyncTimestamp WHERE id = 1") + suspend fun updateCursor(cursor: Long, epoch: String?, lastSyncTimestamp: Long): Int + + @Query("UPDATE SyncState SET lastReconcileTimestamp = :lastReconcileTimestamp WHERE id = 1") + suspend fun updateLastReconcile(lastReconcileTimestamp: Long): Int + + @Query("UPDATE SyncState SET failureCount = :failureCount WHERE id = 1") + suspend fun updateFailureCount(failureCount: Int): Int + + @Query("DELETE FROM SyncState") + suspend fun clear() +} diff --git a/core/fulldatarefresh/build.gradle.kts b/core/fulldatarefresh/build.gradle.kts index 826665039..ecbd74fa3 100644 --- a/core/fulldatarefresh/build.gradle.kts +++ b/core/fulldatarefresh/build.gradle.kts @@ -22,6 +22,8 @@ dependencies { implementation(project(":database")) implementation(project(":coreui")) implementation(project(":notifications")) + implementation(project(":accounts-domain")) + implementation(project(":sync")) implementation(platform(libs.koin.bom)) implementation(libs.koin) @@ -30,4 +32,11 @@ dependencies { implementation(libs.androidx.lifecycle.service) testImplementation(project(":commontest")) + testImplementation(project(":navigation")) + testImplementation(project(":passphrasememorycache")) + testImplementation(libs.mockito.kotlin) + testImplementation(libs.truth) + testImplementation(libs.kotlin.coroutines.test) + testImplementation(libs.koin.test) + testImplementation(libs.koin.test.junit) } diff --git a/core/fulldatarefresh/src/main/java/com/passbolt/mobile/android/core/fulldatarefresh/FullDataRefreshExecutor.kt b/core/fulldatarefresh/src/main/java/com/passbolt/mobile/android/core/fulldatarefresh/FullDataRefreshExecutor.kt index 1041286fe..9d1d9d759 100644 --- a/core/fulldatarefresh/src/main/java/com/passbolt/mobile/android/core/fulldatarefresh/FullDataRefreshExecutor.kt +++ b/core/fulldatarefresh/src/main/java/com/passbolt/mobile/android/core/fulldatarefresh/FullDataRefreshExecutor.kt @@ -6,61 +6,80 @@ import net.svaroh.passly.common.datarefresh.DataRefreshStatus.Idle.FinishedWithF import net.svaroh.passly.common.datarefresh.DataRefreshStatus.Idle.FinishedWithSuccess import net.svaroh.passly.common.datarefresh.DataRefreshStatus.InProgress import net.svaroh.passly.common.datarefresh.DataRefreshTrackingFlow +import net.svaroh.passly.common.usecase.UserIdInput import net.svaroh.passly.core.fulldatarefresh.HomeDataInteractor.Output.Failure import net.svaroh.passly.core.fulldatarefresh.HomeDataInteractor.Output.Success import net.svaroh.passly.core.mvp.coroutinecontext.CoroutineLaunchContext +import net.svaroh.passly.core.sync.SyncEngine +import net.svaroh.passly.core.sync.SyncResult +import net.svaroh.passly.core.sync.SyncTrigger +import net.svaroh.passly.database.usecase.HasLocalReplicaUseCase +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase import net.svaroh.passly.feature.authentication.session.runAuthenticatedOperation import timber.log.Timber import kotlin.time.Duration.Companion.milliseconds /** - * Passbolt - Open source password manager for teams - * Copyright (c) 2021 Passbolt SA - * - * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General - * Public License (AGPL) as published by the Free Software Foundation version 3. - * - * The name "Passbolt" is a registered trademark of Passbolt SA, and Passbolt SA hereby declines to grant a trademark - * license to "Passbolt" pursuant to the GNU Affero General Public License version 3 Section 7(e), without a separate - * agreement with Passbolt SA. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License along with this program. If not, - * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). - * - * @copyright Copyright (c) Passbolt SA (https://www.passbolt.com) - * @license https://opensource.org/licenses/AGPL-3.0 AGPL License - * @link https://www.passbolt.com Passbolt (tm) - * @since v1.0 + * Executes data refresh requests according to the offline-first autonomy policy: + * - Full initial data refresh is ONLY executed when local replica data is completely absent. + * - Whenever local data is present, lightweight incremental delta synchronization is performed via SyncEngine. */ - class FullDataRefreshExecutor( private val homeDataInteractor: HomeDataInteractor, private val dataRefreshTrackingFlow: DataRefreshTrackingFlow, private val coroutineLaunchContext: CoroutineLaunchContext, + private val syncEngine: SyncEngine, + private val hasLocalReplicaUseCase: HasLocalReplicaUseCase, + private val getSelectedAccountUseCase: GetSelectedAccountUseCase, ) { suspend fun performFullDataRefresh(isUserInitiated: Boolean = false) { - Timber.d("Full data refresh initiated") + Timber.d("Data refresh initiated (isUserInitiated=$isUserInitiated)") if (!dataRefreshTrackingFlow.isInProgress()) { dataRefreshTrackingFlow.startTracking(isUserInitiated) - val output = - runAuthenticatedOperation(canPromptForAuthentication = isUserInitiated) { - withContext(coroutineLaunchContext.default) { - homeDataInteractor.refreshAllHomeScreenData { progress -> - dataRefreshTrackingFlow.updateStatus(InProgress(progress)) - } + + val selectedAccount = getSelectedAccountUseCase.execute(Unit).selectedAccount + val hasData = if (selectedAccount != null) { + hasLocalReplicaUseCase.execute(UserIdInput(selectedAccount)).hasLocalReplica + } else { + false + } + + if (hasData) { + Timber.d("Local data present: performing fast incremental delta sync") + dataRefreshTrackingFlow.updateStatus(InProgress(progress = 0.5f)) + val syncResult = syncEngine.sync(SyncTrigger.MANUAL) + when (syncResult) { + is SyncResult.Success, is SyncResult.Skipped -> { + dataRefreshTrackingFlow.updateStatus(InProgress(progress = 1f)) + delay(FULL_PROGRESS_DISPLAY_MILLIS.milliseconds) + dataRefreshTrackingFlow.updateStatus(FinishedWithSuccess) + } + is SyncResult.Failure -> { + Timber.w("Delta sync returned failure during refresh: ${syncResult.reason}") + dataRefreshTrackingFlow.updateStatus(FinishedWithFailure) } } + } else { + Timber.i("No local data found: performing full initial bootstrap / data refresh") + val output = + runAuthenticatedOperation(canPromptForAuthentication = isUserInitiated) { + withContext(coroutineLaunchContext.default) { + homeDataInteractor.refreshAllHomeScreenData { progress -> + dataRefreshTrackingFlow.updateStatus(InProgress(progress)) + } + } + } - when (output) { - is Success -> { - dataRefreshTrackingFlow.updateStatus(InProgress(progress = 1f)) - delay(FULL_PROGRESS_DISPLAY_MILLIS.milliseconds) - dataRefreshTrackingFlow.updateStatus(FinishedWithSuccess) + when (output) { + is Success -> { + // After full initial refresh, trigger sync to establish initial watermark/cursor + syncEngine.sync(SyncTrigger.MANUAL) + dataRefreshTrackingFlow.updateStatus(InProgress(progress = 1f)) + delay(FULL_PROGRESS_DISPLAY_MILLIS.milliseconds) + dataRefreshTrackingFlow.updateStatus(FinishedWithSuccess) + } + is Failure -> dataRefreshTrackingFlow.updateStatus(FinishedWithFailure) } - is Failure -> dataRefreshTrackingFlow.updateStatus(FinishedWithFailure) } } } diff --git a/core/fulldatarefresh/src/test/java/net/svaroh/passly/core/fulldatarefresh/FullDataRefreshExecutorTest.kt b/core/fulldatarefresh/src/test/java/net/svaroh/passly/core/fulldatarefresh/FullDataRefreshExecutorTest.kt new file mode 100644 index 000000000..cb94e7207 --- /dev/null +++ b/core/fulldatarefresh/src/test/java/net/svaroh/passly/core/fulldatarefresh/FullDataRefreshExecutorTest.kt @@ -0,0 +1,124 @@ +package net.svaroh.passly.core.fulldatarefresh + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.common.datarefresh.DataRefreshStatus +import net.svaroh.passly.common.datarefresh.DataRefreshTrackingFlow +import net.svaroh.passly.common.usecase.UserIdInput +import net.svaroh.passly.commontest.TestCoroutineLaunchContext +import net.svaroh.passly.core.mvp.authentication.SessionRefreshTrackingFlow +import net.svaroh.passly.core.navigation.AppForegroundListener +import net.svaroh.passly.core.passphrasememorycache.PassphraseMemoryCache +import net.svaroh.passly.core.sync.SyncEngine +import net.svaroh.passly.core.sync.SyncResult +import net.svaroh.passly.core.sync.SyncStats +import net.svaroh.passly.core.sync.SyncTrigger +import net.svaroh.passly.database.usecase.HasLocalReplicaUseCase +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase +import net.svaroh.passly.feature.authentication.auth.usecase.GetSessionExpiryUseCase +import net.svaroh.passly.feature.authentication.auth.usecase.RefreshSessionUseCase +import org.junit.Rule +import org.junit.Test +import org.koin.core.logger.Level +import org.koin.core.module.dsl.singleOf +import org.koin.dsl.module +import org.koin.test.KoinTest +import org.koin.test.KoinTestRule +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.time.ZonedDateTime + +@OptIn(ExperimentalCoroutinesApi::class) +class FullDataRefreshExecutorTest : KoinTest { + + private val mockPassphraseMemoryCache = mock() + private val mockGetSessionExpiryUseCase = mock() + private val mockRefreshSessionUseCase = mock() + private val mockAppForegroundListener = mock() + + @get:Rule + val koinTestRule = KoinTestRule.create { + printLogger(Level.ERROR) + modules( + module { + single { mockGetSessionExpiryUseCase } + single { mockPassphraseMemoryCache } + single { mockRefreshSessionUseCase } + single { mockAppForegroundListener } + singleOf(::SessionRefreshTrackingFlow) + }, + ) + } + + private val testCoroutineLaunchContext = TestCoroutineLaunchContext() + private val mockHomeDataInteractor = mock() + private val dataRefreshTrackingFlow = DataRefreshTrackingFlow() + private val mockSyncEngine = mock() + private val mockHasLocalReplicaUseCase = mock() + private val mockGetSelectedAccountUseCase = mock() + + private val executor by lazy { + FullDataRefreshExecutor( + homeDataInteractor = mockHomeDataInteractor, + dataRefreshTrackingFlow = dataRefreshTrackingFlow, + coroutineLaunchContext = testCoroutineLaunchContext, + syncEngine = mockSyncEngine, + hasLocalReplicaUseCase = mockHasLocalReplicaUseCase, + getSelectedAccountUseCase = mockGetSelectedAccountUseCase, + ) + } + + @Test + fun `when local data exists - only fast delta sync is executed, full refresh is NOT called`() = + runTest(testCoroutineLaunchContext.ui) { + val userId = "user-123" + whenever(mockGetSelectedAccountUseCase.execute(Unit)) + .thenReturn(GetSelectedAccountUseCase.Output(userId)) + whenever(mockHasLocalReplicaUseCase.execute(UserIdInput(userId))) + .thenReturn(HasLocalReplicaUseCase.Output(hasLocalReplica = true)) + whenever(mockSyncEngine.sync(SyncTrigger.MANUAL)) + .thenReturn(SyncResult.Success(SyncStats(upserted = 1))) + + executor.performFullDataRefresh(isUserInitiated = true) + + // Verify delta sync was called + verify(mockSyncEngine).sync(SyncTrigger.MANUAL) + // Verify full refresh was strictly NOT called! + verify(mockHomeDataInteractor, never()).refreshAllHomeScreenData(any()) + + assertThat(dataRefreshTrackingFlow.dataRefreshStatusFlow.value) + .isEqualTo(DataRefreshStatus.Idle.FinishedWithSuccess) + } + + @Test + fun `when local data is absent - full initial data refresh is executed`() = + runTest { + val userId = "user-123" + whenever(mockAppForegroundListener.isForeground()) doReturn true + whenever(mockGetSessionExpiryUseCase.execute(Unit)).thenReturn( + GetSessionExpiryUseCase.Output.JwtWillExpire(ZonedDateTime.now().plusSeconds(60L)), + ) + whenever(mockPassphraseMemoryCache.getSessionDurationSeconds()).thenReturn(60L) + whenever(mockGetSelectedAccountUseCase.execute(Unit)) + .thenReturn(GetSelectedAccountUseCase.Output(userId)) + whenever(mockHasLocalReplicaUseCase.execute(UserIdInput(userId))) + .thenReturn(HasLocalReplicaUseCase.Output(hasLocalReplica = false)) + whenever(mockHomeDataInteractor.refreshAllHomeScreenData(any())) + .thenReturn(HomeDataInteractor.Output.Success) + whenever(mockSyncEngine.sync(SyncTrigger.MANUAL)) + .thenReturn(SyncResult.Success(SyncStats.EMPTY)) + + executor.performFullDataRefresh(isUserInitiated = true) + + // Verify full data refresh was called for bootstrapping + verify(mockHomeDataInteractor).refreshAllHomeScreenData(any()) + + assertThat(dataRefreshTrackingFlow.dataRefreshStatusFlow.value) + .isEqualTo(DataRefreshStatus.Idle.FinishedWithSuccess) + } +} diff --git a/core/sync/build.gradle.kts b/core/sync/build.gradle.kts index a169b353e..7abeeee55 100644 --- a/core/sync/build.gradle.kts +++ b/core/sync/build.gradle.kts @@ -2,12 +2,40 @@ plugins { id("passbolt.android.library") } +android { + namespace = "net.svaroh.passly.core.sync" +} + dependencies { + implementation(project(":architecture")) + implementation(project(":networking")) + implementation(project(":database")) + implementation(project(":entity")) + implementation(project(":dto")) + implementation(project(":common")) + implementation(project(":accounts-domain")) + implementation(project(":resources-domain")) + implementation(project(":folders-domain")) + implementation(project(":users-domain")) + implementation(project(":groups-domain")) + implementation(project(":resourcetypes-domain")) + implementation(project(":metadata-domain")) + implementation(project(":secrets-domain")) + implementation(project(":mappers")) + implementation(project(":uimodel")) + + implementation(libs.room.runtime) + implementation(libs.room.core) implementation(platform(libs.koin.bom)) implementation(libs.koin) implementation(libs.work.runtime) -} + implementation(libs.retrofit) + implementation(libs.retrofit.gsonconverter) + implementation(libs.timber) -android { - namespace = "net.svaroh.passly.core.sync" + testImplementation(project(":commontest")) + testImplementation(libs.truth) + testImplementation(libs.mockito.kotlin) + testImplementation(libs.turbine) + testImplementation(libs.work.testing) } diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/BootstrapStrategy.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/BootstrapStrategy.kt new file mode 100644 index 000000000..e3e5ee873 --- /dev/null +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/BootstrapStrategy.kt @@ -0,0 +1,88 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import net.svaroh.passly.core.sync.api.SyncApi +import timber.log.Timber + +sealed interface BootstrapResult { + data class Success( + val stats: SyncStats, + val pinnedCursor: Long, + val epoch: String, + ) : BootstrapResult + + data class Failure( + val cause: Throwable, + ) : BootstrapResult +} + +/** + * Executes initial or recovery bootstrap synchronization against /sync/bootstrap.json. + * Pins cursor on page 1 and downloads paginated chunks directly into the local replica. + */ +class BootstrapStrategy( + private val syncApi: SyncApi, + private val changesApplier: ChangesApplier, +) { + suspend fun execute(limit: Int = 500): BootstrapResult { + var page = 1 + var pinnedCursor: Long? = null + var pinnedEpoch: String? = null + var totalStats = SyncStats.EMPTY + + try { + while (true) { + Timber.d("Querying /sync/bootstrap.json?page=$page&limit=$limit&cursor=$pinnedCursor") + val response = syncApi.getBootstrap(page = page, limit = limit, cursor = pinnedCursor) + val body = response.body + val pagination = response.header.pagination + + if (pinnedCursor == null) { + pinnedCursor = body.cursor + pinnedEpoch = body.epoch + } + + val pageStats = changesApplier.applyBootstrapPage(body, page) + totalStats = totalStats + pageStats + + val totalCount = pagination.count + val currentLimit = pagination.limit ?: limit + val isLastPage = (page * currentLimit) >= totalCount || totalCount == 0 + + if (isLastPage) { + break + } + page++ + } + + val finalCursor = pinnedCursor ?: 0L + val finalEpoch = pinnedEpoch.orEmpty() + + return BootstrapResult.Success( + stats = totalStats, + pinnedCursor = finalCursor, + epoch = finalEpoch, + ) + } catch (e: Exception) { + Timber.e(e, "Error during bootstrap sync") + return BootstrapResult.Failure(e) + } + } +} diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/ChangesApplier.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/ChangesApplier.kt new file mode 100644 index 000000000..a071105e6 --- /dev/null +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/ChangesApplier.kt @@ -0,0 +1,445 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import net.svaroh.passly.common.transaction.DatabaseTransactionRunner +import net.svaroh.passly.core.sync.dto.SyncBootstrapDto +import net.svaroh.passly.core.sync.dto.SyncChangesDto +import net.svaroh.passly.core.sync.dto.SyncDeletionsDto +import net.svaroh.passly.core.sync.dto.SyncUpsertsDto +import net.svaroh.passly.database.DatabaseProvider +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase +import net.svaroh.passly.domain.resourcetypes.usecase.ResourceTypeIdToSlugMappingProvider +import net.svaroh.passly.dto.response.FolderResponseDto +import net.svaroh.passly.dto.response.GroupsResponseDto +import net.svaroh.passly.dto.response.MetadataKeysResponseDto +import net.svaroh.passly.dto.response.ResourceTypeDto +import net.svaroh.passly.dto.response.UserDto +import net.svaroh.passly.entity.folder.Folder +import net.svaroh.passly.entity.folder.FolderAndUsersCrossRef +import net.svaroh.passly.entity.folder.FolderUpdateState +import net.svaroh.passly.entity.group.FolderAndGroupsCrossRef +import net.svaroh.passly.entity.group.GroupUpdateState +import net.svaroh.passly.entity.group.ResourceAndGroupsCrossRef +import net.svaroh.passly.entity.group.UsersAndGroupCrossRef +import net.svaroh.passly.entity.group.UsersGroup +import net.svaroh.passly.entity.metadata.MetadataKey +import net.svaroh.passly.entity.resource.Permission +import net.svaroh.passly.entity.resource.Resource +import net.svaroh.passly.entity.resource.ResourceAndTagsCrossRef +import net.svaroh.passly.entity.resource.ResourceMetadata +import net.svaroh.passly.entity.resource.ResourceType +import net.svaroh.passly.entity.resource.ResourceUri +import net.svaroh.passly.entity.resource.ResourceUpdateState +import net.svaroh.passly.entity.resource.Tag +import net.svaroh.passly.entity.secret.Secret +import net.svaroh.passly.entity.sync.SyncState +import net.svaroh.passly.entity.user.ResourceAndUsersCrossRef +import net.svaroh.passly.entity.user.User +import net.svaroh.passly.entity.user.UserGpgKey +import net.svaroh.passly.entity.user.UserProfile +import net.svaroh.passly.entity.user.UserUpdateState +import net.svaroh.passly.mappers.PermissionsModelMapper +import net.svaroh.passly.mappers.ResourceModelMapper +import timber.log.Timber +import java.time.ZonedDateTime +import java.time.format.DateTimeParseException + +/** + * Applies sync changes (upserts and deletions) to the local Room database within a single transaction + * along with the updated cursor, ensuring strict consistency and atomic durability. + */ +class ChangesApplier( + private val databaseProvider: DatabaseProvider, + private val getSelectedAccountUseCase: GetSelectedAccountUseCase, + private val databaseTransactionRunner: DatabaseTransactionRunner, + private val resourceModelMapper: ResourceModelMapper, + private val permissionsModelMapper: PermissionsModelMapper, + private val resourceTypeIdToSlugMappingProvider: ResourceTypeIdToSlugMappingProvider, +) { + /** + * Applies a single delta page to Room and advances the sync cursor atomically. + */ + suspend fun applyChanges( + changes: SyncChangesDto, + epoch: String? = null, + ): SyncStats = + databaseTransactionRunner.runInTransaction { + val userId = requireNotNull(getSelectedAccountUseCase.execute(Unit).selectedAccount) { + "No selected account during applyChanges" + } + val db = databaseProvider.get(userId) + + val upsertStats = applyUpserts(db, changes.upserts, userId) + val deletedCount = applyDeletions(db, changes.deletions) + + val currentState = db.syncStateDao().getSyncState() + val resolvedEpoch = epoch ?: currentState?.epoch + db.syncStateDao().upsert( + SyncState( + id = SyncState.SINGLE_ROW_ID, + cursor = changes.cursor, + epoch = resolvedEpoch, + lastSyncTimestamp = System.currentTimeMillis(), + lastReconcileTimestamp = currentState?.lastReconcileTimestamp, + failureCount = 0, + ), + ) + + SyncStats( + upserted = upsertStats.upserted, + deleted = deletedCount, + secretsUpdated = upsertStats.secretsUpdated, + ) + } + + /** + * Applies a bootstrap slice to Room and records the pinned cursor. + */ + suspend fun applyBootstrapPage( + bootstrap: SyncBootstrapDto, + page: Int, + ): SyncStats = + databaseTransactionRunner.runInTransaction { + val userId = requireNotNull(getSelectedAccountUseCase.execute(Unit).selectedAccount) { + "No selected account during applyBootstrapPage" + } + val db = databaseProvider.get(userId) + + val upsertStats = applyUpserts(db, bootstrap.upserts, userId) + + val currentState = db.syncStateDao().getSyncState() + db.syncStateDao().upsert( + SyncState( + id = SyncState.SINGLE_ROW_ID, + cursor = bootstrap.cursor, + epoch = bootstrap.epoch, + lastSyncTimestamp = System.currentTimeMillis(), + lastReconcileTimestamp = currentState?.lastReconcileTimestamp, + failureCount = 0, + ), + ) + + SyncStats( + upserted = upsertStats.upserted, + deleted = 0, + secretsUpdated = upsertStats.secretsUpdated, + ) + } + + private suspend fun applyUpserts( + db: net.svaroh.passly.database.ResourceDatabase, + upserts: SyncUpsertsDto, + userId: String, + ): SyncStats { + var upsertedCount = 0 + var secretsUpdatedCount = 0 + + // 1. Metadata keys + if (upserts.metadataKeys.isNotEmpty()) { + val keys = mapMetadataKeys(upserts.metadataKeys) + db.metadataKeysDao().insertAll(keys) + upsertedCount += keys.size + } + + // 2. Resource types + if (upserts.resourceTypes.isNotEmpty()) { + val types = upserts.resourceTypes.map(::mapResourceType) + db.resourceTypesDao().upsertAll(types) + upsertedCount += types.size + } + + // 3. Users + if (upserts.users.isNotEmpty()) { + val users = upserts.users.mapNotNull(::mapUser) + db.usersDao().upsertAll(users) + upsertedCount += users.size + } + + // 4. Groups + if (upserts.groups.isNotEmpty()) { + val groups = upserts.groups.map(::mapGroup) + db.groupsDao().upsertAll(groups) + upsertedCount += groups.size + + val userGroupRefs = upserts.groups.flatMap { gDto -> + gDto.users?.map { uDto -> + UsersAndGroupCrossRef( + groupId = gDto.id.toString(), + userId = uDto.id.toString(), + ) + }.orEmpty() + } + if (userGroupRefs.isNotEmpty()) { + db.usersAndGroupsCrossRefDao().upsertAll(userGroupRefs) + } + } + + // 5. Folders + if (upserts.folders.isNotEmpty()) { + val folders = upserts.folders.map { mapFolder(it, userId) } + db.foldersDao().upsertAll(folders) + upsertedCount += folders.size + + val folderUserRefs = upserts.folders.flatMap { fDto -> + fDto.permissions.filter { it.group == null }.map { p -> + FolderAndUsersCrossRef( + folderId = fDto.id.toString(), + userId = p.aroForeignKey.toString(), + permission = mapEntityPermission(p.type), + permissionId = p.id.toString(), + ) + } + } + if (folderUserRefs.isNotEmpty()) { + db.folderAndUsersCrossRefDao().upsertAll(folderUserRefs) + } + + val folderGroupRefs = upserts.folders.flatMap { fDto -> + fDto.permissions.filter { it.group != null }.map { p -> + FolderAndGroupsCrossRef( + folderId = fDto.id.toString(), + groupId = p.group!!.id.toString(), + permission = mapEntityPermission(p.type), + permissionId = p.id.toString(), + ) + } + } + if (folderGroupRefs.isNotEmpty()) { + db.folderAndGroupsCrossRefDao().upsertAll(folderGroupRefs) + } + } + + // 6. Resources & associated secrets, tags, permissions, metadata + if (upserts.resources.isNotEmpty()) { + val slugMapping = resourceTypeIdToSlugMappingProvider.provideMappingForSelectedAccount() + val resourceEntities = mutableListOf() + val metadataEntities = mutableListOf() + val uriEntities = mutableListOf() + val tagEntities = mutableListOf() + val tagCrossRefs = mutableListOf() + val userCrossRefs = mutableListOf() + val groupCrossRefs = mutableListOf() + val resourceSecrets = mutableListOf() + + for (resDto in upserts.resources) { + try { + val slug = slugMapping[resDto.resourceTypeId] ?: "password-and-description" + val mappedResource = resourceModelMapper.map(resDto, slug = slug) + resourceEntities.add(resourceModelMapper.map(mappedResource, resourceUpdateState = ResourceUpdateState.UPDATED)) + metadataEntities.add(resourceModelMapper.mapResourceMetadata(mappedResource)) + uriEntities.addAll(resourceModelMapper.mapResourceUris(mappedResource)) + + resDto.tags?.forEach { tagDto -> + tagEntities.add(Tag(id = tagDto.id.toString(), slug = tagDto.slug, isShared = tagDto.isShared)) + tagCrossRefs.add(ResourceAndTagsCrossRef(tagId = tagDto.id.toString(), resourceId = resDto.id.toString())) + } + + resDto.permissions?.forEach { permDto -> + if (permDto.group != null) { + groupCrossRefs.add( + ResourceAndGroupsCrossRef( + resourceId = resDto.id.toString(), + groupId = permDto.group!!.id.toString(), + permission = mapEntityPermission(permDto.type), + permissionId = permDto.id.toString(), + ), + ) + } else { + userCrossRefs.add( + ResourceAndUsersCrossRef( + resourceId = resDto.id.toString(), + userId = permDto.aroForeignKey.toString(), + permission = mapEntityPermission(permDto.type), + permissionId = permDto.id.toString(), + ), + ) + } + } + + resDto.secrets?.firstOrNull()?.let { sDto -> + resourceSecrets.add( + Secret( + resourceId = resDto.id.toString(), + secretId = sDto.id?.toString(), + armoredData = sDto.data, + modified = sDto.modified?.let(::parseZonedDateTime), + fetchedAt = ZonedDateTime.now(), + ), + ) + } + } catch (e: Exception) { + Timber.w(e, "Skipping unparseable resource payload: ${resDto.id}") + } + } + + db.resourcesDao().upsertAll(resourceEntities) + db.resourceMetadataDao().upsertAll(metadataEntities) + + for (res in resourceEntities) { + db.resourceUriDao().deleteForResource(res.resourceId) + } + db.resourceUriDao().insertAll(uriEntities) + + if (tagEntities.isNotEmpty()) { + db.tagsDao().upsertAll(tagEntities) + } + if (tagCrossRefs.isNotEmpty()) { + db.resourcesAndTagsCrossRefDao().upsertAll(tagCrossRefs) + } + if (userCrossRefs.isNotEmpty()) { + db.resourcesAndUsersCrossRefDao().upsertAll(userCrossRefs) + } + if (groupCrossRefs.isNotEmpty()) { + db.resourcesAndGroupsCrossRefDao().upsertAll(groupCrossRefs) + } + if (resourceSecrets.isNotEmpty()) { + db.secretsDao().upsertAll(resourceSecrets) + secretsUpdatedCount += resourceSecrets.size + } + + upsertedCount += resourceEntities.size + } + + // 7. Standalone secrets + if (upserts.secrets.isNotEmpty()) { + val standaloneSecrets = upserts.secrets.mapNotNull { sDto -> + sDto.resourceId?.toString()?.let { resId -> + Secret( + resourceId = resId, + secretId = sDto.id?.toString(), + armoredData = sDto.data, + modified = sDto.modified?.let(::parseZonedDateTime), + fetchedAt = ZonedDateTime.now(), + ) + } + } + if (standaloneSecrets.isNotEmpty()) { + db.secretsDao().upsertAll(standaloneSecrets) + secretsUpdatedCount += standaloneSecrets.size + } + } + + return SyncStats( + upserted = upsertedCount, + secretsUpdated = secretsUpdatedCount, + ) + } + + private suspend fun applyDeletions( + db: net.svaroh.passly.database.ResourceDatabase, + deletions: SyncDeletionsDto, + ): Int { + var totalDeleted = 0 + if (deletions.resources.isNotEmpty()) { + db.resourcesDao().deleteAll(deletions.resources) + totalDeleted += deletions.resources.size + } + if (deletions.folders.isNotEmpty()) { + db.foldersDao().deleteAll(deletions.folders) + totalDeleted += deletions.folders.size + } + if (deletions.users.isNotEmpty()) { + db.usersDao().deleteAll(deletions.users) + totalDeleted += deletions.users.size + } + if (deletions.groups.isNotEmpty()) { + db.groupsDao().deleteAll(deletions.groups) + totalDeleted += deletions.groups.size + } + return totalDeleted + } + + private fun mapMetadataKeys( + dtos: List, + ): List = + dtos.map { dto -> + MetadataKey( + id = dto.id.toString(), + fingerprint = dto.fingerprint, + armoredKey = dto.armoredKey, + modified = parseZonedDateTime(dto.modified) ?: ZonedDateTime.now(), + expired = dto.expired?.let(::parseZonedDateTime), + deleted = dto.deleted?.let(::parseZonedDateTime), + ) + } + + private fun mapResourceType(dto: ResourceTypeDto): ResourceType = + ResourceType( + resourceTypeId = dto.id.toString(), + name = dto.name, + slug = dto.slug, + deleted = dto.deleted?.let(::parseZonedDateTime), + ) + + private fun mapUser(dto: UserDto): User? { + val gpg = dto.gpgKey ?: return null + return User( + id = dto.id.toString(), + userName = dto.username, + disabled = dto.disabled?.let { parseZonedDateTime(it)?.isBefore(ZonedDateTime.now()) } ?: false, + profile = UserProfile( + firstName = dto.profile?.firstName, + lastName = dto.profile?.lastName, + avatarUrl = dto.profile?.avatar?.url?.medium, + ), + gpgKey = UserGpgKey( + id = gpg.id.toString(), + armoredKey = gpg.armoredKey, + bits = gpg.bits, + uid = gpg.uid, + keyId = gpg.keyId, + fingerprint = gpg.fingerprint, + type = gpg.type, + expires = gpg.expires?.let(::parseZonedDateTime), + created = gpg.keyCreated?.let(::parseZonedDateTime), + ), + updateState = UserUpdateState.UPDATED, + ) + } + + private fun mapGroup(dto: GroupsResponseDto): UsersGroup = + UsersGroup( + groupId = dto.id.toString(), + name = dto.name, + updateState = GroupUpdateState.UPDATED, + ) + + private fun mapFolder(dto: FolderResponseDto, currentUserId: String): Folder = + Folder( + folderId = dto.id.toString(), + name = dto.name.orEmpty(), + permission = mapEntityPermission(dto.permission.type), + parentId = dto.folderParentId?.toString(), + isShared = dto.permissions.any { p -> p.group != null || p.aroForeignKey.toString() != currentUserId }, + modified = dto.modified?.let(::parseZonedDateTime) ?: ZonedDateTime.now(), + updateState = FolderUpdateState.UPDATED, + ) + + private fun mapEntityPermission(typeInt: Int): Permission = + permissionsModelMapper.map(permissionsModelMapper.map(typeInt)) + + private fun parseZonedDateTime(value: String): ZonedDateTime? = + try { + ZonedDateTime.parse(value) + } catch (e: DateTimeParseException) { + Timber.w(e, "Could not parse ISO timestamp: $value") + null + } +} diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/DeltaSyncStrategy.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/DeltaSyncStrategy.kt new file mode 100644 index 000000000..f089be538 --- /dev/null +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/DeltaSyncStrategy.kt @@ -0,0 +1,87 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import net.svaroh.passly.core.sync.api.SyncApi +import retrofit2.HttpException +import timber.log.Timber + +sealed interface DeltaSyncResult { + data class Success( + val stats: SyncStats, + val newCursor: Long, + ) : DeltaSyncResult + + data object Gone : DeltaSyncResult + + data class Failure( + val cause: Throwable, + ) : DeltaSyncResult +} + +/** + * Executes incremental delta synchronization against /sync/changes.json starting from local cursor. + * Handles multi-page deltas (has_more) and gracefully reports 410 Gone when cursor is purged. + */ +class DeltaSyncStrategy( + private val syncApi: SyncApi, + private val changesApplier: ChangesApplier, +) { + suspend fun execute( + sinceCursor: Long, + epoch: String? = null, + limit: Int = 500, + ): DeltaSyncResult { + var currentCursor = sinceCursor + var accumulatedStats = SyncStats.EMPTY + + try { + var hasMore = true + while (hasMore) { + Timber.d("Querying /sync/changes.json?since=$currentCursor&limit=$limit") + val response = syncApi.getChanges(since = currentCursor, limit = limit) + val body = response.body + + val pageStats = changesApplier.applyChanges(body, epoch = epoch) + accumulatedStats = accumulatedStats + pageStats + currentCursor = body.cursor + hasMore = body.hasMore + } + + return DeltaSyncResult.Success( + stats = accumulatedStats, + newCursor = currentCursor, + ) + } catch (e: HttpException) { + if (e.code() == HTTP_GONE) { + Timber.w("Server returned 410 Gone for cursor $currentCursor; retention expired or epoch mismatch.") + return DeltaSyncResult.Gone + } + Timber.e(e, "HTTP error during delta sync") + return DeltaSyncResult.Failure(e) + } catch (e: Exception) { + Timber.e(e, "Unexpected error during delta sync") + return DeltaSyncResult.Failure(e) + } + } + + private companion object { + const val HTTP_GONE = 410 + } +} diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/ManifestReconciler.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/ManifestReconciler.kt new file mode 100644 index 000000000..6fee595e0 --- /dev/null +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/ManifestReconciler.kt @@ -0,0 +1,99 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import net.svaroh.passly.common.transaction.DatabaseTransactionRunner +import net.svaroh.passly.core.sync.api.SyncApi +import net.svaroh.passly.core.sync.dto.SyncManifestItemDto +import net.svaroh.passly.database.DatabaseProvider +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase +import timber.log.Timber + +sealed interface ManifestReconcileResult { + data class Success( + val totalRemote: Int, + val deletedExtraLocal: Int, + val needsRefetchCount: Int, + ) : ManifestReconcileResult + + data class Failure( + val cause: Throwable, + ) : ManifestReconcileResult +} + +/** + * Reconciles local resources against the server's compact manifest (/sync/manifest.json). + * Detects silently revoked resources, purging orphaned local rows and identifying discrepancies. + */ +class ManifestReconciler( + private val syncApi: SyncApi, + private val databaseProvider: DatabaseProvider, + private val getSelectedAccountUseCase: GetSelectedAccountUseCase, + private val databaseTransactionRunner: DatabaseTransactionRunner, +) { + suspend fun execute(): ManifestReconcileResult { + try { + val userId = requireNotNull(getSelectedAccountUseCase.execute(Unit).selectedAccount) { + "No selected account during manifest reconciliation" + } + val db = databaseProvider.get(userId) + + val manifestResponse = syncApi.getManifest(type = "resources") + val remoteItems = manifestResponse.body + + val remoteMap = remoteItems.associateBy { it.id } + + var deletedCount = 0 + var needsRefetch = 0 + + databaseTransactionRunner.runInTransaction { + val localResources = db.resourcesDao().getAll() + val localIds = localResources.map { it.resourceId }.toSet() + + val extraLocalIds = localIds.filter { !remoteMap.containsKey(it) } + if (extraLocalIds.isNotEmpty()) { + Timber.i("Manifest reconciliation: deleting ${extraLocalIds.size} orphaned local resources") + db.resourcesDao().deleteAll(extraLocalIds) + deletedCount = extraLocalIds.size + } + + val remoteMissingLocally = remoteItems.count { !localIds.contains(it.id) } + needsRefetch = remoteMissingLocally + + val currentState = db.syncStateDao().getSyncState() + if (currentState != null) { + db.syncStateDao().upsert( + currentState.copy( + lastReconcileTimestamp = System.currentTimeMillis(), + ), + ) + } + } + + return ManifestReconcileResult.Success( + totalRemote = remoteItems.size, + deletedExtraLocal = deletedCount, + needsRefetchCount = needsRefetch, + ) + } catch (e: Exception) { + Timber.e(e, "Error during manifest reconciliation") + return ManifestReconcileResult.Failure(e) + } + } +} diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncEngine.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncEngine.kt new file mode 100644 index 000000000..80df2bcc2 --- /dev/null +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncEngine.kt @@ -0,0 +1,164 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import kotlinx.coroutines.sync.Mutex +import net.svaroh.passly.database.DatabaseProvider +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase +import retrofit2.HttpException +import timber.log.Timber +import java.io.IOException +import java.time.ZonedDateTime + +/** + * Orchestrates client synchronization against the Passly server according to the `sync/1` protocol. + * Coordinates delta fetch, transparent bootstrap fallback, and manifest reconciliation. + */ +class SyncEngine( + private val networkStateProvider: NetworkStateProvider, + private val getSelectedAccountUseCase: GetSelectedAccountUseCase, + private val databaseProvider: DatabaseProvider, + private val deltaSyncStrategy: DeltaSyncStrategy, + private val bootstrapStrategy: BootstrapStrategy, + private val manifestReconciler: ManifestReconciler, + private val syncStatusRepository: SyncStatusRepository, +) { + private val syncMutex = Mutex() + + suspend fun sync(trigger: SyncTrigger): SyncResult { + if (!syncMutex.tryLock()) { + Timber.i("Sync skipped: already running") + return SyncResult.Skipped(SyncResult.Skipped.Reason.ALREADY_RUNNING) + } + + try { + if (!networkStateProvider.isAvailable) { + Timber.i("Sync skipped: no network connection") + syncStatusRepository.onOffline() + return SyncResult.Skipped(SyncResult.Skipped.Reason.NO_NETWORK) + } + + val userId = getSelectedAccountUseCase.execute(Unit).selectedAccount + if (userId == null) { + Timber.w("Sync skipped: no active account selected") + return SyncResult.Skipped(SyncResult.Skipped.Reason.NO_ACCOUNT) + } + + val db = databaseProvider.get(userId) + val currentState = db.syncStateDao().getSyncState() + var accumulatedStats = SyncStats.EMPTY + + val currentCursor = currentState?.cursor + // 1. Delta or Bootstrap + if (currentCursor == null || currentCursor == 0L) { + syncStatusRepository.onRunStarted(SyncStatus.Running.Phase.BOOTSTRAP) + when (val result = bootstrapStrategy.execute()) { + is BootstrapResult.Success -> { + accumulatedStats = accumulatedStats + result.stats + } + is BootstrapResult.Failure -> { + return handleFailure(db, result.cause) + } + } + } else { + syncStatusRepository.onRunStarted(SyncStatus.Running.Phase.DELTA) + when (val result = deltaSyncStrategy.execute(sinceCursor = currentCursor, epoch = currentState.epoch)) { + is DeltaSyncResult.Success -> { + accumulatedStats = accumulatedStats + result.stats + } + is DeltaSyncResult.Gone -> { + Timber.i("Cursor expired on server (410 Gone); falling back to bootstrap") + syncStatusRepository.onRunStarted(SyncStatus.Running.Phase.BOOTSTRAP) + when (val bResult = bootstrapStrategy.execute()) { + is BootstrapResult.Success -> { + accumulatedStats = accumulatedStats + bResult.stats + } + is BootstrapResult.Failure -> { + return handleFailure(db, bResult.cause) + } + } + } + is DeltaSyncResult.Failure -> { + return handleFailure(db, result.cause) + } + } + } + + // 2. Manifest Reconciliation check + val updatedState = db.syncStateDao().getSyncState() + val lastReconcile = updatedState?.lastReconcileTimestamp + val shouldReconcile = trigger == SyncTrigger.MANUAL || + lastReconcile == null || + (System.currentTimeMillis() - lastReconcile > RECONCILE_INTERVAL_MS) + + if (shouldReconcile) { + syncStatusRepository.onRunStarted(SyncStatus.Running.Phase.RECONCILE) + when (val mResult = manifestReconciler.execute()) { + is ManifestReconcileResult.Success -> { + Timber.d("Manifest reconciliation completed: $mResult") + } + is ManifestReconcileResult.Failure -> { + Timber.w(mResult.cause, "Manifest reconciliation warning") + } + } + } + + // 3. Mark success + val now = ZonedDateTime.now() + syncStatusRepository.onSuccess(now) + db.syncStateDao().updateFailureCount(0) + + return SyncResult.Success(accumulatedStats) + } finally { + syncMutex.unlock() + } + } + + private suspend fun handleFailure( + db: net.svaroh.passly.database.ResourceDatabase, + cause: Throwable, + ): SyncResult.Failure { + val failureReason = when (cause) { + is HttpException -> { + when (cause.code()) { + HTTP_UNAUTHORIZED, HTTP_FORBIDDEN -> SyncFailureReason.SESSION + else -> SyncFailureReason.UNREACHABLE + } + } + is IOException -> SyncFailureReason.UNREACHABLE + else -> SyncFailureReason.PROTOCOL + } + + val currentState = db.syncStateDao().getSyncState() + val nextFailureCount = (currentState?.failureCount ?: 0) + 1 + db.syncStateDao().updateFailureCount(nextFailureCount) + + val retryDuration = SyncBackoff.delayAfter(nextFailureCount) + val retryAt = ZonedDateTime.now().plus(retryDuration) + + syncStatusRepository.onFailure(failureReason, retryAt) + return SyncResult.Failure(failureReason) + } + + private companion object { + const val HTTP_UNAUTHORIZED = 401 + const val HTTP_FORBIDDEN = 403 + const val RECONCILE_INTERVAL_MS = 24 * 60 * 60 * 1000L // 24 hours + } +} diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncModule.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncModule.kt index 8f1b4b905..8659207d2 100644 --- a/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncModule.kt +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncModule.kt @@ -18,6 +18,9 @@ */ package net.svaroh.passly.core.sync +import net.svaroh.passly.core.networking.RestService +import net.svaroh.passly.core.sync.api.SyncApi +import net.svaroh.passly.core.sync.work.SyncScheduler import org.koin.android.ext.koin.androidApplication import org.koin.core.module.dsl.singleOf import org.koin.dsl.module @@ -26,4 +29,11 @@ val syncModule = module { single { NetworkStateProvider(androidApplication()) } singleOf(::SyncStatusRepository) + single { get().service(SyncApi::class.java) } + singleOf(::ChangesApplier) + singleOf(::DeltaSyncStrategy) + singleOf(::BootstrapStrategy) + singleOf(::ManifestReconciler) + singleOf(::SyncEngine) + single { SyncScheduler(androidApplication()) } } diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncResult.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncResult.kt index 17ca74a1b..1922ce8b4 100644 --- a/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncResult.kt +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/SyncResult.kt @@ -77,4 +77,17 @@ data class SyncStats( ) { val isEmpty: Boolean get() = upserted == 0 && deleted == 0 && secretsUpdated == 0 && pushedOperations == 0 + + operator fun plus(other: SyncStats): SyncStats = + SyncStats( + upserted = this.upserted + other.upserted, + deleted = this.deleted + other.deleted, + secretsUpdated = this.secretsUpdated + other.secretsUpdated, + pushedOperations = this.pushedOperations + other.pushedOperations, + reconciled = this.reconciled || other.reconciled, + ) + + companion object { + val EMPTY = SyncStats() + } } diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/api/SyncApi.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/api/SyncApi.kt new file mode 100644 index 000000000..80633133e --- /dev/null +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/api/SyncApi.kt @@ -0,0 +1,57 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync.api + +import net.svaroh.passly.core.sync.dto.SyncBootstrapDto +import net.svaroh.passly.core.sync.dto.SyncChangesDto +import net.svaroh.passly.core.sync.dto.SyncManifestItemDto +import net.svaroh.passly.core.sync.dto.SyncMetaDto +import net.svaroh.passly.dto.response.BasePaginatedResponse +import net.svaroh.passly.dto.response.BaseResponse +import retrofit2.http.GET +import retrofit2.http.Query + +interface SyncApi { + @GET("sync/changes.json") + suspend fun getChanges( + @Query("since") since: Long, + @Query("limit") limit: Int = DEFAULT_LIMIT, + ): BaseResponse + + @GET("sync/bootstrap.json") + suspend fun getBootstrap( + @Query("page") page: Int = FIRST_PAGE, + @Query("limit") limit: Int = DEFAULT_LIMIT, + @Query("cursor") cursor: Long? = null, + ): BasePaginatedResponse + + @GET("sync/manifest.json") + suspend fun getManifest( + @Query("type") type: String = DEFAULT_MANIFEST_TYPE, + ): BaseResponse> + + @GET("sync/meta.json") + suspend fun getMeta(): BaseResponse + + companion object { + const val DEFAULT_LIMIT = 500 + const val FIRST_PAGE = 1 + const val DEFAULT_MANIFEST_TYPE = "resources" + } +} diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/dto/SyncDtos.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/dto/SyncDtos.kt new file mode 100644 index 000000000..6e15b43c5 --- /dev/null +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/dto/SyncDtos.kt @@ -0,0 +1,116 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync.dto + +import com.google.gson.annotations.SerializedName +import net.svaroh.passly.dto.response.FolderResponseDto +import net.svaroh.passly.dto.response.GroupsResponseDto +import net.svaroh.passly.dto.response.MetadataKeysResponseDto +import net.svaroh.passly.dto.response.ResourceResponseDto +import net.svaroh.passly.dto.response.ResourceTypeDto +import net.svaroh.passly.dto.response.SecretDto +import net.svaroh.passly.dto.response.UserDto + +/** + * Snapshot entities keyed by collection, returned during delta and bootstrap sync. + */ +data class SyncUpsertsDto( + @SerializedName("resources") + val resources: List = emptyList(), + @SerializedName("secrets") + val secrets: List = emptyList(), + @SerializedName("folders") + val folders: List = emptyList(), + @SerializedName("users") + val users: List = emptyList(), + @SerializedName("groups") + val groups: List = emptyList(), + @SerializedName("resource_types") + val resourceTypes: List = emptyList(), + @SerializedName("metadata_keys") + val metadataKeys: List = emptyList(), +) + +/** + * Identifier lists of entities that the caller can no longer see (deleted or revoked access). + */ +data class SyncDeletionsDto( + @SerializedName("resources") + val resources: List = emptyList(), + @SerializedName("folders") + val folders: List = emptyList(), + @SerializedName("users") + val users: List = emptyList(), + @SerializedName("groups") + val groups: List = emptyList(), +) + +/** + * Response payload for `GET /sync/changes.json`. + */ +data class SyncChangesDto( + @SerializedName("cursor") + val cursor: Long, + @SerializedName("has_more") + val hasMore: Boolean = false, + @SerializedName("upserts") + val upserts: SyncUpsertsDto = SyncUpsertsDto(), + @SerializedName("deletions") + val deletions: SyncDeletionsDto = SyncDeletionsDto(), +) + +/** + * Response payload for `GET /sync/bootstrap.json`. + */ +data class SyncBootstrapDto( + @SerializedName("cursor") + val cursor: Long, + @SerializedName("epoch") + val epoch: String, + @SerializedName("upserts") + val upserts: SyncUpsertsDto = SyncUpsertsDto(), +) + +/** + * One item from the lightweight reconciliation list returned by `GET /sync/manifest.json`. + */ +data class SyncManifestItemDto( + @SerializedName("id") + val id: String, + @SerializedName("modified") + val modified: String, + @SerializedName("secret_modified") + val secretModified: String? = null, +) + +/** + * Server protocol metadata from `GET /sync/meta.json`. + */ +data class SyncMetaDto( + @SerializedName("protocol") + val protocol: String, + @SerializedName("epoch") + val epoch: String, + @SerializedName("min_client") + val minClient: String, + @SerializedName("max_page_size") + val maxPageSize: Int, + @SerializedName("retention_days") + val retentionDays: Int, +) diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/work/SyncScheduler.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/work/SyncScheduler.kt new file mode 100644 index 000000000..e775df0b5 --- /dev/null +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/work/SyncScheduler.kt @@ -0,0 +1,92 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync.work + +import android.content.Context +import androidx.work.Constraints +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.ExistingWorkPolicy +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import timber.log.Timber +import java.util.concurrent.TimeUnit + +/** + * Manages background scheduling of delta sync with WorkManager. + */ +class SyncScheduler( + private val context: Context, +) { + fun schedulePeriodicSync(intervalMinutes: Long = DEFAULT_INTERVAL_MINUTES) { + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val periodicWork = PeriodicWorkRequestBuilder( + intervalMinutes, + TimeUnit.MINUTES, + FLEX_INTERVAL_MINUTES, + TimeUnit.MINUTES, + ) + .setConstraints(constraints) + .addTag(TAG_SYNC_PERIODIC) + .build() + + WorkManager.getInstance(context).enqueueUniquePeriodicWork( + WORK_NAME_PERIODIC, + ExistingPeriodicWorkPolicy.UPDATE, + periodicWork, + ) + Timber.i("Scheduled periodic sync with interval $intervalMinutes min") + } + + fun scheduleImmediateSync() { + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val immediateWork = OneTimeWorkRequestBuilder() + .setConstraints(constraints) + .addTag(TAG_SYNC_IMMEDIATE) + .build() + + WorkManager.getInstance(context).enqueueUniqueWork( + WORK_NAME_IMMEDIATE, + ExistingWorkPolicy.REPLACE, + immediateWork, + ) + Timber.i("Scheduled immediate sync work") + } + + fun cancelPeriodicSync() { + WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME_PERIODIC) + Timber.i("Cancelled periodic sync") + } + + companion object { + const val DEFAULT_INTERVAL_MINUTES = 60L + const val FLEX_INTERVAL_MINUTES = 15L + const val WORK_NAME_PERIODIC = "passly_periodic_sync" + const val WORK_NAME_IMMEDIATE = "passly_immediate_sync" + const val TAG_SYNC_PERIODIC = "tag_passly_sync_periodic" + const val TAG_SYNC_IMMEDIATE = "tag_passly_sync_immediate" + } +} diff --git a/core/sync/src/main/java/net/svaroh/passly/core/sync/work/SyncWorker.kt b/core/sync/src/main/java/net/svaroh/passly/core/sync/work/SyncWorker.kt new file mode 100644 index 000000000..fe978e9da --- /dev/null +++ b/core/sync/src/main/java/net/svaroh/passly/core/sync/work/SyncWorker.kt @@ -0,0 +1,58 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync.work + +import android.content.Context +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import net.svaroh.passly.core.sync.SyncEngine +import net.svaroh.passly.core.sync.SyncResult +import net.svaroh.passly.core.sync.SyncTrigger +import org.koin.core.component.KoinComponent +import org.koin.core.component.inject +import timber.log.Timber + +/** + * WorkManager CoroutineWorker for executing background delta synchronization runs. + */ +class SyncWorker( + appContext: Context, + workerParams: WorkerParameters, +) : CoroutineWorker(appContext, workerParams), KoinComponent { + + private val syncEngine: SyncEngine by inject() + + override suspend fun doWork(): Result { + Timber.i("SyncWorker: background delta sync triggered") + return when (val result = syncEngine.sync(SyncTrigger.BACKGROUND)) { + is SyncResult.Success -> { + Timber.i("SyncWorker: finished successfully ($result)") + Result.success() + } + is SyncResult.Skipped -> { + Timber.i("SyncWorker: skipped ($result)") + Result.success() + } + is SyncResult.Failure -> { + Timber.w("SyncWorker: failed ($result), scheduling retry") + Result.retry() + } + } + } +} diff --git a/core/sync/src/test/java/net/svaroh/passly/core/sync/BootstrapStrategyTest.kt b/core/sync/src/test/java/net/svaroh/passly/core/sync/BootstrapStrategyTest.kt new file mode 100644 index 000000000..67606fab6 --- /dev/null +++ b/core/sync/src/test/java/net/svaroh/passly/core/sync/BootstrapStrategyTest.kt @@ -0,0 +1,138 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.core.sync.api.SyncApi +import net.svaroh.passly.core.sync.dto.SyncBootstrapDto +import net.svaroh.passly.core.sync.dto.SyncUpsertsDto +import net.svaroh.passly.dto.response.BasePaginatedResponse +import net.svaroh.passly.dto.response.HeaderWithPaginationResponse +import net.svaroh.passly.dto.response.Pagination +import net.svaroh.passly.dto.response.StatusResponse +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.io.IOException + +class BootstrapStrategyTest { + private val syncApi: SyncApi = mock() + private val changesApplier: ChangesApplier = mock() + private val strategy = BootstrapStrategy(syncApi, changesApplier) + + @Test + fun `single page bootstrap completes and returns pinned cursor`() = runTest { + val bootstrap = SyncBootstrapDto( + cursor = 1000L, + epoch = "epoch-abc", + upserts = SyncUpsertsDto(), + ) + val response = BasePaginatedResponse( + header = HeaderWithPaginationResponse( + id = "1", + status = StatusResponse.COMPLETE, + message = "ok", + url = "/sync/bootstrap.json", + code = 200, + serverTime = 1234567890L, + pagination = Pagination(count = 10, page = 1, limit = 500), + ), + body = bootstrap, + ) + whenever(syncApi.getBootstrap(page = 1, limit = 500, cursor = null)).thenReturn(response) + whenever(changesApplier.applyBootstrapPage(bootstrap, 1)).thenReturn(SyncStats(upserted = 10)) + + val result = strategy.execute(limit = 500) + + assertThat(result).isInstanceOf(BootstrapResult.Success::class.java) + val success = result as BootstrapResult.Success + assertThat(success.pinnedCursor).isEqualTo(1000L) + assertThat(success.epoch).isEqualTo("epoch-abc") + assertThat(success.stats.upserted).isEqualTo(10) + verify(changesApplier).applyBootstrapPage(bootstrap, 1) + } + + @Test + fun `multi page bootstrap pins cursor from page 1 and passes to page 2`() = runTest { + val page1Body = SyncBootstrapDto( + cursor = 5000L, + epoch = "epoch-123", + upserts = SyncUpsertsDto(), + ) + val page2Body = SyncBootstrapDto( + cursor = 5000L, + epoch = "epoch-123", + upserts = SyncUpsertsDto(), + ) + val page1Response = BasePaginatedResponse( + header = HeaderWithPaginationResponse( + id = "1", + status = StatusResponse.COMPLETE, + message = "ok", + url = "/sync/bootstrap.json", + code = 200, + serverTime = 1234567890L, + pagination = Pagination(count = 800, page = 1, limit = 500), + ), + body = page1Body, + ) + val page2Response = BasePaginatedResponse( + header = HeaderWithPaginationResponse( + id = "2", + status = StatusResponse.COMPLETE, + message = "ok", + url = "/sync/bootstrap.json", + code = 200, + serverTime = 1234567890L, + pagination = Pagination(count = 800, page = 2, limit = 500), + ), + body = page2Body, + ) + + whenever(syncApi.getBootstrap(page = 1, limit = 500, cursor = null)).thenReturn(page1Response) + whenever(syncApi.getBootstrap(page = 2, limit = 500, cursor = 5000L)).thenReturn(page2Response) + + whenever(changesApplier.applyBootstrapPage(page1Body, 1)).thenReturn(SyncStats(upserted = 500)) + whenever(changesApplier.applyBootstrapPage(page2Body, 2)).thenReturn(SyncStats(upserted = 300)) + + val result = strategy.execute(limit = 500) + + assertThat(result).isInstanceOf(BootstrapResult.Success::class.java) + val success = result as BootstrapResult.Success + assertThat(success.pinnedCursor).isEqualTo(5000L) + assertThat(success.stats.upserted).isEqualTo(800) + } + + @Test + fun `bootstrap error returns Failure`() = runTest { + whenever(syncApi.getBootstrap(any(), any(), anyOrNull())).thenAnswer { + throw IOException("Timeout") + } + + val result = strategy.execute() + + assertThat(result).isInstanceOf(BootstrapResult.Failure::class.java) + val failure = result as BootstrapResult.Failure + assertThat(failure.cause).isInstanceOf(IOException::class.java) + } +} diff --git a/core/sync/src/test/java/net/svaroh/passly/core/sync/ChangesApplierTest.kt b/core/sync/src/test/java/net/svaroh/passly/core/sync/ChangesApplierTest.kt new file mode 100644 index 000000000..e34fa3c16 --- /dev/null +++ b/core/sync/src/test/java/net/svaroh/passly/core/sync/ChangesApplierTest.kt @@ -0,0 +1,112 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.common.transaction.DatabaseTransactionRunner +import net.svaroh.passly.core.sync.dto.SyncChangesDto +import net.svaroh.passly.core.sync.dto.SyncDeletionsDto +import net.svaroh.passly.core.sync.dto.SyncUpsertsDto +import net.svaroh.passly.database.DatabaseProvider +import net.svaroh.passly.database.ResourceDatabase +import net.svaroh.passly.database.impl.folders.FoldersDao +import net.svaroh.passly.database.impl.groups.GroupsDao +import net.svaroh.passly.database.impl.resources.ResourcesDao +import net.svaroh.passly.database.impl.sync.SyncStateDao +import net.svaroh.passly.database.impl.users.UsersDao +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase +import net.svaroh.passly.domain.resourcetypes.usecase.ResourceTypeIdToSlugMappingProvider +import net.svaroh.passly.mappers.PermissionsModelMapper +import net.svaroh.passly.mappers.ResourceModelMapper +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class ChangesApplierTest { + private val databaseProvider: DatabaseProvider = mock() + private val getSelectedAccountUseCase: GetSelectedAccountUseCase = mock() + private val databaseTransactionRunner: DatabaseTransactionRunner = mock() + private val resourceModelMapper: ResourceModelMapper = mock() + private val permissionsModelMapper: PermissionsModelMapper = mock() + private val resourceTypeIdToSlugMappingProvider: ResourceTypeIdToSlugMappingProvider = mock() + + private val db: ResourceDatabase = mock() + private val resourcesDao: ResourcesDao = mock() + private val foldersDao: FoldersDao = mock() + private val usersDao: UsersDao = mock() + private val groupsDao: GroupsDao = mock() + private val syncStateDao: SyncStateDao = mock() + + private val changesApplier = ChangesApplier( + databaseProvider, + getSelectedAccountUseCase, + databaseTransactionRunner, + resourceModelMapper, + permissionsModelMapper, + resourceTypeIdToSlugMappingProvider, + ) + + @Before + fun setUp() = runTest { + whenever(getSelectedAccountUseCase.execute(Unit)).thenReturn( + GetSelectedAccountUseCase.Output(selectedAccount = "user-1"), + ) + whenever(databaseProvider.get("user-1")).thenReturn(db) + whenever(db.resourcesDao()).thenReturn(resourcesDao) + whenever(db.foldersDao()).thenReturn(foldersDao) + whenever(db.usersDao()).thenReturn(usersDao) + whenever(db.groupsDao()).thenReturn(groupsDao) + whenever(db.syncStateDao()).thenReturn(syncStateDao) + whenever(resourceTypeIdToSlugMappingProvider.provideMappingForSelectedAccount()).thenReturn(emptyMap()) + + whenever(databaseTransactionRunner.runInTransaction(any Any?>())).thenAnswer { + val block = it.getArgument Any?>(0) + kotlinx.coroutines.runBlocking { block() } + } + } + + @Test + fun `applyChanges executes deletions and updates cursor atomically`() = runTest { + val deletions = SyncDeletionsDto( + resources = listOf("res-1", "res-2"), + folders = listOf("folder-1"), + users = listOf("user-deleted"), + groups = listOf("group-deleted"), + ) + val changes = SyncChangesDto( + cursor = 100L, + hasMore = false, + upserts = SyncUpsertsDto(), + deletions = deletions, + ) + + val stats = changesApplier.applyChanges(changes, epoch = "epoch-1") + + assertThat(stats.deleted).isEqualTo(5) + verify(resourcesDao).deleteAll(listOf("res-1", "res-2")) + verify(foldersDao).deleteAll(listOf("folder-1")) + verify(usersDao).deleteAll(listOf("user-deleted")) + verify(groupsDao).deleteAll(listOf("group-deleted")) + verify(syncStateDao).upsert(any()) + } +} diff --git a/core/sync/src/test/java/net/svaroh/passly/core/sync/DeltaSyncStrategyTest.kt b/core/sync/src/test/java/net/svaroh/passly/core/sync/DeltaSyncStrategyTest.kt new file mode 100644 index 000000000..345914e57 --- /dev/null +++ b/core/sync/src/test/java/net/svaroh/passly/core/sync/DeltaSyncStrategyTest.kt @@ -0,0 +1,135 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.core.sync.api.SyncApi +import net.svaroh.passly.core.sync.dto.SyncChangesDto +import net.svaroh.passly.core.sync.dto.SyncDeletionsDto +import net.svaroh.passly.core.sync.dto.SyncUpsertsDto +import net.svaroh.passly.dto.response.BaseResponse +import net.svaroh.passly.dto.response.HeaderResponse +import net.svaroh.passly.dto.response.StatusResponse +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import retrofit2.HttpException +import retrofit2.Response +import java.io.IOException + +class DeltaSyncStrategyTest { + private val syncApi: SyncApi = mock() + private val changesApplier: ChangesApplier = mock() + private val strategy = DeltaSyncStrategy(syncApi, changesApplier) + + private fun testHeader() = HeaderResponse( + id = "1", + status = StatusResponse.COMPLETE, + message = "ok", + url = "/sync/changes.json", + code = 200, + serverTime = 1234567890L, + ) + + @Test + fun `single page delta applies changes and returns success`() = runTest { + val changes = SyncChangesDto( + cursor = 100L, + hasMore = false, + upserts = SyncUpsertsDto(), + deletions = SyncDeletionsDto(), + ) + whenever(syncApi.getChanges(since = 50L, limit = 500)).thenReturn( + BaseResponse(header = testHeader(), body = changes), + ) + whenever(changesApplier.applyChanges(eq(changes), eq("epoch-1"))).thenReturn( + SyncStats(upserted = 3, deleted = 1), + ) + + val result = strategy.execute(sinceCursor = 50L, epoch = "epoch-1") + + assertThat(result).isInstanceOf(DeltaSyncResult.Success::class.java) + val success = result as DeltaSyncResult.Success + assertThat(success.newCursor).isEqualTo(100L) + assertThat(success.stats.upserted).isEqualTo(3) + assertThat(success.stats.deleted).isEqualTo(1) + verify(changesApplier).applyChanges(changes, "epoch-1") + } + + @Test + fun `multi page delta queries until hasMore is false and accumulates stats`() = runTest { + val page1 = SyncChangesDto( + cursor = 100L, + hasMore = true, + upserts = SyncUpsertsDto(), + deletions = SyncDeletionsDto(), + ) + val page2 = SyncChangesDto( + cursor = 150L, + hasMore = false, + upserts = SyncUpsertsDto(), + deletions = SyncDeletionsDto(), + ) + whenever(syncApi.getChanges(since = 50L, limit = 500)).thenReturn( + BaseResponse(header = testHeader(), body = page1), + ) + whenever(syncApi.getChanges(since = 100L, limit = 500)).thenReturn( + BaseResponse(header = testHeader(), body = page2), + ) + + whenever(changesApplier.applyChanges(eq(page1), eq("epoch-1"))).thenReturn(SyncStats(upserted = 5)) + whenever(changesApplier.applyChanges(eq(page2), eq("epoch-1"))).thenReturn(SyncStats(upserted = 2, deleted = 1)) + + val result = strategy.execute(sinceCursor = 50L, epoch = "epoch-1") + + assertThat(result).isInstanceOf(DeltaSyncResult.Success::class.java) + val success = result as DeltaSyncResult.Success + assertThat(success.newCursor).isEqualTo(150L) + assertThat(success.stats.upserted).isEqualTo(7) + assertThat(success.stats.deleted).isEqualTo(1) + } + + @Test + fun `server 410 Gone returns DeltaSyncResult Gone`() = runTest { + val httpException = HttpException(Response.error(410, "".toResponseBody())) + whenever(syncApi.getChanges(any(), any())).thenThrow(httpException) + + val result = strategy.execute(sinceCursor = 50L, epoch = "epoch-1") + + assertThat(result).isEqualTo(DeltaSyncResult.Gone) + } + + @Test + fun `network error returns DeltaSyncResult Failure`() = runTest { + whenever(syncApi.getChanges(any(), any())).thenAnswer { + throw IOException("Connection reset") + } + + val result = strategy.execute(sinceCursor = 50L, epoch = "epoch-1") + + assertThat(result).isInstanceOf(DeltaSyncResult.Failure::class.java) + val failure = result as DeltaSyncResult.Failure + assertThat(failure.cause).isInstanceOf(IOException::class.java) + } +} diff --git a/core/sync/src/test/java/net/svaroh/passly/core/sync/ManifestReconcilerTest.kt b/core/sync/src/test/java/net/svaroh/passly/core/sync/ManifestReconcilerTest.kt new file mode 100644 index 000000000..a6ef0155e --- /dev/null +++ b/core/sync/src/test/java/net/svaroh/passly/core/sync/ManifestReconcilerTest.kt @@ -0,0 +1,135 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.common.transaction.DatabaseTransactionRunner +import net.svaroh.passly.core.sync.api.SyncApi +import net.svaroh.passly.core.sync.dto.SyncManifestItemDto +import net.svaroh.passly.database.DatabaseProvider +import net.svaroh.passly.database.ResourceDatabase +import net.svaroh.passly.database.impl.resources.ResourcesDao +import net.svaroh.passly.database.impl.sync.SyncStateDao +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase +import net.svaroh.passly.dto.response.BaseResponse +import net.svaroh.passly.dto.response.HeaderResponse +import net.svaroh.passly.dto.response.StatusResponse +import net.svaroh.passly.entity.resource.Permission +import net.svaroh.passly.entity.resource.ResourceWithMetadata +import net.svaroh.passly.entity.sync.SyncState +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.io.IOException +import java.time.ZonedDateTime + +class ManifestReconcilerTest { + private val syncApi: SyncApi = mock() + private val databaseProvider: DatabaseProvider = mock() + private val getSelectedAccountUseCase: GetSelectedAccountUseCase = mock() + private val databaseTransactionRunner: DatabaseTransactionRunner = mock() + private val db: ResourceDatabase = mock() + private val resourcesDao: ResourcesDao = mock() + private val syncStateDao: SyncStateDao = mock() + + private val reconciler = ManifestReconciler( + syncApi, + databaseProvider, + getSelectedAccountUseCase, + databaseTransactionRunner, + ) + + private fun testHeader() = HeaderResponse( + id = "1", + status = StatusResponse.COMPLETE, + message = "ok", + url = "/sync/manifest.json", + code = 200, + serverTime = 1234567890L, + ) + + @Before + fun setUp() = runTest { + whenever(getSelectedAccountUseCase.execute(Unit)).thenReturn( + GetSelectedAccountUseCase.Output(selectedAccount = "user-1"), + ) + whenever(databaseProvider.get("user-1")).thenReturn(db) + whenever(db.resourcesDao()).thenReturn(resourcesDao) + whenever(db.syncStateDao()).thenReturn(syncStateDao) + whenever(databaseTransactionRunner.runInTransaction(any Any?>())).thenAnswer { + val block = it.getArgument Any?>(0) + kotlinx.coroutines.runBlocking { block() } + } + } + + @Test + fun `reconcile deletes local resources that are not present in server manifest`() = runTest { + val remoteManifest = listOf( + SyncManifestItemDto(id = "res-1", modified = "2026-11-01T10:00:00Z"), + ) + whenever(syncApi.getManifest(type = "resources")).thenReturn( + BaseResponse(header = testHeader(), body = remoteManifest), + ) + + val localRes1 = createResourceWithMetadata("res-1") + val localRes2 = createResourceWithMetadata("res-2") // Orphaned on server! + whenever(resourcesDao.getAll()).thenReturn(listOf(localRes1, localRes2)) + whenever(syncStateDao.getSyncState()).thenReturn(SyncState(id = 1, cursor = 100L)) + + val result = reconciler.execute() + + assertThat(result).isInstanceOf(ManifestReconcileResult.Success::class.java) + val success = result as ManifestReconcileResult.Success + assertThat(success.totalRemote).isEqualTo(1) + assertThat(success.deletedExtraLocal).isEqualTo(1) + + verify(resourcesDao).deleteAll(listOf("res-2")) + verify(syncStateDao).upsert(any()) + } + + @Test + fun `reconcile reports Failure when remote API call fails`() = runTest { + whenever(syncApi.getManifest(any())).thenAnswer { + throw IOException("Network error") + } + + val result = reconciler.execute() + + assertThat(result).isInstanceOf(ManifestReconcileResult.Failure::class.java) + } + + private fun createResourceWithMetadata(id: String) = + ResourceWithMetadata( + resourceId = id, + folderId = null, + resourcePermission = Permission.OWNER, + resourceTypeId = "type-1", + slug = "password-and-description", + favouriteId = null, + modified = ZonedDateTime.now(), + expiry = null, + metadataJson = "{}", + metadataKeyId = null, + metadataKeyType = null, + ) +} diff --git a/core/sync/src/test/java/net/svaroh/passly/core/sync/SyncEngineTest.kt b/core/sync/src/test/java/net/svaroh/passly/core/sync/SyncEngineTest.kt new file mode 100644 index 000000000..8f5834dbd --- /dev/null +++ b/core/sync/src/test/java/net/svaroh/passly/core/sync/SyncEngineTest.kt @@ -0,0 +1,195 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.database.DatabaseProvider +import net.svaroh.passly.database.ResourceDatabase +import net.svaroh.passly.database.impl.sync.SyncStateDao +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase +import net.svaroh.passly.entity.sync.SyncState +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import retrofit2.HttpException +import retrofit2.Response + +class SyncEngineTest { + private val networkStateProvider: NetworkStateProvider = mock() + private val getSelectedAccountUseCase: GetSelectedAccountUseCase = mock() + private val databaseProvider: DatabaseProvider = mock() + private val deltaSyncStrategy: DeltaSyncStrategy = mock() + private val bootstrapStrategy: BootstrapStrategy = mock() + private val manifestReconciler: ManifestReconciler = mock() + private val syncStatusRepository: SyncStatusRepository = mock() + private val db: ResourceDatabase = mock() + private val syncStateDao: SyncStateDao = mock() + + private val engine = SyncEngine( + networkStateProvider, + getSelectedAccountUseCase, + databaseProvider, + deltaSyncStrategy, + bootstrapStrategy, + manifestReconciler, + syncStatusRepository, + ) + + @Before + fun setUp() = runTest { + whenever(networkStateProvider.isAvailable).thenReturn(true) + whenever(getSelectedAccountUseCase.execute(Unit)).thenReturn( + GetSelectedAccountUseCase.Output(selectedAccount = "user-1"), + ) + whenever(databaseProvider.get("user-1")).thenReturn(db) + whenever(db.syncStateDao()).thenReturn(syncStateDao) + whenever(manifestReconciler.execute()).thenReturn( + ManifestReconcileResult.Success(totalRemote = 0, deletedExtraLocal = 0, needsRefetchCount = 0), + ) + } + + @Test + fun `sync is skipped when network is unavailable`() = runTest { + whenever(networkStateProvider.isAvailable).thenReturn(false) + + val result = engine.sync(SyncTrigger.BACKGROUND) + + assertThat(result).isEqualTo(SyncResult.Skipped(SyncResult.Skipped.Reason.NO_NETWORK)) + verify(syncStatusRepository).onOffline() + } + + @Test + fun `sync is skipped when no account is selected`() = runTest { + whenever(getSelectedAccountUseCase.execute(Unit)).thenReturn( + GetSelectedAccountUseCase.Output(selectedAccount = null), + ) + + val result = engine.sync(SyncTrigger.BACKGROUND) + + assertThat(result).isEqualTo(SyncResult.Skipped(SyncResult.Skipped.Reason.NO_ACCOUNT)) + } + + @Test + fun `initial sync triggers bootstrap when cursor is null`() = runTest { + whenever(syncStateDao.getSyncState()).thenReturn(null) + whenever(bootstrapStrategy.execute()).thenReturn( + BootstrapResult.Success( + stats = SyncStats(upserted = 15), + pinnedCursor = 500L, + epoch = "ep-1", + ), + ) + + val result = engine.sync(SyncTrigger.BACKGROUND) + + assertThat(result).isInstanceOf(SyncResult.Success::class.java) + val success = result as SyncResult.Success + assertThat(success.stats.upserted).isEqualTo(15) + verify(bootstrapStrategy).execute() + verify(syncStatusRepository).onRunStarted(SyncStatus.Running.Phase.BOOTSTRAP) + verify(syncStatusRepository).onSuccess(any()) + verify(syncStateDao).updateFailureCount(0) + } + + @Test + fun `subsequent sync triggers delta sync`() = runTest { + whenever(syncStateDao.getSyncState()).thenReturn( + SyncState(id = 1, cursor = 500L, epoch = "ep-1", lastSyncTimestamp = 1000L, lastReconcileTimestamp = System.currentTimeMillis()), + ) + whenever(deltaSyncStrategy.execute(sinceCursor = 500L, epoch = "ep-1")).thenReturn( + DeltaSyncResult.Success( + stats = SyncStats(upserted = 2, deleted = 1), + newCursor = 505L, + ), + ) + + val result = engine.sync(SyncTrigger.BACKGROUND) + + assertThat(result).isInstanceOf(SyncResult.Success::class.java) + val success = result as SyncResult.Success + assertThat(success.stats.upserted).isEqualTo(2) + assertThat(success.stats.deleted).isEqualTo(1) + verify(deltaSyncStrategy).execute(sinceCursor = 500L, epoch = "ep-1") + verify(syncStatusRepository).onRunStarted(SyncStatus.Running.Phase.DELTA) + } + + @Test + fun `delta 410 Gone triggers transparent fallback to bootstrap`() = runTest { + whenever(syncStateDao.getSyncState()).thenReturn( + SyncState(id = 1, cursor = 500L, epoch = "ep-1", lastSyncTimestamp = 1000L, lastReconcileTimestamp = System.currentTimeMillis()), + ) + whenever(deltaSyncStrategy.execute(sinceCursor = 500L, epoch = "ep-1")).thenReturn( + DeltaSyncResult.Gone, + ) + whenever(bootstrapStrategy.execute()).thenReturn( + BootstrapResult.Success( + stats = SyncStats(upserted = 100), + pinnedCursor = 1500L, + epoch = "ep-2", + ), + ) + + val result = engine.sync(SyncTrigger.BACKGROUND) + + assertThat(result).isInstanceOf(SyncResult.Success::class.java) + verify(bootstrapStrategy).execute() + verify(syncStatusRepository).onRunStarted(SyncStatus.Running.Phase.BOOTSTRAP) + } + + @Test + fun `manual sync forces manifest reconciliation pass`() = runTest { + whenever(syncStateDao.getSyncState()).thenReturn( + SyncState(id = 1, cursor = 500L, epoch = "ep-1", lastSyncTimestamp = 1000L, lastReconcileTimestamp = System.currentTimeMillis()), + ) + whenever(deltaSyncStrategy.execute(sinceCursor = 500L, epoch = "ep-1")).thenReturn( + DeltaSyncResult.Success(stats = SyncStats(), newCursor = 500L), + ) + whenever(manifestReconciler.execute()).thenReturn( + ManifestReconcileResult.Success(totalRemote = 10, deletedExtraLocal = 0, needsRefetchCount = 0), + ) + + val result = engine.sync(SyncTrigger.MANUAL) + + assertThat(result).isInstanceOf(SyncResult.Success::class.java) + verify(manifestReconciler).execute() + verify(syncStatusRepository).onRunStarted(SyncStatus.Running.Phase.RECONCILE) + } + + @Test + fun `session failure reports Failure with SESSION reason and schedules backoff`() = runTest { + whenever(syncStateDao.getSyncState()).thenReturn( + SyncState(id = 1, cursor = 500L, epoch = "ep-1", lastSyncTimestamp = 1000L, lastReconcileTimestamp = null, failureCount = 0), + ) + val http401 = HttpException(Response.error(401, "".toResponseBody())) + whenever(deltaSyncStrategy.execute(sinceCursor = 500L, epoch = "ep-1")).thenReturn( + DeltaSyncResult.Failure(http401), + ) + + val result = engine.sync(SyncTrigger.BACKGROUND) + + assertThat(result).isEqualTo(SyncResult.Failure(SyncFailureReason.SESSION)) + verify(syncStateDao).updateFailureCount(1) + verify(syncStatusRepository).onFailure(any(), any()) + } +} diff --git a/core/sync/src/test/java/net/svaroh/passly/core/sync/SyncIntegrationE2ETest.kt b/core/sync/src/test/java/net/svaroh/passly/core/sync/SyncIntegrationE2ETest.kt new file mode 100644 index 000000000..a454fc78d --- /dev/null +++ b/core/sync/src/test/java/net/svaroh/passly/core/sync/SyncIntegrationE2ETest.kt @@ -0,0 +1,298 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.common.transaction.DatabaseTransactionRunner +import net.svaroh.passly.core.sync.api.SyncApi +import net.svaroh.passly.core.sync.dto.SyncBootstrapDto +import net.svaroh.passly.core.sync.dto.SyncChangesDto +import net.svaroh.passly.core.sync.dto.SyncDeletionsDto +import net.svaroh.passly.core.sync.dto.SyncManifestItemDto +import net.svaroh.passly.core.sync.dto.SyncUpsertsDto +import net.svaroh.passly.database.DatabaseProvider +import net.svaroh.passly.database.ResourceDatabase +import net.svaroh.passly.database.impl.folders.FoldersDao +import net.svaroh.passly.database.impl.groups.GroupsDao +import net.svaroh.passly.database.impl.resources.ResourcesDao +import net.svaroh.passly.database.impl.sync.SyncStateDao +import net.svaroh.passly.database.impl.users.UsersDao +import net.svaroh.passly.domain.accounts.usecase.GetSelectedAccountUseCase +import net.svaroh.passly.domain.resourcetypes.usecase.ResourceTypeIdToSlugMappingProvider +import net.svaroh.passly.dto.response.BasePaginatedResponse +import net.svaroh.passly.dto.response.BaseResponse +import net.svaroh.passly.dto.response.HeaderResponse +import net.svaroh.passly.dto.response.HeaderWithPaginationResponse +import net.svaroh.passly.dto.response.Pagination +import net.svaroh.passly.dto.response.StatusResponse +import net.svaroh.passly.entity.resource.Permission +import net.svaroh.passly.entity.resource.ResourceWithMetadata +import net.svaroh.passly.entity.sync.SyncState +import net.svaroh.passly.mappers.PermissionsModelMapper +import net.svaroh.passly.mappers.ResourceModelMapper +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import retrofit2.HttpException +import retrofit2.Response +import java.io.IOException +import java.time.ZonedDateTime + +/** + * End-to-end integration test verifying the full lifecycle of the sync/1 engine: + * 1. Cold start bootstrap + * 2. Incremental delta sync + * 3. 410 Gone recovery + * 4. Manifest reconciliation & access revocation + * 5. Offline skipped runs + */ +class SyncIntegrationE2ETest { + private val syncApi: SyncApi = mock() + private val networkStateProvider: NetworkStateProvider = mock() + private val getSelectedAccountUseCase: GetSelectedAccountUseCase = mock() + private val databaseProvider: DatabaseProvider = mock() + private val databaseTransactionRunner: DatabaseTransactionRunner = mock() + private val resourceModelMapper: ResourceModelMapper = mock() + private val permissionsModelMapper: PermissionsModelMapper = mock() + private val resourceTypeIdToSlugMappingProvider: ResourceTypeIdToSlugMappingProvider = mock() + + private val db: ResourceDatabase = mock() + private val syncStateDao: SyncStateDao = mock() + private val resourcesDao: ResourcesDao = mock() + private val foldersDao: FoldersDao = mock() + private val usersDao: UsersDao = mock() + private val groupsDao: GroupsDao = mock() + + private val syncStatusRepository = SyncStatusRepository() + + private lateinit var changesApplier: ChangesApplier + private lateinit var deltaSyncStrategy: DeltaSyncStrategy + private lateinit var bootstrapStrategy: BootstrapStrategy + private lateinit var manifestReconciler: ManifestReconciler + private lateinit var syncEngine: SyncEngine + + // Simulated local persistent state in Room + private var persistedSyncState: SyncState? = null + + private fun testHeader(url: String = "") = HeaderResponse( + id = "1", + status = StatusResponse.COMPLETE, + message = "ok", + url = url, + code = 200, + serverTime = 1234567890L, + ) + + private fun testPaginationHeader(url: String, count: Int, page: Int = 1, limit: Int = 500) = + HeaderWithPaginationResponse( + id = "1", + status = StatusResponse.COMPLETE, + message = "ok", + url = url, + code = 200, + serverTime = 1234567890L, + pagination = Pagination(count = count, page = page, limit = limit), + ) + + @Before + fun setUp() = runTest { + persistedSyncState = null + + whenever(networkStateProvider.isAvailable).thenReturn(true) + whenever(getSelectedAccountUseCase.execute(Unit)).thenReturn( + GetSelectedAccountUseCase.Output(selectedAccount = "user-alice"), + ) + whenever(databaseProvider.get("user-alice")).thenReturn(db) + whenever(db.syncStateDao()).thenReturn(syncStateDao) + whenever(db.resourcesDao()).thenReturn(resourcesDao) + whenever(db.foldersDao()).thenReturn(foldersDao) + whenever(db.usersDao()).thenReturn(usersDao) + whenever(db.groupsDao()).thenReturn(groupsDao) + + whenever(syncStateDao.getSyncState()).thenAnswer { persistedSyncState } + whenever(syncStateDao.upsert(any())).thenAnswer { + val state = it.getArgument(0) + persistedSyncState = state + 1L + } + whenever(syncStateDao.updateFailureCount(any())).thenAnswer { + val count = it.getArgument(0) + persistedSyncState = persistedSyncState?.copy(failureCount = count) + 1 + } + + whenever(databaseTransactionRunner.runInTransaction(any Any?>())).thenAnswer { + val block = it.getArgument Any?>(0) + kotlinx.coroutines.runBlocking { block() } + } + + changesApplier = ChangesApplier( + databaseProvider, + getSelectedAccountUseCase, + databaseTransactionRunner, + resourceModelMapper, + permissionsModelMapper, + resourceTypeIdToSlugMappingProvider, + ) + deltaSyncStrategy = DeltaSyncStrategy(syncApi, changesApplier) + bootstrapStrategy = BootstrapStrategy(syncApi, changesApplier) + manifestReconciler = ManifestReconciler( + syncApi, + databaseProvider, + getSelectedAccountUseCase, + databaseTransactionRunner, + ) + syncEngine = SyncEngine( + networkStateProvider, + getSelectedAccountUseCase, + databaseProvider, + deltaSyncStrategy, + bootstrapStrategy, + manifestReconciler, + syncStatusRepository, + ) + } + + @Test + fun `full lifecycle E2E - bootstrap then delta then manifest reconciliation`() = runTest { + // --- STEP 1: Cold start (database is empty, cursor is null) --- + val bootstrapBody = SyncBootstrapDto( + cursor = 1000L, + epoch = "epoch-2026-v1", + upserts = SyncUpsertsDto(), + ) + whenever(syncApi.getBootstrap(page = eq(1), limit = any(), cursor = anyOrNull())).thenReturn( + BasePaginatedResponse( + header = testPaginationHeader(url = "/sync/bootstrap.json", count = 0), + body = bootstrapBody, + ), + ) + + val bootstrapResult = syncEngine.sync(SyncTrigger.BACKGROUND) + assertThat(bootstrapResult).isInstanceOf(SyncResult.Success::class.java) + assertThat(persistedSyncState?.cursor).isEqualTo(1000L) + assertThat(persistedSyncState?.epoch).isEqualTo("epoch-2026-v1") + assertThat(syncStatusRepository.status.value).isInstanceOf(SyncStatus.Idle::class.java) + + // --- STEP 2: Incremental delta sync (cursor advances to 1025) --- + val deltaChanges = SyncChangesDto( + cursor = 1025L, + hasMore = false, + upserts = SyncUpsertsDto(), + deletions = SyncDeletionsDto(folders = listOf("deleted-folder-id")), + ) + whenever(syncApi.getChanges(since = 1000L, limit = 500)).thenReturn( + BaseResponse(header = testHeader("/sync/changes.json"), body = deltaChanges), + ) + + val deltaResult = syncEngine.sync(SyncTrigger.BACKGROUND) + assertThat(deltaResult).isInstanceOf(SyncResult.Success::class.java) + val deltaSuccess = deltaResult as SyncResult.Success + assertThat(deltaSuccess.stats.deleted).isEqualTo(1) + assertThat(persistedSyncState?.cursor).isEqualTo(1025L) + verify(foldersDao).deleteAll(listOf("deleted-folder-id")) + + // --- STEP 3: Manual sync triggers Manifest Reconciliation & Access Revocation --- + val remoteManifest = listOf( + SyncManifestItemDto(id = "res-valid-1", modified = "2026-11-01T10:00:00Z"), + ) + whenever(syncApi.getChanges(since = 1025L, limit = 500)).thenReturn( + BaseResponse( + header = testHeader("/sync/changes.json"), + body = SyncChangesDto(cursor = 1025L, hasMore = false, upserts = SyncUpsertsDto(), deletions = SyncDeletionsDto()), + ), + ) + whenever(syncApi.getManifest(type = "resources")).thenReturn( + BaseResponse(header = testHeader("/sync/manifest.json"), body = remoteManifest), + ) + + val localResValid = createResourceWithMetadata("res-valid-1") + val localResRevoked = createResourceWithMetadata("res-revoked-secret") + whenever(resourcesDao.getAll()).thenReturn(listOf(localResValid, localResRevoked)) + + val manualResult = syncEngine.sync(SyncTrigger.MANUAL) + assertThat(manualResult).isInstanceOf(SyncResult.Success::class.java) + // Access revoked on server -> resource removed locally + verify(resourcesDao).deleteAll(listOf("res-revoked-secret")) + assertThat(persistedSyncState?.lastReconcileTimestamp).isNotNull() + } + + @Test + fun `410 Gone recovery E2E - transparent bootstrap resets cursor without data loss`() = runTest { + persistedSyncState = SyncState(id = 1, cursor = 200L, epoch = "old-epoch") + + val http410 = HttpException(Response.error(410, "Gone".toResponseBody())) + whenever(syncApi.getChanges(since = 200L, limit = 500)).thenThrow(http410) + + val newBootstrap = SyncBootstrapDto( + cursor = 9999L, + epoch = "new-epoch-2026", + upserts = SyncUpsertsDto(), + ) + whenever(syncApi.getBootstrap(page = 1, limit = 500, cursor = null)).thenReturn( + BasePaginatedResponse( + header = testPaginationHeader(url = "/sync/bootstrap.json", count = 0), + body = newBootstrap, + ), + ) + + val result = syncEngine.sync(SyncTrigger.BACKGROUND) + + assertThat(result).isInstanceOf(SyncResult.Success::class.java) + assertThat(persistedSyncState?.cursor).isEqualTo(9999L) + assertThat(persistedSyncState?.epoch).isEqualTo("new-epoch-2026") + // Verify no local data was purged + verify(resourcesDao, never()).deleteAll(any()) + } + + @Test + fun `offline behavior E2E - no network round trips and status updated to Offline`() = runTest { + whenever(networkStateProvider.isAvailable).thenReturn(false) + + val result = syncEngine.sync(SyncTrigger.BACKGROUND) + + assertThat(result).isEqualTo(SyncResult.Skipped(SyncResult.Skipped.Reason.NO_NETWORK)) + assertThat(syncStatusRepository.status.value).isInstanceOf(SyncStatus.Offline::class.java) + verify(syncApi, never()).getChanges(any(), any()) + verify(syncApi, never()).getBootstrap(any(), any(), anyOrNull()) + } + + private fun createResourceWithMetadata(id: String) = + ResourceWithMetadata( + resourceId = id, + folderId = null, + resourcePermission = Permission.OWNER, + resourceTypeId = "type-1", + slug = "password-and-description", + favouriteId = null, + modified = ZonedDateTime.now(), + expiry = null, + metadataJson = "{}", + metadataKeyId = null, + metadataKeyType = null, + ) +} diff --git a/core/sync/src/test/java/net/svaroh/passly/core/sync/SyncStatusRepositoryTest.kt b/core/sync/src/test/java/net/svaroh/passly/core/sync/SyncStatusRepositoryTest.kt new file mode 100644 index 000000000..834a83521 --- /dev/null +++ b/core/sync/src/test/java/net/svaroh/passly/core/sync/SyncStatusRepositoryTest.kt @@ -0,0 +1,73 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync + +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import java.time.ZonedDateTime + +class SyncStatusRepositoryTest { + private val repository = SyncStatusRepository() + + @Test + fun `initial status is Idle with null lastSuccessAt`() { + val initial = repository.status.value + assertThat(initial).isInstanceOf(SyncStatus.Idle::class.java) + assertThat(initial.lastSuccessAt).isNull() + } + + @Test + fun `onRunStarted updates status to Running with specified phase`() { + repository.onRunStarted(SyncStatus.Running.Phase.BOOTSTRAP) + val status = repository.status.value + assertThat(status).isInstanceOf(SyncStatus.Running::class.java) + val running = status as SyncStatus.Running + assertThat(running.phase).isEqualTo(SyncStatus.Running.Phase.BOOTSTRAP) + } + + @Test + fun `onSuccess transitions to Idle with timestamp`() { + val now = ZonedDateTime.now() + repository.onSuccess(now) + val status = repository.status.value + assertThat(status).isEqualTo(SyncStatus.Idle(lastSuccessAt = now)) + } + + @Test + fun `onOffline transitions to Offline preserving lastSuccessAt`() { + val now = ZonedDateTime.now() + repository.onSuccess(now) + repository.onOffline() + val status = repository.status.value + assertThat(status).isEqualTo(SyncStatus.Offline(lastSuccessAt = now)) + } + + @Test + fun `onFailure transitions to Failed with reason and retry schedule`() { + val now = ZonedDateTime.now() + val retry = now.plusMinutes(5) + repository.onSuccess(now) + repository.onFailure(SyncFailureReason.UNREACHABLE, retry) + + val status = repository.status.value + assertThat(status).isEqualTo( + SyncStatus.Failed(lastSuccessAt = now, reason = SyncFailureReason.UNREACHABLE, retryAt = retry), + ) + } +} diff --git a/core/sync/src/test/java/net/svaroh/passly/core/sync/work/SyncWorkerTest.kt b/core/sync/src/test/java/net/svaroh/passly/core/sync/work/SyncWorkerTest.kt new file mode 100644 index 000000000..a67c748e5 --- /dev/null +++ b/core/sync/src/test/java/net/svaroh/passly/core/sync/work/SyncWorkerTest.kt @@ -0,0 +1,101 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.core.sync.work + +import android.content.Context +import androidx.work.ListenableWorker +import androidx.work.WorkerParameters +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import net.svaroh.passly.core.sync.SyncEngine +import net.svaroh.passly.core.sync.SyncFailureReason +import net.svaroh.passly.core.sync.SyncResult +import net.svaroh.passly.core.sync.SyncStats +import net.svaroh.passly.core.sync.SyncTrigger +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.dsl.module +import org.koin.test.KoinTest +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class SyncWorkerTest : KoinTest { + private val syncEngine: SyncEngine = mock() + private val context: Context = mock() + private val workerParams: WorkerParameters = mock() + + @Before + fun setUp() { + startKoin { + modules( + module { + single { syncEngine } + }, + ) + } + } + + @After + fun tearDown() { + stopKoin() + } + + @Test + fun `doWork returns success when engine returns Success`() = runTest { + whenever(syncEngine.sync(SyncTrigger.BACKGROUND)).thenReturn( + SyncResult.Success(stats = SyncStats(upserted = 5)), + ) + + val worker = SyncWorker(context, workerParams) + val result = worker.doWork() + + assertThat(result).isEqualTo(ListenableWorker.Result.success()) + verify(syncEngine).sync(SyncTrigger.BACKGROUND) + } + + @Test + fun `doWork returns success when engine is Skipped`() = runTest { + whenever(syncEngine.sync(SyncTrigger.BACKGROUND)).thenReturn( + SyncResult.Skipped(SyncResult.Skipped.Reason.NO_NETWORK), + ) + + val worker = SyncWorker(context, workerParams) + val result = worker.doWork() + + assertThat(result).isEqualTo(ListenableWorker.Result.success()) + verify(syncEngine).sync(SyncTrigger.BACKGROUND) + } + + @Test + fun `doWork returns retry when engine returns Failure`() = runTest { + whenever(syncEngine.sync(SyncTrigger.BACKGROUND)).thenReturn( + SyncResult.Failure(SyncFailureReason.UNREACHABLE), + ) + + val worker = SyncWorker(context, workerParams) + val result = worker.doWork() + + assertThat(result).isEqualTo(ListenableWorker.Result.retry()) + verify(syncEngine).sync(SyncTrigger.BACKGROUND) + } +} diff --git a/features/autofillresources/src/main/java/com/passbolt/mobile/android/feature/autofill/passkey/PasskeyCredentialProviderService.kt b/features/autofillresources/src/main/java/com/passbolt/mobile/android/feature/autofill/passkey/PasskeyCredentialProviderService.kt index ceebcc29a..1c2c3c81f 100644 --- a/features/autofillresources/src/main/java/com/passbolt/mobile/android/feature/autofill/passkey/PasskeyCredentialProviderService.kt +++ b/features/autofillresources/src/main/java/com/passbolt/mobile/android/feature/autofill/passkey/PasskeyCredentialProviderService.kt @@ -67,10 +67,54 @@ class PasskeyCredentialProviderService : private val serviceScope by lazy { CoroutineScope(serviceJob + coroutineLaunchContext.ui) } override fun onDestroy() { + serviceJob.cancel() serviceScope.cancel() + cleanUpFrameworkLeak() super.onDestroy() } + private fun cleanUpFrameworkLeak() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + runCatching { + var currentClass: Class<*>? = javaClass + while (currentClass != null && currentClass != Any::class.java) { + val className = currentClass.name + if (className == "android.service.credentials.CredentialProviderService" || + className == "androidx.credentials.provider.CredentialProviderService" + ) { + for (field in currentClass.declaredFields) { + runCatching { + field.isAccessible = true + val fieldValue = field.get(this) ?: return@runCatching + clearServiceReferences(fieldValue) + } + } + } + currentClass = currentClass.superclass + } + }.onFailure { error -> + Timber.w(error, "Failed to clean up CredentialProviderService framework leak") + } + } + } + + private fun clearServiceReferences(target: Any) { + var targetClass: Class<*>? = target.javaClass + while (targetClass != null && targetClass != Any::class.java) { + for (field in targetClass.declaredFields) { + if (field.name.startsWith("this$") || + android.app.Service::class.java.isAssignableFrom(field.type) + ) { + runCatching { + field.isAccessible = true + field.set(target, null) + } + } + } + targetClass = targetClass.superclass + } + } + override fun onBeginGetCredentialRequest( request: BeginGetCredentialRequest, cancellationSignal: CancellationSignal, diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 1cea3bba7..cceb15bc6 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -85,6 +85,7 @@ camerax-mlvision = { module = "androidx.camera:camera-mlkit-vision", version.ref lifecycle-process = { module = "androidx.lifecycle:lifecycle-process", version.ref = "lifecycle" } app-startup = { module = "androidx.startup:startup-runtime", version.ref = "appStartUp" } work-runtime = { module = "androidx.work:work-runtime-ktx", version.ref = "work" } +work-testing = { module = "androidx.work:work-testing", version.ref = "work" } splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "splashScreen" } androidx-navigation3-runtime = { module = "androidx.navigation3:navigation3-runtime", version.ref = "nav3Core" } androidx-navigation3-ui = { module = "androidx.navigation3:navigation3-ui", version.ref = "nav3Core" } diff --git a/gradle/versions.gradle.kts b/gradle/versions.gradle.kts index fb080cae9..a7cab570b 100644 --- a/gradle/versions.gradle.kts +++ b/gradle/versions.gradle.kts @@ -1,7 +1,7 @@ import org.gradle.internal.extensions.core.extra -extra["projectVersionName"] = "6.0.8" -extra["projectVersionCode"] = 65 +extra["projectVersionName"] = "6.0.12" +extra["projectVersionCode"] = 69 extra["projectMinSdk"] = 30 extra["projectMinFullySupportedSdk"] = 31 diff --git a/model/entity/src/main/java/net/svaroh/passly/entity/sync/SyncState.kt b/model/entity/src/main/java/net/svaroh/passly/entity/sync/SyncState.kt new file mode 100644 index 000000000..a2a6ab7ae --- /dev/null +++ b/model/entity/src/main/java/net/svaroh/passly/entity/sync/SyncState.kt @@ -0,0 +1,43 @@ +/** + * Passly - Open source password manager for teams + * Copyright (c) 2026 Svaroh + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General + * Public License (AGPL) as published by the Free Software Foundation version 3. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, + * see GNU Affero General Public License v3 (http://www.gnu.org/licenses/agpl-3.0.html). + * + * @copyright Copyright (c) Svaroh + * @license https://opensource.org/licenses/AGPL-3.0 AGPL License + * @link https://passly.svaroh.net Passly + * @since v1.0 + */ +package net.svaroh.passly.entity.sync + +import androidx.room.Entity +import androidx.room.PrimaryKey + +/** + * Durable state of the sync engine for a given account. + * + * Stored in the local encrypted Room database alongside the replica data so that updates to the + * cursor and data occur in the exact same transaction. + */ +@Entity(tableName = "SyncState") +data class SyncState( + @PrimaryKey + val id: Int = SINGLE_ROW_ID, + val cursor: Long?, + val epoch: String? = null, + val lastSyncTimestamp: Long? = null, + val lastReconcileTimestamp: Long? = null, + val failureCount: Int = 0, +) { + companion object { + const val SINGLE_ROW_ID = 1 + } +}