include::../description.adoc[]

== Noncompliant Code Example

Standard xml module (https://docs.python.org/3/library/xml.etree.elementtree.html[xml.etree.ElementTree]) is not recommended:

* it https://docs.python.org/3/library/xml.etree.elementtree.html#xpath-support[provides a limited support of xpath] expressions
* to parse https://docs.python.org/3.9/library/xml.html#xml-vulnerabilities[untrusted xml for other security reasons]
* does not have a way to https://wiki.sei.cmu.edu/confluence/display/java/IDS53-J.+Prevent+XPath+Injection[parameterized xpath expressions]

----
from flask import request
import xml.etree.ElementTree as ET

tree = ET.parse('users.xml')
root = tree.getroot()

@app.route('/user')
def user_location():
    username = request.args['username']
    query = "./users/user/[@name='"+username+"']/location"
    elmts = root.findall(query) # Noncompliant
    return 'Location %s' % list(elmts)
----

== Compliant Solution

https://lxml.de/xpathxslt.html[lxml] module:

----
from flask import request
from lxml import etree

parser = etree.XMLParser(resolve_entities=False)
tree = etree.parse('users.xml', parser)
root = tree.getroot()

@app.route('/user')
def user_location():
    username = request.args['username']
    query = "/collection/users/user[@name = $paramname]/location/text()"
    elmts = root.xpath(query, paramname = username)
    return 'Location %s' % list(elmts)
----

include::../see.adoc[]

ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]
