Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
163 changes: 163 additions & 0 deletions tests/test_csrf_form_token_session_binding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# Copyright (c) 2026 Code Infinity
# SPDX-License-Identifier: MPL-2.0
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

# A form token rendered during a request is bound to that request's session.
#
# The CSRF check compares a token's session_id with the session of the write
# that carries it, but it can only do so when the token HAS a session_id. The
# rendered token never had one: form_token() read a process-wide id that no
# dispatch path set, so a token rendered for one browser was accepted on a
# write carrying any other browser's session cookie. These tests render the
# token through the real front controller, in one browser, and post it in
# another.
import os
import re

import pytest

from tina4_python.auth import get_token
from tina4_python.cache import ResponseCache
from tina4_python.core.middleware import CsrfMiddleware, Middleware
from tina4_python.core.router import Router, get as route_get, middleware, post as route_post
from tina4_python.frond.engine import Frond
from tina4_python.test_client import TestClient


@pytest.fixture(autouse=True)
def _app(tmp_path, monkeypatch):
(tmp_path / "src" / "templates").mkdir(parents=True)
(tmp_path / "src" / "templates" / "form.twig").write_text("{{ form_token_value() }}")
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("TINA4_CSRF", "true")
monkeypatch.setenv("TINA4_SECRET", "test-csrf-secret-0123456789abcdef")
monkeypatch.setenv("TINA4_SESSION_PATH", str(tmp_path / "sessions"))
Router.clear()
saved = list(Middleware.get_global())
Middleware._global_middleware = [CsrfMiddleware]

@route_get("/login")
async def login(request, response):
request.session.set("token", get_token({"user": "victim"}))
return response.json({"logged_in": True})

@route_get("/form")
async def form(request, response):
request.session.set("seen", True)
return response.render("form.twig", {})

@route_get("/fresh")
async def fresh(request, response):
return response.render("form.twig", {})

@middleware(ResponseCache)
@route_get("/cached")
async def cached(request, response):
return response.render("form.twig", {})

@route_post("/save")
async def save(request, response):
return response.json({"saved": True})

yield
Router.clear()
Middleware._global_middleware = saved


class Browser:
"""One cookie jar, sent with every request through the real dispatcher."""

def __init__(self):
self.client = TestClient()
self.cookies = {}

def _headers(self):
if not self.cookies:
return {}
return {"cookie": "; ".join(f"{k}={v}" for k, v in self.cookies.items())}

def _keep(self, response):
for value in response.get_all("set-cookie"):
name, rest = value.split("=", 1)
self.cookies[name] = rest.split(";", 1)[0]
return response

def get(self, path):
return self._keep(self.client.get(path, headers=self._headers()))

def post(self, path, token):
return self._keep(self.client.post(path, json={"formToken": token}, headers=self._headers()))


def _rendered_token(browser, path="/form"):
token = browser.get(path).text().strip()
assert re.fullmatch(r"[\w-]+\.[\w-]+\.[\w-]+", token), token
return token


def test_a_token_rendered_for_one_session_is_refused_on_another():
attacker, victim = Browser(), Browser()
stolen = _rendered_token(attacker)
victim.get("/login")
_rendered_token(victim)

assert victim.post("/save", stolen).status == 403


def test_a_token_rendered_for_a_session_passes_on_that_session():
victim = Browser()
victim.get("/login")
own = _rendered_token(victim)

assert victim.post("/save", own).status == 200


def test_a_page_that_writes_no_session_still_binds_and_keeps_the_session():
# Nothing else stores the session on /fresh, so without a marker it would
# send no cookie, and the visitor's own POST would arrive under a new id.
visitor, other = Browser(), Browser()
token = _rendered_token(visitor, "/fresh")
assert visitor.cookies, "rendering a bound token must leave a session cookie"
visitor.get("/login")
other.get("/login")

assert visitor.post("/save", token).status == 200
assert other.post("/save", token).status == 403


def test_a_cached_page_does_not_replay_one_visitors_token_to_the_next():
# The session cookie is set after the response cache decides to store the
# page, so a page whose token is bound to a NEW session must not be stored:
# every later visitor would be served the first visitor's token.
first, second = Browser(), Browser()
first_token = _rendered_token(first, "/cached")
second_token = _rendered_token(second, "/cached")

assert first.post("/save", first_token).status != 403
assert second.post("/save", second_token).status != 403


def test_a_render_outside_a_request_is_unbound():
token = str(Frond().render_string("{{ form_token_value() }}")).strip()
from tina4_python.auth import Auth
assert "session_id" not in Auth(secret=os.environ["TINA4_SECRET"]).get_payload(token)


def test_a_dispatch_does_not_leave_its_session_bound_afterwards():
# An embedder awaits handle() in its own task; a token it renders after the
# request is finished belongs to no request and must not carry its session.
import asyncio
from tina4_python.auth import Auth
from tina4_python.core.request import Request
from tina4_python.core.server import handle

