summaryrefslogtreecommitdiffstats
path: root/keystone-moon/keystone/tests/unit/test_v3_auth.py
blob: 96f0ff1f1772ab20c9f9dd5569d2db1a3a5f8c27 (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
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
# 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 copy
import datetime
import json
import operator
import uuid

from keystoneclient.common import cms
import mock
from oslo_config import cfg
from oslo_utils import timeutils
from six.moves import range
from testtools import matchers
from testtools import testcase

from keystone import auth
from keystone.common import utils
from keystone import exception
from keystone.policy.backends import rules
from keystone.tests import unit as tests
from keystone.tests.unit import ksfixtures
from keystone.tests.unit import test_v3

CONF = cfg.CONF


class TestAuthInfo(test_v3.AuthTestMixin, testcase.TestCase):
    def setUp(self):
        super(TestAuthInfo, self).setUp()
        auth.controllers.load_auth_methods()

    def test_missing_auth_methods(self):
        auth_data = {'identity': {}}
        auth_data['identity']['token'] = {'id': uuid.uuid4().hex}
        self.assertRaises(exception.ValidationError,
                          auth.controllers.AuthInfo.create,
                          None,
                          auth_data)

    def test_unsupported_auth_method(self):
        auth_data = {'methods': ['abc']}
        auth_data['abc'] = {'test': 'test'}
        auth_data = {'identity': auth_data}
        self.assertRaises(exception.AuthMethodNotSupported,
                          auth.controllers.AuthInfo.create,
                          None,
                          auth_data)

    def test_missing_auth_method_data(self):
        auth_data = {'methods': ['password']}
        auth_data = {'identity': auth_data}
        self.assertRaises(exception.ValidationError,
                          auth.controllers.AuthInfo.create,
                          None,
                          auth_data)

    def test_project_name_no_domain(self):
        auth_data = self.build_authentication_request(
            username='test',
            password='test',
            project_name='abc')['auth']
        self.assertRaises(exception.ValidationError,
                          auth.controllers.AuthInfo.create,
                          None,
                          auth_data)

    def test_both_project_and_domain_in_scope(self):
        auth_data = self.build_authentication_request(
            user_id='test',
            password='test',
            project_name='test',
            domain_name='test')['auth']
        self.assertRaises(exception.ValidationError,
                          auth.controllers.AuthInfo.create,
                          None,
                          auth_data)

    def test_get_method_names_duplicates(self):
        auth_data = self.build_authentication_request(
            token='test',
            user_id='test',
            password='test')['auth']
        auth_data['identity']['methods'] = ['password', 'token',
                                            'password', 'password']
        context = None
        auth_info = auth.controllers.AuthInfo.create(context, auth_data)
        self.assertEqual(['password', 'token'],
                         auth_info.get_method_names())

    def test_get_method_data_invalid_method(self):
        auth_data = self.build_authentication_request(
            user_id='test',
            password='test')['auth']
        context = None
        auth_info = auth.controllers.AuthInfo.create(context, auth_data)

        method_name = uuid.uuid4().hex
        self.assertRaises(exception.ValidationError,
                          auth_info.get_method_data,
                          method_name)


class TokenAPITests(object):
    # Why is this not just setUp? Because TokenAPITests is not a test class
    # itself. If TokenAPITests became a subclass of the testcase, it would get
    # called by the enumerate-tests-in-file code. The way the functions get
    # resolved in Python for multiple inheritance means that a setUp in this
    # would get skipped by the testrunner.
    def doSetUp(self):
        r = self.v3_authenticate_token(self.build_authentication_request(
            username=self.user['name'],
            user_domain_id=self.domain_id,
            password=self.user['password']))
        self.v3_token_data = r.result
        self.v3_token = r.headers.get('X-Subject-Token')
        self.headers = {'X-Subject-Token': r.headers.get('X-Subject-Token')}

    def test_default_fixture_scope_token(self):
        self.assertIsNotNone(self.get_scoped_token())

    def test_v3_v2_intermix_non_default_domain_failed(self):
        v3_token = self.get_requested_token(self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password']))

        # now validate the v3 token with v2 API
        self.admin_request(
            path='/v2.0/tokens/%s' % v3_token,
            token=CONF.admin_token,
            method='GET',
            expected_status=401)

    def test_v3_v2_intermix_new_default_domain(self):
        # If the default_domain_id config option is changed, then should be
        # able to validate a v3 token with user in the new domain.

        # 1) Create a new domain for the user.
        new_domain = {
            'description': uuid.uuid4().hex,
            'enabled': True,
            'id': uuid.uuid4().hex,
            'name': uuid.uuid4().hex,
        }
        self.resource_api.create_domain(new_domain['id'], new_domain)

        # 2) Create user in new domain.
        new_user_password = uuid.uuid4().hex
        new_user = {
            'name': uuid.uuid4().hex,
            'domain_id': new_domain['id'],
            'password': new_user_password,
            'email': uuid.uuid4().hex,
        }
        new_user = self.identity_api.create_user(new_user)

        # 3) Update the default_domain_id config option to the new domain
        self.config_fixture.config(
            group='identity',
            default_domain_id=new_domain['id'])

        # 4) Get a token using v3 API.
        v3_token = self.get_requested_token(self.build_authentication_request(
            user_id=new_user['id'],
            password=new_user_password))

        # 5) Validate token using v2 API.
        self.admin_request(
            path='/v2.0/tokens/%s' % v3_token,
            token=CONF.admin_token,
            method='GET')

    def test_v3_v2_intermix_domain_scoped_token_failed(self):
        # grant the domain role to user
        self.put(
            path='/domains/%s/users/%s/roles/%s' % (
                self.domain['id'], self.user['id'], self.role['id']))

        # generate a domain-scoped v3 token
        v3_token = self.get_requested_token(self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            domain_id=self.domain['id']))

        # domain-scoped tokens are not supported by v2
        self.admin_request(
            method='GET',
            path='/v2.0/tokens/%s' % v3_token,
            token=CONF.admin_token,
            expected_status=401)

    def test_v3_v2_intermix_non_default_project_failed(self):
        # self.project is in a non-default domain
        v3_token = self.get_requested_token(self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            project_id=self.project['id']))

        # v2 cannot reference projects outside the default domain
        self.admin_request(
            method='GET',
            path='/v2.0/tokens/%s' % v3_token,
            token=CONF.admin_token,
            expected_status=401)

    def test_v3_v2_intermix_non_default_user_failed(self):
        self.assignment_api.create_grant(
            self.role['id'],
            user_id=self.user['id'],
            project_id=self.default_domain_project['id'])

        # self.user is in a non-default domain
        v3_token = self.get_requested_token(self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=self.default_domain_project['id']))

        # v2 cannot reference projects outside the default domain
        self.admin_request(
            method='GET',
            path='/v2.0/tokens/%s' % v3_token,
            token=CONF.admin_token,
            expected_status=401)

    def test_v3_v2_intermix_domain_scope_failed(self):
        self.assignment_api.create_grant(
            self.role['id'],
            user_id=self.default_domain_user['id'],
            domain_id=self.domain['id'])

        v3_token = self.get_requested_token(self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            domain_id=self.domain['id']))

        # v2 cannot reference projects outside the default domain
        self.admin_request(
            path='/v2.0/tokens/%s' % v3_token,
            token=CONF.admin_token,
            method='GET',
            expected_status=401)

    def test_v3_v2_unscoped_token_intermix(self):
        r = self.v3_authenticate_token(self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password']))
        self.assertValidUnscopedTokenResponse(r)
        v3_token_data = r.result
        v3_token = r.headers.get('X-Subject-Token')

        # now validate the v3 token with v2 API
        r = self.admin_request(
            path='/v2.0/tokens/%s' % v3_token,
            token=CONF.admin_token,
            method='GET')
        v2_token_data = r.result

        self.assertEqual(v2_token_data['access']['user']['id'],
                         v3_token_data['token']['user']['id'])
        # v2 token time has not fraction of second precision so
        # just need to make sure the non fraction part agrees
        self.assertIn(v2_token_data['access']['token']['expires'][:-1],
                      v3_token_data['token']['expires_at'])

    def test_v3_v2_token_intermix(self):
        # FIXME(gyee): PKI tokens are not interchangeable because token
        # data is baked into the token itself.
        r = self.v3_authenticate_token(self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            project_id=self.default_domain_project['id']))
        self.assertValidProjectScopedTokenResponse(r)
        v3_token_data = r.result
        v3_token = r.headers.get('X-Subject-Token')

        # now validate the v3 token with v2 API
        r = self.admin_request(
            method='GET',
            path='/v2.0/tokens/%s' % v3_token,
            token=CONF.admin_token)
        v2_token_data = r.result

        self.assertEqual(v2_token_data['access']['user']['id'],
                         v3_token_data['token']['user']['id'])
        # v2 token time has not fraction of second precision so
        # just need to make sure the non fraction part agrees
        self.assertIn(v2_token_data['access']['token']['expires'][:-1],
                      v3_token_data['token']['expires_at'])
        self.assertEqual(v2_token_data['access']['user']['roles'][0]['name'],
                         v3_token_data['token']['roles'][0]['name'])

    def test_v2_v3_unscoped_token_intermix(self):
        r = self.admin_request(
            method='POST',
            path='/v2.0/tokens',
            body={
                'auth': {
                    'passwordCredentials': {
                        'userId': self.default_domain_user['id'],
                        'password': self.default_domain_user['password']
                    }
                }
            })
        v2_token_data = r.result
        v2_token = v2_token_data['access']['token']['id']

        r = self.get('/auth/tokens', headers={'X-Subject-Token': v2_token})
        # FIXME(dolph): Due to bug 1476329, v2 tokens validated on v3 are
        # missing timezones, so they will not pass this assertion.
        # self.assertValidUnscopedTokenResponse(r)
        v3_token_data = r.result

        self.assertEqual(v2_token_data['access']['user']['id'],
                         v3_token_data['token']['user']['id'])
        # v2 token time has not fraction of second precision so
        # just need to make sure the non fraction part agrees
        self.assertIn(v2_token_data['access']['token']['expires'][-1],
                      v3_token_data['token']['expires_at'])

    def test_v2_v3_token_intermix(self):
        r = self.admin_request(
            path='/v2.0/tokens',
            method='POST',
            body={
                'auth': {
                    'passwordCredentials': {
                        'userId': self.default_domain_user['id'],
                        'password': self.default_domain_user['password']
                    },
                    'tenantId': self.default_domain_project['id']
                }
            })
        v2_token_data = r.result
        v2_token = v2_token_data['access']['token']['id']

        r = self.get('/auth/tokens', headers={'X-Subject-Token': v2_token})
        # FIXME(dolph): Due to bug 1476329, v2 tokens validated on v3 are
        # missing timezones, so they will not pass this assertion.
        # self.assertValidProjectScopedTokenResponse(r)
        v3_token_data = r.result

        self.assertEqual(v2_token_data['access']['user']['id'],
                         v3_token_data['token']['user']['id'])
        # v2 token time has not fraction of second precision so
        # just need to make sure the non fraction part agrees
        self.assertIn(v2_token_data['access']['token']['expires'][-1],
                      v3_token_data['token']['expires_at'])
        self.assertEqual(v2_token_data['access']['user']['roles'][0]['name'],
                         v3_token_data['token']['roles'][0]['name'])

        v2_issued_at = timeutils.parse_isotime(
            v2_token_data['access']['token']['issued_at'])
        v3_issued_at = timeutils.parse_isotime(
            v3_token_data['token']['issued_at'])

        self.assertEqual(v2_issued_at, v3_issued_at)

    def test_v2_token_deleted_on_v3(self):
        # Create a v2 token.
        body = {
            'auth': {
                'passwordCredentials': {
                    'userId': self.default_domain_user['id'],
                    'password': self.default_domain_user['password']
                },
                'tenantId': self.default_domain_project['id']
            }
        }
        r = self.admin_request(
            path='/v2.0/tokens', method='POST', body=body)
        v2_token = r.result['access']['token']['id']

        # Delete the v2 token using v3.
        resp = self.delete(
            '/auth/tokens', headers={'X-Subject-Token': v2_token})
        self.assertEqual(resp.status_code, 204)

        # Attempting to use the deleted token on v2 should fail.
        self.admin_request(
            path='/v2.0/tenants', method='GET', token=v2_token,
            expected_status=401)

    def test_rescoping_token(self):
        expires = self.v3_token_data['token']['expires_at']

        # rescope the token
        r = self.v3_authenticate_token(self.build_authentication_request(
            token=self.v3_token,
            project_id=self.project_id))
        self.assertValidProjectScopedTokenResponse(r)

        # ensure token expiration stayed the same
        self.assertEqual(expires, r.result['token']['expires_at'])

    def test_check_token(self):
        self.head('/auth/tokens', headers=self.headers, expected_status=200)

    def test_validate_token(self):
        r = self.get('/auth/tokens', headers=self.headers)
        self.assertValidUnscopedTokenResponse(r)

    def test_validate_token_nocatalog(self):
        v3_token = self.get_requested_token(self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=self.project['id']))
        r = self.get(
            '/auth/tokens?nocatalog',
            headers={'X-Subject-Token': v3_token})
        self.assertValidProjectScopedTokenResponse(r, require_catalog=False)


class AllowRescopeScopedTokenDisabledTests(test_v3.RestfulTestCase):
    def config_overrides(self):
        super(AllowRescopeScopedTokenDisabledTests, self).config_overrides()
        self.config_fixture.config(
            group='token',
            allow_rescope_scoped_token=False)

    def test_rescoping_v3_to_v3_disabled(self):
        self.v3_authenticate_token(
            self.build_authentication_request(
                token=self.get_scoped_token(),
                project_id=self.project_id),
            expected_status=403)

    def _v2_token(self):
        body = {
            'auth': {
                "tenantId": self.default_domain_project['id'],
                'passwordCredentials': {
                    'userId': self.default_domain_user['id'],
                    'password': self.default_domain_user['password']
                }
            }}
        resp = self.admin_request(path='/v2.0/tokens',
                                  method='POST',
                                  body=body)
        v2_token_data = resp.result
        return v2_token_data

    def _v2_token_from_token(self, token):
        body = {
            'auth': {
                "tenantId": self.project['id'],
                "token": token
            }}
        self.admin_request(path='/v2.0/tokens',
                           method='POST',
                           body=body,
                           expected_status=403)

    def test_rescoping_v2_to_v3_disabled(self):
        token = self._v2_token()
        self.v3_authenticate_token(
            self.build_authentication_request(
                token=token['access']['token']['id'],
                project_id=self.project_id),
            expected_status=403)

    def test_rescoping_v3_to_v2_disabled(self):
        token = {'id': self.get_scoped_token()}
        self._v2_token_from_token(token)

    def test_rescoping_v2_to_v2_disabled(self):
        token = self._v2_token()
        self._v2_token_from_token(token['access']['token'])

    def test_rescoped_domain_token_disabled(self):

        self.domainA = self.new_domain_ref()
        self.resource_api.create_domain(self.domainA['id'], self.domainA)
        self.assignment_api.create_grant(self.role['id'],
                                         user_id=self.user['id'],
                                         domain_id=self.domainA['id'])
        unscoped_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.user['id'],
                password=self.user['password']))
        # Get a domain-scoped token from the unscoped token
        domain_scoped_token = self.get_requested_token(
            self.build_authentication_request(
                token=unscoped_token,
                domain_id=self.domainA['id']))
        self.v3_authenticate_token(
            self.build_authentication_request(
                token=domain_scoped_token,
                project_id=self.project_id),
            expected_status=403)


class TestPKITokenAPIs(test_v3.RestfulTestCase, TokenAPITests):
    def config_overrides(self):
        super(TestPKITokenAPIs, self).config_overrides()
        self.config_fixture.config(group='token', provider='pki')

    def setUp(self):
        super(TestPKITokenAPIs, self).setUp()
        self.doSetUp()

    def verify_token(self, *args, **kwargs):
        return cms.verify_token(*args, **kwargs)

    def test_v3_token_id(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        resp = self.v3_authenticate_token(auth_data)
        token_data = resp.result
        token_id = resp.headers.get('X-Subject-Token')
        self.assertIn('expires_at', token_data['token'])

        decoded_token = self.verify_token(token_id, CONF.signing.certfile,
                                          CONF.signing.ca_certs)
        decoded_token_dict = json.loads(decoded_token)

        token_resp_dict = json.loads(resp.body)

        self.assertEqual(decoded_token_dict, token_resp_dict)
        # should be able to validate hash PKI token as well
        hash_token_id = cms.cms_hash_token(token_id)
        headers = {'X-Subject-Token': hash_token_id}
        resp = self.get('/auth/tokens', headers=headers)
        expected_token_data = resp.result
        self.assertDictEqual(expected_token_data, token_data)

    def test_v3_v2_hashed_pki_token_intermix(self):
        auth_data = self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            project_id=self.default_domain_project['id'])
        resp = self.v3_authenticate_token(auth_data)
        token_data = resp.result
        token = resp.headers.get('X-Subject-Token')

        # should be able to validate a hash PKI token in v2 too
        token = cms.cms_hash_token(token)
        path = '/v2.0/tokens/%s' % (token)
        resp = self.admin_request(path=path,
                                  token=CONF.admin_token,
                                  method='GET')
        v2_token = resp.result
        self.assertEqual(v2_token['access']['user']['id'],
                         token_data['token']['user']['id'])
        # v2 token time has not fraction of second precision so
        # just need to make sure the non fraction part agrees
        self.assertIn(v2_token['access']['token']['expires'][:-1],
                      token_data['token']['expires_at'])
        self.assertEqual(v2_token['access']['user']['roles'][0]['id'],
                         token_data['token']['roles'][0]['id'])


