Skip to content

Commit 07adc12

Browse files
authored
Merge pull request #287 from CoreTrace/fix/285-block-placement
fix(templates): put each render together over its extends chain as Django places blocks
2 parents 8846ebb + cc98e80 commit 07adc12

5 files changed

Lines changed: 479 additions & 114 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@
1111
a parent including the child that extends it. A filter reached this way may be
1212
reported as `exploitable-vulnerability` where it was not. Where no cycle is reached,
1313
the filters and their order do not change.
14+
- A template's render is put together over its extends chain as Django places its
15+
blocks (#285). A filter in a block no template of the chain places, or in a block
16+
whose only placeholder a child replaces, is no longer reached, and an advisory naming
17+
it is no longer `exploitable-vulnerability` through it. A block a child redefines with
18+
`{{ block.super }}` inside a block it replaces now renders the parent's definition and
19+
what it includes. Where the chain cannot be followed to a root, every block counts as
20+
placed, as before.
1421

1522
### Performance
1623

‎docs/usage.md‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -605,9 +605,14 @@ certain of it:
605605
of includes is followed as far as Django may render it: a template reached again on
606606
the way applies its filters to what each include binds at every level, as a template
607607
including itself with other bindings, or a recursive tree, does (#284).
608-
- The filter renders: a template extending another renders only its blocks, which
609-
replace the blocks of that name in what it extends, unless the block renders
610-
`{{ block.super }}`, which keeps the parent's content and the filters it applies.
608+
- The filter renders: a template extending another renders only its blocks, and only
609+
where its chain of parents places them (#285). The root's blocks are placed; a placed
610+
block renders its most derived definition, and through `{{ block.super }}` the next
611+
ones up, which keep the parent's content and the filters it applies; the blocks a
612+
rendered definition holds are placed in turn. A block no template of the chain
613+
places never renders, nor does a block whose only placeholder a child replaces. When
614+
the chain cannot be followed to a root (a parent named by an expression, not found or
615+
in several files, or an extends cycle), every block of the chain counts as placed.
611616
- One file has the template's name; of two files of the same name, which one renders
612617
depends on the loaders.
613618

‎src/coretrace_python/taint/templates.py‎

Lines changed: 121 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@
5353
import re
5454
from bisect import bisect_left
5555
from collections import deque
56-
from collections.abc import Container, Iterable, Iterator, Mapping, Sequence
56+
from collections.abc import Callable, Container, Iterable, Iterator, Mapping, Sequence
5757
from dataclasses import dataclass, field
5858
from pathlib import Path
5959
from types import MappingProxyType
@@ -989,29 +989,16 @@ def overrides(self, name: str) -> bool | None:
989989
@dataclass(frozen=True)
990990
class _Template:
991991
"""What one template file applies and references, the ``blocks`` it defines, and
992-
among them the ``extended`` ones, which render ``{{ block.super }}``, and the loads
993-
under which it applies a filter the engine could not resolve."""
992+
among them the ``extended`` ones, which render ``{{ block.super }}``, the loads under
993+
which it applies a filter the engine could not resolve, and the block each block
994+
stands in, None for one standing in none (#285)."""
994995

995996
applications: tuple[_Application, ...]
996997
references: tuple[_Reference, ...]
997998
blocks: frozenset[str]
998999
extended: frozenset[str] = frozenset()
9991000
unresolved: tuple[_Load, ...] = ()
1000-
1001-
def rendered(self, blocks: tuple[str, ...], overridden: frozenset[str]) -> bool:
1002-
"""Whether what stands in ``blocks`` renders when a template extending this one
1003-
defines the ``overridden`` blocks: a template extending another renders only
1004-
its blocks, where they replace the blocks of that name in what it extends."""
1005-
1006-
extends = any(reference.extends for reference in self.references)
1007-
return not overridden.intersection(blocks) and (bool(blocks) or not extends)
1008-
1009-
@property
1010-
def replaced(self) -> frozenset[str]:
1011-
"""The blocks this template replaces in what it extends: those it defines
1012-
without rendering ``{{ block.super }}``, which keeps the parent's content."""
1013-
1014-
return self.blocks - self.extended
1001+
enclosing: Mapping[str, str | None] = field(default_factory=dict)
10151002

10161003

10171004
def project_templates(root: Path) -> ProjectTemplates:
@@ -1056,7 +1043,7 @@ def project_templates(root: Path) -> ProjectTemplates:
10561043
name: tuple(
10571044
dict.fromkeys(
10581045
TemplateFilter(symbol, span, where, tuple(sorted(value)), tuple(sorted(argument)))
1059-
for symbol, span, where, value, argument in settled.get((name, frozenset()), ())
1046+
for symbol, span, where, value, argument in settled.get(name, ())
10601047
)
10611048
)
10621049
for name in files
@@ -1067,68 +1054,115 @@ def project_templates(root: Path) -> ProjectTemplates:
10671054
# A filter a template's render reaches: the function, where it is applied, the template
10681055
# applying it, and the names free in the rendered template reaching its value and argument.
10691056
_Reached = tuple[SymbolId, SourceSpan, str, frozenset[str], frozenset[str]]
1070-
# A template, and the blocks the templates extending it override: what rendering the
1071-
# template applies depends on both.
1072-
_Pair = tuple[str, frozenset[str]]
10731057

10741058

10751059
class _Render(NamedTuple):
1076-
"""What rendering a pair applies itself, and the pairs its references render, each
1060+
"""What rendering a template on its own applies, and the templates it includes, each
10771061
with its reference."""
10781062

10791063
applied: tuple[_Reached, ...]
1080-
references: tuple[tuple[_Pair, _Reference], ...]
1064+
references: tuple[tuple[str, _Reference], ...]
1065+
1066+
1067+
def _page(name: str, readable: Callable[[str | None], _Template | None]) -> _Render:
1068+
"""What rendering ``name`` on its own applies and includes, its extends chain put
1069+
together as Django puts it (#285).
1070+
1071+
The chain runs from ``name`` up to its root, the template extending none. The root's
1072+
blocks standing in no other block are placed; a placed block renders its most derived
1073+
definition, then, while a definition renders ``{{ block.super }}``, the next one up;
1074+
the blocks a rendered definition holds are placed in turn. A filter or an include
1075+
renders when the definition of the innermost block it stands in renders; outside
1076+
every block, only in the root, Django ignoring a child's text outside its blocks.
1077+
1078+
When the chain reaches no known root, as through a parent named by an expression, a
1079+
name several files have, a file the engine cannot read, or an extends cycle Django
1080+
refuses, every block of the chain is placed: no filter is dropped on a placement the
1081+
engine cannot establish.
1082+
1083+
What the chain applies is listed from ``name`` up to the root, and what it includes
1084+
from the root down to ``name``: the order of a walk of each path through extends."""
1085+
1086+
chain: list[tuple[str, _Template]] = []
1087+
seen: set[str] = set()
1088+
known = True
1089+
current: str | None = name
1090+
while True:
1091+
template = readable(current)
1092+
if current is None or template is None or current in seen:
1093+
known = False
1094+
break
1095+
chain.append((current, template))
1096+
seen.add(current)
1097+
parent = next((reference for reference in template.references if reference.extends), None)
1098+
if parent is None:
1099+
break
1100+
current = parent.name
1101+
defining: dict[str, list[int]] = {}
1102+
held: dict[tuple[int, str | None], list[str]] = {}
1103+
for level, (_, template) in enumerate(chain):
1104+
for block in template.blocks:
1105+
defining.setdefault(block, []).append(level)
1106+
held.setdefault((level, template.enclosing.get(block)), []).append(block)
1107+
pending = list(held.get((len(chain) - 1, None), ())) if known else list(defining)
1108+
placed: set[str] = set()
1109+
shown: set[tuple[int, str]] = set()
1110+
while pending:
1111+
block = pending.pop()
1112+
if block in placed:
1113+
continue
1114+
placed.add(block)
1115+
for level in defining.get(block, []):
1116+
shown.add((level, block))
1117+
pending.extend(held.get((level, block), ()))
1118+
if block not in chain[level][1].extended:
1119+
break
1120+
1121+
def renders(level: int, blocks: tuple[str, ...]) -> bool:
1122+
return (level, blocks[-1]) in shown if blocks else known and level == len(chain) - 1
1123+
1124+
applied = tuple(
1125+
(application.symbol, application.span, template_name, application.value, application.argument)
1126+
for level, (template_name, template) in enumerate(chain)
1127+
for application in template.applications
1128+
if renders(level, application.blocks)
1129+
)
1130+
references = tuple(
1131+
(reference.name, reference)
1132+
for level in reversed(range(len(chain)))
1133+
for reference in chain[level][1].references
1134+
if not reference.extends
1135+
and reference.name is not None
1136+
and readable(reference.name) is not None
1137+
and renders(level, reference.blocks)
1138+
)
1139+
return _Render(applied, references)
10811140

10821141

1083-
def _renders(files: Mapping[str, list[Path]], read: Mapping[Path, _Template]) -> dict[_Pair, _Render]:
1084-
"""Every pair the render of a template reaches, each template rendered on its own. A
1085-
name several files have, or a file the engine could not read, renders nothing."""
1142+
def _renders(files: Mapping[str, list[Path]], read: Mapping[Path, _Template]) -> dict[str, _Render]:
1143+
"""What rendering each template on its own applies and includes. A name several files
1144+
have, or a file the engine could not read, renders nothing."""
10861145

1087-
def pair(name: str, overridden: frozenset[str]) -> _Pair | None:
1088-
paths = files.get(name, [])
1089-
return (name, overridden) if len(paths) == 1 and paths[0] in read else None
1146+
def readable(name: str | None) -> _Template | None:
1147+
paths = files.get(name or "", [])
1148+
return read[paths[0]] if len(paths) == 1 and paths[0] in read else None
10901149

1091-
renders: dict[_Pair, _Render] = {}
1092-
pending = [root for name in files if (root := pair(name, frozenset())) is not None]
1093-
while pending:
1094-
current = pending.pop()
1095-
if current in renders:
1096-
continue
1097-
name, overridden = current
1098-
template = read[files[name][0]]
1099-
applied = tuple(
1100-
(a.symbol, a.span, name, a.value, a.argument) for a in template.applications if template.rendered(a.blocks, overridden)
1101-
)
1102-
references: list[tuple[_Pair, _Reference]] = []
1103-
for reference in template.references:
1104-
if reference.name is None:
1105-
continue
1106-
if reference.extends:
1107-
below = pair(reference.name, overridden | template.replaced)
1108-
elif template.rendered(reference.blocks, overridden):
1109-
below = pair(reference.name, frozenset())
1110-
else:
1111-
continue
1112-
if below is not None:
1113-
references.append((below, reference))
1114-
pending.append(below)
1115-
renders[current] = _Render(applied, tuple(references))
1116-
return renders
1150+
return {name: _page(name, readable) for name in files if readable(name) is not None}
11171151

11181152

1119-
def _components(renders: Mapping[_Pair, _Render]) -> list[list[_Pair]]:
1153+
def _components(renders: Mapping[str, _Render]) -> list[list[str]]:
11201154
"""The strongly connected components of the renders, each after every component its
11211155
references reach: Tarjan's algorithm, without recursion."""
11221156

1123-
index: dict[_Pair, int] = {}
1124-
low: dict[_Pair, int] = {}
1125-
stack: list[_Pair] = []
1126-
on_stack: set[_Pair] = set()
1127-
components: list[list[_Pair]] = []
1157+
index: dict[str, int] = {}
1158+
low: dict[str, int] = {}
1159+
stack: list[str] = []
1160+
on_stack: set[str] = set()
1161+
components: list[list[str]] = []
11281162
for root in renders:
11291163
if root in index:
11301164
continue
1131-
# Each entry is a pair and the position of the next reference to follow.
1165+
# Each entry is a template and the position of the next reference to follow.
11321166
work = [(root, 0)]
11331167
while work:
11341168
current, position = work.pop()
@@ -1147,7 +1181,7 @@ def _components(renders: Mapping[_Pair, _Render]) -> list[list[_Pair]]:
11471181
low[current] = min(low[current], index[below])
11481182
else:
11491183
if low[current] == index[current]:
1150-
component: list[_Pair] = []
1184+
component: list[str] = []
11511185
while not component or component[-1] != current:
11521186
component.append(stack.pop())
11531187
on_stack.discard(component[-1])
@@ -1166,7 +1200,7 @@ def _mapped(found: Iterable[_Reached], reference: _Reference) -> Iterator[_Reach
11661200

11671201

11681202
def _canonical(found: _Reached) -> tuple[str, int, int, str, list[str], list[str]]:
1169-
"""The order of the filters a pair in a cycle reaches beyond what it applies."""
1203+
"""The order of the filters a template in a cycle reaches beyond what it applies."""
11701204

11711205
symbol, span, where, value, argument = found
11721206
return where, span.start_line, span.start_column, str(symbol), sorted(value), sorted(argument)
@@ -1191,11 +1225,12 @@ def _facts(names: Mapping[_Site, tuple[frozenset[str], frozenset[str]]], sites:
11911225
return [(symbol, span, where, *names[symbol, span, where]) for symbol, span, where in sites]
11921226

11931227

1194-
def _settled(files: Mapping[str, list[Path]], read: Mapping[Path, _Template]) -> dict[_Pair, list[_Reached]]:
1195-
"""The filters the render of each pair reaches, in order (#284).
1228+
def _settled(files: Mapping[str, list[Path]], read: Mapping[Path, _Template]) -> dict[str, list[_Reached]]:
1229+
"""The filters the render of each template reaches, in order (#284).
11961230
1197-
What a pair reaches is the least set holding what it applies, and what each of its
1198-
references reaches mapped through the reference's bindings. The sets are computed
1231+
What a template reaches is the least set holding what it applies, its extends chain
1232+
put together (#285), and what each template it includes reaches, mapped through the
1233+
reference's bindings. The sets are computed
11991234
component by component, each after those its references reach, which are then
12001235
final. No cycle is cut: a template including itself with other bindings reaches what
12011236
Django renders at its next levels.
@@ -1205,20 +1240,20 @@ def _settled(files: Mapping[str, list[Path]], read: Mapping[Path, _Template]) ->
12051240
analysis reads those names position by position, joining what each brings, so the
12061241
join loses nothing, and it keeps the facts few: bindings permuted around a cycle
12071242
would otherwise make one fact of every combination of names. In a component, every
1208-
pair starts with no names and is recomputed from its references' facts; names only
1209-
join, and the applications and names of a project are finitely many, so the names of
1210-
an application grow at most once for each name. A pair is recomputed when a fact it
1211-
reads grew, until none grows.
1212-
1213-
Once the facts are settled, a pair outside any cycle lists what it applies, then what
1214-
each reference reaches, in order, first occurrences only, as a walk of each path
1215-
would. A pair in a cycle has no such first occurrence, the cycle having no start: it
1216-
lists what it applies, then the rest by template, position, function and names. The
1217-
order thus depends only on the facts and the templates, never on the order of the
1218-
computation."""
1243+
template starts with no names and is recomputed from its references' facts; names
1244+
only join, and the applications and names of a project are finitely many, so the
1245+
names of an application grow at most once for each name. A template is recomputed
1246+
when a fact it reads grew, until none grows.
1247+
1248+
Once the facts are settled, a template outside any cycle lists what it applies,
1249+
then what each reference reaches, in order, first occurrences only, as a walk of
1250+
each path would. A template in a cycle has no such first occurrence, the cycle
1251+
having no start: it lists what it applies, then the rest by template, position,
1252+
function and names. The order thus depends only on the facts and the templates,
1253+
never on the order of the computation."""
12191254

12201255
renders = _renders(files, read)
1221-
reached: dict[_Pair, list[_Reached]] = {}
1256+
reached: dict[str, list[_Reached]] = {}
12221257
for component in _components(renders):
12231258
single = component[0]
12241259
if len(component) == 1 and all(below != single for below, _ in renders[single].references):
@@ -1229,12 +1264,12 @@ def _settled(files: Mapping[str, list[Path]], read: Mapping[Path, _Template]) ->
12291264
reached[single] = list(found)
12301265
continue
12311266
members = set(component)
1232-
readers: dict[_Pair, list[_Pair]] = {member: [] for member in component}
1267+
readers: dict[str, list[str]] = {member: [] for member in component}
12331268
for member in component:
12341269
for below, _ in renders[member].references:
12351270
if below in members:
12361271
readers[below].append(member)
1237-
names: dict[_Pair, dict[_Site, tuple[frozenset[str], frozenset[str]]]] = {member: {} for member in component}
1272+
names: dict[str, dict[_Site, tuple[frozenset[str], frozenset[str]]]] = {member: {} for member in component}
12381273
sizes = dict.fromkeys(component, 0)
12391274
pending = deque(component)
12401275
queued = set(component)
@@ -1275,6 +1310,7 @@ def _read_scopes(text: str, source: SourceId, libraries: Mapping[str, _Library])
12751310
opened: list[str] = []
12761311
defined: set[str] = set()
12771312
extended: set[str] = set()
1313+
enclosing: dict[str, str | None] = {}
12781314
scopes: list[dict[str, frozenset[str]]] = [{}]
12791315
blocks: list[tuple[list[tuple[str, int, frozenset[str]]], set[str]]] = []
12801316
loaded: list[_Load] = []
@@ -1360,6 +1396,7 @@ def apply(head: frozenset[str], chain: list[tuple[str, int, frozenset[str]]]) ->
13601396
else:
13611397
values.setdefault(word, reached)
13621398
if name == "block" and len(words) > 1:
1399+
enclosing.setdefault(words[1], opened[-1] if opened else None)
13631400
opened.append(words[1])
13641401
defined.add(words[1])
13651402
elif name == "endblock" and opened:
@@ -1388,7 +1425,7 @@ def apply(head: frozenset[str], chain: list[tuple[str, int, frozenset[str]]]) ->
13881425
target = words[words.index("as", 1) + 1]
13891426
scopes[-1][target] = values.get(words[1], frozenset()) if name == "regroup" else frozenset()
13901427
return _Template(
1391-
tuple(applications), tuple(references), frozenset(defined), frozenset(extended), tuple(unresolved)
1428+
tuple(applications), tuple(references), frozenset(defined), frozenset(extended), tuple(unresolved), enclosing
13921429
)
13931430

13941431

0 commit comments

Comments
 (0)