oidutil.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. """This module contains general utility code that is used throughout
  2. the library.
  3. """
  4. __all__ = [
  5. 'log', 'appendArgs', 'toBase64', 'fromBase64', 'autoSubmitHTML',
  6. 'toUnicode'
  7. ]
  8. import binascii
  9. import logging
  10. # import urllib.parse as urlparse
  11. from urllib.parse import urlencode
  12. logger = logging.getLogger(__name__)
  13. xxe_safe_elementtree_modules = [
  14. 'defusedxml.cElementTree',
  15. 'defusedxml.ElementTree',
  16. ]
  17. elementtree_modules = [
  18. 'xml.etree.cElementTree',
  19. 'xml.etree.ElementTree',
  20. 'cElementTree',
  21. 'elementtree.ElementTree',
  22. ]
  23. def toUnicode(value):
  24. """Returns the given argument as a unicode object.
  25. @param value: A UTF-8 encoded string or a unicode (coercable) object
  26. @type message: str or unicode
  27. @returns: Unicode object representing the input value.
  28. """
  29. if isinstance(value, bytes):
  30. return value.decode('utf-8')
  31. return str(value)
  32. def autoSubmitHTML(form, title='OpenID transaction in progress'):
  33. if isinstance(form, bytes):
  34. form = str(form, encoding="utf-8")
  35. if isinstance(title, bytes):
  36. title = str(title, encoding="utf-8")
  37. html = """
  38. <html>
  39. <head>
  40. <title>%s</title>
  41. </head>
  42. <body onload="document.forms[0].submit();">
  43. %s
  44. <script>
  45. var elements = document.forms[0].elements;
  46. for (var i = 0; i < elements.length; i++) {
  47. elements[i].style.display = "none";
  48. }
  49. </script>
  50. </body>
  51. </html>
  52. """ % (title, form)
  53. return html
  54. def importSafeElementTree(module_names=None):
  55. """Find a working ElementTree implementation that is not vulnerable
  56. to XXE, using `defusedxml`.
  57. >>> XXESafeElementTree = importSafeElementTree()
  58. @param module_names: The names of modules to try to use as
  59. a safe ElementTree. Defaults to C{L{xxe_safe_elementtree_modules}}
  60. @returns: An ElementTree module that is not vulnerable to XXE.
  61. """
  62. if module_names is None:
  63. module_names = xxe_safe_elementtree_modules
  64. try:
  65. return importElementTree(module_names)
  66. except ImportError:
  67. raise ImportError('Unable to find a ElementTree module '
  68. 'that is not vulnerable to XXE. '
  69. 'Tried importing %r' % (module_names, ))
  70. def importElementTree(module_names=None):
  71. """Find a working ElementTree implementation, trying the standard
  72. places that such a thing might show up.
  73. >>> ElementTree = importElementTree()
  74. @param module_names: The names of modules to try to use as
  75. ElementTree. Defaults to C{L{elementtree_modules}}
  76. @returns: An ElementTree module
  77. """
  78. if module_names is None:
  79. module_names = elementtree_modules
  80. for mod_name in module_names:
  81. try:
  82. ElementTree = __import__(mod_name, None, None, ['unused'])
  83. except ImportError:
  84. pass
  85. else:
  86. # Make sure it can actually parse XML
  87. try:
  88. ElementTree.XML('<unused/>')
  89. except (SystemExit, MemoryError, AssertionError):
  90. raise
  91. except:
  92. logger.exception(
  93. 'Not using ElementTree library %r because it failed to '
  94. 'parse a trivial document: %s' % mod_name)
  95. else:
  96. return ElementTree
  97. else:
  98. raise ImportError('No ElementTree library found. '
  99. 'You may need to install one. '
  100. 'Tried importing %r' % (module_names, ))
  101. def log(message, level=0):
  102. """Handle a log message from the OpenID library.
  103. This is a legacy function which redirects to logger.error.
  104. The logging module should be used instead of this
  105. @param message: A string containing a debugging message from the
  106. OpenID library
  107. @type message: str
  108. @param level: The severity of the log message. This parameter is
  109. currently unused, but in the future, the library may indicate
  110. more important information with a higher level value.
  111. @type level: int or None
  112. @returns: Nothing.
  113. """
  114. logger.error("This is a legacy log message, please use the "
  115. "logging module. Message: %s", message)
  116. def appendArgs(url, args):
  117. """Append query arguments to a HTTP(s) URL. If the URL already has
  118. query arguemtns, these arguments will be added, and the existing
  119. arguments will be preserved. Duplicate arguments will not be
  120. detected or collapsed (both will appear in the output).
  121. @param url: The url to which the arguments will be appended
  122. @type url: str
  123. @param args: The query arguments to add to the URL. If a
  124. dictionary is passed, the items will be sorted before
  125. appending them to the URL. If a sequence of pairs is passed,
  126. the order of the sequence will be preserved.
  127. @type args: A dictionary from string to string, or a sequence of
  128. pairs of strings.
  129. @returns: The URL with the parameters added
  130. @rtype: str
  131. """
  132. if hasattr(args, 'items'):
  133. args = sorted(args.items())
  134. else:
  135. args = list(args)
  136. if not isinstance(url, str):
  137. url = str(url, encoding="utf-8")
  138. if not args:
  139. return url
  140. if '?' in url:
  141. sep = '&'
  142. else:
  143. sep = '?'
  144. # Map unicode to UTF-8 if present. Do not make any assumptions
  145. # about the encodings of plain bytes (str).
  146. i = 0
  147. for k, v in args:
  148. if not isinstance(k, bytes):
  149. k = k.encode('utf-8')
  150. if not isinstance(v, bytes):
  151. v = v.encode('utf-8')
  152. args[i] = (k, v)
  153. i += 1
  154. return '%s%s%s' % (url, sep, urlencode(args))
  155. def toBase64(s):
  156. """Represent string / bytes s as base64, omitting newlines"""
  157. if isinstance(s, str):
  158. s = s.encode("utf-8")
  159. return binascii.b2a_base64(s)[:-1]
  160. def fromBase64(s):
  161. if isinstance(s, str):
  162. s = s.encode("utf-8")
  163. try:
  164. return binascii.a2b_base64(s)
  165. except binascii.Error as why:
  166. # Convert to a common exception type
  167. raise ValueError(str(why))
  168. class Symbol(object):
  169. """This class implements an object that compares equal to others
  170. of the same type that have the same name. These are distict from
  171. str or unicode objects.
  172. """
  173. def __init__(self, name):
  174. self.name = name
  175. def __eq__(self, other):
  176. return type(self) is type(other) and self.name == other.name
  177. def __ne__(self, other):
  178. return not (self == other)
  179. def __hash__(self):
  180. return hash((self.__class__, self.name))
  181. def __repr__(self):
  182. return '<Symbol %s>' % (self.name, )