class TestPKIZTokenAPIs(TestPKITokenAPIs):
    def config_overrides(self):
        super(TestPKIZTokenAPIs, self).config_overrides()
        self.config_fixture.config(group='token', provider='pkiz')

    def verify_token(self, *args, **kwargs):
        return cms.pkiz_verify(*args, **kwargs)


class TestUUIDTokenAPIs(test_v3.RestfulTestCase, TokenAPITests):
    def config_overrides(self):
        super(TestUUIDTokenAPIs, self).config_overrides()
        self.config_fixture.config(group='token', provider='uuid')

    def setUp(self):
        super(TestUUIDTokenAPIs, self).setUp()
        self.doSetUp()

    def test_v3_token_id(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        resp = self.v3_authenticate_token(auth_data)
        token_data = resp.result
        token_id = resp.headers.get('X-Subject-Token')
        self.assertIn('expires_at', token_data['token'])
        self.assertFalse(cms.is_asn1_token(token_id))


class TestFernetTokenAPIs(test_v3.RestfulTestCase, TokenAPITests):
    def config_overrides(self):
        super(TestFernetTokenAPIs, self).config_overrides()
        self.config_fixture.config(group='token', provider='fernet')
        self.useFixture(ksfixtures.KeyRepository(self.config_fixture))

    def setUp(self):
        super(TestFernetTokenAPIs, self).setUp()
        self.doSetUp()


class TestTokenRevokeSelfAndAdmin(test_v3.RestfulTestCase):
    """Test token revoke using v3 Identity API by token owner and admin."""

    def load_sample_data(self):
        """Load Sample Data for Test Cases.

        Two domains, domainA and domainB
        Two users in domainA, userNormalA and userAdminA
        One user in domainB, userAdminB

        """
        super(TestTokenRevokeSelfAndAdmin, self).load_sample_data()
        # DomainA setup
        self.domainA = self.new_domain_ref()
        self.resource_api.create_domain(self.domainA['id'], self.domainA)

        self.userAdminA = self.new_user_ref(domain_id=self.domainA['id'])
        password = self.userAdminA['password']
        self.userAdminA = self.identity_api.create_user(self.userAdminA)
        self.userAdminA['password'] = password

        self.userNormalA = self.new_user_ref(
            domain_id=self.domainA['id'])
        password = self.userNormalA['password']
        self.userNormalA = self.identity_api.create_user(self.userNormalA)
        self.userNormalA['password'] = password

        self.assignment_api.create_grant(self.role['id'],
                                         user_id=self.userAdminA['id'],
                                         domain_id=self.domainA['id'])

    def config_overrides(self):
        super(TestTokenRevokeSelfAndAdmin, self).config_overrides()
        self.config_fixture.config(
            group='oslo_policy',
            policy_file=tests.dirs.etc('policy.v3cloudsample.json'))

    def test_user_revokes_own_token(self):
        user_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.userNormalA['id'],
                password=self.userNormalA['password'],
                user_domain_id=self.domainA['id']))
        self.assertNotEmpty(user_token)
        headers = {'X-Subject-Token': user_token}

        adminA_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.userAdminA['id'],
                password=self.userAdminA['password'],
                domain_name=self.domainA['name']))

        self.head('/auth/tokens', headers=headers, expected_status=200,
                  token=adminA_token)
        self.head('/auth/tokens', headers=headers, expected_status=200,
                  token=user_token)
        self.delete('/auth/tokens', headers=headers, expected_status=204,
                    token=user_token)
        # invalid X-Auth-Token and invalid X-Subject-Token (401)
        self.head('/auth/tokens', headers=headers, expected_status=401,
                  token=user_token)
        # invalid X-Auth-Token and invalid X-Subject-Token (401)
        self.delete('/auth/tokens', headers=headers, expected_status=401,
                    token=user_token)
        # valid X-Auth-Token and invalid X-Subject-Token (404)
        self.delete('/auth/tokens', headers=headers, expected_status=404,
                    token=adminA_token)
        # valid X-Auth-Token and invalid X-Subject-Token (404)
        self.head('/auth/tokens', headers=headers, expected_status=404,
                  token=adminA_token)

    def test_adminA_revokes_userA_token(self):
        user_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.userNormalA['id'],
                password=self.userNormalA['password'],
                user_domain_id=self.domainA['id']))
        self.assertNotEmpty(user_token)
        headers = {'X-Subject-Token': user_token}

        adminA_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.userAdminA['id'],
                password=self.userAdminA['password'],
                domain_name=self.domainA['name']))

        self.head('/auth/tokens', headers=headers, expected_status=200,
                  token=adminA_token)
        self.head('/auth/tokens', headers=headers, expected_status=200,
                  token=user_token)
        self.delete('/auth/tokens', headers=headers, expected_status=204,
                    token=adminA_token)
        # invalid X-Auth-Token and invalid X-Subject-Token (401)
        self.head('/auth/tokens', headers=headers, expected_status=401,
                  token=user_token)
        # valid X-Auth-Token and invalid X-Subject-Token (404)
        self.delete('/auth/tokens', headers=headers, expected_status=404,
                    token=adminA_token)
        # valid X-Auth-Token and invalid X-Subject-Token (404)
        self.head('/auth/tokens', headers=headers, expected_status=404,
                  token=adminA_token)

    def test_adminB_fails_revoking_userA_token(self):
        # DomainB setup
        self.domainB = self.new_domain_ref()
        self.resource_api.create_domain(self.domainB['id'], self.domainB)
        self.userAdminB = self.new_user_ref(domain_id=self.domainB['id'])
        password = self.userAdminB['password']
        self.userAdminB = self.identity_api.create_user(self.userAdminB)
        self.userAdminB['password'] = password
        self.assignment_api.create_grant(self.role['id'],
                                         user_id=self.userAdminB['id'],
                                         domain_id=self.domainB['id'])

        user_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.userNormalA['id'],
                password=self.userNormalA['password'],
                user_domain_id=self.domainA['id']))
        headers = {'X-Subject-Token': user_token}

        adminB_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.userAdminB['id'],
                password=self.userAdminB['password'],
                domain_name=self.domainB['name']))

        self.head('/auth/tokens', headers=headers, expected_status=403,
                  token=adminB_token)
        self.delete('/auth/tokens', headers=headers, expected_status=403,
                    token=adminB_token)


class TestTokenRevokeById(test_v3.RestfulTestCase):
    """Test token revocation on the v3 Identity API."""

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

    def setUp(self):
        """Setup for Token Revoking Test Cases.

        As well as the usual housekeeping, create a set of domains,
        users, groups, roles and projects for the subsequent tests:

        - Two domains: A & B
        - Three users (1, 2 and 3)
        - Three groups (1, 2 and 3)
        - Two roles (1 and 2)
        - DomainA owns user1, domainB owns user2 and user3
        - DomainA owns group1 and group2, domainB owns group3
        - User1 and user2 are members of group1
        - User3 is a member of group2
        - Two projects: A & B, both in domainA
        - Group1 has role1 on Project A and B, meaning that user1 and user2
          will get these roles by virtue of membership
        - User1, 2 and 3 have role1 assigned to projectA
        - Group1 has role1 on Project A and B, meaning that user1 and user2
          will get role1 (duplicated) by virtue of membership
        - User1 has role2 assigned to domainA

        """
        super(TestTokenRevokeById, self).setUp()

        # Start by creating a couple of domains and projects
        self.domainA = self.new_domain_ref()
        self.resource_api.create_domain(self.domainA['id'], self.domainA)
        self.domainB = self.new_domain_ref()
        self.resource_api.create_domain(self.domainB['id'], self.domainB)
        self.projectA = self.new_project_ref(domain_id=self.domainA['id'])
        self.resource_api.create_project(self.projectA['id'], self.projectA)
        self.projectB = self.new_project_ref(domain_id=self.domainA['id'])
        self.resource_api.create_project(self.projectB['id'], self.projectB)

        # Now create some users
        self.user1 = self.new_user_ref(
            domain_id=self.domainA['id'])
        password = self.user1['password']
        self.user1 = self.identity_api.create_user(self.user1)
        self.user1['password'] = password

        self.user2 = self.new_user_ref(
            domain_id=self.domainB['id'])
        password = self.user2['password']
        self.user2 = self.identity_api.create_user(self.user2)
        self.user2['password'] = password

        self.user3 = self.new_user_ref(
            domain_id=self.domainB['id'])
        password = self.user3['password']
        self.user3 = self.identity_api.create_user(self.user3)
        self.user3['password'] = password

        self.group1 = self.new_group_ref(
            domain_id=self.domainA['id'])
        self.group1 = self.identity_api.create_group(self.group1)

        self.group2 = self.new_group_ref(
            domain_id=self.domainA['id'])
        self.group2 = self.identity_api.create_group(self.group2)

        self.group3 = self.new_group_ref(
            domain_id=self.domainB['id'])
        self.group3 = self.identity_api.create_group(self.group3)

        self.identity_api.add_user_to_group(self.user1['id'],
                                            self.group1['id'])
        self.identity_api.add_user_to_group(self.user2['id'],
                                            self.group1['id'])
        self.identity_api.add_user_to_group(self.user3['id'],
                                            self.group2['id'])

        self.role1 = self.new_role_ref()
        self.role_api.create_role(self.role1['id'], self.role1)
        self.role2 = self.new_role_ref()
        self.role_api.create_role(self.role2['id'], self.role2)

        self.assignment_api.create_grant(self.role2['id'],
                                         user_id=self.user1['id'],
                                         domain_id=self.domainA['id'])
        self.assignment_api.create_grant(self.role1['id'],
                                         user_id=self.user1['id'],
                                         project_id=self.projectA['id'])
        self.assignment_api.create_grant(self.role1['id'],
                                         user_id=self.user2['id'],
                                         project_id=self.projectA['id'])
        self.assignment_api.create_grant(self.role1['id'],
                                         user_id=self.user3['id'],
                                         project_id=self.projectA['id'])
        self.assignment_api.create_grant(self.role1['id'],
                                         group_id=self.group1['id'],
                                         project_id=self.projectA['id'])

    def test_unscoped_token_remains_valid_after_role_assignment(self):
        unscoped_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.user1['id'],
                password=self.user1['password']))

        scoped_token = self.get_requested_token(
            self.build_authentication_request(
                token=unscoped_token,
                project_id=self.projectA['id']))

        # confirm both tokens are valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': unscoped_token},
                  expected_status=200)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': scoped_token},
                  expected_status=200)

        # create a new role
        role = self.new_role_ref()
        self.role_api.create_role(role['id'], role)

        # assign a new role
        self.put(
            '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' % {
                'project_id': self.projectA['id'],
                'user_id': self.user1['id'],
                'role_id': role['id']})

        # both tokens should remain valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': unscoped_token},
                  expected_status=200)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': scoped_token},
                  expected_status=200)

    def test_deleting_user_grant_revokes_token(self):
        """Test deleting a user grant revokes token.

        Test Plan:

        - Get a token for user1, scoped to ProjectA
        - Delete the grant user1 has on ProjectA
        - Check token is no longer valid

        """
        auth_data = self.build_authentication_request(
            user_id=self.user1['id'],
            password=self.user1['password'],
            project_id=self.projectA['id'])
        token = self.get_requested_token(auth_data)
        # Confirm token is valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=200)
        # Delete the grant, which should invalidate the token
        grant_url = (
            '/projects/%(project_id)s/users/%(user_id)s/'
            'roles/%(role_id)s' % {
                'project_id': self.projectA['id'],
                'user_id': self.user1['id'],
                'role_id': self.role1['id']})
        self.delete(grant_url)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=404)

    def role_data_fixtures(self):
        self.projectC = self.new_project_ref(domain_id=self.domainA['id'])
        self.resource_api.create_project(self.projectC['id'], self.projectC)
        self.user4 = self.new_user_ref(domain_id=self.domainB['id'])
        password = self.user4['password']
        self.user4 = self.identity_api.create_user(self.user4)
        self.user4['password'] = password
        self.user5 = self.new_user_ref(
            domain_id=self.domainA['id'])
        password = self.user5['password']
        self.user5 = self.identity_api.create_user(self.user5)
        self.user5['password'] = password
        self.user6 = self.new_user_ref(
            domain_id=self.domainA['id'])
        password = self.user6['password']
        self.user6 = self.identity_api.create_user(self.user6)
        self.user6['password'] = password
        self.identity_api.add_user_to_group(self.user5['id'],
                                            self.group1['id'])
        self.assignment_api.create_grant(self.role1['id'],
                                         group_id=self.group1['id'],
                                         project_id=self.projectB['id'])
        self.assignment_api.create_grant(self.role2['id'],
                                         user_id=self.user4['id'],
                                         project_id=self.projectC['id'])
        self.assignment_api.create_grant(self.role1['id'],
                                         user_id=self.user6['id'],
                                         project_id=self.projectA['id'])
        self.assignment_api.create_grant(self.role1['id'],
                                         user_id=self.user6['id'],
                                         domain_id=self.domainA['id'])

    def test_deleting_role_revokes_token(self):
        """Test deleting a role revokes token.

            Add some additional test data, namely:
             - A third project (project C)
             - Three additional users - user4 owned by domainB and user5 and 6
               owned by domainA (different domain ownership should not affect
               the test results, just provided to broaden test coverage)
             - User5 is a member of group1
             - Group1 gets an additional assignment - role1 on projectB as
               well as its existing role1 on projectA
             - User4 has role2 on Project C
             - User6 has role1 on projectA and domainA
             - This allows us to create 5 tokens by virtue of different types
               of role assignment:
               - user1, scoped to ProjectA by virtue of user role1 assignment
               - user5, scoped to ProjectB by virtue of group role1 assignment
               - user4, scoped to ProjectC by virtue of user role2 assignment
               - user6, scoped to ProjectA by virtue of user role1 assignment
               - user6, scoped to DomainA by virtue of user role1 assignment
             - role1 is then deleted
             - Check the tokens on Project A and B, and DomainA are revoked,
               but not the one for Project C

        """

        self.role_data_fixtures()

        # Now we are ready to start issuing requests
        auth_data = self.build_authentication_request(
            user_id=self.user1['id'],
            password=self.user1['password'],
            project_id=self.projectA['id'])
        tokenA = self.get_requested_token(auth_data)
        auth_data = self.build_authentication_request(
            user_id=self.user5['id'],
            password=self.user5['password'],
            project_id=self.projectB['id'])
        tokenB = self.get_requested_token(auth_data)
        auth_data = self.build_authentication_request(
            user_id=self.user4['id'],
            password=self.user4['password'],
            project_id=self.projectC['id'])
        tokenC = self.get_requested_token(auth_data)
        auth_data = self.build_authentication_request(
            user_id=self.user6['id'],
            password=self.user6['password'],
            project_id=self.projectA['id'])
        tokenD = self.get_requested_token(auth_data)
        auth_data = self.build_authentication_request(
            user_id=self.user6['id'],
            password=self.user6['password'],
            domain_id=self.domainA['id'])
        tokenE = self.get_requested_token(auth_data)
        # Confirm tokens are valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenA},
                  expected_status=200)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenB},
                  expected_status=200)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenC},
                  expected_status=200)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenD},
                  expected_status=200)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenE},
                  expected_status=200)

        # Delete the role, which should invalidate the tokens
        role_url = '/roles/%s' % self.role1['id']
        self.delete(role_url)

        # Check the tokens that used role1 is invalid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenA},
                  expected_status=404)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenB},
                  expected_status=404)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenD},
                  expected_status=404)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenE},
                  expected_status=404)

        # ...but the one using role2 is still valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': tokenC},
                  expected_status=200)

    def test_domain_user_role_assignment_maintains_token(self):
        """Test user-domain role assignment maintains existing token.

        Test Plan:

        - Get a token for user1, scoped to ProjectA
        - Create a grant for user1 on DomainB
        - Check token is still valid

        """
        auth_data = self.build_authentication_request(
            user_id=self.user1['id'],
            password=self.user1['password'],
            project_id=self.projectA['id'])
        token = self.get_requested_token(auth_data)
        # Confirm token is valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=200)
        # Assign a role, which should not affect the token
        grant_url = (
            '/domains/%(domain_id)s/users/%(user_id)s/'
            'roles/%(role_id)s' % {
                'domain_id': self.domainB['id'],
                'user_id': self.user1['id'],
                'role_id': self.role1['id']})
        self.put(grant_url)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=200)

    def test_disabling_project_revokes_token(self):
        token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.user3['id'],
                password=self.user3['password'],
                project_id=self.projectA['id']))

        # confirm token is valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=200)

        # disable the project, which should invalidate the token
        self.patch(
            '/projects/%(project_id)s' % {'project_id': self.projectA['id']},
            body={'project': {'enabled': False}})

        # user should no longer have access to the project
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=404)
        self.v3_authenticate_token(
            self.build_authentication_request(
                user_id=self.user3['id'],
                password=self.user3['password'],
                project_id=self.projectA['id']),
            expected_status=401)

    def test_deleting_project_revokes_token(self):
        token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.user3['id'],
                password=self.user3['password'],
                project_id=self.projectA['id']))

        # confirm token is valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=200)

        # delete the project, which should invalidate the token
        self.delete(
            '/projects/%(project_id)s' % {'project_id': self.projectA['id']})

        # user should no longer have access to the project
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=404)
        self.v3_authenticate_token(
            self.build_authentication_request(
                user_id=self.user3['id'],
                password=self.user3['password'],
                project_id=self.projectA['id']),
            expected_status=401)

    def test_deleting_group_grant_revokes_tokens(self):
        """Test deleting a group grant revokes tokens.

        Test Plan:

        - Get a token for user1, scoped to ProjectA
        - Get a token for user2, scoped to ProjectA
        - Get a token for user3, scoped to ProjectA
        - Delete the grant group1 has on ProjectA
        - Check tokens for user1 & user2 are no longer valid,
          since user1 and user2 are members of group1
        - Check token for user3 is invalid too

        """
        auth_data = self.build_authentication_request(
            user_id=self.user1['id'],
            password=self.user1['password'],
            project_id=self.projectA['id'])
        token1 = self.get_requested_token(auth_data)
        auth_data = self.build_authentication_request(
            user_id=self.user2['id'],
            password=self.user2['password'],
            project_id=self.projectA['id'])
        token2 = self.get_requested_token(auth_data)
        auth_data = self.build_authentication_request(
            user_id=self.user3['id'],
            password=self.user3['password'],
            project_id=self.projectA['id'])
        token3 = self.get_requested_token(auth_data)
        # Confirm tokens are valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token1},
                  expected_status=200)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token2},
                  expected_status=200)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token3},
                  expected_status=200)
        # Delete the group grant, which should invalidate the
        # tokens for user1 and user2
        grant_url = (
            '/projects/%(project_id)s/groups/%(group_id)s/'
            'roles/%(role_id)s' % {
                'project_id': self.projectA['id'],
                'group_id': self.group1['id'],
                'role_id': self.role1['id']})
        self.delete(grant_url)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token1},
                  expected_status=404)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token2},
                  expected_status=404)
        # But user3's token should be invalid too as revocation is done for
        # scope role & project
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token3},
                  expected_status=404)

    def test_domain_group_role_assignment_maintains_token(self):
        """Test domain-group role assignment maintains existing token.

        Test Plan:

        - Get a token for user1, scoped to ProjectA
        - Create a grant for group1 on DomainB
        - Check token is still longer valid

        """
        auth_data = self.build_authentication_request(
            user_id=self.user1['id'],
            password=self.user1['password'],
            project_id=self.projectA['id'])
        token = self.get_requested_token(auth_data)
        # Confirm token is valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=200)
        # Delete the grant, which should invalidate the token
        grant_url = (
            '/domains/%(domain_id)s/groups/%(group_id)s/'
            'roles/%(role_id)s' % {
                'domain_id': self.domainB['id'],
                'group_id': self.group1['id'],
                'role_id': self.role1['id']})
        self.put(grant_url)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=200)

    def test_group_membership_changes_revokes_token(self):
        """Test add/removal to/from group revokes token.

        Test Plan:

        - Get a token for user1, scoped to ProjectA
        - Get a token for user2, scoped to ProjectA
        - Remove user1 from group1
        - Check token for user1 is no longer valid
        - Check token for user2 is still valid, even though
          user2 is also part of group1
        - Add user2 to group2
        - Check token for user2 is now no longer valid

        """
        auth_data = self.build_authentication_request(
            user_id=self.user1['id'],
            password=self.user1['password'],
            project_id=self.projectA['id'])
        token1 = self.get_requested_token(auth_data)
        auth_data = self.build_authentication_request(
            user_id=self.user2['id'],
            password=self.user2['password'],
            project_id=self.projectA['id'])
        token2 = self.get_requested_token(auth_data)
        # Confirm tokens are valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token1},
                  expected_status=200)
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token2},
                  expected_status=200)
        # Remove user1 from group1, which should invalidate
        # the token
        self.delete('/groups/%(group_id)s/users/%(user_id)s' % {
            'group_id': self.group1['id'],
            'user_id': self.user1['id']})
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token1},
                  expected_status=404)
        # But user2's token should still be valid
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token2},
                  expected_status=200)
        # Adding user2 to a group should not invalidate token
        self.put('/groups/%(group_id)s/users/%(user_id)s' % {
            'group_id': self.group2['id'],
            'user_id': self.user2['id']})
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token2},
                  expected_status=200)

    def test_removing_role_assignment_does_not_affect_other_users(self):
        """Revoking a role from one user should not affect other users."""

        # This group grant is not needed for the test
        self.delete(
            '/projects/%(project_id)s/groups/%(group_id)s/roles/%(role_id)s' %
            {'project_id': self.projectA['id'],
             'group_id': self.group1['id'],
             'role_id': self.role1['id']})

        user1_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.user1['id'],
                password=self.user1['password'],
                project_id=self.projectA['id']))

        user3_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.user3['id'],
                password=self.user3['password'],
                project_id=self.projectA['id']))

        # delete relationships between user1 and projectA from setUp
        self.delete(
            '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' % {
                'project_id': self.projectA['id'],
                'user_id': self.user1['id'],
                'role_id': self.role1['id']})
        # authorization for the first user should now fail
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': user1_token},
                  expected_status=404)
        self.v3_authenticate_token(
            self.build_authentication_request(
                user_id=self.user1['id'],
                password=self.user1['password'],
                project_id=self.projectA['id']),
            expected_status=401)

        # authorization for the second user should still succeed
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': user3_token},
                  expected_status=200)
        self.v3_authenticate_token(
            self.build_authentication_request(
                user_id=self.user3['id'],
                password=self.user3['password'],
                project_id=self.projectA['id']))

    def test_deleting_project_deletes_grants(self):
        # This is to make it a little bit more pretty with PEP8
        role_path = ('/projects/%(project_id)s/users/%(user_id)s/'
                     'roles/%(role_id)s')
        role_path = role_path % {'user_id': self.user['id'],
                                 'project_id': self.projectA['id'],
                                 'role_id': self.role['id']}

        # grant the user a role on the project
        self.put(role_path)

        # delete the project, which should remove the roles
        self.delete(
            '/projects/%(project_id)s' % {'project_id': self.projectA['id']})

        # Make sure that we get a NotFound(404) when heading that role.
        self.head(role_path, expected_status=404)

    def get_v2_token(self, token=None, project_id=None):
        body = {'auth': {}, }

        if token:
            body['auth']['token'] = {
                'id': token
            }
        else:
            body['auth']['passwordCredentials'] = {
                'username': self.default_domain_user['name'],
                'password': self.default_domain_user['password'],
            }

        if project_id:
            body['auth']['tenantId'] = project_id

        r = self.admin_request(method='POST', path='/v2.0/tokens', body=body)
        return r.json_body['access']['token']['id']

    def test_revoke_v2_token_no_check(self):
        # Test that a V2 token can be revoked without validating it first.

        token = self.get_v2_token()

        self.delete('/auth/tokens',
                    headers={'X-Subject-Token': token},
                    expected_status=204)

        self.head('/auth/tokens',
                  headers={'X-Subject-Token': token},
                  expected_status=404)

    def test_revoke_token_from_token(self):
        # Test that a scoped token can be requested from an unscoped token,
        # the scoped token can be revoked, and the unscoped token remains
        # valid.

        unscoped_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.user1['id'],
                password=self.user1['password']))

        # Get a project-scoped token from the unscoped token
        project_scoped_token = self.get_requested_token(
            self.build_authentication_request(
                token=unscoped_token,
                project_id=self.projectA['id']))

        # Get a domain-scoped token from the unscoped token
        domain_scoped_token = self.get_requested_token(
            self.build_authentication_request(
                token=unscoped_token,
                domain_id=self.domainA['id']))

        # revoke the project-scoped token.
        self.delete('/auth/tokens',
                    headers={'X-Subject-Token': project_scoped_token},
                    expected_status=204)

        # The project-scoped token is invalidated.
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': project_scoped_token},
                  expected_status=404)

        # The unscoped token should still be valid.
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': unscoped_token},
                  expected_status=200)

        # The domain-scoped token should still be valid.
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': domain_scoped_token},
                  expected_status=200)

        # revoke the domain-scoped token.
        self.delete('/auth/tokens',
                    headers={'X-Subject-Token': domain_scoped_token},
                    expected_status=204)

        # The domain-scoped token is invalid.
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': domain_scoped_token},
                  expected_status=404)

        # The unscoped token should still be valid.
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': unscoped_token},
                  expected_status=200)

    def test_revoke_token_from_token_v2(self):
        # Test that a scoped token can be requested from an unscoped token,
        # the scoped token can be revoked, and the unscoped token remains
        # valid.

        # FIXME(blk-u): This isn't working correctly. The scoped token should
        # be revoked. See bug 1347318.

        unscoped_token = self.get_v2_token()

        # Get a project-scoped token from the unscoped token
        project_scoped_token = self.get_v2_token(
            token=unscoped_token, project_id=self.default_domain_project['id'])

        # revoke the project-scoped token.
        self.delete('/auth/tokens',
                    headers={'X-Subject-Token': project_scoped_token},
                    expected_status=204)

        # The project-scoped token is invalidated.
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': project_scoped_token},
                  expected_status=404)

        # The unscoped token should still be valid.
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': unscoped_token},
                  expected_status=200)


