diff --git a/app/src/main/java/com/rousecontext/app/ui/screens/SettingsScreen.kt b/app/src/main/java/com/rousecontext/app/ui/screens/SettingsScreen.kt index 94d8d849..ccdde55e 100644 --- a/app/src/main/java/com/rousecontext/app/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/rousecontext/app/ui/screens/SettingsScreen.kt @@ -22,6 +22,7 @@ import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.Error import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Home +import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Warning import androidx.compose.material3.ButtonDefaults @@ -733,6 +734,13 @@ private fun TrustCheckRow(label: String, result: String, timeAgo: String) { ext.alertContent, stringResource(R.string.screen_settings_trust_result_alert) ) + // Issue #228: "skipped" is the pre-onboarding / not-yet-configured + // state. Rendered in muted colours so it does not read like a failure. + "skipped" -> Triple( + Icons.Default.Info, + MaterialTheme.colorScheme.onSurfaceVariant, + stringResource(R.string.screen_settings_trust_result_skipped) + ) else -> Triple( Icons.Default.Warning, MaterialTheme.colorScheme.onSurfaceVariant, diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4ccc2db8..a79d6011 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -205,6 +205,7 @@ Unable to verify Verification failed Not checked + Waiting for onboarding %1$s: %2$s Integration requests are blocked while an alert is active. Acknowledge diff --git a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/CtLogMonitor.kt b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/CtLogMonitor.kt index e282bc15..e5d41bae 100644 --- a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/CtLogMonitor.kt +++ b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/CtLogMonitor.kt @@ -46,7 +46,10 @@ class CtLogMonitor( } if (subdomain == null) { - return SecurityCheckResult.Warning("No subdomain configured") + // Issue #228: no subdomain means the device has not yet completed + // onboarding (or is between reinstall and re-onboarding). That is + // not a security issue, so MUST NOT fire a user notification. + return SecurityCheckResult.Skipped("No subdomain configured") } val domain = "$subdomain.$baseDomain" diff --git a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/HttpCtLogFetcher.kt b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/HttpCtLogFetcher.kt index b0b50047..68d00e96 100644 --- a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/HttpCtLogFetcher.kt +++ b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/HttpCtLogFetcher.kt @@ -4,6 +4,8 @@ import io.ktor.client.HttpClient import io.ktor.client.request.get import io.ktor.client.request.parameter import io.ktor.client.statement.bodyAsText +import io.ktor.http.isSuccess +import java.io.IOException /** * Production [CtLogFetcher] that queries crt.sh over HTTPS for certificates @@ -11,6 +13,12 @@ import io.ktor.client.statement.bodyAsText * * crt.sh returns a JSON array of certificate entries when invoked with `output=json`. * Any I/O exception is propagated so [CtLogMonitor] can classify it as a Warning. + * + * Issue #227: crt.sh (maintained by Sectigo) periodically returns 502/503 HTML + * error pages under load. We MUST check the HTTP status here and throw, so + * [CtLogMonitor] classifies the outage as "Could not reach CT log service" + * rather than letting the HTML body flow into the JSON parser and producing + * a misleading "Malformed CT log response" warning. */ class HttpCtLogFetcher( private val httpClient: HttpClient = RelayApiClient.createDefaultClient(), @@ -22,11 +30,32 @@ class HttpCtLogFetcher( parameter("q", domain) parameter("output", "json") } + if (!response.status.isSuccess()) { + // Include a short body preview for diagnosability: crt.sh's HTML + // outage pages typically lead with the error number and are useful + // context in the worker log without bloating the notification text. + val preview = runCatching { response.bodyAsText() } + .getOrDefault("") + .take(MAX_ERROR_BODY_PREVIEW) + .replace('\n', ' ') + .replace('\r', ' ') + .trim() + val suffix = if (preview.isEmpty()) "" else " body=\"$preview\"" + throw IOException("crt.sh returned HTTP ${response.status.value}$suffix") + } return response.bodyAsText() } companion object { /** Public crt.sh JSON query endpoint. */ const val DEFAULT_CRT_SH_URL = "https://crt.sh/" + + /** + * Cap on how much of an error body we echo back into the exception + * message. Short enough to stay readable in the notifications UI, + * long enough to surface the "502 Bad Gateway" / "503" wording crt.sh + * leads with. + */ + private const val MAX_ERROR_BODY_PREVIEW = 120 } } diff --git a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/SecurityCheckResult.kt b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/SecurityCheckResult.kt index 424b27e8..15a6db11 100644 --- a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/SecurityCheckResult.kt +++ b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/SecurityCheckResult.kt @@ -4,12 +4,17 @@ package com.rousecontext.tunnel * Result of a security monitoring check. * * [Verified] means everything looks normal. + * [Skipped] means the check is not applicable yet (e.g. pre-onboarding: no + * cert stored, no subdomain provisioned). This is NOT an error and MUST NOT + * surface a user-facing notification; it only exists so the settings / audit + * UI can render "waiting for onboarding" instead of claiming verified. * [Warning] means a transient issue occurred (e.g. network unreachable) -- * the check could not be completed but there is no evidence of compromise. * [Alert] means a potential security issue was detected that requires attention. */ sealed class SecurityCheckResult { data object Verified : SecurityCheckResult() + data class Skipped(val reason: String) : SecurityCheckResult() data class Warning(val reason: String) : SecurityCheckResult() data class Alert(val reason: String) : SecurityCheckResult() } diff --git a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/CtLogMonitorTest.kt b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/CtLogMonitorTest.kt index 368eceb5..5f6060ae 100644 --- a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/CtLogMonitorTest.kt +++ b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/CtLogMonitorTest.kt @@ -118,6 +118,24 @@ class CtLogMonitorTest { assertIs(result) } + + @Test + fun `no subdomain configured - skipped not warning (issue 228)`(): Unit = runBlocking { + // Pre-onboarding / post-reinstall: no subdomain has been requested yet. + // This is "not set up" and must not fire a user notification. + val fetcher = FakeCtLogFetcher(response = "[]") + val store = SecurityCertificateStore(subdomain = null) + val monitor = CtLogMonitor( + certificateStore = store, + ctLogFetcher = fetcher, + expectedIssuers = setOf("C=US, O=Let's Encrypt, CN=R3"), + baseDomain = "rousecontext.com" + ) + + val result = monitor.check() + + assertIs(result) + } } /** Fake fetcher for testing CtLogMonitor without real network calls. */ diff --git a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/HttpCtLogFetcherTest.kt b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/HttpCtLogFetcherTest.kt new file mode 100644 index 00000000..6cbc12fb --- /dev/null +++ b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/HttpCtLogFetcherTest.kt @@ -0,0 +1,145 @@ +package com.rousecontext.tunnel + +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import io.ktor.utils.io.ByteReadChannel +import java.io.IOException +import kotlin.test.Test +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking + +/** + * Unit tests for [HttpCtLogFetcher]. These guard issue #227: crt.sh periodically + * returns 502/503 HTML error pages, and before this fix the fetcher passed that + * HTML straight to the JSON parser, producing a misleading "Malformed CT log + * response" warning instead of the correct "Could not reach CT log service" + * classification. + */ +class HttpCtLogFetcherTest { + + @Test + fun `fetch throws IOException when crt sh returns 502 with HTML body`(): Unit = runBlocking { + val htmlBody = "

