forked from getredash/redash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_authentication.py
426 lines (348 loc) · 15.7 KB
/
test_authentication.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
import importlib
import os
import time
from flask import request
from mock import patch
from redash import models, settings
from redash.authentication import (
api_key_load_user_from_request,
get_login_url,
hmac_load_user_from_request,
sign,
)
from redash.authentication.google_oauth import create_and_login_user, verify_profile
from redash.utils import utcnow
from sqlalchemy.orm.exc import NoResultFound
from tests import BaseTestCase
class TestApiKeyAuthentication(BaseTestCase):
#
# This is a bad way to write these tests, but the way Flask works doesn't make it easy to write them properly...
#
def setUp(self):
super(TestApiKeyAuthentication, self).setUp()
self.api_key = "10"
self.query = self.factory.create_query(api_key=self.api_key)
models.db.session.flush()
self.query_url = "/{}/api/queries/{}".format(
self.factory.org.slug, self.query.id
)
self.queries_url = "/{}/api/queries".format(self.factory.org.slug)
def test_no_api_key(self):
with self.app.test_client() as c:
rv = c.get(self.query_url)
self.assertIsNone(api_key_load_user_from_request(request))
def test_wrong_api_key(self):
with self.app.test_client() as c:
rv = c.get(self.query_url, query_string={"api_key": "whatever"})
self.assertIsNone(api_key_load_user_from_request(request))
def test_correct_api_key(self):
with self.app.test_client() as c:
rv = c.get(self.query_url, query_string={"api_key": self.api_key})
self.assertIsNotNone(api_key_load_user_from_request(request))
def test_no_query_id(self):
with self.app.test_client() as c:
rv = c.get(self.queries_url, query_string={"api_key": self.api_key})
self.assertIsNone(api_key_load_user_from_request(request))
def test_user_api_key(self):
user = self.factory.create_user(api_key="user_key")
models.db.session.flush()
with self.app.test_client() as c:
rv = c.get(self.queries_url, query_string={"api_key": user.api_key})
self.assertEqual(user.id, api_key_load_user_from_request(request).id)
def test_disabled_user_api_key(self):
user = self.factory.create_user(api_key="user_key")
user.disable()
models.db.session.flush()
with self.app.test_client() as c:
rv = c.get(self.queries_url, query_string={"api_key": user.api_key})
self.assertEqual(None, api_key_load_user_from_request(request))
def test_api_key_header(self):
with self.app.test_client() as c:
rv = c.get(
self.query_url, headers={"Authorization": "Key {}".format(self.api_key)}
)
self.assertIsNotNone(api_key_load_user_from_request(request))
def test_api_key_header_with_wrong_key(self):
with self.app.test_client() as c:
rv = c.get(self.query_url, headers={"Authorization": "Key oops"})
self.assertIsNone(api_key_load_user_from_request(request))
def test_api_key_for_wrong_org(self):
other_user = self.factory.create_admin(org=self.factory.create_org())
with self.app.test_client() as c:
rv = c.get(
self.query_url,
headers={"Authorization": "Key {}".format(other_user.api_key)},
)
self.assertEqual(404, rv.status_code)
class TestHMACAuthentication(BaseTestCase):
#
# This is a bad way to write these tests, but the way Flask works doesn't make it easy to write them properly...
#
def setUp(self):
super(TestHMACAuthentication, self).setUp()
self.api_key = "10"
self.query = self.factory.create_query(api_key=self.api_key)
models.db.session.flush()
self.path = "/{}/api/queries/{}".format(self.query.org.slug, self.query.id)
self.expires = time.time() + 1800
def signature(self, expires):
return sign(self.query.api_key, self.path, expires)
def test_no_signature(self):
with self.app.test_client() as c:
rv = c.get(self.path)
self.assertIsNone(hmac_load_user_from_request(request))
def test_wrong_signature(self):
with self.app.test_client() as c:
rv = c.get(
self.path,
query_string={"signature": "whatever", "expires": self.expires},
)
self.assertIsNone(hmac_load_user_from_request(request))
def test_correct_signature(self):
with self.app.test_client() as c:
rv = c.get(
self.path,
query_string={
"signature": self.signature(self.expires),
"expires": self.expires,
},
)
self.assertIsNotNone(hmac_load_user_from_request(request))
def test_no_query_id(self):
with self.app.test_client() as c:
rv = c.get(
"/{}/api/queries".format(self.query.org.slug),
query_string={"api_key": self.api_key},
)
self.assertIsNone(hmac_load_user_from_request(request))
def test_user_api_key(self):
user = self.factory.create_user(api_key="user_key")
path = "/api/queries/"
models.db.session.flush()
signature = sign(user.api_key, path, self.expires)
with self.app.test_client() as c:
rv = c.get(
path,
query_string={
"signature": signature,
"expires": self.expires,
"user_id": user.id,
},
)
self.assertEqual(user.id, hmac_load_user_from_request(request).id)
class TestSessionAuthentication(BaseTestCase):
def test_prefers_api_key_over_session_user_id(self):
user = self.factory.create_user()
query = self.factory.create_query(user=user)
other_org = self.factory.create_org()
other_user = self.factory.create_user(org=other_org)
models.db.session.flush()
rv = self.make_request(
"get",
"/api/queries/{}?api_key={}".format(query.id, query.api_key),
user=other_user,
)
self.assertEqual(rv.status_code, 200)
class TestCreateAndLoginUser(BaseTestCase):
def test_logins_valid_user(self):
user = self.factory.create_user(email="[email protected]")
with patch("redash.authentication.login_user") as login_user_mock:
create_and_login_user(self.factory.org, user.name, user.email)
login_user_mock.assert_called_once_with(user, remember=True)
def test_creates_vaild_new_user(self):
email = "[email protected]"
name = "Test User"
with patch("redash.authentication.login_user") as login_user_mock:
create_and_login_user(self.factory.org, name, email)
self.assertTrue(login_user_mock.called)
user = models.User.query.filter(models.User.email == email).one()
self.assertEqual(user.email, email)
def test_updates_user_name(self):
user = self.factory.create_user(email="[email protected]")
with patch("redash.authentication.login_user") as login_user_mock:
create_and_login_user(self.factory.org, "New Name", user.email)
login_user_mock.assert_called_once_with(user, remember=True)
class TestVerifyProfile(BaseTestCase):
def test_no_domain_allowed_for_org(self):
profile = dict(email="[email protected]")
self.assertFalse(verify_profile(self.factory.org, profile))
def test_domain_not_in_org_domains_list(self):
profile = dict(email="[email protected]")
self.factory.org.settings[models.Organization.SETTING_GOOGLE_APPS_DOMAINS] = [
"example.org"
]
self.assertFalse(verify_profile(self.factory.org, profile))
def test_domain_in_org_domains_list(self):
profile = dict(email="[email protected]")
self.factory.org.settings[models.Organization.SETTING_GOOGLE_APPS_DOMAINS] = [
"example.com"
]
self.assertTrue(verify_profile(self.factory.org, profile))
self.factory.org.settings[models.Organization.SETTING_GOOGLE_APPS_DOMAINS] = [
"example.org",
"example.com",
]
self.assertTrue(verify_profile(self.factory.org, profile))
def test_org_in_public_mode_accepts_any_domain(self):
profile = dict(email="[email protected]")
self.factory.org.settings[models.Organization.SETTING_IS_PUBLIC] = True
self.factory.org.settings[models.Organization.SETTING_GOOGLE_APPS_DOMAINS] = []
self.assertTrue(verify_profile(self.factory.org, profile))
def test_user_not_in_domain_but_account_exists(self):
profile = dict(email="[email protected]")
self.factory.create_user(email="[email protected]")
self.factory.org.settings[models.Organization.SETTING_GOOGLE_APPS_DOMAINS] = [
"example.org"
]
self.assertTrue(verify_profile(self.factory.org, profile))
class TestGetLoginUrl(BaseTestCase):
def test_when_multi_org_enabled_and_org_exists(self):
with self.app.test_request_context("/{}/".format(self.factory.org.slug)):
self.assertEqual(
get_login_url(next=None), "/{}/login".format(self.factory.org.slug)
)
def test_when_multi_org_enabled_and_org_doesnt_exist(self):
with self.app.test_request_context(
"/{}_notexists/".format(self.factory.org.slug)
):
self.assertEqual(get_login_url(next=None), "/")
class TestRedirectToUrlAfterLoggingIn(BaseTestCase):
def setUp(self):
super(TestRedirectToUrlAfterLoggingIn, self).setUp()
self.user = self.factory.user
self.password = "test1234"
def test_no_next_param(self):
response = self.post_request(
"/login",
data={"email": self.user.email, "password": self.password},
org=self.factory.org,
)
self.assertEqual(
response.location, "http://localhost/{}/".format(self.user.org.slug)
)
def test_simple_path_in_next_param(self):
response = self.post_request(
"/login?next=queries",
data={"email": self.user.email, "password": self.password},
org=self.factory.org,
)
self.assertEqual(response.location, "http://localhost/default/queries")
def test_starts_scheme_url_in_next_param(self):
response = self.post_request(
"/login?next=https://redash.io",
data={"email": self.user.email, "password": self.password},
org=self.factory.org,
)
self.assertEqual(response.location, "http://localhost/default/")
def test_without_scheme_url_in_next_param(self):
response = self.post_request(
"/login?next=//redash.io",
data={"email": self.user.email, "password": self.password},
org=self.factory.org,
)
self.assertEqual(response.location, "http://localhost/default/")
def test_without_scheme_with_path_url_in_next_param(self):
response = self.post_request(
"/login?next=//localhost/queries",
data={"email": self.user.email, "password": self.password},
org=self.factory.org,
)
self.assertEqual(response.location, "http://localhost/queries")
class TestRemoteUserAuth(BaseTestCase):
DEFAULT_SETTING_OVERRIDES = {"REDASH_REMOTE_USER_LOGIN_ENABLED": "true"}
def setUp(self):
# Apply default setting overrides to every test
self.override_settings(None)
super(TestRemoteUserAuth, self).setUp()
def override_settings(self, overrides):
"""Override settings for testing purposes.
This helper method can be used to override specific environmental
variables to enable / disable Re:Dash features for the duration
of the test.
Note that these overrides only affect code that checks the value of
the setting at runtime. It doesn't affect code that only checks the
value during program initialization.
:param dict overrides: a dict of environmental variables to override
when the settings are reloaded
"""
variables = self.DEFAULT_SETTING_OVERRIDES.copy()
variables.update(overrides or {})
with patch.dict(os.environ, variables):
importlib.reload(settings)
# Queue a cleanup routine that reloads the settings without overrides
# once the test ends
self.addCleanup(lambda: importlib.reload(settings))
def assert_correct_user_attributes(
self,
user,
email="[email protected]",
name="[email protected]",
groups=None,
org=None,
):
"""Helper to assert that the user attributes are correct."""
groups = groups or []
if self.factory.org.default_group.id not in groups:
groups.append(self.factory.org.default_group.id)
self.assertIsNotNone(user)
self.assertEqual(user.email, email)
self.assertEqual(user.name, name)
self.assertEqual(user.org, org or self.factory.org)
self.assertCountEqual(user.group_ids, groups)
def get_test_user(self, email="[email protected]", org=None):
"""Helper to fetch an user from the database."""
# Expire all cached objects to ensure these values are read directly
# from the database.
models.db.session.expire_all()
return models.User.get_by_email_and_org(email, org or self.factory.org)
def test_remote_login_disabled(self):
self.override_settings({"REDASH_REMOTE_USER_LOGIN_ENABLED": "false"})
self.get_request(
"/remote_user/login",
org=self.factory.org,
headers={"X-Forwarded-Remote-User": "[email protected]"},
)
with self.assertRaises(NoResultFound):
self.get_test_user()
def test_remote_login_default_header(self):
self.get_request(
"/remote_user/login",
org=self.factory.org,
headers={"X-Forwarded-Remote-User": "[email protected]"},
)
self.assert_correct_user_attributes(self.get_test_user())
def test_remote_login_custom_header(self):
self.override_settings({"REDASH_REMOTE_USER_HEADER": "X-Custom-User"})
self.get_request(
"/remote_user/login",
org=self.factory.org,
headers={"X-Custom-User": "[email protected]"},
)
self.assert_correct_user_attributes(self.get_test_user())
class TestUserForgotPassword(BaseTestCase):
def test_user_should_receive_password_reset_link(self):
user = self.factory.create_user()
with patch(
"redash.handlers.authentication.send_password_reset_email"
) as send_password_reset_email_mock:
response = self.post_request(
"/forgot", org=user.org, data={"email": user.email}
)
self.assertEqual(response.status_code, 200)
send_password_reset_email_mock.assert_called_with(user)
def test_disabled_user_should_not_receive_password_reset_link(self):
user = self.factory.create_user()
user.disable()
self.db.session.add(user)
self.db.session.commit()
with patch(
"redash.handlers.authentication.send_password_reset_email"
) as send_password_reset_email_mock, patch(
"redash.handlers.authentication.send_user_disabled_email"
) as send_user_disabled_email_mock:
response = self.post_request(
"/forgot", org=user.org, data={"email": user.email}
)
self.assertEqual(response.status_code, 200)
send_password_reset_email_mock.assert_not_called()
send_user_disabled_email_mock.assert_called_with(user)