class TestTokenRevokeByAssignment(TestTokenRevokeById):

    def config_overrides(self):
        super(TestTokenRevokeById, self).config_overrides()
        self.config_fixture.config(
            group='revoke',
            driver='kvs')
        self.config_fixture.config(
            group='token',
            provider='uuid',
            revoke_by_id=True)

    def test_removing_role_assignment_keeps_other_project_token_groups(self):
        """Test assignment isolation.

        Revoking a group role from one project should not invalidate all group
        users' tokens
        """
        self.assignment_api.create_grant(self.role1['id'],
                                         group_id=self.group1['id'],
                                         project_id=self.projectB['id'])

        project_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.user1['id'],
                password=self.user1['password'],
                project_id=self.projectB['id']))

        other_project_token = self.get_requested_token(
            self.build_authentication_request(
                user_id=self.user1['id'],
                password=self.user1['password'],
                project_id=self.projectA['id']))

        self.assignment_api.delete_grant(self.role1['id'],
                                         group_id=self.group1['id'],
                                         project_id=self.projectB['id'])

        # authorization for the projectA should still succeed
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': other_project_token},
                  expected_status=200)
        # while token for the projectB should not
        self.head('/auth/tokens',
                  headers={'X-Subject-Token': project_token},
                  expected_status=404)
        revoked_tokens = [
            t['id'] for t in self.token_provider_api.list_revoked_tokens()]
        # token is in token revocation list
        self.assertIn(project_token, revoked_tokens)


class TestTokenRevokeApi(TestTokenRevokeById):
    EXTENSION_NAME = 'revoke'
    EXTENSION_TO_ADD = 'revoke_extension'

    """Test token revocation on the v3 Identity API."""
    def config_overrides(self):
        super(TestTokenRevokeApi, self).config_overrides()
        self.config_fixture.config(group='revoke', driver='kvs')
        self.config_fixture.config(
            group='token',
            provider='pki',
            revoke_by_id=False)

    def assertValidDeletedProjectResponse(self, events_response, project_id):
        events = events_response['events']
        self.assertEqual(1, len(events))
        self.assertEqual(project_id, events[0]['project_id'])
        self.assertIsNotNone(events[0]['issued_before'])
        self.assertIsNotNone(events_response['links'])
        del (events_response['events'][0]['issued_before'])
        del (events_response['links'])
        expected_response = {'events': [{'project_id': project_id}]}
        self.assertEqual(expected_response, events_response)

    def assertDomainInList(self, events_response, domain_id):
        events = events_response['events']
        self.assertEqual(1, len(events))
        self.assertEqual(domain_id, events[0]['domain_id'])
        self.assertIsNotNone(events[0]['issued_before'])
        self.assertIsNotNone(events_response['links'])
        del (events_response['events'][0]['issued_before'])
        del (events_response['links'])
        expected_response = {'events': [{'domain_id': domain_id}]}
        self.assertEqual(expected_response, events_response)

    def assertValidRevokedTokenResponse(self, events_response, **kwargs):
        events = events_response['events']
        self.assertEqual(1, len(events))
        for k, v in kwargs.items():
            self.assertEqual(v, events[0].get(k))
        self.assertIsNotNone(events[0]['issued_before'])
        self.assertIsNotNone(events_response['links'])
        del (events_response['events'][0]['issued_before'])
        del (events_response['links'])

        expected_response = {'events': [kwargs]}
        self.assertEqual(expected_response, events_response)

    def test_revoke_token(self):
        scoped_token = self.get_scoped_token()
        headers = {'X-Subject-Token': scoped_token}
        response = self.get('/auth/tokens', headers=headers,
                            expected_status=200).json_body['token']

        self.delete('/auth/tokens', headers=headers, expected_status=204)
        self.head('/auth/tokens', headers=headers, expected_status=404)
        events_response = self.get('/OS-REVOKE/events',
                                   expected_status=200).json_body
        self.assertValidRevokedTokenResponse(events_response,
                                             audit_id=response['audit_ids'][0])

    def test_revoke_v2_token(self):
        token = self.get_v2_token()
        headers = {'X-Subject-Token': token}
        response = self.get('/auth/tokens', headers=headers,
                            expected_status=200).json_body['token']
        self.delete('/auth/tokens', headers=headers, expected_status=204)
        self.head('/auth/tokens', headers=headers, expected_status=404)
        events_response = self.get('/OS-REVOKE/events',
                                   expected_status=200).json_body

        self.assertValidRevokedTokenResponse(
            events_response,
            audit_id=response['audit_ids'][0])

    def test_revoke_by_id_false_410(self):
        self.get('/auth/tokens/OS-PKI/revoked', expected_status=410)

    def test_list_delete_project_shows_in_event_list(self):
        self.role_data_fixtures()
        events = self.get('/OS-REVOKE/events',
                          expected_status=200).json_body['events']
        self.assertEqual([], events)
        self.delete(
            '/projects/%(project_id)s' % {'project_id': self.projectA['id']})
        events_response = self.get('/OS-REVOKE/events',
                                   expected_status=200).json_body

        self.assertValidDeletedProjectResponse(events_response,
                                               self.projectA['id'])

    def test_disable_domain_shows_in_event_list(self):
        events = self.get('/OS-REVOKE/events',
                          expected_status=200).json_body['events']
        self.assertEqual([], events)
        disable_body = {'domain': {'enabled': False}}
        self.patch(
            '/domains/%(project_id)s' % {'project_id': self.domainA['id']},
            body=disable_body)

        events = self.get('/OS-REVOKE/events',
                          expected_status=200).json_body

        self.assertDomainInList(events, self.domainA['id'])

    def assertEventDataInList(self, events, **kwargs):
        found = False
        for e in events:
            for key, value in kwargs.items():
                try:
                    if e[key] != value:
                        break
                except KeyError:
                    # Break the loop and present a nice error instead of
                    # KeyError
                    break
            else:
                # If the value of the event[key] matches the value of the kwarg
                # for each item in kwargs, the event was fully matched and
                # the assertTrue below should succeed.
                found = True
        self.assertTrue(found,
                        'event with correct values not in list, expected to '
                        'find event with key-value pairs. Expected: '
                        '"%(expected)s" Events: "%(events)s"' %
                        {'expected': ','.join(
                            ["'%s=%s'" % (k, v) for k, v in kwargs.items()]),
                         'events': events})

    def test_list_delete_token_shows_in_event_list(self):
        self.role_data_fixtures()
        events = self.get('/OS-REVOKE/events',
                          expected_status=200).json_body['events']
        self.assertEqual([], events)

        scoped_token = self.get_scoped_token()
        headers = {'X-Subject-Token': scoped_token}
        auth_req = self.build_authentication_request(token=scoped_token)
        response = self.v3_authenticate_token(auth_req)
        token2 = response.json_body['token']
        headers2 = {'X-Subject-Token': response.headers['X-Subject-Token']}

        response = self.v3_authenticate_token(auth_req)
        response.json_body['token']
        headers3 = {'X-Subject-Token': response.headers['X-Subject-Token']}

        self.head('/auth/tokens', headers=headers, expected_status=200)
        self.head('/auth/tokens', headers=headers2, expected_status=200)
        self.head('/auth/tokens', headers=headers3, expected_status=200)

        self.delete('/auth/tokens', headers=headers, expected_status=204)
        # NOTE(ayoung): not deleting token3, as it should be deleted
        # by previous
        events_response = self.get('/OS-REVOKE/events',
                                   expected_status=200).json_body
        events = events_response['events']
        self.assertEqual(1, len(events))
        self.assertEventDataInList(
            events,
            audit_id=token2['audit_ids'][1])
        self.head('/auth/tokens', headers=headers, expected_status=404)
        self.head('/auth/tokens', headers=headers2, expected_status=200)
        self.head('/auth/tokens', headers=headers3, expected_status=200)

    def test_list_with_filter(self):

        self.role_data_fixtures()
        events = self.get('/OS-REVOKE/events',
                          expected_status=200).json_body['events']
        self.assertEqual(0, len(events))

        scoped_token = self.get_scoped_token()
        headers = {'X-Subject-Token': scoped_token}
        auth = self.build_authentication_request(token=scoped_token)
        headers2 = {'X-Subject-Token': self.get_requested_token(auth)}
        self.delete('/auth/tokens', headers=headers, expected_status=204)
        self.delete('/auth/tokens', headers=headers2, expected_status=204)

        events = self.get('/OS-REVOKE/events',
                          expected_status=200).json_body['events']

        self.assertEqual(2, len(events))
        future = utils.isotime(timeutils.utcnow() +
                               datetime.timedelta(seconds=1000))

        events = self.get('/OS-REVOKE/events?since=%s' % (future),
                          expected_status=200).json_body['events']
        self.assertEqual(0, len(events))


