Skip to content

Commit e15208b

Browse files
committed
Merge branch 'feat/entry-point-aliases' into fix/template-filter-overrides
# Conflicts: # CHANGELOG.md # src/coretrace_python/taint/templates.py
2 parents 40f6f0a + 215aefb commit e15208b

9 files changed

Lines changed: 537 additions & 31 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,14 @@
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).
8+
- 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).
79
- A project tag library registering a filter of a built-in's name replaces the built-in in every Django template loading it before applying the filter, as Django's parser does: `{% load custom %}{{ bio|striptags }}` calls the project's `striptags` when `app/templatetags/custom.py` registers one, so it is no longer a reachable or exploitable call to `django.template.defaultfilters.striptags`; the project's function is ordinary code, analysed as any other. A load affects only the filters after it, a later load overrides an earlier one, `{% load striptags from custom %}` replaces only what it names, and Django's own libraries change nothing. The analyzer reads the registrations on `register`, a `django.template.Library` however it is imported, in decorator and call form, at module level or under `if`, `try` or a function. Where it cannot tell what a library registers — no such library file, one it cannot read or parse, a name not written as a constant, `register` passed elsewhere or filled through `filters=` or `register.filters`, or two apps giving the name and registering different filters — a filter of that name applied under the load is neither the built-in nor certainly replaced: no call is claimed, and the load counts among the templates the analyzer could not read (`app/templates/app/profile.html:1 loads 'custom', not read`), so an advisory naming the filter stays `under_investigation` in the VEX document. The settings' `OPTIONS["libraries"]` and `OPTIONS["builtins"]` are not read (#183).
810

11+
### Plugins
12+
13+
- An `EntryPoint` naming a project function or class applies through a module-level alias of it: `main = actual` makes `python.app.handlers.main` name `actual`, so a deployment declaring `handlers.main` reaches the function doing the work. An alias is an assignment of one name to another at module level, followed transitively and in source order, in a conditional or a `try` as well; a name bound inside a function or class, or to a call, an import or anything but a name, is no alias, and the engine still infers nothing from a name. A model naming a method wins over one naming its class, whichever name it uses.
14+
915
## 0.18.0 (2026-09-28)
1016

1117
### Precision

‎docs/usage.md‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,8 @@ certain of it:
408408
arguments of the filters before it, or the output of a `{% filter %}` block. A name a
409409
tag binds shadows the context, and `{% include ... only %}` passes none of it.
410410
- The filter renders: a template extending another renders only its blocks, which
411-
replace the blocks of that name in what it extends.
411+
replace the blocks of that name in what it extends, unless the block renders
412+
`{{ block.super }}`, which keeps the parent's content and the filters it applies.
412413
- One file has the template's name; of two files of the same name, which one renders
413414
depends on the loaders.
414415

@@ -421,9 +422,12 @@ With the `django.template.context_processors.request` context processor, a templ
421422
rendered with the request reads it as `request`: `{{ request.GET.q|striptags }}` is
422423
exploitable at the render call too. The analyzer counts it only where all of these hold:
423424

424-
- The project's settings assign `TEMPLATES` a literal list, every `DjangoTemplates`
425-
engine of it lists the processor in a literal `context_processors`, and no other code
426-
of the project names `TEMPLATES`. A mere mention of the processor proves nothing.
425+
- The project's settings assign `TEMPLATES` a literal list at module level, every
426+
`DjangoTemplates` engine of it lists the processor in a literal `context_processors`,
427+
and no other code of the project names the module's `TEMPLATES`, or a `TEMPLATES` it
428+
does not bind, as a star import gives. A `TEMPLATES` bound in a function or a class
429+
is another name: it configures nothing and changes nothing.
430+
A mere mention of the processor proves nothing.
427431
- The render call passes the request: `render` and `TemplateResponse` always do,
428432
`render_to_string` when given `request`, `SimpleTemplateResponse` never.
429433
- 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/engine.py‎

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -836,20 +836,26 @@ def function_entry_point(
836836
) -> EntryPoint | None:
837837
"""The entry point ``function`` is: one of its decorators or, for a method, one of its
838838
class's bases matching an entry-point model, a registration elsewhere (``routes``), or
839-
a model naming the function, or its class, by its own project symbol."""
839+
a model naming the function, or its class, by its own project symbol or by a
840+
module-level alias of it (``main = actual`` names ``actual`` as ``main``). A model
841+
naming the method wins over one naming its class, whichever name it uses."""
840842

841843
owner = _owner(module, function)
842844
enclosing_function = _enclosing(module, function)
843845
if enclosing_function is not None:
844846
# ``app = Flask(__name__)`` inside ``create_app``: routes defined there resolve.
845847
instances = {**(instances or {}), **local_instances(enclosing_function, scopes, symbols)}
846848
entry = entry_point_of(function, models, scopes, symbols, owner, instances, project)
847-
if entry is None:
848-
qualified = function.name if owner is None else f"{owner.name}.{function.name}"
849-
entry = _declared(project_symbol(module.name, qualified), models, routes)
850-
if entry is None and owner is not None:
851-
entry = _declared(project_symbol(module.name, owner.name), models, routes)
852-
return entry
849+
if entry is not None:
850+
return entry
851+
defined = function if owner is None else owner
852+
names = (defined.name, *_aliases(module, defined.name))
853+
qualified = names if owner is None else (*(f"{name}.{function.name}" for name in names), *names)
854+
for name in qualified:
855+
entry = _declared(project_symbol(module.name, name), models, routes)
856+
if entry is not None:
857+
return entry
858+
return None
853859

854860

855861
def _declared(symbol: SymbolId, models: ModelTable, routes: Routes | None) -> EntryPoint | None:
@@ -860,6 +866,43 @@ def _declared(symbol: SymbolId, models: ModelTable, routes: Routes | None) -> En
860866
return registered if registered is not None else models.entry_point(symbol)
861867

862868

869+
def _aliases(module: nodes.Module, name: str) -> Iterable[str]:
870+
"""The module-level names bound to ``name`` by assigning one name to another,
871+
transitively and in source order: ``handler = actual`` then ``main = handler`` make
872+
both aliases of ``actual``. A name bound inside a function or class, or to anything
873+
but a name (a call, an import), is no alias."""
874+
875+
aliases: dict[str, list[str]] = {}
876+
for statement in _module_level(module.body):
877+
if isinstance(statement, nodes.Assign) and isinstance(statement.target, nodes.Name) and isinstance(statement.value, nodes.Name):
878+
aliases.setdefault(statement.value.identifier, []).append(statement.target.identifier)
879+
found = {name}
880+
pending = [name]
881+
while pending:
882+
for alias in aliases.get(pending.pop(0), ()):
883+
if alias not in found:
884+
found.add(alias)
885+
pending.append(alias)
886+
yield alias
887+
888+
889+
def _module_level(body: Iterable[nodes.Statement]) -> Iterable[nodes.Statement]:
890+
"""The statements executed at module level: the body and what its compound
891+
statements hold, not what a function or class defines."""
892+
893+
for statement in body:
894+
if isinstance(statement, nodes.Function | nodes.Class):
895+
continue
896+
yield statement
897+
for attribute in ("body", "orelse", "finalbody"):
898+
nested = getattr(statement, attribute, None)
899+
if isinstance(nested, tuple):
900+
yield from _module_level(nested)
901+
if isinstance(statement, nodes.Try):
902+
for handler in statement.handlers:
903+
yield from _module_level(handler.body)
904+
905+
863906
def _owner(module: nodes.Module, function: nodes.Function) -> nodes.Class | None:
864907
"""The top-level class ``function`` is a method of, if any."""
865908

‎src/coretrace_python/taint/templates.py‎

Lines changed: 45 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
discover_files,
5858
)
5959
from coretrace_python.semantic.imports import ImportResolutionError, analyze_imports
60-
from coretrace_python.semantic.scopes import BindingKind, ScopeError, analyze_scopes
60+
from coretrace_python.semantic.scopes import BindingKind, ResolutionKind, ScopeError, ScopeId, ScopeTable, analyze_scopes
6161
from coretrace_python.semantic.symbols import SymbolId, analyze_symbols
6262
from coretrace_python.source import SourceId, SourceManager, SourceSpan
6363
from coretrace_python.taint.models import ModelTable
@@ -150,6 +150,8 @@
150150
# the request context processor adds gives (``request.GET``).
151151
_VARIABLE = re.compile(r"([A-Za-z_]\w*)(?:\.(\w+))?")
152152
_LITERALS = frozenset({"True", "False", "None"})
153+
# The variable a block renders to keep the parent's content, as ``_chain`` reads it.
154+
_BLOCK_SUPER = "block.super"
153155

154156
REQUEST_PROCESSOR = "django.template.context_processors.request"
155157
_DJANGO_ENGINE = "django.template.backends.django.DjangoTemplates"
@@ -413,11 +415,13 @@ def overrides(self, name: str) -> bool | None:
413415
@dataclass(frozen=True)
414416
class _Template:
415417
"""What one template file applies and references, the ``blocks`` it defines, and
416-
the loads under which it applies a filter the engine could not resolve."""
418+
among them the ``extended`` ones, which render ``{{ block.super }}``, and the loads
419+
under which it applies a filter the engine could not resolve."""
417420

418421
applications: tuple[_Application, ...]
419422
references: tuple[_Reference, ...]
420423
blocks: frozenset[str]
424+
extended: frozenset[str] = frozenset()
421425
unresolved: tuple[_Load, ...] = ()
422426

423427
def rendered(self, blocks: tuple[str, ...], overridden: frozenset[str]) -> bool:
@@ -428,6 +432,13 @@ def rendered(self, blocks: tuple[str, ...], overridden: frozenset[str]) -> bool:
428432
extends = any(reference.extends for reference in self.references)
429433
return not overridden.intersection(blocks) and (bool(blocks) or not extends)
430434

435+
@property
436+
def replaced(self) -> frozenset[str]:
437+
"""The blocks this template replaces in what it extends: those it defines
438+
without rendering ``{{ block.super }}``, which keeps the parent's content."""
439+
440+
return self.blocks - self.extended
441+
431442

432443
def project_templates(root: Path) -> ProjectTemplates:
433444
"""What the templates under ``root`` call, and the templates they include or extend
@@ -500,7 +511,7 @@ def _reaching(
500511
if reference.name is None:
501512
continue
502513
if reference.extends:
503-
found = _reaching(reference.name, files, read, visiting | {name}, overridden | template.blocks)
514+
found = _reaching(reference.name, files, read, visiting | {name}, overridden | template.replaced)
504515
elif template.rendered(reference.blocks, overridden):
505516
found = _reaching(reference.name, files, read, visiting | {name})
506517
else:
@@ -521,6 +532,7 @@ def _read_scopes(text: str, source: SourceId, libraries: Mapping[str, _Library])
521532
references: list[_Reference] = []
522533
opened: list[str] = []
523534
defined: set[str] = set()
535+
extended: set[str] = set()
524536
scopes: list[dict[str, frozenset[str]]] = [{}]
525537
blocks: list[tuple[list[tuple[str, int, frozenset[str]]], set[str]]] = []
526538
loaded: list[_Load] = []
@@ -573,6 +585,8 @@ def apply(head: frozenset[str], chain: list[tuple[str, int, frozenset[str]]]) ->
573585
for offset, expression, tag in _expressions(text):
574586
if not tag:
575587
head, chain = _chain(expression, offset)
588+
if opened and _BLOCK_SUPER in head:
589+
extended.add(opened[-1])
576590
printed = apply(free(head), chain)
577591
for _, collected in blocks:
578592
collected |= printed
@@ -631,7 +645,9 @@ def apply(head: frozenset[str], chain: list[tuple[str, int, frozenset[str]]]) ->
631645
elif "as" in words[1:-1]:
632646
target = words[words.index("as", 1) + 1]
633647
scopes[-1][target] = values.get(words[1], frozenset()) if name == "regroup" else frozenset()
634-
return _Template(tuple(applications), tuple(references), frozenset(defined), tuple(unresolved))
648+
return _Template(
649+
tuple(applications), tuple(references), frozenset(defined), frozenset(extended), tuple(unresolved)
650+
)
635651

636652

637653
def _libraries(paths: Iterable[Path]) -> dict[str, _Library]:
@@ -793,29 +809,41 @@ def _through(bound: frozenset[str], name: str) -> frozenset[str]:
793809
return frozenset(".".join(f"{b}.{attribute}".split(".")[:2]) if attribute else b for b in bound)
794810

795811

796-
def request_processor(modules: Iterable[nodes.Module]) -> bool:
812+
def request_processor(modules: Iterable[tuple[nodes.Module, ScopeTable]]) -> bool:
797813
"""Whether every Django template engine the project's settings configure runs the
798-
``request`` context processor, for certain: each assignment to ``TEMPLATES`` is a
799-
literal list of literal engines, at least one of them ``DjangoTemplates``, and each
800-
of those lists the processor in a literal ``context_processors``; no other code
801-
names ``TEMPLATES``, which could change it. A mere mention of the processor proves
802-
nothing."""
814+
``request`` context processor, for certain: each module-level assignment to
815+
``TEMPLATES`` is a literal list of literal engines, at least one of them
816+
``DjangoTemplates``, and each of those lists the processor in a literal
817+
``context_processors``; no other code names the module's ``TEMPLATES``, or a
818+
``TEMPLATES`` it does not bind (a star import), which could change it. A
819+
``TEMPLATES`` bound in a function or a class is another name, which configures
820+
nothing and changes nothing. A mere mention of the processor proves nothing."""
803821

804822
assignments = mentions = 0
805-
for module in modules:
806-
stack: list[Node] = list(module.body)
807-
while stack:
808-
node = stack.pop()
809-
stack.extend(children(node))
823+
for module, scopes in modules:
824+
for node, scope in _scoped(module, scopes):
810825
if isinstance(node, nodes.Name) and node.identifier == _ENGINES_SETTING:
811-
mentions += 1
812-
elif isinstance(node, nodes.Assign) and _names_engines(node.target):
826+
if scopes.resolve(scope, node.identifier).kind in (ResolutionKind.GLOBAL, ResolutionKind.UNBOUND):
827+
mentions += 1
828+
elif isinstance(node, nodes.Assign) and _names_engines(node.target) and scope == scopes.module_scope.id:
813829
if not _runs_request_processor(node.value):
814830
return False
815831
assignments += 1
816832
return assignments > 0 and mentions == assignments
817833

818834

835+
def _scoped(module: nodes.Module, scopes: ScopeTable) -> Iterator[tuple[Node, ScopeId]]:
836+
"""Every node of ``module`` with the scope it stands in."""
837+
838+
stack: list[tuple[Node, ScopeId]] = [(node, scopes.module_scope.id) for node in module.body]
839+
while stack:
840+
node, scope = stack.pop()
841+
yield node, scope
842+
if isinstance(node, nodes.Function | nodes.Lambda | nodes.Class | nodes.Comprehension):
843+
scope = scopes.scope_for(node).id
844+
stack.extend((child, scope) for child in children(node))
845+
846+
819847
def _names_engines(target: nodes.Expression) -> bool:
820848
return isinstance(target, nodes.Name) and target.identifier == _ENGINES_SETTING
821849

0 commit comments

Comments
 (0)