summaryrefslogtreecommitdiff
path: root/keystone/tests/unit/test_v3_assignment.py
blob: 3bc15af6ed1bcff248dbfcdfe57b83b0f5aca17d (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
# 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 datetime
import random
import uuid

import freezegun
from six.moves import http_client
from six.moves import range
from testtools import matchers

from keystone.common import provider_api
import keystone.conf
from keystone import exception
from keystone.resource.backends import base as resource_base
from keystone.tests import unit
from keystone.tests.unit import test_v3
from keystone.tests.unit import utils as test_utils


CONF = keystone.conf.CONF
PROVIDERS = provider_api.ProviderAPIs


class SystemRoleAssignmentMixin(object):

    def _create_new_role(self):
        """Create a role available for use anywhere and return the ID."""
        ref = unit.new_role_ref()
        response = self.post('/roles', body={'role': ref})
        # We only really need the role ID, so omit the rest of the response and
        # return the ID of the role we just created.
        return response.json_body['role']['id']

    def _create_group(self):
        body = {
            'group': {
                'domain_id': self.domain_id,
                'name': uuid.uuid4().hex
            }
        }
        response = self.post('/groups/', body=body)
        return response.json_body['group']

    def _create_user(self):
        body = {
            'user': {
                'domain_id': self.domain_id,
                'name': uuid.uuid4().hex
            }
        }
        response = self.post('/users/', body=body)
        return response.json_body['user']


class AssignmentTestCase(test_v3.RestfulTestCase,
                         test_v3.AssignmentTestMixin,
                         SystemRoleAssignmentMixin):
    """Test roles and role assignments."""

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

        self.group = unit.new_group_ref(domain_id=self.domain_id)
        self.group = PROVIDERS.identity_api.create_group(self.group)
        self.group_id = self.group['id']

    # Role CRUD tests

    def test_create_role(self):
        """Call ``POST /roles``."""
        ref = unit.new_role_ref()
        r = self.post(
            '/roles',
            body={'role': ref})
        return self.assertValidRoleResponse(r, ref)

    def test_create_role_bad_request(self):
        """Call ``POST /roles``."""
        self.post('/roles', body={'role': {}},
                  expected_status=http_client.BAD_REQUEST)

    def test_list_head_roles(self):
        """Call ``GET & HEAD /roles``."""
        resource_url = '/roles'
        r = self.get(resource_url)
        self.assertValidRoleListResponse(r, ref=self.role,
                                         resource_url=resource_url)
        self.head(resource_url, expected_status=http_client.OK)

    def test_get_head_role(self):
        """Call ``GET & HEAD /roles/{role_id}``."""
        resource_url = '/roles/%(role_id)s' % {
            'role_id': self.role_id}
        r = self.get(resource_url)
        self.assertValidRoleResponse(r, self.role)
        self.head(resource_url, expected_status=http_client.OK)

    def test_update_role(self):
        """Call ``PATCH /roles/{role_id}``."""
        ref = unit.new_role_ref()
        del ref['id']
        r = self.patch('/roles/%(role_id)s' % {
            'role_id': self.role_id},
            body={'role': ref})
        self.assertValidRoleResponse(r, ref)

    def test_delete_role(self):
        """Call ``DELETE /roles/{role_id}``."""
        self.delete('/roles/%(role_id)s' % {
            'role_id': self.role_id})

    # Role Grants tests

    def test_crud_user_project_role_grants(self):
        role = unit.new_role_ref()
        PROVIDERS.role_api.create_role(role['id'], role)

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

        # There is a role assignment for self.user on self.project
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, ref=self.role,
                                         expected_length=1)

        self.put(member_url)
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, ref=role,
                                         resource_url=collection_url,
                                         expected_length=2)
        self.head(collection_url, expected_status=http_client.OK)

        self.delete(member_url)
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, ref=self.role, expected_length=1)
        self.assertIn(collection_url, r.result['links']['self'])
        self.head(collection_url, expected_status=http_client.OK)

    def test_crud_user_project_role_grants_no_user(self):
        """Grant role on a project to a user that doesn't exist.

        When grant a role on a project to a user that doesn't exist, the server
        returns Not Found for the user.

        """
        user_id = uuid.uuid4().hex

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

        self.put(member_url, expected_status=http_client.NOT_FOUND)
        self.head(member_url, expected_status=http_client.NOT_FOUND)
        self.get(member_url, expected_status=http_client.NOT_FOUND)

    def test_crud_user_domain_role_grants(self):
        time = datetime.datetime.utcnow()
        with freezegun.freeze_time(time) as frozen_datetime:
            collection_url = (
                '/domains/%(domain_id)s/users/%(user_id)s/roles' % {
                    'domain_id': self.domain_id,
                    'user_id': self.user['id']})
            member_url = '%(collection_url)s/%(role_id)s' % {
                'collection_url': collection_url,
                'role_id': self.role_id}

            self.put(member_url)
            self.head(member_url)
            self.get(member_url, expected_status=http_client.NO_CONTENT)
            r = self.get(collection_url)
            self.assertValidRoleListResponse(r, ref=self.role,
                                             resource_url=collection_url)
            self.head(collection_url, expected_status=http_client.OK)

            self.delete(member_url)
            # NOTE(lbragstad): Make sure we wait a second before we ask for the
            # roles. This ensures the token we use isn't considered revoked
            # because it was issued within the same second as a revocation
            # event.
            frozen_datetime.tick(delta=datetime.timedelta(seconds=1))
            r = self.get(collection_url)
            self.assertValidRoleListResponse(r, expected_length=0,
                                             resource_url=collection_url)
            self.head(collection_url, expected_status=http_client.OK)

    def test_crud_user_domain_role_grants_no_user(self):
        """Grant role on a domain to a user that doesn't exist.

        When grant a role on a domain to a user that doesn't exist, the server
        returns 404 Not Found for the user.

        """
        user_id = uuid.uuid4().hex

        collection_url = (
            '/domains/%(domain_id)s/users/%(user_id)s/roles' % {
                'domain_id': self.domain_id, 'user_id': user_id})
        member_url = '%(collection_url)s/%(role_id)s' % {
            'collection_url': collection_url,
            'role_id': self.role_id}

        self.put(member_url, expected_status=http_client.NOT_FOUND)
        self.head(member_url, expected_status=http_client.NOT_FOUND)
        self.get(member_url, expected_status=http_client.NOT_FOUND)

    def test_crud_group_project_role_grants(self):
        time = datetime.datetime.utcnow()
        with freezegun.freeze_time(time) as frozen_datetime:
            collection_url = (
                '/projects/%(project_id)s/groups/%(group_id)s/roles' % {
                    'project_id': self.project_id,
                    'group_id': self.group_id})
            member_url = '%(collection_url)s/%(role_id)s' % {
                'collection_url': collection_url,
                'role_id': self.role_id}

            self.put(member_url)
            self.head(member_url)
            self.get(member_url, expected_status=http_client.NO_CONTENT)
            r = self.get(collection_url)
            self.assertValidRoleListResponse(r, ref=self.role,
                                             resource_url=collection_url)
            self.head(collection_url, expected_status=http_client.OK)

            self.delete(member_url)
            # NOTE(lbragstad): Make sure we wait a second before we ask for the
            # roles. This ensures the token we use isn't considered revoked
            # because it was issued within the same second as a revocation
            # event.
            frozen_datetime.tick(delta=datetime.timedelta(seconds=1))
            r = self.get(collection_url)
            self.assertValidRoleListResponse(r, expected_length=0,
                                             resource_url=collection_url)
            self.head(collection_url, expected_status=http_client.OK)

    def test_crud_group_project_role_grants_no_group(self):
        """Grant role on a project to a group that doesn't exist.

        When grant a role on a project to a group that doesn't exist, the
        server returns 404 Not Found for the group.

        """
        group_id = uuid.uuid4().hex

        collection_url = (
            '/projects/%(project_id)s/groups/%(group_id)s/roles' % {
                'project_id': self.project_id,
                'group_id': group_id})
        member_url = '%(collection_url)s/%(role_id)s' % {
            'collection_url': collection_url,
            'role_id': self.role_id}

        self.put(member_url, expected_status=http_client.NOT_FOUND)
        self.head(member_url, expected_status=http_client.NOT_FOUND)
        self.get(member_url, expected_status=http_client.NOT_FOUND)

    def test_crud_group_domain_role_grants(self):
        time = datetime.datetime.utcnow()
        with freezegun.freeze_time(time) as frozen_datetime:
            collection_url = (
                '/domains/%(domain_id)s/groups/%(group_id)s/roles' % {
                    'domain_id': self.domain_id,
                    'group_id': self.group_id})
            member_url = '%(collection_url)s/%(role_id)s' % {
                'collection_url': collection_url,
                'role_id': self.role_id}

            self.put(member_url)
            self.head(member_url)
            self.get(member_url, expected_status=http_client.NO_CONTENT)
            r = self.get(collection_url)
            self.assertValidRoleListResponse(r, ref=self.role,
                                             resource_url=collection_url)
            self.head(collection_url, expected_status=http_client.OK)

            self.delete(member_url)
            # NOTE(lbragstad): Make sure we wait a second before we ask for the
            # roles. This ensures the token we use isn't considered revoked
            # because it was issued within the same second as a revocation
            # event.
            frozen_datetime.tick(delta=datetime.timedelta(seconds=1))
            r = self.get(collection_url)
            self.assertValidRoleListResponse(r, expected_length=0,
                                             resource_url=collection_url)
            self.head(collection_url, expected_status=http_client.OK)

    def test_crud_group_domain_role_grants_no_group(self):
        """Grant role on a domain to a group that doesn't exist.

        When grant a role on a domain to a group that doesn't exist, the server
        returns 404 Not Found for the group.

        """
        group_id = uuid.uuid4().hex

        collection_url = (
            '/domains/%(domain_id)s/groups/%(group_id)s/roles' % {
                'domain_id': self.domain_id,
                'group_id': group_id})
        member_url = '%(collection_url)s/%(role_id)s' % {
            'collection_url': collection_url,
            'role_id': self.role_id}

        self.put(member_url, expected_status=http_client.NOT_FOUND)
        self.head(member_url, expected_status=http_client.NOT_FOUND)
        self.get(member_url, expected_status=http_client.NOT_FOUND)

    def _create_new_user_and_assign_role_on_project(self):
        """Create a new user and assign user a role on a project."""
        # Create a new user
        new_user = unit.new_user_ref(domain_id=self.domain_id)
        user_ref = PROVIDERS.identity_api.create_user(new_user)
        # Assign the user a role on the project
        collection_url = (
            '/projects/%(project_id)s/users/%(user_id)s/roles' % {
                'project_id': self.project_id,
                'user_id': user_ref['id']})
        member_url = ('%(collection_url)s/%(role_id)s' % {
            'collection_url': collection_url,
            'role_id': self.role_id})
        self.put(member_url)
        # Check the user has the role assigned
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        return member_url, user_ref

    def test_delete_user_before_removing_role_assignment_succeeds(self):
        """Call ``DELETE`` on the user before the role assignment."""
        member_url, user = self._create_new_user_and_assign_role_on_project()
        # Delete the user from identity backend
        PROVIDERS.identity_api.driver.delete_user(user['id'])
        # Clean up the role assignment
        self.delete(member_url)
        # Make sure the role is gone
        self.head(member_url, expected_status=http_client.NOT_FOUND)

    def test_delete_group_before_removing_role_assignment_succeeds(self):
        # Disable the cache so that we perform a fresh check of the identity
        # backend when attempting to remove the role assignment.
        self.config_fixture.config(group='cache', enabled=False)

        # Create a new group
        group = unit.new_group_ref(domain_id=self.domain_id)
        group_ref = PROVIDERS.identity_api.create_group(group)

        # Assign the user a role on the project
        collection_url = (
            '/projects/%(project_id)s/groups/%(group_id)s/roles' % {
                'project_id': self.project_id,
                'group_id': group_ref['id']})
        member_url = ('%(collection_url)s/%(role_id)s' % {
            'collection_url': collection_url,
            'role_id': self.role_id})
        self.put(member_url)

        # Check the user has the role assigned
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)

        # Simulate removing the group via LDAP by directly removing it from the
        # identity backend.
        PROVIDERS.identity_api.driver.delete_group(group_ref['id'])

        # Ensure we can clean up the role assignment even though the group
        # doesn't exist
        self.delete(member_url)

    def test_delete_user_before_removing_system_assignments_succeeds(self):
        system_role = self._create_new_role()
        user = self._create_user()
        path = (
            '/system/users/%(user_id)s/roles/%(role_id)s' %
            {'user_id': user['id'], 'role_id': system_role}
        )
        self.put(path)

        response = self.get('/role_assignments')
        number_of_assignments = len(response.json_body['role_assignments'])

        path = '/users/%(user_id)s' % {'user_id': user['id']}
        self.delete(path)

        # The user with the system role assignment is a new user and only has
        # one role on the system. We should expect one less role assignment in
        # the list.
        response = self.get('/role_assignments')
        self.assertValidRoleAssignmentListResponse(
            response, expected_length=number_of_assignments - 1
        )

    def test_delete_user_and_check_role_assignment_fails(self):
        """Call ``DELETE`` on the user and check the role assignment."""
        member_url, user = self._create_new_user_and_assign_role_on_project()
        # Delete the user from identity backend
        PROVIDERS.identity_api.delete_user(user['id'])
        # We should get a 404 Not Found when looking for the user in the
        # identity backend because we're not performing a delete operation on
        # the role.
        self.head(member_url, expected_status=http_client.NOT_FOUND)

    def test_token_revoked_once_group_role_grant_revoked(self):
        """Test token invalid when direct & indirect role on user is revoked.

        When a role granted to a group is revoked for a given scope,
        and user direct role is revoked, then tokens created
        by user will be invalid.

        """
        time = datetime.datetime.utcnow()
        with freezegun.freeze_time(time) as frozen_datetime:
            # creates grant from group on project.
            PROVIDERS.assignment_api.create_grant(
                role_id=self.role['id'], project_id=self.project['id'],
                group_id=self.group['id']
            )

            # adds user to the group.
            PROVIDERS.identity_api.add_user_to_group(
                user_id=self.user['id'], group_id=self.group['id']
            )

            # creates a token for the user
            auth_body = self.build_authentication_request(
                user_id=self.user['id'],
                password=self.user['password'],
                project_id=self.project['id'])
            token_resp = self.post('/auth/tokens', body=auth_body)
            token = token_resp.headers.get('x-subject-token')

            # validates the returned token; it should be valid.
            self.head('/auth/tokens',
                      headers={'x-subject-token': token},
                      expected_status=http_client.OK)

            frozen_datetime.tick(delta=datetime.timedelta(seconds=1))
            # revokes the grant from group on project.
            PROVIDERS.assignment_api.delete_grant(
                role_id=self.role['id'], project_id=self.project['id'],
                group_id=self.group['id'])
            # revokes the direct role form user on project
            PROVIDERS.assignment_api.delete_grant(
                role_id=self.role['id'], project_id=self.project['id'],
                user_id=self.user['id']
            )

            frozen_datetime.tick(delta=datetime.timedelta(seconds=1))
            # validates the same token again; it should not longer be valid.
            self.head('/auth/tokens', token=token,
                      expected_status=http_client.UNAUTHORIZED)

    def test_delete_group_before_removing_system_assignments_succeeds(self):
        system_role = self._create_new_role()
        group = self._create_group()
        path = (
            '/system/groups/%(group_id)s/roles/%(role_id)s' %
            {'group_id': group['id'], 'role_id': system_role}
        )
        self.put(path)

        response = self.get('/role_assignments')
        number_of_assignments = len(response.json_body['role_assignments'])

        path = '/groups/%(group_id)s' % {'group_id': group['id']}
        self.delete(path)

        # The group with the system role assignment is a new group and only has
        # one role on the system. We should expect one less role assignment in
        # the list.
        response = self.get('/role_assignments')
        self.assertValidRoleAssignmentListResponse(
            response, expected_length=number_of_assignments - 1
        )

    @unit.skip_if_cache_disabled('assignment')
    def test_delete_grant_from_user_and_project_invalidate_cache(self):
        # create a new project
        new_project = unit.new_project_ref(domain_id=self.domain_id)
        PROVIDERS.resource_api.create_project(new_project['id'], new_project)

        collection_url = (
            '/projects/%(project_id)s/users/%(user_id)s/roles' % {
                'project_id': new_project['id'],
                'user_id': self.user['id']})
        member_url = '%(collection_url)s/%(role_id)s' % {
            'collection_url': collection_url,
            'role_id': self.role_id}

        # create the user a grant on the new project
        self.put(member_url)

        # check the grant that was just created
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        resp = self.get(collection_url)
        self.assertValidRoleListResponse(resp, ref=self.role,
                                         resource_url=collection_url)

        # delete the grant
        self.delete(member_url)

        # get the collection and ensure there are no roles on the project
        resp = self.get(collection_url)
        self.assertListEqual(resp.json_body['roles'], [])

    @unit.skip_if_cache_disabled('assignment')
    def test_delete_grant_from_user_and_domain_invalidates_cache(self):
        # create a new domain
        new_domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(new_domain['id'], new_domain)

        collection_url = (
            '/domains/%(domain_id)s/users/%(user_id)s/roles' % {
                'domain_id': new_domain['id'],
                'user_id': self.user['id']})
        member_url = '%(collection_url)s/%(role_id)s' % {
            'collection_url': collection_url,
            'role_id': self.role_id}

        # create the user a grant on the new domain
        self.put(member_url)

        # check the grant that was just created
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        resp = self.get(collection_url)
        self.assertValidRoleListResponse(resp, ref=self.role,
                                         resource_url=collection_url)

        # delete the grant
        self.delete(member_url)

        # get the collection and ensure there are no roles on the domain
        resp = self.get(collection_url)
        self.assertListEqual(resp.json_body['roles'], [])

    @unit.skip_if_cache_disabled('assignment')
    def test_delete_grant_from_group_and_project_invalidates_cache(self):
        # create a new project
        new_project = unit.new_project_ref(domain_id=self.domain_id)
        PROVIDERS.resource_api.create_project(new_project['id'], new_project)

        collection_url = (
            '/projects/%(project_id)s/groups/%(group_id)s/roles' % {
                'project_id': new_project['id'],
                'group_id': self.group['id']})
        member_url = '%(collection_url)s/%(role_id)s' % {
            'collection_url': collection_url,
            'role_id': self.role_id}

        # create the group a grant on the new project
        self.put(member_url)

        # check the grant that was just created
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        resp = self.get(collection_url)
        self.assertValidRoleListResponse(resp, ref=self.role,
                                         resource_url=collection_url)

        # delete the grant
        self.delete(member_url)

        # get the collection and ensure there are no roles on the project
        resp = self.get(collection_url)
        self.assertListEqual(resp.json_body['roles'], [])

    @unit.skip_if_cache_disabled('assignment')
    def test_delete_grant_from_group_and_domain_invalidates_cache(self):
        # create a new domain
        new_domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(new_domain['id'], new_domain)

        collection_url = (
            '/domains/%(domain_id)s/groups/%(group_id)s/roles' % {
                'domain_id': new_domain['id'],
                'group_id': self.group['id']})
        member_url = '%(collection_url)s/%(role_id)s' % {
            'collection_url': collection_url,
            'role_id': self.role_id}

        # create the group a grant on the new domain
        self.put(member_url)

        # check the grant that was just created
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        resp = self.get(collection_url)
        self.assertValidRoleListResponse(resp, ref=self.role,
                                         resource_url=collection_url)

        # delete the grant
        self.delete(member_url)

        # get the collection and ensure there are no roles on the domain
        resp = self.get(collection_url)
        self.assertListEqual(resp.json_body['roles'], [])

    # Role Assignments tests

    def test_get_head_role_assignments(self):
        """Call ``GET & HEAD /role_assignments``.

        The sample data set up already has a user, group and project
        that is part of self.domain. We use these plus a new user
        we create as our data set, making sure we ignore any
        role assignments that are already in existence.

        Since we don't yet support a first class entity for role
        assignments, we are only testing the LIST API.  To create
        and delete the role assignments we use the old grant APIs.

        Test Plan:

        - Create extra user for tests
        - Get a list of all existing role assignments
        - Add a new assignment for each of the four combinations, i.e.
          group+domain, user+domain, group+project, user+project, using
          the same role each time
        - Get a new list of all role assignments, checking these four new
          ones have been added
        - Then delete the four we added
        - Get a new list of all role assignments, checking the four have
          been removed

        """
        time = datetime.datetime.utcnow()
        with freezegun.freeze_time(time) as frozen_datetime:
            # Since the default fixtures already assign some roles to the
            # user it creates, we also need a new user that will not have any
            # existing assignments
            user1 = unit.new_user_ref(domain_id=self.domain['id'])
            user1 = PROVIDERS.identity_api.create_user(user1)

            role = unit.new_role_ref()
            PROVIDERS.role_api.create_role(role['id'], role)

            collection_url = '/role_assignments'
            r = self.get(collection_url)
            self.assertValidRoleAssignmentListResponse(
                r, resource_url=collection_url)
            self.head(collection_url, expected_status=http_client.OK)
            existing_assignments = len(r.result.get('role_assignments'))

            # Now add one of each of the four types of assignment, making sure
            # that we get them all back.
            gd_entity = self.build_role_assignment_entity(
                domain_id=self.domain_id,
                group_id=self.group_id,
                role_id=role['id'])
            self.put(gd_entity['links']['assignment'])
            r = self.get(collection_url)
            self.assertValidRoleAssignmentListResponse(
                r,
                expected_length=existing_assignments + 1,
                resource_url=collection_url)
            self.assertRoleAssignmentInListResponse(r, gd_entity)
            self.head(collection_url, expected_status=http_client.OK)

            ud_entity = self.build_role_assignment_entity(
                domain_id=self.domain_id,
                user_id=user1['id'],
                role_id=role['id'])
            self.put(ud_entity['links']['assignment'])
            r = self.get(collection_url)
            self.assertValidRoleAssignmentListResponse(
                r,
                expected_length=existing_assignments + 2,
                resource_url=collection_url)
            self.assertRoleAssignmentInListResponse(r, ud_entity)
            self.head(collection_url, expected_status=http_client.OK)

            gp_entity = self.build_role_assignment_entity(
                project_id=self.project_id, group_id=self.group_id,
                role_id=role['id'])
            self.put(gp_entity['links']['assignment'])
            r = self.get(collection_url)
            self.assertValidRoleAssignmentListResponse(
                r,
                expected_length=existing_assignments + 3,
                resource_url=collection_url)
            self.assertRoleAssignmentInListResponse(r, gp_entity)
            self.head(collection_url, expected_status=http_client.OK)

            up_entity = self.build_role_assignment_entity(
                project_id=self.project_id, user_id=user1['id'],
                role_id=role['id'])
            self.put(up_entity['links']['assignment'])
            r = self.get(collection_url)
            self.assertValidRoleAssignmentListResponse(
                r,
                expected_length=existing_assignments + 4,
                resource_url=collection_url)
            self.assertRoleAssignmentInListResponse(r, up_entity)
            self.head(collection_url, expected_status=http_client.OK)

            # Now delete the four we added and make sure they are removed
            # from the collection.

            self.delete(gd_entity['links']['assignment'])
            self.delete(ud_entity['links']['assignment'])
            self.delete(gp_entity['links']['assignment'])
            self.delete(up_entity['links']['assignment'])
            frozen_datetime.tick(delta=datetime.timedelta(seconds=1))
            r = self.get(collection_url)
            self.assertValidRoleAssignmentListResponse(
                r,
                expected_length=existing_assignments,
                resource_url=collection_url)
            self.assertRoleAssignmentNotInListResponse(r, gd_entity)
            self.assertRoleAssignmentNotInListResponse(r, ud_entity)
            self.assertRoleAssignmentNotInListResponse(r, gp_entity)
            self.assertRoleAssignmentNotInListResponse(r, up_entity)
            self.head(collection_url, expected_status=http_client.OK)

    def test_get_effective_role_assignments(self):
        """Call ``GET /role_assignments?effective``.

        Test Plan:

        - Create two extra user for tests
        - Add these users to a group
        - Add a role assignment for the group on a domain
        - Get a list of all role assignments, checking one has been added
        - Then get a list of all effective role assignments - the group
          assignment should have turned into assignments on the domain
          for each of the group members.

        """
        user1 = unit.create_user(PROVIDERS.identity_api,
                                 domain_id=self.domain['id'])
        user2 = unit.create_user(PROVIDERS.identity_api,
                                 domain_id=self.domain['id'])

        PROVIDERS.identity_api.add_user_to_group(user1['id'], self.group['id'])
        PROVIDERS.identity_api.add_user_to_group(user2['id'], self.group['id'])

        collection_url = '/role_assignments'
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   resource_url=collection_url)
        existing_assignments = len(r.result.get('role_assignments'))

        gd_entity = self.build_role_assignment_entity(domain_id=self.domain_id,
                                                      group_id=self.group_id,
                                                      role_id=self.role_id)
        self.put(gd_entity['links']['assignment'])
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(
            r,
            expected_length=existing_assignments + 1,
            resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(r, gd_entity)

        # Now re-read the collection asking for effective roles - this
        # should mean the group assignment is translated into the two
        # member user assignments
        collection_url = '/role_assignments?effective'
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(
            r,
            expected_length=existing_assignments + 2,
            resource_url=collection_url)
        ud_entity = self.build_role_assignment_entity(
            link=gd_entity['links']['assignment'], domain_id=self.domain_id,
            user_id=user1['id'], role_id=self.role_id)
        self.assertRoleAssignmentInListResponse(r, ud_entity)
        ud_entity = self.build_role_assignment_entity(
            link=gd_entity['links']['assignment'], domain_id=self.domain_id,
            user_id=user2['id'], role_id=self.role_id)
        self.assertRoleAssignmentInListResponse(r, ud_entity)

    def test_check_effective_values_for_role_assignments(self):
        """Call ``GET & HEAD /role_assignments?effective=value``.

        Check the various ways of specifying the 'effective'
        query parameter.  If the 'effective' query parameter
        is included then this should always be treated as meaning 'True'
        unless it is specified as:

        {url}?effective=0

        This is by design to match the agreed way of handling
        policy checking on query/filter parameters.

        Test Plan:

        - Create two extra user for tests
        - Add these users to a group
        - Add a role assignment for the group on a domain
        - Get a list of all role assignments, checking one has been added
        - Then issue various request with different ways of defining
          the 'effective' query parameter. As we have tested the
          correctness of the data coming back when we get effective roles
          in other tests, here we just use the count of entities to
          know if we are getting effective roles or not

        """
        user1 = unit.create_user(PROVIDERS.identity_api,
                                 domain_id=self.domain['id'])
        user2 = unit.create_user(PROVIDERS.identity_api,
                                 domain_id=self.domain['id'])

        PROVIDERS.identity_api.add_user_to_group(user1['id'], self.group['id'])
        PROVIDERS.identity_api.add_user_to_group(user2['id'], self.group['id'])

        collection_url = '/role_assignments'
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(r,
                                                   resource_url=collection_url)
        existing_assignments = len(r.result.get('role_assignments'))

        gd_entity = self.build_role_assignment_entity(domain_id=self.domain_id,
                                                      group_id=self.group_id,
                                                      role_id=self.role_id)
        self.put(gd_entity['links']['assignment'])
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(
            r,
            expected_length=existing_assignments + 1,
            resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(r, gd_entity)

        # Now re-read the collection asking for effective roles,
        # using the most common way of defining "effective'. This
        # should mean the group assignment is translated into the two
        # member user assignments
        collection_url = '/role_assignments?effective'
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(
            r,
            expected_length=existing_assignments + 2,
            resource_url=collection_url)
        # Now set 'effective' to false explicitly - should get
        # back the regular roles
        collection_url = '/role_assignments?effective=0'
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(
            r,
            expected_length=existing_assignments + 1,
            resource_url=collection_url)
        # Now try setting  'effective' to 'False' explicitly- this is
        # NOT supported as a way of setting a query or filter
        # parameter to false by design. Hence we should get back
        # effective roles.
        collection_url = '/role_assignments?effective=False'
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(
            r,
            expected_length=existing_assignments + 2,
            resource_url=collection_url)
        # Now set 'effective' to True explicitly
        collection_url = '/role_assignments?effective=True'
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(
            r,
            expected_length=existing_assignments + 2,
            resource_url=collection_url)

    def test_filtered_role_assignments(self):
        """Call ``GET /role_assignments?filters``.

        Test Plan:

        - Create extra users, group, role and project for tests
        - Make the following assignments:
          Give group1, role1 on project1 and domain
          Give user1, role2 on project1 and domain
          Make User1 a member of Group1
        - Test a series of single filter list calls, checking that
          the correct results are obtained
        - Test a multi-filtered list call
        - Test listing all effective roles for a given user
        - Test the equivalent of the list of roles in a project scoped
          token (all effective roles for a user on a project)

        """
        # Since the default fixtures already assign some roles to the
        # user it creates, we also need a new user that will not have any
        # existing assignments
        user1 = unit.create_user(PROVIDERS.identity_api,
                                 domain_id=self.domain['id'])
        user2 = unit.create_user(PROVIDERS.identity_api,
                                 domain_id=self.domain['id'])

        group1 = unit.new_group_ref(domain_id=self.domain['id'])
        group1 = PROVIDERS.identity_api.create_group(group1)
        PROVIDERS.identity_api.add_user_to_group(user1['id'], group1['id'])
        PROVIDERS.identity_api.add_user_to_group(user2['id'], group1['id'])
        project1 = unit.new_project_ref(domain_id=self.domain['id'])
        PROVIDERS.resource_api.create_project(project1['id'], project1)
        self.role1 = unit.new_role_ref()
        PROVIDERS.role_api.create_role(self.role1['id'], self.role1)
        self.role2 = unit.new_role_ref()
        PROVIDERS.role_api.create_role(self.role2['id'], self.role2)

        # Now add one of each of the four types of assignment

        gd_entity = self.build_role_assignment_entity(
            domain_id=self.domain_id, group_id=group1['id'],
            role_id=self.role1['id'])
        self.put(gd_entity['links']['assignment'])

        ud_entity = self.build_role_assignment_entity(domain_id=self.domain_id,
                                                      user_id=user1['id'],
                                                      role_id=self.role2['id'])
        self.put(ud_entity['links']['assignment'])

        gp_entity = self.build_role_assignment_entity(
            project_id=project1['id'],
            group_id=group1['id'],
            role_id=self.role1['id'])
        self.put(gp_entity['links']['assignment'])

        up_entity = self.build_role_assignment_entity(
            project_id=project1['id'],
            user_id=user1['id'],
            role_id=self.role2['id'])
        self.put(up_entity['links']['assignment'])

        # Now list by various filters to make sure we get back the right ones

        collection_url = ('/role_assignments?scope.project.id=%s' %
                          project1['id'])
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=2,
                                                   resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(r, up_entity)
        self.assertRoleAssignmentInListResponse(r, gp_entity)

        collection_url = ('/role_assignments?scope.domain.id=%s' %
                          self.domain['id'])
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=2,
                                                   resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(r, ud_entity)
        self.assertRoleAssignmentInListResponse(r, gd_entity)

        collection_url = '/role_assignments?user.id=%s' % user1['id']
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=2,
                                                   resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(r, up_entity)
        self.assertRoleAssignmentInListResponse(r, ud_entity)

        collection_url = '/role_assignments?group.id=%s' % group1['id']
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=2,
                                                   resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(r, gd_entity)
        self.assertRoleAssignmentInListResponse(r, gp_entity)

        collection_url = '/role_assignments?role.id=%s' % self.role1['id']
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=2,
                                                   resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(r, gd_entity)
        self.assertRoleAssignmentInListResponse(r, gp_entity)

        # Let's try combining two filers together....

        collection_url = (
            '/role_assignments?user.id=%(user_id)s'
            '&scope.project.id=%(project_id)s' % {
                'user_id': user1['id'],
                'project_id': project1['id']})
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=1,
                                                   resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(r, up_entity)

        # Now for a harder one - filter for user with effective
        # roles - this should return role assignment that were directly
        # assigned as well as by virtue of group membership

        collection_url = ('/role_assignments?effective&user.id=%s' %
                          user1['id'])
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=4,
                                                   resource_url=collection_url)
        # Should have the two direct roles...
        self.assertRoleAssignmentInListResponse(r, up_entity)
        self.assertRoleAssignmentInListResponse(r, ud_entity)
        # ...and the two via group membership...
        gp1_link = self.build_role_assignment_link(
            project_id=project1['id'],
            group_id=group1['id'],
            role_id=self.role1['id'])
        gd1_link = self.build_role_assignment_link(domain_id=self.domain_id,
                                                   group_id=group1['id'],
                                                   role_id=self.role1['id'])

        up1_entity = self.build_role_assignment_entity(
            link=gp1_link, project_id=project1['id'],
            user_id=user1['id'], role_id=self.role1['id'])
        ud1_entity = self.build_role_assignment_entity(
            link=gd1_link, domain_id=self.domain_id, user_id=user1['id'],
            role_id=self.role1['id'])
        self.assertRoleAssignmentInListResponse(r, up1_entity)
        self.assertRoleAssignmentInListResponse(r, ud1_entity)

        # ...and for the grand-daddy of them all, simulate the request
        # that would generate the list of effective roles in a project
        # scoped token.

        collection_url = (
            '/role_assignments?effective&user.id=%(user_id)s'
            '&scope.project.id=%(project_id)s' % {
                'user_id': user1['id'],
                'project_id': project1['id']})
        r = self.get(collection_url, expected_status=http_client.OK)
        self.head(collection_url, expected_status=http_client.OK)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=2,
                                                   resource_url=collection_url)
        # Should have one direct role and one from group membership...
        self.assertRoleAssignmentInListResponse(r, up_entity)
        self.assertRoleAssignmentInListResponse(r, up1_entity)

    def test_list_system_role_assignments(self):
        # create a bunch of roles
        user_system_role_id = self._create_new_role()
        user_domain_role_id = self._create_new_role()
        user_project_role_id = self._create_new_role()
        group_system_role_id = self._create_new_role()
        group_domain_role_id = self._create_new_role()
        group_project_role_id = self._create_new_role()

        # create a user and grant the user a role on the system, domain, and
        # project
        user = self._create_user()
        url = '/system/users/%s/roles/%s' % (user['id'], user_system_role_id)
        self.put(url)
        url = '/domains/%s/users/%s/roles/%s' % (
            self.domain_id, user['id'], user_domain_role_id
        )
        self.put(url)
        url = '/projects/%s/users/%s/roles/%s' % (
            self.project_id, user['id'], user_project_role_id
        )
        self.put(url)

        # create a group and grant the group a role on the system, domain, and
        # project
        group = self._create_group()
        url = '/system/groups/%s/roles/%s' % (
            group['id'], group_system_role_id
        )
        self.put(url)
        url = '/domains/%s/groups/%s/roles/%s' % (
            self.domain_id, group['id'], group_domain_role_id
        )
        self.put(url)
        url = '/projects/%s/groups/%s/roles/%s' % (
            self.project_id, group['id'], group_project_role_id
        )
        self.put(url)

        # /v3/role_assignments?scope.system=all should return two assignments
        response = self.get('/role_assignments?scope.system=all')
        self.assertValidRoleAssignmentListResponse(response, expected_length=2)
        for assignment in response.json_body['role_assignments']:
            self.assertTrue(assignment['scope']['system']['all'])
            if assignment.get('user'):
                self.assertEqual(user_system_role_id, assignment['role']['id'])
            if assignment.get('group'):
                self.assertEqual(
                    group_system_role_id,
                    assignment['role']['id']
                )

        # /v3/role_assignments?scope_system=all&user.id=$USER_ID should return
        # one role assignment
        url = '/role_assignments?scope.system=all&user.id=%s' % user['id']
        response = self.get(url)
        self.assertValidRoleAssignmentListResponse(response, expected_length=1)
        self.assertEqual(
            user_system_role_id,
            response.json_body['role_assignments'][0]['role']['id']
        )

        # /v3/role_assignments?scope_system=all&group.id=$GROUP_ID should
        # return one role assignment
        url = '/role_assignments?scope.system=all&group.id=%s' % group['id']
        response = self.get(url)
        self.assertValidRoleAssignmentListResponse(response, expected_length=1)
        self.assertEqual(
            group_system_role_id,
            response.json_body['role_assignments'][0]['role']['id']
        )

        # /v3/role_assignments?user.id=$USER_ID should return 3 assignments
        # and system should be in that list of assignments
        url = '/role_assignments?user.id=%s' % user['id']
        response = self.get(url)
        self.assertValidRoleAssignmentListResponse(response, expected_length=3)
        for assignment in response.json_body['role_assignments']:
            if 'system' in assignment['scope']:
                self.assertEqual(
                    user_system_role_id, assignment['role']['id']
                )
            if 'domain' in assignment['scope']:
                self.assertEqual(
                    user_domain_role_id, assignment['role']['id']
                )
            if 'project' in assignment['scope']:
                self.assertEqual(
                    user_project_role_id, assignment['role']['id']
                )

        # /v3/role_assignments?group.id=$GROUP_ID should return 3 assignments
        # and system should be in that list of assignments
        url = '/role_assignments?group.id=%s' % group['id']
        response = self.get(url)
        self.assertValidRoleAssignmentListResponse(response, expected_length=3)
        for assignment in response.json_body['role_assignments']:
            if 'system' in assignment['scope']:
                self.assertEqual(
                    group_system_role_id, assignment['role']['id']
                )
            if 'domain' in assignment['scope']:
                self.assertEqual(
                    group_domain_role_id, assignment['role']['id']
                )
            if 'project' in assignment['scope']:
                self.assertEqual(
                    group_project_role_id, assignment['role']['id']
                )


