Files
StarPunk/starpunk/csrf.py
T
PhilandClaude Opus 5.5 75946be7b2 maint: Dependency upgrades and High backlog items (v2.11.0)
- All dependencies to current releases (97 known vulnerabilities -> 0),
  Python 3.14, uv pinned, requirements-test.txt, lxml/dateutil pinned
- CSRF tokens on admin forms, logout and IndieAuth consent
- IndieAuth client and crosspost link-card fetches via safe_get
- FLASK_DEBUG/FLASK_ENV default off/production; image sets them
- Foreign keys enforced on pooled connections; migration 018 removes orphans
- Rate limits shared across processes (rate_limits, migration 019)
- datetime.utcnow() and sqlite3 default adapters replaced
- compose.yaml fixed; duplicate dev_auth.py and test.ini removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:09:52 -07:00

57 lines
2.0 KiB
Python

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