Skip to content

Commit

Permalink
fix(_inject_tooldrawer): fix "bad escape \u"
Browse files Browse the repository at this point in the history
We were using re.sub() to inject the tooldrawer HTML.  Re.sub treats
backslashes in the replacement string specially.  When the injected
HTML includes a backslash (e.g. in JSON string data), this was
resulting in a "bad escape \u" exception.
  • Loading branch information
dairiki committed Dec 22, 2023
1 parent 81d8e31 commit 802ad8d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lektor/admin/modules/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ def _inject_tooldrawer(
tooldrawer_config=dataclasses.asdict(tooldrawer_config),
tooldrawer_js=url_for("static", filename="tooldrawer.js"),
).encode("utf-8")
html = re.sub(rb"(?i)(?=</\s*head\s*>|\Z)", tooldrawer_html, html, count=1)
match = re.search(rb"(?i)</\s*head\s*>|\Z", html)
assert match is not None
head_end = match.start()
html = html[:head_end] + tooldrawer_html + html[head_end:]
return html


Expand Down
10 changes: 10 additions & 0 deletions tests/admin/test_serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ def test_inject_tooldrawer(html_text, expect_at_tail):

@pytest.mark.usefixtures("dummy_app_context")
def test_inject_tooldrawer_adds_livereload(dummy_app, make_dummy_artifact):
# Exercises a bug: the injected HTML includes backslash escapes within JSON
# strings. re.sub(pat, repl, s) doesn't work in that case, as it treats backslashes
# in repl specially. This results in an exception: "re.error: bad escape \u at
# position [...]"
dummy_app.register_blueprint(livereload.bp)
artifact = make_dummy_artifact(artifact_name="ARTIFACT_NAME")
config = make_tooldrawer_config("EDIT_URL", artifact)
Expand All @@ -83,6 +87,12 @@ def test_inject_tooldrawer_adds_livereload(dummy_app, make_dummy_artifact):
)


@pytest.mark.usefixtures("dummy_app_context")
def test_inject_tooldrawer_unicode_escapes():
config = make_tooldrawer_config("http://example.com/EDIT_URL?path=/foo&alt=de")
assert b"TOOLDRAWER_CONFIG" in serve._inject_tooldrawer(b"", config)


@pytest.fixture
def make_dummy_artifact(tmp_path):
def make_dummy_artifact(
Expand Down

0 comments on commit 802ad8d

Please sign in to comment.