class TestAuthExternalDisabled(test_v3.RestfulTestCase):
    def config_overrides(self):
        super(TestAuthExternalDisabled, self).config_overrides()
        self.config_fixture.config(
            group='auth',
            methods=['password', 'token'])

    def test_remote_user_disabled(self):
        api = auth.controllers.Auth()
        remote_user = '%s@%s' % (self.user['name'], self.domain['name'])
        context, auth_info, auth_context = self.build_external_auth_request(
            remote_user)
        self.assertRaises(exception.Unauthorized,
                          api.authenticate,
                          context,
                          auth_info,
                          auth_context)


class TestAuthExternalDomain(test_v3.RestfulTestCase):
    content_type = 'json'

    def config_overrides(self):
        super(TestAuthExternalDomain, self).config_overrides()
        self.kerberos = False
        self.auth_plugin_config_override(external='Domain')

    def test_remote_user_with_realm(self):
        api = auth.controllers.Auth()
        remote_user = self.user['name']
        remote_domain = self.domain['name']
        context, auth_info, auth_context = self.build_external_auth_request(
            remote_user, remote_domain=remote_domain, kerberos=self.kerberos)

        api.authenticate(context, auth_info, auth_context)
        self.assertEqual(self.user['id'], auth_context['user_id'])

        # Now test to make sure the user name can, itself, contain the
        # '@' character.
        user = {'name': 'myname@mydivision'}
        self.identity_api.update_user(self.user['id'], user)
        remote_user = user['name']
        context, auth_info, auth_context = self.build_external_auth_request(
            remote_user, remote_domain=remote_domain, kerberos=self.kerberos)

        api.authenticate(context, auth_info, auth_context)
        self.assertEqual(self.user['id'], auth_context['user_id'])

    def test_project_id_scoped_with_remote_user(self):
        self.config_fixture.config(group='token', bind=['kerberos'])
        auth_data = self.build_authentication_request(
            project_id=self.project['id'],
            kerberos=self.kerberos)
        remote_user = self.user['name']
        remote_domain = self.domain['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'REMOTE_DOMAIN': remote_domain,
                                             'AUTH_TYPE': 'Negotiate'})
        r = self.v3_authenticate_token(auth_data)
        token = self.assertValidProjectScopedTokenResponse(r)
        self.assertEqual(self.user['name'], token['bind']['kerberos'])

    def test_unscoped_bind_with_remote_user(self):
        self.config_fixture.config(group='token', bind=['kerberos'])
        auth_data = self.build_authentication_request(kerberos=self.kerberos)
        remote_user = self.user['name']
        remote_domain = self.domain['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'REMOTE_DOMAIN': remote_domain,
                                             'AUTH_TYPE': 'Negotiate'})
        r = self.v3_authenticate_token(auth_data)
        token = self.assertValidUnscopedTokenResponse(r)
        self.assertEqual(self.user['name'], token['bind']['kerberos'])


