Repository navigation
Expand file tree
/
Copy pathtest_consumer.py
More file actions
2097 lines (1695 loc) · 76 KB
/
Copy pathtest_consumer.py
File metadata and controls
2097 lines (1695 loc) · 76 KB
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
import urlparse
import cgi
import time
import warnings
from openid.message import Message, OPENID_NS, OPENID2_NS, IDENTIFIER_SELECT, \
OPENID1_NS, BARE_NS
from openid import cryptutil, dh, oidutil, kvform
from openid.store.nonce import mkNonce, split as splitNonce
from openid.consumer.discover import OpenIDServiceEndpoint, OPENID_2_0_TYPE, \
OPENID_1_1_TYPE
from openid.consumer.consumer import \
AuthRequest, GenericConsumer, SUCCESS, FAILURE, CANCEL, SETUP_NEEDED, \
SuccessResponse, FailureResponse, SetupNeededResponse, CancelResponse, \
DiffieHellmanSHA1ConsumerSession, Consumer, PlainTextConsumerSession, \
SetupNeededError, DiffieHellmanSHA256ConsumerSession, ServerError, \
ProtocolError, _httpResponseToMessage
from openid import association
from openid.server.server import \
PlainTextServerSession, DiffieHellmanSHA1ServerSession
from openid.yadis.manager import Discovery
from openid.yadis.discover import DiscoveryFailure
from openid.dh import DiffieHellman
from openid.fetchers import HTTPResponse, HTTPFetchingError
from openid import fetchers
from openid.store import memstore
from support import CatchLogs
assocs = [
('another 20-byte key.', 'Snarky'),
('\x00' * 20, 'Zeros'),
]
def mkSuccess(endpoint, q):
"""Convenience function to create a SuccessResponse with the given
arguments, all signed."""
signed_list = ['openid.' + k for k in q.keys()]
return SuccessResponse(endpoint, Message.fromOpenIDArgs(q), signed_list)
def parseQuery(qs):
q = {}
for (k, v) in cgi.parse_qsl(qs):
assert not q.has_key(k)
q[k] = v
return q
def associate(qs, assoc_secret, assoc_handle):
"""Do the server's half of the associate call, using the given
secret and handle."""
q = parseQuery(qs)
assert q['openid.mode'] == 'associate'
assert q['openid.assoc_type'] == 'HMAC-SHA1'
reply_dict = {
'assoc_type':'HMAC-SHA1',
'assoc_handle':assoc_handle,
'expires_in':'600',
}
if q.get('openid.session_type') == 'DH-SHA1':
assert len(q) == 6 or len(q) == 4
message = Message.fromPostArgs(q)
session = DiffieHellmanSHA1ServerSession.fromMessage(message)
reply_dict['session_type'] = 'DH-SHA1'
else:
assert len(q) == 2
session = PlainTextServerSession.fromQuery(q)
reply_dict.update(session.answer(assoc_secret))
return kvform.dictToKV(reply_dict)
GOODSIG = "[A Good Signature]"
class GoodAssociation:
expiresIn = 3600
handle = "-blah-"
def getExpiresIn(self):
return self.expiresIn
def checkMessageSignature(self, message):
return message.getArg(OPENID_NS, 'sig') == GOODSIG
class GoodAssocStore(memstore.MemoryStore):
def getAssociation(self, server_url, handle=None):
return GoodAssociation()
class TestFetcher(object):
def __init__(self, user_url, user_page, (assoc_secret, assoc_handle)):
self.get_responses = {user_url:self.response(user_url, 200, user_page)}
self.assoc_secret = assoc_secret
self.assoc_handle = assoc_handle
self.num_assocs = 0
def response(self, url, status, body):
return HTTPResponse(
final_url=url, status=status, headers={}, body=body)
def fetch(self, url, body=None, headers=None):
if body is None:
if url in self.get_responses:
return self.get_responses[url]
else:
try:
body.index('openid.mode=associate')
except ValueError:
pass # fall through
else:
assert body.find('DH-SHA1') != -1
response = associate(
body, self.assoc_secret, self.assoc_handle)
self.num_assocs += 1
return self.response(url, 200, response)
return self.response(url, 404, 'Not found')
def makeFastConsumerSession():
"""
Create custom DH object so tests run quickly.
"""
dh = DiffieHellman(100389557, 2)
return DiffieHellmanSHA1ConsumerSession(dh)
def setConsumerSession(con):
con.session_types = {'DH-SHA1': makeFastConsumerSession}
def _test_success(server_url, user_url, delegate_url, links, immediate=False):
store = memstore.MemoryStore()
if immediate:
mode = 'checkid_immediate'
else:
mode = 'checkid_setup'
endpoint = OpenIDServiceEndpoint()
endpoint.claimed_id = user_url
endpoint.server_url = server_url
endpoint.local_id = delegate_url
endpoint.type_uris = [OPENID_1_1_TYPE]
fetcher = TestFetcher(None, None, assocs[0])
fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False)
def run():
trust_root = consumer_url
consumer = GenericConsumer(store)
setConsumerSession(consumer)
request = consumer.begin(endpoint)
return_to = consumer_url
m = request.getMessage(trust_root, return_to, immediate)
redirect_url = request.redirectURL(trust_root, return_to, immediate)
parsed = urlparse.urlparse(redirect_url)
qs = parsed[4]
q = parseQuery(qs)
new_return_to = q['openid.return_to']
del q['openid.return_to']
assert q == {
'openid.mode':mode,
'openid.identity':delegate_url,
'openid.trust_root':trust_root,
'openid.assoc_handle':fetcher.assoc_handle,
}, (q, user_url, delegate_url, mode)
assert new_return_to.startswith(return_to)
assert redirect_url.startswith(server_url)
parsed = urlparse.urlparse(new_return_to)
query = parseQuery(parsed[4])
query.update({
'openid.mode':'id_res',
'openid.return_to':new_return_to,
'openid.identity':delegate_url,
'openid.assoc_handle':fetcher.assoc_handle,
})
assoc = store.getAssociation(server_url, fetcher.assoc_handle)
message = Message.fromPostArgs(query)
message = assoc.signMessage(message)
info = consumer.complete(message, request.endpoint, new_return_to)
assert info.status == SUCCESS, info.message
assert info.identity_url == user_url
assert fetcher.num_assocs == 0
run()
assert fetcher.num_assocs == 1
# Test that doing it again uses the existing association
run()
assert fetcher.num_assocs == 1
# Another association is created if we remove the existing one
store.removeAssociation(server_url, fetcher.assoc_handle)
run()
assert fetcher.num_assocs == 2
# Test that doing it again uses the existing association
run()
assert fetcher.num_assocs == 2
import unittest
http_server_url = 'http://server.example.com/'
consumer_url = 'http://consumer.example.com/'
https_server_url = 'https://server.example.com/'
class TestSuccess(unittest.TestCase, CatchLogs):
server_url = http_server_url
user_url = 'http://www.example.com/user.html'
delegate_url = 'http://consumer.example.com/user'
def setUp(self):
CatchLogs.setUp(self)
self.links = '<link rel="openid.server" href="%s" />' % (
self.server_url,)
self.delegate_links = ('<link rel="openid.server" href="%s" />'
'<link rel="openid.delegate" href="%s" />') % (
self.server_url, self.delegate_url)
def tearDown(self):
CatchLogs.tearDown(self)
def test_nodelegate(self):
_test_success(self.server_url, self.user_url,
self.user_url, self.links)
def test_nodelegateImmediate(self):
_test_success(self.server_url, self.user_url,
self.user_url, self.links, True)
def test_delegate(self):
_test_success(self.server_url, self.user_url,
self.delegate_url, self.delegate_links)
def test_delegateImmediate(self):
_test_success(self.server_url, self.user_url,
self.delegate_url, self.delegate_links, True)
class TestSuccessHTTPS(TestSuccess):
server_url = https_server_url
class TestConstruct(unittest.TestCase):
def setUp(self):
self.store_sentinel = object()
def test_construct(self):
oidc = GenericConsumer(self.store_sentinel)
self.failUnless(oidc.store is self.store_sentinel)
def test_nostore(self):
self.failUnlessRaises(TypeError, GenericConsumer)
class TestIdRes(unittest.TestCase, CatchLogs):
consumer_class = GenericConsumer
def setUp(self):
CatchLogs.setUp(self)
self.store = memstore.MemoryStore()
self.consumer = self.consumer_class(self.store)
self.return_to = "nonny"
self.endpoint = OpenIDServiceEndpoint()
self.endpoint.claimed_id = self.consumer_id = "consu"
self.endpoint.server_url = self.server_url = "serlie"
self.endpoint.local_id = self.server_id = "sirod"
self.endpoint.type_uris = [OPENID_1_1_TYPE]
def disableDiscoveryVerification(self):
"""Set the discovery verification to a no-op for test cases in
which we don't care."""
def dummyVerifyDiscover(_, endpoint):
return endpoint
self.consumer._verifyDiscoveryResults = dummyVerifyDiscover
def disableReturnToChecking(self):
def checkReturnTo(unused1, unused2):
return True
self.consumer._checkReturnTo = checkReturnTo
complete = self.consumer.complete
def callCompleteWithoutReturnTo(message, endpoint):
return complete(message, endpoint, None)
self.consumer.complete = callCompleteWithoutReturnTo
class TestIdResCheckSignature(TestIdRes):
def setUp(self):
TestIdRes.setUp(self)
self.assoc = GoodAssociation()
self.assoc.handle = "{not_dumb}"
self.store.storeAssociation(self.endpoint.server_url, self.assoc)
self.message = Message.fromPostArgs({
'openid.mode': 'id_res',
'openid.identity': '=example',
'openid.sig': GOODSIG,
'openid.assoc_handle': self.assoc.handle,
'openid.signed': 'mode,identity,assoc_handle,signed',
'frobboz': 'banzit',
})
def test_sign(self):
# assoc_handle to assoc with good sig
self.consumer._idResCheckSignature(self.message,
self.endpoint.server_url)
def test_signFailsWithBadSig(self):
self.message.setArg(OPENID_NS, 'sig', 'BAD SIGNATURE')
self.failUnlessRaises(
ProtocolError, self.consumer._idResCheckSignature,
self.message, self.endpoint.server_url)
def test_stateless(self):
# assoc_handle missing assoc, consumer._checkAuth returns goodthings
self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle")
self.consumer._processCheckAuthResponse = (
lambda response, server_url: True)
self.consumer._makeKVPost = lambda args, server_url: {}
self.consumer._idResCheckSignature(self.message,
self.endpoint.server_url)
def test_statelessRaisesError(self):
# assoc_handle missing assoc, consumer._checkAuth returns goodthings
self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle")
self.consumer._checkAuth = lambda unused1, unused2: False
self.failUnlessRaises(
ProtocolError, self.consumer._idResCheckSignature,
self.message, self.endpoint.server_url)
def test_stateless_noStore(self):
# assoc_handle missing assoc, consumer._checkAuth returns goodthings
self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle")
self.consumer.store = None
self.consumer._processCheckAuthResponse = (
lambda response, server_url: True)
self.consumer._makeKVPost = lambda args, server_url: {}
self.consumer._idResCheckSignature(self.message,
self.endpoint.server_url)
def test_statelessRaisesError_noStore(self):
# assoc_handle missing assoc, consumer._checkAuth returns goodthings
self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle")
self.consumer._checkAuth = lambda unused1, unused2: False
self.consumer.store = None
self.failUnlessRaises(
ProtocolError, self.consumer._idResCheckSignature,
self.message, self.endpoint.server_url)
class TestQueryFormat(TestIdRes):
def test_notAList(self):
# XXX: should be a Message object test, not a consumer test
# Value should be a single string. If it's a list, it should generate
# an exception.
query = {'openid.mode': ['cancel']}
try:
r = Message.fromPostArgs(query)
except TypeError, err:
self.failUnless(str(err).find('values') != -1, err)
else:
self.fail("expected TypeError, got this instead: %s" % (r,))
class TestComplete(TestIdRes):
"""Testing GenericConsumer.complete.
Other TestIdRes subclasses test more specific aspects.
"""
def test_setupNeededIdRes(self):
message = Message.fromOpenIDArgs({'mode': 'id_res'})
setup_url_sentinel = object()
def raiseSetupNeeded(msg):
self.failUnless(msg is message)
raise SetupNeededError(setup_url_sentinel)
self.consumer._checkSetupNeeded = raiseSetupNeeded
response = self.consumer.complete(message, None, None)
self.failUnlessEqual(SETUP_NEEDED, response.status)
self.failUnless(setup_url_sentinel is response.setup_url)
def test_cancel(self):
message = Message.fromPostArgs({'openid.mode': 'cancel'})
self.disableReturnToChecking()
r = self.consumer.complete(message, self.endpoint)
self.failUnlessEqual(r.status, CANCEL)
self.failUnless(r.identity_url == self.endpoint.claimed_id)
def test_cancel_with_return_to(self):
message = Message.fromPostArgs({'openid.mode': 'cancel'})
r = self.consumer.complete(message, self.endpoint, self.return_to)
self.failUnlessEqual(r.status, CANCEL)
self.failUnless(r.identity_url == self.endpoint.claimed_id)
def test_error(self):
msg = 'an error message'
message = Message.fromPostArgs({'openid.mode': 'error',
'openid.error': msg,
})
self.disableReturnToChecking()
r = self.consumer.complete(message, self.endpoint)
self.failUnlessEqual(r.status, FAILURE)
self.failUnless(r.identity_url == self.endpoint.claimed_id)
self.failUnlessEqual(r.message, msg)
def test_errorWithNoOptionalKeys(self):
msg = 'an error message'
contact = 'some contact info here'
message = Message.fromPostArgs({'openid.mode': 'error',
'openid.error': msg,
'openid.contact': contact,
})
self.disableReturnToChecking()
r = self.consumer.complete(message, self.endpoint)
self.failUnlessEqual(r.status, FAILURE)
self.failUnless(r.identity_url == self.endpoint.claimed_id)
self.failUnless(r.contact == contact)
self.failUnless(r.reference is None)
self.failUnlessEqual(r.message, msg)
def test_errorWithOptionalKeys(self):
msg = 'an error message'
contact = 'me'
reference = 'support ticket'
message = Message.fromPostArgs({'openid.mode': 'error',
'openid.error': msg, 'openid.reference': reference,
'openid.contact': contact, 'openid.ns': OPENID2_NS,
})
r = self.consumer.complete(message, self.endpoint, None)
self.failUnlessEqual(r.status, FAILURE)
self.failUnless(r.identity_url == self.endpoint.claimed_id)
self.failUnless(r.contact == contact)
self.failUnless(r.reference == reference)
self.failUnlessEqual(r.message, msg)
def test_noMode(self):
message = Message.fromPostArgs({})
r = self.consumer.complete(message, self.endpoint, None)
self.failUnlessEqual(r.status, FAILURE)
self.failUnless(r.identity_url == self.endpoint.claimed_id)
def test_idResMissingField(self):
# XXX - this test is passing, but not necessarily by what it
# is supposed to test for. status in FAILURE, but it's because
# *check_auth* failed, not because it's missing an arg, exactly.
message = Message.fromPostArgs({'openid.mode': 'id_res'})
self.failUnlessRaises(ProtocolError, self.consumer._doIdRes,
message, self.endpoint, None)
def test_idResURLMismatch(self):
class VerifiedError(Exception): pass
def discoverAndVerify(claimed_id, _to_match_endpoints):
raise VerifiedError
self.consumer._discoverAndVerify = discoverAndVerify
self.disableReturnToChecking()
message = Message.fromPostArgs(
{'openid.mode': 'id_res',
'openid.return_to': 'return_to (just anything)',
'openid.identity': 'something wrong (not self.consumer_id)',
'openid.assoc_handle': 'does not matter',
'openid.sig': GOODSIG,
'openid.signed': 'identity,return_to',
})
self.consumer.store = GoodAssocStore()
self.failUnlessRaises(VerifiedError,
self.consumer.complete,
message, self.endpoint)
self.failUnlessLogMatches('Error attempting to use stored',
'Attempting discovery')
class TestCompleteMissingSig(unittest.TestCase, CatchLogs):
def setUp(self):
self.store = GoodAssocStore()
self.consumer = GenericConsumer(self.store)
self.server_url = "http://idp.unittest/"
CatchLogs.setUp(self)
claimed_id = 'bogus.claimed'
self.message = Message.fromOpenIDArgs(
{'mode': 'id_res',
'return_to': 'return_to (just anything)',
'identity': claimed_id,
'assoc_handle': 'does not matter',
'sig': GOODSIG,
'response_nonce': mkNonce(),
'signed': 'identity,return_to,response_nonce,assoc_handle,claimed_id,op_endpoint',
'claimed_id': claimed_id,
'op_endpoint': self.server_url,
'ns':OPENID2_NS,
})
self.endpoint = OpenIDServiceEndpoint()
self.endpoint.server_url = self.server_url
self.endpoint.claimed_id = claimed_id
self.consumer._checkReturnTo = lambda unused1, unused2 : True
def tearDown(self):
CatchLogs.tearDown(self)
def test_idResMissingNoSigs(self):
def _vrfy(resp_msg, endpoint=None):
return endpoint
self.consumer._verifyDiscoveryResults = _vrfy
r = self.consumer.complete(self.message, self.endpoint, None)
self.failUnlessSuccess(r)
def test_idResNoIdentity(self):
self.message.delArg(OPENID_NS, 'identity')
self.message.delArg(OPENID_NS, 'claimed_id')
self.endpoint.claimed_id = None
self.message.setArg(OPENID_NS, 'signed', 'return_to,response_nonce,assoc_handle,op_endpoint')
r = self.consumer.complete(self.message, self.endpoint, None)
self.failUnlessSuccess(r)
def test_idResMissingIdentitySig(self):
self.message.setArg(OPENID_NS, 'signed', 'return_to,response_nonce,assoc_handle,claimed_id')
r = self.consumer.complete(self.message, self.endpoint, None)
self.failUnlessEqual(r.status, FAILURE)
def test_idResMissingReturnToSig(self):
self.message.setArg(OPENID_NS, 'signed', 'identity,response_nonce,assoc_handle,claimed_id')
r = self.consumer.complete(self.message, self.endpoint, None)
self.failUnlessEqual(r.status, FAILURE)
def test_idResMissingAssocHandleSig(self):
self.message.setArg(OPENID_NS, 'signed', 'identity,response_nonce,return_to,claimed_id')
r = self.consumer.complete(self.message, self.endpoint, None)
self.failUnlessEqual(r.status, FAILURE)
def test_idResMissingClaimedIDSig(self):
self.message.setArg(OPENID_NS, 'signed', 'identity,response_nonce,return_to,assoc_handle')
r = self.consumer.complete(self.message, self.endpoint, None)
self.failUnlessEqual(r.status, FAILURE)
def failUnlessSuccess(self, response):
if response.status != SUCCESS:
self.fail("Non-successful response: %s" % (response,))
class TestCheckAuthResponse(TestIdRes, CatchLogs):
def setUp(self):
CatchLogs.setUp(self)
TestIdRes.setUp(self)
def tearDown(self):
CatchLogs.tearDown(self)
def _createAssoc(self):
issued = time.time()
lifetime = 1000
assoc = association.Association(
'handle', 'secret', issued, lifetime, 'HMAC-SHA1')
store = self.consumer.store
store.storeAssociation(self.server_url, assoc)
assoc2 = store.getAssociation(self.server_url)
self.failUnlessEqual(assoc, assoc2)
def test_goodResponse(self):
"""successful response to check_authentication"""
response = Message.fromOpenIDArgs({'is_valid':'true',})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.failUnless(r)
def test_missingAnswer(self):
"""check_authentication returns false when the server sends no answer"""
response = Message.fromOpenIDArgs({})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.failIf(r)
def test_badResponse(self):
"""check_authentication returns false when is_valid is false"""
response = Message.fromOpenIDArgs({'is_valid':'false',})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.failIf(r)
def test_badResponseInvalidate(self):
"""Make sure that the handle is invalidated when is_valid is false
From "Verifying directly with the OpenID Provider"::
If the OP responds with "is_valid" set to "true", and
"invalidate_handle" is present, the Relying Party SHOULD
NOT send further authentication requests with that handle.
"""
self._createAssoc()
response = Message.fromOpenIDArgs({
'is_valid':'false',
'invalidate_handle':'handle',
})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.failIf(r)
self.failUnless(
self.consumer.store.getAssociation(self.server_url) is None)
def test_invalidateMissing(self):
"""invalidate_handle with a handle that is not present"""
response = Message.fromOpenIDArgs({
'is_valid':'true',
'invalidate_handle':'missing',
})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.failUnless(r)
self.failUnlessLogMatches(
'Received "invalidate_handle"'
)
def test_invalidateMissing_noStore(self):
"""invalidate_handle with a handle that is not present"""
response = Message.fromOpenIDArgs({
'is_valid':'true',
'invalidate_handle':'missing',
})
self.consumer.store = None
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.failUnless(r)
self.failUnlessLogMatches(
'Received "invalidate_handle"',
'Unexpectedly got invalidate_handle without a store')
def test_invalidatePresent(self):
"""invalidate_handle with a handle that exists
From "Verifying directly with the OpenID Provider"::
If the OP responds with "is_valid" set to "true", and
"invalidate_handle" is present, the Relying Party SHOULD
NOT send further authentication requests with that handle.
"""
self._createAssoc()
response = Message.fromOpenIDArgs({
'is_valid':'true',
'invalidate_handle':'handle',
})
r = self.consumer._processCheckAuthResponse(response, self.server_url)
self.failUnless(r)
self.failUnless(
self.consumer.store.getAssociation(self.server_url) is None)
class TestSetupNeeded(TestIdRes):
def failUnlessSetupNeeded(self, expected_setup_url, message):
try:
self.consumer._checkSetupNeeded(message)
except SetupNeededError, why:
self.failUnlessEqual(expected_setup_url, why.user_setup_url)
else:
self.fail("Expected to find an immediate-mode response")
def test_setupNeededOpenID1(self):
"""The minimum conditions necessary to trigger Setup Needed"""
setup_url = 'http://unittest/setup-here'
message = Message.fromPostArgs({
'openid.mode': 'id_res',
'openid.user_setup_url': setup_url,
})
self.failUnless(message.isOpenID1())
self.failUnlessSetupNeeded(setup_url, message)
def test_setupNeededOpenID1_extra(self):
"""Extra stuff along with setup_url still trigger Setup Needed"""
setup_url = 'http://unittest/setup-here'
message = Message.fromPostArgs({
'openid.mode': 'id_res',
'openid.user_setup_url': setup_url,
'openid.identity': 'bogus',
})
self.failUnless(message.isOpenID1())
self.failUnlessSetupNeeded(setup_url, message)
def test_noSetupNeededOpenID1(self):
"""When the user_setup_url is missing on an OpenID 1 message,
we assume that it's not a cancel response to checkid_immediate"""
message = Message.fromOpenIDArgs({'mode': 'id_res'})
self.failUnless(message.isOpenID1())
# No SetupNeededError raised
self.consumer._checkSetupNeeded(message)
def test_setupNeededOpenID2(self):
message = Message.fromOpenIDArgs({
'mode':'setup_needed',
'ns':OPENID2_NS,
})
self.failUnless(message.isOpenID2())
response = self.consumer.complete(message, None, None)
self.failUnlessEqual('setup_needed', response.status)
self.failUnlessEqual(None, response.setup_url)
def test_setupNeededDoesntWorkForOpenID1(self):
message = Message.fromOpenIDArgs({
'mode':'setup_needed',
})
# No SetupNeededError raised
self.consumer._checkSetupNeeded(message)
response = self.consumer.complete(message, None, None)
self.failUnlessEqual('failure', response.status)
self.failUnless(response.message.startswith('Invalid openid.mode'))
def test_noSetupNeededOpenID2(self):
message = Message.fromOpenIDArgs({
'mode':'id_res',
'game':'puerto_rico',
'ns':OPENID2_NS,
})
self.failUnless(message.isOpenID2())
# No SetupNeededError raised
self.consumer._checkSetupNeeded(message)
class IdResCheckForFieldsTest(TestIdRes):
def setUp(self):
self.consumer = GenericConsumer(None)
def mkSuccessTest(openid_args, signed_list):
def test(self):
message = Message.fromOpenIDArgs(openid_args)
message.setArg(OPENID_NS, 'signed', ','.join(signed_list))
self.consumer._idResCheckForFields(message)
return test
test_openid1Success = mkSuccessTest(
{'return_to':'return',
'assoc_handle':'assoc handle',
'sig':'a signature',
'identity':'someone',
},
['return_to', 'identity'])
test_openid2Success = mkSuccessTest(
{'ns':OPENID2_NS,
'return_to':'return',
'assoc_handle':'assoc handle',
'sig':'a signature',
'op_endpoint':'my favourite server',
'response_nonce':'use only once',
},
['return_to', 'response_nonce', 'assoc_handle', 'op_endpoint'])
test_openid2Success_identifiers = mkSuccessTest(
{'ns':OPENID2_NS,
'return_to':'return',
'assoc_handle':'assoc handle',
'sig':'a signature',
'claimed_id':'i claim to be me',
'identity':'my server knows me as me',
'op_endpoint':'my favourite server',
'response_nonce':'use only once',
},
['return_to', 'response_nonce', 'identity',
'claimed_id', 'assoc_handle', 'op_endpoint'])
def mkMissingFieldTest(openid_args):
def test(self):
message = Message.fromOpenIDArgs(openid_args)
try:
self.consumer._idResCheckForFields(message)
except ProtocolError, why:
self.failUnless(why[0].startswith('Missing required'))
else:
self.fail('Expected an error, but none occurred')
return test
def mkMissingSignedTest(openid_args):
def test(self):
message = Message.fromOpenIDArgs(openid_args)
try:
self.consumer._idResCheckForFields(message)
except ProtocolError, why:
self.failUnless(why[0].endswith('not signed'))
else:
self.fail('Expected an error, but none occurred')
return test
test_openid1Missing_returnToSig = mkMissingSignedTest(
{'return_to':'return',
'assoc_handle':'assoc handle',
'sig':'a signature',
'identity':'someone',
'signed':'identity',
})
test_openid1Missing_identitySig = mkMissingSignedTest(
{'return_to':'return',
'assoc_handle':'assoc handle',
'sig':'a signature',
'identity':'someone',
'signed':'return_to'
})
test_openid2Missing_opEndpointSig = mkMissingSignedTest(
{'ns':OPENID2_NS,
'return_to':'return',
'assoc_handle':'assoc handle',
'sig':'a signature',
'identity':'someone',
'op_endpoint':'the endpoint',
'signed':'return_to,identity,assoc_handle'
})
test_openid1MissingReturnTo = mkMissingFieldTest(
{'assoc_handle':'assoc handle',
'sig':'a signature',
'identity':'someone',
})
test_openid1MissingAssocHandle = mkMissingFieldTest(
{'return_to':'return',
'sig':'a signature',
'identity':'someone',
})
# XXX: I could go on...
class CheckAuthHappened(Exception): pass
class CheckNonceVerifyTest(TestIdRes, CatchLogs):
def setUp(self):
CatchLogs.setUp(self)
TestIdRes.setUp(self)
self.consumer.openid1_nonce_query_arg_name = 'nonce'
def tearDown(self):
CatchLogs.tearDown(self)
def test_openid1Success(self):
"""use consumer-generated nonce"""
nonce_value = mkNonce()
self.return_to = 'http://rt.unittest/?nonce=%s' % (nonce_value,)
self.response = Message.fromOpenIDArgs({'return_to': self.return_to})
self.response.setArg(BARE_NS, 'nonce', nonce_value)
self.consumer._idResCheckNonce(self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_openid1Missing(self):
"""use consumer-generated nonce"""
self.response = Message.fromOpenIDArgs({})
n = self.consumer._idResGetNonceOpenID1(self.response, self.endpoint)
self.failUnless(n is None, n)
self.failUnlessLogEmpty()
def test_consumerNonceOpenID2(self):
"""OpenID 2 does not use consumer-generated nonce"""
self.return_to = 'http://rt.unittest/?nonce=%s' % (mkNonce(),)
self.response = Message.fromOpenIDArgs(
{'return_to': self.return_to, 'ns':OPENID2_NS})
self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_serverNonce(self):
"""use server-generated nonce"""
self.response = Message.fromOpenIDArgs(
{'ns':OPENID2_NS, 'response_nonce': mkNonce(),})
self.consumer._idResCheckNonce(self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_serverNonceOpenID1(self):
"""OpenID 1 does not use server-generated nonce"""
self.response = Message.fromOpenIDArgs(
{'ns':OPENID1_NS,
'return_to': 'http://return.to/',
'response_nonce': mkNonce(),})
self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_badNonce(self):
"""remove the nonce from the store
From "Checking the Nonce"::
When the Relying Party checks the signature on an assertion, the
Relying Party SHOULD ensure that an assertion has not yet
been accepted with the same value for "openid.response_nonce"
from the same OP Endpoint URL.
"""
nonce = mkNonce()
stamp, salt = splitNonce(nonce)
self.store.useNonce(self.server_url, stamp, salt)
self.response = Message.fromOpenIDArgs(
{'response_nonce': nonce,
'ns':OPENID2_NS,
})
self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
def test_successWithNoStore(self):
"""When there is no store, checking the nonce succeeds"""
self.consumer.store = None
self.response = Message.fromOpenIDArgs(
{'response_nonce': mkNonce(),
'ns':OPENID2_NS,
})
self.consumer._idResCheckNonce(self.response, self.endpoint)
self.failUnlessLogEmpty()
def test_tamperedNonce(self):
"""Malformed nonce"""
self.response = Message.fromOpenIDArgs(
{'ns':OPENID2_NS,
'response_nonce':'malformed'})
self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
def test_missingNonce(self):
"""no nonce parameter on the return_to"""
self.response = Message.fromOpenIDArgs(
{'return_to': self.return_to})
self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce,
self.response, self.endpoint)
class CheckAuthDetectingConsumer(GenericConsumer):
def _checkAuth(self, *args):
raise CheckAuthHappened(args)
def _idResCheckNonce(self, *args):
"""We're not testing nonce-checking, so just return success
when it asks."""
return True
class TestCheckAuthTriggered(TestIdRes, CatchLogs):
consumer_class = CheckAuthDetectingConsumer
def setUp(self):
TestIdRes.setUp(self)
CatchLogs.setUp(self)
self.disableDiscoveryVerification()
def test_checkAuthTriggered(self):
message = Message.fromPostArgs({
'openid.return_to':self.return_to,
'openid.identity':self.server_id,
'openid.assoc_handle':'not_found',
'openid.sig': GOODSIG,
'openid.signed': 'identity,return_to',
})
self.disableReturnToChecking()
try:
result = self.consumer._doIdRes(message, self.endpoint, None)
except CheckAuthHappened:
pass
else:
self.fail('_checkAuth did not happen. Result was: %r %s' %
(result, self.messages))
def test_checkAuthTriggeredWithAssoc(self):
# Store an association for this server that does not match the
# handle that is in the message
issued = time.time()
lifetime = 1000
assoc = association.Association(
'handle', 'secret', issued, lifetime, 'HMAC-SHA1')
self.store.storeAssociation(self.server_url, assoc)
self.disableReturnToChecking()
message = Message.fromPostArgs({
'openid.return_to':self.return_to,
'openid.identity':self.server_id,
'openid.assoc_handle':'not_found',
'openid.sig': GOODSIG,
'openid.signed': 'identity,return_to',
})
try:
result = self.consumer._doIdRes(message, self.endpoint, None)
except CheckAuthHappened:
pass
else: