aboutsummaryrefslogtreecommitdiffstats
path: root/keystone-moon/keystone/tests/unit/test_v2.py
blob: acdfca5f063c1299e5363b4b3022029577260a95 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
# Copyright 2012 OpenStack Foundation
#
# 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.

import json
import time
import uuid

from keystoneclient.common import cms
from oslo_config import cfg
import six
from six.moves import http_client
from testtools import matchers

from keystone.common import extension as keystone_extension
from keystone.tests.unit import ksfixtures
from keystone.tests.unit import rest


CONF = cfg.CONF


class CoreApiTests(object):
    def assertValidError(self, error):
        self.assertIsNotNone(error.get('code'))
        self.assertIsNotNone(error.get('title'))
        self.assertIsNotNone(error.get('message'))

    def assertValidVersion(self, version):
        self.assertIsNotNone(version)
        self.assertIsNotNone(version.get('id'))
        self.assertIsNotNone(version.get('status'))
        self.assertIsNotNone(version.get('updated'))

    def assertValidExtension(self, extension):
        self.assertIsNotNone(extension)
        self.assertIsNotNone(extension.get('name'))
        self.assertIsNotNone(extension.get('namespace'))
        self.assertIsNotNone(extension.get('alias'))
        self.assertIsNotNone(extension.get('updated'))

    def assertValidExtensionLink(self, link):
        self.assertIsNotNone(link.get('rel'))
        self.assertIsNotNone(link.get('type'))
        self.assertIsNotNone(link.get('href'))

    def assertValidTenant(self, tenant):
        self.assertIsNotNone(tenant.get('id'))
        self.assertIsNotNone(tenant.get('name'))
        self.assertNotIn('domain_id', tenant)
        self.assertNotIn('parent_id', tenant)

    def assertValidUser(self, user):
        self.assertIsNotNone(user.get('id'))
        self.assertIsNotNone(user.get('name'))

    def assertValidRole(self, tenant):
        self.assertIsNotNone(tenant.get('id'))
        self.assertIsNotNone(tenant.get('name'))

    def test_public_not_found(self):
        r = self.public_request(
            path='/%s' % uuid.uuid4().hex,
            expected_status=http_client.NOT_FOUND)
        self.assertValidErrorResponse(r)

    def test_admin_not_found(self):
        r = self.admin_request(
            path='/%s' % uuid.uuid4().hex,
            expected_status=http_client.NOT_FOUND)
        self.assertValidErrorResponse(r)

    def test_public_multiple_choice(self):
        r = self.public_request(path='/', expected_status=300)
        self.assertValidMultipleChoiceResponse(r)

    def test_admin_multiple_choice(self):
        r = self.admin_request(path='/', expected_status=300)
        self.assertValidMultipleChoiceResponse(r)

    def test_public_version(self):
        r = self.public_request(path='/v2.0/')
        self.assertValidVersionResponse(r)

    def test_admin_version(self):
        r = self.admin_request(path='/v2.0/')
        self.assertValidVersionResponse(r)

    def test_public_extensions(self):
        r = self.public_request(path='/v2.0/extensions')
        self.assertValidExtensionListResponse(
            r, keystone_extension.PUBLIC_EXTENSIONS)

    def test_admin_extensions(self):
        r = self.admin_request(path='/v2.0/extensions')
        self.assertValidExtensionListResponse(
            r, keystone_extension.ADMIN_EXTENSIONS)

    def test_admin_extensions_404(self):
        self.admin_request(path='/v2.0/extensions/invalid-extension',
                           expected_status=http_client.NOT_FOUND)

    def test_public_osksadm_extension_404(self):
        self.public_request(path='/v2.0/extensions/OS-KSADM',
                            expected_status=http_client.NOT_FOUND)

    def test_admin_osksadm_extension(self):
        r = self.admin_request(path='/v2.0/extensions/OS-KSADM')
        self.assertValidExtensionResponse(
            r, keystone_extension.ADMIN_EXTENSIONS)

    def test_authenticate(self):
        r = self.public_request(
            method='POST',
            path='/v2.0/tokens',
            body={
                'auth': {
                    'passwordCredentials': {
                        'username': self.user_foo['name'],
                        'password': self.user_foo['password'],
                    },
                    'tenantId': self.tenant_bar['id'],
                },
            },
            expected_status=200)
        self.assertValidAuthenticationResponse(r, require_service_catalog=True)

    def test_authenticate_unscoped(self):
        r = self.public_request(
            method='POST',
            path='/v2.0/tokens',
            body={
                'auth': {
                    'passwordCredentials': {
                        'username': self.user_foo['name'],
                        'password': self.user_foo['password'],
                    },
                },
            },
            expected_status=200)
        self.assertValidAuthenticationResponse(r)

    def test_get_tenants_for_token(self):
        r = self.public_request(path='/v2.0/tenants',
                                token=self.get_scoped_token())
        self.assertValidTenantListResponse(r)

    def test_validate_token(self):
        token = self.get_scoped_token()
        r = self.admin_request(
            path='/v2.0/tokens/%(token_id)s' % {
                'token_id': token,
            },
            token=token)
        self.assertValidAuthenticationResponse(r)

    def test_invalid_token_404(self):
        token = self.get_scoped_token()
        self.admin_request(
            path='/v2.0/tokens/%(token_id)s' % {
                'token_id': 'invalid',
            },
            token=token,
            expected_status=http_client.NOT_FOUND)

    def test_validate_token_service_role(self):
        self.md_foobar = self.assignment_api.add_role_to_user_and_project(
            self.user_foo['id'],
            self.tenant_service['id'],
            self.role_service['id'])

        token = self.get_scoped_token(tenant_id='service')
        r = self.admin_request(
            path='/v2.0/tokens/%s' % token,
            token=token)
        self.assertValidAuthenticationResponse(r)

    def test_remove_role_revokes_token(self):
        self.md_foobar = self.assignment_api.add_role_to_user_and_project(
            self.user_foo['id'],
            self.tenant_service['id'],
            self.role_service['id'])

        token = self.get_scoped_token(tenant_id='service')
        r = self.admin_request(
            path='/v2.0/tokens/%s' % token,
            token=token)
        self.assertValidAuthenticationResponse(r)

        self.assignment_api.remove_role_from_user_and_project(
            self.user_foo['id'],
            self.tenant_service['id'],
            self.role_service['id'])

        r = self.admin_request(
            path='/v2.0/tokens/%s' % token,
            token=token,
            expected_status=http_client.UNAUTHORIZED)

    def test_validate_token_belongs_to(self):
        token = self.get_scoped_token()
        path = ('/v2.0/tokens/%s?belongsTo=%s' % (token,
                                                  self.tenant_bar['id']))
        r = self.admin_request(path=path, token=token)
        self.assertValidAuthenticationResponse(r, require_service_catalog=True)

    def test_validate_token_no_belongs_to_still_returns_catalog(self):
        token = self.get_scoped_token()
        path = ('/v2.0/tokens/%s' % token)
        r = self.admin_request(path=path, token=token)
        self.assertValidAuthenticationResponse(r, require_service_catalog=True)

    def test_validate_token_head(self):
        """The same call as above, except using HEAD.

        There's no response to validate here, but this is included for the
        sake of completely covering the core API.

        """
        token = self.get_scoped_token()
        self.admin_request(
            method='HEAD',
            path='/v2.0/tokens/%(token_id)s' % {
                'token_id': token,
            },
            token=token,
            expected_status=200)

    def test_endpoints(self):
        token = self.get_scoped_token()
        r = self.admin_request(
            path='/v2.0/tokens/%(token_id)s/endpoints' % {
                'token_id': token,
            },
            token=token)
        self.assertValidEndpointListResponse(r)

    def test_get_tenant(self):
        token = self.get_scoped_token()
        r = self.admin_request(
            path='/v2.0/tenants/%(tenant_id)s' % {
                'tenant_id': self.tenant_bar['id'],
            },
            token=token)
        self.assertValidTenantResponse(r)

    def test_get_tenant_by_name(self):
        token = self.get_scoped_token()
        r = self.admin_request(
            path='/v2.0/tenants?name=%(tenant_name)s' % {
                'tenant_name': self.tenant_bar['name'],
            },
            token=token)
        self.assertValidTenantResponse(r)

    def test_get_user_roles_with_tenant(self):
        token = self.get_scoped_token()
        r = self.admin_request(
            path='/v2.0/tenants/%(tenant_id)s/users/%(user_id)s/roles' % {
                'tenant_id': self.tenant_bar['id'],
                'user_id': self.user_foo['id'],
            },
            token=token)
        self.assertValidRoleListResponse(r)

    def test_get_user(self):
        token = self.get_scoped_token()
        r = self.admin_request(
            path='/v2.0/users/%(user_id)s' % {
                'user_id': self.user_foo['id'],
            },
            token=token)
        self.assertValidUserResponse(r)

    def test_get_user_by_name(self):
        token = self.get_scoped_token()
        r = self.admin_request(
            path='/v2.0/users?name=%(user_name)s' % {
                'user_name': self.user_foo['name'],
            },
            token=token)
        self.assertValidUserResponse(r)

    def test_create_update_user_invalid_enabled_type(self):
        # Enforce usage of boolean for 'enabled' field
        token = self.get_scoped_token()

        # Test CREATE request
        r = self.admin_request(
            method='POST',
            path='/v2.0/users',
            body={
                'user': {
                    'name': uuid.uuid4().hex,
                    'password': uuid.uuid4().hex,
                    'enabled': "False",
                },
            },
            token=token,
            expected_status=http_client.BAD_REQUEST)
        self.assertValidErrorResponse(r)

        r = self.admin_request(
            method='POST',
            path='/v2.0/users',
            body={
                'user': {
                    'name': uuid.uuid4().hex,
                    'password': uuid.uuid4().hex,
                    # In JSON, 0|1 are not booleans
                    'enabled': 0,
                },
            },
            token=token,
            expected_status=http_client.BAD_REQUEST)
        self.assertValidErrorResponse(r)

        # Test UPDATE request
        path = '/v2.0/users/%(user_id)s' % {
               'user_id': self.user_foo['id'],
        }

        r = self.admin_request(
            method='PUT',
            path=path,
            body={
                'user': {
                    'enabled': "False",
                },
            },
            token=token,
            expected_status=http_client.BAD_REQUEST)
        self.assertValidErrorResponse(r)

        r = self.admin_request(
            method='PUT',
            path=path,
            body={
                'user': {
                    # In JSON, 0|1 are not booleans
                    'enabled': 1,
                },
            },
            token=token,
            expected_status=http_client.BAD_REQUEST)
        self.assertValidErrorResponse(r)

    def test_create_update_user_valid_enabled_type(self):
        # Enforce usage of boolean for 'enabled' field
        token = self.get_scoped_token()

        # Test CREATE request
        self.admin_request(method='POST',
                           path='/v2.0/users',
                           body={
                               'user': {
                                   'name': uuid.uuid4().hex,
                                   'password': uuid.uuid4().hex,
                                   'enabled': False,
                               },
                           },
                           token=token,
                           expected_status=200)

    def test_error_response(self):
        """This triggers assertValidErrorResponse by convention."""
        self.public_request(path='/v2.0/tenants',
                            expected_status=http_client.UNAUTHORIZED)

    def test_invalid_parameter_error_response(self):
        token = self.get_scoped_token()
        bad_body = {
            'OS-KSADM:service%s' % uuid.uuid4().hex: {
                'name': uuid.uuid4().hex,
                'type': uuid.uuid4().hex,
            },
        }
        res = self.admin_request(method='POST',
                                 path='/v2.0/OS-KSADM/services',
                                 body=bad_body,
                                 token=token,
                                 expected_status=http_client.BAD_REQUEST)
        self.assertValidErrorResponse(res)
        res = self.admin_request(method='POST',
                                 path='/v2.0/users',
                                 body=bad_body,
                                 token=token,
                                 expected_status=http_client.BAD_REQUEST)
        self.assertValidErrorResponse(res)

    def _get_user_id(self, r):
        """Helper method to return user ID from a response.

        This needs to be overridden by child classes
        based on their content type.

        """
        raise NotImplementedError()

    def _get_role_id(self, r):
        """Helper method to return a role ID from a response.

        This needs to be overridden by child classes
        based on their content type.

        """
        raise NotImplementedError()

    def _get_role_name(self, r):
        """Helper method to return role NAME from a response.

        This needs to be overridden by child classes
        based on their content type.

        """
        raise NotImplementedError()

    def _get_project_id(self, r):
        """Helper method to return project ID from a response.

        This needs to be overridden by child classes
        based on their content type.

        """
        raise NotImplementedError()

    def assertNoRoles(self, r):
        """Helper method to assert No Roles

        This needs to be overridden by child classes
        based on their content type.

        """
        raise NotImplementedError()

    def test_update_user_tenant(self):
        token = self.get_scoped_token()

        # Create a new user
        r = self.admin_request(
            method='POST',
            path='/v2.0/users',
            body={
                'user': {
                    'name': uuid.uuid4().hex,
                    'password': uuid.uuid4().hex,
                    'tenantId': self.tenant_bar['id'],
                    'enabled': True,
                },
            },
            token=token,
            expected_status=200)

        user_id = self._get_user_id(r.result)

        # Check if member_role is in tenant_bar
        r = self.admin_request(
            path='/v2.0/tenants/%(project_id)s/users/%(user_id)s/roles' % {
                'project_id': self.tenant_bar['id'],
                'user_id': user_id
            },
            token=token,
            expected_status=200)
        self.assertEqual(CONF.member_role_name, self._get_role_name(r.result))

        # Create a new tenant
        r = self.admin_request(
            method='POST',
            path='/v2.0/tenants',
            body={
                'tenant': {
                    'name': 'test_update_user',
                    'description': 'A description ...',
                    'enabled': True,
                },
            },
            token=token,
            expected_status=200)

        project_id = self._get_project_id(r.result)

        # Update user's tenant
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%(user_id)s' % {
                'user_id': user_id,
            },
            body={
                'user': {
                    'tenantId': project_id,
                },
            },
            token=token,
            expected_status=200)

        # 'member_role' should be in new_tenant
        r = self.admin_request(
            path='/v2.0/tenants/%(project_id)s/users/%(user_id)s/roles' % {
                'project_id': project_id,
                'user_id': user_id
            },
            token=token,
            expected_status=200)
        self.assertEqual('_member_', self._get_role_name(r.result))

        # 'member_role' should not be in tenant_bar any more
        r = self.admin_request(
            path='/v2.0/tenants/%(project_id)s/users/%(user_id)s/roles' % {
                'project_id': self.tenant_bar['id'],
                'user_id': user_id
            },
            token=token,
            expected_status=200)
        self.assertNoRoles(r.result)

    def test_update_user_with_invalid_tenant(self):
        token = self.get_scoped_token()

        # Create a new user
        r = self.admin_request(
            method='POST',
            path='/v2.0/users',
            body={
                'user': {
                    'name': 'test_invalid_tenant',
                    'password': uuid.uuid4().hex,
                    'tenantId': self.tenant_bar['id'],
                    'enabled': True,
                },
            },
            token=token,
            expected_status=200)
        user_id = self._get_user_id(r.result)

        # Update user with an invalid tenant
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%(user_id)s' % {
                'user_id': user_id,
            },
            body={
                'user': {
                    'tenantId': 'abcde12345heha',
                },
            },
            token=token,
            expected_status=http_client.NOT_FOUND)

    def test_update_user_with_invalid_tenant_no_prev_tenant(self):
        token = self.get_scoped_token()

        # Create a new user
        r = self.admin_request(
            method='POST',
            path='/v2.0/users',
            body={
                'user': {
                    'name': 'test_invalid_tenant',
                    'password': uuid.uuid4().hex,
                    'enabled': True,
                },
            },
            token=token,
            expected_status=200)
        user_id = self._get_user_id(r.result)

        # Update user with an invalid tenant
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%(user_id)s' % {
                'user_id': user_id,
            },
            body={
                'user': {
                    'tenantId': 'abcde12345heha',
                },
            },
            token=token,
            expected_status=http_client.NOT_FOUND)

    def test_update_user_with_old_tenant(self):
        token = self.get_scoped_token()

        # Create a new user
        r = self.admin_request(
            method='POST',
            path='/v2.0/users',
            body={
                'user': {
                    'name': uuid.uuid4().hex,
                    'password': uuid.uuid4().hex,
                    'tenantId': self.tenant_bar['id'],
                    'enabled': True,
                },
            },
            token=token,
            expected_status=200)

        user_id = self._get_user_id(r.result)

        # Check if member_role is in tenant_bar
        r = self.admin_request(
            path='/v2.0/tenants/%(project_id)s/users/%(user_id)s/roles' % {
                'project_id': self.tenant_bar['id'],
                'user_id': user_id
            },
            token=token,
            expected_status=200)
        self.assertEqual(CONF.member_role_name, self._get_role_name(r.result))

        # Update user's tenant with old tenant id
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%(user_id)s' % {
                'user_id': user_id,
            },
            body={
                'user': {
                    'tenantId': self.tenant_bar['id'],
                },
            },
            token=token,
            expected_status=200)

        # 'member_role' should still be in tenant_bar
        r = self.admin_request(
            path='/v2.0/tenants/%(project_id)s/users/%(user_id)s/roles' % {
                'project_id': self.tenant_bar['id'],
                'user_id': user_id
            },
            token=token,
            expected_status=200)
        self.assertEqual('_member_', self._get_role_name(r.result))

    def test_authenticating_a_user_with_no_password(self):
        token = self.get_scoped_token()

        username = uuid.uuid4().hex

        # create the user
        self.admin_request(
            method='POST',
            path='/v2.0/users',
            body={
                'user': {
                    'name': username,
                    'enabled': True,
                },
            },
            token=token)

        # fail to authenticate
        r = self.public_request(
            method='POST',
            path='/v2.0/tokens',
            body={
                'auth': {
                    'passwordCredentials': {
                        'username': username,
                        'password': 'password',
                    },
                },
            },
            expected_status=http_client.UNAUTHORIZED)
        self.assertValidErrorResponse(r)

    def test_www_authenticate_header(self):
        r = self.public_request(
            path='/v2.0/tenants',
            expected_status=http_client.UNAUTHORIZED)
        self.assertEqual('Keystone uri="http://localhost"',
                         r.headers.get('WWW-Authenticate'))

    def test_www_authenticate_header_host(self):
        test_url = 'http://%s:4187' % uuid.uuid4().hex
        self.config_fixture.config(public_endpoint=test_url)
        r = self.public_request(
            path='/v2.0/tenants',
            expected_status=http_client.UNAUTHORIZED)
        self.assertEqual('Keystone uri="%s"' % test_url,
                         r.headers.get('WWW-Authenticate'))


