Fixed #36733 -- Escaped attributes in Stylesheet.__str__.

This commit is contained in:
varunkasyap 2025-11-15 10:36:46 +05:30
parent 5c60763561
commit 9e9e17c99d
3 changed files with 30 additions and 6 deletions

View file

@ -29,6 +29,7 @@ from io import StringIO
from urllib.parse import urlparse
from django.utils.encoding import iri_to_uri
from django.utils.html import escape
from django.utils.xmlutils import SimplerXMLGenerator
@ -95,11 +96,15 @@ class Stylesheet:
return self._mimetype
def __str__(self):
data = [f'href="{self.url}"']
if self.mimetype is not None:
data.append(f'type="{self.mimetype}"')
if self.media is not None:
data.append(f'media="{self.media}"')
url = escape(iri_to_uri(self._url))
mimetype = escape(self.mimetype) if self.mimetype is not None else None
media = escape(self.media) if self.media is not None else None
data = [f'href="{url}"']
if mimetype is not None:
data.append(f'type="{mimetype}"')
if media is not None:
data.append(f'media="{media}"')
return " ".join(data)
def __repr__(self):

View file

@ -9,4 +9,6 @@ Django 5.2.9 fixes several bugs in 5.2.8.
Bugfixes
========
* ...
* Fixed a bug where ``django.utils.feedgenerator.Stylesheet.__str__()`` did not
escape the ``url``, ``mimetype``, and ``media`` attributes, potentially
leading to invalid XML markup (:ticket:`36733`).

View file

@ -159,3 +159,20 @@ class FeedgeneratorTests(SimpleTestCase):
str(stylesheet), 'href="test.css" type="text/css" media="screen"'
)
m.assert_called_once()
def test_stylesheet_attribute_escaping(self):
"""
Stylesheet.__str__() should escape attribute values.
"""
style = feedgenerator.Stylesheet(
url='http://example.com/style.css?foo="bar"&baz=<>',
mimetype='text/css; charset="utf-8"',
media='screen and (max-width: "600px")',
)
self.assertEqual(
str(style),
'href="http://example.com/style.css?foo=%22bar%22&amp;baz=%3C%3E" '
'type="text/css; charset=&quot;utf-8&quot;" '
'media="screen and (max-width: &quot;600px&quot;)"',
)