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
@@ -0,0 +1,106 @@
package io.privkey.keep

import androidx.compose.ui.test.assertIsDisplayed
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
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.
*/
@RunWith(AndroidJUnit4::class)
class CertificatePinHoldsCardTest {

// createComposeRule() is deprecated in favor of the v2 API; the classic rule
// is intentional here, and the project builds with -Werror.
@Suppress("DEPRECATION")
@get:Rule
val compose = createComposeRule()

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 {
KeepAndroidTheme {
CertificatePinsCard(
pins = emptyList(),
holds = holds,
onStagePin = { _, _ -> },
onRetirePin = { _, _ -> },
onTrustNextKey = { trusted += it },
onClearAllPins = {},
)
}
}

@Test
fun eachHeldHostOffersToTrustItsNextKey() {
val trusted = mutableListOf<String>()
show(CertificatePinHolds(listOf("relay.one.com", "relay.two.com"), false, emptyList()), trusted)

compose.onNodeWithText(heldTitle).assertIsDisplayed()
compose.onNodeWithText("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.onAllNodesWithText(trustNext).let { it[it.fetchSemanticsNodes().size - 1] }.performClick()
assertEquals(listOf("relay.two.com"), trusted)
assertEquals(0, compose.onAllNodesWithText(trustHost).fetchSemanticsNodes().size)
}

@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)
}

@Test
fun cancellingTheWarningTrustsNothing() {
val trusted = mutableListOf<String>()
show(CertificatePinHolds(listOf("relay.one.com"), false, emptyList()), trusted)
compose.onNodeWithText(trustNext).performClick()
compose.onNodeWithText(context.getString(R.string.settings_cancel)).performClick()
assertEquals(emptyList<String>(), trusted)
}

@Test
fun theMismatchDialogWarnsBeforeClearingAndTrusting() {
var cleared = 0
compose.setContent {
KeepAndroidTheme { PinMismatchDialog("relay.example.com", onClearAndRetry = { cleared++ }, onDismiss = {}) }
}
compose.onNodeWithText(context.getString(R.string.main_clear_pin_and_retry_text, "relay.example.com")).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())
assertEquals(0, compose.onAllNodesWithText(heldTitle).fetchSemanticsNodes().size)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import org.junit.runner.RunWith
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.PrivateKey
import java.net.URI
import java.security.SecureRandom
import java.security.Signature
import java.security.interfaces.ECPublicKey
Expand All @@ -26,9 +27,8 @@ 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 restart is refused, and nothing in this
* process starts it either, since a start would trust whatever key the relay shows; only
* a start by hand does. Manual-only, since it needs the relay: run it with `-e approverManual 1`.
* 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`.
* The test key needs no biometric, unlike the app's approver key, and is deleted after.
*/
@RunWith(AndroidJUnit4::class)
Expand All @@ -51,6 +51,8 @@ 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)

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 @@ -80,18 +82,25 @@ 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)
controller.startIfPaired()
assertTrue("a start by hand serves again", awaitStatus(handler) { it.running && it.pairing })
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 })
assertFalse(handler.status().paired)
} finally {
runCatching { handler.forget() }
mobile.clearCertificatePins()
devicePins.forEach { mobile.stageCertificatePin(it.hostname, it.spkiHash) }
(mobile.certificatePinHolds().hosts - heldBefore).forEach { mobile.releaseCertificatePinHold(it) }
runCatching { controller.startIfPaired() }
runCatching { keyStore().deleteEntry(ALIAS) }
}
assertFalse(handler.status().running)
assertEquals(devicePins, mobile.getCertificatePins())
assertEquals(heldBefore, mobile.certificatePinHolds().hosts.toSet())
}

// The stop lands before the pin call returns, and the restart probes the relay before it
Expand Down
34 changes: 31 additions & 3 deletions app/src/main/kotlin/io/privkey/keep/KeepMobileApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ 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 Down Expand Up @@ -833,10 +834,37 @@ class KeepMobileApp : Application() {
onLiveNodeDropped()
}

fun clearCertificatePin(hostname: String) {
runCatching { keepMobile?.clearCertificatePin(hostname) }
.onSuccess { if (it != null) onLiveNodeDropped() }
fun clearCertificatePin(hostname: String): Boolean =
runCatching { checkNotNull(keepMobile).clearCertificatePin(hostname) }
.onSuccess { onLiveNodeDropped() }
.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()

/**
* 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.
*/
fun releaseCertificatePinHold(hostname: String): Boolean {
val released = 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
}

fun clearAllCertificatePins() {
Expand Down
Loading