class LegacyV2UsernameTests(object):
    """Tests to show the broken username behavior in V2.

    The V2 API is documented to use `username` instead of `name`.  The
    API forced used to use name and left the username to fall into the
    `extra` field.

    These tests ensure this behavior works so fixes to `username`/`name`
    will be backward compatible.
    """

    def create_user(self, **user_attrs):
        """Creates a users and returns the response object.

        :param user_attrs: attributes added to the request body (optional)
        """
        token = self.get_scoped_token()
        body = {
            'user': {
                'name': uuid.uuid4().hex,
                'enabled': True,
            },
        }
        body['user'].update(user_attrs)

        return self.admin_request(
            method='POST',
            path='/v2.0/users',
            token=token,
            body=body,
            expected_status=200)

    def test_create_with_extra_username(self):
        """The response for creating a user will contain the extra fields."""
        fake_username = uuid.uuid4().hex
        r = self.create_user(username=fake_username)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual(fake_username, user.get('username'))

    def test_get_returns_username_from_extra(self):
        """The response for getting a user will contain the extra fields."""
        token = self.get_scoped_token()

        fake_username = uuid.uuid4().hex
        r = self.create_user(username=fake_username)

        id_ = self.get_user_attribute_from_response(r, 'id')
        r = self.admin_request(path='/v2.0/users/%s' % id_, token=token)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual(fake_username, user.get('username'))

    def test_update_returns_new_username_when_adding_username(self):
        """The response for updating a user will contain the extra fields.

        This is specifically testing for updating a username when a value
        was not previously set.
        """
        token = self.get_scoped_token()

        r = self.create_user()

        id_ = self.get_user_attribute_from_response(r, 'id')
        name = self.get_user_attribute_from_response(r, 'name')
        enabled = self.get_user_attribute_from_response(r, 'enabled')
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%s' % id_,
            token=token,
            body={
                'user': {
                    'name': name,
                    'username': 'new_username',
                    'enabled': enabled,
                },
            },
            expected_status=200)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual('new_username', user.get('username'))

    def test_update_returns_new_username_when_updating_username(self):
        """The response for updating a user will contain the extra fields.

        This tests updating a username that was previously set.
        """
        token = self.get_scoped_token()

        r = self.create_user(username='original_username')

        id_ = self.get_user_attribute_from_response(r, 'id')
        name = self.get_user_attribute_from_response(r, 'name')
        enabled = self.get_user_attribute_from_response(r, 'enabled')
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%s' % id_,
            token=token,
            body={
                'user': {
                    'name': name,
                    'username': 'new_username',
                    'enabled': enabled,
                },
            },
            expected_status=200)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual('new_username', user.get('username'))

    def test_username_is_always_returned_create(self):
        """Username is set as the value of name if no username is provided.

        This matches the v2.0 spec where we really should be using username
        and not name.
        """
        r = self.create_user()

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual(user.get('name'), user.get('username'))

    def test_username_is_always_returned_get(self):
        """Username is set as the value of name if no username is provided.

        This matches the v2.0 spec where we really should be using username
        and not name.
        """
        token = self.get_scoped_token()

        r = self.create_user()

        id_ = self.get_user_attribute_from_response(r, 'id')
        r = self.admin_request(path='/v2.0/users/%s' % id_, token=token)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual(user.get('name'), user.get('username'))

    def test_username_is_always_returned_get_by_name(self):
        """Username is set as the value of name if no username is provided.

        This matches the v2.0 spec where we really should be using username
        and not name.
        """
        token = self.get_scoped_token()

        r = self.create_user()

        name = self.get_user_attribute_from_response(r, 'name')
        r = self.admin_request(path='/v2.0/users?name=%s' % name, token=token)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual(user.get('name'), user.get('username'))

    def test_username_is_always_returned_update_no_username_provided(self):
        """Username is set as the value of name if no username is provided.

        This matches the v2.0 spec where we really should be using username
        and not name.
        """
        token = self.get_scoped_token()

        r = self.create_user()

        id_ = self.get_user_attribute_from_response(r, 'id')
        name = self.get_user_attribute_from_response(r, 'name')
        enabled = self.get_user_attribute_from_response(r, 'enabled')
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%s' % id_,
            token=token,
            body={
                'user': {
                    'name': name,
                    'enabled': enabled,
                },
            },
            expected_status=200)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual(user.get('name'), user.get('username'))

    def test_updated_username_is_returned(self):
        """Username is set as the value of name if no username is provided.

        This matches the v2.0 spec where we really should be using username
        and not name.
        """
        token = self.get_scoped_token()

        r = self.create_user()

        id_ = self.get_user_attribute_from_response(r, 'id')
        name = self.get_user_attribute_from_response(r, 'name')
        enabled = self.get_user_attribute_from_response(r, 'enabled')
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%s' % id_,
            token=token,
            body={
                'user': {
                    'name': name,
                    'enabled': enabled,
                },
            },
            expected_status=200)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual(user.get('name'), user.get('username'))

    def test_username_can_be_used_instead_of_name_create(self):
        token = self.get_scoped_token()

        r = self.admin_request(
            method='POST',
            path='/v2.0/users',
            token=token,
            body={
                'user': {
                    'username': uuid.uuid4().hex,
                    'enabled': True,
                },
            },
            expected_status=200)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual(user.get('name'), user.get('username'))

    def test_username_can_be_used_instead_of_name_update(self):
        token = self.get_scoped_token()

        r = self.create_user()

        id_ = self.get_user_attribute_from_response(r, 'id')
        new_username = uuid.uuid4().hex
        enabled = self.get_user_attribute_from_response(r, 'enabled')
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%s' % id_,
            token=token,
            body={
                'user': {
                    'username': new_username,
                    'enabled': enabled,
                },
            },
            expected_status=200)

        self.assertValidUserResponse(r)

        user = self.get_user_from_response(r)
        self.assertEqual(new_username, user.get('name'))
        self.assertEqual(user.get('name'), user.get('username'))


