4f7099738dff
wip: fail closed release signing and inventory merged Android release surface (v2.17.18); focused tests and negative signing check pass, full serial gate remains blocked by unavailable local signing inputs and lint analyzer failure
- time
- 2026-09-10 03:29 UTC · 2 months ago
- machine
- koh2
- agent
- camel-stream/auto
- session
- assessment assurance and conformance evidence
- parent
- d6ca03097bf4
↓ peach-android-4f709973.tar.gzatlas at this save
files changed28 files
VERSION+1 −1app/build.gradle+8 −1app/src/androidTest/java/com/peachpasswords/MainActivityDeepLinkTest.kt+34 −0app/src/main/AndroidManifest.xml+0 −6app/src/main/java/com/peachpasswords/autofill/AssistStructureParser.kt+1 −2app/src/main/java/com/peachpasswords/license/LicenseRepository.kt+11 −3app/src/main/java/com/peachpasswords/sync/RustNoiseNative.kt+1 −6app/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+3 −3app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+2 −10app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+1 −5app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+1 −2app/src/main/java/com/peachpasswords/ui/updates/UpdateScreen.kt+12 −6app/src/main/java/com/peachpasswords/ui/vault/ImportScreen.kt+1 −3app/src/main/java/com/peachpasswords/updates/UpdateCheckWorker.kt+3 −3app/src/main/java/com/peachpasswords/updates/UpdateManifest.kt+8 −23app/src/main/java/com/peachpasswords/updates/UpdateMetadataSignature.kt+0 −23app/src/main/java/com/peachpasswords/updates/UpdateRepository.kt+20 −16app/src/main/java/com/peachpasswords/vault/PasswordGenerator.kt+2 −1app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+9 −2app/src/test/java/com/peachpasswords/MainActivityManifestTest.kt+50 −0app/src/test/java/com/peachpasswords/autofill/AssistStructureOtpRegexTest.kt+4 −0app/src/test/java/com/peachpasswords/sync/CrossClientSyncProcessTest.kt+130 −0app/src/test/java/com/peachpasswords/sync/RustNoiseNativeCoverageTest.kt+33 −0app/src/test/java/com/peachpasswords/sync/VaultAdoptTest.kt+29 −3app/src/test/java/com/peachpasswords/updates/UpdateMetadataSignatureTest.kt+0 −26app/src/test/java/com/peachpasswords/vault/SlotPaddingTest.kt+21 −0app/src/test/java/com/peachpasswords/vault/VaultCryptoTest.kt+7 −2scripts/check-release-manifest.py+44 −0app/build.gradle+8 −1
@@ -68,6 +68,13 @@6868 if (localPropertiesFile.isFile()) {6969 localPropertiesFile.withInputStream { props.load(it) }7070 }71+ def signingProperties = [72+ "peachStoreFile", "peachStorePassword", "peachKeyAlias", "peachKeyPassword",73+ ]74+ def missingSigningProperties = signingProperties.findAll { !props.getProperty(it) }75+ if (!missingSigningProperties.empty && gradle.startParameter.taskNames.any { it.toLowerCase().contains("assemblerelease") }) {76+ throw new GradleException("Missing release signing inputs: ${missingSigningProperties.join(", ")}")77+ }7178 if (props.getProperty("peachStoreFile")) {7279 storeFile file(props.getProperty("peachStoreFile"))7380 storePassword props.getProperty("peachStorePassword")@@ -134,7 +141,7 @@134141 )135142 if (coreDir.exists()) {136143 dependsOn rootProject.tasks.named(name.contains("Test") ? "buildRustNoiseHostTest" : "buildRustNoiseHost")137- systemProperty "peach.noise.library.path", nativeLibrary.absolutePath144+ systemProperty "java.library.path", nativeLibrary.parentFile.absolutePath138145 }139146 }140147 }app/src/androidTest/java/com/peachpasswords/MainActivityDeepLinkTest.kt+34 −0
@@ -0,0 +1,34 @@1+package com.peachpasswords2+3+import android.content.Intent4+import android.net.Uri5+import androidx.test.ext.junit.runners.AndroidJUnit46+import androidx.test.platform.app.InstrumentationRegistry7+import org.junit.Assert.assertEquals8+import org.junit.Assert.assertFalse9+import org.junit.Test10+import org.junit.runner.RunWith11+12+@RunWith(AndroidJUnit4::class)13+class MainActivityDeepLinkTest {14+ @Test15+ fun merged_manifest_keeps_main_activity_launcher_only_and_rejects_peach_uri() {16+ val context = InstrumentationRegistry.getInstrumentation().targetContext17+ val packageManager = context.packageManager18+19+ val launcher = Intent(Intent.ACTION_MAIN)20+ .addCategory(Intent.CATEGORY_LAUNCHER)21+ .setPackage(context.packageName)22+ val launcherMatches = packageManager.queryIntentActivities(launcher, 0)23+ assertEquals(1, launcherMatches.count { it.activityInfo.name == MainActivity::class.java.name })24+25+ val peachUri = Intent(Intent.ACTION_VIEW, Uri.parse("peach://anything"))26+ .addCategory(Intent.CATEGORY_BROWSABLE)27+ assertFalse(28+ "peach://anything must not resolve to Peach",29+ packageManager.queryIntentActivities(peachUri, 0).any {30+ it.activityInfo.packageName == context.packageName31+ },32+ )33+ }34+}app/src/main/AndroidManifest.xml+0 −6
@@ -58,12 +58,6 @@5858 <action android:name="android.intent.action.MAIN" />5959 <category android:name="android.intent.category.LAUNCHER" />6060 </intent-filter>61- <intent-filter>62- <action android:name="android.intent.action.VIEW" />63- <category android:name="android.intent.category.DEFAULT" />64- <category android:name="android.intent.category.BROWSABLE" />65- <data android:scheme="peach" />66- </intent-filter>6761 <meta-data6862 android:name="android.app.shortcuts"6963 android:resource="@xml/shortcuts" />app/src/main/java/com/peachpasswords/autofill/AssistStructureParser.kt+1 −2
@@ -165,8 +165,7 @@165165 if (type and InputType.TYPE_MASK_CLASS != InputType.TYPE_CLASS_NUMBER) return false166166 val haystack = listOfNotNull(node.idEntry, node.hint, node.text?.toString())167167 .joinToString(" ").lowercase()168- return haystack.isBlank() ||169- Regex("\b(otp|2fa|mfa|one[- ]?time|verification code|auth code|pin)\b").containsMatchIn(haystack)168+ return haystack.isBlank() || OTP_HAYSTACK_RX.containsMatchIn(haystack)170169 }171170 172171 private enum class FieldKind { USERNAME, EMAIL, PASSWORD, OTP, CARD_NUMBER, CARD_EXP_MONTH, CARD_EXP_YEAR, CARD_EXP_DATE, CARD_CVC, CARD_NAME, NONE }app/src/main/java/com/peachpasswords/license/LicenseRepository.kt+11 −3
@@ -23,6 +23,9 @@2323 private const val BASE58_ALPHABET =2424 "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"2525 26+ // A 76-byte payload encodes to at most 104 base58 characters.27+ private const val MAX_BASE58_LENGTH = 10428+2629 const val PAYLOAD_SIZE = 122730 const val SIGNATURE_SIZE = 642831 const val TOTAL_SIZE = 76@@ -44,9 +47,13 @@4447 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,4548 )4649 47- fun storeLicense(key: String) {48- prefs.edit().putString(KEY_LICENSE, key).apply()49- prefs.edit().remove(KEY_PRO_CELEBRATED).apply()50+ fun storeLicense(key: String): Boolean {51+ if (!validateLicense(key)) return false52+ prefs.edit()53+ .putString(KEY_LICENSE, key)54+ .remove(KEY_PRO_CELEBRATED)55+ .apply()56+ return true5057 }5158 5259 fun getLicenseKey(): String? = prefs.getString(KEY_LICENSE, null)@@ -97,6 +104,7 @@97104 }98105 99106 private fun base58Decode(input: String): ByteArray? {107+ if (input.length > MAX_BASE58_LENGTH) return null100108 return try {101109 var n = BigInteger.ZERO102110 for (char in input) {app/src/main/java/com/peachpasswords/sync/RustNoiseNative.kt+1 −6
@@ -7,12 +7,7 @@77 */88 internal object RustNoiseNative {99 init {10- val explicitPath = System.getProperty("peach.noise.library.path")11- if (explicitPath.isNullOrBlank()) {12- System.loadLibrary("peach_noise_core")13- } else {14- System.load(explicitPath)15- }10+ System.loadLibrary("peach_noise_core")1611 }1712 1813 external fun nativeCreateNkInitiator(remotePublicKey: ByteArray): Longapp/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+3 −3
@@ -479,15 +479,15 @@479479 }480480 }481481 482+ if (receiverLicense == null) {483+ acceptedGrant.license?.let { deps.applyLicense(it) }484+ }482485 val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)483486 if (vaultId != acceptedGrant.vaultId) {484487 deps.onError("ADOPT_VAULT_ID_MISMATCH")485488 return null486489 }487490 488- if (receiverLicense == null) {489- acceptedGrant.license?.let { deps.applyLicense(it) }490- }491491 492492 val identity = deps.deriveLocalIdentity()493493 sendFrame(channel, AdoptionFrame.Identity(app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+2 −10
@@ -305,13 +305,9 @@305305 }306306 307307 override suspend fun applyLicense(licenseKey: String) {308- if (!license.validateLicense(licenseKey)) {308+ if (!license.storeLicense(licenseKey) || !license.isProActive()) {309309 throw IllegalStateException("license_transfer_failed")310310 }311- license.storeLicense(licenseKey)312- if (!license.isProActive()) {313- throw IllegalStateException("license_transfer_failed")314- }315311 }316312 317313 override suspend fun license(): String? =@@ -384,11 +380,7 @@384380 license.getLicenseKey()?.takeIf(license::validateLicense)385381 386382 override suspend fun applyLicense(licenseKey: String) {387- if (!license.validateLicense(licenseKey)) {388- throw IllegalStateException("license_transfer_failed")389- }390- license.storeLicense(licenseKey)391- if (!license.isProActive()) {383+ if (!license.storeLicense(licenseKey) || !license.isProActive()) {392384 throw IllegalStateException("license_transfer_failed")393385 }394386 }app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+1 −5
@@ -179,11 +179,7 @@179179 license.getLicenseKey()?.takeIf(license::validateLicense)180180 181181 override suspend fun applyLicense(licenseKey: String) {182- if (!license.validateLicense(licenseKey)) {183- throw IllegalStateException("license_transfer_failed")184- }185- license.storeLicense(licenseKey)186- if (!license.isProActive()) {182+ if (!license.storeLicense(licenseKey) || !license.isProActive()) {187183 throw IllegalStateException("license_transfer_failed")188184 }189185 }app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+1 −2
@@ -248,8 +248,7 @@248248 _activationError.value = null249249 viewModelScope.launch {250250 val key = rawKey.trim()251- if (license.validateLicense(key)) {252- license.storeLicense(key)251+ if (license.storeLicense(key)) {253252 _isPro.value = true254253 _licenseKey.value = key255254 _licenseIssuedAt.value = license.licenseIssuedAtMillis(key)app/src/main/java/com/peachpasswords/ui/updates/UpdateScreen.kt+12 −6
@@ -44,6 +44,7 @@4444 import androidx.hilt.navigation.compose.hiltViewModel4545 import androidx.lifecycle.ViewModel4646 import androidx.lifecycle.viewModelScope47+import dagger.hilt.android.lifecycle.HiltViewModel4748 import com.peachpasswords.ui.components.PeachSectionHeader4849 import com.peachpasswords.ui.theme.LocalPeachAccent4950 import com.peachpasswords.ui.theme.PeachSpacing@@ -53,8 +54,8 @@5354 import com.peachpasswords.updates.ChecksumMismatchException5455 import com.peachpasswords.updates.ReleaseManifest5556 import com.peachpasswords.updates.ReleaseNote57+import com.peachpasswords.updates.UpdateCheckResult5658 import com.peachpasswords.updates.UpdateRepository57-import dagger.hilt.android.lifecycle.HiltViewModel5859 import kotlinx.coroutines.flow.MutableStateFlow5960 import kotlinx.coroutines.flow.StateFlow6061 import kotlinx.coroutines.flow.asStateFlow@@ -124,11 +125,16 @@124125 _state.value = _state.value.copy(phase = UpdatePhase.Checking, error = null)125126 viewModelScope.launch {126127 _state.value = try {127- val manifest = updates.check()128- if (manifest == null) {129- UpdateUiState(phase = UpdatePhase.UpToDate)130- } else {131- UpdateUiState(phase = UpdatePhase.Available, manifest = manifest)128+ when (val result = updates.check()) {129+ is UpdateCheckResult.Accepted -> UpdateUiState(130+ phase = UpdatePhase.Available,131+ manifest = result.manifest,132+ )133+ is UpdateCheckResult.NoUpdate -> UpdateUiState(phase = UpdatePhase.UpToDate)134+ is UpdateCheckResult.RollbackSuppressed -> _state.value.copy(135+ phase = if (_state.value.manifest != null) UpdatePhase.Available else UpdatePhase.UpToDate,136+ error = "A rollback was suppressed (served ${result.servedVersion}; local high-water ${result.highWaterVersion}).",137+ )132138 }133139 } catch (e: Exception) {134140 // A failed re-check doesn't invalidate an update we already knowapp/src/main/java/com/peachpasswords/ui/vault/ImportScreen.kt+1 −3
@@ -360,9 +360,7 @@360360 }361361 withContext(Dispatchers.Default) {362362 preview.settings?.let { vault.updateSettings(it) }363- preview.licenseKey364- ?.takeIf { license.validateLicense(it) }365- ?.let { license.storeLicense(it) }363+ preview.licenseKey?.let { license.storeLicense(it) }366364 }367365 _state.value = ImportUiState.Done(imported, createdVault = createdVault)368366 } catch (e: Exception) {app/src/main/java/com/peachpasswords/updates/UpdateCheckWorker.kt+3 −3
@@ -43,14 +43,14 @@4343 ) : CoroutineWorker(appContext, params) {4444 4545 override suspend fun doWork(): Result {46- val manifest = try {46+ val outcome = try {4747 updates.check()4848 } catch (e: Exception) {4949 // Offline, DNS failure, a repo not registered yet — all transient from5050 // here. Never surface a failed background check to the user.5151 return Result.retry()52- } ?: return Result.success()53-52+ }53+ val manifest = (outcome as? UpdateCheckResult.Accepted)?.manifest ?: return Result.success()5454 if (updates.shouldNotifyFor(manifest.version) &&5555 postUpdateNotification(applicationContext, manifest.version)5656 ) {app/src/main/java/com/peachpasswords/updates/UpdateManifest.kt+8 −23
@@ -24,10 +24,6 @@2424 val checksum: String,2525 /** Absent — not empty, not "null" — when the release carries no notes. */2626 val notes: String?,27- /** Base64 Ed25519 signature over the canonical release metadata payload. */28- val signature: String = "",29- /** Provenance source bound into [signature]. */30- val provenanceSource: String = "",3127 /** Kepr platform key represented by this flattened manifest. */3228 val platformKey: String = ANDROID_PLATFORM_KEY,3329 ) {@@ -37,27 +33,13 @@3733 put("platforms", JSONObject().put(platformKey, JSONObject().apply {3834 put("url", url)3935 put(checksum.substringBefore(':'), checksum.substringAfter(':'))40- put("provenance", JSONObject().apply {41- put("version", version)42- put("platform", platformKey)43- put("checksum", checksum)44- put("source", provenanceSource)45- })46- put("signature", signature)4736 }))4837 }.toString()4938 5039 companion object {51- /**52- * The cached manifest is re-read straight into the download path, so it53- * has to clear the same strict-SemVer bar [parseReleaseManifest] applies54- * to a fresh fetch — otherwise a rewritten cache entry reaches55- * `downloadAndVerify`, whose filename safety argument rests on that56- * validation having happened. A malformed cache entry parses to null,57- * which callers already treat as "no update known".58- */40+ /** Cached and network manifests share the same strict parser. */5941 fun fromCachedJson(json: String): ReleaseManifest? = runCatching {60- parseSignedReleaseManifest(json)42+ parseReleaseManifest(json)6143 }.getOrNull()6244 }6345 }@@ -84,6 +66,11 @@8466 else -> null8567 }8668 69+sealed interface UpdateCheckResult {70+ data class Accepted(val manifest: ReleaseManifest) : UpdateCheckResult71+ data class NoUpdate(val version: String) : UpdateCheckResult72+ data class RollbackSuppressed(val servedVersion: String, val highWaterVersion: String) : UpdateCheckResult73+}8774 /**8875 * Hard ceiling on a downloaded APK. Kepr publishes ~24 MB today; 50 MB leaves8976 * headroom for growth without letting a hostile manifest exhaust cache or disk.@@ -199,9 +186,7 @@199186 *200187 * Security note: the canonical platform key is required and the sole-artifact201188 * fallback is gone. A Kepr build that only published, say, `android-x86` would202- * otherwise point an Android phone at the wrong binary; signed metadata is now203- * verified by [parseSignedReleaseManifest] before this parser is used by the204- * update network path.189+ * otherwise point an Android phone at the wrong binary.205190 */206191 fun parseReleaseManifest(body: String, platformKey: String = ANDROID_PLATFORM_KEY): ReleaseManifest {207192 val root = runCatching { JSONObject(body) }app/src/main/java/com/peachpasswords/updates/UpdateMetadataSignature.kt+0 −23
@@ -1,23 +0,0 @@1-package com.peachpasswords.updates2-3-import org.json.JSONObject4-5-internal fun canonicalReleaseMetadataPayload(6- version: String,7- platform: String,8- url: String,9- checksumHex: String,10- provenanceSource: String,11-): ByteArray = "$version\\n$platform\\n$url\\n$checksumHex\\n$version\\n$platform\\n$checksumHex\\n$provenanceSource"12- .toByteArray(Charsets.UTF_8)13-14-/**15- * Compatibility parser for release metadata produced by the established Kepr16- * APK release workflow. APK integrity is verified after download; release17- * metadata does not require a separate update-signing key.18- */19-fun parseSignedReleaseManifest(20- body: String,21- platformKey: String = ANDROID_PLATFORM_KEY,22- publicKeyHex: String = "",23-): ReleaseManifest = parseReleaseManifest(body, platformKey)app/src/main/java/com/peachpasswords/updates/UpdateRepository.kt+20 −16
@@ -79,26 +79,30 @@7979 /* ──────────────────────────────── check ──────────────────────────────── */8080 8181 /**82- * Fetch the release manifest and reconcile it against the running build.83- * Returns the manifest when a newer version exists, null when up to date.84- * Throws on network/parse failure — callers decide whether that is worth85- * surfacing (the periodic worker retries; the Settings "check now" reports).82+ * Fetch and reconcile the release manifest. A suppressed rollback never83+ * changes the currently offerable manifest or the persisted high-water mark.8684 */87- suspend fun check(): ReleaseManifest? {85+ suspend fun check(): UpdateCheckResult {8886 val manifest = fetchLatest()89- val newer = isNewerVersion(manifest.version, currentVersion)87+ val highWater = prefs.getString(KEY_VERSION_HIGH_WATER, null)88+ if (highWater != null && compareVersions(manifest.version, highWater) < 0) {89+ return UpdateCheckResult.RollbackSuppressed(manifest.version, highWater)90+ }9091 91- _available.value = manifest.takeIf { newer }92- prefs.edit().apply {93- if (newer) putString(KEY_LATEST_MANIFEST, manifest.toJson()) else remove(KEY_LATEST_MANIFEST)94- }.apply()92+ if (highWater == null || compareVersions(manifest.version, highWater) > 0) {93+ prefs.edit().putString(KEY_VERSION_HIGH_WATER, manifest.version).apply()94+ }9595 96- // The manifest for the version we're already running is the only place the97- // post-update changelog can come from, so cache it the moment we see it.96+ val newer = isNewerVersion(manifest.version, currentVersion)97+ if (newer) {98+ _available.value = manifest99+ prefs.edit().putString(KEY_LATEST_MANIFEST, manifest.toJson()).apply()100+ }101+102+ // The manifest for the version we're already running is the only place103+ // the post-update changelog can come from, so cache it when observed.98104 if (normalizeVersion(manifest.version) == currentVersion) {99105 if (manifest.notes == null) {100- // Genuinely no notes for this release — nothing to ever show, so101- // stop waiting for them rather than leaving the flag armed forever.102106 markChangelogSeen()103107 } else {104108 prefs.edit()@@ -108,7 +112,7 @@108112 refreshWhatsNew()109113 }110114 }111- return _available.value115+ return if (newer) UpdateCheckResult.Accepted(manifest) else UpdateCheckResult.NoUpdate(manifest.version)112116 }113117 114118 private suspend fun fetchLatest(): ReleaseManifest = withContext(Dispatchers.IO) {@@ -447,13 +451,13 @@447451 const val KEPR_REPO = "peach-android"448452 const val LATEST_RELEASE_URL = "https://kepr.uk/api/$KEPR_REPO/releases/latest"449453 const val HISTORY_URL = "https://kepr.uk/api/$KEPR_REPO/releases/history"450-451454 private const val APK_MIME = "application/vnd.android.package-archive"452455 private const val USER_AGENT = "Peach-Android"453456 private const val CACHE_DIR = "updates"454457 455458 private const val PREFS = "peach_updates"456459 private const val KEY_LATEST_MANIFEST = "latest_manifest"460+ private const val KEY_VERSION_HIGH_WATER = "version_high_water"457461 private const val KEY_LAST_SEEN_VERSION = "last_seen_changelog_version"458462 private const val KEY_NOTES_VERSION = "notes_version"459463 private const val KEY_NOTES = "notes"app/src/main/java/com/peachpasswords/vault/PasswordGenerator.kt+2 −1
@@ -19,6 +19,7 @@1919 private const val SYMBOLS = "!@#$%^&*"2020 2121 private val rng = SecureRandom()22+ private val passphraseWords = EffShortWordList.words.filterNot { it.contains("-") }2223 2324 data class Options(2425 val length: Int = 20,@@ -52,7 +53,7 @@5253 separator: String = "-",5354 ): String {5455 val count = wordCount.coerceIn(MIN_PASSPHRASE_WORDS, MAX_PASSPHRASE_WORDS)55- return List(count) { EffShortWordList.words[rng.nextInt(EffShortWordList.words.size)] }56+ return List(count) { passphraseWords[rng.nextInt(passphraseWords.size)] }5657 .joinToString(separator)5758 }5859 }app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+9 −2
@@ -21,6 +21,7 @@2121 const val DURESS_SLOT_SIZE = 262_1442222 2323 val PADDING_BUCKETS = intArrayOf(1024, 4096, 16384, 65536, 262144)24+ private const val LARGE_PADDING_STEP = 65_5362425 2526 const val AAD_SLOT_A = "slot_a_v1"2627 const val AAD_SLOT_B = "slot_b_v1"@@ -127,8 +128,14 @@127128 fun generateNoise(): ByteArray = ByteArray(DURESS_SLOT_SIZE).also(secureRandom::nextBytes)128129 129130 fun padToBucket(data: ByteArray): ByteArray {130- val target = PADDING_BUCKETS.firstOrNull { it >= data.size } ?: data.size131- return data.copyOf(target)131+ val target = PADDING_BUCKETS.firstOrNull { it >= data.size }?.toLong()132+ ?: run {133+ val size = data.size.toLong()134+ val remainder = size % LARGE_PADDING_STEP135+ size + if (remainder == 0L) 0L else LARGE_PADDING_STEP - remainder136+ }137+ require(target <= Int.MAX_VALUE) { "padded plaintext is too large" }138+ return data.copyOf(target.toInt())132139 }133140 134141 fun padToBlock(data: ByteArray): ByteArray {app/src/test/java/com/peachpasswords/MainActivityManifestTest.kt+50 −0
@@ -0,0 +1,50 @@1+package com.peachpasswords2+3+import java.io.File4+import javax.xml.parsers.DocumentBuilderFactory5+import org.junit.Assert.assertEquals6+import org.junit.Assert.assertTrue7+import org.junit.Test8+import org.w3c.dom.Element9+10+class MainActivityManifestTest {11+ @Test12+ fun main_activity_declares_only_the_launcher_filter() {13+ val manifest = manifestFile()14+ val document = DocumentBuilderFactory.newInstance().apply {15+ isNamespaceAware = true16+ }.newDocumentBuilder().parse(manifest)17+ val activities = document.getElementsByTagName("activity")18+ val mainActivity = (0 until activities.length)19+ .mapNotNull { activities.item(it) as? Element }20+ .single { it.getAttributeNS(ANDROID_NAMESPACE, "name") == ".MainActivity" }21+22+ val filters = mainActivity.getElementsByTagName("intent-filter")23+ assertEquals("MainActivity must have only its launcher filter", 1, filters.length)24+ val filter = filters.item(0) as Element25+ val actions = filter.getElementsByTagName("action")26+ val categories = filter.getElementsByTagName("category")27+ assertEquals(1, actions.length)28+ assertEquals(29+ "android.intent.action.MAIN",30+ (actions.item(0) as Element).getAttributeNS(ANDROID_NAMESPACE, "name"),31+ )32+ assertEquals(1, categories.length)33+ assertEquals(34+ "android.intent.category.LAUNCHER",35+ (categories.item(0) as Element).getAttributeNS(ANDROID_NAMESPACE, "name"),36+ )37+ assertTrue(38+ "MainActivity must not declare a custom peach URI handler",39+ filter.getElementsByTagName("data").length == 0,40+ )41+ }42+43+ private fun manifestFile(): File = File("src/main/AndroidManifest.xml")44+ .takeIf { it.isFile }45+ ?: File("app/src/main/AndroidManifest.xml")46+47+ private companion object {48+ const val ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android"49+ }50+}app/src/test/java/com/peachpasswords/autofill/AssistStructureOtpRegexTest.kt+4 −0
@@ -25,6 +25,10 @@2525 assertTrue(rx.containsMatchIn("auth code"))2626 }2727 28+ @Test fun does_not_match_card_number_label() {29+ assertFalse(rx.containsMatchIn("card number"))30+ }31+2832 @Test fun matches_labels_real_forms_use() {2933 // These were silent misses before the widening.3034 assertTrue(rx.containsMatchIn("verification"))app/src/test/java/com/peachpasswords/sync/CrossClientSyncProcessTest.kt+130 −0
@@ -0,0 +1,130 @@1+package com.peachpasswords.sync2+3+import java.io.BufferedReader4+import java.io.BufferedWriter5+import java.io.File6+import java.io.InputStreamReader7+import java.io.OutputStreamWriter8+import java.net.InetSocketAddress9+import java.net.ServerSocket10+import java.net.Socket11+import java.util.Base6412+import kotlinx.coroutines.runBlocking13+import org.junit.Assert.assertEquals14+import org.junit.Test15+16+/**17+ * Process endpoint for scripts/check-cross-client-sync.mjs. The socket carries18+ * one base64-encoded production SyncMessage frame per line; the transcript is19+ * kept separately so the parent process can assert every ordered wire type.20+ */21+class CrossClientSyncProcessTest {22+ @Test23+ fun exchange_production_frames_with_browser_process() {24+ val mode = configured("PEACH_SYNC_HARNESS_MODE") ?: return25+ val portFile = File(requireConfigured("PEACH_SYNC_HARNESS_PORT_FILE"))26+ val transcriptFile = File(requireConfigured("PEACH_SYNC_HARNESS_TRANSCRIPT_FILE"))27+ val mismatch = configured("PEACH_SYNC_HARNESS_MISMATCH") == "message-order"28+ val socket = if (mode == "initiator") {29+ ServerSocket(0).also {30+ portFile.writeText(it.localPort.toString())31+ }.accept().also { portFile.delete() }32+ } else {33+ Socket().also {34+ it.connect(InetSocketAddress("127.0.0.1", requireConfigured("PEACH_SYNC_HARNESS_PORT").toInt()), 5_000)35+ }36+ }37+38+ socket.use { raw ->39+ val input = BufferedReader(InputStreamReader(raw.getInputStream(), Charsets.UTF_8))40+ val output = BufferedWriter(OutputStreamWriter(raw.getOutputStream(), Charsets.UTF_8))41+ val transcript = mutableListOf<String>()42+ val session = SyncSession(43+ remoteStaticPublicKey = ByteArray(32) { 7 },44+ send = { bytes ->45+ val message = decodeSyncMessage(bytes)46+ val wireMessage = if (mismatch && message is SyncMessage.Manifest) {47+ SyncMessage.Request(emptyList())48+ } else message49+ transcript += "send:${messageType(wireMessage)}"50+ val wire = wireMessage.encodeToBytes()51+ output.write(Base64.getEncoder().encodeToString(wire))52+ output.newLine()53+ output.flush()54+ },55+ receive = {56+ val line = input.readLine() ?: error("cross-client peer closed")57+ val bytes = Base64.getDecoder().decode(line)58+ val message = decodeSyncMessage(bytes)59+ transcript += "recv:${messageType(message)}"60+ bytes61+ },62+ close = {},63+ )64+ val vault = ProcessVault(if (mode == "initiator") "android" else "browser")65+ val outcome = runBlocking {66+ if (mode == "initiator") runSyncInitiator(session, vault, nowMs = System.currentTimeMillis())67+ else runSyncResponder(session, vault, nowMs = System.currentTimeMillis())68+ }69+ transcriptFile.writeText(70+ buildString {71+ append("{\"status\":\"").append(outcome.status.name).append("\"")72+ outcome.error?.let { append(",\"error\":\"").append(it.replace("\"", "\\\"")) .append("\"") }73+ append(",\"events\":[")74+ transcript.forEachIndexed { index, event ->75+ if (index > 0) append(',')76+ append('\"').append(event).append('\"')77+ }78+ append("]}")79+ },80+ )81+ assertEquals("Android process sync outcome", if (mismatch) SyncOutcomeStatus.ERRORED else SyncOutcomeStatus.COMPLETED, outcome.status)82+ }83+ }84+85+ private fun configured(name: String): String? =86+ System.getenv(name) ?: System.getProperty(name.lowercase().replace('_', '.'))87+88+ private fun requireConfigured(name: String): String =89+ configured(name) ?: error("missing $name")90+91+ private fun messageType(message: SyncMessage): String = when (message) {92+ is SyncMessage.Hello -> "SYNC_HELLO"93+ is SyncMessage.Manifest -> "SYNC_MANIFEST"94+ is SyncMessage.Request -> "SYNC_REQUEST"95+ is SyncMessage.Entries -> "SYNC_ENTRIES"96+ is SyncMessage.Tombstones -> "SYNC_TOMBSTONES"97+ is SyncMessage.DeviceManifest -> "SYNC_DEVICE_MANIFEST"98+ is SyncMessage.Done -> "SYNC_DONE"99+ is SyncMessage.Error -> "SYNC_ERROR"100+ }101+102+ private class ProcessVault(private val id: String) : SyncVaultAdapter {103+ private val entries = linkedMapOf("$id-entry" to if (id == "android") 20L else 10L)104+ private val blobs = linkedMapOf("$id-entry" to if (id == "android") "android-frame" else "browser-frame")105+ private val tombstones = emptyMap<String, Long>()106+ private val manifest = SignedDeviceManifest(107+ DeviceManifestBody(DEVICE_MANIFEST_VERSION, id, 1_700_000_000_000L, emptyList()),108+ "11".repeat(64),109+ )110+111+ override suspend fun computeVaultId() = "cross-client-vault"112+ override suspend fun getOurDeviceId() = id113+ override suspend fun getLocalVersion() = 7L114+ override suspend fun buildEntryManifest() = entries.toMap()115+ override suspend fun buildTombstoneManifest() = tombstones116+ override suspend fun getEncryptedEntries(entryIds: List<String>) =117+ entryIds.mapNotNull { key -> blobs[key]?.let { key to it } }.toMap()118+ override suspend fun applyEntries(entries: Map<String, String>, remoteManifest: Map<String, Long>) {119+ this.entries.putAll(entries.mapValues { remoteManifest[it.key] ?: 0L })120+ blobs.putAll(entries)121+ }122+ override suspend fun applyTombstones(tombstones: Map<String, Long>) = Unit123+ override suspend fun buildOutgoingDeviceManifest() = manifest124+ override suspend fun applyIncomingDeviceManifest(125+ manifest: SignedDeviceManifest,126+ authenticatedRemoteStaticPublicKey: ByteArray,127+ ) = Unit128+ override val supportsDeviceManifest = true129+ }130+}app/src/test/java/com/peachpasswords/sync/RustNoiseNativeCoverageTest.kt+33 −0
@@ -0,0 +1,33 @@1+package com.peachpasswords.sync2+3+import org.junit.Assert.assertFalse4+import org.junit.Assert.assertTrue5+import org.junit.Test6+import java.io.File7+8+class RustNoiseNativeCoverageTest {9+ @Test10+ fun `release Noise loader uses only the packaged library name`() {11+ val source = projectFile("app/src/main/java/com/peachpasswords/sync/RustNoiseNative.kt").readText()12+13+ assertTrue(source.contains("System.loadLibrary(\"peach_noise_core\")"))14+ assertFalse(source.contains("System.load("))15+ assertFalse(source.contains("peach.noise.library.path"))16+ assertFalse(source.contains("System.getProperty"))17+ }18+19+ @Test20+ fun `host loading configuration stays outside the release loader`() {21+ val gradle = projectFile("app/build.gradle").readText()22+ val rustBuild = projectFile("scripts/build-noise-core.sh").readText()23+24+ assertTrue(gradle.contains("target/release/libpeach_noise_core.dylib"))25+ assertTrue(gradle.contains("systemProperty \"java.library.path\""))26+ assertFalse(gradle.contains("systemProperty \"peach.noise.library.path\""))27+ assertFalse(rustBuild.contains("test-constructors"))28+ }29+ private fun projectFile(relativePath: String): File =30+ listOf(File(relativePath), File("../$relativePath"), File("../../$relativePath"))31+ .firstOrNull { it.exists() && (relativePath != "build.gradle" || it.readText().contains("PEACH_NOISE_CORE_FEATURES")) }32+ ?: error("project file not found: $relativePath")33+}app/src/test/java/com/peachpasswords/sync/VaultAdoptTest.kt+29 −3
@@ -550,11 +550,11 @@550550 assertNull(receiver.createCalledWith)551551 }552552 553- @Test fun does_not_apply_license_when_vault_creation_fails() = runBlocking {553+ @Test fun applies_valid_license_before_vault_creation_failure() = runBlocking {554554 val (receiverCh, sourceCh) = memoryPair()555555 val rootKeyHex = "44".repeat(32)556556 val vaultId = vaultIdFor(rootKeyHex)557- val receiver = RecorderReceiver("Receiver", DeviceType.ANDROID, vaultId, createThrows = true)557+ val receiver = RecorderReceiver("Receiver", DeviceType.ANDROID, vaultId, createThrows = true, localLicense = null)558558 val recvJob = async {559559 runCatching { requestAdoption(receiverCh, receiver) { 0L } }560560 }@@ -568,7 +568,33 @@568568 val outcome = recvJob.await()569569 570570 assertTrue(outcome.isFailure)571- assertNull(receiver.licenseApplied)571+ assertEquals("PPK-test", receiver.licenseApplied)572+ assertEquals(rootKeyHex, receiver.createCalledWith)573+ }574+575+ @Test fun invalid_license_fails_before_vault_creation() = runBlocking {576+ val (receiverCh, sourceCh) = memoryPair()577+ val rootKeyHex = "45".repeat(32)578+ val vaultId = vaultIdFor(rootKeyHex)579+ val receiver = object : RecorderReceiver("Receiver", DeviceType.ANDROID, vaultId, localLicense = null) {580+ override suspend fun applyLicense(license: String) {581+ throw IllegalStateException("license_transfer_failed")582+ }583+ }584+ val receiverJob = async { runCatching { requestAdoption(receiverCh, receiver) { 0L } } }585+ receiveFrame(sourceCh)586+ sendFrame(sourceCh, AdoptionFrame.Grant(587+ rootKeyHex = rootKeyHex,588+ vaultId = vaultId,589+ license = "PPK-invalid",590+ source = AdoptionFrame.Source("source", "Source", "extension", "ab".repeat(32)),591+ ))592+593+ val outcome = receiverJob.await()594+ assertTrue(outcome.isFailure)595+ assertEquals("license_transfer_failed", outcome.exceptionOrNull()?.message)596+ assertNull(receiver.createCalledWith)597+ assertTrue(receiver.upserted.isEmpty())572598 }573599 574600 @Test fun validator_rejects_short_and_uppercase_root_keys() {app/src/test/java/com/peachpasswords/updates/UpdateMetadataSignatureTest.kt+0 −26
@@ -1,26 +0,0 @@1-package com.peachpasswords.updates2-3-import org.junit.Assert.assertEquals4-import org.junit.Test5-6-class UpdateMetadataSignatureTest {7- @Test8- fun `established release metadata without a separate signature is accepted`() {9- val body = """10- {11- "version":"2.15.5",12- "platforms":{13- "$ANDROID_PLATFORM_KEY":{14- "url":"https://kepr.uk/peach-android/releases/2.15.5/android-arm64",15- "blake3":"${"a".repeat(64)}"16- }17- }18- }19- """.trimIndent()20-21- assertEquals(22- "https://kepr.uk/peach-android/releases/2.15.5/android-arm64",23- parseReleaseManifest(body).url,24- )25- }26-}app/src/test/java/com/peachpasswords/vault/SlotPaddingTest.kt+21 −0
@@ -46,6 +46,27 @@4646 assertEquals("X", VaultCodec.decode(raw).rootKeyB64)4747 }4848 49+ @Test fun above_top_bucket_vault_codec_round_trip_preserves_payload() {50+ val notes = "n".repeat(300_000)51+ val payload = VaultPayload(52+ entries = listOf(53+ VaultEntry(54+ id = "large",55+ title = "Large note",56+ type = "note",57+ notes = notes,58+ createdAt = 0,59+ modifiedAt = 0,60+ ),61+ ),62+ rootKeyB64 = "root",63+ )64+65+ val encoded = VaultCodec.encode(payload)66+ assertEquals(327680, encoded.size)67+ assertEquals(notes, VaultCodec.decode(encoded).entries.single().notes)68+ }69+4970 @Test fun real_and_duress_slots_share_a_bucket_for_small_vaults() = runBlocking {5071 val storage = PaddingFakeStorage()5172 val repo = VaultRepository(storage)app/src/test/java/com/peachpasswords/vault/VaultCryptoTest.kt+7 −2
@@ -151,8 +151,13 @@151151 assertEquals(262144, VaultCrypto.padToBucket(ByteArray(70000)).size)152152 }153153 154- @Test fun pad_to_bucket_beyond_largest_keeps_size() {155- assertEquals(300000, VaultCrypto.padToBucket(ByteArray(300000)).size)154+ @Test fun pad_to_bucket_keeps_the_top_bucket_boundary() {155+ assertEquals(262144, VaultCrypto.padToBucket(ByteArray(262144)).size)156+ }157+158+ @Test fun pad_to_bucket_rounds_above_top_to_the_next_64k_multiple() {159+ assertEquals(327680, VaultCrypto.padToBucket(ByteArray(262145)).size)160+ assertEquals(327680, VaultCrypto.padToBucket(ByteArray(300000)).size)156161 }157162 158163 @Test fun pad_to_block_rounds_up_to_1024() {scripts/check-release-manifest.py+44 −0
@@ -0,0 +1,44 @@1+#!/usr/bin/env python32+"""Check the checked-in Android release manifest inventory against merged output."""3+4+from pathlib import Path5+import sys6+import xml.etree.ElementTree as ET7+8+ANDROID_NS = "{http://schemas.android.com/apk/res/android}"9+ROOT = Path(__file__).resolve().parents[1]10+INVENTORY = ROOT / "docs" / "android-release-manifest-inventory.txt"11+MERGED = ROOT / "app" / "build" / "intermediates" / "merged_manifest" / "release" / "processReleaseMainManifest" / "AndroidManifest.xml"12+13+14+def inventory(path: Path) -> str:15+ root = ET.parse(path).getroot()16+ lines = []17+ for permission in sorted(root.findall("uses-permission"), key=lambda node: node.get(ANDROID_NS + "name", "")):18+ lines.append(f"permission|{permission.get(ANDROID_NS + 'name', '')}")19+ application = root.find("application")20+ if application is None:21+ raise SystemExit("release manifest has no application")22+ for child in sorted(application, key=lambda node: (node.tag, node.get(ANDROID_NS + "name", ""))):23+ name = child.get(ANDROID_NS + "name", "")24+ exported = child.get(ANDROID_NS + "exported", "")25+ permission = child.get(ANDROID_NS + "permission", "")26+ lines.append(f"component|{child.tag}|{name}|exported={exported}|permission={permission}")27+ for intent_filter in child.findall("intent-filter"):28+ actions = sorted(action.get(ANDROID_NS + "name", "") for action in intent_filter.findall("action"))29+ categories = sorted(category.get(ANDROID_NS + "name", "") for category in intent_filter.findall("category"))30+ lines.append(f"intent-filter|{child.tag}|{name}|actions={','.join(actions)}|categories={','.join(categories)}")31+ return "\n".join(lines) + "\n"32+33+34+if len(sys.argv) != 2:35+ raise SystemExit(f"usage: {Path(sys.argv[0]).name} check|write")36+if sys.argv[1] == "write":37+ INVENTORY.write_text(inventory(MERGED))38+elif sys.argv[1] == "check":39+ actual = inventory(MERGED)40+ expected = INVENTORY.read_text()41+ if actual != expected:42+ raise SystemExit("merged release manifest differs from checked-in inventory")43+else:44+ raise SystemExit(f"unknown command: {sys.argv[1]}")