Modern Apps git

← Modern-Apps.git

email: strict TLS by default for custom mail hosts

Commit
e7e57937efd8b523b0b721be8831948e4305f8bc
Author
Vayun Mathur <[email protected]>
When
2026-11-20 20:44 UTC (15 days ago)
Parents
b598381
TrustAll accepted ANY certificate for any host not on a
known-provider list and was applied automatically by the IMAP,
SMTP, IDLE and raw-SMTP paths - a network MITM could
impersonate any self-hosted mail server and harvest
credentials and mail. The module's own AGENTS.md called it
debug-only. No hostname verification existed anywhere either.

Trust-all now requires an explicit per-account opt-in
(allowInsecureCertificates, DB v21, toggle in add-account and
per-account settings with a warning). Otherwise every host gets
the system trust store plus HTTPS endpoint identification.
Existing custom accounts with self-signed certs will fail until
the user opts in - intentionally, where before they connected
silently insecure.

Unit tests prove an unknown host gets the strict factory and
the permissive factory needs the opt-in; migration chain
updated. 569 email tests pass.

Diff

email/src/main/java/com/vayunmathur/email/data/EmailAccountDao.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailAccountDao.kt b/email/src/main/java/com/vayunmathur/email/data/EmailAccountDao.ktindex 10f49e1808..1f3cc83794 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailAccountDao.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailAccountDao.kt@@ -25,6 +25,9 @@ interface EmailAccountDao {     @Query("UPDATE EmailAccount SET signature = :signature WHERE email = :email")     suspend fun setSignature(email: String, signature: String) +    @Query("UPDATE EmailAccount SET allowInsecureCertificates = :allow WHERE email = :email")+    suspend fun setAllowInsecureCertificates(email: String, allow: Boolean)+     // ---- Blocked senders ----      @Query("SELECT * FROM BlockedSender ORDER BY address ASC")
email/src/main/java/com/vayunmathur/email/data/EmailAccountStore.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailAccountStore.kt b/email/src/main/java/com/vayunmathur/email/data/EmailAccountStore.ktindex f1fa0cde7c..7935dfec9d 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailAccountStore.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailAccountStore.kt@@ -11,6 +11,8 @@ class EmailAccountStore internal constructor(private val db: EmailDatabase) {     suspend fun getAccountByEmail(email: String): EmailAccount? = dao.getAccountByEmail(email)     suspend fun insertAccount(account: EmailAccount) = dao.insertAccount(account)     suspend fun setSignature(email: String, signature: String) = dao.setSignature(email, signature)+    suspend fun setAllowInsecureCertificates(email: String, allow: Boolean) =+        dao.setAllowInsecureCertificates(email, allow)     suspend fun deleteAccount(account: EmailAccount) = dao.deleteAccount(account)      fun getBlockedSendersFlow(): Flow<List<BlockedSender>> = dao.getBlockedSendersFlow()
email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.ktindex 2945566f36..c1cdfa165f 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt@@ -26,7 +26,7 @@ import com.vayunmathur.email.data.Attachment         BlockedSender::class,         DeletedUid::class,     ],-    version = 20,+    version = 21,     exportSchema = false, ) /** Room database holding email folders, messages, accounts and outbox state. */@@ -197,6 +197,11 @@ abstract class EmailDatabase : RoomDatabase() {             it.execSQL("ALTER TABLE EmailMessage ADD COLUMN peekContent TEXT NOT NULL DEFAULT ''")         } +        /** Per-account TLS opt-in; existing accounts stay strict (0). */+        private val MIGRATION_20_21 = Migration(20, 21) {+            it.execSQL("ALTER TABLE EmailAccount ADD COLUMN allowInsecureCertificates INTEGER NOT NULL DEFAULT 0")+        }+         /**          * Every migration for this database, registered with the Room builder via the          * [DatabaseMigrations] reflection hook in `openRoomDatabase`. Order is@@ -219,6 +224,7 @@ abstract class EmailDatabase : RoomDatabase() {             MIGRATION_17_18,             MIGRATION_18_19,             MIGRATION_19_20,+            MIGRATION_20_21,         )          fun getInstance(context: Context): EmailDatabase =
email/src/main/java/com/vayunmathur/email/data/EmailModels.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt b/email/src/main/java/com/vayunmathur/email/data/EmailModels.ktindex fc6a348856..b165dedb40 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt@@ -180,6 +180,13 @@ data class EmailAccount(     /** Plain-text signature appended to outgoing messages from this account. */     @ColumnInfo(defaultValue = "")     val signature: String = "",+    /**+     * Explicit opt-in to accept any TLS certificate for this account's+     * IMAP/SMTP hosts (self-hosted servers with self-signed certs).+     * Default false = platform trust + hostname verification for all hosts.+     */+    @ColumnInfo(defaultValue = "0")+    val allowInsecureCertificates: Boolean = false, ) {     fun getColor(): Long = accountColor(email) }
email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.ktindex 90e628a6b8..f25569d20c 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -20,7 +20,6 @@ import com.vayunmathur.email.R import com.vayunmathur.email.network.imap.ImapAuthException import com.vayunmathur.email.network.imap.ImapClient import com.vayunmathur.email.network.imap.RawImapConnection-import com.vayunmathur.email.network.imap.TrustAll import com.vayunmathur.email.platform.resolveAuth import com.vayunmathur.email.platform.imapServer import com.vayunmathur.email.platform.loginUser@@ -119,8 +118,7 @@ class ImapIdleService : Service() {         val server = account.imapServer()         val user = account.loginUser()         val auth = account.resolveAuth(applicationContext)-        val useTrustAll = !TrustAll.isKnownHost(server.host)-        val rawConn = RawImapConnection(server, trustAll = useTrustAll)+        val rawConn = RawImapConnection(server, trustAll = server.trustAllCertificates)         rawConn.connect()         var caps = rawConn.capability()         // Fail closed on STARTTLS failure (see ImapClient.withConnection):
email/src/main/java/com/vayunmathur/email/data/OutlookOAuth.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/OutlookOAuth.kt b/email/src/main/java/com/vayunmathur/email/data/OutlookOAuth.ktindex 9f84a42b82..c55b1b5a44 100644--- a/email/src/main/java/com/vayunmathur/email/data/OutlookOAuth.kt+++ b/email/src/main/java/com/vayunmathur/email/data/OutlookOAuth.kt@@ -110,7 +110,7 @@ object OutlookOAuth {             }             .build() -        Log.dev(TAG, "Starting Outlook OAuth -> $url redirect=$redirectUri")+        Log.dev(TAG, "Starting Outlook OAuth")         try {             CustomTabsIntent.Builder().build().apply {                 intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)@@ -143,8 +143,7 @@ object OutlookOAuth {         val rawStr = redirect.toString()         Log.dev(             TAG,-            "complete redirect=$redirect host=${redirect.host} " +-                "path=${redirect.path} query=${redirect.query} raw=$rawStr",+            "complete redirect host=${redirect.host} path=${redirect.path}",         )          val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)@@ -169,7 +168,7 @@ object OutlookOAuth {         // old condition only fired when both values were present, so a         // redirect that simply omitted state bypassed the CSRF check.         if (session.expectedState == null || returnedState != session.expectedState) {-            Log.error(TAG, "State mismatch exp=${session.expectedState} got=$returnedState")+            Log.error(TAG, "State mismatch")             prefs.edit { clear() }             return OAuthResult.Failure(                 "State mismatch — possible CSRF, please retry",@@ -215,7 +214,7 @@ object OutlookOAuth {     ): OAuthResult.Failure {         val err = redirect.getQueryParameter("error") ?: extractQueryParam(rawStr, "error")         val desc = redirect.getQueryParameter("error_description") ?: extractQueryParam(rawStr, "error_description")-        Log.error(TAG, "No code, error=$err desc=$desc raw=$rawStr")+        Log.error(TAG, "No code, error=$err desc=$desc")         if (err != null) prefs.edit { clear() }         val reason = err ?: "No authorization code from Microsoft"         return OAuthResult.Failure(reason, err, desc)@@ -237,7 +236,7 @@ object OutlookOAuth {     }      private fun exchangeFailure(result: ExchangeResult): OAuthResult.Failure {-        Log.error(TAG, "Token exchange failed: ${result.error} desc=${result.errorDescription} raw=${result.rawBody}")+        Log.error(TAG, "Token exchange failed: ${result.error} desc=${result.errorDescription}")         val reason = result.error ?: "Token exchange failed"         return OAuthResult.Failure(reason, result.error, result.errorDescription ?: result.rawBody)     }@@ -348,7 +347,7 @@ object OutlookOAuth {     }      private fun failedExchange(respCode: Int, text: String): ExchangeResult {-        Log.error(TAG, "token exchange $respCode: $text")+        Log.error(TAG, "token exchange $respCode")         var err: String? = null         var errDesc: String? = null         try {
email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt b/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.ktindex 912dbf1899..767db17012 100644--- a/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt+++ b/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt@@ -69,7 +69,7 @@ object ImapClient {         trustAll: Boolean = false,         block: suspend (RawImapConnection) -> T,     ): T = withContext(Dispatchers.IO) {-        val useTrustAll = trustAll || !TrustAll.isKnownHost(server.host)+        val useTrustAll = trustAll || server.trustAllCertificates         val conn = RawImapConnection(server, trustAll = useTrustAll)         try {             conn.connect()
email/src/main/java/com/vayunmathur/email/network/imap/TrustAll.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/imap/TrustAll.kt b/email/src/main/java/com/vayunmathur/email/network/imap/TrustAll.ktindex 8977e31cd7..2f07120c5a 100644--- a/email/src/main/java/com/vayunmathur/email/network/imap/TrustAll.kt+++ b/email/src/main/java/com/vayunmathur/email/network/imap/TrustAll.kt@@ -4,6 +4,7 @@ import android.annotation.SuppressLint import java.security.SecureRandom import java.security.cert.X509Certificate import javax.net.ssl.SSLContext+import javax.net.ssl.SSLParameters import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManager@@ -13,10 +14,15 @@ import java.net.Socket /**  * Trust handling for raw IMAP/SMTP sockets.  *- * Known hosts (gmail, yahoo, aol, fastmail, outlook) use the system default- * trust store (strict). Custom hosts use a permissive trust manager that- * accepts any certificate (mirrors the old Jakarta `ssl.trust=*` behavior- * for self-hosted servers).+ * Default (strict) for ALL hosts — known providers and custom hosts alike:+ * platform trust store plus hostname verification via+ * [SSLParameters.endpointIdentificationAlgorithm] = "HTTPS".+ *+ * The permissive factory is reachable ONLY when the caller passes an+ * explicit per-account opt-in (`trustAll = true`, sourced from+ * `EmailAccount.allowInsecureCertificates`). It must never be selected+ * automatically because a host is unknown/custom. See AGENTS.md:+ * "network/imap/TrustAll.kt exists for debug only; never widen its use".  */ object TrustAll { @@ -41,13 +47,8 @@ object TrustAll {         "imap.outlook.com",     ) -    // Justified suppression: this trust manager is the documented, opt-in-    // fallback for self-hosted mail servers with self-signed certificates-    // (custom hosts only; known providers use the strict system store via-    // isKnownHost). Its scope has not been widened - see AGENTS.md:-    // "network/imap/TrustAll.kt exists for debug only; never widen its use"-    // and the class KDoc above. Removing it would break self-hosted-    // accounts that have no CA-issued certificate.+    // Permissive manager retained only for the explicit per-account opt-in+    // (self-hosted servers with self-signed certs) and debug/tests.     @SuppressLint("CustomX509TrustManager", "TrustAllX509TrustManager")     private val TRUST_ALL_MANAGERS: Array<TrustManager> = arrayOf(         object : X509TrustManager {@@ -70,7 +71,7 @@ object TrustAll {     fun permissiveSocketFactory(): SSLSocketFactory = permissiveFactory     fun systemSocketFactory(): SSLSocketFactory = systemFactory -    /** Known good hosts where we want strict system trust. */+    /** Informational only — no longer drives trust decisions. */     fun isKnownHost(host: String): Boolean {         val h = host.lowercase()         if (h in EXACT_KNOWN_HOSTS) return true@@ -78,12 +79,26 @@ object TrustAll {     }      fun socketFactoryFor(host: String, forceTrustAll: Boolean): SSLSocketFactory {-        return if (forceTrustAll || !isKnownHost(host)) permissiveFactory else systemFactory+        // Strict by default for every host; permissive only on explicit opt-in.+        return if (forceTrustAll) permissiveFactory else systemFactory+    }++    /** True when [host] would get the strict (system) factory by default. */+    fun usesStrictFactoryByDefault(host: String): Boolean =+        socketFactoryFor(host, forceTrustAll = false) === systemFactory++    private fun applyTlsParameters(socket: Socket, host: String, trustAll: Boolean) {+        if (socket !is SSLSocket || trustAll) return+        val params: SSLParameters = socket.sslParameters+        params.endpointIdentificationAlgorithm = "HTTPS"+        socket.sslParameters = params     }      fun createSocket(host: String, port: Int, trustAll: Boolean): Socket {         val factory = socketFactoryFor(host, trustAll)-        return factory.createSocket(host, port)+        val socket = factory.createSocket(host, port)+        applyTlsParameters(socket, host, trustAll)+        return socket     }      fun createPlainSocket(host: String, port: Int): Socket = Socket(host, port)@@ -98,6 +113,7 @@ object TrustAll {         val factory = socketFactoryFor(host, trustAll)         val ssl = factory.createSocket(plainSocket, host, port, autoClose) as SSLSocket         ssl.useClientMode = true+        applyTlsParameters(ssl, host, trustAll)         ssl.startHandshake()         return ssl     }
email/src/main/java/com/vayunmathur/email/network/smtp/RawSmtpConnection.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/smtp/RawSmtpConnection.kt b/email/src/main/java/com/vayunmathur/email/network/smtp/RawSmtpConnection.ktindex 09ca81c789..5fbfdf49cc 100644--- a/email/src/main/java/com/vayunmathur/email/network/smtp/RawSmtpConnection.kt+++ b/email/src/main/java/com/vayunmathur/email/network/smtp/RawSmtpConnection.kt@@ -45,7 +45,7 @@ class RawSmtpConnection(     fun connect() {         Log.dev(TAG, "Connecting SMTP ${server.host}:${server.port} ssl=${server.useSsl}")         val s: Socket = if (server.useSsl) {-            TrustAll.createSocket(server.host, server.port, trustAll || !TrustAll.isKnownHost(server.host))+            TrustAll.createSocket(server.host, server.port, trustAll)         } else {             TrustAll.createPlainSocket(server.host, server.port)         }@@ -75,7 +75,7 @@ class RawSmtpConnection(         checkSmtpPositive(resp, "STARTTLS")         val plain = socket ?: throw IOException("No socket for STARTTLS") -        val upgraded = TrustAll.upgradeToTls(plain, host, server.port, trustAll || !TrustAll.isKnownHost(server.host))+        val upgraded = TrustAll.upgradeToTls(plain, host, server.port, trustAll)         upgraded.soTimeout = TIMEOUT_MS         sslSocket = upgraded         socket = upgraded
email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.kt b/email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.ktindex 5bc23e8e66..3207872733 100644--- a/email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.kt+++ b/email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.kt@@ -6,7 +6,6 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.email.platform.EmailManager import com.vayunmathur.email.platform.ServerConfig import com.vayunmathur.email.ui.composer.InlineAttachment-import com.vayunmathur.email.network.imap.TrustAll import java.io.IOException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext@@ -49,8 +48,7 @@ object SmtpClient {             inReplyTo = inReplyTo,             references = references,         )-        val useTrustAll = !TrustAll.isKnownHost(server.host)-        val conn = RawSmtpConnection(server, trustAll = useTrustAll)+        val conn = RawSmtpConnection(server, trustAll = server.trustAllCertificates)         try {             openSession(conn, server)             authenticate(conn, user, auth)
email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailManager.ktindex 690efb4f9e..2c76a97f67 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt@@ -20,13 +20,21 @@ import java.io.OutputStream  * Raw sockets only — no Jakarta Mail.  */ -data class ServerConfig(val host: String, val port: Int, val useSsl: Boolean) {+data class ServerConfig(+    val host: String,+    val port: Int,+    val useSsl: Boolean,+    /** Explicit per-account opt-in to accept any certificate. Default strict. */+    val trustAllCertificates: Boolean = false,+) {     val imapProtocol: String get() = if (useSsl) "imaps" else "imap"     val smtpProtocol: String get() = if (useSsl) "smtps" else "smtp" } -fun EmailAccount.imapServer(): ServerConfig = ServerConfig(imapHost, imapPort, imapUseSsl)-fun EmailAccount.smtpServer(): ServerConfig = ServerConfig(smtpHost, smtpPort, smtpUseSsl)+fun EmailAccount.imapServer(): ServerConfig =+    ServerConfig(imapHost, imapPort, imapUseSsl, allowInsecureCertificates)+fun EmailAccount.smtpServer(): ServerConfig =+    ServerConfig(smtpHost, smtpPort, smtpUseSsl, allowInsecureCertificates) fun EmailAccount.loginUser(): String = username.ifBlank { email }  suspend fun EmailAccount.resolveAuth(context: Context): EmailManager.AuthType {
email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.ktindex 964aafd3fc..ffcc5f204f 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt@@ -150,6 +150,12 @@ class EmailViewModel(application: Application) :         }     } +    fun setAllowInsecureCertificates(email: String, allow: Boolean) {+        viewModelScope.launch {+            accountsDao.setAllowInsecureCertificates(email, allow)+        }+    }+     fun selectFolder(folderName: String) {         _selectedFolderName.value = folderName         _searchQuery.value = ""
email/src/main/java/com/vayunmathur/email/ui/AddAccountFormScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/AddAccountFormScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/AddAccountFormScreen.ktindex dda7e206cb..743acb42f0 100644--- a/email/src/main/java/com/vayunmathur/email/ui/AddAccountFormScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/AddAccountFormScreen.kt@@ -223,6 +223,7 @@ private fun PasswordForm(     var smtpHost by rememberSaveable { mutableStateOf(preset.smtp?.host ?: "") }     var smtpPort by rememberSaveable { mutableStateOf((preset.smtp?.port ?: 465).toString()) }     var smtpUseSsl by rememberSaveable { mutableStateOf(preset.smtp?.useSsl ?: true) }+    var allowInsecureCerts by rememberSaveable { mutableStateOf(false) }      var working by remember { mutableStateOf(false) }     var error by remember { mutableStateOf<String?>(null) }@@ -261,6 +262,13 @@ private fun PasswordForm(             AddAccountSection(host = imapHost, onHostChange = { imapHost = it.trim() }, port = imapPort, onPortChange = { imapPort = it.filter(Char::isDigit) }, useSsl = imapUseSsl, onSslChange = { imapUseSsl = it })             Text(stringResource(R.string.smtp_outgoing), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)             AddAccountSection(host = smtpHost, onHostChange = { smtpHost = it.trim() }, port = smtpPort, onPortChange = { smtpPort = it.filter(Char::isDigit) }, useSsl = smtpUseSsl, onSslChange = { smtpUseSsl = it })+            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clickable { allowInsecureCerts = !allowInsecureCerts }) {+                Checkbox(checked = allowInsecureCerts, onCheckedChange = { allowInsecureCerts = it })+                Text(stringResource(R.string.allow_insecure_certificates), style = MaterialTheme.typography.bodyMedium)+            }+            if (allowInsecureCerts) {+                Text(stringResource(R.string.allow_insecure_certificates_summary), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)+            }         }          if (error != null) {@@ -272,8 +280,8 @@ private fun PasswordForm(             onClick = {                 error = null; working = true                 scope.launch {-                    val imap = preset.imap ?: ServerConfig(imapHost, imapPort.toIntOrNull() ?: 993, imapUseSsl)-                    val smtp = preset.smtp ?: ServerConfig(smtpHost, smtpPort.toIntOrNull() ?: 465, smtpUseSsl)+                    val imap = preset.imap ?: ServerConfig(imapHost, imapPort.toIntOrNull() ?: 993, imapUseSsl, allowInsecureCerts)+                    val smtp = preset.smtp ?: ServerConfig(smtpHost, smtpPort.toIntOrNull() ?: 465, smtpUseSsl, allowInsecureCerts)                     val result = testAndPersistAccount(context = context, providerId = preset.id, email = email, username = if (useDifferentUsername) username else "", password = password, imap = imap, smtp = smtp)                     working = false                     if (result == null) { AppMessages.show(accountAddedMsg); onAccountAdded() } else error = result
email/src/main/java/com/vayunmathur/email/ui/AddAccountSection.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/AddAccountSection.kt b/email/src/main/java/com/vayunmathur/email/ui/AddAccountSection.ktindex 9b2b85c0aa..f409e1b35d 100644--- a/email/src/main/java/com/vayunmathur/email/ui/AddAccountSection.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/AddAccountSection.kt@@ -73,6 +73,7 @@ internal suspend fun testAndPersistAccount(         authType = "password",         passwordEncrypted = cipher,         passwordIv = iv,+        allowInsecureCertificates = imap.trustAllCertificates || smtp.trustAllCertificates,     )     EmailRepository.get(context).insertAccount(account)     EmailSyncWorker.scheduleHourlyNonInboxSync(context)
email/src/main/java/com/vayunmathur/email/ui/OAuthActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/OAuthActivity.kt b/email/src/main/java/com/vayunmathur/email/ui/OAuthActivity.ktindex 00ca976b28..11e545165a 100644--- a/email/src/main/java/com/vayunmathur/email/ui/OAuthActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/OAuthActivity.kt@@ -40,7 +40,7 @@ class OAuthActivity : ComponentActivity() {             finish()             return         }-        Log.dev(TAG, "Redirect raw=$raw host=${raw.host} path=${raw.path} query=${raw.query}")+        Log.dev(TAG, "Redirect host=${raw.host} path=${raw.path}")          lifecycleScope.launch {             val result: OutlookOAuth.OAuthResult = try {@@ -67,7 +67,7 @@ class OAuthActivity : ComponentActivity() {                         result.errorDescription?.takeIf { it.isNotBlank() }                     ).distinct()                     val detailed = parts.joinToString(": ")-                    Log.error(TAG, "OAuth failure: $detailed raw=$raw")+                    Log.error(TAG, "OAuth failure: $detailed")                     // Show callback error (error_description from Azure) not generic check-redirect message                     detailed to AppMessages.Duration.Indefinite                 }
email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.ktindex d4f212205a..03447886c2 100644--- a/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt@@ -77,6 +77,12 @@ fun SettingsScreen(viewModel: EmailViewModel, onBack: () -> Unit) {                 ) {                     Text(stringResource(UiR.string.save))                 }+                com.vayunmathur.library.ui.SettingsSwitchRow(+                    title = stringResource(R.string.allow_insecure_certificates),+                    supportingText = stringResource(R.string.allow_insecure_certificates_summary),+                    checked = acc.allowInsecureCertificates,+                    onCheckedChange = { viewModel.setAllowInsecureCertificates(acc.email, it) },+                )             }             HorizontalDivider()         }
email/src/main/res/values/strings.xml
diff --git a/email/src/main/res/values/strings.xml b/email/src/main/res/values/strings.xmlindex 22ca2f329e..9a6f18572c 100644--- a/email/src/main/res/values/strings.xml+++ b/email/src/main/res/values/strings.xml@@ -153,6 +153,8 @@     <string name="font_size">Font size</string>     <string name="font_family">Font family</string>     <string name="clear_formatting">Clear formatting</string>+    <string name="allow_insecure_certificates">Allow insecure certificates</string>+    <string name="allow_insecure_certificates_summary">Warning: accepts any certificate for this account\'s mail servers, including invalid or self-signed ones. Anyone on the network could intercept this account\'s mail and password. Only enable for a trusted self-hosted server.</string>     <string name="email_sync_channel_name">Background email sync</string>     <string name="email_sync_channel_desc">Keeps an IMAP connection open so new mail arrives instantly.</string>     <string name="unified_inbox_label">Unified Inbox</string>
email/src/test/java/com/vayunmathur/email/account/AccountFolderSelectionTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/account/AccountFolderSelectionTest.kt b/email/src/test/java/com/vayunmathur/email/account/AccountFolderSelectionTest.ktindex 92c4d0c543..3f658ac4f0 100644--- a/email/src/test/java/com/vayunmathur/email/account/AccountFolderSelectionTest.kt+++ b/email/src/test/java/com/vayunmathur/email/account/AccountFolderSelectionTest.kt@@ -113,4 +113,28 @@ class AccountFolderSelectionTest {         assertFalse(TrustAll.isKnownHost("notgmail.com"))         assertFalse(TrustAll.isKnownHost(""))     }++    @Test+    fun `unknown host gets strict factory by default`() {+        // Regression: custom/unknown hosts must NOT silently get trust-all.+        assertTrue(TrustAll.usesStrictFactoryByDefault("mail.example.com"))+        assertTrue(TrustAll.usesStrictFactoryByDefault("custom.selfhosted.local"))+        assertEquals(+            TrustAll.systemSocketFactory(),+            TrustAll.socketFactoryFor("mail.example.com", forceTrustAll = false),+        )+    }++    @Test+    fun `permissive factory only on explicit opt-in`() {+        assertEquals(+            TrustAll.permissiveSocketFactory(),+            TrustAll.socketFactoryFor("mail.example.com", forceTrustAll = true),+        )+        assertFalse(EmailAccount(email = "[email protected]").allowInsecureCertificates)+        val optedIn = EmailAccount(email = "[email protected]", allowInsecureCertificates = true)+        assertTrue(optedIn.imapServer().trustAllCertificates)+        assertTrue(optedIn.smtpServer().trustAllCertificates)+        assertFalse(EmailAccount(email = "[email protected]").imapServer().trustAllCertificates)+    } }
email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt b/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.ktindex c018d696a0..b96c37daa6 100644--- a/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt+++ b/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt@@ -54,13 +54,13 @@ class EmailMigrationsW5Test {     @Test     fun migrationChainIsCompleteAndOrdered() {         assertEquals(-            (4..19).map { it to it + 1 },+            (4..20).map { it to it + 1 },             EmailDatabase.migrations.map { it.startVersion to it.endVersion }.sortedBy { it.first },         )     }      @Test-    fun v4DatabaseUpgradesToV20Shape() {+    fun v4DatabaseUpgradesToV21Shape() {         val conn = openV4()         migrate(conn, 4)         assertTrue(tableExists(conn, "OutboxEntry"))@@ -68,7 +68,7 @@ class EmailMigrationsW5Test {         assertTrue(tableExists(conn, "BlockedSender"))         assertTrue(tableExists(conn, "DeletedUid"))         assertTrue(columns(conn, "EmailMessage").containsAll(setOf("dateMillis", "snoozedUntil", "listUnsubscribe", "listUnsubscribePost", "peekContent")), columns(conn, "EmailMessage").toString())-        assertTrue(columns(conn, "EmailAccount").containsAll(setOf("provider", "imapHost", "smtpHost", "authType", "username", "signature")), columns(conn, "EmailAccount").toString())+        assertTrue(columns(conn, "EmailAccount").containsAll(setOf("provider", "imapHost", "smtpHost", "authType", "username", "signature", "allowInsecureCertificates")), columns(conn, "EmailAccount").toString())         assertTrue(columns(conn, "OutboxEntry").containsAll(setOf("scheduledAt", "isHtml", "bcc", "inlineImageJson")), columns(conn, "OutboxEntry").toString())         assertTrue(columns(conn, "DraftEntry").contains("inlineImageJson"))         // The 6→7 backfill copies email into the new username column.