/
test_journalist.py
2898 lines (2301 loc) · 115 KB
/
test_journalist.py
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
# -*- coding: utf-8 -*-
import base64
import binascii
import io
from mock import call
import os
from pathlib import Path
import pytest
import random
import zipfile
from base64 import b64decode
from io import BytesIO
from flask import current_app, escape, g, session, url_for
from mock import patch
from pyotp import TOTP
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import StaleDataError
from sqlalchemy.sql.expression import func
from html import escape as htmlescape
import journalist_app as journalist_app_module
from journalist_app.utils import mark_seen
import models
from db import db
from models import (
InvalidPasswordLength,
InstanceConfig,
Journalist,
Reply,
SeenFile,
SeenMessage,
SeenReply,
Source,
InvalidUsernameException,
Submission
)
from sdconfig import config
from .utils.instrument import InstrumentedApp
from . import utils
# Smugly seed the RNG for deterministic testing
random.seed(r'¯\_(ツ)_/¯')
VALID_PASSWORD = 'correct horse battery staple generic passphrase hooray'
VALID_PASSWORD_2 = 'another correct horse battery staple generic passphrase'
# These are factored out of the tests because some test have a
# postive/negative case under varying conditions, and we don't want
# false postives after modifying a string in the application.
EMPTY_REPLY_TEXT = "You cannot send an empty reply."
ADMIN_LINK = '<a href="/admin/" id="link-admin-index">'
def _login_user(app, username, password, otp_secret):
resp = app.post(url_for('main.login'),
data={'username': username,
'password': password,
'token': TOTP(otp_secret).now()},
follow_redirects=True)
assert resp.status_code == 200
assert hasattr(g, 'user') # ensure logged in
def test_user_sees_os_warning_if_server_past_eol(config, journalist_app, test_journo):
journalist_app.config.update(OS_PAST_EOL=True, OS_NEAR_EOL=False)
with journalist_app.test_client() as app:
_login_user(
app, test_journo["username"], test_journo["password"], test_journo["otp_secret"]
)
resp = app.get(url_for("main.index"))
text = resp.data.decode("utf-8")
assert 'id="os-past-eol"' in text, text
assert 'id="os-near-eol"' not in text, text
def test_user_sees_os_warning_if_server_past_eol_sanity_check(config, journalist_app, test_journo):
"""
Sanity check (both conditions cannot be True but test guard against developer error)
"""
journalist_app.config.update(OS_PAST_EOL=True, OS_NEAR_EOL=True)
with journalist_app.test_client() as app:
_login_user(
app, test_journo["username"], test_journo["password"], test_journo["otp_secret"]
)
resp = app.get(url_for("main.index"))
text = resp.data.decode("utf-8")
assert 'id="os-past-eol"' in text, text
assert 'id="os-near-eol"' not in text, text
def test_user_sees_os_warning_if_server_close_to_eol(config, journalist_app, test_journo):
journalist_app.config.update(OS_PAST_EOL=False, OS_NEAR_EOL=True)
with journalist_app.test_client() as app:
_login_user(
app, test_journo["username"], test_journo["password"], test_journo["otp_secret"]
)
resp = app.get(url_for("main.index"))
text = resp.data.decode("utf-8")
assert 'id="os-past-eol"' not in text, text
assert 'id="os-near-eol"' in text, text
def test_user_does_not_see_os_warning_if_server_is_current(config, journalist_app, test_journo):
journalist_app.config.update(OS_PAST_EOL=False, OS_NEAR_EOL=False)
with journalist_app.test_client() as app:
_login_user(
app, test_journo["username"], test_journo["password"], test_journo["otp_secret"]
)
resp = app.get(url_for("main.index"))
text = resp.data.decode("utf-8")
assert 'id="os-past-eol"' not in text, text
assert 'id="os-near-eol"' not in text, text
def test_user_with_whitespace_in_username_can_login(journalist_app):
# Create a user with whitespace at the end of the username
with journalist_app.app_context():
username_with_whitespace = 'journalist '
user, password = utils.db_helper.init_journalist(is_admin=False)
otp_secret = user.otp_secret
user.username = username_with_whitespace
db.session.add(user)
db.session.commit()
# Verify that user is able to login successfully
with journalist_app.test_client() as app:
_login_user(app, username_with_whitespace, password,
otp_secret)
def test_reply_error_logging(journalist_app, test_journo, test_source):
exception_class = StaleDataError
exception_msg = 'Potentially sensitive content!'
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'],
test_journo['password'], test_journo['otp_secret'])
with patch.object(journalist_app.logger, 'error') \
as mocked_error_logger:
with patch.object(db.session, 'commit',
side_effect=exception_class(exception_msg)):
resp = app.post(
url_for('main.reply'),
data={'filesystem_id': test_source['filesystem_id'],
'message': '_'},
follow_redirects=True)
assert resp.status_code == 200
# Notice the "potentially sensitive" exception_msg is not present in
# the log event.
mocked_error_logger.assert_called_once_with(
"Reply from '{}' (ID {}) failed: {}!".format(
test_journo['username'],
test_journo['id'],
exception_class))
def test_reply_error_flashed_message(journalist_app, test_journo, test_source):
exception_class = StaleDataError
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'],
test_journo['password'], test_journo['otp_secret'])
with InstrumentedApp(app) as ins:
with patch.object(db.session, 'commit',
side_effect=exception_class()):
app.post(url_for('main.reply'),
data={'filesystem_id': test_source['filesystem_id'],
'message': '_'})
ins.assert_message_flashed(
'An unexpected error occurred! Please '
'inform your admin.', 'error')
def test_empty_replies_are_rejected(journalist_app, test_journo, test_source):
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'],
test_journo['password'], test_journo['otp_secret'])
resp = app.post(url_for('main.reply'),
data={'filesystem_id': test_source['filesystem_id'],
'message': ''},
follow_redirects=True)
text = resp.data.decode('utf-8')
assert EMPTY_REPLY_TEXT in text
def test_nonempty_replies_are_accepted(journalist_app, test_journo,
test_source):
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'],
test_journo['password'], test_journo['otp_secret'])
resp = app.post(url_for('main.reply'),
data={'filesystem_id': test_source['filesystem_id'],
'message': '_'},
follow_redirects=True)
text = resp.data.decode('utf-8')
assert EMPTY_REPLY_TEXT not in text
def test_successful_reply_marked_as_seen_by_sender(journalist_app, test_journo, test_source):
with journalist_app.test_client() as app:
journo = test_journo['journalist']
_login_user(app, journo.username, test_journo['password'], test_journo['otp_secret'])
seen_reply = SeenReply.query.filter_by(journalist_id=journo.id).one_or_none()
assert not seen_reply
resp = app.post(
url_for('main.reply'),
data={'filesystem_id': test_source['filesystem_id'], 'message': '_'},
follow_redirects=True
)
text = resp.data.decode('utf-8')
assert EMPTY_REPLY_TEXT not in text
seen_reply = SeenReply.query.filter_by(journalist_id=journo.id).one_or_none()
assert seen_reply
def test_unauthorized_access_redirects_to_login(journalist_app):
with journalist_app.test_client() as app:
with InstrumentedApp(journalist_app) as ins:
resp = app.get(url_for('main.index'))
ins.assert_redirects(resp, url_for('main.login'))
def test_login_throttle(journalist_app, test_journo):
# Overwrite the default value used during testing
original_hardening = models.LOGIN_HARDENING
models.LOGIN_HARDENING = True
try:
with journalist_app.test_client() as app:
for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD):
resp = app.post(
url_for('main.login'),
data=dict(username=test_journo['username'],
password='invalid',
token='invalid'))
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert "Login failed" in text
resp = app.post(
url_for('main.login'),
data=dict(username=test_journo['username'],
password='invalid',
token='invalid'))
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert ("Please wait at least {} seconds".format(
Journalist._LOGIN_ATTEMPT_PERIOD) in text)
finally:
models.LOGIN_HARDENING = original_hardening
def test_login_throttle_is_not_global(journalist_app, test_journo, test_admin):
"""The login throttling should be per-user, not global. Global login
throttling can prevent all users logging into the application."""
original_hardening = models.LOGIN_HARDENING
# Overwrite the default value used during testing
# Note that this may break other tests if doing parallel testing
models.LOGIN_HARDENING = True
try:
with journalist_app.test_client() as app:
for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD):
resp = app.post(
url_for('main.login'),
data=dict(username=test_journo['username'],
password='invalid',
token='invalid'))
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert "Login failed" in text
resp = app.post(
url_for('main.login'),
data=dict(username=test_journo['username'],
password='invalid',
token='invalid'))
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert ("Please wait at least {} seconds".format(
Journalist._LOGIN_ATTEMPT_PERIOD) in text)
# A different user should be able to login
resp = app.post(
url_for('main.login'),
data=dict(username=test_admin['username'],
password=test_admin['password'],
token=TOTP(test_admin['otp_secret']).now()),
follow_redirects=True)
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert "Sources" in text
finally:
models.LOGIN_HARDENING = original_hardening
def test_login_invalid_credentials(journalist_app, test_journo):
with journalist_app.test_client() as app:
resp = app.post(url_for('main.login'),
data=dict(username=test_journo['username'],
password='invalid',
token='mocked'))
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert "Login failed" in text
def test_validate_redirect(journalist_app):
with journalist_app.test_client() as app:
resp = app.post(url_for('main.index'), follow_redirects=True)
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert "Login to access" in text
def test_login_valid_credentials(journalist_app, test_journo):
with journalist_app.test_client() as app:
resp = app.post(
url_for('main.login'),
data=dict(username=test_journo['username'],
password=test_journo['password'],
token=TOTP(test_journo['otp_secret']).now()),
follow_redirects=True)
assert resp.status_code == 200 # successful login redirects to index
text = resp.data.decode('utf-8')
assert "Sources" in text
assert "No documents have been submitted!" in text
def test_admin_login_redirects_to_index(journalist_app, test_admin):
with journalist_app.test_client() as app:
with InstrumentedApp(journalist_app) as ins:
resp = app.post(
url_for('main.login'),
data=dict(username=test_admin['username'],
password=test_admin['password'],
token=TOTP(test_admin['otp_secret']).now()),
follow_redirects=False)
ins.assert_redirects(resp, url_for('main.index'))
def test_user_login_redirects_to_index(journalist_app, test_journo):
with journalist_app.test_client() as app:
with InstrumentedApp(journalist_app) as ins:
resp = app.post(
url_for('main.login'),
data=dict(username=test_journo['username'],
password=test_journo['password'],
token=TOTP(test_journo['otp_secret']).now()),
follow_redirects=False)
ins.assert_redirects(resp, url_for('main.index'))
def test_admin_has_link_to_edit_account_page_in_index_page(journalist_app,
test_admin):
with journalist_app.test_client() as app:
resp = app.post(
url_for('main.login'),
data=dict(username=test_admin['username'],
password=test_admin['password'],
token=TOTP(test_admin['otp_secret']).now()),
follow_redirects=True)
edit_account_link = ('<a href="/account/account" '
'id="link-edit-account">')
text = resp.data.decode('utf-8')
assert edit_account_link in text
def test_user_has_link_to_edit_account_page_in_index_page(journalist_app,
test_journo):
with journalist_app.test_client() as app:
resp = app.post(
url_for('main.login'),
data=dict(username=test_journo['username'],
password=test_journo['password'],
token=TOTP(test_journo['otp_secret']).now()),
follow_redirects=True)
edit_account_link = ('<a href="/account/account" '
'id="link-edit-account">')
text = resp.data.decode('utf-8')
assert edit_account_link in text
def test_admin_has_link_to_admin_index_page_in_index_page(journalist_app,
test_admin):
with journalist_app.test_client() as app:
resp = app.post(
url_for('main.login'),
data=dict(username=test_admin['username'],
password=test_admin['password'],
token=TOTP(test_admin['otp_secret']).now()),
follow_redirects=True)
text = resp.data.decode('utf-8')
assert ADMIN_LINK in text
def test_user_lacks_link_to_admin_index_page_in_index_page(journalist_app,
test_journo):
with journalist_app.test_client() as app:
resp = app.post(
url_for('main.login'),
data=dict(username=test_journo['username'],
password=test_journo['password'],
token=TOTP(test_journo['otp_secret']).now()),
follow_redirects=True)
text = resp.data.decode('utf-8')
assert ADMIN_LINK not in text
def test_admin_logout_redirects_to_index(journalist_app, test_admin):
with journalist_app.test_client() as app:
with InstrumentedApp(journalist_app) as ins:
_login_user(app, test_admin['username'],
test_admin['password'],
test_admin['otp_secret'])
resp = app.get(url_for('main.logout'))
ins.assert_redirects(resp, url_for('main.index'))
def test_user_logout_redirects_to_index(journalist_app, test_journo):
with journalist_app.test_client() as app:
with InstrumentedApp(journalist_app) as ins:
_login_user(app, test_journo['username'],
test_journo['password'],
test_journo['otp_secret'])
resp = app.get(url_for('main.logout'))
ins.assert_redirects(resp, url_for('main.index'))
def test_admin_index(journalist_app, test_admin):
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
resp = app.get(url_for('admin.index'))
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert "Admin Interface" in text
def test_admin_delete_user(journalist_app, test_admin, test_journo):
# Verify journalist is in the database
with journalist_app.app_context():
assert Journalist.query.get(test_journo['id']) is not None
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
resp = app.post(url_for('admin.delete_user',
user_id=test_journo['id']),
follow_redirects=True)
# Assert correct interface behavior
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert escape("Deleted user '{}'".format(test_journo['username'])) \
in text
# Verify journalist is no longer in the database
with journalist_app.app_context():
assert Journalist.query.get(test_journo['id']) is None
def test_admin_cannot_delete_self(journalist_app, test_admin, test_journo):
# Verify journalist is in the database
with journalist_app.app_context():
assert Journalist.query.get(test_journo['id']) is not None
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
resp = app.post(url_for('admin.delete_user',
user_id=test_admin['id']),
follow_redirects=True)
# Assert correct interface behavior
assert resp.status_code == 403
resp = app.get(url_for('admin.index'), follow_redirects=True)
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert "Admin Interface" in text
# The user can be edited and deleted
assert escape("Edit user {}".format(test_journo['username'])) in text
assert escape("Delete user {}".format(test_journo['username'])) in text
# The admin can be edited but cannot deleted
assert escape("Edit user {}".format(test_admin['username'])) in text
assert escape("Delete user {}".format(test_admin['username'])) \
not in text
def test_admin_edits_user_password_success_response(journalist_app,
test_admin,
test_journo):
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
resp = app.post(url_for('admin.new_password',
user_id=test_journo['id']),
data=dict(password=VALID_PASSWORD_2),
follow_redirects=True)
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert 'Password updated.' in text
assert VALID_PASSWORD_2 in text
def test_admin_edits_user_password_session_invalidate(journalist_app,
test_admin,
test_journo):
# Start the journalist session.
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'], test_journo['password'],
test_journo['otp_secret'])
# Change the journalist password via an admin session.
with journalist_app.test_client() as admin_app:
_login_user(admin_app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
resp = admin_app.post(url_for('admin.new_password',
user_id=test_journo['id']),
data=dict(password=VALID_PASSWORD_2),
follow_redirects=True)
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert 'Password updated.' in text
assert VALID_PASSWORD_2 in text
# Now verify the password change error is flashed.
resp = app.get(url_for('main.index'), follow_redirects=True)
text = resp.data.decode('utf-8')
assert 'You have been logged out due to password change' in text
# Also ensure that session is now invalid.
session.pop('expires', None)
session.pop('csrf_token', None)
session.pop('locale', None)
assert not session, session
def test_admin_deletes_invalid_user_404(journalist_app, test_admin):
with journalist_app.app_context():
invalid_id = db.session.query(func.max(Journalist.id)).scalar() + 1
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
resp = app.post(url_for('admin.delete_user', user_id=invalid_id))
assert resp.status_code == 404
def test_admin_edits_user_password_error_response(journalist_app,
test_admin,
test_journo):
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
with patch('sqlalchemy.orm.scoping.scoped_session.commit',
side_effect=Exception()):
resp = app.post(url_for('admin.new_password',
user_id=test_journo['id']),
data=dict(password=VALID_PASSWORD_2),
follow_redirects=True)
text = resp.data.decode('utf-8')
assert ('There was an error, and the new password might not have '
'been saved correctly.') in text
def test_user_edits_password_success_response(journalist_app, test_journo):
original_hardening = models.LOGIN_HARDENING
try:
# Set this to false because we login then immediately reuse the same
# token when authenticating to change the password. This triggers login
# hardening measures.
models.LOGIN_HARDENING = False
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'], test_journo['password'],
test_journo['otp_secret'])
token = TOTP(test_journo['otp_secret']).now()
resp = app.post(url_for('account.new_password'),
data=dict(current_password=test_journo['password'],
token=token,
password=VALID_PASSWORD_2),
follow_redirects=True)
text = resp.data.decode('utf-8')
assert "Password updated." in text
assert VALID_PASSWORD_2 in text
finally:
models.LOGIN_HARDENING = original_hardening
def test_user_edits_password_expires_session(journalist_app, test_journo):
original_hardening = models.LOGIN_HARDENING
try:
# Set this to false because we login then immediately reuse the same
# token when authenticating to change the password. This triggers login
# hardening measures.
models.LOGIN_HARDENING = False
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'], test_journo['password'],
test_journo['otp_secret'])
assert 'uid' in session
with InstrumentedApp(journalist_app) as ins:
token = TOTP(test_journo['otp_secret']).now()
resp = app.post(url_for('account.new_password'),
data=dict(
current_password=test_journo['password'],
token=token,
password=VALID_PASSWORD_2))
ins.assert_redirects(resp, url_for('main.login'))
# verify the session was expired after the password was changed
assert 'uid' not in session
finally:
models.LOGIN_HARDENING = original_hardening
def test_user_edits_password_error_reponse(journalist_app, test_journo):
original_hardening = models.LOGIN_HARDENING
try:
# Set this to false because we login then immediately reuse the same
# token when authenticating to change the password. This triggers login
# hardening measures.
models.LOGIN_HARDENING = False
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'], test_journo['password'],
test_journo['otp_secret'])
# patch token verification because there are multiple commits
# to the database and this isolates the one we want to fail
with patch.object(Journalist, 'verify_token', return_value=True):
with patch.object(db.session, 'commit',
side_effect=Exception()):
resp = app.post(
url_for('account.new_password'),
data=dict(current_password=test_journo['password'],
token='mocked',
password=VALID_PASSWORD_2),
follow_redirects=True)
text = resp.data.decode('utf-8')
assert ('There was an error, and the new password might not have '
'been saved correctly.') in text
finally:
models.LOGIN_HARDENING = original_hardening
def test_admin_add_user_when_username_already_taken(journalist_app, test_admin):
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret'])
resp = app.post(url_for('admin.add_user'),
data=dict(username=test_admin['username'],
first_name='',
last_name='',
password=VALID_PASSWORD,
is_admin=None))
text = resp.data.decode('utf-8')
assert 'already taken' in text
def test_max_password_length():
"""Creating a Journalist with a password that is greater than the
maximum password length should raise an exception"""
overly_long_password = VALID_PASSWORD + \
'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1)
with pytest.raises(InvalidPasswordLength):
Journalist(username="My Password is Too Big!",
password=overly_long_password)
def test_login_password_too_long(journalist_app, test_journo, mocker):
mocked_error_logger = mocker.patch('journalist.app.logger.error')
with journalist_app.test_client() as app:
resp = app.post(url_for('main.login'),
data=dict(username=test_journo['username'],
password='a' * (Journalist.MAX_PASSWORD_LEN + 1),
token=TOTP(test_journo['otp_secret']).now()))
assert resp.status_code == 200
text = resp.data.decode('utf-8')
assert "Login failed" in text
mocked_error_logger.assert_called_once_with(
"Login for '{}' failed: Password too long (len={})".format(
test_journo['username'], Journalist.MAX_PASSWORD_LEN + 1))
def test_min_password_length():
"""Creating a Journalist with a password that is smaller than the
minimum password length should raise an exception. This uses the
magic number 7 below to get around the "diceware-like" requirement
that may cause a failure before the length check.
"""
password = ('a ' * 7)[0:(Journalist.MIN_PASSWORD_LEN - 1)]
with pytest.raises(InvalidPasswordLength):
Journalist(username="My Password is Too Small!",
password=password)
def test_admin_edits_user_password_too_long_warning(journalist_app,
test_admin,
test_journo):
# append a bunch of a's to a diceware password to keep it "diceware-like"
overly_long_password = VALID_PASSWORD + \
'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1)
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
with InstrumentedApp(journalist_app) as ins:
app.post(
url_for('admin.new_password', user_id=test_journo['id']),
data=dict(username=test_journo['username'],
first_name='',
last_name='',
is_admin=None,
password=overly_long_password),
follow_redirects=True)
ins.assert_message_flashed('The password you submitted is invalid. '
'Password not changed.', 'error')
def test_user_edits_password_too_long_warning(journalist_app, test_journo):
overly_long_password = VALID_PASSWORD + \
'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1)
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'], test_journo['password'],
test_journo['otp_secret'])
with InstrumentedApp(journalist_app) as ins:
app.post(
url_for('account.new_password'),
data=dict(username=test_journo['username'],
first_name='',
last_name='',
is_admin=None,
token=TOTP(test_journo['otp_secret']).now(),
current_password=test_journo['password'],
password=overly_long_password),
follow_redirects=True)
ins.assert_message_flashed('The password you submitted is invalid. '
'Password not changed.', 'error')
def test_admin_add_user_password_too_long_warning(journalist_app, test_admin):
overly_long_password = VALID_PASSWORD + \
'a' * (Journalist.MAX_PASSWORD_LEN - len(VALID_PASSWORD) + 1)
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
with InstrumentedApp(journalist_app) as ins:
app.post(
url_for('admin.add_user'),
data=dict(username='dellsberg',
first_name='',
last_name='',
password=overly_long_password,
is_admin=None))
ins.assert_message_flashed(
'There was an error with the autogenerated password. User not '
'created. Please try again.', 'error')
def test_admin_add_user_first_name_too_long_warning(journalist_app, test_admin):
with journalist_app.test_client() as app:
overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1)
_login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret'])
resp = app.post(url_for('admin.add_user'),
data=dict(username=test_admin['username'],
first_name=overly_long_name,
last_name='',
password=VALID_PASSWORD,
is_admin=None))
text = resp.data.decode('utf-8')
assert 'Cannot be longer than' in text
def test_admin_add_user_last_name_too_long_warning(journalist_app, test_admin):
with journalist_app.test_client() as app:
overly_long_name = 'a' * (Journalist.MAX_NAME_LEN + 1)
_login_user(app, test_admin['username'], test_admin['password'], test_admin['otp_secret'])
resp = app.post(url_for('admin.add_user'),
data=dict(username=test_admin['username'],
first_name='',
last_name=overly_long_name,
password=VALID_PASSWORD,
is_admin=None))
text = resp.data.decode('utf-8')
assert 'Cannot be longer than' in text
def test_admin_edits_user_invalid_username(
journalist_app, test_admin, test_journo):
"""Test expected error message when admin attempts to change a user's
username to a username that is taken by another user."""
new_username = test_journo['username']
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
with InstrumentedApp(journalist_app) as ins:
app.post(
url_for('admin.edit_user', user_id=test_admin['id']),
data=dict(username=new_username,
first_name='',
last_name='',
is_admin=None))
ins.assert_message_flashed(
'Username "{}" already taken.'.format(new_username),
'error')
def test_admin_edits_user_invalid_username_deleted(
journalist_app, test_admin, test_journo):
"""Test expected error message when admin attempts to change a user's
username to deleted"""
new_username = "deleted"
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
with InstrumentedApp(journalist_app) as ins:
app.post(
url_for('admin.edit_user', user_id=test_admin['id']),
data=dict(username=new_username,
first_name='',
last_name='',
is_admin=None))
ins.assert_message_flashed(
'Invalid username: This username is invalid because it '
'is reserved for internal use by the software.',
'error')
def test_admin_resets_user_hotp_format_non_hexa(
journalist_app, test_admin, test_journo):
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
journo = test_journo['journalist']
# guard to ensure check below tests the correct condition
assert journo.is_totp
old_secret = journo.otp_secret
with InstrumentedApp(journalist_app) as ins:
app.post(url_for('admin.reset_two_factor_hotp'),
data=dict(uid=test_journo['id'], otp_secret='ZZ'))
# fetch altered DB object
journo = Journalist.query.get(journo.id)
new_secret = journo.otp_secret
assert old_secret == new_secret
# ensure we didn't accidentally enable hotp
assert journo.is_totp
ins.assert_message_flashed(
"Invalid secret format: please only submit letters A-F and "
"numbers 0-9.", "error")
def test_admin_resets_user_hotp(journalist_app, test_admin, test_journo):
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
journo = test_journo['journalist']
old_secret = journo.otp_secret
with InstrumentedApp(journalist_app) as ins:
resp = app.post(url_for('admin.reset_two_factor_hotp'),
data=dict(uid=test_journo['id'],
otp_secret=123456))
# fetch altered DB object
journo = Journalist.query.get(journo.id)
new_secret = journo.otp_secret
assert old_secret != new_secret
assert not journo.is_totp
# Redirect to admin 2FA view
ins.assert_redirects(resp, url_for('admin.new_user_two_factor',
uid=journo.id))
def test_admin_resets_user_hotp_format_odd(journalist_app,
test_admin,
test_journo):
old_secret = test_journo['otp_secret']
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
with InstrumentedApp(journalist_app) as ins:
app.post(url_for('admin.reset_two_factor_hotp'),
data=dict(uid=test_journo['id'], otp_secret='Z'))
ins.assert_message_flashed(
"Invalid secret format: "
"odd-length secret. Did you mistype the secret?", "error")
# Re-fetch journalist to get fresh DB instance
user = Journalist.query.get(test_journo['id'])
new_secret = user.otp_secret
assert old_secret == new_secret
def test_admin_resets_user_hotp_error(mocker,
journalist_app,
test_admin,
test_journo):
bad_secret = '1234'
error_message = 'SOMETHING WRONG!'
mocked_error_logger = mocker.patch('journalist.app.logger.error')
old_secret = test_journo['otp_secret']
with journalist_app.test_client() as app:
_login_user(app, test_admin['username'], test_admin['password'],
test_admin['otp_secret'])
mocker.patch('models.Journalist.set_hotp_secret',
side_effect=binascii.Error(error_message))
with InstrumentedApp(journalist_app) as ins:
app.post(url_for('admin.reset_two_factor_hotp'),
data=dict(uid=test_journo['id'], otp_secret=bad_secret))
ins.assert_message_flashed("An unexpected error occurred! "
"Please inform your admin.",
"error")
# Re-fetch journalist to get fresh DB instance
user = Journalist.query.get(test_journo['id'])
new_secret = user.otp_secret
assert new_secret == old_secret
mocked_error_logger.assert_called_once_with(
"set_hotp_secret '{}' (id {}) failed: {}".format(
bad_secret, test_journo['id'], error_message))
def test_user_resets_hotp(journalist_app, test_journo):
old_secret = test_journo['otp_secret']
new_secret = 123456
# Precondition
assert new_secret != old_secret
with journalist_app.test_client() as app:
_login_user(app, test_journo['username'], test_journo['password'],
test_journo['otp_secret'])
with InstrumentedApp(journalist_app) as ins:
resp = app.post(url_for('account.reset_two_factor_hotp'),
data=dict(otp_secret=new_secret))
# should redirect to verification page
ins.assert_redirects(resp, url_for('account.new_two_factor'))