class RestfulTestCase(rest.RestfulTestCase):

    def setUp(self):
        super(RestfulTestCase, self).setUp()

        # TODO(termie): add an admin user to the fixtures and use that user
        # override the fixtures, for now
        self.assignment_api.add_role_to_user_and_project(
            self.user_foo['id'],
            self.tenant_bar['id'],
            self.role_admin['id'])


class V2TestCase(RestfulTestCase, CoreApiTests, LegacyV2UsernameTests):
    def _get_user_id(self, r):
        return r['user']['id']

    def _get_role_name(self, r):
        return r['roles'][0]['name']

    def _get_role_id(self, r):
        return r['roles'][0]['id']

    def _get_project_id(self, r):
        return r['tenant']['id']

    def _get_token_id(self, r):
        return r.result['access']['token']['id']

    def assertNoRoles(self, r):
        self.assertEqual([], r['roles'])

    def assertValidErrorResponse(self, r):
        self.assertIsNotNone(r.result.get('error'))
        self.assertValidError(r.result['error'])
        self.assertEqual(r.result['error']['code'], r.status_code)

    def assertValidExtension(self, extension, expected):
        super(V2TestCase, self).assertValidExtension(extension)
        descriptions = [ext['description'] for ext in six.itervalues(expected)]
        description = extension.get('description')
        self.assertIsNotNone(description)
        self.assertIn(description, descriptions)
        self.assertIsNotNone(extension.get('links'))
        self.assertNotEmpty(extension.get('links'))
        for link in extension.get('links'):
            self.assertValidExtensionLink(link)

    def assertValidExtensionListResponse(self, r, expected):
        self.assertIsNotNone(r.result.get('extensions'))
        self.assertIsNotNone(r.result['extensions'].get('values'))
        self.assertNotEmpty(r.result['extensions'].get('values'))
        for extension in r.result['extensions']['values']:
            self.assertValidExtension(extension, expected)

    def assertValidExtensionResponse(self, r, expected):
        self.assertValidExtension(r.result.get('extension'), expected)

    def assertValidUser(self, user):
        super(V2TestCase, self).assertValidUser(user)
        self.assertNotIn('default_project_id', user)
        if 'tenantId' in user:
            # NOTE(morganfainberg): tenantId should never be "None", it gets
            # filtered out of the object if it is there. This is suspenders
            # and a belt check to avoid unintended regressions.
            self.assertIsNotNone(user.get('tenantId'))

    def assertValidAuthenticationResponse(self, r,
                                          require_service_catalog=False):
        self.assertIsNotNone(r.result.get('access'))
        self.assertIsNotNone(r.result['access'].get('token'))
        self.assertIsNotNone(r.result['access'].get('user'))

        # validate token
        self.assertIsNotNone(r.result['access']['token'].get('id'))
        self.assertIsNotNone(r.result['access']['token'].get('expires'))
        tenant = r.result['access']['token'].get('tenant')
        if tenant is not None:
            # validate tenant
            self.assertIsNotNone(tenant.get('id'))
            self.assertIsNotNone(tenant.get('name'))

        # validate user
        self.assertIsNotNone(r.result['access']['user'].get('id'))
        self.assertIsNotNone(r.result['access']['user'].get('name'))

        if require_service_catalog:
            # roles are only provided with a service catalog
            roles = r.result['access']['user'].get('roles')
            self.assertNotEmpty(roles)
            for role in roles:
                self.assertIsNotNone(role.get('name'))

        serviceCatalog = r.result['access'].get('serviceCatalog')
        # validate service catalog
        if require_service_catalog:
            self.assertIsNotNone(serviceCatalog)
        if serviceCatalog is not None:
            self.assertIsInstance(serviceCatalog, list)
            if require_service_catalog:
                self.assertNotEmpty(serviceCatalog)
            for service in r.result['access']['serviceCatalog']:
                # validate service
                self.assertIsNotNone(service.get('name'))
                self.assertIsNotNone(service.get('type'))

                # services contain at least one endpoint
                self.assertIsNotNone(service.get('endpoints'))
                self.assertNotEmpty(service['endpoints'])
                for endpoint in service['endpoints']:
                    # validate service endpoint
                    self.assertIsNotNone(endpoint.get('publicURL'))

    def assertValidTenantListResponse(self, r):
        self.assertIsNotNone(r.result.get('tenants'))
        self.assertNotEmpty(r.result['tenants'])
        for tenant in r.result['tenants']:
            self.assertValidTenant(tenant)
            self.assertIsNotNone(tenant.get('enabled'))
            self.assertIn(tenant.get('enabled'), [True, False])

    def assertValidUserResponse(self, r):
        self.assertIsNotNone(r.result.get('user'))
        self.assertValidUser(r.result['user'])

    def assertValidTenantResponse(self, r):
        self.assertIsNotNone(r.result.get('tenant'))
        self.assertValidTenant(r.result['tenant'])

    def assertValidRoleListResponse(self, r):
        self.assertIsNotNone(r.result.get('roles'))
        self.assertNotEmpty(r.result['roles'])
        for role in r.result['roles']:
            self.assertValidRole(role)

    def assertValidVersion(self, version):
        super(V2TestCase, self).assertValidVersion(version)

        self.assertIsNotNone(version.get('links'))
        self.assertNotEmpty(version.get('links'))
        for link in version.get('links'):
            self.assertIsNotNone(link.get('rel'))
            self.assertIsNotNone(link.get('href'))

        self.assertIsNotNone(version.get('media-types'))
        self.assertNotEmpty(version.get('media-types'))
        for media in version.get('media-types'):
            self.assertIsNotNone(media.get('base'))
            self.assertIsNotNone(media.get('type'))

    def assertValidMultipleChoiceResponse(self, r):
        self.assertIsNotNone(r.result.get('versions'))
        self.assertIsNotNone(r.result['versions'].get('values'))
        self.assertNotEmpty(r.result['versions']['values'])
        for version in r.result['versions']['values']:
            self.assertValidVersion(version)

    def assertValidVersionResponse(self, r):
        self.assertValidVersion(r.result.get('version'))

    def assertValidEndpointListResponse(self, r):
        self.assertIsNotNone(r.result.get('endpoints'))
        self.assertNotEmpty(r.result['endpoints'])
        for endpoint in r.result['endpoints']:
            self.assertIsNotNone(endpoint.get('id'))
            self.assertIsNotNone(endpoint.get('name'))
            self.assertIsNotNone(endpoint.get('type'))
            self.assertIsNotNone(endpoint.get('publicURL'))
            self.assertIsNotNone(endpoint.get('internalURL'))
            self.assertIsNotNone(endpoint.get('adminURL'))

    def get_user_from_response(self, r):
        return r.result.get('user')

    def get_user_attribute_from_response(self, r, attribute_name):
        return r.result['user'][attribute_name]

    def test_service_crud_requires_auth(self):
        """Service CRUD should return unauthorized without an X-Auth-Token."""
        # values here don't matter because it will be unauthorized before
        # they're checked (bug 1006822).
        service_path = '/v2.0/OS-KSADM/services/%s' % uuid.uuid4().hex
        service_body = {
            'OS-KSADM:service': {
                'name': uuid.uuid4().hex,
                'type': uuid.uuid4().hex,
            },
        }

        r = self.admin_request(method='GET',
                               path='/v2.0/OS-KSADM/services',
                               expected_status=http_client.UNAUTHORIZED)
        self.assertValidErrorResponse(r)

        r = self.admin_request(method='POST',
                               path='/v2.0/OS-KSADM/services',
                               body=service_body,
                               expected_status=http_client.UNAUTHORIZED)
        self.assertValidErrorResponse(r)

        r = self.admin_request(method='GET',
                               path=service_path,
                               expected_status=http_client.UNAUTHORIZED)
        self.assertValidErrorResponse(r)

        r = self.admin_request(method='DELETE',
                               path=service_path,
                               expected_status=http_client.UNAUTHORIZED)
        self.assertValidErrorResponse(r)

    def test_user_role_list_requires_auth(self):
        """User role list return unauthorized without an X-Auth-Token."""
        # values here don't matter because it will be unauthorized before
        # they're checked (bug 1006815).
        path = '/v2.0/tenants/%(tenant_id)s/users/%(user_id)s/roles' % {
            'tenant_id': uuid.uuid4().hex,
            'user_id': uuid.uuid4().hex,
        }

        r = self.admin_request(path=path,
                               expected_status=http_client.UNAUTHORIZED)
        self.assertValidErrorResponse(r)

    def test_fetch_revocation_list_nonadmin_fails(self):
        self.admin_request(
            method='GET',
            path='/v2.0/tokens/revoked',
            expected_status=http_client.UNAUTHORIZED)

    def test_fetch_revocation_list_admin_200(self):
        token = self.get_scoped_token()
        r = self.admin_request(
            method='GET',
            path='/v2.0/tokens/revoked',
            token=token,
            expected_status=200)
        self.assertValidRevocationListResponse(r)

    def assertValidRevocationListResponse(self, response):
        self.assertIsNotNone(response.result['signed'])

    def _fetch_parse_revocation_list(self):

        token1 = self.get_scoped_token()

        # TODO(morganfainberg): Because this is making a restful call to the
        # app a change to UTCNOW via mock.patch will not affect the returned
        # token. The only surefire way to ensure there is not a transient bug
        # based upon when the second token is issued is with a sleep. This
        # issue all stems from the limited resolution (no microseconds) on the
        # expiry time of tokens and the way revocation events utilizes token
        # expiry to revoke individual tokens. This is a stop-gap until all
        # associated issues with resolution on expiration and revocation events
        # are resolved.
        time.sleep(1)

        token2 = self.get_scoped_token()

        self.admin_request(method='DELETE',
                           path='/v2.0/tokens/%s' % token2,
                           token=token1)

        r = self.admin_request(
            method='GET',
            path='/v2.0/tokens/revoked',
            token=token1,
            expected_status=200)
        signed_text = r.result['signed']

        data_json = cms.cms_verify(signed_text, CONF.signing.certfile,
                                   CONF.signing.ca_certs)

        data = json.loads(data_json)

        return (data, token2)

    def test_fetch_revocation_list_md5(self):
        """If the server is configured for md5, then the revocation list has
           tokens hashed with MD5.
        """

        # The default hash algorithm is md5.
        hash_algorithm = 'md5'

        (data, token) = self._fetch_parse_revocation_list()
        token_hash = cms.cms_hash_token(token, mode=hash_algorithm)
        self.assertThat(token_hash, matchers.Equals(data['revoked'][0]['id']))

    def test_fetch_revocation_list_sha256(self):
        """If the server is configured for sha256, then the revocation list has
           tokens hashed with SHA256
        """

        hash_algorithm = 'sha256'
        self.config_fixture.config(group='token',
                                   hash_algorithm=hash_algorithm)

        (data, token) = self._fetch_parse_revocation_list()
        token_hash = cms.cms_hash_token(token, mode=hash_algorithm)
        self.assertThat(token_hash, matchers.Equals(data['revoked'][0]['id']))

    def test_create_update_user_invalid_enabled_type(self):
        # Enforce usage of boolean for 'enabled' field
        token = self.get_scoped_token()

        # Test CREATE request
        r = self.admin_request(
            method='POST',
            path='/v2.0/users',
            body={
                'user': {
                    'name': uuid.uuid4().hex,
                    'password': uuid.uuid4().hex,
                    # In JSON, "true|false" are not boolean
                    'enabled': "true",
                },
            },
            token=token,
            expected_status=http_client.BAD_REQUEST)
        self.assertValidErrorResponse(r)

        # Test UPDATE request
        r = self.admin_request(
            method='PUT',
            path='/v2.0/users/%(user_id)s' % {
                 'user_id': self.user_foo['id'],
            },
            body={
                'user': {
                    # In JSON, "true|false" are not boolean
                    'enabled': "true",
                },
            },
            token=token,
            expected_status=http_client.BAD_REQUEST)
        self.assertValidErrorResponse(r)

    def test_authenticating_a_user_with_an_OSKSADM_password(self):
        token = self.get_scoped_token()

        username = uuid.uuid4().hex
        password = uuid.uuid4().hex

        # create the user
        r = self.admin_request(
            method='POST',
            path='/v2.0/users',
            body={
                'user': {
                    'name': username,
                    'OS-KSADM:password': password,
                    'enabled': True,
                },
            },
            token=token)

        # successfully authenticate
        self.public_request(
            method='POST',
            path='/v2.0/tokens',
            body={
                'auth': {
                    'passwordCredentials': {
                        'username': username,
                        'password': password,
                    },
                },
            },
            expected_status=200)

        # ensure password doesn't leak
        user_id = r.result['user']['id']
        r = self.admin_request(
            method='GET',
            path='/v2.0/users/%s' % user_id,
            token=token,
            expected_status=200)
        self.assertNotIn('OS-KSADM:password', r.result['user'])

    def test_updating_a_user_with_an_OSKSADM_password(self):
        token = self.get_scoped_token()

        user_id = self.user_foo['id']
        password = uuid.uuid4().hex

        # update the user
        self.admin_request(
            method='PUT',
            path='/v2.0/users/%s/OS-KSADM/password' % user_id,
            body={
                'user': {
                   'password': password,
                },
            },
            token=token,
            expected_status=200)

        # successfully authenticate
        self.public_request(
            method='POST',
            path='/v2.0/tokens',
            body={
                'auth': {
                    'passwordCredentials': {
                        'username': self.user_foo['name'],
                        'password': password,
                    },
                },
            },
            expected_status=200)


