1
0

server.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824
  1. # -*- test-case-name: openid.test.test_server -*-
  2. """OpenID server protocol and logic.
  3. Overview
  4. ========
  5. An OpenID server must perform three tasks:
  6. 1. Examine the incoming request to determine its nature and validity.
  7. 2. Make a decision about how to respond to this request.
  8. 3. Format the response according to the protocol.
  9. The first and last of these tasks may performed by
  10. the L{decodeRequest<Server.decodeRequest>} and
  11. L{encodeResponse<Server.encodeResponse>} methods of the
  12. L{Server} object. Who gets to do the intermediate task -- deciding
  13. how to respond to the request -- will depend on what type of request it
  14. is.
  15. If it's a request to authenticate a user (a X{C{checkid_setup}} or
  16. X{C{checkid_immediate}} request), you need to decide if you will assert
  17. that this user may claim the identity in question. Exactly how you do
  18. that is a matter of application policy, but it generally involves making
  19. sure the user has an account with your system and is logged in, checking
  20. to see if that identity is hers to claim, and verifying with the user that
  21. she does consent to releasing that information to the party making the
  22. request.
  23. Examine the properties of the L{CheckIDRequest} object, optionally
  24. check L{CheckIDRequest.returnToVerified}, and and when you've come
  25. to a decision, form a response by calling L{CheckIDRequest.answer}.
  26. Other types of requests relate to establishing associations between client
  27. and server and verifying the authenticity of previous communications.
  28. L{Server} contains all the logic and data necessary to respond to
  29. such requests; just pass the request to L{Server.handleRequest}.
  30. OpenID Extensions
  31. =================
  32. Do you want to provide other information for your users
  33. in addition to authentication? Version 2.0 of the OpenID
  34. protocol allows consumers to add extensions to their requests.
  35. For example, with sites using the U{Simple Registration
  36. Extension<http://openid.net/specs/openid-simple-registration-extension-1_0.html>},
  37. a user can agree to have their nickname and e-mail address sent to a
  38. site when they sign up.
  39. Since extensions do not change the way OpenID authentication works,
  40. code to handle extension requests may be completely separate from the
  41. L{OpenIDRequest} class here. But you'll likely want data sent back by
  42. your extension to be signed. L{OpenIDResponse} provides methods with
  43. which you can add data to it which can be signed with the other data in
  44. the OpenID signature.
  45. For example::
  46. # when request is a checkid_* request
  47. response = request.answer(True)
  48. # this will a signed 'openid.sreg.timezone' parameter to the response
  49. # as well as a namespace declaration for the openid.sreg namespace
  50. response.fields.setArg('http://openid.net/sreg/1.0', 'timezone', 'America/Los_Angeles')
  51. There are helper modules for a number of extensions, including
  52. L{Attribute Exchange<openid.extensions.ax>},
  53. L{PAPE<openid.extensions.pape>}, and
  54. L{Simple Registration<openid.extensions.sreg>} in the L{openid.extensions}
  55. package.
  56. Stores
  57. ======
  58. The OpenID server needs to maintain state between requests in order
  59. to function. Its mechanism for doing this is called a store. The
  60. store interface is defined in C{L{openid.store.interface.OpenIDStore}}.
  61. Additionally, several concrete store implementations are provided, so that
  62. most sites won't need to implement a custom store. For a store backed
  63. by flat files on disk, see C{L{openid.store.filestore.FileOpenIDStore}}.
  64. For stores based on MySQL or SQLite, see the C{L{openid.store.sqlstore}}
  65. module.
  66. Upgrading
  67. =========
  68. From 1.0 to 1.1
  69. ---------------
  70. The keys by which a server looks up associations in its store have changed
  71. in version 1.2 of this library. If your store has entries created from
  72. version 1.0 code, you should empty it.
  73. From 1.1 to 2.0
  74. ---------------
  75. One of the additions to the OpenID protocol was a specified nonce
  76. format for one-way nonces. As a result, the nonce table in the store
  77. has changed. You'll need to run contrib/upgrade-store-1.1-to-2.0 to
  78. upgrade your store, or you'll encounter errors about the wrong number
  79. of columns in the oid_nonces table.
  80. If you've written your own custom store or code that interacts
  81. directly with it, you'll need to review the change notes in
  82. L{openid.store.interface}.
  83. @group Requests: OpenIDRequest, AssociateRequest, CheckIDRequest,
  84. CheckAuthRequest
  85. @group Responses: OpenIDResponse
  86. @group HTTP Codes: HTTP_OK, HTTP_REDIRECT, HTTP_ERROR
  87. @group Response Encodings: ENCODE_KVFORM, ENCODE_HTML_FORM, ENCODE_URL
  88. """
  89. import time
  90. import warnings
  91. import logging
  92. from copy import deepcopy
  93. from openid import cryptutil
  94. from openid import oidutil
  95. from openid import kvform
  96. from openid.dh import DiffieHellman
  97. from openid.store.nonce import mkNonce
  98. from openid.server.trustroot import TrustRoot, verifyReturnTo
  99. from openid.association import Association, default_negotiator, getSecretSize
  100. from openid.message import Message, InvalidOpenIDNamespace, \
  101. OPENID_NS, OPENID2_NS, IDENTIFIER_SELECT, OPENID1_URL_LIMIT
  102. from openid.urinorm import urinorm
  103. logger = logging.getLogger(__name__)
  104. HTTP_OK = 200
  105. HTTP_REDIRECT = 302
  106. HTTP_ERROR = 400
  107. BROWSER_REQUEST_MODES = ['checkid_setup', 'checkid_immediate']
  108. ENCODE_KVFORM = ('kvform', )
  109. ENCODE_URL = ('URL/redirect', )
  110. ENCODE_HTML_FORM = ('HTML form', )
  111. UNUSED = None
  112. class OpenIDRequest(object):
  113. """I represent an incoming OpenID request.
  114. @cvar mode: the C{X{openid.mode}} of this request.
  115. @type mode: str
  116. """
  117. mode = None
  118. class CheckAuthRequest(OpenIDRequest):
  119. """A request to verify the validity of a previous response.
  120. @cvar mode: "X{C{check_authentication}}"
  121. @type mode: str
  122. @ivar assoc_handle: The X{association handle} the response was signed with.
  123. @type assoc_handle: str
  124. @ivar signed: The message with the signature which wants checking.
  125. @type signed: L{Message}
  126. @ivar invalidate_handle: An X{association handle} the client is asking
  127. about the validity of. Optional, may be C{None}.
  128. @type invalidate_handle: str
  129. @see: U{OpenID Specs, Mode: check_authentication
  130. <http://openid.net/specs.bml#mode-check_authentication>}
  131. """
  132. mode = "check_authentication"
  133. required_fields = ["identity", "return_to", "response_nonce"]
  134. def __init__(self, assoc_handle, signed, invalidate_handle=None):
  135. """Construct me.
  136. These parameters are assigned directly as class attributes, see
  137. my L{class documentation<CheckAuthRequest>} for their descriptions.
  138. @type assoc_handle: str
  139. @type signed: L{Message}
  140. @type invalidate_handle: str
  141. """
  142. self.assoc_handle = assoc_handle
  143. self.signed = signed
  144. self.invalidate_handle = invalidate_handle
  145. self.namespace = OPENID2_NS
  146. @classmethod
  147. def fromMessage(klass, message, op_endpoint=UNUSED):
  148. """Construct me from an OpenID Message.
  149. @param message: An OpenID check_authentication Message
  150. @type message: L{openid.message.Message}
  151. @returntype: L{CheckAuthRequest}
  152. """
  153. self = klass.__new__(klass)
  154. self.message = message
  155. self.namespace = message.getOpenIDNamespace()
  156. self.assoc_handle = message.getArg(OPENID_NS, 'assoc_handle')
  157. self.sig = message.getArg(OPENID_NS, 'sig')
  158. if (self.assoc_handle is None or self.sig is None):
  159. fmt = "%s request missing required parameter from message %s"
  160. raise ProtocolError(message, text=fmt % (self.mode, message))
  161. self.invalidate_handle = message.getArg(OPENID_NS, 'invalidate_handle')
  162. self.signed = message.copy()
  163. # openid.mode is currently check_authentication because
  164. # that's the mode of this request. But the signature
  165. # was made on something with a different openid.mode.
  166. # http://article.gmane.org/gmane.comp.web.openid.general/537
  167. if self.signed.hasKey(OPENID_NS, "mode"):
  168. self.signed.setArg(OPENID_NS, "mode", "id_res")
  169. return self
  170. def answer(self, signatory):
  171. """Respond to this request.
  172. Given a L{Signatory}, I can check the validity of the signature and
  173. the X{C{invalidate_handle}}.
  174. @param signatory: The L{Signatory} to use to check the signature.
  175. @type signatory: L{Signatory}
  176. @returns: A response with an X{C{is_valid}} (and, if
  177. appropriate X{C{invalidate_handle}}) field.
  178. @returntype: L{OpenIDResponse}
  179. """
  180. is_valid = signatory.verify(self.assoc_handle, self.signed)
  181. # Now invalidate that assoc_handle so it this checkAuth message cannot
  182. # be replayed.
  183. signatory.invalidate(self.assoc_handle, dumb=True)
  184. response = OpenIDResponse(self)
  185. valid_str = (is_valid and "true") or "false"
  186. response.fields.setArg(OPENID_NS, 'is_valid', valid_str)
  187. if self.invalidate_handle:
  188. assoc = signatory.getAssociation(
  189. self.invalidate_handle, dumb=False)
  190. if not assoc:
  191. response.fields.setArg(OPENID_NS, 'invalidate_handle',
  192. self.invalidate_handle)
  193. return response
  194. def __str__(self):
  195. if self.invalidate_handle:
  196. ih = " invalidate? %r" % (self.invalidate_handle, )
  197. else:
  198. ih = ""
  199. s = "<%s handle: %r sig: %r: signed: %r%s>" % (
  200. self.__class__.__name__, self.assoc_handle, self.sig, self.signed,
  201. ih)
  202. return s
  203. class PlainTextServerSession(object):
  204. """An object that knows how to handle association requests with no
  205. session type.
  206. @cvar session_type: The session_type for this association
  207. session. There is no type defined for plain-text in the OpenID
  208. specification, so we use 'no-encryption'.
  209. @type session_type: str
  210. @see: U{OpenID Specs, Mode: associate
  211. <http://openid.net/specs.bml#mode-associate>}
  212. @see: AssociateRequest
  213. """
  214. session_type = 'no-encryption'
  215. allowed_assoc_types = ['HMAC-SHA1', 'HMAC-SHA256']
  216. def fromMessage(cls, unused_request):
  217. return cls()
  218. fromMessage = classmethod(fromMessage)
  219. def answer(self, secret):
  220. return {'mac_key': oidutil.toBase64(secret)}
  221. class DiffieHellmanSHA1ServerSession(object):
  222. """An object that knows how to handle association requests with the
  223. Diffie-Hellman session type.
  224. @cvar session_type: The session_type for this association
  225. session.
  226. @type session_type: str
  227. @ivar dh: The Diffie-Hellman algorithm values for this request
  228. @type dh: DiffieHellman
  229. @ivar consumer_pubkey: The public key sent by the consumer in the
  230. associate request
  231. @type consumer_pubkey: long
  232. @see: U{OpenID Specs, Mode: associate
  233. <http://openid.net/specs.bml#mode-associate>}
  234. @see: AssociateRequest
  235. """
  236. session_type = 'DH-SHA1'
  237. hash_func = staticmethod(cryptutil.sha1)
  238. allowed_assoc_types = ['HMAC-SHA1']
  239. def __init__(self, dh, consumer_pubkey):
  240. self.dh = dh
  241. self.consumer_pubkey = consumer_pubkey
  242. def fromMessage(cls, message):
  243. """
  244. @param message: The associate request message
  245. @type message: openid.message.Message
  246. @returntype: L{DiffieHellmanSHA1ServerSession}
  247. @raises ProtocolError: When parameters required to establish the
  248. session are missing.
  249. """
  250. dh_modulus = message.getArg(OPENID_NS, 'dh_modulus')
  251. dh_gen = message.getArg(OPENID_NS, 'dh_gen')
  252. if (dh_modulus is None and dh_gen is not None or dh_gen is None and
  253. dh_modulus is not None):
  254. if dh_modulus is None:
  255. missing = 'modulus'
  256. else:
  257. missing = 'generator'
  258. raise ProtocolError(
  259. message, 'If non-default modulus or generator is '
  260. 'supplied, both must be supplied. Missing %s' % (missing, ))
  261. if dh_modulus or dh_gen:
  262. dh_modulus = cryptutil.base64ToLong(dh_modulus)
  263. dh_gen = cryptutil.base64ToLong(dh_gen)
  264. dh = DiffieHellman(dh_modulus, dh_gen)
  265. else:
  266. dh = DiffieHellman.fromDefaults()
  267. consumer_pubkey = message.getArg(OPENID_NS, 'dh_consumer_public')
  268. if consumer_pubkey is None:
  269. raise ProtocolError(message, "Public key for DH-SHA1 session "
  270. "not found in message %s" % (message, ))
  271. consumer_pubkey = cryptutil.base64ToLong(consumer_pubkey)
  272. return cls(dh, consumer_pubkey)
  273. fromMessage = classmethod(fromMessage)
  274. def answer(self, secret):
  275. mac_key = self.dh.xorSecret(self.consumer_pubkey, secret,
  276. self.hash_func)
  277. return {
  278. 'dh_server_public': cryptutil.longToBase64(self.dh.public),
  279. 'enc_mac_key': oidutil.toBase64(mac_key),
  280. }
  281. class DiffieHellmanSHA256ServerSession(DiffieHellmanSHA1ServerSession):
  282. session_type = 'DH-SHA256'
  283. hash_func = staticmethod(cryptutil.sha256)
  284. allowed_assoc_types = ['HMAC-SHA256']
  285. class AssociateRequest(OpenIDRequest):
  286. """A request to establish an X{association}.
  287. @cvar mode: "X{C{check_authentication}}"
  288. @type mode: str
  289. @ivar assoc_type: The type of association. The protocol currently only
  290. defines one value for this, "X{C{HMAC-SHA1}}".
  291. @type assoc_type: str
  292. @ivar session: An object that knows how to handle association
  293. requests of a certain type.
  294. @see: U{OpenID Specs, Mode: associate
  295. <http://openid.net/specs.bml#mode-associate>}
  296. """
  297. mode = "associate"
  298. session_classes = {
  299. 'no-encryption': PlainTextServerSession,
  300. 'DH-SHA1': DiffieHellmanSHA1ServerSession,
  301. 'DH-SHA256': DiffieHellmanSHA256ServerSession,
  302. }
  303. def __init__(self, session, assoc_type):
  304. """Construct me.
  305. The session is assigned directly as a class attribute. See my
  306. L{class documentation<AssociateRequest>} for its description.
  307. """
  308. super(AssociateRequest, self).__init__()
  309. self.session = session
  310. self.assoc_type = assoc_type
  311. self.namespace = OPENID2_NS
  312. def fromMessage(klass, message, op_endpoint=UNUSED):
  313. """Construct me from an OpenID Message.
  314. @param message: The OpenID associate request
  315. @type message: openid.message.Message
  316. @returntype: L{AssociateRequest}
  317. """
  318. if message.isOpenID1():
  319. session_type = message.getArg(OPENID_NS, 'session_type')
  320. if session_type == 'no-encryption':
  321. logger.warning(
  322. 'Received OpenID 1 request with a no-encryption '
  323. 'assocaition session type. Continuing anyway.')
  324. elif not session_type:
  325. session_type = 'no-encryption'
  326. else:
  327. session_type = message.getArg(OPENID2_NS, 'session_type')
  328. if session_type is None:
  329. raise ProtocolError(
  330. message, text="session_type missing from request")
  331. try:
  332. session_class = klass.session_classes[session_type]
  333. except KeyError:
  334. raise ProtocolError(message,
  335. "Unknown session type %r" % (session_type, ))
  336. try:
  337. session = session_class.fromMessage(message)
  338. except ValueError as why:
  339. raise ProtocolError(message, 'Error parsing %s session: %s' %
  340. (session_class.session_type, why))
  341. assoc_type = message.getArg(OPENID_NS, 'assoc_type', 'HMAC-SHA1')
  342. if assoc_type not in session.allowed_assoc_types:
  343. fmt = 'Session type %s does not support association type %s'
  344. raise ProtocolError(message, fmt % (session_type, assoc_type))
  345. self = klass(session, assoc_type)
  346. self.message = message
  347. self.namespace = message.getOpenIDNamespace()
  348. return self
  349. fromMessage = classmethod(fromMessage)
  350. def answer(self, assoc):
  351. """Respond to this request with an X{association}.
  352. @param assoc: The association to send back.
  353. @type assoc: L{openid.association.Association}
  354. @returns: A response with the association information, encrypted
  355. to the consumer's X{public key} if appropriate.
  356. @returntype: L{OpenIDResponse}
  357. """
  358. response = OpenIDResponse(self)
  359. response.fields.updateArgs(OPENID_NS, {
  360. 'expires_in': str(assoc.expiresIn),
  361. 'assoc_type': self.assoc_type,
  362. 'assoc_handle': assoc.handle,
  363. })
  364. response.fields.updateArgs(OPENID_NS,
  365. self.session.answer(assoc.secret))
  366. if not (self.session.session_type == 'no-encryption' and
  367. self.message.isOpenID1()):
  368. # The session type "no-encryption" did not have a name
  369. # in OpenID v1, it was just omitted.
  370. response.fields.setArg(OPENID_NS, 'session_type',
  371. self.session.session_type)
  372. return response
  373. def answerUnsupported(self,
  374. message,
  375. preferred_association_type=None,
  376. preferred_session_type=None):
  377. """Respond to this request indicating that the association
  378. type or association session type is not supported."""
  379. if self.message.isOpenID1():
  380. raise ProtocolError(self.message)
  381. response = OpenIDResponse(self)
  382. response.fields.setArg(OPENID_NS, 'error_code', 'unsupported-type')
  383. response.fields.setArg(OPENID_NS, 'error', message)
  384. if preferred_association_type:
  385. response.fields.setArg(OPENID_NS, 'assoc_type',
  386. preferred_association_type)
  387. if preferred_session_type:
  388. response.fields.setArg(OPENID_NS, 'session_type',
  389. preferred_session_type)
  390. return response
  391. class CheckIDRequest(OpenIDRequest):
  392. """A request to confirm the identity of a user.
  393. This class handles requests for openid modes X{C{checkid_immediate}}
  394. and X{C{checkid_setup}}.
  395. @cvar mode: "X{C{checkid_immediate}}" or "X{C{checkid_setup}}"
  396. @type mode: str
  397. @ivar immediate: Is this an immediate-mode request?
  398. @type immediate: bool
  399. @ivar identity: The OP-local identifier being checked.
  400. @type identity: str
  401. @ivar claimed_id: The claimed identifier. Not present in OpenID 1.x
  402. messages.
  403. @type claimed_id: str
  404. @ivar trust_root: "Are you Frank?" asks the checkid request. "Who wants
  405. to know?" C{trust_root}, that's who. This URL identifies the party
  406. making the request, and the user will use that to make her decision
  407. about what answer she trusts them to have. Referred to as "realm" in
  408. OpenID 2.0.
  409. @type trust_root: str
  410. @ivar return_to: The URL to send the user agent back to to reply to this
  411. request.
  412. @type return_to: str
  413. @ivar assoc_handle: Provided in smart mode requests, a handle for a
  414. previously established association. C{None} for dumb mode requests.
  415. @type assoc_handle: str
  416. """
  417. def __init__(self,
  418. identity,
  419. return_to,
  420. trust_root=None,
  421. immediate=False,
  422. assoc_handle=None,
  423. op_endpoint=None,
  424. claimed_id=None):
  425. """Construct me.
  426. These parameters are assigned directly as class attributes, see
  427. my L{class documentation<CheckIDRequest>} for their descriptions.
  428. @raises MalformedReturnURL: When the C{return_to} URL is not a URL.
  429. """
  430. self.assoc_handle = assoc_handle
  431. self.identity = identity
  432. self.claimed_id = claimed_id or identity
  433. self.return_to = return_to
  434. self.trust_root = trust_root or return_to
  435. self.op_endpoint = op_endpoint
  436. assert self.op_endpoint is not None
  437. if immediate:
  438. self.immediate = True
  439. self.mode = "checkid_immediate"
  440. else:
  441. self.immediate = False
  442. self.mode = "checkid_setup"
  443. if self.return_to is not None and \
  444. not TrustRoot.parse(self.return_to):
  445. raise MalformedReturnURL(None, self.return_to)
  446. if not self.trustRootValid():
  447. raise UntrustedReturnURL(None, self.return_to, self.trust_root)
  448. self.message = None
  449. def _getNamespace(self):
  450. warnings.warn(
  451. 'The "namespace" attribute of CheckIDRequest objects '
  452. 'is deprecated. Use "message.getOpenIDNamespace()" '
  453. 'instead',
  454. DeprecationWarning,
  455. stacklevel=2)
  456. return self.message.getOpenIDNamespace()
  457. namespace = property(_getNamespace)
  458. def fromMessage(klass, message, op_endpoint):
  459. """Construct me from an OpenID message.
  460. @raises ProtocolError: When not all required parameters are present
  461. in the message.
  462. @raises MalformedReturnURL: When the C{return_to} URL is not a URL.
  463. @raises UntrustedReturnURL: When the C{return_to} URL is outside
  464. the C{trust_root}.
  465. @param message: An OpenID checkid_* request Message
  466. @type message: openid.message.Message
  467. @param op_endpoint: The endpoint URL of the server that this
  468. message was sent to.
  469. @type op_endpoint: str
  470. @returntype: L{CheckIDRequest}
  471. """
  472. self = klass.__new__(klass)
  473. self.message = message
  474. self.op_endpoint = op_endpoint
  475. mode = message.getArg(OPENID_NS, 'mode')
  476. if mode == "checkid_immediate":
  477. self.immediate = True
  478. self.mode = "checkid_immediate"
  479. else:
  480. self.immediate = False
  481. self.mode = "checkid_setup"
  482. self.return_to = message.getArg(OPENID_NS, 'return_to')
  483. if message.isOpenID1() and not self.return_to:
  484. fmt = "Missing required field 'return_to' from %r"
  485. raise ProtocolError(message, text=fmt % (message, ))
  486. self.identity = message.getArg(OPENID_NS, 'identity')
  487. self.claimed_id = message.getArg(OPENID_NS, 'claimed_id')
  488. if message.isOpenID1():
  489. if self.identity is None:
  490. s = "OpenID 1 message did not contain openid.identity"
  491. raise ProtocolError(message, text=s)
  492. else:
  493. if self.identity and not self.claimed_id:
  494. s = ("OpenID 2.0 message contained openid.identity but not "
  495. "claimed_id")
  496. raise ProtocolError(message, text=s)
  497. elif self.claimed_id and not self.identity:
  498. s = ("OpenID 2.0 message contained openid.claimed_id but not "
  499. "identity")
  500. raise ProtocolError(message, text=s)
  501. # There's a case for making self.trust_root be a TrustRoot
  502. # here. But if TrustRoot isn't currently part of the "public" API,
  503. # I'm not sure it's worth doing.
  504. if message.isOpenID1():
  505. trust_root_param = 'trust_root'
  506. else:
  507. trust_root_param = 'realm'
  508. # Using 'or' here is slightly different than sending a default
  509. # argument to getArg, as it will treat no value and an empty
  510. # string as equivalent.
  511. self.trust_root = (message.getArg(OPENID_NS, trust_root_param) or
  512. self.return_to)
  513. if not message.isOpenID1():
  514. if self.return_to is self.trust_root is None:
  515. raise ProtocolError(
  516. message,
  517. "openid.realm required when " + "openid.return_to absent")
  518. self.assoc_handle = message.getArg(OPENID_NS, 'assoc_handle')
  519. # Using TrustRoot.parse here is a bit misleading, as we're not
  520. # parsing return_to as a trust root at all. However, valid URLs
  521. # are valid trust roots, so we can use this to get an idea if it
  522. # is a valid URL. Not all trust roots are valid return_to URLs,
  523. # however (particularly ones with wildcards), so this is still a
  524. # little sketchy.
  525. if self.return_to is not None and \
  526. not TrustRoot.parse(self.return_to):
  527. raise MalformedReturnURL(message, self.return_to)
  528. # I first thought that checking to see if the return_to is within
  529. # the trust_root is premature here, a logic-not-decoding thing. But
  530. # it was argued that this is really part of data validation. A
  531. # request with an invalid trust_root/return_to is broken regardless of
  532. # application, right?
  533. if not self.trustRootValid():
  534. raise UntrustedReturnURL(message, self.return_to, self.trust_root)
  535. return self
  536. fromMessage = classmethod(fromMessage)
  537. def idSelect(self):
  538. """Is the identifier to be selected by the IDP?
  539. @returntype: bool
  540. """
  541. # So IDPs don't have to import the constant
  542. return self.identity == IDENTIFIER_SELECT
  543. def trustRootValid(self):
  544. """Is my return_to under my trust_root?
  545. @returntype: bool
  546. """
  547. if not self.trust_root:
  548. return True
  549. tr = TrustRoot.parse(self.trust_root)
  550. if tr is None:
  551. raise MalformedTrustRoot(self.message, self.trust_root)
  552. if self.return_to is not None:
  553. return tr.validateURL(self.return_to)
  554. else:
  555. return True
  556. def returnToVerified(self):
  557. """Does the relying party publish the return_to URL for this
  558. response under the realm? It is up to the provider to set a
  559. policy for what kinds of realms should be allowed. This
  560. return_to URL verification reduces vulnerability to data-theft
  561. attacks based on open proxies, cross-site-scripting, or open
  562. redirectors.
  563. This check should only be performed after making sure that the
  564. return_to URL matches the realm.
  565. @see: L{trustRootValid}
  566. @raises openid.yadis.discover.DiscoveryFailure: if the realm
  567. URL does not support Yadis discovery (and so does not
  568. support the verification process).
  569. @raises openid.fetchers.HTTPFetchingError: if the realm URL
  570. is not reachable. When this is the case, the RP may be hosted
  571. on the user's intranet.
  572. @returntype: bool
  573. @returns: True if the realm publishes a document with the
  574. return_to URL listed
  575. @since: 2.1.0
  576. """
  577. return verifyReturnTo(self.trust_root, self.return_to)
  578. def answer(self, allow, server_url=None, identity=None, claimed_id=None):
  579. """Respond to this request.
  580. @param allow: Allow this user to claim this identity, and allow the
  581. consumer to have this information?
  582. @type allow: bool
  583. @param server_url: DEPRECATED. Passing C{op_endpoint} to the
  584. L{Server} constructor makes this optional.
  585. When an OpenID 1.x immediate mode request does not succeed,
  586. it gets back a URL where the request may be carried out
  587. in a not-so-immediate fashion. Pass my URL in here (the
  588. fully qualified address of this server's endpoint, i.e.
  589. C{http://example.com/server}), and I will use it as a base for the
  590. URL for a new request.
  591. Optional for requests where C{CheckIDRequest.immediate} is C{False}
  592. or C{allow} is C{True}.
  593. @type server_url: str
  594. @param identity: The OP-local identifier to answer with. Only for use
  595. when the relying party requested identifier selection.
  596. @type identity: str or None
  597. @param claimed_id: The claimed identifier to answer with, for use
  598. with identifier selection in the case where the claimed identifier
  599. and the OP-local identifier differ, i.e. when the claimed_id uses
  600. delegation.
  601. If C{identity} is provided but this is not, C{claimed_id} will
  602. default to the value of C{identity}. When answering requests
  603. that did not ask for identifier selection, the response
  604. C{claimed_id} will default to that of the request.
  605. This parameter is new in OpenID 2.0.
  606. @type claimed_id: str or None
  607. @returntype: L{OpenIDResponse}
  608. @change: Version 2.0 deprecates C{server_url} and adds C{claimed_id}.
  609. @raises NoReturnError: when I do not have a return_to.
  610. """
  611. assert self.message is not None
  612. if not self.return_to:
  613. raise NoReturnToError
  614. if not server_url:
  615. if not self.message.isOpenID1() and not self.op_endpoint:
  616. # In other words, that warning I raised in Server.__init__?
  617. # You should pay attention to it now.
  618. raise RuntimeError("%s should be constructed with op_endpoint "
  619. "to respond to OpenID 2.0 messages." %
  620. (self, ))
  621. server_url = self.op_endpoint
  622. if allow:
  623. mode = 'id_res'
  624. elif self.message.isOpenID1():
  625. if self.immediate:
  626. mode = 'id_res'
  627. else:
  628. mode = 'cancel'
  629. else:
  630. if self.immediate:
  631. mode = 'setup_needed'
  632. else:
  633. mode = 'cancel'
  634. response = OpenIDResponse(self)
  635. if claimed_id and self.message.isOpenID1():
  636. namespace = self.message.getOpenIDNamespace()
  637. raise VersionError("claimed_id is new in OpenID 2.0 and not "
  638. "available for %s" % (namespace, ))
  639. if allow:
  640. if self.identity == IDENTIFIER_SELECT:
  641. if not identity:
  642. raise ValueError(
  643. "This request uses IdP-driven identifier selection."
  644. "You must supply an identifier in the response.")
  645. response_identity = identity
  646. response_claimed_id = claimed_id or identity
  647. elif self.identity:
  648. if identity and (self.identity != identity):
  649. normalized_request_identity = urinorm(self.identity)
  650. normalized_answer_identity = urinorm(identity)
  651. if (normalized_request_identity !=
  652. normalized_answer_identity):
  653. raise ValueError(
  654. "Request was for identity %r, cannot reply "
  655. "with identity %r" % (self.identity, identity))
  656. # The "identity" value in the response shall always be
  657. # the same as that in the request, otherwise the RP is
  658. # likely to not validate the response.
  659. response_identity = self.identity
  660. response_claimed_id = self.claimed_id
  661. else:
  662. if identity:
  663. raise ValueError(
  664. "This request specified no identity and you "
  665. "supplied %r" % (identity, ))
  666. response_identity = None
  667. if self.message.isOpenID1() and response_identity is None:
  668. raise ValueError(
  669. "Request was an OpenID 1 request, so response must "
  670. "include an identifier.")
  671. response.fields.updateArgs(OPENID_NS, {
  672. 'mode': mode,
  673. 'return_to': self.return_to,
  674. 'response_nonce': mkNonce(),
  675. })
  676. if server_url:
  677. response.fields.setArg(OPENID_NS, 'op_endpoint', server_url)
  678. if response_identity is not None:
  679. response.fields.setArg(OPENID_NS, 'identity',
  680. response_identity)
  681. if self.message.isOpenID2():
  682. response.fields.setArg(OPENID_NS, 'claimed_id',
  683. response_claimed_id)
  684. else:
  685. response.fields.setArg(OPENID_NS, 'mode', mode)
  686. if self.immediate:
  687. if self.message.isOpenID1() and not server_url:
  688. raise ValueError("setup_url is required for allow=False "
  689. "in OpenID 1.x immediate mode.")
  690. # Make a new request just like me, but with immediate=False.
  691. setup_request = self.__class__(
  692. self.identity,
  693. self.return_to,
  694. self.trust_root,
  695. immediate=False,
  696. assoc_handle=self.assoc_handle,
  697. op_endpoint=self.op_endpoint,
  698. claimed_id=self.claimed_id)
  699. # XXX: This API is weird.
  700. setup_request.message = self.message
  701. setup_url = setup_request.encodeToURL(server_url)
  702. response.fields.setArg(OPENID_NS, 'user_setup_url', setup_url)
  703. return response
  704. def encodeToURL(self, server_url):
  705. """Encode this request as a URL to GET.
  706. @param server_url: URL of the OpenID server to make this request of.
  707. @type server_url: str
  708. @returntype: str
  709. @raises NoReturnError: when I do not have a return_to.
  710. """
  711. if not self.return_to:
  712. raise NoReturnToError
  713. # Imported from the alternate reality where these classes are used
  714. # in both the client and server code, so Requests are Encodable too.
  715. # That's right, code imported from alternate realities all for the
  716. # love of you, id_res/user_setup_url.
  717. q = {
  718. 'mode': self.mode,
  719. 'identity': self.identity,
  720. 'claimed_id': self.claimed_id,
  721. 'return_to': self.return_to
  722. }
  723. if self.trust_root:
  724. if self.message.isOpenID1():
  725. q['trust_root'] = self.trust_root
  726. else:
  727. q['realm'] = self.trust_root
  728. if self.assoc_handle:
  729. q['assoc_handle'] = self.assoc_handle
  730. response = Message(self.message.getOpenIDNamespace())
  731. response.updateArgs(OPENID_NS, q)
  732. return response.toURL(server_url)
  733. def getCancelURL(self):
  734. """Get the URL to cancel this request.
  735. Useful for creating a "Cancel" button on a web form so that operation
  736. can be carried out directly without another trip through the server.
  737. (Except you probably want to make another trip through the server so
  738. that it knows that the user did make a decision. Or you could simulate
  739. this method by doing C{.answer(False).encodeToURL()})
  740. @returntype: str
  741. @returns: The return_to URL with openid.mode = cancel.
  742. @raises NoReturnError: when I do not have a return_to.
  743. """
  744. if not self.return_to:
  745. raise NoReturnToError
  746. if self.immediate:
  747. raise ValueError("Cancel is not an appropriate response to "
  748. "immediate mode requests.")
  749. response = Message(self.message.getOpenIDNamespace())
  750. response.setArg(OPENID_NS, 'mode', 'cancel')
  751. return response.toURL(self.return_to)
  752. def __repr__(self):
  753. return '<%s id:%r im:%s tr:%r ah:%r>' % (
  754. self.__class__.__name__, self.identity, self.immediate,
  755. self.trust_root, self.assoc_handle)
  756. class OpenIDResponse(object):
  757. """I am a response to an OpenID request.
  758. @ivar request: The request I respond to.
  759. @type request: L{OpenIDRequest}
  760. @ivar fields: My parameters as a dictionary with each key mapping to
  761. one value. Keys are parameter names with no leading "C{openid.}".
  762. e.g. "C{identity}" and "C{mac_key}", never "C{openid.identity}".
  763. @type fields: L{openid.message.Message}
  764. @ivar signed: The names of the fields which should be signed.
  765. @type signed: list of str
  766. """
  767. # Implementer's note: In a more symmetric client/server
  768. # implementation, there would be more types of OpenIDResponse
  769. # object and they would have validated attributes according to the
  770. # type of response. But as it is, Response objects in a server are
  771. # basically write-only, their only job is to go out over the wire,
  772. # so this is just a loose wrapper around OpenIDResponse.fields.
  773. def __init__(self, request):
  774. """Make a response to an L{OpenIDRequest}.
  775. @type request: L{OpenIDRequest}
  776. """
  777. self.request = request
  778. self.fields = Message(request.namespace)
  779. def __str__(self):
  780. return "%s for %s: %s" % (self.__class__.__name__,
  781. self.request.__class__.__name__, self.fields)
  782. def toFormMarkup(self, form_tag_attrs=None):
  783. """Returns the form markup for this response.
  784. @param form_tag_attrs: Dictionary of attributes to be added to
  785. the form tag. 'accept-charset' and 'enctype' have defaults
  786. that can be overridden. If a value is supplied for
  787. 'action' or 'method', it will be replaced.
  788. @returntype: str
  789. @since: 2.1.0
  790. """
  791. return self.fields.toFormMarkup(
  792. self.request.return_to, form_tag_attrs=form_tag_attrs)
  793. def toHTML(self, form_tag_attrs=None):
  794. """Returns an HTML document that auto-submits the form markup
  795. for this response.
  796. @returntype: str
  797. @see: toFormMarkup
  798. @since: 2.1.?
  799. """
  800. return oidutil.autoSubmitHTML(self.toFormMarkup(form_tag_attrs))
  801. def renderAsForm(self):
  802. """Returns True if this response's encoding is
  803. ENCODE_HTML_FORM. Convenience method for server authors.
  804. @returntype: bool
  805. @since: 2.1.0
  806. """
  807. return self.whichEncoding() == ENCODE_HTML_FORM
  808. def needsSigning(self):
  809. """Does this response require signing?
  810. @returntype: bool
  811. """
  812. return self.fields.getArg(OPENID_NS, 'mode') == 'id_res'
  813. # implements IEncodable
  814. def whichEncoding(self):
  815. """How should I be encoded?
  816. @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM.
  817. @change: 2.1.0 added the ENCODE_HTML_FORM response.
  818. """
  819. if self.request.mode in BROWSER_REQUEST_MODES:
  820. if self.fields.getOpenIDNamespace() == OPENID2_NS and \
  821. len(self.encodeToURL()) > OPENID1_URL_LIMIT:
  822. return ENCODE_HTML_FORM
  823. else:
  824. return ENCODE_URL
  825. else:
  826. return ENCODE_KVFORM
  827. def encodeToURL(self):
  828. """Encode a response as a URL for the user agent to GET.
  829. You will generally use this URL with a HTTP redirect.
  830. @returns: A URL to direct the user agent back to.
  831. @returntype: str
  832. """
  833. return self.fields.toURL(self.request.return_to)
  834. def addExtension(self, extension_response):
  835. """
  836. Add an extension response to this response message.
  837. @param extension_response: An object that implements the
  838. extension interface for adding arguments to an OpenID
  839. message.
  840. @type extension_response: L{openid.extension}
  841. @returntype: None
  842. """
  843. extension_response.toMessage(self.fields)
  844. def encodeToKVForm(self):
  845. """Encode a response in key-value colon/newline format.
  846. This is a machine-readable format used to respond to messages which
  847. came directly from the consumer and not through the user agent.
  848. @see: OpenID Specs,
  849. U{Key-Value Colon/Newline format<http://openid.net/specs.bml#keyvalue>}
  850. @returntype: str
  851. """
  852. return self.fields.toKVForm()
  853. class WebResponse(object):
  854. """I am a response to an OpenID request in terms a web server understands.
  855. I generally come from an L{Encoder}, either directly or from
  856. L{Server.encodeResponse}.
  857. @ivar code: The HTTP code of this response.
  858. @type code: int
  859. @ivar headers: Headers to include in this response.
  860. @type headers: dict
  861. @ivar body: The body of this response.
  862. @type body: str
  863. """
  864. def __init__(self, code=HTTP_OK, headers=None, body=b""):
  865. """Construct me.
  866. These parameters are assigned directly as class attributes, see
  867. my L{class documentation<WebResponse>} for their descriptions.
  868. """
  869. self.code = code
  870. if headers is not None:
  871. self.headers = headers
  872. else:
  873. self.headers = {}
  874. if isinstance(body, bytes):
  875. body = str(body, encoding="utf-8")
  876. self.body = body
  877. class Signatory(object):
  878. """I sign things.
  879. I also check signatures.
  880. All my state is encapsulated in an
  881. L{OpenIDStore<openid.store.interface.OpenIDStore>}, which means
  882. I'm not generally pickleable but I am easy to reconstruct.
  883. @cvar SECRET_LIFETIME: The number of seconds a secret remains valid.
  884. @type SECRET_LIFETIME: int
  885. """
  886. SECRET_LIFETIME = 14 * 24 * 60 * 60 # 14 days, in seconds
  887. # keys have a bogus server URL in them because the filestore
  888. # really does expect that key to be a URL. This seems a little
  889. # silly for the server store, since I expect there to be only one
  890. # server URL.
  891. _normal_key = 'http://localhost/|normal'
  892. _dumb_key = 'http://localhost/|dumb'
  893. def __init__(self, store):
  894. """Create a new Signatory.
  895. @param store: The back-end where my associations are stored.
  896. @type store: L{openid.store.interface.OpenIDStore}
  897. """
  898. assert store is not None
  899. self.store = store
  900. def verify(self, assoc_handle, message):
  901. """Verify that the signature for some data is valid.
  902. @param assoc_handle: The handle of the association used to sign the
  903. data.
  904. @type assoc_handle: str
  905. @param message: The signed message to verify
  906. @type message: openid.message.Message
  907. @returns: C{True} if the signature is valid, C{False} if not.
  908. @returntype: bool
  909. """
  910. assoc = self.getAssociation(assoc_handle, dumb=True)
  911. if not assoc:
  912. logger.error("failed to get assoc with handle %r to verify "
  913. "message %r" % (assoc_handle, message))
  914. return False
  915. try:
  916. valid = assoc.checkMessageSignature(message)
  917. except ValueError as ex:
  918. logger.exception("Error in verifying %s with %s: %s" %
  919. (message, assoc, ex))
  920. return False
  921. return valid
  922. def sign(self, response):
  923. """Sign a response.
  924. I take a L{OpenIDResponse}, create a signature for everything
  925. in its L{signed<OpenIDResponse.signed>} list, and return a new
  926. copy of the response object with that signature included.
  927. @param response: A response to sign.
  928. @type response: L{OpenIDResponse}
  929. @returns: A signed copy of the response.
  930. @returntype: L{OpenIDResponse}
  931. """
  932. signed_response = deepcopy(response)
  933. assoc_handle = response.request.assoc_handle
  934. if assoc_handle:
  935. # normal mode
  936. # disabling expiration check because even if the association
  937. # is expired, we still need to know some properties of the
  938. # association so that we may preserve those properties when
  939. # creating the fallback association.
  940. assoc = self.getAssociation(
  941. assoc_handle, dumb=False, checkExpiration=False)
  942. if not assoc or assoc.expiresIn <= 0:
  943. # fall back to dumb mode
  944. signed_response.fields.setArg(OPENID_NS, 'invalidate_handle',
  945. assoc_handle)
  946. assoc_type = assoc and assoc.assoc_type or 'HMAC-SHA1'
  947. if assoc and assoc.expiresIn <= 0:
  948. # now do the clean-up that the disabled checkExpiration
  949. # code didn't get to do.
  950. self.invalidate(assoc_handle, dumb=False)
  951. assoc = self.createAssociation(
  952. dumb=True, assoc_type=assoc_type)
  953. else:
  954. # dumb mode.
  955. assoc = self.createAssociation(dumb=True)
  956. try:
  957. signed_response.fields = assoc.signMessage(signed_response.fields)
  958. except kvform.KVFormError as err:
  959. raise EncodingError(response, explanation=str(err))
  960. return signed_response
  961. def createAssociation(self, dumb=True, assoc_type='HMAC-SHA1'):
  962. """Make a new association.
  963. @param dumb: Is this association for a dumb-mode transaction?
  964. @type dumb: bool
  965. @param assoc_type: The type of association to create. Currently
  966. there is only one type defined, C{HMAC-SHA1}.
  967. @type assoc_type: str
  968. @returns: the new association.
  969. @returntype: L{openid.association.Association}
  970. """
  971. secret = cryptutil.getBytes(getSecretSize(assoc_type))
  972. uniq = oidutil.toBase64(cryptutil.getBytes(4))
  973. handle = '{%s}{%x}{%s}' % (assoc_type, int(time.time()), uniq)
  974. assoc = Association.fromExpiresIn(self.SECRET_LIFETIME, handle, secret,
  975. assoc_type)
  976. if dumb:
  977. key = self._dumb_key
  978. else:
  979. key = self._normal_key
  980. self.store.storeAssociation(key, assoc)
  981. return assoc
  982. def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
  983. """Get the association with the specified handle.
  984. @type assoc_handle: str
  985. @param dumb: Is this association used with dumb mode?
  986. @type dumb: bool
  987. @returns: the association, or None if no valid association with that
  988. handle was found.
  989. @returntype: L{openid.association.Association}
  990. """
  991. # Hmm. We've created an interface that deals almost entirely with
  992. # assoc_handles. The only place outside the Signatory that uses this
  993. # (and thus the only place that ever sees Association objects) is
  994. # when creating a response to an association request, as it must have
  995. # the association's secret.
  996. if assoc_handle is None:
  997. raise ValueError("assoc_handle must not be None")
  998. if dumb:
  999. key = self._dumb_key
  1000. else:
  1001. key = self._normal_key
  1002. assoc = self.store.getAssociation(key, assoc_handle)
  1003. if assoc is not None and assoc.expiresIn <= 0:
  1004. logger.info("requested %sdumb key %r is expired (by %s seconds)" %
  1005. ((not dumb) and 'not-' or '', assoc_handle,
  1006. assoc.expiresIn))
  1007. if checkExpiration:
  1008. self.store.removeAssociation(key, assoc_handle)
  1009. assoc = None
  1010. return assoc
  1011. def invalidate(self, assoc_handle, dumb):
  1012. """Invalidates the association with the given handle.
  1013. @type assoc_handle: str
  1014. @param dumb: Is this association used with dumb mode?
  1015. @type dumb: bool
  1016. """
  1017. if dumb:
  1018. key = self._dumb_key
  1019. else:
  1020. key = self._normal_key
  1021. self.store.removeAssociation(key, assoc_handle)
  1022. class Encoder(object):
  1023. """I encode responses in to L{WebResponses<WebResponse>}.
  1024. If you don't like L{WebResponses<WebResponse>}, you can do
  1025. your own handling of L{OpenIDResponses<OpenIDResponse>} with
  1026. L{OpenIDResponse.whichEncoding}, L{OpenIDResponse.encodeToURL}, and
  1027. L{OpenIDResponse.encodeToKVForm}.
  1028. """
  1029. responseFactory = WebResponse
  1030. def encode(self, response):
  1031. """Encode a response to a L{WebResponse}.
  1032. @raises EncodingError: When I can't figure out how to encode this
  1033. message.
  1034. """
  1035. encode_as = response.whichEncoding()
  1036. if encode_as == ENCODE_KVFORM:
  1037. wr = self.responseFactory(body=response.encodeToKVForm())
  1038. if isinstance(response, Exception):
  1039. wr.code = HTTP_ERROR
  1040. elif encode_as == ENCODE_URL:
  1041. location = response.encodeToURL()
  1042. wr = self.responseFactory(
  1043. code=HTTP_REDIRECT, headers={'location': location})
  1044. elif encode_as == ENCODE_HTML_FORM:
  1045. wr = self.responseFactory(code=HTTP_OK, body=response.toHTML())
  1046. else:
  1047. # Can't encode this to a protocol message. You should probably
  1048. # render it to HTML and show it to the user.
  1049. raise EncodingError(response)
  1050. return wr
  1051. class SigningEncoder(Encoder):
  1052. """I encode responses in to L{WebResponses<WebResponse>}, signing them when required.
  1053. """
  1054. def __init__(self, signatory):
  1055. """Create a L{SigningEncoder}.
  1056. @param signatory: The L{Signatory} I will make signatures with.
  1057. @type signatory: L{Signatory}
  1058. """
  1059. self.signatory = signatory
  1060. def encode(self, response):
  1061. """Encode a response to a L{WebResponse}, signing it first if appropriate.
  1062. @raises EncodingError: When I can't figure out how to encode this
  1063. message.
  1064. @raises AlreadySigned: When this response is already signed.
  1065. @returntype: L{WebResponse}
  1066. """
  1067. # the isinstance is a bit of a kludge... it means there isn't really
  1068. # an adapter to make the interfaces quite match.
  1069. if (not isinstance(response, Exception)) and response.needsSigning():
  1070. if not self.signatory:
  1071. raise ValueError("Must have a store to sign this request: %s" %
  1072. (response, ), response)
  1073. if response.fields.hasKey(OPENID_NS, 'sig'):
  1074. raise AlreadySigned(response)
  1075. response = self.signatory.sign(response)
  1076. return super(SigningEncoder, self).encode(response)
  1077. class Decoder(object):
  1078. """I decode an incoming web request in to a L{OpenIDRequest}.
  1079. """
  1080. _handlers = {
  1081. 'checkid_setup': CheckIDRequest.fromMessage,
  1082. 'checkid_immediate': CheckIDRequest.fromMessage,
  1083. 'check_authentication': CheckAuthRequest.fromMessage,
  1084. 'associate': AssociateRequest.fromMessage,
  1085. }
  1086. def __init__(self, server):
  1087. """Construct a Decoder.
  1088. @param server: The server which I am decoding requests for.
  1089. (Necessary because some replies reference their server.)
  1090. @type server: L{Server}
  1091. """
  1092. self.server = server
  1093. def decode(self, query):
  1094. """I transform query parameters into an L{OpenIDRequest}.
  1095. If the query does not seem to be an OpenID request at all, I return
  1096. C{None}.
  1097. @param query: The query parameters as a dictionary with each
  1098. key mapping to one value.
  1099. @type query: dict
  1100. @raises ProtocolError: When the query does not seem to be a valid
  1101. OpenID request.
  1102. @returntype: L{OpenIDRequest}
  1103. """
  1104. if not query:
  1105. return None
  1106. try:
  1107. message = Message.fromPostArgs(query)
  1108. except InvalidOpenIDNamespace as err:
  1109. # It's useful to have a Message attached to a ProtocolError, so we
  1110. # override the bad ns value to build a Message out of it. Kinda
  1111. # kludgy, since it's made of lies, but the parts that aren't lies
  1112. # are more useful than a 'None'.
  1113. query = query.copy()
  1114. query['openid.ns'] = OPENID2_NS
  1115. message = Message.fromPostArgs(query)
  1116. raise ProtocolError(message, str(err))
  1117. mode = message.getArg(OPENID_NS, 'mode')
  1118. if not mode:
  1119. fmt = "No mode value in message %s"
  1120. raise ProtocolError(message, text=fmt % (message, ))
  1121. handler = self._handlers.get(mode, self.defaultDecoder)
  1122. return handler(message, self.server.op_endpoint)
  1123. def defaultDecoder(self, message, server):
  1124. """Called to decode queries when no handler for that mode is found.
  1125. @raises ProtocolError: This implementation always raises
  1126. L{ProtocolError}.
  1127. """
  1128. mode = message.getArg(OPENID_NS, 'mode')
  1129. fmt = "Unrecognized OpenID mode %r"
  1130. raise ProtocolError(message, text=fmt % (mode, ))
  1131. class Server(object):
  1132. """I handle requests for an OpenID server.
  1133. Some types of requests (those which are not C{checkid} requests) may be
  1134. handed to my L{handleRequest} method, and I will take care of it and
  1135. return a response.
  1136. For your convenience, I also provide an interface to L{Decoder.decode}
  1137. and L{SigningEncoder.encode} through my methods L{decodeRequest} and
  1138. L{encodeResponse}.
  1139. All my state is encapsulated in an
  1140. L{OpenIDStore<openid.store.interface.OpenIDStore>}, which means
  1141. I'm not generally pickleable but I am easy to reconstruct.
  1142. Example::
  1143. oserver = Server(FileOpenIDStore(data_path), "http://example.com/op")
  1144. request = oserver.decodeRequest(query)
  1145. if request.mode in ['checkid_immediate', 'checkid_setup']:
  1146. if self.isAuthorized(request.identity, request.trust_root):
  1147. response = request.answer(True)
  1148. elif request.immediate:
  1149. response = request.answer(False)
  1150. else:
  1151. self.showDecidePage(request)
  1152. return
  1153. else:
  1154. response = oserver.handleRequest(request)
  1155. webresponse = oserver.encode(response)
  1156. @ivar signatory: I'm using this for associate requests and to sign things.
  1157. @type signatory: L{Signatory}
  1158. @ivar decoder: I'm using this to decode things.
  1159. @type decoder: L{Decoder}
  1160. @ivar encoder: I'm using this to encode things.
  1161. @type encoder: L{Encoder}
  1162. @ivar op_endpoint: My URL.
  1163. @type op_endpoint: str
  1164. @ivar negotiator: I use this to determine which kinds of
  1165. associations I can make and how.
  1166. @type negotiator: L{openid.association.SessionNegotiator}
  1167. """
  1168. def __init__(self,
  1169. store,
  1170. op_endpoint=None,
  1171. signatoryClass=Signatory,
  1172. encoderClass=SigningEncoder,
  1173. decoderClass=Decoder):
  1174. """A new L{Server}.
  1175. @param store: The back-end where my associations are stored.
  1176. @type store: L{openid.store.interface.OpenIDStore}
  1177. @param op_endpoint: My URL, the fully qualified address of this
  1178. server's endpoint, i.e. C{http://example.com/server}
  1179. @type op_endpoint: str
  1180. @change: C{op_endpoint} is new in library version 2.0. It
  1181. currently defaults to C{None} for compatibility with
  1182. earlier versions of the library, but you must provide it
  1183. if you want to respond to any version 2 OpenID requests.
  1184. """
  1185. self.store = store
  1186. self.signatory = signatoryClass(self.store)
  1187. self.encoder = encoderClass(self.signatory)
  1188. self.decoder = decoderClass(self)
  1189. self.negotiator = default_negotiator.copy()
  1190. if not op_endpoint:
  1191. warnings.warn(
  1192. "%s.%s constructor requires op_endpoint parameter "
  1193. "for OpenID 2.0 servers" %
  1194. (self.__class__.__module__, self.__class__.__name__),
  1195. stacklevel=2)
  1196. self.op_endpoint = op_endpoint
  1197. def handleRequest(self, request):
  1198. """Handle a request.
  1199. Give me a request, I will give you a response. Unless it's a type
  1200. of request I cannot handle myself, in which case I will raise
  1201. C{NotImplementedError}. In that case, you can handle it yourself,
  1202. or add a method to me for handling that request type.
  1203. @raises NotImplementedError: When I do not have a handler defined
  1204. for that type of request.
  1205. @returntype: L{OpenIDResponse}
  1206. """
  1207. handler = getattr(self, 'openid_' + request.mode, None)
  1208. if handler is not None:
  1209. return handler(request)
  1210. else:
  1211. raise NotImplementedError(
  1212. "%s has no handler for a request of mode %r." %
  1213. (self, request.mode))
  1214. def openid_check_authentication(self, request):
  1215. """Handle and respond to C{check_authentication} requests.
  1216. @returntype: L{OpenIDResponse}
  1217. """
  1218. return request.answer(self.signatory)
  1219. def openid_associate(self, request):
  1220. """Handle and respond to C{associate} requests.
  1221. @returntype: L{OpenIDResponse}
  1222. """
  1223. # XXX: TESTME
  1224. assoc_type = request.assoc_type
  1225. session_type = request.session.session_type
  1226. if self.negotiator.isAllowed(assoc_type, session_type):
  1227. assoc = self.signatory.createAssociation(
  1228. dumb=False, assoc_type=assoc_type)
  1229. return request.answer(assoc)
  1230. else:
  1231. message = ('Association type %r is not supported with '
  1232. 'session type %r' % (assoc_type, session_type))
  1233. (preferred_assoc_type, preferred_session_type) = \
  1234. self.negotiator.getAllowedType()
  1235. return request.answerUnsupported(message, preferred_assoc_type,
  1236. preferred_session_type)
  1237. def decodeRequest(self, query):
  1238. """Transform query parameters into an L{OpenIDRequest}.
  1239. If the query does not seem to be an OpenID request at all, I return
  1240. C{None}.
  1241. @param query: The query parameters as a dictionary with each
  1242. key mapping to one value.
  1243. @type query: dict
  1244. @raises ProtocolError: When the query does not seem to be a valid
  1245. OpenID request.
  1246. @returntype: L{OpenIDRequest}
  1247. @see: L{Decoder.decode}
  1248. """
  1249. return self.decoder.decode(query)
  1250. def encodeResponse(self, response):
  1251. """Encode a response to a L{WebResponse}, signing it first if appropriate.
  1252. @raises EncodingError: When I can't figure out how to encode this
  1253. message.
  1254. @raises AlreadySigned: When this response is already signed.
  1255. @returntype: L{WebResponse}
  1256. @see: L{SigningEncoder.encode}
  1257. """
  1258. return self.encoder.encode(response)
  1259. class ProtocolError(Exception):
  1260. """A message did not conform to the OpenID protocol.
  1261. @ivar message: The query that is failing to be a valid OpenID request.
  1262. @type message: openid.message.Message
  1263. """
  1264. def __init__(self, message, text=None, reference=None, contact=None):
  1265. """When an error occurs.
  1266. @param message: The message that is failing to be a valid
  1267. OpenID request.
  1268. @type message: openid.message.Message
  1269. @param text: A message about the encountered error. Set as C{args[0]}.
  1270. @type text: str
  1271. """
  1272. self.openid_message = message
  1273. self.reference = reference
  1274. self.contact = contact
  1275. assert type(message) not in [str, str]
  1276. Exception.__init__(self, text)
  1277. def getReturnTo(self):
  1278. """Get the return_to argument from the request, if any.
  1279. @returntype: str
  1280. """
  1281. if self.openid_message is None:
  1282. return None
  1283. else:
  1284. return self.openid_message.getArg(OPENID_NS, 'return_to')
  1285. def hasReturnTo(self):
  1286. """Did this request have a return_to parameter?
  1287. @returntype: bool
  1288. """
  1289. return self.getReturnTo() is not None
  1290. def toMessage(self):
  1291. """Generate a Message object for sending to the relying party,
  1292. after encoding.
  1293. """
  1294. namespace = self.openid_message.getOpenIDNamespace()
  1295. reply = Message(namespace)
  1296. reply.setArg(OPENID_NS, 'mode', 'error')
  1297. reply.setArg(OPENID_NS, 'error', str(self))
  1298. if self.contact is not None:
  1299. reply.setArg(OPENID_NS, 'contact', str(self.contact))
  1300. if self.reference is not None:
  1301. reply.setArg(OPENID_NS, 'reference', str(self.reference))
  1302. return reply
  1303. # implements IEncodable
  1304. def encodeToURL(self):
  1305. return self.toMessage().toURL(self.getReturnTo())
  1306. def encodeToKVForm(self):
  1307. return self.toMessage().toKVForm()
  1308. def toFormMarkup(self):
  1309. """Encode to HTML form markup for POST.
  1310. @since: 2.1.0
  1311. """
  1312. return self.toMessage().toFormMarkup(self.getReturnTo())
  1313. def toHTML(self):
  1314. """Encode to a full HTML page, wrapping the form markup in a page
  1315. that will autosubmit the form.
  1316. @since: 2.1.?
  1317. """
  1318. return oidutil.autoSubmitHTML(self.toFormMarkup())
  1319. def whichEncoding(self):
  1320. """How should I be encoded?
  1321. @returns: one of ENCODE_URL, ENCODE_KVFORM, or None. If None,
  1322. I cannot be encoded as a protocol message and should be
  1323. displayed to the user.
  1324. """
  1325. if self.hasReturnTo():
  1326. if self.openid_message.getOpenIDNamespace() == OPENID2_NS and \
  1327. len(self.encodeToURL()) > OPENID1_URL_LIMIT:
  1328. return ENCODE_HTML_FORM
  1329. else:
  1330. return ENCODE_URL
  1331. if self.openid_message is None:
  1332. return None
  1333. mode = self.openid_message.getArg(OPENID_NS, 'mode')
  1334. if mode:
  1335. if mode not in BROWSER_REQUEST_MODES:
  1336. return ENCODE_KVFORM
  1337. # According to the OpenID spec as of this writing, we are probably
  1338. # supposed to switch on request type here (GET versus POST) to figure
  1339. # out if we're supposed to print machine-readable or human-readable
  1340. # content at this point. GET/POST seems like a pretty lousy way of
  1341. # making the distinction though, as it's just as possible that the
  1342. # user agent could have mistakenly been directed to post to the
  1343. # server URL.
  1344. # Basically, if your request was so broken that you didn't manage to
  1345. # include an openid.mode, I'm not going to worry too much about
  1346. # returning you something you can't parse.
  1347. return None
  1348. class VersionError(Exception):
  1349. """Raised when an operation was attempted that is not compatible with
  1350. the protocol version being used."""
  1351. class NoReturnToError(Exception):
  1352. """Raised when a response to a request cannot be generated because
  1353. the request contains no return_to URL.
  1354. """
  1355. pass
  1356. class EncodingError(Exception):
  1357. """Could not encode this as a protocol message.
  1358. You should probably render it and show it to the user.
  1359. @ivar response: The response that failed to encode.
  1360. @type response: L{OpenIDResponse}
  1361. """
  1362. def __init__(self, response, explanation=None):
  1363. Exception.__init__(self, response)
  1364. self.response = response
  1365. self.explanation = explanation
  1366. def __str__(self):
  1367. if self.explanation:
  1368. s = '%s: %s' % (self.__class__.__name__, self.explanation)
  1369. else:
  1370. s = '%s for Response %s' % (self.__class__.__name__, self.response)
  1371. return s
  1372. class AlreadySigned(EncodingError):
  1373. """This response is already signed."""
  1374. class UntrustedReturnURL(ProtocolError):
  1375. """A return_to is outside the trust_root."""
  1376. def __init__(self, message, return_to, trust_root):
  1377. ProtocolError.__init__(self, message)
  1378. self.return_to = return_to
  1379. self.trust_root = trust_root
  1380. def __str__(self):
  1381. return "return_to %r not under trust_root %r" % (self.return_to,
  1382. self.trust_root)
  1383. class MalformedReturnURL(ProtocolError):
  1384. """The return_to URL doesn't look like a valid URL."""
  1385. def __init__(self, openid_message, return_to):
  1386. self.return_to = return_to
  1387. ProtocolError.__init__(self, openid_message)
  1388. class MalformedTrustRoot(ProtocolError):
  1389. """The trust root is not well-formed.
  1390. @see: OpenID Specs, U{openid.trust_root<http://openid.net/specs.bml#mode-checkid_immediate>}
  1391. """
  1392. pass
  1393. #class IEncodable: # Interface
  1394. # def encodeToURL(return_to):
  1395. # """Encode a response as a URL for redirection.
  1396. #
  1397. # @returns: A URL to direct the user agent back to.
  1398. # @returntype: str
  1399. # """
  1400. # pass
  1401. #
  1402. # def encodeToKvform():
  1403. # """Encode a response in key-value colon/newline format.
  1404. #
  1405. # This is a machine-readable format used to respond to messages which
  1406. # came directly from the consumer and not through the user agent.
  1407. #
  1408. # @see: OpenID Specs,
  1409. # U{Key-Value Colon/Newline format<http://openid.net/specs.bml#keyvalue>}
  1410. #
  1411. # @returntype: str
  1412. # """
  1413. # pass
  1414. #
  1415. # def whichEncoding():
  1416. # """How should I be encoded?
  1417. #
  1418. # @returns: one of ENCODE_URL, ENCODE_KVFORM, or None. If None,
  1419. # I cannot be encoded as a protocol message and should be
  1420. # displayed to the user.
  1421. # """
  1422. # pass