|
| 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) |
0 commit comments