Skip to content

Commit e274ee4

Browse files
committed
Merge branch 'fix/request-processor-scope' into fix/block-super
# Conflicts: # CHANGELOG.md
2 parents 9e5beee + b2e1f23 commit e274ee4

6 files changed

Lines changed: 146 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
### Precision
66

7+
- A `TEMPLATES` assigned inside a function or a class no longer counts as Django settings: only a module-level assignment can activate the `request` context processor, and only a mention of the module's `TEMPLATES` elsewhere leaves that activation uncertain. A function-local `TEMPLATES`, called or not, used to enable the implicit request source, upgrading a template filter finding to exploitable (#184).
78
- A template block that renders `{{ block.super }}` keeps the parent block's content, so the filters the parent applies stay fed by the render context, with the parent template as the place of the call; a block without it still replaces the parent's whole block, and a chain of templates keeps exactly the parents each level renders. The parent's filters used to drop out of the exploitable flow as soon as a child defined the block (#185).
89

910
## 0.18.0 (2026-09-28)

‎docs/usage.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -400,9 +400,12 @@ With the `django.template.context_processors.request` context processor, a templ
400400
rendered with the request reads it as `request`: `{{ request.GET.q|striptags }}` is
401401
exploitable at the render call too. The analyzer counts it only where all of these hold:
402402

403-
- The project's settings assign `TEMPLATES` a literal list, every `DjangoTemplates`
404-
engine of it lists the processor in a literal `context_processors`, and no other code
405-
of the project names `TEMPLATES`. A mere mention of the processor proves nothing.
403+
- The project's settings assign `TEMPLATES` a literal list at module level, every
404+
`DjangoTemplates` engine of it lists the processor in a literal `context_processors`,
405+
and no other code of the project names the module's `TEMPLATES`, or a `TEMPLATES` it
406+
does not bind, as a star import gives. A `TEMPLATES` bound in a function or a class
407+
is another name: it configures nothing and changes nothing.
408+
A mere mention of the processor proves nothing.
406409
- The render call passes the request: `render` and `TemplateResponse` always do,
407410
`render_to_string` when given `request`, `SimpleTemplateResponse` never.
408411
- The render's context is certain, absent or a dict literal as above, so it cannot hide

‎src/coretrace_python/engine.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,8 @@ def analyze_project(
447447
templates = project_templates(root)
448448
clearing = models.clearing(escaped)
449449
template_calls = models.template_calls(
450-
templates.filters, request_processor(modules[name] for name in sorted(analysable))
450+
templates.filters,
451+
request_processor((modules[name], analysable[name].get(ScopeAnalysis)) for name in sorted(analysable)),
451452
)
452453
for manager in analysable.values():
453454
manager.provide(RegisteredRoutes, routes)

‎src/coretrace_python/semantic/scopes.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,8 @@ def scope(self, scope_id: ScopeId) -> Scope:
113113
def children(self, scope_id: ScopeId) -> tuple[Scope, ...]:
114114
return self._children[scope_id]
115115

116-
def scope_for(self, node: nodes.Function | nodes.Class | nodes.Comprehension) -> Scope:
117-
"""Return the scope introduced by a definition or comprehension node."""
116+
def scope_for(self, node: nodes.Function | nodes.Class | nodes.Lambda | nodes.Comprehension) -> Scope:
117+
"""Return the scope introduced by a definition, lambda or comprehension node."""
118118

119119
return self._scopes[self._spans[node.span]]
120120

‎src/coretrace_python/taint/templates.py‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
TemplateFilter,
4545
discover_files,
4646
)
47+
from coretrace_python.semantic.scopes import ResolutionKind, ScopeId, ScopeTable
4748
from coretrace_python.semantic.symbols import SymbolId
4849
from coretrace_python.source import SourceId, SourceSpan
4950
from coretrace_python.taint.models import ModelTable
@@ -592,29 +593,41 @@ def _through(bound: frozenset[str], name: str) -> frozenset[str]:
592593
return frozenset(".".join(f"{b}.{attribute}".split(".")[:2]) if attribute else b for b in bound)
593594

