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

+98
View File
@@ -0,0 +1,98 @@
"""End-to-end check of the CSRF/session flow against a fake backend.
Reproduces the real backend behaviour that broke sign-in:
* a state-changing request without a matching X-CSRF-Token is rejected with
403 "CSRF Token Validation Failed";
* cookies are issued with the Secure flag, but the bot talks plain HTTP.
Run: python bots/_csrf_test.py
"""
import os
import sys
import threading
import uuid
from http.server import BaseHTTPRequestHandler, HTTPServer
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from meetings_telegram_bot.api import GoChatApi
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def _csrf_cookie(self):
raw = self.headers.get("Cookie", "")
for part in raw.split(";"):
name, _, value = part.strip().partition("=")
if name == "csrf":
return value
return ""
def _session_cookie(self):
raw = self.headers.get("Cookie", "")
for part in raw.split(";"):
name, _, value = part.strip().partition("=")
if name == "session":
return value
return ""
def _send(self, code, body=b"", cookies=None):
self.send_response(code)
self.send_header("Content-Type", "application/json")
for c in cookies or []:
self.send_header("Set-Cookie", c)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path.startswith("/api/config"):
# Seed a csrf cookie, Secure, exactly like the real server.
self._send(200, b"{}", [f"csrf={uuid.uuid4().hex}; Path=/; Secure; SameSite=Lax"])
elif self.path.startswith("/api/profile") or self.path.startswith("/api/meetings"):
if not self._session_cookie():
self._send(401, b'{"error":"unauthorized"}')
elif self.path.startswith("/api/meetings"):
self._send(200, b"[]")
else:
self._send(200, b'{"id":1}')
else:
self._send(404, b"{}")
def do_POST(self):
if self.path.startswith("/api/auth/signin"):
if self.headers.get("X-CSRF-Token", "") != self._csrf_cookie() or not self._csrf_cookie():
self._send(403, b'{"error":"CSRF Token Validation Failed"}')
return
self._send(
200,
b'{"id":1}',
[
f"session={uuid.uuid4().hex}; Path=/; Secure; HttpOnly; SameSite=Lax",
f"csrf={uuid.uuid4().hex}; Path=/; Secure; SameSite=Lax",
],
)
else:
self._send(404, b"{}")
def main():
server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
api = GoChatApi(f"http://127.0.0.1:{port}")
api.signin("bot-user", "secret") # must not raise
assert api.has_session, "no session cookie captured"
assert api.list_meetings() == []
print("CSRF/session flow OK")
finally:
server.shutdown()
if __name__ == "__main__":
main()
+10
View File
@@ -53,3 +53,13 @@ SOCKS5_PROXY=socks5://user:password@127.0.0.1:1080
Routes both API and Telegram traffic through the proxy. Leave empty to connect
directly.
## Troubleshooting
- `CSRF Token Validation Failed`: delete `state.json` (stale cookies) and run
again. The bot seeds the csrf cookie itself and sends cookies even when the
server marks them `Secure`, so plain-HTTP setups work.
- `401 Unauthorized`: check `API_LOGIN` / `API_PASSWORD`.
- `chat not found`: check `TELEGRAM_CHAT_ID` and that the bot is in the group.
- Nothing posted: the first run intentionally stays silent. Create a meeting
after the bot starts.
+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