/
test_auth.py
897 lines (760 loc) · 33.7 KB
/
test_auth.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
# Copyright (c) 2013 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import division
import base64
import datetime
import hashlib
import logging
from wsgiref import simple_server
import ddt
import fakeredis
from keystoneclient import access
from keystoneclient import exceptions
import mock
import msgpack.exceptions
import simplejson as json
import six
from eom import auth
import tests
from tests.mocks import servicecatalog
from tests import util
LOG = logging.getLogger(__name__)
auth.configure(util.CONF)
def run_server(app, host, port):
httpd = simple_server.make_server(host, port, app)
httpd.serve_forever()
# Monkey patch the FakeRedis so we can expire data - even if it does nothing
def fakeredis_pexpireat(self, key, when):
pass
fakeredis.FakeRedis.pexpireat = fakeredis_pexpireat
def fakeredis_pexpire(self, key, ttl):
pass
fakeredis.FakeRedis.pexpire = fakeredis_pexpire
def fakeredis_connection():
return fakeredis.FakeRedis()
def fake_catalog(tenant, token):
"""Generate a fake Service Catalog
"""
catalog_gen = servicecatalog.ServiceCatalogGenerator(token, tenant)
catalog = catalog_gen.generate_full_catalog()['access']
return access.AccessInfoV2(**catalog)
def fake_auth_raise(self, auth_url, tenant_id, token):
raise exceptions.AuthorizationFailure('mock Keystone error')
class fake_client_object_raise(object):
def get_raw_token_from_identity_service(self, auth_url, tenant_id, token):
raise exceptions.AuthorizationFailure(
'mocking - identity crisis')
class fake_client_object_check_credentials(object):
def get_raw_token_from_identity_service(self, auth_url, tenant_id, token):
LOG.debug('URL: {0}'.format(auth_url))
LOG.debug('Token: {0}'.format(token))
LOG.debug('Tenant: {0}'.format(tenant_id))
if token == 'valid_token' and tenant_id == 'valid_projectid':
catalog_gen = servicecatalog.ServiceCatalogGenerator(
token, tenant_id)
catalog = catalog_gen.generate_full_catalog()['access']
return access.AccessInfoV2(**catalog)
else:
if token == 'valid_token':
raise exceptions.AuthorizationFailure(
'mocking - invalid project id')
elif tenant_id == 'valid_projectid':
raise exceptions.AuthorizationFailure(
'mocking - invalid token')
else:
raise exceptions.AuthorizationFailure(
'mocking - invalid or missing token or project id')
class fake_access_data(object):
def __init__(self, result):
self.result = result
def will_expire_soon(self):
return self.result
@ddt.ddt
class TestAuth(util.TestCase):
def setUp(self):
super(TestAuth, self).setUp()
redis_client = fakeredis_connection()
self.auth = auth.wrap(tests.util.app, redis_client)
self.test_url = '/v2/vault'
self.default_max_cache_life = 30
# config = auth.CONF['eom:auth']
# self.runtime_url = config['auth_url']
# config['auth_url'] = 'localhost/v2'
def tearDown(self):
super(TestAuth, self).tearDown()
redis_client = fakeredis_connection()
redis_client.flushall()
# config = auth.CONF['eom:auth']
# config['auth_url'] = self.runtime_url
def test_get_conf_auth(self):
config = auth.get_conf()
self.assertIsNotNone(config)
def test_get_conf_auth_redis(self):
auth_config = auth.get_conf()
redis_config = auth.get_conf(True)
self.assertIsNotNone(auth_config)
self.assertIsNotNone(redis_config)
self.assertNotEqual(auth_config, redis_config)
def test_cache_key(self):
value_input = ('1', '2', '3', '4')
value_hash = hashlib.sha1()
if six.PY3:
value_hash.update('(1,2,3,4)'.encode('utf-8'))
else:
value_hash.update('(1,2,3,4)')
value_output = value_hash.hexdigest()
test_result = auth._tuple_to_cache_key(value_input)
self.assertEqual(test_result, value_output)
def test_blacklist_cachekey(self):
value_input = 'fr4nkb3t4p3t3r'
value_hash = hashlib.sha1()
if six.PY3:
value_hash.update('blacklist'.encode('utf-8'))
value_hash.update(value_input.encode('utf-8'))
else:
value_hash.update('blacklist')
value_hash.update(value_input)
value_output = value_hash.hexdigest()
test_result = auth._blacklist_cache_key(
value_input
)
self.assertNotEqual(value_input, test_result)
self.assertEqual(value_output, test_result)
def test_blacklist_insertion(self):
token = 'h0t3l4lph4tang0'
bttl = 5
redis_client = fakeredis_connection()
# The data that will get cached
packed_data = msgpack.packb(True,
use_bin_type=True,
encoding='utf-8')
# Redis fails to expire ttl
with mock.patch(
'fakeredis.FakeRedis.pexpire') as MockRedisExpire:
MockRedisExpire.side_effect = Exception(
'mock redis expire failure')
redis_error = auth._blacklist_token(redis_client,
token,
bttl)
self.assertFalse(redis_error)
# Redis fails to set the data
with mock.patch(
'fakeredis.FakeRedis.set') as MockRedisSet:
MockRedisSet.side_effect = Exception('mock redis set data failed')
redis_error = auth._blacklist_token(redis_client,
token,
bttl)
self.assertFalse(redis_error)
# Happy path
store_result = auth._blacklist_token(redis_client,
token,
bttl)
self.assertTrue(store_result)
stored_data = redis_client.get(
auth._blacklist_cache_key(token)
)
self.assertIsNotNone(stored_data)
self.assertEqual(stored_data, packed_data)
stored_data_original = msgpack.unpackb(stored_data, encoding='utf-8')
self.assertEqual(True, stored_data_original)
@ddt.data(
(datetime.datetime.max, 500, True),
((datetime.datetime.utcnow() + datetime.timedelta(seconds=50)),
500, False),
((datetime.datetime.utcnow() + datetime.timedelta(seconds=500)),
50, True)
)
@ddt.unpack
def test_expiration_time(self, time_to_check,
slop, slop_makes_younger_time):
auth_time = auth._get_expiration_time(time_to_check, slop)
if slop_makes_younger_time:
self.assertLess(auth_time, time_to_check)
else:
self.assertEqual(auth_time, time_to_check)
def test_store_data_to_cache(self):
url = 'myfakeurl'
tenant_id = '0987654321'
token = 'fedcbaFEDCBA'
key_data = (tenant_id, token, url)
key_value = auth._tuple_to_cache_key(key_data)
redis_client = fakeredis_connection()
# The data that will get cached
access_data = fake_catalog(tenant_id, token)
packed_data = msgpack.packb(access_data,
use_bin_type=True,
encoding='utf-8')
# Redis fails the expiration time
with mock.patch(
'fakeredis.FakeRedis.pexpireat') as MockRedisExpire:
MockRedisExpire.side_effect = Exception(
'mock redis expire failure')
redis_error = auth._send_data_to_cache(redis_client,
url,
access_data,
self.default_max_cache_life)
self.assertFalse(redis_error)
# Redis fails to set the data
with mock.patch(
'fakeredis.FakeRedis.set') as MockRedisSet:
MockRedisSet.side_effect = Exception('mock redis set data failed')
redis_error = auth._send_data_to_cache(redis_client,
url,
access_data,
self.default_max_cache_life)
self.assertFalse(redis_error)
# Happy Path
store_result = auth._send_data_to_cache(redis_client,
url,
access_data,
self.default_max_cache_life)
self.assertTrue(store_result)
stored_data = redis_client.get(key_value)
self.assertIsNotNone(stored_data)
self.assertEqual(stored_data, packed_data)
stored_data_original = msgpack.unpackb(stored_data, encoding='utf-8')
self.assertEqual(stored_data_original, access_data)
def test_retrieve_cache_data(self):
url = 'myurl'
tenant_id = '123456890'
token = 'ABCDEFabcdef'
key_data = (tenant_id, token, url)
key_value = auth._tuple_to_cache_key(key_data)
data = fake_catalog(tenant_id, token)
data_packed = msgpack.packb(data, encoding='utf-8', use_bin_type=True)
redis_client = fakeredis_connection()
self.assertTrue(redis_client.set(key_value, data_packed))
# Invalid Cache Error
# - we use a random url for the cache conflict portion
invalid_cached_data = auth._retrieve_data_from_cache(redis_client,
'/random/url',
tenant_id,
token)
self.assertIsNone(invalid_cached_data)
# Test: Redis Client tosses exception
def redis_toss_exception(*args, **kwargs):
raise Exception('mock redis exception')
redis_exception_result = auth._retrieve_data_from_cache(
redis_toss_exception, url, tenant_id, token)
self.assertEqual(redis_exception_result, None)
# msgpack error
with mock.patch('eom.auth.__unpacker') as MockMsgPacker:
MockMsgPacker.side_effect = msgpack.exceptions.UnpackException(
'mock')
msgpack_error = auth._retrieve_data_from_cache(redis_client,
url,
tenant_id, token)
self.assertIsNone(msgpack_error)
# Test: Happy case V2 data
happy_v2_result = auth._retrieve_data_from_cache(redis_client,
url,
tenant_id,
token)
self.assertEqual(happy_v2_result, data)
def test_retrieve_keystone_bad_client_authorization_error(self):
url = 'myurl'
tenant_id = '789012345'
token = 'abcdefABCDEF'
bttl = 5
redis_client = fakeredis_connection()
with mock.patch(
'keystoneclient.v2_0.client.Client') as MockKeystoneClient:
MockKeystoneClient.side_effect = exceptions.Unauthorized(
'Mock - invalid client object')
keystone_create_error = auth._retrieve_data_from_keystone(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertIsNone(keystone_create_error)
with mock.patch(
'keystoneclient.v2_0.client.Client') as MockKeystoneClient:
MockKeystoneClient.side_effect = exceptions.AuthorizationFailure(
'Mock - invalid client object')
keystone_create_error = auth._retrieve_data_from_keystone(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertIsNone(keystone_create_error)
def test_retrieve_keystone_unauthorized_error_from_413_error(self):
url = 'myurl'
tenant_id = '789012345'
token = 'abcdefABCDEF'
bttl = 5
redis_client = fakeredis_connection()
with mock.patch(
'keystoneclient.v2_0.client.Client') as MockKeystoneClient:
MockKeystoneClient.side_effect = exceptions.AuthorizationFailure(
'Authorization Failed: Request Entity Too Large (HTTP 413)')
self.assertRaises(
exceptions.RequestEntityTooLarge,
auth._retrieve_data_from_keystone,
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life
)
def test_retrieve_keystone_bad_client(self):
url = 'myurl'
tenant_id = '789012345'
token = 'abcdefABCDEF'
bttl = 5
redis_client = fakeredis_connection()
with mock.patch(
'keystoneclient.v2_0.client.Client') as MockKeystoneClient:
MockKeystoneClient.side_effect = Exception(
'Mock - invalid client object')
keystone_create_error = auth._retrieve_data_from_keystone(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertIsNone(keystone_create_error)
def test_retrieve_keystone_bad_identity_access(self):
url = 'myurl'
tenant_id = '789012345'
token = 'abcdefABCDEF'
bttl = 5
redis_client = fakeredis_connection()
with mock.patch(
'keystoneclient.v2_0.client.Client') as MockKeystoneClient:
MockKeystoneClient.return_value = fake_client_object_raise()
# Fail to get a valid Client object
# Note: Client() uses the requests package to do an auth;
# on failure it is the requests module that fails.
keystone_error = auth._retrieve_data_from_keystone(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertIsNone(keystone_error)
def test_retrieve_keystone_check_credentials(self):
url = 'myurl'
bttl = 5
redis_client = fakeredis_connection()
with mock.patch(
'keystoneclient.v2_0.client.Client') as MockKeystoneClient:
MockKeystoneClient.return_value = (
fake_client_object_check_credentials())
credential_sets = [
{
'projectid': 'valid_projectid',
'authtoken': 'valid_token',
'is_none': False
},
{
'projectid': None,
'authtoken': 'valid_token',
'is_none': True
},
{
'projectid': 'valid_projectid',
'authtoken': None,
'is_none': True
},
{
'projectid': None,
'authtoken': None,
'is_none': True
},
{
'projectid': 'invalid_projectid',
'authtoken': 'valid_token',
'is_none': True
},
{
'projectid': 'valid_projectid',
'authtoken': 'invalid_token',
'is_none': True
},
{
'projectid': 'invalid_projectid',
'authtoken': 'invalid_token',
'is_none': True
}
]
for creds in credential_sets:
keystone_error = auth._retrieve_data_from_keystone(
redis_client,
url,
creds['projectid'],
creds['authtoken'],
bttl,
self.default_max_cache_life)
if creds['is_none']:
self.assertIsNone(keystone_error)
else:
self.assertIsNotNone(keystone_error)
def test__retrieve_data_from_keystone_alt_auth(self):
redis_client = fakeredis_connection()
tenant_id = '172839405'
token = 'AaBbCcDdEeFf'
url = 'myurl'
bttl = 5
with mock.patch('eom.auth.get_conf') as mock_auth_conf:
with mock.patch('requests.get') as mock_requests:
mock_auth_conf.return_value.alternate_validation = True
cat = servicecatalog.ServiceCatalogGenerator(token, tenant_id)
resp_json = cat.generate_without_catalog()
mock_requests.return_value.json.return_value = resp_json
mock_requests.return_value.status_code = 200
access_info = auth._retrieve_data_from_keystone(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life
)
self.assertEqual(
access_info,
access.AccessInfoV2(
cat.generate_without_catalog()['access']
)
)
def test__retrieve_data_from_keystone_alt_auth_returns_413(self):
redis_client = fakeredis_connection()
tenant_id = '172839405'
token = 'AaBbCcDdEeFf'
url = 'myurl'
bttl = 5
with mock.patch('eom.auth.get_conf') as mock_auth_conf:
with mock.patch('requests.get') as mock_requests:
mock_auth_conf.return_value.alternate_validation = True
mock_requests.return_value.status_code = 413
self.assertRaises(
exceptions.RequestEntityTooLarge,
auth._retrieve_data_from_keystone,
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life
)
def test_get_access_info(self):
url = 'myurl'
tenant_id = '172839405'
token = 'AaBbCcDdEeFf'
bttl = 5
redis_client = fakeredis_connection()
with mock.patch(
'eom.auth._retrieve_data_from_cache') as MockRetrieveCacheData:
with mock.patch(
'eom.auth._retrieve_data_from_keystone') as (
MockRetrieveKeystoneData):
# No data in cache, keystone can't retrieve
MockRetrieveCacheData.return_value = None
MockRetrieveKeystoneData.return_value = None
access_info = auth._get_access_info(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertIsNone(access_info)
# Data in cache, not expired
MockRetrieveCacheData.return_value = fake_access_data(False)
MockRetrieveKeystoneData.return_value = None
access_info = auth._get_access_info(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertEqual(access_info,
MockRetrieveCacheData.return_value)
# No data in cache, keystone retrieves
MockRetrieveCacheData.return_value = None
MockRetrieveKeystoneData.return_value = fake_access_data(False)
access_info = auth._get_access_info(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertEqual(access_info,
MockRetrieveKeystoneData.return_value)
# Expired data in cache, keystone can't retrieve
MockRetrieveCacheData.return_value = fake_access_data(True)
MockRetrieveKeystoneData.return_value = None
access_info = auth._get_access_info(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertNotEqual(access_info,
MockRetrieveCacheData.return_value)
self.assertIsNone(access_info)
# No data in cache, keystone returns expired data
MockRetrieveCacheData.return_value = None
MockRetrieveKeystoneData.return_value = fake_access_data(True)
access_info = auth._get_access_info(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertNotEqual(access_info,
MockRetrieveKeystoneData.return_value)
self.assertIsNone(access_info)
# Expired data in cache, keystone returns expired data
MockRetrieveCacheData.return_value = fake_access_data(True)
MockRetrieveKeystoneData.return_value = fake_access_data(True)
access_info = auth._get_access_info(
redis_client,
url,
tenant_id,
token,
bttl,
self.default_max_cache_life)
self.assertNotEqual(access_info,
MockRetrieveCacheData.return_value)
self.assertNotEqual(access_info,
MockRetrieveKeystoneData.return_value)
self.assertIsNone(access_info)
def test_validate_client_exception(self):
url = 'myurl'
tenant_id = '172839405'
token = 'AaBbCcDdEeFf'
redis_client = fakeredis_connection()
bttl = 5
# Throw an exception - anything, just needs to throw
with mock.patch(
'eom.auth._get_access_info') as MockGetAccessInfo:
env_exception_thrown = {}
MockGetAccessInfo.side_effect = Exception(
'mock - just blowing it up')
result = auth._validate_client(redis_client,
url,
tenant_id,
token,
env_exception_thrown,
bttl,
self.default_max_cache_life)
self.assertFalse(result)
def test_validate_client_invalid_data(self):
url = 'myurl'
tenant_id = '172839405'
token = 'AaBbCcDdEeFf'
redis_client = fakeredis_connection()
bttl = 5
# No data is returned
with mock.patch(
'eom.auth._get_access_info') as MockGetAccessInfo:
env_no_data = {}
MockGetAccessInfo.return_value = None
result = auth._validate_client(redis_client,
url,
tenant_id,
token,
env_no_data,
bttl,
self.default_max_cache_life)
self.assertFalse(result)
def test_validate_client_token_blacklisted(self):
url = 'myurl'
tenant_id = '504938271'
token = '1nd14r0m303ch0n0v3mb3r3ch0'
redis_client = fakeredis_connection()
bttl = 5
# We have data
with mock.patch(
'eom.auth._is_token_blacklisted') as MockBlacklist:
env_result = {}
MockBlacklist.return_value = True
result = auth._validate_client(redis_client,
url,
tenant_id,
token,
env_result,
bttl,
self.default_max_cache_life)
self.assertFalse(result)
def test_validate_client_b64decode_error(self):
url = 'myurl'
tenant_id = '172839405'
token = 'AaBbCcDdEeFf'
redis_client = fakeredis_connection()
bttl = 5
# The data that will get cached
access_info = fake_catalog(tenant_id, token)
# We have data
with mock.patch(
'eom.auth._get_access_info') as MockGetAccessInfo:
with mock.patch(
'eom.auth._is_token_blacklisted') as MockBlacklist:
with mock.patch(
'base64.b64decode') as MockB64Decode:
MockB64Decode.side_effect = Exception(
'mock b64decode error')
env_result = {}
MockBlacklist.return_value = False
MockGetAccessInfo.return_value = access_info
result = auth._validate_client(redis_client,
url,
tenant_id,
token,
env_result,
bttl,
self.default_max_cache_life)
self.assertFalse(result)
def test_validate_client_valid_data(self):
url = 'myurl'
tenant_id = '172839405'
token = 'AaBbCcDdEeFf'
redis_client = fakeredis_connection()
bttl = 5
# The data that will get cached
access_info = fake_catalog(tenant_id, token)
# Encode a version of the data for verification tests later
data = access_info.service_catalog.catalog
json_data = json.dumps(data)
u_json_data = json_data
if six.PY2:
if isinstance(u_json_data, bytes):
u_json_data = json_data.decode('utf-8')
access_data_utf8 = u_json_data.encode(encoding='utf-8',
errors='strict')
access_data_b64 = base64.b64encode(access_data_utf8)
# We have data
with mock.patch(
'eom.auth._get_access_info') as MockGetAccessInfo:
with mock.patch(
'eom.auth._is_token_blacklisted') as MockBlacklist:
env_result = {}
MockBlacklist.return_value = False
MockGetAccessInfo.return_value = access_info
result = auth._validate_client(redis_client,
url,
tenant_id,
token,
env_result,
bttl,
self.default_max_cache_life)
self.assertTrue(result)
self.assertEqual(env_result['HTTP_X_IDENTITY_STATUS'],
'Confirmed')
self.assertEqual(env_result['HTTP_X_USER_ID'],
MockGetAccessInfo.return_value.user_id)
self.assertEqual(env_result['HTTP_X_USER_NAME'],
MockGetAccessInfo.return_value.username)
self.assertEqual(env_result['HTTP_X_USER_DOMAIN_ID'],
MockGetAccessInfo.return_value.user_domain_id)
self.assertEqual(env_result['HTTP_X_USER_DOMAIN_NAME'],
MockGetAccessInfo.return_value.
user_domain_name)
role_names = MockGetAccessInfo.return_value.role_names
self.assertEqual(env_result['HTTP_X_ROLES'],
','.join(role for role in role_names))
self.assertEqual(env_result['HTTP_X_SERVICE_CATALOG'],
access_data_b64)
env_service_catalog_utf8 = base64.b64decode(
env_result['HTTP_X_SERVICE_CATALOG'])
self.assertEqual(env_service_catalog_utf8, access_data_utf8)
env_service_catalog = json.loads(env_service_catalog_utf8)
self.assertEqual(env_service_catalog, data)
self.assertTrue(MockGetAccessInfo.return_value.project_scoped)
self.assertEqual(env_result['HTTP_X_PROJECT_ID'], tenant_id)
self.assertEqual(env_result['HTTP_X_PROJECT_ID'],
MockGetAccessInfo.return_value.project_id)
self.assertEqual(env_result['HTTP_X_PROJECT_NAME'],
MockGetAccessInfo.return_value.project_name)
if MockGetAccessInfo.return_value.domain_scoped:
self.assertEqual(env_result['HTTP_X_DOMAIN_ID'],
MockGetAccessInfo.return_value.domain_id)
self.assertEqual(env_result['HTTP_X_DOMAIN_NAME'],
MockGetAccessInfo.return_value.
domain_name)
else:
self.assertTrue('HTTP_X_DOMAIN_ID' not in
env_result.keys())
self.assertTrue('HTTP_X_DOMAIN_NAME' not in
env_result.keys())
if MockGetAccessInfo.return_value.project_scoped and (
MockGetAccessInfo.return_value.domain_scoped):
self.assertEqual(env_result['HTTP_X_PROJECT_DOMAIN_ID'],
MockGetAccessInfo.return_value.
project_domain_id)
self.assertEqual(env_result['HTTP_X_PROJECT_DOMAIN_NAME'],
MockGetAccessInfo.return_value.
project_domain_name)
else:
self.assertTrue('HTTP_X_PROJECT_DOMAIN_ID' not in
env_result.keys())
self.assertTrue('HTTP_X_PROJECT_DOMAIN_NAME' not in
env_result.keys())
"""
def check_credentials(self, projectid, token, result):
env = self.create_env(self.test_url,
project_id=projectid,
auth_token=token)
self.auth(env, self.start_response)
self.assertEqual(self.status, result)
"""
def test_eom_auth_wrap(self):
with mock.patch(
'eom.auth._validate_client') as MockValidateClient:
# Create a LookupError or KeyError when the X-Auth-Token
# Header is not located
env_no_token = {
'HTTP_X_PROJECT_ID': 'valid_projectid'
}
self.auth(env_no_token, self.start_response)
self.assertEqual(self.status, '412 Precondition Failed')
# Create a LookupError or KeyError when the X-Project-ID
# Header is not located
env_no_projectid = {
'HTTP_X_AUTH_TOKEN': 'valid_auth_token'
}
self.auth(env_no_projectid, self.start_response)
self.assertEqual(self.status, '412 Precondition Failed')
# Valid Headers from here on out
env_valid = {}
env_valid.update(env_no_token)
env_valid.update(env_no_projectid)
# Assume the client fails validation
MockValidateClient.return_value = False
self.auth(env_valid, self.start_response)
self.assertEqual(self.status, '401 Unauthorized')
# With everything else working correctly, simulate too many
# requests sent to auth endpoint which should result in
# HTTP 503 - Service Unavailable
MockValidateClient.side_effect = exceptions.RequestEntityTooLarge(
'Mock - request entity too large'
)
self.auth(env_valid, self.start_response)
self.assertEqual(self.status, '503 Service Unavailable')
# Client passes validation
MockValidateClient.side_effect = [True]
self.auth(env_valid, self.start_response)
self.assertEqual(self.status, '204 No Content')