Fix #227, #228: classify pre-onboarding as Skipped, check CT HTTP status (#229)

Two related bugs in the security-check pipeline that produced noisy
and misleading notifications for a freshly-installed device:

#227: HttpCtLogFetcher passed the response body straight to the JSON
parser without checking the HTTP status. crt.sh's transient 502/503
HTML error pages got surfaced as "Malformed CT log response" -- wording
that reads as "the CT log itself is corrupt" when the actual cause is
a Sectigo outage. Now throw IOException on non-2xx so CtLogMonitor
classifies as "Could not reach CT log service" instead.

#228: Pre-onboarding devices (no cert, no subdomain) fired "Security
Check" warning notifications describing a state that is just "not set
up yet." Introduce SecurityCheckResult.Skipped for "not applicable"
cases and route it through the worker without firing a notification.
The Settings screen renders "Waiting for onboarding" in muted colours
so the audit trail is still visible for users who look.

Constraints preserved:
- Alert path unchanged -- real issuer mismatches still fire loudly.
- Genuine network / I/O failures still produce Warning notifications.
- Only pre-onboarding classifications were reclassified to Skipped.

Closes #227
Closes #228

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jason Monk 2026-04-18 06:24:34 -04:00 • committed by GitHub
parent 674dd21353
commit 6d5b82cc20
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 379 additions and 3 deletions

View file

@ -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,

View file

@ -205,6 +205,7 @@
<string name="screen_settings_trust_result_warning">Unable to verify</string>
<string name="screen_settings_trust_result_alert">Verification failed</string>
<string name="screen_settings_trust_result_unchecked">Not checked</string>
<string name="screen_settings_trust_result_skipped">Waiting for onboarding</string>
<string name="screen_settings_trust_row">%1$s: %2$s</string>
<string name="screen_settings_trust_alert_note">Integration requests are blocked while an alert is active.</string>
<string name="screen_settings_trust_acknowledge">Acknowledge</string>

View file

@ -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"

View file

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

View file

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

View file

@ -118,6 +118,24 @@ class CtLogMonitorTest {
assertIs<SecurityCheckResult.Warning>(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<SecurityCheckResult.Skipped>(result)
}
}
/** Fake fetcher for testing CtLogMonitor without real network calls. */

View file

@ -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 = "<html><body><h1>502 Bad Gateway</h1></body></html>"
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<IOException> {
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("<html>service unavailable</html>"),
status = HttpStatusCode.ServiceUnavailable,
headers = headersOf(HttpHeaders.ContentType, "text/html")
)
}
}
}
val fetcher = HttpCtLogFetcher(httpClient = httpClient)
val thrown = assertFailsWith<IOException> {
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 = "<html><body>502 Bad Gateway</body></html>"
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<SecurityCheckResult.Warning>(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()
}
}

View file

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

View file

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

View file

@ -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<ByteArray>?,
private val subdomain: String?
) : CertificateStore {
override suspend fun getCertChain(): List<ByteArray>? = certChain
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 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<String, String>) = Unit
override suspend fun getIntegrationSecrets(): Map<String, String>? = 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<ByteArray>? =
throw java.io.IOException("Storage unavailable")
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 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<String, String>) = Unit
override suspend fun getIntegrationSecrets(): Map<String, String>? = null
override suspend fun clear() = Unit
override suspend fun clearCertificates() = Unit
}

View file

@ -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<FakeSecurityCheckNotifier.Call>(),
fakeNotifier.calls
)
}
@Test
fun `network warning on both - notifier postInfo invoked for each check`() = runBlocking {
val worker = buildWorker(