From 9cafc4abcd5f8aca5df4c929b289d02c615e9cb2 Mon Sep 17 00:00:00 2001 From: Patrick Uiterwijk Date: Fri, 21 Oct 2016 10:14:49 +0000 Subject: [PATCH] Allow restricting the list of attributes able to be set with attr_list Signed-off-by: Patrick Uiterwijk --- docs/extensions/attr_list.txt | 5 ++++- markdown/extensions/attr_list.py | 21 +++++++++++++++++---- tests/test_extensions.py | 19 +++++++++++++++++++ 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/docs/extensions/attr_list.txt b/docs/extensions/attr_list.txt index 195134731..abf0d8f67 100644 --- a/docs/extensions/attr_list.txt +++ b/docs/extensions/attr_list.txt @@ -85,4 +85,7 @@ Usage See [Extensions](index.html) for general extension usage, specify `markdown.extensions.attr_list` as the name of the extension. -This extension does not accept any special configuration options. +The following options are provided to configure the output: + +* **`allowed_attributes`**: + List of attributes to allow setting. `['*']` means all. Defaults to `['*']`. diff --git a/markdown/extensions/attr_list.py b/markdown/extensions/attr_list.py index 9f6a99a5a..3e46a4a31 100644 --- a/markdown/extensions/attr_list.py +++ b/markdown/extensions/attr_list.py @@ -156,7 +156,10 @@ def assign_attrs(self, elem, attrs): elem.set('class', v) else: # assign attr k with v - elem.set(self.sanitize_name(k), v) + k = self.sanitize_name(k) + allowed = self.config['allowed_attributes'] + if '*' in allowed or k in allowed: + elem.set(k, v) def sanitize_name(self, name): """ @@ -167,10 +170,20 @@ def sanitize_name(self, name): class AttrListExtension(Extension): + def __init__(self, *args, **kwargs): + # define default configs + self.config = { + 'allowed_attributes': [['*'], + "List of attributes allowed to be set. " + "['*']=All."] + } + + super(AttrListExtension, self).__init__(*args, **kwargs) + def extendMarkdown(self, md, md_globals): - md.treeprocessors.add( - 'attr_list', AttrListTreeprocessor(md), '>prettify' - ) + processor = AttrListTreeprocessor(md) + processor.config = self.getConfigs() + md.treeprocessors.add('attr_list', processor, '>prettify') def makeExtension(*args, **kwargs): diff --git a/tests/test_extensions.py b/tests/test_extensions.py index a43de7961..6324464c3 100644 --- a/tests/test_extensions.py +++ b/tests/test_extensions.py @@ -97,6 +97,25 @@ def testNestedAbbr(self): ) +class TestAtrrList(unittest.TestCase): + """ Test abbr extension. """ + + def testDisallowedAttr(self): + """ Test Disallowed Attributes. """ + md = markdown.Markdown(extensions=['markdown.extensions.attr_list']) + text = '# Header 1 {: onclick="insecure" bar="baz" }' + self.assertEqual( + md.convert(text), + '

Header 1

' + ) + md = markdown.Markdown( + extensions=[markdown.extensions.attr_list.AttrListExtension(allowed_attributes=['bar'])]) + self.assertEqual( + md.convert(text), + '

Header 1

' + ) + + class TestCodeHilite(TestCaseWithAssertStartsWith): """ Test codehilite extension. """