server.py 64 KB

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