Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(http): 共用传输层自己跟重定向,同源保留 Cookie、跨源丢凭据

longmeidaoa86663a5e14f
diff --git a/src/peach/http.py b/src/peach/http.py
index 4d29baade..3a79e5c4f 100644
--- a/src/peach/http.py
+++ b/src/peach/http.py
@@ -23,9 +23,9 @@ class HttpResponse:
status: int
headers: Mapping[str, str]
body: bytes
- #: 跟完重定向后的最终地址。两个 transport 都开着 follow_redirects,请求 URL
- #: 因此不等于实际取到的页面;判断「这一页属于谁」必须看最终地址,而不是我们
- #: 发出去的那个。默认空字符串是为了让既有的三参数构造(多在测试里)保持可用。
+ #: 跟完重定向后的最终地址。两个 transport 都跟重定向,请求 URL 因此不等于实际
+ #: 取到的页面;判断「这一页属于谁」必须看最终地址,而不是我们发出去的那个。
+ #: 默认空字符串是为了让既有的三参数构造(多在测试里)保持可用。
url: str = ""
@@ -38,12 +38,35 @@ class HttpTransport(Protocol):
) -> HttpResponse: ...
+#: 跟这些状态的 Location。与 httpx 自己的判据一致。
+_REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308})
+#: 跨源跳转时丢掉的请求头:凭据只属于发出它的那个站。
+_CREDENTIAL_HEADERS = ("cookie", "authorization")
+
+
+def _same_origin(left: httpx.URL, right: httpx.URL) -> bool:
+ return (left.scheme, left.host, left.port) == (right.scheme, right.host, right.port)
+
+
+def _without(headers: dict[str, str], names: tuple[str, ...]) -> dict[str, str]:
+ return {key: value for key, value in headers.items() if key.lower() not in names}
+
+
class HttpxTransport:
- """可跨请求复用的同步 HTTPX client;不会自动重试或持久化响应。"""
+ """可跨请求复用的同步 HTTPX client;不会自动重试或持久化响应。
+
+ 重定向自己跟,不交给 httpx 的 `follow_redirects`:httpx 跟跳时会无条件丢掉显式的
+ `Cookie` 头,只保留 client 自己 cookie jar 里的那些。连接器的登录会话正是作为请求头
+ 传进来的,于是「直接请求目标页 200、经一次同源 30x 到达就 403」(2026-09-08 实测
+ simpcity.cr 的 `/latest` 与纯数字线程地址)。这里同源跳转保留全部请求头,跨源跳转
+ 丢掉 Cookie 与 Authorization——凭据只属于发出它的那个站。
+ """
+
+ #: 最多跟几跳。站点正常只跳一两次,再多就是环。
+ MAX_REDIRECTS = 5
def __init__(self, client: httpx.Client | None = None, *, owns_client: bool = False):
self.client = client or httpx.Client(
- follow_redirects=True,
limits=httpx.Limits(max_connections=32, max_keepalive_connections=16),
headers={"User-Agent": USER_AGENT},
)
@@ -55,35 +78,57 @@ class HttpxTransport:
timeout: float,
max_bytes: int,
) -> HttpResponse:
- chunks: list[bytes] = []
- total = 0
- with self.client.stream(
- request.method,
- request.url,
- headers=dict(request.headers),
- content=request.body,
- timeout=timeout,
- ) as response:
- for chunk in response.iter_bytes():
- remaining = max_bytes + 1 - total
- if remaining <= 0:
- break
- chunks.append(chunk[:remaining])
- total += min(len(chunk), remaining)
- if total > max_bytes:
- break
- return HttpResponse(
- response.status_code,
- dict(response.headers),
- b"".join(chunks),
- str(response.url),
- )
+ method = request.method
+ url = httpx.URL(request.url)
+ headers = dict(request.headers)
+ body = request.body
+ for _ in range(self.MAX_REDIRECTS + 1):
+ with self.client.stream(
+ method, url, headers=headers, content=body, timeout=timeout,
+ follow_redirects=False,
+ ) as response:
+ location = response.headers.get("location")
+ if response.status_code not in _REDIRECT_STATUSES or not location:
+ return HttpResponse(
+ response.status_code,
+ dict(response.headers),
+ _bounded_body(response.iter_bytes(), max_bytes),
+ str(response.url),
+ )
+ target = response.url.join(location)
+ if not _same_origin(url, target):
+ headers = _without(headers, _CREDENTIAL_HEADERS)
+ # 303 一律改成 GET;301/302 只把非 GET 改成 GET,和浏览器与 httpx 的做法一致。
+ if response.status_code == 303 or (
+ response.status_code in (301, 302) and method not in ("GET", "HEAD")):
+ if method != "HEAD":
+ method = "GET"
+ body = None
+ headers = _without(headers, ("content-length", "content-type"))
+ url = target
+ raise httpx.TooManyRedirects(
+ f"超过 {self.MAX_REDIRECTS} 次重定向", request=response.request)
def close(self) -> None:
if self._owns_client:
self.client.close()
+def _bounded_body(chunks, max_bytes: int) -> bytes:
+ """最多读 `max_bytes + 1` 字节:多出的那一个字节让调用方能判「超限」而不是「刚好」。"""
+ kept: list[bytes] = []
+ total = 0
+ for chunk in chunks:
+ remaining = max_bytes + 1 - total
+ if remaining <= 0:
+ break
+ kept.append(chunk[:remaining])
+ total += min(len(chunk), remaining)
+ if total > max_bytes:
+ break
+ return b"".join(kept)
+
+
class CurlCffiTransport:
"""保持浏览器 TLS/HTTP2 指纹的有界同步 transport。
diff --git a/tests/test_http.py b/tests/test_http.py
index e5087a37b..9b247a47f 100644
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -79,8 +79,63 @@ class HttpTransportTests(unittest.TestCase):
self.assertEqual(response.body, b"abcde")
self.assertEqual(response.headers["etag"], '"v1"')
+ def test_cookies_survive_a_same_origin_redirect_and_die_at_the_origin_boundary(self):
+ """httpx 自己跟跳会丢掉显式 Cookie 头;连接器的登录会话正是这么传进来的。
+
+ 真实用例:simpcity.cr 的纯数字线程地址 301 到带 slug 的地址,带 cookie 直接请求
+ 目标页 200,经 httpx 跟跳到达就是 403(2026-09-08 实测)。
+ """
+ seen = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append((str(request.url), request.headers.get("Cookie"),
+ request.headers.get("Authorization")))
+ if request.url.path == "/threads/1/":
+ return httpx.Response(301, headers={"Location": "/threads/slug.1/"})
+ if request.url.path == "/threads/slug.1/":
+ return httpx.Response(302, headers={"Location": "https://cdn.example/x"})
+ return httpx.Response(200, content=b"ok")
+
+ with httpx.Client(transport=httpx.MockTransport(handler)) as client:
+ response = HttpxTransport(client)(
+ HttpRequest("GET", "https://forum.test/threads/1/",
+ {"Cookie": "s=1", "Authorization": "Bearer t"}),
+ timeout=2, max_bytes=64)
+ self.assertEqual(response.status, 200)
+ self.assertEqual(response.url, "https://cdn.example/x")
+ self.assertEqual(seen, [
+ ("https://forum.test/threads/1/", "s=1", "Bearer t"),
+ ("https://forum.test/threads/slug.1/", "s=1", "Bearer t"),
+ ("https://cdn.example/x", None, None),
+ ])
+
+ def test_a_303_turns_the_post_into_a_get_without_its_body(self):
+ seen = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append((request.method, request.content, request.headers.get("Content-Type")))
+ if request.method == "POST":
+ return httpx.Response(303, headers={"Location": "/done"})
+ return httpx.Response(200, content=b"ok")
+
+ with httpx.Client(transport=httpx.MockTransport(handler)) as client:
+ HttpxTransport(client)(
+ HttpRequest("POST", "https://forum.test/login", {"Content-Type": "text/plain"},
+ b"x=1"),
+ timeout=2, max_bytes=64)
+ self.assertEqual(seen, [("POST", b"x=1", "text/plain"), ("GET", b"", None)])
+
+ def test_a_redirect_loop_is_reported_as_an_http_error(self):
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(302, headers={"Location": request.url.path})
+
+ with httpx.Client(transport=httpx.MockTransport(handler)) as client:
+ with self.assertRaises(httpx.HTTPError):
+ HttpxTransport(client)(HttpRequest("GET", "https://forum.test/loop", {}),
+ timeout=2, max_bytes=64)
+
def test_the_final_url_after_a_redirect_is_reported_not_the_requested_one(self):
- """两个 transport 都开着 follow_redirects,请求地址因此不等于实际取到的页面。
+ """两个 transport 都跟重定向,请求地址因此不等于实际取到的页面。
真实用例:minnano-av 的女优检索唯一命中时会跳到 `actressNNN.html`,多命中则
停在检索页。两种情况的请求地址一模一样,只有最终地址能区分——而检索页正文里