Repository navigation
Description
What happens
A template expression whose string literal holds a lone surrogate escape
(\u or \U with a code point from D800 to DFFF), such as
{{ row['\ud800'] }}, reads the key U+D800 on some renders and the key
U+FFFD (the Unicode replacement character) on others. With this data:
row = {"\ud800": "SURR", "\ufffd": "FFFD"}
data = {"\ud800": ["SURR"], "\ufffd": ["FFFD"]} # for the c-for rowsa component shows SURR or FFFD depending on the template's shape, the
type of the value it reads, and the component kind. (A simple = "vue"
component is one that Citry renders without creating a Component
instance.)
| Template | Ordinary component | simple = "vue" |
|---|---|---|
<p>{{ row['\ud800'] }}</p> |
SURR | SURR |
<p>{{ row['\ud800'] or '' }}</p> |
FFFD | TypeError (template not supported) |
<p c-title="row['\ud800']">x</p> |
FFFD | SURR |
<c-Child c-label="row['\ud800']" /> |
FFFD | SURR |
<p c-if="row['\ud800'] == 'SURR'"> |
FFFD | TypeError (template not supported) |
<i c-for="it in data['\ud800']">{{ it }}</i> |
SURR | SURR |
<i c-for="it in data['\ud800']">{{ it or '' }}</i> |
FFFD | TypeError (template not supported) |
In an ordinary component the first row also changes with the data: when
the two values are str, int or float it reads U+D800, and when they
are dicts or lists it reads U+FFFD. With
Citry(sandbox_expressions=False) every row reads U+D800. The results are
the same on the Python render path (CITRY_NATIVE_RENDER=0) and on the
default path, which reads some rows in Rust.
Reproduction
On main at 0305dfb:
from typing import Any
from citry import Citry, Component
from citry_core._rust import safe_eval
# The template text holds the six characters \ud800.
KEY = "row['\\ud800']"
print(ascii(safe_eval.safe_eval(KEY)))
def show(body: str, kind: bool | str) -> str:
engine = Citry(secret="x" * 32, autodiscover=False)
class Child(Component):
citry = engine
template = """
<b>{{ label }}</b>
"""
def template_data(self, kwargs: Any, slots: Any) -> dict[str, Any]:
return {"label": kwargs["label"]}
class Leaf(Component):
citry = engine
simple = kind
template = body
class Page(Component):
citry = engine
template = """
<c-Leaf c-row="row" />
"""
def template_data(self, kwargs: Any, slots: Any) -> dict[str, Any]:
return {"row": {"\ud800": "SURR", "\ufffd": "FFFD"}}
try:
html = Page().render().serialize(deps_strategy="ignore")
except TypeError:
return "TypeError"
return "SURR" if "SURR" in html else "FFFD"
for body in [
f"<p>{{{{ {KEY} }}}}</p>",
f"<p>{{{{ {KEY} or '' }}}}</p>",
f'<p c-title="{KEY}">x</p>',
f'<c-Child c-label="{KEY}" />',
]:
print(f"{body:34} {show(body, False):5} {show(body, 'vue')}")Output:
"subscript(context, source, (0, 13), variable(context, source, (0, 3), 'row'), '\ufffd')"
<p>{{ row['\ud800'] }}</p> SURR SURR
<p>{{ row['\ud800'] or '' }}</p> FFFD TypeError
<p c-title="row['\ud800']">x</p> FFFD SURR
<c-Child c-label="row['\ud800']" /> FFFD SURR
The first line is the Python code that the expression sandbox (Citry's
default evaluator, described below) writes for row['\ud800']: the key is
already '\ufffd'.
Cause
Citry runs a template expression through one of three evaluators:
- The expression sandbox (the default,
sandbox_expressions=True)
parses the expression in Rust with ruff's parser, rewrites it, and writes
new Python code for it. A Rust string cannot hold a lone surrogate, so
ruff decodes such an escape to U+FFFD
(third_party/rust/ruff/crates/ruff_python_parser/src/string.rs:179), and
generate_python_code(crates/python_safe_eval/src/codegen.rs:6) writes
the literal back from that decoded value. The same decoded value is used
for f-string and t-string text and format specs
(crates/python_safe_eval/src/transformer.rs:1140,:1177,:1285,
:1326), sof'\ud800{x}'andf'{x:\ud800}'change too. - The leaf evaluator in
packages/py/citry/citry/_vue/leaf_program.py
reads the same text with Python'sastmodule, which keeps U+D800
(_simple_json_expr_from_astat line 378, used by
_compile_simple_json_expr,_compile_call_inputand
_compile_simple_json_loop).simple = "vue"components use it, or
refuse the template. An ordinary component uses it only for some
templates and values (in the table, the first row with string or number
values, and the firstc-forrow) and uses the sandbox for the rest. - Unsandboxed evaluation (
sandbox_expressions=False) compiles the text
with Python'scompile, which also keeps U+D800.
So the sandbox is the one evaluator that disagrees with Python. Escapes
outside the surrogate range (\x41, \xe9, \U0001F600, \N{...}) and
number literals read alike on every path. Implicit concatenation does not
help: '\ud800' 'a' still becomes '\ufffd' 'a'.
The Rust row reader for simple = "vue" rows (#265) and the Rust loop walk
(#268) already avoid this: the row reader refuses such a key
(leaf_program.py:2397), and the loop walk refuses any path whose two
readings differ (_vue/native_walk.py:16). Both leave those rows to the
Python evaluator.
Fix direction
Fix the sandbox so it reads these literals as Python does. For a plain
string literal whose source text holds a surrogate escape, write the
literal's original source text into the generated code instead of
rewriting it from the decoded value. Python then decodes it to U+D800
when it runs the generated code (citry_core/safe_eval/eval.py runs that
code with exec). Raw strings and bytes literals need no change,
because \u is not an escape in them. For an f-string or t-string part,
which the sandbox rebuilds from decoded text, either write the escape back
the same way or raise a clear error that names the literal.
A guard in leaf_program.py alone would not fix this: it would only move
ordinary components onto the U+FFFD reading, which still disagrees with
sandbox_expressions=False.
Tests: add one test that renders the same template in an ordinary and a
simple = "vue" component, with the sandbox on and off, for text, an
attribute, c-if, a child component input and a c-for iterable, using
the two-key row above, plus a python_safe_eval test for the generated
code of '\ud800', f'\ud800{x}' and f'{x:\ud800}'.
Activity