1
2 """Implements the OpenID Attribute Exchange specification, version 1.0.
3
4 @since: 2.1.0
5 """
6
7 __all__ = [
8 'AttributeRequest',
9 'FetchRequest',
10 'FetchResponse',
11 'StoreRequest',
12 'StoreResponse',
13 ]
14
15 from openid import extension
16 from openid.server.trustroot import TrustRoot
17 from openid.message import NamespaceMap, OPENID_NS
18
19
20
21 UNLIMITED_VALUES = "unlimited"
22
23
24
25 MINIMUM_SUPPORTED_ALIAS_LENGTH = 32
26
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,))
36
37
39 """Results from data that does not meet the attribute exchange 1.0
40 specification"""
41
42
44 """Raised when there is no Attribute Exchange mode in the message."""
45
47 return self.__class__.__name__
48
50 return self.__class__.__name__
51
52
54 """Abstract class containing common code for attribute exchange messages
55
56 @cvar ns_alias: The preferred namespace alias for attribute
57 exchange messages
58
59 @cvar mode: The type of this attribute exchange message. This must
60 be overridden in subclasses.
61 """
62
63
64
65
66
67
68 ns_alias = 'ax'
69 mode = None
70 ns_uri = 'http://openid.net/srv/ax/1.0'
71
73 """Raise an exception if the mode in the attribute exchange
74 arguments does not match what is expected for this class.
75
76 @raises NotAXMessage: When there is no mode value in ax_args at all.
77
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))
87
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}
94
95
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.
100
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
105
106 @ivar count: How many values of this type to request from the
107 subject. Defaults to one.
108 @type count: int
109
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
115
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
123 """
124
125
126
127
128
129
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
135
136 if self.alias is not None:
137 checkAlias(self.alias)
138
140 """
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.
146 """
147 return self.count == UNLIMITED_VALUES
148
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.
153
154 @param namespace_map: The mapping from namespace URI to alias
155 @type namespace_map: openid.message.NamespaceMap
156
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
160
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.
164
165 @raise KeyError: If an alias is present in the list of aliases but
166 is not present in the namespace map.
167 """
168 uris = []
169
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)
178
179 return uris
180
181
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.
186
187 @ivar requested_attributes: The attributes that have been
188 requested thus far, indexed by the type URI.
189 @type requested_attributes: {str:AttrInfo}
190
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.
194 """
195 mode = 'fetch_request'
196
198 AXMessage.__init__(self)
199 self.requested_attributes = {}
200 self.update_url = update_url
201
202 - def add(self, attribute):
203 """Add an attribute to this attribute exchange request.
204
205 @param attribute: The attribute that is being requested
206 @type attribute: C{L{AttrInfo}}
207
208 @returns: None
209
210 @raise KeyError: when the requested attribute is already
211 present in this fetch request.
212 """
213 if attribute.type_uri in self.requested_attributes:
214 raise KeyError('The attribute %r has already been requested'
215 % (attribute.type_uri,))
216
217 self.requested_attributes[attribute.type_uri] = attribute
218
220 """Get the serialized form of this attribute fetch request.
221
222 @returns: The fetch request message parameters
223 @rtype: {unicode:unicode}
224 """
225 aliases = NamespaceMap()
226
227 required = []
228 if_available = []
229
230 ax_args = self._newArgs()
231
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
237
238
239
240
241
242
243
244
245
246
247
248
249 alias = aliases.addAlias(type_uri, attribute.alias)
250
251 if attribute.required:
252 required.append(alias)
253 else:
254 if_available.append(alias)
255
256 if attribute.count != 1:
257 ax_args['count.' + alias] = str(attribute.count)
258
259 ax_args['type.' + alias] = type_uri
260
261 if required:
262 ax_args['required'] = ','.join(required)
263
264 if if_available:
265 ax_args['if_available'] = ','.join(if_available)
266
267 return ax_args
268
270 """Get the type URIs for all attributes that have been marked
271 as required.
272
273 @returns: A list of the type URIs for attributes that have
274 been marked as required.
275 @rtype: [str]
276 """
277 required = []
278 for type_uri, attribute in self.requested_attributes.iteritems():
279 if attribute.required:
280 required.append(type_uri)
281
282 return required
283
285 """Extract a FetchRequest from an OpenID message
286
287 @param openid_request: The OpenID authentication request
288 containing the attribute fetch request
289 @type openid_request: C{L{openid.server.server.CheckIDRequest}}
290
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.
294
295 @raises KeyError: if the AuthRequest is not consistent in its use
296 of namespace aliases.
297
298 @raises AXError: When parseExtensionArgs would raise same.
299
300 @see: L{parseExtensionArgs}
301 """
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
309
310 if self.update_url:
311
312
313 realm = message.getArg(OPENID_NS, 'realm',
314 message.getArg(OPENID_NS, 'return_to'))
315
316 if not realm:
317 raise AXError(("Cannot validate update_url %r " +
318 "against absent realm") % (self.update_url,))
319
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,))
324
325 return self
326
327 fromOpenIDRequest = classmethod(fromOpenIDRequest)
328
330 """Given attribute exchange arguments, populate this FetchRequest.
331
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
335
336 @raises KeyError: if the message is not consistent in its use
337 of namespace aliases.
338
339 @raises NotAXMessage: If ax_args does not include an Attribute Exchange
340 mode.
341
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.
346 """
347
348 self._checkMode(ax_args)
349
350 aliases = NamespaceMap()
351
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)
357
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
371
372 self.add(AttrInfo(type_uri, alias=alias, count=count))
373
374 required = toTypeURIs(aliases, ax_args.get('required'))
375
376 for type_uri in required:
377 self.requested_attributes[type_uri].required = True
378
379 if_available = toTypeURIs(aliases, ax_args.get('if_available'))
380
381 all_type_uris = required + if_available
382
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,))
388
389 self.update_url = ax_args.get('update_url')
390
392 """Iterate over the AttrInfo objects that are
393 contained in this fetch_request.
394 """
395 return self.requested_attributes.itervalues()
396
398 """Iterate over the attribute type URIs in this fetch_request
399 """
400 return iter(self.requested_attributes)
401
403 """Is the given type URI present in this fetch_request?
404 """
405 return type_uri in self.requested_attributes
406
407 __contains__ = has_key
408
409
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.
414 """
415
416
417
418
419
420
424
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.
430
431 @param type_uri: The URI for the attribute
432
433 @param value: The value to add to the response to the relying
434 party for this attribute
435 @type value: unicode
436
437 @returns: None
438 """
439 try:
440 values = self.data[type_uri]
441 except KeyError:
442 values = self.data[type_uri] = []
443
444 values.append(value)
445
447 """Set the values for the given attribute type. This replaces
448 any values that have already been set for this attribute.
449
450 @param type_uri: The URI for the attribute
451
452 @param values: A list of values to send for this attribute.
453 @type values: [unicode]
454 """
455
456 self.data[type_uri] = values
457
458 - def _getExtensionKVArgs(self, aliases=None):
459 """Get the extension arguments for the key/value pairs
460 contained in this message.
461
462 @param aliases: An alias mapping. Set to None if you don't
463 care about the aliases for this request.
464 """
465 if aliases is None:
466 aliases = NamespaceMap()
467
468 ax_args = {}
469
470 for type_uri, values in self.data.iteritems():
471 alias = aliases.add(type_uri)
472
473 ax_args['type.' + alias] = type_uri
474 ax_args['count.' + alias] = str(len(values))
475
476 for i, value in enumerate(values):
477 key = 'value.%s.%d' % (alias, i + 1)
478 ax_args[key] = value
479
480 return ax_args
481
483 """Parse attribute exchange key/value arguments into this
484 object.
485
486 @param ax_args: The attribute exchange fetch_response
487 arguments, with namespacing removed.
488 @type ax_args: {unicode:unicode}
489
490 @returns: None
491
492 @raises ValueError: If the message has bad values for
493 particular fields
494
495 @raises KeyError: If the namespace mapping is bad or required
496 arguments are missing
497 """
498 self._checkMode(ax_args)
499
500 aliases = NamespaceMap()
501
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)
508
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]
514
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)
526
527 self.data[type_uri] = values
528
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.
533
534 @type type_uri: str
535 @param type_uri: The URI for the attribute
536
537 @param default: The value to return if the attribute was not
538 sent in the fetch_response.
539
540 @returns: The value of the attribute in the fetch_response
541 message, or the default supplied
542 @rtype: unicode or NoneType
543
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
547 """
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,))
556
557 - def get(self, type_uri):
558 """Get the list of values for this attribute in the
559 fetch_response.
560
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 []?
566
567 @param type_uri: The URI of the attribute
568
569 @returns: The list of values for this attribute in the
570 response. May be an empty list.
571 @rtype: [unicode]
572
573 @raises KeyError: If the attribute was not sent in the response
574 """
575 return self.data[type_uri]
576
577 - def count(self, type_uri):
578 """Get the number of responses for a particular attribute in
579 this fetch_response message.
580
581 @param type_uri: The URI of the attribute
582
583 @returns: The number of values sent for this attribute
584
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.
588 """
589 return len(self.get(type_uri))
590
591
593 """A fetch_response attribute exchange message
594 """
595 mode = 'fetch_response'
596
597 - def __init__(self, request=None, update_url=None):
598 """
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.
603
604 @type request: L{FetchRequest}
605
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.
609
610 @type update_url: str
611 """
612 AXKeyValueMessage.__init__(self)
613 self.update_url = update_url
614 self.request = request
615
617 """Serialize this object into arguments in the attribute
618 exchange namespace
619
620 @returns: The dictionary of unqualified attribute exchange
621 arguments that represent this fetch_response.
622 @rtype: {unicode;unicode}
623 """
624
625 aliases = NamespaceMap()
626
627 zero_value_types = []
628
629 if self.request is not None:
630
631
632
633
634
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,))
640
641 for attr_info in self.request.iterAttrs():
642
643
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)
648
649 try:
650 values = self.data[attr_info.type_uri]
651 except KeyError:
652 values = []
653 zero_value_types.append(attr_info)
654
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,))
660
661 kv_args = self._getExtensionKVArgs(aliases)
662
663
664
665 ax_args = self._newArgs()
666
667
668
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'
673
674 update_url = ((self.request and self.request.update_url)
675 or self.update_url)
676
677 if update_url:
678 ax_args['update_url'] = update_url
679
680 ax_args.update(kv_args)
681
682 return ax_args
683
685 """@see: {Extension.parseExtensionArgs<openid.extension.Extension.parseExtensionArgs>}"""
686 super(FetchResponse, self).parseExtensionArgs(ax_args)
687 self.update_url = ax_args.get('update_url')
688
690 """Construct a FetchResponse object from an OpenID library
691 SuccessResponse object.
692
693 @param success_response: A successful id_res response object
694 @type success_response: openid.consumer.consumer.SuccessResponse
695
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
700
701 @returns: A FetchResponse containing the data from the OpenID
702 message, or None if the SuccessResponse did not contain AX
703 extension data.
704
705 @raises AXError: when the AX data cannot be parsed.
706 """
707 self = cls()
708 ax_args = success_response.extensionResponse(self.ns_uri, signed)
709
710 try:
711 self.parseExtensionArgs(ax_args)
712 except NotAXMessage, err:
713 return None
714 else:
715 return self
716
717 fromSuccessResponse = classmethod(fromSuccessResponse)
718
719
721 """A store request attribute exchange message representation
722 """
723 mode = 'store_request'
724
726 """
727 @param aliases: The namespace aliases to use when making this
728 store request. Leave as None to use defaults.
729 """
730 super(StoreRequest, self).__init__()
731 self.aliases = aliases
732
734 """
735 @see: L{Extension.getExtensionArgs<openid.extension.Extension.getExtensionArgs>}
736 """
737 ax_args = self._newArgs()
738 kv_args = self._getExtensionKVArgs(self.aliases)
739 ax_args.update(kv_args)
740 return ax_args
741
742
744 """An indication that the store request was processed along with
745 this OpenID transaction.
746 """
747
748 SUCCESS_MODE = 'store_response_success'
749 FAILURE_MODE = 'store_response_failure'
750
751 - def __init__(self, succeeded=True, error_message=None):
752 AXMessage.__init__(self)
753
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
761
762 self.error_message = error_message
763
765 """Was this response a success response?"""
766 return self.mode == self.SUCCESS_MODE
767
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
773
774 return ax_args
775