From ad052bafe7a446413bf8b5016000500912111f5b Mon Sep 17 00:00:00 2001 From: Restioson Date: Thu, 7 Nov 2024 12:18:13 +0200 Subject: [PATCH] refactor: inline _bs_icon `_bs_icon` is only called in `icon`, so there is no reason for it to be a separate function. Additionally, by moving it to `icon`, we can ensure that only whitelisted icon names are used, reducing the chance of actual string injection attacks. --- app/general/templatetags/bs_icons.py | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/app/general/templatetags/bs_icons.py b/app/general/templatetags/bs_icons.py index fe459d98..407a580a 100644 --- a/app/general/templatetags/bs_icons.py +++ b/app/general/templatetags/bs_icons.py @@ -1,5 +1,3 @@ -import re - from django import template from django.utils.safestring import mark_safe @@ -12,20 +10,6 @@ register = template.Library() -icon_name_re = re.compile(r"[a-z0-9\-]+") - - -def _bs_icon(name): - assert icon_name_re.fullmatch(name) - return mark_safe(f' ') - # The trailing space is intentional: Since this is an inline element - # usually followed by text, the absence/presence of a space is significant, - # and usually wanted for layout. That's too hard to remember, so we always - # add it. Multiple spaces are equal to one. That way the exact layout of - # code in the templates doesn't matter. Beware of using {% spaceless %} - # which will negate this. A pure CSS solution escaped me thus far, since a - # space will take additional space in addition to a margin. - # a mapping from project types to Bootstrap icon names: _icons = { @@ -44,4 +28,14 @@ def icon(name): if not (bs_name := _icons.get(name)): raise template.TemplateSyntaxError(f"'icon' requires a registered icon name (got {name!r})") - return _bs_icon(bs_name) + # This `mark_safe` is okay because we only allow certain, whitelisted strings. This is enforced above by fetching it + # from the `_icons` dictionary + return mark_safe(f' ') # noqa: S308 - see above + + # The trailing space is intentional: Since this is an inline element + # usually followed by text, the absence/presence of a space is significant, + # and usually wanted for layout. That's too hard to remember, so we always + # add it. Multiple spaces are equal to one. That way the exact layout of + # code in the templates doesn't matter. Beware of using {% spaceless %} + # which will negate this. A pure CSS solution escaped me thus far, since a + # space will take additional space in addition to a margin.