Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,13 @@ class BangumiPasswordLoginClient private constructor(
?: return@guarded BangumiPasswordLoginStep.Failed(
parseBangumiNotice(authorizeLanded.body) ?: "Bangumi 授权页没有返回可提交的表单。",
)
// Bangumi 的授权表单没有 action 属性:真实浏览器会把表单提交回"当前页面 URL",
// 而 client_id / response_type / redirect_uri / state 全在那条 URL 的查询串里。
// 提交到裸的 /oauth/authorize 会丢掉这些参数,Bangumi 直接回 app_nonexistence。
val actionUrl = if (form.action.isBlank()) authorizeUrl else resolveAgainst(authorizeUrl, form.action)
val submitted = execute(
Request.Builder()
.url(resolveUrl(form.action))
.url(actionUrl)
.header("Referer", authorizeUrl)
.header("Origin", origin())
.post(
Expand Down Expand Up @@ -256,6 +260,10 @@ class BangumiPasswordLoginClient private constructor(
?: throw IllegalStateException("无法解析 Bangumi 地址")
}

/** Resolves a form action the way a browser does: relative to the page that rendered it. */
private fun resolveAgainst(pageUrl: String, reference: String): String =
pageUrl.toHttpUrlOrNull()?.resolve(reference)?.toString() ?: resolveUrl(reference)

private fun origin(): String = baseUrl.trimEnd('/')

private fun sameSite(url: String): Boolean {
Expand Down Expand Up @@ -350,7 +358,8 @@ internal fun parseAuthorizeForm(html: String): BangumiAuthorizeForm? {
val submitValue = submit?.attr("value")?.ifBlank { null } ?: submit?.text()?.ifBlank { null } ?: "授权"
if (fields.none { it.first == submitName }) fields += submitName to submitValue
if (fields.none { it.first == "formhash" && it.second.isNotBlank() }) return null
return BangumiAuthorizeForm(form.attr("action").ifBlank { "/oauth/authorize" }, fields)
// Keep a blank action blank: the caller must post back to the page URL (query string included).
return BangumiAuthorizeForm(form.attr("action"), fields)
}

internal fun parseBangumiNotice(html: String): String? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test

Expand All @@ -24,15 +25,18 @@ class BangumiPasswordLoginClientTest {
""".trimIndent()
assertEquals("/FollowTheRabbit" to "4a09722d", parseBangumiLoginForm(login))

// 线上授权页的表单没有 action 属性(浏览器会提交回当前 URL,查询串里带
// client_id/response_type/redirect_uri/state),fixture 必须保持同样形态。
val authorize = """
<form method="post" action="/oauth/authorize?client_id=test-id">
<form id="authForm" method="post" name="auth">
<input type="hidden" name="formhash" value="auth-hash">
<input type="hidden" name="redirect_uri" value="http://127.0.0.1:13712/callback">
<input type="hidden" name="client_id" value="test-id">
<input type="submit" name="submit" value="授权">
</form>
""".trimIndent()
val form = parseAuthorizeForm(authorize)!!
assertEquals("/oauth/authorize?client_id=test-id", form.action)
assertEquals("", form.action)
assertEquals("auth-hash", form.fields.first { it.first == "formhash" }.second)
assertEquals("授权", form.fields.first { it.first == "submit" }.second)

Expand All @@ -55,8 +59,9 @@ class BangumiPasswordLoginClientTest {
@Test
fun `wrong captcha retries and a later correct captcha returns the callback without storing the password`() = runBlocking {
val posts = mutableListOf<String>()
val paths = mutableListOf<String>()
MockWebServer().use { server ->
server.dispatcher = scriptedDispatcher(posts, authorizeRedirect = false)
server.dispatcher = scriptedDispatcher(posts, paths, authorizeRedirect = false)
val client = BangumiPasswordLoginClient(
baseUrl = server.url("/").toString().trimEnd('/'),
captchaSuffix = { 1 },
Expand Down Expand Up @@ -97,14 +102,21 @@ class BangumiPasswordLoginClientTest {
assertTrue(posts.any { it.contains("password=$SECRET") && it.contains("captcha_challenge_field=bad") })
assertTrue(posts.any { it.contains("password=$SECRET") && it.contains("captcha_challenge_field=ok") })
assertTrue(posts.any { it.contains("formhash=auth-hash") && it.contains("submit=") })
// 授权表单没有 action:POST 必须回到带查询串的授权页 URL;裸 /oauth/authorize
// 会丢 client_id/response_type/state,Bangumi 回 app_nonexistence(回归 #99 的线上故障)。
val authorizePost = paths.firstOrNull { it.startsWith("/oauth/authorize?") }
assertNotNull("authorize POST must target the authorize URL with its query string", authorizePost)
assertTrue(authorizePost!!.contains("client_id=test-id"))
assertTrue(authorizePost.contains("response_type=code"))
assertTrue(authorizePost.contains("state=state-1"))
assertFalse(client.toString().contains(SECRET))
}
}

@Test
fun `already approved app is a redirect straight to the loopback callback`() = runBlocking {
MockWebServer().use { server ->
server.dispatcher = scriptedDispatcher(mutableListOf(), authorizeRedirect = true)
server.dispatcher = scriptedDispatcher(mutableListOf(), mutableListOf(), authorizeRedirect = true)
val client = BangumiPasswordLoginClient(baseUrl = server.url("/").toString().trimEnd('/'))
assertTrue(client.startChallenge() is BangumiPasswordLoginStep.Challenge)
val authorized = client.loginAndAuthorize(
Expand Down Expand Up @@ -164,11 +176,18 @@ class BangumiPasswordLoginClientTest {
assertEquals("无法连接 Bangumi,请检查电视的出站代理或网络。", failed.message)
}

private fun scriptedDispatcher(posts: MutableList<String>, authorizeRedirect: Boolean): Dispatcher =
private fun scriptedDispatcher(
posts: MutableList<String>,
paths: MutableList<String>,
authorizeRedirect: Boolean,
): Dispatcher =
object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
val path = request.path.orEmpty()
if (request.method == "POST") posts += request.body.readUtf8()
if (request.method == "POST") {
posts += request.body.readUtf8()
paths += path
}
return when {
path.startsWith("/login") -> MockResponse().setBody(LOGIN_HTML).setHeader("Set-Cookie", "chii_sid=sid; Path=/")
path.startsWith("/signup/captcha") -> image()
Expand Down Expand Up @@ -219,8 +238,9 @@ class BangumiPasswordLoginClientTest {
<div id="colunmNotice"><div class="message"><p class="text">累计 5 次错误尝试,15 分钟内您将不能登录本站。</p></div></div>
"""
const val AUTHORIZE_HTML = """
<form method="post" action="/oauth/authorize">
<form id="authForm" method="post" name="auth">
<input type="hidden" name="formhash" value="auth-hash">
<input type="hidden" name="redirect_uri" value="http://127.0.0.1:13712/callback">
<input type="hidden" name="client_id" value="test-id">
<input type="submit" name="submit" value="授权">
</form>
Expand Down
Loading