class TestAuthExternalDefaultDomain(test_v3.RestfulTestCase):
    content_type = 'json'

    def config_overrides(self):
        super(TestAuthExternalDefaultDomain, self).config_overrides()
        self.kerberos = False
        self.auth_plugin_config_override(
            external='keystone.auth.plugins.external.DefaultDomain')

    def test_remote_user_with_default_domain(self):
        api = auth.controllers.Auth()
        remote_user = self.default_domain_user['name']
        context, auth_info, auth_context = self.build_external_auth_request(
            remote_user, kerberos=self.kerberos)

        api.authenticate(context, auth_info, auth_context)
        self.assertEqual(self.default_domain_user['id'],
                         auth_context['user_id'])

        # Now test to make sure the user name can, itself, contain the
        # '@' character.
        user = {'name': 'myname@mydivision'}
        self.identity_api.update_user(self.default_domain_user['id'], user)
        remote_user = user['name']
        context, auth_info, auth_context = self.build_external_auth_request(
            remote_user, kerberos=self.kerberos)

        api.authenticate(context, auth_info, auth_context)
        self.assertEqual(self.default_domain_user['id'],
                         auth_context['user_id'])

    def test_project_id_scoped_with_remote_user(self):
        self.config_fixture.config(group='token', bind=['kerberos'])
        auth_data = self.build_authentication_request(
            project_id=self.default_domain_project['id'],
            kerberos=self.kerberos)
        remote_user = self.default_domain_user['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'AUTH_TYPE': 'Negotiate'})
        r = self.v3_authenticate_token(auth_data)
        token = self.assertValidProjectScopedTokenResponse(r)
        self.assertEqual(self.default_domain_user['name'],
                         token['bind']['kerberos'])

    def test_unscoped_bind_with_remote_user(self):
        self.config_fixture.config(group='token', bind=['kerberos'])
        auth_data = self.build_authentication_request(kerberos=self.kerberos)
        remote_user = self.default_domain_user['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'AUTH_TYPE': 'Negotiate'})
        r = self.v3_authenticate_token(auth_data)
        token = self.assertValidUnscopedTokenResponse(r)
        self.assertEqual(self.default_domain_user['name'],
                         token['bind']['kerberos'])


class TestAuthKerberos(TestAuthExternalDomain):

    def config_overrides(self):
        super(TestAuthKerberos, self).config_overrides()
        self.kerberos = True
        self.auth_plugin_config_override(
            methods=['kerberos', 'password', 'token'])


class TestAuth(test_v3.RestfulTestCase):

    def test_unscoped_token_with_user_id(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidUnscopedTokenResponse(r)

    def test_unscoped_token_with_user_domain_id(self):
        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_id=self.domain['id'],
            password=self.user['password'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidUnscopedTokenResponse(r)

    def test_unscoped_token_with_user_domain_name(self):
        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_name=self.domain['name'],
            password=self.user['password'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidUnscopedTokenResponse(r)

    def test_project_id_scoped_token_with_user_id(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=self.project['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectScopedTokenResponse(r)

    def _second_project_as_default(self):
        ref = self.new_project_ref(domain_id=self.domain_id)
        r = self.post('/projects', body={'project': ref})
        project = self.assertValidProjectResponse(r, ref)

        # grant the user a role on the project
        self.put(
            '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' % {
                'user_id': self.user['id'],
                'project_id': project['id'],
                'role_id': self.role['id']})

        # set the user's preferred project
        body = {'user': {'default_project_id': project['id']}}
        r = self.patch('/users/%(user_id)s' % {
            'user_id': self.user['id']},
            body=body)
        self.assertValidUserResponse(r)

        return project

    def test_default_project_id_scoped_token_with_user_id(self):
        project = self._second_project_as_default()

        # attempt to authenticate without requesting a project
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectScopedTokenResponse(r)
        self.assertEqual(project['id'], r.result['token']['project']['id'])

    def test_default_project_id_scoped_token_with_user_id_no_catalog(self):
        project = self._second_project_as_default()

        # attempt to authenticate without requesting a project
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        r = self.post('/auth/tokens?nocatalog', body=auth_data, noauth=True)
        self.assertValidProjectScopedTokenResponse(r, require_catalog=False)
        self.assertEqual(project['id'], r.result['token']['project']['id'])

    def test_explicit_unscoped_token(self):
        self._second_project_as_default()

        # attempt to authenticate without requesting a project
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            unscoped="unscoped")
        r = self.post('/auth/tokens', body=auth_data, noauth=True)

        self.assertIsNone(r.result['token'].get('project'))
        self.assertIsNone(r.result['token'].get('domain'))
        self.assertIsNone(r.result['token'].get('scope'))

    def test_implicit_project_id_scoped_token_with_user_id_no_catalog(self):
        # attempt to authenticate without requesting a project
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=self.project['id'])
        r = self.post('/auth/tokens?nocatalog', body=auth_data, noauth=True)
        self.assertValidProjectScopedTokenResponse(r, require_catalog=False)
        self.assertEqual(self.project['id'],
                         r.result['token']['project']['id'])

    def test_auth_catalog_attributes(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=self.project['id'])
        r = self.v3_authenticate_token(auth_data)

        catalog = r.result['token']['catalog']
        self.assertEqual(1, len(catalog))
        catalog = catalog[0]

        self.assertEqual(self.service['id'], catalog['id'])
        self.assertEqual(self.service['name'], catalog['name'])
        self.assertEqual(self.service['type'], catalog['type'])

        endpoint = catalog['endpoints']
        self.assertEqual(1, len(endpoint))
        endpoint = endpoint[0]

        self.assertEqual(self.endpoint['id'], endpoint['id'])
        self.assertEqual(self.endpoint['interface'], endpoint['interface'])
        self.assertEqual(self.endpoint['region_id'], endpoint['region_id'])
        self.assertEqual(self.endpoint['url'], endpoint['url'])

    def _check_disabled_endpoint_result(self, catalog, disabled_endpoint_id):
        endpoints = catalog[0]['endpoints']
        endpoint_ids = [ep['id'] for ep in endpoints]
        self.assertEqual([self.endpoint_id], endpoint_ids)

    def test_auth_catalog_disabled_service(self):
        """On authenticate, get a catalog that excludes disabled services."""
        # although the child endpoint is enabled, the service is disabled
        self.assertTrue(self.endpoint['enabled'])
        self.catalog_api.update_service(
            self.endpoint['service_id'], {'enabled': False})
        service = self.catalog_api.get_service(self.endpoint['service_id'])
        self.assertFalse(service['enabled'])

        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=self.project['id'])
        r = self.v3_authenticate_token(auth_data)

        self.assertEqual([], r.result['token']['catalog'])

    def test_auth_catalog_disabled_endpoint(self):
        """On authenticate, get a catalog that excludes disabled endpoints."""

        # Create a disabled endpoint that's like the enabled one.
        disabled_endpoint_ref = copy.copy(self.endpoint)
        disabled_endpoint_id = uuid.uuid4().hex
        disabled_endpoint_ref.update({
            'id': disabled_endpoint_id,
            'enabled': False,
            'interface': 'internal'
        })
        self.catalog_api.create_endpoint(disabled_endpoint_id,
                                         disabled_endpoint_ref)

        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=self.project['id'])
        r = self.v3_authenticate_token(auth_data)

        self._check_disabled_endpoint_result(r.result['token']['catalog'],
                                             disabled_endpoint_id)

    def test_project_id_scoped_token_with_user_id_401(self):
        project = self.new_project_ref(domain_id=self.domain_id)
        self.resource_api.create_project(project['id'], project)

        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=project['id'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_user_and_group_roles_scoped_token(self):
        """Test correct roles are returned in scoped token.

        Test Plan:

        - Create a domain, with 1 project, 2 users (user1 and user2)
          and 2 groups (group1 and group2)
        - Make user1 a member of group1, user2 a member of group2
        - Create 8 roles, assigning them to each of the 8 combinations
          of users/groups on domain/project
        - Get a project scoped token for user1, checking that the right
          two roles are returned (one directly assigned, one by virtue
          of group membership)
        - Repeat this for a domain scoped token
        - Make user1 also a member of group2
        - Get another scoped token making sure the additional role
          shows up
        - User2 is just here as a spoiler, to make sure we don't get
          any roles uniquely assigned to it returned in any of our
          tokens

        """

        domainA = self.new_domain_ref()
        self.resource_api.create_domain(domainA['id'], domainA)
        projectA = self.new_project_ref(domain_id=domainA['id'])
        self.resource_api.create_project(projectA['id'], projectA)

        user1 = self.new_user_ref(
            domain_id=domainA['id'])
        password = user1['password']
        user1 = self.identity_api.create_user(user1)
        user1['password'] = password

        user2 = self.new_user_ref(
            domain_id=domainA['id'])
        password = user2['password']
        user2 = self.identity_api.create_user(user2)
        user2['password'] = password

        group1 = self.new_group_ref(
            domain_id=domainA['id'])
        group1 = self.identity_api.create_group(group1)

        group2 = self.new_group_ref(
            domain_id=domainA['id'])
        group2 = self.identity_api.create_group(group2)

        self.identity_api.add_user_to_group(user1['id'],
                                            group1['id'])
        self.identity_api.add_user_to_group(user2['id'],
                                            group2['id'])

        # Now create all the roles and assign them
        role_list = []
        for _ in range(8):
            role = self.new_role_ref()
            self.role_api.create_role(role['id'], role)
            role_list.append(role)

        self.assignment_api.create_grant(role_list[0]['id'],
                                         user_id=user1['id'],
                                         domain_id=domainA['id'])
        self.assignment_api.create_grant(role_list[1]['id'],
                                         user_id=user1['id'],
                                         project_id=projectA['id'])
        self.assignment_api.create_grant(role_list[2]['id'],
                                         user_id=user2['id'],
                                         domain_id=domainA['id'])
        self.assignment_api.create_grant(role_list[3]['id'],
                                         user_id=user2['id'],
                                         project_id=projectA['id'])
        self.assignment_api.create_grant(role_list[4]['id'],
                                         group_id=group1['id'],
                                         domain_id=domainA['id'])
        self.assignment_api.create_grant(role_list[5]['id'],
                                         group_id=group1['id'],
                                         project_id=projectA['id'])
        self.assignment_api.create_grant(role_list[6]['id'],
                                         group_id=group2['id'],
                                         domain_id=domainA['id'])
        self.assignment_api.create_grant(role_list[7]['id'],
                                         group_id=group2['id'],
                                         project_id=projectA['id'])

        # First, get a project scoped token - which should
        # contain the direct user role and the one by virtue
        # of group membership
        auth_data = self.build_authentication_request(
            user_id=user1['id'],
            password=user1['password'],
            project_id=projectA['id'])
        r = self.v3_authenticate_token(auth_data)
        token = self.assertValidScopedTokenResponse(r)
        roles_ids = []
        for ref in token['roles']:
            roles_ids.append(ref['id'])
        self.assertEqual(2, len(token['roles']))
        self.assertIn(role_list[1]['id'], roles_ids)
        self.assertIn(role_list[5]['id'], roles_ids)

        # Now the same thing for a domain scoped token
        auth_data = self.build_authentication_request(
            user_id=user1['id'],
            password=user1['password'],
            domain_id=domainA['id'])
        r = self.v3_authenticate_token(auth_data)
        token = self.assertValidScopedTokenResponse(r)
        roles_ids = []
        for ref in token['roles']:
            roles_ids.append(ref['id'])
        self.assertEqual(2, len(token['roles']))
        self.assertIn(role_list[0]['id'], roles_ids)
        self.assertIn(role_list[4]['id'], roles_ids)

        # Finally, add user1 to the 2nd group, and get a new
        # scoped token - the extra role should now be included
        # by virtue of the 2nd group
        self.identity_api.add_user_to_group(user1['id'],
                                            group2['id'])
        auth_data = self.build_authentication_request(
            user_id=user1['id'],
            password=user1['password'],
            project_id=projectA['id'])
        r = self.v3_authenticate_token(auth_data)
        token = self.assertValidScopedTokenResponse(r)
        roles_ids = []
        for ref in token['roles']:
            roles_ids.append(ref['id'])
        self.assertEqual(3, len(token['roles']))
        self.assertIn(role_list[1]['id'], roles_ids)
        self.assertIn(role_list[5]['id'], roles_ids)
        self.assertIn(role_list[7]['id'], roles_ids)

    def test_auth_token_cross_domain_group_and_project(self):
        """Verify getting a token in cross domain group/project roles."""
        # create domain, project and group and grant roles to user
        domain1 = {'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex}
        self.resource_api.create_domain(domain1['id'], domain1)
        project1 = {'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex,
                    'domain_id': domain1['id']}
        self.resource_api.create_project(project1['id'], project1)
        user_foo = self.new_user_ref(domain_id=test_v3.DEFAULT_DOMAIN_ID)
        password = user_foo['password']
        user_foo = self.identity_api.create_user(user_foo)
        user_foo['password'] = password
        role_member = {'id': uuid.uuid4().hex,
                       'name': uuid.uuid4().hex}
        self.role_api.create_role(role_member['id'], role_member)
        role_admin = {'id': uuid.uuid4().hex,
                      'name': uuid.uuid4().hex}
        self.role_api.create_role(role_admin['id'], role_admin)
        role_foo_domain1 = {'id': uuid.uuid4().hex,
                            'name': uuid.uuid4().hex}
        self.role_api.create_role(role_foo_domain1['id'], role_foo_domain1)
        role_group_domain1 = {'id': uuid.uuid4().hex,
                              'name': uuid.uuid4().hex}
        self.role_api.create_role(role_group_domain1['id'], role_group_domain1)
        self.assignment_api.add_user_to_project(project1['id'],
                                                user_foo['id'])
        new_group = {'domain_id': domain1['id'], 'name': uuid.uuid4().hex}
        new_group = self.identity_api.create_group(new_group)
        self.identity_api.add_user_to_group(user_foo['id'],
                                            new_group['id'])
        self.assignment_api.create_grant(
            user_id=user_foo['id'],
            project_id=project1['id'],
            role_id=role_member['id'])
        self.assignment_api.create_grant(
            group_id=new_group['id'],
            project_id=project1['id'],
            role_id=role_admin['id'])
        self.assignment_api.create_grant(
            user_id=user_foo['id'],
            domain_id=domain1['id'],
            role_id=role_foo_domain1['id'])
        self.assignment_api.create_grant(
            group_id=new_group['id'],
            domain_id=domain1['id'],
            role_id=role_group_domain1['id'])

        # Get a scoped token for the project
        auth_data = self.build_authentication_request(
            username=user_foo['name'],
            user_domain_id=test_v3.DEFAULT_DOMAIN_ID,
            password=user_foo['password'],
            project_name=project1['name'],
            project_domain_id=domain1['id'])

        r = self.v3_authenticate_token(auth_data)
        scoped_token = self.assertValidScopedTokenResponse(r)
        project = scoped_token["project"]
        roles_ids = []
        for ref in scoped_token['roles']:
            roles_ids.append(ref['id'])
        self.assertEqual(project1['id'], project["id"])
        self.assertIn(role_member['id'], roles_ids)
        self.assertIn(role_admin['id'], roles_ids)
        self.assertNotIn(role_foo_domain1['id'], roles_ids)
        self.assertNotIn(role_group_domain1['id'], roles_ids)

    def test_project_id_scoped_token_with_user_domain_id(self):
        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_id=self.domain['id'],
            password=self.user['password'],
            project_id=self.project['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectScopedTokenResponse(r)

    def test_project_id_scoped_token_with_user_domain_name(self):
        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_name=self.domain['name'],
            password=self.user['password'],
            project_id=self.project['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectScopedTokenResponse(r)

    def test_domain_id_scoped_token_with_user_id(self):
        path = '/domains/%s/users/%s/roles/%s' % (
            self.domain['id'], self.user['id'], self.role['id'])
        self.put(path=path)

        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            domain_id=self.domain['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidDomainScopedTokenResponse(r)

    def test_domain_id_scoped_token_with_user_domain_id(self):
        path = '/domains/%s/users/%s/roles/%s' % (
            self.domain['id'], self.user['id'], self.role['id'])
        self.put(path=path)

        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_id=self.domain['id'],
            password=self.user['password'],
            domain_id=self.domain['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidDomainScopedTokenResponse(r)

    def test_domain_id_scoped_token_with_user_domain_name(self):
        path = '/domains/%s/users/%s/roles/%s' % (
            self.domain['id'], self.user['id'], self.role['id'])
        self.put(path=path)

        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_name=self.domain['name'],
            password=self.user['password'],
            domain_id=self.domain['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidDomainScopedTokenResponse(r)

    def test_domain_name_scoped_token_with_user_id(self):
        path = '/domains/%s/users/%s/roles/%s' % (
            self.domain['id'], self.user['id'], self.role['id'])
        self.put(path=path)

        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            domain_name=self.domain['name'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidDomainScopedTokenResponse(r)

    def test_domain_name_scoped_token_with_user_domain_id(self):
        path = '/domains/%s/users/%s/roles/%s' % (
            self.domain['id'], self.user['id'], self.role['id'])
        self.put(path=path)

        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_id=self.domain['id'],
            password=self.user['password'],
            domain_name=self.domain['name'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidDomainScopedTokenResponse(r)

    def test_domain_name_scoped_token_with_user_domain_name(self):
        path = '/domains/%s/users/%s/roles/%s' % (
            self.domain['id'], self.user['id'], self.role['id'])
        self.put(path=path)

        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_name=self.domain['name'],
            password=self.user['password'],
            domain_name=self.domain['name'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidDomainScopedTokenResponse(r)

    def test_domain_scope_token_with_group_role(self):
        group = self.new_group_ref(
            domain_id=self.domain_id)
        group = self.identity_api.create_group(group)

        # add user to group
        self.identity_api.add_user_to_group(self.user['id'], group['id'])

        # grant the domain role to group
        path = '/domains/%s/groups/%s/roles/%s' % (
            self.domain['id'], group['id'], self.role['id'])
        self.put(path=path)

        # now get a domain-scoped token
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            domain_id=self.domain['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidDomainScopedTokenResponse(r)

    def test_domain_scope_token_with_name(self):
        # grant the domain role to user
        path = '/domains/%s/users/%s/roles/%s' % (
            self.domain['id'], self.user['id'], self.role['id'])
        self.put(path=path)
        # now get a domain-scoped token
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            domain_name=self.domain['name'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidDomainScopedTokenResponse(r)

    def test_domain_scope_failed(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            domain_id=self.domain['id'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_auth_with_id(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidUnscopedTokenResponse(r)

        token = r.headers.get('X-Subject-Token')

        # test token auth
        auth_data = self.build_authentication_request(token=token)
        r = self.v3_authenticate_token(auth_data)
        self.assertValidUnscopedTokenResponse(r)

    def get_v2_token(self, tenant_id=None):
        body = {
            'auth': {
                'passwordCredentials': {
                    'username': self.default_domain_user['name'],
                    'password': self.default_domain_user['password'],
                },
            },
        }
        r = self.admin_request(method='POST', path='/v2.0/tokens', body=body)
        return r

    def test_validate_v2_unscoped_token_with_v3_api(self):
        v2_token = self.get_v2_token().result['access']['token']['id']
        auth_data = self.build_authentication_request(token=v2_token)
        r = self.v3_authenticate_token(auth_data)
        self.assertValidUnscopedTokenResponse(r)

    def test_validate_v2_scoped_token_with_v3_api(self):
        v2_response = self.get_v2_token(
            tenant_id=self.default_domain_project['id'])
        result = v2_response.result
        v2_token = result['access']['token']['id']
        auth_data = self.build_authentication_request(
            token=v2_token,
            project_id=self.default_domain_project['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidScopedTokenResponse(r)

    def test_invalid_user_id(self):
        auth_data = self.build_authentication_request(
            user_id=uuid.uuid4().hex,
            password=self.user['password'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_invalid_user_name(self):
        auth_data = self.build_authentication_request(
            username=uuid.uuid4().hex,
            user_domain_id=self.domain['id'],
            password=self.user['password'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_invalid_domain_id(self):
        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_id=uuid.uuid4().hex,
            password=self.user['password'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_invalid_domain_name(self):
        auth_data = self.build_authentication_request(
            username=self.user['name'],
            user_domain_name=uuid.uuid4().hex,
            password=self.user['password'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_invalid_password(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=uuid.uuid4().hex)
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_remote_user_no_realm(self):
        api = auth.controllers.Auth()
        context, auth_info, auth_context = self.build_external_auth_request(
            self.default_domain_user['name'])
        api.authenticate(context, auth_info, auth_context)
        self.assertEqual(self.default_domain_user['id'],
                         auth_context['user_id'])
        # Now test to make sure the user name can, itself, contain the
        # '@' character.
        user = {'name': 'myname@mydivision'}
        self.identity_api.update_user(self.default_domain_user['id'], user)
        context, auth_info, auth_context = self.build_external_auth_request(
            user["name"])
        api.authenticate(context, auth_info, auth_context)
        self.assertEqual(self.default_domain_user['id'],
                         auth_context['user_id'])

    def test_remote_user_no_domain(self):
        api = auth.controllers.Auth()
        context, auth_info, auth_context = self.build_external_auth_request(
            self.user['name'])
        self.assertRaises(exception.Unauthorized,
                          api.authenticate,
                          context,
                          auth_info,
                          auth_context)

    def test_remote_user_and_password(self):
        # both REMOTE_USER and password methods must pass.
        # note that they do not have to match
        api = auth.controllers.Auth()
        auth_data = self.build_authentication_request(
            user_domain_id=self.default_domain_user['domain_id'],
            username=self.default_domain_user['name'],
            password=self.default_domain_user['password'])['auth']
        context, auth_info, auth_context = self.build_external_auth_request(
            self.default_domain_user['name'], auth_data=auth_data)

        api.authenticate(context, auth_info, auth_context)

    def test_remote_user_and_explicit_external(self):
        # both REMOTE_USER and password methods must pass.
        # note that they do not have to match
        auth_data = self.build_authentication_request(
            user_domain_id=self.domain['id'],
            username=self.user['name'],
            password=self.user['password'])['auth']
        auth_data['identity']['methods'] = ["password", "external"]
        auth_data['identity']['external'] = {}
        api = auth.controllers.Auth()
        auth_info = auth.controllers.AuthInfo(None, auth_data)
        auth_context = {'extras': {}, 'method_names': []}
        self.assertRaises(exception.Unauthorized,
                          api.authenticate,
                          self.empty_context,
                          auth_info,
                          auth_context)

    def test_remote_user_bad_password(self):
        # both REMOTE_USER and password methods must pass.
        api = auth.controllers.Auth()
        auth_data = self.build_authentication_request(
            user_domain_id=self.domain['id'],
            username=self.user['name'],
            password='badpassword')['auth']
        context, auth_info, auth_context = self.build_external_auth_request(
            self.default_domain_user['name'], auth_data=auth_data)
        self.assertRaises(exception.Unauthorized,
                          api.authenticate,
                          context,
                          auth_info,
                          auth_context)

    def test_bind_not_set_with_remote_user(self):
        self.config_fixture.config(group='token', bind=[])
        auth_data = self.build_authentication_request()
        remote_user = self.default_domain_user['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'AUTH_TYPE': 'Negotiate'})
        r = self.v3_authenticate_token(auth_data)
        token = self.assertValidUnscopedTokenResponse(r)
        self.assertNotIn('bind', token)

    # TODO(ayoung): move to TestPKITokenAPIs; it will be run for both formats
    def test_verify_with_bound_token(self):
        self.config_fixture.config(group='token', bind='kerberos')
        auth_data = self.build_authentication_request(
            project_id=self.project['id'])
        remote_user = self.default_domain_user['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'AUTH_TYPE': 'Negotiate'})

        token = self.get_requested_token(auth_data)
        headers = {'X-Subject-Token': token}
        r = self.get('/auth/tokens', headers=headers, token=token)
        token = self.assertValidProjectScopedTokenResponse(r)
        self.assertEqual(self.default_domain_user['name'],
                         token['bind']['kerberos'])

    def test_auth_with_bind_token(self):
        self.config_fixture.config(group='token', bind=['kerberos'])

        auth_data = self.build_authentication_request()
        remote_user = self.default_domain_user['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'AUTH_TYPE': 'Negotiate'})
        r = self.v3_authenticate_token(auth_data)

        # the unscoped token should have bind information in it
        token = self.assertValidUnscopedTokenResponse(r)
        self.assertEqual(remote_user, token['bind']['kerberos'])

        token = r.headers.get('X-Subject-Token')

        # using unscoped token with remote user succeeds
        auth_params = {'token': token, 'project_id': self.project_id}
        auth_data = self.build_authentication_request(**auth_params)
        r = self.v3_authenticate_token(auth_data)
        token = self.assertValidProjectScopedTokenResponse(r)

        # the bind information should be carried over from the original token
        self.assertEqual(remote_user, token['bind']['kerberos'])

    def test_v2_v3_bind_token_intermix(self):
        self.config_fixture.config(group='token', bind='kerberos')

        # we need our own user registered to the default domain because of
        # the way external auth works.
        remote_user = self.default_domain_user['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'AUTH_TYPE': 'Negotiate'})
        body = {'auth': {}}
        resp = self.admin_request(path='/v2.0/tokens',
                                  method='POST',
                                  body=body)

        v2_token_data = resp.result

        bind = v2_token_data['access']['token']['bind']
        self.assertEqual(self.default_domain_user['name'], bind['kerberos'])

        v2_token_id = v2_token_data['access']['token']['id']
        # NOTE(gyee): self.get() will try to obtain an auth token if one
        # is not provided. When REMOTE_USER is present in the request
        # environment, the external user auth plugin is used in conjunction
        # with the password auth for the admin user. Therefore, we need to
        # cleanup the REMOTE_USER information from the previous call.
        del self.admin_app.extra_environ['REMOTE_USER']
        headers = {'X-Subject-Token': v2_token_id}
        resp = self.get('/auth/tokens', headers=headers)
        token_data = resp.result

        self.assertDictEqual(v2_token_data['access']['token']['bind'],
                             token_data['token']['bind'])

    def test_authenticating_a_user_with_no_password(self):
        user = self.new_user_ref(domain_id=self.domain['id'])
        user.pop('password', None)  # can't have a password for this test
        user = self.identity_api.create_user(user)

        auth_data = self.build_authentication_request(
            user_id=user['id'],
            password='password')

        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_disabled_default_project_result_in_unscoped_token(self):
        # create a disabled project to work with
        project = self.create_new_default_project_for_user(
            self.user['id'], self.domain_id, enable_project=False)

        # assign a role to user for the new project
        self.assignment_api.add_role_to_user_and_project(self.user['id'],
                                                         project['id'],
                                                         self.role_id)

        # attempt to authenticate without requesting a project
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidUnscopedTokenResponse(r)

    def test_disabled_default_project_domain_result_in_unscoped_token(self):
        domain_ref = self.new_domain_ref()
        r = self.post('/domains', body={'domain': domain_ref})
        domain = self.assertValidDomainResponse(r, domain_ref)

        project = self.create_new_default_project_for_user(
            self.user['id'], domain['id'])

        # assign a role to user for the new project
        self.assignment_api.add_role_to_user_and_project(self.user['id'],
                                                         project['id'],
                                                         self.role_id)

        # now disable the project domain
        body = {'domain': {'enabled': False}}
        r = self.patch('/domains/%(domain_id)s' % {'domain_id': domain['id']},
                       body=body)
        self.assertValidDomainResponse(r)

        # attempt to authenticate without requesting a project
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidUnscopedTokenResponse(r)

    def test_no_access_to_default_project_result_in_unscoped_token(self):
        # create a disabled project to work with
        self.create_new_default_project_for_user(self.user['id'],
                                                 self.domain_id)

        # attempt to authenticate without requesting a project
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidUnscopedTokenResponse(r)

    def test_disabled_scope_project_domain_result_in_401(self):
        # create a disabled domain
        domain = self.new_domain_ref()
        domain['enabled'] = False
        self.resource_api.create_domain(domain['id'], domain)

        # create a project in the disabled domain
        project = self.new_project_ref(domain_id=domain['id'])
        self.resource_api.create_project(project['id'], project)

        # assign some role to self.user for the project in the disabled domain
        self.assignment_api.add_role_to_user_and_project(
            self.user['id'],
            project['id'],
            self.role_id)

        # user should not be able to auth with project_id
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=project['id'])
        self.v3_authenticate_token(auth_data, expected_status=401)

        # user should not be able to auth with project_name & domain
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_name=project['name'],
            project_domain_id=domain['id'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_auth_methods_with_different_identities_fails(self):
        # get the token for a user. This is self.user which is different from
        # self.default_domain_user.
        token = self.get_scoped_token()
        # try both password and token methods with different identities and it
        # should fail
        auth_data = self.build_authentication_request(
            token=token,
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'])
        self.v3_authenticate_token(auth_data, expected_status=401)


class TestAuthJSONExternal(test_v3.RestfulTestCase):
    content_type = 'json'

    def auth_plugin_config_override(self, methods=None, **method_classes):
        self.config_fixture.config(group='auth', methods=[])

    def test_remote_user_no_method(self):
        api = auth.controllers.Auth()
        context, auth_info, auth_context = self.build_external_auth_request(
            self.default_domain_user['name'])
        self.assertRaises(exception.Unauthorized,
                          api.authenticate,
                          context,
                          auth_info,
                          auth_context)


class TestTrustOptional(test_v3.RestfulTestCase):
    def config_overrides(self):
        super(TestTrustOptional, self).config_overrides()
        self.config_fixture.config(group='trust', enabled=False)

    def test_trusts_404(self):
        self.get('/OS-TRUST/trusts', body={'trust': {}}, expected_status=404)
        self.post('/OS-TRUST/trusts', body={'trust': {}}, expected_status=404)

    def test_auth_with_scope_in_trust_403(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            trust_id=uuid.uuid4().hex)
        self.v3_authenticate_token(auth_data, expected_status=403)


class TestTrustRedelegation(test_v3.RestfulTestCase):
    """Redelegation valid and secure

    Redelegation is a hierarchical structure of trusts between initial trustor
    and a group of users allowed to impersonate trustor and act in his name.
    Hierarchy is created in a process of trusting already trusted permissions
    and organized as an adjacency list using 'redelegated_trust_id' field.
    Redelegation is valid if each subsequent trust in a chain passes 'not more'
    permissions than being redelegated.

    Trust constraints are:
     * roles - set of roles trusted by trustor
     * expiration_time
     * allow_redelegation - a flag
     * redelegation_count - decreasing value restricting length of trust chain
     * remaining_uses - DISALLOWED when allow_redelegation == True

    Trust becomes invalid in case:
     * trust roles were revoked from trustor
     * one of the users in the delegation chain was disabled or deleted
     * expiration time passed
     * one of the parent trusts has become invalid
     * one of the parent trusts was deleted

    """

    def config_overrides(self):
        super(TestTrustRedelegation, self).config_overrides()
        self.config_fixture.config(
            group='trust',
            enabled=True,
            allow_redelegation=True,
            max_redelegation_count=10
        )

    def setUp(self):
        super(TestTrustRedelegation, self).setUp()
        # Create a trustee to delegate stuff to
        trustee_user_ref = self.new_user_ref(domain_id=self.domain_id)
        self.trustee_user = self.identity_api.create_user(trustee_user_ref)
        self.trustee_user['password'] = trustee_user_ref['password']

        # trustor->trustee
        self.redelegated_trust_ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user['id'],
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=1),
            role_ids=[self.role_id],
            allow_redelegation=True)

        # trustor->trustee (no redelegation)
        self.chained_trust_ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user['id'],
            project_id=self.project_id,
            impersonation=True,
            role_ids=[self.role_id],
            allow_redelegation=True)

    def _get_trust_token(self, trust):
        trust_id = trust['id']
        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust_id)
        trust_token = self.get_requested_token(auth_data)
        return trust_token

    def test_depleted_redelegation_count_error(self):
        self.redelegated_trust_ref['redelegation_count'] = 0
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': self.redelegated_trust_ref})
        trust = self.assertValidTrustResponse(r)
        trust_token = self._get_trust_token(trust)

        # Attempt to create a redelegated trust.
        self.post('/OS-TRUST/trusts',
                  body={'trust': self.chained_trust_ref},
                  token=trust_token,
                  expected_status=403)

    def test_modified_redelegation_count_error(self):
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': self.redelegated_trust_ref})
        trust = self.assertValidTrustResponse(r)
        trust_token = self._get_trust_token(trust)

        # Attempt to create a redelegated trust with incorrect
        # redelegation_count.
        correct = trust['redelegation_count'] - 1
        incorrect = correct - 1
        self.chained_trust_ref['redelegation_count'] = incorrect
        self.post('/OS-TRUST/trusts',
                  body={'trust': self.chained_trust_ref},
                  token=trust_token,
                  expected_status=403)

    def test_max_redelegation_count_constraint(self):
        incorrect = CONF.trust.max_redelegation_count + 1
        self.redelegated_trust_ref['redelegation_count'] = incorrect
        self.post('/OS-TRUST/trusts',
                  body={'trust': self.redelegated_trust_ref},
                  expected_status=403)

    def test_redelegation_expiry(self):
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': self.redelegated_trust_ref})
        trust = self.assertValidTrustResponse(r)
        trust_token = self._get_trust_token(trust)

        # Attempt to create a redelegated trust supposed to last longer
        # than the parent trust: let's give it 10 minutes (>1 minute).
        too_long_live_chained_trust_ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user['id'],
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=10),
            role_ids=[self.role_id])
        self.post('/OS-TRUST/trusts',
                  body={'trust': too_long_live_chained_trust_ref},
                  token=trust_token,
                  expected_status=403)

    def test_redelegation_remaining_uses(self):
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': self.redelegated_trust_ref})
        trust = self.assertValidTrustResponse(r)
        trust_token = self._get_trust_token(trust)

        # Attempt to create a redelegated trust with remaining_uses defined.
        # It must fail according to specification: remaining_uses must be
        # omitted for trust redelegation. Any number here.
        self.chained_trust_ref['remaining_uses'] = 5
        self.post('/OS-TRUST/trusts',
                  body={'trust': self.chained_trust_ref},
                  token=trust_token,
                  expected_status=400)

    def test_roles_subset(self):
        # Build second role
        role = self.new_role_ref()
        self.role_api.create_role(role['id'], role)
        # assign a new role to the user
        self.assignment_api.create_grant(role_id=role['id'],
                                         user_id=self.user_id,
                                         project_id=self.project_id)

        # Create first trust with extended set of roles
        ref = self.redelegated_trust_ref
        ref['roles'].append({'id': role['id']})
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': ref})
        trust = self.assertValidTrustResponse(r)
        # Trust created with exact set of roles (checked by role id)
        role_id_set = set(r['id'] for r in ref['roles'])
        trust_role_id_set = set(r['id'] for r in trust['roles'])
        self.assertEqual(role_id_set, trust_role_id_set)

        trust_token = self._get_trust_token(trust)

        # Chain second trust with roles subset
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': self.chained_trust_ref},
                      token=trust_token)
        trust2 = self.assertValidTrustResponse(r)
        # First trust contains roles superset
        # Second trust contains roles subset
        role_id_set1 = set(r['id'] for r in trust['roles'])
        role_id_set2 = set(r['id'] for r in trust2['roles'])
        self.assertThat(role_id_set1, matchers.GreaterThan(role_id_set2))

    def test_redelegate_with_role_by_name(self):
        # For role by name testing
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user['id'],
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=1),
            role_names=[self.role['name']],
            allow_redelegation=True)
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': ref})
        trust = self.assertValidTrustResponse(r)
        # Ensure we can get a token with this trust
        trust_token = self._get_trust_token(trust)
        # Chain second trust with roles subset
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user['id'],
            project_id=self.project_id,
            impersonation=True,
            role_names=[self.role['name']],
            allow_redelegation=True)
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': ref},
                      token=trust_token)
        trust = self.assertValidTrustResponse(r)
        # Ensure we can get a token with this trust
        self._get_trust_token(trust)

    def test_redelegate_new_role_fails(self):
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': self.redelegated_trust_ref})
        trust = self.assertValidTrustResponse(r)
        trust_token = self._get_trust_token(trust)

        # Build second trust with a role not in parent's roles
        role = self.new_role_ref()
        self.role_api.create_role(role['id'], role)
        # assign a new role to the user
        self.assignment_api.create_grant(role_id=role['id'],
                                         user_id=self.user_id,
                                         project_id=self.project_id)

        # Try to chain a trust with the role not from parent trust
        self.chained_trust_ref['roles'] = [{'id': role['id']}]

        # Bypass policy enforcement
        with mock.patch.object(rules, 'enforce', return_value=True):
            self.post('/OS-TRUST/trusts',
                      body={'trust': self.chained_trust_ref},
                      token=trust_token,
                      expected_status=403)

    def test_redelegation_terminator(self):
        r = self.post('/OS-TRUST/trusts',
                      body={'trust': self.redelegated_trust_ref})
        trust = self.assertValidTrustResponse(r)
        trust_token = self._get_trust_token(trust)

        # Build second trust - the terminator
        ref = dict(self.chained_trust_ref,
                   redelegation_count=1,
                   allow_redelegation=False)

        r = self.post('/OS-TRUST/trusts',
                      body={'trust': ref},
                      token=trust_token)

        trust = self.assertValidTrustResponse(r)
        # Check that allow_redelegation == False caused redelegation_count
        # to be set to 0, while allow_redelegation is removed
        self.assertNotIn('allow_redelegation', trust)
        self.assertEqual(0, trust['redelegation_count'])
        trust_token = self._get_trust_token(trust)

        # Build third trust, same as second
        self.post('/OS-TRUST/trusts',
                  body={'trust': ref},
                  token=trust_token,
                  expected_status=403)


class TestTrustChain(test_v3.RestfulTestCase):

    def config_overrides(self):
        super(TestTrustChain, self).config_overrides()
        self.config_fixture.config(
            group='trust',
            enabled=True,
            allow_redelegation=True,
            max_redelegation_count=10
        )

    def setUp(self):
        super(TestTrustChain, self).setUp()
        # Create trust chain
        self.user_chain = list()
        self.trust_chain = list()
        for _ in range(3):
            user_ref = self.new_user_ref(domain_id=self.domain_id)
            user = self.identity_api.create_user(user_ref)
            user['password'] = user_ref['password']
            self.user_chain.append(user)

        # trustor->trustee
        trustee = self.user_chain[0]
        trust_ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=trustee['id'],
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=1),
            role_ids=[self.role_id])
        trust_ref.update(
            allow_redelegation=True,
            redelegation_count=3)

        r = self.post('/OS-TRUST/trusts',
                      body={'trust': trust_ref})

        trust = self.assertValidTrustResponse(r)
        auth_data = self.build_authentication_request(
            user_id=trustee['id'],
            password=trustee['password'],
            trust_id=trust['id'])
        trust_token = self.get_requested_token(auth_data)
        self.trust_chain.append(trust)

        for trustee in self.user_chain[1:]:
            trust_ref = self.new_trust_ref(
                trustor_user_id=self.user_id,
                trustee_user_id=trustee['id'],
                project_id=self.project_id,
                impersonation=True,
                role_ids=[self.role_id])
            trust_ref.update(
                allow_redelegation=True)
            r = self.post('/OS-TRUST/trusts',
                          body={'trust': trust_ref},
                          token=trust_token)
            trust = self.assertValidTrustResponse(r)
            auth_data = self.build_authentication_request(
                user_id=trustee['id'],
                password=trustee['password'],
                trust_id=trust['id'])
            trust_token = self.get_requested_token(auth_data)
            self.trust_chain.append(trust)

        trustee = self.user_chain[-1]
        trust = self.trust_chain[-1]
        auth_data = self.build_authentication_request(
            user_id=trustee['id'],
            password=trustee['password'],
            trust_id=trust['id'])

        self.last_token = self.get_requested_token(auth_data)

    def assert_user_authenticate(self, user):
        auth_data = self.build_authentication_request(
            user_id=user['id'],
            password=user['password']
        )
        r = self.v3_authenticate_token(auth_data)
        self.assertValidTokenResponse(r)

    def assert_trust_tokens_revoked(self, trust_id):
        trustee = self.user_chain[0]
        auth_data = self.build_authentication_request(
            user_id=trustee['id'],
            password=trustee['password']
        )
        r = self.v3_authenticate_token(auth_data)
        self.assertValidTokenResponse(r)

        revocation_response = self.get('/OS-REVOKE/events')
        revocation_events = revocation_response.json_body['events']
        found = False
        for event in revocation_events:
            if event.get('OS-TRUST:trust_id') == trust_id:
                found = True
        self.assertTrue(found, 'event with trust_id %s not found in list' %
                        trust_id)

    def test_delete_trust_cascade(self):
        self.assert_user_authenticate(self.user_chain[0])
        self.delete('/OS-TRUST/trusts/%(trust_id)s' % {
            'trust_id': self.trust_chain[0]['id']},
            expected_status=204)

        headers = {'X-Subject-Token': self.last_token}
        self.head('/auth/tokens', headers=headers, expected_status=404)
        self.assert_trust_tokens_revoked(self.trust_chain[0]['id'])

    def test_delete_broken_chain(self):
        self.assert_user_authenticate(self.user_chain[0])
        self.delete('/OS-TRUST/trusts/%(trust_id)s' % {
            'trust_id': self.trust_chain[1]['id']},
            expected_status=204)

        self.delete('/OS-TRUST/trusts/%(trust_id)s' % {
            'trust_id': self.trust_chain[0]['id']},
            expected_status=204)

    def test_trustor_roles_revoked(self):
        self.assert_user_authenticate(self.user_chain[0])

        self.assignment_api.remove_role_from_user_and_project(
            self.user_id, self.project_id, self.role_id
        )

        auth_data = self.build_authentication_request(
            token=self.last_token,
            trust_id=self.trust_chain[-1]['id'])
        self.v3_authenticate_token(auth_data, expected_status=404)

    def test_intermediate_user_disabled(self):
        self.assert_user_authenticate(self.user_chain[0])

        disabled = self.user_chain[0]
        disabled['enabled'] = False
        self.identity_api.update_user(disabled['id'], disabled)

        # Bypass policy enforcement
        with mock.patch.object(rules, 'enforce', return_value=True):
            headers = {'X-Subject-Token': self.last_token}
            self.head('/auth/tokens', headers=headers, expected_status=403)

    def test_intermediate_user_deleted(self):
        self.assert_user_authenticate(self.user_chain[0])

        self.identity_api.delete_user(self.user_chain[0]['id'])

        # Bypass policy enforcement
        with mock.patch.object(rules, 'enforce', return_value=True):
            headers = {'X-Subject-Token': self.last_token}
            self.head('/auth/tokens', headers=headers, expected_status=403)


class TestTrustAuth(test_v3.RestfulTestCase):
    EXTENSION_NAME = 'revoke'
    EXTENSION_TO_ADD = 'revoke_extension'

    def config_overrides(self):
        super(TestTrustAuth, self).config_overrides()
        self.config_fixture.config(group='revoke', driver='kvs')
        self.config_fixture.config(
            group='token',
            provider='pki',
            revoke_by_id=False)
        self.config_fixture.config(group='trust', enabled=True)

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

        # create a trustee to delegate stuff to
        self.trustee_user = self.new_user_ref(domain_id=self.domain_id)
        password = self.trustee_user['password']
        self.trustee_user = self.identity_api.create_user(self.trustee_user)
        self.trustee_user['password'] = password
        self.trustee_user_id = self.trustee_user['id']

    def test_create_trust_400(self):
        # The server returns a 403 Forbidden rather than a 400, see bug 1133435
        self.post('/OS-TRUST/trusts', body={'trust': {}}, expected_status=403)

    def test_create_unscoped_trust(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id)
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        self.assertValidTrustResponse(r, ref)

    def test_create_trust_no_roles(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id)
        self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=403)

    def _initialize_test_consume_trust(self, count):
        # Make sure remaining_uses is decremented as we consume the trust
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            remaining_uses=count,
            role_ids=[self.role_id])
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        # make sure the trust exists
        trust = self.assertValidTrustResponse(r, ref)
        r = self.get(
            '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']},
            expected_status=200)
        # get a token for the trustee
        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'])
        r = self.v3_authenticate_token(auth_data)
        token = r.headers.get('X-Subject-Token')
        # get a trust token, consume one use
        auth_data = self.build_authentication_request(
            token=token,
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data)
        return trust

    def test_consume_trust_once(self):
        trust = self._initialize_test_consume_trust(2)
        # check decremented value
        r = self.get(
            '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']},
            expected_status=200)
        trust = r.result.get('trust')
        self.assertIsNotNone(trust)
        self.assertEqual(1, trust['remaining_uses'])

    def test_create_one_time_use_trust(self):
        trust = self._initialize_test_consume_trust(1)
        # No more uses, the trust is made unavailable
        self.get(
            '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']},
            expected_status=404)
        # this time we can't get a trust token
        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_create_trust_with_bad_values_for_remaining_uses(self):
        # negative values for the remaining_uses parameter are forbidden
        self._create_trust_with_bad_remaining_use(bad_value=-1)
        # 0 is a forbidden value as well
        self._create_trust_with_bad_remaining_use(bad_value=0)
        # as are non integer values
        self._create_trust_with_bad_remaining_use(bad_value="a bad value")
        self._create_trust_with_bad_remaining_use(bad_value=7.2)

    def _create_trust_with_bad_remaining_use(self, bad_value):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            remaining_uses=bad_value,
            role_ids=[self.role_id])
        self.post('/OS-TRUST/trusts',
                  body={'trust': ref},
                  expected_status=400)

    def test_invalid_trust_request_without_impersonation(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            role_ids=[self.role_id])

        del ref['impersonation']

        self.post('/OS-TRUST/trusts',
                  body={'trust': ref},
                  expected_status=400)

    def test_invalid_trust_request_without_trustee(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            role_ids=[self.role_id])

        del ref['trustee_user_id']

        self.post('/OS-TRUST/trusts',
                  body={'trust': ref},
                  expected_status=400)

    def test_create_unlimited_use_trust(self):
        # by default trusts are unlimited in terms of tokens that can be
        # generated from them, this test creates such a trust explicitly
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            remaining_uses=None,
            role_ids=[self.role_id])
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r, ref)

        r = self.get(
            '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']},
            expected_status=200)
        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'])
        r = self.v3_authenticate_token(auth_data)
        token = r.headers.get('X-Subject-Token')
        auth_data = self.build_authentication_request(
            token=token,
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data)
        r = self.get(
            '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']},
            expected_status=200)
        trust = r.result.get('trust')
        self.assertIsNone(trust['remaining_uses'])

    def test_trust_crud(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            role_ids=[self.role_id])
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r, ref)

        r = self.get(
            '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']},
            expected_status=200)
        self.assertValidTrustResponse(r, ref)

        # validate roles on the trust
        r = self.get(
            '/OS-TRUST/trusts/%(trust_id)s/roles' % {
                'trust_id': trust['id']},
            expected_status=200)
        roles = self.assertValidRoleListResponse(r, self.role)
        self.assertIn(self.role['id'], [x['id'] for x in roles])
        self.head(
            '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' % {
                'trust_id': trust['id'],
                'role_id': self.role['id']},
            expected_status=200)
        r = self.get(
            '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' % {
                'trust_id': trust['id'],
                'role_id': self.role['id']},
            expected_status=200)
        self.assertValidRoleResponse(r, self.role)

        r = self.get('/OS-TRUST/trusts', expected_status=200)
        self.assertValidTrustListResponse(r, trust)

        # trusts are immutable
        self.patch(
            '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']},
            body={'trust': ref},
            expected_status=404)

        self.delete(
            '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']},
            expected_status=204)

        self.get(
            '/OS-TRUST/trusts/%(trust_id)s' % {'trust_id': trust['id']},
            expected_status=404)

    def test_create_trust_trustee_404(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=uuid.uuid4().hex,
            project_id=self.project_id,
            role_ids=[self.role_id])
        self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=404)

    def test_create_trust_trustor_trustee_backwards(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.trustee_user_id,
            trustee_user_id=self.user_id,
            project_id=self.project_id,
            role_ids=[self.role_id])
        self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=403)

    def test_create_trust_project_404(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=uuid.uuid4().hex,
            role_ids=[self.role_id])
        self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=404)

    def test_create_trust_role_id_404(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            role_ids=[uuid.uuid4().hex])
        self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=404)

    def test_create_trust_role_name_404(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            role_names=[uuid.uuid4().hex])
        self.post('/OS-TRUST/trusts', body={'trust': ref}, expected_status=404)

    def test_v3_v2_intermix_trustor_not_in_default_domain_failed(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.default_domain_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r)

        auth_data = self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectTrustScopedTokenResponse(
            r, self.default_domain_user)

        token = r.headers.get('X-Subject-Token')

        # now validate the v3 token with v2 API
        path = '/v2.0/tokens/%s' % (token)
        self.admin_request(
            path=path, token=CONF.admin_token,
            method='GET', expected_status=401)

    def test_v3_v2_intermix_trustor_not_in_default_domaini_failed(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.default_domain_user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.default_domain_project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        auth_data = self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            project_id=self.default_domain_project_id)
        token = self.get_requested_token(auth_data)

        r = self.post('/OS-TRUST/trusts', body={'trust': ref}, token=token)
        trust = self.assertValidTrustResponse(r)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectTrustScopedTokenResponse(
            r, self.trustee_user)
        token = r.headers.get('X-Subject-Token')

        # now validate the v3 token with v2 API
        path = '/v2.0/tokens/%s' % (token)
        self.admin_request(
            path=path, token=CONF.admin_token,
            method='GET', expected_status=401)

    def test_v3_v2_intermix_project_not_in_default_domaini_failed(self):
        # create a trustee in default domain to delegate stuff to
        trustee_user = self.new_user_ref(domain_id=test_v3.DEFAULT_DOMAIN_ID)
        password = trustee_user['password']
        trustee_user = self.identity_api.create_user(trustee_user)
        trustee_user['password'] = password
        trustee_user_id = trustee_user['id']

        ref = self.new_trust_ref(
            trustor_user_id=self.default_domain_user_id,
            trustee_user_id=trustee_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        auth_data = self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            project_id=self.default_domain_project_id)
        token = self.get_requested_token(auth_data)

        r = self.post('/OS-TRUST/trusts', body={'trust': ref}, token=token)
        trust = self.assertValidTrustResponse(r)

        auth_data = self.build_authentication_request(
            user_id=trustee_user['id'],
            password=trustee_user['password'],
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectTrustScopedTokenResponse(
            r, trustee_user)
        token = r.headers.get('X-Subject-Token')

        # now validate the v3 token with v2 API
        path = '/v2.0/tokens/%s' % (token)
        self.admin_request(
            path=path, token=CONF.admin_token,
            method='GET', expected_status=401)

    def test_v3_v2_intermix(self):
        # create a trustee in default domain to delegate stuff to
        trustee_user = self.new_user_ref(domain_id=test_v3.DEFAULT_DOMAIN_ID)
        password = trustee_user['password']
        trustee_user = self.identity_api.create_user(trustee_user)
        trustee_user['password'] = password
        trustee_user_id = trustee_user['id']

        ref = self.new_trust_ref(
            trustor_user_id=self.default_domain_user_id,
            trustee_user_id=trustee_user_id,
            project_id=self.default_domain_project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])
        auth_data = self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            project_id=self.default_domain_project_id)
        token = self.get_requested_token(auth_data)

        r = self.post('/OS-TRUST/trusts', body={'trust': ref}, token=token)
        trust = self.assertValidTrustResponse(r)

        auth_data = self.build_authentication_request(
            user_id=trustee_user['id'],
            password=trustee_user['password'],
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectTrustScopedTokenResponse(
            r, trustee_user)
        token = r.headers.get('X-Subject-Token')

        # now validate the v3 token with v2 API
        path = '/v2.0/tokens/%s' % (token)
        self.admin_request(
            path=path, token=CONF.admin_token,
            method='GET', expected_status=200)

    def test_exercise_trust_scoped_token_without_impersonation(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectTrustScopedTokenResponse(r, self.trustee_user)
        self.assertEqual(self.trustee_user['id'],
                         r.result['token']['user']['id'])
        self.assertEqual(self.trustee_user['name'],
                         r.result['token']['user']['name'])
        self.assertEqual(self.domain['id'],
                         r.result['token']['user']['domain']['id'])
        self.assertEqual(self.domain['name'],
                         r.result['token']['user']['domain']['name'])
        self.assertEqual(self.project['id'],
                         r.result['token']['project']['id'])
        self.assertEqual(self.project['name'],
                         r.result['token']['project']['name'])

    def test_exercise_trust_scoped_token_with_impersonation(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectTrustScopedTokenResponse(r, self.user)
        self.assertEqual(self.user['id'], r.result['token']['user']['id'])
        self.assertEqual(self.user['name'], r.result['token']['user']['name'])
        self.assertEqual(self.domain['id'],
                         r.result['token']['user']['domain']['id'])
        self.assertEqual(self.domain['name'],
                         r.result['token']['user']['domain']['name'])
        self.assertEqual(self.project['id'],
                         r.result['token']['project']['id'])
        self.assertEqual(self.project['name'],
                         r.result['token']['project']['name'])

    def test_impersonation_token_cannot_create_new_trust(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])

        trust_token = self.get_requested_token(auth_data)

        # Build second trust
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        self.post('/OS-TRUST/trusts',
                  body={'trust': ref},
                  token=trust_token,
                  expected_status=403)

    def test_trust_deleted_grant(self):
        # create a new role
        role = self.new_role_ref()
        self.role_api.create_role(role['id'], role)

        grant_url = (
            '/projects/%(project_id)s/users/%(user_id)s/'
            'roles/%(role_id)s' % {
                'project_id': self.project_id,
                'user_id': self.user_id,
                'role_id': role['id']})

        # assign a new role
        self.put(grant_url)

        # create a trust that delegates the new role
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[role['id']])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r)

        # delete the grant
        self.delete(grant_url)

        # attempt to get a trust token with the deleted grant
        # and ensure it's unauthorized
        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data, expected_status=403)

    def test_trust_chained(self):
        """Test that a trust token can't be used to execute another trust.

        To do this, we create an A->B->C hierarchy of trusts, then attempt to
        execute the trusts in series (C->B->A).

        """
        # create a sub-trustee user
        sub_trustee_user = self.new_user_ref(
            domain_id=test_v3.DEFAULT_DOMAIN_ID)
        password = sub_trustee_user['password']
        sub_trustee_user = self.identity_api.create_user(sub_trustee_user)
        sub_trustee_user['password'] = password
        sub_trustee_user_id = sub_trustee_user['id']

        # create a new role
        role = self.new_role_ref()
        self.role_api.create_role(role['id'], role)

        # assign the new role to trustee
        self.put(
            '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' % {
                'project_id': self.project_id,
                'user_id': self.trustee_user_id,
                'role_id': role['id']})

        # create a trust from trustor -> trustee
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=1),
            role_ids=[self.role_id])
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust1 = self.assertValidTrustResponse(r)

        # authenticate as trustee so we can create a second trust
        auth_data = self.build_authentication_request(
            user_id=self.trustee_user_id,
            password=self.trustee_user['password'],
            project_id=self.project_id)
        token = self.get_requested_token(auth_data)

        # create a trust from trustee -> sub-trustee
        ref = self.new_trust_ref(
            trustor_user_id=self.trustee_user_id,
            trustee_user_id=sub_trustee_user_id,
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=1),
            role_ids=[role['id']])
        r = self.post('/OS-TRUST/trusts', token=token, body={'trust': ref})
        trust2 = self.assertValidTrustResponse(r)

        # authenticate as sub-trustee and get a trust token
        auth_data = self.build_authentication_request(
            user_id=sub_trustee_user['id'],
            password=sub_trustee_user['password'],
            trust_id=trust2['id'])
        trust_token = self.get_requested_token(auth_data)

        # attempt to get the second trust using a trust token
        auth_data = self.build_authentication_request(
            token=trust_token,
            trust_id=trust1['id'])
        r = self.v3_authenticate_token(auth_data, expected_status=403)

    def assertTrustTokensRevoked(self, trust_id):
        revocation_response = self.get('/OS-REVOKE/events',
                                       expected_status=200)
        revocation_events = revocation_response.json_body['events']
        found = False
        for event in revocation_events:
            if event.get('OS-TRUST:trust_id') == trust_id:
                found = True
        self.assertTrue(found, 'event with trust_id %s not found in list' %
                        trust_id)

    def test_delete_trust_revokes_tokens(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r)
        trust_id = trust['id']
        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust_id)
        r = self.v3_authenticate_token(auth_data)
        self.assertValidProjectTrustScopedTokenResponse(
            r, self.trustee_user)
        trust_token = r.headers['X-Subject-Token']
        self.delete('/OS-TRUST/trusts/%(trust_id)s' % {
            'trust_id': trust_id},
            expected_status=204)
        headers = {'X-Subject-Token': trust_token}
        self.head('/auth/tokens', headers=headers, expected_status=404)
        self.assertTrustTokensRevoked(trust_id)

    def disable_user(self, user):
        user['enabled'] = False
        self.identity_api.update_user(user['id'], user)

    def test_trust_get_token_fails_if_trustor_disabled(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})

        trust = self.assertValidTrustResponse(r, ref)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        self.v3_authenticate_token(auth_data, expected_status=201)

        self.disable_user(self.user)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        self.v3_authenticate_token(auth_data, expected_status=403)

    def test_trust_get_token_fails_if_trustee_disabled(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})

        trust = self.assertValidTrustResponse(r, ref)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        self.v3_authenticate_token(auth_data, expected_status=201)

        self.disable_user(self.trustee_user)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_delete_trust(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})

        trust = self.assertValidTrustResponse(r, ref)

        self.delete('/OS-TRUST/trusts/%(trust_id)s' % {
            'trust_id': trust['id']},
            expected_status=204)

        self.get('/OS-TRUST/trusts/%(trust_id)s' % {
            'trust_id': trust['id']},
            expected_status=404)

        self.get('/OS-TRUST/trusts/%(trust_id)s' % {
            'trust_id': trust['id']},
            expected_status=404)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        self.v3_authenticate_token(auth_data, expected_status=401)

    def test_list_trusts(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        for i in range(3):
            r = self.post('/OS-TRUST/trusts', body={'trust': ref})
            self.assertValidTrustResponse(r, ref)

        r = self.get('/OS-TRUST/trusts', expected_status=200)
        trusts = r.result['trusts']
        self.assertEqual(3, len(trusts))
        self.assertValidTrustListResponse(r)

        r = self.get('/OS-TRUST/trusts?trustor_user_id=%s' %
                     self.user_id, expected_status=200)
        trusts = r.result['trusts']
        self.assertEqual(3, len(trusts))
        self.assertValidTrustListResponse(r)

        r = self.get('/OS-TRUST/trusts?trustee_user_id=%s' %
                     self.user_id, expected_status=200)
        trusts = r.result['trusts']
        self.assertEqual(0, len(trusts))

    def test_change_password_invalidates_trust_tokens(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=True,
            expires=dict(minutes=1),
            role_ids=[self.role_id])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'],
            trust_id=trust['id'])
        r = self.v3_authenticate_token(auth_data)

        self.assertValidProjectTrustScopedTokenResponse(r, self.user)
        trust_token = r.headers.get('X-Subject-Token')

        self.get('/OS-TRUST/trusts?trustor_user_id=%s' %
                 self.user_id, expected_status=200,
                 token=trust_token)

        self.assertValidUserResponse(
            self.patch('/users/%s' % self.trustee_user['id'],
                       body={'user': {'password': uuid.uuid4().hex}},
                       expected_status=200))

        self.get('/OS-TRUST/trusts?trustor_user_id=%s' %
                 self.user_id, expected_status=401,
                 token=trust_token)

    def test_trustee_can_do_role_ops(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=True,
            role_ids=[self.role_id])

        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r)

        auth_data = self.build_authentication_request(
            user_id=self.trustee_user['id'],
            password=self.trustee_user['password'])

        r = self.get(
            '/OS-TRUST/trusts/%(trust_id)s/roles' % {
                'trust_id': trust['id']},
            auth=auth_data)
        self.assertValidRoleListResponse(r, self.role)

        self.head(
            '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' % {
                'trust_id': trust['id'],
                'role_id': self.role['id']},
            auth=auth_data,
            expected_status=200)

        r = self.get(
            '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' % {
                'trust_id': trust['id'],
                'role_id': self.role['id']},
            auth=auth_data,
            expected_status=200)
        self.assertValidRoleResponse(r, self.role)

    def test_do_not_consume_remaining_uses_when_get_token_fails(self):
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=self.trustee_user_id,
            project_id=self.project_id,
            impersonation=False,
            expires=dict(minutes=1),
            role_ids=[self.role_id],
            remaining_uses=3)
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})

        new_trust = r.result.get('trust')
        trust_id = new_trust.get('id')
        # Pass in another user's ID as the trustee, the result being a failed
        # token authenticate and the remaining_uses of the trust should not be
        # decremented.
        auth_data = self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            trust_id=trust_id)
        self.v3_authenticate_token(auth_data, expected_status=403)

        r = self.get('/OS-TRUST/trusts/%s' % trust_id)
        self.assertEqual(3, r.result.get('trust').get('remaining_uses'))


