Skip to content

Commit e4c1b95

Browse files
committed
fix(csrf): a form token is bound to the session that rendered it
A token rendered by form_token() during a request is now bound to that request's session, so the CSRF check compares it with the session that sends it back. A page that renders a token for a visitor with no session yet marks the session so it gets a cookie, and the response cache does not store such a page. Signed-off-by: Michael <michael@codeinfinity.co.za>
1 parent 2d912a5 commit e4c1b95

5 files changed

Lines changed: 220 additions & 4 deletions

File tree

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
# Copyright (c) 2026 Code Infinity
2+
# SPDX-License-Identifier: MPL-2.0
3+
# This Source Code Form is subject to the terms of the Mozilla Public
4+
# License, v. 2.0. If a copy of the MPL was not distributed with this
5+
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
6+
7+
# A form token rendered during a request is bound to that request's session.
8+
#
9+
# The CSRF check compares a token's session_id with the session of the write
10+
# that carries it, but it can only do so when the token HAS a session_id. The
11+
# rendered token never had one: form_token() read a process-wide id that no
12+
# dispatch path set, so a token rendered for one browser was accepted on a
13+
# write carrying any other browser's session cookie. These tests render the
14+
# token through the real front controller, in one browser, and post it in
15+
# another.
16+
import os
17+
import re
18+
19+
import pytest
20+
21+
from tina4_python.auth import get_token
22+
from tina4_python.cache import ResponseCache
23+
from tina4_python.core.middleware import CsrfMiddleware, Middleware
24+
from tina4_python.core.router import Router, get as route_get, middleware, post as route_post
25+
from tina4_python.frond.engine import Frond
26+
from tina4_python.test_client import TestClient
27+
28+
29+
@pytest.fixture(autouse=True)
30+
def _app(tmp_path, monkeypatch):
31+
(tmp_path / "src" / "templates").mkdir(parents=True)
32+
(tmp_path / "src" / "templates" / "form.twig").write_text("{{ form_token_value() }}")
33+
monkeypatch.chdir(tmp_path)
34+
monkeypatch.setenv("TINA4_CSRF", "true")
35+
monkeypatch.setenv("TINA4_SECRET", "test-csrf-secret-0123456789abcdef")
36+
monkeypatch.setenv("TINA4_SESSION_PATH", str(tmp_path / "sessions"))
37+
Router.clear()
38+
saved = list(Middleware.get_global())
39+
Middleware._global_middleware = [CsrfMiddleware]
40+
41+
@route_get("/login")
42+
async def login(request, response):
43+
request.session.set("token", get_token({"user": "victim"}))
44+
return response.json({"logged_in": True})
45+
46+
@route_get("/form")
47+
async def form(request, response):
48+
request.session.set("seen", True)
49+
return response.render("form.twig", {})
50+
51+
@route_get("/fresh")
52+
async def fresh(request, response):
53+
return response.render("form.twig", {})
54+
55+
@middleware(ResponseCache)
56+
@route_get("/cached")
57+
async def cached(request, response):
58+
return response.render("form.twig", {})
59+
60+
@route_post("/save")
61+
async def save(request, response):
62+
return response.json({"saved": True})
63+
64+
yield
65+
Router.clear()
66+
Middleware._global_middleware = saved
67+
68+
69+
class Browser:
70+
"""One cookie jar, sent with every request through the real dispatcher."""
71+
72+
def __init__(self):
73+
self.client = TestClient()
74+
self.cookies = {}
75+
76+
def _headers(self):
77+
if not self.cookies:
78+
return {}
79+
return {"cookie": "; ".join(f"{k}={v}" for k, v in self.cookies.items())}
80+
81+
def _keep(self, response):
82+
for value in response.get_all("set-cookie"):
83+
name, rest = value.split("=", 1)
84+
self.cookies[name] = rest.split(";", 1)[0]
85+
return response
86+
87+
def get(self, path):
88+
return self._keep(self.client.get(path, headers=self._headers()))
89+
90+
def post(self, path, token):
91+
return self._keep(self.client.post(path, json={"formToken": token}, headers=self._headers()))
92+
93+
94+
def _rendered_token(browser, path="/form"):
95+
token = browser.get(path).text().strip()
96+
assert re.fullmatch(r"[\w-]+\.[\w-]+\.[\w-]+", token), token
97+
return token
98+
99+
100+
def test_a_token_rendered_for_one_session_is_refused_on_another():
101+
attacker, victim = Browser(), Browser()
102+
stolen = _rendered_token(attacker)
103+
victim.get("/login")
104+
_rendered_token(victim)
105+
106+
assert victim.post("/save", stolen).status == 403
107+
108+
109+
def test_a_token_rendered_for_a_session_passes_on_that_session():
110+
victim = Browser()
111+
victim.get("/login")
112+
own = _rendered_token(victim)
113+
114+
assert victim.post("/save", own).status == 200
115+
116+
117+
def test_a_page_that_writes_no_session_still_binds_and_keeps_the_session():
118+
# Nothing else stores the session on /fresh, so without a marker it would
119+
# send no cookie, and the visitor's own POST would arrive under a new id.
120+
visitor, other = Browser(), Browser()
121+
token = _rendered_token(visitor, "/fresh")
122+
assert visitor.cookies, "rendering a bound token must leave a session cookie"
123+
visitor.get("/login")
124+
other.get("/login")
125+
126+
assert visitor.post("/save", token).status == 200
127+
assert other.post("/save", token).status == 403
128+
129+
130+
def test_a_cached_page_does_not_replay_one_visitors_token_to_the_next():
131+
# The session cookie is set after the response cache decides to store the
132+
# page, so a page whose token is bound to a NEW session must not be stored:
133+
# every later visitor would be served the first visitor's token.
134+
first, second = Browser(), Browser()
135+
first_token = _rendered_token(first, "/cached")
136+
second_token = _rendered_token(second, "/cached")
137+
138+
assert first.post("/save", first_token).status != 403
139+
assert second.post("/save", second_token).status != 403
140+
141+
142+
def test_a_render_outside_a_request_is_unbound():
143+
token = str(Frond().render_string("{{ form_token_value() }}")).strip()
144+
from tina4_python.auth import Auth
145+
assert "session_id" not in Auth(secret=os.environ["TINA4_SECRET"]).get_payload(token)
146+
147+
148+
def test_a_dispatch_does_not_leave_its_session_bound_afterwards():
149+
# An embedder awaits handle() in its own task; a token it renders after the
150+
# request is finished belongs to no request and must not carry its session.
151+
import asyncio
152+
from tina4_python.auth import Auth
153+
from tina4_python.core.request import Request
154+
from tina4_python.core.server import handle
155+
156+
async def dispatch_then_render():
157+
scope = {"type": "http", "method": "GET", "path": "/form", "query_string": b"",
158+
"headers": [], "client": ("127.0.0.1", 1)}
159+
await handle(Request.from_scope(scope, b""))
160+
return str(Frond().render_string("{{ form_token_value() }}")).strip()
161+
162+
token = asyncio.run(dispatch_then_render())
163+
assert "session_id" not in Auth(secret=os.environ["TINA4_SECRET"]).get_payload(token)

