Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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()
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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")
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ConnectIdentityStatus> = 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>, 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;
Expand Down Expand Up @@ -103,12 +115,18 @@ open class DashConnectConfig @Inject constructor(
// BaseConfig's empty-preferences fallback for ordinary settings.
suspend fun getGrants(): List<JSONObject> = observeGrants().first()

/** A single strict snapshot includes retained audits and legacy rows, regardless of scope. */
fun observeHasRecords(): Flow<Boolean> = 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<RetainedConnectRecords> = 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<List<JSONObject>> = configContext.dataStore.data.map { preferences ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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") }
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading
Loading