Debian Codegraph @

doc/resolvers.txt

raw
1 Document loading and URL resolving
2 ==================================
3
4 .. contents::
5 ..
6 1 XML Catalogs
7 2 URI Resolvers
8 3 Document loading in context
9 4 I/O access control in XSLT
10
11
12 The normal way to load external entities (such as DTDs) is by using
13 XML catalogs. Lxml also has support for user provided document
14 loaders in both the parsers and XSL transformations. These so-called
15 resolvers are subclasses of the etree.Resolver class.
16
17 ..
18 >>> try: from StringIO import StringIO
19 ... except ImportError:
20 ... from io import BytesIO
21 ... def StringIO(s):
22 ... if isinstance(s, str): s = s.encode("UTF-8")
23 ... return BytesIO(s)
24
25
26 XML Catalogs
27 ------------
28
29 When loading an external entity for a document, e.g. a DTD, the parser
30 is normally configured to prevent network access (see the
31 ``no_network`` parser option). Instead, it will try to load the
32 entity from its local file system path or, in the most common case
33 that the entity uses a network URL as reference, from a local XML
34 catalog.
35
36 `XML catalogs`_ are the preferred and agreed-on mechanism to load
37 external entities from XML processors. Most tools will use them, so
38 it is worth configuring them properly on a system. Many Linux
39 installations use them by default, but on other systems they may need
40 to get enabled manually. The `libxml2 site`_ has some documentation
41 on `how to set up XML catalogs`_.
42
43 .. _`XML catalogs`: http://www.oasis-open.org/committees/entity/spec.html
44 .. _`libxml2 site`: http://xmlsoft.org/
45 .. _`how to set up XML catalogs`: http://xmlsoft.org/catalog.html
46
47
48 URI Resolvers
49 -------------
50
51 Here is an example of a custom resolver:
52
53 .. sourcecode:: pycon
54
55 >>> from lxml import etree
56
57 >>> class DTDResolver(etree.Resolver):
58 ... def resolve(self, url, id, context):
59 ... print("Resolving URL '%s'" % url)
60 ... return self.resolve_string(
61 ... '<!ENTITY myentity "[resolved text: %s]">' % url, context)
62
63 This defines a resolver that always returns a dynamically generated DTD
64 fragment defining an entity. The ``url`` argument passes the system URL of
65 the requested document, the ``id`` argument is the public ID. Note that any
66 of these may be None. The context object is not normally used by client code.
67
68 Resolving is based on the methods of the Resolver object that build
69 internal representations of the result document. The following
70 methods exist:
71
72 * ``resolve_string`` takes a parsable string as result document
73 * ``resolve_filename`` takes a filename
74 * ``resolve_file`` takes an open file-like object that has at least a read() method
75 * ``resolve_empty`` resolves into an empty document
76
77 The ``resolve()`` method may choose to return None, in which case the next
78 registered resolver (or the default resolver) is consulted. Resolving always
79 terminates if ``resolve()`` returns the result of any of the above
80 ``resolve_*()`` methods.
81
82 Resolvers are registered local to a parser:
83
84 .. sourcecode:: pycon
85
86 >>> parser = etree.XMLParser(load_dtd=True)
87 >>> parser.resolvers.add( DTDResolver() )
88
89 Note that we instantiate a parser that loads the DTD. This is not done by the
90 default parser, which does no validation. When we use this parser to parse a
91 document that requires resolving a URL, it will call our custom resolver:
92
93 .. sourcecode:: pycon
94
95 >>> xml = '<!DOCTYPE doc SYSTEM "MissingDTD.dtd"><doc>&myentity;</doc>'
96 >>> tree = etree.parse(StringIO(xml), parser)
97 Resolving URL 'MissingDTD.dtd'
98 >>> root = tree.getroot()
99 >>> print(root.text)
100 [resolved text: MissingDTD.dtd]
101
102 The entity in the document was correctly resolved by the generated DTD
103 fragment.
104
105
106 Document loading in context
107 ---------------------------
108
109 XML documents memorise their initial parser (and its resolvers) during their
110 life-time. This means that a lookup process related to a document will use
111 the resolvers of the document's parser. We can demonstrate this with a
112 resolver that only responds to a specific prefix:
113
114 .. sourcecode:: pycon
115
116 >>> class PrefixResolver(etree.Resolver):
117 ... def __init__(self, prefix):
118 ... self.prefix = prefix
119 ... self.result_xml = '''\
120 ... <xsl:stylesheet
121 ... xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
122 ... <test xmlns="testNS">%s-TEST</test>
123 ... </xsl:stylesheet>
124 ... ''' % prefix
125 ... def resolve(self, url, pubid, context):
126 ... if url.startswith(self.prefix):
127 ... print("Resolved url %s as prefix %s" % (url, self.prefix))
128 ... return self.resolve_string(self.result_xml, context)
129
130 We demonstrate this in XSLT and use the following stylesheet as an example:
131
132 .. sourcecode:: pycon
133
134 >>> xml_text = """\
135 ... <xsl:stylesheet version="1.0"
136 ... xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
137 ... <xsl:include href="honk:test"/>
138 ... <xsl:template match="/">
139 ... <test>
140 ... <xsl:value-of select="document('hoi:test')/*/*/text()"/>
141 ... </test>
142 ... </xsl:template>
143 ... </xsl:stylesheet>
144 ... """
145
146 Note that it needs to resolve two URIs: ``honk:test`` when compiling the XSLT
147 document (i.e. when resolving ``xsl:import`` and ``xsl:include`` elements) and
148 ``hoi:test`` at transformation time, when calls to the ``document`` function
149 are resolved. If we now register different resolvers with two different
150 parsers, we can parse our document twice in different resolver contexts:
151
152 .. sourcecode:: pycon
153
154 >>> hoi_parser = etree.XMLParser()
155 >>> normal_doc = etree.parse(StringIO(xml_text), hoi_parser)
156
157 >>> hoi_parser.resolvers.add( PrefixResolver("hoi") )
158 >>> hoi_doc = etree.parse(StringIO(xml_text), hoi_parser)
159
160 >>> honk_parser = etree.XMLParser()
161 >>> honk_parser.resolvers.add( PrefixResolver("honk") )
162 >>> honk_doc = etree.parse(StringIO(xml_text), honk_parser)
163
164 These contexts are important for the further behaviour of the documents. They
165 memorise their original parser so that the correct set of resolvers is used in
166 subsequent lookups. To compile the stylesheet, XSLT must resolve the
167 ``honk:test`` URI in the ``xsl:include`` element. The ``hoi`` resolver cannot
168 do that:
169
170 .. sourcecode:: pycon
171
172 >>> transform = etree.XSLT(normal_doc)
173 Traceback (most recent call last):
174 ...
175 lxml.etree.XSLTParseError: Cannot resolve URI honk:test
176
177 >>> transform = etree.XSLT(hoi_doc)
178 Traceback (most recent call last):
179 ...
180 lxml.etree.XSLTParseError: Cannot resolve URI honk:test
181
182 However, if we use the ``honk`` resolver associated with the respective
183 document, everything works fine:
184
185 .. sourcecode:: pycon
186
187 >>> transform = etree.XSLT(honk_doc)
188 Resolved url honk:test as prefix honk
189
190 Running the transform accesses the same parser context again, but since it now
191 needs to resolve the ``hoi`` URI in the call to the document function, its
192 ``honk`` resolver will fail to do so:
193
194 .. sourcecode:: pycon
195
196 >>> result = transform(normal_doc)
197 Traceback (most recent call last):
198 ...
199 lxml.etree.XSLTApplyError: Cannot resolve URI hoi:test
200
201 >>> result = transform(hoi_doc)
202 Traceback (most recent call last):
203 ...
204 lxml.etree.XSLTApplyError: Cannot resolve URI hoi:test
205
206 >>> result = transform(honk_doc)
207 Traceback (most recent call last):
208 ...
209 lxml.etree.XSLTApplyError: Cannot resolve URI hoi:test
210
211 This can only be solved by adding a ``hoi`` resolver to the original parser:
212
213 .. sourcecode:: pycon
214
215 >>> honk_parser.resolvers.add( PrefixResolver("hoi") )
216 >>> result = transform(honk_doc)
217 Resolved url hoi:test as prefix hoi
218 >>> print(str(result)[:-1])
219 <?xml version="1.0"?>
220 <test>hoi-TEST</test>
221
222 We can see that the ``hoi`` resolver was called to generate a document that
223 was then inserted into the result document by the XSLT transformation. Note
224 that this is completely independent of the XML file you transform, as the URI
225 is resolved from within the stylesheet context:
226
227 .. sourcecode:: pycon
228
229 >>> result = transform(normal_doc)
230 Resolved url hoi:test as prefix hoi
231 >>> print(str(result)[:-1])
232 <?xml version="1.0"?>
233 <test>hoi-TEST</test>
234
235 It may be seen as a matter of taste what resolvers the generated document
236 inherits. For XSLT, the output document inherits the resolvers of the input
237 document and not those of the stylesheet. Therefore, the last result does not
238 inherit any resolvers at all.
239
240
241 I/O access control in XSLT
242 --------------------------
243
244 By default, XSLT supports all extension functions from libxslt and libexslt as
245 well as Python regular expressions through EXSLT. Some extensions enable
246 style sheets to read and write files on the local file system.
247
248 XSLT has a mechanism to control the access to certain I/O operations during
249 the transformation process. This is most interesting where XSL scripts come
250 from potentially insecure sources and must be prevented from modifying the
251 local file system. Note, however, that there is no way to keep them from
252 eating up your precious CPU time, so this should not stop you from thinking
253 about what XSLT you execute.
254
255 Access control is configured using the ``XSLTAccessControl`` class. It can be
256 called with a number of keyword arguments that allow or deny specific
257 operations:
258
259 .. sourcecode:: pycon
260
261 >>> transform = etree.XSLT(honk_doc)
262 Resolved url honk:test as prefix honk
263 >>> result = transform(normal_doc)
264 Resolved url hoi:test as prefix hoi
265
266 >>> ac = etree.XSLTAccessControl(read_network=False, read_file=False)
267 >>> transform = etree.XSLT(honk_doc, access_control=ac)
268 Resolved url honk:test as prefix honk
269 >>> result = transform(normal_doc)
270 Traceback (most recent call last):
271 ...
272 lxml.etree.XSLTApplyError: xsltLoadDocument: read rights for hoi:test denied
273
274 There are a few things to keep in mind:
275
276 * XSL parsing (``xsl:import``, etc.) is not affected by this mechanism
277 * ``read_file=False`` does not imply ``write_file=False``, all controls are
278 independent.
279 * ``read_file`` only applies to files in the file system. Any other scheme
280 for URLs is controlled by the ``*_network`` keywords.
281 * If you need more fine-grained control than switching access on and off, you
282 should consider writing a custom document loader that returns empty
283 documents or raises exceptions if access is denied.