‎tests/test_security_headers_on_refusals.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,11 @@ def test_csrf_refusal_of_a_signed_in_forged_write_carries_the_headers(server):
183183

184184

185185
def test_auth_gate_refusal_of_a_write_carries_the_headers(server):
186-
"""A valid form token gets past CSRF; no credentials, so the auth gate says 401."""
187-
opener = urllib.request.build_opener()
186+
"""A valid form token gets past CSRF; no credentials, so the auth gate says 401.
187+
188+
The token is bound to the session that rendered it, so the write carries
189+
that session's cookie, as a browser would."""
190+
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor())
188191
token = json.loads(opener.open(f"{server['base']}/refusal/form-token", timeout=10).read())["token"]
189192
status, headers, body = _send(opener, f"{server['base']}/refusal/write", "POST", {"X-Form-Token": token})
190193
_assert_refused_with_headers(server, "auth gate (write)", status, headers, body, 401)

‎tina4_python/cache/__init__.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1418,7 +1418,8 @@ def _may_store(request, response) -> bool:
14181418
Authorization, and Tina4's own session mechanism IS a cookie. Because
14191419
the key is method + URL, storing such a response replays one signed-in
14201420
user's page to whoever asks for that URL next. A response that installs
1421-
a session is per-user by construction for the same reason.
1421+
a session is per-user by construction for the same reason, whether it
1422+
already carries the Set-Cookie or the session is about to add it.
14221423
14231424
Both cookie cases stay cacheable when the response opts in explicitly with
14241425
a shared-cache directive, which is how a genuinely public page served to
@@ -1435,6 +1436,13 @@ def _may_store(request, response) -> bool:
14351436
return _shared_cache_allowed(response)
14361437
if _header_value(response, "Set-Cookie") is not None:
14371438
return _shared_cache_allowed(response)
1439+
# The session cookie is added after this check, so a response that is
1440+
# about to install one carries no Set-Cookie yet: a request that came
1441+
# without a cookie and leaves its session holding data (a form token
1442+
# bound to it marks it) is that case.
1443+
session = getattr(request, "session", None)
1444+
if session is not None and not session.is_fresh():
1445+
return _shared_cache_allowed(response)
14381446
return True
14391447