class RoleAssignmentBaseTestCase(test_v3.RestfulTestCase,
                                 test_v3.AssignmentTestMixin):
    """Base class for testing /v3/role_assignments API behavior."""

    MAX_HIERARCHY_BREADTH = 3
    MAX_HIERARCHY_DEPTH = CONF.max_project_tree_depth - 1

    def load_sample_data(self):
        """Create sample data to be used on tests.

        Created data are i) a role and ii) a domain containing: a project
        hierarchy and 3 users within 3 groups.

        """
        def create_project_hierarchy(parent_id, depth):
            """Create a random project hierarchy."""
            if depth == 0:
                return

            breadth = random.randint(1, self.MAX_HIERARCHY_BREADTH)

            subprojects = []
            for i in range(breadth):
                subprojects.append(unit.new_project_ref(
                    domain_id=self.domain_id, parent_id=parent_id))
                PROVIDERS.resource_api.create_project(
                    subprojects[-1]['id'], subprojects[-1]
                )

            new_parent = subprojects[random.randint(0, breadth - 1)]
            create_project_hierarchy(new_parent['id'], depth - 1)

        super(RoleAssignmentBaseTestCase, self).load_sample_data()

        # Create a domain
        self.domain = unit.new_domain_ref()
        self.domain_id = self.domain['id']
        PROVIDERS.resource_api.create_domain(self.domain_id, self.domain)

        # Create a project hierarchy
        self.project = unit.new_project_ref(domain_id=self.domain_id)
        self.project_id = self.project['id']
        PROVIDERS.resource_api.create_project(self.project_id, self.project)

        # Create a random project hierarchy
        create_project_hierarchy(self.project_id,
                                 random.randint(1, self.MAX_HIERARCHY_DEPTH))

        # Create 3 users
        self.user_ids = []
        for i in range(3):
            user = unit.new_user_ref(domain_id=self.domain_id)
            user = PROVIDERS.identity_api.create_user(user)
            self.user_ids.append(user['id'])

        # Create 3 groups
        self.group_ids = []
        for i in range(3):
            group = unit.new_group_ref(domain_id=self.domain_id)
            group = PROVIDERS.identity_api.create_group(group)
            self.group_ids.append(group['id'])

            # Put 2 members on each group
            PROVIDERS.identity_api.add_user_to_group(
                user_id=self.user_ids[i], group_id=group['id']
            )
            PROVIDERS.identity_api.add_user_to_group(
                user_id=self.user_ids[i % 2], group_id=group['id']
            )

        PROVIDERS.assignment_api.create_grant(
            user_id=self.user_id, project_id=self.project_id,
            role_id=self.role_id
        )

        # Create a role
        self.role = unit.new_role_ref()
        self.role_id = self.role['id']
        PROVIDERS.role_api.create_role(self.role_id, self.role)

        # Set default user and group to be used on tests
        self.default_user_id = self.user_ids[0]
        self.default_group_id = self.group_ids[0]

    def get_role_assignments(self, expected_status=http_client.OK, **filters):
        """Return the result from querying role assignment API + queried URL.

        Calls GET /v3/role_assignments?<params> and returns its result, where
        <params> is the HTTP query parameters form of effective option plus
        filters, if provided. Queried URL is returned as well.

        :returns: a tuple containing the list role assignments API response and
                  queried URL.

        """
        query_url = self._get_role_assignments_query_url(**filters)
        response = self.get(query_url, expected_status=expected_status)

        return (response, query_url)

    def _get_role_assignments_query_url(self, **filters):
        """Return non-effective role assignments query URL from given filters.

        :param filters: query parameters are created with the provided filters
                        on role assignments attributes. Valid filters are:
                        role_id, domain_id, project_id, group_id, user_id and
                        inherited_to_projects.

        :returns: role assignments query URL.

        """
        return self.build_role_assignment_query_url(**filters)