502 Bad Gateway

" + val httpClient = HttpClient(MockEngine) { + engine { + addHandler { + respond( + content = ByteReadChannel(htmlBody), + status = HttpStatusCode.BadGateway, + headers = headersOf(HttpHeaders.ContentType, "text/html") + ) + } + } + } + val fetcher = HttpCtLogFetcher(httpClient = httpClient) + + val thrown = assertFailsWith { + fetcher.fetch("abc123.rousecontext.com") + } + assertTrue( + thrown.message!!.contains("502"), + "Status code must appear in exception message for diagnosability, " + + "was: ${thrown.message}" + ) + + httpClient.close() + } + + @Test + fun `fetch throws IOException when crt sh returns 503`(): Unit = runBlocking { + val httpClient = HttpClient(MockEngine) { + engine { + addHandler { + respond( + content = ByteReadChannel("service unavailable"), + status = HttpStatusCode.ServiceUnavailable, + headers = headersOf(HttpHeaders.ContentType, "text/html") + ) + } + } + } + val fetcher = HttpCtLogFetcher(httpClient = httpClient) + + val thrown = assertFailsWith { + fetcher.fetch("abc123.rousecontext.com") + } + assertTrue( + thrown.message!!.contains("503"), + "Status code must appear in exception message, was: ${thrown.message}" + ) + + httpClient.close() + } + + @Test + fun `fetch returns body unchanged on 200 OK`(): Unit = runBlocking { + val jsonBody = "[]" + val httpClient = HttpClient(MockEngine) { + engine { + addHandler { + respond( + content = ByteReadChannel(jsonBody), + status = HttpStatusCode.OK, + headers = headersOf(HttpHeaders.ContentType, "application/json") + ) + } + } + } + val fetcher = HttpCtLogFetcher(httpClient = httpClient) + + val result = fetcher.fetch("abc123.rousecontext.com") + kotlin.test.assertEquals(jsonBody, result) + + httpClient.close() + } + + /** + * Integration-level check (no real network): routes an HTML 5xx body through + * the full [HttpCtLogFetcher] + [CtLogMonitor] stack and asserts the final + * classification is the network-failure warning, not the JSON-parse warning. + * This is the whole point of issue #227 at the worker level. + */ + @Test + fun `crt sh 502 HTML classified as network failure not malformed`(): Unit = runBlocking { + val htmlBody = "502 Bad Gateway" + val httpClient = HttpClient(MockEngine) { + engine { + addHandler { + respond( + content = ByteReadChannel(htmlBody), + status = HttpStatusCode.BadGateway, + headers = headersOf(HttpHeaders.ContentType, "text/html") + ) + } + } + } + val fetcher = HttpCtLogFetcher(httpClient = httpClient) + val store = SecurityCertificateStore(subdomain = "abc123") + val monitor = CtLogMonitor( + certificateStore = store, + ctLogFetcher = fetcher, + expectedIssuers = setOf("C=US, O=Let's Encrypt, CN=R3"), + baseDomain = "rousecontext.com" + ) + + val result = monitor.check() + + assertIs(result) + assertTrue( + result.reason.contains("Could not reach CT log service"), + "Expected network-failure wording, got: ${result.reason}" + ) + assertTrue( + !result.reason.contains("Malformed"), + "Must NOT classify an HTTP 5xx as malformed, got: ${result.reason}" + ) + + httpClient.close() + } +} diff --git a/work/src/main/kotlin/com/rousecontext/work/SecurityCheckSources.kt b/work/src/main/kotlin/com/rousecontext/work/SecurityCheckSources.kt index 67e45a00..0ee001f8 100644 --- a/work/src/main/kotlin/com/rousecontext/work/SecurityCheckSources.kt +++ b/work/src/main/kotlin/com/rousecontext/work/SecurityCheckSources.kt @@ -28,8 +28,12 @@ class StoredCertVerifierSource( ) } if (chain.isNullOrEmpty()) { - // No cert stored yet (pre-onboarding) — nothing to verify against. - return SecurityCheckResult.Warning("No certificate stored") + // Issue #228: no cert stored yet (pre-onboarding / post-reinstall) + // — nothing to verify against. This is not a security condition, + // so MUST NOT surface a user-facing notification. The worker still + // records "skipped" so the Settings screen can show the waiting + // state if the user checks. + return SecurityCheckResult.Skipped("No certificate stored") } return verifier.verify(chain) } diff --git a/work/src/main/kotlin/com/rousecontext/work/SecurityCheckWorker.kt b/work/src/main/kotlin/com/rousecontext/work/SecurityCheckWorker.kt index fb5c0ce7..e19e5dc5 100644 --- a/work/src/main/kotlin/com/rousecontext/work/SecurityCheckWorker.kt +++ b/work/src/main/kotlin/com/rousecontext/work/SecurityCheckWorker.kt @@ -73,6 +73,12 @@ class SecurityCheckWorker(context: Context, params: WorkerParameters) : Log.d(TAG, "$checkName: verified") } + is SecurityCheckResult.Skipped -> { + // Issue #228: pre-onboarding / "not yet configured" states log + // for diagnostics but MUST NOT fire a user notification. + Log.d(TAG, "$checkName: skipped - ${result.reason}") + } + is SecurityCheckResult.Warning -> { Log.w(TAG, "$checkName: warning - ${result.reason}") notifier.postInfo(check, result.reason) @@ -91,6 +97,7 @@ class SecurityCheckWorker(context: Context, params: WorkerParameters) : private fun resultToString(result: SecurityCheckResult): String = when (result) { is SecurityCheckResult.Verified -> "verified" + is SecurityCheckResult.Skipped -> "skipped" is SecurityCheckResult.Warning -> "warning" is SecurityCheckResult.Alert -> "alert" } diff --git a/work/src/test/kotlin/com/rousecontext/work/SecurityCheckSourcesTest.kt b/work/src/test/kotlin/com/rousecontext/work/SecurityCheckSourcesTest.kt new file mode 100644 index 00000000..9787417a --- /dev/null +++ b/work/src/test/kotlin/com/rousecontext/work/SecurityCheckSourcesTest.kt @@ -0,0 +1,133 @@ +package com.rousecontext.work + +import com.rousecontext.tunnel.CertificateStore +import com.rousecontext.tunnel.CtLogFetcher +import com.rousecontext.tunnel.CtLogMonitor +import com.rousecontext.tunnel.SecurityCheckResult +import com.rousecontext.tunnel.SelfCertVerifier +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Tests for [StoredCertVerifierSource] and [CtLogMonitorSource] that cover + * issue #228 -- the "pre-onboarding" classification paths MUST produce + * [SecurityCheckResult.Skipped] rather than [SecurityCheckResult.Warning] + * so the worker does not fire a user notification for a state that is + * simply "not set up yet." + */ +class SecurityCheckSourcesTest { + + @Test + fun `stored cert source returns Skipped when chain is null (pre-onboarding)`() = runBlocking { + val store = SourcesTestStore(certChain = null, subdomain = null) + val source = StoredCertVerifierSource(store, SelfCertVerifier(store)) + + val result = source.check() + + assertTrue( + "expected Skipped, got $result", + result is SecurityCheckResult.Skipped + ) + } + + @Test + fun `stored cert source returns Skipped when chain is empty`() = runBlocking { + val store = SourcesTestStore(certChain = emptyList(), subdomain = null) + val source = StoredCertVerifierSource(store, SelfCertVerifier(store)) + + val result = source.check() + + assertTrue( + "expected Skipped, got $result", + result is SecurityCheckResult.Skipped + ) + } + + @Test + fun `stored cert source still returns Warning when chain fetch throws`() = runBlocking { + // Genuine I/O failure must still surface a warning, not a skip. + val store = ThrowingStore() + val source = StoredCertVerifierSource(store, SelfCertVerifier(store)) + + val result = source.check() + + assertTrue( + "expected Warning, got $result", + result is SecurityCheckResult.Warning + ) + } + + @Test + fun `ct log monitor source returns Skipped when subdomain is null`() = runBlocking { + val store = SourcesTestStore(certChain = null, subdomain = null) + val monitor = CtLogMonitor( + certificateStore = store, + ctLogFetcher = object : CtLogFetcher { + override suspend fun fetch(domain: String): String = "[]" + }, + expectedIssuers = setOf("C=US, O=Let's Encrypt, CN=R3"), + baseDomain = "rousecontext.com" + ) + val source = CtLogMonitorSource(monitor) + + val result = source.check() + + assertTrue( + "expected Skipped, got $result", + result is SecurityCheckResult.Skipped + ) + } +} + +/** Minimal CertificateStore for source-level tests. */ +private class SourcesTestStore( + private val certChain: List?, + private val subdomain: String? +) : CertificateStore { + override suspend fun getCertChain(): List? = certChain + override suspend fun getPrivateKeyBytes(): ByteArray? = null + override suspend fun storeCertChain(chain: List) = Unit + override suspend fun getCertExpiry(): Long? = null + override suspend fun getKnownFingerprints(): Set = emptySet() + override suspend fun storeFingerprint(fingerprint: String) = Unit + override suspend fun hasFingerprintBootstrapMarker(): Boolean = false + override suspend fun writeFingerprintBootstrapMarker() = Unit + 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? = subdomain + override suspend fun storeIntegrationSecrets(secrets: Map) = Unit + override suspend fun getIntegrationSecrets(): Map? = null + override suspend fun clear() = Unit + override suspend fun clearCertificates() = Unit +} + +/** CertificateStore that throws on getCertChain, simulating a real storage failure. */ +private class ThrowingStore : CertificateStore { + override suspend fun getCertChain(): List? = + throw java.io.IOException("Storage unavailable") + override suspend fun getPrivateKeyBytes(): ByteArray? = null + override suspend fun storeCertChain(chain: List) = Unit + override suspend fun getCertExpiry(): Long? = null + override suspend fun getKnownFingerprints(): Set = emptySet() + override suspend fun storeFingerprint(fingerprint: String) = Unit + override suspend fun hasFingerprintBootstrapMarker(): Boolean = false + override suspend fun writeFingerprintBootstrapMarker() = Unit + 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? = null + override suspend fun storeIntegrationSecrets(secrets: Map) = Unit + override suspend fun getIntegrationSecrets(): Map? = null + override suspend fun clear() = Unit + override suspend fun clearCertificates() = Unit +} diff --git a/work/src/test/kotlin/com/rousecontext/work/SecurityCheckWorkerTest.kt b/work/src/test/kotlin/com/rousecontext/work/SecurityCheckWorkerTest.kt index 4def9160..d8be924f 100644 --- a/work/src/test/kotlin/com/rousecontext/work/SecurityCheckWorkerTest.kt +++ b/work/src/test/kotlin/com/rousecontext/work/SecurityCheckWorkerTest.kt @@ -126,6 +126,29 @@ class SecurityCheckWorkerTest { ) } + @Test + fun `skipped on both - no notifications fired and preferences record skipped`() = runBlocking { + // Issue #228: "no cert stored" / "no subdomain configured" must NOT + // surface a notification -- that's a pre-onboarding state, not a + // security issue. + val worker = buildWorker( + selfCertResult = SecurityCheckResult.Skipped("No certificate stored"), + ctResult = SecurityCheckResult.Skipped("No subdomain configured") + ) + + val result = worker.doWork() + + assertEquals(ListenableWorker.Result.success(), result) + assertEquals("skipped", prefs.selfCertResult()) + assertEquals("skipped", prefs.ctLogResult()) + assertTrue(prefs.lastCheckAt() > 0) + assertEquals( + "Skipped result MUST NOT fire a notification", + emptyList(), + fakeNotifier.calls + ) + } + @Test fun `network warning on both - notifier postInfo invoked for each check`() = runBlocking { val worker = buildWorker(