getting file size for all dict files to be downloaded. coming to be 400mb or so.
[worddb.git] / libs / openid / extensions / ax.py
blob65d0a512b6329ea7e6bb70df9be8b81a698f3f32
1 # -*- test-case-name: openid.test.test_ax -*-
2 """Implements the OpenID Attribute Exchange specification, version 1.0.
4 @since: 2.1.0
5 """
7 __all__ = [
8 'AttributeRequest',
9 'FetchRequest',
10 'FetchResponse',
11 'StoreRequest',
12 'StoreResponse',
15 from openid import extension
16 from openid.server.trustroot import TrustRoot
17 from openid.message import NamespaceMap, OPENID_NS
19 # Use this as the 'count' value for an attribute in a FetchRequest to
20 # ask for as many values as the OP can provide.
21 UNLIMITED_VALUES = "unlimited"
23 # Minimum supported alias length in characters. Here for
24 # completeness.
25 MINIMUM_SUPPORTED_ALIAS_LENGTH = 32
27 def checkAlias(alias):
28 """
29 Check an alias for invalid characters; raise AXError if any are
30 found. Return None if the alias is valid.
31 """
32 if ',' in alias:
33 raise AXError("Alias %r must not contain comma" % (alias,))
34 if '.' in alias:
35 raise AXError("Alias %r must not contain period" % (alias,))
38 class AXError(ValueError):
39 """Results from data that does not meet the attribute exchange 1.0
40 specification"""
43 class NotAXMessage(AXError):
44 """Raised when there is no Attribute Exchange mode in the message."""
46 def __repr__(self):
47 return self.__class__.__name__
49 def __str__(self):
50 return self.__class__.__name__
53 class AXMessage(extension.Extension):
54 """Abstract class containing common code for attribute exchange messages
56 @cvar ns_alias: The preferred namespace alias for attribute
57 exchange messages
59 @cvar mode: The type of this attribute exchange message. This must
60 be overridden in subclasses.
61 """
63 # This class is abstract, so it's OK that it doesn't override the
64 # abstract method in Extension:
66 #pylint:disable-msg=W0223
68 ns_alias = 'ax'
69 mode = None
70 ns_uri = 'http://openid.net/srv/ax/1.0'
72 def _checkMode(self, ax_args):
73 """Raise an exception if the mode in the attribute exchange
74 arguments does not match what is expected for this class.
76 @raises NotAXMessage: When there is no mode value in ax_args at all.
78 @raises AXError: When mode does not match.
79 """
80 mode = ax_args.get('mode')
81 if mode != self.mode:
82 if not mode:
83 raise NotAXMessage()
84 else:
85 raise AXError(
86 'Expected mode %r; got %r' % (self.mode, mode))
88 def _newArgs(self):
89 """Return a set of attribute exchange arguments containing the
90 basic information that must be in every attribute exchange
91 message.
92 """
93 return {'mode':self.mode}
96 class AttrInfo(object):
97 """Represents a single attribute in an attribute exchange
98 request. This should be added to an AXRequest object in order to
99 request the attribute.
101 @ivar required: Whether the attribute will be marked as required
102 when presented to the subject of the attribute exchange
103 request.
104 @type required: bool
106 @ivar count: How many values of this type to request from the
107 subject. Defaults to one.
108 @type count: int
110 @ivar type_uri: The identifier that determines what the attribute
111 represents and how it is serialized. For example, one type URI
112 representing dates could represent a Unix timestamp in base 10
113 and another could represent a human-readable string.
114 @type type_uri: str
116 @ivar alias: The name that should be given to this alias in the
117 request. If it is not supplied, a generic name will be
118 assigned. For example, if you want to call a Unix timestamp
119 value 'tstamp', set its alias to that value. If two attributes
120 in the same message request to use the same alias, the request
121 will fail to be generated.
122 @type alias: str or NoneType
125 # It's OK that this class doesn't have public methods (it's just a
126 # holder for a bunch of attributes):
128 #pylint:disable-msg=R0903
130 def __init__(self, type_uri, count=1, required=False, alias=None):
131 self.required = required
132 self.count = count
133 self.type_uri = type_uri
134 self.alias = alias
136 if self.alias is not None:
137 checkAlias(self.alias)
139 def wantsUnlimitedValues(self):
141 When processing a request for this attribute, the OP should
142 call this method to determine whether all available attribute
143 values were requested. If self.count == UNLIMITED_VALUES,
144 this returns True. Otherwise this returns False, in which
145 case self.count is an integer.
147 return self.count == UNLIMITED_VALUES
149 def toTypeURIs(namespace_map, alias_list_s):
150 """Given a namespace mapping and a string containing a
151 comma-separated list of namespace aliases, return a list of type
152 URIs that correspond to those aliases.
154 @param namespace_map: The mapping from namespace URI to alias
155 @type namespace_map: openid.message.NamespaceMap
157 @param alias_list_s: The string containing the comma-separated
158 list of aliases. May also be None for convenience.
159 @type alias_list_s: str or NoneType
161 @returns: The list of namespace URIs that corresponds to the
162 supplied list of aliases. If the string was zero-length or
163 None, an empty list will be returned.
165 @raise KeyError: If an alias is present in the list of aliases but
166 is not present in the namespace map.
168 uris = []
170 if alias_list_s:
171 for alias in alias_list_s.split(','):
172 type_uri = namespace_map.getNamespaceURI(alias)
173 if type_uri is None:
174 raise KeyError(
175 'No type is defined for attribute name %r' % (alias,))
176 else:
177 uris.append(type_uri)
179 return uris
182 class FetchRequest(AXMessage):
183 """An attribute exchange 'fetch_request' message. This message is
184 sent by a relying party when it wishes to obtain attributes about
185 the subject of an OpenID authentication request.
187 @ivar requested_attributes: The attributes that have been
188 requested thus far, indexed by the type URI.
189 @type requested_attributes: {str:AttrInfo}
191 @ivar update_url: A URL that will accept responses for this
192 attribute exchange request, even in the absence of the user
193 who made this request.
195 mode = 'fetch_request'
197 def __init__(self, update_url=None):
198 AXMessage.__init__(self)
199 self.requested_attributes = {}
200 self.update_url = update_url
202 def add(self, attribute):
203 """Add an attribute to this attribute exchange request.
205 @param attribute: The attribute that is being requested
206 @type attribute: C{L{AttrInfo}}
208 @returns: None
210 @raise KeyError: when the requested attribute is already
211 present in this fetch request.
213 if attribute.type_uri in self.requested_attributes:
214 raise KeyError('The attribute %r has already been requested'
215 % (attribute.type_uri,))
217 self.requested_attributes[attribute.type_uri] = attribute
219 def getExtensionArgs(self):
220 """Get the serialized form of this attribute fetch request.
222 @returns: The fetch request message parameters
223 @rtype: {unicode:unicode}
225 aliases = NamespaceMap()
227 required = []
228 if_available = []
230 ax_args = self._newArgs()
232 for type_uri, attribute in self.requested_attributes.iteritems():
233 if attribute.alias is None:
234 alias = aliases.add(type_uri)
235 else:
236 # This will raise an exception when the second
237 # attribute with the same alias is added. I think it
238 # would be better to complain at the time that the
239 # attribute is added to this object so that the code
240 # that is adding it is identified in the stack trace,
241 # but it's more work to do so, and it won't be 100%
242 # accurate anyway, since the attributes are
243 # mutable. So for now, just live with the fact that
244 # we'll learn about the error later.
246 # The other possible approach is to hide the error and
247 # generate a new alias on the fly. I think that would
248 # probably be bad.
249 alias = aliases.addAlias(type_uri, attribute.alias)
251 if attribute.required:
252 required.append(alias)
253 else:
254 if_available.append(alias)
256 if attribute.count != 1:
257 ax_args['count.' + alias] = str(attribute.count)
259 ax_args['type.' + alias] = type_uri
261 if required:
262 ax_args['required'] = ','.join(required)
264 if if_available:
265 ax_args['if_available'] = ','.join(if_available)
267 return ax_args
269 def getRequiredAttrs(self):
270 """Get the type URIs for all attributes that have been marked
271 as required.
273 @returns: A list of the type URIs for attributes that have
274 been marked as required.
275 @rtype: [str]
277 required = []
278 for type_uri, attribute in self.requested_attributes.iteritems():
279 if attribute.required:
280 required.append(type_uri)
282 return required
284 def fromOpenIDRequest(cls, openid_request):
285 """Extract a FetchRequest from an OpenID message
287 @param openid_request: The OpenID authentication request
288 containing the attribute fetch request
289 @type openid_request: C{L{openid.server.server.CheckIDRequest}}
291 @rtype: C{L{FetchRequest}} or C{None}
292 @returns: The FetchRequest extracted from the message or None, if
293 the message contained no AX extension.
295 @raises KeyError: if the AuthRequest is not consistent in its use
296 of namespace aliases.
298 @raises AXError: When parseExtensionArgs would raise same.
300 @see: L{parseExtensionArgs}
302 message = openid_request.message
303 ax_args = message.getArgs(cls.ns_uri)
304 self = cls()
305 try:
306 self.parseExtensionArgs(ax_args)
307 except NotAXMessage, err:
308 return None
310 if self.update_url:
311 # Update URL must match the openid.realm of the underlying
312 # OpenID 2 message.
313 realm = message.getArg(OPENID_NS, 'realm',
314 message.getArg(OPENID_NS, 'return_to'))
316 if not realm:
317 raise AXError(("Cannot validate update_url %r " +
318 "against absent realm") % (self.update_url,))
320 tr = TrustRoot.parse(realm)
321 if not tr.validateURL(self.update_url):
322 raise AXError("Update URL %r failed validation against realm %r" %
323 (self.update_url, realm,))
325 return self
327 fromOpenIDRequest = classmethod(fromOpenIDRequest)
329 def parseExtensionArgs(self, ax_args):
330 """Given attribute exchange arguments, populate this FetchRequest.
332 @param ax_args: Attribute Exchange arguments from the request.
333 As returned from L{Message.getArgs<openid.message.Message.getArgs>}.
334 @type ax_args: dict
336 @raises KeyError: if the message is not consistent in its use
337 of namespace aliases.
339 @raises NotAXMessage: If ax_args does not include an Attribute Exchange
340 mode.
342 @raises AXError: If the data to be parsed does not follow the
343 attribute exchange specification. At least when
344 'if_available' or 'required' is not specified for a
345 particular attribute type.
347 # Raises an exception if the mode is not the expected value
348 self._checkMode(ax_args)
350 aliases = NamespaceMap()
352 for key, value in ax_args.iteritems():
353 if key.startswith('type.'):
354 alias = key[5:]
355 type_uri = value
356 aliases.addAlias(type_uri, alias)
358 count_key = 'count.' + alias
359 count_s = ax_args.get(count_key)
360 if count_s:
361 try:
362 count = int(count_s)
363 if count <= 0:
364 raise AXError("Count %r must be greater than zero, got %r" % (count_key, count_s,))
365 except ValueError:
366 if count_s != UNLIMITED_VALUES:
367 raise AXError("Invalid count value for %r: %r" % (count_key, count_s,))
368 count = count_s
369 else:
370 count = 1
372 self.add(AttrInfo(type_uri, alias=alias, count=count))
374 required = toTypeURIs(aliases, ax_args.get('required'))
376 for type_uri in required:
377 self.requested_attributes[type_uri].required = True
379 if_available = toTypeURIs(aliases, ax_args.get('if_available'))
381 all_type_uris = required + if_available
383 for type_uri in aliases.iterNamespaceURIs():
384 if type_uri not in all_type_uris:
385 raise AXError(
386 'Type URI %r was in the request but not '
387 'present in "required" or "if_available"' % (type_uri,))
389 self.update_url = ax_args.get('update_url')
391 def iterAttrs(self):
392 """Iterate over the AttrInfo objects that are
393 contained in this fetch_request.
395 return self.requested_attributes.itervalues()
397 def __iter__(self):
398 """Iterate over the attribute type URIs in this fetch_request
400 return iter(self.requested_attributes)
402 def has_key(self, type_uri):
403 """Is the given type URI present in this fetch_request?
405 return type_uri in self.requested_attributes
407 __contains__ = has_key
410 class AXKeyValueMessage(AXMessage):
411 """An abstract class that implements a message that has attribute
412 keys and values. It contains the common code between
413 fetch_response and store_request.
416 # This class is abstract, so it's OK that it doesn't override the
417 # abstract method in Extension:
419 #pylint:disable-msg=W0223
421 def __init__(self):
422 AXMessage.__init__(self)
423 self.data = {}
425 def addValue(self, type_uri, value):
426 """Add a single value for the given attribute type to the
427 message. If there are already values specified for this type,
428 this value will be sent in addition to the values already
429 specified.
431 @param type_uri: The URI for the attribute
433 @param value: The value to add to the response to the relying
434 party for this attribute
435 @type value: unicode
437 @returns: None
439 try:
440 values = self.data[type_uri]
441 except KeyError:
442 values = self.data[type_uri] = []
444 values.append(value)
446 def setValues(self, type_uri, values):
447 """Set the values for the given attribute type. This replaces
448 any values that have already been set for this attribute.
450 @param type_uri: The URI for the attribute
452 @param values: A list of values to send for this attribute.
453 @type values: [unicode]
456 self.data[type_uri] = values
458 def _getExtensionKVArgs(self, aliases=None):
459 """Get the extension arguments for the key/value pairs
460 contained in this message.
462 @param aliases: An alias mapping. Set to None if you don't
463 care about the aliases for this request.
465 if aliases is None:
466 aliases = NamespaceMap()
468 ax_args = {}
470 for type_uri, values in self.data.iteritems():
471 alias = aliases.add(type_uri)
473 ax_args['type.' + alias] = type_uri
474 ax_args['count.' + alias] = str(len(values))
476 for i, value in enumerate(values):
477 key = 'value.%s.%d' % (alias, i + 1)
478 ax_args[key] = value
480 return ax_args
482 def parseExtensionArgs(self, ax_args):
483 """Parse attribute exchange key/value arguments into this
484 object.
486 @param ax_args: The attribute exchange fetch_response
487 arguments, with namespacing removed.
488 @type ax_args: {unicode:unicode}
490 @returns: None
492 @raises ValueError: If the message has bad values for
493 particular fields
495 @raises KeyError: If the namespace mapping is bad or required
496 arguments are missing
498 self._checkMode(ax_args)
500 aliases = NamespaceMap()
502 for key, value in ax_args.iteritems():
503 if key.startswith('type.'):
504 type_uri = value
505 alias = key[5:]
506 checkAlias(alias)
507 aliases.addAlias(type_uri, alias)
509 for type_uri, alias in aliases.iteritems():
510 try:
511 count_s = ax_args['count.' + alias]
512 except KeyError:
513 value = ax_args['value.' + alias]
515 if value == u'':
516 values = []
517 else:
518 values = [value]
519 else:
520 count = int(count_s)
521 values = []
522 for i in range(1, count + 1):
523 value_key = 'value.%s.%d' % (alias, i)
524 value = ax_args[value_key]
525 values.append(value)
527 self.data[type_uri] = values
529 def getSingle(self, type_uri, default=None):
530 """Get a single value for an attribute. If no value was sent
531 for this attribute, use the supplied default. If there is more
532 than one value for this attribute, this method will fail.
534 @type type_uri: str
535 @param type_uri: The URI for the attribute
537 @param default: The value to return if the attribute was not
538 sent in the fetch_response.
540 @returns: The value of the attribute in the fetch_response
541 message, or the default supplied
542 @rtype: unicode or NoneType
544 @raises ValueError: If there is more than one value for this
545 parameter in the fetch_response message.
546 @raises KeyError: If the attribute was not sent in this response
548 values = self.data.get(type_uri)
549 if not values:
550 return default
551 elif len(values) == 1:
552 return values[0]
553 else:
554 raise AXError(
555 'More than one value present for %r' % (type_uri,))
557 def get(self, type_uri):
558 """Get the list of values for this attribute in the
559 fetch_response.
561 XXX: what to do if the values are not present? default
562 parameter? this is funny because it's always supposed to
563 return a list, so the default may break that, though it's
564 provided by the user's code, so it might be okay. If no
565 default is supplied, should the return be None or []?
567 @param type_uri: The URI of the attribute
569 @returns: The list of values for this attribute in the
570 response. May be an empty list.
571 @rtype: [unicode]
573 @raises KeyError: If the attribute was not sent in the response
575 return self.data[type_uri]
577 def count(self, type_uri):
578 """Get the number of responses for a particular attribute in
579 this fetch_response message.
581 @param type_uri: The URI of the attribute
583 @returns: The number of values sent for this attribute
585 @raises KeyError: If the attribute was not sent in the
586 response. KeyError will not be raised if the number of
587 values was zero.
589 return len(self.get(type_uri))
592 class FetchResponse(AXKeyValueMessage):
593 """A fetch_response attribute exchange message
595 mode = 'fetch_response'
597 def __init__(self, request=None, update_url=None):
599 @param request: When supplied, I will use namespace aliases
600 that match those in this request. I will also check to
601 make sure I do not respond with attributes that were not
602 requested.
604 @type request: L{FetchRequest}
606 @param update_url: By default, C{update_url} is taken from the
607 request. But if you do not supply the request, you may set
608 the C{update_url} here.
610 @type update_url: str
612 AXKeyValueMessage.__init__(self)
613 self.update_url = update_url
614 self.request = request
616 def getExtensionArgs(self):
617 """Serialize this object into arguments in the attribute
618 exchange namespace
620 @returns: The dictionary of unqualified attribute exchange
621 arguments that represent this fetch_response.
622 @rtype: {unicode;unicode}
625 aliases = NamespaceMap()
627 zero_value_types = []
629 if self.request is not None:
630 # Validate the data in the context of the request (the
631 # same attributes should be present in each, and the
632 # counts in the response must be no more than the counts
633 # in the request)
635 for type_uri in self.data:
636 if type_uri not in self.request:
637 raise KeyError(
638 'Response attribute not present in request: %r'
639 % (type_uri,))
641 for attr_info in self.request.iterAttrs():
642 # Copy the aliases from the request so that reading
643 # the response in light of the request is easier
644 if attr_info.alias is None:
645 aliases.add(attr_info.type_uri)
646 else:
647 aliases.addAlias(attr_info.type_uri, attr_info.alias)
649 try:
650 values = self.data[attr_info.type_uri]
651 except KeyError:
652 values = []
653 zero_value_types.append(attr_info)
655 if (attr_info.count != UNLIMITED_VALUES) and \
656 (attr_info.count < len(values)):
657 raise AXError(
658 'More than the number of requested values were '
659 'specified for %r' % (attr_info.type_uri,))
661 kv_args = self._getExtensionKVArgs(aliases)
663 # Add the KV args into the response with the args that are
664 # unique to the fetch_response
665 ax_args = self._newArgs()
667 # For each requested attribute, put its type/alias and count
668 # into the response even if no data were returned.
669 for attr_info in zero_value_types:
670 alias = aliases.getAlias(attr_info.type_uri)
671 kv_args['type.' + alias] = attr_info.type_uri
672 kv_args['count.' + alias] = '0'
674 update_url = ((self.request and self.request.update_url)
675 or self.update_url)
677 if update_url:
678 ax_args['update_url'] = update_url
680 ax_args.update(kv_args)
682 return ax_args
684 def parseExtensionArgs(self, ax_args):
685 """@see: {Extension.parseExtensionArgs<openid.extension.Extension.parseExtensionArgs>}"""
686 super(FetchResponse, self).parseExtensionArgs(ax_args)
687 self.update_url = ax_args.get('update_url')
689 def fromSuccessResponse(cls, success_response, signed=True):
690 """Construct a FetchResponse object from an OpenID library
691 SuccessResponse object.
693 @param success_response: A successful id_res response object
694 @type success_response: openid.consumer.consumer.SuccessResponse
696 @param signed: Whether non-signed args should be
697 processsed. If True (the default), only signed arguments
698 will be processsed.
699 @type signed: bool
701 @returns: A FetchResponse containing the data from the OpenID
702 message, or None if the SuccessResponse did not contain AX
703 extension data.
705 @raises AXError: when the AX data cannot be parsed.
707 self = cls()
708 ax_args = success_response.extensionResponse(self.ns_uri, signed)
710 try:
711 self.parseExtensionArgs(ax_args)
712 except NotAXMessage, err:
713 return None
714 else:
715 return self
717 fromSuccessResponse = classmethod(fromSuccessResponse)
720 class StoreRequest(AXKeyValueMessage):
721 """A store request attribute exchange message representation
723 mode = 'store_request'
725 def __init__(self, aliases=None):
727 @param aliases: The namespace aliases to use when making this
728 store request. Leave as None to use defaults.
730 super(StoreRequest, self).__init__()
731 self.aliases = aliases
733 def getExtensionArgs(self):
735 @see: L{Extension.getExtensionArgs<openid.extension.Extension.getExtensionArgs>}
737 ax_args = self._newArgs()
738 kv_args = self._getExtensionKVArgs(self.aliases)
739 ax_args.update(kv_args)
740 return ax_args
743 class StoreResponse(AXMessage):
744 """An indication that the store request was processed along with
745 this OpenID transaction.
748 SUCCESS_MODE = 'store_response_success'
749 FAILURE_MODE = 'store_response_failure'
751 def __init__(self, succeeded=True, error_message=None):
752 AXMessage.__init__(self)
754 if succeeded and error_message is not None:
755 raise AXError('An error message may only be included in a '
756 'failing fetch response')
757 if succeeded:
758 self.mode = self.SUCCESS_MODE
759 else:
760 self.mode = self.FAILURE_MODE
762 self.error_message = error_message
764 def succeeded(self):
765 """Was this response a success response?"""
766 return self.mode == self.SUCCESS_MODE
768 def getExtensionArgs(self):
769 """@see: {Extension.getExtensionArgs<openid.extension.Extension.getExtensionArgs>}"""
770 ax_args = self._newArgs()
771 if not self.succeeded() and self.error_message:
772 ax_args['error'] = self.error_message
774 return ax_args