consumer.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900
  1. # -*- test-case-name: openid.test.test_consumer -*-
  2. """OpenID support for Relying Parties (aka Consumers).
  3. This module documents the main interface with the OpenID consumer
  4. library. The only part of the library which has to be used and isn't
  5. documented in full here is the store required to create an
  6. C{L{Consumer}} instance. More on the abstract store type and
  7. concrete implementations of it that are provided in the documentation
  8. for the C{L{__init__<Consumer.__init__>}} method of the
  9. C{L{Consumer}} class.
  10. OVERVIEW
  11. ========
  12. The OpenID identity verification process most commonly uses the
  13. following steps, as visible to the user of this library:
  14. 1. The user enters their OpenID into a field on the consumer's
  15. site, and hits a login button.
  16. 2. The consumer site discovers the user's OpenID provider using
  17. the Yadis protocol.
  18. 3. The consumer site sends the browser a redirect to the
  19. OpenID provider. This is the authentication request as
  20. described in the OpenID specification.
  21. 4. The OpenID provider's site sends the browser a redirect
  22. back to the consumer site. This redirect contains the
  23. provider's response to the authentication request.
  24. The most important part of the flow to note is the consumer's site
  25. must handle two separate HTTP requests in order to perform the
  26. full identity check.
  27. LIBRARY DESIGN
  28. ==============
  29. This consumer library is designed with that flow in mind. The
  30. goal is to make it as easy as possible to perform the above steps
  31. securely.
  32. At a high level, there are two important parts in the consumer
  33. library. The first important part is this module, which contains
  34. the interface to actually use this library. The second is the
  35. C{L{openid.store.interface}} module, which describes the
  36. interface to use if you need to create a custom method for storing
  37. the state this library needs to maintain between requests.
  38. In general, the second part is less important for users of the
  39. library to know about, as several implementations are provided
  40. which cover a wide variety of situations in which consumers may
  41. use the library.
  42. This module contains a class, C{L{Consumer}}, with methods
  43. corresponding to the actions necessary in each of steps 2, 3, and
  44. 4 described in the overview. Use of this library should be as easy
  45. as creating an C{L{Consumer}} instance and calling the methods
  46. appropriate for the action the site wants to take.
  47. SESSIONS, STORES, AND STATELESS MODE
  48. ====================================
  49. The C{L{Consumer}} object keeps track of two types of state:
  50. 1. State of the user's current authentication attempt. Things like
  51. the identity URL, the list of endpoints discovered for that
  52. URL, and in case where some endpoints are unreachable, the list
  53. of endpoints already tried. This state needs to be held from
  54. Consumer.begin() to Consumer.complete(), but it is only applicable
  55. to a single session with a single user agent, and at the end of
  56. the authentication process (i.e. when an OP replies with either
  57. C{id_res} or C{cancel}) it may be discarded.
  58. 2. State of relationships with servers, i.e. shared secrets
  59. (associations) with servers and nonces seen on signed messages.
  60. This information should persist from one session to the next and
  61. should not be bound to a particular user-agent.
  62. These two types of storage are reflected in the first two arguments of
  63. Consumer's constructor, C{session} and C{store}. C{session} is a
  64. dict-like object and we hope your web framework provides you with one
  65. of these bound to the user agent. C{store} is an instance of
  66. L{openid.store.interface.OpenIDStore}.
  67. Since the store does hold secrets shared between your application and the
  68. OpenID provider, you should be careful about how you use it in a shared
  69. hosting environment. If the filesystem or database permissions of your
  70. web host allow strangers to read from them, do not store your data there!
  71. If you have no safe place to store your data, construct your consumer
  72. with C{None} for the store, and it will operate only in stateless mode.
  73. Stateless mode may be slower, put more load on the OpenID provider, and
  74. trusts the provider to keep you safe from replay attacks.
  75. Several store implementation are provided, and the interface is
  76. fully documented so that custom stores can be used as well. See
  77. the documentation for the C{L{Consumer}} class for more
  78. information on the interface for stores. The implementations that
  79. are provided allow the consumer site to store the necessary data
  80. in several different ways, including several SQL databases and
  81. normal files on disk.
  82. IMMEDIATE MODE
  83. ==============
  84. In the flow described above, the user may need to confirm to the
  85. OpenID provider that it's ok to disclose his or her identity.
  86. The provider may draw pages asking for information from the user
  87. before it redirects the browser back to the consumer's site. This
  88. is generally transparent to the consumer site, so it is typically
  89. ignored as an implementation detail.
  90. There can be times, however, where the consumer site wants to get
  91. a response immediately. When this is the case, the consumer can
  92. put the library in immediate mode. In immediate mode, there is an
  93. extra response possible from the server, which is essentially the
  94. server reporting that it doesn't have enough information to answer
  95. the question yet.
  96. USING THIS LIBRARY
  97. ==================
  98. Integrating this library into an application is usually a
  99. relatively straightforward process. The process should basically
  100. follow this plan:
  101. Add an OpenID login field somewhere on your site. When an OpenID
  102. is entered in that field and the form is submitted, it should make
  103. a request to your site which includes that OpenID URL.
  104. First, the application should L{instantiate a Consumer<Consumer.__init__>}
  105. with a session for per-user state and store for shared state.
  106. using the store of choice.
  107. Next, the application should call the 'C{L{begin<Consumer.begin>}}' method on the
  108. C{L{Consumer}} instance. This method takes the OpenID URL. The
  109. C{L{begin<Consumer.begin>}} method returns an C{L{AuthRequest}}
  110. object.
  111. Next, the application should call the
  112. C{L{redirectURL<AuthRequest.redirectURL>}} method on the
  113. C{L{AuthRequest}} object. The parameter C{return_to} is the URL
  114. that the OpenID server will send the user back to after attempting
  115. to verify his or her identity. The C{realm} parameter is the
  116. URL (or URL pattern) that identifies your web site to the user
  117. when he or she is authorizing it. Send a redirect to the
  118. resulting URL to the user's browser.
  119. That's the first half of the authentication process. The second
  120. half of the process is done after the user's OpenID Provider sends the
  121. user's browser a redirect back to your site to complete their
  122. login.
  123. When that happens, the user will contact your site at the URL
  124. given as the C{return_to} URL to the
  125. C{L{redirectURL<AuthRequest.redirectURL>}} call made
  126. above. The request will have several query parameters added to
  127. the URL by the OpenID provider as the information necessary to
  128. finish the request.
  129. Get a C{L{Consumer}} instance with the same session and store as
  130. before and call its C{L{complete<Consumer.complete>}} method,
  131. passing in all the received query arguments.
  132. There are multiple possible return types possible from that
  133. method. These indicate whether or not the login was successful,
  134. and include any additional information appropriate for their type.
  135. @var SUCCESS: constant used as the status for
  136. L{SuccessResponse<openid.consumer.consumer.SuccessResponse>} objects.
  137. @var FAILURE: constant used as the status for
  138. L{FailureResponse<openid.consumer.consumer.FailureResponse>} objects.
  139. @var CANCEL: constant used as the status for
  140. L{CancelResponse<openid.consumer.consumer.CancelResponse>} objects.
  141. @var SETUP_NEEDED: constant used as the status for
  142. L{SetupNeededResponse<openid.consumer.consumer.SetupNeededResponse>}
  143. objects.
  144. """
  145. import cgi
  146. import copy
  147. from urlparse import urlparse, urldefrag
  148. from openid import fetchers
  149. from openid.consumer.discover import discover, OpenIDServiceEndpoint, \
  150. DiscoveryFailure, OPENID_1_0_TYPE, OPENID_1_1_TYPE, OPENID_2_0_TYPE
  151. from openid.message import Message, OPENID_NS, OPENID2_NS, OPENID1_NS, \
  152. IDENTIFIER_SELECT, no_default, BARE_NS
  153. from openid import cryptutil
  154. from openid import oidutil
  155. from openid.association import Association, default_negotiator, \
  156. SessionNegotiator
  157. from openid.dh import DiffieHellman
  158. from openid.store.nonce import mkNonce, split as splitNonce
  159. from openid.yadis.manager import Discovery
  160. from openid import urinorm
  161. __all__ = ['AuthRequest', 'Consumer', 'SuccessResponse',
  162. 'SetupNeededResponse', 'CancelResponse', 'FailureResponse',
  163. 'SUCCESS', 'FAILURE', 'CANCEL', 'SETUP_NEEDED',
  164. ]
  165. def makeKVPost(request_message, server_url):
  166. """Make a Direct Request to an OpenID Provider and return the
  167. result as a Message object.
  168. @raises openid.fetchers.HTTPFetchingError: if an error is
  169. encountered in making the HTTP post.
  170. @rtype: L{openid.message.Message}
  171. """
  172. # XXX: TESTME
  173. resp = fetchers.fetch(server_url, body=request_message.toURLEncoded())
  174. # Process response in separate function that can be shared by async code.
  175. return _httpResponseToMessage(resp, server_url)
  176. def _httpResponseToMessage(response, server_url):
  177. """Adapt a POST response to a Message.
  178. @type response: L{openid.fetchers.HTTPResponse}
  179. @param response: Result of a POST to an OpenID endpoint.
  180. @rtype: L{openid.message.Message}
  181. @raises openid.fetchers.HTTPFetchingError: if the server returned a
  182. status of other than 200 or 400.
  183. @raises ServerError: if the server returned an OpenID error.
  184. """
  185. # Should this function be named Message.fromHTTPResponse instead?
  186. response_message = Message.fromKVForm(response.body)
  187. if response.status == 400:
  188. raise ServerError.fromMessage(response_message)
  189. elif response.status not in (200, 206):
  190. fmt = 'bad status code from server %s: %s'
  191. error_message = fmt % (server_url, response.status)
  192. raise fetchers.HTTPFetchingError(error_message)
  193. return response_message
  194. class Consumer(object):
  195. """An OpenID consumer implementation that performs discovery and
  196. does session management.
  197. @ivar consumer: an instance of an object implementing the OpenID
  198. protocol, but doing no discovery or session management.
  199. @type consumer: GenericConsumer
  200. @ivar session: A dictionary-like object representing the user's
  201. session data. This is used for keeping state of the OpenID
  202. transaction when the user is redirected to the server.
  203. @cvar session_key_prefix: A string that is prepended to session
  204. keys to ensure that they are unique. This variable may be
  205. changed to suit your application.
  206. """
  207. session_key_prefix = "_openid_consumer_"
  208. _token = 'last_token'
  209. _discover = staticmethod(discover)
  210. def __init__(self, session, store, consumer_class=None):
  211. """Initialize a Consumer instance.
  212. You should create a new instance of the Consumer object with
  213. every HTTP request that handles OpenID transactions.
  214. @param session: See L{the session instance variable<openid.consumer.consumer.Consumer.session>}
  215. @param store: an object that implements the interface in
  216. C{L{openid.store.interface.OpenIDStore}}. Several
  217. implementations are provided, to cover common database
  218. environments.
  219. @type store: C{L{openid.store.interface.OpenIDStore}}
  220. @see: L{openid.store.interface}
  221. @see: L{openid.store}
  222. """
  223. self.session = session
  224. if consumer_class is None:
  225. consumer_class = GenericConsumer
  226. self.consumer = consumer_class(store)
  227. self._token_key = self.session_key_prefix + self._token
  228. def begin(self, user_url, anonymous=False):
  229. """Start the OpenID authentication process. See steps 1-2 in
  230. the overview at the top of this file.
  231. @param user_url: Identity URL given by the user. This method
  232. performs a textual transformation of the URL to try and
  233. make sure it is normalized. For example, a user_url of
  234. example.com will be normalized to http://example.com/
  235. normalizing and resolving any redirects the server might
  236. issue.
  237. @type user_url: unicode
  238. @param anonymous: Whether to make an anonymous request of the OpenID
  239. provider. Such a request does not ask for an authorization
  240. assertion for an OpenID identifier, but may be used with
  241. extensions to pass other data. e.g. "I don't care who you are,
  242. but I'd like to know your time zone."
  243. @type anonymous: bool
  244. @returns: An object containing the discovered information will
  245. be returned, with a method for building a redirect URL to
  246. the server, as described in step 3 of the overview. This
  247. object may also be used to add extension arguments to the
  248. request, using its
  249. L{addExtensionArg<openid.consumer.consumer.AuthRequest.addExtensionArg>}
  250. method.
  251. @returntype: L{AuthRequest<openid.consumer.consumer.AuthRequest>}
  252. @raises openid.consumer.discover.DiscoveryFailure: when I fail to
  253. find an OpenID server for this URL. If the C{yadis} package
  254. is available, L{openid.consumer.discover.DiscoveryFailure} is
  255. an alias for C{yadis.discover.DiscoveryFailure}.
  256. """
  257. disco = Discovery(self.session, user_url, self.session_key_prefix)
  258. try:
  259. service = disco.getNextService(self._discover)
  260. except fetchers.HTTPFetchingError, why:
  261. raise DiscoveryFailure(
  262. 'Error fetching XRDS document: %s' % (why[0],), None)
  263. if service is None:
  264. raise DiscoveryFailure(
  265. 'No usable OpenID services found for %s' % (user_url,), None)
  266. else:
  267. return self.beginWithoutDiscovery(service, anonymous)
  268. def beginWithoutDiscovery(self, service, anonymous=False):
  269. """Start OpenID verification without doing OpenID server
  270. discovery. This method is used internally by Consumer.begin
  271. after discovery is performed, and exists to provide an
  272. interface for library users needing to perform their own
  273. discovery.
  274. @param service: an OpenID service endpoint descriptor. This
  275. object and factories for it are found in the
  276. L{openid.consumer.discover} module.
  277. @type service:
  278. L{OpenIDServiceEndpoint<openid.consumer.discover.OpenIDServiceEndpoint>}
  279. @returns: an OpenID authentication request object.
  280. @rtype: L{AuthRequest<openid.consumer.consumer.AuthRequest>}
  281. @See: Openid.consumer.consumer.Consumer.begin
  282. @see: openid.consumer.discover
  283. """
  284. auth_req = self.consumer.begin(service)
  285. self.session[self._token_key] = auth_req.endpoint
  286. try:
  287. auth_req.setAnonymous(anonymous)
  288. except ValueError, why:
  289. raise ProtocolError(str(why))
  290. return auth_req
  291. def complete(self, query, current_url):
  292. """Called to interpret the server's response to an OpenID
  293. request. It is called in step 4 of the flow described in the
  294. consumer overview.
  295. @param query: A dictionary of the query parameters for this
  296. HTTP request.
  297. @param current_url: The URL used to invoke the application.
  298. Extract the URL from your application's web
  299. request framework and specify it here to have it checked
  300. against the openid.return_to value in the response. If
  301. the return_to URL check fails, the status of the
  302. completion will be FAILURE.
  303. @returns: a subclass of Response. The type of response is
  304. indicated by the status attribute, which will be one of
  305. SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED.
  306. @see: L{SuccessResponse<openid.consumer.consumer.SuccessResponse>}
  307. @see: L{CancelResponse<openid.consumer.consumer.CancelResponse>}
  308. @see: L{SetupNeededResponse<openid.consumer.consumer.SetupNeededResponse>}
  309. @see: L{FailureResponse<openid.consumer.consumer.FailureResponse>}
  310. """
  311. endpoint = self.session.get(self._token_key)
  312. message = Message.fromPostArgs(query)
  313. response = self.consumer.complete(message, endpoint, current_url)
  314. try:
  315. del self.session[self._token_key]
  316. except KeyError:
  317. pass
  318. if (response.status in ['success', 'cancel'] and
  319. response.identity_url is not None):
  320. disco = Discovery(self.session,
  321. response.identity_url,
  322. self.session_key_prefix)
  323. # This is OK to do even if we did not do discovery in
  324. # the first place.
  325. disco.cleanup(force=True)
  326. return response
  327. def setAssociationPreference(self, association_preferences):
  328. """Set the order in which association types/sessions should be
  329. attempted. For instance, to only allow HMAC-SHA256
  330. associations created with a DH-SHA256 association session:
  331. >>> consumer.setAssociationPreference([('HMAC-SHA256', 'DH-SHA256')])
  332. Any association type/association type pair that is not in this
  333. list will not be attempted at all.
  334. @param association_preferences: The list of allowed
  335. (association type, association session type) pairs that
  336. should be allowed for this consumer to use, in order from
  337. most preferred to least preferred.
  338. @type association_preferences: [(str, str)]
  339. @returns: None
  340. @see: C{L{openid.association.SessionNegotiator}}
  341. """
  342. self.consumer.negotiator = SessionNegotiator(association_preferences)
  343. class DiffieHellmanSHA1ConsumerSession(object):
  344. session_type = 'DH-SHA1'
  345. hash_func = staticmethod(cryptutil.sha1)
  346. secret_size = 20
  347. allowed_assoc_types = ['HMAC-SHA1']
  348. def __init__(self, dh=None):
  349. if dh is None:
  350. dh = DiffieHellman.fromDefaults()
  351. self.dh = dh
  352. def getRequest(self):
  353. cpub = cryptutil.longToBase64(self.dh.public)
  354. args = {'dh_consumer_public': cpub}
  355. if not self.dh.usingDefaultValues():
  356. args.update({
  357. 'dh_modulus': cryptutil.longToBase64(self.dh.modulus),
  358. 'dh_gen': cryptutil.longToBase64(self.dh.generator),
  359. })
  360. return args
  361. def extractSecret(self, response):
  362. dh_server_public64 = response.getArg(
  363. OPENID_NS, 'dh_server_public', no_default)
  364. enc_mac_key64 = response.getArg(OPENID_NS, 'enc_mac_key', no_default)
  365. dh_server_public = cryptutil.base64ToLong(dh_server_public64)
  366. enc_mac_key = oidutil.fromBase64(enc_mac_key64)
  367. return self.dh.xorSecret(dh_server_public, enc_mac_key, self.hash_func)
  368. class DiffieHellmanSHA256ConsumerSession(DiffieHellmanSHA1ConsumerSession):
  369. session_type = 'DH-SHA256'
  370. hash_func = staticmethod(cryptutil.sha256)
  371. secret_size = 32
  372. allowed_assoc_types = ['HMAC-SHA256']
  373. class PlainTextConsumerSession(object):
  374. session_type = 'no-encryption'
  375. allowed_assoc_types = ['HMAC-SHA1', 'HMAC-SHA256']
  376. def getRequest(self):
  377. return {}
  378. def extractSecret(self, response):
  379. mac_key64 = response.getArg(OPENID_NS, 'mac_key', no_default)
  380. return oidutil.fromBase64(mac_key64)
  381. class SetupNeededError(Exception):
  382. """Internally-used exception that indicates that an immediate-mode
  383. request cancelled."""
  384. def __init__(self, user_setup_url=None):
  385. Exception.__init__(self, user_setup_url)
  386. self.user_setup_url = user_setup_url
  387. class ProtocolError(ValueError):
  388. """Exception that indicates that a message violated the
  389. protocol. It is raised and caught internally to this file."""
  390. class TypeURIMismatch(ProtocolError):
  391. """A protocol error arising from type URIs mismatching
  392. """
  393. def __init__(self, expected, endpoint):
  394. ProtocolError.__init__(self, expected, endpoint)
  395. self.expected = expected
  396. self.endpoint = endpoint
  397. def __str__(self):
  398. s = '<%s.%s: Required type %s not found in %s for endpoint %s>' % (
  399. self.__class__.__module__, self.__class__.__name__,
  400. self.expected, self.endpoint.type_uris, self.endpoint)
  401. return s
  402. class ServerError(Exception):
  403. """Exception that is raised when the server returns a 400 response
  404. code to a direct request."""
  405. def __init__(self, error_text, error_code, message):
  406. Exception.__init__(self, error_text)
  407. self.error_text = error_text
  408. self.error_code = error_code
  409. self.message = message
  410. def fromMessage(cls, message):
  411. """Generate a ServerError instance, extracting the error text
  412. and the error code from the message."""
  413. error_text = message.getArg(
  414. OPENID_NS, 'error', '<no error message supplied>')
  415. error_code = message.getArg(OPENID_NS, 'error_code')
  416. return cls(error_text, error_code, message)
  417. fromMessage = classmethod(fromMessage)
  418. class GenericConsumer(object):
  419. """This is the implementation of the common logic for OpenID
  420. consumers. It is unaware of the application in which it is
  421. running.
  422. @ivar negotiator: An object that controls the kind of associations
  423. that the consumer makes. It defaults to
  424. C{L{openid.association.default_negotiator}}. Assign a
  425. different negotiator to it if you have specific requirements
  426. for how associations are made.
  427. @type negotiator: C{L{openid.association.SessionNegotiator}}
  428. """
  429. # The name of the query parameter that gets added to the return_to
  430. # URL when using OpenID1. You can change this value if you want or
  431. # need a different name, but don't make it start with openid,
  432. # because it's not a standard protocol thing for OpenID1. For
  433. # OpenID2, the library will take care of the nonce using standard
  434. # OpenID query parameter names.
  435. openid1_nonce_query_arg_name = 'janrain_nonce'
  436. # Another query parameter that gets added to the return_to for
  437. # OpenID 1; if the user's session state is lost, use this claimed
  438. # identifier to do discovery when verifying the response.
  439. openid1_return_to_identifier_name = 'openid1_claimed_id'
  440. session_types = {
  441. 'DH-SHA1':DiffieHellmanSHA1ConsumerSession,
  442. 'DH-SHA256':DiffieHellmanSHA256ConsumerSession,
  443. 'no-encryption':PlainTextConsumerSession,
  444. }
  445. _discover = staticmethod(discover)
  446. def __init__(self, store):
  447. self.store = store
  448. self.negotiator = default_negotiator.copy()
  449. def begin(self, service_endpoint):
  450. """Create an AuthRequest object for the specified
  451. service_endpoint. This method will create an association if
  452. necessary."""
  453. if self.store is None:
  454. assoc = None
  455. else:
  456. assoc = self._getAssociation(service_endpoint)
  457. request = AuthRequest(service_endpoint, assoc)
  458. request.return_to_args[self.openid1_nonce_query_arg_name] = mkNonce()
  459. if request.message.isOpenID1():
  460. request.return_to_args[self.openid1_return_to_identifier_name] = \
  461. request.endpoint.claimed_id
  462. return request
  463. def complete(self, message, endpoint, return_to):
  464. """Process the OpenID message, using the specified endpoint
  465. and return_to URL as context. This method will handle any
  466. OpenID message that is sent to the return_to URL.
  467. """
  468. mode = message.getArg(OPENID_NS, 'mode', '<No mode set>')
  469. modeMethod = getattr(self, '_complete_' + mode,
  470. self._completeInvalid)
  471. return modeMethod(message, endpoint, return_to)
  472. def _complete_cancel(self, message, endpoint, _):
  473. return CancelResponse(endpoint)
  474. def _complete_error(self, message, endpoint, _):
  475. error = message.getArg(OPENID_NS, 'error')
  476. contact = message.getArg(OPENID_NS, 'contact')
  477. reference = message.getArg(OPENID_NS, 'reference')
  478. return FailureResponse(endpoint, error, contact=contact,
  479. reference=reference)
  480. def _complete_setup_needed(self, message, endpoint, _):
  481. if not message.isOpenID2():
  482. return self._completeInvalid(message, endpoint, _)
  483. user_setup_url = message.getArg(OPENID2_NS, 'user_setup_url')
  484. return SetupNeededResponse(endpoint, user_setup_url)
  485. def _complete_id_res(self, message, endpoint, return_to):
  486. try:
  487. self._checkSetupNeeded(message)
  488. except SetupNeededError, why:
  489. return SetupNeededResponse(endpoint, why.user_setup_url)
  490. else:
  491. try:
  492. return self._doIdRes(message, endpoint, return_to)
  493. except (ProtocolError, DiscoveryFailure), why:
  494. return FailureResponse(endpoint, why[0])
  495. def _completeInvalid(self, message, endpoint, _):
  496. mode = message.getArg(OPENID_NS, 'mode', '<No mode set>')
  497. return FailureResponse(endpoint,
  498. 'Invalid openid.mode: %r' % (mode,))
  499. def _checkReturnTo(self, message, return_to):
  500. """Check an OpenID message and its openid.return_to value
  501. against a return_to URL from an application. Return True on
  502. success, False on failure.
  503. """
  504. # Check the openid.return_to args against args in the original
  505. # message.
  506. try:
  507. self._verifyReturnToArgs(message.toPostArgs())
  508. except ProtocolError, why:
  509. oidutil.log("Verifying return_to arguments: %s" % (why[0],))
  510. return False
  511. # Check the return_to base URL against the one in the message.
  512. msg_return_to = message.getArg(OPENID_NS, 'return_to')
  513. # The URL scheme, authority, and path MUST be the same between
  514. # the two URLs.
  515. app_parts = urlparse(urinorm.urinorm(return_to))
  516. msg_parts = urlparse(urinorm.urinorm(msg_return_to))
  517. # (addressing scheme, network location, path) must be equal in
  518. # both URLs.
  519. for part in range(0, 3):
  520. if app_parts[part] != msg_parts[part]:
  521. return False
  522. return True
  523. _makeKVPost = staticmethod(makeKVPost)
  524. def _checkSetupNeeded(self, message):
  525. """Check an id_res message to see if it is a
  526. checkid_immediate cancel response.
  527. @raises SetupNeededError: if it is a checkid_immediate cancellation
  528. """
  529. # In OpenID 1, we check to see if this is a cancel from
  530. # immediate mode by the presence of the user_setup_url
  531. # parameter.
  532. if message.isOpenID1():
  533. user_setup_url = message.getArg(OPENID1_NS, 'user_setup_url')
  534. if user_setup_url is not None:
  535. raise SetupNeededError(user_setup_url)
  536. def _doIdRes(self, message, endpoint, return_to):
  537. """Handle id_res responses that are not cancellations of
  538. immediate mode requests.
  539. @param message: the response paramaters.
  540. @param endpoint: the discovered endpoint object. May be None.
  541. @raises ProtocolError: If the message contents are not
  542. well-formed according to the OpenID specification. This
  543. includes missing fields or not signing fields that should
  544. be signed.
  545. @raises DiscoveryFailure: If the subject of the id_res message
  546. does not match the supplied endpoint, and discovery on the
  547. identifier in the message fails (this should only happen
  548. when using OpenID 2)
  549. @returntype: L{Response}
  550. """
  551. # Checks for presence of appropriate fields (and checks
  552. # signed list fields)
  553. self._idResCheckForFields(message)
  554. if not self._checkReturnTo(message, return_to):
  555. raise ProtocolError(
  556. "return_to does not match return URL. Expected %r, got %r"
  557. % (return_to, message.getArg(OPENID_NS, 'return_to')))
  558. # Verify discovery information:
  559. endpoint = self._verifyDiscoveryResults(message, endpoint)
  560. oidutil.log("Received id_res response from %s using association %s" %
  561. (endpoint.server_url,
  562. message.getArg(OPENID_NS, 'assoc_handle')))
  563. self._idResCheckSignature(message, endpoint.server_url)
  564. # Will raise a ProtocolError if the nonce is bad
  565. self._idResCheckNonce(message, endpoint)
  566. signed_list_str = message.getArg(OPENID_NS, 'signed', no_default)
  567. signed_list = signed_list_str.split(',')
  568. signed_fields = ["openid." + s for s in signed_list]
  569. return SuccessResponse(endpoint, message, signed_fields)
  570. def _idResGetNonceOpenID1(self, message, endpoint):
  571. """Extract the nonce from an OpenID 1 response. Return the
  572. nonce from the BARE_NS since we independently check the
  573. return_to arguments are the same as those in the response
  574. message.
  575. See the openid1_nonce_query_arg_name class variable
  576. @returns: The nonce as a string or None
  577. """
  578. return message.getArg(BARE_NS, self.openid1_nonce_query_arg_name)
  579. def _idResCheckNonce(self, message, endpoint):
  580. if message.isOpenID1():
  581. # This indicates that the nonce was generated by the consumer
  582. nonce = self._idResGetNonceOpenID1(message, endpoint)
  583. server_url = ''
  584. else:
  585. nonce = message.getArg(OPENID2_NS, 'response_nonce')
  586. server_url = endpoint.server_url
  587. if nonce is None:
  588. raise ProtocolError('Nonce missing from response')
  589. try:
  590. timestamp, salt = splitNonce(nonce)
  591. except ValueError, why:
  592. raise ProtocolError('Malformed nonce: %s' % (why[0],))
  593. if (self.store is not None and
  594. not self.store.useNonce(server_url, timestamp, salt)):
  595. raise ProtocolError('Nonce already used or out of range')
  596. def _idResCheckSignature(self, message, server_url):
  597. assoc_handle = message.getArg(OPENID_NS, 'assoc_handle')
  598. if self.store is None:
  599. assoc = None
  600. else:
  601. assoc = self.store.getAssociation(server_url, assoc_handle)
  602. if assoc:
  603. if assoc.getExpiresIn() <= 0:
  604. # XXX: It might be a good idea sometimes to re-start the
  605. # authentication with a new association. Doing it
  606. # automatically opens the possibility for
  607. # denial-of-service by a server that just returns expired
  608. # associations (or really short-lived associations)
  609. raise ProtocolError(
  610. 'Association with %s expired' % (server_url,))
  611. if not assoc.checkMessageSignature(message):
  612. raise ProtocolError('Bad signature')
  613. else:
  614. # It's not an association we know about. Stateless mode is our
  615. # only possible path for recovery.
  616. # XXX - async framework will not want to block on this call to
  617. # _checkAuth.
  618. if not self._checkAuth(message, server_url):
  619. raise ProtocolError('Server denied check_authentication')
  620. def _idResCheckForFields(self, message):
  621. # XXX: this should be handled by the code that processes the
  622. # response (that is, if a field is missing, we should not have
  623. # to explicitly check that it's present, just make sure that
  624. # the fields are actually being used by the rest of the code
  625. # in tests). Although, which fields are signed does need to be
  626. # checked somewhere.
  627. basic_fields = ['return_to', 'assoc_handle', 'sig', 'signed']
  628. basic_sig_fields = ['return_to', 'identity']
  629. require_fields = {
  630. OPENID2_NS: basic_fields + ['op_endpoint'],
  631. OPENID1_NS: basic_fields + ['identity'],
  632. }
  633. require_sigs = {
  634. OPENID2_NS: basic_sig_fields + ['response_nonce',
  635. 'claimed_id',
  636. 'assoc_handle',
  637. 'op_endpoint',],
  638. OPENID1_NS: basic_sig_fields,
  639. }
  640. for field in require_fields[message.getOpenIDNamespace()]:
  641. if not message.hasKey(OPENID_NS, field):
  642. raise ProtocolError('Missing required field %r' % (field,))
  643. signed_list_str = message.getArg(OPENID_NS, 'signed', no_default)
  644. signed_list = signed_list_str.split(',')
  645. for field in require_sigs[message.getOpenIDNamespace()]:
  646. # Field is present and not in signed list
  647. if message.hasKey(OPENID_NS, field) and field not in signed_list:
  648. raise ProtocolError('"%s" not signed' % (field,))
  649. def _verifyReturnToArgs(query):
  650. """Verify that the arguments in the return_to URL are present in this
  651. response.
  652. """
  653. message = Message.fromPostArgs(query)
  654. return_to = message.getArg(OPENID_NS, 'return_to')
  655. if return_to is None:
  656. raise ProtocolError('Response has no return_to')
  657. parsed_url = urlparse(return_to)
  658. rt_query = parsed_url[4]
  659. parsed_args = cgi.parse_qsl(rt_query)
  660. for rt_key, rt_value in parsed_args:
  661. try:
  662. value = query[rt_key]
  663. if rt_value != value:
  664. format = ("parameter %s value %r does not match "
  665. "return_to's value %r")
  666. raise ProtocolError(format % (rt_key, value, rt_value))
  667. except KeyError:
  668. format = "return_to parameter %s absent from query %r"
  669. raise ProtocolError(format % (rt_key, query))
  670. # Make sure all non-OpenID arguments in the response are also
  671. # in the signed return_to.
  672. bare_args = message.getArgs(BARE_NS)
  673. for pair in bare_args.iteritems():
  674. if pair not in parsed_args:
  675. raise ProtocolError("Parameter %s not in return_to URL" % (pair[0],))
  676. _verifyReturnToArgs = staticmethod(_verifyReturnToArgs)
  677. def _verifyDiscoveryResults(self, resp_msg, endpoint=None):
  678. """
  679. Extract the information from an OpenID assertion message and
  680. verify it against the original
  681. @param endpoint: The endpoint that resulted from doing discovery
  682. @param resp_msg: The id_res message object
  683. @returns: the verified endpoint
  684. """
  685. if resp_msg.getOpenIDNamespace() == OPENID2_NS:
  686. return self._verifyDiscoveryResultsOpenID2(resp_msg, endpoint)
  687. else:
  688. return self._verifyDiscoveryResultsOpenID1(resp_msg, endpoint)
  689. def _verifyDiscoveryResultsOpenID2(self, resp_msg, endpoint):
  690. to_match = OpenIDServiceEndpoint()
  691. to_match.type_uris = [OPENID_2_0_TYPE]
  692. to_match.claimed_id = resp_msg.getArg(OPENID2_NS, 'claimed_id')
  693. to_match.local_id = resp_msg.getArg(OPENID2_NS, 'identity')
  694. # Raises a KeyError when the op_endpoint is not present
  695. to_match.server_url = resp_msg.getArg(
  696. OPENID2_NS, 'op_endpoint', no_default)
  697. # claimed_id and identifier must both be present or both
  698. # be absent
  699. if (to_match.claimed_id is None and
  700. to_match.local_id is not None):
  701. raise ProtocolError(
  702. 'openid.identity is present without openid.claimed_id')
  703. elif (to_match.claimed_id is not None and
  704. to_match.local_id is None):
  705. raise ProtocolError(
  706. 'openid.claimed_id is present without openid.identity')
  707. # This is a response without identifiers, so there's really no
  708. # checking that we can do, so return an endpoint that's for
  709. # the specified `openid.op_endpoint'
  710. elif to_match.claimed_id is None:
  711. return OpenIDServiceEndpoint.fromOPEndpointURL(to_match.server_url)
  712. # The claimed ID doesn't match, so we have to do discovery
  713. # again. This covers not using sessions, OP identifier
  714. # endpoints and responses that didn't match the original
  715. # request.
  716. if not endpoint:
  717. oidutil.log('No pre-discovered information supplied.')
  718. endpoint = self._discoverAndVerify(to_match.claimed_id, [to_match])
  719. else:
  720. # The claimed ID matches, so we use the endpoint that we
  721. # discovered in initiation. This should be the most common
  722. # case.
  723. try:
  724. self._verifyDiscoverySingle(endpoint, to_match)
  725. except ProtocolError, e:
  726. oidutil.log(
  727. "Error attempting to use stored discovery information: " +
  728. str(e))
  729. oidutil.log("Attempting discovery to verify endpoint")
  730. endpoint = self._discoverAndVerify(
  731. to_match.claimed_id, [to_match])
  732. # The endpoint we return should have the claimed ID from the
  733. # message we just verified, fragment and all.
  734. if endpoint.claimed_id != to_match.claimed_id:
  735. endpoint = copy.copy(endpoint)
  736. endpoint.claimed_id = to_match.claimed_id
  737. return endpoint
  738. def _verifyDiscoveryResultsOpenID1(self, resp_msg, endpoint):
  739. claimed_id = resp_msg.getArg(BARE_NS, self.openid1_return_to_identifier_name)
  740. if endpoint is None and claimed_id is None:
  741. raise RuntimeError(
  742. 'When using OpenID 1, the claimed ID must be supplied, '
  743. 'either by passing it through as a return_to parameter '
  744. 'or by using a session, and supplied to the GenericConsumer '
  745. 'as the argument to complete()')
  746. elif endpoint is not None and claimed_id is None:
  747. claimed_id = endpoint.claimed_id
  748. to_match = OpenIDServiceEndpoint()
  749. to_match.type_uris = [OPENID_1_1_TYPE]
  750. to_match.local_id = resp_msg.getArg(OPENID1_NS, 'identity')
  751. # Restore delegate information from the initiation phase
  752. to_match.claimed_id = claimed_id
  753. if to_match.local_id is None:
  754. raise ProtocolError('Missing required field openid.identity')
  755. to_match_1_0 = copy.copy(to_match)
  756. to_match_1_0.type_uris = [OPENID_1_0_TYPE]
  757. if endpoint is not None:
  758. try:
  759. try:
  760. self._verifyDiscoverySingle(endpoint, to_match)
  761. except TypeURIMismatch:
  762. self._verifyDiscoverySingle(endpoint, to_match_1_0)
  763. except ProtocolError, e:
  764. oidutil.log("Error attempting to use stored discovery information: " +
  765. str(e))
  766. oidutil.log("Attempting discovery to verify endpoint")
  767. else:
  768. return endpoint
  769. # Endpoint is either bad (failed verification) or None
  770. return self._discoverAndVerify(claimed_id, [to_match, to_match_1_0])
  771. def _verifyDiscoverySingle(self, endpoint, to_match):
  772. """Verify that the given endpoint matches the information
  773. extracted from the OpenID assertion, and raise an exception if
  774. there is a mismatch.
  775. @type endpoint: openid.consumer.discover.OpenIDServiceEndpoint
  776. @type to_match: openid.consumer.discover.OpenIDServiceEndpoint
  777. @rtype: NoneType
  778. @raises ProtocolError: when the endpoint does not match the
  779. discovered information.
  780. """
  781. # Every type URI that's in the to_match endpoint has to be
  782. # present in the discovered endpoint.
  783. for type_uri in to_match.type_uris:
  784. if not endpoint.usesExtension(type_uri):
  785. raise TypeURIMismatch(type_uri, endpoint)
  786. # Fragments do not influence discovery, so we can't compare a
  787. # claimed identifier with a fragment to discovered information.
  788. defragged_claimed_id, _ = urldefrag(to_match.claimed_id)
  789. if defragged_claimed_id != endpoint.claimed_id:
  790. raise ProtocolError(
  791. 'Claimed ID does not match (different subjects!), '
  792. 'Expected %s, got %s' %
  793. (defragged_claimed_id, endpoint.claimed_id))
  794. if to_match.getLocalID() != endpoint.getLocalID():
  795. raise ProtocolError('local_id mismatch. Expected %s, got %s' %
  796. (to_match.getLocalID(), endpoint.getLocalID()))
  797. # If the server URL is None, this must be an OpenID 1
  798. # response, because op_endpoint is a required parameter in
  799. # OpenID 2. In that case, we don't actually care what the
  800. # discovered server_url is, because signature checking or
  801. # check_auth should take care of that check for us.
  802. if to_match.server_url is None:
  803. assert to_match.preferredNamespace() == OPENID1_NS, (
  804. """The code calling this must ensure that OpenID 2
  805. responses have a non-none `openid.op_endpoint' and
  806. that it is set as the `server_url' attribute of the
  807. `to_match' endpoint.""")
  808. elif to_match.server_url != endpoint.server_url:
  809. raise ProtocolError('OP Endpoint mismatch. Expected %s, got %s' %
  810. (to_match.server_url, endpoint.server_url))
  811. def _discoverAndVerify(self, claimed_id, to_match_endpoints):
  812. """Given an endpoint object created from the information in an
  813. OpenID response, perform discovery and verify the discovery
  814. results, returning the matching endpoint that is the result of
  815. doing that discovery.
  816. @type to_match: openid.consumer.discover.OpenIDServiceEndpoint
  817. @param to_match: The endpoint whose information we're confirming
  818. @rtype: openid.consumer.discover.OpenIDServiceEndpoint
  819. @returns: The result of performing discovery on the claimed
  820. identifier in `to_match'
  821. @raises DiscoveryFailure: when discovery fails.
  822. """
  823. oidutil.log('Performing discovery on %s' % (claimed_id,))
  824. _, services = self._discover(claimed_id)
  825. if not services:
  826. raise DiscoveryFailure('No OpenID information found at %s' %
  827. (claimed_id,), None)
  828. return self._verifyDiscoveredServices(claimed_id, services,
  829. to_match_endpoints)
  830. def _verifyDiscoveredServices(self, claimed_id, services, to_match_endpoints):
  831. """See @L{_discoverAndVerify}"""
  832. # Search the services resulting from discovery to find one
  833. # that matches the information from the assertion
  834. failure_messages = []
  835. for endpoint in services:
  836. for to_match_endpoint in to_match_endpoints:
  837. try:
  838. self._verifyDiscoverySingle(
  839. endpoint, to_match_endpoint)
  840. except ProtocolError, why:
  841. failure_messages.append(str(why))
  842. else:
  843. # It matches, so discover verification has
  844. # succeeded. Return this endpoint.
  845. return endpoint
  846. else:
  847. oidutil.log('Discovery verification failure for %s' %
  848. (claimed_id,))
  849. for failure_message in failure_messages:
  850. oidutil.log(' * Endpoint mismatch: ' + failure_message)
  851. raise DiscoveryFailure(
  852. 'No matching endpoint found after discovering %s'
  853. % (claimed_id,), None)
  854. def _checkAuth(self, message, server_url):
  855. """Make a check_authentication request to verify this message.
  856. @returns: True if the request is valid.
  857. @rtype: bool
  858. """
  859. oidutil.log('Using OpenID check_authentication')
  860. request = self._createCheckAuthRequest(message)
  861. if request is None:
  862. return False
  863. try:
  864. response = self._makeKVPost(request, server_url)
  865. except (fetchers.HTTPFetchingError, ServerError), e:
  866. oidutil.log('check_authentication failed: %s' % (e[0],))
  867. return False
  868. else:
  869. return self._processCheckAuthResponse(response, server_url)
  870. def _createCheckAuthRequest(self, message):
  871. """Generate a check_authentication request message given an
  872. id_res message.
  873. """
  874. signed = message.getArg(OPENID_NS, 'signed')
  875. if signed:
  876. for k in signed.split(','):
  877. oidutil.log(k)
  878. val = message.getAliasedArg(k)
  879. # Signed value is missing
  880. if val is None:
  881. oidutil.log('Missing signed field %r' % (k,))
  882. return None
  883. check_auth_message = message.copy()
  884. check_auth_message.setArg(OPENID_NS, 'mode', 'check_authentication')
  885. return check_auth_message
  886. def _processCheckAuthResponse(self, response, server_url):
  887. """Process the response message from a check_authentication
  888. request, invalidating associations if requested.
  889. """
  890. is_valid = response.getArg(OPENID_NS, 'is_valid', 'false')
  891. invalidate_handle = response.getArg(OPENID_NS, 'invalidate_handle')
  892. if invalidate_handle is not None:
  893. oidutil.log(
  894. 'Received "invalidate_handle" from server %s' % (server_url,))
  895. if self.store is None:
  896. oidutil.log('Unexpectedly got invalidate_handle without '
  897. 'a store!')
  898. else:
  899. self.store.removeAssociation(server_url, invalidate_handle)
  900. if is_valid == 'true':
  901. return True
  902. else:
  903. oidutil.log('Server responds that checkAuth call is not valid')
  904. return False
  905. def _getAssociation(self, endpoint):
  906. """Get an association for the endpoint's server_url.
  907. First try seeing if we have a good association in the
  908. store. If we do not, then attempt to negotiate an association
  909. with the server.
  910. If we negotiate a good association, it will get stored.
  911. @returns: A valid association for the endpoint's server_url or None
  912. @rtype: openid.association.Association or NoneType
  913. """
  914. assoc = self.store.getAssociation(endpoint.server_url)
  915. if assoc is None or assoc.expiresIn <= 0:
  916. assoc = self._negotiateAssociation(endpoint)
  917. if assoc is not None:
  918. self.store.storeAssociation(endpoint.server_url, assoc)
  919. return assoc
  920. def _negotiateAssociation(self, endpoint):
  921. """Make association requests to the server, attempting to
  922. create a new association.
  923. @returns: a new association object
  924. @rtype: L{openid.association.Association}
  925. """
  926. # Get our preferred session/association type from the negotiatior.
  927. assoc_type, session_type = self.negotiator.getAllowedType()
  928. try:
  929. assoc = self._requestAssociation(
  930. endpoint, assoc_type, session_type)
  931. except ServerError, why:
  932. supportedTypes = self._extractSupportedAssociationType(why,
  933. endpoint,
  934. assoc_type)
  935. if supportedTypes is not None:
  936. assoc_type, session_type = supportedTypes
  937. # Attempt to create an association from the assoc_type
  938. # and session_type that the server told us it
  939. # supported.
  940. try:
  941. assoc = self._requestAssociation(
  942. endpoint, assoc_type, session_type)
  943. except ServerError, why:
  944. # Do not keep trying, since it rejected the
  945. # association type that it told us to use.
  946. oidutil.log('Server %s refused its suggested association '
  947. 'type: session_type=%s, assoc_type=%s'
  948. % (endpoint.server_url, session_type,
  949. assoc_type))
  950. return None
  951. else:
  952. return assoc
  953. else:
  954. return assoc
  955. def _extractSupportedAssociationType(self, server_error, endpoint,
  956. assoc_type):
  957. """Handle ServerErrors resulting from association requests.
  958. @returns: If server replied with an C{unsupported-type} error,
  959. return a tuple of supported C{association_type}, C{session_type}.
  960. Otherwise logs the error and returns None.
  961. @rtype: tuple or None
  962. """
  963. # Any error message whose code is not 'unsupported-type'
  964. # should be considered a total failure.
  965. if server_error.error_code != 'unsupported-type' or \
  966. server_error.message.isOpenID1():
  967. oidutil.log(
  968. 'Server error when requesting an association from %r: %s'
  969. % (endpoint.server_url, server_error.error_text))
  970. return None
  971. # The server didn't like the association/session type
  972. # that we sent, and it sent us back a message that
  973. # might tell us how to handle it.
  974. oidutil.log(
  975. 'Unsupported association type %s: %s' % (assoc_type,
  976. server_error.error_text,))
  977. # Extract the session_type and assoc_type from the
  978. # error message
  979. assoc_type = server_error.message.getArg(OPENID_NS, 'assoc_type')
  980. session_type = server_error.message.getArg(OPENID_NS, 'session_type')
  981. if assoc_type is None or session_type is None:
  982. oidutil.log('Server responded with unsupported association '
  983. 'session but did not supply a fallback.')
  984. return None
  985. elif not self.negotiator.isAllowed(assoc_type, session_type):
  986. fmt = ('Server sent unsupported session/association type: '
  987. 'session_type=%s, assoc_type=%s')
  988. oidutil.log(fmt % (session_type, assoc_type))
  989. return None
  990. else:
  991. return assoc_type, session_type
  992. def _requestAssociation(self, endpoint, assoc_type, session_type):
  993. """Make and process one association request to this endpoint's
  994. OP endpoint URL.
  995. @returns: An association object or None if the association
  996. processing failed.
  997. @raises ServerError: when the remote OpenID server returns an error.
  998. """
  999. assoc_session, args = self._createAssociateRequest(
  1000. endpoint, assoc_type, session_type)
  1001. try:
  1002. response = self._makeKVPost(args, endpoint.server_url)
  1003. except fetchers.HTTPFetchingError, why:
  1004. oidutil.log('openid.associate request failed: %s' % (why[0],))
  1005. return None
  1006. try:
  1007. assoc = self._extractAssociation(response, assoc_session)
  1008. except KeyError, why:
  1009. oidutil.log('Missing required parameter in response from %s: %s'
  1010. % (endpoint.server_url, why[0]))
  1011. return None
  1012. except ProtocolError, why:
  1013. oidutil.log('Protocol error parsing response from %s: %s' % (
  1014. endpoint.server_url, why[0]))
  1015. return None
  1016. else:
  1017. return assoc
  1018. def _createAssociateRequest(self, endpoint, assoc_type, session_type):
  1019. """Create an association request for the given assoc_type and
  1020. session_type.
  1021. @param endpoint: The endpoint whose server_url will be
  1022. queried. The important bit about the endpoint is whether
  1023. it's in compatiblity mode (OpenID 1.1)
  1024. @param assoc_type: The association type that the request
  1025. should ask for.
  1026. @type assoc_type: str
  1027. @param session_type: The session type that should be used in
  1028. the association request. The session_type is used to
  1029. create an association session object, and that session
  1030. object is asked for any additional fields that it needs to
  1031. add to the request.
  1032. @type session_type: str
  1033. @returns: a pair of the association session object and the
  1034. request message that will be sent to the server.
  1035. @rtype: (association session type (depends on session_type),
  1036. openid.message.Message)
  1037. """
  1038. session_type_class = self.session_types[session_type]
  1039. assoc_session = session_type_class()
  1040. args = {
  1041. 'mode': 'associate',
  1042. 'assoc_type': assoc_type,
  1043. }
  1044. if not endpoint.compatibilityMode():
  1045. args['ns'] = OPENID2_NS
  1046. # Leave out the session type if we're in compatibility mode
  1047. # *and* it's no-encryption.
  1048. if (not endpoint.compatibilityMode() or
  1049. assoc_session.session_type != 'no-encryption'):
  1050. args['session_type'] = assoc_session.session_type
  1051. args.update(assoc_session.getRequest())
  1052. message = Message.fromOpenIDArgs(args)
  1053. return assoc_session, message
  1054. def _getOpenID1SessionType(self, assoc_response):
  1055. """Given an association response message, extract the OpenID
  1056. 1.X session type.
  1057. This function mostly takes care of the 'no-encryption' default
  1058. behavior in OpenID 1.
  1059. If the association type is plain-text, this function will
  1060. return 'no-encryption'
  1061. @returns: The association type for this message
  1062. @rtype: str
  1063. @raises KeyError: when the session_type field is absent.
  1064. """
  1065. # If it's an OpenID 1 message, allow session_type to default
  1066. # to None (which signifies "no-encryption")
  1067. session_type = assoc_response.getArg(OPENID1_NS, 'session_type')
  1068. # Handle the differences between no-encryption association
  1069. # respones in OpenID 1 and 2:
  1070. # no-encryption is not really a valid session type for
  1071. # OpenID 1, but we'll accept it anyway, while issuing a
  1072. # warning.
  1073. if session_type == 'no-encryption':
  1074. oidutil.log('WARNING: OpenID server sent "no-encryption"'
  1075. 'for OpenID 1.X')
  1076. # Missing or empty session type is the way to flag a
  1077. # 'no-encryption' response. Change the session type to
  1078. # 'no-encryption' so that it can be handled in the same
  1079. # way as OpenID 2 'no-encryption' respones.
  1080. elif session_type == '' or session_type is None:
  1081. session_type = 'no-encryption'
  1082. return session_type
  1083. def _extractAssociation(self, assoc_response, assoc_session):
  1084. """Attempt to extract an association from the response, given
  1085. the association response message and the established
  1086. association session.
  1087. @param assoc_response: The association response message from
  1088. the server
  1089. @type assoc_response: openid.message.Message
  1090. @param assoc_session: The association session object that was
  1091. used when making the request
  1092. @type assoc_session: depends on the session type of the request
  1093. @raises ProtocolError: when data is malformed
  1094. @raises KeyError: when a field is missing
  1095. @rtype: openid.association.Association
  1096. """
  1097. # Extract the common fields from the response, raising an
  1098. # exception if they are not found
  1099. assoc_type = assoc_response.getArg(
  1100. OPENID_NS, 'assoc_type', no_default)
  1101. assoc_handle = assoc_response.getArg(
  1102. OPENID_NS, 'assoc_handle', no_default)
  1103. # expires_in is a base-10 string. The Python parsing will
  1104. # accept literals that have whitespace around them and will
  1105. # accept negative values. Neither of these are really in-spec,
  1106. # but we think it's OK to accept them.
  1107. expires_in_str = assoc_response.getArg(
  1108. OPENID_NS, 'expires_in', no_default)
  1109. try:
  1110. expires_in = int(expires_in_str)
  1111. except ValueError, why:
  1112. raise ProtocolError('Invalid expires_in field: %s' % (why[0],))
  1113. # OpenID 1 has funny association session behaviour.
  1114. if assoc_response.isOpenID1():
  1115. session_type = self._getOpenID1SessionType(assoc_response)
  1116. else:
  1117. session_type = assoc_response.getArg(
  1118. OPENID2_NS, 'session_type', no_default)
  1119. # Session type mismatch
  1120. if assoc_session.session_type != session_type:
  1121. if (assoc_response.isOpenID1() and
  1122. session_type == 'no-encryption'):
  1123. # In OpenID 1, any association request can result in a
  1124. # 'no-encryption' association response. Setting
  1125. # assoc_session to a new no-encryption session should
  1126. # make the rest of this function work properly for
  1127. # that case.
  1128. assoc_session = PlainTextConsumerSession()
  1129. else:
  1130. # Any other mismatch, regardless of protocol version
  1131. # results in the failure of the association session
  1132. # altogether.
  1133. fmt = 'Session type mismatch. Expected %r, got %r'
  1134. message = fmt % (assoc_session.session_type, session_type)
  1135. raise ProtocolError(message)
  1136. # Make sure assoc_type is valid for session_type
  1137. if assoc_type not in assoc_session.allowed_assoc_types:
  1138. fmt = 'Unsupported assoc_type for session %s returned: %s'
  1139. raise ProtocolError(fmt % (assoc_session.session_type, assoc_type))
  1140. # Delegate to the association session to extract the secret
  1141. # from the response, however is appropriate for that session
  1142. # type.
  1143. try:
  1144. secret = assoc_session.extractSecret(assoc_response)
  1145. except ValueError, why:
  1146. fmt = 'Malformed response for %s session: %s'
  1147. raise ProtocolError(fmt % (assoc_session.session_type, why[0]))
  1148. return Association.fromExpiresIn(
  1149. expires_in, assoc_handle, secret, assoc_type)
  1150. class AuthRequest(object):
  1151. """An object that holds the state necessary for generating an
  1152. OpenID authentication request. This object holds the association
  1153. with the server and the discovered information with which the
  1154. request will be made.
  1155. It is separate from the consumer because you may wish to add
  1156. things to the request before sending it on its way to the
  1157. server. It also has serialization options that let you encode the
  1158. authentication request as a URL or as a form POST.
  1159. """
  1160. def __init__(self, endpoint, assoc):
  1161. """
  1162. Creates a new AuthRequest object. This just stores each
  1163. argument in an appropriately named field.
  1164. Users of this library should not create instances of this
  1165. class. Instances of this class are created by the library
  1166. when needed.
  1167. """
  1168. self.assoc = assoc
  1169. self.endpoint = endpoint
  1170. self.return_to_args = {}
  1171. self.message = Message(endpoint.preferredNamespace())
  1172. self._anonymous = False
  1173. def setAnonymous(self, is_anonymous):
  1174. """Set whether this request should be made anonymously. If a
  1175. request is anonymous, the identifier will not be sent in the
  1176. request. This is only useful if you are making another kind of
  1177. request with an extension in this request.
  1178. Anonymous requests are not allowed when the request is made
  1179. with OpenID 1.
  1180. @raises ValueError: when attempting to set an OpenID1 request
  1181. as anonymous
  1182. """
  1183. if is_anonymous and self.message.isOpenID1():
  1184. raise ValueError('OpenID 1 requests MUST include the '
  1185. 'identifier in the request')
  1186. else:
  1187. self._anonymous = is_anonymous
  1188. def addExtension(self, extension_request):
  1189. """Add an extension to this checkid request.
  1190. @param extension_request: An object that implements the
  1191. extension interface for adding arguments to an OpenID
  1192. message.
  1193. """
  1194. extension_request.toMessage(self.message)
  1195. def addExtensionArg(self, namespace, key, value):
  1196. """Add an extension argument to this OpenID authentication
  1197. request.
  1198. Use caution when adding arguments, because they will be
  1199. URL-escaped and appended to the redirect URL, which can easily
  1200. get quite long.
  1201. @param namespace: The namespace for the extension. For
  1202. example, the simple registration extension uses the
  1203. namespace C{sreg}.
  1204. @type namespace: str
  1205. @param key: The key within the extension namespace. For
  1206. example, the nickname field in the simple registration
  1207. extension's key is C{nickname}.
  1208. @type key: str
  1209. @param value: The value to provide to the server for this
  1210. argument.
  1211. @type value: str
  1212. """
  1213. self.message.setArg(namespace, key, value)
  1214. def getMessage(self, realm, return_to=None, immediate=False):
  1215. """Produce a L{openid.message.Message} representing this request.
  1216. @param realm: The URL (or URL pattern) that identifies your
  1217. web site to the user when she is authorizing it.
  1218. @type realm: str
  1219. @param return_to: The URL that the OpenID provider will send the
  1220. user back to after attempting to verify her identity.
  1221. Not specifying a return_to URL means that the user will not
  1222. be returned to the site issuing the request upon its
  1223. completion.
  1224. @type return_to: str
  1225. @param immediate: If True, the OpenID provider is to send back
  1226. a response immediately, useful for behind-the-scenes
  1227. authentication attempts. Otherwise the OpenID provider
  1228. may engage the user before providing a response. This is
  1229. the default case, as the user may need to provide
  1230. credentials or approve the request before a positive
  1231. response can be sent.
  1232. @type immediate: bool
  1233. @returntype: L{openid.message.Message}
  1234. """
  1235. if return_to:
  1236. return_to = oidutil.appendArgs(return_to, self.return_to_args)
  1237. elif immediate:
  1238. raise ValueError(
  1239. '"return_to" is mandatory when using "checkid_immediate"')
  1240. elif self.message.isOpenID1():
  1241. raise ValueError('"return_to" is mandatory for OpenID 1 requests')
  1242. elif self.return_to_args:
  1243. raise ValueError('extra "return_to" arguments were specified, '
  1244. 'but no return_to was specified')
  1245. if immediate:
  1246. mode = 'checkid_immediate'
  1247. else:
  1248. mode = 'checkid_setup'
  1249. message = self.message.copy()
  1250. if message.isOpenID1():
  1251. realm_key = 'trust_root'
  1252. else:
  1253. realm_key = 'realm'
  1254. message.updateArgs(OPENID_NS,
  1255. {
  1256. realm_key:realm,
  1257. 'mode':mode,
  1258. 'return_to':return_to,
  1259. })
  1260. if not self._anonymous:
  1261. if self.endpoint.isOPIdentifier():
  1262. # This will never happen when we're in compatibility
  1263. # mode, as long as isOPIdentifier() returns False
  1264. # whenever preferredNamespace() returns OPENID1_NS.
  1265. claimed_id = request_identity = IDENTIFIER_SELECT
  1266. else:
  1267. request_identity = self.endpoint.getLocalID()
  1268. claimed_id = self.endpoint.claimed_id
  1269. # This is true for both OpenID 1 and 2
  1270. message.setArg(OPENID_NS, 'identity', request_identity)
  1271. if message.isOpenID2():
  1272. message.setArg(OPENID2_NS, 'claimed_id', claimed_id)
  1273. if self.assoc:
  1274. message.setArg(OPENID_NS, 'assoc_handle', self.assoc.handle)
  1275. assoc_log_msg = 'with assocication %s' % (self.assoc.handle,)
  1276. else:
  1277. assoc_log_msg = 'using stateless mode.'
  1278. oidutil.log("Generated %s request to %s %s" %
  1279. (mode, self.endpoint.server_url, assoc_log_msg))
  1280. return message
  1281. def redirectURL(self, realm, return_to=None, immediate=False):
  1282. """Returns a URL with an encoded OpenID request.
  1283. The resulting URL is the OpenID provider's endpoint URL with
  1284. parameters appended as query arguments. You should redirect
  1285. the user agent to this URL.
  1286. OpenID 2.0 endpoints also accept POST requests, see
  1287. C{L{shouldSendRedirect}} and C{L{formMarkup}}.
  1288. @param realm: The URL (or URL pattern) that identifies your
  1289. web site to the user when she is authorizing it.
  1290. @type realm: str
  1291. @param return_to: The URL that the OpenID provider will send the
  1292. user back to after attempting to verify her identity.
  1293. Not specifying a return_to URL means that the user will not
  1294. be returned to the site issuing the request upon its
  1295. completion.
  1296. @type return_to: str
  1297. @param immediate: If True, the OpenID provider is to send back
  1298. a response immediately, useful for behind-the-scenes
  1299. authentication attempts. Otherwise the OpenID provider
  1300. may engage the user before providing a response. This is
  1301. the default case, as the user may need to provide
  1302. credentials or approve the request before a positive
  1303. response can be sent.
  1304. @type immediate: bool
  1305. @returns: The URL to redirect the user agent to.
  1306. @returntype: str
  1307. """
  1308. message = self.getMessage(realm, return_to, immediate)
  1309. return message.toURL(self.endpoint.server_url)
  1310. def formMarkup(self, realm, return_to=None, immediate=False,
  1311. form_tag_attrs=None):
  1312. """Get html for a form to submit this request to the IDP.
  1313. @param form_tag_attrs: Dictionary of attributes to be added to
  1314. the form tag. 'accept-charset' and 'enctype' have defaults
  1315. that can be overridden. If a value is supplied for
  1316. 'action' or 'method', it will be replaced.
  1317. @type form_tag_attrs: {unicode: unicode}
  1318. """
  1319. message = self.getMessage(realm, return_to, immediate)
  1320. return message.toFormMarkup(self.endpoint.server_url,
  1321. form_tag_attrs)
  1322. def htmlMarkup(self, realm, return_to=None, immediate=False,
  1323. form_tag_attrs=None):
  1324. """Get an autosubmitting HTML page that submits this request to the
  1325. IDP. This is just a wrapper for formMarkup.
  1326. @see: formMarkup
  1327. @returns: str
  1328. """
  1329. return oidutil.autoSubmitHTML(self.formMarkup(realm,
  1330. return_to,
  1331. immediate,
  1332. form_tag_attrs))
  1333. def shouldSendRedirect(self):
  1334. """Should this OpenID authentication request be sent as a HTTP
  1335. redirect or as a POST (form submission)?
  1336. @rtype: bool
  1337. """
  1338. return self.endpoint.compatibilityMode()
  1339. FAILURE = 'failure'
  1340. SUCCESS = 'success'
  1341. CANCEL = 'cancel'
  1342. SETUP_NEEDED = 'setup_needed'
  1343. class Response(object):
  1344. status = None
  1345. def setEndpoint(self, endpoint):
  1346. self.endpoint = endpoint
  1347. if endpoint is None:
  1348. self.identity_url = None
  1349. else:
  1350. self.identity_url = endpoint.claimed_id
  1351. def getDisplayIdentifier(self):
  1352. """Return the display identifier for this response.
  1353. The display identifier is related to the Claimed Identifier, but the
  1354. two are not always identical. The display identifier is something the
  1355. user should recognize as what they entered, whereas the response's
  1356. claimed identifier (in the L{identity_url} attribute) may have extra
  1357. information for better persistence.
  1358. URLs will be stripped of their fragments for display. XRIs will
  1359. display the human-readable identifier (i-name) instead of the
  1360. persistent identifier (i-number).
  1361. Use the display identifier in your user interface. Use
  1362. L{identity_url} for querying your database or authorization server.
  1363. """
  1364. if self.endpoint is not None:
  1365. return self.endpoint.getDisplayIdentifier()
  1366. return None
  1367. class SuccessResponse(Response):
  1368. """A response with a status of SUCCESS. Indicates that this request is a
  1369. successful acknowledgement from the OpenID server that the
  1370. supplied URL is, indeed controlled by the requesting agent.
  1371. @ivar identity_url: The identity URL that has been authenticated; the Claimed Identifier.
  1372. See also L{getDisplayIdentifier}.
  1373. @ivar endpoint: The endpoint that authenticated the identifier. You
  1374. may access other discovered information related to this endpoint,
  1375. such as the CanonicalID of an XRI, through this object.
  1376. @type endpoint: L{OpenIDServiceEndpoint<openid.consumer.discover.OpenIDServiceEndpoint>}
  1377. @ivar signed_fields: The arguments in the server's response that
  1378. were signed and verified.
  1379. @cvar status: SUCCESS
  1380. """
  1381. status = SUCCESS
  1382. def __init__(self, endpoint, message, signed_fields=None):
  1383. # Don't use setEndpoint, because endpoint should never be None
  1384. # for a successfull transaction.
  1385. self.endpoint = endpoint
  1386. self.identity_url = endpoint.claimed_id
  1387. self.message = message
  1388. if signed_fields is None:
  1389. signed_fields = []
  1390. self.signed_fields = signed_fields
  1391. def isOpenID1(self):
  1392. """Was this authentication response an OpenID 1 authentication
  1393. response?
  1394. """
  1395. return self.message.isOpenID1()
  1396. def isSigned(self, ns_uri, ns_key):
  1397. """Return whether a particular key is signed, regardless of
  1398. its namespace alias
  1399. """
  1400. return self.message.getKey(ns_uri, ns_key) in self.signed_fields
  1401. def getSigned(self, ns_uri, ns_key, default=None):
  1402. """Return the specified signed field if available,
  1403. otherwise return default
  1404. """
  1405. if self.isSigned(ns_uri, ns_key):
  1406. return self.message.getArg(ns_uri, ns_key, default)
  1407. else:
  1408. return default
  1409. def getSignedNS(self, ns_uri):
  1410. """Get signed arguments from the response message. Return a
  1411. dict of all arguments in the specified namespace. If any of
  1412. the arguments are not signed, return None.
  1413. """
  1414. msg_args = self.message.getArgs(ns_uri)
  1415. for key in msg_args.iterkeys():
  1416. if not self.isSigned(ns_uri, key):
  1417. oidutil.log("SuccessResponse.getSignedNS: (%s, %s) not signed."
  1418. % (ns_uri, key))
  1419. return None
  1420. return msg_args
  1421. def extensionResponse(self, namespace_uri, require_signed):
  1422. """Return response arguments in the specified namespace.
  1423. @param namespace_uri: The namespace URI of the arguments to be
  1424. returned.
  1425. @param require_signed: True if the arguments should be among
  1426. those signed in the response, False if you don't care.
  1427. If require_signed is True and the arguments are not signed,
  1428. return None.
  1429. """
  1430. if require_signed:
  1431. return self.getSignedNS(namespace_uri)
  1432. else:
  1433. return self.message.getArgs(namespace_uri)
  1434. def getReturnTo(self):
  1435. """Get the openid.return_to argument from this response.
  1436. This is useful for verifying that this request was initiated
  1437. by this consumer.
  1438. @returns: The return_to URL supplied to the server on the
  1439. initial request, or C{None} if the response did not contain
  1440. an C{openid.return_to} argument.
  1441. @returntype: str
  1442. """
  1443. return self.getSigned(OPENID_NS, 'return_to')
  1444. def __eq__(self, other):
  1445. return (
  1446. (self.endpoint == other.endpoint) and
  1447. (self.identity_url == other.identity_url) and
  1448. (self.message == other.message) and
  1449. (self.signed_fields == other.signed_fields) and
  1450. (self.status == other.status))
  1451. def __ne__(self, other):
  1452. return not (self == other)
  1453. def __repr__(self):
  1454. return '<%s.%s id=%r signed=%r>' % (
  1455. self.__class__.__module__,
  1456. self.__class__.__name__,
  1457. self.identity_url, self.signed_fields)
  1458. class FailureResponse(Response):
  1459. """A response with a status of FAILURE. Indicates that the OpenID
  1460. protocol has failed. This could be locally or remotely triggered.
  1461. @ivar identity_url: The identity URL for which authenitcation was
  1462. attempted, if it can be determined. Otherwise, None.
  1463. @ivar message: A message indicating why the request failed, if one
  1464. is supplied. otherwise, None.
  1465. @cvar status: FAILURE
  1466. """
  1467. status = FAILURE
  1468. def __init__(self, endpoint, message=None, contact=None,
  1469. reference=None):
  1470. self.setEndpoint(endpoint)
  1471. self.message = message
  1472. self.contact = contact
  1473. self.reference = reference
  1474. def __repr__(self):
  1475. return "<%s.%s id=%r message=%r>" % (
  1476. self.__class__.__module__, self.__class__.__name__,
  1477. self.identity_url, self.message)
  1478. class CancelResponse(Response):
  1479. """A response with a status of CANCEL. Indicates that the user
  1480. cancelled the OpenID authentication request.
  1481. @ivar identity_url: The identity URL for which authenitcation was
  1482. attempted, if it can be determined. Otherwise, None.
  1483. @cvar status: CANCEL
  1484. """
  1485. status = CANCEL
  1486. def __init__(self, endpoint):
  1487. self.setEndpoint(endpoint)
  1488. class SetupNeededResponse(Response):
  1489. """A response with a status of SETUP_NEEDED. Indicates that the
  1490. request was in immediate mode, and the server is unable to
  1491. authenticate the user without further interaction.
  1492. @ivar identity_url: The identity URL for which authenitcation was
  1493. attempted.
  1494. @ivar setup_url: A URL that can be used to send the user to the
  1495. server to set up for authentication. The user should be
  1496. redirected in to the setup_url, either in the current window
  1497. or in a new browser window. C{None} in OpenID 2.0.
  1498. @cvar status: SETUP_NEEDED
  1499. """
  1500. status = SETUP_NEEDED
  1501. def __init__(self, endpoint, setup_url=None):
  1502. self.setEndpoint(endpoint)
  1503. self.setup_url = setup_url