diff --git a/ANDROID_SECURITY_PLAN.md b/ANDROID_SECURITY_PLAN.md index e0b02e0..a1f9e63 100644 --- a/ANDROID_SECURITY_PLAN.md +++ b/ANDROID_SECURITY_PLAN.md @@ -16,7 +16,7 @@ Tracking legend: `[x]` implemented for the stated item; `[~]` partially implemen OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, and on-demand PGP/MIME or inline-encrypted-message decryption. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**. -**Validation evidence:** DAV URL, attachment-name, and notification privacy policies have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock and unlock. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. Phone and landscape layouts were checked for horizontal overflow. The latest validation was 152 passing Node tests and a successful Android debug build with 12 Android unit tests. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android. +**Validation evidence:** DAV URL, attachment-name, notification privacy, and Android OpenPGP trust/plaintext policy decisions have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock and unlock. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. Phone and landscape layouts were checked for horizontal overflow. Current validation: 152 passing Node tests, 18 Android unit tests, and a successful Android debug build. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android. **Release blockers:** independent human cryptography/security review; automated native confirmation and bypass tests; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric design; invalid-certificate integration tests; production-signed APK/manifest review; app-lock recovery polish; and compatibility review/remediation of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain. @@ -64,7 +64,7 @@ These are implementation observations, not proof that all paths are safe. In par - [ ] Add optional biometric/device-credential release of PGP key access and test Keystore invalidation/recovery. Background sync does not use PGP private keys. - [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, and trust. Native prompts now guard trust elevation and replacement; automated cancel/confirm regression tests remain open. - [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, and ciphertext-before-queueing are implemented. Signed-only/clear-signed/inline signature parity, full hostile-input/tampering suite, and Android interoperability remain open. -- [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; the native send path checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel. Automated bypass, stale-key, and queue policy tests remain open. +- [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; the native send path checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy-level unit tests cover prompt/no-prompt decisions. Automated dialog-interaction, bypass, stale-key, and queue-policy tests remain open. - [x] Key-server lookup and publication are disabled in the initial Android test implementation. **Exit criteria:** parity tests for desktop message formats and trust rules; Android-specific tests for cancel/confirm paths, tampering, malformed/oversized messages, key replacement, offline queueing, process death, and passphrase expiry; independent human review before release. diff --git a/TODO.md b/TODO.md index 79d0b51..81a8506 100644 --- a/TODO.md +++ b/TODO.md @@ -33,7 +33,8 @@ - [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout. - [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption. - [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation. - - [ ] Android release gate: native confirmation accept/cancel and bypass tests, full parity/interoperability tests, independent human cryptography/security review, and signed release review. + - [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions. + - [ ] Android release gate: automated native-dialog interaction and bypass tests, full parity/interoperability tests, independent human cryptography/security review, and signed release review. - [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, signed/inline verification parity, and dependency advisory remediation. - [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests. - [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures). diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidPgpPolicy.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidPgpPolicy.kt new file mode 100644 index 0000000..c39f196 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidPgpPolicy.kt @@ -0,0 +1,86 @@ +package studio.daybreak.mail + +import java.util.Locale + +internal object AndroidPgpPolicy { + data class ContactKey( + val fingerprint: String, + val emails: List, + val trust: String + ) + + data class RecipientKey( + val email: String, + val fingerprint: String + ) + + private val trustOrder = mapOf("unknown" to 0, "trusted" to 1, "verified" to 2) + + fun storeChangeWarning(previous: List, candidate: List): String? { + val oldByFingerprint = previous.associateBy { it.fingerprint.uppercase(Locale.ROOT) } + val warnings = ArrayList() + + for (current in candidate) { + val fingerprint = current.fingerprint.uppercase(Locale.ROOT) + val old = oldByFingerprint[fingerprint] + if (old != null && (trustOrder[current.trust] ?: 0) > (trustOrder[old.trust] ?: 0)) { + warnings.add( + "Trust change for ${safeLabel(current.emails)}\n" + + "Fingerprint: ${formatFingerprint(fingerprint)}\n" + + "New trust: ${current.trust}" + ) + } + + if (old == null) { + val newEmails = current.emails.map { it.lowercase(Locale.ROOT) }.toSet() + for (previousKey in previous) { + val oldFingerprint = previousKey.fingerprint.uppercase(Locale.ROOT) + val overlaps = previousKey.emails.any { it.lowercase(Locale.ROOT) in newEmails } + if (overlaps && oldFingerprint != fingerprint) { + warnings.add( + "A different key is already stored for ${safeLabel(current.emails)}.\n" + + "New fingerprint: ${formatFingerprint(fingerprint)}\n" + + "Existing fingerprint: ${formatFingerprint(oldFingerprint)}" + ) + } + } + } + } + + return warnings.take(MAX_WARNINGS).takeIf { it.isNotEmpty() }?.joinToString("\n\n")?.let { + "$it\n\nOnly confirm trust or a replacement after comparing fingerprints with the key owner through another channel." + } + } + + fun plaintextSendWarning( + recipients: List, + availableKeys: List, + encryptionWasRequested: Boolean + ): String? { + val uniqueRecipients = recipients.map { it.trim().lowercase(Locale.ROOT) }.filter(String::isNotBlank).distinct() + if (uniqueRecipients.isEmpty()) return null + val matchedKeys = availableKeys.filter { key -> key.email.trim().lowercase(Locale.ROOT) in uniqueRecipients } + if (!encryptionWasRequested && matchedKeys.isEmpty()) return null + + val recipientLines = uniqueRecipients.take(MAX_RECIPIENTS).map { email -> + val fingerprints = matchedKeys.filter { it.email.trim().equals(email, ignoreCase = true) } + .map { formatFingerprint(it.fingerprint.uppercase()) }.distinct() + if (fingerprints.isEmpty()) "$email — no key stored" else "$email\n${fingerprints.joinToString("\n")}" + }.joinToString("\n\n") + val prefix = if (encryptionWasRequested) { + "OpenPGP was requested, but this message will be sent in plaintext." + } else { + "A stored OpenPGP key is available for at least one recipient." + } + return "$prefix\n\nRecipients and stored key fingerprints:\n$recipientLines\n\n" + + "The message body and attachments will be readable by the mail provider and anyone who receives it. Send plaintext anyway?" + } + + private fun safeLabel(values: List): String = + values.joinToString(", ").replace(Regex("[\\r\\n\\u0000]"), " ").take(300).ifBlank { "this contact" } + + private fun formatFingerprint(value: String): String = value.chunked(4).joinToString(" ").take(200) + + private const val MAX_WARNINGS = 6 + private const val MAX_RECIPIENTS = 10 +} diff --git a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt index 5773a8e..c22fc98 100644 --- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -154,43 +154,21 @@ class EpMailPlugin : Plugin() { private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? { val oldContacts = previous.optJSONArray("contacts") ?: JSONArray() val newContacts = candidate.optJSONArray("contacts") ?: JSONArray() - val oldByFingerprint = (0 until oldContacts.length()).mapNotNull { oldContacts.optJSONObject(it) } - .associateBy { it.optString("fingerprint").uppercase(Locale.ROOT) } - val warnings = ArrayList() - for (index in 0 until newContacts.length()) { - val current = newContacts.optJSONObject(index) ?: continue - val fingerprint = current.optString("fingerprint").uppercase(Locale.ROOT) - val previousContact = oldByFingerprint[fingerprint] - val trustOrder = mapOf("unknown" to 0, "trusted" to 1, "verified" to 2) - if (previousContact != null && - (trustOrder[current.optString("trust")] ?: 0) > (trustOrder[previousContact.optString("trust")] ?: 0)) { - warnings.add("Trust change for ${safePgpLabel(current.optJSONArray("emails"))}\nFingerprint: ${formatPgpFingerprint(fingerprint)}\nNew trust: ${current.optString("trust")}") - } - if (previousContact == null) { - val newEmails = jsonStrings(current.optJSONArray("emails")).map { it.lowercase(Locale.ROOT) }.toSet() - for (oldIndex in 0 until oldContacts.length()) { - val old = oldContacts.optJSONObject(oldIndex) ?: continue - val oldFingerprint = old.optString("fingerprint").uppercase(Locale.ROOT) - val overlap = jsonStrings(old.optJSONArray("emails")).map { it.lowercase(Locale.ROOT) }.any(newEmails::contains) - if (overlap && oldFingerprint != fingerprint) { - warnings.add("A different key is already stored for ${safePgpLabel(current.optJSONArray("emails"))}.\nNew fingerprint: ${formatPgpFingerprint(fingerprint)}\nExisting fingerprint: ${formatPgpFingerprint(oldFingerprint)}") - } - } - } - } - return warnings.take(6).takeIf { it.isNotEmpty() }?.joinToString("\n\n")?.let { - "$it\n\nOnly confirm trust or a replacement after comparing fingerprints with the key owner through another channel." - } + return AndroidPgpPolicy.storeChangeWarning(pgpContacts(oldContacts), pgpContacts(newContacts)) } + private fun pgpContacts(values: JSONArray): List = + (0 until values.length()).mapNotNull { values.optJSONObject(it) }.map { contact -> + AndroidPgpPolicy.ContactKey( + fingerprint = contact.optString("fingerprint"), + emails = jsonStrings(contact.optJSONArray("emails")), + trust = contact.optString("trust") + ) + } + private fun jsonStrings(values: JSONArray?): List = values?.let { array -> (0 until array.length()).mapNotNull { array.optString(it).takeIf(String::isNotBlank) } }.orEmpty() - private fun safePgpLabel(values: JSONArray?): String = - jsonStrings(values).joinToString(", ").replace(Regex("[\\r\\n\\u0000]"), " ").take(300).ifBlank { "this contact" } - - private fun formatPgpFingerprint(value: String): String = value.chunked(4).joinToString(" ").take(200) - @PluginMethod fun pgpGetMessageSource(call: PluginCall) { try { @@ -496,31 +474,25 @@ class EpMailPlugin : Plugin() { .filter(String::isNotBlank) .flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } }) .distinct() - if (recipients.isEmpty()) return null val data = AndroidAccountVault.pgpStore() val contacts = data.optJSONArray("contacts") ?: JSONArray() val keys = data.optJSONArray("keys") ?: JSONArray() - val available = ArrayList>() + val available = ArrayList() for (address in recipients) { for (index in 0 until contacts.length()) { val contact = contacts.optJSONObject(index) ?: continue if (jsonStrings(contact.optJSONArray("emails")).any { it.equals(address, true) }) { - available.add(address to contact.optString("fingerprint")) + available.add(AndroidPgpPolicy.RecipientKey(address, contact.optString("fingerprint"))) } } for (index in 0 until keys.length()) { val key = keys.optJSONObject(index) ?: continue - if (key.optString("email").equals(address, true)) available.add(address to key.optString("fingerprint")) + if (key.optString("email").equals(address, true)) { + available.add(AndroidPgpPolicy.RecipientKey(address, key.optString("fingerprint"))) + } } } - val explicitRequest = input.optBoolean("pgpRequested") - if (!explicitRequest && available.isEmpty()) return null - val recipientLines = recipients.take(10).map { address -> - val fingerprints = available.filter { it.first == address }.map { formatPgpFingerprint(it.second) }.distinct() - if (fingerprints.isEmpty()) "$address — no key stored" else "$address\n${fingerprints.joinToString("\n")}" - }.joinToString("\n\n") - val prefix = if (explicitRequest) "OpenPGP was requested, but this message will be sent in plaintext." else "A stored OpenPGP key is available for at least one recipient." - return "$prefix\n\nRecipients and stored key fingerprints:\n$recipientLines\n\nThe message body and attachments will be readable by the mail provider and anyone who receives it. Send plaintext anyway?" + return AndroidPgpPolicy.plaintextSendWarning(recipients, available, input.optBoolean("pgpRequested")) } @PluginMethod diff --git a/android/app/src/test/java/studio/daybreak/mail/AndroidPgpPolicyTest.kt b/android/app/src/test/java/studio/daybreak/mail/AndroidPgpPolicyTest.kt new file mode 100644 index 0000000..57b13ab --- /dev/null +++ b/android/app/src/test/java/studio/daybreak/mail/AndroidPgpPolicyTest.kt @@ -0,0 +1,83 @@ +package studio.daybreak.mail + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class AndroidPgpPolicyTest { + private val firstFingerprint = "0123456789ABCDEF0123456789ABCDEF01234567" + private val secondFingerprint = "89ABCDEF0123456789ABCDEF0123456789ABCDEF" + + @Test + fun unchangedOrLoweredTrustDoesNotPrompt() { + val verified = contact(firstFingerprint, "alice@example.test", "verified") + assertNull(AndroidPgpPolicy.storeChangeWarning(listOf(verified), listOf(verified))) + assertNull(AndroidPgpPolicy.storeChangeWarning(listOf(verified), listOf(verified.copy(trust = "unknown")))) + } + + @Test + fun trustElevationRequiresTheFullFingerprintWarning() { + val previous = contact(firstFingerprint, "alice@example.test", "unknown") + val warning = AndroidPgpPolicy.storeChangeWarning( + listOf(previous), + listOf(previous.copy(trust = "verified")) + ) + + assertTrue(warning!!.contains("alice@example.test")) + assertTrue(warning.contains("0123 4567 89AB CDEF")) + assertTrue(warning.contains("New trust: verified")) + } + + @Test + fun addingAKeyForAnExistingAddressRequiresReplacementWarning() { + val previous = contact(firstFingerprint, "alice@example.test", "unknown") + val replacement = contact(secondFingerprint, "ALICE@example.test", "unknown") + val warning = AndroidPgpPolicy.storeChangeWarning(listOf(previous), listOf(previous, replacement)) + + assertTrue(warning!!.contains("different key is already stored")) + assertTrue(warning.contains("0123 4567 89AB CDEF")) + assertTrue(warning.contains("89AB CDEF 0123 4567")) + } + + @Test + fun plaintextPromptNamesRecipientsAndMatchingKeyFingerprints() { + val warning = AndroidPgpPolicy.plaintextSendWarning( + recipients = listOf("Alice@example.test", "bob@example.test"), + availableKeys = listOf(AndroidPgpPolicy.RecipientKey("alice@example.test", firstFingerprint)), + encryptionWasRequested = false + ) + + assertTrue(warning!!.contains("alice@example.test")) + assertTrue(warning.contains("0123 4567 89AB CDEF")) + assertTrue(warning.contains("bob@example.test — no key stored")) + assertTrue(warning.contains("readable by the mail provider")) + } + + @Test + fun noPlaintextPromptWhenNoKeyExistsAndEncryptionWasNotRequested() { + assertNull( + AndroidPgpPolicy.plaintextSendWarning( + recipients = listOf("alice@example.test"), + availableKeys = emptyList(), + encryptionWasRequested = false + ) + ) + } + + @Test + fun explicitEncryptionRequestPromptsEvenWhenNoRecipientKeyExists() { + val warning = AndroidPgpPolicy.plaintextSendWarning( + recipients = listOf("alice@example.test"), + availableKeys = emptyList(), + encryptionWasRequested = true + ) + + assertTrue(warning!!.contains("OpenPGP was requested")) + assertTrue(warning.contains("alice@example.test — no key stored")) + assertFalse(warning.contains("Fingerprint:")) + } + + private fun contact(fingerprint: String, email: String, trust: String) = + AndroidPgpPolicy.ContactKey(fingerprint, listOf(email), trust) +} diff --git a/tests/android-ui-support.test.cjs b/tests/android-ui-support.test.cjs index eae6850..1007a1a 100644 --- a/tests/android-ui-support.test.cjs +++ b/tests/android-ui-support.test.cjs @@ -11,6 +11,7 @@ const transport = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main const mainActivity = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'MainActivity.java'), 'utf8'); const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8'); const androidMailService = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8'); +const androidPgpPolicy = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpPolicy.kt'), 'utf8'); const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8'); const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8'); const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8'); @@ -76,6 +77,12 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data', assert.match(plugin, /pgpStoreChangeWarning/); assert.match(plugin, /plaintextSendWarning/); assert.match(plugin, /Send plaintext/); + assert.match(plugin, /\.setNegativeButton\("Cancel"\) \{ _, _ -> call\.reject\("OpenPGP key change cancelled\."\) \}/); + assert.match(plugin, /\.setPositiveButton\("Confirm changes"\)[\s\S]*bridge\.execute \{[\s\S]*AndroidAccountVault\.savePgpStore\(next\)/); + assert.match(plugin, /\.setNegativeButton\("Cancel"\)[\s\S]*PLAINTEXT_CANCELLED/); + assert.match(plugin, /\.setPositiveButton\("Send plaintext"\)[\s\S]*sendPrepared\(call, input\)/); + assert.match(androidPgpPolicy, /fun storeChangeWarning/); + assert.match(androidPgpPolicy, /fun plaintextSendWarning/); assert.match(androidPgp, /curve25519Legacy/); assert.match(androidPgp, /multipart\/encrypted/); assert.match(androidPgp, /MAX_MESSAGE_BYTES = 25 \* 1024 \* 1024/);