class TestAPIProtectionWithoutAuthContextMiddleware(test_v3.RestfulTestCase):
    def test_api_protection_with_no_auth_context_in_env(self):
        auth_data = self.build_authentication_request(
            user_id=self.default_domain_user['id'],
            password=self.default_domain_user['password'],
            project_id=self.project['id'])
        token = self.get_requested_token(auth_data)
        auth_controller = auth.controllers.Auth()
        # all we care is that auth context is not in the environment and
        # 'token_id' is used to build the auth context instead
        context = {'subject_token_id': token,
                   'token_id': token,
                   'query_string': {},
                   'environment': {}}
        r = auth_controller.validate_token(context)
        self.assertEqual(200, r.status_code)


class TestAuthContext(tests.TestCase):
    def setUp(self):
        super(TestAuthContext, self).setUp()
        self.auth_context = auth.controllers.AuthContext()

    def test_pick_lowest_expires_at(self):
        expires_at_1 = utils.isotime(timeutils.utcnow())
        expires_at_2 = utils.isotime(timeutils.utcnow() +
                                     datetime.timedelta(seconds=10))
        # make sure auth_context picks the lowest value
        self.auth_context['expires_at'] = expires_at_1
        self.auth_context['expires_at'] = expires_at_2
        self.assertEqual(expires_at_1, self.auth_context['expires_at'])

    def test_identity_attribute_conflict(self):
        for identity_attr in auth.controllers.AuthContext.IDENTITY_ATTRIBUTES:
            self.auth_context[identity_attr] = uuid.uuid4().hex
            if identity_attr == 'expires_at':
                # 'expires_at' is a special case. Will test it in a separate
                # test case.
                continue
            self.assertRaises(exception.Unauthorized,
                              operator.setitem,
                              self.auth_context,
                              identity_attr,
                              uuid.uuid4().hex)

    def test_identity_attribute_conflict_with_none_value(self):
        for identity_attr in auth.controllers.AuthContext.IDENTITY_ATTRIBUTES:
            self.auth_context[identity_attr] = None

            if identity_attr == 'expires_at':
                # 'expires_at' is a special case and is tested above.
                self.auth_context['expires_at'] = uuid.uuid4().hex
                continue

            self.assertRaises(exception.Unauthorized,
                              operator.setitem,
                              self.auth_context,
                              identity_attr,
                              uuid.uuid4().hex)

    def test_non_identity_attribute_conflict_override(self):
        # for attributes Keystone doesn't know about, make sure they can be
        # freely manipulated
        attr_name = uuid.uuid4().hex
        attr_val_1 = uuid.uuid4().hex
        attr_val_2 = uuid.uuid4().hex
        self.auth_context[attr_name] = attr_val_1
        self.auth_context[attr_name] = attr_val_2
        self.assertEqual(attr_val_2, self.auth_context[attr_name])


