Skip to content
Open
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 @@ -5,11 +5,9 @@ import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onAllNodesWithText
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextInput
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import io.privkey.keep.ui.theme.KeepAndroidTheme
import io.privkey.keep.uniffi.CertificatePinHolds
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
Expand All @@ -18,7 +16,7 @@ import org.junit.runner.RunWith
/**
* A relay whose pin was removed stays disconnected until the user acts, so the card has to
* show it and offer the way back for each one, including the case where the core could not
* read which hosts it holds.
* read the pin records.
*/
@RunWith(AndroidJUnit4::class)
class CertificatePinHoldsCardTest {
Expand All @@ -31,14 +29,13 @@ class CertificatePinHoldsCardTest {

private val context = InstrumentationRegistry.getInstrumentation().targetContext
private val trustNext get() = context.getString(R.string.settings_cert_pins_trust_next)
private val trustHost get() = context.getString(R.string.settings_cert_pins_trust_host)
private val heldTitle get() = context.getString(R.string.settings_cert_pins_held_title)

private fun show(holds: CertificatePinHolds?, trusted: MutableList<String>) = compose.setContent {
private fun show(held: List<String>?, trusted: MutableList<String>) = compose.setContent {
KeepAndroidTheme {
CertificatePinsCard(
pins = emptyList(),
holds = holds,
held = held,
onStagePin = { _, _ -> },
onRetirePin = { _, _ -> },
onTrustNextKey = { trusted += it },
Expand All @@ -50,37 +47,28 @@ class CertificatePinHoldsCardTest {
@Test
fun eachHeldHostOffersToTrustItsNextKey() {
val trusted = mutableListOf<String>()
show(CertificatePinHolds(listOf("relay.one.com", "relay.two.com"), false, emptyList()), trusted)
show(listOf("wss://relay.one.com", "wss://relay.two.com"), trusted)

compose.onNodeWithText(heldTitle).assertIsDisplayed()
compose.onNodeWithText("relay.two.com").assertIsDisplayed()
compose.onNodeWithText("wss://relay.two.com").assertIsDisplayed()
compose.onAllNodesWithText(trustNext)[1].performClick()
assertEquals("nothing is trusted before the warning is confirmed", emptyList<String>(), trusted)
compose.onNodeWithText(context.getString(R.string.settings_cert_pins_trust_dialog_text, "relay.two.com")).assertIsDisplayed()
compose.onNodeWithText(context.getString(R.string.settings_cert_pins_trust_dialog_text, "wss://relay.two.com")).assertIsDisplayed()
compose.onAllNodesWithText(trustNext).let { it[it.fetchSemanticsNodes().size - 1] }.performClick()
assertEquals(listOf("relay.two.com"), trusted)
assertEquals(0, compose.onAllNodesWithText(trustHost).fetchSemanticsNodes().size)
assertEquals(listOf("wss://relay.two.com"), trusted)
}

@Test
fun unreadableHoldsOfferToTrustAHostByName() {
val trusted = mutableListOf<String>()
show(CertificatePinHolds(emptyList(), true, emptyList()), trusted)

compose.onNodeWithText(context.getString(R.string.settings_cert_pins_held_all_text)).assertIsDisplayed()
compose.onNodeWithText(trustHost).performClick()
compose.onNodeWithText(context.getString(R.string.settings_cert_pins_stage_host_label)).performTextInput(" relay.example.com ")
compose.onNodeWithText(trustNext).performClick()
assertEquals(emptyList<String>(), trusted)
compose.onNodeWithText(context.getString(R.string.settings_cert_pins_trust_dialog_text, "relay.example.com")).assertIsDisplayed()
compose.onNodeWithText(trustNext).performClick()
assertEquals(listOf("relay.example.com"), trusted)
fun unreadableHoldsSayTheRecordsCouldNotBeRead() {
show(null, mutableListOf())
compose.onNodeWithText(context.getString(R.string.settings_cert_pins_held_unreadable)).assertIsDisplayed()
assertEquals(0, compose.onAllNodesWithText(context.getString(R.string.settings_cert_pins_empty)).fetchSemanticsNodes().size)
}

@Test
fun cancellingTheWarningTrustsNothing() {
val trusted = mutableListOf<String>()
show(CertificatePinHolds(listOf("relay.one.com"), false, emptyList()), trusted)
show(listOf("wss://relay.one.com"), trusted)
compose.onNodeWithText(trustNext).performClick()
compose.onNodeWithText(context.getString(R.string.settings_cancel)).performClick()
assertEquals(emptyList<String>(), trusted)
Expand All @@ -90,17 +78,23 @@ class CertificatePinHoldsCardTest {
fun theMismatchDialogWarnsBeforeClearingAndTrusting() {
var cleared = 0
compose.setContent {
KeepAndroidTheme { PinMismatchDialog("relay.example.com", onClearAndRetry = { cleared++ }, onDismiss = {}) }
KeepAndroidTheme { PinMismatchDialog("relay.example.com", NEW_KEY, onClearAndRetry = { cleared++ }, onDismiss = {}) }
}
compose.onNodeWithText(context.getString(R.string.main_clear_pin_and_retry_text, "relay.example.com")).assertIsDisplayed()
compose.onNodeWithText(context.getString(R.string.main_pin_mismatch_new_key, NEW_KEY)).assertIsDisplayed()
assertEquals(0, cleared)
compose.onNodeWithText(context.getString(R.string.main_clear_pin_and_retry)).performClick()
assertEquals(1, cleared)
}

@Test
fun nothingHeldShowsNoSection() {
show(CertificatePinHolds(emptyList(), false, emptyList()), mutableListOf())
show(emptyList(), mutableListOf())
assertEquals(0, compose.onAllNodesWithText(heldTitle).fetchSemanticsNodes().size)
compose.onNodeWithText(context.getString(R.string.settings_cert_pins_empty)).assertIsDisplayed()
}

private companion object {
const val NEW_KEY = "3b2f000000000000000000000000000000000000000000000000000000000a1c"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import java.security.spec.ECGenParameterSpec
* End-to-end: the app's own approver, paired with a gateway that never answers over a
* public relay, is started again by the core after a certificate pin change. Once a
* change leaves its relay without a pin the relay is held: the restart is refused, and so
* is any start, until the user trusts the relay's next key. Manual-only, since it needs the relay: run it with `-e approverManual 1`.
* is any start, until the user trusts the relay's next key, which resumes the approver. Manual-only, since it needs the relay: run it with `-e approverManual 1`.
* The test key needs no biometric, unlike the app's approver key, and is deleted after.
*/
@RunWith(AndroidJUnit4::class)
Expand All @@ -51,8 +51,10 @@ class ApproverPinChangeE2ETest {
// The run clears every pin, so the device's own are put back after it.
val mobile = checkNotNull(app.getKeepMobile()) { "Keep not initialized" }
val devicePins = mobile.getCertificatePins()
val heldBefore = mobile.certificatePinHolds().hosts.toSet()
val relayHost = checkNotNull(URI(relay).host)
// A run that died before its cleanup leaves the relay held, which no pairing can reach.
// This is a test device's relay, so trusting its next key here is the run's own choice.
mobile.heldRelays(listOf(relay)).forEach { mobile.releaseCertificatePinHold(it) }

val secret = ByteArray(32).also(SecureRandom()::nextBytes).joinToString("") { "%02x".format(it) }
val uri = "keep-approver:v1?gateway=$GATEWAY&secret=$secret&relay=$relay"
Expand Down Expand Up @@ -82,25 +84,29 @@ class ApproverPinChangeE2ETest {
Thread.sleep(SETTLE_MS)
assertFalse("nothing started the approver on an unpinned relay", handler.status().running)

assertTrue("clearing the pin holds the relay", relayHost in mobile.certificatePinHolds().hosts)
assertEquals("clearing the pin holds the relay", listOf(relay), mobile.heldRelays(listOf(relay)))
controller.startIfPaired()
assertFalse("a start does not learn a key for a held relay", handler.status().running)

assertTrue(app.releaseCertificatePinHold(relayHost))
controller.startIfPaired()
assertTrue("a start after the user trusts the next key serves again", awaitStatus(handler) { it.running && it.pairing })
assertEquals(relayHost, app.releaseCertificatePinHold(relay))
assertTrue("the core resumes the approver the hold stopped", awaitStatus(handler) { it.running && it.pairing })
assertFalse(handler.status().paired)
assertTrue("the resumed start pinned the relay", mobile.getCertificatePins().any { it.hostname == relayHost })
} finally {
runCatching { handler.forget() }
// Clearing holds the relay, and only a pin ends that, so the key it showed goes back.
val relayPins = mobile.getCertificatePins().filter { it.hostname == relayHost }
mobile.clearCertificatePins()
devicePins.forEach { mobile.stageCertificatePin(it.hostname, it.spkiHash) }
(mobile.certificatePinHolds().hosts - heldBefore).forEach { mobile.releaseCertificatePinHold(it) }
if (devicePins.none { it.hostname == relayHost }) {
relayPins.forEach { mobile.stageCertificatePin(it.hostname, it.spkiHash) }
}
runCatching { controller.startIfPaired() }
runCatching { keyStore().deleteEntry(ALIAS) }
}
assertFalse(handler.status().running)
assertEquals(devicePins, mobile.getCertificatePins())
assertEquals(heldBefore, mobile.certificatePinHolds().hosts.toSet())
assertEquals(devicePins.toSet(), mobile.getCertificatePins().filter { it.hostname != relayHost || it in devicePins }.toSet())
assertEquals("the relay is not left held", emptyList<String>(), mobile.heldRelays(listOf(relay)))
}

// The stop lands before the pin call returns, and the restart probes the relay before it
Expand Down
56 changes: 30 additions & 26 deletions app/src/main/kotlin/io/privkey/keep/KeepMobileApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ import io.privkey.keep.uniffi.ProxyConfigInfo
import io.privkey.keep.uniffi.RelayConfigInfo
import io.privkey.keep.uniffi.SignPolicyStore
import io.privkey.keep.uniffi.SigningAuditLog
import io.privkey.keep.uniffi.CertificatePinHolds
import io.privkey.keep.uniffi.SigningRateLimiter
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
Expand All @@ -67,6 +66,7 @@ import java.util.UUID
import javax.crypto.Cipher

private const val TAG = "KeepMobileApp"
private val DEFAULT_NODE_RELAYS = listOf("wss://relay.damus.io", "wss://nos.lol", "wss://relay.primal.net")
private const val EVENT_LOG_MAX_AGE_MS = 7L * 24 * 60 * 60 * 1000

class KeepMobileApp : Application() {
Expand Down Expand Up @@ -519,9 +519,7 @@ class KeepMobileApp : Application() {
initMutex.withLock {
if (isNodeLive() && mobile.getShareInfo() != null) return

val relays = getActiveRelays().ifEmpty {
listOf("wss://relay.damus.io", "wss://nos.lol", "wss://relay.primal.net")
}
val relays = getActiveRelays().ifEmpty { DEFAULT_NODE_RELAYS }
val store = storage
withContext(initDispatcher) {
if (requestId != null && store != null) {
Expand Down Expand Up @@ -840,32 +838,38 @@ class KeepMobileApp : Application() {
.onFailure { if (BuildConfig.DEBUG) Log.e(TAG, "Failed to clearCertificatePin: ${it::class.simpleName}") }
.isSuccess

fun certificatePinHolds(): CertificatePinHolds? =
runCatching { keepMobile?.certificatePinHolds() }
.onFailure { if (BuildConfig.DEBUG) Log.e(TAG, "Failed to read certificatePinHolds: ${it::class.simpleName}") }
.getOrNull()
/**
* The node, bunker and approver relays waiting on the user for a pin, or null if unreadable.
* The candidates are gathered here until the core lists the relays it connects to itself.
* Any source that cannot be read makes the whole list unreadable rather than incomplete.
*/
fun heldRelays(): List<String>? = runCatching {
val mobile = checkNotNull(keepMobile)
val nodeRelays = mobile.getRelayConfig(storage?.getActiveShareKey()).frostRelays.ifEmpty { DEFAULT_NODE_RELAYS }
val bunkerRelays = mobile.getRelayConfig(null).bunkerRelays
val approverRelays = approverController?.handlerStatusRelays().orEmpty()
mobile.heldRelays((nodeRelays + bunkerRelays + approverRelays).distinct())
}.onFailure { if (BuildConfig.DEBUG) Log.e(TAG, "Failed to read heldRelays: ${it::class.simpleName}") }
.getOrNull()

/** Pins [spkiHash] as the host's only key, for a mismatch the user chose to accept. Gate it on the user. */
fun replaceCertificatePins(hostname: String, spkiHash: String): Boolean =
runCatching { checkNotNull(keepMobile).replaceCertificatePins(hostname, spkiHash) }
.onSuccess { onLiveNodeDropped() }
.onFailure { if (BuildConfig.DEBUG) Log.e(TAG, "Failed to replaceCertificatePins: ${it::class.simpleName}") }
.isSuccess

/**
* Lets the next connection to [hostname] trust whatever key it shows, so callers gate it
* on the user. That choice is also the start the hold waited for: a bunker serving without
* the relay and a paired approver the hold stopped start again, and the caller reconnects
* the node.
* Lets a probe of [hostname] in the next ten minutes trust whatever key it shows, so callers
* gate it on the user and reconnect right after. Returns the host the core released. The core
* resumes an approver waiting on it, but not the bunker yet, so that restart stays here.
*/
fun releaseCertificatePinHold(hostname: String): Boolean {
val released = runCatching { checkNotNull(keepMobile).releaseCertificatePinHold(hostname) }
fun releaseCertificatePinHold(hostname: String): String? =
runCatching { checkNotNull(keepMobile).releaseCertificatePinHold(hostname) }
.onFailure { if (BuildConfig.DEBUG) Log.e(TAG, "Failed to releaseCertificatePinHold: ${it::class.simpleName}") }
.isSuccess
if (!released) return false
io.privkey.keep.nip46.BunkerService.restartAfterNodeDrop()
approverController?.let { controller ->
applicationScope.launch(Dispatchers.IO) {
runCatching { controller.startIfPaired() }.onFailure {
if (BuildConfig.DEBUG) Log.e(TAG, "Failed to start approver: ${it::class.simpleName}")
}
}
}
return true
}
.getOrNull()
// The core drops the node when it uses the host; this also restarts the bunker.
?.also { onLiveNodeDropped() }

fun clearAllCertificatePins() {
runCatching { keepMobile?.clearCertificatePins() }
Expand Down
Loading