""" CSRF protection for the admin and consent forms (v2.11.0) The token is an HMAC of the login session cookie under the app secret: no storage, tied to the session, and different after every login. Forms carry it as a hidden `csrf_token` field (template global `csrf_token()`); POSTs to protected endpoints without the right token get 400. Protected: every admin POST, logout, and the IndieAuth consent ("approve"). Endpoints used by apps with bearer tokens (Micropub, token, revoke, Webmention, WebSub) are not: they have no cookie-based authority. """ import hashlib import hmac from flask import abort, current_app, request SESSION_COOKIE = "starpunk_session" FIELD = "csrf_token" HEADER = "X-CSRF-Token" PROTECTED_ENDPOINTS = {"auth.logout", "indieauth.approve"} def csrf_token() -> str: """The CSRF token for the current login session ('' when not logged in)""" session = request.cookies.get(SESSION_COOKIE) if not session: return "" key = str(current_app.config["SECRET_KEY"]).encode("utf-8") return hmac.new(key, b"csrf:" + session.encode("utf-8"), hashlib.sha256).hexdigest() def _protected() -> bool: return request.blueprint == "admin" or request.endpoint in PROTECTED_ENDPOINTS def check_csrf(): """before_request: refuse state-changing requests without a valid token""" if request.method in ("GET", "HEAD", "OPTIONS") or not current_app.config.get("CSRF_ENABLED", True): return None if not _protected(): return None expected = csrf_token() if not expected: return None # not logged in: the route's own auth check refuses it sent = request.form.get(FIELD) or request.headers.get(HEADER) or "" if not hmac.compare_digest(sent, expected): current_app.logger.warning(f"CSRF token missing or wrong for {request.endpoint}") abort(400, description="The form expired or came from another site. Reload the page and try again.") return None def init_app(app) -> None: app.before_request(check_csrf) app.add_template_global(csrf_token, "csrf_token")