class RoleAssignmentFailureTestCase(RoleAssignmentBaseTestCase):
    """Class for testing invalid query params on /v3/role_assignments API.

    Querying domain and project, or user and group results in a HTTP 400 Bad
    Request, since a role assignment must contain only a single pair of (actor,
    target). In addition, since filtering on role assignments applies only to
    the final result, effective mode cannot be combined with i) group or ii)
    domain and inherited, because it would always result in an empty list.

    """

    def test_get_role_assignments_by_domain_and_project(self):
        self.get_role_assignments(domain_id=self.domain_id,
                                  project_id=self.project_id,
                                  expected_status=http_client.BAD_REQUEST)

    def test_get_role_assignments_by_user_and_group(self):
        self.get_role_assignments(user_id=self.default_user_id,
                                  group_id=self.default_group_id,
                                  expected_status=http_client.BAD_REQUEST)

    def test_get_role_assignments_by_effective_and_inherited(self):
        self.get_role_assignments(domain_id=self.domain_id, effective=True,
                                  inherited_to_projects=True,
                                  expected_status=http_client.BAD_REQUEST)

    def test_get_role_assignments_by_effective_and_group(self):
        self.get_role_assignments(effective=True,
                                  group_id=self.default_group_id,
                                  expected_status=http_client.BAD_REQUEST)


class RoleAssignmentDirectTestCase(RoleAssignmentBaseTestCase):
    """Class for testing direct assignments on /v3/role_assignments API.

    Direct assignments on a domain or project have effect on them directly,
    instead of on their project hierarchy, i.e they are non-inherited. In
    addition, group direct assignments are not expanded to group's users.

    Tests on this class make assertions on the representation and API filtering
    of direct assignments.

    """

    def _test_get_role_assignments(self, **filters):
        """Generic filtering test method.

        According to the provided filters, this method:
        - creates a new role assignment;
        - asserts that list role assignments API reponds correctly;
        - deletes the created role assignment.

        :param filters: filters to be considered when listing role assignments.
                        Valid filters are: role_id, domain_id, project_id,
                        group_id, user_id and inherited_to_projects.

        """
        # Fills default assignment with provided filters
        test_assignment = self._set_default_assignment_attributes(**filters)

        # Create new role assignment for this test
        PROVIDERS.assignment_api.create_grant(**test_assignment)

        # Get expected role assignments
        expected_assignments = self._list_expected_role_assignments(
            **test_assignment)

        # Get role assignments from API
        response, query_url = self.get_role_assignments(**test_assignment)
        self.assertValidRoleAssignmentListResponse(response,
                                                   resource_url=query_url)
        self.assertEqual(len(expected_assignments),
                         len(response.result.get('role_assignments')))

        # Assert that expected role assignments were returned by the API call
        for assignment in expected_assignments:
            self.assertRoleAssignmentInListResponse(response, assignment)

        # Delete created role assignment
        PROVIDERS.assignment_api.delete_grant(**test_assignment)

    def _set_default_assignment_attributes(self, **attribs):
        """Insert default values for missing attributes of role assignment.

        If no actor, target or role are provided, they will default to values
        from sample data.

        :param attribs: info from a role assignment entity. Valid attributes
                        are: role_id, domain_id, project_id, group_id, user_id
                        and inherited_to_projects.

        """
        if not any(target in attribs
                   for target in ('domain_id', 'projects_id')):
            attribs['project_id'] = self.project_id

        if not any(actor in attribs for actor in ('user_id', 'group_id')):
            attribs['user_id'] = self.default_user_id

        if 'role_id' not in attribs:
            attribs['role_id'] = self.role_id

        return attribs

    def _list_expected_role_assignments(self, **filters):
        """Given the filters, it returns expected direct role assignments.

        :param filters: filters that will be considered when listing role
                        assignments. Valid filters are: role_id, domain_id,
                        project_id, group_id, user_id and
                        inherited_to_projects.

        :returns: the list of the expected role assignments.

        """
        return [self.build_role_assignment_entity(**filters)]

    # Test cases below call the generic test method, providing different filter
    # combinations. Filters are provided as specified in the method name, after
    # 'by'. For example, test_get_role_assignments_by_project_user_and_role
    # calls the generic test method with project_id, user_id and role_id.

    def test_get_role_assignments_by_domain(self, **filters):
        self._test_get_role_assignments(domain_id=self.domain_id, **filters)

    def test_get_role_assignments_by_project(self, **filters):
        self._test_get_role_assignments(project_id=self.project_id, **filters)

    def test_get_role_assignments_by_user(self, **filters):
        self._test_get_role_assignments(user_id=self.default_user_id,
                                        **filters)

    def test_get_role_assignments_by_group(self, **filters):
        self._test_get_role_assignments(group_id=self.default_group_id,
                                        **filters)

    def test_get_role_assignments_by_role(self, **filters):
        self._test_get_role_assignments(role_id=self.role_id, **filters)

    def test_get_role_assignments_by_domain_and_user(self, **filters):
        self.test_get_role_assignments_by_domain(user_id=self.default_user_id,
                                                 **filters)

    def test_get_role_assignments_by_domain_and_group(self, **filters):
        self.test_get_role_assignments_by_domain(
            group_id=self.default_group_id, **filters)

    def test_get_role_assignments_by_project_and_user(self, **filters):
        self.test_get_role_assignments_by_project(user_id=self.default_user_id,
                                                  **filters)

    def test_get_role_assignments_by_project_and_group(self, **filters):
        self.test_get_role_assignments_by_project(
            group_id=self.default_group_id, **filters)

    def test_get_role_assignments_by_domain_user_and_role(self, **filters):
        self.test_get_role_assignments_by_domain_and_user(role_id=self.role_id,
                                                          **filters)

    def test_get_role_assignments_by_domain_group_and_role(self, **filters):
        self.test_get_role_assignments_by_domain_and_group(
            role_id=self.role_id, **filters)

    def test_get_role_assignments_by_project_user_and_role(self, **filters):
        self.test_get_role_assignments_by_project_and_user(
            role_id=self.role_id, **filters)

    def test_get_role_assignments_by_project_group_and_role(self, **filters):
        self.test_get_role_assignments_by_project_and_group(
            role_id=self.role_id, **filters)


class RoleAssignmentInheritedTestCase(RoleAssignmentDirectTestCase):
    """Class for testing inherited assignments on /v3/role_assignments API.

    Inherited assignments on a domain or project have no effect on them
    directly, but on the projects under them instead.

    Tests on this class do not make assertions on the effect of inherited
    assignments, but in their representation and API filtering.

    """

    def _test_get_role_assignments(self, **filters):
        """Add inherited_to_project filter to expected entity in tests."""
        super(RoleAssignmentInheritedTestCase,
              self)._test_get_role_assignments(inherited_to_projects=True,
                                               **filters)


class RoleAssignmentEffectiveTestCase(RoleAssignmentInheritedTestCase):
    """Class for testing inheritance effects on /v3/role_assignments API.

    Inherited assignments on a domain or project have no effect on them
    directly, but on the projects under them instead.

    Tests on this class make assertions on the effect of inherited assignments
    and API filtering.

    """

    def _get_role_assignments_query_url(self, **filters):
        """Return effective role assignments query URL from given filters.

        For test methods in this class, effetive will always be true. As in
        effective mode, inherited_to_projects, group_id, domain_id and
        project_id will always be desconsidered from provided filters.

        :param filters: query parameters are created with the provided filters.
                        Valid filters are: role_id, domain_id, project_id,
                        group_id, user_id and inherited_to_projects.

        :returns: role assignments query URL.

        """
        query_filters = filters.copy()
        query_filters.pop('inherited_to_projects')

        query_filters.pop('group_id', None)
        query_filters.pop('domain_id', None)
        query_filters.pop('project_id', None)

        return self.build_role_assignment_query_url(effective=True,
                                                    **query_filters)

    def _list_expected_role_assignments(self, **filters):
        """Given the filters, it returns expected direct role assignments.

        :param filters: filters that will be considered when listing role
                        assignments. Valid filters are: role_id, domain_id,
                        project_id, group_id, user_id and
                        inherited_to_projects.

        :returns: the list of the expected role assignments.

        """
        # Get assignment link, to be put on 'links': {'assignment': link}
        assignment_link = self.build_role_assignment_link(**filters)

        # Expand group membership
        user_ids = [None]
        if filters.get('group_id'):
            user_ids = [user['id'] for user in
                        PROVIDERS.identity_api.list_users_in_group(
                            filters['group_id'])]
        else:
            user_ids = [self.default_user_id]

        # Expand role inheritance
        project_ids = [None]
        if filters.get('domain_id'):
            project_ids = [project['id'] for project in
                           PROVIDERS.resource_api.list_projects_in_domain(
                               filters.pop('domain_id'))]
        else:
            project_ids = [project['id'] for project in
                           PROVIDERS.resource_api.list_projects_in_subtree(
                               self.project_id)]

        # Compute expected role assignments
        assignments = []
        for project_id in project_ids:
            filters['project_id'] = project_id
            for user_id in user_ids:
                filters['user_id'] = user_id
                assignments.append(self.build_role_assignment_entity(
                    link=assignment_link, **filters))

        return assignments


