-
Notifications
You must be signed in to change notification settings - Fork 23
/
sanitizer.py
357 lines (297 loc) · 11.2 KB
/
sanitizer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
from __future__ import unicode_literals
import re
import unicodedata
from collections import deque
import lxml.html
import lxml.html.clean
__all__ = ("Sanitizer",)
only_whitespace_re = re.compile(r"^\s*$")
whitespace_re = re.compile(r"\s+")
def sanitize_href(href):
"""
Verify that a given href is benign and allowed.
This is a stupid check, which probably should be much more elaborate
to be safe.
"""
if href.startswith(("/", "mailto:", "http:", "https:", "#", "tel:")):
return href
return "#"
def normalize_overall_whitespace(html):
# remove all sorts of newline and nbsp characters
whitespace = [
"\n",
" ",
"
",
"\r",
" ",
"
",
"\xa0",
" ",
" ",
" ",
]
for ch in whitespace:
html = html.replace(ch, " ")
html = re.sub(r"(?u)\s+", " ", html)
return html
def bold_span_to_strong(element):
if element.tag == "span" and "bold" in element.get("style", ""):
element.tag = "strong"
return element
def italic_span_to_em(element):
if element.tag == "span" and "italic" in element.get("style", ""):
element.tag = "em"
return element
def tag_replacer(from_, to_):
def replacer(element):
if element.tag == from_:
element.tag = to_
return element
return replacer
def target_blank_noopener(element):
if (
element.tag == "a"
and element.attrib.get("target") == "_blank"
and "noopener" not in element.attrib.get("rel", "")
):
element.attrib["rel"] = " ".join(
part for part in (element.attrib.get("rel", ""), "noopener") if part
)
return element
def normalize_whitespace_in_text_or_tail(element):
if element.text:
while True:
text = whitespace_re.sub(" ", element.text)
if element.text == text:
break
element.text = text
if element.tail:
while True:
text = whitespace_re.sub(" ", element.tail)
if element.tail == text:
break
element.tail = text
return element
DEFAULT_SETTINGS = {
"tags": {
"a",
"h1",
"h2",
"h3",
"strong",
"em",
"p",
"ul",
"ol",
"li",
"br",
"sub",
"sup",
"hr",
},
"attributes": {"a": ("href", "name", "target", "title", "id", "rel")},
"empty": {"hr", "a", "br"},
"separate": {"a", "p", "li"},
"whitespace": {"br"},
"add_nofollow": False,
"autolink": False,
"sanitize_href": sanitize_href,
"element_preprocessors": [
# convert span elements into em/strong if a matching style rule
# has been found. strong has precedence, strong & em at the same
# time is not supported
bold_span_to_strong,
italic_span_to_em,
tag_replacer("b", "strong"),
tag_replacer("i", "em"),
tag_replacer("form", "p"),
target_blank_noopener,
],
"element_postprocessors": [],
}
class Sanitizer(object):
def __init__(self, settings=None):
self.__dict__.update(DEFAULT_SETTINGS)
self.__dict__.update(settings or {})
# Allow iterables of any kind, not just sets.
self.tags = set(self.tags)
self.empty = set(self.empty)
self.separate = set(self.separate)
self.whitespace = set(self.whitespace)
# Validate the settings.
if not self.tags:
raise TypeError(
"Empty list of allowed tags is not supported by the underlying"
" lxml cleaner. If you really do not want to pass any tags"
" pass a made-up tag name which will never exist in your"
" document."
)
if not self.tags.issuperset(self.empty):
raise TypeError(
'Tags in "empty", but not allowed: %r' % (self.empty - self.tags,)
)
if not self.tags.issuperset(self.separate):
raise TypeError(
'Tags in "separate", but not allowed: %r' % (self.separate - self.tags,)
)
if not self.tags.issuperset(self.attributes.keys()):
raise TypeError(
'Tags in "attributes", but not allowed: %r'
% (set(self.attributes.keys()) - self.tags,)
)
anchor_attributes = self.attributes.get("a", ())
if "target" in anchor_attributes and "rel" not in anchor_attributes:
raise TypeError(
'Always allow "rel" when allowing "target" as anchor' " attribute"
)
@staticmethod
def is_mergeable(e1, e2):
"""
Decide if the adjacent elements of the same type e1 and e2 can be
merged. This can be overriden to honouring distinct classes etc.
"""
return True
def sanitize(self, html):
"""
Clean HTML code from ugly copy-pasted CSS and empty elements
Removes everything not explicitly allowed in ``self.allowed_tags``.
Requires ``lxml`` and, for especially broken HTML, ``beautifulsoup4``.
"""
html = normalize_overall_whitespace(html)
html = "<div>%s</div>" % html
try:
doc = lxml.html.fromstring(html)
lxml.html.tostring(doc, encoding="utf-8")
except Exception: # We could and maybe should be more specific...
from lxml.html import soupparser
doc = soupparser.fromstring(html)
lxml.html.clean.Cleaner(
remove_unknown_tags=False,
# Remove style *tags*
style=True,
# Do not strip out style attributes; we still need the style
# information to convert spans into em/strong tags
safe_attrs_only=False,
inline_style=False,
# Do not strip all form tags; we will filter them below
forms=False,
)(doc)
# walk the tree recursively, because we want to be able to remove
# previously emptied elements completely
backlog = deque(doc.iterdescendants())
while True:
try:
element = backlog.pop()
except IndexError:
break
for processor in self.element_preprocessors:
element = processor(element)
element = normalize_whitespace_in_text_or_tail(element)
# remove empty tags if they are not explicitly allowed
if (
(not element.text or only_whitespace_re.match(element.text))
and element.tag not in self.empty
and not len(element)
):
element.drop_tag()
continue
# remove tags which only contain whitespace and/or <br>s
if (
element.tag not in self.empty
and only_whitespace_re.match(element.text or "")
and {e.tag for e in element} <= self.whitespace
and all(only_whitespace_re.match(e.tail or "") for e in element)
):
element.drop_tree()
continue
if element.tag in {"li", "p"}:
# remove p-in-li and p-in-p tags
for p in element.findall("p"):
if getattr(p, "text", None):
p.text = " " + p.text + " "
p.drop_tag()
# remove list markers, maybe copy-pasted from word or whatever
if element.text:
element.text = re.sub(
r"^(\ |\ |\s)*(-|\*|·)(\ |\ |\s)+", # noqa
"",
element.text,
)
elif element.tag in self.whitespace:
# Drop the next element if
# 1. it is a <br> too and 2. there is no content in-between
nx = element.getnext()
if (
nx is not None
and nx.tag == element.tag
and (not element.tail or only_whitespace_re.match(element.tail))
):
nx.drop_tag()
continue
if not element.text:
# No text before first child and first child is a <br>: Drop it
first = list(element)[0] if list(element) else None
if first is not None and first.tag in self.whitespace:
first.drop_tag()
# Maybe we have more than one <br>
backlog.append(element)
continue
if element.tag in (self.tags - self.separate):
# Check whether we should merge adjacent elements of the same
# tag type
nx = element.getnext()
if (
only_whitespace_re.match(element.tail or "")
and nx is not None
and nx.tag == element.tag
and self.is_mergeable(element, nx)
):
# Yes, we should. Tail is empty, that is, no text between
# tags of a mergeable type.
if nx.text:
if len(element):
list(element)[-1].tail = "%s %s" % (
list(element)[-1].tail or "",
nx.text,
)
else:
element.text = "%s %s" % (element.text or "", nx.text)
for child in nx:
element.append(child)
# tail is merged with previous element.
nx.drop_tree()
# Process element again
backlog.append(element)
continue
for processor in self.element_postprocessors:
element = processor(element)
# remove all attributes which are not explicitly allowed
allowed = self.attributes.get(element.tag, [])
for key in element.keys():
if key not in allowed:
del element.attrib[key]
# Clean hrefs so that they are benign
href = element.get("href")
if href is not None:
element.set("href", self.sanitize_href(href))
element = normalize_whitespace_in_text_or_tail(element)
if self.autolink:
lxml.html.clean.autolink(doc)
elif isinstance(self.autolink, dict):
lxml.html.clean.autolink(doc, **self.autolink)
# Run cleaner again, but this time with even more strict settings
lxml.html.clean.Cleaner(
allow_tags=self.tags,
remove_unknown_tags=False,
safe_attrs_only=True,
add_nofollow=self.add_nofollow,
forms=False,
)(doc)
html = lxml.html.tostring(doc, encoding="unicode")
# add a space before the closing slash in empty tags
html = re.sub(r"<([^/>]+)/>", r"<\1 />", html)
# remove wrapping tag needed by XML parser
html = re.sub(r"^<div>|</div>$", "", html)
# normalize unicode
html = unicodedata.normalize("NFKC", html)
return html