1 # -*- test-case-name: openid.test.test_server -*-
2 """OpenID server protocol and logic.
7 An OpenID server must perform three tasks:
9 1. Examine the incoming request to determine its nature and validity.
11 2. Make a decision about how to respond to this request.
13 3. Format the response according to the protocol.
15 The first and last of these tasks may performed by
16 the L{decodeRequest<Server.decodeRequest>} and
17 L{encodeResponse<Server.encodeResponse>} methods of the
18 L{Server} object. Who gets to do the intermediate task -- deciding
19 how to respond to the request -- will depend on what type of request it
22 If it's a request to authenticate a user (a X{C{checkid_setup}} or
23 X{C{checkid_immediate}} request), you need to decide if you will assert
24 that this user may claim the identity in question. Exactly how you do
25 that is a matter of application policy, but it generally involves making
26 sure the user has an account with your system and is logged in, checking
27 to see if that identity is hers to claim, and verifying with the user that
28 she does consent to releasing that information to the party making the
31 Examine the properties of the L{CheckIDRequest} object, optionally
32 check L{CheckIDRequest.returnToVerified}, and and when you've come
33 to a decision, form a response by calling L{CheckIDRequest.answer}.
35 Other types of requests relate to establishing associations between client
36 and server and verifying the authenticity of previous communications.
37 L{Server} contains all the logic and data necessary to respond to
38 such requests; just pass the request to L{Server.handleRequest}.
44 Do you want to provide other information for your users
45 in addition to authentication? Version 2.0 of the OpenID
46 protocol allows consumers to add extensions to their requests.
47 For example, with sites using the U{Simple Registration
48 Extension<http://openid.net/specs/openid-simple-registration-extension-1_0.html>},
49 a user can agree to have their nickname and e-mail address sent to a
50 site when they sign up.
52 Since extensions do not change the way OpenID authentication works,
53 code to handle extension requests may be completely separate from the
54 L{OpenIDRequest} class here. But you'll likely want data sent back by
55 your extension to be signed. L{OpenIDResponse} provides methods with
56 which you can add data to it which can be signed with the other data in
61 # when request is a checkid_* request
62 response = request.answer(True)
63 # this will a signed 'openid.sreg.timezone' parameter to the response
64 # as well as a namespace declaration for the openid.sreg namespace
65 response.fields.setArg('http://openid.net/sreg/1.0', 'timezone', 'America/Los_Angeles')
67 There are helper modules for a number of extensions, including
68 L{Attribute Exchange<openid.extensions.ax>},
69 L{PAPE<openid.extensions.pape>}, and
70 L{Simple Registration<openid.extensions.sreg>} in the L{openid.extensions}
76 The OpenID server needs to maintain state between requests in order
77 to function. Its mechanism for doing this is called a store. The
78 store interface is defined in C{L{openid.store.interface.OpenIDStore}}.
79 Additionally, several concrete store implementations are provided, so that
80 most sites won't need to implement a custom store. For a store backed
81 by flat files on disk, see C{L{openid.store.filestore.FileOpenIDStore}}.
82 For stores based on MySQL or SQLite, see the C{L{openid.store.sqlstore}}
92 The keys by which a server looks up associations in its store have changed
93 in version 1.2 of this library. If your store has entries created from
94 version 1.0 code, you should empty it.
99 One of the additions to the OpenID protocol was a specified nonce
100 format for one-way nonces. As a result, the nonce table in the store
101 has changed. You'll need to run contrib/upgrade-store-1.1-to-2.0 to
102 upgrade your store, or you'll encounter errors about the wrong number
103 of columns in the oid_nonces table.
105 If you've written your own custom store or code that interacts
106 directly with it, you'll need to review the change notes in
107 L{openid.store.interface}.
109 @group Requests: OpenIDRequest, AssociateRequest, CheckIDRequest,
112 @group Responses: OpenIDResponse
114 @group HTTP Codes: HTTP_OK, HTTP_REDIRECT, HTTP_ERROR
116 @group Response Encodings: ENCODE_KVFORM, ENCODE_HTML_FORM, ENCODE_URL
119 import time
, warnings
120 from copy
import deepcopy
122 from openid
import cryptutil
123 from openid
import oidutil
124 from openid
import kvform
125 from openid
.dh
import DiffieHellman
126 from openid
.store
.nonce
import mkNonce
127 from openid
.server
.trustroot
import TrustRoot
, verifyReturnTo
128 from openid
.association
import Association
, default_negotiator
, getSecretSize
129 from openid
.message
import Message
, InvalidOpenIDNamespace
, \
130 OPENID_NS
, OPENID2_NS
, IDENTIFIER_SELECT
, OPENID1_URL_LIMIT
136 BROWSER_REQUEST_MODES
= ['checkid_setup', 'checkid_immediate']
138 ENCODE_KVFORM
= ('kvform',)
139 ENCODE_URL
= ('URL/redirect',)
140 ENCODE_HTML_FORM
= ('HTML form',)
144 class OpenIDRequest(object):
145 """I represent an incoming OpenID request.
147 @cvar mode: the C{X{openid.mode}} of this request.
153 class CheckAuthRequest(OpenIDRequest
):
154 """A request to verify the validity of a previous response.
156 @cvar mode: "X{C{check_authentication}}"
159 @ivar assoc_handle: The X{association handle} the response was signed with.
160 @type assoc_handle: str
161 @ivar signed: The message with the signature which wants checking.
162 @type signed: L{Message}
164 @ivar invalidate_handle: An X{association handle} the client is asking
165 about the validity of. Optional, may be C{None}.
166 @type invalidate_handle: str
168 @see: U{OpenID Specs, Mode: check_authentication
169 <http://openid.net/specs.bml#mode-check_authentication>}
171 mode
= "check_authentication"
173 required_fields
= ["identity", "return_to", "response_nonce"]
175 def __init__(self
, assoc_handle
, signed
, invalidate_handle
=None):
178 These parameters are assigned directly as class attributes, see
179 my L{class documentation<CheckAuthRequest>} for their descriptions.
181 @type assoc_handle: str
182 @type signed: L{Message}
183 @type invalidate_handle: str
185 self
.assoc_handle
= assoc_handle
187 self
.invalidate_handle
= invalidate_handle
188 self
.namespace
= OPENID2_NS
191 def fromMessage(klass
, message
, op_endpoint
=UNUSED
):
192 """Construct me from an OpenID Message.
194 @param message: An OpenID check_authentication Message
195 @type message: L{openid.message.Message}
197 @returntype: L{CheckAuthRequest}
199 self
= klass
.__new
__(klass
)
200 self
.message
= message
201 self
.namespace
= message
.getOpenIDNamespace()
202 self
.assoc_handle
= message
.getArg(OPENID_NS
, 'assoc_handle')
203 self
.sig
= message
.getArg(OPENID_NS
, 'sig')
205 if (self
.assoc_handle
is None or
207 fmt
= "%s request missing required parameter from message %s"
209 message
, text
=fmt
% (self
.mode
, message
))
211 self
.invalidate_handle
= message
.getArg(OPENID_NS
, 'invalidate_handle')
213 self
.signed
= message
.copy()
214 # openid.mode is currently check_authentication because
215 # that's the mode of this request. But the signature
216 # was made on something with a different openid.mode.
217 # http://article.gmane.org/gmane.comp.web.openid.general/537
218 if self
.signed
.hasKey(OPENID_NS
, "mode"):
219 self
.signed
.setArg(OPENID_NS
, "mode", "id_res")
223 fromMessage
= classmethod(fromMessage
)
225 def answer(self
, signatory
):
226 """Respond to this request.
228 Given a L{Signatory}, I can check the validity of the signature and
229 the X{C{invalidate_handle}}.
231 @param signatory: The L{Signatory} to use to check the signature.
232 @type signatory: L{Signatory}
234 @returns: A response with an X{C{is_valid}} (and, if
235 appropriate X{C{invalidate_handle}}) field.
236 @returntype: L{OpenIDResponse}
238 is_valid
= signatory
.verify(self
.assoc_handle
, self
.signed
)
239 # Now invalidate that assoc_handle so it this checkAuth message cannot
241 signatory
.invalidate(self
.assoc_handle
, dumb
=True)
242 response
= OpenIDResponse(self
)
243 valid_str
= (is_valid
and "true") or "false"
244 response
.fields
.setArg(OPENID_NS
, 'is_valid', valid_str
)
246 if self
.invalidate_handle
:
247 assoc
= signatory
.getAssociation(self
.invalidate_handle
, dumb
=False)
249 response
.fields
.setArg(
250 OPENID_NS
, 'invalidate_handle', self
.invalidate_handle
)
255 if self
.invalidate_handle
:
256 ih
= " invalidate? %r" % (self
.invalidate_handle
,)
259 s
= "<%s handle: %r sig: %r: signed: %r%s>" % (
260 self
.__class
__.__name
__, self
.assoc_handle
,
261 self
.sig
, self
.signed
, ih
)
265 class PlainTextServerSession(object):
266 """An object that knows how to handle association requests with no
269 @cvar session_type: The session_type for this association
270 session. There is no type defined for plain-text in the OpenID
271 specification, so we use 'no-encryption'.
272 @type session_type: str
274 @see: U{OpenID Specs, Mode: associate
275 <http://openid.net/specs.bml#mode-associate>}
276 @see: AssociateRequest
278 session_type
= 'no-encryption'
279 allowed_assoc_types
= ['HMAC-SHA1', 'HMAC-SHA256']
281 def fromMessage(cls
, unused_request
):
284 fromMessage
= classmethod(fromMessage
)
286 def answer(self
, secret
):
287 return {'mac_key': oidutil
.toBase64(secret
)}
290 class DiffieHellmanSHA1ServerSession(object):
291 """An object that knows how to handle association requests with the
292 Diffie-Hellman session type.
294 @cvar session_type: The session_type for this association
296 @type session_type: str
298 @ivar dh: The Diffie-Hellman algorithm values for this request
299 @type dh: DiffieHellman
301 @ivar consumer_pubkey: The public key sent by the consumer in the
303 @type consumer_pubkey: long
305 @see: U{OpenID Specs, Mode: associate
306 <http://openid.net/specs.bml#mode-associate>}
307 @see: AssociateRequest
309 session_type
= 'DH-SHA1'
310 hash_func
= staticmethod(cryptutil
.sha1
)
311 allowed_assoc_types
= ['HMAC-SHA1']
313 def __init__(self
, dh
, consumer_pubkey
):
315 self
.consumer_pubkey
= consumer_pubkey
317 def fromMessage(cls
, message
):
319 @param message: The associate request message
320 @type message: openid.message.Message
322 @returntype: L{DiffieHellmanSHA1ServerSession}
324 @raises ProtocolError: When parameters required to establish the
327 dh_modulus
= message
.getArg(OPENID_NS
, 'dh_modulus')
328 dh_gen
= message
.getArg(OPENID_NS
, 'dh_gen')
329 if (dh_modulus
is None and dh_gen
is not None or
330 dh_gen
is None and dh_modulus
is not None):
332 if dh_modulus
is None:
335 missing
= 'generator'
337 raise ProtocolError(message
,
338 'If non-default modulus or generator is '
339 'supplied, both must be supplied. Missing %s'
342 if dh_modulus
or dh_gen
:
343 dh_modulus
= cryptutil
.base64ToLong(dh_modulus
)
344 dh_gen
= cryptutil
.base64ToLong(dh_gen
)
345 dh
= DiffieHellman(dh_modulus
, dh_gen
)
347 dh
= DiffieHellman
.fromDefaults()
349 consumer_pubkey
= message
.getArg(OPENID_NS
, 'dh_consumer_public')
350 if consumer_pubkey
is None:
351 raise ProtocolError(message
, "Public key for DH-SHA1 session "
352 "not found in message %s" % (message
,))
354 consumer_pubkey
= cryptutil
.base64ToLong(consumer_pubkey
)
356 return cls(dh
, consumer_pubkey
)
358 fromMessage
= classmethod(fromMessage
)
360 def answer(self
, secret
):
361 mac_key
= self
.dh
.xorSecret(self
.consumer_pubkey
,
365 'dh_server_public': cryptutil
.longToBase64(self
.dh
.public
),
366 'enc_mac_key': oidutil
.toBase64(mac_key
),
369 class DiffieHellmanSHA256ServerSession(DiffieHellmanSHA1ServerSession
):
370 session_type
= 'DH-SHA256'
371 hash_func
= staticmethod(cryptutil
.sha256
)
372 allowed_assoc_types
= ['HMAC-SHA256']
374 class AssociateRequest(OpenIDRequest
):
375 """A request to establish an X{association}.
377 @cvar mode: "X{C{check_authentication}}"
380 @ivar assoc_type: The type of association. The protocol currently only
381 defines one value for this, "X{C{HMAC-SHA1}}".
382 @type assoc_type: str
384 @ivar session: An object that knows how to handle association
385 requests of a certain type.
387 @see: U{OpenID Specs, Mode: associate
388 <http://openid.net/specs.bml#mode-associate>}
394 'no-encryption': PlainTextServerSession
,
395 'DH-SHA1': DiffieHellmanSHA1ServerSession
,
396 'DH-SHA256': DiffieHellmanSHA256ServerSession
,
399 def __init__(self
, session
, assoc_type
):
402 The session is assigned directly as a class attribute. See my
403 L{class documentation<AssociateRequest>} for its description.
405 super(AssociateRequest
, self
).__init
__()
406 self
.session
= session
407 self
.assoc_type
= assoc_type
408 self
.namespace
= OPENID2_NS
411 def fromMessage(klass
, message
, op_endpoint
=UNUSED
):
412 """Construct me from an OpenID Message.
414 @param message: The OpenID associate request
415 @type message: openid.message.Message
417 @returntype: L{AssociateRequest}
419 if message
.isOpenID1():
420 session_type
= message
.getArg(OPENID_NS
, 'session_type')
421 if session_type
== 'no-encryption':
422 oidutil
.log('Received OpenID 1 request with a no-encryption '
423 'assocaition session type. Continuing anyway.')
424 elif not session_type
:
425 session_type
= 'no-encryption'
427 session_type
= message
.getArg(OPENID2_NS
, 'session_type')
428 if session_type
is None:
429 raise ProtocolError(message
,
430 text
="session_type missing from request")
433 session_class
= klass
.session_classes
[session_type
]
435 raise ProtocolError(message
,
436 "Unknown session type %r" % (session_type
,))
439 session
= session_class
.fromMessage(message
)
440 except ValueError, why
:
441 raise ProtocolError(message
, 'Error parsing %s session: %s' %
442 (session_class
.session_type
, why
[0]))
444 assoc_type
= message
.getArg(OPENID_NS
, 'assoc_type', 'HMAC-SHA1')
445 if assoc_type
not in session
.allowed_assoc_types
:
446 fmt
= 'Session type %s does not support association type %s'
447 raise ProtocolError(message
, fmt
% (session_type
, assoc_type
))
449 self
= klass(session
, assoc_type
)
450 self
.message
= message
451 self
.namespace
= message
.getOpenIDNamespace()
454 fromMessage
= classmethod(fromMessage
)
456 def answer(self
, assoc
):
457 """Respond to this request with an X{association}.
459 @param assoc: The association to send back.
460 @type assoc: L{openid.association.Association}
462 @returns: A response with the association information, encrypted
463 to the consumer's X{public key} if appropriate.
464 @returntype: L{OpenIDResponse}
466 response
= OpenIDResponse(self
)
467 response
.fields
.updateArgs(OPENID_NS
, {
468 'expires_in': '%d' % (assoc
.getExpiresIn(),),
469 'assoc_type': self
.assoc_type
,
470 'assoc_handle': assoc
.handle
,
472 response
.fields
.updateArgs(OPENID_NS
,
473 self
.session
.answer(assoc
.secret
))
475 if not (self
.session
.session_type
== 'no-encryption' and
476 self
.message
.isOpenID1()):
477 # The session type "no-encryption" did not have a name
478 # in OpenID v1, it was just omitted.
479 response
.fields
.setArg(
480 OPENID_NS
, 'session_type', self
.session
.session_type
)
484 def answerUnsupported(self
, message
, preferred_association_type
=None,
485 preferred_session_type
=None):
486 """Respond to this request indicating that the association
487 type or association session type is not supported."""
488 if self
.message
.isOpenID1():
489 raise ProtocolError(self
.message
)
491 response
= OpenIDResponse(self
)
492 response
.fields
.setArg(OPENID_NS
, 'error_code', 'unsupported-type')
493 response
.fields
.setArg(OPENID_NS
, 'error', message
)
495 if preferred_association_type
:
496 response
.fields
.setArg(
497 OPENID_NS
, 'assoc_type', preferred_association_type
)
499 if preferred_session_type
:
500 response
.fields
.setArg(
501 OPENID_NS
, 'session_type', preferred_session_type
)
505 class CheckIDRequest(OpenIDRequest
):
506 """A request to confirm the identity of a user.
508 This class handles requests for openid modes X{C{checkid_immediate}}
509 and X{C{checkid_setup}}.
511 @cvar mode: "X{C{checkid_immediate}}" or "X{C{checkid_setup}}"
514 @ivar immediate: Is this an immediate-mode request?
515 @type immediate: bool
517 @ivar identity: The OP-local identifier being checked.
520 @ivar claimed_id: The claimed identifier. Not present in OpenID 1.x
522 @type claimed_id: str
524 @ivar trust_root: "Are you Frank?" asks the checkid request. "Who wants
525 to know?" C{trust_root}, that's who. This URL identifies the party
526 making the request, and the user will use that to make her decision
527 about what answer she trusts them to have. Referred to as "realm" in
529 @type trust_root: str
531 @ivar return_to: The URL to send the user agent back to to reply to this
535 @ivar assoc_handle: Provided in smart mode requests, a handle for a
536 previously established association. C{None} for dumb mode requests.
537 @type assoc_handle: str
540 def __init__(self
, identity
, return_to
, trust_root
=None, immediate
=False,
541 assoc_handle
=None, op_endpoint
=None):
544 These parameters are assigned directly as class attributes, see
545 my L{class documentation<CheckIDRequest>} for their descriptions.
547 @raises MalformedReturnURL: When the C{return_to} URL is not a URL.
549 self
.assoc_handle
= assoc_handle
550 self
.identity
= identity
551 self
.claimed_id
= identity
552 self
.return_to
= return_to
553 self
.trust_root
= trust_root
or return_to
554 self
.op_endpoint
= op_endpoint
555 assert self
.op_endpoint
is not None
557 self
.immediate
= True
558 self
.mode
= "checkid_immediate"
560 self
.immediate
= False
561 self
.mode
= "checkid_setup"
563 if self
.return_to
is not None and \
564 not TrustRoot
.parse(self
.return_to
):
565 raise MalformedReturnURL(None, self
.return_to
)
566 if not self
.trustRootValid():
567 raise UntrustedReturnURL(None, self
.return_to
, self
.trust_root
)
570 def _getNamespace(self
):
571 warnings
.warn('The "namespace" attribute of CheckIDRequest objects '
572 'is deprecated. Use "message.getOpenIDNamespace()" '
573 'instead', DeprecationWarning, stacklevel
=2)
574 return self
.message
.getOpenIDNamespace()
576 namespace
= property(_getNamespace
)
578 def fromMessage(klass
, message
, op_endpoint
):
579 """Construct me from an OpenID message.
581 @raises ProtocolError: When not all required parameters are present
584 @raises MalformedReturnURL: When the C{return_to} URL is not a URL.
586 @raises UntrustedReturnURL: When the C{return_to} URL is outside
589 @param message: An OpenID checkid_* request Message
590 @type message: openid.message.Message
592 @param op_endpoint: The endpoint URL of the server that this
594 @type op_endpoint: str
596 @returntype: L{CheckIDRequest}
598 self
= klass
.__new
__(klass
)
599 self
.message
= message
600 self
.op_endpoint
= op_endpoint
601 mode
= message
.getArg(OPENID_NS
, 'mode')
602 if mode
== "checkid_immediate":
603 self
.immediate
= True
604 self
.mode
= "checkid_immediate"
606 self
.immediate
= False
607 self
.mode
= "checkid_setup"
609 self
.return_to
= message
.getArg(OPENID_NS
, 'return_to')
610 if message
.isOpenID1() and not self
.return_to
:
611 fmt
= "Missing required field 'return_to' from %r"
612 raise ProtocolError(message
, text
=fmt
% (message
,))
614 self
.identity
= message
.getArg(OPENID_NS
, 'identity')
615 self
.claimed_id
= message
.getArg(OPENID_NS
, 'claimed_id')
616 if message
.isOpenID1():
617 if self
.identity
is None:
618 s
= "OpenID 1 message did not contain openid.identity"
619 raise ProtocolError(message
, text
=s
)
621 if self
.identity
and not self
.claimed_id
:
622 s
= ("OpenID 2.0 message contained openid.identity but not "
624 raise ProtocolError(message
, text
=s
)
625 elif self
.claimed_id
and not self
.identity
:
626 s
= ("OpenID 2.0 message contained openid.claimed_id but not "
628 raise ProtocolError(message
, text
=s
)
630 # There's a case for making self.trust_root be a TrustRoot
631 # here. But if TrustRoot isn't currently part of the "public" API,
632 # I'm not sure it's worth doing.
634 if message
.isOpenID1():
635 trust_root_param
= 'trust_root'
637 trust_root_param
= 'realm'
639 # Using 'or' here is slightly different than sending a default
640 # argument to getArg, as it will treat no value and an empty
641 # string as equivalent.
642 self
.trust_root
= (message
.getArg(OPENID_NS
, trust_root_param
)
645 if not message
.isOpenID1():
646 if self
.return_to
is self
.trust_root
is None:
647 raise ProtocolError(message
, "openid.realm required when " +
648 "openid.return_to absent")
650 self
.assoc_handle
= message
.getArg(OPENID_NS
, 'assoc_handle')
652 # Using TrustRoot.parse here is a bit misleading, as we're not
653 # parsing return_to as a trust root at all. However, valid URLs
654 # are valid trust roots, so we can use this to get an idea if it
655 # is a valid URL. Not all trust roots are valid return_to URLs,
656 # however (particularly ones with wildcards), so this is still a
658 if self
.return_to
is not None and \
659 not TrustRoot
.parse(self
.return_to
):
660 raise MalformedReturnURL(message
, self
.return_to
)
662 # I first thought that checking to see if the return_to is within
663 # the trust_root is premature here, a logic-not-decoding thing. But
664 # it was argued that this is really part of data validation. A
665 # request with an invalid trust_root/return_to is broken regardless of
666 # application, right?
667 if not self
.trustRootValid():
668 raise UntrustedReturnURL(message
, self
.return_to
, self
.trust_root
)
672 fromMessage
= classmethod(fromMessage
)
675 """Is the identifier to be selected by the IDP?
679 # So IDPs don't have to import the constant
680 return self
.identity
== IDENTIFIER_SELECT
682 def trustRootValid(self
):
683 """Is my return_to under my trust_root?
687 if not self
.trust_root
:
689 tr
= TrustRoot
.parse(self
.trust_root
)
691 raise MalformedTrustRoot(self
.message
, self
.trust_root
)
693 if self
.return_to
is not None:
694 return tr
.validateURL(self
.return_to
)
698 def returnToVerified(self
):
699 """Does the relying party publish the return_to URL for this
700 response under the realm? It is up to the provider to set a
701 policy for what kinds of realms should be allowed. This
702 return_to URL verification reduces vulnerability to data-theft
703 attacks based on open proxies, cross-site-scripting, or open
706 This check should only be performed after making sure that the
707 return_to URL matches the realm.
709 @see: L{trustRootValid}
711 @raises openid.yadis.discover.DiscoveryFailure: if the realm
712 URL does not support Yadis discovery (and so does not
713 support the verification process).
715 @raises openid.fetchers.HTTPFetchingError: if the realm URL
716 is not reachable. When this is the case, the RP may be hosted
717 on the user's intranet.
721 @returns: True if the realm publishes a document with the
726 return verifyReturnTo(self
.trust_root
, self
.return_to
)
728 def answer(self
, allow
, server_url
=None, identity
=None, claimed_id
=None):
729 """Respond to this request.
731 @param allow: Allow this user to claim this identity, and allow the
732 consumer to have this information?
735 @param server_url: DEPRECATED. Passing C{op_endpoint} to the
736 L{Server} constructor makes this optional.
738 When an OpenID 1.x immediate mode request does not succeed,
739 it gets back a URL where the request may be carried out
740 in a not-so-immediate fashion. Pass my URL in here (the
741 fully qualified address of this server's endpoint, i.e.
742 C{http://example.com/server}), and I will use it as a base for the
743 URL for a new request.
745 Optional for requests where C{CheckIDRequest.immediate} is C{False}
746 or C{allow} is C{True}.
748 @type server_url: str
750 @param identity: The OP-local identifier to answer with. Only for use
751 when the relying party requested identifier selection.
752 @type identity: str or None
754 @param claimed_id: The claimed identifier to answer with, for use
755 with identifier selection in the case where the claimed identifier
756 and the OP-local identifier differ, i.e. when the claimed_id uses
759 If C{identity} is provided but this is not, C{claimed_id} will
760 default to the value of C{identity}. When answering requests
761 that did not ask for identifier selection, the response
762 C{claimed_id} will default to that of the request.
764 This parameter is new in OpenID 2.0.
765 @type claimed_id: str or None
767 @returntype: L{OpenIDResponse}
769 @change: Version 2.0 deprecates C{server_url} and adds C{claimed_id}.
771 @raises NoReturnError: when I do not have a return_to.
773 assert self
.message
is not None
775 if not self
.return_to
:
776 raise NoReturnToError
779 if not self
.message
.isOpenID1() and not self
.op_endpoint
:
780 # In other words, that warning I raised in Server.__init__?
781 # You should pay attention to it now.
782 raise RuntimeError("%s should be constructed with op_endpoint "
783 "to respond to OpenID 2.0 messages." %
785 server_url
= self
.op_endpoint
789 elif self
.message
.isOpenID1():
796 mode
= 'setup_needed'
800 response
= OpenIDResponse(self
)
802 if claimed_id
and self
.message
.isOpenID1():
803 namespace
= self
.message
.getOpenIDNamespace()
804 raise VersionError("claimed_id is new in OpenID 2.0 and not "
805 "available for %s" % (namespace
,))
807 if identity
and not claimed_id
:
808 claimed_id
= identity
811 if self
.identity
== IDENTIFIER_SELECT
:
814 "This request uses IdP-driven identifier selection."
815 "You must supply an identifier in the response.")
816 response_identity
= identity
817 response_claimed_id
= claimed_id
820 if identity
and (self
.identity
!= identity
):
822 "Request was for identity %r, cannot reply "
823 "with identity %r" % (self
.identity
, identity
))
824 response_identity
= self
.identity
825 response_claimed_id
= self
.claimed_id
830 "This request specified no identity and you "
831 "supplied %r" % (identity
,))
832 response_identity
= None
834 if self
.message
.isOpenID1() and response_identity
is None:
836 "Request was an OpenID 1 request, so response must "
837 "include an identifier."
840 response
.fields
.updateArgs(OPENID_NS
, {
842 'return_to': self
.return_to
,
843 'response_nonce': mkNonce(),
847 response
.fields
.setArg(OPENID_NS
, 'op_endpoint', server_url
)
849 if response_identity
is not None:
850 response
.fields
.setArg(
851 OPENID_NS
, 'identity', response_identity
)
852 if self
.message
.isOpenID2():
853 response
.fields
.setArg(
854 OPENID_NS
, 'claimed_id', response_claimed_id
)
856 response
.fields
.setArg(OPENID_NS
, 'mode', mode
)
858 if self
.message
.isOpenID1() and not server_url
:
859 raise ValueError("setup_url is required for allow=False "
860 "in OpenID 1.x immediate mode.")
861 # Make a new request just like me, but with immediate=False.
862 setup_request
= self
.__class
__(
863 self
.identity
, self
.return_to
, self
.trust_root
,
864 immediate
=False, assoc_handle
=self
.assoc_handle
,
865 op_endpoint
=self
.op_endpoint
)
867 # XXX: This API is weird.
868 setup_request
.message
= self
.message
870 setup_url
= setup_request
.encodeToURL(server_url
)
871 response
.fields
.setArg(OPENID_NS
, 'user_setup_url', setup_url
)
876 def encodeToURL(self
, server_url
):
877 """Encode this request as a URL to GET.
879 @param server_url: The URL of the OpenID server to make this request of.
880 @type server_url: str
884 @raises NoReturnError: when I do not have a return_to.
886 if not self
.return_to
:
887 raise NoReturnToError
889 # Imported from the alternate reality where these classes are used
890 # in both the client and server code, so Requests are Encodable too.
891 # That's right, code imported from alternate realities all for the
892 # love of you, id_res/user_setup_url.
893 q
= {'mode': self
.mode
,
894 'identity': self
.identity
,
895 'claimed_id': self
.claimed_id
,
896 'return_to': self
.return_to
}
898 if self
.message
.isOpenID1():
899 q
['trust_root'] = self
.trust_root
901 q
['realm'] = self
.trust_root
902 if self
.assoc_handle
:
903 q
['assoc_handle'] = self
.assoc_handle
905 response
= Message(self
.message
.getOpenIDNamespace())
906 response
.updateArgs(OPENID_NS
, q
)
907 return response
.toURL(server_url
)
910 def getCancelURL(self
):
911 """Get the URL to cancel this request.
913 Useful for creating a "Cancel" button on a web form so that operation
914 can be carried out directly without another trip through the server.
916 (Except you probably want to make another trip through the server so
917 that it knows that the user did make a decision. Or you could simulate
918 this method by doing C{.answer(False).encodeToURL()})
921 @returns: The return_to URL with openid.mode = cancel.
923 @raises NoReturnError: when I do not have a return_to.
925 if not self
.return_to
:
926 raise NoReturnToError
929 raise ValueError("Cancel is not an appropriate response to "
930 "immediate mode requests.")
932 response
= Message(self
.message
.getOpenIDNamespace())
933 response
.setArg(OPENID_NS
, 'mode', 'cancel')
934 return response
.toURL(self
.return_to
)
938 return '<%s id:%r im:%s tr:%r ah:%r>' % (self
.__class
__.__name
__,
946 class OpenIDResponse(object):
947 """I am a response to an OpenID request.
949 @ivar request: The request I respond to.
950 @type request: L{OpenIDRequest}
952 @ivar fields: My parameters as a dictionary with each key mapping to
953 one value. Keys are parameter names with no leading "C{openid.}".
954 e.g. "C{identity}" and "C{mac_key}", never "C{openid.identity}".
955 @type fields: L{openid.message.Message}
957 @ivar signed: The names of the fields which should be signed.
958 @type signed: list of str
961 # Implementer's note: In a more symmetric client/server
962 # implementation, there would be more types of OpenIDResponse
963 # object and they would have validated attributes according to the
964 # type of response. But as it is, Response objects in a server are
965 # basically write-only, their only job is to go out over the wire,
966 # so this is just a loose wrapper around OpenIDResponse.fields.
968 def __init__(self
, request
):
969 """Make a response to an L{OpenIDRequest}.
971 @type request: L{OpenIDRequest}
973 self
.request
= request
974 self
.fields
= Message(request
.namespace
)
977 return "%s for %s: %s" % (
978 self
.__class
__.__name
__,
979 self
.request
.__class
__.__name
__,
983 def toFormMarkup(self
, form_tag_attrs
=None):
984 """Returns the form markup for this response.
986 @param form_tag_attrs: Dictionary of attributes to be added to
987 the form tag. 'accept-charset' and 'enctype' have defaults
988 that can be overridden. If a value is supplied for
989 'action' or 'method', it will be replaced.
995 return self
.fields
.toFormMarkup(self
.request
.return_to
,
996 form_tag_attrs
=form_tag_attrs
)
998 def toHTML(self
, form_tag_attrs
=None):
999 """Returns an HTML document that auto-submits the form markup
1008 return oidutil
.autoSubmitHTML(self
.toFormMarkup(form_tag_attrs
))
1010 def renderAsForm(self
):
1011 """Returns True if this response's encoding is
1012 ENCODE_HTML_FORM. Convenience method for server authors.
1018 return self
.whichEncoding() == ENCODE_HTML_FORM
1021 def needsSigning(self
):
1022 """Does this response require signing?
1026 return self
.fields
.getArg(OPENID_NS
, 'mode') == 'id_res'
1029 # implements IEncodable
1031 def whichEncoding(self
):
1032 """How should I be encoded?
1034 @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM.
1036 @change: 2.1.0 added the ENCODE_HTML_FORM response.
1038 if self
.request
.mode
in BROWSER_REQUEST_MODES
:
1039 if self
.fields
.getOpenIDNamespace() == OPENID2_NS
and \
1040 len(self
.encodeToURL()) > OPENID1_URL_LIMIT
:
1041 return ENCODE_HTML_FORM
1045 return ENCODE_KVFORM
1048 def encodeToURL(self
):
1049 """Encode a response as a URL for the user agent to GET.
1051 You will generally use this URL with a HTTP redirect.
1053 @returns: A URL to direct the user agent back to.
1056 return self
.fields
.toURL(self
.request
.return_to
)
1059 def addExtension(self
, extension_response
):
1061 Add an extension response to this response message.
1063 @param extension_response: An object that implements the
1064 extension interface for adding arguments to an OpenID
1066 @type extension_response: L{openid.extension}
1070 extension_response
.toMessage(self
.fields
)
1073 def encodeToKVForm(self
):
1074 """Encode a response in key-value colon/newline format.
1076 This is a machine-readable format used to respond to messages which
1077 came directly from the consumer and not through the user agent.
1080 U{Key-Value Colon/Newline format<http://openid.net/specs.bml#keyvalue>}
1084 return self
.fields
.toKVForm()
1088 class WebResponse(object):
1089 """I am a response to an OpenID request in terms a web server understands.
1091 I generally come from an L{Encoder}, either directly or from
1092 L{Server.encodeResponse}.
1094 @ivar code: The HTTP code of this response.
1097 @ivar headers: Headers to include in this response.
1100 @ivar body: The body of this response.
1104 def __init__(self
, code
=HTTP_OK
, headers
=None, body
=""):
1107 These parameters are assigned directly as class attributes, see
1108 my L{class documentation<WebResponse>} for their descriptions.
1111 if headers
is not None:
1112 self
.headers
= headers
1119 class Signatory(object):
1122 I also check signatures.
1124 All my state is encapsulated in an
1125 L{OpenIDStore<openid.store.interface.OpenIDStore>}, which means
1126 I'm not generally pickleable but I am easy to reconstruct.
1128 @cvar SECRET_LIFETIME: The number of seconds a secret remains valid.
1129 @type SECRET_LIFETIME: int
1132 SECRET_LIFETIME
= 14 * 24 * 60 * 60 # 14 days, in seconds
1134 # keys have a bogus server URL in them because the filestore
1135 # really does expect that key to be a URL. This seems a little
1136 # silly for the server store, since I expect there to be only one
1138 _normal_key
= 'http://localhost/|normal'
1139 _dumb_key
= 'http://localhost/|dumb'
1142 def __init__(self
, store
):
1143 """Create a new Signatory.
1145 @param store: The back-end where my associations are stored.
1146 @type store: L{openid.store.interface.OpenIDStore}
1148 assert store
is not None
1152 def verify(self
, assoc_handle
, message
):
1153 """Verify that the signature for some data is valid.
1155 @param assoc_handle: The handle of the association used to sign the
1157 @type assoc_handle: str
1159 @param message: The signed message to verify
1160 @type message: openid.message.Message
1162 @returns: C{True} if the signature is valid, C{False} if not.
1165 assoc
= self
.getAssociation(assoc_handle
, dumb
=True)
1167 oidutil
.log("failed to get assoc with handle %r to verify "
1169 % (assoc_handle
, message
))
1173 valid
= assoc
.checkMessageSignature(message
)
1174 except ValueError, ex
:
1175 oidutil
.log("Error in verifying %s with %s: %s" % (message
,
1182 def sign(self
, response
):
1185 I take a L{OpenIDResponse}, create a signature for everything
1186 in its L{signed<OpenIDResponse.signed>} list, and return a new
1187 copy of the response object with that signature included.
1189 @param response: A response to sign.
1190 @type response: L{OpenIDResponse}
1192 @returns: A signed copy of the response.
1193 @returntype: L{OpenIDResponse}
1195 signed_response
= deepcopy(response
)
1196 assoc_handle
= response
.request
.assoc_handle
1199 # disabling expiration check because even if the association
1200 # is expired, we still need to know some properties of the
1201 # association so that we may preserve those properties when
1202 # creating the fallback association.
1203 assoc
= self
.getAssociation(assoc_handle
, dumb
=False,
1204 checkExpiration
=False)
1206 if not assoc
or assoc
.expiresIn
<= 0:
1207 # fall back to dumb mode
1208 signed_response
.fields
.setArg(
1209 OPENID_NS
, 'invalidate_handle', assoc_handle
)
1210 assoc_type
= assoc
and assoc
.assoc_type
or 'HMAC-SHA1'
1211 if assoc
and assoc
.expiresIn
<= 0:
1212 # now do the clean-up that the disabled checkExpiration
1213 # code didn't get to do.
1214 self
.invalidate(assoc_handle
, dumb
=False)
1215 assoc
= self
.createAssociation(dumb
=True, assoc_type
=assoc_type
)
1218 assoc
= self
.createAssociation(dumb
=True)
1221 signed_response
.fields
= assoc
.signMessage(signed_response
.fields
)
1222 except kvform
.KVFormError
, err
:
1223 raise EncodingError(response
, explanation
=str(err
))
1224 return signed_response
1227 def createAssociation(self
, dumb
=True, assoc_type
='HMAC-SHA1'):
1228 """Make a new association.
1230 @param dumb: Is this association for a dumb-mode transaction?
1233 @param assoc_type: The type of association to create. Currently
1234 there is only one type defined, C{HMAC-SHA1}.
1235 @type assoc_type: str
1237 @returns: the new association.
1238 @returntype: L{openid.association.Association}
1240 secret
= cryptutil
.getBytes(getSecretSize(assoc_type
))
1241 uniq
= oidutil
.toBase64(cryptutil
.getBytes(4))
1242 handle
= '{%s}{%x}{%s}' % (assoc_type
, int(time
.time()), uniq
)
1244 assoc
= Association
.fromExpiresIn(
1245 self
.SECRET_LIFETIME
, handle
, secret
, assoc_type
)
1248 key
= self
._dumb
_key
1250 key
= self
._normal
_key
1251 self
.store
.storeAssociation(key
, assoc
)
1255 def getAssociation(self
, assoc_handle
, dumb
, checkExpiration
=True):
1256 """Get the association with the specified handle.
1258 @type assoc_handle: str
1260 @param dumb: Is this association used with dumb mode?
1263 @returns: the association, or None if no valid association with that
1265 @returntype: L{openid.association.Association}
1267 # Hmm. We've created an interface that deals almost entirely with
1268 # assoc_handles. The only place outside the Signatory that uses this
1269 # (and thus the only place that ever sees Association objects) is
1270 # when creating a response to an association request, as it must have
1271 # the association's secret.
1273 if assoc_handle
is None:
1274 raise ValueError("assoc_handle must not be None")
1277 key
= self
._dumb
_key
1279 key
= self
._normal
_key
1280 assoc
= self
.store
.getAssociation(key
, assoc_handle
)
1281 if assoc
is not None and assoc
.expiresIn
<= 0:
1282 oidutil
.log("requested %sdumb key %r is expired (by %s seconds)" %
1283 ((not dumb
) and 'not-' or '',
1284 assoc_handle
, assoc
.expiresIn
))
1286 self
.store
.removeAssociation(key
, assoc_handle
)
1291 def invalidate(self
, assoc_handle
, dumb
):
1292 """Invalidates the association with the given handle.
1294 @type assoc_handle: str
1296 @param dumb: Is this association used with dumb mode?
1300 key
= self
._dumb
_key
1302 key
= self
._normal
_key
1303 self
.store
.removeAssociation(key
, assoc_handle
)
1307 class Encoder(object):
1308 """I encode responses in to L{WebResponses<WebResponse>}.
1310 If you don't like L{WebResponses<WebResponse>}, you can do
1311 your own handling of L{OpenIDResponses<OpenIDResponse>} with
1312 L{OpenIDResponse.whichEncoding}, L{OpenIDResponse.encodeToURL}, and
1313 L{OpenIDResponse.encodeToKVForm}.
1316 responseFactory
= WebResponse
1319 def encode(self
, response
):
1320 """Encode a response to a L{WebResponse}.
1322 @raises EncodingError: When I can't figure out how to encode this
1325 encode_as
= response
.whichEncoding()
1326 if encode_as
== ENCODE_KVFORM
:
1327 wr
= self
.responseFactory(body
=response
.encodeToKVForm())
1328 if isinstance(response
, Exception):
1329 wr
.code
= HTTP_ERROR
1330 elif encode_as
== ENCODE_URL
:
1331 location
= response
.encodeToURL()
1332 wr
= self
.responseFactory(code
=HTTP_REDIRECT
,
1333 headers
={'location': location
})
1334 elif encode_as
== ENCODE_HTML_FORM
:
1335 wr
= self
.responseFactory(code
=HTTP_OK
,
1336 body
=response
.toFormMarkup())
1338 # Can't encode this to a protocol message. You should probably
1339 # render it to HTML and show it to the user.
1340 raise EncodingError(response
)
1345 class SigningEncoder(Encoder
):
1346 """I encode responses in to L{WebResponses<WebResponse>}, signing them when required.
1349 def __init__(self
, signatory
):
1350 """Create a L{SigningEncoder}.
1352 @param signatory: The L{Signatory} I will make signatures with.
1353 @type signatory: L{Signatory}
1355 self
.signatory
= signatory
1358 def encode(self
, response
):
1359 """Encode a response to a L{WebResponse}, signing it first if appropriate.
1361 @raises EncodingError: When I can't figure out how to encode this
1364 @raises AlreadySigned: When this response is already signed.
1366 @returntype: L{WebResponse}
1368 # the isinstance is a bit of a kludge... it means there isn't really
1369 # an adapter to make the interfaces quite match.
1370 if (not isinstance(response
, Exception)) and response
.needsSigning():
1371 if not self
.signatory
:
1373 "Must have a store to sign this request: %s" %
1374 (response
,), response
)
1375 if response
.fields
.hasKey(OPENID_NS
, 'sig'):
1376 raise AlreadySigned(response
)
1377 response
= self
.signatory
.sign(response
)
1378 return super(SigningEncoder
, self
).encode(response
)
1382 class Decoder(object):
1383 """I decode an incoming web request in to a L{OpenIDRequest}.
1387 'checkid_setup': CheckIDRequest
.fromMessage
,
1388 'checkid_immediate': CheckIDRequest
.fromMessage
,
1389 'check_authentication': CheckAuthRequest
.fromMessage
,
1390 'associate': AssociateRequest
.fromMessage
,
1393 def __init__(self
, server
):
1394 """Construct a Decoder.
1396 @param server: The server which I am decoding requests for.
1397 (Necessary because some replies reference their server.)
1398 @type server: L{Server}
1400 self
.server
= server
1402 def decode(self
, query
):
1403 """I transform query parameters into an L{OpenIDRequest}.
1405 If the query does not seem to be an OpenID request at all, I return
1408 @param query: The query parameters as a dictionary with each
1409 key mapping to one value.
1412 @raises ProtocolError: When the query does not seem to be a valid
1415 @returntype: L{OpenIDRequest}
1421 message
= Message
.fromPostArgs(query
)
1422 except InvalidOpenIDNamespace
, err
:
1423 # It's useful to have a Message attached to a ProtocolError, so we
1424 # override the bad ns value to build a Message out of it. Kinda
1425 # kludgy, since it's made of lies, but the parts that aren't lies
1426 # are more useful than a 'None'.
1427 query
= query
.copy()
1428 query
['openid.ns'] = OPENID2_NS
1429 message
= Message
.fromPostArgs(query
)
1430 raise ProtocolError(message
, str(err
))
1432 mode
= message
.getArg(OPENID_NS
, 'mode')
1434 fmt
= "No mode value in message %s"
1435 raise ProtocolError(message
, text
=fmt
% (message
,))
1437 handler
= self
._handlers
.get(mode
, self
.defaultDecoder
)
1438 return handler(message
, self
.server
.op_endpoint
)
1441 def defaultDecoder(self
, message
, server
):
1442 """Called to decode queries when no handler for that mode is found.
1444 @raises ProtocolError: This implementation always raises
1447 mode
= message
.getArg(OPENID_NS
, 'mode')
1448 fmt
= "Unrecognized OpenID mode %r"
1449 raise ProtocolError(message
, text
=fmt
% (mode
,))
1453 class Server(object):
1454 """I handle requests for an OpenID server.
1456 Some types of requests (those which are not C{checkid} requests) may be
1457 handed to my L{handleRequest} method, and I will take care of it and
1460 For your convenience, I also provide an interface to L{Decoder.decode}
1461 and L{SigningEncoder.encode} through my methods L{decodeRequest} and
1464 All my state is encapsulated in an
1465 L{OpenIDStore<openid.store.interface.OpenIDStore>}, which means
1466 I'm not generally pickleable but I am easy to reconstruct.
1470 oserver = Server(FileOpenIDStore(data_path), "http://example.com/op")
1471 request = oserver.decodeRequest(query)
1472 if request.mode in ['checkid_immediate', 'checkid_setup']:
1473 if self.isAuthorized(request.identity, request.trust_root):
1474 response = request.answer(True)
1475 elif request.immediate:
1476 response = request.answer(False)
1478 self.showDecidePage(request)
1481 response = oserver.handleRequest(request)
1483 webresponse = oserver.encode(response)
1485 @ivar signatory: I'm using this for associate requests and to sign things.
1486 @type signatory: L{Signatory}
1488 @ivar decoder: I'm using this to decode things.
1489 @type decoder: L{Decoder}
1491 @ivar encoder: I'm using this to encode things.
1492 @type encoder: L{Encoder}
1494 @ivar op_endpoint: My URL.
1495 @type op_endpoint: str
1497 @ivar negotiator: I use this to determine which kinds of
1498 associations I can make and how.
1499 @type negotiator: L{openid.association.SessionNegotiator}
1502 signatoryClass
= Signatory
1503 encoderClass
= SigningEncoder
1504 decoderClass
= Decoder
1506 def __init__(self
, store
, op_endpoint
=None):
1509 @param store: The back-end where my associations are stored.
1510 @type store: L{openid.store.interface.OpenIDStore}
1512 @param op_endpoint: My URL, the fully qualified address of this
1513 server's endpoint, i.e. C{http://example.com/server}
1514 @type op_endpoint: str
1516 @change: C{op_endpoint} is new in library version 2.0. It
1517 currently defaults to C{None} for compatibility with
1518 earlier versions of the library, but you must provide it
1519 if you want to respond to any version 2 OpenID requests.
1522 self
.signatory
= self
.signatoryClass(self
.store
)
1523 self
.encoder
= self
.encoderClass(self
.signatory
)
1524 self
.decoder
= self
.decoderClass(self
)
1525 self
.negotiator
= default_negotiator
.copy()
1528 warnings
.warn("%s.%s constructor requires op_endpoint parameter "
1529 "for OpenID 2.0 servers" %
1530 (self
.__class
__.__module
__, self
.__class
__.__name
__),
1532 self
.op_endpoint
= op_endpoint
1535 def handleRequest(self
, request
):
1536 """Handle a request.
1538 Give me a request, I will give you a response. Unless it's a type
1539 of request I cannot handle myself, in which case I will raise
1540 C{NotImplementedError}. In that case, you can handle it yourself,
1541 or add a method to me for handling that request type.
1543 @raises NotImplementedError: When I do not have a handler defined
1544 for that type of request.
1546 @returntype: L{OpenIDResponse}
1548 handler
= getattr(self
, 'openid_' + request
.mode
, None)
1549 if handler
is not None:
1550 return handler(request
)
1552 raise NotImplementedError(
1553 "%s has no handler for a request of mode %r." %
1554 (self
, request
.mode
))
1557 def openid_check_authentication(self
, request
):
1558 """Handle and respond to C{check_authentication} requests.
1560 @returntype: L{OpenIDResponse}
1562 return request
.answer(self
.signatory
)
1565 def openid_associate(self
, request
):
1566 """Handle and respond to C{associate} requests.
1568 @returntype: L{OpenIDResponse}
1571 assoc_type
= request
.assoc_type
1572 session_type
= request
.session
.session_type
1573 if self
.negotiator
.isAllowed(assoc_type
, session_type
):
1574 assoc
= self
.signatory
.createAssociation(dumb
=False,
1575 assoc_type
=assoc_type
)
1576 return request
.answer(assoc
)
1578 message
= ('Association type %r is not supported with '
1579 'session type %r' % (assoc_type
, session_type
))
1580 (preferred_assoc_type
, preferred_session_type
) = \
1581 self
.negotiator
.getAllowedType()
1582 return request
.answerUnsupported(
1584 preferred_assoc_type
,
1585 preferred_session_type
)
1588 def decodeRequest(self
, query
):
1589 """Transform query parameters into an L{OpenIDRequest}.
1591 If the query does not seem to be an OpenID request at all, I return
1594 @param query: The query parameters as a dictionary with each
1595 key mapping to one value.
1598 @raises ProtocolError: When the query does not seem to be a valid
1601 @returntype: L{OpenIDRequest}
1603 @see: L{Decoder.decode}
1605 return self
.decoder
.decode(query
)
1608 def encodeResponse(self
, response
):
1609 """Encode a response to a L{WebResponse}, signing it first if appropriate.
1611 @raises EncodingError: When I can't figure out how to encode this
1614 @raises AlreadySigned: When this response is already signed.
1616 @returntype: L{WebResponse}
1618 @see: L{SigningEncoder.encode}
1620 return self
.encoder
.encode(response
)
1624 class ProtocolError(Exception):
1625 """A message did not conform to the OpenID protocol.
1627 @ivar message: The query that is failing to be a valid OpenID request.
1628 @type message: openid.message.Message
1631 def __init__(self
, message
, text
=None, reference
=None, contact
=None):
1632 """When an error occurs.
1634 @param message: The message that is failing to be a valid
1636 @type message: openid.message.Message
1638 @param text: A message about the encountered error. Set as C{args[0]}.
1641 self
.openid_message
= message
1642 self
.reference
= reference
1643 self
.contact
= contact
1644 assert type(message
) not in [str, unicode]
1645 Exception.__init
__(self
, text
)
1648 def getReturnTo(self
):
1649 """Get the return_to argument from the request, if any.
1653 if self
.openid_message
is None:
1656 return self
.openid_message
.getArg(OPENID_NS
, 'return_to')
1658 def hasReturnTo(self
):
1659 """Did this request have a return_to parameter?
1663 return self
.getReturnTo() is not None
1665 def toMessage(self
):
1666 """Generate a Message object for sending to the relying party,
1669 namespace
= self
.openid_message
.getOpenIDNamespace()
1670 reply
= Message(namespace
)
1671 reply
.setArg(OPENID_NS
, 'mode', 'error')
1672 reply
.setArg(OPENID_NS
, 'error', str(self
))
1674 if self
.contact
is not None:
1675 reply
.setArg(OPENID_NS
, 'contact', str(self
.contact
))
1677 if self
.reference
is not None:
1678 reply
.setArg(OPENID_NS
, 'reference', str(self
.reference
))
1682 # implements IEncodable
1684 def encodeToURL(self
):
1685 return self
.toMessage().toURL(self
.getReturnTo())
1687 def encodeToKVForm(self
):
1688 return self
.toMessage().toKVForm()
1690 def toFormMarkup(self
):
1691 """Encode to HTML form markup for POST.
1695 return self
.toMessage().toFormMarkup(self
.getReturnTo())
1698 """Encode to a full HTML page, wrapping the form markup in a page
1699 that will autosubmit the form.
1703 return oidutil
.autoSubmitHTML(self
.toFormMarkup())
1705 def whichEncoding(self
):
1706 """How should I be encoded?
1708 @returns: one of ENCODE_URL, ENCODE_KVFORM, or None. If None,
1709 I cannot be encoded as a protocol message and should be
1710 displayed to the user.
1712 if self
.hasReturnTo():
1713 if self
.openid_message
.getOpenIDNamespace() == OPENID2_NS
and \
1714 len(self
.encodeToURL()) > OPENID1_URL_LIMIT
:
1715 return ENCODE_HTML_FORM
1719 if self
.openid_message
is None:
1722 mode
= self
.openid_message
.getArg(OPENID_NS
, 'mode')
1724 if mode
not in BROWSER_REQUEST_MODES
:
1725 return ENCODE_KVFORM
1727 # According to the OpenID spec as of this writing, we are probably
1728 # supposed to switch on request type here (GET versus POST) to figure
1729 # out if we're supposed to print machine-readable or human-readable
1730 # content at this point. GET/POST seems like a pretty lousy way of
1731 # making the distinction though, as it's just as possible that the
1732 # user agent could have mistakenly been directed to post to the
1735 # Basically, if your request was so broken that you didn't manage to
1736 # include an openid.mode, I'm not going to worry too much about
1737 # returning you something you can't parse.
1742 class VersionError(Exception):
1743 """Raised when an operation was attempted that is not compatible with
1744 the protocol version being used."""
1748 class NoReturnToError(Exception):
1749 """Raised when a response to a request cannot be generated because
1750 the request contains no return_to URL.
1756 class EncodingError(Exception):
1757 """Could not encode this as a protocol message.
1759 You should probably render it and show it to the user.
1761 @ivar response: The response that failed to encode.
1762 @type response: L{OpenIDResponse}
1765 def __init__(self
, response
, explanation
=None):
1766 Exception.__init
__(self
, response
)
1767 self
.response
= response
1768 self
.explanation
= explanation
1771 if self
.explanation
:
1772 s
= '%s: %s' % (self
.__class
__.__name
__,
1775 s
= '%s for Response %s' % (
1776 self
.__class
__.__name
__, response
)
1780 class AlreadySigned(EncodingError
):
1781 """This response is already signed."""
1785 class UntrustedReturnURL(ProtocolError
):
1786 """A return_to is outside the trust_root."""
1788 def __init__(self
, message
, return_to
, trust_root
):
1789 ProtocolError
.__init
__(self
, message
)
1790 self
.return_to
= return_to
1791 self
.trust_root
= trust_root
1794 return "return_to %r not under trust_root %r" % (self
.return_to
,
1798 class MalformedReturnURL(ProtocolError
):
1799 """The return_to URL doesn't look like a valid URL."""
1800 def __init__(self
, openid_message
, return_to
):
1801 self
.return_to
= return_to
1802 ProtocolError
.__init
__(self
, openid_message
)
1806 class MalformedTrustRoot(ProtocolError
):
1807 """The trust root is not well-formed.
1809 @see: OpenID Specs, U{openid.trust_root<http://openid.net/specs.bml#mode-checkid_immediate>}
1814 #class IEncodable: # Interface
1815 # def encodeToURL(return_to):
1816 # """Encode a response as a URL for redirection.
1818 # @returns: A URL to direct the user agent back to.
1823 # def encodeToKvform():
1824 # """Encode a response in key-value colon/newline format.
1826 # This is a machine-readable format used to respond to messages which
1827 # came directly from the consumer and not through the user agent.
1829 # @see: OpenID Specs,
1830 # U{Key-Value Colon/Newline format<http://openid.net/specs.bml#keyvalue>}
1836 # def whichEncoding():
1837 # """How should I be encoded?
1839 # @returns: one of ENCODE_URL, ENCODE_KVFORM, or None. If None,
1840 # I cannot be encoded as a protocol message and should be
1841 # displayed to the user.