forked from ietf-tools/datatracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.py
More file actions
1271 lines (1079 loc) · 51.4 KB
/
tests.py
File metadata and controls
1271 lines (1079 loc) · 51.4 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
# Copyright The IETF Trust 2009-2023, All Rights Reserved
# -*- coding: utf-8 -*-
import datetime
import logging # pyflakes:ignore
import re
import requests
import requests_mock
import time
import urllib
from .factories import OidClientRecordFactory
from Cryptodome.PublicKey import RSA
from oic import rndstr
from oic.oic import Client as OidClient
from oic.oic.message import RegistrationResponse, AuthorizationResponse
from oic.utils.authn.client import CLIENT_AUTHN_METHOD
from oidc_provider.models import RSAKey
from pyquery import PyQuery
from urllib.parse import urlsplit
import django.core.signing
from django.urls import reverse as urlreverse
from django.contrib.auth.models import User
from django.conf import settings
from django.template.loader import render_to_string
from django.utils import timezone
import debug # pyflakes:ignore
from ietf.group.factories import GroupFactory, RoleFactory
from ietf.group.models import Group, Role, RoleName
from ietf.ietfauth.utils import has_role
from ietf.meeting.factories import MeetingFactory, RegistrationFactory, RegistrationTicketFactory
from ietf.nomcom.factories import NomComFactory
from ietf.person.factories import PersonFactory, EmailFactory, UserFactory, PersonalApiKeyFactory
from ietf.person.models import Person, Email
from ietf.person.tasks import send_apikey_usage_emails_task
from ietf.review.factories import ReviewRequestFactory, ReviewAssignmentFactory
from ietf.review.models import ReviewWish, UnavailablePeriod
from ietf.utils.mail import outbox, empty_outbox, get_payload_text
from ietf.utils.test_utils import TestCase, login_testing_unauthorized
from ietf.utils.timezone import date_today
class IetfAuthTests(TestCase):
def test_index(self):
self.assertEqual(self.client.get(urlreverse("ietf.ietfauth.views.index")).status_code, 200)
def test_login_and_logout(self):
PersonFactory(user__username='plain')
# try logging in without a next
r = self.client.get(urlreverse("ietf.ietfauth.views.login"))
self.assertEqual(r.status_code, 200)
r = self.client.post(urlreverse("ietf.ietfauth.views.login"), {"username":"plain", "password":"plain+password"})
self.assertEqual(r.status_code, 302)
self.assertEqual(urlsplit(r["Location"])[2], urlreverse("ietf.ietfauth.views.profile"))
# try logging out
r = self.client.post(urlreverse('django.contrib.auth.views.logout'), {})
self.assertEqual(r.status_code, 200)
self.assertNotContains(r, "accounts/logout")
r = self.client.get(urlreverse("ietf.ietfauth.views.profile"))
self.assertEqual(r.status_code, 302)
self.assertEqual(urlsplit(r["Location"])[2], urlreverse("ietf.ietfauth.views.login"))
# try logging in with a next
r = self.client.post(urlreverse("ietf.ietfauth.views.login") + "?next=/foobar", {"username":"plain", "password":"plain+password"})
self.assertEqual(r.status_code, 302)
self.assertEqual(urlsplit(r["Location"])[2], "/foobar")
def test_login_button(self):
PersonFactory(user__username='plain')
def _test_login(url):
# try mashing the sign-in button repeatedly
r = self.client.get(url)
if r.status_code == 302:
r = self.client.get(r["Location"])
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
login_url = q("a:Contains('Sign in')").attr("href")
self.assertEqual(login_url, "/accounts/login/?next=" + url)
r = self.client.get(login_url)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
login_url = q("a:Contains('Sign in')").attr("href")
self.assertEqual(login_url, "/accounts/login/?next=" + url)
# try logging in with the provided next
r = self.client.post(login_url, {"username":"plain", "password":"plain+password"})
self.assertEqual(r.status_code, 302)
self.assertEqual(urlsplit(r["Location"])[2], url)
self.client.logout()
# try with a trivial next
_test_login("/")
# try with a next that requires login
_test_login(urlreverse("ietf.ietfauth.views.profile"))
def test_login_with_different_email(self):
person = PersonFactory(user__username='plain')
email = EmailFactory(person=person)
# try logging in without a next
r = self.client.get(urlreverse("ietf.ietfauth.views.login"))
self.assertEqual(r.status_code, 200)
r = self.client.post(urlreverse("ietf.ietfauth.views.login"), {"username":email, "password":"plain+password"})
self.assertEqual(r.status_code, 302)
self.assertEqual(urlsplit(r["Location"])[2], urlreverse("ietf.ietfauth.views.profile"))
def extract_confirm_url(self, confirm_email):
# dig out confirm_email link
msg = get_payload_text(confirm_email)
line_re = r"http.*/.*confirm"
confirm_url = None
for line in msg.split("\n"):
if re.search(line_re, line.strip()):
confirm_url = line.strip()
self.assertTrue(confirm_url)
return confirm_url
# For the lowered barrier to account creation period, we are disabling this kind of failure
# def test_create_account_failure(self):
# url = urlreverse("ietf.ietfauth.views.create_account")
# # get
# r = self.client.get(url)
# self.assertEqual(r.status_code, 200)
# # register email and verify failure
# email = 'new-account@example.com'
# empty_outbox()
# r = self.client.post(url, { 'email': email })
# self.assertEqual(r.status_code, 200)
# self.assertContains(r, "Additional Assistance Required")
# Rather than delete the failure template just yet, here's a test to make sure it still renders should we need to revert to it.
def test_create_account_failure_template(self):
r = render_to_string('registration/manual.html', { 'account_request_email': settings.ACCOUNT_REQUEST_EMAIL })
self.assertTrue("Additional Assistance Required" in r)
def register(self, email):
url = urlreverse("ietf.ietfauth.views.create_account")
# register email
empty_outbox()
r = self.client.post(url, { 'email': email })
self.assertEqual(r.status_code, 200)
self.assertContains(r, "Account request received")
self.assertEqual(len(outbox), 1)
def register_and_verify(self, email):
self.register(email)
# go to confirm page
confirm_url = self.extract_confirm_url(outbox[-1])
r = self.client.get(confirm_url)
self.assertEqual(r.status_code, 200)
# password mismatch
r = self.client.post(
confirm_url, {
"password": "secret-and-secure",
"password_confirmation": "not-secret-or-secure",
}
)
self.assertEqual(r.status_code, 200)
self.assertEqual(User.objects.filter(username=email).count(), 0)
# weak password
r = self.client.post(
confirm_url, {
"password": "password1234",
"password_confirmation": "password1234",
}
)
self.assertEqual(r.status_code, 200)
self.assertEqual(User.objects.filter(username=email).count(), 0)
# confirm
r = self.client.post(
confirm_url,
{
"name": "User Name",
"ascii": "User Name",
"password": "secret-and-secure",
"password_confirmation": "secret-and-secure",
},
)
self.assertEqual(r.status_code, 200)
self.assertEqual(User.objects.filter(username=email).count(), 1)
self.assertEqual(Person.objects.filter(user__username=email).count(), 1)
self.assertEqual(Email.objects.filter(person__user__username=email).count(), 1)
# This also tests new account creation.
def test_create_existing_account(self):
# create account once
email = "new-account@example.com"
self.register_and_verify(email)
# create account again
self.register(email)
# check notification
note = get_payload_text(outbox[-1])
self.assertIn(email, note)
self.assertIn("A datatracker account for that email already exists", note)
self.assertIn(urlreverse("ietf.ietfauth.views.password_reset"), note)
def test_ietfauth_profile(self):
EmailFactory(person__user__username='plain')
GroupFactory(acronym='mars')
username = "plain"
email_address = Email.objects.filter(person__user__username=username).first().address
url = urlreverse("ietf.ietfauth.views.profile")
login_testing_unauthorized(self, username, url)
# get
r = self.client.get(url)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertEqual(len(q('.form-control-plaintext:contains("%s")' % username)), 1)
self.assertEqual(len(q('[name="active_emails"][value="%s"][checked]' % email_address)), 1)
base_data = {
"name": "Test Nãme",
"plain": "",
"ascii": "Test Name",
"ascii_short": "T. Name",
"pronouns_freetext": "foo/bar",
"affiliation": "Test Org",
"active_emails": email_address,
}
# edit details - faulty ASCII
faulty_ascii = base_data.copy()
faulty_ascii["ascii"] = "Test Nãme"
r = self.client.post(url, faulty_ascii)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertTrue(len(q("form .invalid-feedback")) == 1)
# edit details - blank ASCII
blank_ascii = base_data.copy()
blank_ascii["ascii"] = ""
r = self.client.post(url, blank_ascii)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertTrue(len(q("form div.invalid-feedback")) == 1) # we get a warning about reconstructed name
self.assertEqual(q("input[name=ascii]").val(), base_data["ascii"])
# edit details
r = self.client.post(url, base_data)
self.assertEqual(r.status_code, 200)
person = Person.objects.get(user__username=username)
self.assertEqual(person.name, "Test Nãme")
self.assertEqual(person.ascii, "Test Name")
self.assertEqual(Person.objects.filter(alias__name="Test Name", user__username=username).count(), 1)
self.assertEqual(Person.objects.filter(alias__name="Test Nãme", user__username=username).count(), 1)
self.assertEqual(Email.objects.filter(address=email_address, person__user__username=username, active=True).count(), 1)
# deactivate address
without_email_address = { k: v for k, v in base_data.items() if k != "active_emails" }
r = self.client.post(url, without_email_address)
self.assertEqual(r.status_code, 200)
self.assertEqual(Email.objects.filter(address=email_address, person__user__username="plain", active=True).count(), 0)
r = self.client.get(url)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertEqual(len(q('[name="%s"][checked]' % email_address)), 0)
# add email address
empty_outbox()
new_email_address = "plain2@example.com"
with_new_email_address = base_data.copy()
with_new_email_address["new_email"] = new_email_address
r = self.client.post(url, with_new_email_address)
self.assertEqual(r.status_code, 200)
self.assertEqual(len(outbox), 1)
# confirm new email address
confirm_url = self.extract_confirm_url(outbox[-1])
r = self.client.get(confirm_url)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertEqual(len(q('[name="action"][value=confirm]')), 1)
r = self.client.post(confirm_url, { "action": "confirm" })
self.assertEqual(r.status_code, 200)
self.assertEqual(Email.objects.filter(address=new_email_address, person__user__username=username, active=1).count(), 1)
# try and add it again
empty_outbox()
r = self.client.post(url, with_new_email_address)
self.assertEqual(r.status_code, 200)
self.assertEqual(len(outbox), 1)
note = get_payload_text(outbox[-1])
self.assertIn(new_email_address, note)
self.assertIn("already associated with your account", note)
pronoundish = base_data.copy()
pronoundish["pronouns_freetext"] = "baz/boom"
r = self.client.post(url, pronoundish)
self.assertEqual(r.status_code, 200)
person = Person.objects.get(user__username=username)
self.assertEqual(person.pronouns_freetext,"baz/boom")
pronoundish["pronouns_freetext"]=""
r = self.client.post(url, pronoundish)
self.assertEqual(r.status_code, 200)
person = Person.objects.get(user__username=username)
self.assertEqual(person.pronouns_freetext, None)
pronoundish = base_data.copy()
del pronoundish["pronouns_freetext"]
pronoundish["pronouns_selectable"] = []
r = self.client.post(url, pronoundish)
self.assertEqual(r.status_code, 200)
person = Person.objects.get(user__username=username)
self.assertEqual(person.pronouns_selectable,[])
pronoundish["pronouns_selectable"] = ['he/him','she/her']
r = self.client.post(url, pronoundish)
self.assertEqual(r.status_code, 200)
person = Person.objects.get(user__username=username)
self.assertEqual(person.pronouns_selectable,['he/him','she/her'])
self.assertEqual(person.pronouns(),"he/him, she/her")
# Can't have both selectables and freetext
pronoundish["pronouns_freetext"] = "foo/bar/baz"
r = self.client.post(url, pronoundish)
self.assertContains(r, 'but not both' ,status_code=200)
q = PyQuery(r.content)
self.assertTrue(len(q("form div.invalid-feedback")) == 1)
# change role email
role = Role.objects.create(
person=Person.objects.get(user__username=username),
email=Email.objects.get(address=email_address),
name=RoleName.objects.get(slug="chair"),
group=Group.objects.get(acronym="mars"),
)
role_email_input_name = "role_%s-email" % role.pk
r = self.client.get(url)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertEqual(len(q('[name="%s"]' % role_email_input_name)), 1)
with_changed_role_email = base_data.copy()
with_changed_role_email["active_emails"] = new_email_address
with_changed_role_email[role_email_input_name] = new_email_address
r = self.client.post(url, with_changed_role_email)
self.assertEqual(r.status_code, 200)
updated_roles = Role.objects.filter(person=role.person, name=role.name, group=role.group)
self.assertEqual(len(updated_roles), 1)
self.assertEqual(updated_roles[0].email_id, new_email_address)
def test_email_case_insensitive_protection(self):
EmailFactory(address="TestAddress@example.net")
person = PersonFactory()
url = urlreverse("ietf.ietfauth.views.profile")
login_testing_unauthorized(self, person.user.username, url)
data = {
"name": person.name,
"plain": person.plain,
"ascii": person.ascii,
"active_emails": [e.address for e in person.email_set.filter(active=True)],
"new_email": "testaddress@example.net",
}
r = self.client.post(url, data)
self.assertContains(r, "A confirmation email has been sent to", status_code=200)
def test_nomcom_dressing_on_profile(self):
url = urlreverse('ietf.ietfauth.views.profile')
nobody = PersonFactory()
login_testing_unauthorized(self, nobody.user.username, url)
r = self.client.get(url)
self.assertEqual(r.status_code,200)
q = PyQuery(r.content)
self.assertFalse(q('#volunteer-button'))
self.assertFalse(q('#volunteered'))
year = date_today().year
nomcom = NomComFactory(group__acronym=f'nomcom{year}',is_accepting_volunteers=True)
r = self.client.get(url)
self.assertEqual(r.status_code,200)
q = PyQuery(r.content)
self.assertTrue(q('#volunteer-button'))
self.assertFalse(q('#volunteered'))
nomcom.volunteer_set.create(person=nobody)
r = self.client.get(url)
self.assertEqual(r.status_code,200)
q = PyQuery(r.content)
self.assertFalse(q('#volunteer-button'))
self.assertTrue(q('#volunteered'))
def test_reset_password(self):
WEAK_PASSWORD="password1234"
VALID_PASSWORD = "complex-and-long-valid-password"
ANOTHER_VALID_PASSWORD = "very-complicated-and-lengthy-password"
url = urlreverse("ietf.ietfauth.views.password_reset")
email = "someone@example.com"
user = PersonFactory(user__email=email).user
user.set_password(VALID_PASSWORD)
user.save()
# get
r = self.client.get(url)
self.assertEqual(r.status_code, 200)
# ask for reset, wrong username (form should not fail)
r = self.client.post(url, {"username": "nobody@example.com"})
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertTrue(len(q("form .is-invalid")) == 0)
# ask for reset
empty_outbox()
r = self.client.post(url, {"username": user.username})
self.assertEqual(r.status_code, 200)
self.assertEqual(len(outbox), 1)
# goto change password page, logged in as someone else
confirm_url = self.extract_confirm_url(outbox[-1])
other_user = UserFactory()
self.client.login(
username=other_user.username, password=other_user.username + "+password"
)
r = self.client.get(confirm_url)
self.assertEqual(r.status_code, 403)
# sign out and go back to change password page
self.client.logout()
r = self.client.get(confirm_url)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertNotIn(
user.username,
q(".nav").text(),
"user should not appear signed in while resetting password",
)
# password mismatch
r = self.client.post(
confirm_url,
{
"password": ANOTHER_VALID_PASSWORD,
"password_confirmation": ANOTHER_VALID_PASSWORD[::-1],
},
)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertTrue(len(q("form .is-invalid")) > 0)
# weak password
r = self.client.post(
confirm_url,
{
"password": WEAK_PASSWORD,
"password_confirmation": WEAK_PASSWORD,
},
)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertTrue(len(q("form .is-invalid")) > 0)
# confirm
r = self.client.post(
confirm_url,
{
"password": ANOTHER_VALID_PASSWORD,
"password_confirmation": ANOTHER_VALID_PASSWORD,
},
)
self.assertEqual(r.status_code, 200)
q = PyQuery(r.content)
self.assertEqual(len(q("form .is-invalid")), 0)
# reuse reset url
r = self.client.get(confirm_url)
self.assertEqual(r.status_code, 404)
# login after reset request
empty_outbox()
user.set_password(VALID_PASSWORD)
user.save()
r = self.client.post(url, {"username": user.username})
self.assertEqual(r.status_code, 200)
self.assertEqual(len(outbox), 1)
confirm_url = self.extract_confirm_url(outbox[-1])
r = self.client.post(
urlreverse("ietf.ietfauth.views.login"),
{"username": email, "password": VALID_PASSWORD},
)
r = self.client.get(confirm_url)
self.assertEqual(r.status_code, 404)
# change password after reset request
empty_outbox()
r = self.client.post(url, {"username": user.username})
self.assertEqual(r.status_code, 200)
self.assertEqual(len(outbox), 1)
confirm_url = self.extract_confirm_url(outbox[-1])
user.set_password(ANOTHER_VALID_PASSWORD)
user.save()
r = self.client.get(confirm_url)
self.assertEqual(r.status_code, 404)
def test_reset_password_without_person(self):
"""No password reset for account without a person"""
url = urlreverse('ietf.ietfauth.views.password_reset')
user = UserFactory()
user.set_password('some password')
user.save()
empty_outbox()
r = self.client.post(url, { 'username': user.username})
self.assertContains(r, 'We have sent you an email with instructions', status_code=200)
q = PyQuery(r.content)
self.assertTrue(len(q("form .is-invalid")) == 0)
self.assertEqual(len(outbox), 0)
def test_reset_password_address_handling(self):
"""Reset password links are only sent to known, active addresses"""
url = urlreverse('ietf.ietfauth.views.password_reset')
person = PersonFactory()
person.email_set.update(active=False)
empty_outbox()
r = self.client.post(url, { 'username': person.user.username})
self.assertContains(r, 'We have sent you an email with instructions', status_code=200)
q = PyQuery(r.content)
self.assertTrue(len(q("form .is-invalid")) == 0)
self.assertEqual(len(outbox), 0)
active_address = EmailFactory(person=person).address
r = self.client.post(url, {'username': person.user.username})
self.assertContains(r, 'We have sent you an email with instructions', status_code=200)
self.assertEqual(len(outbox), 1)
to = outbox[0].get('To')
self.assertIn(active_address, to)
self.assertNotIn(person.user.username, to)
def test_reset_password_without_username(self):
"""Reset password using non-username email address"""
url = urlreverse('ietf.ietfauth.views.password_reset')
person = PersonFactory()
secondary_address = EmailFactory(person=person).address
inactive_secondary_address = EmailFactory(person=person, active=False).address
empty_outbox()
r = self.client.post(url, { 'username': secondary_address})
self.assertContains(r, 'We have sent you an email with instructions', status_code=200)
self.assertEqual(len(outbox), 1)
to = outbox[0].get('To')
self.assertIn(person.user.username, to)
self.assertIn(secondary_address, to)
self.assertNotIn(inactive_secondary_address, to)
def test_reset_password_without_user(self):
"""Reset password using email address for person without a user account"""
url = urlreverse('ietf.ietfauth.views.password_reset')
email = EmailFactory()
person = email.person
# Remove the user object from the person to get a Email/Person without User:
person.user = None
person.save()
# Remove the remaining User record, since reset_password looks for that by username:
User.objects.filter(username__iexact=email.address).delete()
empty_outbox()
r = self.client.post(url, { 'username': email.address })
self.assertEqual(len(outbox), 1)
lastReceivedEmail = outbox[-1]
self.assertIn(email.address, lastReceivedEmail.get('To'))
self.assertTrue(lastReceivedEmail.get('Subject').startswith("Confirm password reset"))
self.assertContains(r, "Your password reset request has been successfully received", status_code=200)
def test_review_overview(self):
review_req = ReviewRequestFactory()
assignment = ReviewAssignmentFactory(review_request=review_req,reviewer=EmailFactory(person__user__username='reviewer'))
RoleFactory(name_id='reviewer',group=review_req.team,person=assignment.reviewer.person)
doc = review_req.doc
reviewer = assignment.reviewer.person
UnavailablePeriod.objects.create(
team=review_req.team,
person=reviewer,
start_date=date_today() - datetime.timedelta(days=10),
availability="unavailable",
)
url = urlreverse("ietf.ietfauth.views.review_overview")
login_testing_unauthorized(self, reviewer.user.username, url)
# get
r = self.client.get(url)
self.assertEqual(r.status_code, 200)
self.assertContains(r, review_req.doc.name)
# wish to review
r = self.client.post(url, {
"action": "add_wish",
'doc': doc.pk,
"team": review_req.team_id,
})
self.assertEqual(r.status_code, 302)
self.assertEqual(ReviewWish.objects.filter(doc=doc, team=review_req.team).count(), 1)
# delete wish
r = self.client.post(url, {
"action": "delete_wish",
'wish_id': ReviewWish.objects.get(doc=doc, team=review_req.team).pk,
})
self.assertEqual(r.status_code, 302)
self.assertEqual(ReviewWish.objects.filter(doc=doc, team=review_req.team).count(), 0)
def test_change_password(self):
VALID_PASSWORD = "complex-and-long-valid-password"
ANOTHER_VALID_PASSWORD = "very-complicated-and-lengthy-password"
chpw_url = urlreverse("ietf.ietfauth.views.change_password")
prof_url = urlreverse("ietf.ietfauth.views.profile")
login_url = urlreverse("ietf.ietfauth.views.login")
redir_url = "%s?next=%s" % (login_url, chpw_url)
# get without logging in
r = self.client.get(chpw_url)
self.assertRedirects(r, redir_url)
user = User.objects.create(
username="someone@example.com", email="someone@example.com"
)
user.set_password(VALID_PASSWORD)
user.save()
p = Person.objects.create(name="Some One", ascii="Some One", user=user)
Email.objects.create(address=user.username, person=p, origin=user.username)
# log in
r = self.client.post(
redir_url, {"username": user.username, "password": VALID_PASSWORD}
)
self.assertRedirects(r, chpw_url)
# wrong current password
r = self.client.post(
chpw_url,
{
"current_password": "fiddlesticks",
"password": ANOTHER_VALID_PASSWORD,
"password_confirmation": ANOTHER_VALID_PASSWORD,
},
)
self.assertEqual(r.status_code, 200)
self.assertFormError(r.context["form"], "current_password", "Invalid password")
# mismatching new passwords
r = self.client.post(
chpw_url,
{
"current_password": VALID_PASSWORD,
"password": ANOTHER_VALID_PASSWORD,
"password_confirmation": ANOTHER_VALID_PASSWORD[::-1],
},
)
self.assertEqual(r.status_code, 200)
self.assertFormError(
r.context["form"],
"password_confirmation",
"The password confirmation is different than the new password",
)
# password too short
r = self.client.post(
chpw_url,
{
"current_password": VALID_PASSWORD,
"password": "sh0rtpw0rd",
"password_confirmation": "sh0rtpw0rd",
}
)
self.assertEqual(r.status_code, 200)
self.assertFormError(
r.context["form"],
"password",
"This password is too short. It must contain at least "
f"{settings.PASSWORD_POLICY_MIN_LENGTH} characters."
)
# password too simple
r = self.client.post(
chpw_url,
{
"current_password": VALID_PASSWORD,
"password": "passwordpassword",
"password_confirmation": "passwordpassword",
}
)
self.assertEqual(r.status_code, 200)
self.assertFormError(
r.context["form"],
"password",
"This password does not meet complexity requirements "
"and is easily guessable."
)
# correct password change
r = self.client.post(
chpw_url,
{
"current_password": VALID_PASSWORD,
"password": ANOTHER_VALID_PASSWORD,
"password_confirmation": ANOTHER_VALID_PASSWORD,
},
)
self.assertRedirects(r, prof_url)
# refresh user object
user = User.objects.get(username="someone@example.com")
self.assertTrue(user.check_password(ANOTHER_VALID_PASSWORD))
def test_change_username(self):
VALID_PASSWORD = "complex-and-long-valid-password"
chun_url = urlreverse("ietf.ietfauth.views.change_username")
prof_url = urlreverse("ietf.ietfauth.views.profile")
login_url = urlreverse("ietf.ietfauth.views.login")
redir_url = "%s?next=%s" % (login_url, chun_url)
# get without logging in
r = self.client.get(chun_url)
self.assertRedirects(r, redir_url)
user = User.objects.create(
username="someone@example.com", email="someone@example.com"
)
user.set_password(VALID_PASSWORD)
user.save()
p = Person.objects.create(name="Some One", ascii="Some One", user=user)
Email.objects.create(address=user.username, person=p, origin=user.username)
Email.objects.create(
address="othername@example.org", person=p, origin=user.username
)
# log in
r = self.client.post(
redir_url, {"username": user.username, "password": VALID_PASSWORD}
)
self.assertRedirects(r, chun_url)
# wrong username
r = self.client.post(
chun_url,
{
"username": "fiddlesticks",
"password": VALID_PASSWORD,
},
)
self.assertEqual(r.status_code, 200)
self.assertFormError(
r.context["form"],
"username",
"Select a valid choice. fiddlesticks is not one of the available choices.",
)
# wrong password
r = self.client.post(
chun_url,
{
"username": "othername@example.org",
"password": "foobar",
},
)
self.assertEqual(r.status_code, 200)
self.assertFormError(r.context["form"], "password", "Invalid password")
# correct username change
r = self.client.post(
chun_url,
{
"username": "othername@example.org",
"password": VALID_PASSWORD,
},
)
self.assertRedirects(r, prof_url)
# refresh user object
prev = user
user = User.objects.get(username="othername@example.org")
self.assertEqual(prev, user)
self.assertTrue(user.check_password(VALID_PASSWORD))
def test_apikey_management(self):
# Create a person with a role that will give at least one valid apikey
person = RoleFactory(name_id='robot', group__acronym='secretariat').person
url = urlreverse('ietf.ietfauth.views.apikey_index')
# Check that the url is protected, then log in
login_testing_unauthorized(self, person.user.username, url)
# Check api key list content
r = self.client.get(url)
self.assertContains(r, 'API keys')
self.assertContains(r, 'Get a new personal API key')
# Check the add key form content
url = urlreverse('ietf.ietfauth.views.apikey_create')
r = self.client.get(url)
self.assertContains(r, 'Create a new personal API key')
self.assertContains(r, 'Endpoint')
# Add 2 keys
endpoints = person.available_api_endpoints()
for endpoint, display in endpoints:
r = self.client.post(url, {'endpoint': endpoint})
self.assertRedirects(r, urlreverse('ietf.ietfauth.views.apikey_index'))
# Check api key list content
url = urlreverse('ietf.ietfauth.views.apikey_index')
r = self.client.get(url)
for endpoint, display in endpoints:
self.assertContains(r, endpoint)
q = PyQuery(r.content)
self.assertEqual(len(q('td code')), len(endpoints) * 2) # hash and endpoint
self.assertEqual(len(q('td a:contains("Disable")')), len(endpoints))
# Get one of the keys
key = person.apikeys.first()
# Check the disable key form content
url = urlreverse('ietf.ietfauth.views.apikey_disable')
r = self.client.get(url)
self.assertEqual(r.status_code, 200)
self.assertContains(r, 'Disable a personal API key')
self.assertContains(r, 'Key')
# Try to delete something that doesn't exist
r = self.client.post(url, {'hash': key.hash()+'bad'})
self.assertEqual(r.status_code, 200)
self.assertContains(r,"Key validation failed; key not disabled")
# Try to delete someone else's key
otherkey = PersonalApiKeyFactory()
r = self.client.post(url, {'hash': otherkey.hash()})
self.assertEqual(r.status_code, 200)
self.assertContains(r,"Key validation failed; key not disabled")
# Delete a key
r = self.client.post(url, {'hash': key.hash()})
self.assertRedirects(r, urlreverse('ietf.ietfauth.views.apikey_index'))
# Check the api key list content again
url = urlreverse('ietf.ietfauth.views.apikey_index')
r = self.client.get(url)
q = PyQuery(r.content)
self.assertEqual(len(q('td code')), len(endpoints) * 2) # key hash and endpoint
self.assertEqual(len(q('td a:contains("Disable")')), len(endpoints)-1)
def test_apikey_errors(self):
BAD_KEY = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
person = PersonFactory()
area = GroupFactory(type_id='area')
area.role_set.create(name_id='ad', person=person, email=person.email())
url = urlreverse('ietf.ietfauth.views.apikey_create')
# Check that the url is protected, then log in
login_testing_unauthorized(self, person.user.username, url)
# Add keys
for endpoint, display in person.available_api_endpoints():
r = self.client.post(url, {'endpoint': endpoint})
self.assertRedirects(r, urlreverse('ietf.ietfauth.views.apikey_index'))
for key in person.apikeys.all()[:3]:
# bad method
r = self.client.put(key.endpoint, {'apikey':key.hash()})
self.assertContains(r, 'Method not allowed', status_code=405)
# missing apikey
r = self.client.post(key.endpoint, {'dummy':'dummy',})
self.assertContains(r, 'Missing apikey parameter', status_code=400)
# invalid apikey
r = self.client.post(key.endpoint, {'apikey':BAD_KEY, 'dummy':'dummy',})
self.assertContains(r, 'Invalid apikey', status_code=403)
# invalid garbage apikey (decode error)
r = self.client.post(key.endpoint, {'apikey':'foobar', 'dummy':'dummy',})
self.assertContains(r, 'Invalid apikey', status_code=403)
# invalid garbage apikey (struct unpack error)
# number of characters in apikey must be divisible by 4
r = self.client.post(key.endpoint, {'apikey':'foob', 'dummy':'dummy',})
self.assertContains(r, 'Invalid apikey', status_code=403)
# invalid apikey (invalidated api key)
unauthorized_url = urlreverse('ietf.api.views.app_auth', kwargs={'app': 'authortools'})
invalidated_apikey = PersonalApiKeyFactory(endpoint=unauthorized_url, person=person, valid=False)
r = self.client.post(unauthorized_url, {'apikey': invalidated_apikey.hash()})
self.assertContains(r, 'Invalid apikey', status_code=403)
# too long since regular login
person.user.last_login = timezone.now() - datetime.timedelta(days=settings.UTILS_APIKEY_GUI_LOGIN_LIMIT_DAYS+1)
person.user.save()
r = self.client.post(key.endpoint, {'apikey':key.hash(), 'dummy':'dummy',})
self.assertContains(r, 'Too long since last regular login', status_code=400)
person.user.last_login = timezone.now()
person.user.save()
# endpoint mismatch
key2 = PersonalApiKeyFactory(
person=person,
endpoint='/',
validate_model=False, # allow invalid endpoint
)
r = self.client.post(key.endpoint, {'apikey':key2.hash(), 'dummy':'dummy',})
self.assertContains(r, 'Apikey endpoint mismatch', status_code=400)
key2.delete()
def test_send_apikey_report(self):
person = RoleFactory(name_id='secr', group__acronym='secretariat').person
url = urlreverse('ietf.ietfauth.views.apikey_create')
# Check that the url is protected, then log in
login_testing_unauthorized(self, person.user.username, url)
# Add keys
endpoints = person.available_api_endpoints()
for endpoint, display in endpoints:
r = self.client.post(url, {'endpoint': endpoint})
self.assertRedirects(r, urlreverse('ietf.ietfauth.views.apikey_index'))
# Use the endpoints (the form content will not be acceptable, but the
# apikey usage will be registered)
count = 2
# avoid usage across dates
if timezone.now().time() > datetime.time(hour=23, minute=59, second=58):
time.sleep(2)
for i in range(count):
for key in person.apikeys.all():
self.client.post(key.endpoint, {'apikey':key.hash(), 'dummy': 'dummy', })
date = str(date_today())
empty_outbox()
send_apikey_usage_emails_task(days=7)
self.assertEqual(len(outbox), len(endpoints))
for mail in outbox:
body = get_payload_text(mail)
self.assertIn("API key usage", mail['subject'])
self.assertIn(" %s times" % count, body)
self.assertIn(date, body)
def test_edit_person_extresources(self):
url = urlreverse('ietf.ietfauth.views.edit_person_externalresources')
person = PersonFactory()
r = self.client.get(url)
self.assertNotEqual(r.status_code, 200)
self.client.login(username=person.user.username,password=person.user.username+'+password')
r = self.client.get(url)
self.assertEqual(r.status_code,200)
q = PyQuery(r.content)
self.assertEqual(len(q('form textarea[id=id_resources]')),1)
badlines = (
'github_repo https://github3.com/some/repo',
'github_notify badaddr',
'website /not/a/good/url',
'notavalidtag blahblahblah',
'website',
)