Mercurial > genshi > genshi-test
annotate markup/filters.py @ 15:f083101b8e8a
Port HTML sanitizer fix from trac:changeset:3417.
author | cmlenz |
---|---|
date | Fri, 16 Jun 2006 09:55:48 +0000 |
parents | 76b5d4b189e6 |
children | ad63ad459524 |
rev | line source |
---|---|
1 | 1 # -*- coding: utf-8 -*- |
2 # | |
3 # Copyright (C) 2006 Christopher Lenz | |
4 # All rights reserved. | |
5 # | |
6 # This software is licensed as described in the file COPYING, which | |
7 # you should have received as part of this distribution. The terms | |
8 # are also available at http://trac.edgewall.com/license.html. | |
9 # | |
10 # This software consists of voluntary contributions made by many | |
11 # individuals. For the exact contribution history, see the revision | |
12 # history and logs, available at http://projects.edgewall.com/trac/. | |
13 | |
14 """Implementation of a number of stream filters.""" | |
15 | |
16 try: | |
17 frozenset | |
18 except NameError: | |
19 from sets import ImmutableSet as frozenset | |
20 import re | |
21 | |
22 from markup.core import Attributes, Markup, Stream | |
23 from markup.path import Path | |
24 | |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
25 __all__ = ['EvalFilter', 'IncludeFilter', 'WhitespaceFilter', 'HTMLSanitizer'] |
1 | 26 |
27 | |
28 class EvalFilter(object): | |
29 """Responsible for evaluating expressions in a template.""" | |
30 | |
31 def __call__(self, stream, ctxt=None): | |
10
c5890ef863ba
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
1
diff
changeset
|
32 from markup.template import Template |
c5890ef863ba
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
1
diff
changeset
|
33 |
1 | 34 for kind, data, pos in stream: |
35 | |
36 if kind is Stream.START: | |
37 # Attributes may still contain expressions in start tags at | |
38 # this point, so do some evaluation | |
39 tag, attrib = data | |
40 new_attrib = [] | |
41 for name, substream in attrib: | |
42 if isinstance(substream, basestring): | |
43 value = substream | |
44 else: | |
45 values = [] | |
46 for subkind, subdata, subpos in substream: | |
10
c5890ef863ba
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
1
diff
changeset
|
47 if subkind is Template.EXPR: |
1 | 48 values.append(subdata.evaluate(ctxt)) |
49 else: | |
50 values.append(subdata) | |
51 value = filter(lambda x: x is not None, values) | |
52 if not value: | |
53 continue | |
54 new_attrib.append((name, ''.join(value))) | |
55 yield kind, (tag, Attributes(new_attrib)), pos | |
56 | |
10
c5890ef863ba
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
1
diff
changeset
|
57 elif kind is Template.EXPR: |
1 | 58 result = data.evaluate(ctxt) |
59 if result is None: | |
60 continue | |
61 | |
62 # First check for a string, otherwise the iterable | |
63 # test below succeeds, and the string will be | |
64 # chopped up into characters | |
65 if isinstance(result, basestring): | |
66 yield Stream.TEXT, result, pos | |
67 else: | |
68 # Test if the expression evaluated to an | |
69 # iterable, in which case we yield the | |
70 # individual items | |
71 try: | |
10
c5890ef863ba
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
1
diff
changeset
|
72 yield Template.SUB, ([], iter(result)), pos |
1 | 73 except TypeError: |
74 # Neither a string nor an iterable, so just | |
75 # pass it through | |
76 yield Stream.TEXT, unicode(result), pos | |
77 | |
78 else: | |
79 yield kind, data, pos | |
80 | |
81 | |
82 class IncludeFilter(object): | |
83 """Template filter providing (very) basic XInclude support | |
84 (see http://www.w3.org/TR/xinclude/) in templates. | |
85 """ | |
86 | |
87 _NAMESPACE = 'http://www.w3.org/2001/XInclude' | |
88 | |
13
bf9de5a4c896
Match directives should now also be applied when included indirectly.
cmlenz
parents:
12
diff
changeset
|
89 def __init__(self, loader, template): |
1 | 90 """Initialize the filter. |
91 | |
92 @param loader: the `TemplateLoader` to use for resolving references to | |
93 external template files | |
94 """ | |
95 self.loader = loader | |
13
bf9de5a4c896
Match directives should now also be applied when included indirectly.
cmlenz
parents:
12
diff
changeset
|
96 self.template = template |
bf9de5a4c896
Match directives should now also be applied when included indirectly.
cmlenz
parents:
12
diff
changeset
|
97 if not hasattr(template, '_included_filters'): |
bf9de5a4c896
Match directives should now also be applied when included indirectly.
cmlenz
parents:
12
diff
changeset
|
98 template._included_filters = [] |
1 | 99 |
12
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
100 def __call__(self, stream, ctxt=None, ns_prefixes=None): |
1 | 101 """Filter the stream, processing any XInclude directives it may |
102 contain. | |
103 | |
104 @param ctxt: the template context | |
105 @param stream: the markup event stream to filter | |
106 """ | |
12
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
107 from markup.template import Template, TemplateError, TemplateNotFound |
1 | 108 |
12
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
109 if ns_prefixes is None: |
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
110 ns_prefixes = [] |
1 | 111 in_fallback = False |
112 include_href, fallback_stream = None, None | |
113 indent = 0 | |
114 | |
115 for kind, data, pos in stream: | |
116 | |
117 if kind is Stream.START and data[0].namespace == self._NAMESPACE \ | |
118 and not in_fallback: | |
119 tag, attrib = data | |
120 if tag.localname == 'include': | |
121 include_href = attrib.get('href') | |
122 indent = pos[1] | |
123 elif tag.localname == 'fallback': | |
124 in_fallback = True | |
125 fallback_stream = [] | |
126 | |
127 elif kind is Stream.END and data.namespace == self._NAMESPACE: | |
128 if data.localname == 'include': | |
129 try: | |
130 if not include_href: | |
131 raise TemplateError('Include misses required ' | |
132 'attribute "href"') | |
133 template = self.loader.load(include_href) | |
134 for ikind, idata, ipos in template.generate(ctxt): | |
135 # Fixup indentation of included markup | |
136 if ikind is Stream.TEXT: | |
137 idata = idata.replace('\n', '\n' + ' ' * indent) | |
138 yield ikind, idata, ipos | |
139 | |
140 # If the included template defines any filters added at | |
141 # runtime (such as py:match templates), those need to be | |
142 # applied to the including template, too. | |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
143 filters = template._included_filters + template.filters |
13
bf9de5a4c896
Match directives should now also be applied when included indirectly.
cmlenz
parents:
12
diff
changeset
|
144 for filter_ in filters: |
1 | 145 stream = filter_(stream, ctxt) |
146 | |
13
bf9de5a4c896
Match directives should now also be applied when included indirectly.
cmlenz
parents:
12
diff
changeset
|
147 # Runtime filters included need to be propagated up |
bf9de5a4c896
Match directives should now also be applied when included indirectly.
cmlenz
parents:
12
diff
changeset
|
148 self.template._included_filters += filters |
bf9de5a4c896
Match directives should now also be applied when included indirectly.
cmlenz
parents:
12
diff
changeset
|
149 |
1 | 150 except TemplateNotFound: |
151 if fallback_stream is None: | |
152 raise | |
153 for event in fallback_stream: | |
154 yield event | |
155 | |
156 include_href = None | |
157 fallback_stream = None | |
158 indent = 0 | |
159 break | |
160 elif data.localname == 'fallback': | |
161 in_fallback = False | |
162 | |
163 elif in_fallback: | |
164 fallback_stream.append((kind, data, pos)) | |
165 | |
166 elif kind is Stream.START_NS and data[1] == self._NAMESPACE: | |
12
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
167 ns_prefixes.append(data[0]) |
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
168 continue |
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
169 |
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
170 elif kind is Stream.END_NS and data in ns_prefixes: |
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
171 ns_prefixes.pop() |
1 | 172 continue |
173 | |
174 else: | |
175 yield kind, data, pos | |
176 else: | |
177 # The loop exited normally, so there shouldn't be further events to | |
178 # process | |
179 return | |
180 | |
12
87238328a71d
Make the XInclude filter track namespace context, to enable it to omit `END_NS` events for the XInclude namespace.
cmlenz
parents:
10
diff
changeset
|
181 for event in self(stream, ctxt, ns_prefixes=ns_prefixes): |
1 | 182 yield event |
183 | |
184 | |
185 class WhitespaceFilter(object): | |
186 """A filter that removes extraneous white space from the stream. | |
187 | |
188 Todo: | |
189 * Support for xml:space | |
190 """ | |
191 | |
192 _TRAILING_SPACE = re.compile('[ \t]+(?=\n)') | |
193 _LINE_COLLAPSE = re.compile('\n{2,}') | |
194 | |
195 def __call__(self, stream, ctxt=None): | |
196 textbuf = [] | |
197 prev_kind = None | |
198 for kind, data, pos in stream: | |
199 if kind is Stream.TEXT: | |
200 textbuf.append(data) | |
201 elif prev_kind is Stream.TEXT: | |
202 text = ''.join(textbuf) | |
203 text = self._TRAILING_SPACE.sub('', text) | |
204 text = self._LINE_COLLAPSE.sub('\n', text) | |
205 yield Stream.TEXT, text, pos | |
206 del textbuf[:] | |
207 prev_kind = kind | |
208 if kind is not Stream.TEXT: | |
209 yield kind, data, pos | |
210 | |
211 if textbuf: | |
212 text = self._LINE_COLLAPSE.sub('\n', ''.join(textbuf)) | |
213 yield Stream.TEXT, text, pos | |
214 | |
215 | |
216 class HTMLSanitizer(object): | |
217 """A filter that removes potentially dangerous HTML tags and attributes | |
218 from the stream. | |
219 """ | |
220 | |
221 _SAFE_TAGS = frozenset(['a', 'abbr', 'acronym', 'address', 'area', 'b', | |
222 'big', 'blockquote', 'br', 'button', 'caption', 'center', 'cite', | |
223 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', | |
224 'em', 'fieldset', 'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', | |
225 'hr', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'map', | |
226 'menu', 'ol', 'optgroup', 'option', 'p', 'pre', 'q', 's', 'samp', | |
227 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', | |
228 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', | |
229 'ul', 'var']) | |
230 | |
231 _SAFE_ATTRS = frozenset(['abbr', 'accept', 'accept-charset', 'accesskey', | |
15 | 232 'action', 'align', 'alt', 'axis', 'bgcolor', 'border', 'cellpadding', |
1 | 233 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class', |
234 'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime', | |
235 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height', | |
236 'href', 'hreflang', 'hspace', 'id', 'ismap', 'label', 'lang', | |
237 'longdesc', 'maxlength', 'media', 'method', 'multiple', 'name', | |
238 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly', 'rel', 'rev', | |
239 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', | |
240 'span', 'src', 'start', 'style', 'summary', 'tabindex', 'target', | |
241 'title', 'type', 'usemap', 'valign', 'value', 'vspace', 'width']) | |
242 _URI_ATTRS = frozenset(['action', 'background', 'dynsrc', 'href', 'lowsrc', | |
243 'src']) | |
244 _SAFE_SCHEMES = frozenset(['file', 'ftp', 'http', 'https', 'mailto', None]) | |
245 | |
246 def __call__(self, stream, ctxt=None): | |
247 waiting_for = None | |
248 | |
249 for kind, data, pos in stream: | |
250 if kind is Stream.START: | |
251 if waiting_for: | |
252 continue | |
253 tag, attrib = data | |
254 if tag not in self._SAFE_TAGS: | |
255 waiting_for = tag | |
256 continue | |
257 | |
258 new_attrib = [] | |
259 for attr, value in attrib: | |
260 if attr not in self._SAFE_ATTRS: | |
261 continue | |
262 elif attr in self._URI_ATTRS: | |
263 # Don't allow URI schemes such as "javascript:" | |
264 if self._get_scheme(value) not in self._SAFE_SCHEMES: | |
265 continue | |
266 elif attr == 'style': | |
267 # Remove dangerous CSS declarations from inline styles | |
268 decls = [] | |
269 for decl in filter(None, value.split(';')): | |
270 is_evil = False | |
271 if 'expression' in decl: | |
272 is_evil = True | |
273 for m in re.finditer(r'url\s*\(([^)]+)', decl): | |
274 if self._get_scheme(m.group(1)) not in self._SAFE_SCHEMES: | |
275 is_evil = True | |
276 break | |
277 if not is_evil: | |
278 decls.append(decl.strip()) | |
279 if not decls: | |
280 continue | |
281 value = '; '.join(decls) | |
282 new_attrib.append((attr, value)) | |
283 | |
284 yield kind, (tag, new_attrib), pos | |
285 | |
286 elif kind is Stream.END: | |
287 tag = data | |
288 if waiting_for: | |
289 if waiting_for == tag: | |
290 waiting_for = None | |
291 else: | |
292 yield kind, data, pos | |
293 | |
294 else: | |
295 if not waiting_for: | |
296 yield kind, data, pos | |
297 | |
298 def _get_scheme(self, text): | |
299 if ':' not in text: | |
300 return None | |
301 chars = [char for char in text.split(':', 1)[0] if char.isalnum()] | |
302 return ''.join(chars).lower() |