class TestAuthSpecificData(test_v3.RestfulTestCase):

    def test_get_catalog_project_scoped_token(self):
        """Call ``GET /auth/catalog`` with a project-scoped token."""
        r = self.get(
            '/auth/catalog',
            expected_status=200)
        self.assertValidCatalogResponse(r)

    def test_get_catalog_domain_scoped_token(self):
        """Call ``GET /auth/catalog`` with a domain-scoped token."""
        # grant a domain role to a user
        self.put(path='/domains/%s/users/%s/roles/%s' % (
            self.domain['id'], self.user['id'], self.role['id']))

        self.get(
            '/auth/catalog',
            auth=self.build_authentication_request(
                user_id=self.user['id'],
                password=self.user['password'],
                domain_id=self.domain['id']),
            expected_status=403)

    def test_get_catalog_unscoped_token(self):
        """Call ``GET /auth/catalog`` with an unscoped token."""
        self.get(
            '/auth/catalog',
            auth=self.build_authentication_request(
                user_id=self.default_domain_user['id'],
                password=self.default_domain_user['password']),
            expected_status=403)

    def test_get_catalog_no_token(self):
        """Call ``GET /auth/catalog`` without a token."""
        self.get(
            '/auth/catalog',
            noauth=True,
            expected_status=401)

    def test_get_projects_project_scoped_token(self):
        r = self.get('/auth/projects', expected_status=200)
        self.assertThat(r.json['projects'], matchers.HasLength(1))
        self.assertValidProjectListResponse(r)

    def test_get_domains_project_scoped_token(self):
        self.put(path='/domains/%s/users/%s/roles/%s' % (
            self.domain['id'], self.user['id'], self.role['id']))

        r = self.get('/auth/domains', expected_status=200)
        self.assertThat(r.json['domains'], matchers.HasLength(1))
        self.assertValidDomainListResponse(r)


