1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
|
/**
* ============LICENSE_START====================================================
* org.onap.aaf
* ===========================================================================
* Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
* ===========================================================================
* 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.
* ============LICENSE_END====================================================
*
*/
package org.onap.aaf.auth.service;
import static org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE.force;
import static org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE.future;
import static org.onap.aaf.auth.layer.Result.OK;
import static org.onap.aaf.auth.rserv.HttpMethods.DELETE;
import static org.onap.aaf.auth.rserv.HttpMethods.GET;
import static org.onap.aaf.auth.rserv.HttpMethods.POST;
import static org.onap.aaf.auth.rserv.HttpMethods.PUT;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.onap.aaf.auth.common.Define;
import org.onap.aaf.auth.dao.DAOException;
import org.onap.aaf.auth.dao.cass.ApprovalDAO;
import org.onap.aaf.auth.dao.cass.CertDAO;
import org.onap.aaf.auth.dao.cass.CredDAO;
import org.onap.aaf.auth.dao.cass.DelegateDAO;
import org.onap.aaf.auth.dao.cass.FutureDAO;
import org.onap.aaf.auth.dao.cass.HistoryDAO;
import org.onap.aaf.auth.dao.cass.Namespace;
import org.onap.aaf.auth.dao.cass.NsDAO;
import org.onap.aaf.auth.dao.cass.NsDAO.Data;
import org.onap.aaf.auth.dao.cass.NsSplit;
import org.onap.aaf.auth.dao.cass.NsType;
import org.onap.aaf.auth.dao.cass.PermDAO;
import org.onap.aaf.auth.dao.cass.RoleDAO;
import org.onap.aaf.auth.dao.cass.Status;
import org.onap.aaf.auth.dao.cass.UserRoleDAO;
import org.onap.aaf.auth.dao.hl.CassExecutor;
import org.onap.aaf.auth.dao.hl.Function;
import org.onap.aaf.auth.dao.hl.Function.FUTURE_OP;
import org.onap.aaf.auth.dao.hl.Function.Lookup;
import org.onap.aaf.auth.dao.hl.Function.OP_STATUS;
import org.onap.aaf.auth.dao.hl.Question;
import org.onap.aaf.auth.dao.hl.Question.Access;
import org.onap.aaf.auth.env.AuthzTrans;
import org.onap.aaf.auth.layer.Result;
import org.onap.aaf.auth.org.Executor;
import org.onap.aaf.auth.org.Organization;
import org.onap.aaf.auth.org.Organization.Expiration;
import org.onap.aaf.auth.org.Organization.Identity;
import org.onap.aaf.auth.org.Organization.Policy;
import org.onap.aaf.auth.org.OrganizationException;
import org.onap.aaf.auth.rserv.doc.ApiDoc;
import org.onap.aaf.auth.service.mapper.Mapper;
import org.onap.aaf.auth.service.mapper.Mapper.API;
import org.onap.aaf.auth.service.validation.ServiceValidator;
import org.onap.aaf.auth.validation.Validator;
import org.onap.aaf.cadi.principal.BasicPrincipal;
import org.onap.aaf.misc.env.Env;
import org.onap.aaf.misc.env.TimeTaken;
import org.onap.aaf.misc.env.util.Chrono;
import org.onap.aaf.misc.env.util.Split;
import aaf.v2_0.CredRequest;
/**
* AuthzCassServiceImpl implements AuthzCassService for
*
* @author Jonathan
*
* @param <NSS>
* @param <PERMS>
* @param <PERMKEY>
* @param <ROLES>
* @param <USERS>
* @param <DELGS>
* @param <REQUEST>
* @param <HISTORY>
* @param <ERR>
* @param <APPROVALS>
*/
public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS>
implements AuthzService <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> {
private Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper;
@Override
public Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper() {return mapper;}
private static final String ASTERIX = "*";
private static final String CACHE = "cache";
private static final String ROOT_NS = Define.ROOT_NS();
private static final String ROOT_COMPANY = Define.ROOT_COMPANY();
private final Question ques;
private final Function func;
public AuthzCassServiceImpl(AuthzTrans trans, Mapper<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper,Question question) {
this.ques = question;
func = new Function(trans, question);
this.mapper = mapper;
}
/***********************************
* NAMESPACE
***********************************/
/**
* createNS
* @throws DAOException
* @see org.onap.aaf.auth.service.AuthzService#createNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String)
*/
@ApiDoc(
method = POST,
path = "/authz/ns",
params = {},
expectedCode = 201,
errorCodes = { 403,404,406,409 },
text = { "Namespace consists of: ",
"<ul><li>name - What you want to call this Namespace</li>",
"<li>responsible(s) - Person(s) who receive Notifications and approves Requests ",
"regarding this Namespace. Companies have Policies as to who may take on ",
"this Responsibility. Separate multiple identities with commas</li>",
"<li>admin(s) - Person(s) who are allowed to make changes on the namespace, ",
"including creating Roles, Permissions and Credentials. Separate multiple ",
"identities with commas</li></ul>",
"Note: Namespaces are dot-delimited (i.e. com.myCompany.myApp) and must be ",
"created with parent credentials (i.e. To create com.myCompany.myApp, you must ",
"be an admin of com.myCompany or com"
}
)
@Override
public Result<Void> createNS(final AuthzTrans trans, REQUEST from, NsType type) {
final Result<Namespace> rnamespace = mapper.ns(trans, from);
final ServiceValidator v = new ServiceValidator();
if(v.ns(rnamespace).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
final Namespace namespace = rnamespace.value;
final Result<NsDAO.Data> parentNs = ques.deriveNs(trans,namespace.name);
if(parentNs.notOK()) {
return Result.err(parentNs);
}
if(namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed
return func.createNS(trans, namespace, false);
}
Result<FutureDAO.Data> fd = mapper.future(trans, NsDAO.TABLE,from,namespace,true,
new Mapper.Memo() {
@Override
public String get() {
return "Create Namespace [" + namespace.name + ']';
}
},
new MayChange() {
private Result<NsDAO.Data> rnd;
@Override
public Result<?> mayChange() {
if(rnd==null) {
rnd = ques.mayUser(trans, trans.user(), parentNs.value,Access.write);
}
return rnd;
}
});
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, FUTURE_OP.C);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "NS [%s] is saved for future processing",namespace.name);
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
return func.createNS(trans, namespace, false);
default:
return Result.err(fd);
}
}
@ApiDoc(
method = POST,
path = "/authz/ns/:ns/admin/:id",
params = { "ns|string|true",
"id|string|true"
},
expectedCode = 201,
errorCodes = { 403,404,406,409 },
text = { "Add an Identity :id to the list of Admins for the Namespace :ns",
"Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" }
)
@Override
public Result<Void> addAdminNS(AuthzTrans trans, String ns, String id) {
return func.addUserRole(trans, id, ns,Question.ADMIN);
}
@ApiDoc(
method = DELETE,
path = "/authz/ns/:ns/admin/:id",
params = { "ns|string|true",
"id|string|true"
},
expectedCode = 200,
errorCodes = { 403,404 },
text = { "Remove an Identity :id from the list of Admins for the Namespace :ns",
"Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" }
)
@Override
public Result<Void> delAdminNS(AuthzTrans trans, String ns, String id) {
return func.delAdmin(trans,ns,id);
}
@ApiDoc(
method = POST,
path = "/authz/ns/:ns/responsible/:id",
params = { "ns|string|true",
"id|string|true"
},
expectedCode = 201,
errorCodes = { 403,404,406,409 },
text = { "Add an Identity :id to the list of Responsibles for the Namespace :ns",
"Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" }
)
@Override
public Result<Void> addResponsibleNS(AuthzTrans trans, String ns, String id) {
return func.addUserRole(trans,id,ns,Question.OWNER);
}
@ApiDoc(
method = DELETE,
path = "/authz/ns/:ns/responsible/:id",
params = { "ns|string|true",
"id|string|true"
},
expectedCode = 200,
errorCodes = { 403,404 },
text = { "Remove an Identity :id to the list of Responsibles for the Namespace :ns",
"Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)",
"Note: A namespace must have at least 1 responsible party"
}
)
@Override
public Result<Void> delResponsibleNS(AuthzTrans trans, String ns, String id) {
return func.delOwner(trans,ns,id);
}
/* (non-Javadoc)
* @see org.onap.aaf.auth.service.AuthzService#applyModel(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object)
*/
@ApiDoc(
method = POST,
path = "/authz/ns/:ns/attrib/:key/:value",
params = { "ns|string|true",
"key|string|true",
"value|string|true"},
expectedCode = 201,
errorCodes = { 403,404,406,409 },
text = {
"Create an attribute in the Namespace",
"You must be given direct permission for key by AAF"
}
)
@Override
public Result<Void> createNsAttrib(AuthzTrans trans, String ns, String key, String value) {
TimeTaken tt = trans.start("Create NsAttrib " + ns + ':' + key + ':' + value, Env.SUB);
try {
// Check inputs
final Validator v = new ServiceValidator();
if(v.ns(ns).err() ||
v.key(key).err() ||
v.value(value).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// Check if exists already
Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
if(rlnsd.notOKorIsEmpty()) {
return Result.err(rlnsd);
}
NsDAO.Data nsd = rlnsd.value.get(0);
// Check for Existence
if(nsd.attrib.get(key)!=null) {
return Result.err(Status.ERR_ConflictAlreadyExists, "NS Property %s:%s exists", ns, key);
}
// Check if User may put
if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB,
":"+trans.org().getDomain()+".*:"+key, Access.write.name())) {
return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key);
}
// Add Attrib
nsd.attrib.put(key, value);
ques.nsDAO.dao().attribAdd(trans,ns,key,value);
return Result.ok();
} finally {
tt.done();
}
}
@ApiDoc(
method = GET,
path = "/authz/ns/attrib/:key",
params = { "key|string|true" },
expectedCode = 200,
errorCodes = { 403,404 },
text = {
"Read Attributes for Namespace"
}
)
@Override
public Result<KEYS> readNsByAttrib(AuthzTrans trans, String key) {
// Check inputs
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Key",key).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// May Read
if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB,
":"+trans.org().getDomain()+".*:"+key, Question.READ)) {
return Result.err(Status.ERR_Denied,"%s may not read NS by Attrib '%s'",trans.user(),key);
}
Result<Set<String>> rsd = ques.nsDAO.dao().readNsByAttrib(trans, key);
if(rsd.notOK()) {
return Result.err(rsd);
}
return mapper().keys(rsd.value);
}
@ApiDoc(
method = PUT,
path = "/authz/ns/:ns/attrib/:key/:value",
params = { "ns|string|true",
"key|string|true"},
expectedCode = 200,
errorCodes = { 403,404 },
text = {
"Update Value on an existing attribute in the Namespace",
"You must be given direct permission for key by AAF"
}
)
@Override
public Result<?> updateNsAttrib(AuthzTrans trans, String ns, String key, String value) {
TimeTaken tt = trans.start("Update NsAttrib " + ns + ':' + key + ':' + value, Env.SUB);
try {
// Check inputs
final Validator v = new ServiceValidator();
if(v.ns(ns).err() ||
v.key(key).err() ||
v.value(value).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// Check if exists already (NS must exist)
Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
if(rlnsd.notOKorIsEmpty()) {
return Result.err(rlnsd);
}
NsDAO.Data nsd = rlnsd.value.get(0);
// Check for Existence
if(nsd.attrib.get(key)==null) {
return Result.err(Status.ERR_NotFound, "NS Property %s:%s exists", ns, key);
}
// Check if User may put
if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB,
":"+trans.org().getDomain()+".*:"+key, Access.write.name())) {
return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key);
}
// Add Attrib
nsd.attrib.put(key, value);
return ques.nsDAO.update(trans,nsd);
} finally {
tt.done();
}
}
@ApiDoc(
method = DELETE,
path = "/authz/ns/:ns/attrib/:key",
params = { "ns|string|true",
"key|string|true"},
expectedCode = 200,
errorCodes = { 403,404 },
text = {
"Delete an attribute in the Namespace",
"You must be given direct permission for key by AAF"
}
)
@Override
public Result<Void> deleteNsAttrib(AuthzTrans trans, String ns, String key) {
TimeTaken tt = trans.start("Delete NsAttrib " + ns + ':' + key, Env.SUB);
try {
// Check inputs
final Validator v = new ServiceValidator();
if(v.nullOrBlank("NS",ns).err() ||
v.nullOrBlank("Key",key).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// Check if exists already
Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
if(rlnsd.notOKorIsEmpty()) {
return Result.err(rlnsd);
}
NsDAO.Data nsd = rlnsd.value.get(0);
// Check for Existence
if(nsd.attrib.get(key)==null) {
return Result.err(Status.ERR_NotFound, "NS Property [%s:%s] does not exist", ns, key);
}
// Check if User may del
if(!ques.isGranted(trans, trans.user(), ROOT_NS, "attrib", ":" + ROOT_COMPANY + ".*:"+key, Access.write.name())) {
return Result.err(Status.ERR_Denied, "%s may not delete NS Attrib [%s:%s]", trans.user(),ns, key);
}
// Add Attrib
nsd.attrib.remove(key);
ques.nsDAO.dao().attribRemove(trans,ns,key);
return Result.ok();
} finally {
tt.done();
}
}
@ApiDoc(
method = GET,
path = "/authz/nss/:id",
params = { "id|string|true" },
expectedCode = 200,
errorCodes = { 404,406 },
text = {
"Lists the Admin(s), Responsible Party(s), Role(s), Permission(s)",
"Credential(s) and Expiration of Credential(s) in Namespace :id",
}
)
@Override
public Result<NSS> getNSbyName(AuthzTrans trans, String ns) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("NS", ns).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, ns);
if(rlnd.isOK()) {
if(rlnd.isEmpty()) {
return Result.err(Status.ERR_NotFound, "No data found for %s",ns);
}
Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
Namespace namespace = new Namespace(rnd.value);
Result<List<String>> rd = func.getOwners(trans, namespace.name, false);
if(rd.isOK()) {
namespace.owner = rd.value;
}
rd = func.getAdmins(trans, namespace.name, false);
if(rd.isOK()) {
namespace.admin = rd.value;
}
NSS nss = mapper.newInstance(API.NSS);
return mapper.nss(trans, namespace, nss);
} else {
return Result.err(rlnd);
}
}
@ApiDoc(
method = GET,
path = "/authz/nss/admin/:id",
params = { "id|string|true" },
expectedCode = 200,
errorCodes = { 403,404 },
text = { "Lists all Namespaces where Identity :id is an Admin",
"Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)"
}
)
@Override
public Result<NSS> getNSbyAdmin(AuthzTrans trans, String user, boolean full) {
final Validator v = new ServiceValidator();
if (v.nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData, v.errs());
}
Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".admin", full);
if(rn.notOK()) {
return Result.err(rn);
}
if (rn.isEmpty()) {
return Result.err(Status.ERR_NotFound, "[%s] is not an admin for any namespaces",user);
}
NSS nss = mapper.newInstance(API.NSS);
// Note: "loadNamespace" already validates view of Namespace
return mapper.nss(trans, rn.value, nss);
}
@ApiDoc(
method = GET,
path = "/authz/nss/either/:id",
params = { "id|string|true" },
expectedCode = 200,
errorCodes = { 403,404 },
text = { "Lists all Namespaces where Identity :id is either an Admin or an Owner",
"Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)"
}
)
@Override
public Result<NSS> getNSbyEither(AuthzTrans trans, String user, boolean full) {
final Validator v = new ServiceValidator();
if (v.nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData, v.errs());
}
Result<Collection<Namespace>> rn = loadNamepace(trans, user, null, full);
if(rn.notOK()) {
return Result.err(rn);
}
if (rn.isEmpty()) {
return Result.err(Status.ERR_NotFound, "[%s] is not an admin or owner for any namespaces",user);
}
NSS nss = mapper.newInstance(API.NSS);
// Note: "loadNamespace" already validates view of Namespace
return mapper.nss(trans, rn.value, nss);
}
private Result<Collection<Namespace>> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) {
Result<List<UserRoleDAO.Data>> urd = ques.userRoleDAO.readByUser(trans, user);
if(urd.notOKorIsEmpty()) {
return Result.err(urd);
}
Map<String, Namespace> lm = new HashMap<String,Namespace>();
Map<String, Namespace> other = full || endsWith==null?null:new TreeMap<String,Namespace>();
for(UserRoleDAO.Data urdd : urd.value) {
if(full) {
if(endsWith==null || urdd.role.endsWith(endsWith)) {
RoleDAO.Data rd = RoleDAO.Data.decode(urdd);
Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read);
if(nsd.isOK()) {
Namespace namespace = lm.get(nsd.value.name);
if(namespace==null) {
namespace = new Namespace(nsd.value);
lm.put(namespace.name,namespace);
}
Result<List<String>> rls = func.getAdmins(trans, namespace.name, false);
if(rls.isOK()) {
namespace.admin=rls.value;
}
rls = func.getOwners(trans, namespace.name, false);
if(rls.isOK()) {
namespace.owner=rls.value;
}
}
}
} else { // Shortened version. Only Namespace Info available from Role.
if(Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) {
RoleDAO.Data rd = RoleDAO.Data.decode(urdd);
Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read);
if(nsd.isOK()) {
Namespace namespace = lm.get(nsd.value.name);
if(namespace==null) {
if(other!=null) {
namespace = other.remove(nsd.value.name);
}
if(namespace==null) {
namespace = new Namespace(nsd.value);
namespace.admin=new ArrayList<String>();
namespace.owner=new ArrayList<String>();
}
if(endsWith==null || urdd.role.endsWith(endsWith)) {
lm.put(namespace.name,namespace);
} else {
other.put(namespace.name,namespace);
}
}
if(Question.OWNER.equals(urdd.rname)) {
namespace.owner.add(urdd.user);
} else {
namespace.admin.add(urdd.user);
}
}
}
}
}
return Result.ok(lm.values());
}
@ApiDoc(
method = GET,
path = "/authz/nss/responsible/:id",
params = { "id|string|true" },
expectedCode = 200,
errorCodes = { 403,404 },
text = { "Lists all Namespaces where Identity :id is a Responsible Party",
"Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)"
}
)
@Override
public Result<NSS> getNSbyResponsible(AuthzTrans trans, String user, boolean full) {
final Validator v = new ServiceValidator();
if (v.nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData, v.errs());
}
Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".owner",full);
if(rn.notOK()) {
return Result.err(rn);
}
if (rn.isEmpty()) {
return Result.err(Status.ERR_NotFound, "[%s] is not an owner for any namespaces",user);
}
NSS nss = mapper.newInstance(API.NSS);
// Note: "loadNamespace" prevalidates
return mapper.nss(trans, rn.value, nss);
}
@ApiDoc(
method = GET,
path = "/authz/nss/children/:id",
params = { "id|string|true" },
expectedCode = 200,
errorCodes = { 403,404 },
text = { "Lists all Child Namespaces of Namespace :id",
"Note: This is not a cached read"
}
)
@Override
public Result<NSS> getNSsChildren(AuthzTrans trans, String parent) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("NS", parent).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<NsDAO.Data> rnd = ques.deriveNs(trans, parent);
if(rnd.notOK()) {
return Result.err(rnd);
}
rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
Set<Namespace> lm = new HashSet<Namespace>();
Result<List<NsDAO.Data>> rlnd = ques.nsDAO.dao().getChildren(trans, parent);
if(rlnd.isOK()) {
if(rlnd.isEmpty()) {
return Result.err(Status.ERR_NotFound, "No data found for %s",parent);
}
for(NsDAO.Data ndd : rlnd.value) {
Namespace namespace = new Namespace(ndd);
Result<List<String>> rls = func.getAdmins(trans, namespace.name, false);
if(rls.isOK()) {
namespace.admin=rls.value;
}
rls = func.getOwners(trans, namespace.name, false);
if(rls.isOK()) {
namespace.owner=rls.value;
}
lm.add(namespace);
}
NSS nss = mapper.newInstance(API.NSS);
return mapper.nss(trans,lm, nss);
} else {
return Result.err(rlnd);
}
}
@ApiDoc(
method = PUT,
path = "/authz/ns",
params = {},
expectedCode = 200,
errorCodes = { 403,404,406 },
text = { "Replace the Current Description of a Namespace with a new one"
}
)
@Override
public Result<Void> updateNsDescription(AuthzTrans trans, REQUEST from) {
final Result<Namespace> nsd = mapper.ns(trans, from);
final ServiceValidator v = new ServiceValidator();
if(v.ns(nsd).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
if(v.nullOrBlank("description", nsd.value.description).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Namespace namespace = nsd.value;
Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, namespace.name);
if(rlnd.notOKorIsEmpty()) {
return Result.err(Status.ERR_NotFound, "Namespace [%s] does not exist",namespace.name);
}
if (ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.write).notOK()) {
return Result.err(Status.ERR_Denied, "You do not have approval to change %s",namespace.name);
}
Result<Void> rdr = ques.nsDAO.dao().addDescription(trans, namespace.name, namespace.description);
if(rdr.isOK()) {
return Result.ok();
} else {
return Result.err(rdr);
}
}
/**
* deleteNS
* @throws DAOException
* @see org.onap.aaf.auth.service.AuthzService#deleteNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String)
*/
@ApiDoc(
method = DELETE,
path = "/authz/ns/:ns",
params = { "ns|string|true" },
expectedCode = 200,
errorCodes = { 403,404,424 },
text = { "Delete the Namespace :ns. Namespaces cannot normally be deleted when there ",
"are still credentials associated with them, but they can be deleted by setting ",
"the \"force\" property. To do this: Add 'force=true' as a query parameter",
"<p>WARNING: Using force will delete all credentials attached to this namespace. Use with care.</p>"
+ "if the \"force\" property is set to 'force=move', then Permissions and Roles are not deleted,"
+ "but are retained, and assigned to the Parent Namespace. 'force=move' is not permitted "
+ "at or below Application Scope"
}
)
@Override
public Result<Void> deleteNS(AuthzTrans trans, String ns) {
return func.deleteNS(trans, ns);
}
/***********************************
* PERM
***********************************/
/*
* (non-Javadoc)
* @see org.onap.aaf.auth.service.AuthzService#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object, boolean, java.lang.String, java.lang.String, java.lang.String, java.util.List, java.util.List)
*/
@ApiDoc(
method = POST,
path = "/authz/perm",
params = {},
expectedCode = 201,
errorCodes = {403,404,406,409},
text = { "Permission consists of:",
"<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
+ "is being protected</li>",
"<li>instance - a key, possibly multi-dimensional, that identifies a specific "
+ " instance of the type</li>",
"<li>action - what kind of action is allowed</li></ul>",
"Note: instance and action can be an *"
}
)
@Override
public Result<Void> createPerm(final AuthzTrans trans,REQUEST rreq) {
final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq);
final ServiceValidator v = new ServiceValidator();
if(v.perm(newPd).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false,
new Mapper.Memo() {
@Override
public String get() {
return "Create Permission [" +
newPd.value.fullType() + '|' +
newPd.value.instance + '|' +
newPd.value.action + ']';
}
},
new MayChange() {
private Result<NsDAO.Data> nsd;
@Override
public Result<?> mayChange() {
if(nsd==null) {
nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write);
}
return nsd;
}
});
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, newPd.value.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans,fd.value,
newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action,
trans.user(),
nsr.value.get(0),
FUTURE_OP.C);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
newPd.value.ns,
newPd.value.type,
newPd.value.instance,
newPd.value.action);
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
return func.createPerm(trans, newPd.value, true);
default:
return Result.err(fd);
}
}
@ApiDoc(
method = GET,
path = "/authz/perms/:type",
params = {"type|string|true"},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "List All Permissions that match the :type element of the key" }
)
@Override
public Result<PERMS> getPermsByType(AuthzTrans trans, final String permType) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("PermType", permType).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<PermDAO.Data>> rlpd = ques.getPermsByType(trans, permType);
if(rlpd.notOK()) {
return Result.err(rlpd);
}
// We don't have instance & action for mayUserView... do we want to loop through all returned here as well as in mapper?
// Result<NsDAO.Data> r;
// if((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r);
PERMS perms = mapper.newInstance(API.PERMS);
if(!rlpd.isEmpty()) {
// Note: Mapper will restrict what can be viewed
return mapper.perms(trans, rlpd.value, perms, true);
}
return Result.ok(perms);
}
@ApiDoc(
method = GET,
path = "/authz/perms/:type/:instance/:action",
params = {"type|string|true",
"instance|string|true",
"action|string|true"},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "List Permissions that match key; :type, :instance and :action" }
)
@Override
public Result<PERMS> getPermsByName(AuthzTrans trans, String type, String instance, String action) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("PermType", type).err()
|| v.nullOrBlank("PermInstance", instance).err()
|| v.nullOrBlank("PermAction", action).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<PermDAO.Data>> rlpd = ques.getPermsByName(trans, type, instance, action);
if(rlpd.notOK()) {
return Result.err(rlpd);
}
PERMS perms = mapper.newInstance(API.PERMS);
if(!rlpd.isEmpty()) {
// Note: Mapper will restrict what can be viewed
return mapper.perms(trans, rlpd.value, perms, true);
}
return Result.ok(perms);
}
@ApiDoc(
method = GET,
path = "/authz/perms/user/:user",
params = {"user|string|true"},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "List All Permissions that match user :user",
"<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>"}
)
@Override
public Result<PERMS> getPermsByUser(AuthzTrans trans, String user) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,
trans.requested(force));
if(rlpd.notOK()) {
return Result.err(rlpd);
}
PERMS perms = mapper.newInstance(API.PERMS);
if(rlpd.isEmpty()) {
return Result.ok(perms);
}
// Note: Mapper will restrict what can be viewed
// if user is the same as that which is looked up, no filtering is required
return mapper.perms(trans, rlpd.value,
perms,
!user.equals(trans.user()));
}
@ApiDoc(
method = GET,
path = "/authz/perms/user/:user/scope/:scope",
params = {"user|string|true","scope|string|true"},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "List All Permissions that match user :user, filtered by NS (Scope)",
"<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>",
"<p>'scope' must be expressed as NSs separated by ':'</p>"
}
)
@Override
public Result<PERMS> getPermsByUserScope(AuthzTrans trans, String user, String[] scopes) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user, trans.requested(force));
if(rlpd.notOK()) {
return Result.err(rlpd);
}
PERMS perms = mapper.newInstance(API.PERMS);
if(rlpd.isEmpty()) {
return Result.ok(perms);
}
// Note: Mapper will restrict what can be viewed
// if user is the same as that which is looked up, no filtering is required
return mapper.perms(trans, rlpd.value,
perms,
scopes,
!user.equals(trans.user()));
}
@ApiDoc(
method = POST,
path = "/authz/perms/user/:user",
params = {"user|string|true"},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "List All Permissions that match user :user",
"<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>",
"",
"Present Queries as one or more Permissions (see ContentType Links below for format).",
"",
"If the Caller is Granted this specific Permission, and the Permission is valid",
" for the User, it will be included in response Permissions, along with",
" all the normal permissions on the 'GET' version of this call. If it is not",
" valid, or Caller does not have permission to see, it will be removed from the list",
"",
" *Note: This design allows you to make one call for all expected permissions",
" The permission to be included MUST be:",
" <user namespace>.access|:<ns|role|perm>[:key]|<create|read|write>",
" examples:",
" com.att.myns.access|:ns|write",
" com.att.myns.access|:role:myrole|create",
" com.att.myns.access|:perm:mytype:myinstance:myaction|read",
""
}
)
@Override
public Result<PERMS> getPermsByUser(AuthzTrans trans, PERMS _perms, String user) {
PERMS perms = _perms;
final Validator v = new ServiceValidator();
if(v.nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
//////////////
Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,trans.requested(force));
if(rlpd.notOK()) {
return Result.err(rlpd);
}
/*//TODO
1) See if allowed to query
2) See if User is allowed
*/
Result<List<PermDAO.Data>> in = mapper.perms(trans, perms);
if(in.isOKhasData()) {
List<PermDAO.Data> out = rlpd.value;
boolean ok;
for(PermDAO.Data pdd : in.value) {
ok = false;
if("access".equals(pdd.type)) {
Access access = Access.valueOf(pdd.action);
String[] mdkey = Split.splitTrim(':',pdd.instance);
if(mdkey.length>1) {
String type = mdkey[1];
if("role".equals(type)) {
if(mdkey.length>2) {
RoleDAO.Data rdd = new RoleDAO.Data();
rdd.ns=pdd.ns;
rdd.name=mdkey[2];
ok = ques.mayUser(trans, trans.user(), rdd, Access.read).isOK() && ques.mayUser(trans, user, rdd , access).isOK();
}
} else if("perm".equals(type)) {
if(mdkey.length>4) { // also need instance/action
PermDAO.Data p = new PermDAO.Data();
p.ns=pdd.ns;
p.type=mdkey[2];
p.instance=mdkey[3];
p.action=mdkey[4];
ok = ques.mayUser(trans, trans.user(), p, Access.read).isOK() && ques.mayUser(trans, user, p , access).isOK();
}
} else if("ns".equals(type)) {
NsDAO.Data ndd = new NsDAO.Data();
ndd.name=pdd.ns;
ok = ques.mayUser(trans, trans.user(), ndd, Access.read).isOK() && ques.mayUser(trans, user, ndd , access).isOK();
}
}
}
if(ok) {
out.add(pdd);
}
}
}
perms = mapper.newInstance(API.PERMS);
if(rlpd.isEmpty()) {
return Result.ok(perms);
}
// Note: Mapper will restrict what can be viewed
// if user is the same as that which is looked up, no filtering is required
return mapper.perms(trans, rlpd.value,
perms,
!user.equals(trans.user()));
}
@ApiDoc(
method = GET,
path = "/authz/perms/role/:role",
params = {"role|string|true"},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "List All Permissions that are granted to :role" }
)
@Override
public Result<PERMS> getPermsByRole(AuthzTrans trans,String role) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Role", role).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques,role);
if(rrdd.notOK()) {
return Result.err(rrdd);
}
Result<NsDAO.Data> r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read);
if(r.notOK()) {
return Result.err(r);
}
PERMS perms = mapper.newInstance(API.PERMS);
Result<List<PermDAO.Data>> rlpd = ques.getPermsByRole(trans, role, trans.requested(force));
if(rlpd.isOKhasData()) {
// Note: Mapper will restrict what can be viewed
return mapper.perms(trans, rlpd.value, perms, true);
}
return Result.ok(perms);
}
@ApiDoc(
method = GET,
path = "/authz/perms/ns/:ns",
params = {"ns|string|true"},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "List All Permissions that are in Namespace :ns" }
)
@Override
public Result<PERMS> getPermsByNS(AuthzTrans trans,String ns) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("NS", ns).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<NsDAO.Data> rnd = ques.deriveNs(trans, ns);
if(rnd.notOK()) {
return Result.err(rnd);
}
rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
Result<List<PermDAO.Data>> rlpd = ques.permDAO.readNS(trans, ns);
if(rlpd.notOK()) {
return Result.err(rlpd);
}
PERMS perms = mapper.newInstance(API.PERMS);
if(!rlpd.isEmpty()) {
// Note: Mapper will restrict what can be viewed
return mapper.perms(trans, rlpd.value,perms, true);
}
return Result.ok(perms);
}
@ApiDoc(
method = PUT,
path = "/authz/perm/:type/:instance/:action",
params = {"type|string|true",
"instance|string|true",
"action|string|true"},
expectedCode = 200,
errorCodes = { 404,406, 409 },
text = { "Rename the Permission referenced by :type :instance :action, and "
+ "rename (copy/delete) to the Permission described in PermRequest" }
)
@Override
public Result<Void> renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) {
final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq);
final ServiceValidator v = new ServiceValidator();
if(v.perm(newPd).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
if (ques.mayUser(trans, trans.user(), newPd.value,Access.write).notOK()) {
return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]",
newPd.value.ns,newPd.value.type,newPd.value.instance,newPd.value.action);
}
Result<NsSplit> nss = ques.deriveNsSplit(trans, origType);
Result<List<PermDAO.Data>> origRlpd = ques.permDAO.read(trans, nss.value.ns, nss.value.name, origInstance, origAction);
if(origRlpd.notOKorIsEmpty()) {
return Result.err(Status.ERR_PermissionNotFound,
"Permission [%s|%s|%s] does not exist",
origType,origInstance,origAction);
}
PermDAO.Data origPd = origRlpd.value.get(0);
if (!origPd.ns.equals(newPd.value.ns)) {
return Result.err(Status.ERR_Denied, "Cannot change namespace with rename command. " +
"<new type> must start with [" + origPd.ns + "]");
}
if ( origPd.type.equals(newPd.value.type) &&
origPd.action.equals(newPd.value.action) &&
origPd.instance.equals(newPd.value.instance) ) {
return Result.err(Status.ERR_ConflictAlreadyExists, "New Permission must be different than original permission");
}
Set<String> origRoles = origPd.roles(false);
if (!origRoles.isEmpty()) {
Set<String> roles = newPd.value.roles(true);
for (String role : origPd.roles) {
roles.add(role);
}
}
newPd.value.description = origPd.description;
Result<Void> rv = null;
rv = func.createPerm(trans, newPd.value, false);
if (rv.isOK()) {
rv = func.deletePerm(trans, origPd, true, false);
}
return rv;
}
@ApiDoc(
method = PUT,
path = "/authz/perm",
params = {},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "Add Description Data to Perm" }
)
@Override
public Result<Void> updatePermDescription(AuthzTrans trans, REQUEST from) {
final Result<PermDAO.Data> pd = mapper.perm(trans, from);
final ServiceValidator v = new ServiceValidator();
if(v.perm(pd).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
if(v.nullOrBlank("description", pd.value.description).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
final PermDAO.Data perm = pd.value;
if(ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) {
return Result.err(Status.ERR_NotFound, "Permission [%s.%s|%s|%s] does not exist",
perm.ns,perm.type,perm.instance,perm.action);
}
if (ques.mayUser(trans, trans.user(), perm, Access.write).notOK()) {
return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]",
perm.ns,perm.type,perm.instance,perm.action);
}
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pd.value.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
Result<Void> rdr = ques.permDAO.addDescription(trans, perm.ns, perm.type, perm.instance,
perm.action, perm.description);
if(rdr.isOK()) {
return Result.ok();
} else {
return Result.err(rdr);
}
}
@ApiDoc(
method = PUT,
path = "/authz/role/perm",
params = {},
expectedCode = 201,
errorCodes = {403,404,406,409},
text = { "Set a permission's roles to roles given" }
)
@Override
public Result<Void> resetPermRoles(final AuthzTrans trans, REQUEST rreq) {
final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq);
if(updt.notOKorIsEmpty()) {
return Result.err(updt);
}
final ServiceValidator v = new ServiceValidator();
if(v.perm(updt).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write);
if (nsd.notOK()) {
return Result.err(nsd);
}
// Read full set to get CURRENT values
Result<List<PermDAO.Data>> rcurr = ques.permDAO.read(trans,
updt.value.ns,
updt.value.type,
updt.value.instance,
updt.value.action);
if(rcurr.notOKorIsEmpty()) {
return Result.err(Status.ERR_PermissionNotFound,
"Permission [%s.%s|%s|%s] does not exist",
updt.value.ns,updt.value.type,updt.value.instance,updt.value.action);
}
// Create a set of Update Roles, which are in Internal Format
Set<String> updtRoles = new HashSet<String>();
Result<NsSplit> nss;
for(String role : updt.value.roles(false)) {
nss = ques.deriveNsSplit(trans, role);
if(nss.isOK()) {
updtRoles.add(nss.value.ns + '|' + nss.value.name);
} else {
trans.error().log(nss.errorString());
}
}
Result<Void> rv = null;
for(PermDAO.Data curr : rcurr.value) {
Set<String> currRoles = curr.roles(false);
// must add roles to this perm, and add this perm to each role
// in the update, but not in the current
for (String role : updtRoles) {
if (!currRoles.contains(role)) {
Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role);
if(key.isOKhasData()) {
Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, key.value);
if(rrd.isOKhasData()) {
for(RoleDAO.Data r : rrd.value) {
rv = func.addPermToRole(trans, r, curr, false);
if (rv.notOK() && rv.status!=Result.ERR_ConflictAlreadyExists) {
return Result.err(rv);
}
}
} else {
return Result.err(rrd);
}
}
}
}
// similarly, must delete roles from this perm, and delete this perm from each role
// in the update, but not in the current
for (String role : currRoles) {
if (!updtRoles.contains(role)) {
Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role);
if(key.isOKhasData()) {
Result<List<RoleDAO.Data>> rdd = ques.roleDAO.read(trans, key.value);
if(rdd.isOKhasData()) {
for(RoleDAO.Data r : rdd.value) {
rv = func.delPermFromRole(trans, r, curr, true);
if (rv.notOK() && rv.status!=Status.ERR_PermissionNotFound) {
return Result.err(rv);
}
}
}
}
}
}
}
return rv==null?Result.ok():rv;
}
@ApiDoc(
method = DELETE,
path = "/authz/perm",
params = {},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "Delete the Permission referenced by PermKey.",
"You cannot normally delete a permission which is still granted to roles,",
"however the \"force\" property allows you to do just that. To do this: Add",
"'force=true' as a query parameter.",
"<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>" }
)
@Override
public Result<Void> deletePerm(final AuthzTrans trans, REQUEST from) {
Result<PermDAO.Data> pd = mapper.perm(trans, from);
if(pd.notOK()) {
return Result.err(pd);
}
final ServiceValidator v = new ServiceValidator();
if(v.nullOrBlank(pd.value).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
final PermDAO.Data perm = pd.value;
if (ques.permDAO.read(trans, perm).notOKorIsEmpty()) {
return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist",
perm.ns,perm.type,perm.instance,perm.action );
}
Result<FutureDAO.Data> fd = mapper.future(trans,PermDAO.TABLE,from,perm,false,
new Mapper.Memo() {
@Override
public String get() {
return "Delete Permission [" + perm.fullPerm() + ']';
}
},
new MayChange() {
private Result<NsDAO.Data> nsd;
@Override
public Result<?> mayChange() {
if(nsd==null) {
nsd = ques.mayUser(trans, trans.user(), perm, Access.write);
}
return nsd;
}
});
switch(fd.status) {
case OK:
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, perm.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
Result<String> rfc = func.createFuture(trans, fd.value,
perm.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Perm Deletion [%s] is saved for future processing",perm.encode());
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
return func.deletePerm(trans,perm,trans.requested(force), false);
default:
return Result.err(fd);
}
}
@ApiDoc(
method = DELETE,
path = "/authz/perm/:name/:type/:action",
params = {"type|string|true",
"instance|string|true",
"action|string|true"},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "Delete the Permission referenced by :type :instance :action",
"You cannot normally delete a permission which is still granted to roles,",
"however the \"force\" property allows you to do just that. To do this: Add",
"'force=true' as a query parameter",
"<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>"}
)
@Override
public Result<Void> deletePerm(AuthzTrans trans, String type, String instance, String action) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Type",type)
.nullOrBlank("Instance",instance)
.nullOrBlank("Action",action)
.err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<PermDAO.Data> pd = ques.permFrom(trans, type, instance, action);
if(pd.isOK()) {
return func.deletePerm(trans, pd.value, trans.requested(force), false);
} else {
return Result.err(pd);
}
}
/***********************************
* ROLE
***********************************/
@ApiDoc(
method = POST,
path = "/authz/role",
params = {},
expectedCode = 201,
errorCodes = {403,404,406,409},
text = {
"Roles are part of Namespaces",
"Examples:",
"<ul><li>org.onap.aaf - The team that created and maintains AAF</li>",
"Roles do not include implied permissions for an App. Instead, they contain explicit Granted Permissions by any Namespace in AAF (See Permissions)",
"Restrictions on Role Names:",
"<ul><li>Must start with valid Namespace name, terminated by . (dot/period)</li>",
"<li>Allowed Characters are a-zA-Z0-9._-</li>",
"<li>role names are Case Sensitive</li></ul>",
"The right questions to ask for defining and populating a Role in AAF, therefore, are:",
"<ul><li>'What Job Function does this represent?'</li>",
"<li>'Does this person perform this Job Function?'</li></ul>" }
)
@Override
public Result<Void> createRole(final AuthzTrans trans, REQUEST from) {
final Result<RoleDAO.Data> rd = mapper.role(trans, from);
final ServiceValidator v = new ServiceValidator();
if(v.role(rd).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
final RoleDAO.Data role = rd.value;
if(ques.roleDAO.read(trans, role.ns, role.name).isOKhasData()) {
return Result.err(Status.ERR_ConflictAlreadyExists, "Role [" + role.fullName() + "] already exists");
}
Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false,
new Mapper.Memo() {
@Override
public String get() {
return "Create Role [" +
rd.value.fullName() +
']';
}
},
new MayChange() {
private Result<NsDAO.Data> nsd;
@Override
public Result<?> mayChange() {
if(nsd==null) {
nsd = ques.mayUser(trans, trans.user(), role, Access.write);
}
return nsd;
}
});
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans, fd.value,
role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.C);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Role [%s.%s] is saved for future processing",
rd.value.ns,
rd.value.name);
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
Result<RoleDAO.Data> rdr = ques.roleDAO.create(trans, role);
if(rdr.isOK()) {
return Result.ok();
} else {
return Result.err(rdr);
}
default:
return Result.err(fd);
}
}
/* (non-Javadoc)
* @see org.onap.aaf.auth.service.AuthzService#getRolesByName(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
*/
@ApiDoc(
method = GET,
path = "/authz/roles/:role",
params = {"role|string|true"},
expectedCode = 200,
errorCodes = {404,406},
text = { "List Roles that match :role",
"Note: You must have permission to see any given role"
}
)
@Override
public Result<ROLES> getRolesByName(AuthzTrans trans, String role) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Role", role).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// Determine if User can ask this question
Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
if(rrdd.isOKhasData()) {
Result<NsDAO.Data> r;
if((r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read)).notOK()) {
return Result.err(r);
}
} else {
return Result.err(rrdd);
}
// Look up data
int query = role.indexOf('?');
Result<List<RoleDAO.Data>> rlrd = ques.getRolesByName(trans, query<0?role:role.substring(0, query));
if(rlrd.isOK()) {
// Note: Mapper will restrict what can be viewed
ROLES roles = mapper.newInstance(API.ROLES);
return mapper.roles(trans, rlrd.value, roles, true);
} else {
return Result.err(rlrd);
}
}
/* (non-Javadoc)
* @see org.onap.aaf.auth.service.AuthzService#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
*/
@ApiDoc(
method = GET,
path = "/authz/roles/user/:name",
params = {"name|string|true"},
expectedCode = 200,
errorCodes = {404,406},
text = { "List all Roles that match user :name",
"'user' must be expressed as full identity (ex: id@full.domain.com)",
"Note: You must have permission to see any given role"
}
)
@Override
public Result<ROLES> getRolesByUser(AuthzTrans trans, String user) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
ROLES roles = mapper.newInstance(API.ROLES);
// Get list of roles per user, then add to Roles as we go
Result<List<RoleDAO.Data>> rlrd;
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user);
if(rlurd.isOKhasData()) {
for(UserRoleDAO.Data urd : rlurd.value ) {
rlrd = ques.roleDAO.read(trans, urd.ns,urd.rname);
// Note: Mapper will restrict what can be viewed
// if user is the same as that which is looked up, no filtering is required
if(rlrd.isOKhasData()) {
mapper.roles(trans, rlrd.value,roles, !user.equals(trans.user()));
}
}
}
return Result.ok(roles);
}
/*
* (non-Javadoc)
* @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
*/
@ApiDoc(
method = GET,
path = "/authz/roles/ns/:ns",
params = {"ns|string|true"},
expectedCode = 200,
errorCodes = {404,406},
text = { "List all Roles for the Namespace :ns",
"Note: You must have permission to see any given role"
}
)
@Override
public Result<ROLES> getRolesByNS(AuthzTrans trans, String ns) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("NS", ns).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// check if user is allowed to view NS
Result<NsDAO.Data> rnsd = ques.deriveNs(trans, ns);
if(rnsd.notOK()) {
return Result.err(rnsd);
}
rnsd = ques.mayUser(trans, trans.user(), rnsd.value, Access.read);
if(rnsd.notOK()) {
return Result.err(rnsd);
}
TimeTaken tt = trans.start("MAP Roles by NS to Roles", Env.SUB);
try {
ROLES roles = mapper.newInstance(API.ROLES);
// Get list of roles per user, then add to Roles as we go
Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readNS(trans, ns);
if(rlrd.isOK()) {
if(!rlrd.isEmpty()) {
// Note: Mapper doesn't need to restrict what can be viewed, because we did it already.
mapper.roles(trans,rlrd.value,roles,false);
}
return Result.ok(roles);
} else {
return Result.err(rlrd);
}
} finally {
tt.done();
}
}
/*
* (non-Javadoc)
* @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
*/
@ApiDoc(
method = GET,
path = "/authz/roles/name/:name",
params = {"name|string|true"},
expectedCode = 200,
errorCodes = {404,406},
text = { "List all Roles for only the Name of Role (without Namespace)",
"Note: You must have permission to see any given role"
}
)
@Override
public Result<ROLES> getRolesByNameOnly(AuthzTrans trans, String name) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Name", name).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// User Mapper to make sure user is allowed to view NS
TimeTaken tt = trans.start("MAP Roles by Name to Roles", Env.SUB);
try {
ROLES roles = mapper.newInstance(API.ROLES);
// Get list of roles per user, then add to Roles as we go
Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readName(trans, name);
if(rlrd.isOK()) {
if(!rlrd.isEmpty()) {
// Note: Mapper will restrict what can be viewed
mapper.roles(trans,rlrd.value,roles,true);
}
return Result.ok(roles);
} else {
return Result.err(rlrd);
}
} finally {
tt.done();
}
}
@ApiDoc(
method = GET,
path = "/authz/roles/perm/:type/:instance/:action",
params = {"type|string|true",
"instance|string|true",
"action|string|true"},
expectedCode = 200,
errorCodes = {404,406},
text = { "Find all Roles containing the given Permission." +
"Permission consists of:",
"<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
+ "is being protected</li>",
"<li>instance - a key, possibly multi-dimensional, that identifies a specific "
+ " instance of the type</li>",
"<li>action - what kind of action is allowed</li></ul>",
"Notes: instance and action can be an *",
" You must have permission to see any given role"
}
)
@Override
public Result<ROLES> getRolesByPerm(AuthzTrans trans, String type, String instance, String action) {
final Validator v = new ServiceValidator();
if(v.permType(type)
.permInstance(instance)
.permAction(action)
.err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
TimeTaken tt = trans.start("Map Perm Roles Roles", Env.SUB);
try {
ROLES roles = mapper.newInstance(API.ROLES);
// Get list of roles per user, then add to Roles as we go
Result<NsSplit> nsSplit = ques.deriveNsSplit(trans, type);
if(nsSplit.isOK()) {
PermDAO.Data pdd = new PermDAO.Data(nsSplit.value, instance, action);
Result<?> res;
if((res=ques.mayUser(trans, trans.user(), pdd, Question.Access.read)).notOK()) {
return Result.err(res);
}
Result<List<PermDAO.Data>> pdlr = ques.permDAO.read(trans, pdd);
if(pdlr.isOK())for(PermDAO.Data pd : pdlr.value) {
Result<List<RoleDAO.Data>> rlrd;
for(String r : pd.roles) {
Result<String[]> rs = RoleDAO.Data.decodeToArray(trans, ques, r);
if(rs.isOK()) {
rlrd = ques.roleDAO.read(trans, rs.value[0],rs.value[1]);
// Note: Mapper will restrict what can be viewed
if(rlrd.isOKhasData()) {
mapper.roles(trans,rlrd.value,roles,true);
}
}
}
}
}
return Result.ok(roles);
} finally {
tt.done();
}
}
@ApiDoc(
method = PUT,
path = "/authz/role",
params = {},
expectedCode = 200,
errorCodes = {404,406},
text = { "Add Description Data to a Role" }
)
@Override
public Result<Void> updateRoleDescription(AuthzTrans trans, REQUEST from) {
final Result<RoleDAO.Data> rd = mapper.role(trans, from);
final ServiceValidator v = new ServiceValidator();
if(v.role(rd).err()) {
return Result.err(Status.ERR_BadData,v.errs());
} {
if(v.nullOrBlank("description", rd.value.description).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
}
final RoleDAO.Data role = rd.value;
if(ques.roleDAO.read(trans, role.ns, role.name).notOKorIsEmpty()) {
return Result.err(Status.ERR_NotFound, "Role [" + role.fullName() + "] does not exist");
}
if (ques.mayUser(trans, trans.user(), role, Access.write).notOK()) {
return Result.err(Status.ERR_Denied, "You do not have approval to change " + role.fullName());
}
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
Result<Void> rdr = ques.roleDAO.addDescription(trans, role.ns, role.name, role.description);
if(rdr.isOK()) {
return Result.ok();
} else {
return Result.err(rdr);
}
}
@ApiDoc(
method = POST,
path = "/authz/role/perm",
params = {},
expectedCode = 201,
errorCodes = {403,404,406,409},
text = { "Grant a Permission to a Role",
"Permission consists of:",
"<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
+ "is being protected</li>",
"<li>instance - a key, possibly multi-dimensional, that identifies a specific "
+ " instance of the type</li>",
"<li>action - what kind of action is allowed</li></ul>",
"Note: instance and action can be an *",
"Note: Using the \"force\" property will create the Permission, if it doesn't exist AND the requesting " +
" ID is allowed to create. It will then grant",
" the permission to the role in one step. To do this: add 'force=true' as a query parameter."
}
)
@Override
public Result<Void> addPermToRole(final AuthzTrans trans, REQUEST rreq) {
// Translate Request into Perm and Role Objects
final Result<PermDAO.Data> rpd = mapper.permFromRPRequest(trans, rreq);
if(rpd.notOKorIsEmpty()) {
return Result.err(rpd);
}
final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq);
if(rrd.notOKorIsEmpty()) {
return Result.err(rrd);
}
// Validate Role and Perm values
final ServiceValidator v = new ServiceValidator();
if(v.perm(rpd.value)
.role(rrd.value)
.err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.read(trans, rrd.value.ns, rrd.value.name);
if(rlrd.notOKorIsEmpty()) {
return Result.err(Status.ERR_RoleNotFound, "Role [%s] does not exist", rrd.value.fullName());
}
// Check Status of Data in DB (does it exist)
Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, rpd.value.ns,
rpd.value.type, rpd.value.instance, rpd.value.action);
PermDAO.Data createPerm = null; // if not null, create first
if(rlpd.notOKorIsEmpty()) { // Permission doesn't exist
if(trans.requested(force)) {
// Remove roles from perm data object so we just create the perm here
createPerm = rpd.value;
createPerm.roles.clear();
} else {
return Result.err(Status.ERR_PermissionNotFound,"Permission [%s.%s|%s|%s] does not exist",
rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action);
}
} else {
if (rlpd.value.get(0).roles(false).contains(rrd.value.encode())) {
return Result.err(Status.ERR_ConflictAlreadyExists,
"Permission [%s.%s|%s|%s] already granted to Role [%s.%s]",
rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action,
rrd.value.ns,rrd.value.name
);
}
}
Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, rpd.value,true, // Allow grants to create Approvals
new Mapper.Memo() {
@Override
public String get() {
return "Grant Permission [" + rpd.value.fullPerm() + ']' +
" to Role [" + rrd.value.fullName() + "]";
}
},
new MayChange() {
private Result<NsDAO.Data> nsd;
@Override
public Result<?> mayChange() {
if(nsd==null) {
nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write);
}
return nsd;
}
});
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rpd.value.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans,fd.value,
rpd.value.fullPerm(),
trans.user(),
nsr.value.get(0),
FUTURE_OP.G);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
rpd.value.ns,
rpd.value.type,
rpd.value.instance,
rpd.value.action);
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
Result<Void> rv = null;
if(createPerm!=null) {// has been validated for creating
rv = func.createPerm(trans, createPerm, false);
}
if(rv==null || rv.isOK()) {
rv = func.addPermToRole(trans, rrd.value, rpd.value, false);
}
return rv;
default:
return Result.err(fd);
}
}
/**
* Delete Perms from Roles (UnGrant)
* @param trans
* @param roleFullName
* @return
*/
@ApiDoc(
method = DELETE,
path = "/authz/role/:role/perm",
params = {"role|string|true"},
expectedCode = 200,
errorCodes = {404,406},
text = { "Ungrant a permission from Role :role" }
)
@Override
public Result<Void> delPermFromRole(final AuthzTrans trans, REQUEST rreq) {
final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq);
if(updt.notOKorIsEmpty()) {
return Result.err(updt);
}
final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq);
if(rrd.notOKorIsEmpty()) {
return Result.err(rrd);
}
final ServiceValidator v = new ServiceValidator();
if(v.nullOrBlank(updt.value)
.nullOrBlank(rrd.value)
.err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
return delPermFromRole(trans, updt.value,rrd.value, rreq);
}
private Result<Void> delPermFromRole(final AuthzTrans trans, PermDAO.Data pdd, RoleDAO.Data rdd, REQUEST rreq) {
Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, pdd.ns, pdd.type,
pdd.instance, pdd.action);
if(rlpd.notOKorIsEmpty()) {
return Result.err(Status.ERR_PermissionNotFound,
"Permission [%s.%s|%s|%s] does not exist",
pdd.ns,pdd.type,pdd.instance,pdd.action);
}
Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, pdd,true, // allow ungrants requests
new Mapper.Memo() {
@Override
public String get() {
return "Ungrant Permission [" + pdd.fullPerm() + ']' +
" from Role [" + rdd.fullName() + "]";
}
},
new MayChange() {
private Result<NsDAO.Data> nsd;
@Override
public Result<?> mayChange() {
if(nsd==null) {
nsd = ques.mayUser(trans, trans.user(), pdd, Access.write);
}
return nsd;
}
});
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pdd.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans,fd.value,
pdd.fullPerm(),
trans.user(),
nsr.value.get(0),
FUTURE_OP.UG
);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
pdd.ns,
pdd.type,
pdd.instance,
pdd.action);
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
return func.delPermFromRole(trans, rdd, pdd, false);
default:
return Result.err(fd);
}
}
/*
@ApiDoc(
method = DELETE,
path = "/authz/role/:role/perm/:type/:instance/:action",
params = {"role|string|true",
"perm type|string|true",
"perm instance|string|true",
"perm action|string|true"
},
expectedCode = 200,
errorCodes = {404,406},
text = { "Ungrant a single permission from Role :role with direct key" }
)
*/
@Override
public Result<Void> delPermFromRole(AuthzTrans trans, String role, String type, String instance, String action) {
Result<Data> rpns = ques.deriveNs(trans, type);
if(rpns.notOKorIsEmpty()) {
return Result.err(rpns);
}
final Validator v = new ServiceValidator();
if(v.role(role)
.permType(rpns.value.name,rpns.value.parent)
.permInstance(instance)
.permAction(action)
.err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<Data> rrns = ques.deriveNs(trans, role);
if(rrns.notOKorIsEmpty()) {
return Result.err(rrns);
}
final Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, rrns.value.parent, rrns.value.name);
if(rrd.notOKorIsEmpty()) {
return Result.err(rrd);
}
final Result<List<PermDAO.Data>> rpd = ques.permDAO.read(trans, rpns.value.parent, rpns.value.name, instance, action);
if(rpd.notOKorIsEmpty()) {
return Result.err(rpd);
}
return delPermFromRole(trans,rpd.value.get(0), rrd.value.get(0), mapper.ungrantRequest(trans, role, type, instance, action));
}
@ApiDoc(
method = DELETE,
path = "/authz/role/:role",
params = {"role|string|true"},
expectedCode = 200,
errorCodes = {404,406},
text = { "Delete the Role named :role"}
)
@Override
public Result<Void> deleteRole(AuthzTrans trans, String role) {
Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
if(rrdd.isOKhasData()) {
final ServiceValidator v = new ServiceValidator();
if(v.nullOrBlank(rrdd.value).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
return func.deleteRole(trans, rrdd.value, false, false);
} else {
return Result.err(rrdd);
}
}
@ApiDoc(
method = DELETE,
path = "/authz/role",
params = {},
expectedCode = 200,
errorCodes = { 404,406 },
text = { "Delete the Role referenced by RoleKey",
"You cannot normally delete a role which still has permissions granted or users assigned to it,",
"however the \"force\" property allows you to do just that. To do this: Add 'force=true'",
"as a query parameter.",
"<p>WARNING: Using force will remove all users and permission from this role. Use with care.</p>"}
)
@Override
public Result<Void> deleteRole(final AuthzTrans trans, REQUEST from) {
final Result<RoleDAO.Data> rd = mapper.role(trans, from);
final ServiceValidator v = new ServiceValidator();
if(rd==null) {
return Result.err(Status.ERR_BadData,"Request does not contain Role");
}
if(v.nullOrBlank(rd.value).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
final RoleDAO.Data role = rd.value;
if(ques.roleDAO.read(trans, role).notOKorIsEmpty() && !trans.requested(force)) {
return Result.err(Status.ERR_RoleNotFound, "Role [" + role.fullName() + "] does not exist");
}
Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false,
new Mapper.Memo() {
@Override
public String get() {
return "Delete Role [" + role.fullName() + ']'
+ " and all attached user roles";
}
},
new MayChange() {
private Result<NsDAO.Data> nsd;
@Override
public Result<?> mayChange() {
if(nsd==null) {
nsd = ques.mayUser(trans, trans.user(), role, Access.write);
}
return nsd;
}
});
switch(fd.status) {
case OK:
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
Result<String> rfc = func.createFuture(trans, fd.value,
role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Role Deletion [%s.%s] is saved for future processing",
rd.value.ns,
rd.value.name);
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
return func.deleteRole(trans,role,trans.requested(force), true /*preapproved*/);
default:
return Result.err(fd);
}
}
/***********************************
* CRED
***********************************/
private class MayCreateCred implements MayChange {
private Result<NsDAO.Data> nsd;
private AuthzTrans trans;
private CredDAO.Data cred;
private Executor exec;
public MayCreateCred(AuthzTrans trans, CredDAO.Data cred, Executor exec) {
this.trans = trans;
this.cred = cred;
this.exec = exec;
}
@Override
public Result<?> mayChange() {
if(nsd==null) {
nsd = ques.validNSOfDomain(trans, cred.id);
}
// is Ns of CredID valid?
if(nsd.isOK()) {
try {
// Check Org Policy
if(trans.org().validate(trans,Policy.CREATE_MECHID, exec, cred.id)==null) {
return Result.ok();
} else {
Result<?> rmc = ques.mayUser(trans, trans.user(), nsd.value, Access.write);
if(rmc.isOKhasData()) {
return rmc;
}
}
} catch (Exception e) {
trans.warn().log(e);
}
} else {
trans.warn().log(nsd.errorString());
}
return Result.err(Status.ERR_Denied,"%s is not allowed to create %s in %s",trans.user(),cred.id,cred.ns);
}
}
private class MayChangeCred implements MayChange {
private Result<NsDAO.Data> nsd;
private AuthzTrans trans;
private CredDAO.Data cred;
public MayChangeCred(AuthzTrans trans, CredDAO.Data cred) {
this.trans = trans;
this.cred = cred;
}
@Override
public Result<?> mayChange() {
// User can change himself (but not create)
if(trans.user().equals(cred.id)) {
return Result.ok();
}
if(nsd==null) {
nsd = ques.validNSOfDomain(trans, cred.id);
}
// Get the Namespace
if(nsd.isOK()) {
if(ques.mayUser(trans, trans.user(), nsd.value,Access.write).isOK()) {
return Result.ok();
}
String user[] = Split.split('.',trans.user());
if(user.length>2) {
String company = user[user.length-1] + '.' + user[user.length-2];
if(ques.isGranted(trans, trans.user(), ROOT_NS,"password",company,"reset")) {
return Result.ok();
}
}
}
return Result.err(Status.ERR_Denied,"%s is not allowed to change %s in %s",trans.user(),cred.id,cred.ns);
}
}
private final long DAY_IN_MILLIS = 24*3600*1000L;
@ApiDoc(
method = POST,
path = "/authn/cred",
params = {},
expectedCode = 201,
errorCodes = {403,404,406,409},
text = { "A credential consists of:",
"<ul><li>id - the ID to create within AAF. The domain is in reverse",
"order of Namespace (i.e. Users of Namespace com.att.myapp would be",
"AB1234@myapp.att.com</li>",
"<li>password - Company Policy Compliant Password</li></ul>",
"Note: AAF does support multiple credentials with the same ID.",
"Check with your organization if you have this implemented."
}
)
@Override
public Result<Void> createUserCred(final AuthzTrans trans, REQUEST from) {
final String cmdDescription = ("Create User Credential");
TimeTaken tt = trans.start(cmdDescription, Env.SUB);
try {
Result<CredDAO.Data> rcred = mapper.cred(trans, from, true);
if(rcred.isOKhasData()) {
byte[] rawCred = rcred.value.cred.array();
rcred = ques.userCredSetup(trans, rcred.value);
final ServiceValidator v = new ServiceValidator();
if(v.cred(trans, trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations
return Result.err(Status.ERR_BadData,v.errs());
}
// 2016-4 Jonathan, New Behavior - If MechID is not registered with Org, deny creation
Identity mechID = null;
Organization org = trans.org();
try {
mechID = org.getIdentity(trans, rcred.value.id);
} catch (Exception e1) {
trans.error().log(e1,rcred.value.id,"cannot be validated at this time");
}
if(mechID==null || !mechID.isFound()) {
return Result.err(Status.ERR_Policy,"MechIDs must be registered with %s before provisioning in AAF",org.getName());
}
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(Status.ERR_NsNotFound,"Cannot provision %s on non-existent Namespace %s",mechID.id(),rcred.value.ns);
}
boolean firstID = false;
MayChange mc;
CassExecutor exec = new CassExecutor(trans, func);
Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id);
if (rlcd.isOKhasData()) {
if (!org.canHaveMultipleCreds(rcred.value.id)) {
return Result.err(Status.ERR_ConflictAlreadyExists, "Credential exists");
}
Result<Boolean> rb;
for (CredDAO.Data curr : rlcd.value) {
// May not use the same password in the list
// Note: ASPR specifies character differences, but we don't actually store the
// password to validate char differences.
rb = ques.userCredCheck(trans, curr, rawCred);
if(rb.notOK()) {
return Result.err(rb);
} else if(rb.value){
return Result.err(Status.ERR_Policy, "Credential content cannot be reused.");
} else if (Chrono.dateOnlyStamp(curr.expires).equals(Chrono.dateOnlyStamp(rcred.value.expires)) && curr.type==rcred.value.type) {
return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists, use 'reset'");
}
}
} else {
try {
// 2016-04-12 Jonathan If Caller is the Sponsor and is also an Owner of NS, allow without special Perm
String theMechID = rcred.value.id;
Boolean otherMechIDs = false;
// find out if this is the only mechID. other MechIDs mean special handling (not automated)
for(CredDAO.Data cd : ques.credDAO.readNS(trans,nsr.value.get(0).name).value) {
if(!cd.id.equals(theMechID)) {
otherMechIDs = true;
break;
}
}
String reason;
// We can say "ID does not exist" here
if((reason=org.validate(trans, Policy.CREATE_MECHID, exec, theMechID,trans.user(),otherMechIDs.toString()))!=null) {
return Result.err(Status.ERR_Denied, reason);
}
firstID=true;
} catch (Exception e) {
return Result.err(e);
}
}
mc = new MayCreateCred(trans, rcred.value, exec);
final CredDAO.Data cdd = rcred.value;
Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, // may want to enable in future.
new Mapper.Memo() {
@Override
public String get() {
return cmdDescription + " [" +
cdd.id + '|'
+ cdd.type + '|'
+ cdd.expires + ']';
}
},
mc);
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans, fd.value,
rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
trans.user(), nsr.value.get(0), FUTURE_OP.C);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s] is saved for future processing",
rcred.value.id,
Integer.toString(rcred.value.type),
rcred.value.expires.toString());
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
try {
if(firstID) {
// && !nsr.value.get(0).isAdmin(trans.getUserPrincipal().getName())) {
Result<List<String>> admins = func.getAdmins(trans, nsr.value.get(0).name, false);
// OK, it's a first ID, and not by NS Admin, so let's set TempPassword length
// Note, we only do this on First time, because of possibility of
// prematurely expiring a production id
if(admins.isOKhasData() && !admins.value.contains(trans.user())) {
rcred.value.expires = org.expiration(null, Expiration.TempPassword).getTime();
}
}
} catch (Exception e) {
trans.error().log(e, "While setting expiration to TempPassword");
}
Result<?>udr = ques.credDAO.create(trans, rcred.value);
if(udr.isOK()) {
return Result.ok();
}
return Result.err(udr);
default:
return Result.err(fd);
}
} else {
return Result.err(rcred);
}
} finally {
tt.done();
}
}
@ApiDoc(
method = GET,
path = "/authn/creds/ns/:ns",
params = {"ns|string|true"},
expectedCode = 200,
errorCodes = {403,404,406},
text = { "Return all IDs in Namespace :ns"
}
)
@Override
public Result<USERS> getCredsByNS(AuthzTrans trans, String ns) {
final Validator v = new ServiceValidator();
if(v.ns(ns).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// check if user is allowed to view NS
Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
if(rnd.notOK()) {
return Result.err(rnd);
}
rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
TimeTaken tt = trans.start("MAP Creds by NS to Creds", Env.SUB);
try {
USERS users = mapper.newInstance(API.USERS);
Result<List<CredDAO.Data>> rlcd = ques.credDAO.readNS(trans, ns);
if(rlcd.isOK()) {
if(!rlcd.isEmpty()) {
return mapper.cred(rlcd.value, users);
}
return Result.ok(users);
} else {
return Result.err(rlcd);
}
} finally {
tt.done();
}
}
@ApiDoc(
method = GET,
path = "/authn/creds/id/:ns",
params = {"id|string|true"},
expectedCode = 200,
errorCodes = {403,404,406},
text = { "Return all IDs in for ID"
,"(because IDs are multiple, due to multiple Expiration Dates)"
}
)
@Override
public Result<USERS> getCredsByID(AuthzTrans trans, String id) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("ID",id).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
String ns = Question.domain2ns(id);
// check if user is allowed to view NS
Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
if(rnd.notOK()) {
return Result.err(rnd);
}
rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
TimeTaken tt = trans.start("MAP Creds by ID to Creds", Env.SUB);
try {
USERS users = mapper.newInstance(API.USERS);
Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, id);
if(rlcd.isOK()) {
if(!rlcd.isEmpty()) {
return mapper.cred(rlcd.value, users);
}
return Result.ok(users);
} else {
return Result.err(rlcd);
}
} finally {
tt.done();
}
}
@ApiDoc(
method = GET,
path = "/authn/certs/id/:id",
params = {"id|string|true"},
expectedCode = 200,
errorCodes = {403,404,406},
text = { "Return Cert Info for ID"
}
)
@Override
public Result<CERTS> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id) {
TimeTaken tt = trans.start("Get Cert Info by ID", Env.SUB);
try {
CERTS certs = mapper.newInstance(API.CERTS);
Result<List<CertDAO.Data>> rlcd = ques.certDAO.readID(trans, id);
if(rlcd.isOK()) {
if(!rlcd.isEmpty()) {
return mapper.cert(rlcd.value, certs);
}
return Result.ok(certs);
} else {
return Result.err(rlcd);
}
} finally {
tt.done();
}
}
@ApiDoc(
method = PUT,
path = "/authn/cred",
params = {},
expectedCode = 200,
errorCodes = {300,403,404,406},
text = { "Reset a Credential Password. If multiple credentials exist for this",
"ID, you will need to specify which entry you are resetting in the",
"CredRequest object"
}
)
@Override
public Result<Void> changeUserCred(final AuthzTrans trans, REQUEST from) {
final String cmdDescription = "Update User Credential";
TimeTaken tt = trans.start(cmdDescription, Env.SUB);
try {
Result<CredDAO.Data> rcred = mapper.cred(trans, from, true);
if(rcred.isOKhasData()) {
rcred = ques.userCredSetup(trans, rcred.value);
final ServiceValidator v = new ServiceValidator();
if(v.cred(trans, trans.org(),rcred,false).err()) {// Note: Creates have stricter Validations
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id);
if(rlcd.notOKorIsEmpty()) {
return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
}
MayChange mc = new MayChangeCred(trans, rcred.value);
Result<?> rmc = mc.mayChange();
if (rmc.notOK()) {
return Result.err(rmc);
}
Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value);
if(ri.notOK()) {
return Result.err(ri);
}
int entry = ri.value;
final CredDAO.Data cred = rcred.value;
Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false,
new Mapper.Memo() {
@Override
public String get() {
return cmdDescription + " [" +
cred.id + '|'
+ cred.type + '|'
+ cred.expires + ']';
}
},
mc);
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans, fd.value,
rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
trans.user(), nsr.value.get(0), FUTURE_OP.U);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s]",
rcred.value.id,
Integer.toString(rcred.value.type),
rcred.value.expires.toString());
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
Result<?>udr = null;
// If we are Resetting Password on behalf of someone else (am not the Admin)
// use TempPassword Expiration time.
Expiration exp;
if(ques.isAdmin(trans, trans.user(), nsr.value.get(0).name)) {
exp = Expiration.Password;
} else {
exp = Expiration.TempPassword;
}
Organization org = trans.org();
CredDAO.Data current = rlcd.value.get(entry);
// If user resets password in same day, we will have a primary key conflict, so subtract 1 day
if (current.expires.equals(rcred.value.expires)
&& rlcd.value.get(entry).type==rcred.value.type) {
GregorianCalendar gc = org.expiration(null, exp,rcred.value.id);
gc = Chrono.firstMomentOfDay(gc);
gc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay());
rcred.value.expires = new Date(gc.getTimeInMillis() - DAY_IN_MILLIS);
} else {
rcred.value.expires = org.expiration(null,exp).getTime();
}
// Copy in other fields 10/21/2016
rcred.value.notes=current.notes;
udr = ques.credDAO.create(trans, rcred.value);
if(udr.isOK()) {
udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false);
}
if (udr.isOK()) {
return Result.ok();
}
return Result.err(udr);
default:
return Result.err(fd);
}
} else {
return Result.err(rcred);
}
} finally {
tt.done();
}
}
/*
* Codify the way to get Either Choice Needed or actual Integer from Credit Request
*/
private Result<Integer> selectEntryIfMultiple(final CredRequest cr, List<CredDAO.Data> lcd) {
int entry = 0;
if (lcd.size() > 1) {
String inputOption = cr.getEntry();
if (inputOption == null) {
String message = selectCredFromList(lcd, false);
String[] variables = buildVariables(lcd);
return Result.err(Status.ERR_ChoiceNeeded, message, variables);
} else {
entry = Integer.parseInt(inputOption) - 1;
}
if (entry < 0 || entry >= lcd.size()) {
return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
}
}
return Result.ok(entry);
}
@ApiDoc(
method = PUT,
path = "/authn/cred/:days",
params = {"days|string|true"},
expectedCode = 200,
errorCodes = {300,403,404,406},
text = { "Extend a Credential Expiration Date. The intention of this API is",
"to avoid an outage in PROD due to a Credential expiring before it",
"can be configured correctly. Measures are being put in place ",
"so that this is not abused."
}
)
@Override
public Result<Void> extendUserCred(final AuthzTrans trans, REQUEST from, String days) {
TimeTaken tt = trans.start("Extend User Credential", Env.SUB);
try {
Result<CredDAO.Data> cred = mapper.cred(trans, from, false);
Organization org = trans.org();
final ServiceValidator v = new ServiceValidator();
if(v.notOK(cred).err() ||
v.nullOrBlank(cred.value.id, "Invalid ID").err() ||
v.user(org,cred.value.id).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
try {
String reason;
if ((reason=org.validate(trans, Policy.MAY_EXTEND_CRED_EXPIRES, new CassExecutor(trans,func)))!=null) {
return Result.err(Status.ERR_Policy,reason);
}
} catch (Exception e) {
String msg;
trans.error().log(e, msg="Could not contact Organization for User Validation");
return Result.err(Status.ERR_Denied, msg);
}
// Get the list of Cred Entries
Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id);
if(rlcd.notOKorIsEmpty()) {
return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
}
//Need to do the "Pick Entry" mechanism
Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value);
if(ri.notOK()) {
return Result.err(ri);
}
CredDAO.Data found = rlcd.value.get(ri.value);
CredDAO.Data cd = cred.value;
// Copy over the cred
cd.id = found.id;
cd.cred = found.cred;
cd.other = found.other;
cd.type = found.type;
cd.notes = found.notes;
cd.ns = found.ns;
cd.expires = org.expiration(null, Expiration.ExtendPassword,days).getTime();
cred = ques.credDAO.create(trans, cd);
if(cred.isOK()) {
return Result.ok();
}
return Result.err(cred);
} finally {
tt.done();
}
}
private String[] buildVariables(List<CredDAO.Data> value) {
// ensure credentials are sorted so we can fully automate Cred regression test
Collections.sort(value, new Comparator<CredDAO.Data>() {
@Override
public int compare(CredDAO.Data cred1, CredDAO.Data cred2) {
return cred1.expires.compareTo(cred2.expires);
}
});
String [] vars = new String[value.size()+1];
vars[0]="Choice";
for (int i = 0; i < value.size(); i++) {
vars[i+1] = value.get(i).id + " " + value.get(i).type
+ " |" + value.get(i).expires;
}
return vars;
}
private String selectCredFromList(List<CredDAO.Data> value, boolean isDelete) {
StringBuilder errMessage = new StringBuilder();
String userPrompt = isDelete?"Select which cred to delete (set force=true to delete all):":"Select which cred to update:";
int numSpaces = value.get(0).id.length() - "Id".length();
errMessage.append(userPrompt + '\n');
errMessage.append(" Id");
for (int i = 0; i < numSpaces; i++) {
errMessage.append(' ');
}
errMessage.append(" Type Expires" + '\n');
for(int i=0;i<value.size();++i) {
errMessage.append(" %s\n");
}
errMessage.append("Run same command again with chosen entry as last parameter");
return errMessage.toString();
}
@ApiDoc(
method = DELETE,
path = "/authn/cred",
params = {},
expectedCode = 200,
errorCodes = {300,403,404,406},
text = { "Delete a Credential. If multiple credentials exist for this",
"ID, you will need to specify which entry you are deleting in the",
"CredRequest object."
}
)
@Override
public Result<Void> deleteUserCred(AuthzTrans trans, REQUEST from) {
final Result<CredDAO.Data> cred = mapper.cred(trans, from, false);
final Validator v = new ServiceValidator();
if(v.nullOrBlank("cred", cred.value.id).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id);
if(rlcd.notOKorIsEmpty()) {
// Empty Creds should have no user_roles.
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id);
if(rlurd.isOK()) {
for(UserRoleDAO.Data data : rlurd.value) {
ques.userRoleDAO.delete(trans, data, false);
}
}
return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
}
boolean isLastCred = rlcd.value.size()==1;
MayChange mc = new MayChangeCred(trans,cred.value);
Result<?> rmc = mc.mayChange();
if (rmc.notOK()) {
return Result.err(rmc);
}
int entry = 0;
if(!trans.requested(force)) {
if (rlcd.value.size() > 1) {
CredRequest cr = (CredRequest)from;
String inputOption = cr.getEntry();
if (inputOption == null) {
String message = selectCredFromList(rlcd.value, true);
String[] variables = buildVariables(rlcd.value);
return Result.err(Status.ERR_ChoiceNeeded, message, variables);
} else {
try {
if(inputOption.length()>5) { // should be a date
Date d = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(inputOption).toGregorianCalendar().getTime();
entry = 0;
for(CredDAO.Data cd : rlcd.value) {
if(cd.type.equals(cr.getType()) && cd.expires.equals(d)) {
break;
}
++entry;
}
} else {
entry = Integer.parseInt(inputOption) - 1;
}
} catch(NullPointerException e) {
return Result.err(Status.ERR_BadData, "Invalid Date Format for Entry");
} catch(NumberFormatException e) {
return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
}
}
isLastCred = (entry==-1)?true:false;
} else {
isLastCred = true;
}
if (entry < -1 || entry >= rlcd.value.size()) {
return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
}
}
Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from,cred.value,false,
new Mapper.Memo() {
@Override
public String get() {
return "Delete Credential [" +
cred.value.id +
']';
}
},
mc);
Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, cred.value.ns);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans, fd.value, cred.value.id,
trans.user(), nsr.value.get(0), FUTURE_OP.D);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Credential Delete [%s] is saved for future processing",cred.value.id);
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
Result<?>udr = null;
if (!trans.requested(force)) {
if(entry<0 || entry >= rlcd.value.size()) {
return Result.err(Status.ERR_BadData,"Invalid Choice [" + entry + "] chosen for Delete [%s] is saved for future processing",cred.value.id);
}
udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false);
} else {
for (CredDAO.Data curr : rlcd.value) {
udr = ques.credDAO.delete(trans, curr, false);
if (udr.notOK()) {
return Result.err(udr);
}
}
}
if(isLastCred) {
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id);
if(rlurd.isOK()) {
for(UserRoleDAO.Data data : rlurd.value) {
ques.userRoleDAO.delete(trans, data, false);
}
}
}
if(udr==null) {
return Result.err(Result.ERR_NotFound,"No User Data found");
}
if (udr.isOK()) {
return Result.ok();
}
return Result.err(udr);
default:
return Result.err(fd);
}
}
@Override
public Result<Date> doesCredentialMatch(AuthzTrans trans, REQUEST credReq) {
TimeTaken tt = trans.start("Does Credential Match", Env.SUB);
try {
// Note: Mapper assigns RAW type
Result<CredDAO.Data> data = mapper.cred(trans, credReq,false);
if(data.notOKorIsEmpty()) {
return Result.err(data);
}
CredDAO.Data cred = data.value; // of the Mapped Cred
if(cred.cred==null) {
return Result.err(Result.ERR_BadData,"No Password");
} else {
return ques.doesUserCredMatch(trans, cred.id, cred.cred.array());
}
} catch (DAOException e) {
trans.error().log(e,"Error looking up cred");
return Result.err(Status.ERR_Denied,"Credential does not match");
} finally {
tt.done();
}
}
@ApiDoc(
method = GET,
path = "/authn/basicAuth",
params = {},
expectedCode = 200,
errorCodes = { 403 },
text = { "!!!! DEPRECATED without X509 Authentication STOP USING THIS API BY DECEMBER 2017, or use Certificates !!!!\n"
+ "Use /authn/validate instead\n"
+ "Note: Validate a Password using BasicAuth Base64 encoded Header. This HTTP/S call is intended as a fast"
+ " User/Password lookup for Security Frameworks, and responds 200 if it passes BasicAuth "
+ "security, and 403 if it does not." }
)
private void basicAuth() {
// This is a place holder for Documentation. The real BasicAuth API does not call Service.
}
@ApiDoc(
method = POST,
path = "/authn/validate",
params = {},
expectedCode = 200,
errorCodes = { 403 },
text = { "Validate a Credential given a Credential Structure. This is a more comprehensive validation, can "
+ "do more than BasicAuth as Credential types exp" }
)
@Override
public Result<Date> validateBasicAuth(AuthzTrans trans, String basicAuth) {
//TODO how to make sure people don't use this in browsers? Do we care?
TimeTaken tt = trans.start("Validate Basic Auth", Env.SUB);
try {
BasicPrincipal bp = new BasicPrincipal(basicAuth,trans.org().getRealm());
Result<Date> rq = ques.doesUserCredMatch(trans, bp.getName(), bp.getCred());
// Note: Only want to log problem, don't want to send back to end user
if(rq.isOK()) {
return rq;
} else {
trans.audit().log(rq.errorString());
}
} catch (Exception e) {
trans.warn().log(e);
} finally {
tt.done();
}
return Result.err(Status.ERR_Denied,"Bad Basic Auth");
}
/***********************************
* USER-ROLE
***********************************/
@ApiDoc(
method = POST,
path = "/authz/userRole",
params = {},
expectedCode = 201,
errorCodes = {403,404,406,409},
text = { "Create a UserRole relationship (add User to Role)",
"A UserRole is an object Representation of membership of a Role for limited time.",
"If a shorter amount of time for Role ownership is required, use the 'End' field.",
"** Note: Owners of Namespaces will be required to revalidate users in these roles ",
"before Expirations expire. Namespace owners will be notified by email."
}
)
@Override
public Result<Void> createUserRole(final AuthzTrans trans, REQUEST from) {
TimeTaken tt = trans.start("Create UserRole", Env.SUB);
try {
Result<UserRoleDAO.Data> urr = mapper.userRole(trans, from);
if(urr.notOKorIsEmpty()) {
return Result.err(urr);
}
final UserRoleDAO.Data userRole = urr.value;
final ServiceValidator v = new ServiceValidator();
if(v.user_role(userRole).err() ||
v.user(trans.org(), userRole.user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// Check if user can change first
Result<FutureDAO.Data> fd = mapper.future(trans,UserRoleDAO.TABLE,from,urr.value,true, // may request Approvals
new Mapper.Memo() {
@Override
public String get() {
return "Add User [" + userRole.user + "] to Role [" +
userRole.role +
']';
}
},
new MayChange() {
private Result<NsDAO.Data> nsd;
@Override
public Result<?> mayChange() {
if(nsd==null) {
RoleDAO.Data r = RoleDAO.Data.decode(userRole);
nsd = ques.mayUser(trans, trans.user(), r, Access.write);
}
return nsd;
}
});
Result<NsDAO.Data> nsr = ques.deriveNs(trans, userRole.role);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans, fd.value, userRole.user+'|'+userRole.ns + '.' + userRole.rname,
userRole.user, nsr.value, FUTURE_OP.C);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "UserRole [%s - %s.%s] is saved for future processing",
userRole.user,
userRole.ns,
userRole.rname);
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
return func.addUserRole(trans, userRole);
default:
return Result.err(fd);
}
} finally {
tt.done();
}
}
/**
* getUserRolesByRole
*/
@ApiDoc(
method = GET,
path = "/authz/userRoles/role/:role",
params = {"role|string|true"},
expectedCode = 200,
errorCodes = {404,406},
text = { "List all Users that are attached to Role specified in :role",
}
)
@Override
public Result<USERROLES> getUserRolesByRole(AuthzTrans trans, String role) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Role",role).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<RoleDAO.Data> rrdd;
rrdd = RoleDAO.Data.decode(trans,ques,role);
if(rrdd.notOK()) {
return Result.err(rrdd);
}
// May Requester see result?
Result<NsDAO.Data> ns = ques.mayUser(trans,trans.user(), rrdd.value,Access.read);
if (ns.notOK()) {
return Result.err(ns);
}
// boolean filter = true;
// if (ns.value.isAdmin(trans.user()) || ns.value.isResponsible(trans.user()))
// filter = false;
// Get list of roles per user, then add to Roles as we go
HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role);
if(rlurd.isOK()) {
for(UserRoleDAO.Data data : rlurd.value) {
userSet.add(data);
}
}
@SuppressWarnings("unchecked")
USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES);
// Checked for permission
mapper.userRoles(trans, userSet, users);
return Result.ok(users);
}
/**
* getUserRolesByRole
*/
@ApiDoc(
method = GET,
path = "/authz/userRoles/user/:user",
params = {"role|string|true"},
expectedCode = 200,
errorCodes = {404,406},
text = { "List all UserRoles for :user",
}
)
@Override
public Result<USERROLES> getUserRolesByUser(AuthzTrans trans, String user) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("User",user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// Get list of roles per user, then add to Roles as we go
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user);
if(rlurd.notOK()) {
return Result.err(rlurd);
}
/* Check for
* 1) is User
* 2) is User's Supervisor
* 3) Has special global access =read permission
*
* If none of the 3, then filter results to NSs in which Calling User has Ns.access * read
*/
boolean mustFilter;
String callingUser = trans.getUserPrincipal().getName();
NsDAO.Data ndd = new NsDAO.Data();
if(user.equals(callingUser)) {
mustFilter = false;
} else {
Organization org = trans.org();
try {
Identity orgID = org.getIdentity(trans, user);
Identity manager = orgID==null?null:orgID.responsibleTo();
if(orgID!=null && (manager!=null && callingUser.equals(manager.fullID()))) {
mustFilter = false;
} else if(ques.isGranted(trans, callingUser, ROOT_NS, Question.ACCESS, "*", Access.read.name())) {
mustFilter=false;
} else {
mustFilter = true;
}
} catch (OrganizationException e) {
trans.env().log(e);
mustFilter = true;
}
}
List<UserRoleDAO.Data> content;
if(mustFilter) {
content = new ArrayList<UserRoleDAO.Data>(rlurd.value.size()); // avoid multi-memory redos
for(UserRoleDAO.Data data : rlurd.value) {
ndd.name=data.ns;
Result<Data> mur = ques.mayUser(trans, callingUser, ndd, Access.read);
if(mur.isOK()){
content.add(data);
}
}
} else {
content = rlurd.value;
}
@SuppressWarnings("unchecked")
USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES);
// Checked for permission
mapper.userRoles(trans, content, users);
return Result.ok(users);
}
@ApiDoc(
method = PUT,
path = "/authz/userRole/user",
params = {},
expectedCode = 200,
errorCodes = {403,404,406},
text = { "Set a User's roles to the roles specified in the UserRoleRequest object.",
"WARNING: Roles supplied will be the ONLY roles attached to this user",
"If no roles are supplied, user's roles are reset."
}
)
@Override
public Result<Void> resetRolesForUser(AuthzTrans trans, REQUEST rreq) {
Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq);
final ServiceValidator v = new ServiceValidator();
if(rurdd.notOKorIsEmpty()) {
return Result.err(rurdd);
}
if (v.user(trans.org(), rurdd.value.user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Set<String> currRoles = new HashSet<String>();
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, rurdd.value.user);
if(rlurd.isOK()) {
for(UserRoleDAO.Data data : rlurd.value) {
currRoles.add(data.role);
}
}
Result<Void> rv = null;
String[] roles;
if(rurdd.value.role==null) {
roles = new String[0];
} else {
roles = rurdd.value.role.split(",");
}
for (String role : roles) {
if (v.role(role).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
if(rrdd.notOK()) {
return Result.err(rrdd);
}
rurdd.value.role(rrdd.value);
Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rrdd.value,Access.write);
if (nsd.notOK()) {
return Result.err(nsd);
}
Result<NsDAO.Data> nsr = ques.deriveNs(trans, role);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
if(currRoles.contains(role)) {
currRoles.remove(role);
} else {
rv = func.addUserRole(trans, rurdd.value);
if (rv.notOK()) {
return rv;
}
}
}
for (String role : currRoles) {
rurdd.value.role(trans,ques,role);
rv = ques.userRoleDAO.delete(trans, rurdd.value, false);
if(rv.notOK()) {
trans.info().log(rurdd.value.user,"/",rurdd.value.role, "expected to be deleted, but does not exist");
// return rv; // if it doesn't exist, don't error out
}
}
return Result.ok();
}
@ApiDoc(
method = PUT,
path = "/authz/userRole/role",
params = {},
expectedCode = 200,
errorCodes = {403,404,406},
text = { "Set a Role's users to the users specified in the UserRoleRequest object.",
"WARNING: Users supplied will be the ONLY users attached to this role",
"If no users are supplied, role's users are reset."
}
)
@Override
public Result<Void> resetUsersForRole(AuthzTrans trans, REQUEST rreq) {
Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq);
if(rurdd.notOKorIsEmpty()) {
return Result.err(rurdd);
}
final ServiceValidator v = new ServiceValidator();
if (v.user_role(rurdd.value).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
RoleDAO.Data rd = RoleDAO.Data.decode(rurdd.value);
Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rd, Access.write);
if (nsd.notOK()) {
return Result.err(nsd);
}
Result<NsDAO.Data> nsr = ques.deriveNs(trans, rurdd.value.role);
if(nsr.notOKorIsEmpty()) {
return Result.err(nsr);
}
Set<String> currUsers = new HashSet<String>();
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, rurdd.value.role);
if(rlurd.isOK()) {
for(UserRoleDAO.Data data : rlurd.value) {
currUsers.add(data.user);
}
}
// found when connected remotely to DEVL, can't replicate locally
// inconsistent errors with cmd: role user setTo [nothing]
// deleteUserRole --> read --> get --> cacheIdx(?)
// sometimes returns idx for last added user instead of user passed in
// cache bug?
Result<Void> rv = null;
String[] users = {};
if (rurdd.value.user != null) {
users = rurdd.value.user.split(",");
}
for (String user : users) {
if (v.user(trans.org(), user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
rurdd.value.user = user;
if(currUsers.contains(user)) {
currUsers.remove(user);
} else {
rv = func.addUserRole(trans, rurdd.value);
if (rv.notOK()) {
return rv;
}
}
}
for (String user : currUsers) {
rurdd.value.user = user;
rv = ques.userRoleDAO.delete(trans, rurdd.value, false);
if(rv.notOK()) {
trans.info().log(rurdd.value, "expected to be deleted, but not exists");
return rv;
}
}
return Result.ok();
}
@ApiDoc(
method = GET,
path = "/authz/userRole/extend/:user/:role",
params = { "user|string|true",
"role|string|true"
},
expectedCode = 200,
errorCodes = {403,404,406},
text = { "Extend the Expiration of this User Role by the amount set by Organization",
"Requestor must be allowed to modify the role"
}
)
@Override
public Result<Void> extendUserRole(AuthzTrans trans, String user, String role) {
Organization org = trans.org();
final ServiceValidator v = new ServiceValidator();
if(v.user(org, user)
.role(role)
.err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
if(rrdd.notOK()) {
return Result.err(rrdd);
}
Result<NsDAO.Data> rcr = ques.mayUser(trans, trans.user(), rrdd.value, Access.write);
boolean mayNotChange;
if((mayNotChange = rcr.notOK()) && !trans.requested(future)) {
return Result.err(rcr);
}
Result<List<UserRoleDAO.Data>> rr = ques.userRoleDAO.read(trans, user,role);
if(rr.notOK()) {
return Result.err(rr);
}
for(UserRoleDAO.Data userRole : rr.value) {
if(mayNotChange) { // Function exited earlier if !trans.futureRequested
FutureDAO.Data fto = new FutureDAO.Data();
fto.target=UserRoleDAO.TABLE;
fto.memo = "Extend User ["+userRole.user+"] in Role ["+userRole.role+"]";
GregorianCalendar now = new GregorianCalendar();
fto.start = now.getTime();
fto.expires = org.expiration(now, Expiration.Future).getTime();
try {
fto.construct = userRole.bytify();
} catch (IOException e) {
trans.error().log(e, "Error while bytifying UserRole for Future");
return Result.err(e);
}
Result<String> rfc = func.createFuture(trans, fto,
userRole.user+'|'+userRole.role, userRole.user, rcr.value, FUTURE_OP.U);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing",
userRole.user,
userRole.role);
} else {
return Result.err(rfc);
}
} else {
return func.extendUserRole(trans, userRole, false);
}
}
return Result.err(Result.ERR_NotFound,"This user and role doesn't exist");
}
@ApiDoc(
method = DELETE,
path = "/authz/userRole/:user/:role",
params = { "user|string|true",
"role|string|true"
},
expectedCode = 200,
errorCodes = {403,404,406},
text = { "Remove Role :role from User :user."
}
)
@Override
public Result<Void> deleteUserRole(AuthzTrans trans, String usr, String role) {
Validator val = new ServiceValidator();
if(val.nullOrBlank("User", usr)
.nullOrBlank("Role", role).err()) {
return Result.err(Status.ERR_BadData, val.errs());
}
boolean mayNotChange;
Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
if(rrdd.notOK()) {
return Result.err(rrdd);
}
RoleDAO.Data rdd = rrdd.value;
Result<NsDAO.Data> rns = ques.mayUser(trans, trans.user(), rdd, Access.write);
// Make sure we don't delete the last owner of valid NS
if(rns.isOKhasData() && Question.OWNER.equals(rdd.name) && ques.countOwner(trans,rdd.ns)<=1) {
return Result.err(Status.ERR_Denied,"You may not delete the last Owner of " + rdd.ns );
}
if(mayNotChange=rns.notOK()) {
if(!trans.requested(future)) {
return Result.err(rns);
}
}
Result<List<UserRoleDAO.Data>> rulr;
if((rulr=ques.userRoleDAO.read(trans, usr, role)).notOKorIsEmpty()) {
return Result.err(Status.ERR_UserRoleNotFound, "User [ "+usr+" ] is not "
+ "Assigned to the Role [ " + role + " ]");
}
UserRoleDAO.Data userRole = rulr.value.get(0);
if(mayNotChange) { // Function exited earlier if !trans.futureRequested
FutureDAO.Data fto = new FutureDAO.Data();
fto.target=UserRoleDAO.TABLE;
fto.memo = "Remove User ["+userRole.user+"] from Role ["+userRole.role+"]";
GregorianCalendar now = new GregorianCalendar();
fto.start = now.getTime();
fto.expires = trans.org().expiration(now, Expiration.Future).getTime();
Result<String> rfc = func.createFuture(trans, fto,
userRole.user+'|'+userRole.role, userRole.user, rns.value, FUTURE_OP.D);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing",
userRole.user,
userRole.role);
} else {
return Result.err(rfc);
}
} else {
return ques.userRoleDAO.delete(trans, rulr.value.get(0), false);
}
}
@ApiDoc(
method = GET,
path = "/authz/userRole/:user/:role",
params = {"user|string|true",
"role|string|true"},
expectedCode = 200,
errorCodes = {403,404,406},
text = { "Returns the User (with Expiration date from listed User/Role) if it exists"
}
)
@Override
public Result<USERS> getUserInRole(AuthzTrans trans, String user, String role) {
final Validator v = new ServiceValidator();
if(v.role(role).nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// Result<NsDAO.Data> ns = ques.deriveNs(trans, role);
// if (ns.notOK()) return Result.err(ns);
//
// Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write);
// May calling user see by virtue of the Role
Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
if(rrdd.notOK()) {
return Result.err(rrdd);
}
Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readUserInRole(trans, user, role);
if(rlurd.isOK()) {
for(UserRoleDAO.Data data : rlurd.value) {
userSet.add(data);
}
}
@SuppressWarnings("unchecked")
USERS users = (USERS) mapper.newInstance(API.USERS);
mapper.users(trans, userSet, users);
return Result.ok(users);
}
@ApiDoc(
method = GET,
path = "/authz/users/role/:role",
params = {"user|string|true",
"role|string|true"},
expectedCode = 200,
errorCodes = {403,404,406},
text = { "Returns the User (with Expiration date from listed User/Role) if it exists"
}
)
@Override
public Result<USERS> getUsersByRole(AuthzTrans trans, String role) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Role",role).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// Result<NsDAO.Data> ns = ques.deriveNs(trans, role);
// if (ns.notOK()) return Result.err(ns);
//
// Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write);
// May calling user see by virtue of the Role
Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
if(rrdd.notOK()) {
return Result.err(rrdd);
}
boolean contactOnly = false;
// Allow the request of any valid user to find the contact of the NS (Owner)
Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read);
if(rnd.notOK()) {
if(Question.OWNER.equals(rrdd.value.name)) {
contactOnly = true;
} else {
return Result.err(rnd);
}
}
HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role);
if(rlurd.isOK()) {
for(UserRoleDAO.Data data : rlurd.value) {
if(contactOnly) { //scrub data
// Can't change actual object, or will mess up the cache.
UserRoleDAO.Data scrub = new UserRoleDAO.Data();
scrub.ns = data.ns;
scrub.rname = data.rname;
scrub.role = data.role;
scrub.user = data.user;
userSet.add(scrub);
} else {
userSet.add(data);
}
}
}
@SuppressWarnings("unchecked")
USERS users = (USERS) mapper.newInstance(API.USERS);
mapper.users(trans, userSet, users);
return Result.ok(users);
}
/**
* getUsersByPermission
*/
@ApiDoc(
method = GET,
path = "/authz/users/perm/:type/:instance/:action",
params = { "type|string|true",
"instance|string|true",
"action|string|true"
},
expectedCode = 200,
errorCodes = {404,406},
text = { "List all Users that have Permission specified by :type :instance :action",
}
)
@Override
public Result<USERS> getUsersByPermission(AuthzTrans trans, String type, String instance, String action) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Type",type)
.nullOrBlank("Instance",instance)
.nullOrBlank("Action",action)
.err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<NsSplit> nss = ques.deriveNsSplit(trans, type);
if(nss.notOK()) {
return Result.err(nss);
}
Result<List<NsDAO.Data>> nsd = ques.nsDAO.read(trans, nss.value.ns);
if (nsd.notOK()) {
return Result.err(nsd);
}
boolean allInstance = ASTERIX.equals(instance);
boolean allAction = ASTERIX.equals(action);
// Get list of roles per Permission,
// Then loop through Roles to get Users
// Note: Use Sets to avoid processing or responding with Duplicates
Set<String> roleUsed = new HashSet<String>();
Set<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
if(!nss.isEmpty()) {
Result<List<PermDAO.Data>> rlp = ques.permDAO.readByType(trans, nss.value.ns, nss.value.name);
if(rlp.isOKhasData()) {
for(PermDAO.Data pd : rlp.value) {
if((allInstance || pd.instance.equals(instance)) &&
(allAction || pd.action.equals(action))) {
if(ques.mayUser(trans, trans.user(),pd,Access.read).isOK()) {
for(String role : pd.roles) {
if(!roleUsed.contains(role)) { // avoid evaluating Role many times
roleUsed.add(role);
Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role.replace('|', '.'));
if(rlurd.isOKhasData()) {
for(UserRoleDAO.Data urd : rlurd.value) {
userSet.add(urd);
}
}
}
}
}
}
}
}
}
@SuppressWarnings("unchecked")
USERS users = (USERS) mapper.newInstance(API.USERS);
mapper.users(trans, userSet, users);
return Result.ok(users);
}
/***********************************
* HISTORY
***********************************/
@Override
public Result<HISTORY> getHistoryByUser(final AuthzTrans trans, String user, final int[] yyyymm, final int sort) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("User",user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<NsDAO.Data> rnd;
// Users may look at their own data
if(trans.user().equals(user)) {
// Users may look at their own data
} else {
int at = user.indexOf('@');
if(at>=0 && trans.org().getRealm().equals(user.substring(at+1))) {
NsDAO.Data nsd = new NsDAO.Data();
nsd.name = Question.domain2ns(user);
rnd = ques.mayUser(trans, trans.user(), nsd, Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
} else {
rnd = ques.validNSOfDomain(trans, user);
if(rnd.notOK()) {
return Result.err(rnd);
}
rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
}
}
Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readByUser(trans, user, yyyymm);
if(resp.notOK()) {
return Result.err(resp);
}
return mapper.history(trans, resp.value,sort);
}
@Override
public Result<HISTORY> getHistoryByRole(AuthzTrans trans, String role, int[] yyyymm, final int sort) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Role",role).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
if(rrdd.notOK()) {
return Result.err(rrdd);
}
Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value, Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, role, "role", yyyymm);
if(resp.notOK()) {
return Result.err(resp);
}
return mapper.history(trans, resp.value,sort);
}
@Override
public Result<HISTORY> getHistoryByPerm(AuthzTrans trans, String type, int[] yyyymm, final int sort) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Type",type)
.err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
// May user see Namespace of Permission (since it's only one piece... we can't check for "is permission part of")
Result<NsDAO.Data> rnd = ques.deriveNs(trans,type);
if(rnd.notOK()) {
return Result.err(rnd);
}
rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, type, "perm", yyyymm);
if(resp.notOK()) {
return Result.err(resp);
}
return mapper.history(trans, resp.value,sort);
}
@Override
public Result<HISTORY> getHistoryByNS(AuthzTrans trans, String ns, int[] yyyymm, final int sort) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("NS",ns)
.err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
if(rnd.notOK()) {
return Result.err(rnd);
}
rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
if(rnd.notOK()) {
return Result.err(rnd);
}
Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, ns, "ns", yyyymm);
if(resp.notOK()) {
return Result.err(resp);
}
return mapper.history(trans, resp.value,sort);
}
/***********************************
* DELEGATE
***********************************/
@Override
public Result<Void> createDelegate(final AuthzTrans trans, REQUEST base) {
return createOrUpdateDelegate(trans, base, Question.Access.create);
}
@Override
public Result<Void> updateDelegate(AuthzTrans trans, REQUEST base) {
return createOrUpdateDelegate(trans, base, Question.Access.write);
}
private Result<Void> createOrUpdateDelegate(final AuthzTrans trans, REQUEST base, final Access access) {
final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base);
final ServiceValidator v = new ServiceValidator();
if(v.delegate(trans.org(),rd).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
final DelegateDAO.Data dd = rd.value;
Result<List<DelegateDAO.Data>> ddr = ques.delegateDAO.read(trans, dd);
if(access==Access.create && ddr.isOKhasData()) {
return Result.err(Status.ERR_ConflictAlreadyExists, "[%s] already delegates to [%s]", dd.user, ddr.value.get(0).delegate);
} else if(access!=Access.create && ddr.notOKorIsEmpty()) {
return Result.err(Status.ERR_NotFound, "[%s] does not have a Delegate Record to [%s].",dd.user,access.name());
}
Result<Void> rv = ques.mayUser(trans, dd, access);
if(rv.notOK()) {
return rv;
}
Result<FutureDAO.Data> fd = mapper.future(trans,DelegateDAO.TABLE,base, dd, false,
new Mapper.Memo() {
@Override
public String get() {
StringBuilder sb = new StringBuilder();
sb.append(access.name());
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
sb.append("Delegate ");
sb.append(access==Access.create?"[":"to [");
sb.append(rd.value.delegate);
sb.append("] for [");
sb.append(rd.value.user);
sb.append(']');
return sb.toString();
}
},
new MayChange() {
@Override
public Result<?> mayChange() {
return Result.ok(); // Validate in code above
}
});
switch(fd.status) {
case OK:
Result<String> rfc = func.createFuture(trans, fd.value,
dd.user, trans.user(),null, access==Access.create?FUTURE_OP.C:FUTURE_OP.U);
if(rfc.isOK()) {
return Result.err(Status.ACC_Future, "Delegate for [%s]",
dd.user);
} else {
return Result.err(rfc);
}
case Status.ACC_Now:
if(access==Access.create) {
Result<DelegateDAO.Data> rdr = ques.delegateDAO.create(trans, dd);
if(rdr.isOK()) {
return Result.ok();
} else {
return Result.err(rdr);
}
} else {
return ques.delegateDAO.update(trans, dd);
}
default:
return Result.err(fd);
}
}
@Override
public Result<Void> deleteDelegate(AuthzTrans trans, REQUEST base) {
final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base);
final Validator v = new ServiceValidator();
if(v.notOK(rd).nullOrBlank("User", rd.value.user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<DelegateDAO.Data>> ddl;
if((ddl=ques.delegateDAO.read(trans, rd.value)).notOKorIsEmpty()) {
return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate");
}
final DelegateDAO.Data dd = ddl.value.get(0);
Result<Void> rv = ques.mayUser(trans, dd, Access.write);
if(rv.notOK()) {
return rv;
}
return ques.delegateDAO.delete(trans, dd, false);
}
@Override
public Result<Void> deleteDelegate(AuthzTrans trans, String userName) {
DelegateDAO.Data dd = new DelegateDAO.Data();
final Validator v = new ServiceValidator();
if(v.nullOrBlank("User", userName).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
dd.user = userName;
Result<List<DelegateDAO.Data>> ddl;
if((ddl=ques.delegateDAO.read(trans, dd)).notOKorIsEmpty()) {
return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate");
}
dd = ddl.value.get(0);
Result<Void> rv = ques.mayUser(trans, dd, Access.write);
if(rv.notOK()) {
return rv;
}
return ques.delegateDAO.delete(trans, dd, false);
}
@Override
public Result<DELGS> getDelegatesByUser(AuthzTrans trans, String user) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
DelegateDAO.Data ddd = new DelegateDAO.Data();
ddd.user = user;
ddd.delegate = null;
Result<Void> rv = ques.mayUser(trans, ddd, Access.read);
if(rv.notOK()) {
return Result.err(rv);
}
TimeTaken tt = trans.start("Get delegates for a user", Env.SUB);
Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.read(trans, user);
try {
if (dbDelgs.isOKhasData()) {
return mapper.delegate(dbDelgs.value);
} else {
return Result.err(Status.ERR_DelegateNotFound,"No Delegate found for [%s]",user);
}
} finally {
tt.done();
}
}
@Override
public Result<DELGS> getDelegatesByDelegate(AuthzTrans trans, String delegate) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Delegate", delegate).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
DelegateDAO.Data ddd = new DelegateDAO.Data();
ddd.user = delegate;
Result<Void> rv = ques.mayUser(trans, ddd, Access.read);
if(rv.notOK()) {
return Result.err(rv);
}
TimeTaken tt = trans.start("Get users for a delegate", Env.SUB);
Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.readByDelegate(trans, delegate);
try {
if (dbDelgs.isOKhasData()) {
return mapper.delegate(dbDelgs.value);
} else {
return Result.err(Status.ERR_DelegateNotFound,"Delegate [%s] is not delegating for anyone.",delegate);
}
} finally {
tt.done();
}
}
/***********************************
* APPROVAL
***********************************/
private static final String APPR_FMT = "actor=%s, action=%s, operation=\"%s\", requestor=%s, delegator=%s";
@Override
public Result<Void> updateApproval(AuthzTrans trans, APPROVALS approvals) {
Result<List<ApprovalDAO.Data>> rlad = mapper.approvals(approvals);
if(rlad.notOK()) {
return Result.err(rlad);
}
int numApprs = rlad.value.size();
if(numApprs<1) {
return Result.err(Status.ERR_NoApprovals,"No Approvals sent for Updating");
}
int numProcessed = 0;
String user = trans.user();
Result<List<ApprovalDAO.Data>> curr;
Lookup<List<ApprovalDAO.Data>> apprByTicket=null;
for(ApprovalDAO.Data updt : rlad.value) {
if(updt.ticket!=null) {
curr = ques.approvalDAO.readByTicket(trans, updt.ticket);
if(curr.isOKhasData()) {
final List<ApprovalDAO.Data> add = curr.value;
apprByTicket = new Lookup<List<ApprovalDAO.Data>>() { // Store a Pre-Lookup
@Override
public List<ApprovalDAO.Data> get(AuthzTrans trans, Object ... noop) {
return add;
}
};
}
} else if(updt.id!=null) {
curr = ques.approvalDAO.read(trans, updt);
} else if(updt.approver!=null) {
curr = ques.approvalDAO.readByApprover(trans, updt.approver);
} else {
return Result.err(Status.ERR_BadData,"Approvals need ID, Ticket or Approval data to update");
}
if(curr.isOKhasData()) {
Map<String, Result<List<DelegateDAO.Data>>> delegateCache = new HashMap<String, Result<List<DelegateDAO.Data>>>();
Map<UUID, FutureDAO.Data> futureCache = new HashMap<UUID, FutureDAO.Data>();
FutureDAO.Data hasDeleted = new FutureDAO.Data();
for(ApprovalDAO.Data cd : curr.value) {
if("pending".equals(cd.status)) {
// Check for right record. Need ID, or (Ticket&Trans.User==Appr)
// If Default ID
boolean delegatedAction = ques.isDelegated(trans, user, cd.approver, delegateCache);
String delegator = cd.approver;
if(updt.id!=null ||
(updt.ticket!=null && user.equals(cd.approver)) ||
(updt.ticket!=null && delegatedAction)) {
if(updt.ticket.equals(cd.ticket)) {
Changed ch = new Changed();
cd.id = ch.changed(cd.id,updt.id);
// cd.ticket = changed(cd.ticket,updt.ticket);
cd.user = ch.changed(cd.user,updt.user);
cd.approver = ch.changed(cd.approver,updt.approver);
cd.type = ch.changed(cd.type,updt.type);
cd.status = ch.changed(cd.status,updt.status);
cd.memo = ch.changed(cd.memo,updt.memo);
cd.operation = ch.changed(cd.operation,updt.operation);
cd.updated = ch.changed(cd.updated,updt.updated==null?new Date():updt.updated);
if(updt.status.equals("denied")) {
cd.last_notified = null;
}
if(cd.ticket!=null) {
FutureDAO.Data fdd = futureCache.get(cd.ticket);
if(fdd==null) { // haven't processed ticket yet
Result<FutureDAO.Data> rfdd = ques.futureDAO.readPrimKey(trans, cd.ticket);
if(rfdd.isOK()) {
fdd = rfdd.value; // null is ok
} else {
fdd = hasDeleted;
}
futureCache.put(cd.ticket, fdd); // processed this Ticket... don't do others on this ticket
}
if(fdd==hasDeleted) { // YES, by Object
cd.ticket = null;
cd.status = "ticketDeleted";
ch.hasChanged(true);
} else {
FUTURE_OP fop = FUTURE_OP.toFO(cd.operation);
if(fop==null) {
trans.info().printf("Approval Status %s is not actionable",cd.status);
} else if(apprByTicket!=null) {
Result<OP_STATUS> rv = func.performFutureOp(trans, fop, fdd, apprByTicket,func.urDBLookup);
if (rv.isOK()) {
switch(rv.value) {
case E:
if (delegatedAction) {
trans.audit().printf(APPR_FMT,user,updt.status,cd.memo,cd.user,delegator);
}
futureCache.put(cd.ticket, hasDeleted);
break;
case D:
case L:
ch.hasChanged(true);
trans.audit().printf(APPR_FMT,user,rv.value.desc(),cd.memo,cd.user,delegator);
futureCache.put(cd.ticket, hasDeleted);
break;
default:
}
} else {
trans.info().log(rv.toString());
}
}
}
++numProcessed;
}
if(ch.hasChanged()) {
ques.approvalDAO.update(trans, cd, true);
}
}
}
}
}
}
}
if(numApprs==numProcessed) {
return Result.ok();
}
return Result.err(Status.ERR_ActionNotCompleted,numProcessed + " out of " + numApprs + " completed");
}
private static class Changed {
private boolean hasChanged = false;
public<T> T changed(T src, T proposed) {
if(proposed==null || (src!=null && src.equals(proposed))) {
return src;
}
hasChanged=true;
return proposed;
}
public void hasChanged(boolean b) {
hasChanged=b;
}
public boolean hasChanged() {
return hasChanged;
}
}
@Override
public Result<APPROVALS> getApprovalsByUser(AuthzTrans trans, String user) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("User", user).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByUser(trans, user);
if(rapd.isOK()) {
return mapper.approvals(rapd.value);
} else {
return Result.err(rapd);
}
}
@Override
public Result<APPROVALS> getApprovalsByTicket(AuthzTrans trans, String ticket) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Ticket", ticket).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
UUID uuid;
try {
uuid = UUID.fromString(ticket);
} catch (IllegalArgumentException e) {
return Result.err(Status.ERR_BadData,e.getMessage());
}
Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByTicket(trans, uuid);
if(rapd.isOK()) {
return mapper.approvals(rapd.value);
} else {
return Result.err(rapd);
}
}
@Override
public Result<APPROVALS> getApprovalsByApprover(AuthzTrans trans, String approver) {
final Validator v = new ServiceValidator();
if(v.nullOrBlank("Approver", approver).err()) {
return Result.err(Status.ERR_BadData,v.errs());
}
List<ApprovalDAO.Data> listRapds = new ArrayList<ApprovalDAO.Data>();
Result<List<ApprovalDAO.Data>> myRapd = ques.approvalDAO.readByApprover(trans, approver);
if(myRapd.notOK()) {
return Result.err(myRapd);
}
listRapds.addAll(myRapd.value);
Result<List<DelegateDAO.Data>> delegatedFor = ques.delegateDAO.readByDelegate(trans, approver);
if (delegatedFor.isOK()) {
for (DelegateDAO.Data dd : delegatedFor.value) {
if (dd.expires.after(new Date())) {
String delegator = dd.user;
Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByApprover(trans, delegator);
if (rapd.isOK()) {
for (ApprovalDAO.Data d : rapd.value) {
if (!d.user.equals(trans.user())) {
listRapds.add(d);
}
}
}
}
}
}
return mapper.approvals(listRapds);
}
/* (non-Javadoc)
* @see org.onap.aaf.auth.service.AuthzService#clearCache(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
*/
@Override
public Result<Void> cacheClear(AuthzTrans trans, String cname) {
if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) {
return ques.clearCache(trans,cname);
}
return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear",
trans.user(),ROOT_NS,CACHE,cname);
}
/* (non-Javadoc)
* @see org.onap.aaf.auth.service.AuthzService#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.Integer)
*/
@Override
public Result<Void> cacheClear(AuthzTrans trans, String cname, int[] segment) {
if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) {
Result<Void> v=null;
for(int i: segment) {
v=ques.cacheClear(trans,cname,i);
}
if(v!=null) {
return v;
}
}
return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear",
trans.user(),ROOT_NS,CACHE,cname);
}
/* (non-Javadoc)
* @see org.onap.aaf.auth.service.AuthzService#dbReset(org.onap.aaf.auth.env.test.AuthzTrans)
*/
@Override
public void dbReset(AuthzTrans trans) {
ques.historyDAO.reportPerhapsReset(trans, null);
}
}
|