mirror of
https://github.com/Monkopedia/rouse-context.git
synced 2026-11-24 22:37:45 +00:00
Stop AddIntegrationDestination swallowing cancellation (#662)
#660 made CertProvisioningFlow.execute propagate CancellationException instead of reporting StorageFailed. AddIntegrationDestination's bare `catch (_: Exception)` converted it straight back, one frame above that guard -- the same shape #616 found on #615. The comment was the tell: "best-effort; integrationSetup will retry" is an argument about a provisioning FAILURE, not about cancellation. A cancelled screen is gone and will not retry. The launch body is extracted to `provisionCertsInBackground` so the contract is unit-testable, and a CancellationException rethrow goes above the broad catch (matching SessionHandler:185/:221 and CertProvisioningFlow's own #646 guard). Both directions are pinned: cancellation propagates, an ordinary provisioning failure stays silent. Also records why OnboardingFlow's storeSubdomain/storeIntegrationSecrets pair is safe without a cancellation rollback. That safety is a property of FileCertificateStore in another module (non-suspend atomicWrite, no withContext), and OnboardingFlow does not self-heal -- its onboarded gate is `getSubdomain() != null`, so nothing repairs "subdomain present, secrets absent". OnboardingHalfWriteWindowTest pins the property so an ordinary move of atomicWrite to Dispatchers.IO fails loudly instead of silently opening the window. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
This commit is contained in:
parent
e4e27434d6
commit
fd92a1c2d6
4 changed files with 296 additions and 8 deletions
|
|
@ -16,6 +16,7 @@ import com.rousecontext.app.ui.navigation.Routes
|
|||
import com.rousecontext.app.ui.screens.AddIntegrationPickerContent
|
||||
import com.rousecontext.app.ui.viewmodels.AddIntegrationViewModel
|
||||
import com.rousecontext.tunnel.CertProvisioningFlow
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
|
|
@ -56,14 +57,7 @@ fun NavGraphBuilder.addIntegrationDestination(navController: NavController) {
|
|||
// user configures the integration. Survives navigation
|
||||
// since it uses the app-scoped coroutine scope.
|
||||
appScope.launch {
|
||||
try {
|
||||
val credential = credentialProvider.forProvisioning()
|
||||
if (credential != null) {
|
||||
certProvisioningFlow.execute(credential)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Best-effort; integrationSetup will retry
|
||||
}
|
||||
provisionCertsInBackground(credentialProvider, certProvisioningFlow)
|
||||
}
|
||||
navController.navigate(setupRouteForIntegration(id))
|
||||
}
|
||||
|
|
@ -71,3 +65,31 @@ fun NavGraphBuilder.addIntegrationDestination(navController: NavController) {
|
|||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort background cert provisioning kicked off when the user picks an
|
||||
* integration. Extracted from the destination so the cancellation/failure
|
||||
* contract is unit-testable.
|
||||
*/
|
||||
internal suspend fun provisionCertsInBackground(
|
||||
credentialProvider: DeviceCredentialProvider,
|
||||
certProvisioningFlow: CertProvisioningFlow
|
||||
) {
|
||||
try {
|
||||
val credential = credentialProvider.forProvisioning()
|
||||
if (credential != null) {
|
||||
certProvisioningFlow.execute(credential)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
// MUST stay above the broad catch (issue #662). #660 made
|
||||
// CertProvisioningFlow.execute propagate cancellation instead of
|
||||
// reporting StorageFailed; a bare `catch (Exception)` here converts it
|
||||
// straight back one frame above the fix. "integrationSetup will retry"
|
||||
// is an argument about a provisioning FAILURE -- it is not an argument
|
||||
// about cancellation, because a cancelled screen is gone and will not
|
||||
// retry.
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// Best-effort; integrationSetup will retry
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,70 @@
|
|||
package com.rousecontext.app.cert
|
||||
|
||||
import android.app.Application
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* Issue #662: pins the property that makes `OnboardingFlow`'s two-write
|
||||
* sequence (`storeSubdomain` then `storeIntegrationSecrets`) safe to run
|
||||
* without a cancellation rollback.
|
||||
*
|
||||
* Both methods are declared `suspend` on `CertificateStore`, but
|
||||
* [FileCertificateStore] delegates them to a non-suspend `atomicWrite` and has
|
||||
* no `withContext` anywhere, so there is no suspension point *between* the two
|
||||
* writes and therefore no way for cancellation to land between them.
|
||||
*
|
||||
* That safety lives in this file, while the code that depends on it lives in
|
||||
* `OnboardingFlow` (`:core:tunnel`) -- and `OnboardingFlow` does not self-heal:
|
||||
* its onboarded gate is `getSubdomain() != null`, so a device with a subdomain
|
||||
* and no secrets stays that way. Moving `atomicWrite` onto `Dispatchers.IO`
|
||||
* would be an entirely ordinary refactor that silently opens that window, so
|
||||
* this test fails if it happens.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], application = com.rousecontext.app.TestApplication::class)
|
||||
class OnboardingHalfWriteWindowTest {
|
||||
|
||||
@Test
|
||||
fun `an already-cancelled caller still lands both onboarding writes`() = runBlocking {
|
||||
val store = FileCertificateStore(ApplicationProvider.getApplicationContext<Application>())
|
||||
val secrets = mapOf("health" to "brisk-health")
|
||||
var reachedEnd = false
|
||||
|
||||
val scope = CoroutineScope(Job())
|
||||
val job = scope.launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
// Cancel ourselves before the pair runs. Cancellation is only
|
||||
// *delivered* at a real suspension point, so with a non-suspend
|
||||
// atomicWrite both writes must still complete. If either store
|
||||
// method gains one (a `withContext`, a `delay`, an actual async
|
||||
// hop), the first write throws here and the second never happens --
|
||||
// exactly the half-onboarded state OnboardingFlow cannot repair.
|
||||
coroutineContext.cancel()
|
||||
store.storeSubdomain("device")
|
||||
store.storeIntegrationSecrets(secrets)
|
||||
reachedEnd = true
|
||||
}
|
||||
job.join()
|
||||
|
||||
assertTrue(
|
||||
"OnboardingFlow's store sequence no longer runs to completion under " +
|
||||
"cancellation: FileCertificateStore gained a suspension point. " +
|
||||
"Wrap the pair in withContext(NonCancellable) or add a repair " +
|
||||
"path for 'subdomain present, secrets absent' (see #662).",
|
||||
reachedEnd
|
||||
)
|
||||
assertEquals("device", store.getSubdomain())
|
||||
assertEquals(secrets, store.getIntegrationSecrets())
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
package com.rousecontext.app.ui.navigation.destinations
|
||||
|
||||
import com.rousecontext.app.auth.DeviceCredentialProvider
|
||||
import com.rousecontext.tunnel.CertProvisioningFlow
|
||||
import com.rousecontext.tunnel.CertificateStore
|
||||
import com.rousecontext.tunnel.CsrGenerator
|
||||
import com.rousecontext.tunnel.DeviceCredential
|
||||
import com.rousecontext.tunnel.DeviceKeyManager
|
||||
import com.rousecontext.tunnel.RelayApiClient
|
||||
import java.io.IOException
|
||||
import java.security.KeyPair
|
||||
import java.security.KeyPairGenerator
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.cancelChildren
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Issue #662: `AddIntegrationDestination` kicks off cert provisioning with a
|
||||
* bare `catch (_: Exception)`. That catch was written for a *provisioning
|
||||
* failure* ("best-effort; integrationSetup will retry") but it also swallows
|
||||
* coroutine cancellation, undoing the guard #660 added one frame below in
|
||||
* [CertProvisioningFlow.execute] -- the same shape #616 found on #615.
|
||||
*
|
||||
* Both directions are pinned here, because the careless fix (widening the
|
||||
* rethrow) breaks the second one:
|
||||
* - cancellation while `execute` is suspended must PROPAGATE;
|
||||
* - an ordinary provisioning failure must stay best-effort and SILENT.
|
||||
*/
|
||||
class AddIntegrationProvisioningTest {
|
||||
|
||||
// --- direction 1: cancellation propagates -------------------------------
|
||||
|
||||
@Test
|
||||
fun `cancellation during cert provisioning propagates out of the destination`() = runBlocking {
|
||||
val suspended = CompletableDeferred<Unit>()
|
||||
val outcome = CompletableDeferred<String>()
|
||||
// getCertificate() is the first suspend call inside
|
||||
// CertProvisioningFlow.execute; parking there puts the cancellation
|
||||
// squarely inside the call the destination wraps.
|
||||
val flow = certProvisioningFlow(
|
||||
ParkingCertStore(parked = suspended, release = CompletableDeferred())
|
||||
)
|
||||
|
||||
val job = launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
try {
|
||||
provisionCertsInBackground(StubCredentialProvider(CREDENTIAL), flow)
|
||||
outcome.complete("returned normally (cancellation swallowed)")
|
||||
} catch (e: CancellationException) {
|
||||
outcome.complete("threw CancellationException")
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
suspended.await()
|
||||
job.cancel()
|
||||
job.join()
|
||||
|
||||
assertEquals("threw CancellationException", outcome.await())
|
||||
coroutineContext.cancelChildren()
|
||||
}
|
||||
|
||||
// --- direction 2: ordinary failure stays best-effort --------------------
|
||||
|
||||
@Test
|
||||
fun `provisioning failure is swallowed`() = runBlocking {
|
||||
val flow = certProvisioningFlow(ThrowingCertStore(RuntimeException("relay exploded")))
|
||||
// Must not throw: the destination has no error surface for this.
|
||||
provisionCertsInBackground(StubCredentialProvider(CREDENTIAL), flow)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `credential provider failure is swallowed`() = runBlocking {
|
||||
val flow = certProvisioningFlow(ThrowingCertStore(RuntimeException("unreached")))
|
||||
provisionCertsInBackground(FailingCredentialProvider(), flow)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `null credential skips provisioning`() = runBlocking {
|
||||
val store = ThrowingCertStore(RuntimeException("must not be reached"))
|
||||
provisionCertsInBackground(StubCredentialProvider(null), certProvisioningFlow(store))
|
||||
assertEquals(0, store.reads)
|
||||
}
|
||||
|
||||
// --- fixtures ------------------------------------------------------------
|
||||
|
||||
private fun certProvisioningFlow(store: CertificateStore) = CertProvisioningFlow(
|
||||
csrGenerator = CsrGenerator(),
|
||||
relayApiClient = RelayApiClient(baseUrl = "http://localhost:1"),
|
||||
certificateStore = store,
|
||||
deviceKeyManager = StubDeviceKeyManager()
|
||||
)
|
||||
|
||||
private class StubCredentialProvider(private val credential: DeviceCredential?) :
|
||||
DeviceCredentialProvider {
|
||||
override suspend fun forRegistration(): DeviceCredential? = credential
|
||||
override suspend fun forProvisioning(): DeviceCredential? = credential
|
||||
}
|
||||
|
||||
private class FailingCredentialProvider : DeviceCredentialProvider {
|
||||
override suspend fun forRegistration(): DeviceCredential? =
|
||||
throw IOException("no credential")
|
||||
|
||||
override suspend fun forProvisioning(): DeviceCredential? =
|
||||
throw IOException("no credential")
|
||||
}
|
||||
|
||||
private class StubDeviceKeyManager : DeviceKeyManager {
|
||||
override fun getOrCreateKeyPair(): KeyPair = KEY_PAIR
|
||||
}
|
||||
|
||||
/** Parks forever in [getCertificate] so the test can cancel mid-`execute`. */
|
||||
private class ParkingCertStore(
|
||||
private val parked: CompletableDeferred<Unit>,
|
||||
private val release: CompletableDeferred<Unit>
|
||||
) : NoopCertStore() {
|
||||
override suspend fun getCertificate(): String? {
|
||||
parked.complete(Unit)
|
||||
release.await()
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Fails the very first read, exercising the ordinary-failure path. */
|
||||
private class ThrowingCertStore(private val cause: RuntimeException) : NoopCertStore() {
|
||||
var reads = 0
|
||||
private set
|
||||
|
||||
override suspend fun getCertificate(): String? {
|
||||
reads++
|
||||
throw cause
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val KEY_PAIR: KeyPair = KeyPairGenerator.getInstance("EC")
|
||||
.apply { initialize(256) }
|
||||
.generateKeyPair()
|
||||
val CREDENTIAL: DeviceCredential = DeviceCredential.Firebase("test-id-token")
|
||||
}
|
||||
}
|
||||
|
||||
private open class NoopCertStore : CertificateStore {
|
||||
override suspend fun storeCertificate(pemChain: String) = Unit
|
||||
override suspend fun getCertificate(): String? = null
|
||||
override suspend fun storeClientCertificate(pemChain: String) = Unit
|
||||
override suspend fun getClientCertificate(): String? = null
|
||||
override suspend fun storeRelayCaCert(pem: String) = Unit
|
||||
override suspend fun getRelayCaCert(): String? = null
|
||||
override suspend fun storeSubdomain(subdomain: String) = Unit
|
||||
override suspend fun getSubdomain(): String? = "device"
|
||||
override suspend fun storeIntegrationSecrets(secrets: Map<String, String>) = Unit
|
||||
override suspend fun getIntegrationSecrets(): Map<String, String>? = null
|
||||
override suspend fun getCertChain(): List<ByteArray>? = null
|
||||
override suspend fun getPrivateKeyBytes(): ByteArray? = null
|
||||
override suspend fun storeCertChain(chain: List<ByteArray>) = Unit
|
||||
override suspend fun getCertExpiry(): Long? = null
|
||||
override suspend fun getKnownFingerprints(): Set<String> = emptySet()
|
||||
override suspend fun storeFingerprint(fingerprint: String) = Unit
|
||||
override suspend fun hasFingerprintBootstrapMarker(): Boolean = false
|
||||
override suspend fun writeFingerprintBootstrapMarker() = Unit
|
||||
override suspend fun clear() = Unit
|
||||
override suspend fun clearCertificates() = Unit
|
||||
}
|
||||
|
|
@ -111,6 +111,34 @@ class OnboardingFlow(
|
|||
val registerData = (registerResult as RelayApiResult.Success).data
|
||||
|
||||
return try {
|
||||
// Cancellation-safety of this two-write pair is a property of a
|
||||
// DIFFERENT file, and nothing but this note connects them (#662).
|
||||
//
|
||||
// `storeSubdomain` and `storeIntegrationSecrets` are declared
|
||||
// `suspend` on [CertificateStore], but the production
|
||||
// implementation (`FileCertificateStore`, in `:app`) delegates both
|
||||
// to a NON-suspend `atomicWrite` and contains no `withContext`
|
||||
// anywhere. Cancellation is only delivered at a real suspension
|
||||
// point, so none can land between the two writes: either both land
|
||||
// or neither does. Production callers reinforce that -- both
|
||||
// (`OnboardingViewModel.startOnboarding` and, on foss,
|
||||
// `UnifiedPushBackgroundDelivery.onEndpoint`) run on the
|
||||
// application `SupervisorJob`, which is never cancelled -- and
|
||||
// `clear()` is itself `suspend`, so the rollback below was never a
|
||||
// guarantee on a cancelled job to begin with.
|
||||
//
|
||||
// Why that matters here specifically: OnboardingFlow does NOT
|
||||
// self-heal. Its onboarded gate is `getSubdomain() != null`
|
||||
// (`OnboardingViewModel.init`, `UnifiedPushBackgroundDelivery`),
|
||||
// and nothing repairs "subdomain present, secrets absent" -- unlike
|
||||
// CertProvisioningFlow, whose re-entry guard requires BOTH certs
|
||||
// and so re-runs itself. The day `atomicWrite` (or either store
|
||||
// method) becomes genuinely suspending -- an ordinary move to
|
||||
// `Dispatchers.IO` would do it -- this window goes live and a
|
||||
// half-onboarded device persists. If you make that change, wrap the
|
||||
// pair in `withContext(NonCancellable)` or add a repair path for
|
||||
// the half-written state. `OnboardingHalfWriteWindowTest` (:app)
|
||||
// fails when the window opens.
|
||||
certificateStore.storeSubdomain(registerData.subdomain)
|
||||
if (registerData.secrets.isNotEmpty()) {
|
||||
certificateStore.storeIntegrationSecrets(registerData.secrets)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue