FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
python-openid/openid/server/server.py at master · Jumple/python-openid · GitHub
Jumple
/
python-openid
Public
forked from
openid/python-openid
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
python-openid
/
openid
/
server
/
server.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1852 lines (1414 loc) · 64.2 KB
Breadcrumbs
python-openid
/
openid
/
server
/
server.py
Copy path
File metadata and controls
1852 lines (1414 loc) · 64.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- test-case-name: openid.test.test_server -*-
"""OpenID server protocol and logic.
Overview
========
An OpenID server must perform three tasks:
1. Examine the incoming request to determine its nature and validity.
2. Make a decision about how to respond to this request.
3. Format the response according to the protocol.
The first and last of these tasks may performed by
the L{decodeRequest<Server.decodeRequest>} and
L{encodeResponse<Server.encodeResponse>} methods of the
L{Server} object. Who gets to do the intermediate task -- deciding
how to respond to the request -- will depend on what type of request it
is.
If it's a request to authenticate a user (a X{C{checkid_setup}} or
X{C{checkid_immediate}} request), you need to decide if you will assert
that this user may claim the identity in question. Exactly how you do
that is a matter of application policy, but it generally involves making
sure the user has an account with your system and is logged in, checking
to see if that identity is hers to claim, and verifying with the user that
she does consent to releasing that information to the party making the
request.
Examine the properties of the L{CheckIDRequest} object, optionally
check L{CheckIDRequest.returnToVerified}, and and when you've come
to a decision, form a response by calling L{CheckIDRequest.answer}.
Other types of requests relate to establishing associations between client
and server and verifying the authenticity of previous communications.
L{Server} contains all the logic and data necessary to respond to
such requests; just pass the request to L{Server.handleRequest}.
OpenID Extensions
=================
Do you want to provide other information for your users
in addition to authentication? Version 2.0 of the OpenID
protocol allows consumers to add extensions to their requests.
For example, with sites using the U{Simple Registration
Extension<http://openid.net/specs/openid-simple-registration-extension-1_0.html>},
a user can agree to have their nickname and e-mail address sent to a
site when they sign up.
Since extensions do not change the way OpenID authentication works,
code to handle extension requests may be completely separate from the
L{OpenIDRequest} class here. But you'll likely want data sent back by
your extension to be signed. L{OpenIDResponse} provides methods with
which you can add data to it which can be signed with the other data in
the OpenID signature.
For example::
# when request is a checkid_* request
response = request.answer(True)
# this will a signed 'openid.sreg.timezone' parameter to the response
# as well as a namespace declaration for the openid.sreg namespace
response.fields.setArg('http://openid.net/sreg/1.0', 'timezone', 'America/Los_Angeles')
There are helper modules for a number of extensions, including
L{Attribute Exchange<openid.extensions.ax>},
L{PAPE<openid.extensions.pape>}, and
L{Simple Registration<openid.extensions.sreg>} in the L{openid.extensions}
package.
Stores
======
The OpenID server needs to maintain state between requests in order
to function. Its mechanism for doing this is called a store. The
store interface is defined in C{L{openid.store.interface.OpenIDStore}}.
Additionally, several concrete store implementations are provided, so that
most sites won't need to implement a custom store. For a store backed
by flat files on disk, see C{L{openid.store.filestore.FileOpenIDStore}}.
For stores based on MySQL or SQLite, see the C{L{openid.store.sqlstore}}
module.
Upgrading
=========
From 1.0 to 1.1
---------------
The keys by which a server looks up associations in its store have changed
in version 1.2 of this library. If your store has entries created from
version 1.0 code, you should empty it.
From 1.1 to 2.0
---------------
One of the additions to the OpenID protocol was a specified nonce
format for one-way nonces. As a result, the nonce table in the store
has changed. You'll need to run contrib/upgrade-store-1.1-to-2.0 to
upgrade your store, or you'll encounter errors about the wrong number
of columns in the oid_nonces table.
If you've written your own custom store or code that interacts
directly with it, you'll need to review the change notes in
L{openid.store.interface}.
@group Requests: OpenIDRequest, AssociateRequest, CheckIDRequest,
CheckAuthRequest
@group Responses: OpenIDResponse
@group HTTP Codes: HTTP_OK, HTTP_REDIRECT, HTTP_ERROR
@group Response Encodings: ENCODE_KVFORM, ENCODE_HTML_FORM, ENCODE_URL
"""
import
time
,
warnings
import
logging
from
copy
import
deepcopy
from
openid
import
cryptutil
from
openid
import
oidutil
from
openid
import
kvform
from
openid
.
dh
import
DiffieHellman
from
openid
.
store
.
nonce
import
mkNonce
from
openid
.
server
.
trustroot
import
TrustRoot
,
verifyReturnTo
from
openid
.
association
import
Association
,
default_negotiator
,
getSecretSize
from
openid
.
message
import
Message
,
InvalidOpenIDNamespace
, \
OPENID_NS
,
OPENID2_NS
,
IDENTIFIER_SELECT
,
OPENID1_URL_LIMIT
from
openid
.
urinorm
import
urinorm
HTTP_OK
=
200
HTTP_REDIRECT
=
302
HTTP_ERROR
=
400
BROWSER_REQUEST_MODES
=
[
'checkid_setup'
,
'checkid_immediate'
]
ENCODE_KVFORM
=
(
'kvform'
,)
ENCODE_URL
=
(
'URL/redirect'
,)
ENCODE_HTML_FORM
=
(
'HTML form'
,)
UNUSED
=
None
class
OpenIDRequest
(
object
):
"""I represent an incoming OpenID request.
@cvar mode: the C{X{openid.mode}} of this request.
@type mode: str
"""
mode
=
None
class
CheckAuthRequest
(
OpenIDRequest
):
"""A request to verify the validity of a previous response.
@cvar mode: "X{C{check_authentication}}"
@type mode: str
@ivar assoc_handle: The X{association handle} the response was signed with.
@type assoc_handle: str
@ivar signed: The message with the signature which wants checking.
@type signed: L{Message}
@ivar invalidate_handle: An X{association handle} the client is asking
about the validity of. Optional, may be C{None}.
@type invalidate_handle: str
@see: U{OpenID Specs, Mode: check_authentication
<http://openid.net/specs.bml#mode-check_authentication>}
"""
mode
=
"check_authentication"
required_fields
=
[
"identity"
,
"return_to"
,
"response_nonce"
]
def
__init__
(
self
,
assoc_handle
,
signed
,
invalidate_handle
=
None
):
"""Construct me.
These parameters are assigned directly as class attributes, see
my L{class documentation<CheckAuthRequest>} for their descriptions.
@type assoc_handle: str
@type signed: L{Message}
@type invalidate_handle: str
"""
self
.
assoc_handle
=
assoc_handle
self
.
signed
=
signed
self
.
invalidate_handle
=
invalidate_handle
self
.
namespace
=
OPENID2_NS
def
fromMessage
(
klass
,
message
,
op_endpoint
=
UNUSED
):
"""Construct me from an OpenID Message.
@param message: An OpenID check_authentication Message
@type message: L{openid.message.Message}
@returntype: L{CheckAuthRequest}
"""
self
=
klass
.
__new__
(
klass
)
self
.
message
=
message
self
.
namespace
=
message
.
getOpenIDNamespace
()
self
.
assoc_handle
=
message
.
getArg
(
OPENID_NS
,
'assoc_handle'
)
self
.
sig
=
message
.
getArg
(
OPENID_NS
,
'sig'
)
if
(
self
.
assoc_handle
is
None
or
self
.
sig
is
None
):
fmt
=
"%s request missing required parameter from message %s"
raise
ProtocolError
(
message
,
text
=
fmt
%
(
self
.
mode
,
message
))
self
.
invalidate_handle
=
message
.
getArg
(
OPENID_NS
,
'invalidate_handle'
)
self
.
signed
=
message
.
copy
()
# openid.mode is currently check_authentication because
# that's the mode of this request. But the signature
# was made on something with a different openid.mode.
# http://article.gmane.org/gmane.comp.web.openid.general/537
if
self
.
signed
.
hasKey
(
OPENID_NS
,
"mode"
):
self
.
signed
.
setArg
(
OPENID_NS
,
"mode"
,
"id_res"
)
return
self
fromMessage
=
classmethod
(
fromMessage
)
def
answer
(
self
,
signatory
):
"""Respond to this request.
Given a L{Signatory}, I can check the validity of the signature and
the X{C{invalidate_handle}}.
@param signatory: The L{Signatory} to use to check the signature.
@type signatory: L{Signatory}
@returns: A response with an X{C{is_valid}} (and, if
appropriate X{C{invalidate_handle}}) field.
@returntype: L{OpenIDResponse}
"""
is_valid
=
signatory
.
verify
(
self
.
assoc_handle
,
self
.
signed
)
# Now invalidate that assoc_handle so it this checkAuth message cannot
# be replayed.
signatory
.
invalidate
(
self
.
assoc_handle
,
dumb
=
True
)
response
=
OpenIDResponse
(
self
)
valid_str
=
(
is_valid
and
"true"
)
or
"false"
response
.
fields
.
setArg
(
OPENID_NS
,
'is_valid'
,
valid_str
)
if
self
.
invalidate_handle
:
assoc
=
signatory
.
getAssociation
(
self
.
invalidate_handle
,
dumb
=
False
)
if
not
assoc
:
response
.
fields
.
setArg
(
OPENID_NS
,
'invalidate_handle'
,
self
.
invalidate_handle
)
return
response
def
__str__
(
self
):
if
self
.
invalidate_handle
:
ih
=
" invalidate? %r"
%
(
self
.
invalidate_handle
,)
else
:
ih
=
""
s
=
"<%s handle: %r sig: %r: signed: %r%s>"
%
(
self
.
__class__
.
__name__
,
self
.
assoc_handle
,
self
.
sig
,
self
.
signed
,
ih
)
return
s
class
PlainTextServerSession
(
object
):
"""An object that knows how to handle association requests with no
session type.
@cvar session_type: The session_type for this association
session. There is no type defined for plain-text in the OpenID
specification, so we use 'no-encryption'.
@type session_type: str
@see: U{OpenID Specs, Mode: associate
<http://openid.net/specs.bml#mode-associate>}
@see: AssociateRequest
"""
session_type
=
'no-encryption'
allowed_assoc_types
=
[
'HMAC-SHA1'
,
'HMAC-SHA256'
]
def
fromMessage
(
cls
,
unused_request
):
return
cls
()
fromMessage
=
classmethod
(
fromMessage
)
def
answer
(
self
,
secret
):
return
{
'mac_key'
:
oidutil
.
toBase64
(
secret
)}
class
DiffieHellmanSHA1ServerSession
(
object
):
"""An object that knows how to handle association requests with the
Diffie-Hellman session type.
@cvar session_type: The session_type for this association
session.
@type session_type: str
@ivar dh: The Diffie-Hellman algorithm values for this request
@type dh: DiffieHellman
@ivar consumer_pubkey: The public key sent by the consumer in the
associate request
@type consumer_pubkey: long
@see: U{OpenID Specs, Mode: associate
<http://openid.net/specs.bml#mode-associate>}
@see: AssociateRequest
"""
session_type
=
'DH-SHA1'
hash_func
=
staticmethod
(
cryptutil
.
sha1
)
allowed_assoc_types
=
[
'HMAC-SHA1'
]
def
__init__
(
self
,
dh
,
consumer_pubkey
):
self
.
dh
=
dh
self
.
consumer_pubkey
=
consumer_pubkey
def
fromMessage
(
cls
,
message
):
"""
@param message: The associate request message
@type message: openid.message.Message
@returntype: L{DiffieHellmanSHA1ServerSession}
@raises ProtocolError: When parameters required to establish the
session are missing.
"""
dh_modulus
=
message
.
getArg
(
OPENID_NS
,
'dh_modulus'
)
dh_gen
=
message
.
getArg
(
OPENID_NS
,
'dh_gen'
)
if
(
dh_modulus
is
None
and
dh_gen
is
not
None
or
dh_gen
is
None
and
dh_modulus
is
not
None
):
if
dh_modulus
is
None
:
missing
=
'modulus'
else
:
missing
=
'generator'
raise
ProtocolError
(
message
,
'If non-default modulus or generator is '
'supplied, both must be supplied. Missing %s'
%
(
missing
,))
if
dh_modulus
or
dh_gen
:
dh_modulus
=
cryptutil
.
base64ToLong
(
dh_modulus
)
dh_gen
=
cryptutil
.
base64ToLong
(
dh_gen
)
dh
=
DiffieHellman
(
dh_modulus
,
dh_gen
)
else
:
dh
=
DiffieHellman
.
fromDefaults
()
consumer_pubkey
=
message
.
getArg
(
OPENID_NS
,
'dh_consumer_public'
)
if
consumer_pubkey
is
None
:
raise
ProtocolError
(
message
,
"Public key for DH-SHA1 session "
"not found in message %s"
%
(
message
,))
consumer_pubkey
=
cryptutil
.
base64ToLong
(
consumer_pubkey
)
return
cls
(
dh
,
consumer_pubkey
)
fromMessage
=
classmethod
(
fromMessage
)
def
answer
(
self
,
secret
):
mac_key
=
self
.
dh
.
xorSecret
(
self
.
consumer_pubkey
,
secret
,
self
.
hash_func
)
return
{
'dh_server_public'
:
cryptutil
.
longToBase64
(
self
.
dh
.
public
),
'enc_mac_key'
:
oidutil
.
toBase64
(
mac_key
),
}
class
DiffieHellmanSHA256ServerSession
(
DiffieHellmanSHA1ServerSession
):
session_type
=
'DH-SHA256'
hash_func
=
staticmethod
(
cryptutil
.
sha256
)
allowed_assoc_types
=
[
'HMAC-SHA256'
]
class
AssociateRequest
(
OpenIDRequest
):
"""A request to establish an X{association}.
@cvar mode: "X{C{check_authentication}}"
@type mode: str
@ivar assoc_type: The type of association. The protocol currently only
defines one value for this, "X{C{HMAC-SHA1}}".
@type assoc_type: str
@ivar session: An object that knows how to handle association
requests of a certain type.
@see: U{OpenID Specs, Mode: associate
<http://openid.net/specs.bml#mode-associate>}
"""
mode
=
"associate"
session_classes
=
{
'no-encryption'
:
PlainTextServerSession
,
'DH-SHA1'
:
DiffieHellmanSHA1ServerSession
,
'DH-SHA256'
:
DiffieHellmanSHA256ServerSession
,
}
def
__init__
(
self
,
session
,
assoc_type
):
"""Construct me.
The session is assigned directly as a class attribute. See my
L{class documentation<AssociateRequest>} for its description.
"""
super
(
AssociateRequest
,
self
).
__init__
()
self
.
session
=
session
self
.
assoc_type
=
assoc_type
self
.
namespace
=
OPENID2_NS
def
fromMessage
(
klass
,
message
,
op_endpoint
=
UNUSED
):
"""Construct me from an OpenID Message.
@param message: The OpenID associate request
@type message: openid.message.Message
@returntype: L{AssociateRequest}
"""
if
message
.
isOpenID1
():
session_type
=
message
.
getArg
(
OPENID_NS
,
'session_type'
)
if
session_type
==
'no-encryption'
:
logging
.
warn
(
'Received OpenID 1 request with a no-encryption '
'assocaition session type. Continuing anyway.'
)
elif
not
session_type
:
session_type
=
'no-encryption'
else
:
session_type
=
message
.
getArg
(
OPENID2_NS
,
'session_type'
)
if
session_type
is
None
:
raise
ProtocolError
(
message
,
text
=
"session_type missing from request"
)
try
:
session_class
=
klass
.
session_classes
[
session_type
]
except
KeyError
:
raise
ProtocolError
(
message
,
"Unknown session type %r"
%
(
session_type
,))
try
:
session
=
session_class
.
fromMessage
(
message
)
except
ValueError
,
why
:
raise
ProtocolError
(
message
,
'Error parsing %s session: %s'
%
(
session_class
.
session_type
,
why
[
0
]))
assoc_type
=
message
.
getArg
(
OPENID_NS
,
'assoc_type'
,
'HMAC-SHA1'
)
if
assoc_type
not
in
session
.
allowed_assoc_types
:
fmt
=
'Session type %s does not support association type %s'
raise
ProtocolError
(
message
,
fmt
%
(
session_type
,
assoc_type
))
self
=
klass
(
session
,
assoc_type
)
self
.
message
=
message
self
.
namespace
=
message
.
getOpenIDNamespace
()
return
self
fromMessage
=
classmethod
(
fromMessage
)
def
answer
(
self
,
assoc
):
"""Respond to this request with an X{association}.
@param assoc: The association to send back.
@type assoc: L{openid.association.Association}
@returns: A response with the association information, encrypted
to the consumer's X{public key} if appropriate.
@returntype: L{OpenIDResponse}
"""
response
=
OpenIDResponse
(
self
)
response
.
fields
.
updateArgs
(
OPENID_NS
, {
'expires_in'
:
'%d'
%
(
assoc
.
getExpiresIn
(),),
'assoc_type'
:
self
.
assoc_type
,
'assoc_handle'
:
assoc
.
handle
,
})
response
.
fields
.
updateArgs
(
OPENID_NS
,
self
.
session
.
answer
(
assoc
.
secret
))
if
not
(
self
.
session
.
session_type
==
'no-encryption'
and
self
.
message
.
isOpenID1
()):
# The session type "no-encryption" did not have a name
# in OpenID v1, it was just omitted.
response
.
fields
.
setArg
(
OPENID_NS
,
'session_type'
,
self
.
session
.
session_type
)
return
response
def
answerUnsupported
(
self
,
message
,
preferred_association_type
=
None
,
preferred_session_type
=
None
):
"""Respond to this request indicating that the association
type or association session type is not supported."""
if
self
.
message
.
isOpenID1
():
raise
ProtocolError
(
self
.
message
)
response
=
OpenIDResponse
(
self
)
response
.
fields
.
setArg
(
OPENID_NS
,
'error_code'
,
'unsupported-type'
)
response
.
fields
.
setArg
(
OPENID_NS
,
'error'
,
message
)
if
preferred_association_type
:
response
.
fields
.
setArg
(
OPENID_NS
,
'assoc_type'
,
preferred_association_type
)
if
preferred_session_type
:
response
.
fields
.
setArg
(
OPENID_NS
,
'session_type'
,
preferred_session_type
)
return
response
class
CheckIDRequest
(
OpenIDRequest
):
"""A request to confirm the identity of a user.
This class handles requests for openid modes X{C{checkid_immediate}}
and X{C{checkid_setup}}.
@cvar mode: "X{C{checkid_immediate}}" or "X{C{checkid_setup}}"
@type mode: str
@ivar immediate: Is this an immediate-mode request?
@type immediate: bool
@ivar identity: The OP-local identifier being checked.
@type identity: str
@ivar claimed_id: The claimed identifier. Not present in OpenID 1.x
messages.
@type claimed_id: str
@ivar trust_root: "Are you Frank?" asks the checkid request. "Who wants
to know?" C{trust_root}, that's who. This URL identifies the party
making the request, and the user will use that to make her decision
about what answer she trusts them to have. Referred to as "realm" in
OpenID 2.0.
@type trust_root: str
@ivar return_to: The URL to send the user agent back to to reply to this
request.
@type return_to: str
@ivar assoc_handle: Provided in smart mode requests, a handle for a
previously established association. C{None} for dumb mode requests.
@type assoc_handle: str
"""
def
__init__
(
self
,
identity
,
return_to
,
trust_root
=
None
,
immediate
=
False
,
assoc_handle
=
None
,
op_endpoint
=
None
,
claimed_id
=
None
):
"""Construct me.
These parameters are assigned directly as class attributes, see
my L{class documentation<CheckIDRequest>} for their descriptions.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
"""
self
.
assoc_handle
=
assoc_handle
self
.
identity
=
identity
self
.
claimed_id
=
claimed_id
or
identity
self
.
return_to
=
return_to
self
.
trust_root
=
trust_root
or
return_to
self
.
op_endpoint
=
op_endpoint
assert
self
.
op_endpoint
is
not
None
if
immediate
:
self
.
immediate
=
True
self
.
mode
=
"checkid_immediate"
else
:
self
.
immediate
=
False
self
.
mode
=
"checkid_setup"
if
self
.
return_to
is
not
None
and
\
not
TrustRoot
.
parse
(
self
.
return_to
):
raise
MalformedReturnURL
(
None
,
self
.
return_to
)
if
not
self
.
trustRootValid
():
raise
UntrustedReturnURL
(
None
,
self
.
return_to
,
self
.
trust_root
)
self
.
message
=
None
def
_getNamespace
(
self
):
warnings
.
warn
(
'The "namespace" attribute of CheckIDRequest objects '
'is deprecated. Use "message.getOpenIDNamespace()" '
'instead'
,
DeprecationWarning
,
stacklevel
=
2
)
return
self
.
message
.
getOpenIDNamespace
()
namespace
=
property
(
_getNamespace
)
def
fromMessage
(
klass
,
message
,
op_endpoint
):
"""Construct me from an OpenID message.
@raises ProtocolError: When not all required parameters are present
in the message.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
@raises UntrustedReturnURL: When the C{return_to} URL is outside
the C{trust_root}.
@param message: An OpenID checkid_* request Message
@type message: openid.message.Message
@param op_endpoint: The endpoint URL of the server that this
message was sent to.
@type op_endpoint: str
@returntype: L{CheckIDRequest}
"""
self
=
klass
.
__new__
(
klass
)
self
.
message
=
message
self
.
op_endpoint
=
op_endpoint
mode
=
message
.
getArg
(
OPENID_NS
,
'mode'
)
if
mode
==
"checkid_immediate"
:
self
.
immediate
=
True
self
.
mode
=
"checkid_immediate"
else
:
self
.
immediate
=
False
self
.
mode
=
"checkid_setup"
self
.
return_to
=
message
.
getArg
(
OPENID_NS
,
'return_to'
)
if
message
.
isOpenID1
()
and
not
self
.
return_to
:
fmt
=
"Missing required field 'return_to' from %r"
raise
ProtocolError
(
message
,
text
=
fmt
%
(
message
,))
self
.
identity
=
message
.
getArg
(
OPENID_NS
,
'identity'
)
self
.
claimed_id
=
message
.
getArg
(
OPENID_NS
,
'claimed_id'
)
if
message
.
isOpenID1
():
if
self
.
identity
is
None
:
s
=
"OpenID 1 message did not contain openid.identity"
raise
ProtocolError
(
message
,
text
=
s
)
else
:
if
self
.
identity
and
not
self
.
claimed_id
:
s
=
(
"OpenID 2.0 message contained openid.identity but not "
"claimed_id"
)
raise
ProtocolError
(
message
,
text
=
s
)
elif
self
.
claimed_id
and
not
self
.
identity
:
s
=
(
"OpenID 2.0 message contained openid.claimed_id but not "
"identity"
)
raise
ProtocolError
(
message
,
text
=
s
)
# There's a case for making self.trust_root be a TrustRoot
# here. But if TrustRoot isn't currently part of the "public" API,
# I'm not sure it's worth doing.
if
message
.
isOpenID1
():
trust_root_param
=
'trust_root'
else
:
trust_root_param
=
'realm'
# Using 'or' here is slightly different than sending a default
# argument to getArg, as it will treat no value and an empty
# string as equivalent.
self
.
trust_root
=
(
message
.
getArg
(
OPENID_NS
,
trust_root_param
)
or
self
.
return_to
)
if
not
message
.
isOpenID1
():
if
self
.
return_to
is
self
.
trust_root
is
None
:
raise
ProtocolError
(
message
,
"openid.realm required when "
+
"openid.return_to absent"
)
self
.
assoc_handle
=
message
.
getArg
(
OPENID_NS
,
'assoc_handle'
)
# Using TrustRoot.parse here is a bit misleading, as we're not
# parsing return_to as a trust root at all. However, valid URLs
# are valid trust roots, so we can use this to get an idea if it
# is a valid URL. Not all trust roots are valid return_to URLs,
# however (particularly ones with wildcards), so this is still a
# little sketchy.
if
self
.
return_to
is
not
None
and
\
not
TrustRoot
.
parse
(
self
.
return_to
):
raise
MalformedReturnURL
(
message
,
self
.
return_to
)
# I first thought that checking to see if the return_to is within
# the trust_root is premature here, a logic-not-decoding thing. But
# it was argued that this is really part of data validation. A
# request with an invalid trust_root/return_to is broken regardless of
# application, right?
if
not
self
.
trustRootValid
():
raise
UntrustedReturnURL
(
message
,
self
.
return_to
,
self
.
trust_root
)
return
self
fromMessage
=
classmethod
(
fromMessage
)
def
idSelect
(
self
):
"""Is the identifier to be selected by the IDP?
@returntype: bool
"""
# So IDPs don't have to import the constant
return
self
.
identity
==
IDENTIFIER_SELECT
def
trustRootValid
(
self
):
"""Is my return_to under my trust_root?
@returntype: bool
"""
if
not
self
.
trust_root
:
return
True
tr
=
TrustRoot
.
parse
(
self
.
trust_root
)
if
tr
is
None
:
raise
MalformedTrustRoot
(
self
.
message
,
self
.
trust_root
)
if
self
.
return_to
is
not
None
:
return
tr
.
validateURL
(
self
.
return_to
)
else
:
return
True
def
returnToVerified
(
self
):
"""Does the relying party publish the return_to URL for this
response under the realm? It is up to the provider to set a
policy for what kinds of realms should be allowed. This
return_to URL verification reduces vulnerability to data-theft
attacks based on open proxies, cross-site-scripting, or open
redirectors.
This check should only be performed after making sure that the
return_to URL matches the realm.
@see: L{trustRootValid}
@raises openid.yadis.discover.DiscoveryFailure: if the realm
URL does not support Yadis discovery (and so does not
support the verification process).
@raises openid.fetchers.HTTPFetchingError: if the realm URL
is not reachable. When this is the case, the RP may be hosted
on the user's intranet.
@returntype: bool
@returns: True if the realm publishes a document with the
return_to URL listed
@since: 2.1.0
"""
return
verifyReturnTo
(
self
.
trust_root
,
self
.
return_to
)
def
answer
(
self
,
allow
,
server_url
=
None
,
identity
=
None
,
claimed_id
=
None
):
"""Respond to this request.
@param allow: Allow this user to claim this identity, and allow the
consumer to have this information?
@type allow: bool
@param server_url: DEPRECATED. Passing C{op_endpoint} to the
L{Server} constructor makes this optional.
When an OpenID 1.x immediate mode request does not succeed,
it gets back a URL where the request may be carried out
in a not-so-immediate fashion. Pass my URL in here (the
fully qualified address of this server's endpoint, i.e.
C{http://example.com/server}), and I will use it as a base for the
URL for a new request.
Optional for requests where C{CheckIDRequest.immediate} is C{False}
or C{allow} is C{True}.
@type server_url: str
@param identity: The OP-local identifier to answer with. Only for use
when the relying party requested identifier selection.
@type identity: str or None
@param claimed_id: The claimed identifier to answer with, for use
with identifier selection in the case where the claimed identifier
and the OP-local identifier differ, i.e. when the claimed_id uses
delegation.
If C{identity} is provided but this is not, C{claimed_id} will
default to the value of C{identity}. When answering requests
that did not ask for identifier selection, the response
C{claimed_id} will default to that of the request.
This parameter is new in OpenID 2.0.
@type claimed_id: str or None
@returntype: L{OpenIDResponse}
@change: Version 2.0 deprecates C{server_url} and adds C{claimed_id}.
@raises NoReturnError: when I do not have a return_to.
"""
assert
self
.
message
is
not
None
if
not
self
.
return_to
:
raise
NoReturnToError
if
not
server_url
:
if
not
self
.
message
.
isOpenID1
()
and
not
self
.
op_endpoint
:
# In other words, that warning I raised in Server.__init__?
# You should pay attention to it now.
raise
RuntimeError
(
"%s should be constructed with op_endpoint "
"to respond to OpenID 2.0 messages."
%
(
self
,))
server_url
=
self
.
op_endpoint
if
allow
:
mode
=
'id_res'
elif
self
.
message
.
isOpenID1
():
if
self
.
immediate
:
mode
=
'id_res'
else
:
mode
=
'cancel'
else
:
if
self
.
immediate
:
mode
=
'setup_needed'
else
:
mode
=
'cancel'
response
=
OpenIDResponse
(
self
)
if
claimed_id
and
self
.
message
.
isOpenID1
():
namespace
=
self
.
message
.
getOpenIDNamespace
()
raise
VersionError
(
"claimed_id is new in OpenID 2.0 and not "
"available for %s"
%
(
namespace
,))
if
allow
:
if
self
.
identity
==
IDENTIFIER_SELECT
:
if
not
identity
:
raise
ValueError
(
"This request uses IdP-driven identifier selection."
"You must supply an identifier in the response."
)
response_identity
=
identity
response_claimed_id
=
claimed_id
or
identity
elif
self
.
identity
:
if
identity
and
(
self
.
identity
!=
identity
):
normalized_request_identity
=
urinorm
(
self
.
identity
)
normalized_answer_identity
=
urinorm
(
identity
)
if
(
normalized_request_identity
!=
normalized_answer_identity
):
raise
ValueError
(
"Request was for identity %r, cannot reply "
"with identity %r"
%
(
self
.
identity
,
identity
))
# The "identity" value in the response shall always be
# the same as that in the request, otherwise the RP is
# likely to not validate the response.
response_identity
=
self
.
identity
response_claimed_id
=
self
.
claimed_id
else
:
if
identity
:
raise
ValueError
(
"This request specified no identity and you "
"supplied %r"
%
(
identity
,))
response_identity
=
None
if
self
.
message
.
isOpenID1
()
and
response_identity
is
None
:
raise
ValueError
(
"Request was an OpenID 1 request, so response must "
"include an identifier."
)
response
.
fields
.
updateArgs
(
OPENID_NS
, {
'mode'
:
mode
,
'return_to'
:
self
.
return_to
,
'response_nonce'
:
mkNonce
(),
})
if
server_url
:
response
.
fields
.
setArg
(
OPENID_NS
,
'op_endpoint'
,
server_url
)
if
response_identity
is
not
None
:
response
.
fields
.
setArg
(
OPENID_NS
,
'identity'
,
response_identity
)
if
self
.
message
.
isOpenID2
():
response
.
fields
.
setArg
(
OPENID_NS
,
'claimed_id'
,
response_claimed_id
)
else
:
response
.
fields
.
setArg
(
OPENID_NS
,
'mode'
,
mode
)
if
self
.
immediate
:
if
self
.
message
.
isOpenID1
()
and
not
server_url
:
raise
ValueError
(
"setup_url is required for allow=False "
"in OpenID 1.x immediate mode."
)
# Make a new request just like me, but with immediate=False.
setup_request
=
self
.
__class__
(
self
.
identity
,
self
.
return_to
,
self
.
trust_root
,
immediate
=
False
,
assoc_handle
=
self
.
assoc_handle
,
op_endpoint
=
self
.
op_endpoint
,
claimed_id
=
self
.
claimed_id
)
# XXX: This API is weird.
setup_request
.
message
=
self
.
message
setup_url
=
setup_request
.
encodeToURL
(
server_url
)
response
.
fields
.
setArg
(
OPENID_NS
,
'user_setup_url'
,
setup_url
)
return
response
def
encodeToURL
(
self
,
server_url
):
"""Encode this request as a URL to GET.
@param server_url: The URL of the OpenID server to make this request of.
@type server_url: str
@returntype: str
@raises NoReturnError: when I do not have a return_to.
"""
if
not
self
.
return_to
:
raise
NoReturnToError
# Imported from the alternate reality where these classes are used
# in both the client and server code, so Requests are Encodable too.
# That's right, code imported from alternate realities all for the
# love of you, id_res/user_setup_url.
q
=
{
'mode'
:
self
.
mode
,
'identity'
:
self
.
identity
,
'claimed_id'
:
self
.
claimed_id
,
'return_to'
:
self
.
return_to
}
if
self
.
trust_root
:
if
self
.
message
.
isOpenID1
():
q
[
'trust_root'
]
=
self
.
trust_root
else
:
q
[
'realm'
]
=
self
.
trust_root
if
self
.
assoc_handle
:
q
[
'assoc_handle'
]
=
self
.
assoc_handle
response
=
Message
(
self
.
message
.
getOpenIDNamespace
())
response
.
updateArgs
(
OPENID_NS
,
q
)
return
response
.
toURL
(
server_url
)
def
getCancelURL
(
self
):
"""Get the URL to cancel this request.
Useful for creating a "Cancel" button on a web form so that operation
can be carried out directly without another trip through the server.
(Except you probably want to make another trip through the server so
that it knows that the user did make a decision. Or you could simulate
this method by doing C{.answer(False).encodeToURL()})
@returntype: str
@returns: The return_to URL with openid.mode = cancel.
@raises NoReturnError: when I do not have a return_to.
"""
if
not
self
.
return_to
:
raise
NoReturnToError
if
self
.
immediate
:
raise
ValueError
(
"Cancel is not an appropriate response to "
"immediate mode requests."
)
response
=
Message
(
self
.
message
.
getOpenIDNamespace
())
response
.
setArg
(
OPENID_NS
,
'mode'
,
'cancel'
)
return
response
.
toURL
(
self
.
return_to
)
def
__repr__
(
self
):
return
'<%s id:%r im:%s tr:%r ah:%r>'
%
(
self
.
__class__
.
__name__
,
self
.
identity
,
self
.
immediate
,
self
.
trust_root
,
self
.
assoc_handle
)
class
OpenIDResponse
(
object
):
"""I am a response to an OpenID request.
@ivar request: The request I respond to.
@type request: L{OpenIDRequest}
@ivar fields: My parameters as a dictionary with each key mapping to
one value. Keys are parameter names with no leading "C{openid.}".
e.g. "C{identity}" and "C{mac_key}", never "C{openid.identity}".
@type fields: L{openid.message.Message}
@ivar signed: The names of the fields which should be signed.
@type signed: list of str
"""
# Implementer's note: In a more symmetric client/server
# implementation, there would be more types of OpenIDResponse
# object and they would have validated attributes according to the
# type of response. But as it is, Response objects in a server are
# basically write-only, their only job is to go out over the wire,
# so this is just a loose wrapper around OpenIDResponse.fields.
def
__init__
(
self
,
request
):
"""Make a response to an L{OpenIDRequest}.
@type request: L{OpenIDRequest}
"""
self
.
request
=
request
self
.
fields
=
Message
(
request
.
namespace
)
def
__str__
(
self
):
return
"%s for %s: %s"
%
(
self
.
__class__
.
__name__
,
self
.
request
.
__class__
.
__name__
,
self
.
fields
)
def
toFormMarkup
(
self
,
form_tag_attrs
=
None
):
"""Returns the form markup for this response.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@returntype: str
@since: 2.1.0
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL