-
-
Notifications
You must be signed in to change notification settings - Fork 8k
/
test_decorators.py
1715 lines (1439 loc) · 68.9 KB
/
test_decorators.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
import base64
import os
import re
import uuid
from collections import defaultdict
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Union
from unittest import mock, skipUnless
import orjson
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.http import HttpRequest, HttpResponse
from django.utils.timezone import now as timezone_now
from zerver.actions.create_realm import do_create_realm
from zerver.actions.create_user import do_reactivate_user
from zerver.actions.realm_settings import do_deactivate_realm, do_reactivate_realm
from zerver.actions.user_settings import do_change_user_setting
from zerver.actions.users import change_user_is_active, do_deactivate_user
from zerver.decorator import (
authenticate_notify,
authenticated_json_view,
authenticated_rest_api_view,
authenticated_uploads_api_view,
internal_notify_view,
process_client,
public_json_view,
return_success_on_head_request,
validate_api_key,
web_public_view,
webhook_view,
zulip_login_required,
zulip_otp_required_if_logged_in,
)
from zerver.forms import OurAuthenticationForm
from zerver.lib.cache import dict_to_items_tuple, ignore_unhashable_lru_cache, items_tuple_to_dict
from zerver.lib.exceptions import (
AccessDeniedError,
InvalidAPIKeyError,
InvalidAPIKeyFormatError,
JsonableError,
UnsupportedWebhookEventTypeError,
)
from zerver.lib.initial_password import initial_password
from zerver.lib.rate_limiter import is_local_addr
from zerver.lib.request import RequestNotes, RequestVariableMissingError
from zerver.lib.response import json_response, json_success
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import HostRequestMock, dummy_handler, queries_captured
from zerver.lib.user_agent import parse_user_agent
from zerver.lib.users import get_api_key
from zerver.lib.utils import generate_api_key, has_api_key_format
from zerver.middleware import LogRequests, parse_client
from zerver.models import Client, Realm, UserProfile, clear_client_cache, get_realm, get_user
if settings.ZILENCER_ENABLED:
from zilencer.models import RemoteZulipServer
if TYPE_CHECKING:
from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse
class DecoratorTestCase(ZulipTestCase):
def test_parse_client(self) -> None:
req = HostRequestMock()
self.assertEqual(parse_client(req), ("Unspecified", None))
req = HostRequestMock()
req.META[
"HTTP_USER_AGENT"
] = "ZulipElectron/4.0.3 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Zulip/4.0.3 Chrome/66.0.3359.181 Electron/3.1.10 Safari/537.36"
self.assertEqual(parse_client(req), ("ZulipElectron", "4.0.3"))
req = HostRequestMock()
req.META["HTTP_USER_AGENT"] = "ZulipDesktop/0.4.4 (Mac)"
self.assertEqual(parse_client(req), ("ZulipDesktop", "0.4.4"))
req = HostRequestMock()
req.META["HTTP_USER_AGENT"] = "ZulipMobile/26.22.145 (Android 10)"
self.assertEqual(parse_client(req), ("ZulipMobile", "26.22.145"))
req = HostRequestMock()
req.META["HTTP_USER_AGENT"] = "ZulipMobile/26.22.145 (iOS 13.3.1)"
self.assertEqual(parse_client(req), ("ZulipMobile", "26.22.145"))
# TODO: This should ideally be Firefox.
req = HostRequestMock()
req.META[
"HTTP_USER_AGENT"
] = "Mozilla/5.0 (X11; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0"
self.assertEqual(parse_client(req), ("Mozilla", None))
# TODO: This should ideally be Chrome.
req = HostRequestMock()
req.META[
"HTTP_USER_AGENT"
] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.43 Safari/537.36"
self.assertEqual(parse_client(req), ("Mozilla", None))
# TODO: This should ideally be Mobile Safari if we had better user-agent parsing.
req = HostRequestMock()
req.META[
"HTTP_USER_AGENT"
] = "Mozilla/5.0 (Linux; Android 8.0.0; SM-G930F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Mobile Safari/537.36"
self.assertEqual(parse_client(req), ("Mozilla", None))
post_req_with_client = HostRequestMock()
post_req_with_client.POST["client"] = "test_client_1"
post_req_with_client.META["HTTP_USER_AGENT"] = "ZulipMobile/26.22.145 (iOS 13.3.1)"
self.assertEqual(parse_client(post_req_with_client), ("test_client_1", None))
get_req_with_client = HostRequestMock()
get_req_with_client.GET["client"] = "test_client_2"
get_req_with_client.META["HTTP_USER_AGENT"] = "ZulipMobile/26.22.145 (iOS 13.3.1)"
self.assertEqual(parse_client(get_req_with_client), ("test_client_2", None))
def test_unparsable_user_agent(self) -> None:
request = HttpRequest()
request.POST["param"] = "test"
request.META["HTTP_USER_AGENT"] = "mocked should fail"
with mock.patch(
"zerver.middleware.parse_client", side_effect=JsonableError("message")
) as m, self.assertLogs(level="ERROR"):
LogRequests(lambda request: HttpResponse()).process_request(request)
request_notes = RequestNotes.get_notes(request)
self.assertEqual(request_notes.client_name, "Unparsable")
m.assert_called_once()
def logger_output(self, output_string: str, type: str, logger: str) -> str:
return f"{type.upper()}:zulip.zerver.{logger}:{output_string}"
def test_webhook_view(self) -> None:
@webhook_view("ClientName")
def my_webhook(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
return json_response(msg=user_profile.email)
@webhook_view("ClientName")
def my_webhook_raises_exception(
request: HttpRequest, user_profile: UserProfile
) -> HttpResponse:
raise Exception("raised by webhook function")
@webhook_view("ClientName")
def my_webhook_raises_exception_unsupported_event(
request: HttpRequest, user_profile: UserProfile
) -> HttpResponse:
raise UnsupportedWebhookEventTypeError("test_event")
webhook_bot_email = "[email protected]"
webhook_bot_realm = get_realm("zulip")
webhook_bot = get_user(webhook_bot_email, webhook_bot_realm)
webhook_bot_api_key = get_api_key(webhook_bot)
request = HostRequestMock()
request.POST["api_key"] = "X" * 32
with self.assertRaisesRegex(JsonableError, "Invalid API key"):
my_webhook(request)
# Start a valid request here
request = HostRequestMock()
request.POST["api_key"] = webhook_bot_api_key
with self.assertLogs(level="WARNING") as m:
with self.assertRaisesRegex(
JsonableError, "Account is not associated with this subdomain"
):
api_result = my_webhook(request)
self.assertEqual(
m.output,
[
"WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(
webhook_bot_email, "zulip", ""
)
],
)
request = HostRequestMock()
request.POST["api_key"] = webhook_bot_api_key
with self.assertLogs(level="WARNING") as m:
with self.assertRaisesRegex(
JsonableError, "Account is not associated with this subdomain"
):
request.host = "acme." + settings.EXTERNAL_HOST
api_result = my_webhook(request)
self.assertEqual(
m.output,
[
"WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(
webhook_bot_email, "zulip", "acme"
)
],
)
# Test when content_type is application/json and request.body
# is valid JSON; exception raised in the webhook function
# should be re-raised
request = HostRequestMock()
request.host = "zulip.testserver"
request.POST["api_key"] = webhook_bot_api_key
with self.assertLogs("zulip.zerver.webhooks", level="INFO") as log:
with self.assertRaisesRegex(Exception, "raised by webhook function"):
request.body = b"{}"
request.content_type = "application/json"
my_webhook_raises_exception(request)
# Test when content_type is not application/json; exception raised
# in the webhook function should be re-raised
request = HostRequestMock()
request.host = "zulip.testserver"
request.POST["api_key"] = webhook_bot_api_key
with self.assertLogs("zulip.zerver.webhooks", level="INFO") as log:
with self.assertRaisesRegex(Exception, "raised by webhook function"):
request.body = b"notjson"
request.content_type = "text/plain"
my_webhook_raises_exception(request)
# Test when content_type is application/json but request.body
# is not valid JSON; invalid JSON should be logged and the
# exception raised in the webhook function should be re-raised
request = HostRequestMock()
request.host = "zulip.testserver"
request.POST["api_key"] = webhook_bot_api_key
with self.assertLogs("zulip.zerver.webhooks", level="ERROR") as log:
with self.assertRaisesRegex(Exception, "raised by webhook function"):
request.body = b"invalidjson"
request.content_type = "application/json"
request.META["HTTP_X_CUSTOM_HEADER"] = "custom_value"
my_webhook_raises_exception(request)
self.assertIn(
self.logger_output("raised by webhook function\n", "error", "webhooks"), log.output[0]
)
# Test when an unsupported webhook event occurs
request = HostRequestMock()
request.host = "zulip.testserver"
request.POST["api_key"] = webhook_bot_api_key
exception_msg = (
"The 'test_event' event isn't currently supported by the ClientName webhook; ignoring"
)
with self.assertLogs("zulip.zerver.webhooks.unsupported", level="ERROR") as log:
with self.assertRaisesRegex(UnsupportedWebhookEventTypeError, exception_msg):
request.body = b"invalidjson"
request.content_type = "application/json"
request.META["HTTP_X_CUSTOM_HEADER"] = "custom_value"
my_webhook_raises_exception_unsupported_event(request)
self.assertIn(
self.logger_output(exception_msg, "error", "webhooks.unsupported"), log.output[0]
)
request = HostRequestMock()
request.host = "zulip.testserver"
request.POST["api_key"] = webhook_bot_api_key
with self.settings(RATE_LIMITING=True):
with mock.patch("zerver.decorator.rate_limit_user") as rate_limit_mock:
api_result = orjson.loads(my_webhook(request).content).get("msg")
# Verify rate limiting was attempted.
self.assertTrue(rate_limit_mock.called)
# Verify the main purpose of the decorator, which is that it passed in the
# user_profile to my_webhook, allowing it return the correct
# email for the bot (despite the API caller only knowing the API key).
self.assertEqual(api_result, webhook_bot_email)
# Now deactivate the user
change_user_is_active(webhook_bot, False)
request = HostRequestMock()
request.host = "zulip.testserver"
request.POST["api_key"] = webhook_bot_api_key
with self.assertRaisesRegex(JsonableError, "Account is deactivated"):
my_webhook(request)
# Reactive the user, but deactivate their realm.
change_user_is_active(webhook_bot, True)
webhook_bot.realm.deactivated = True
webhook_bot.realm.save()
request = HostRequestMock()
request.host = "zulip.testserver"
request.POST["api_key"] = webhook_bot_api_key
with self.assertRaisesRegex(JsonableError, "This organization has been deactivated"):
my_webhook(request)
class SkipRateLimitingTest(ZulipTestCase):
def test_authenticated_rest_api_view(self) -> None:
@authenticated_rest_api_view(skip_rate_limiting=False)
def my_rate_limited_view(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
return json_success(request) # nocoverage # mock prevents this from being called
@authenticated_rest_api_view(skip_rate_limiting=True)
def my_unlimited_view(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
return json_success(request)
request = HostRequestMock(host="zulip.testserver")
request.META["HTTP_AUTHORIZATION"] = self.encode_email(self.example_email("hamlet"))
request.method = "POST"
with mock.patch("zerver.decorator.rate_limit_user") as rate_limit_mock:
result = my_unlimited_view(request)
self.assert_json_success(result)
self.assertFalse(rate_limit_mock.called)
request = HostRequestMock(host="zulip.testserver")
request.META["HTTP_AUTHORIZATION"] = self.encode_email(self.example_email("hamlet"))
request.method = "POST"
with mock.patch("zerver.decorator.rate_limit_user") as rate_limit_mock:
result = my_rate_limited_view(request)
# Don't assert json_success, since it'll be the rate_limit mock object
self.assertTrue(rate_limit_mock.called)
def test_authenticated_uploads_api_view(self) -> None:
@authenticated_uploads_api_view(skip_rate_limiting=False)
def my_rate_limited_view(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
return json_success(request) # nocoverage # mock prevents this from being called
@authenticated_uploads_api_view(skip_rate_limiting=True)
def my_unlimited_view(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
return json_success(request)
request = HostRequestMock(host="zulip.testserver")
request.method = "POST"
request.POST["api_key"] = get_api_key(self.example_user("hamlet"))
with mock.patch("zerver.decorator.rate_limit_user") as rate_limit_mock:
result = my_unlimited_view(request)
self.assert_json_success(result)
self.assertFalse(rate_limit_mock.called)
request = HostRequestMock(host="zulip.testserver")
request.method = "POST"
request.POST["api_key"] = get_api_key(self.example_user("hamlet"))
with mock.patch("zerver.decorator.rate_limit_user") as rate_limit_mock:
result = my_rate_limited_view(request)
# Don't assert json_success, since it'll be the rate_limit mock object
self.assertTrue(rate_limit_mock.called)
def test_authenticated_json_view(self) -> None:
def my_view(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
return json_success(request)
my_rate_limited_view = authenticated_json_view(my_view, skip_rate_limiting=False)
my_unlimited_view = authenticated_json_view(my_view, skip_rate_limiting=True)
request = HostRequestMock(host="zulip.testserver")
request.method = "POST"
request.user = self.example_user("hamlet")
with mock.patch("zerver.decorator.rate_limit_user") as rate_limit_mock:
result = my_unlimited_view(request)
self.assert_json_success(result)
self.assertFalse(rate_limit_mock.called)
request = HostRequestMock(host="zulip.testserver")
request.method = "POST"
request.user = self.example_user("hamlet")
with mock.patch("zerver.decorator.rate_limit_user") as rate_limit_mock:
result = my_rate_limited_view(request)
# Don't assert json_success, since it'll be the rate_limit mock object
self.assertTrue(rate_limit_mock.called)
class DecoratorLoggingTestCase(ZulipTestCase):
def test_authenticated_rest_api_view_logging(self) -> None:
@authenticated_rest_api_view(webhook_client_name="ClientName")
def my_webhook_raises_exception(
request: HttpRequest, user_profile: UserProfile
) -> HttpResponse:
raise Exception("raised by webhook function")
webhook_bot_email = "[email protected]"
request = HostRequestMock()
request.META["HTTP_AUTHORIZATION"] = self.encode_email(webhook_bot_email)
request.method = "POST"
request.host = "zulip.testserver"
request.body = b"{}"
request.content_type = "text/plain"
with self.assertLogs("zulip.zerver.webhooks") as logger:
with self.assertRaisesRegex(Exception, "raised by webhook function"):
my_webhook_raises_exception(request)
self.assertIn("raised by webhook function", logger.output[0])
def test_authenticated_rest_api_view_logging_unsupported_event(self) -> None:
@authenticated_rest_api_view(webhook_client_name="ClientName")
def my_webhook_raises_exception(
request: HttpRequest, user_profile: UserProfile
) -> HttpResponse:
raise UnsupportedWebhookEventTypeError("test_event")
webhook_bot_email = "[email protected]"
request = HostRequestMock()
request.META["HTTP_AUTHORIZATION"] = self.encode_email(webhook_bot_email)
request.method = "POST"
request.host = "zulip.testserver"
request.body = b"{}"
request.content_type = "text/plain"
with mock.patch(
"zerver.decorator.webhook_unsupported_events_logger.exception"
) as mock_exception:
exception_msg = "The 'test_event' event isn't currently supported by the ClientName webhook; ignoring"
with self.assertRaisesRegex(UnsupportedWebhookEventTypeError, exception_msg):
my_webhook_raises_exception(request)
mock_exception.assert_called_with(
exception_msg, stack_info=True, extra={"request": request}
)
def test_authenticated_rest_api_view_with_non_webhook_view(self) -> None:
@authenticated_rest_api_view()
def non_webhook_view_raises_exception(
request: HttpRequest, user_profile: UserProfile
) -> HttpResponse:
raise Exception("raised by a non-webhook view")
request = HostRequestMock()
request.META["HTTP_AUTHORIZATION"] = self.encode_email("[email protected]")
request.method = "POST"
request.host = "zulip.testserver"
request.body = b"{}"
request.content_type = "application/json"
with mock.patch("zerver.decorator.webhook_logger.exception") as mock_exception:
with self.assertRaisesRegex(Exception, "raised by a non-webhook view"):
non_webhook_view_raises_exception(request)
self.assertFalse(mock_exception.called)
def test_authenticated_rest_api_view_errors(self) -> None:
user_profile = self.example_user("hamlet")
api_key = get_api_key(user_profile)
credentials = f"{user_profile.email}:{api_key}"
api_auth = "Digest " + base64.b64encode(credentials.encode()).decode()
result = self.client_post("/api/v1/external/zendesk", {}, HTTP_AUTHORIZATION=api_auth)
self.assert_json_error(result, "This endpoint requires HTTP basic authentication.")
api_auth = "Basic " + base64.b64encode(b"foo").decode()
result = self.client_post("/api/v1/external/zendesk", {}, HTTP_AUTHORIZATION=api_auth)
self.assert_json_error(
result, "Invalid authorization header for basic auth", status_code=401
)
result = self.client_post("/api/v1/external/zendesk", {})
self.assert_json_error(
result, "Missing authorization header for basic auth", status_code=401
)
class RateLimitTestCase(ZulipTestCase):
@staticmethod
@public_json_view
def ratelimited_json_view(
req: HttpRequest, maybe_user_profile: Union[AnonymousUser, UserProfile], /
) -> HttpResponse:
return HttpResponse("some value")
@staticmethod
@web_public_view
def ratelimited_web_view(req: HttpRequest) -> HttpResponse:
return HttpResponse("some value")
def check_rate_limit_public_or_user_views(
self,
remote_addr: str,
client_name: str,
expect_rate_limit: bool,
check_web_view: bool = False,
) -> None:
META = {"REMOTE_ADDR": remote_addr, "PATH_INFO": "test"}
request = HostRequestMock(host="zulip.testserver", client_name=client_name, meta_data=META)
view_func = self.ratelimited_web_view if check_web_view else self.ratelimited_json_view
with mock.patch(
"zerver.lib.rate_limiter.RateLimitedUser"
) as rate_limit_user_mock, mock.patch(
"zerver.lib.rate_limiter.RateLimitedIPAddr"
) as rate_limit_ip_mock:
self.assert_in_success_response(["some value"], view_func(request))
self.assertEqual(rate_limit_ip_mock.called, expect_rate_limit)
self.assertFalse(rate_limit_user_mock.called)
# We need to recreate the request, because process_client mutates client on
# the associated RequestNotes, causing the request to be incorrectly rate limited, since
# should_rate_limit checks the client to determine if rate limiting should be skipped.
user = self.example_user("hamlet")
request = HostRequestMock(
user_profile=user, host="zulip.testserver", client_name=client_name, meta_data=META
)
with mock.patch(
"zerver.lib.rate_limiter.RateLimitedUser"
) as rate_limit_user_mock, mock.patch(
"zerver.lib.rate_limiter.RateLimitedIPAddr"
) as rate_limit_ip_mock:
self.assert_in_success_response(["some value"], view_func(request))
self.assertEqual(rate_limit_user_mock.called, expect_rate_limit)
self.assertFalse(rate_limit_ip_mock.called)
def test_internal_local_clients_skip_rate_limiting(self) -> None:
with self.settings(RATE_LIMITING=True):
self.check_rate_limit_public_or_user_views(
remote_addr="127.0.0.1", client_name="internal", expect_rate_limit=False
)
def test_debug_clients_skip_rate_limiting(self) -> None:
with self.settings(DEBUG_RATE_LIMITING=True, RATE_LIMITING=True):
# Rate limiting is skipped for internal clients with an external address
# when DEBUG_RATE_LIMITING is True.
self.check_rate_limit_public_or_user_views(
remote_addr="3.3.3.3", client_name="internal", expect_rate_limit=False
)
def test_rate_limit_setting_of_false_bypasses_rate_limiting(self) -> None:
with self.settings(RATE_LIMITING=False):
self.check_rate_limit_public_or_user_views(
remote_addr="3.3.3.3", client_name="external", expect_rate_limit=False
)
def test_rate_limiting_happens_in_normal_case(self) -> None:
with self.settings(RATE_LIMITING=True):
self.check_rate_limit_public_or_user_views(
remote_addr="3.3.3.3", client_name="external", expect_rate_limit=True
)
def test_rate_limiting_web_public_views(self) -> None:
with self.settings(RATE_LIMITING=True):
self.check_rate_limit_public_or_user_views(
remote_addr="3.3.3.3",
client_name="external",
expect_rate_limit=True,
check_web_view=True,
)
@skipUnless(settings.ZILENCER_ENABLED, "requires zilencer")
def test_rate_limiting_happens_if_remote_server(self) -> None:
user = self.example_user("hamlet")
server_uuid = str(uuid.uuid4())
server = RemoteZulipServer(
uuid=server_uuid,
api_key="magic_secret_api_key",
hostname="demo.example.com",
last_updated=timezone_now(),
)
server.save()
with self.settings(RATE_LIMITING=True), mock.patch(
"zilencer.auth.rate_limit_remote_server"
) as rate_limit_mock:
result = self.uuid_post(
server_uuid,
"/api/v1/remotes/push/unregister/all",
{"user_id": user.id},
subdomain="",
)
self.assert_json_success(result)
self.assertTrue(rate_limit_mock.called)
class DeactivatedRealmTest(ZulipTestCase):
def test_send_deactivated_realm(self) -> None:
"""
rest_dispatch rejects requests in a deactivated realm, both /json and api
"""
realm = get_realm("zulip")
do_deactivate_realm(get_realm("zulip"), acting_user=None)
result = self.client_post(
"/json/messages",
{
"type": "private",
"content": "Test message",
"to": self.example_email("othello"),
},
)
self.assert_json_error_contains(result, "Not logged in", status_code=401)
# Even if a logged-in session was leaked, it still wouldn't work
realm.deactivated = False
realm.save()
self.login("hamlet")
realm.deactivated = True
realm.save()
result = self.client_post(
"/json/messages",
{
"type": "private",
"content": "Test message",
"to": self.example_email("othello"),
},
)
self.assert_json_error_contains(
result, "This organization has been deactivated", status_code=401
)
result = self.api_post(
self.example_user("hamlet"),
"/api/v1/messages",
{
"type": "private",
"content": "Test message",
"to": self.example_email("othello"),
},
)
self.assert_json_error_contains(
result, "This organization has been deactivated", status_code=401
)
def test_fetch_api_key_deactivated_realm(self) -> None:
"""
authenticated_json_view views fail in a deactivated realm
"""
realm = get_realm("zulip")
user_profile = self.example_user("hamlet")
test_password = "abcd1234"
user_profile.set_password(test_password)
self.login_user(user_profile)
realm.deactivated = True
realm.save()
result = self.client_post("/json/fetch_api_key", {"password": test_password})
self.assert_json_error_contains(
result, "This organization has been deactivated", status_code=401
)
def test_webhook_deactivated_realm(self) -> None:
"""
Using a webhook while in a deactivated realm fails
"""
do_deactivate_realm(get_realm("zulip"), acting_user=None)
user_profile = self.example_user("hamlet")
api_key = get_api_key(user_profile)
url = f"/api/v1/external/jira?api_key={api_key}&stream=jira_custom"
data = self.webhook_fixture_data("jira", "created_v2")
result = self.client_post(url, data, content_type="application/json")
self.assert_json_error_contains(
result, "This organization has been deactivated", status_code=401
)
class LoginRequiredTest(ZulipTestCase):
def test_login_required(self) -> None:
"""
Verifies the zulip_login_required decorator blocks deactivated users.
"""
user_profile = self.example_user("hamlet")
# Verify fails if logged-out
result = self.client_get("/accounts/accept_terms/")
self.assertEqual(result.status_code, 302)
# Verify succeeds once logged-in
self.login_user(user_profile)
result = self.client_get("/accounts/accept_terms/")
self.assert_in_response("I agree to the", result)
# Verify fails if user deactivated (with session still valid)
change_user_is_active(user_profile, False)
result = self.client_get("/accounts/accept_terms/")
self.assertEqual(result.status_code, 302)
# Verify succeeds if user reactivated
do_reactivate_user(user_profile, acting_user=None)
self.login_user(user_profile)
result = self.client_get("/accounts/accept_terms/")
self.assert_in_response("I agree to the", result)
# Verify fails if realm deactivated
user_profile.realm.deactivated = True
user_profile.realm.save()
result = self.client_get("/accounts/accept_terms/")
self.assertEqual(result.status_code, 302)
class FetchAPIKeyTest(ZulipTestCase):
def test_fetch_api_key_success(self) -> None:
user = self.example_user("cordelia")
self.login_user(user)
result = self.client_post(
"/json/fetch_api_key", dict(password=initial_password(user.delivery_email))
)
self.assert_json_success(result)
def test_fetch_api_key_email_address_visibility(self) -> None:
user = self.example_user("cordelia")
do_change_user_setting(
user,
"email_address_visibility",
UserProfile.EMAIL_ADDRESS_VISIBILITY_ADMINS,
acting_user=None,
)
self.login_user(user)
result = self.client_post(
"/json/fetch_api_key", dict(password=initial_password(user.delivery_email))
)
self.assert_json_success(result)
def test_fetch_api_key_wrong_password(self) -> None:
self.login("cordelia")
result = self.client_post("/json/fetch_api_key", dict(password="wrong_password"))
self.assert_json_error_contains(result, "Password is incorrect")
class InactiveUserTest(ZulipTestCase):
def test_send_deactivated_user(self) -> None:
"""
rest_dispatch rejects requests from deactivated users, both /json and api
"""
user_profile = self.example_user("hamlet")
self.login_user(user_profile)
with self.captureOnCommitCallbacks(execute=True):
do_deactivate_user(user_profile, acting_user=None)
result = self.client_post(
"/json/messages",
{
"type": "private",
"content": "Test message",
"to": self.example_email("othello"),
},
)
self.assert_json_error_contains(result, "Not logged in", status_code=401)
# Even if a logged-in session was leaked, it still wouldn't work
do_reactivate_user(user_profile, acting_user=None)
self.login_user(user_profile)
change_user_is_active(user_profile, False)
result = self.client_post(
"/json/messages",
{
"type": "private",
"content": "Test message",
"to": self.example_email("othello"),
},
)
self.assert_json_error_contains(result, "Account is deactivated", status_code=401)
result = self.api_post(
self.example_user("hamlet"),
"/api/v1/messages",
{
"type": "private",
"content": "Test message",
"to": self.example_email("othello"),
},
)
self.assert_json_error_contains(result, "Account is deactivated", status_code=401)
def test_fetch_api_key_deactivated_user(self) -> None:
"""
authenticated_json_view views fail with a deactivated user
"""
user_profile = self.example_user("hamlet")
email = user_profile.delivery_email
test_password = "abcd1234"
user_profile.set_password(test_password)
user_profile.save()
self.login_by_email(email, password=test_password)
change_user_is_active(user_profile, False)
result = self.client_post("/json/fetch_api_key", {"password": test_password})
self.assert_json_error_contains(result, "Account is deactivated", status_code=401)
def test_login_deactivated_user(self) -> None:
"""
logging in fails with an inactive user
"""
user_profile = self.example_user("hamlet")
do_deactivate_user(user_profile, acting_user=None)
result = self.login_with_return(user_profile.delivery_email)
self.assert_in_response(
f"Your account {user_profile.delivery_email} has been deactivated.", result
)
def test_login_deactivated_mirror_dummy(self) -> None:
"""
logging in fails with an inactive user
"""
user_profile = self.example_user("hamlet")
user_profile.is_mirror_dummy = True
user_profile.save()
password = initial_password(user_profile.delivery_email)
request = mock.MagicMock()
request.get_host.return_value = "zulip.testserver"
payload = dict(
username=user_profile.delivery_email,
password=password,
)
# Test a mirror-dummy active user.
form = OurAuthenticationForm(request, payload)
with self.settings(AUTHENTICATION_BACKENDS=("zproject.backends.EmailAuthBackend",)):
self.assertTrue(form.is_valid())
# Test a mirror-dummy deactivated user.
do_deactivate_user(user_profile, acting_user=None)
user_profile.save()
form = OurAuthenticationForm(request, payload)
with self.settings(AUTHENTICATION_BACKENDS=("zproject.backends.EmailAuthBackend",)):
self.assertFalse(form.is_valid())
self.assertIn("Please enter a correct email", str(form.errors))
# Test a non-mirror-dummy deactivated user.
user_profile.is_mirror_dummy = False
user_profile.save()
form = OurAuthenticationForm(request, payload)
with self.settings(AUTHENTICATION_BACKENDS=("zproject.backends.EmailAuthBackend",)):
self.assertFalse(form.is_valid())
self.assertIn(
f"Your account {user_profile.delivery_email} has been deactivated",
str(form.errors),
)
def test_webhook_deactivated_user(self) -> None:
"""
Deactivated users can't use webhooks
"""
user_profile = self.example_user("hamlet")
do_deactivate_user(user_profile, acting_user=None)
api_key = get_api_key(user_profile)
url = f"/api/v1/external/jira?api_key={api_key}&stream=jira_custom"
data = self.webhook_fixture_data("jira", "created_v2")
result = self.client_post(url, data, content_type="application/json")
self.assert_json_error_contains(result, "Account is deactivated", status_code=401)
class TestIncomingWebhookBot(ZulipTestCase):
def test_webhook_bot_permissions(self) -> None:
webhook_bot = self.example_user("webhook_bot")
othello = self.example_user("othello")
payload = dict(
type="private",
content="Test message",
to=orjson.dumps([othello.email]).decode(),
)
result = self.api_post(webhook_bot, "/api/v1/messages", payload)
self.assert_json_success(result)
post_params = {"anchor": 1, "num_before": 1, "num_after": 1}
result = self.api_get(webhook_bot, "/api/v1/messages", dict(post_params))
self.assert_json_error(
result, "This API is not available to incoming webhook bots.", status_code=401
)
class TestValidateApiKey(ZulipTestCase):
def setUp(self) -> None:
super().setUp()
zulip_realm = get_realm("zulip")
self.webhook_bot = get_user("[email protected]", zulip_realm)
self.default_bot = get_user("[email protected]", zulip_realm)
def test_has_api_key_format(self) -> None:
self.assertFalse(has_api_key_format("TooShort"))
# Has an invalid character:
self.assertFalse(has_api_key_format("32LONGXXXXXXXXXXXXXXXXXXXXXXXXX-"))
# Too long:
self.assertFalse(has_api_key_format("33LONGXXXXXXXXXXXXXXXXXXXXXXXXXXX"))
self.assertTrue(has_api_key_format("VIzRVw2CspUOnEm9Yu5vQiQtJNkvETkp"))
for i in range(0, 10):
self.assertTrue(has_api_key_format(generate_api_key()))
def test_validate_api_key_if_profile_does_not_exist(self) -> None:
with self.assertRaises(JsonableError):
validate_api_key(
HostRequestMock(), "[email protected]", "VIzRVw2CspUOnEm9Yu5vQiQtJNkvETkp"
)
def test_validate_api_key_if_api_key_does_not_match_profile_api_key(self) -> None:
with self.assertRaises(InvalidAPIKeyFormatError):
validate_api_key(HostRequestMock(), self.webhook_bot.email, "not_32_length")
with self.assertRaises(InvalidAPIKeyError):
# We use default_bot's key but webhook_bot's email address to test
# the logic when an API key is passed and it doesn't belong to the
# user whose email address has been provided.
api_key = get_api_key(self.default_bot)
validate_api_key(HostRequestMock(), self.webhook_bot.email, api_key)
def test_validate_api_key_if_profile_is_not_active(self) -> None:
change_user_is_active(self.default_bot, False)
with self.assertRaises(JsonableError):
api_key = get_api_key(self.default_bot)
validate_api_key(HostRequestMock(), self.default_bot.email, api_key)
change_user_is_active(self.default_bot, True)
def test_validate_api_key_if_profile_is_incoming_webhook_and_is_webhook_is_unset(self) -> None:
with self.assertRaises(JsonableError), self.assertLogs(level="WARNING") as root_warn_log:
api_key = get_api_key(self.webhook_bot)
validate_api_key(HostRequestMock(), self.webhook_bot.email, api_key)
self.assertEqual(
root_warn_log.output,
[
"WARNING:root:User [email protected] (zulip) attempted to access API on wrong subdomain ()"
],
)
def test_validate_api_key_if_profile_is_incoming_webhook_and_is_webhook_is_set(self) -> None:
api_key = get_api_key(self.webhook_bot)
profile = validate_api_key(
HostRequestMock(host="zulip.testserver"),
self.webhook_bot.email,
api_key,
allow_webhook_access=True,
)
self.assertEqual(profile.id, self.webhook_bot.id)
def test_validate_api_key_if_email_is_case_insensitive(self) -> None:
api_key = get_api_key(self.default_bot)
profile = validate_api_key(
HostRequestMock(host="zulip.testserver"), self.default_bot.email.upper(), api_key
)
self.assertEqual(profile.id, self.default_bot.id)
def test_valid_api_key_if_user_is_on_wrong_subdomain(self) -> None:
with self.settings(RUNNING_INSIDE_TORNADO=False):
api_key = get_api_key(self.default_bot)
with self.assertLogs(level="WARNING") as m:
with self.assertRaisesRegex(
JsonableError, "Account is not associated with this subdomain"
):
validate_api_key(
HostRequestMock(host=settings.EXTERNAL_HOST),
self.default_bot.email,
api_key,
)
self.assertEqual(
m.output,
[
"WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(
self.default_bot.email, "zulip", ""
)
],
)
with self.assertLogs(level="WARNING") as m:
with self.assertRaisesRegex(
JsonableError, "Account is not associated with this subdomain"
):
validate_api_key(
HostRequestMock(host="acme." + settings.EXTERNAL_HOST),
self.default_bot.email,
api_key,
)
self.assertEqual(
m.output,
[
"WARNING:root:User {} ({}) attempted to access API on wrong subdomain ({})".format(
self.default_bot.email, "zulip", "acme"
)
],
)
class TestInternalNotifyView(ZulipTestCase):
BORING_RESULT = "boring"
def internal_notify(self, is_tornado: bool, req: HttpRequest) -> HttpResponse:
boring_view = lambda req: json_response(msg=self.BORING_RESULT)
return internal_notify_view(is_tornado)(boring_view)(req)
def test_valid_internal_requests(self) -> None:
secret = "random"
request = HostRequestMock(
post_data=dict(secret=secret),
meta_data=dict(REMOTE_ADDR="127.0.0.1"),
)