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 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
|
.. _clean-chapter:
.. highlightlang:: python
=========================
Sanitizing text fragments
=========================
:py:func:`bleach.clean` is Bleach's HTML sanitization method.
Given a fragment of HTML, Bleach will parse it according to the HTML5 parsing
algorithm and sanitize any disallowed tags or attributes. This algorithm also
takes care of things like unclosed and (some) misnested tags.
You may pass in a ``string`` or a ``unicode`` object, but Bleach will always
return ``unicode``.
.. Note::
:py:func:`bleach.clean` is for sanitizing HTML **fragments** and not entire
HTML documents.
.. Warning::
:py:func:`bleach.clean` is for sanitising HTML fragments to use in an HTML
context--not for HTML attributes, CSS, JSON, xhtml, SVG, or other contexts.
For example, this is a safe use of ``clean`` output in an HTML context::
<p>
{{ bleach.clean(user_bio) }}
</p>
This is a **not safe** use of ``clean`` output in an HTML attribute::
<body data-bio="{{ bleach.clean(user_bio} }}">
If you need to use the output of ``bleach.clean()`` in an HTML attribute, you
need to pass it through your template library's escape function. For example,
Jinja2's ``escape`` or ``django.utils.html.escape`` or something like that.
If you need to use the output of ``bleach.clean()`` in any other context,
you need to pass it through an appropriate sanitizer/escaper for that
context.
.. autofunction:: bleach.clean
Allowed tags (``tags``)
=======================
The ``tags`` kwarg specifies the allowed set of HTML tags. It should be a list,
tuple, or other iterable. Any HTML tags not in this list will be escaped or
stripped from the text.
For example:
.. doctest::
>>> import bleach
>>> bleach.clean(
... '<b><i>an example</i></b>',
... tags=['b'],
... )
'<b><i>an example</i></b>'
The default value is a relatively conservative list found in
``bleach.sanitizer.ALLOWED_TAGS``.
.. autodata:: bleach.sanitizer.ALLOWED_TAGS
Allowed Attributes (``attributes``)
===================================
The ``attributes`` kwarg lets you specify which attributes are allowed. The
value can be a list, a callable or a map of tag name to list or callable.
The default value is also a conservative dict found in
``bleach.sanitizer.ALLOWED_ATTRIBUTES``.
.. autodata:: bleach.sanitizer.ALLOWED_ATTRIBUTES
.. versionchanged:: 2.0
Prior to 2.0, the ``attributes`` kwarg value could only be a list or a map.
As a list
---------
The ``attributes`` value can be a list which specifies the list of attributes
allowed for any tag.
For example:
.. doctest::
>>> import bleach
>>> bleach.clean(
... '<p class="foo" style="color: red; font-weight: bold;">blah blah blah</p>',
... tags=['p'],
... attributes=['style'],
... styles=['color'],
... )
'<p style="color: red;">blah blah blah</p>'
As a dict
---------
The ``attributes`` value can be a dict which maps tags to what attributes they can have.
You can also specify ``*``, which will match any tag.
For example, this allows "href" and "rel" for "a" tags, "alt" for the "img" tag
and "class" for any tag (including "a" and "img"):
.. doctest::
>>> import bleach
>>> attrs = {
... '*': ['class'],
... 'a': ['href', 'rel'],
... 'img': ['alt'],
... }
>>> bleach.clean(
... '<img alt="an example" width=500>',
... tags=['img'],
... attributes=attrs
... )
'<img alt="an example">'
Using functions
---------------
You can also use callables that take the tag, attribute name and attribute value
and returns ``True`` to keep the attribute or ``False`` to drop it.
You can pass a callable as the attributes argument value and it'll run for
every tag/attr.
For example:
.. doctest::
>>> import bleach
>>> def allow_h(tag, name, value):
... return name[0] == 'h'
>>> bleach.clean(
... '<a href="http://example.com" title="link">link</a>',
... tags=['a'],
... attributes=allow_h,
... )
'<a href="http://example.com">link</a>'
You can also pass a callable as a value in an attributes dict and it'll run for
attributes for specified tags:
.. doctest::
>>> from six.moves.urllib.parse import urlparse
>>> import bleach
>>> def allow_src(tag, name, value):
... if name in ('alt', 'height', 'width'):
... return True
... if name == 'src':
... p = urlparse(value)
... return (not p.netloc) or p.netloc == 'mydomain.com'
... return False
>>> bleach.clean(
... '<img src="http://example.com" alt="an example">',
... tags=['img'],
... attributes={
... 'img': allow_src
... }
... )
'<img alt="an example">'
.. versionchanged:: 2.0
In previous versions of Bleach, the callable took an attribute name and a
attribute value. Now it takes a tag, an attribute name and an attribute
value.
Allowed styles (``styles``)
===========================
If you allow the ``style`` attribute, you will also need to specify the allowed
styles users are allowed to set, for example ``color`` and ``background-color``.
The default value is an empty list. In other words, the ``style`` attribute will
be allowed but no style declaration names will be allowed.
For example, to allow users to set the color and font-weight of text:
.. doctest::
>>> import bleach
>>> tags = ['p', 'em', 'strong']
>>> attrs = {
... '*': ['style']
... }
>>> styles = ['color', 'font-weight']
>>> bleach.clean(
... '<p style="font-weight: heavy;">my html</p>',
... tags=tags,
... attributes=attrs,
... styles=styles
... )
'<p style="font-weight: heavy;">my html</p>'
Default styles are stored in ``bleach.sanitizer.ALLOWED_STYLES``.
.. autodata:: bleach.sanitizer.ALLOWED_STYLES
Allowed protocols (``protocols``)
=================================
If you allow tags that have attributes containing a URI value (like the ``href``
attribute of an anchor tag, you may want to adapt the accepted protocols.
For example, this sets allowed protocols to http, https and smb:
.. doctest::
>>> import bleach
>>> bleach.clean(
... '<a href="smb://more_text">allowed protocol</a>',
... protocols=['http', 'https', 'smb']
... )
'<a href="smb://more_text">allowed protocol</a>'
This adds smb to the Bleach-specified set of allowed protocols:
.. doctest::
>>> import bleach
>>> bleach.clean(
... '<a href="smb://more_text">allowed protocol</a>',
... protocols=bleach.ALLOWED_PROTOCOLS + ['smb']
... )
'<a href="smb://more_text">allowed protocol</a>'
Default protocols are in ``bleach.sanitizer.ALLOWED_PROTOCOLS``.
.. autodata:: bleach.sanitizer.ALLOWED_PROTOCOLS
Stripping markup (``strip``)
============================
By default, Bleach *escapes* tags that aren't specified in the allowed tags list
and invalid markup. For example:
.. doctest::
>>> import bleach
>>> bleach.clean('<span>is not allowed</span>')
'<span>is not allowed</span>'
>>> bleach.clean('<b><span>is not allowed</span></b>', tags=['b'])
'<b><span>is not allowed</span></b>'
If you would rather Bleach stripped this markup entirely, you can pass
``strip=True``:
.. doctest::
>>> import bleach
>>> bleach.clean('<span>is not allowed</span>', strip=True)
'is not allowed'
>>> bleach.clean('<b><span>is not allowed</span></b>', tags=['b'], strip=True)
'<b>is not allowed</b>'
Stripping comments (``strip_comments``)
=======================================
By default, Bleach will strip out HTML comments. To disable this behavior, set
``strip_comments=False``:
.. doctest::
>>> import bleach
>>> html = 'my<!-- commented --> html'
>>> bleach.clean(html)
'my html'
>>> bleach.clean(html, strip_comments=False)
'my<!-- commented --> html'
Using ``bleach.sanitizer.Cleaner``
==================================
If you're cleaning a lot of text or you need better control of things, you
should create a :py:class:`bleach.sanitizer.Cleaner` instance.
.. autoclass:: bleach.sanitizer.Cleaner
:members:
.. versionadded:: 2.0
html5lib Filters (``filters``)
------------------------------
Bleach sanitizing is implemented as an html5lib filter. The consequence of this
is that we can pass the streamed content through additional specified filters
after the :py:class:`bleach.sanitizer.BleachSanitizingFilter` filter has run.
This lets you add data, drop data and change data as it is being serialized back
to a unicode.
Documentation on html5lib Filters is here:
http://html5lib.readthedocs.io/en/latest/movingparts.html#filters
Trivial Filter example:
.. doctest::
>>> from bleach.sanitizer import Cleaner
>>> from bleach.html5lib_shim import Filter
>>> class MooFilter(Filter):
... def __iter__(self):
... for token in Filter.__iter__(self):
... if token['type'] in ['StartTag', 'EmptyTag'] and token['data']:
... for attr, value in token['data'].items():
... token['data'][attr] = 'moo'
... yield token
...
>>> ATTRS = {
... 'img': ['rel', 'src']
... }
...
>>> TAGS = ['img']
>>> cleaner = Cleaner(tags=TAGS, attributes=ATTRS, filters=[MooFilter])
>>> dirty = 'this is cute! <img src="http://example.com/puppy.jpg" rel="nofollow">'
>>> cleaner.clean(dirty)
'this is cute! <img rel="moo" src="moo">'
.. Warning::
Filters change the output of cleaning. Make sure that whatever changes the
filter is applying maintain the safety guarantees of the output.
.. versionadded:: 2.0
Using ``bleach.sanitizer.BleachSanitizerFilter``
================================================
``bleach.clean`` creates a ``bleach.sanitizer.Cleaner`` which creates a
``bleach.sanitizer.BleachSanitizerFilter`` which does the sanitizing work.
``BleachSanitizerFilter`` is an html5lib filter and can be used anywhere you can
use an html5lib filter.
.. autoclass:: bleach.sanitizer.BleachSanitizerFilter
.. versionadded:: 2.0
|