class AssignmentInheritanceTestCase(test_v3.RestfulTestCase,
                                    test_v3.AssignmentTestMixin):
    """Test inheritance crud and its effects."""

    def test_get_token_from_inherited_user_domain_role_grants(self):
        # Create a new user to ensure that no grant is loaded from sample data
        user = unit.create_user(
            PROVIDERS.identity_api, domain_id=self.domain_id
        )

        # Define domain and project authentication data
        domain_auth_data = self.build_authentication_request(
            user_id=user['id'],
            password=user['password'],
            domain_id=self.domain_id)
        project_auth_data = self.build_authentication_request(
            user_id=user['id'],
            password=user['password'],
            project_id=self.project_id)

        # Check the user cannot get a domain nor a project token
        self.v3_create_token(domain_auth_data,
                             expected_status=http_client.UNAUTHORIZED)
        self.v3_create_token(project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

        # Grant non-inherited role for user on domain
        non_inher_ud_link = self.build_role_assignment_link(
            domain_id=self.domain_id, user_id=user['id'], role_id=self.role_id)
        self.put(non_inher_ud_link)

        # Check the user can get only a domain token
        self.v3_create_token(domain_auth_data)
        self.v3_create_token(project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

        # Create inherited role
        inherited_role = unit.new_role_ref(name='inherited')
        PROVIDERS.role_api.create_role(inherited_role['id'], inherited_role)

        # Grant inherited role for user on domain
        inher_ud_link = self.build_role_assignment_link(
            domain_id=self.domain_id, user_id=user['id'],
            role_id=inherited_role['id'], inherited_to_projects=True)
        self.put(inher_ud_link)

        # Check the user can get both a domain and a project token
        self.v3_create_token(domain_auth_data)
        self.v3_create_token(project_auth_data)

        # Delete inherited grant
        self.delete(inher_ud_link)

        # Check the user can only get a domain token
        self.v3_create_token(domain_auth_data)
        self.v3_create_token(project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

        # Delete non-inherited grant
        self.delete(non_inher_ud_link)

        # Check the user cannot get a domain token anymore
        self.v3_create_token(domain_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

    def test_get_token_from_inherited_group_domain_role_grants(self):
        # Create a new group and put a new user in it to
        # ensure that no grant is loaded from sample data
        user = unit.create_user(
            PROVIDERS.identity_api, domain_id=self.domain_id
        )

        group = unit.new_group_ref(domain_id=self.domain['id'])
        group = PROVIDERS.identity_api.create_group(group)
        PROVIDERS.identity_api.add_user_to_group(user['id'], group['id'])

        # Define domain and project authentication data
        domain_auth_data = self.build_authentication_request(
            user_id=user['id'],
            password=user['password'],
            domain_id=self.domain_id)
        project_auth_data = self.build_authentication_request(
            user_id=user['id'],
            password=user['password'],
            project_id=self.project_id)

        # Check the user cannot get a domain nor a project token
        self.v3_create_token(domain_auth_data,
                             expected_status=http_client.UNAUTHORIZED)
        self.v3_create_token(project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

        # Grant non-inherited role for user on domain
        non_inher_gd_link = self.build_role_assignment_link(
            domain_id=self.domain_id, user_id=user['id'], role_id=self.role_id)
        self.put(non_inher_gd_link)

        # Check the user can get only a domain token
        self.v3_create_token(domain_auth_data)
        self.v3_create_token(project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

        # Create inherited role
        inherited_role = unit.new_role_ref(name='inherited')
        PROVIDERS.role_api.create_role(inherited_role['id'], inherited_role)

        # Grant inherited role for user on domain
        inher_gd_link = self.build_role_assignment_link(
            domain_id=self.domain_id, user_id=user['id'],
            role_id=inherited_role['id'], inherited_to_projects=True)
        self.put(inher_gd_link)

        # Check the user can get both a domain and a project token
        self.v3_create_token(domain_auth_data)
        self.v3_create_token(project_auth_data)

        # Delete inherited grant
        self.delete(inher_gd_link)

        # Check the user can only get a domain token
        self.v3_create_token(domain_auth_data)
        self.v3_create_token(project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

        # Delete non-inherited grant
        self.delete(non_inher_gd_link)

        # Check the user cannot get a domain token anymore
        self.v3_create_token(domain_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

    def _test_crud_inherited_and_direct_assignment_on_target(self, target_url):
        time = datetime.datetime.utcnow()
        with freezegun.freeze_time(time) as frozen_datetime:
            # Create a new role to avoid assignments loaded from sample data
            role = unit.new_role_ref()
            PROVIDERS.role_api.create_role(role['id'], role)

            # Define URLs
            direct_url = '%s/users/%s/roles/%s' % (
                target_url, self.user_id, role['id'])
            inherited_url = ('/OS-INHERIT/%s/inherited_to_projects' %
                             direct_url.lstrip('/'))

            # Create the direct assignment
            self.put(direct_url)
            # Check the direct assignment exists, but the inherited one does
            # not
            self.head(direct_url)
            self.head(inherited_url, expected_status=http_client.NOT_FOUND)

            # Now add the inherited assignment
            self.put(inherited_url)
            # Check both the direct and inherited assignment exist
            self.head(direct_url)
            self.head(inherited_url)

            # Delete indirect assignment
            self.delete(inherited_url)
            frozen_datetime.tick(delta=datetime.timedelta(seconds=1))
            # Check the direct assignment exists, but the inherited one does
            # not
            self.head(direct_url)
            self.head(inherited_url, expected_status=http_client.NOT_FOUND)

            # Now delete the inherited assignment
            self.delete(direct_url)
            # Check that none of them exist
            self.head(direct_url, expected_status=http_client.NOT_FOUND)
            self.head(inherited_url, expected_status=http_client.NOT_FOUND)

    def test_crud_inherited_and_direct_assignment_on_domains(self):
        self._test_crud_inherited_and_direct_assignment_on_target(
            '/domains/%s' % self.domain_id)

    def test_crud_inherited_and_direct_assignment_on_projects(self):
        self._test_crud_inherited_and_direct_assignment_on_target(
            '/projects/%s' % self.project_id)

    def test_crud_user_inherited_domain_role_grants(self):
        role_list = []
        for _ in range(2):
            role = unit.new_role_ref()
            PROVIDERS.role_api.create_role(role['id'], role)
            role_list.append(role)

        # Create a non-inherited role as a spoiler
        PROVIDERS.assignment_api.create_grant(
            role_list[1]['id'], user_id=self.user['id'],
            domain_id=self.domain_id)

        base_collection_url = (
            '/OS-INHERIT/domains/%(domain_id)s/users/%(user_id)s/roles' % {
                'domain_id': self.domain_id,
                'user_id': self.user['id']})
        member_url = '%(collection_url)s/%(role_id)s/inherited_to_projects' % {
            'collection_url': base_collection_url,
            'role_id': role_list[0]['id']}
        collection_url = base_collection_url + '/inherited_to_projects'

        self.put(member_url)

        # Check we can read it back
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, ref=role_list[0],
                                         resource_url=collection_url)

        # Now delete and check its gone
        self.delete(member_url)
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, expected_length=0,
                                         resource_url=collection_url)

    def test_list_role_assignments_for_inherited_domain_grants(self):
        """Call ``GET /role_assignments with inherited domain grants``.

        Test Plan:

        - Create 4 roles
        - Create a domain with a user and two projects
        - Assign two direct roles to project1
        - Assign a spoiler role to project2
        - Issue the URL to add inherited role to the domain
        - Issue the URL to check it is indeed on the domain
        - Issue the URL to check effective roles on project1 - this
          should return 3 roles.

        """
        role_list = []
        for _ in range(4):
            role = unit.new_role_ref()
            PROVIDERS.role_api.create_role(role['id'], role)
            role_list.append(role)

        domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(domain['id'], domain)
        user1 = unit.create_user(
            PROVIDERS.identity_api, domain_id=domain['id']
        )
        project1 = unit.new_project_ref(domain_id=domain['id'])
        PROVIDERS.resource_api.create_project(project1['id'], project1)
        project2 = unit.new_project_ref(domain_id=domain['id'])
        PROVIDERS.resource_api.create_project(project2['id'], project2)
        # Add some roles to the project
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project1['id'], role_list[0]['id'])
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project1['id'], role_list[1]['id'])
        # ..and one on a different project as a spoiler
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project2['id'], role_list[2]['id'])

        # Now create our inherited role on the domain
        base_collection_url = (
            '/OS-INHERIT/domains/%(domain_id)s/users/%(user_id)s/roles' % {
                'domain_id': domain['id'],
                'user_id': user1['id']})
        member_url = '%(collection_url)s/%(role_id)s/inherited_to_projects' % {
            'collection_url': base_collection_url,
            'role_id': role_list[3]['id']}
        collection_url = base_collection_url + '/inherited_to_projects'

        self.put(member_url)
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, ref=role_list[3],
                                         resource_url=collection_url)

        # Now use the list domain role assignments api to check if this
        # is included
        collection_url = (
            '/role_assignments?user.id=%(user_id)s'
            '&scope.domain.id=%(domain_id)s' % {
                'user_id': user1['id'],
                'domain_id': domain['id']})
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=1,
                                                   resource_url=collection_url)
        ud_entity = self.build_role_assignment_entity(
            domain_id=domain['id'], user_id=user1['id'],
            role_id=role_list[3]['id'], inherited_to_projects=True)
        self.assertRoleAssignmentInListResponse(r, ud_entity)

        # Now ask for effective list role assignments - the role should
        # turn into a project role, along with the two direct roles that are
        # on the project
        collection_url = (
            '/role_assignments?effective&user.id=%(user_id)s'
            '&scope.project.id=%(project_id)s' % {
                'user_id': user1['id'],
                'project_id': project1['id']})
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=3,
                                                   resource_url=collection_url)
        # An effective role for an inherited role will be a project
        # entity, with a domain link to the inherited assignment
        ud_url = self.build_role_assignment_link(
            domain_id=domain['id'], user_id=user1['id'],
            role_id=role_list[3]['id'], inherited_to_projects=True)
        up_entity = self.build_role_assignment_entity(
            link=ud_url, project_id=project1['id'],
            user_id=user1['id'], role_id=role_list[3]['id'],
            inherited_to_projects=True)
        self.assertRoleAssignmentInListResponse(r, up_entity)

    def _test_list_role_assignments_include_names(self, role1):
        """Call ``GET /role_assignments with include names``.

        Test Plan:

        - Create a domain with a group and a user
        - Create a project with a group and a user

        """
        role1 = unit.new_role_ref()
        PROVIDERS.role_api.create_role(role1['id'], role1)
        user1 = unit.create_user(
            PROVIDERS.identity_api, domain_id=self.domain_id
        )
        group = unit.new_group_ref(domain_id=self.domain_id)
        group = PROVIDERS.identity_api.create_group(group)
        project1 = unit.new_project_ref(domain_id=self.domain_id)
        PROVIDERS.resource_api.create_project(project1['id'], project1)

        expected_entity1 = self.build_role_assignment_entity_include_names(
            role_ref=role1,
            project_ref=project1,
            user_ref=user1)
        self.put(expected_entity1['links']['assignment'])
        expected_entity2 = self.build_role_assignment_entity_include_names(
            role_ref=role1,
            domain_ref=self.domain,
            group_ref=group)
        self.put(expected_entity2['links']['assignment'])
        expected_entity3 = self.build_role_assignment_entity_include_names(
            role_ref=role1,
            domain_ref=self.domain,
            user_ref=user1)
        self.put(expected_entity3['links']['assignment'])
        expected_entity4 = self.build_role_assignment_entity_include_names(
            role_ref=role1,
            project_ref=project1,
            group_ref=group)
        self.put(expected_entity4['links']['assignment'])

        collection_url_domain = (
            '/role_assignments?include_names&scope.domain.id=%(domain_id)s' % {
                'domain_id': self.domain_id})
        rs_domain = self.get(collection_url_domain)
        collection_url_project = (
            '/role_assignments?include_names&'
            'scope.project.id=%(project_id)s' % {
                'project_id': project1['id']})
        rs_project = self.get(collection_url_project)
        collection_url_group = (
            '/role_assignments?include_names&group.id=%(group_id)s' % {
                'group_id': group['id']})
        rs_group = self.get(collection_url_group)
        collection_url_user = (
            '/role_assignments?include_names&user.id=%(user_id)s' % {
                'user_id': user1['id']})
        rs_user = self.get(collection_url_user)
        collection_url_role = (
            '/role_assignments?include_names&role.id=%(role_id)s' % {
                'role_id': role1['id']})
        rs_role = self.get(collection_url_role)
        # Make sure all entities were created successfully
        self.assertEqual(http_client.OK, rs_domain.status_int)
        self.assertEqual(http_client.OK, rs_project.status_int)
        self.assertEqual(http_client.OK, rs_group.status_int)
        self.assertEqual(http_client.OK, rs_user.status_int)
        # Make sure we can get back the correct number of entities
        self.assertValidRoleAssignmentListResponse(
            rs_domain,
            expected_length=2,
            resource_url=collection_url_domain)
        self.assertValidRoleAssignmentListResponse(
            rs_project,
            expected_length=2,
            resource_url=collection_url_project)
        self.assertValidRoleAssignmentListResponse(
            rs_group,
            expected_length=2,
            resource_url=collection_url_group)
        self.assertValidRoleAssignmentListResponse(
            rs_user,
            expected_length=2,
            resource_url=collection_url_user)
        self.assertValidRoleAssignmentListResponse(
            rs_role,
            expected_length=4,
            resource_url=collection_url_role)
        # Verify all types of entities have the correct format
        self.assertRoleAssignmentInListResponse(rs_domain, expected_entity2)
        self.assertRoleAssignmentInListResponse(rs_project, expected_entity1)
        self.assertRoleAssignmentInListResponse(rs_group, expected_entity4)
        self.assertRoleAssignmentInListResponse(rs_user, expected_entity3)
        self.assertRoleAssignmentInListResponse(rs_role, expected_entity1)

    def test_list_role_assignments_include_names_global_role(self):
        role = unit.new_role_ref()
        PROVIDERS.role_api.create_role(role['id'], role)

        self._test_list_role_assignments_include_names(role)

    def test_list_role_assignments_include_names_domain_role(self):
        role = unit.new_role_ref(domain_id=self.domain['id'])
        PROVIDERS.role_api.create_role(role['id'], role)

        self._test_list_role_assignments_include_names(role)

    @test_utils.wip("Skipped until Bug 1754677 is resolved")
    def test_remove_assignment_for_project_acting_as_domain(self):
        """Test goal: remove assignment for project acting as domain.

        Ensure when we have two role assignments for the project
        acting as domain, one dealing with it as a domain and other as a
        project, we still able to remove those assignments later.

        Test plan:
        - Create a role and a domain with a user;
        - Grant a role for this user in this domain;
        - Grant a role for this user in the same entity as a project;
        - Ensure that both assignments were created and it was valid;
        - Remove the domain assignment for the user and show that the project
        assignment for him still valid

        """
        role = unit.new_role_ref()
        PROVIDERS.role_api.create_role(role['id'], role)
        domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(domain['id'], domain)
        user = unit.create_user(PROVIDERS.identity_api, domain_id=domain['id'])

        assignment_domain = self.build_role_assignment_entity(
            role_id=role['id'], domain_id=domain['id'], user_id=user['id'],
            inherited_to_projects=False)
        assignment_project = self.build_role_assignment_entity(
            role_id=role['id'], project_id=domain['id'], user_id=user['id'],
            inherited_to_projects=False)

        self.put(assignment_domain['links']['assignment'])
        self.put(assignment_project['links']['assignment'])

        collection_url = '/role_assignments?user.id=%(user_id)s' % (
                         {'user_id': user['id']})
        result = self.get(collection_url)
        # We have two role assignments based in both roles for the domain and
        # project scope
        self.assertValidRoleAssignmentListResponse(
            result, expected_length=2, resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(result, assignment_domain)

        domain_url = '/domains/%s/users/%s/roles/%s' % (
            domain['id'], user['id'], role['id'])
        self.delete(domain_url)

        collection_url = '/role_assignments?user.id=%(user_id)s' % (
                         {'user_id': user['id']})
        result = self.get(collection_url)
        # Now we only have one assignment for the project scope since the
        # domain scope was removed.
        self.assertValidRoleAssignmentListResponse(
            result, expected_length=1, resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(result, assignment_project)

    def test_list_inherited_role_assignments_include_names(self):
        """Call ``GET /role_assignments?include_names``.

        Test goal: ensure calling list role assignments including names
        honors the inherited role assignments flag.

        Test plan:
        - Create a role and a domain with a user;
        - Create a inherited role assignment;
        - List role assignments for that user;
        - List role assignments for that user including names.

        """
        role = unit.new_role_ref()
        PROVIDERS.role_api.create_role(role['id'], role)
        domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(domain['id'], domain)
        user = unit.create_user(PROVIDERS.identity_api, domain_id=domain['id'])

        # Create and store expected assignment refs
        assignment = self.build_role_assignment_entity(
            role_id=role['id'], domain_id=domain['id'], user_id=user['id'],
            inherited_to_projects=True)
        assignment_names = self.build_role_assignment_entity_include_names(
            role_ref=role, domain_ref=domain, user_ref=user,
            inherited_assignment=True)

        # Ensure expected assignment refs are inherited and have the same URL
        self.assertEqual('projects',
                         assignment['scope']['OS-INHERIT:inherited_to'])
        self.assertEqual('projects',
                         assignment_names['scope']['OS-INHERIT:inherited_to'])
        self.assertEqual(assignment['links']['assignment'],
                         assignment_names['links']['assignment'])

        self.put(assignment['links']['assignment'])

        collection_url = '/role_assignments?user.id=%(user_id)s' % (
                         {'user_id': user['id']})
        result = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(
            result, expected_length=1, resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(result, assignment)

        collection_url = ('/role_assignments?include_names&'
                          'user.id=%(user_id)s' % {'user_id': user['id']})
        result = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(
            result, expected_length=1, resource_url=collection_url)
        self.assertRoleAssignmentInListResponse(result, assignment_names)

    def test_list_role_assignments_for_disabled_inheritance_extension(self):
        """Call ``GET /role_assignments with inherited domain grants``.

        Test Plan:

        - Issue the URL to add inherited role to the domain
        - Issue the URL to check effective roles on project include the
          inherited role
        - Disable the extension
        - Re-check the effective roles, proving the inherited role no longer
          shows up.

        """
        role_list = []
        for _ in range(4):
            role = unit.new_role_ref()
            PROVIDERS.role_api.create_role(role['id'], role)
            role_list.append(role)

        domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(domain['id'], domain)
        user1 = unit.create_user(
            PROVIDERS.identity_api, domain_id=domain['id']
        )
        project1 = unit.new_project_ref(domain_id=domain['id'])
        PROVIDERS.resource_api.create_project(project1['id'], project1)
        project2 = unit.new_project_ref(domain_id=domain['id'])
        PROVIDERS.resource_api.create_project(project2['id'], project2)
        # Add some roles to the project
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project1['id'], role_list[0]['id'])
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project1['id'], role_list[1]['id'])
        # ..and one on a different project as a spoiler
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project2['id'], role_list[2]['id'])

        # Now create our inherited role on the domain
        base_collection_url = (
            '/OS-INHERIT/domains/%(domain_id)s/users/%(user_id)s/roles' % {
                'domain_id': domain['id'],
                'user_id': user1['id']})
        member_url = '%(collection_url)s/%(role_id)s/inherited_to_projects' % {
            'collection_url': base_collection_url,
            'role_id': role_list[3]['id']}
        collection_url = base_collection_url + '/inherited_to_projects'

        self.put(member_url)
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, ref=role_list[3],
                                         resource_url=collection_url)

        # Get effective list role assignments - the role should
        # turn into a project role, along with the two direct roles that are
        # on the project
        collection_url = (
            '/role_assignments?effective&user.id=%(user_id)s'
            '&scope.project.id=%(project_id)s' % {
                'user_id': user1['id'],
                'project_id': project1['id']})
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=3,
                                                   resource_url=collection_url)

        ud_url = self.build_role_assignment_link(
            domain_id=domain['id'], user_id=user1['id'],
            role_id=role_list[3]['id'], inherited_to_projects=True)
        up_entity = self.build_role_assignment_entity(
            link=ud_url, project_id=project1['id'],
            user_id=user1['id'], role_id=role_list[3]['id'],
            inherited_to_projects=True)

        self.assertRoleAssignmentInListResponse(r, up_entity)

    def test_list_role_assignments_for_inherited_group_domain_grants(self):
        """Call ``GET /role_assignments with inherited group domain grants``.

        Test Plan:

        - Create 4 roles
        - Create a domain with a user and two projects
        - Assign two direct roles to project1
        - Assign a spoiler role to project2
        - Issue the URL to add inherited role to the domain
        - Issue the URL to check it is indeed on the domain
        - Issue the URL to check effective roles on project1 - this
          should return 3 roles.

        """
        role_list = []
        for _ in range(4):
            role = unit.new_role_ref()
            PROVIDERS.role_api.create_role(role['id'], role)
            role_list.append(role)

        domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(domain['id'], domain)
        user1 = unit.create_user(
            PROVIDERS.identity_api, domain_id=domain['id']
        )
        user2 = unit.create_user(
            PROVIDERS.identity_api, domain_id=domain['id']
        )
        group1 = unit.new_group_ref(domain_id=domain['id'])
        group1 = PROVIDERS.identity_api.create_group(group1)
        PROVIDERS.identity_api.add_user_to_group(
            user1['id'], group1['id']
        )
        PROVIDERS.identity_api.add_user_to_group(
            user2['id'], group1['id']
        )
        project1 = unit.new_project_ref(domain_id=domain['id'])
        PROVIDERS.resource_api.create_project(project1['id'], project1)
        project2 = unit.new_project_ref(domain_id=domain['id'])
        PROVIDERS.resource_api.create_project(project2['id'], project2)
        # Add some roles to the project
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project1['id'], role_list[0]['id'])
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project1['id'], role_list[1]['id'])
        # ..and one on a different project as a spoiler
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project2['id'], role_list[2]['id'])

        # Now create our inherited role on the domain
        base_collection_url = (
            '/OS-INHERIT/domains/%(domain_id)s/groups/%(group_id)s/roles' % {
                'domain_id': domain['id'],
                'group_id': group1['id']})
        member_url = '%(collection_url)s/%(role_id)s/inherited_to_projects' % {
            'collection_url': base_collection_url,
            'role_id': role_list[3]['id']}
        collection_url = base_collection_url + '/inherited_to_projects'

        self.put(member_url)
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, ref=role_list[3],
                                         resource_url=collection_url)

        # Now use the list domain role assignments api to check if this
        # is included
        collection_url = (
            '/role_assignments?group.id=%(group_id)s'
            '&scope.domain.id=%(domain_id)s' % {
                'group_id': group1['id'],
                'domain_id': domain['id']})
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=1,
                                                   resource_url=collection_url)
        gd_entity = self.build_role_assignment_entity(
            domain_id=domain['id'], group_id=group1['id'],
            role_id=role_list[3]['id'], inherited_to_projects=True)
        self.assertRoleAssignmentInListResponse(r, gd_entity)

        # Now ask for effective list role assignments - the role should
        # turn into a user project role, along with the two direct roles
        # that are on the project
        collection_url = (
            '/role_assignments?effective&user.id=%(user_id)s'
            '&scope.project.id=%(project_id)s' % {
                'user_id': user1['id'],
                'project_id': project1['id']})
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=3,
                                                   resource_url=collection_url)
        # An effective role for an inherited role will be a project
        # entity, with a domain link to the inherited assignment
        up_entity = self.build_role_assignment_entity(
            link=gd_entity['links']['assignment'], project_id=project1['id'],
            user_id=user1['id'], role_id=role_list[3]['id'],
            inherited_to_projects=True)
        self.assertRoleAssignmentInListResponse(r, up_entity)

    def test_filtered_role_assignments_for_inherited_grants(self):
        """Call ``GET /role_assignments?scope.OS-INHERIT:inherited_to``.

        Test Plan:

        - Create 5 roles
        - Create a domain with a user, group and two projects
        - Assign three direct spoiler roles to projects
        - Issue the URL to add an inherited user role to the domain
        - Issue the URL to add an inherited group role to the domain
        - Issue the URL to filter by inherited roles - this should
          return just the 2 inherited roles.

        """
        role_list = []
        for _ in range(5):
            role = unit.new_role_ref()
            PROVIDERS.role_api.create_role(role['id'], role)
            role_list.append(role)

        domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(domain['id'], domain)
        user1 = unit.create_user(
            PROVIDERS.identity_api, domain_id=domain['id']
        )
        group1 = unit.new_group_ref(domain_id=domain['id'])
        group1 = PROVIDERS.identity_api.create_group(group1)
        project1 = unit.new_project_ref(domain_id=domain['id'])
        PROVIDERS.resource_api.create_project(project1['id'], project1)
        project2 = unit.new_project_ref(domain_id=domain['id'])
        PROVIDERS.resource_api.create_project(project2['id'], project2)
        # Add some spoiler roles to the projects
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project1['id'], role_list[0]['id'])
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user1['id'], project2['id'], role_list[1]['id'])
        # Create a non-inherited role as a spoiler
        PROVIDERS.assignment_api.create_grant(
            role_list[2]['id'], user_id=user1['id'], domain_id=domain['id'])

        # Now create two inherited roles on the domain, one for a user
        # and one for a domain
        base_collection_url = (
            '/OS-INHERIT/domains/%(domain_id)s/users/%(user_id)s/roles' % {
                'domain_id': domain['id'],
                'user_id': user1['id']})
        member_url = '%(collection_url)s/%(role_id)s/inherited_to_projects' % {
            'collection_url': base_collection_url,
            'role_id': role_list[3]['id']}
        collection_url = base_collection_url + '/inherited_to_projects'

        self.put(member_url)
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, ref=role_list[3],
                                         resource_url=collection_url)

        base_collection_url = (
            '/OS-INHERIT/domains/%(domain_id)s/groups/%(group_id)s/roles' % {
                'domain_id': domain['id'],
                'group_id': group1['id']})
        member_url = '%(collection_url)s/%(role_id)s/inherited_to_projects' % {
            'collection_url': base_collection_url,
            'role_id': role_list[4]['id']}
        collection_url = base_collection_url + '/inherited_to_projects'

        self.put(member_url)
        self.head(member_url)
        self.get(member_url, expected_status=http_client.NO_CONTENT)
        r = self.get(collection_url)
        self.assertValidRoleListResponse(r, ref=role_list[4],
                                         resource_url=collection_url)

        # Now use the list role assignments api to get a list of inherited
        # roles on the domain - should get back the two roles
        collection_url = (
            '/role_assignments?scope.OS-INHERIT:inherited_to=projects')
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   expected_length=2,
                                                   resource_url=collection_url)
        ud_entity = self.build_role_assignment_entity(
            domain_id=domain['id'], user_id=user1['id'],
            role_id=role_list[3]['id'], inherited_to_projects=True)
        gd_entity = self.build_role_assignment_entity(
            domain_id=domain['id'], group_id=group1['id'],
            role_id=role_list[4]['id'], inherited_to_projects=True)
        self.assertRoleAssignmentInListResponse(r, ud_entity)
        self.assertRoleAssignmentInListResponse(r, gd_entity)

    def _setup_hierarchical_projects_scenario(self):
        """Create basic hierarchical projects scenario.

        This basic scenario contains a root with one leaf project and
        two roles with the following names: non-inherited and inherited.

        """
        # Create project hierarchy
        root = unit.new_project_ref(domain_id=self.domain['id'])
        leaf = unit.new_project_ref(domain_id=self.domain['id'],
                                    parent_id=root['id'])

        PROVIDERS.resource_api.create_project(root['id'], root)
        PROVIDERS.resource_api.create_project(leaf['id'], leaf)

        # Create 'non-inherited' and 'inherited' roles
        non_inherited_role = unit.new_role_ref(name='non-inherited')
        PROVIDERS.role_api.create_role(
            non_inherited_role['id'], non_inherited_role
        )
        inherited_role = unit.new_role_ref(name='inherited')
        PROVIDERS.role_api.create_role(inherited_role['id'], inherited_role)

        return (root['id'], leaf['id'],
                non_inherited_role['id'], inherited_role['id'])

    def test_get_token_from_inherited_user_project_role_grants(self):
        # Create default scenario
        root_id, leaf_id, non_inherited_role_id, inherited_role_id = (
            self._setup_hierarchical_projects_scenario())

        # Define root and leaf projects authentication data
        root_project_auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=root_id)
        leaf_project_auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=leaf_id)

        # Check the user cannot get a token on root nor leaf project
        self.v3_create_token(root_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)
        self.v3_create_token(leaf_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

        # Grant non-inherited role for user on leaf project
        non_inher_up_link = self.build_role_assignment_link(
            project_id=leaf_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.put(non_inher_up_link)

        # Check the user can only get a token on leaf project
        self.v3_create_token(root_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)
        self.v3_create_token(leaf_project_auth_data)

        # Grant inherited role for user on root project
        inher_up_link = self.build_role_assignment_link(
            project_id=root_id, user_id=self.user['id'],
            role_id=inherited_role_id, inherited_to_projects=True)
        self.put(inher_up_link)

        # Check the user still can get a token only on leaf project
        self.v3_create_token(root_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)
        self.v3_create_token(leaf_project_auth_data)

        # Delete non-inherited grant
        self.delete(non_inher_up_link)

        # Check the inherited role still applies for leaf project
        self.v3_create_token(root_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)
        self.v3_create_token(leaf_project_auth_data)

        # Delete inherited grant
        self.delete(inher_up_link)

        # Check the user cannot get a token on leaf project anymore
        self.v3_create_token(leaf_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

    def test_get_token_from_inherited_group_project_role_grants(self):
        # Create default scenario
        root_id, leaf_id, non_inherited_role_id, inherited_role_id = (
            self._setup_hierarchical_projects_scenario())

        # Create group and add user to it
        group = unit.new_group_ref(domain_id=self.domain['id'])
        group = PROVIDERS.identity_api.create_group(group)
        PROVIDERS.identity_api.add_user_to_group(self.user['id'], group['id'])

        # Define root and leaf projects authentication data
        root_project_auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=root_id)
        leaf_project_auth_data = self.build_authentication_request(
            user_id=self.user['id'],
            password=self.user['password'],
            project_id=leaf_id)

        # Check the user cannot get a token on root nor leaf project
        self.v3_create_token(root_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)
        self.v3_create_token(leaf_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

        # Grant non-inherited role for group on leaf project
        non_inher_gp_link = self.build_role_assignment_link(
            project_id=leaf_id, group_id=group['id'],
            role_id=non_inherited_role_id)
        self.put(non_inher_gp_link)

        # Check the user can only get a token on leaf project
        self.v3_create_token(root_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)
        self.v3_create_token(leaf_project_auth_data)

        # Grant inherited role for group on root project
        inher_gp_link = self.build_role_assignment_link(
            project_id=root_id, group_id=group['id'],
            role_id=inherited_role_id, inherited_to_projects=True)
        self.put(inher_gp_link)

        # Check the user still can get a token only on leaf project
        self.v3_create_token(root_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)
        self.v3_create_token(leaf_project_auth_data)

        # Delete no-inherited grant
        self.delete(non_inher_gp_link)

        # Check the inherited role still applies for leaf project
        self.v3_create_token(leaf_project_auth_data)

        # Delete inherited grant
        self.delete(inher_gp_link)

        # Check the user cannot get a token on leaf project anymore
        self.v3_create_token(leaf_project_auth_data,
                             expected_status=http_client.UNAUTHORIZED)

    def test_get_role_assignments_for_project_hierarchy(self):
        """Call ``GET /role_assignments``.

        Test Plan:

        - Create 2 roles
        - Create a hierarchy of projects with one root and one leaf project
        - Issue the URL to add a non-inherited user role to the root project
        - Issue the URL to add an inherited user role to the root project
        - Issue the URL to get all role assignments - this should return just
          2 roles (non-inherited and inherited) in the root project.

        """
        # Create default scenario
        root_id, leaf_id, non_inherited_role_id, inherited_role_id = (
            self._setup_hierarchical_projects_scenario())

        # Grant non-inherited role
        non_inher_up_entity = self.build_role_assignment_entity(
            project_id=root_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.put(non_inher_up_entity['links']['assignment'])

        # Grant inherited role
        inher_up_entity = self.build_role_assignment_entity(
            project_id=root_id, user_id=self.user['id'],
            role_id=inherited_role_id, inherited_to_projects=True)
        self.put(inher_up_entity['links']['assignment'])

        # Get role assignments
        collection_url = '/role_assignments'
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   resource_url=collection_url)

        # Assert that the user has non-inherited role on root project
        self.assertRoleAssignmentInListResponse(r, non_inher_up_entity)

        # Assert that the user has inherited role on root project
        self.assertRoleAssignmentInListResponse(r, inher_up_entity)

        # Assert that the user does not have non-inherited role on leaf project
        non_inher_up_entity = self.build_role_assignment_entity(
            project_id=leaf_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.assertRoleAssignmentNotInListResponse(r, non_inher_up_entity)

        # Assert that the user does not have inherited role on leaf project
        inher_up_entity['scope']['project']['id'] = leaf_id
        self.assertRoleAssignmentNotInListResponse(r, inher_up_entity)

    def test_get_effective_role_assignments_for_project_hierarchy(self):
        """Call ``GET /role_assignments?effective``.

        Test Plan:

        - Create 2 roles
        - Create a hierarchy of projects with one root and one leaf project
        - Issue the URL to add a non-inherited user role to the root project
        - Issue the URL to add an inherited user role to the root project
        - Issue the URL to get effective role assignments - this should return
          1 role (non-inherited) on the root project and 1 role (inherited) on
          the leaf project.

        """
        # Create default scenario
        root_id, leaf_id, non_inherited_role_id, inherited_role_id = (
            self._setup_hierarchical_projects_scenario())

        # Grant non-inherited role
        non_inher_up_entity = self.build_role_assignment_entity(
            project_id=root_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.put(non_inher_up_entity['links']['assignment'])

        # Grant inherited role
        inher_up_entity = self.build_role_assignment_entity(
            project_id=root_id, user_id=self.user['id'],
            role_id=inherited_role_id, inherited_to_projects=True)
        self.put(inher_up_entity['links']['assignment'])

        # Get effective role assignments
        collection_url = '/role_assignments?effective'
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   resource_url=collection_url)

        # Assert that the user has non-inherited role on root project
        self.assertRoleAssignmentInListResponse(r, non_inher_up_entity)

        # Assert that the user does not have inherited role on root project
        self.assertRoleAssignmentNotInListResponse(r, inher_up_entity)

        # Assert that the user does not have non-inherited role on leaf project
        non_inher_up_entity = self.build_role_assignment_entity(
            project_id=leaf_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.assertRoleAssignmentNotInListResponse(r, non_inher_up_entity)

        # Assert that the user has inherited role on leaf project
        inher_up_entity['scope']['project']['id'] = leaf_id
        self.assertRoleAssignmentInListResponse(r, inher_up_entity)

    def test_project_id_specified_if_include_subtree_specified(self):
        """When using include_subtree, you must specify a project ID."""
        self.get('/role_assignments?include_subtree=True',
                 expected_status=http_client.BAD_REQUEST)
        self.get('/role_assignments?scope.project.id&'
                 'include_subtree=True',
                 expected_status=http_client.BAD_REQUEST)

    def test_get_role_assignments_for_project_tree(self):
        """Get role_assignment?scope.project.id=X&include_subtree``.

        Test Plan:

        - Create 2 roles and a hierarchy of projects with one root and one leaf
        - Issue the URL to add a non-inherited user role to the root project
          and the leaf project
        - Issue the URL to get role assignments for the root project but
          not the subtree - this should return just the root assignment
        - Issue the URL to get role assignments for the root project and
          it's subtree - this should return both assignments
        - Check that explicitly setting include_subtree to False is the
          equivalent to not including it at all in the query.

        """
        # Create default scenario
        root_id, leaf_id, non_inherited_role_id, unused_role_id = (
            self._setup_hierarchical_projects_scenario())

        # Grant non-inherited role to root and leaf projects
        non_inher_entity_root = self.build_role_assignment_entity(
            project_id=root_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.put(non_inher_entity_root['links']['assignment'])
        non_inher_entity_leaf = self.build_role_assignment_entity(
            project_id=leaf_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.put(non_inher_entity_leaf['links']['assignment'])

        # Without the subtree, we should get the one assignment on the
        # root project
        collection_url = (
            '/role_assignments?scope.project.id=%(project)s' % {
                'project': root_id})
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(
            r, resource_url=collection_url)

        self.assertThat(r.result['role_assignments'], matchers.HasLength(1))
        self.assertRoleAssignmentInListResponse(r, non_inher_entity_root)

        # With the subtree, we should get both assignments
        collection_url = (
            '/role_assignments?scope.project.id=%(project)s'
            '&include_subtree=True' % {
                'project': root_id})
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(
            r, resource_url=collection_url)

        self.assertThat(r.result['role_assignments'], matchers.HasLength(2))
        self.assertRoleAssignmentInListResponse(r, non_inher_entity_root)
        self.assertRoleAssignmentInListResponse(r, non_inher_entity_leaf)

        # With subtree=0, we should also only get the one assignment on the
        # root project
        collection_url = (
            '/role_assignments?scope.project.id=%(project)s'
            '&include_subtree=0' % {
                'project': root_id})
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(
            r, resource_url=collection_url)

        self.assertThat(r.result['role_assignments'], matchers.HasLength(1))
        self.assertRoleAssignmentInListResponse(r, non_inher_entity_root)

    def test_get_effective_role_assignments_for_project_tree(self):
        """Get role_assignment ?project_id=X&include_subtree=True&effective``.

        Test Plan:

        - Create 2 roles and a hierarchy of projects with one root and 4 levels
          of child project
        - Issue the URL to add a non-inherited user role to the root project
          and a level 1 project
        - Issue the URL to add an inherited user role on the level 2 project
        - Issue the URL to get effective role assignments for the level 1
          project and it's subtree - this should return a role (non-inherited)
          on the level 1 project and roles (inherited) on each of the level
          2, 3 and 4 projects

        """
        # Create default scenario
        root_id, leaf_id, non_inherited_role_id, inherited_role_id = (
            self._setup_hierarchical_projects_scenario())

        # Add some extra projects to the project hierarchy
        level2 = unit.new_project_ref(domain_id=self.domain['id'],
                                      parent_id=leaf_id)
        level3 = unit.new_project_ref(domain_id=self.domain['id'],
                                      parent_id=level2['id'])
        level4 = unit.new_project_ref(domain_id=self.domain['id'],
                                      parent_id=level3['id'])
        PROVIDERS.resource_api.create_project(level2['id'], level2)
        PROVIDERS.resource_api.create_project(level3['id'], level3)
        PROVIDERS.resource_api.create_project(level4['id'], level4)

        # Grant non-inherited role to root (as a spoiler) and to
        # the level 1 (leaf) project
        non_inher_entity_root = self.build_role_assignment_entity(
            project_id=root_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.put(non_inher_entity_root['links']['assignment'])
        non_inher_entity_leaf = self.build_role_assignment_entity(
            project_id=leaf_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.put(non_inher_entity_leaf['links']['assignment'])

        # Grant inherited role to level 2
        inher_entity = self.build_role_assignment_entity(
            project_id=level2['id'], user_id=self.user['id'],
            role_id=inherited_role_id, inherited_to_projects=True)
        self.put(inher_entity['links']['assignment'])

        # Get effective role assignments
        collection_url = (
            '/role_assignments?scope.project.id=%(project)s'
            '&include_subtree=True&effective' % {
                'project': leaf_id})
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(
            r, resource_url=collection_url)

        # There should be three assignments returned in total
        self.assertThat(r.result['role_assignments'], matchers.HasLength(3))

        # Assert that the user does not non-inherited role on root project
        self.assertRoleAssignmentNotInListResponse(r, non_inher_entity_root)

        # Assert that the user does have non-inherited role on leaf project
        self.assertRoleAssignmentInListResponse(r, non_inher_entity_leaf)

        # Assert that the user has inherited role on levels 3 and 4
        inher_entity['scope']['project']['id'] = level3['id']
        self.assertRoleAssignmentInListResponse(r, inher_entity)
        inher_entity['scope']['project']['id'] = level4['id']
        self.assertRoleAssignmentInListResponse(r, inher_entity)

    def test_get_inherited_role_assignments_for_project_hierarchy(self):
        """Call ``GET /role_assignments?scope.OS-INHERIT:inherited_to``.

        Test Plan:

        - Create 2 roles
        - Create a hierarchy of projects with one root and one leaf project
        - Issue the URL to add a non-inherited user role to the root project
        - Issue the URL to add an inherited user role to the root project
        - Issue the URL to filter inherited to projects role assignments - this
          should return 1 role (inherited) on the root project.

        """
        # Create default scenario
        root_id, leaf_id, non_inherited_role_id, inherited_role_id = (
            self._setup_hierarchical_projects_scenario())

        # Grant non-inherited role
        non_inher_up_entity = self.build_role_assignment_entity(
            project_id=root_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.put(non_inher_up_entity['links']['assignment'])

        # Grant inherited role
        inher_up_entity = self.build_role_assignment_entity(
            project_id=root_id, user_id=self.user['id'],
            role_id=inherited_role_id, inherited_to_projects=True)
        self.put(inher_up_entity['links']['assignment'])

        # Get inherited role assignments
        collection_url = ('/role_assignments'
                          '?scope.OS-INHERIT:inherited_to=projects')
        r = self.get(collection_url)
        self.assertValidRoleAssignmentListResponse(r,
                                                   resource_url=collection_url)

        # Assert that the user does not have non-inherited role on root project
        self.assertRoleAssignmentNotInListResponse(r, non_inher_up_entity)

        # Assert that the user has inherited role on root project
        self.assertRoleAssignmentInListResponse(r, inher_up_entity)

        # Assert that the user does not have non-inherited role on leaf project
        non_inher_up_entity = self.build_role_assignment_entity(
            project_id=leaf_id, user_id=self.user['id'],
            role_id=non_inherited_role_id)
        self.assertRoleAssignmentNotInListResponse(r, non_inher_up_entity)

        # Assert that the user does not have inherited role on leaf project
        inher_up_entity['scope']['project']['id'] = leaf_id
        self.assertRoleAssignmentNotInListResponse(r, inher_up_entity)


class ImpliedRolesTests(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin,
                        unit.TestCase):
    def _create_role(self):
        """Call ``POST /roles``."""
        ref = unit.new_role_ref()
        r = self.post('/roles', body={'role': ref})
        return self.assertValidRoleResponse(r, ref)

    def test_list_implied_roles_none(self):
        self.prior = self._create_role()
        url = '/roles/%s/implies' % (self.prior['id'])
        response = self.get(url).json["role_inference"]
        self.head(url, expected_status=http_client.OK)
        self.assertEqual(self.prior['id'], response['prior_role']['id'])
        self.assertEqual(0, len(response['implies']))

    def _create_implied_role(self, prior, implied):
        self.put('/roles/%s/implies/%s' % (prior['id'], implied['id']),
                 expected_status=http_client.CREATED)

    def _delete_implied_role(self, prior, implied):
        self.delete('/roles/%s/implies/%s' % (prior['id'], implied['id']))

    def _setup_prior_two_implied(self):
        self.prior = self._create_role()
        self.implied1 = self._create_role()
        self._create_implied_role(self.prior, self.implied1)
        self.implied2 = self._create_role()
        self._create_implied_role(self.prior, self.implied2)

    def _assert_expected_implied_role_response(
            self, expected_prior_id, expected_implied_ids):
        r = self.get('/roles/%s/implies' % expected_prior_id)
        response = r.json
        role_inference = response['role_inference']
        self.assertEqual(expected_prior_id, role_inference['prior_role']['id'])
        prior_link = '/v3/roles/' + expected_prior_id + '/implies'
        self.assertThat(response['links']['self'],
                        matchers.EndsWith(prior_link))

        actual_implied_ids = [implied['id']
                              for implied in role_inference['implies']]

        self.assertItemsEqual(expected_implied_ids, actual_implied_ids)

        self.assertIsNotNone(role_inference['prior_role']['links']['self'])
        for implied in role_inference['implies']:
            self.assertIsNotNone(implied['links']['self'])

    def _assert_expected_role_inference_rule_response(
            self, expected_prior_id, expected_implied_id):
        url = '/roles/%s/implies/%s' % (expected_prior_id, expected_implied_id)
        response = self.get(url).json
        self.assertThat(response['links']['self'],
                        matchers.EndsWith('/v3%s' % url))
        role_inference = response['role_inference']
        prior_role = role_inference['prior_role']
        self.assertEqual(expected_prior_id, prior_role['id'])
        self.assertIsNotNone(prior_role['name'])
        self.assertThat(prior_role['links']['self'],
                        matchers.EndsWith('/v3/roles/%s' % expected_prior_id))
        implied_role = role_inference['implies']
        self.assertEqual(expected_implied_id, implied_role['id'])
        self.assertIsNotNone(implied_role['name'])
        self.assertThat(implied_role['links']['self'], matchers.EndsWith(
            '/v3/roles/%s' % expected_implied_id))

    def _assert_two_roles_implied(self):
        self._assert_expected_implied_role_response(
            self.prior['id'], [self.implied1['id'], self.implied2['id']])
        self._assert_expected_role_inference_rule_response(
            self.prior['id'], self.implied1['id'])
        self._assert_expected_role_inference_rule_response(
            self.prior['id'], self.implied2['id'])

    def _assert_one_role_implied(self):
        self._assert_expected_implied_role_response(
            self.prior['id'], [self.implied1['id']])

        self.get('/roles/%s/implies/%s' %
                 (self.prior['id'], self.implied2['id']),
                 expected_status=http_client.NOT_FOUND)

    def _assert_two_rules_defined(self):
        r = self.get('/role_inferences/')

        rules = r.result['role_inferences']

        self.assertEqual(self.prior['id'], rules[0]['prior_role']['id'])
        self.assertEqual(2, len(rules[0]['implies']))
        implied_ids = [implied['id'] for implied in rules[0]['implies']]
        implied_names = [implied['name'] for implied in rules[0]['implies']]

        self.assertIn(self.implied1['id'], implied_ids)
        self.assertIn(self.implied2['id'], implied_ids)
        self.assertIn(self.implied1['name'], implied_names)
        self.assertIn(self.implied2['name'], implied_names)

    def _assert_one_rule_defined(self):
        r = self.get('/role_inferences/')
        rules = r.result['role_inferences']
        self.assertEqual(self.prior['id'], rules[0]['prior_role']['id'])
        self.assertEqual(self.implied1['id'], rules[0]['implies'][0]['id'])
        self.assertEqual(self.implied1['name'], rules[0]['implies'][0]['name'])
        self.assertEqual(1, len(rules[0]['implies']))

    def test_list_all_rules(self):
        self._setup_prior_two_implied()
        self._assert_two_rules_defined()

        self._delete_implied_role(self.prior, self.implied2)
        self._assert_one_rule_defined()

    def test_CRD_implied_roles(self):

        self._setup_prior_two_implied()
        self._assert_two_roles_implied()

        self._delete_implied_role(self.prior, self.implied2)
        self._assert_one_role_implied()

    def _create_three_roles(self):
        self.role_list = []
        for _ in range(3):
            role = unit.new_role_ref()
            PROVIDERS.role_api.create_role(role['id'], role)
            self.role_list.append(role)

    def _create_test_domain_user_project(self):
        domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(domain['id'], domain)
        user = unit.create_user(PROVIDERS.identity_api, domain_id=domain['id'])
        project = unit.new_project_ref(domain_id=domain['id'])
        PROVIDERS.resource_api.create_project(project['id'], project)
        return domain, user, project

    def _assign_top_role_to_user_on_project(self, user, project):
        PROVIDERS.assignment_api.add_role_to_user_and_project(
            user['id'], project['id'], self.role_list[0]['id'])

    def _build_effective_role_assignments_url(self, user):
        return '/role_assignments?effective&user.id=%(user_id)s' % {
            'user_id': user['id']}

    def _assert_all_roles_in_assignment(self, response, user):
        # Now use the list role assignments api to check that all three roles
        # appear in the collection
        self.assertValidRoleAssignmentListResponse(
            response,
            expected_length=len(self.role_list),
            resource_url=self._build_effective_role_assignments_url(user))

    def _assert_initial_assignment_in_effective(self, response, user, project):
        # The initial assignment should be there (the link url will be
        # generated and checked automatically since it matches the assignment)
        entity = self.build_role_assignment_entity(
            project_id=project['id'],
            user_id=user['id'], role_id=self.role_list[0]['id'])
        self.assertRoleAssignmentInListResponse(response, entity)

    def _assert_effective_role_for_implied_has_prior_in_links(
            self, response, user, project, prior_index, implied_index):
        # An effective role for an implied role will have the prior role
        # assignment in the links
        prior_link = '/prior_roles/%(prior)s/implies/%(implied)s' % {
            'prior': self.role_list[prior_index]['id'],
            'implied': self.role_list[implied_index]['id']}
        link = self.build_role_assignment_link(
            project_id=project['id'], user_id=user['id'],
            role_id=self.role_list[prior_index]['id'])
        entity = self.build_role_assignment_entity(
            link=link, project_id=project['id'],
            user_id=user['id'], role_id=self.role_list[implied_index]['id'],
            prior_link=prior_link)
        self.assertRoleAssignmentInListResponse(response, entity)

    def test_list_role_assignments_with_implied_roles(self):
        """Call ``GET /role_assignments`` with implied role grant.

        Test Plan:

        - Create a domain with a user and a project
        - Create 3 roles
        - Role 0 implies role 1 and role 1 implies role 2
        - Assign the top role to the project
        - Issue the URL to check effective roles on project - this
          should return all 3 roles.
        - Check the links of the 3 roles indicate the prior role where
          appropriate

        """
        (domain, user, project) = self._create_test_domain_user_project()
        self._create_three_roles()
        self._create_implied_role(self.role_list[0], self.role_list[1])
        self._create_implied_role(self.role_list[1], self.role_list[2])
        self._assign_top_role_to_user_on_project(user, project)

        response = self.get(self._build_effective_role_assignments_url(user))
        r = response

        self._assert_all_roles_in_assignment(r, user)
        self._assert_initial_assignment_in_effective(response, user, project)
        self._assert_effective_role_for_implied_has_prior_in_links(
            response, user, project, 0, 1)
        self._assert_effective_role_for_implied_has_prior_in_links(
            response, user, project, 1, 2)

    def _create_named_role(self, name):
        role = unit.new_role_ref()
        role['name'] = name
        PROVIDERS.role_api.create_role(role['id'], role)
        return role

    def test_root_role_as_implied_role_forbidden(self):
        """Test root role is forbidden to be set as an implied role.

        Create 2 roles that are prohibited from being an implied role.
        Create 1 additional role which should be accepted as an implied
        role. Assure the prohibited role names cannot be set as an implied
        role. Assure the accepted role name which is not a member of the
        prohibited implied role list can be successfully set an implied
        role.
        """
        prohibited_name1 = 'root1'
        prohibited_name2 = 'root2'
        accepted_name1 = 'implied1'

        prohibited_names = [prohibited_name1, prohibited_name2]
        self.config_fixture.config(group='assignment',
                                   prohibited_implied_role=prohibited_names)

        prior_role = self._create_role()

        prohibited_role1 = self._create_named_role(prohibited_name1)
        url = '/roles/{prior_role_id}/implies/{implied_role_id}'.format(
            prior_role_id=prior_role['id'],
            implied_role_id=prohibited_role1['id'])
        self.put(url, expected_status=http_client.FORBIDDEN)

        prohibited_role2 = self._create_named_role(prohibited_name2)
        url = '/roles/{prior_role_id}/implies/{implied_role_id}'.format(
            prior_role_id=prior_role['id'],
            implied_role_id=prohibited_role2['id'])
        self.put(url, expected_status=http_client.FORBIDDEN)

        accepted_role1 = self._create_named_role(accepted_name1)
        url = '/roles/{prior_role_id}/implies/{implied_role_id}'.format(
            prior_role_id=prior_role['id'],
            implied_role_id=accepted_role1['id'])
        self.put(url, expected_status=http_client.CREATED)

    def test_trusts_from_implied_role(self):
        self._create_three_roles()
        self._create_implied_role(self.role_list[0], self.role_list[1])
        self._create_implied_role(self.role_list[1], self.role_list[2])
        self._assign_top_role_to_user_on_project(self.user, self.project)

        # Create a trustee and assign the prior role to her
        trustee = unit.create_user(
            PROVIDERS.identity_api, domain_id=self.domain_id
        )
        ref = unit.new_trust_ref(
            trustor_user_id=self.user['id'],
            trustee_user_id=trustee['id'],
            project_id=self.project['id'],
            role_ids=[self.role_list[0]['id']])
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = r.result['trust']

        # Only the role that was specified is in the trust, NOT implied roles
        self.assertEqual(self.role_list[0]['id'], trust['roles'][0]['id'])
        self.assertThat(trust['roles'], matchers.HasLength(1))

        # Authenticate as the trustee
        auth_data = self.build_authentication_request(
            user_id=trustee['id'],
            password=trustee['password'],
            trust_id=trust['id'])
        r = self.v3_create_token(auth_data)
        token = r.result['token']
        self.assertThat(token['roles'],
                        matchers.HasLength(len(self.role_list)))
        for role in token['roles']:
            self.assertIn(role, self.role_list)
        for role in self.role_list:
            self.assertIn(role, token['roles'])

    def test_trusts_from_domain_specific_implied_role(self):
        self._create_three_roles()
        # Overwrite the first role with a domain specific role
        role = unit.new_role_ref(domain_id=self.domain_id)
        self.role_list[0] = PROVIDERS.role_api.create_role(role['id'], role)
        self._create_implied_role(self.role_list[0], self.role_list[1])
        self._create_implied_role(self.role_list[1], self.role_list[2])
        self._assign_top_role_to_user_on_project(self.user, self.project)

        # Create a trustee and assign the prior role to her
        trustee = unit.create_user(
            PROVIDERS.identity_api, domain_id=self.domain_id
        )
        ref = unit.new_trust_ref(
            trustor_user_id=self.user['id'],
            trustee_user_id=trustee['id'],
            project_id=self.project['id'],
            role_ids=[self.role_list[0]['id']])
        r = self.post('/OS-TRUST/trusts', body={'trust': ref})
        trust = r.result['trust']

        # Only the role that was specified is in the trust, NOT implied roles
        self.assertEqual(self.role_list[0]['id'], trust['roles'][0]['id'])
        self.assertThat(trust['roles'], matchers.HasLength(1))

        # Authenticate as the trustee
        auth_data = self.build_authentication_request(
            user_id=trustee['id'],
            password=trustee['password'],
            trust_id=trust['id'])
        r = self.v3_create_token(auth_data)
        token = r.result['token']

        # The token should have the roles implies by the domain specific role,
        # but not the domain specific role itself.
        self.assertThat(token['roles'],
                        matchers.HasLength(len(self.role_list) - 1))
        for role in token['roles']:
            self.assertIn(role, self.role_list)
        for role in [self.role_list[1], self.role_list[2]]:
            self.assertIn(role, token['roles'])
        self.assertNotIn(self.role_list[0], token['roles'])

    def test_global_role_cannot_imply_domain_specific_role(self):
        domain = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(domain['id'], domain)

        domain_role_ref = unit.new_role_ref(domain_id=domain['id'])
        domain_role = PROVIDERS.role_api.create_role(
            domain_role_ref['id'], domain_role_ref
        )
        global_role_ref = unit.new_role_ref()
        global_role = PROVIDERS.role_api.create_role(
            global_role_ref['id'], global_role_ref
        )

        self.put('/roles/%s/implies/%s' % (global_role['id'],
                                           domain_role['id']),
                 expected_status=http_client.FORBIDDEN)


class DomainSpecificRoleTests(test_v3.RestfulTestCase, unit.TestCase):
    def setUp(self):
        def create_role(domain_id=None):
            """Call ``POST /roles``."""
            ref = unit.new_role_ref(domain_id=domain_id)
            r = self.post(
                '/roles',
                body={'role': ref})
            return self.assertValidRoleResponse(r, ref)

        super(DomainSpecificRoleTests, self).setUp()
        self.domainA = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(self.domainA['id'], self.domainA)
        self.domainB = unit.new_domain_ref()
        PROVIDERS.resource_api.create_domain(self.domainB['id'], self.domainB)

        self.global_role1 = create_role()
        self.global_role2 = create_role()
        # Since there maybe other global roles already created, let's count
        # them, so we can ensure we can check subsequent list responses
        # are correct
        r = self.get('/roles')
        self.existing_global_roles = len(r.result['roles'])

        # And now create some domain specific roles
        self.domainA_role1 = create_role(domain_id=self.domainA['id'])
        self.domainA_role2 = create_role(domain_id=self.domainA['id'])
        self.domainB_role = create_role(domain_id=self.domainB['id'])

    def test_get_and_list_domain_specific_roles(self):
        # Check we can get a domain specific role
        r = self.get('/roles/%s' % self.domainA_role1['id'])
        self.assertValidRoleResponse(r, self.domainA_role1)

        # If we list without specifying a domain, we should only get global
        # roles back.
        r = self.get('/roles')
        self.assertValidRoleListResponse(
            r, expected_length=self.existing_global_roles)
        self.assertRoleInListResponse(r, self.global_role1)
        self.assertRoleInListResponse(r, self.global_role2)
        self.assertRoleNotInListResponse(r, self.domainA_role1)
        self.assertRoleNotInListResponse(r, self.domainA_role2)
        self.assertRoleNotInListResponse(r, self.domainB_role)

        # Now list those in domainA, making sure that's all we get back
        r = self.get('/roles?domain_id=%s' % self.domainA['id'])
        self.assertValidRoleListResponse(r, expected_length=2)
        self.assertRoleInListResponse(r, self.domainA_role1)
        self.assertRoleInListResponse(r, self.domainA_role2)

    def test_update_domain_specific_roles(self):
        self.domainA_role1['name'] = uuid.uuid4().hex
        self.patch('/roles/%(role_id)s' % {
            'role_id': self.domainA_role1['id']},
            body={'role': self.domainA_role1})
        r = self.get('/roles/%s' % self.domainA_role1['id'])
        self.assertValidRoleResponse(r, self.domainA_role1)

    def test_delete_domain_specific_roles(self):
        # Check delete only removes that one domain role
        self.delete('/roles/%(role_id)s' % {
            'role_id': self.domainA_role1['id']})

        self.get('/roles/%s' % self.domainA_role1['id'],
                 expected_status=http_client.NOT_FOUND)
        # Now re-list those in domainA, making sure there's only one left
        r = self.get('/roles?domain_id=%s' % self.domainA['id'])
        self.assertValidRoleListResponse(r, expected_length=1)
        self.assertRoleInListResponse(r, self.domainA_role2)

    def test_same_domain_assignment(self):
        user = unit.create_user(PROVIDERS.identity_api,
                                domain_id=self.domainA['id'])

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

        PROVIDERS.assignment_api.create_grant(
            self.domainA_role1['id'], user_id=user['id'],
            project_id=projectA['id']
        )

    def test_cross_domain_assignment_valid(self):
        user = unit.create_user(PROVIDERS.identity_api,
                                domain_id=self.domainB['id'])

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

        # Positive: a role on domainA can be assigned to a user from domainB
        # but only for use on a project from domainA
        PROVIDERS.assignment_api.create_grant(
            self.domainA_role1['id'], user_id=user['id'],
            project_id=projectA['id']
        )

    def test_cross_domain_assignment_invalid(self):
        user = unit.create_user(PROVIDERS.identity_api,
                                domain_id=self.domainB['id'])

        projectB = unit.new_project_ref(domain_id=self.domainB['id'])
        PROVIDERS.resource_api.create_project(projectB['id'], projectB)

        # Negative: a role on domainA can be assigned to a user from domainB
        # only for a project from domainA
        self.assertRaises(exception.DomainSpecificRoleMismatch,
                          PROVIDERS.assignment_api.create_grant,
                          self.domainA_role1['id'],
                          user_id=user['id'],
                          project_id=projectB['id'])

    def test_cross_domain_implied_roles_authentication(self):
        # Create a user in domainB
        user = unit.create_user(PROVIDERS.identity_api,
                                domain_id=self.domainB['id'])

        # Create project in domainA
        projectA = unit.new_project_ref(domain_id=self.domainA['id'])
        PROVIDERS.resource_api.create_project(projectA['id'], projectA)

        # Now we create an implied rule from a role in domainA to a
        # role in domainB
        self.put('/roles/%s/implies/%s' %
                 (self.domainA_role1['id'], self.domainB_role['id']),
                 expected_status=http_client.CREATED)

        # A role in domainA can be assigned to a user from domainB
        # only for a project from domainA
        PROVIDERS.assignment_api.create_grant(
            self.domainA_role1['id'], user_id=user['id'],
            project_id=projectA['id']
        )

        # The role assignments should return an empty list since domain roles
        # can only be used to imply another roles
        assignments = PROVIDERS.assignment_api.list_role_assignments(
            user_id=user['id'], effective=True)
        self.assertEqual([], assignments)

        # This also means we can't authenticate using the existing assignment
        auth_body = self.build_authentication_request(
            user_id=user['id'],
            password=user['password'],
            project_id=projectA['id'])
        self.post('/auth/tokens', body=auth_body,
                  expected_status=http_client.UNAUTHORIZED)


class ListUserProjectsTestCase(test_v3.RestfulTestCase):
    """Test for /users/<user>/projects."""

    def load_sample_data(self):
        # do not load base class's data, keep it focused on the tests

        self.auths = []
        self.domains = []
        self.projects = []
        self.roles = []
        self.users = []

        root_domain = unit.new_domain_ref(
            id=resource_base.NULL_DOMAIN_ID,
            name=resource_base.NULL_DOMAIN_ID
        )
        self.resource_api.create_domain(resource_base.NULL_DOMAIN_ID,
                                        root_domain)

        # Create 3 sets of domain, roles, projects, and users to demonstrate
        # the right user's data is loaded and only projects they can access
        # are returned.

        for _ in range(3):
            domain = unit.new_domain_ref()
            PROVIDERS.resource_api.create_domain(domain['id'], domain)

            user = unit.create_user(
                PROVIDERS.identity_api, domain_id=domain['id']
            )

            role = unit.new_role_ref()
            PROVIDERS.role_api.create_role(role['id'], role)

            PROVIDERS.assignment_api.create_grant(
                role['id'], user_id=user['id'], domain_id=domain['id']
            )

            project = unit.new_project_ref(domain_id=domain['id'])
            PROVIDERS.resource_api.create_project(project['id'], project)

            PROVIDERS.assignment_api.create_grant(
                role['id'], user_id=user['id'], project_id=project['id']
            )

            auth = self.build_authentication_request(
                user_id=user['id'],
                password=user['password'],
                domain_id=domain['id'])

            self.auths.append(auth)
            self.domains.append(domain)
            self.projects.append(project)
            self.roles.append(role)
            self.users.append(user)

    def test_list_head_all(self):
        for i in range(len(self.users)):
            user = self.users[i]
            auth = self.auths[i]

            url = '/users/%s/projects' % user['id']
            result = self.get(url, auth=auth)
            projects_result = result.json['projects']
            self.assertEqual(1, len(projects_result))
            self.assertEqual(self.projects[i]['id'], projects_result[0]['id'])
            self.head(url, auth=auth, expected_status=http_client.OK)

    def test_list_enabled(self):
        for i in range(len(self.users)):
            user = self.users[i]
            auth = self.auths[i]

            # There are no disabled projects
            url = '/users/%s/projects?enabled=True' % user['id']
            result = self.get(url, auth=auth)
            projects_result = result.json['projects']
            self.assertEqual(1, len(projects_result))
            self.assertEqual(self.projects[i]['id'], projects_result[0]['id'])

    def test_list_disabled(self):
        for i in range(len(self.users)):
            user = self.users[i]
            auth = self.auths[i]
            project = self.projects[i]

            # There are no disabled projects
            url = '/users/%s/projects?enabled=False' % user['id']
            result = self.get(url, auth=auth)
            self.assertEqual(0, len(result.json['projects']))

            # disable this one and check again
            project['enabled'] = False
            PROVIDERS.resource_api.update_project(project['id'], project)
            result = self.get(url, auth=auth)
            projects_result = result.json['projects']
            self.assertEqual(1, len(projects_result))
            self.assertEqual(self.projects[i]['id'], projects_result[0]['id'])

    def test_list_by_domain_id(self):
        for i in range(len(self.users)):
            user = self.users[i]
            domain = self.domains[i]
            auth = self.auths[i]

            # Try looking for projects with a non-existent domain_id
            url = '/users/%s/projects?domain_id=%s' % (user['id'],
                                                       uuid.uuid4().hex)
            result = self.get(url, auth=auth)
            self.assertEqual(0, len(result.json['projects']))

            # Now try a valid one
            url = '/users/%s/projects?domain_id=%s' % (user['id'],
                                                       domain['id'])
            result = self.get(url, auth=auth)
            projects_result = result.json['projects']
            self.assertEqual(1, len(projects_result))
            self.assertEqual(self.projects[i]['id'], projects_result[0]['id'])


# FIXME(lbragstad): These tests contain system-level API calls, which means
# they will log a warning message if they are called with a project-scoped
# token, regardless of the role assignment on the project.  We need to fix
# them by using a proper system-scoped admin token to make the call instead
# of a project scoped token.
class UserSystemRoleAssignmentTestCase(test_v3.RestfulTestCase,
                                       SystemRoleAssignmentMixin):

    def test_assign_system_role_to_user(self):
        system_role_id = self._create_new_role()

        # assign the user a role on the system
        member_url = (
            '/system/users/%(user_id)s/roles/%(role_id)s' % {
                'user_id': self.user['id'],
                'role_id': system_role_id
            }
        )
        self.put(member_url)

        # validate the role assignment
        self.head(member_url)

        # list system roles
        collection_url = (
            '/system/users/%(user_id)s/roles' % {'user_id': self.user['id']}
        )
        roles = self.get(collection_url).json_body['roles']
        self.assertEqual(len(roles), 1)
        self.assertEqual(roles[0]['id'], system_role_id)
        self.head(collection_url, expected_status=http_client.OK)

        response = self.get(
            '/role_assignments?scope.system=all&user.id=%(user_id)s' % {
                'user_id': self.user['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response)

    def test_list_role_assignments_for_user_returns_all_assignments(self):
        system_role_id = self._create_new_role()

        # assign the user a role on the system
        member_url = '/system/users/%(user_id)s/roles/%(role_id)s' % {
            'user_id': self.user['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # the response should contain one role assignment for the system role
        # and one for a role that was setup during setUp().
        response = self.get(
            '/role_assignments?user.id=%(user_id)s' % {
                'user_id': self.user['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=2)

    def test_list_system_roles_for_user_returns_none_without_assignment(self):
        # list system roles for user
        collection_url = '/system/users/%(user_id)s/roles' % {
            'user_id': self.user['id']
        }
        response = self.get(collection_url)

        # assert that the user doesn't have any system role assignments, which
        # is denoted by an empty list
        self.assertEqual(response.json_body['roles'], [])

        response = self.get(
            '/role_assignments?scope.system=all&user.id=%(user_id)s' % {
                'user_id': self.user['id']
            }
        )
        self.assertEqual(len(response.json_body['role_assignments']), 0)
        self.assertValidRoleAssignmentListResponse(response)

    def test_list_system_roles_for_user_does_not_return_project_roles(self):
        system_role_id = self._create_new_role()

        # assign the user a role on the system
        member_url = '/system/users/%(user_id)s/roles/%(role_id)s' % {
            'user_id': self.user['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # list project role assignments and save the role id of that
        # assignment, this assignment was created during setUp
        response = self.get(
            '/projects/%(project_id)s/users/%(user_id)s/roles' % {
                'project_id': self.project['id'],
                'user_id': self.user['id']
            }
        )
        self.assertEqual(len(response.json_body['roles']), 1)
        project_role_id = response.json_body['roles'][0]['id']

        # list system role assignments
        collection_url = '/system/users/%(user_id)s/roles' % {
            'user_id': self.user['id']
        }
        response = self.get(collection_url)

        # assert the project role assignment is not in the system role
        # assignments
        for role in response.json_body['roles']:
            self.assertNotEqual(role['id'], project_role_id)

        # make sure the role_assignment API filters correctly based on system
        # scope
        response = self.get(
            '/role_assignments?scope.system=all&user.id=%(user_id)s' % {
                'user_id': self.user['id']
            }
        )
        self.assertEqual(len(response.json_body['role_assignments']), 1)
        system_assignment = response.json_body['role_assignments'][0]
        self.assertEqual(system_assignment['role']['id'], system_role_id)
        self.assertTrue(system_assignment['scope']['system']['all'])

        # make sure the role_assignment API doesn't include the system role
        # assignment when we filter based on project
        path = (
            '/role_assignments?scope.project.id=%(project_id)s&'
            'user.id=%(user_id)s'
        ) % {'project_id': self.project['id'],
             'user_id': self.user['id']}
        response = self.get(path)
        self.assertEqual(len(response.json_body['role_assignments']), 1)
        project_assignment = response.json_body['role_assignments'][0]
        self.assertEqual(project_assignment['role']['id'], project_role_id)

    def test_list_system_roles_for_user_does_not_return_domain_roles(self):
        system_role_id = self._create_new_role()
        domain_role_id = self._create_new_role()

        # assign a role to the user on a domain
        domain_member_url = (
            '/domains/%(domain_id)s/users/%(user_id)s/roles/%(role_id)s' % {
                'domain_id': self.user['domain_id'],
                'user_id': self.user['id'],
                'role_id': domain_role_id
            }
        )
        self.put(domain_member_url)

        # assign the user a role on the system
        member_url = '/system/users/%(user_id)s/roles/%(role_id)s' % {
            'user_id': self.user['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # list domain role assignments
        response = self.get(
            '/domains/%(domain_id)s/users/%(user_id)s/roles' % {
                'domain_id': self.user['domain_id'],
                'user_id': self.user['id']
            }
        )
        self.assertEqual(len(response.json_body['roles']), 1)

        # list system role assignments
        collection_url = '/system/users/%(user_id)s/roles' % {
            'user_id': self.user['id']
        }
        response = self.get(collection_url)

        # assert the domain role assignment is not in the system role
        # assignments
        for role in response.json_body['roles']:
            self.assertNotEqual(role['id'], domain_role_id)

        # make sure the role_assignment API filters correctly based on system
        # scope
        response = self.get(
            '/role_assignments?scope.system=all&user.id=%(user_id)s' % {
                'user_id': self.user['id']
            }
        )
        self.assertEqual(len(response.json_body['role_assignments']), 1)
        system_assignment = response.json_body['role_assignments'][0]
        self.assertEqual(system_assignment['role']['id'], system_role_id)
        self.assertTrue(system_assignment['scope']['system']['all'])

        # make sure the role_assignment API doesn't include the system role
        # assignment when we filter based on domain
        path = (
            '/role_assignments?scope.domain.id=%(domain_id)s&'
            'user.id=%(user_id)s'
        ) % {'domain_id': self.user['domain_id'],
             'user_id': self.user['id']}
        response = self.get(path)
        self.assertEqual(len(response.json_body['role_assignments']), 1)
        domain_assignment = response.json_body['role_assignments'][0]
        self.assertEqual(domain_assignment['role']['id'], domain_role_id)

    def test_check_user_has_system_role_when_assignment_exists(self):
        system_role_id = self._create_new_role()

        # assign the user a role on the system
        member_url = '/system/users/%(user_id)s/roles/%(role_id)s' % {
            'user_id': self.user['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # check the user has the system role assignment
        self.head(member_url)

    def test_check_user_does_not_have_system_role_without_assignment(self):
        system_role_id = self._create_new_role()

        # check the user does't have the system role assignment
        member_url = '/system/users/%(user_id)s/roles/%(role_id)s' % {
            'user_id': self.user['id'],
            'role_id': system_role_id
        }
        self.head(member_url, expected_status=http_client.NOT_FOUND)

        response = self.get(
            '/role_assignments?scope.system=all&user.id=%(user_id)s' % {
                'user_id': self.user['id']
            }
        )
        self.assertEqual(len(response.json_body['role_assignments']), 0)
        self.assertValidRoleAssignmentListResponse(response)

    def test_unassign_system_role_from_user(self):
        system_role_id = self._create_new_role()

        # assign the user a role on the system
        member_url = '/system/users/%(user_id)s/roles/%(role_id)s' % {
            'user_id': self.user['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # ensure the user has the role assignment
        self.head(member_url)

        response = self.get(
            '/role_assignments?scope.system=all&user.id=%(user_id)s' % {
                'user_id': self.user['id']
            }
        )
        self.assertEqual(len(response.json_body['role_assignments']), 1)
        self.assertValidRoleAssignmentListResponse(response)

        # remove the system role assignment from the user
        self.delete(member_url)

        # ensure the user doesn't have any system role assignments
        collection_url = '/system/users/%(user_id)s/roles' % {
            'user_id': self.user['id']
        }
        response = self.get(collection_url)
        self.assertEqual(len(response.json_body['roles']), 0)
        response = self.get(
            '/role_assignments?scope.system=all&user.id=%(user_id)s' % {
                'user_id': self.user['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=0)

    def test_query_for_system_scope_and_domain_scope_fails(self):
        # When asking for assignments and providing query parameters, we
        # shouldn't be able to ask for two different types of scope. This is
        # also true for project + domain scope.
        path = (
            '/role_assignments?scope.system=all'
            '&scope.domain.id=%(domain_id)s'
        ) % {'domain_id': self.domain_id}
        self.get(path, expected_status=http_client.BAD_REQUEST)

    def test_query_for_system_scope_and_project_scope_fails(self):
        # When asking for assignments and providing query parameters, we
        # shouldn't be able to ask for two different types of scope. This is
        # also true for project + domain scope.
        path = (
            '/role_assignments?scope.system=all'
            '&scope.project.id=%(project_id)s'
        ) % {'project_id': self.project_id}
        self.get(path, expected_status=http_client.BAD_REQUEST)

    def test_query_for_role_id_does_not_return_system_user_roles(self):
        system_role_id = self._create_new_role()

        # assign the user a role on the system
        member_url = '/system/users/%(user_id)s/roles/%(role_id)s' % {
            'user_id': self.user['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # Make sure we only get one role assignment back since the system role
        # assignment shouldn't be returned.
        path = (
            '/role_assignments?role.id=%(role_id)s&user.id=%(user_id)s'
        ) % {'role_id': self.role_id, 'user_id': self.user['id']}
        response = self.get(path)
        self.assertValidRoleAssignmentListResponse(response, expected_length=1)


# FIXME(lbragstad): These tests contain system-level API calls, which means
# they will log a warning message if they are called with a project-scoped
# token, regardless of the role assignment on the project.  We need to fix
# them by using a proper system-scoped admin token to make the call instead
# of a project scoped token.
class GroupSystemRoleAssignmentTestCase(test_v3.RestfulTestCase,
                                        SystemRoleAssignmentMixin):

    def test_assign_system_role_to_group(self):
        system_role_id = self._create_new_role()
        group = self._create_group()

        # assign the role to the group globally
        member_url = '/system/groups/%(group_id)s/roles/%(role_id)s' % {
            'group_id': group['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # validate the role assignment
        self.head(member_url)

        # list global roles
        collection_url = '/system/groups/%(group_id)s/roles' % {
            'group_id': group['id']
        }
        roles = self.get(collection_url).json_body['roles']
        self.assertEqual(len(roles), 1)
        self.assertEqual(roles[0]['id'], system_role_id)
        self.head(collection_url, expected_status=http_client.OK)

        response = self.get(
            '/role_assignments?scope.system=all&group.id=%(group_id)s' % {
                'group_id': group['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=1)
        self.assertEqual(
            response.json_body['role_assignments'][0]['role']['id'],
            system_role_id
        )

    def test_assign_system_role_to_non_existant_group_fails(self):
        system_role_id = self._create_new_role()
        group_id = uuid.uuid4().hex

        # assign the role to the group globally
        member_url = '/system/groups/%(group_id)s/roles/%(role_id)s' % {
            'group_id': group_id,
            'role_id': system_role_id
        }
        self.put(member_url, expected_status=http_client.NOT_FOUND)

    def test_list_role_assignments_for_group_returns_all_assignments(self):
        system_role_id = self._create_new_role()
        group = self._create_group()

        # assign the role to the group globally and on a single project
        member_url = '/system/groups/%(group_id)s/roles/%(role_id)s' % {
            'group_id': group['id'],
            'role_id': system_role_id
        }
        self.put(member_url)
        member_url = (
            '/projects/%(project_id)s/groups/%(group_id)s/'
            'roles/%(role_id)s'
        ) % {
            'project_id': self.project_id,
            'group_id': group['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # make sure both assignments exist in the response, there should be two
        response = self.get(
            '/role_assignments?group.id=%(group_id)s' % {
                'group_id': group['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=2)

    def test_list_system_roles_for_group_returns_none_without_assignment(self):
        group = self._create_group()

        # list global roles for group
        collection_url = '/system/groups/%(group_id)s/roles' % {
            'group_id': group['id']
        }
        response = self.get(collection_url)

        # assert that the group doesn't have any system role assignments, which
        # is denoted by an empty list
        self.assertEqual(response.json_body['roles'], [])

        response = self.get(
            '/role_assignments?scope.system=all&group.id=%(group_id)s' % {
                'group_id': group['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=0)

    def test_list_system_roles_for_group_does_not_return_project_roles(self):
        system_role_id = self._create_new_role()
        project_role_id = self._create_new_role()
        group = self._create_group()

        # assign the group a role on the system and a role on a project
        member_url = '/system/groups/%(group_id)s/roles/%(role_id)s' % {
            'group_id': group['id'], 'role_id': system_role_id
        }
        self.put(member_url)
        member_url = (
            '/projects/%(project_id)s/groups/%(group_id)s/'
            'roles/%(role_id)s'
        ) % {
            'project_id': self.project_id,
            'group_id': group['id'],
            'role_id': project_role_id
        }
        self.put(member_url)

        # list system role assignments
        collection_url = '/system/groups/%(group_id)s/roles' % {
            'group_id': group['id']
        }
        response = self.get(collection_url)

        # assert the project role assignment is not in the system role
        # assignments
        for role in response.json_body['roles']:
            self.assertNotEqual(role['id'], project_role_id)

        response = self.get(
            '/role_assignments?scope.system=all&group.id=%(group_id)s' % {
                'group_id': group['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=1)

    def test_list_system_roles_for_group_does_not_return_domain_roles(self):
        system_role_id = self._create_new_role()
        domain_role_id = self._create_new_role()
        group = self._create_group()

        # assign a role to the group on a domain
        domain_member_url = (
            '/domains/%(domain_id)s/groups/%(group_id)s/'
            'roles/%(role_id)s' % {
                'domain_id': group['domain_id'],
                'group_id': group['id'],
                'role_id': domain_role_id
            }
        )
        self.put(domain_member_url)

        # assign the group a role on the system
        member_url = '/system/groups/%(group_id)s/roles/%(role_id)s' % {
            'group_id': group['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # list domain role assignments
        response = self.get(
            '/domains/%(domain_id)s/groups/%(group_id)s/roles' % {
                'domain_id': group['domain_id'], 'group_id': group['id']
            }
        )
        self.assertEqual(len(response.json_body['roles']), 1)

        # list system role assignments
        collection_url = '/system/groups/%(group_id)s/roles' % {
            'group_id': group['id']
        }
        response = self.get(collection_url)

        # assert the domain role assignment is not in the system role
        # assignments
        for role in response.json_body['roles']:
            self.assertNotEqual(role['id'], domain_role_id)

        response = self.get(
            '/role_assignments?scope.system=all&group.id=%(group_id)s' % {
                'group_id': group['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=1)

    def test_check_group_has_system_role_when_assignment_exists(self):
        system_role_id = self._create_new_role()
        group = self._create_group()

        # assign the group a role on the system
        member_url = '/system/groups/%(group_id)s/roles/%(role_id)s' % {
            'group_id': group['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # check the group has the system role assignment
        self.head(member_url)

        response = self.get(
            '/role_assignments?scope.system=all&group.id=%(group_id)s' % {
                'group_id': group['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=1)
        self.assertEqual(
            response.json_body['role_assignments'][0]['role']['id'],
            system_role_id
        )

    def test_check_group_does_not_have_system_role_without_assignment(self):
        system_role_id = self._create_new_role()
        group = self._create_group()

        # check the group does't have the system role assignment
        member_url = '/system/groups/%(group_id)s/roles/%(role_id)s' % {
            'group_id': group['id'],
            'role_id': system_role_id
        }
        self.head(member_url, expected_status=http_client.NOT_FOUND)

        response = self.get(
            '/role_assignments?scope.system=all&group.id=%(group_id)s' % {
                'group_id': group['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=0)

    def test_unassign_system_role_from_group(self):
        system_role_id = self._create_new_role()
        group = self._create_group()

        # assign the group a role on the system
        member_url = '/system/groups/%(group_id)s/roles/%(role_id)s' % {
            'group_id': group['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # ensure the group has the role assignment
        self.head(member_url)

        response = self.get(
            '/role_assignments?scope.system=all&group.id=%(group_id)s' % {
                'group_id': group['id']
            }
        )
        self.assertEqual(len(response.json_body['role_assignments']), 1)
        self.assertValidRoleAssignmentListResponse(response)

        # remove the system role assignment from the group
        self.delete(member_url)

        # ensure the group doesn't have any system role assignments
        collection_url = '/system/groups/%(group_id)s/roles' % {
            'group_id': group['id']
        }
        response = self.get(collection_url)
        self.assertEqual(len(response.json_body['roles']), 0)
        response = self.get(
            '/role_assignments?scope.system=all&group.id=%(group_id)s' % {
                'group_id': group['id']
            }
        )
        self.assertValidRoleAssignmentListResponse(response, expected_length=0)

    def test_query_for_role_id_does_not_return_system_group_roles(self):
        system_role_id = self._create_new_role()
        group = self._create_group()

        # assign the group a role on the system
        member_url = '/system/groups/%(group_id)s/roles/%(role_id)s' % {
            'group_id': group['id'],
            'role_id': system_role_id
        }
        self.put(member_url)

        # assign the group a role on the system
        member_url = (
            '/projects/%(project_id)s/groups/%(group_id)s/roles/%(role_id)s' %
            {'project_id': self.project_id,
             'group_id': group['id'],
             'role_id': self.role_id}
        )
        self.put(member_url)

        # Make sure we only get one role assignment back since the system role
        # assignment shouldn't be returned.
        path = (
            '/role_assignments?role.id=%(role_id)s&group.id=%(group_id)s'
        ) % {'role_id': self.role_id, 'group_id': group['id']}
        response = self.get(path)
        self.assertValidRoleAssignmentListResponse(response, expected_length=1)