async def dispatch_then_render():
scope = {"type": "http", "method": "GET", "path": "/form", "query_string": b"",
"headers": [], "client": ("127.0.0.1", 1)}
await handle(Request.from_scope(scope, b""))
return str(Frond().render_string("{{ form_token_value() }}")).strip()

token = asyncio.run(dispatch_then_render())
assert "session_id" not in Auth(secret=os.environ["TINA4_SECRET"]).get_payload(token)
7 changes: 5 additions & 2 deletions tests/test_security_headers_on_refusals.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,11 @@ def test_csrf_refusal_of_a_signed_in_forged_write_carries_the_headers(server):


def test_auth_gate_refusal_of_a_write_carries_the_headers(server):
"""A valid form token gets past CSRF; no credentials, so the auth gate says 401."""
opener = urllib.request.build_opener()
"""A valid form token gets past CSRF; no credentials, so the auth gate says 401.

The token is bound to the session that rendered it, so the write carries
that session's cookie, as a browser would."""
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor())
token = json.loads(opener.open(f"{server['base']}/refusal/form-token", timeout=10).read())["token"]
status, headers, body = _send(opener, f"{server['base']}/refusal/write", "POST", {"X-Form-Token": token})
_assert_refused_with_headers(server, "auth gate (write)", status, headers, body, 401)
Expand Down
10 changes: 9 additions & 1 deletion tina4_python/cache/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1418,7 +1418,8 @@ def _may_store(request, response) -> bool:
Authorization, and Tina4's own session mechanism IS a cookie. Because
the key is method + URL, storing such a response replays one signed-in
user's page to whoever asks for that URL next. A response that installs
a session is per-user by construction for the same reason.
a session is per-user by construction for the same reason, whether it
already carries the Set-Cookie or the session is about to add it.

Both cookie cases stay cacheable when the response opts in explicitly with
a shared-cache directive, which is how a genuinely public page served to
Expand All @@ -1435,6 +1436,13 @@ def _may_store(request, response) -> bool:
return _shared_cache_allowed(response)
if _header_value(response, "Set-Cookie") is not None:
return _shared_cache_allowed(response)
# The session cookie is added after this check, so a response that is
# about to install one carries no Set-Cookie yet: a request that came
# without a cookie and leaves its session holding data (a form token
# bound to it marks it) is that case.
session = getattr(request, "session", None)
if session is not None and not session.is_fresh():
return _shared_cache_allowed(response)
return True

@staticmethod
Expand Down
5 changes: 5 additions & 0 deletions tina4_python/core/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2959,8 +2959,12 @@ async def handle(request: Request) -> Response:
from tina4_python.core.csp import generate_nonce, set_current_nonce, clear_current_nonce
request_nonce = generate_nonce()
set_current_nonce(request_nonce)
from tina4_python.frond.engine import set_request_session, reset_request_session
session_token = set_request_session(None)
try:
_init_session(request)
# form_token() binds each token to this request's session (CSRF).
set_request_session(request.session)

response = Response()
response.csp_nonce = request_nonce
Expand Down Expand Up @@ -2994,6 +2998,7 @@ async def handle(request: Request) -> Response:
# already finished. The CSP nonce has the same lifetime.
clear_request_id()
clear_current_nonce()
reset_request_session(session_token)

def asgi(root_dir: str = "src"):
"""Build the ASGI application, with routes discovered.
Expand Down
39 changes: 38 additions & 1 deletion tina4_python/frond/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
owns expression evaluation, the filter set, and rendering. Structure is never
re-derived here — see the parser's module docstring for why.
"""
import contextvars
import os
import re
import html
Expand Down Expand Up @@ -1577,7 +1578,7 @@ def _generate_form_jwt(descriptor: str = "", session_id: str = "") -> str:
payload["context"] = descriptor

# Include session_id in payload for CSRF session binding
sid = session_id or _form_token_session_id
sid = session_id or _request_session_id() or _form_token_session_id
if sid:
payload["session_id"] = sid

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


# The session of the request being dispatched. The server sets it for each
# request, so a token is bound to the session that rendered it without sharing
# a process-wide value between overlapping requests.
_request_session: contextvars.ContextVar = contextvars.ContextVar(
"tina4_form_token_session", default=None
)


def set_request_session(session):
"""Publish the current request's session to form_token(). Returns the
contextvars token the caller passes to reset_request_session()."""
return _request_session.set(session)


def reset_request_session(token) -> None:
"""Withdraw the session published by set_request_session()."""
_request_session.reset(token)


def _request_session_id() -> str:
"""The current request's session id, or "" outside a request.

A session that holds nothing is sent no cookie, so the form's own POST
would arrive under a newly minted id and fail its own token. Rendering a
bound token therefore stores a marker, which makes the session persist.
"""
session = _request_session.get()
sid = getattr(session, "session_id", None) if session is not None else None
if not sid:
return ""
is_fresh = getattr(session, "is_fresh", None)
if callable(is_fresh) and is_fresh():
session.set("_tina4_csrf", True)
return sid


# ── Frond Engine ────────────────────────────────────────────────


Expand Down
Loading