14401448
@staticmethod

‎tina4_python/core/server.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2959,8 +2959,12 @@ async def handle(request: Request) -> Response:
29592959
from tina4_python.core.csp import generate_nonce, set_current_nonce, clear_current_nonce
29602960
request_nonce = generate_nonce()
29612961
set_current_nonce(request_nonce)
2962+
from tina4_python.frond.engine import set_request_session, reset_request_session
2963+
session_token = set_request_session(None)
29622964
try:
29632965
_init_session(request)
2966+
# form_token() binds each token to this request's session (CSRF).
2967+
set_request_session(request.session)
29642968

29652969
response = Response()
29662970
response.csp_nonce = request_nonce
@@ -2994,6 +2998,7 @@ async def handle(request: Request) -> Response:
29942998
# already finished. The CSP nonce has the same lifetime.
29952999
clear_request_id()
29963000
clear_current_nonce()
3001+
reset_request_session(session_token)
29973002

29983003
def asgi(root_dir: str = "src"):
29993004
"""Build the ASGI application, with routes discovered.

‎tina4_python/frond/engine.py‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
owns expression evaluation, the filter set, and rendering. Structure is never
1616
re-derived here — see the parser's module docstring for why.
1717
"""
18+
import contextvars
1819
import os
1920
import re
2021
import html
@@ -1577,7 +1578,7 @@ def _generate_form_jwt(descriptor: str = "", session_id: str = "") -> str:
15771578
payload["context"] = descriptor
15781579

15791580
# Include session_id in payload for CSRF session binding
1580-
sid = session_id or _form_token_session_id
1581+
sid = session_id or _request_session_id() or _form_token_session_id
15811582
if sid:
15821583
payload["session_id"] = sid
15831584

@@ -1643,6 +1644,42 @@ def set_form_token_session_id(session_id: str) -> None:
16431644
_form_token_session_id = session_id or ""
16441645

16451646

1647+
# The session of the request being dispatched. The server sets it for each
1648+
# request, so a token is bound to the session that rendered it without sharing
1649+
# a process-wide value between overlapping requests.
1650+
_request_session: contextvars.ContextVar = contextvars.ContextVar(
1651+
"tina4_form_token_session", default=None
1652+
)
1653+
1654+
1655+
def set_request_session(session):
1656+
"""Publish the current request's session to form_token(). Returns the
1657+
contextvars token the caller passes to reset_request_session()."""
1658+
return _request_session.set(session)
1659+
1660+
1661+
def reset_request_session(token) -> None:
1662+
"""Withdraw the session published by set_request_session()."""
1663+
_request_session.reset(token)
1664+
1665+
1666+
def _request_session_id() -> str:
1667+
"""The current request's session id, or "" outside a request.
1668+
1669+
A session that holds nothing is sent no cookie, so the form's own POST
1670+
would arrive under a newly minted id and fail its own token. Rendering a
1671+
bound token therefore stores a marker, which makes the session persist.
1672+
"""
1673+
session = _request_session.get()
1674+
sid = getattr(session, "session_id", None) if session is not None else None
1675+
if not sid:
1676+
return ""
1677+
is_fresh = getattr(session, "is_fresh", None)
1678+
if callable(is_fresh) and is_fresh():
1679+
session.set("_tina4_csrf", True)
1680+
return sid
1681+
1682+
16461683
# ── Frond Engine ────────────────────────────────────────────────
16471684

16481685

0 commit comments

Comments
 (0)