diff --git a/wallet/src/de/schildbach/wallet/ui/compose_views/ConnectApprovalSheets.kt b/wallet/src/de/schildbach/wallet/ui/compose_views/ConnectApprovalSheets.kt index 4a44301db1..beed4e897d 100644 --- a/wallet/src/de/schildbach/wallet/ui/compose_views/ConnectApprovalSheets.kt +++ b/wallet/src/de/schildbach/wallet/ui/compose_views/ConnectApprovalSheets.kt @@ -60,6 +60,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import android.app.DatePickerDialog +import androidx.annotation.VisibleForTesting import de.schildbach.wallet.ui.more.connections.AppConnectLimits import java.math.BigInteger import java.text.DecimalFormatSymbols @@ -153,11 +154,22 @@ class ConnectLimitPickerDialog : OffsetDialogFragment(R.layout.dialog_compose_co dismiss() } + /** + * The date picker is a plain dialog, outside the fragment manager. It is dismissed with this sheet's + * view, so locking the wallet, which dismisses the approve sheet and with it this child sheet, takes + * it down too instead of leaving it above the lock screen. + */ + @VisibleForTesting + internal var expiryDatePicker: DatePickerDialog? = null + private set + /** Any day from tomorrow to a year after the request; the connection expires at the end of that day. */ - private fun showDatePicker(blockTime: Long, current: Long?) { + @VisibleForTesting + internal fun showDatePicker(blockTime: Long, current: Long?) { val latest = blockTime + AppConnectLimits.MAX_LIFETIME val initial = Calendar.getInstance().apply { timeInMillis = current ?: latest } - DatePickerDialog(requireContext(), { _, year, month, day -> + expiryDatePicker?.dismiss() + expiryDatePicker = DatePickerDialog(requireContext(), { _, year, month, day -> val endOfDay = Calendar.getInstance().apply { set(year, month, day, 23, 59, 59) set(Calendar.MILLISECOND, 0) @@ -167,7 +179,14 @@ class ConnectLimitPickerDialog : OffsetDialogFragment(R.layout.dialog_compose_co }, initial.get(Calendar.YEAR), initial.get(Calendar.MONTH), initial.get(Calendar.DAY_OF_MONTH)).apply { datePicker.minDate = blockTime + AppConnectLimits.DAY datePicker.maxDate = latest - }.show() + show() + } + } + + override fun onDestroyView() { + expiryDatePicker?.dismiss() + expiryDatePicker = null + super.onDestroyView() } } diff --git a/wallet/src/de/schildbach/wallet/ui/more/connections/AppConnectPlan.kt b/wallet/src/de/schildbach/wallet/ui/more/connections/AppConnectPlan.kt index 7289f31604..246b54be6a 100644 --- a/wallet/src/de/schildbach/wallet/ui/more/connections/AppConnectPlan.kt +++ b/wallet/src/de/schildbach/wallet/ui/more/connections/AppConnectPlan.kt @@ -21,7 +21,13 @@ internal object AppConnectLimits { fun clamp(grant: AuthBinding, blockTime: Long, requireUsableExpiry: Boolean = true): AuthBinding = grant.copy( totalBudget = grant.totalBudget?.min(MAX_BUDGET), expiresAt = minOf(grant.expiresAt ?: (blockTime + 90 * DAY), blockTime + MAX_LIFETIME) - ).also { require(!requireUsableExpiry || it.expiresAt!! > blockTime + MIN_LIFETIME) { "Requested grant expires too soon" } } + ).also { if (requireUsableExpiry) requireUsableExpiry(it, blockTime) } + + /** The grant's own expiry, not one it will be replaced with, must outlast [MIN_LIFETIME]. */ + fun requireUsableExpiry(grant: AuthBinding, blockTime: Long) { + val expiresAt = grant.expiresAt + require(expiresAt != null && expiresAt > blockTime + MIN_LIFETIME) { "Requested grant expires too soon" } + } } /** The immutable terms presented for explicit consent. No private keys are kept here. */ diff --git a/wallet/src/de/schildbach/wallet/ui/more/connections/AppConnectSession.kt b/wallet/src/de/schildbach/wallet/ui/more/connections/AppConnectSession.kt index eba3a86c9d..2652f9b5ba 100644 --- a/wallet/src/de/schildbach/wallet/ui/more/connections/AppConnectSession.kt +++ b/wallet/src/de/schildbach/wallet/ui/more/connections/AppConnectSession.kt @@ -39,6 +39,17 @@ import de.schildbach.wallet.ui.more.connections.AppConnectKeyState.live import de.schildbach.wallet.ui.more.connections.AppConnectKeyState.sameKey import de.schildbach.wallet.ui.more.connections.AppConnectKeyState.sameKeyIdentity +/** + * The network and wallet part of a connection scope, `network:devnet:watching-key hash`. A record whose + * scope starts with it and a `:` was written by this wallet (or a restore of its seed), whichever identity + * it then held. + */ +internal fun connectWalletScope(wallet: org.bitcoinj.wallet.Wallet): String { + val network = Constants.NETWORK_PARAMETERS + val devnet = if (network.id == NetworkParameters.ID_DEVNET) network.devNetName else "" + return "${network.id}:$devnet:${Sha256Hash.of(wallet.watchingKey.pubKey)}" +} + /** One-QR, PV14 grant lifecycle. The mutex covers approval, recovery and revocation. */ internal class AppConnectSession( private val service: PlatformService, @@ -63,9 +74,7 @@ internal class AppConnectSession( fun scope(): String { val wallet = walletRepo.walletApplication.wallet ?: error("Wallet unavailable") - val network = Constants.NETWORK_PARAMETERS - val devnet = if (network.id == NetworkParameters.ID_DEVNET) network.devNetName else "" - return "${network.id}:$devnet:${Sha256Hash.of(wallet.watchingKey.pubKey)}:${identityId()}" + return "${connectWalletScope(wallet)}:${identityId()}" } private fun identityId() = identities.blockchainIdentity?.uniqueIdentifier ?: error("Identity unavailable") @@ -199,15 +208,16 @@ internal class AppConnectSession( val prior = config.getGrants().firstOrNull { it.getString("id") == "$scope:${requestHash(request)}" } val selectedAuth = prior?.let { indices(it, "authIndices") } ?: parsed.auth.indices.toSet() check(0 in selectedAuth && selectedAuth.all { it in parsed.auth.indices }) { "Stored grant does not match request" } - var grants = parsed.auth.mapIndexed { index, grant -> - AppConnectLimits.clamp(grant, blockTime, requireUsableExpiry = index in selectedAuth) - } - if (prior != null) { - val saved = decodeKeys(prior).filter { it.purpose == Purpose.AUTHENTICATION } - check(saved.size == selectedAuth.size) { "Stored grant does not match request" } - grants = grants.mapIndexed { index, grant -> - val position = selectedAuth.sorted().indexOf(index) - if (position < 0) grant else grant.copy(totalBudget = saved[position].totalBudget, expiresAt = saved[position].expiresAt) + val saved = prior?.let { record -> decodeKeys(record).filter { it.purpose == Purpose.AUTHENTICATION } } + check(saved == null || saved.size == selectedAuth.size) { "Stored grant does not match request" } + // The approved limits replace the QR's before the expiry check, so it judges the expiry that will be used. + val grants = parsed.auth.mapIndexed { index, grant -> + val position = selectedAuth.sorted().indexOf(index) + if (saved == null || position < 0) { + AppConnectLimits.clamp(grant, blockTime, requireUsableExpiry = index in selectedAuth) + } else { + grant.copy(totalBudget = saved[position].totalBudget, expiresAt = saved[position].expiresAt) + .also { AppConnectLimits.requireUsableExpiry(it, blockTime) } } } val groupScopes = validateOwnership(request, grants) diff --git a/wallet/src/de/schildbach/wallet/ui/more/connections/ConnectIdentityAvailability.kt b/wallet/src/de/schildbach/wallet/ui/more/connections/ConnectIdentityAvailability.kt index 5a01b82e4f..53252ff4c2 100644 --- a/wallet/src/de/schildbach/wallet/ui/more/connections/ConnectIdentityAvailability.kt +++ b/wallet/src/de/schildbach/wallet/ui/more/connections/ConnectIdentityAvailability.kt @@ -24,14 +24,20 @@ class ConnectIdentityAvailability @Inject constructor( private val connections: DashConnectConfig, private val walletData: WalletData ) { + /** + * Retained records count only for the wallet that wrote them: a wiped wallet's grants stay on disk for + * a restore of its seed, and must not make a new wallet without a username look connected. + */ fun observe(): Flow = combine( identities.initializationResult, identities.blockchainIdentityFlow, - identityConfig.observeIdentityPresence(), connections.observeHasRecords() - ) { initialized, identity, persistedIdentity, hasRecords -> + identityConfig.observeIdentityPresence(), connections.observeRetainedRecords() + ) { initialized, identity, persistedIdentity, records -> + val wallet = walletData.wallet val status = when { initialized == null -> ConnectIdentityStatus.LOADING - initialized.isFailure || walletData.wallet == null -> ConnectIdentityStatus.UNAVAILABLE - identity == null && !persistedIdentity && !hasRecords -> ConnectIdentityStatus.NO_IDENTITY + initialized.isFailure || wallet == null -> ConnectIdentityStatus.UNAVAILABLE + identity == null && !persistedIdentity && !records.belongTo(connectWalletScope(wallet)) -> + ConnectIdentityStatus.NO_IDENTITY else -> ConnectIdentityStatus.AVAILABLE } identity to status diff --git a/wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt b/wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt index 29dd159aca..65ec25297a 100644 --- a/wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt +++ b/wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt @@ -67,6 +67,18 @@ data class StoredConnection( } } +/** + * What [DashConnectConfig] retains: the scopes of its grant and purchase records, and whether it has legacy + * rows. Grants and purchase receipts outlive a wallet wipe so a restore of the same seed sees them again. + */ +data class RetainedConnectRecords(val scopes: List, val hasLegacyRows: Boolean) { + /** + * Whether any record belongs to the wallet with [walletScope] (see [connectWalletScope]). Another + * wallet's or network's records are unreachable from it. Legacy rows carry no scope; the wipe clears them. + */ + fun belongTo(walletScope: String): Boolean = hasLegacyRows || scopes.any { it.startsWith("$walletScope:") } +} + /** * DataStore-backed store of DashConnect connections, following the [BaseConfig] pattern used by * `DashPayConfig`. Connections are serialized to a single JSON-array string preference (kept small; @@ -103,12 +115,18 @@ open class DashConnectConfig @Inject constructor( // BaseConfig's empty-preferences fallback for ordinary settings. suspend fun getGrants(): List = observeGrants().first() - /** A single strict snapshot includes retained audits and legacy rows, regardless of scope. */ - fun observeHasRecords(): Flow = configContext.dataStore.data.map { preferences -> - val grants = decodeGrants(preferences[GRANTS]) + /** + * A single strict snapshot of the retained audits and legacy rows. A grant or purchase receipt without + * a scope is unreadable, not absent, and throws. + */ + fun observeRetainedRecords(): Flow = configContext.dataStore.data.map { preferences -> val connections = JSONArray(preferences[CONNECTIONS] ?: "[]") val purchases = JSONArray(preferences[PURCHASES] ?: "[]") - grants.isNotEmpty() || connections.length() > 0 || purchases.length() > 0 + RetainedConnectRecords( + decodeGrants(preferences[GRANTS]).map { it.getString("scope") } + + (0 until purchases.length()).map { purchases.getJSONObject(it).getString("scope") }, + connections.length() > 0 + ) } fun observeGrants(): Flow> = configContext.dataStore.data.map { preferences -> diff --git a/wallet/src/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUri.kt b/wallet/src/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUri.kt index f8952b1edc..806d91ad9a 100644 --- a/wallet/src/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUri.kt +++ b/wallet/src/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUri.kt @@ -34,8 +34,12 @@ enum class DashConnectNetwork(val code: String) { } } -/** Thrown when a scanned QR is not a well-formed DashConnect URI, or fails validation. */ -class DashConnectUriException(message: String, cause: Throwable? = null) : Exception(message, cause) +/** + * Thrown when a scanned QR is not a well-formed DashConnect URI, or fails validation. It carries no + * cause: a parser exception's message can quote the link, including callback tokens, and this one is + * logged with its whole chain. + */ +class DashConnectUriException(message: String) : Exception(message) data class DashStRequest(val transitionBytes: ByteArray, val network: DashConnectNetwork) @@ -179,7 +183,7 @@ object DashConnectUri { ) return AppConnectParser.parse(body, network, query["cb"]) } catch (e: DashConnectUriException) { throw e } - catch (e: Exception) { throw DashConnectUriException("Invalid connection request", e) } + catch (e: Exception) { throw DashConnectUriException("Invalid connection request") } } /** diff --git a/wallet/test/de/schildbach/wallet/ui/more/connections/AppConnectOwnershipTest.kt b/wallet/test/de/schildbach/wallet/ui/more/connections/AppConnectOwnershipTest.kt index 069817e997..dfb5583d49 100644 --- a/wallet/test/de/schildbach/wallet/ui/more/connections/AppConnectOwnershipTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/more/connections/AppConnectOwnershipTest.kt @@ -182,13 +182,50 @@ class AppConnectOwnershipTest { restarted.requireMatches(bounded) } record.put("authIndices", org.json.JSONArray(listOf(0, 1))) - assertThrows(IllegalArgumentException::class.java) { runBlocking { session.prepare(bounded) } } + val mismatch = assertThrows(IllegalStateException::class.java) { runBlocking { session.prepare(bounded) } } + assertEquals("Stored grant does not match request", mismatch.message) + // A restored second grant is held to its own approved expiry, here as short as the QR's. + record.put("keys", org.json.JSONArray().put(org.json.JSONObject(key.toJSON())) + .put(org.json.JSONObject(savedKey(5, approved.id, start + 65L * 60_000).toJSON()))) + val short = assertThrows(IllegalArgumentException::class.java) { runBlocking { session.prepare(bounded) } } + assertEquals("Requested grant expires too soon", short.message) coEvery { config.getGrants() } returns emptyList() assertThrows(IllegalArgumentException::class.java) { runBlocking { session.prepare(bounded) } } coVerify(exactly = 0) { repo.getWalletSeed() } coVerify(exactly = 0) { config.saveGrant(any()) } } + private fun savedKey(id: Int, bound: ByteArray, expiresAt: Long) = org.dashj.platform.dpp.identity.IdentityPublicKey(id, + org.dashj.platform.sdk.KeyType.ECDSA_HASH160, org.dashj.platform.sdk.Purpose.AUTHENTICATION, + org.dashj.platform.sdk.SecurityLevel.HIGH, org.dashj.platform.dpp.identity.SingleContractBounds(Identifier.from(bound)), + ByteArray(20), false, totalBudget = java.math.BigInteger.ONE, expiresAt = expiresAt, version = 1) + + @Test fun `a retry checks the approved expiry, not the QR expiry it replaces`() = runBlocking { + val start = System.currentTimeMillis() + val raw = request.requireAppConnect() + fun withQrExpiry(expiresAt: Long) = request.copy(appConnect = raw.copy(auth = listOf(raw.auth[0].copy(expiresAt = expiresAt)))) + every { service.platform.client.getPlatformTime(any()) } returns start + val prepared = session.prepare(withQrExpiry(start + 90L * 86_400_000)) + val record = org.json.JSONObject().put("id", "${prepared.scope}:${prepared.requestHash}").put("state", "pending") + .put("authIndices", org.json.JSONArray(listOf(0))).put("encIndices", org.json.JSONArray()) + coEvery { config.getGrants() } returns listOf(record) + // The user approved a day, longer than the QR asked for, so the QR's expiry is now too close. + every { service.platform.client.getPlatformTime(any()) } returns start + 6L * 60_000 + record.put("keys", org.json.JSONArray().put(org.json.JSONObject(savedKey(4, raw.auth[0].id, start + 86_400_000).toJSON()))) + val shortQr = withQrExpiry(start + 65L * 60_000) + val restarted = session.prepare(shortQr) + assertTrue(restarted.recovering) + assertEquals(start + 86_400_000, restarted.grants[0].expiresAt) + restarted.requireMatches(shortQr) + // The approved expiry is about to lapse, so the QR's long one cannot carry the retry. + record.put("keys", org.json.JSONArray().put(org.json.JSONObject(savedKey(4, raw.auth[0].id, start + 65L * 60_000).toJSON()))) + val error = assertThrows(IllegalArgumentException::class.java) { + runBlocking { session.prepare(withQrExpiry(start + 90L * 86_400_000)) } + } + assertEquals("Requested grant expires too soon", error.message) + coVerify(exactly = 0) { config.saveGrant(any()) } + } + @Test fun `legacy preparation and approval retries fail before any identity or signing access`() { val legacy = request.copy(appConnect = null) val plan = AppConnectPlan("hash", "scope", "identity", request.requireAppConnect().auth, "Consent") diff --git a/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectIdentityAvailabilityTest.kt b/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectIdentityAvailabilityTest.kt index 8db72e8db8..1a087a1dcc 100644 --- a/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectIdentityAvailabilityTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectIdentityAvailabilityTest.kt @@ -11,6 +11,7 @@ import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout +import org.bitcoinj.core.NetworkParameters import org.dash.wallet.common.WalletDataProvider import org.dashj.platform.dashpay.BlockchainIdentity import org.json.JSONObject @@ -34,10 +35,16 @@ class ConnectIdentityAvailabilityTest { private val wallet = mockk(relaxed = true) private val walletProvider = mockk(relaxed = true) + private var watchingKey = ByteArray(33) { 1 } + private val dashjWallet = mockk(relaxed = true) + /** The current wallet's scope, as [AppConnectSession.scope] writes it, with an identity. */ + private val ownScope get() = "${connectWalletScope(dashjWallet)}:identity" + init { every { identities.initializationResult } returns initialized every { identities.blockchainIdentityFlow } returns identity - every { wallet.wallet } returns mockk(relaxed = true) + every { dashjWallet.watchingKey.pubKey } answers { watchingKey } + every { wallet.wallet } returns dashjWallet } private inner class Fixture(files: File = temporaryFolder.newFolder()) { @@ -67,7 +74,7 @@ class ConnectIdentityAvailabilityTest { val fixture = Fixture() every { wallet.wallet } returns null assertEquals(ConnectIdentityStatus.UNAVAILABLE, fixture.status()) - every { wallet.wallet } returns mockk(relaxed = true) + every { wallet.wallet } returns dashjWallet identity.value = mockk(relaxed = true) assertEquals(ConnectIdentityStatus.AVAILABLE, fixture.status()) } @@ -80,16 +87,52 @@ class ConnectIdentityAvailabilityTest { @Test fun `grant legacy and purchase audits independently retain recovery access`() = runBlocking { val grant = Fixture() - grant.audits.saveGrant(JSONObject().put("id", "restored-grant")) + grant.audits.saveGrant(JSONObject().put("id", "restored-grant").put("scope", ownScope)) assertEquals(ConnectIdentityStatus.AVAILABLE, grant.status()) val legacy = Fixture() legacy.audits.upsertConnection(StoredConnection("app", "Old", "", "approved", 1)) assertEquals(ConnectIdentityStatus.AVAILABLE, legacy.status()) val purchase = Fixture() - purchase.audits.savePurchase(JSONObject().put("id", "uncertain-purchase")) + purchase.audits.savePurchase(JSONObject().put("id", "uncertain-purchase").put("scope", ownScope)) assertEquals(ConnectIdentityStatus.AVAILABLE, purchase.status()) } + @Test fun `a wiped wallet's retained records do not make a new wallet look connected`() = runBlocking { + val fixture = Fixture() + val wipedScope = ownScope + fixture.audits.saveGrant(JSONObject().put("id", "$wipedScope:grant").put("scope", wipedScope)) + fixture.audits.savePurchase(JSONObject().put("id", "$wipedScope:purchase").put("scope", wipedScope)) + // A new seed after the wipe: the records are kept for a restore, but are not this wallet's. + watchingKey = ByteArray(33) { 2 } + assertEquals(ConnectIdentityStatus.NO_IDENTITY, fixture.status()) + // A scope that only extends this wallet's hash is another wallet's too. + val newScope = connectWalletScope(dashjWallet) + fixture.audits.saveGrant(JSONObject().put("id", "prefix").put("scope", "${newScope}0:identity")) + assertEquals(ConnectIdentityStatus.NO_IDENTITY, fixture.status()) + // Restoring the wiped seed makes them count again. + watchingKey = ByteArray(33) { 1 } + assertEquals(ConnectIdentityStatus.AVAILABLE, fixture.status()) + } + + @Test fun `the same wallet's records on another network do not count`() = runBlocking { + val fixture = Fixture() + val current = de.schildbach.wallet.Constants.NETWORK_PARAMETERS.id + val other = if (current == NetworkParameters.ID_MAINNET) NetworkParameters.ID_TESTNET else NetworkParameters.ID_MAINNET + assertTrue(ownScope.startsWith("$current:")) + val otherNetwork = "$other:${ownScope.removePrefix("$current:")}" + fixture.audits.saveGrant(JSONObject().put("id", "grant").put("scope", otherNetwork)) + assertEquals(ConnectIdentityStatus.NO_IDENTITY, fixture.status()) + } + + @Test fun `a retained record without a scope is unreadable, not another wallet's`() = runBlocking { + val grant = Fixture() + grant.audits.saveGrant(JSONObject().put("id", "unscoped")) + assertEquals(ConnectIdentityStatus.UNAVAILABLE, grant.status()) + val purchase = Fixture() + purchase.audits.savePurchase(JSONObject().put("id", "unscoped")) + assertEquals(ConnectIdentityStatus.UNAVAILABLE, purchase.status()) + } + @Test fun `incomplete registration metadata cannot be declared absent`() = runBlocking { val fixture = Fixture() fixture.identityConfig.set(BlockchainIdentityConfig.CREATION_STATE, "NONE") diff --git a/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectionDialogLockTest.kt b/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectionDialogLockTest.kt index d2bb4c1910..bb51381a78 100644 --- a/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectionDialogLockTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectionDialogLockTest.kt @@ -1,18 +1,33 @@ package de.schildbach.wallet.ui.more.connections import android.app.Application +import android.os.Looper +import android.view.View +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.semantics.SemanticsNode +import androidx.compose.ui.semantics.SemanticsOwner +import androidx.compose.ui.semantics.SemanticsProperties import androidx.fragment.app.FragmentActivity +import de.schildbach.wallet.ui.compose_views.ApproveConnectionDialog +import de.schildbach.wallet.ui.compose_views.ConnectLimitPickerDialog +import de.schildbach.wallet_test.R +import de.schildbach.wallet_test.databinding.DialogComposeContainerBinding +import io.mockk.every +import io.mockk.mockk import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.* +import org.dash.wallet.common.ui.dismissDialogsForLockScreen import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers @OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class) @@ -65,6 +80,139 @@ class ConnectionDialogLockTest { } } + /** Owns the screen's ViewModel, as ConnectionsFragment does for the approve sheet and its child sheets. */ + class ScreenHost : androidx.fragment.app.Fragment() { + lateinit var model: ConnectionsViewModel + override val defaultViewModelProviderFactory = object : androidx.lifecycle.ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") + override fun create(modelClass: Class): T = model as T + } + } + + @Test fun `the expiry date picker goes down with the approve sheet when the wallet locks`() { + val controller = Robolectric.buildActivity(FragmentActivity::class.java) + controller.get().setTheme(org.dash.wallet.common.R.style.My_Theme) + val activity = controller.setup().get() + val request = ConnectionRequest("App", "", "app", "alice", "identity", blockTime = System.currentTimeMillis()) + val screen = ScreenHost().apply { + model = io.mockk.mockk(relaxed = true) { + io.mockk.every { uiState } returns MutableStateFlow(ConnectionsUIState(pendingRequest = request)) + } + } + try { + activity.supportFragmentManager.beginTransaction().add(screen, "screen").commitNow() + // Stands in for the approve sheet, which the lock path dismisses with its child sheets. + val approveSheet = androidx.fragment.app.DialogFragment() + approveSheet.showNow(screen.childFragmentManager, "approve") + val picker = de.schildbach.wallet.ui.compose_views.ConnectLimitPickerDialog + .newInstance(de.schildbach.wallet.ui.compose_views.ConnectLimit.EXPIRATION) + picker.showNow(approveSheet.childFragmentManager, "picker") + picker.showDatePicker(request.blockTime, null) + val datePicker = checkNotNull(picker.expiryDatePicker) + assertTrue(datePicker.isShowing) + approveSheet.dismissAllowingStateLoss() + screen.childFragmentManager.executePendingTransactions() + org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle() + assertFalse(datePicker.isShowing) + assertNull(picker.expiryDatePicker) + } finally { + controller.pause().stop().destroy() + } + } + + @Test fun `locking with the expiry date picker open closes the approve sheet, its picker and the date picker`() { + val controller = Robolectric.buildActivity(FragmentActivity::class.java) + controller.get().setTheme(org.dash.wallet.common.R.style.My_Theme) + val activity = controller.setup().get() + val blockTime = System.currentTimeMillis() + // A grant with capabilities, so the approve sheet offers the funding and expiry limits. + val request = ConnectionRequest( + "App", "", "app", "alice", "identity", blockTime = blockTime, + capabilities = listOf(AppCapability(AppCapabilityKind.ACT_IN_APP)), + expiresAt = blockTime + 90 * AppConnectLimits.DAY + ) + var unlocked = true + val screen = ScreenHost().apply { + model = mockk(relaxed = true) { + every { uiState } returns MutableStateFlow(ConnectionsUIState(pendingRequest = request)) + every { approveResult } returns MutableStateFlow(ConnectionsViewModel.ApproveResult.Idle) + every { isWalletUnlocked } answers { unlocked } + } + } + try { + activity.supportFragmentManager.beginTransaction().add(screen, "screen").commitNow() + // The real approve sheet, as ConnectionsFragment shows it in its child fragment manager. + val approveSheet = ApproveConnectionDialog() + approveSheet.showNow(screen.childFragmentManager, "approve_connection_dialog") + assertTrue(approveSheet.requireDialog().isShowing) + + // The user taps Change on the Expires row of the approve sheet ... + val expiresLabel = activity.getString(R.string.dash_connect_expires) + val changeLabel = activity.getString(R.string.dash_connect_change) + val approveRoot = semanticsRoot(approveSheet) + val expires = textNodes(approveRoot, expiresLabel).single() + val changeExpiry = textNodes(approveRoot, changeLabel).single { change -> + change.boundsInRoot.top < expires.boundsInRoot.bottom && + change.boundsInRoot.bottom > expires.boundsInRoot.top + } + click(changeExpiry) + approveSheet.childFragmentManager.executePendingTransactions() + val picker = approveSheet.childFragmentManager.fragments + .filterIsInstance().single() + assertTrue(picker.requireDialog().isShowing) + + // ... then Set date in the expiry picker, which opens the date picker. + click(textNodes(semanticsRoot(picker), activity.getString(R.string.dash_connect_set_date)).single()) + val datePicker = checkNotNull(picker.expiryDatePicker) { "Set date did not open the date picker" } + assertTrue(datePicker.isShowing) + + // What LockScreenActivity does when the wallet locks. + unlocked = false + dismissDialogsForLockScreen(activity.supportFragmentManager) + screen.childFragmentManager.executePendingTransactions() + shadowOf(Looper.getMainLooper()).idle() + + assertFalse(approveSheet.dialog?.isShowing == true) + assertFalse(approveSheet.isAdded) + assertFalse(picker.dialog?.isShowing == true) + assertFalse(picker.isAdded) + assertFalse(datePicker.isShowing) + assertNull(picker.expiryDatePicker) + } finally { + controller.pause().stop().destroy() + } + } + + /** Lays out a compose sheet's content and returns its semantics root. */ + private fun semanticsRoot(sheet: androidx.fragment.app.DialogFragment): SemanticsNode { + shadowOf(Looper.getMainLooper()).idle() + val view = DialogComposeContainerBinding.bind(sheet.requireView()).composeContainer + view.measure( + View.MeasureSpec.makeMeasureSpec(1080, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(1920, View.MeasureSpec.AT_MOST) + ) + view.layout(0, 0, 1080, view.measuredHeight) + shadowOf(Looper.getMainLooper()).idle() + return ReflectionHelpers.callInstanceMethod(view.getChildAt(0), "getSemanticsOwner") + .rootSemanticsNode + } + + private fun textNodes(root: SemanticsNode, text: String): List { + fun all(node: SemanticsNode): List = listOf(node) + node.children.flatMap { all(it) } + return all(root).filter { node -> + node.config.contains(SemanticsProperties.Text) && + node.config[SemanticsProperties.Text].any { it.text == text } + } + } + + /** Invokes the click of the node, or of its nearest clickable ancestor (a button's label sits inside it). */ + private fun click(node: SemanticsNode) { + val clickable = generateSequence(node) { it.parent }.first { it.config.contains(SemanticsActions.OnClick) } + val action = checkNotNull(clickable.config[SemanticsActions.OnClick].action) { "No click action" } + assertTrue(action()) + shadowOf(Looper.getMainLooper()).idle() + } + @Test fun `details arriving after auto lock are withheld until unlock`() = runTest { Dispatchers.setMain(StandardTestDispatcher(testScheduler)) val controller = Robolectric.buildActivity(FragmentActivity::class.java) diff --git a/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectionsViewModelTest.kt b/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectionsViewModelTest.kt index 9f99897d4d..2c0050ee5a 100644 --- a/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectionsViewModelTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/more/connections/ConnectionsViewModelTest.kt @@ -64,7 +64,7 @@ class ConnectionsViewModelTest { every { identities.blockchainIdentityFlow } returns MutableStateFlow(null) every { identities.initializationResult } returns MutableStateFlow(Result.success(Unit)) every { identityConfig.observeIdentityPresence() } returns MutableStateFlow(true) - every { auditConfig.observeHasRecords() } returns MutableStateFlow(false) + every { auditConfig.observeRetainedRecords() } returns MutableStateFlow(RetainedConnectRecords(emptyList(), false)) every { walletData.wallet } returns mockk(relaxed = true) coEvery { repository.parseQr(any()) } returns DashConnectQr(request) coEvery { repository.prepareLogin(any()) } returns plan @@ -78,6 +78,11 @@ class ConnectionsViewModelTest { } @After fun teardown() { + // A test that paused the Choreographer can end with a Compose frame pending. Robolectric drops it between + // tests, and Compose's process-wide UI dispatcher, still marked as waiting for it, never schedules another + // frame: a later Compose test in this JVM would then never recompose. Run that frame now. + ShadowChoreographer.setPaused(false) + org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle() if (::model.isInitialized) model.viewModelScope.cancel() applicationScope.cancel() Constants.SUPPORTS_PLATFORM = originalSupportsPlatform @@ -532,7 +537,7 @@ class ConnectionsViewModelTest { @Test fun `saved audits without an identity remain unavailable rather than confirmed empty`() { every { identityConfig.observeIdentityPresence() } returns MutableStateFlow(false) - every { auditConfig.observeHasRecords() } returns MutableStateFlow(true) + every { auditConfig.observeRetainedRecords() } returns MutableStateFlow(RetainedConnectRecords(emptyList(), true)) every { repository.observeConnections() } returns kotlinx.coroutines.flow.flow { error("Identity unavailable") } model.refreshConnections() dispatcher.scheduler.runCurrent() diff --git a/wallet/test/de/schildbach/wallet/ui/more/connections/protocol/DashPayConnectUriTest.kt b/wallet/test/de/schildbach/wallet/ui/more/connections/protocol/DashPayConnectUriTest.kt index 7e0e610200..37c633dacd 100644 --- a/wallet/test/de/schildbach/wallet/ui/more/connections/protocol/DashPayConnectUriTest.kt +++ b/wallet/test/de/schildbach/wallet/ui/more/connections/protocol/DashPayConnectUriTest.kt @@ -189,6 +189,20 @@ class DashPayConnectUriTest { rejects(uri(query = "v=2&n=d&r=$r&cb=" + java.net.URLEncoder.encode("https://yap.pr/" + "a".repeat(512), "UTF-8"))) } + @Test fun `a rejected link never reaches the log through the exception chain`() { + // java.net.URI quotes the whole callback, token included, in its syntax error. + val token = "callback-secret-token" + val badCallback = java.net.URLEncoder.encode("https://yap.pr/connect?t=$token bad", "UTF-8") + val keyUri = fixture["uri"].asString.substringBefore("&cb=") + "&cb=$badCallback" + for (link in listOf(uri(query = "v=2&n=d&r=$r&cb=$badCallback"), keyUri)) { + val error = assertThrows(DashConnectUriException::class.java) { DashConnectUri.parseRequest(link) } + assertEquals("Invalid connection request", error.message) + assertNull(error.cause) + val logged = java.io.StringWriter().also { error.printStackTrace(java.io.PrintWriter(it)) }.toString() + assertFalse(logged, logged.contains(token)) + } + } + @Test fun `invite is not a connect link`() { val invite = "dashpay://invite?du=alice&assetlocktx=a0963d1b&pk=cNihCPEQ&islock=0101b1" assertFalse(DashConnectUri.isConnectUri(invite))