From 769edb6dcb18f31b22d63247b3f90d8f43d3b740 Mon Sep 17 00:00:00 2001 From: Tobias Genannt Date: Thu, 21 Aug 2025 08:06:15 +0200 Subject: [PATCH] Review comments --- netbox/core/templatetags/highlight_code.py | 5 +++-- netbox/core/tests/test_templatetags.py | 24 ++++++++++++++-------- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/netbox/core/templatetags/highlight_code.py b/netbox/core/templatetags/highlight_code.py index 237a47a71..38bfb13bc 100644 --- a/netbox/core/templatetags/highlight_code.py +++ b/netbox/core/templatetags/highlight_code.py @@ -4,6 +4,7 @@ from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import get_lexer_for_filename from pygments.util import ClassNotFound +from django.utils.html import escape register = template.Library() @@ -16,11 +17,11 @@ def highlight_code(value, filename: str): if not value: return mark_safe('
')
     if not filename:
-        return mark_safe(f'
{value}
') # Fallback to plain text if no filename is provided + return mark_safe(f'
{escape(value)}
') # Fallback to plain text if no filename is provided try: lexer = get_lexer_for_filename(filename) except ClassNotFound: - return mark_safe(f'
{value}
') # Fallback to plain text if no lexer was found + return mark_safe(f'
{escape(value)}
') # Fallback to plain text if no lexer was found return mark_safe( highlight( value, diff --git a/netbox/core/tests/test_templatetags.py b/netbox/core/tests/test_templatetags.py index 0a1f9ce54..34b2eee37 100644 --- a/netbox/core/tests/test_templatetags.py +++ b/netbox/core/tests/test_templatetags.py @@ -17,6 +17,14 @@ FAKE_PYTHON_RESULT = """\
1def fake_function():\n2    print("This is a fake Python function.")\n
""" +FAKE_BAD_NAME = 'bad.hello' +FAKE_BAD_CONTENT = """\ + +""" +FAKE_BAD_RESULT = """\ +
<script> alert('Hello'); </script>\n
\ +""" + class HighlightCodeTestCase(TestCase): def test_python_highlighting(self): @@ -32,18 +40,18 @@ class HighlightCodeTestCase(TestCase): def test_empty_content(self): result = highlight_code('', 'FAKE_PLAIN_TEXT_NAME') - self.assertTrue(result.startswith('
'))
-        self.assertTrue(len(result) == 11)
+        self.assertTrue(result == '
')
 
         result = highlight_code(None, 'FAKE_PLAIN_TEXT_NAME')
-        self.assertTrue(result.startswith('
'))
-        self.assertTrue(len(result) == 11)
+        self.assertTrue(result == '
')
 
     def test_empty_filename(self):
         result = highlight_code(' ', '')
-        self.assertTrue(result.startswith('
 
')) - self.assertTrue(len(result) == 12) + self.assertTrue(result == '
 
') result = highlight_code(' ', None) - self.assertTrue(result.startswith('
 
')) - self.assertTrue(len(result) == 12) + self.assertTrue(result == '
 
') + + def test_fallback_is_safe(self): + result = highlight_code(FAKE_BAD_CONTENT, FAKE_BAD_NAME) + self.assertTrue(result == FAKE_BAD_RESULT)