Fix CSRF in bot

This commit is contained in:
blankhex committed 2026-10-24 20:19:25 +03:00
1 parent 6d2d9ab9ae
commit fffc1b0c81
3 files changed
+170 -19

No files matched your search

+62 -19
View File
@@ -80,26 +80,79 @@ class GoChatApi:
)
if proxy:
self._http.proxies.update({"http": proxy, "https": proxy})
# Cookies are tracked ourselves (see _send) so they are sent even when
# the server marks them Secure while we talk plain HTTP.
self._cookies: dict[str, str] = {}
self.restore_session(session_token, csrf_token)
def restore_session(self, session_token: str, csrf_token: str) -> None:
if session_token:
self._http.cookies.set(SESSION_COOKIE, session_token)
self._cookies[SESSION_COOKIE] = session_token
if csrf_token:
self._http.cookies.set(CSRF_COOKIE, csrf_token)
self._cookies[CSRF_COOKIE] = csrf_token
@property
def session_token(self) -> str:
return self._http.cookies.get(SESSION_COOKIE, "")
return self._cookies.get(SESSION_COOKIE, "")
@property
def csrf_token(self) -> str:
return self._http.cookies.get(CSRF_COOKIE, "")
return self._cookies.get(CSRF_COOKIE, "")
@property
def has_session(self) -> bool:
return bool(self.session_token)
def _capture(self, response: requests.Response) -> None:
for name in (SESSION_COOKIE, CSRF_COOKIE):
value = response.cookies.get(name)
if value:
self._cookies[name] = value
def _send(
self,
method: str,
path: str,
*,
json_body: dict | None = None,
params: dict | None = None,
headers: dict[str, str] | None = None,
) -> requests.Response:
request_headers = dict(headers or {})
if json_body is not None:
request_headers["Content-Type"] = "application/json"
cookie_header = "; ".join(f"{k}={v}" for k, v in self._cookies.items() if v)
# Keep the jar empty so requests does not override our explicit Cookie
# header (which would drop Secure cookies on plain HTTP).
self._http.cookies.clear()
if cookie_header:
request_headers["Cookie"] = cookie_header
try:
response = self._http.request(
method,
f"{self.base_url}{path}",
json=json_body,
params=params,
headers=request_headers,
timeout=self.timeout,
)
except requests.RequestException as exc:
raise ApiError(f"request to {path} failed: {exc}") from exc
self._capture(response)
return response
def _ensure_csrf(self) -> None:
"""Seed the csrf cookie via a GET when we do not have one yet.
State-changing requests are rejected unless the X-CSRF-Token header
matches the csrf cookie, and the cookie only appears after some request.
"""
if self.csrf_token:
return
self._send("GET", "/api/config")
def _request(
self,
method: str,
@@ -110,22 +163,12 @@ class GoChatApi:
expect_json: bool = True,
) -> Any:
headers: dict[str, str] = {}
if json_body is not None:
headers["Content-Type"] = "application/json"
if method not in ("GET", "HEAD") and self.csrf_token:
headers[CSRF_HEADER] = self.csrf_token
if method not in ("GET", "HEAD"):
self._ensure_csrf()
if self.csrf_token:
headers[CSRF_HEADER] = self.csrf_token
try:
response = self._http.request(
method,
f"{self.base_url}{path}",
json=json_body,
params=params,
headers=headers,
timeout=self.timeout,
)
except requests.RequestException as exc:
raise ApiError(f"request to {path} failed: {exc}") from exc
response = self._send(method, path, json_body=json_body, params=params, headers=headers)
if response.status_code == 204:
return None