annotate genshi/filters/html.py @ 908:5fd4a1e28351

Fix for bug with the `HTMLFormFiller` in the handling of textareas. Thanks to Trevor Morgan for pointing this out on the mailing list.
author cmlenz
date Mon, 10 May 2010 14:02:55 +0000
parents 1e2be9fb3348
children 585fdbd30e05
rev   line source
1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
1 # -*- coding: utf-8 -*-
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
2 #
854
0d9e87c6cf6e More work on reducing the size of the diff produced by 2to3.
cmlenz
parents: 853
diff changeset
3 # Copyright (C) 2006-2009 Edgewall Software
1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
4 # All rights reserved.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
5 #
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
6 # This software is licensed as described in the file COPYING, which
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
7 # you should have received as part of this distribution. The terms
230
24757b771651 Renamed Markup to Genshi in repository.
cmlenz
parents: 182
diff changeset
8 # are also available at http://genshi.edgewall.org/wiki/License.
1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
9 #
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
10 # This software consists of voluntary contributions made by many
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
11 # individuals. For the exact contribution history, see the revision
230
24757b771651 Renamed Markup to Genshi in repository.
cmlenz
parents: 182
diff changeset
12 # history and logs, available at http://genshi.edgewall.org/log/.
1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
13
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
14 """Implementation of a number of stream filters."""
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
15
856
1e2be9fb3348 Add a couple of fallback imports for Python 3.0.
cmlenz
parents: 854
diff changeset
16 try:
1e2be9fb3348 Add a couple of fallback imports for Python 3.0.
cmlenz
parents: 854
diff changeset
17 any
1e2be9fb3348 Add a couple of fallback imports for Python 3.0.
cmlenz
parents: 854
diff changeset
18 except NameError:
1e2be9fb3348 Add a couple of fallback imports for Python 3.0.
cmlenz
parents: 854
diff changeset
19 from genshi.util import any
1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
20 import re
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
21
403
32b283e1d310 Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents: 363
diff changeset
22 from genshi.core import Attrs, QName, stripentities
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
23 from genshi.core import END, START, TEXT, COMMENT
1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
24
363
caf7b68ab5dc Parse template includes at parse time to avoid some runtime overhead.
cmlenz
parents: 345
diff changeset
25 __all__ = ['HTMLFormFiller', 'HTMLSanitizer']
425
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
26 __docformat__ = 'restructuredtext en'
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
27
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
28
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
29 class HTMLFormFiller(object):
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
30 """A stream filter that can populate HTML forms from a dictionary of values.
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
31
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
32 >>> from genshi.input import HTML
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
33 >>> html = HTML('''<form>
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
34 ... <p><input type="text" name="foo" /></p>
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
35 ... </form>''')
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
36 >>> filler = HTMLFormFiller(data={'foo': 'bar'})
853
4376010bb97e Convert a bunch of print statements to py3k compatible syntax.
cmlenz
parents: 844
diff changeset
37 >>> print(html | filler)
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
38 <form>
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
39 <p><input type="text" name="foo" value="bar"/></p>
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
40 </form>
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
41 """
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
42 # TODO: only select the first radio button, and the first select option
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
43 # (if not in a multiple-select)
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
44 # TODO: only apply to elements in the XHTML namespace (or no namespace)?
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
45
841
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
46 def __init__(self, name=None, id=None, data=None, passwords=False):
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
47 """Create the filter.
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
48
425
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
49 :param name: The name of the form that should be populated. If this
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
50 parameter is given, only forms where the ``name`` attribute
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
51 value matches the parameter are processed.
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
52 :param id: The ID of the form that should be populated. If this
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
53 parameter is given, only forms where the ``id`` attribute
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
54 value matches the parameter are processed.
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
55 :param data: The dictionary of form values, where the keys are the names
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
56 of the form fields, and the values are the values to fill
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
57 in.
841
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
58 :param passwords: Whether password input fields should be populated.
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
59 This is off by default for security reasons (for
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
60 example, a password may end up in the browser cache)
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
61 :note: Changed in 0.5.2: added the `passwords` option
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
62 """
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
63 self.name = name
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
64 self.id = id
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
65 if data is None:
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
66 data = {}
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
67 self.data = data
841
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
68 self.passwords = passwords
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
69
439
b84c11a49ad2 Add support for adding custom template filters by passing a custom callback function to the `TemplateLoader`. Closes #89 (see added unit test).
cmlenz
parents: 431
diff changeset
70 def __call__(self, stream):
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
71 """Apply the filter to the given stream.
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
72
425
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
73 :param stream: the markup event stream to filter
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
74 """
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
75 in_form = in_select = in_option = in_textarea = False
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
76 select_value = option_value = textarea_value = None
584
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
77 option_start = None
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
78 option_text = []
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
79 no_option_value = False
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
80
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
81 for kind, data, pos in stream:
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
82
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
83 if kind is START:
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
84 tag, attrs = data
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
85 tagname = tag.localname
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
86
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
87 if tagname == 'form' and (
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
88 self.name and attrs.get('name') == self.name or
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
89 self.id and attrs.get('id') == self.id or
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
90 not (self.id or self.name)):
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
91 in_form = True
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
92
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
93 elif in_form:
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
94 if tagname == 'input':
844
0af77f663a65 Fix two instances of using None, which would cause an AttributeError.
jruigrok
parents: 841
diff changeset
95 type = attrs.get('type', '').lower()
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
96 if type in ('checkbox', 'radio'):
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
97 name = attrs.get('name')
471
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
98 if name and name in self.data:
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
99 value = self.data[name]
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
100 declval = attrs.get('value')
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
101 checked = False
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
102 if isinstance(value, (list, tuple)):
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
103 if declval:
584
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
104 checked = declval in [unicode(v) for v
415
c267061c961f `HTMLFormFiller` now correctly deals with non-string values in the data dictionary for select/checkbox/radio controls.
cmlenz
parents: 408
diff changeset
105 in value]
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
106 else:
856
1e2be9fb3348 Add a couple of fallback imports for Python 3.0.
cmlenz
parents: 854
diff changeset
107 checked = any(value)
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
108 else:
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
109 if declval:
584
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
110 checked = declval == unicode(value)
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
111 elif type == 'checkbox':
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
112 checked = bool(value)
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
113 if checked:
403
32b283e1d310 Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents: 363
diff changeset
114 attrs |= [(QName('checked'), 'checked')]
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
115 elif 'checked' in attrs:
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
116 attrs -= 'checked'
844
0af77f663a65 Fix two instances of using None, which would cause an AttributeError.
jruigrok
parents: 841
diff changeset
117 elif type in ('', 'hidden', 'text') \
841
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
118 or type == 'password' and self.passwords:
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
119 name = attrs.get('name')
471
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
120 if name and name in self.data:
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
121 value = self.data[name]
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
122 if isinstance(value, (list, tuple)):
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
123 value = value[0]
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
124 if value is not None:
841
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
125 attrs |= [
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
126 (QName('value'), unicode(value))
67ec9a402bdc Added an option to the `HTMLFiller` to also populate password fields.
cmlenz
parents: 840
diff changeset
127 ]
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
128 elif tagname == 'select':
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
129 name = attrs.get('name')
471
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
130 if name in self.data:
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
131 select_value = self.data[name]
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
132 in_select = True
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
133 elif tagname == 'textarea':
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
134 name = attrs.get('name')
471
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
135 if name in self.data:
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
136 textarea_value = self.data.get(name)
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
137 if isinstance(textarea_value, (list, tuple)):
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
138 textarea_value = textarea_value[0]
17ce8bf006d7 The `HTMLFormFiller` stream filter no longer alters form elements for which the data element contains no corresponding item.
cmlenz
parents: 446
diff changeset
139 in_textarea = True
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
140 elif in_select and tagname == 'option':
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
141 option_start = kind, data, pos
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
142 option_value = attrs.get('value')
584
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
143 if option_value is None:
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
144 no_option_value = True
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
145 option_value = ''
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
146 in_option = True
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
147 continue
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
148 yield kind, (tag, attrs), pos
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
149
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
150 elif in_form and kind is TEXT:
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
151 if in_select and in_option:
584
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
152 if no_option_value:
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
153 option_value += data
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
154 option_text.append((kind, data, pos))
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
155 continue
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
156 elif in_textarea:
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
157 continue
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
158 yield kind, data, pos
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
159
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
160 elif in_form and kind is END:
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
161 tagname = data.localname
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
162 if tagname == 'form':
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
163 in_form = False
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
164 elif tagname == 'select':
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
165 in_select = False
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
166 select_value = None
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
167 elif in_select and tagname == 'option':
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
168 if isinstance(select_value, (tuple, list)):
584
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
169 selected = option_value in [unicode(v) for v
415
c267061c961f `HTMLFormFiller` now correctly deals with non-string values in the data dictionary for select/checkbox/radio controls.
cmlenz
parents: 408
diff changeset
170 in select_value]
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
171 else:
584
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
172 selected = option_value == unicode(select_value)
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
173 okind, (tag, attrs), opos = option_start
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
174 if selected:
403
32b283e1d310 Remove some magic/overhead from `Attrs` creation and manipulation by not automatically wrapping attribute names in `QName`.
cmlenz
parents: 363
diff changeset
175 attrs |= [(QName('selected'), 'selected')]
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
176 elif 'selected' in attrs:
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
177 attrs -= 'selected'
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
178 yield okind, (tag, attrs), opos
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
179 if option_text:
584
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
180 for event in option_text:
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
181 yield event
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
182 in_option = False
584
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
183 no_option_value = False
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
184 option_start = option_value = None
84137a71a4ca Fixed a few cases where HTMLFormFiller didn't work well with option elements:
jonas
parents: 576
diff changeset
185 option_text = []
908
5fd4a1e28351 Fix for bug with the `HTMLFormFiller` in the handling of textareas. Thanks to Trevor Morgan for pointing this out on the mailing list.
cmlenz
parents: 856
diff changeset
186 elif in_textarea and tagname == 'textarea':
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
187 if textarea_value:
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
188 yield TEXT, unicode(textarea_value), pos
908
5fd4a1e28351 Fix for bug with the `HTMLFormFiller` in the handling of textareas. Thanks to Trevor Morgan for pointing this out on the mailing list.
cmlenz
parents: 856
diff changeset
189 textarea_value = None
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
190 in_textarea = False
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
191 yield kind, data, pos
275
7f24dd6fb904 Integrated `HTMLFormFiller` filter initially presented as a [wiki:FormFilling#Usingatemplatefilter recipe].
cmlenz
parents: 230
diff changeset
192
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
193 else:
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
194 yield kind, data, pos
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
195
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
196
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
197 class HTMLSanitizer(object):
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
198 """A filter that removes potentially dangerous HTML tags and attributes
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
199 from the stream.
431
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
200
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
201 >>> from genshi import HTML
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
202 >>> html = HTML('<div><script>alert(document.cookie)</script></div>')
853
4376010bb97e Convert a bunch of print statements to py3k compatible syntax.
cmlenz
parents: 844
diff changeset
203 >>> print(html | HTMLSanitizer())
431
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
204 <div/>
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
205
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
206 The default set of safe tags and attributes can be modified when the filter
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
207 is instantiated. For example, to allow inline ``style`` attributes, the
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
208 following instantation would work:
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
209
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
210 >>> html = HTML('<div style="background: #000"></div>')
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
211 >>> sanitizer = HTMLSanitizer(safe_attrs=HTMLSanitizer.SAFE_ATTRS | set(['style']))
853
4376010bb97e Convert a bunch of print statements to py3k compatible syntax.
cmlenz
parents: 844
diff changeset
212 >>> print(html | sanitizer)
431
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
213 <div style="background: #000"/>
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
214
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
215 Note that even in this case, the filter *does* attempt to remove dangerous
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
216 constructs from style attributes:
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
217
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
218 >>> html = HTML('<div style="background: url(javascript:void); color: #000"></div>')
853
4376010bb97e Convert a bunch of print statements to py3k compatible syntax.
cmlenz
parents: 844
diff changeset
219 >>> print(html | sanitizer)
431
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
220 <div style="color: #000"/>
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
221
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
222 This handles HTML entities, unicode escapes in CSS and Javascript text, as
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
223 well as a lot of other things. However, the style tag is still excluded by
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
224 default because it is very hard for such sanitizing to be completely safe,
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
225 especially considering how much error recovery current web browsers perform.
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
226
840
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
227 It also does some basic filtering of CSS properties that may be used for
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
228 typical phishing attacks. For more sophisticated filtering, this class
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
229 provides a couple of hooks that can be overridden in sub-classes.
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
230
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
231 :warn: Note that this special processing of CSS is currently only applied to
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
232 style attributes, **not** style elements.
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
233 """
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
234
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
235 SAFE_TAGS = frozenset(['a', 'abbr', 'acronym', 'address', 'area', 'b',
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
236 'big', 'blockquote', 'br', 'button', 'caption', 'center', 'cite',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
237 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
238 'em', 'fieldset', 'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
239 'hr', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'map',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
240 'menu', 'ol', 'optgroup', 'option', 'p', 'pre', 'q', 's', 'samp',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
241 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
242 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
243 'ul', 'var'])
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
244
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
245 SAFE_ATTRS = frozenset(['abbr', 'accept', 'accept-charset', 'accesskey',
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
246 'action', 'align', 'alt', 'axis', 'bgcolor', 'border', 'cellpadding',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
247 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
248 'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
249 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
250 'href', 'hreflang', 'hspace', 'id', 'ismap', 'label', 'lang',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
251 'longdesc', 'maxlength', 'media', 'method', 'multiple', 'name',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
252 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly', 'rel', 'rev',
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
253 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size',
431
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
254 'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title',
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
255 'type', 'usemap', 'valign', 'value', 'vspace', 'width'])
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
256
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
257 SAFE_SCHEMES = frozenset(['file', 'ftp', 'http', 'https', 'mailto', None])
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
258
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
259 URI_ATTRS = frozenset(['action', 'background', 'dynsrc', 'href', 'lowsrc',
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
260 'src'])
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
261
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
262 def __init__(self, safe_tags=SAFE_TAGS, safe_attrs=SAFE_ATTRS,
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
263 safe_schemes=SAFE_SCHEMES, uri_attrs=URI_ATTRS):
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
264 """Create the sanitizer.
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
265
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
266 The exact set of allowed elements and attributes can be configured.
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
267
425
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
268 :param safe_tags: a set of tag names that are considered safe
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
269 :param safe_attrs: a set of attribute names that are considered safe
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
270 :param safe_schemes: a set of URI schemes that are considered safe
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
271 :param uri_attrs: a set of names of attributes that contain URIs
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
272 """
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
273 self.safe_tags = safe_tags
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
274 "The set of tag names that are considered safe."
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
275 self.safe_attrs = safe_attrs
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
276 "The set of attribute names that are considered safe."
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
277 self.uri_attrs = uri_attrs
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
278 "The set of names of attributes that may contain URIs."
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
279 self.safe_schemes = safe_schemes
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
280 "The set of URI schemes that are considered safe."
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
281
439
b84c11a49ad2 Add support for adding custom template filters by passing a custom callback function to the `TemplateLoader`. Closes #89 (see added unit test).
cmlenz
parents: 431
diff changeset
282 def __call__(self, stream):
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
283 """Apply the filter to the given stream.
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
284
425
5b248708bbed Try to use proper reStructuredText for docstrings throughout.
cmlenz
parents: 415
diff changeset
285 :param stream: the markup event stream to filter
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
286 """
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
287 waiting_for = None
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
288
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
289 for kind, data, pos in stream:
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
290 if kind is START:
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
291 if waiting_for:
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
292 continue
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
293 tag, attrs = data
840
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
294 if not self.is_safe_elem(tag, attrs):
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
295 waiting_for = tag
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
296 continue
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
297
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
298 new_attrs = []
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
299 for attr, value in attrs:
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
300 value = stripentities(value)
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
301 if attr not in self.safe_attrs:
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
302 continue
277
c9fd81953169 The `HTMLSanitizer` now lets you override the default set of tag and attribute names that are considered safe.
cmlenz
parents: 275
diff changeset
303 elif attr in self.uri_attrs:
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
304 # Don't allow URI schemes such as "javascript:"
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
305 if not self.is_safe_uri(value):
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
306 continue
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
307 elif attr == 'style':
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
308 # Remove dangerous CSS declarations from inline styles
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
309 decls = self.sanitize_css(value)
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
310 if not decls:
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
311 continue
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
312 value = '; '.join(decls)
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
313 new_attrs.append((attr, value))
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
314
345
8e75b83d3e71 Make `Attrs` instances immutable.
cmlenz
parents: 305
diff changeset
315 yield kind, (tag, Attrs(new_attrs)), pos
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
316
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
317 elif kind is END:
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
318 tag = data
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
319 if waiting_for:
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
320 if waiting_for == tag:
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
321 waiting_for = None
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
322 else:
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
323 yield kind, data, pos
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
324
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
325 elif kind is not COMMENT:
123
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
326 if not waiting_for:
93bbdcf9428b Fix for #18: whitespace in space-sensitive elements such as `<pre>` and `<textarea>` is now preserved.
cmlenz
parents: 113
diff changeset
327 yield kind, data, pos
431
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
328
840
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
329 def is_safe_css(self, propname, value):
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
330 """Determine whether the given css property declaration is to be
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
331 considered safe for inclusion in the output.
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
332
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
333 :param propname: the CSS property name
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
334 :param value: the value of the property
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
335 :return: whether the property value should be considered safe
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
336 :rtype: bool
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
337 :since: version 0.6
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
338 """
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
339 if propname == 'position':
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
340 return False
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
341 if propname.startswith('margin') and '-' in value:
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
342 # Negative margins can be used for phishing
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
343 return False
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
344 return True
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
345
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
346 def is_safe_elem(self, tag, attrs):
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
347 """Determine whether the given element should be considered safe for
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
348 inclusion in the output.
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
349
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
350 :param tag: the tag name of the element
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
351 :type tag: QName
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
352 :param attrs: the element attributes
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
353 :type attrs: Attrs
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
354 :return: whether the element should be considered safe
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
355 :rtype: bool
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
356 :since: version 0.6
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
357 """
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
358 if tag not in self.safe_tags:
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
359 return False
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
360 if tag.localname == 'input':
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
361 input_type = attrs.get('type', '').lower()
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
362 if input_type == 'password':
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
363 return False
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
364 return True
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
365
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
366 def is_safe_uri(self, uri):
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
367 """Determine whether the given URI is to be considered safe for
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
368 inclusion in the output.
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
369
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
370 The default implementation checks whether the scheme of the URI is in
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
371 the set of allowed URIs (`safe_schemes`).
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
372
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
373 >>> sanitizer = HTMLSanitizer()
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
374 >>> sanitizer.is_safe_uri('http://example.org/')
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
375 True
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
376 >>> sanitizer.is_safe_uri('javascript:alert(document.cookie)')
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
377 False
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
378
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
379 :param uri: the URI to check
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
380 :return: `True` if the URI can be considered safe, `False` otherwise
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
381 :rtype: `bool`
576
53f4088e1e3b Improve docs on `Stream.select()` for #135.
cmlenz
parents: 571
diff changeset
382 :since: version 0.4.3
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
383 """
837
44b633a0c6a9 Fix for #274.
cmlenz
parents: 750
diff changeset
384 if '#' in uri:
44b633a0c6a9 Fix for #274.
cmlenz
parents: 750
diff changeset
385 uri = uri.split('#', 1)[0] # Strip out the fragment identifier
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
386 if ':' not in uri:
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
387 return True # This is a relative URI
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
388 chars = [char for char in uri.split(':', 1)[0] if char.isalnum()]
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
389 return ''.join(chars).lower() in self.safe_schemes
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
390
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
391 def sanitize_css(self, text):
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
392 """Remove potentially dangerous property declarations from CSS code.
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
393
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
394 In particular, properties using the CSS ``url()`` function with a scheme
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
395 that is not considered safe are removed:
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
396
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
397 >>> sanitizer = HTMLSanitizer()
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
398 >>> sanitizer.sanitize_css(u'''
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
399 ... background: url(javascript:alert("foo"));
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
400 ... color: #000;
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
401 ... ''')
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
402 [u'color: #000']
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
403
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
404 Also, the proprietary Internet Explorer function ``expression()`` is
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
405 always stripped:
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
406
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
407 >>> sanitizer.sanitize_css(u'''
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
408 ... background: #fff;
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
409 ... color: #000;
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
410 ... width: e/**/xpression(alert("foo"));
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
411 ... ''')
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
412 [u'background: #fff', u'color: #000']
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
413
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
414 :param text: the CSS text; this is expected to be `unicode` and to not
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
415 contain any character or numeric references
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
416 :return: a list of declarations that are considered safe
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
417 :rtype: `list`
576
53f4088e1e3b Improve docs on `Stream.select()` for #135.
cmlenz
parents: 571
diff changeset
418 :since: version 0.4.3
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
419 """
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
420 decls = []
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
421 text = self._strip_css_comments(self._replace_unicode_escapes(text))
856
1e2be9fb3348 Add a couple of fallback imports for Python 3.0.
cmlenz
parents: 854
diff changeset
422 for decl in text.split(';'):
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
423 decl = decl.strip()
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
424 if not decl:
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
425 continue
840
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
426 try:
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
427 propname, value = decl.split(':', 1)
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
428 except ValueError:
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
429 continue
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
430 if not self.is_safe_css(propname.strip().lower(), value.strip()):
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
431 continue
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
432 is_evil = False
840
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
433 if 'expression' in value:
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
434 is_evil = True
840
878306a5b465 Ported some of the HTML sanitization improvements from Trac (see [T7658]).
cmlenz
parents: 837
diff changeset
435 for match in re.finditer(r'url\s*\(([^)]+)', value):
571
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
436 if not self.is_safe_uri(match.group(1)):
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
437 is_evil = True
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
438 break
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
439 if not is_evil:
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
440 decls.append(decl.strip())
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
441 return decls
5815ad5f75a4 * Cleaned up the implementation of the `HTMLSanitizer`.
cmlenz
parents: 556
diff changeset
442
431
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
443 _NORMALIZE_NEWLINES = re.compile(r'\r\n').sub
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
444 _UNICODE_ESCAPE = re.compile(r'\\([0-9a-fA-F]{1,6})\s?').sub
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
445
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
446 def _replace_unicode_escapes(self, text):
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
447 def _repl(match):
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
448 return unichr(int(match.group(1), 16))
747baa1cd597 * Don't allow `style` attributes by default in the `HTMLSanitizer`. Closes #97.
cmlenz
parents: 425
diff changeset
449 return self._UNICODE_ESCAPE(_repl, self._NORMALIZE_NEWLINES('\n', text))
556
d5cb5c200045 The HTML sanitizer now strips any CSS comments in style attributes, which could previously be used to hide malicious property values.
cmlenz
parents: 471
diff changeset
450
d5cb5c200045 The HTML sanitizer now strips any CSS comments in style attributes, which could previously be used to hide malicious property values.
cmlenz
parents: 471
diff changeset
451 _CSS_COMMENTS = re.compile(r'/\*.*?\*/').sub
d5cb5c200045 The HTML sanitizer now strips any CSS comments in style attributes, which could previously be used to hide malicious property values.
cmlenz
parents: 471
diff changeset
452
d5cb5c200045 The HTML sanitizer now strips any CSS comments in style attributes, which could previously be used to hide malicious property values.
cmlenz
parents: 471
diff changeset
453 def _strip_css_comments(self, text):
d5cb5c200045 The HTML sanitizer now strips any CSS comments in style attributes, which could previously be used to hide malicious property values.
cmlenz
parents: 471
diff changeset
454 return self._CSS_COMMENTS('', text)
Copyright (C) 2012-2017 Edgewall Software