Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/mistune/directives/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def render_block_image(
height: Optional[str] = None,
**attrs: Any,
) -> str:
img = '<img src="' + escape_text(src) + '"'
img = '<img src="' + self.safe_url(src) + '"'
style = ""
if alt:
img += ' alt="' + escape_text(alt) + '"'
Expand Down
17 changes: 17 additions & 0 deletions tests/test_directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,20 @@ def test_include_missing_source(self):
s = ".. include:: foo.txt"
html = self.md(s)
self.assertIn("Missing source file", html)


class TestImageDirectiveSrc(BaseTestCase):
md = create_markdown(escape=False, plugins=[RSTDirective([Image()])]) # type: ignore[list-item]

def test_harmful_src_blocked(self):
html = self.md(".. image:: javascript:alert")
self.assertIn('src="#harmful-link"', html)
self.assertNotIn("javascript:alert", html)

def test_safe_src_preserved(self):
html = self.md(".. image:: cat.png")
self.assertIn('src="cat.png"', html)

def test_target_still_filtered(self):
html = self.md(".. image:: cat.png\n :target: javascript:alert")
self.assertNotIn("javascript:alert", html)
28 changes: 28 additions & 0 deletions tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,34 @@ def test_harmful_links(self):
expected = '<p><a href="#harmful-link">h</a></p>'
self.assertEqual(result.strip(), expected)

def test_harmful_links_variants(self):
# entity-decoded, alternate-scheme, and reference-link forms are all
# routed to the #harmful-link sentinel.
for text in [
"[h](javascript:alert)",
"[h](&#x6a;avascript:alert)",
"[h](javascript&colon;alert)",
"[h](vbscript:msgbox)",
"[h](file:///etc/passwd)",
"[h](data:text/html,xss)",
"[h](data:image/svg+xml,xss)",
"[h][r]\n\n[r]: javascript:alert",
]:
result = mistune.html(text)
self.assertIn('href="#harmful-link"', result, text)
self.assertNotIn("javascript:alert", result, text)

def test_control_char_scheme_not_executable(self):
# A control char or encoded colon inside the scheme is percent-encoded
# by escape_url, so the rendered href is never an executable
# javascript: scheme (regardless of the sentinel path).
for text in [
"[h](<java\tscript:alert>)",
"[h](<java&#x09;script:alert>)",
"[h](javascript%3Aalert)",
]:
self.assertNotIn("javascript:alert", mistune.html(text), text)

def test_ref_link(self):
result = mistune.html("[link][h]\n\n[h]: /foo")
expected = '<p><a href="/foo">link</a></p>'
Expand Down
Loading