Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / whatsapp / Y1WaRegistrationHttpTest.kt
Y1WaRegistrationHttpTest.kt176 lines · 9.1 KiBRaw
| 1 | package com.vayunmathur.communicate.whatsapp |
| 2 | |
| 3 | import androidx.test.core.app.ApplicationProvider |
| 4 | import com.sun.net.httpserver.HttpServer |
| 5 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData |
| 6 | import com.vayunmathur.communicate.data.whatsapp.registration.RegistrationHttpClient |
| 7 | import com.vayunmathur.communicate.data.whatsapp.registration.RegistrationKeys |
| 8 | import java.net.InetSocketAddress |
| 9 | import kotlin.test.AfterTest |
| 10 | import kotlin.test.BeforeTest |
| 11 | import kotlin.test.Test |
| 12 | import kotlin.test.assertEquals |
| 13 | import kotlin.test.assertFalse |
| 14 | import kotlin.test.assertNotNull |
| 15 | import kotlin.test.assertNull |
| 16 | import kotlin.test.assertTrue |
| 17 | import kotlinx.coroutines.runBlocking |
| 18 | import org.junit.runner.RunWith |
| 19 | import org.robolectric.RobolectricTestRunner |
| 20 | |
| 21 | /** |
| 22 | * Y1: WhatsApp v2 registration client against a scripted localhost |
| 23 | * server (never the real service), via the client's baseUrlForTest seam. |
| 24 | * Covers every endpoint's request building and response parsing, including |
| 25 | * register finalization (new_jid / login fallback / failure) and the |
| 26 | * unparseable/network error paths. |
| 27 | */ |
| 28 | @RunWith(RobolectricTestRunner::class) |
| 29 | class Y1WaRegistrationHttpTest { |
| 30 | |
| 31 | private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>() |
| 32 | private lateinit var server: HttpServer |
| 33 | private lateinit var client: RegistrationHttpClient |
| 34 | private val requests = mutableListOf<String>() |
| 35 | private val scripted = mutableMapOf<String, String>() |
| 36 | |
| 37 | @BeforeTest fun setUp() { |
| 38 | scripted.clear(); requests.clear() |
| 39 | server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0) |
| 40 | server.createContext("/") { ex -> |
| 41 | val path = ex.requestURI.path.trimStart('/') |
| 42 | val body = ex.requestBody.readBytes().decodeToString() |
| 43 | requests += "$path $body" |
| 44 | val resp = scripted[path] ?: """{"status":"fail","reason":"unscripted"}""" |
| 45 | val bytes = resp.encodeToByteArray() |
| 46 | ex.responseHeaders.add("Content-Type", "text/json") |
| 47 | ex.sendResponseHeaders(200, bytes.size.toLong()) |
| 48 | ex.responseBody.use { it.write(bytes) } |
| 49 | } |
| 50 | server.start() |
| 51 | client = RegistrationHttpClient(ctx) |
| 52 | client.baseUrlForTest = "http://127.0.0.1:${server.address.port}" |
| 53 | // Seed key scaffold so register/security/exist bundle paths run. |
| 54 | WhatsAppAuthData.save(ctx, RegistrationKeys.generate("15550102030").authScaffold) |
| 55 | } |
| 56 | |
| 57 | @AfterTest fun tearDown() { server.stop(0) } |
| 58 | |
| 59 | @Test fun requestCodeParsesSentAndBuildsParams(): Unit = runBlocking { |
| 60 | scripted["code"] = """{"status":"sent","method":"sms","length":6,"retry_after":30}""" |
| 61 | val r = client.requestCode("1", "5550102030", "sms") |
| 62 | assertTrue(r.ok); assertEquals("sent", r.status); assertEquals("sms", r.method) |
| 63 | assertEquals(6, r.length); assertEquals(30L, r.retryAfter) |
| 64 | val req = requests.single { it.startsWith("code ") } |
| 65 | assertTrue(req.contains("cc=1"), req); assertTrue(req.contains("method=sms"), req) |
| 66 | assertTrue(req.contains("token="), req); assertTrue(req.contains("e_ident="), req) |
| 67 | // requestCode persists a fresh scaffold |
| 68 | assertNotNull(WhatsAppAuthData.load(ctx)) |
| 69 | } |
| 70 | |
| 71 | @Test fun requestCodeFailCarriesReasonAndParam(): Unit = runBlocking { |
| 72 | scripted["code"] = """{"status":"fail","reason":"too_recent","param":"retry_after"}""" |
| 73 | val r = client.requestCode("1", "5550102030", "voice") |
| 74 | assertFalse(r.ok); assertEquals("too_recent", r.reason); assertEquals("retry_after", r.param) |
| 75 | assertTrue(requests.single().contains("method=voice")) |
| 76 | } |
| 77 | |
| 78 | @Test fun registerSuccessWithNewJidFinalizesAuth(): Unit = runBlocking { |
| 79 | scripted["register"] = """{"status":"ok","new_jid":"15550102030","lid":"999","server_time":12345}""" |
| 80 | val r = client.register("1", "5550102030", "123-456") |
| 81 | assertTrue(r.ok); assertEquals("15550102030", r.newJid) // raw server value; auth wid is normalized below |
| 82 | assertEquals(12345L, r.serverTime) |
| 83 | assertNotNull(r.auth); assertTrue(r.auth!!.registered) |
| 84 | assertEquals("999@lid", r.auth!!.lid) |
| 85 | assertEquals("[email protected]", WhatsAppAuthData.load(ctx)!!.wid) |
| 86 | assertTrue(requests.single { it.startsWith("register ") }.contains("code=123456")) |
| 87 | } |
| 88 | |
| 89 | @Test fun registerSuccessWithLoginOnlyDerivesJid(): Unit = runBlocking { |
| 90 | scripted["register"] = """{"status":"ok","login":"15559998888","lid":"888@lid"}""" |
| 91 | val r = client.register("1", "5559998888", "000000") |
| 92 | assertTrue(r.ok); assertEquals("[email protected]", r.newJid) |
| 93 | assertEquals("[email protected]", r.auth!!.wid) |
| 94 | assertEquals("888@lid", r.auth!!.lid) |
| 95 | } |
| 96 | |
| 97 | @Test fun registerFailureDoesNotFinalize(): Unit = runBlocking { |
| 98 | scripted["register"] = """{"status":"fail","reason":"incorrect","param":"code"}""" |
| 99 | val r = client.register("1", "5550102030", "111111") |
| 100 | assertFalse(r.ok); assertEquals("incorrect", r.reason); assertNull(r.auth) |
| 101 | assertFalse(WhatsAppAuthData.load(ctx)!!.registered) |
| 102 | } |
| 103 | |
| 104 | @Test fun twoFactorUsesSecurityEndpointAndFinalizes(): Unit = runBlocking { |
| 105 | scripted["security"] = """{"status":"ok","new_jid":"[email protected]"}""" |
| 106 | val r = client.submitTwoFactor("1", "5550102030", "123456") |
| 107 | assertTrue(r.ok) |
| 108 | assertTrue(requests.any { it.startsWith("security ") && it.contains("code=123456") }, "$requests") |
| 109 | } |
| 110 | |
| 111 | @Test fun checkExistParsesAndSendsToken(): Unit = runBlocking { |
| 112 | scripted["exist"] = """{"status":"ok"}""" |
| 113 | val r = client.checkExist("1", "5550102030") |
| 114 | assertEquals("ok", r.status) |
| 115 | assertTrue(requests.single { it.startsWith("exist ") }.contains("token=")) |
| 116 | scripted["exist"] = """{"status":"fail","reason":"bad_param","param":"token"}""" |
| 117 | val r2 = client.checkExist("44", "2079460958") |
| 118 | assertEquals("bad_param", r2.reason); assertEquals("token", r2.param) |
| 119 | } |
| 120 | |
| 121 | @Test fun consentAutoconfAndVerifierParse(): Unit = runBlocking { |
| 122 | scripted["consent"] = """{"status":"ok","pending":"parent","url":"https://example.test/c"}""" |
| 123 | val c = client.consent("1", "5550102030", "dob", dob = "2000-01-01", ageLowerBound = 18, |
| 124 | consentDecision = "accept", consentId = "cid", consentVersion = "2", securityCode = "999") |
| 125 | assertTrue(c.ok); assertEquals("parent", c.pending); assertEquals("https://example.test/c", c.url) |
| 126 | assertTrue(requests.last().contains("context=dob")) |
| 127 | |
| 128 | scripted["autoconf"] = """{"status":"sent","register_start_message":"start"}""" |
| 129 | val a = client.autoconf("1", "5550102030", consent = 1, clientCapabilities = "cap", consentShown = true, createVerifier = true) |
| 130 | assertTrue(a.ok); assertEquals("start", a.registerStartMessage) |
| 131 | assertTrue(requests.last().contains("consent_shown=true")) |
| 132 | |
| 133 | scripted["autoconf_verifier"] = """{"status":"ok"}""" |
| 134 | val v = client.autoconfVerifier("1", "5550102030", "12-34", "encdata", 5) |
| 135 | assertTrue(v.ok); assertTrue(requests.last().contains("code=1234")) |
| 136 | } |
| 137 | |
| 138 | @Test fun captchaChallengeAndClientLogParse(): Unit = runBlocking { |
| 139 | scripted["captcha_verify"] = """{"status":"verified","violation_type":"15","appeal_token":"tok"}""" |
| 140 | val cap = client.captchaVerify("1", "5550102030", "fraud-code") |
| 141 | assertTrue(cap.ok); assertEquals("15", cap.violationType); assertEquals("tok", cap.appealToken) |
| 142 | assertTrue(requests.last().contains("fraud_checkpoint_code=fraud-code")) |
| 143 | |
| 144 | scripted["challenge"] = """{"status":"ok"}""" |
| 145 | val ch = client.challenge("1", "5550102030", "email_enter", email = "[email protected]", oauthToken = null, code = null) |
| 146 | assertTrue(ch.ok); assertTrue(requests.last().contains("challenge_type=email_enter")) |
| 147 | assertTrue(requests.last().contains("email=a%40b.c")) |
| 148 | |
| 149 | scripted["client_log"] = """{"status":"ok"}""" |
| 150 | val log = client.clientLog("ctx", "type", cc = "1", number = "5550102030") |
| 151 | assertTrue(log.ok); assertTrue(requests.last().contains("client_error_context=ctx")) |
| 152 | } |
| 153 | |
| 154 | @Test fun unparseableBodyBecomesErrorStatus(): Unit = runBlocking { |
| 155 | scripted["exist"] = "not json at all" |
| 156 | val r = client.checkExist("1", "5550102030") |
| 157 | assertEquals("error", r.status); assertEquals("unparseable", r.reason) |
| 158 | } |
| 159 | |
| 160 | @Test fun networkFailureBecomesNetworkError(): Unit = runBlocking { |
| 161 | client.baseUrlForTest = "http://127.0.0.1:1" |
| 162 | val r = client.checkExist("1", "5550102030") |
| 163 | assertEquals("error", r.status) |
| 164 | assertTrue(r.reason!!.startsWith("network:"), "${r.reason}") |
| 165 | } |
| 166 | |
| 167 | @Test fun encWrapperClientStillBuildsRequest(): Unit = runBlocking { |
| 168 | val encClient = RegistrationHttpClient(ctx, useEncWrapper = true) |
| 169 | encClient.baseUrlForTest = "http://127.0.0.1:${server.address.port}" |
| 170 | scripted["client_log"] = """{"status":"ok"}""" |
| 171 | val r = encClient.clientLog("c", "t") |
| 172 | // ENC may fail on host (attestation) and fall back to plain query; either way server is hit. |
| 173 | assertTrue(requests.any { it.startsWith("client_log ") }, "$requests") |
| 174 | assertEquals("ok", r.status) |
| 175 | } |
| 176 | } |