bleach stripping style that should be allowed

848 views Asked by At

I have the following string:

html = '<div id="cover" style="display: block; height: 682px"><div class="cover-desktop hidden-xs" style="background-image: linear-gradient(rgba(0, 0, 0, 0.45), rgba(0, 0, 0, 0.45)), url(\'/site_media/covers/cover.jpg\')"></div></div>'

And these are my options:

ALLOWED_TAGS = bleach.sanitizer.ALLOWED_TAGS + [
    'p',
    'div',
    'table',
    'br',
    'style'
]
ALLOWED_STYLES = ['display', 'height', 'background-image']
ALLOWED_ATTRIBUTES = {
    '*': ['id', 'class', 'style']
}

However when running bleach.clean, the background-image style is getting stripped:

cleaned_html = bleach.clean(html, tags=ALLOWED_TAGS, styles=ALLOWED_STYLES, attributes=ALLOWED_ATTRIBUTES)

Output:

u'<div id="cover" style="display: block; height: 682px;"><div class="cover-desktop hidden-xs" style=""></div></div>'

Why? And how can I fix that?

In fact, how can I allow any style? '*' doesn't do the trick.

edit: it turns out it's because of the background image url(). If a rule containts url it just gets stripped. Here's their code in BleachSanitizerFilter.sanitize_css:

# Drop any url values before we do anything else
style = re.compile(r"url\s*\(\s*[^\s)]+?\s*\)\s*").sub(" ", style)

So how am I supposed to allow background-image property then?

1

There are 1 answers

0
zeyad moustafa On

I am using the bleach 6.0 and I am adding css styles like this

import bleach
from bleach.css_sanitizer import CSSSanitizer

ALLOWED_TAGS = ['p', 'strong', 'em', 'ul', 'ol', 'li', "a", "abbr", 
                "acronym", "b", "blockquote", "code", "i",'span']
ALLOWED_ATTRIBUTES = bleach.sanitizer.ALLOWED_ATTRIBUTES
ALLOWED_ATTRIBUTES['span'] = ['style']

ALLOWED_STYLES = [ 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-align', 'text-decoration', 'text-indent',
                   'background-color', 'background-image', 'background-repeat', 'background-size', 'border', 'border-bottom', 
                   'border-left', 'border-radius', 'border-right', 'border-top', 'margin', 'margin-bottom', 'margin-left', 
                   'margin-right', 'margin-top', 'padding', 'padding-bottom', 'padding-left', 'padding-right', 'padding-top',
                   'line-height', 'letter-spacing', 'word-spacing']

css_santizer = CSSSanitizer(allowed_css_properties=ALLOWED_STYLES)

cleaned_description = bleach.clean(description,tags=ALLOWED_TAGS,attributes=ALLOWED_ATTRIBUTES,css_sanitizer=css_santizer)

I hope this works for you or anybody facing this problem and you can see the documentation for more details.