594595

595-
def request_processor(modules: Iterable[nodes.Module]) -> bool:
596+
def request_processor(modules: Iterable[tuple[nodes.Module, ScopeTable]]) -> bool:
596597
"""Whether every Django template engine the project's settings configure runs the
597-
``request`` context processor, for certain: each assignment to ``TEMPLATES`` is a
598-
literal list of literal engines, at least one of them ``DjangoTemplates``, and each
599-
of those lists the processor in a literal ``context_processors``; no other code
600-
names ``TEMPLATES``, which could change it. A mere mention of the processor proves
601-
nothing."""
598+
``request`` context processor, for certain: each module-level assignment to
599+
``TEMPLATES`` is a literal list of literal engines, at least one of them
600+
``DjangoTemplates``, and each of those lists the processor in a literal
601+
``context_processors``; no other code names the module's ``TEMPLATES``, or a
602+
``TEMPLATES`` it does not bind (a star import), which could change it. A
603+
``TEMPLATES`` bound in a function or a class is another name, which configures
604+
nothing and changes nothing. A mere mention of the processor proves nothing."""
602605

603606
assignments = mentions = 0
604-
for module in modules:
605-
stack: list[Node] = list(module.body)
606-
while stack:
607-
node = stack.pop()
608-
stack.extend(children(node))
607+
for module, scopes in modules:
608+
for node, scope in _scoped(module, scopes):
609609
if isinstance(node, nodes.Name) and node.identifier == _ENGINES_SETTING:
610-
mentions += 1
611-
elif isinstance(node, nodes.Assign) and _names_engines(node.target):
610+
if scopes.resolve(scope, node.identifier).kind in (ResolutionKind.GLOBAL, ResolutionKind.UNBOUND):
611+
mentions += 1
612+
elif isinstance(node, nodes.Assign) and _names_engines(node.target) and scope == scopes.module_scope.id:
612613
if not _runs_request_processor(node.value):
613614
return False
614615
assignments += 1
615616
return assignments > 0 and mentions == assignments
616617

617618

619+
def _scoped(module: nodes.Module, scopes: ScopeTable) -> Iterator[tuple[Node, ScopeId]]:
620+
"""Every node of ``module`` with the scope it stands in."""
621+
622+
stack: list[tuple[Node, ScopeId]] = [(node, scopes.module_scope.id) for node in module.body]
623+
while stack:
624+
node, scope = stack.pop()
625+
yield node, scope
626+
if isinstance(node, nodes.Function | nodes.Lambda | nodes.Class | nodes.Comprehension):
627+
scope = scopes.scope_for(node).id
628+
stack.extend((child, scope) for child in children(node))
629+
630+
618631
def _names_engines(target: nodes.Expression) -> bool:
619632
return isinstance(target, nodes.Name) and target.identifier == _ENGINES_SETTING
620633

‎tests/test_settings_scope.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
"""Only module-level settings configure Django.
2+
3+
The request context processor is taken as active only from the settings a project
4+
assigns at module level: a ``TEMPLATES`` assigned inside a function, called or not,
5+
binds a local name and configures nothing, and so does a class attribute. A function
6+
that reads or rebinds the module's ``TEMPLATES`` (through ``global``, or by mutating
7+
it) may change the effective settings, so it leaves the activation uncertain, as any
8+
other mention does. Uncertain activation leaves the filter reachable, neither
9+
exploitable through the processor nor declared absent.
10+
"""
11+
12+
from __future__ import annotations
13+
14+
from pathlib import Path
15+
16+
import pytest
17+
18+
from coretrace_python import engine
19+
from coretrace_python.dependency import Advisory, AdvisoryEntryPoint, dump_advisories
20+
from coretrace_python.findings import Severity
21+
from coretrace_python.semantic.symbols import SymbolId
22+
23+
STRIPTAGS = "python.django.template.defaultfilters.striptags"
24+
ADVISORY = Advisory(
25+
"CVE-2099-5601",
26+
"django",
27+
"<4.2.17",
28+
"striptags is quadratic in its input",
29+
Severity.MEDIUM,
30+
entry_points=(AdvisoryEntryPoint(SymbolId(STRIPTAGS), "a template filter"),),
31+
)
32+
LOCK = """version = 1
33+
34+
[[package]]
35+
name = "app"
36+
version = "0.1.0"
37+
source = { virtual = "." }
38+
dependencies = [{ name = "django" }]
39+
40+
[[package]]
41+
name = "django"
42+
version = "4.2.16"
43+
source = { registry = "https://pypi.org/simple" }
44+
"""
45+
ENGINE = (
46+
"{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, "
47+
"'OPTIONS': {'context_processors': ['django.template.context_processors.request']}}"
48+
)
49+
VIEW = (
50+
"from django.http import HttpRequest\n"
51+
"from django.shortcuts import render\n\n"
52+
"def search(request: HttpRequest):\n"
53+
" return render(request, 'app/search.html')\n"
54+
)
55+
PAGE = "app/templates/app/search.html"
56+
57+
58+
def levels(root: Path, settings: str) -> list[str]:
59+
files = {
60+
"uv.lock": LOCK,
61+
"app/__init__.py": "",
62+
"app/settings.py": settings,
63+
"app/views.py": VIEW,
64+
PAGE: "{{ request.GET.q|striptags }}\n",
65+
}
66+
for relative, text in files.items():
67+
(root / relative).parent.mkdir(parents=True, exist_ok=True)
68+
(root / relative).write_text(text, encoding="utf-8")
69+
(root / "advisories.json").write_text(dump_advisories((ADVISORY,)), encoding="utf-8")
70+
findings = engine.analyze_project(root, [engine.BUNDLED_PLUGINS]).findings
71+
reached = ("reachable-vulnerability", "exploitable-vulnerability")
72+
return sorted(f.metadata["level"] for f in findings if f.rule_id in reached and f.metadata["advisory"] == ADVISORY.id)
73+
74+
75+
def test_module_level_settings_activate_the_processor(tmp_path: Path) -> None:
76+
assert levels(tmp_path, f"TEMPLATES = [{ENGINE}]\n") == ["exploitable", "reachable"]
77+
78+
79+
@pytest.mark.parametrize(
80+
"settings",
81+
[
82+
f"def never_called():\n TEMPLATES = [{ENGINE}]\n",
83+
f"def configure():\n TEMPLATES = [{ENGINE}]\n return TEMPLATES\n\nconfigure()\n",
84+
f"class Settings:\n TEMPLATES = [{ENGINE}]\n",
85+
f"def build():\n templates = [{ENGINE}]\n return templates\n",
86+
],
87+
ids=["uncalled-function", "called-function", "class-attribute", "other-local-name"],
88+
)
89+
def test_settings_bound_below_the_module_do_not_configure_django(tmp_path: Path, settings: str) -> None:
90+
assert levels(tmp_path, settings) == ["reachable"]
91+
92+
93+
@pytest.mark.parametrize(
94+
"settings",
95+
[
96+
f"TEMPLATES = [{ENGINE}]\n\ndef tweak():\n TEMPLATES[0]['OPTIONS']['context_processors'].pop(0)\n",
97+
f"TEMPLATES = [{ENGINE}]\n\ndef reset():\n global TEMPLATES\n TEMPLATES = []\n",
98+
f"TEMPLATES = [{ENGINE}]\n\ndef read():\n return TEMPLATES\n",
99+
],
100+
ids=["mutated-in-a-function", "rebound-through-global", "read-in-a-function"],
101+
)
102+
def test_a_function_touching_the_module_settings_leaves_activation_uncertain(tmp_path: Path, settings: str) -> None:
103+
assert levels(tmp_path, settings) == ["reachable"]
104+
105+
106+
def test_a_local_name_beside_module_settings_changes_nothing(tmp_path: Path) -> None:
107+
settings = f"TEMPLATES = [{ENGINE}]\n\ndef helper():\n TEMPLATES = []\n return TEMPLATES\n"
108+
109+
assert levels(tmp_path, settings) == ["exploitable", "reachable"]

0 commit comments

Comments
 (0)