class TestFernetTokenProvider(test_v3.RestfulTestCase):
    def setUp(self):
        super(TestFernetTokenProvider, self).setUp()
        self.useFixture(ksfixtures.KeyRepository(self.config_fixture))

    def _make_auth_request(self, auth_data):
        resp = self.post('/auth/tokens', body=auth_data, expected_status=201)
        token = resp.headers.get('X-Subject-Token')
        self.assertLess(len(token), 255)
        return token

    def _get_unscoped_token(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'])
        return self._make_auth_request(auth_data)

    def _get_project_scoped_token(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=self.project_id)
        return self._make_auth_request(auth_data)

    def _get_domain_scoped_token(self):
        auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            domain_id=self.domain_id)
        return self._make_auth_request(auth_data)

    def _get_trust_scoped_token(self, trustee_user, trust):
        auth_data = self.build_authentication_request(
            user_id=trustee_user['id'],
            password=trustee_user['password'],
            trust_id=trust['id'])
        return self._make_auth_request(auth_data)

    def _validate_token(self, token, expected_status=200):
        return self.get(
            '/auth/tokens',
            headers={'X-Subject-Token': token},
            expected_status=expected_status)

    def _revoke_token(self, token, expected_status=204):
        return self.delete(
            '/auth/tokens',
            headers={'X-Subject-Token': token},
            expected_status=expected_status)

    def _set_user_enabled(self, user, enabled=True):
        user['enabled'] = enabled
        self.identity_api.update_user(user['id'], user)

    def _create_trust(self):
        # Create a trustee user
        trustee_user_ref = self.new_user_ref(domain_id=self.domain_id)
        trustee_user = self.identity_api.create_user(trustee_user_ref)
        trustee_user['password'] = trustee_user_ref['password']
        ref = self.new_trust_ref(
            trustor_user_id=self.user_id,
            trustee_user_id=trustee_user['id'],
            project_id=self.project_id,
            impersonation=False,
            role_ids=[self.role_id])

        # Create a trust
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = self.assertValidTrustResponse(r)
        return (trustee_user, trust)

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

    def test_validate_unscoped_token(self):
        unscoped_token = self._get_unscoped_token()
        self._validate_token(unscoped_token)

    def test_validate_tampered_unscoped_token_fails(self):
        unscoped_token = self._get_unscoped_token()
        tampered_token = (unscoped_token[:50] + uuid.uuid4().hex +
                          unscoped_token[50 + 32:])
        self._validate_token(tampered_token, expected_status=404)

    def test_revoke_unscoped_token(self):
        unscoped_token = self._get_unscoped_token()
        self._validate_token(unscoped_token)
        self._revoke_token(unscoped_token)
        self._validate_token(unscoped_token, expected_status=404)

    def test_unscoped_token_is_invalid_after_disabling_user(self):
        unscoped_token = self._get_unscoped_token()
        # Make sure the token is valid
        self._validate_token(unscoped_token)
        # Disable the user
        self._set_user_enabled(self.user, enabled=False)
        # Ensure validating a token for a disabled user fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          unscoped_token)

    def test_unscoped_token_is_invalid_after_enabling_disabled_user(self):
        unscoped_token = self._get_unscoped_token()
        # Make sure the token is valid
        self._validate_token(unscoped_token)
        # Disable the user
        self._set_user_enabled(self.user, enabled=False)
        # Ensure validating a token for a disabled user fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          unscoped_token)
        # Enable the user
        self._set_user_enabled(self.user)
        # Ensure validating a token for a re-enabled user fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          unscoped_token)

    def test_unscoped_token_is_invalid_after_disabling_user_domain(self):
        unscoped_token = self._get_unscoped_token()
        # Make sure the token is valid
        self._validate_token(unscoped_token)
        # Disable the user's domain
        self.domain['enabled'] = False
        self.resource_api.update_domain(self.domain['id'], self.domain)
        # Ensure validating a token for a disabled user fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          unscoped_token)

    def test_unscoped_token_is_invalid_after_changing_user_password(self):
        unscoped_token = self._get_unscoped_token()
        # Make sure the token is valid
        self._validate_token(unscoped_token)
        # Change user's password
        self.user['password'] = 'Password1'
        self.identity_api.update_user(self.user['id'], self.user)
        # Ensure updating user's password revokes existing user's tokens
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          unscoped_token)

    def test_validate_project_scoped_token(self):
        project_scoped_token = self._get_project_scoped_token()
        self._validate_token(project_scoped_token)

    def test_validate_domain_scoped_token(self):
        # Grant user access to domain
        self.assignment_api.create_grant(self.role['id'],
                                         user_id=self.user['id'],
                                         domain_id=self.domain['id'])
        domain_scoped_token = self._get_domain_scoped_token()
        resp = self._validate_token(domain_scoped_token)
        resp_json = json.loads(resp.body)
        self.assertIsNotNone(resp_json['token']['catalog'])
        self.assertIsNotNone(resp_json['token']['roles'])
        self.assertIsNotNone(resp_json['token']['domain'])

    def test_validate_tampered_project_scoped_token_fails(self):
        project_scoped_token = self._get_project_scoped_token()
        tampered_token = (project_scoped_token[:50] + uuid.uuid4().hex +
                          project_scoped_token[50 + 32:])
        self._validate_token(tampered_token, expected_status=404)

    def test_revoke_project_scoped_token(self):
        project_scoped_token = self._get_project_scoped_token()
        self._validate_token(project_scoped_token)
        self._revoke_token(project_scoped_token)
        self._validate_token(project_scoped_token, expected_status=404)

    def test_project_scoped_token_is_invalid_after_disabling_user(self):
        project_scoped_token = self._get_project_scoped_token()
        # Make sure the token is valid
        self._validate_token(project_scoped_token)
        # Disable the user
        self._set_user_enabled(self.user, enabled=False)
        # Ensure validating a token for a disabled user fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          project_scoped_token)

    def test_domain_scoped_token_is_invalid_after_disabling_user(self):
        # Grant user access to domain
        self.assignment_api.create_grant(self.role['id'],
                                         user_id=self.user['id'],
                                         domain_id=self.domain['id'])
        domain_scoped_token = self._get_domain_scoped_token()
        # Make sure the token is valid
        self._validate_token(domain_scoped_token)
        # Disable user
        self._set_user_enabled(self.user, enabled=False)
        # Ensure validating a token for a disabled user fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          domain_scoped_token)

    def test_domain_scoped_token_is_invalid_after_deleting_grant(self):
        # Grant user access to domain
        self.assignment_api.create_grant(self.role['id'],
                                         user_id=self.user['id'],
                                         domain_id=self.domain['id'])
        domain_scoped_token = self._get_domain_scoped_token()
        # Make sure the token is valid
        self._validate_token(domain_scoped_token)
        # Delete access to domain
        self.assignment_api.delete_grant(self.role['id'],
                                         user_id=self.user['id'],
                                         domain_id=self.domain['id'])
        # Ensure validating a token for a disabled user fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          domain_scoped_token)

    def test_project_scoped_token_invalid_after_changing_user_password(self):
        project_scoped_token = self._get_project_scoped_token()
        # Make sure the token is valid
        self._validate_token(project_scoped_token)
        # Update user's password
        self.user['password'] = 'Password1'
        self.identity_api.update_user(self.user['id'], self.user)
        # Ensure updating user's password revokes existing tokens
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          project_scoped_token)

    def test_project_scoped_token_invalid_after_disabling_project(self):
        project_scoped_token = self._get_project_scoped_token()
        # Make sure the token is valid
        self._validate_token(project_scoped_token)
        # Disable project
        self.project['enabled'] = False
        self.resource_api.update_project(self.project['id'], self.project)
        # Ensure validating a token for a disabled project fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          project_scoped_token)

    def test_domain_scoped_token_invalid_after_disabling_domain(self):
        # Grant user access to domain
        self.assignment_api.create_grant(self.role['id'],
                                         user_id=self.user['id'],
                                         domain_id=self.domain['id'])
        domain_scoped_token = self._get_domain_scoped_token()
        # Make sure the token is valid
        self._validate_token(domain_scoped_token)
        # Disable domain
        self.domain['enabled'] = False
        self.resource_api.update_domain(self.domain['id'], self.domain)
        # Ensure validating a token for a disabled domain fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          domain_scoped_token)

    def test_rescope_unscoped_token_with_trust(self):
        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        self.assertLess(len(trust_scoped_token), 255)

    def test_validate_a_trust_scoped_token(self):
        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        # Validate a trust scoped token
        self._validate_token(trust_scoped_token)

    def test_validate_tampered_trust_scoped_token_fails(self):
        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        # Get a trust scoped token
        tampered_token = (trust_scoped_token[:50] + uuid.uuid4().hex +
                          trust_scoped_token[50 + 32:])
        self._validate_token(tampered_token, expected_status=404)

    def test_revoke_trust_scoped_token(self):
        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        # Validate a trust scoped token
        self._validate_token(trust_scoped_token)
        self._revoke_token(trust_scoped_token)
        self._validate_token(trust_scoped_token, expected_status=404)

    def test_trust_scoped_token_is_invalid_after_disabling_trustee(self):
        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        # Validate a trust scoped token
        self._validate_token(trust_scoped_token)

        # Disable trustee
        trustee_update_ref = dict(enabled=False)
        self.identity_api.update_user(trustee_user['id'], trustee_update_ref)
        # Ensure validating a token for a disabled user fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          trust_scoped_token)

    def test_trust_scoped_token_invalid_after_changing_trustee_password(self):
        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        # Validate a trust scoped token
        self._validate_token(trust_scoped_token)
        # Change trustee's password
        trustee_update_ref = dict(password='Password1')
        self.identity_api.update_user(trustee_user['id'], trustee_update_ref)
        # Ensure updating trustee's password revokes existing tokens
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          trust_scoped_token)

    def test_trust_scoped_token_is_invalid_after_disabling_trustor(self):
        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        # Validate a trust scoped token
        self._validate_token(trust_scoped_token)

        # Disable the trustor
        trustor_update_ref = dict(enabled=False)
        self.identity_api.update_user(self.user['id'], trustor_update_ref)
        # Ensure validating a token for a disabled user fails
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          trust_scoped_token)

    def test_trust_scoped_token_invalid_after_changing_trustor_password(self):
        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        # Validate a trust scoped token
        self._validate_token(trust_scoped_token)

        # Change trustor's password
        trustor_update_ref = dict(password='Password1')
        self.identity_api.update_user(self.user['id'], trustor_update_ref)
        # Ensure updating trustor's password revokes existing user's tokens
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          trust_scoped_token)

    def test_trust_scoped_token_invalid_after_disabled_trustor_domain(self):
        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        # Validate a trust scoped token
        self._validate_token(trust_scoped_token)

        # Disable trustor's domain
        self.domain['enabled'] = False
        self.resource_api.update_domain(self.domain['id'], self.domain)

        trustor_update_ref = dict(password='Password1')
        self.identity_api.update_user(self.user['id'], trustor_update_ref)
        # Ensure updating trustor's password revokes existing user's tokens
        self.assertRaises(exception.TokenNotFound,
                          self.token_provider_api.validate_token,
                          trust_scoped_token)

    def test_v2_validate_unscoped_token_returns_401(self):
        """Test raised exception when validating unscoped token.

        Test that validating an unscoped token in v2.0 of a v3 user of a
        non-default domain returns unauthorized.
        """
        unscoped_token = self._get_unscoped_token()
        self.assertRaises(exception.Unauthorized,
                          self.token_provider_api.validate_v2_token,
                          unscoped_token)

    def test_v2_validate_domain_scoped_token_returns_401(self):
        """Test raised exception when validating a domain scoped token.

        Test that validating an domain scoped token in v2.0
        returns unauthorized.
        """

        # Grant user access to domain
        self.assignment_api.create_grant(self.role['id'],
                                         user_id=self.user['id'],
                                         domain_id=self.domain['id'])

        scoped_token = self._get_domain_scoped_token()
        self.assertRaises(exception.Unauthorized,
                          self.token_provider_api.validate_v2_token,
                          scoped_token)

    def test_v2_validate_trust_scoped_token(self):
        """Test raised exception when validating a trust scoped token.

        Test that validating an trust scoped token in v2.0 returns
        unauthorized.
        """

        trustee_user, trust = self._create_trust()
        trust_scoped_token = self._get_trust_scoped_token(trustee_user, trust)
        self.assertRaises(exception.Unauthorized,
                          self.token_provider_api.validate_v2_token,
                          trust_scoped_token)


class TestAuthFernetTokenProvider(TestAuth):
    def setUp(self):
        super(TestAuthFernetTokenProvider, self).setUp()
        self.useFixture(ksfixtures.KeyRepository(self.config_fixture))

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

    def test_verify_with_bound_token(self):
        self.config_fixture.config(group='token', bind='kerberos')
        auth_data = self.build_authentication_request(
            project_id=self.project['id'])
        remote_user = self.default_domain_user['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'AUTH_TYPE': 'Negotiate'})
        # Bind not current supported by Fernet, see bug 1433311.
        self.v3_authenticate_token(auth_data, expected_status=501)

    def test_v2_v3_bind_token_intermix(self):
        self.config_fixture.config(group='token', bind='kerberos')

        # we need our own user registered to the default domain because of
        # the way external auth works.
        remote_user = self.default_domain_user['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'AUTH_TYPE': 'Negotiate'})
        body = {'auth': {}}
        # Bind not current supported by Fernet, see bug 1433311.
        self.admin_request(path='/v2.0/tokens',
                           method='POST',
                           body=body,
                           expected_status=501)

    def test_auth_with_bind_token(self):
        self.config_fixture.config(group='token', bind=['kerberos'])

        auth_data = self.build_authentication_request()
        remote_user = self.default_domain_user['name']
        self.admin_app.extra_environ.update({'REMOTE_USER': remote_user,
                                             'AUTH_TYPE': 'Negotiate'})
        # Bind not current supported by Fernet, see bug 1433311.
        self.v3_authenticate_token(auth_data, expected_status=501)