class RevokeApiTestCase(V2TestCase):
    def config_overrides(self):
        super(RevokeApiTestCase, self).config_overrides()
        self.config_fixture.config(group='revoke', driver='kvs')
        self.config_fixture.config(
            group='token',
            provider='pki',
            revoke_by_id=False)

    def test_fetch_revocation_list_admin_200(self):
        self.skipTest('Revoke API disables revocation_list.')

    def test_fetch_revocation_list_md5(self):
        self.skipTest('Revoke API disables revocation_list.')

    def test_fetch_revocation_list_sha256(self):
        self.skipTest('Revoke API disables revocation_list.')


class TestFernetTokenProviderV2(RestfulTestCase):

    def setUp(self):
        super(TestFernetTokenProviderV2, self).setUp()
        self.useFixture(ksfixtures.KeyRepository(self.config_fixture))

    # Used by RestfulTestCase
    def _get_token_id(self, r):
        return r.result['access']['token']['id']

    def new_project_ref(self):
        return {'id': uuid.uuid4().hex,
                'name': uuid.uuid4().hex,
                'description': uuid.uuid4().hex,
                'domain_id': 'default',
                'enabled': True}

    def config_overrides(self):
        super(TestFernetTokenProviderV2, self).config_overrides()
        self.config_fixture.config(group='token', provider='fernet')

    def test_authenticate_unscoped_token(self):
        unscoped_token = self.get_unscoped_token()
        # Fernet token must be of length 255 per usability requirements
        self.assertLess(len(unscoped_token), 255)

    def test_validate_unscoped_token(self):
        # Grab an admin token to validate with
        project_ref = self.new_project_ref()
        self.resource_api.create_project(project_ref['id'], project_ref)
        self.assignment_api.add_role_to_user_and_project(self.user_foo['id'],
                                                         project_ref['id'],
                                                         self.role_admin['id'])
        admin_token = self.get_scoped_token(tenant_id=project_ref['id'])
        unscoped_token = self.get_unscoped_token()
        path = ('/v2.0/tokens/%s' % unscoped_token)
        self.admin_request(
            method='GET',
            path=path,
            token=admin_token,
            expected_status=200)

    def test_authenticate_scoped_token(self):
        project_ref = self.new_project_ref()
        self.resource_api.create_project(project_ref['id'], project_ref)
        self.assignment_api.add_role_to_user_and_project(
            self.user_foo['id'], project_ref['id'], self.role_service['id'])
        token = self.get_scoped_token(tenant_id=project_ref['id'])
        # Fernet token must be of length 255 per usability requirements
        self.assertLess(len(token), 255)

    def test_validate_scoped_token(self):
        project_ref = self.new_project_ref()
        self.resource_api.create_project(project_ref['id'], project_ref)
        self.assignment_api.add_role_to_user_and_project(self.user_foo['id'],
                                                         project_ref['id'],
                                                         self.role_admin['id'])
        project2_ref = self.new_project_ref()
        self.resource_api.create_project(project2_ref['id'], project2_ref)
        self.assignment_api.add_role_to_user_and_project(
            self.user_foo['id'], project2_ref['id'], self.role_member['id'])
        admin_token = self.get_scoped_token(tenant_id=project_ref['id'])
        member_token = self.get_scoped_token(tenant_id=project2_ref['id'])
        path = ('/v2.0/tokens/%s?belongsTo=%s' % (member_token,
                project2_ref['id']))
        # Validate token belongs to project
        self.admin_request(
            method='GET',
            path=path,
            token=admin_token,
            expected_status=200)

    def test_token_authentication_and_validation(self):
        """Test token authentication for Fernet token provider.

        Verify that token authentication returns validate response code and
        valid token belongs to project.
        """
        project_ref = self.new_project_ref()
        self.resource_api.create_project(project_ref['id'], project_ref)
        unscoped_token = self.get_unscoped_token()
        self.assignment_api.add_role_to_user_and_project(self.user_foo['id'],
                                                         project_ref['id'],
                                                         self.role_admin['id'])
        r = self.public_request(
            method='POST',
            path='/v2.0/tokens',
            body={
                'auth': {
                    'tenantName': project_ref['name'],
                    'token': {
                        'id': unscoped_token.encode('ascii')
                    }
                }
            },
            expected_status=200)

        token_id = self._get_token_id(r)
        path = ('/v2.0/tokens/%s?belongsTo=%s' % (token_id, project_ref['id']))
        # Validate token belongs to project
        self.admin_request(
            method='GET',
            path=path,
            token=CONF.admin_token,
            expected_status=200)

    def test_rescoped_tokens_maintain_original_expiration(self):
        project_ref = self.new_project_ref()
        self.resource_api.create_project(project_ref['id'], project_ref)
        self.assignment_api.add_role_to_user_and_project(self.user_foo['id'],
                                                         project_ref['id'],
                                                         self.role_admin['id'])
        resp = self.public_request(
            method='POST',
            path='/v2.0/tokens',
            body={
                'auth': {
                    'tenantName': project_ref['name'],
                    'passwordCredentials': {
                        'username': self.user_foo['name'],
                        'password': self.user_foo['password']
                    }
                }
            },
            # NOTE(lbragstad): This test may need to be refactored if Keystone
            # decides to disallow rescoping using a scoped token.
            expected_status=200)
        original_token = resp.result['access']['token']['id']
        original_expiration = resp.result['access']['token']['expires']

        resp = self.public_request(
            method='POST',
            path='/v2.0/tokens',
            body={
                'auth': {
                    'tenantName': project_ref['name'],
                    'token': {
                        'id': original_token,
                    }
                }
            },
            expected_status=200)
        rescoped_token = resp.result['access']['token']['id']
        rescoped_expiration = resp.result['access']['token']['expires']
        self.assertNotEqual(original_token, rescoped_token)
        self.assertEqual(original_expiration, rescoped_expiration)