"""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()