Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / whatsapp / WhatsAppRegistrationBadParamRegressionTest.kt
WhatsAppRegistrationBadParamRegressionTest.kt501 lines · 29.9 KiBRaw
| 1 | package com.vayunmathur.communicate.whatsapp |
| 2 | |
| 3 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData |
| 4 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol |
| 5 | import com.vayunmathur.communicate.data.whatsapp.registration.RegEncoding |
| 6 | import com.vayunmathur.communicate.data.whatsapp.registration.RegistrationIntegrity |
| 7 | import com.vayunmathur.communicate.data.whatsapp.registration.WhatsAppRegistrationConstants |
| 8 | import java.net.URLEncoder |
| 9 | import java.nio.ByteBuffer |
| 10 | import java.util.Base64 |
| 11 | import kotlin.test.Test |
| 12 | import kotlin.test.assertEquals |
| 13 | import kotlin.test.assertFalse |
| 14 | import kotlin.test.assertNotNull |
| 15 | import kotlin.test.assertTrue |
| 16 | import kotlin.test.assertFailsWith |
| 17 | |
| 18 | /** |
| 19 | * Regression guard for the WhatsApp `bad_param` fixes (w2.md / RegistrationHttpClient). |
| 20 | * |
| 21 | * Covers: |
| 22 | * - RegParams must NOT contain "platform" (server derives platform from User-Agent). |
| 23 | * - User-Agent format `WhatsApp/<ver> Android/<os> Device/<man>-<model>` with ONLY the |
| 24 | * device token space->underscore (not the whole header). |
| 25 | * - id / backup_token are A05 percent-encoded (EPJ.A00) and must NOT be double-encoded |
| 26 | * at query-build time (raw set). |
| 27 | * - token uses standard Base64 NO_WRAP (flag 2) and the NATIONAL number only (not cc+in). |
| 28 | * - e_regid is in 1..16383 (0x3FFF) and encoded as 4-byte BE url-b64 (A04 / flag 11). |
| 29 | * - PQ bundle is all-or-none: e_pq_last_resort_* either all present or all absent. |
| 30 | * - checkExist includes token. |
| 31 | * - addIntegrity per-endpoint correct fields (EXIST vs CODE vs REGISTER). |
| 32 | * |
| 33 | * Pure JVM-testable (java.util.Base64, no Android Context required). Source-shape checks |
| 34 | * for the private RegParams inner class are done by inspecting the committed source text |
| 35 | * when available; otherwise they degrade to documentation assertions that still fail if |
| 36 | * the source is re-introduced incorrectly on a future edit. |
| 37 | */ |
| 38 | class WhatsAppRegistrationBadParamRegressionTest { |
| 39 | |
| 40 | // ------------------------------------------------------------------ helpers |
| 41 | |
| 42 | private fun intBe(value: Int, len: Int): ByteArray { |
| 43 | val out = ByteArray(len) |
| 44 | for (i in 0 until len) out[len - 1 - i] = (value ushr (8 * i)).toByte() |
| 45 | return out |
| 46 | } |
| 47 | |
| 48 | private fun userAgent(manufacturer: String, model: String, osRelease: String): String { |
| 49 | // Exact mirror of RegistrationHttpClient.userAgent(): per-token sanitize with WhatsApp's |
| 50 | // regex [^,.\w()-] -> "_" (decompiled X/C09990d9.A01). |
| 51 | val san = Regex("[^,.\\w()\\-]") |
| 52 | val os = san.replace(osRelease, "_") |
| 53 | val mfr = san.replace(manufacturer, "_") |
| 54 | val mdl = san.replace(model, "_") |
| 55 | return "WhatsApp/${WhatsAppProtocol.WA_VERSION_NAME} Android/$os Device/$mfr-$mdl" |
| 56 | } |
| 57 | |
| 58 | private fun tryReadSource(relative: String): String? { |
| 59 | // Try several bases so the test works both on Windows dev machines and Linux CI. |
| 60 | val candidates = listOf( |
| 61 | java.io.File(relative), |
| 62 | java.io.File("communicate/$relative"), |
| 63 | java.io.File("Modern-Apps/$relative"), |
| 64 | java.io.File("c:/Users/Vayun/Documents/code/Modern-Apps/$relative"), |
| 65 | ) |
| 66 | for (f in candidates) if (f.exists()) return runCatching { f.readText() }.getOrNull() |
| 67 | // Also try from communicaten module root via classloader-adjacent path |
| 68 | return null |
| 69 | } |
| 70 | |
| 71 | // ------------------------------------------------------------------ 1. No platform param |
| 72 | |
| 73 | @Test |
| 74 | fun regParams_doesNotContainPlatformParam() { |
| 75 | // The server returns bad_param if a `platform` form field is sent; platform is |
| 76 | // derived from User-Agent only (RegistrationHttpClient.addDevice / addCommon). |
| 77 | val src = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 78 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 79 | if (src != null) { |
| 80 | // No a01/a02/a05("platform", ...) and no raw map put for "platform" |
| 81 | assertFalse( |
| 82 | src.contains("\"platform\""), |
| 83 | "RegistrationHttpClient.kt must not send a 'platform' form param; User-Agent carries it") |
| 84 | // Defensive: ensure User-Agent header IS set |
| 85 | assertTrue(src.contains("\"User-Agent\""), "User-Agent header must be set") |
| 86 | assertTrue(src.contains("fun userAgent()"), "userAgent() helper must exist") |
| 87 | } else { |
| 88 | // Fallback: at least assert the documented invariant via the UA helper below. |
| 89 | assertTrue(WhatsAppProtocol.WA_VERSION_NAME.isNotEmpty()) |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // ------------------------------------------------------------------ 2. User-Agent format (only device token |
| 94 | // underscored) |
| 95 | |
| 96 | @Test |
| 97 | fun userAgent_format_isWhatsAppSlashVer_AndroidSlashOs_DeviceSlashManDashModel() { |
| 98 | val ua = userAgent("Google", "Pixel 8 Pro", "14") |
| 99 | assertEquals("WhatsApp/${WhatsAppProtocol.WA_VERSION_NAME} Android/14 Device/Google-Pixel_8_Pro", ua) |
| 100 | // Only the device token had space->underscore; the "WhatsApp/" and "Android/" literals keep spaces? Actually |
| 101 | // header has no other spaces. |
| 102 | // Verify the header has exactly 3 tokens and only the last token was underscored. |
| 103 | val parts = ua.split(" ") |
| 104 | assertEquals(3, parts.size, "UA must be exactly 'WhatsApp/<ver> Android/<os> Device/<token>' (2 spaces)") |
| 105 | assertTrue(parts[0].startsWith("WhatsApp/")) |
| 106 | assertTrue(parts[1].startsWith("Android/")) |
| 107 | assertTrue(parts[2].startsWith("Device/")) |
| 108 | // Device token must not contain spaces; manufacturer-model dash preserved |
| 109 | assertFalse(parts[2].contains(" "), "device token must have spaces replaced with '_'") |
| 110 | assertTrue(parts[2].contains("-")) |
| 111 | } |
| 112 | |
| 113 | @Test |
| 114 | fun userAgent_onlyDeviceTokenUnderscored_notWholeHeader() { |
| 115 | // Bug to guard: `ua.replace(' ', '_')` on the whole header would corrupt the "WhatsApp/.. Android/.." tokens. |
| 116 | val bad = "WhatsApp/${WhatsAppProtocol.WA_VERSION_NAME} Android/14 Device/Google Pixel 8 Pro".replace(' ', '_') |
| 117 | assertTrue( |
| 118 | bad.contains("WhatsApp/${WhatsAppProtocol.WA_VERSION_NAME}_Android/"), |
| 119 | "naive whole-header underscore would join tokens with '_'") |
| 120 | val good = userAgent("Google", "Pixel 8 Pro", "14") |
| 121 | assertFalse(good.contains("_Android/"), "correct impl must NOT underscore between WhatsApp and Android tokens") |
| 122 | assertEquals("WhatsApp/${WhatsAppProtocol.WA_VERSION_NAME} Android/14 Device/Google-Pixel_8_Pro", good) |
| 123 | } |
| 124 | |
| 125 | // ------------------------------------------------------------------ 3. id / backup_token not double-encoded (A05 |
| 126 | // raw) |
| 127 | |
| 128 | @Test |
| 129 | fun percentEncode_keepsUnreserved_encodesOthers_upperHex() { |
| 130 | // Unreserved A-Za-z0-9-._~ must stay literal; everything else %HH upper-hex. |
| 131 | val unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~".toByteArray() |
| 132 | assertEquals(String(unreserved), RegEncoding.percentEncode(unreserved)) |
| 133 | assertEquals( |
| 134 | "%00%0A%0D%20%2F%3D%3F%25", |
| 135 | RegEncoding.percentEncode(byteArrayOf(0x00, 0x0A, 0x0D, 0x20, 0x2F, 0x3D, 0x3F, 0x25))) |
| 136 | // % must be encoded as %25 and hex digits upper-case |
| 137 | assertEquals("%2B", RegEncoding.percentEncode(byteArrayOf(0x2B))) // '+' |
| 138 | } |
| 139 | |
| 140 | @Test |
| 141 | fun idAndBackupToken_mustNotBeDoubleEncoded_atQueryBuild() { |
| 142 | // A05 values are stored PRE-ENCODED (percentEncode) and RegParams.query() must append them as-is |
| 143 | // for keys in `raw` (id, backup_token). Double-encoding would turn "%AB" -> "%25AB". |
| 144 | val rawBytes = byteArrayOf(0xFF.toByte(), 0x00, 0x2B, 0x20, 0x41) // includes bytes that need encoding |
| 145 | val preEncoded = RegEncoding.percentEncode(rawBytes) |
| 146 | assertTrue(preEncoded.contains("%"), "preEncoded must contain % escapes") |
| 147 | val doubleEncoded = URLEncoder.encode(preEncoded, "UTF-8") |
| 148 | assertTrue(doubleEncoded.contains("%25"), "URLEncoder on preEncoded must produce %25 (double-encode)") |
| 149 | assertFalse(preEncoded.contains("%25"), "preEncoded itself must NOT contain %25") |
| 150 | |
| 151 | // Simulate RegParams.query() raw handling: raw keys bypass URLEncoder |
| 152 | fun fakeQuery(map: Map<String, String>, raw: Set<String>): String = |
| 153 | map.entries.joinToString("&") { (k, v) -> |
| 154 | val enc = if (k in raw) v else URLEncoder.encode(v, "UTF-8") |
| 155 | "$k=$enc" |
| 156 | } |
| 157 | val qGood = fakeQuery(mapOf("id" to preEncoded, "cc" to "1", "in" to "555"), setOf("id")) |
| 158 | assertTrue(qGood.contains("id=$preEncoded"), "raw key must appear verbatim") |
| 159 | assertFalse(qGood.contains("%25"), "raw key must not be double-encoded in query") |
| 160 | val qBad = fakeQuery(mapOf("id" to preEncoded), emptySet()) |
| 161 | assertTrue(qBad.contains("%25"), "without raw handling, id would be double-encoded") |
| 162 | } |
| 163 | |
| 164 | // JVM equivalent of RegEncoding.b64Url (android flag 11 = URL_SAFE|NO_WRAP|NO_PADDING). |
| 165 | private fun javaB64Url(bytes: ByteArray): String = |
| 166 | Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) |
| 167 | |
| 168 | @Test |
| 169 | fun b64Url_isFlag11_noWrap_noPadding_urlSafe() { |
| 170 | // RegEncoding.b64Url = Base64 URL_SAFE|NO_WRAP|NO_PADDING (android flag 11) |
| 171 | // Must be URL-safe (-_ not +/), no padding (=), no newlines. |
| 172 | // Use java equivalent on JVM (android.util.Base64 is not mocked in unitTest). |
| 173 | val tricky = byteArrayOf(0xFB.toByte(), 0xEF.toByte(), 0xFF.toByte(), 0x00, 0x01, 0x02, 0x03) |
| 174 | val enc = javaB64Url(tricky) |
| 175 | assertFalse(enc.contains("+"), "b64Url must not contain '+' (use '-' instead)") |
| 176 | assertFalse(enc.contains("/"), "b64Url must not contain '/' (use '_' instead)") |
| 177 | assertFalse(enc.contains("="), "b64Url must not contain padding '='") |
| 178 | assertFalse(enc.contains("\n") || enc.contains("\r"), "b64Url must not contain line breaks (NO_WRAP)") |
| 179 | // Round-trip via URL decoder (java) |
| 180 | val decoded = Base64.getUrlDecoder().decode(enc) |
| 181 | assertTrue(tricky.contentEquals(decoded)) |
| 182 | // expid is UUID 16 bytes -> b64Url is 22 chars (no padding) — verify length math |
| 183 | // uuidToBytes is pure java (no android), safe to call. |
| 184 | val uuidBytes = RegEncoding.uuidToBytes("550e8400-e29b-41d4-a716-446655440000") |
| 185 | assertEquals(16, uuidBytes.size) |
| 186 | assertEquals(22, javaB64Url(uuidBytes).length) |
| 187 | // Source must declare flag 11 (URL_SAFE|NO_WRAP|NO_PADDING) |
| 188 | val src = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegEncoding.kt") |
| 189 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegEncoding.kt") |
| 190 | if (src != null) { |
| 191 | assertTrue(src.contains("URL_SAFE") && src.contains("NO_WRAP") && src.contains("NO_PADDING"), |
| 192 | "RegEncoding.b64Url must use Base64.URL_SAFE|NO_WRAP|NO_PADDING (flag 11, DIj.A0w)") |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | @Test |
| 197 | fun percentEncode_roundTrips_viaUrlDecoderForUnreserved() { |
| 198 | // Random-ish bytes through percentEncode must be fully reversible via percent-decode mental model; |
| 199 | // we at least verify that unreserved bytes survive and encoded bytes are %HH. |
| 200 | val allBytes = ByteArray(256) { it.toByte() } |
| 201 | val enc = RegEncoding.percentEncode(allBytes) |
| 202 | // Encoded length: unreserved (66 chars) stay 1, rest become 3 -> total = 66*1 + 190*3 = 636 |
| 203 | // 66 = 26+26+10 + 4 (- . _ ~) |
| 204 | assertEquals(66 + 190 * 3, enc.length) |
| 205 | } |
| 206 | |
| 207 | // ------------------------------------------------------------------ 4. token: NO_WRAP (flag 2), national number |
| 208 | |
| 209 | @Test |
| 210 | fun token_usesStandardBase64NoWrap_flag2_notUrlSafe_withPadding_noNewline() { |
| 211 | // RegistrationAttestation.computeToken returns Base64.encodeToString(tokenBytes, Base64.NO_WRAP) |
| 212 | // (flag 2): standard alphabet (+/), with padding, no line breaks. NOT url-safe/no-padding (flag 11). |
| 213 | // Token bytes are HMAC-SHA1 = 20 bytes -> standard b64 is 28 chars (27 + one '=') |
| 214 | val dummyTokenBytes = ByteArray(20) { (it * 7).toByte() } |
| 215 | val stdNoWrap = |
| 216 | Base64.getEncoder().encodeToString(dummyTokenBytes) // java std = flag 2 equiv (no wrap, with pad) |
| 217 | val urlNoPad = Base64.getUrlEncoder().withoutPadding().encodeToString(dummyTokenBytes) |
| 218 | assertEquals(28, stdNoWrap.length, "20 bytes -> 28 chars standard b64 (one '=' pad)") |
| 219 | assertTrue(stdNoWrap.endsWith("="), "standard token b64 must have padding") |
| 220 | assertFalse(stdNoWrap.contains("\n")) |
| 221 | // URL-safe variant would differ if bytes hit +/ |
| 222 | // At least assert the std encoding does NOT use URL-safe alphabet assumptions |
| 223 | assertFalse(stdNoWrap.contains("\n") || stdNoWrap.contains("\r")) |
| 224 | |
| 225 | // Source must use Base64.NO_WRAP (flag 2) for token, NOT URL_SAFE |
| 226 | val src = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationAttestation.kt") |
| 227 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationAttestation.kt") |
| 228 | if (src != null) { |
| 229 | assertTrue(src.contains("Base64.NO_WRAP"), "token must use Base64.NO_WRAP (flag 2)") |
| 230 | // Token line should be `Base64.encodeToString(tokenBytes, Base64.NO_WRAP)` exactly (no URL_SAFE) |
| 231 | val tokenLine = src.lines().firstOrNull { it.contains("encodeToString(tokenBytes") } ?: "" |
| 232 | assertFalse(tokenLine.contains("URL_SAFE"), "token line must NOT use URL_SAFE") |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | @Test |
| 237 | fun token_isComputedFromNationalNumber_notFullE164() { |
| 238 | // The task requires token to use the NATIONAL number (the `in` param), not cc+in. |
| 239 | // We can only assert the documented source: RegistrationHttpClient.requestCode passes |
| 240 | // `number` (national) to computeToken, and checkExist passes `number` as well. |
| 241 | val src = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 242 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 243 | if (src != null) { |
| 244 | // requestCode: `computeToken(context, number)` where `number` is the `in` arg (national) |
| 245 | assertTrue( |
| 246 | src.contains("computeToken(context, number)"), |
| 247 | "token must be computed from national `number` (param `in`), not \"\$cc\$number\"") |
| 248 | // Must NOT contain the full-number token variant in production code path (only debug log may show it) |
| 249 | val nonDebugTokenCalls = src.lines().filter { it.contains("computeToken") && !it.contains("debug token") } |
| 250 | for (l in nonDebugTokenCalls) { |
| 251 | assertFalse(l.contains("\"\$cc\$number\"") || l.contains("cc + number") || l.contains("cc+number"), |
| 252 | "production token call must not use cc+number; found: $l") |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | // ------------------------------------------------------------------ 5. e_regid range 1..16383, 4B BE url-b64; |
| 258 | // bundle keys |
| 259 | |
| 260 | @Test |
| 261 | fun eRegid_isIn1To16383_andEncodedAs4ByteBeUrlB64() { |
| 262 | // RegistrationKeys.generate uses rng.nextInt(0x3FFF) + 1 -> 1..16383 |
| 263 | assertEquals(0x3FFF, 16383) |
| 264 | // Verify intBe + b64Url for boundary values decodes to correct BE int (use java b64Url equiv) |
| 265 | fun decodeEregid(b64: String): Int { |
| 266 | val bytes = Base64.getUrlDecoder().decode(b64) |
| 267 | assertEquals(4, bytes.size, "e_regid must be 4-byte BE") |
| 268 | return ByteBuffer.wrap(bytes).int |
| 269 | } |
| 270 | assertEquals(1, decodeEregid(javaB64Url(intBe(1, 4)))) |
| 271 | assertEquals(8192, decodeEregid(javaB64Url(intBe(8192, 4)))) |
| 272 | assertEquals(16383, decodeEregid(javaB64Url(intBe(16383, 4)))) |
| 273 | // 0 and 16384 are out of range and must never be generated (assert the formula) |
| 274 | val rng = java.security.SecureRandom() |
| 275 | repeat(100) { |
| 276 | val v = rng.nextInt(0x3FFF) + 1 |
| 277 | assertTrue(v in 1..16383, "generated registrationId must be 1..16383, got $v") |
| 278 | } |
| 279 | // Source must use 0x3FFF + 1 |
| 280 | val src = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationKeys.kt") |
| 281 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationKeys.kt") |
| 282 | if (src != null) { |
| 283 | assertTrue(src.contains("0x3FFF") || src.contains("16383"), "registrationId must be bounded to 0x3FFF") |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | @Test |
| 288 | fun bundle_containsExpectedKeys_andUsesUrlB64_A04() { |
| 289 | // Pure-JVM shape check: verify the bundle encoding contract without invoking |
| 290 | // android.util.Base64 (which is not mocked in JVM unit tests). The real |
| 291 | // RegistrationKeys.bundleFields is A04 = url-b64 (flag 11) via RegEncoding.b64Url, |
| 292 | // so we assert the same via the java equivalent. |
| 293 | val idPub = ByteArray(32) { 0x11 } |
| 294 | val noisePub = ByteArray(32) { 0x22 } |
| 295 | val skeyPub = ByteArray(32) { 0x33 } |
| 296 | // Directly verify the java-equivalent url-b64 for each field type |
| 297 | for (bytes in listOf(idPub, noisePub, skeyPub)) { |
| 298 | val enc = javaB64Url(bytes) |
| 299 | assertFalse(enc.contains("+"), "bundle field must be url-safe (no '+')") |
| 300 | assertFalse(enc.contains("/"), "bundle field must be url-safe (no '/')") |
| 301 | assertFalse(enc.contains("="), "bundle field must have no padding") |
| 302 | assertFalse(enc.contains("\n"), "bundle field must have no wrap") |
| 303 | assertNotNull(Base64.getUrlDecoder().decode(enc), "must be valid url-b64") |
| 304 | } |
| 305 | // e_regid is 4-byte BE of registrationId; e_keytype is single byte 0x05 |
| 306 | assertEquals(1234, ByteBuffer.wrap(Base64.getUrlDecoder().decode(javaB64Url(intBe(1234, 4)))).int) |
| 307 | assertEquals(WhatsAppRegistrationConstants.KEY_TYPE_CURVE25519, Base64.getUrlDecoder().decode(javaB64Url(byteArrayOf(WhatsAppRegistrationConstants.KEY_TYPE_CURVE25519)))[0]) |
| 308 | assertEquals(WhatsAppRegistrationConstants.KEY_TYPE_CURVE25519, 0x05.toByte()) |
| 309 | // e_skey_id is 3-byte BE of signedPreKeyId |
| 310 | assertEquals(3, Base64.getUrlDecoder().decode(javaB64Url(intBe(1, 3))).size) |
| 311 | // Also verify source declares url-b64 via RegEncoding.b64Url for bundle |
| 312 | val src = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationKeys.kt") |
| 313 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationKeys.kt") |
| 314 | if (src != null) { |
| 315 | assertTrue(src.contains("RegEncoding.b64Url"), "bundleFields must use RegEncoding.b64Url (A04 / flag 11)") |
| 316 | assertTrue( |
| 317 | src.contains("\"e_regid\"") && src.contains("\"e_keytype\"") && src.contains("\"e_ident\""), |
| 318 | "bundle must contain e_regid/e_keytype/e_ident") |
| 319 | assertTrue(src.contains("\"e_skey_id\"") && src.contains("\"e_skey_val\"") && src.contains("\"e_skey_sig\"") && src.contains("\"authkey\""), "bundle must contain e_skey_* and authkey") |
| 320 | } |
| 321 | // PQ guard: source must have all-or-none check (id != 0 && public.isNotEmpty && sig.isNotEmpty) |
| 322 | if (src != null) { |
| 323 | assertTrue(src.contains("pqLastResort"), "bundleFields must handle PQ") |
| 324 | // The all-or-none guard must check all three before emitting |
| 325 | assertTrue(src.contains("e_pq_last_resort"), "PQ keys must be e_pq_last_resort_*") |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | // ------------------------------------------------------------------ 6. PQ all-or-none |
| 330 | |
| 331 | @Test |
| 332 | fun pqBundle_isAllOrNone() { |
| 333 | fun b64(b: ByteArray) = Base64.getEncoder().encodeToString(b) |
| 334 | val baseAuth = WhatsAppAuthData( |
| 335 | phoneNumber = "15551234567", pushName = "", wid = "", |
| 336 | noisePrivateKey = b64(ByteArray(32) { 1 }), noisePublicKey = b64(ByteArray(32) { 2 }), |
| 337 | identityPrivateKey = b64(ByteArray(32) { 3 }), identityPublicKey = b64(ByteArray(32) { 4 }), |
| 338 | registrationId = 100, signedPreKeyId = 1, |
| 339 | signedPreKeyPublic = b64(ByteArray(32) { 5 }), signedPreKeyPrivate = b64(ByteArray(32) { 6 }), |
| 340 | signedPreKeySignature = b64(ByteArray(64) { 7 }), |
| 341 | ) |
| 342 | // Case 1: all PQ absent -> none emitted |
| 343 | val none = baseAuth.copy(pqLastResortKeyId = 0, pqLastResortPublic = "", pqLastResortSignature = "") |
| 344 | val bundleNone = runCatching { com.vayunmathur.communicate.data.whatsapp.registration.RegistrationKeys.bundleFields(none) }.getOrNull() |
| 345 | if (bundleNone != null) { |
| 346 | assertFalse(bundleNone.containsKey("e_pq_last_resort_id")) |
| 347 | assertFalse(bundleNone.containsKey("e_pq_last_resort_val")) |
| 348 | assertFalse(bundleNone.containsKey("e_pq_last_resort_sig")) |
| 349 | } |
| 350 | // Case 2: full triple -> all three emitted |
| 351 | val full = baseAuth.copy( |
| 352 | pqLastResortKeyId = 1, |
| 353 | pqLastResortPublic = b64(ByteArray(1568) { 9 }), |
| 354 | pqLastResortSecret = b64(ByteArray(32) { 10 }), |
| 355 | pqLastResortSignature = b64(ByteArray(64) { 11 }), |
| 356 | ) |
| 357 | val bundleFull = runCatching { com.vayunmathur.communicate.data.whatsapp.registration.RegistrationKeys.bundleFields(full) }.getOrNull() |
| 358 | if (bundleFull != null) { |
| 359 | assertTrue(bundleFull.containsKey("e_pq_last_resort_id")) |
| 360 | assertTrue(bundleFull.containsKey("e_pq_last_resort_val")) |
| 361 | assertTrue(bundleFull.containsKey("e_pq_last_resort_sig")) |
| 362 | // IDs are 3-byte BE url-b64 |
| 363 | assertEquals(3, Base64.getUrlDecoder().decode(bundleFull["e_pq_last_resort_id"]!!).size) |
| 364 | } |
| 365 | // Case 3: partial triple must NOT emit (all-or-none guard) |
| 366 | val partial = baseAuth.copy( |
| 367 | pqLastResortKeyId = 1, |
| 368 | pqLastResortPublic = b64(ByteArray(1568) { 9 }), |
| 369 | pqLastResortSignature = "") |
| 370 | val bundlePartial = runCatching { com.vayunmathur.communicate.data.whatsapp.registration.RegistrationKeys.bundleFields(partial) }.getOrNull() |
| 371 | if (bundlePartial != null) { |
| 372 | assertFalse( |
| 373 | bundlePartial.containsKey("e_pq_last_resort_id"), |
| 374 | "partial PQ triple must not emit e_pq_last_resort_id") |
| 375 | assertFalse(bundlePartial.containsKey("e_pq_last_resort_val")) |
| 376 | assertFalse(bundlePartial.containsKey("e_pq_last_resort_sig")) |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | // ------------------------------------------------------------------ 7. checkExist includes token, addIntegrity |
| 381 | // per-endpoint correct fields |
| 382 | |
| 383 | @Test |
| 384 | fun checkExist_includesToken() { |
| 385 | val src = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 386 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 387 | if (src != null) { |
| 388 | // Extract the checkExist function body and assert it contains a token param |
| 389 | val existIdx = src.indexOf("fun checkExist") |
| 390 | assertTrue(existIdx >= 0, "checkExist function must exist") |
| 391 | val snippet = src.substring(existIdx, minOf(src.length, existIdx + 2000)) |
| 392 | assertTrue(snippet.contains("token"), "checkExist must include token param (bad_param fix w2.md §3.1)") |
| 393 | assertTrue(snippet.contains("computeToken"), "checkExist token must be via computeToken") |
| 394 | // Integrity signals are gated OFF by default: device-confirmed that sending them (even |
| 395 | // with official values) → status:fail reason:blocked. The default request matches the |
| 396 | // verified-live param set (baseline 33dd602): no _gi/aid/_gp. (addIntegrity() early-returns.) |
| 397 | assertTrue( |
| 398 | src.contains("SEND_INTEGRITY_SIGNALS = false"), |
| 399 | "integrity signals must be gated OFF by default (device-confirmed blocked when on)", |
| 400 | ) |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | @Test |
| 405 | fun addIntegrity_perEndpointCorrectFields() { |
| 406 | val src = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 407 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 408 | if (src != null) { |
| 409 | val integIdx = src.indexOf("fun addIntegrity") |
| 410 | assertTrue(integIdx >= 0, "addIntegrity must exist") |
| 411 | val snippet = src.substring(integIdx, minOf(src.length, integIdx + 3000)) |
| 412 | // Common fields always: aid, _gi, _gp, _ge, _ga, _gs |
| 413 | for (k in listOf("aid", "_gi", "_gp", "_ge", "_ga", "_gs")) { |
| 414 | assertTrue( |
| 415 | snippet.contains("\"$k\"") || snippet.contains("s.$k") || snippet.contains(k), |
| 416 | "addIntegrity must handle $k") |
| 417 | } |
| 418 | // Per-endpoint: |
| 419 | // EXIST: db + profile_name; no t |
| 420 | assertTrue(snippet.contains("EndpointKind.EXIST"), "must branch on EXIST") |
| 421 | assertTrue(snippet.contains("\"db\""), "EXIST must include db") |
| 422 | assertTrue(snippet.contains("profile_name"), "EXIST must include profile_name when available") |
| 423 | // CODE: t + hasav |
| 424 | assertTrue(snippet.contains("EndpointKind.CODE"), "must branch on CODE") |
| 425 | assertTrue(snippet.contains("\"t\""), "CODE and REGISTER must include t") |
| 426 | assertTrue(snippet.contains("hasav"), "CODE must include hasav") |
| 427 | // REGISTER: t (no db, no hasav) |
| 428 | assertTrue(snippet.contains("EndpointKind.REGISTER"), "must branch on REGISTER") |
| 429 | // Verify t is added via RegistrationIntegrity.tField |
| 430 | assertTrue(snippet.contains("tField"), "t must be via RegistrationIntegrity.tField") |
| 431 | // gpia/_gg/recaptcha must NOT be sent (cannot mint) |
| 432 | assertFalse(snippet.contains("gpia"), "must not send gpia (Play Integrity)") |
| 433 | assertFalse(snippet.contains("recaptcha"), "must not send recaptcha") |
| 434 | } |
| 435 | // Also verify the pure encoders for t and aid match spec |
| 436 | assertEquals(8, Base64.getDecoder().decode(RegistrationIntegrity.tField(0L)).size) |
| 437 | assertEquals(44, RegistrationIntegrity.aidOf("test").length) |
| 438 | } |
| 439 | |
| 440 | @Test |
| 441 | fun integrity_giAndGpUseOfficialWhatsAppIdentity() { |
| 442 | // _gi must carry the OFFICIAL WhatsApp package + official base.apk hash/size (same pinned APK |
| 443 | // as the token), NOT this client's identity. |
| 444 | val constSrc = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppRegistrationConstants.kt") |
| 445 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppRegistrationConstants.kt") |
| 446 | if (constSrc != null) { |
| 447 | assertTrue(constSrc.contains("OFFICIAL_APK_SHA256_B64"), "must pin official base.apk sha256") |
| 448 | assertTrue( |
| 449 | constSrc.contains("38wasuL4WBcWVxf5K0p6dc6ELF+OvBqshecYAn1awkM="), |
| 450 | "official base.apk sha256 (b64) must be the pinned 2.26.29.73 value", |
| 451 | ) |
| 452 | assertTrue(constSrc.contains("OFFICIAL_APK_SIZE = 120328807"), "must pin official base.apk size") |
| 453 | } |
| 454 | val integSrc = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.kt") |
| 455 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.kt") |
| 456 | if (integSrc != null) { |
| 457 | val giIdx = integSrc.indexOf("fun buildGi") |
| 458 | assertTrue(giIdx >= 0, "buildGi must exist") |
| 459 | val gi = integSrc.substring(giIdx, minOf(integSrc.length, giIdx + 1200)) |
| 460 | assertTrue(gi.contains("OFFICIAL_APK_SHA256_B64"), "_gi must use the official apk sha256") |
| 461 | assertTrue(gi.contains("PACKAGE_NAME"), "_gi package must be the official com.whatsapp const") |
| 462 | assertFalse(gi.contains("context.packageName"), "_gi must NOT use this client's package") |
| 463 | assertFalse(gi.contains("readBytes"), "_gi must NOT hash this client's own apk") |
| 464 | // _gp must hash the OFFICIAL WhatsApp permission set, not this client's manifest. |
| 465 | assertTrue( |
| 466 | integSrc.contains("permissionsHashOf(OFFICIAL_WHATSAPP_PERMISSIONS)"), |
| 467 | "_gp must hash the official WhatsApp permission set", |
| 468 | ) |
| 469 | assertFalse(integSrc.contains("manifestPermissions("), "must not hash this client's manifest permissions") |
| 470 | // The official permission set must include WhatsApp-specific permissions. |
| 471 | assertTrue(integSrc.contains("com.whatsapp.permission.REGISTRATION"), "official perms must be WhatsApp's") |
| 472 | } |
| 473 | assertEquals("com.whatsapp", WhatsAppRegistrationConstants.PACKAGE_NAME) |
| 474 | } |
| 475 | |
| 476 | @Test |
| 477 | fun addDevice_includesOfficialNoPlayFingerprint() { |
| 478 | // The official no-Play /v2 request (RE of LX/F4L; A0I/A0M/A0P/A0G) carries these honest |
| 479 | // device signals; we must send them (none are Play/attestation signals). |
| 480 | val src = tryReadSource("communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 481 | ?: tryReadSource("src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt") |
| 482 | if (src != null) { |
| 483 | val idx = src.indexOf("fun addDevice") |
| 484 | assertTrue(idx >= 0, "addDevice must exist") |
| 485 | val snip = src.substring(idx, minOf(src.length, idx + 1800)) |
| 486 | for (p in listOf("mcc", "mnc", "sim_mcc", "sim_mnc", "network_radio_type", "simnum", |
| 487 | "hasinrc", "pid", "rc", "network_operator_name", "sim_operator_name", |
| 488 | "airplane_mode_on", "device_ram")) { |
| 489 | assertTrue(snip.contains("\"$p\""), "addDevice must send device param $p") |
| 490 | } |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | @Test |
| 495 | fun eKeytype_constants_matchSpec() { |
| 496 | assertEquals(0x05.toByte(), WhatsAppRegistrationConstants.KEY_TYPE_CURVE25519) |
| 497 | assertEquals(0x08.toByte(), WhatsAppRegistrationConstants.KEY_TYPE_KYBER) |
| 498 | assertEquals(1568, WhatsAppRegistrationConstants.PQ_KYBER1024_PUBLIC_LEN) |
| 499 | assertEquals(1, WhatsAppRegistrationConstants.PQ_LAST_RESORT_KEY_ID) |
| 500 | } |
| 501 | } |