[ee46bc]: / Allura / allura / tests / functional / test_auth.py  Maximize  Restore  History

Download this file

3058 lines (2660 with data), 137.5 kB

   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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import calendar
from base64 import b32encode
from datetime import datetime, time, timedelta
from time import time as time_time
import json
from urllib.parse import urlparse, parse_qs
from urllib.parse import urlencode
from bson import ObjectId
import re
from ming.odm.odmsession import ThreadLocalODMSession, session
from tg import config, expose
from mock import patch, Mock
import mock
import pytest
from tg import tmpl_context as c, app_globals as g
from allura.tests import TestController
from allura.tests import decorators as td
from allura.tests.decorators import audits, out_audits, assert_logmsg
from alluratest.controller import setup_trove_categories, TestRestApiBase, oauth1_webtest
from allura import model as M
from allura.model.oauth import dummy_oauths
from allura.lib import plugin
from allura.lib import helpers as h
from allura.lib.multifactor import TotpService, RecoveryCodeService
def unentity(s):
return s.replace('"', '"').replace('"', '"')
class TestAuth(TestController):
def test_login(self):
self.app.get('/auth/')
r = self.app.post('/auth/send_verification_link', params=dict(a='test@example.com',
_session_id=self.app.cookies['_session_id']))
email = M.User.query.get(username='test-admin').email_addresses[0]
r = self.app.post('/auth/send_verification_link', params=dict(a=email,
_session_id=self.app.cookies['_session_id']))
ThreadLocalODMSession.flush_all()
r = self.app.get('/auth/verify_addr', params=dict(a='foo'))
assert json.loads(self.webflash(r))['status'] == 'error', self.webflash(r)
ea = M.EmailAddress.find({'email': email}).first()
r = self.app.get('/auth/verify_addr', params=dict(a=ea.nonce))
assert json.loads(self.webflash(r))['status'] == 'ok', self.webflash(r)
r = self.app.get('/auth/logout')
with audits('Successful login', user=True):
r = self.app.post('/auth/do_login', params=dict(
username='test-user', password='foo',
_session_id=self.app.cookies['_session_id']),
antispam=True).follow()
assert r.headers['Location'] == 'http://localhost/dashboard'
r = self.app.post('/auth/do_login', antispam=True, params=dict(
username='test-user', password='foo', honey1='robot', # bad honeypot value
_session_id=self.app.cookies['_session_id']),
extra_environ={'regular_antispam_err_handling_even_when_tests': 'true'},
status=302)
wf = json.loads(self.webflash(r))
assert wf['status'] == 'error'
assert wf['message'] == 'Spambot protection engaged'
with audits('Failed login', user=True):
r = self.app.post('/auth/do_login', antispam=True, params=dict(
username='test-user', password='food',
_session_id=self.app.cookies['_session_id']))
assert 'Invalid login' in str(r), r.showbrowser()
r = self.app.post('/auth/do_login', antispam=True, params=dict(
username='test-usera', password='foo',
_session_id=self.app.cookies['_session_id']))
assert 'Invalid login' in str(r), r.showbrowser()
def test_login_invalid_username(self):
extra = {'username': '*anonymous'}
r = self.app.get('/auth/', extra_environ=extra)
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = 'test@user.com'
f[encoded['password']] = 'foo'
r = f.submit(extra_environ={'username': '*anonymous'})
r.mustcontain('Usernames only include small letters, ')
def test_login_diff_ips_ok(self):
# exercises AntiSpam.validate methods
extra = {'username': '*anonymous', 'REMOTE_ADDR': '11.22.33.44'}
r = self.app.get('/auth/', extra_environ=extra)
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = 'test-user'
f[encoded['password']] = 'foo'
with audits('Successful login', user=True):
r = f.submit(extra_environ={'username': '*anonymous', 'REMOTE_ADDR': '11.22.33.99'})
def test_login_diff_ips_bad(self):
# exercises AntiSpam.validate methods
extra = {'username': '*anonymous', 'REMOTE_ADDR': '24.52.32.123'}
r = self.app.get('/auth/', extra_environ=extra)
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = 'test-user'
f[encoded['password']] = 'foo'
r = f.submit(extra_environ={'username': '*anonymous', 'REMOTE_ADDR': '11.22.33.99',
'regular_antispam_err_handling_even_when_tests': 'true'},
status=302)
wf = json.loads(self.webflash(r))
assert wf['status'] == 'error'
assert wf['message'] == 'Spambot protection engaged'
@patch('allura.lib.plugin.AuthenticationProvider.hibp_password_check_enabled', Mock(return_value=True))
@patch('allura.tasks.mail_tasks.sendsimplemail')
def test_login_hibp_compromised_password_untrusted_client(self, sendsimplemail):
# first & only login by this user, so won't have any trusted previous logins
self.app.extra_environ = {'disable_auth_magic': 'True'}
r = self.app.get('/auth/')
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = 'test-user'
f[encoded['password']] = 'foo'
with audits('Attempted login from untrusted location with password in HIBP breach database', user=True):
r = f.submit(status=200)
r.mustcontain('reset your password via email.')
r.mustcontain('reset your password via email.<br>\nPlease check your email')
args, kwargs = sendsimplemail.post.call_args
assert sendsimplemail.post.call_count == 1
assert kwargs['subject'] == 'Update your %s password' % config['site_name']
assert '/auth/forgotten_password/' in kwargs['text']
assert [] == M.UserLoginDetails.query.find().all() # no records created
@patch('allura.tasks.mail_tasks.sendsimplemail')
def test_login_hibp_compromised_password_trusted_client(self, sendsimplemail):
self.app.extra_environ = {'disable_auth_magic': 'True'}
# regular login first, so IP address will be recorded and then trusted
r = self.app.get('/auth/')
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = 'test-user'
f[encoded['password']] = 'foo'
with audits('Successful login', user=True):
f.submit(status=302)
self.app.get('/auth/logout')
# this login will get caught by HIBP check, but trusted due to IP address being same
with patch('allura.lib.plugin.AuthenticationProvider.hibp_password_check_enabled', Mock(return_value=True)):
r = self.app.get('/auth/')
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = 'test-user'
f[encoded['password']] = 'foo'
with audits(r'Successful login with password in HIBP breach database, from trusted source '
r'\(reason: exact ip\)', user=True):
r = f.submit(status=302)
assert r.session.get('pwd-expired')
assert r.session.get('expired-reason') == 'hibp'
assert r.location == 'http://localhost/auth/pwd_expired'
r = r.follow()
r.mustcontain('must be updated to be more secure')
# changing password covered in TestPasswordExpire
def test_login_disabled(self):
u = M.User.query.get(username='test-user')
u.disabled = True
r = self.app.get('/auth/', extra_environ={'username': '*anonymous'})
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = 'test-user'
f[encoded['password']] = 'foo'
with audits('Failed login', user=True):
r = f.submit(extra_environ={'username': '*anonymous'})
def test_login_pending(self):
u = M.User.query.get(username='test-user')
u.pending = True
r = self.app.get('/auth/', extra_environ={'username': '*anonymous'})
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = 'test-user'
f[encoded['password']] = 'foo'
with audits('Failed login', user=True):
r = f.submit(extra_environ={'username': '*anonymous'})
def test_login_overlay(self):
r = self.app.get('/auth/login_fragment/', extra_environ={'username': '*anonymous'})
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = 'test-user'
f[encoded['password']] = 'foo'
with audits('Successful login', user=True):
r = f.submit(extra_environ={'username': '*anonymous'})
def test_logout(self):
self.app.extra_environ = {'disable_auth_magic': 'True'}
nav_pattern = ('nav', {'class': 'nav-main'})
r = self.app.get('/auth/')
r = self.app.post('/auth/do_login', params=dict(
username='test-user', password='foo',
_session_id=self.app.cookies['_session_id']),
extra_environ={'REMOTE_ADDR': '127.0.0.1'},
antispam=True).follow().follow()
logged_in_session = r.session['_id']
links = r.html.find(*nav_pattern).findAll('a')
assert links[-1].string == "Log Out"
r = self.app.get('/auth/logout').follow().follow()
logged_out_session = r.session['_id']
assert logged_in_session is not logged_out_session
links = r.html.find(*nav_pattern).findAll('a')
assert links[-1].string == 'Log In'
def test_track_login(self):
user = M.User.by_username('test-user')
assert user.last_access['login_date'] is None
assert user.last_access['login_ip'] is None
assert user.last_access['login_ua'] is None
self.app.get('/').follow() # establish session
self.app.post('/auth/do_login',
headers={'User-Agent': 'browser'},
extra_environ={'REMOTE_ADDR': '127.0.0.1'},
params=dict(
username='test-user',
password='foo',
_session_id=self.app.cookies['_session_id'],
),
antispam=True,
)
user = M.User.by_username('test-user')
assert user.last_access['login_date'] is not None
assert user.last_access['login_ip'] == '127.0.0.1'
assert user.last_access['login_ua'] == 'browser'
def test_rememberme(self):
username = M.User.query.get(username='test-user').username
r = self.app.get('/').follow() # establish session
# Login as test-user with remember me checkbox off
r = self.app.post('/auth/do_login', params=dict(
username='test-user', password='foo',
_session_id=self.app.cookies['_session_id'],
), antispam=True)
assert r.session['username'] == username
assert r.session['login_expires'] is True
for header, contents in r.headerlist:
if header == 'Set-cookie':
assert 'expires' not in contents
# Login as test-user with remember me checkbox on
r = self.app.post('/auth/do_login', params=dict(
username='test-user', password='foo', rememberme='on',
_session_id=self.app.cookies['_session_id'],
), antispam=True)
assert r.session['username'] == username
assert r.session['login_expires'] is not True
for header, contents in r.headerlist:
if header == 'Set-cookie':
assert 'expires' in contents
@td.with_user_project('test-admin')
def test_user_can_not_claim_duplicate_emails(self):
email_address = 'test_abcd_123@domain.net'
user = M.User.query.get(username='test-admin')
addresses_number = len(user.email_addresses)
self.app.get('/').follow() # establish session
self.app.post('/auth/preferences/update_emails',
params={
'new_addr.addr': email_address,
'new_addr.claim': 'Claim Address',
'primary_addr': 'test-admin@users.localhost',
'preferences.email_format': 'plain',
'password': 'foo',
'_session_id': self.app.cookies['_session_id'],
},
extra_environ=dict(username='test-admin'))
assert M.EmailAddress.find(dict(email=email_address, claimed_by_user_id=user._id)).count() == 1
r = self.app.post('/auth/preferences/update_emails',
params={
'new_addr.addr': email_address,
'new_addr.claim': 'Claim Address',
'primary_addr': 'test-admin@users.localhost',
'preferences.email_format': 'plain',
'password': 'foo',
'_session_id': self.app.cookies['_session_id'],
},
extra_environ=dict(username='test-admin'))
assert json.loads(self.webflash(r))['status'] == 'error', self.webflash(r)
assert M.EmailAddress.find(dict(email=email_address, claimed_by_user_id=user._id)).count() == 1
assert len(M.User.query.get(username='test-admin').email_addresses) == addresses_number + 1
@td.with_user_project('test-admin')
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_user_added_claimed_address_by_other_user_confirmed(self, gen_message_id, sendsimplemail):
self.app.get('/').follow() # establish session
email_address = 'test_abcd_123@domain.net'
# test-user claimed & confirmed email address
user = M.User.query.get(username='test-user')
user.claim_address(email_address)
email = M.EmailAddress.find(dict(email=email_address)).first()
email.confirmed = True
ThreadLocalODMSession.flush_all()
# Claiming the same email address by test-admin
# the email should be added to the email_addresses list but notifications should not be sent
admin = M.User.query.get(username='test-admin')
addresses_number = len(admin.email_addresses)
r = self.app.post('/auth/preferences/update_emails',
params={
'new_addr.addr': email_address,
'new_addr.claim': 'Claim Address',
'primary_addr': 'test-admin@users.localhost',
'preferences.email_format': 'plain',
'password': 'foo',
'_session_id': self.app.cookies['_session_id'],
},
extra_environ=dict(username='test-admin'))
assert json.loads(self.webflash(r))['status'] == 'ok'
assert json.loads(self.webflash(r))['message'] == 'A verification email has been sent. ' \
'Please check your email and click to confirm.'
args, kwargs = sendsimplemail.post.call_args
assert sendsimplemail.post.call_count == 1
assert kwargs['toaddr'] == email_address
assert kwargs['subject'] == '%s - Email address claim attempt' % config['site_name']
assert "You tried to add %s to your Allura account, " \
"but it is already claimed by your %s account." % (email_address, user.username) in kwargs['text']
assert len(M.User.query.get(username='test-admin').email_addresses) == addresses_number + 1
assert len(M.EmailAddress.find(dict(email=email_address)).all()) == 2
@td.with_user_project('test-admin')
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_user_added_claimed_address_by_other_user_not_confirmed(self, gen_message_id, sendsimplemail):
email_address = 'test_abcd_1235@domain.net'
# test-user claimed email address
user = M.User.query.get(username='test-user')
user.claim_address(email_address)
email = M.EmailAddress.find(dict(email=email_address)).first()
email.confirmed = False
ThreadLocalODMSession.flush_all()
# Claiming the same email address by test-admin
# the email should be added to the email_addresses list but notifications should not be sent
user1 = M.User.query.get(username='test-user-1')
addresses_number = len(user1.email_addresses)
self.app.get('/').follow() # establish session
r = self.app.post('/auth/preferences/update_emails',
params={
'new_addr.addr': email_address,
'new_addr.claim': 'Claim Address',
'primary_addr': 'test-user-1@users.localhost',
'preferences.email_format': 'plain',
'password': 'foo',
'_session_id': self.app.cookies['_session_id'],
},
extra_environ=dict(username='test-user-1'))
assert json.loads(self.webflash(r))['status'] == 'ok'
assert json.loads(self.webflash(r))['message'] == 'A verification email has been sent. ' \
'Please check your email and click to confirm.'
assert sendsimplemail.post.called
assert len(M.User.query.get(username='test-user-1').email_addresses) == addresses_number + 1
assert len(M.EmailAddress.find(dict(email=email_address)).all()) == 2
@td.with_user_project('test-admin')
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_user_cannot_claim_more_than_max_limit(self, gen_message_id, sendsimplemail):
with h.push_config(config, **{'user_prefs.maximum_claimed_emails': '2'}):
self.app.get('/').follow() # establish session
r = self.app.post('/auth/preferences/update_emails',
params={
'new_addr.addr': 'test_abcd_1@domain.net',
'new_addr.claim': 'Claim Address',
'primary_addr': 'test-user-1@users.localhost',
'preferences.email_format': 'plain',
'password': 'foo',
'_session_id': self.app.cookies['_session_id'],
},
extra_environ=dict(username='test-user-1'))
assert json.loads(self.webflash(r))['status'] == 'ok'
r = self.app.post('/auth/preferences/update_emails',
params={
'new_addr.addr': 'test_abcd_2@domain.net',
'new_addr.claim': 'Claim Address',
'primary_addr': 'test-user-1@users.localhost',
'preferences.email_format': 'plain',
'password': 'foo',
'_session_id': self.app.cookies['_session_id'],
},
extra_environ=dict(username='test-user-1'))
assert json.loads(self.webflash(r))['status'] == 'error'
assert json.loads(self.webflash(r))['message'] == 'You cannot claim more than 2 email addresses.'
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_verification_link_for_confirmed_email(self, gen_message_id, sendsimplemail):
self.app.get('/').follow() # establish session
email_address = 'test_abcd@domain.net'
# test-user claimed email address
user = M.User.query.get(username='test-user')
user.claim_address(email_address)
email = M.EmailAddress.find(dict(email=email_address, claimed_by_user_id=user._id)).first()
email.confirmed = True
user1 = M.User.query.get(username='test-user-1')
user1.claim_address(email_address)
email = M.EmailAddress.find(dict(email=email_address, claimed_by_user_id=user1._id)).first()
email.confirmed = False
ThreadLocalODMSession.flush_all()
r = self.app.post('/auth/send_verification_link',
params=dict(a=email_address, _session_id=self.app.cookies['_session_id']),
extra_environ=dict(username='test-user-1', _session_id=self.app.cookies['_session_id']))
assert json.loads(self.webflash(r))['status'] == 'ok'
assert json.loads(self.webflash(r))['message'] == 'Verification link sent'
args, kwargs = sendsimplemail.post.call_args
assert sendsimplemail.post.call_count == 1
assert kwargs['toaddr'] == email_address
assert kwargs['subject'] == '%s - Email address claim attempt' % config['site_name']
assert "You tried to add %s to your Allura account, " \
"but it is already claimed by your %s account." % (email_address, user.username) in kwargs['text']
def test_invalidate_verification_link_if_email_was_confirmed(self):
self.app.get('/').follow() # establish session
email_address = 'test_abcd@domain.net'
# test-user claimed email address
user = M.User.query.get(username='test-user')
user.claim_address(email_address)
email = M.EmailAddress.find(dict(email=email_address, claimed_by_user_id=user._id)).first()
email.confirmed = False
ThreadLocalODMSession.flush_all()
self.app.post('/auth/send_verification_link',
params=dict(a=email_address,
_session_id=self.app.cookies['_session_id']),
extra_environ=dict(username='test-user'))
user1 = M.User.query.get(username='test-user-1')
user1.claim_address(email_address)
email1 = M.EmailAddress.find(dict(email=email_address, claimed_by_user_id=user1._id)).first()
email1.confirmed = True
ThreadLocalODMSession.flush_all()
# Verify first email with the verification link
r = self.app.get('/auth/verify_addr', params=dict(a=email.nonce),
extra_environ=dict(username='test-user'))
assert json.loads(self.webflash(r))['status'] == 'error'
email = M.EmailAddress.find(dict(email=email_address, claimed_by_user_id=user._id)).first()
assert not email.confirmed
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_verify_addr_correct_session(self, gen_message_id, sendsimplemail):
self.app.get('/').follow() # establish session
email_address = 'test_abcd@domain.net'
# test-user claimed email address
user = M.User.query.get(username='test-user')
user.claim_address(email_address)
email = M.EmailAddress.find(dict(email=email_address, claimed_by_user_id=user._id)).first()
email.confirmed = False
ThreadLocalODMSession.flush_all()
self.app.post('/auth/send_verification_link',
params=dict(a=email_address,
_session_id=self.app.cookies['_session_id']),
extra_environ=dict(username='test-user'))
# logged out, gets redirected to login page
r = self.app.get('/auth/verify_addr', params=dict(a=email.nonce),
extra_environ=dict(username='*anonymous'))
assert '/auth/?return_to=%2Fauth%2Fverify_addr' in r.location
# logged in as someone else
r = self.app.get('/auth/verify_addr', params=dict(a=email.nonce),
extra_environ=dict(username='test-admin'))
assert '/auth/?return_to=%2Fauth%2Fverify_addr' in r.location
assert 'You must be logged in to the correct account' == json.loads(self.webflash(r))['message']
assert 'warning' == json.loads(self.webflash(r))['status']
# logged in as correct user
r = self.app.get('/auth/verify_addr', params=dict(a=email.nonce),
extra_environ=dict(username='test-user'))
assert 'confirmed' in json.loads(self.webflash(r))['message']
assert 'ok' == json.loads(self.webflash(r))['status']
# assert 'email added' notification email sent
args, kwargs = sendsimplemail.post.call_args
assert kwargs['toaddr'] == user._id
assert kwargs['subject'] == 'New Email Address Added'
@staticmethod
def _create_password_reset_hash():
""" Generates a password reset token for a given user.
:return: User object
:rtype: User
"""
# test-user claimed email address
user = M.User.by_username('test-admin')
user.set_tool_data('AuthPasswordReset',
hash="generated_hash_value",
hash_expiry="04-08-2020")
hash = user.get_tool_data('AuthPasswordReset', 'hash')
session(user).flush(user)
hash_expiry = user.get_tool_data('AuthPasswordReset', 'hash_expiry')
assert hash == 'generated_hash_value'
assert hash_expiry == '04-08-2020'
return user
@pytest.mark.parametrize(['change_params'], [
pytest.param({'new_addr.addr': 'test_abcd@domain.net', # Change primary address
'primary_addr': 'test@example.com'},
id='change_primary'),
pytest.param({'new_addr.addr': 'test@example.com', # Claim new address
'new_addr.claim': 'Claim Address',
'primary_addr': 'test-admin@users.localhost',
'password': 'foo',
'preferences.email_format': 'plain'},
id='claim_new'),
pytest.param({'addr-1.ord': '1', # remove test-admin@users.localhost
'addr-1.delete': 'on',
'addr-2.ord': '2',
'new_addr.addr': '',
'primary_addr': 'test-admin@users.localhost',
'password': 'foo',
'preferences.email_format': 'plain'},
id='remove_one'),
pytest.param({'addr-1.ord': '1', # Remove email
'addr-2.ord': '2',
'addr-2.delete': 'on',
'new_addr.addr': '',
'primary_addr': 'test-admin@users.localhost'},
id='remove_all'),
])
def test_email_change_invalidates_token(self, change_params):
""" Generates new token invalidation tests.
The tests cover: changing, claiming, updating, removing email addresses.
:returns: email_change_invalidates_token
"""
user = self._create_password_reset_hash()
session(user).flush(user)
self.app.get('/').follow() # establish session
change_params['_session_id'] = self.app.cookies['_session_id']
self.app.post('/auth/preferences/update_emails',
extra_environ=dict(username='test-admin'),
params=change_params)
u = M.User.by_username('test-admin')
print(u.get_tool_data('AuthPasswordReset', 'hash'))
assert u.get_tool_data('AuthPasswordReset', 'hash') == ''
assert u.get_tool_data('AuthPasswordReset', 'hash_expiry') == ''
@td.with_user_project('test-admin')
def test_change_password(self):
self.app.get('/').follow() # establish session
# Get and assert user with password reset token.
user = self._create_password_reset_hash()
old_pass = user.get_pref('password')
# Change password
with audits('Password changed', user=True):
self.app.post('/auth/preferences/change_password',
extra_environ=dict(username='test-admin'),
params={
'oldpw': 'foo',
'pw': 'asdfasdf',
'pw2': 'asdfasdf',
'_session_id': self.app.cookies['_session_id'],
})
# Confirm password was changed.
assert old_pass != user.get_pref('password')
# Confirm any existing tokens were reset.
assert user.get_tool_data('AuthPasswordReset', 'hash') == ''
assert user.get_tool_data('AuthPasswordReset', 'hash_expiry') == ''
# Confirm an email was sent
tasks = M.MonQTask.query.find(dict(task_name='allura.tasks.mail_tasks.sendsimplemail')).all()
assert len(tasks) == 1
assert tasks[0].kwargs['subject'] == 'Password Changed'
assert 'The password for your' in tasks[0].kwargs['text']
@patch('allura.lib.plugin.AuthenticationProvider.hibp_password_check_enabled', Mock(return_value=True))
@td.with_user_project('test-admin')
def test_change_password_hibp(self):
self.app.get('/').follow() # establish session
# Get and assert user with password reset token.
user = self._create_password_reset_hash()
old_pass = user.get_pref('password')
# Attempt change password with weak pwd
r = self.app.post('/auth/preferences/change_password',
extra_environ=dict(username='test-admin'),
params={
'oldpw': 'foo',
'pw': 'password',
'pw2': 'password',
'_session_id': self.app.cookies['_session_id'],
})
assert 'Unsafe' in str(r.headers)
r = self.app.post('/auth/preferences/change_password',
extra_environ=dict(username='test-admin'),
params={
'oldpw': 'foo',
'pw': '3j84rhoirwnoiwrnoiw',
'pw2': '3j84rhoirwnoiwrnoiw',
'_session_id': self.app.cookies['_session_id'],
})
assert 'Unsafe' not in str(r.headers)
# Confirm password was changed.
user = M.User.by_username('test-admin')
assert old_pass != user.get_pref('password')
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
@td.with_user_project('test-admin')
def test_prefs(self, gen_message_id, sendsimplemail):
r = self.app.get('/auth/preferences/',
extra_environ=dict(username='test-admin'))
# check preconditions of test data
assert 'test@example.com' not in r
assert 'test-admin@users.localhost' in r
assert (M.User.query.get(username='test-admin').get_pref('email_address') ==
'test-admin@users.localhost')
# add test@example
with td.audits('New email address: test@example.com', user=True):
r = self.app.post('/auth/preferences/update_emails',
extra_environ=dict(username='test-admin'),
params={
'new_addr.addr': 'test@example.com',
'new_addr.claim': 'Claim Address',
'primary_addr': 'test-admin@users.localhost',
'password': 'foo',
'preferences.email_format': 'plain',
'_session_id': self.app.cookies['_session_id'],
})
r = self.app.get('/auth/preferences/')
assert 'test@example.com' in r
user = M.User.query.get(username='test-admin')
assert user.get_pref('email_address') == 'test-admin@users.localhost'
# remove test-admin@users.localhost
with td.audits('Email address deleted: test-admin@users.localhost', user=True):
r = self.app.post('/auth/preferences/update_emails',
extra_environ=dict(username='test-admin'),
params={
'addr-1.ord': '1',
'addr-1.delete': 'on',
'addr-2.ord': '2',
'new_addr.addr': '',
'primary_addr': 'test-admin@users.localhost',
'password': 'foo',
'preferences.email_format': 'plain',
'_session_id': self.app.cookies['_session_id'],
})
# assert 'email_removed' notification email sent
args, kwargs = sendsimplemail.post.call_args
assert kwargs['toaddr'] == user._id
assert kwargs['subject'] == 'Email Address Removed'
r = self.app.get('/auth/preferences/')
assert 'test-admin@users.localhost' not in r
# preferred address has not changed if email is not verified
user = M.User.query.get(username='test-admin')
assert user.get_pref('email_address') is None
with td.audits('Display Name changed Test Admin => Admin', user=True):
r = self.app.post('/auth/preferences/update',
params={'preferences.display_name': 'Admin',
'_session_id': self.app.cookies['_session_id'],
},
extra_environ=dict(username='test-admin'))
@td.with_user_project('test-admin')
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_email_prefs_change_requires_password(self, gen_message_id, sendsimplemail):
self.app.get('/').follow() # establish session
# Claim new email
new_email_params = {
'new_addr.addr': 'test@example.com',
'new_addr.claim': 'Claim Address',
'primary_addr': 'test-admin@users.localhost',
'_session_id': self.app.cookies['_session_id'],
}
r = self.app.post('/auth/preferences/update_emails',
params=new_email_params,
extra_environ=dict(username='test-admin'))
assert 'You must provide your current password to claim new email' in self.webflash(r)
assert 'test@example.com' not in r.follow()
new_email_params['password'] = 'bad pass'
r = self.app.post('/auth/preferences/update_emails',
params=new_email_params,
extra_environ=dict(username='test-admin'))
assert 'You must provide your current password to claim new email' in self.webflash(r)
assert 'test@example.com' not in r.follow()
new_email_params['password'] = 'foo' # valid password
r = self.app.post('/auth/preferences/update_emails',
params=new_email_params,
extra_environ=dict(username='test-admin'))
assert 'You must provide your current password to claim new email' not in self.webflash(r)
assert 'test@example.com' in r.follow()
# Change primary address
change_primary_params = {
'new_addr.addr': '',
'primary_addr': 'test@example.com',
'_session_id': self.app.cookies['_session_id'],
}
r = self.app.post('/auth/preferences/update_emails',
params=change_primary_params,
extra_environ=dict(username='test-admin'))
assert 'You must provide your current password to change primary address' in self.webflash(r)
assert M.User.by_username('test-admin').get_pref('email_address') == 'test-admin@users.localhost'
change_primary_params['password'] = 'bad pass'
r = self.app.post('/auth/preferences/update_emails',
params=change_primary_params,
extra_environ=dict(username='test-admin'))
assert 'You must provide your current password to change primary address' in self.webflash(r)
assert M.User.by_username('test-admin').get_pref('email_address') == 'test-admin@users.localhost'
change_primary_params['password'] = 'foo' # valid password
self.app.get('/auth/preferences/') # let previous 'flash' message cookie get used up
r = self.app.post('/auth/preferences/update_emails',
params=change_primary_params,
extra_environ=dict(username='test-admin'))
assert 'You must provide your current password to change primary address' not in self.webflash(r)
assert M.User.by_username('test-admin').get_pref('email_address') == 'test@example.com'
# assert 'email added' notification email sent using original primary addr
args, kwargs = sendsimplemail.post.call_args
assert kwargs['toaddr'] == 'test-admin@users.localhost'
assert kwargs['subject'] == 'Primary Email Address Changed'
# Remove email
remove_email_params = {
'addr-1.ord': '1',
'addr-2.ord': '2',
'addr-2.delete': 'on',
'new_addr.addr': '',
'primary_addr': 'test-admin@users.localhost',
'_session_id': self.app.cookies['_session_id'],
}
r = self.app.post('/auth/preferences/update_emails',
params=remove_email_params,
extra_environ=dict(username='test-admin'))
assert 'You must provide your current password to delete an email' in self.webflash(r)
assert 'test@example.com' in r.follow()
remove_email_params['password'] = 'bad pass'
r = self.app.post('/auth/preferences/update_emails',
params=remove_email_params,
extra_environ=dict(username='test-admin'))
assert 'You must provide your current password to delete an email' in self.webflash(r)
assert 'test@example.com' in r.follow()
remove_email_params['password'] = 'foo' # vallid password
r = self.app.post('/auth/preferences/update_emails',
params=remove_email_params,
extra_environ=dict(username='test-admin'))
assert 'You must provide your current password to delete an email' not in self.webflash(r)
assert 'test@example.com' not in r.follow()
@td.with_user_project('test-admin')
def test_prefs_subscriptions(self):
r = self.app.get('/auth/subscriptions/',
extra_environ=dict(username='test-admin'))
subscriptions = M.Mailbox.query.find(dict(
user_id=c.user._id, is_flash=False)).all()
# make sure page actually lists all the user's subscriptions
assert len(subscriptions) > 0, 'Test user has no subscriptions, cannot verify that they are shown'
for m in subscriptions:
assert str(m._id) in r, "Page doesn't list subscription for Mailbox._id = %s" % m._id
# make sure page lists all tools which user can subscribe
user = M.User.query.get(username='test-admin')
for p in user.my_projects():
for ac in p.app_configs:
if not M.Mailbox.subscribed(project_id=p._id, app_config_id=ac._id):
if ac.tool_name in ('activity', 'admin', 'search', 'userstats', 'profile'):
# these have has_notifications=False
assert str(ac._id) not in r, "Page lists tool %s but it should not" % ac.tool_name
else:
assert str(ac._id) in r, "Page doesn't list tool %s" % ac.tool_name
@td.with_user_project('test-admin')
def test_update_user_notifications(self):
self.app.get('/').follow() # establish session
assert not M.User.query.get(username='test-admin').get_pref('mention_notifications')
self.app.post('/auth/subscriptions/update_user_notifications',
params={'_session_id': self.app.cookies['_session_id'],
})
assert not M.User.query.get(username='test-admin').get_pref('mention_notifications')
self.app.post('/auth/subscriptions/update_user_notifications',
params={'allow_umnotif': 'on',
'_session_id': self.app.cookies['_session_id'],
})
assert M.User.query.get(username='test-admin').get_pref('mention_notifications')
def _find_subscriptions_form(self, r):
form = None
for f in r.forms.values():
if f.action == 'update_subscriptions':
form = f
break
assert form is not None, "Can't find subscriptions form"
return form
def _find_subscriptions_field(self, form, subscribed=False):
field_name = None
for k, v in form.fields.items():
if subscribed:
check = v and v[0].value == 'on'
else:
check = v and v[0].value != 'on'
if k and k.endswith('.subscribed') and check:
field_name = k.replace('.subscribed', '')
assert field_name, "Can't find unsubscribed tool for user"
return field_name
@td.with_user_project('test-admin')
def test_prefs_subscriptions_subscribe(self):
resp = self.app.get('/auth/subscriptions/',
extra_environ=dict(username='test-admin'))
form = self._find_subscriptions_form(resp)
# find not subscribed tool, subscribe and verify
field_name = self._find_subscriptions_field(form, subscribed=False)
t_id = ObjectId(form.fields[field_name + '.tool_id'][0].value)
p_id = ObjectId(form.fields[field_name + '.project_id'][0].value)
subscribed = M.Mailbox.subscribed(project_id=p_id, app_config_id=t_id)
assert not subscribed, "User already subscribed for tool %s" % t_id
form.fields[field_name + '.subscribed'][0].value = 'on'
form.submit()
subscribed = M.Mailbox.subscribed(project_id=p_id, app_config_id=t_id)
assert subscribed, "User is not subscribed for tool %s" % t_id
@td.with_user_project('test-admin')
def test_prefs_subscriptions_unsubscribe(self):
resp = self.app.get('/auth/subscriptions/',
extra_environ=dict(username='test-admin'))
form = self._find_subscriptions_form(resp)
field_name = self._find_subscriptions_field(form, subscribed=True)
s_id = ObjectId(form.fields[field_name + '.subscription_id'][0].value)
s = M.Mailbox.query.get(_id=s_id)
assert s, "User has not subscription with Mailbox._id = %s" % s_id
form.fields[field_name + '.subscribed'][0].value = None
form.submit()
s = M.Mailbox.query.get(_id=s_id)
assert not s, "User still has subscription with Mailbox._id %s" % s_id
def test_format_email(self):
self.app.get('/').follow() # establish session
self.app.post('/auth/subscriptions/update_subscriptions',
params={'email_format': 'plain', 'subscriptions': '',
'_session_id': self.app.cookies['_session_id']})
r = self.app.get('/auth/subscriptions/')
assert '<option selected value="plain">Plain Text</option>' in r
self.app.post('/auth/subscriptions/update_subscriptions',
params={'email_format': 'both', 'subscriptions': '',
'_session_id': self.app.cookies['_session_id']})
r = self.app.get('/auth/subscriptions/')
assert '<option selected value="both">HTML</option>' in r
def test_create_account(self):
r = self.app.get('/auth/create_account')
assert 'Create an Account' in r
r = self.app.post('/auth/save_new',
params=dict(username='AAA', pw='123',
_session_id=self.app.cookies['_session_id']))
assert 'Enter a value 6 characters long or more' in r
assert ('Usernames must include only small letters, numbers, '
'and dashes. They must also start with a letter and be '
'at least 3 characters long.' in r)
r = self.app.post(
'/auth/save_new',
params=dict(
username='aaa',
pw='12345678',
pw2='12345678',
display_name='Test Me',
_session_id=self.app.cookies['_session_id'],
))
r = r.follow().follow()
assert 'User "aaa" registered' in unentity(r.text)
r = self.app.post(
'/auth/save_new',
params=dict(
username='aaa',
pw='12345678',
pw2='12345678',
display_name='Test Me',
_session_id=self.app.cookies['_session_id'],
))
assert 'That username is already taken. Please choose another.' in r
r = self.app.get('/auth/logout')
r = self.app.post(
'/auth/do_login',
params=dict(username='aaa', password='12345678',
_session_id=self.app.cookies['_session_id']), antispam=True,
status=302)
def test_create_account_require_email(self):
self.app.get('/').follow() # establish session
with h.push_config(config, **{'auth.require_email_addr': 'false'}):
self.app.post(
'/auth/save_new',
params=dict(
username='aaa',
pw='12345678',
pw2='12345678',
display_name='Test Me',
email='test@example.com',
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='aaa')
assert not user.pending
assert M.Project.query.find({'name': 'u/aaa'}).count() == 1
with h.push_config(config, **{'auth.require_email_addr': 'true'}):
self.app.post(
'/auth/save_new',
params=dict(
username='bbb',
pw='12345678',
pw2='12345678',
display_name='Test Me',
email='test@example.com',
_session_id=self.app.cookies['_session_id']
))
user = M.User.query.get(username='bbb')
assert user.pending
assert M.Project.query.find({'name': 'u/bbb'}).count() == 0
def test_verify_email(self):
with h.push_config(config, **{'auth.require_email_addr': 'true'}):
self.app.get('/').follow() # establish session
r = self.app.post(
'/auth/save_new',
params=dict(
username='aaa',
pw='12345678',
pw2='12345678',
display_name='Test Me',
email='test@example.com',
_session_id=self.app.cookies['_session_id']
))
r = r.follow()
user = M.User.query.get(username='aaa')
em = M.EmailAddress.get(email='test@example.com')
assert user._id == em.claimed_by_user_id
r = self.app.get('/auth/verify_addr', params=dict(a=em.nonce))
user = M.User.query.get(username='aaa')
em = M.EmailAddress.get(email='test@example.com')
assert not user.pending
assert em.confirmed
assert user.get_pref('email_address')
assert M.Project.query.find({'name': 'u/aaa'}).count() == 1
def test_create_account_disabled_header_link(self):
with h.push_config(config, **{'auth.allow_user_registration': 'false'}):
r = self.app.get('/')
assert 'Register' not in r
def test_create_account_disabled_form_gone(self):
with h.push_config(config, **{'auth.allow_user_registration': 'false'}):
r = self.app.get('/auth/create_account', status=404)
assert 'Create an Account' not in r
def test_create_account_disabled_submit_fails(self):
with h.push_config(config, **{'auth.allow_user_registration': 'false'}):
self.app.get('/').follow() # establish session
self.app.post('/auth/save_new',
params=dict(
username='aaa',
pw='12345678',
pw2='12345678',
display_name='Test Me',
_session_id=self.app.cookies['_session_id']
),
status=404)
def test_one_project_role(self):
"""Make sure when a user goes to a new project only one project role is created.
There was an issue with extra project roles getting created if a user went directly to
an admin page."""
p_nbhd = M.Neighborhood.query.get(name='Projects')
p = M.Project.query.get(shortname='test', neighborhood_id=p_nbhd._id)
self.app.get('/').follow() # establish session
self.app.post('/auth/save_new', params=dict(
username='aaa',
pw='12345678',
pw2='12345678',
display_name='Test Me',
email='test@example.com',
_session_id=self.app.cookies['_session_id'],
)).follow()
user = M.User.query.get(username='aaa')
user.pending = False
session(user).flush(user)
assert M.ProjectRole.query.find(
dict(user_id=user._id, project_id=p._id)).count() == 0
self.app.get('/p/test/admin/permissions',
extra_environ=dict(username='aaa'), status=403)
assert M.ProjectRole.query.find(
dict(user_id=user._id, project_id=p._id)).count() <= 1
def test_default_lookup(self):
# Make sure that default _lookup() throws 404
self.app.get('/auth/foobar', status=404)
def test_disabled_user(self):
user = M.User.query.get(username='test-admin')
sess = session(user)
assert not user.disabled
r = self.app.get('/p/test/admin/',
extra_environ={'username': 'test-admin'})
assert r.status_int == 200, 'Redirect to %s' % r.location
user.disabled = True
sess.save(user)
sess.flush()
user = M.User.query.get(username='test-admin')
assert user.disabled
r = self.app.get('/p/test/admin/',
extra_environ={'username': 'test-admin'})
assert r.status_int == 302
assert r.location == 'http://localhost/auth/?return_to=%2Fp%2Ftest%2Fadmin%2F'
def test_no_open_return_to(self):
r = self.app.get('/auth/logout').follow().follow()
r = self.app.post('/auth/do_login', params=dict(
username='test-user', password='foo',
return_to='/foo',
_session_id=self.app.cookies['_session_id']),
antispam=True
)
assert r.location == 'http://localhost/foo'
r = self.app.get('/auth/logout')
r = self.app.post('/auth/do_login', antispam=True, params=dict(
username='test-user', password='foo',
return_to='http://localhost/foo',
_session_id=self.app.cookies['_session_id']))
assert r.location == 'http://localhost/foo'
r = self.app.get('/auth/logout')
r = self.app.post('/auth/do_login', antispam=True, params=dict(
username='test-user', password='foo',
return_to='http://example.com/foo',
_session_id=self.app.cookies['_session_id'])).follow()
assert r.location == 'http://localhost/dashboard'
r = self.app.get('/auth/logout')
r = self.app.post('/auth/do_login', antispam=True, params=dict(
username='test-user', password='foo',
return_to='//example.com/foo',
_session_id=self.app.cookies['_session_id'])).follow()
assert r.location == 'http://localhost/dashboard'
def test_no_injected_headers_in_return_to(self):
r = self.app.get('/auth/logout').follow().follow()
r = self.app.post('/auth/do_login', params=dict(
username='test-user', password='foo',
return_to='/foo\nContent-Length: 777',
# WebTest actually will raise an error if there's an invalid header (webob itself does not)
_session_id=self.app.cookies['_session_id']),
antispam=True
)
assert r.location == 'http://localhost/'
assert r.content_length != 777
class TestAuthRest(TestRestApiBase):
def test_tools_list_anon(self):
resp = self.api_get('/rest/auth/tools/wiki', user='*anonymous')
assert resp.json == {
'tools': []
}
def test_tools_list_invalid_tool(self):
resp = self.api_get('/rest/auth/tools/af732q9547235')
assert resp.json == {
'tools': []
}
@td.with_tool('test', 'Wiki', mount_point='docs', mount_label='Documentation')
def test_tools_list_wiki(self):
resp = self.api_get('/rest/auth/tools/wiki')
assert resp.json == {
'tools': [
{
'mount_label': 'Wiki',
'mount_point': 'wiki',
'name': 'wiki',
'project_name': 'Home Project for Adobe',
'url': 'http://localhost/adobe/wiki/',
'api_url': 'http://localhost/rest/adobe/wiki/',
},
{
'mount_label': 'Documentation',
'mount_point': 'docs',
'name': 'wiki',
'project_name': 'Test Project',
'url': 'http://localhost/p/test/docs/',
'api_url': 'http://localhost/rest/p/test/docs/',
},
]
}
class TestPreferences(TestController):
@td.with_user_project('test-admin')
def test_personal_data(self):
from pytz import country_names
setsex, setbirthdate, setcountry, setcity, settimezone = \
('Male', '19/08/1988', 'IT', 'Milan', 'Europe/Rome')
self.app.get('/auth/user_info/')
# Check if personal data is properly set
r = self.app.post('/auth/user_info/change_personal_data',
params=dict(
sex=setsex,
birthdate=setbirthdate,
country=setcountry,
city=setcity,
timezone=settimezone,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
sex = user.sex
assert sex == setsex
birthdate = user.birthdate.strftime('%d/%m/%Y')
assert birthdate == setbirthdate
country = user.localization.country
assert country_names.get(setcountry) == country
city = user.localization.city
assert city == setcity
timezone = user.timezone
assert timezone == settimezone
# Check if setting a wrong date everything works correctly
r = self.app.post('/auth/user_info/change_personal_data',
params=dict(birthdate='30/02/1998', _session_id=self.app.cookies['_session_id']))
assert 'Please enter a valid date' in r.text
user = M.User.query.get(username='test-admin')
sex = user.sex
assert sex == setsex
birthdate = user.birthdate.strftime('%d/%m/%Y')
assert birthdate == setbirthdate
country = user.localization.country
assert country_names.get(setcountry) == country
city = user.localization.city
assert city == setcity
timezone = user.timezone
assert timezone == settimezone
# Check deleting birthdate
r = self.app.post('/auth/user_info/change_personal_data',
params=dict(
sex=setsex,
birthdate='',
country=setcountry,
city=setcity,
timezone=settimezone,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert user.birthdate is None
@td.with_user_project('test-admin')
def test_contacts_not_allowed(self):
self.app.get('/auth/user_info/')
socialnetwork = 'Facebook'
accounturl = 'http://www.faceboookk.com/test'
self.app.post('/auth/user_info/contacts/add_social_network',
params=dict(socialnetwork=socialnetwork,
accounturl=accounturl,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.socialnetworks) == 0
socialnetwork = 'Instagram'
accounturl = 'http://www.insta.com/test'
self.app.post('/auth/user_info/contacts/add_social_network',
params=dict(socialnetwork=socialnetwork,
accounturl=accounturl,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.socialnetworks) == 0
socialnetwork = 'Mastodon'
accounturl = '@username@server'
self.app.post('/auth/user_info/contacts/add_social_network',
params=dict(socialnetwork=socialnetwork,
accounturl=accounturl,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.socialnetworks) == 0
@td.with_user_project('test-admin')
def test_contacts(self):
# Add skype account
testvalue = 'testaccount'
self.app.get('/auth/user_info/contacts/')
self.app.post('/auth/user_info/contacts/skype_account',
params=dict(skypeaccount=testvalue, _session_id=self.app.cookies['_session_id']))
user = M.User.query.get(username='test-admin')
assert user.skypeaccount == testvalue
# Add social network account
socialnetwork = 'Facebook'
accounturl = 'http://www.facebook.com/test'
self.app.post('/auth/user_info/contacts/add_social_network',
params=dict(socialnetwork=socialnetwork,
accounturl=accounturl,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.socialnetworks) == 1
assert user.socialnetworks[0].socialnetwork == socialnetwork
assert user.socialnetworks[0].accounturl == accounturl
# Add second social network account
socialnetwork2 = 'Twitter'
accounturl2 = 'https://twitter.com/test'
self.app.post('/auth/user_info/contacts/add_social_network',
params=dict(socialnetwork=socialnetwork2,
accounturl='@test',
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.socialnetworks) == 2
expected = [{'socialnetwork': socialnetwork, 'accounturl': accounturl},
{'socialnetwork': socialnetwork2, 'accounturl': accounturl2}]
assert all([social in expected for social in user.socialnetworks])
socialnetwork3 = 'Mastodon'
accounturl3 = '@username@server.social'
self.app.post('/auth/user_info/contacts/add_social_network',
params=dict(socialnetwork=socialnetwork3,
accounturl=accounturl3,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.socialnetworks) == 3
# Remove first social network account
self.app.post('/auth/user_info/contacts/remove_social_network',
params=dict(socialnetwork=socialnetwork,
account=accounturl,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.socialnetworks) == 2
expected = [{'socialnetwork': socialnetwork2, 'accounturl': accounturl2},
{'socialnetwork': socialnetwork3, 'accounturl': accounturl3}]
assert all([social in expected for social in user.socialnetworks])
# Add empty social network account
self.app.post('/auth/user_info/contacts/add_social_network',
params=dict(accounturl=accounturl, socialnetwork='',
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.socialnetworks) == 2
expected = [{'socialnetwork': socialnetwork2, 'accounturl': accounturl2},
{'socialnetwork': socialnetwork3, 'accounturl': accounturl3}]
assert all([social in expected for social in user.socialnetworks])
# Add invalid social network account
self.app.post('/auth/user_info/contacts/add_social_network',
params=dict(accounturl=accounturl, socialnetwork='invalid',
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.socialnetworks) == 2
expected = [{'socialnetwork': socialnetwork2, 'accounturl': accounturl2},
{'socialnetwork': socialnetwork3, 'accounturl': accounturl3}]
assert all([social in expected for social in user.socialnetworks])
# Add telephone number
telnumber = '+3902123456'
self.app.post('/auth/user_info/contacts/add_telnumber',
params=dict(newnumber=telnumber,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert (len(user.telnumbers) == 1 and (user.telnumbers[0] == telnumber))
# Add second telephone number
telnumber2 = '+3902654321'
self.app.post('/auth/user_info/contacts/add_telnumber',
params=dict(newnumber=telnumber2,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert (len(user.telnumbers) == 2 and telnumber in user.telnumbers and telnumber2 in user.telnumbers)
# Remove first telephone number
self.app.post('/auth/user_info/contacts/remove_telnumber',
params=dict(oldvalue=telnumber,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert (len(user.telnumbers) == 1 and telnumber2 in user.telnumbers)
# Add website
website = 'http://www.testurl.com'
self.app.post('/auth/user_info/contacts/add_webpage',
params=dict(newwebsite=website,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert (len(user.webpages) == 1 and (website in user.webpages))
# Add second website
website2 = 'http://www.testurl2.com'
self.app.post('/auth/user_info/contacts/add_webpage',
params=dict(newwebsite=website2,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert (len(user.webpages) == 2 and website in user.webpages and website2 in user.webpages)
# Remove first website
self.app.post('/auth/user_info/contacts/remove_webpage',
params=dict(oldvalue=website,
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert (len(user.webpages) == 1 and website2 in user.webpages)
@td.with_user_project('test-admin')
def test_availability(self):
# Add availability timeslot
weekday = 'Monday'
starttime = time(9, 0, 0)
endtime = time(12, 0, 0)
self.app.get('/auth/user_info/availability/')
r = self.app.post('/auth/user_info/availability/add_timeslot',
params=dict(
weekday=weekday,
starttime=starttime.strftime('%H:%M'),
endtime=endtime.strftime('%H:%M'),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
timeslot1dict = dict(week_day=weekday, start_time=starttime, end_time=endtime)
assert len(user.availability) == 1 and timeslot1dict in user.get_availability_timeslots()
weekday2 = 'Tuesday'
starttime2 = time(14, 0, 0)
endtime2 = time(16, 0, 0)
# Add second availability timeslot
r = self.app.post('/auth/user_info/availability/add_timeslot',
params=dict(
weekday=weekday2,
starttime=starttime2.strftime('%H:%M'),
endtime=endtime2.strftime('%H:%M'),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
timeslot2dict = dict(week_day=weekday2, start_time=starttime2, end_time=endtime2)
assert len(user.availability) == 2
assert timeslot1dict in user.get_availability_timeslots()
assert timeslot2dict in user.get_availability_timeslots()
# Remove availability timeslot
r = self.app.post('/auth/user_info/availability/remove_timeslot',
params=dict(
weekday=weekday,
starttime=starttime.strftime('%H:%M'),
endtime=endtime.strftime('%H:%M'),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.availability) == 1 and timeslot2dict in user.get_availability_timeslots()
# Add invalid availability timeslot
r = self.app.post('/auth/user_info/availability/add_timeslot',
params=dict(
weekday=weekday2,
starttime=endtime2.strftime('%H:%M'),
endtime=starttime2.strftime('%H:%M'),
_session_id=self.app.cookies['_session_id'],
))
assert 'Invalid period:' in str(r)
user = M.User.query.get(username='test-admin')
timeslot2dict = dict(week_day=weekday2, start_time=starttime2, end_time=endtime2)
assert len(user.availability) == 1 and timeslot2dict in user.get_availability_timeslots()
@td.with_user_project('test-admin')
def test_inactivity(self):
# Add inactivity period
now = datetime.utcnow().date()
now = datetime(now.year, now.month, now.day)
startdate = now + timedelta(days=1)
enddate = now + timedelta(days=7)
self.app.get('/auth/user_info/availability/')
r = self.app.post('/auth/user_info/availability/add_inactive_period',
params=dict(
startdate=startdate.strftime('%d/%m/%Y'),
enddate=enddate.strftime('%d/%m/%Y'),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
period1dict = dict(start_date=startdate, end_date=enddate)
assert len(user.inactiveperiod) == 1 and period1dict in user.get_inactive_periods()
# Add second inactivity period
startdate2 = now + timedelta(days=24)
enddate2 = now + timedelta(days=28)
r = self.app.post('/auth/user_info/availability/add_inactive_period',
params=dict(
startdate=startdate2.strftime('%d/%m/%Y'),
enddate=enddate2.strftime('%d/%m/%Y'),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
period2dict = dict(start_date=startdate2, end_date=enddate2)
assert len(user.inactiveperiod) == 2
assert period1dict in user.get_inactive_periods()
assert period2dict in user.get_inactive_periods()
# Remove first inactivity period
r = self.app.post(
'/auth/user_info/availability/remove_inactive_period',
params=dict(
startdate=startdate.strftime('%d/%m/%Y'),
enddate=enddate.strftime('%d/%m/%Y'),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.inactiveperiod) == 1 and period2dict in user.get_inactive_periods()
# Add invalid inactivity period
r = self.app.post('/auth/user_info/availability/add_inactive_period',
params=dict(
startdate='NOT/A/DATE',
enddate=enddate2.strftime('%d/%m/%Y'),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert 'Please enter a valid date' in str(r)
assert len(user.inactiveperiod) == 1 and period2dict in user.get_inactive_periods()
@td.with_user_project('test-admin')
def test_skills(self):
setup_trove_categories()
# Add a skill
skill_cat = M.TroveCategory.query.get(show_as_skill=True)
level = 'low'
comment = 'test comment'
self.app.get('/auth/user_info/skills/')
self.app.post('/auth/user_info/skills/save_skill',
params=dict(
level=level,
comment=comment,
selected_skill=str(skill_cat.trove_cat_id),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
skilldict = dict(category_id=skill_cat._id,
comment=comment, level=level)
assert len(user.skills) == 1 and skilldict in user.skills
# Add again the same skill
level = 'medium'
comment = 'test comment 2'
self.app.get('/auth/user_info/skills/')
self.app.post('/auth/user_info/skills/save_skill',
params=dict(
level=level,
comment=comment,
selected_skill=str(skill_cat.trove_cat_id),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
skilldict = dict(category_id=skill_cat._id,
comment=comment, level=level)
assert len(user.skills) == 1 and skilldict in user.skills
# Add an invalid skill
level2 = 'not a level'
comment2 = 'test comment 2'
self.app.post('/auth/user_info/skills/save_skill',
params=dict(
level=level2,
comment=comment2,
selected_skill=str(skill_cat.trove_cat_id),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
# Check that everything is as it was before
assert len(user.skills) == 1 and skilldict in user.skills
# Remove a skill
self.app.get('/auth/user_info/skills/')
self.app.post('/auth/user_info/skills/remove_skill',
params=dict(
categoryid=str(skill_cat.trove_cat_id),
_session_id=self.app.cookies['_session_id'],
))
user = M.User.query.get(username='test-admin')
assert len(user.skills) == 0
@td.with_user_project('test-admin')
def test_user_message(self):
self.app.get('/').follow() # establish session
assert not M.User.query.get(username='test-admin').get_pref('disable_user_messages')
self.app.post('/auth/preferences/user_message',
params={'_session_id': self.app.cookies['_session_id'],
})
assert M.User.query.get(username='test-admin').get_pref('disable_user_messages')
self.app.post('/auth/preferences/user_message',
params={'allow_user_messages': 'on',
'_session_id': self.app.cookies['_session_id'],
})
assert not M.User.query.get(username='test-admin').get_pref('disable_user_messages')
@td.with_user_project('test-admin')
def test_additional_page(self):
class MyPP(plugin.UserPreferencesProvider):
def not_page(self):
return 'not page'
@expose()
def new_page(self):
return 'new page'
with mock.patch.object(plugin.UserPreferencesProvider, 'get') as upp_get:
upp_get.return_value = MyPP()
r = self.app.get('/auth/new_page')
assert r.text == 'new page'
self.app.get('/auth/not_page', status=404)
class TestPasswordReset(TestController):
test_primary_email = 'testprimaryaddr@mail.com'
def setup_method(self, method):
super().setup_method(method)
# so test-admin isn't automatically logged in for all requests
self.app.extra_environ = {'disable_auth_magic': 'True'}
@patch('allura.model.User.send_password_reset_email')
@patch('allura.lib.plugin.LocalAuthenticationProvider.resend_verification_link')
@patch('allura.tasks.mail_tasks.sendmail')
@patch('allura.lib.helpers.gen_message_id')
def test_email_unconfirmed(self, gen_message_id, sendmail, p_sendlink, p_sendpwd):
user = M.User.query.get(username='test-admin')
user.pending = True
email = M.EmailAddress.find(
{'claimed_by_user_id': user._id}).first()
email.confirmed = False
ThreadLocalODMSession.flush_all()
self.app.get('/').follow() # establish session
self.app.post('/auth/password_recovery_hash', {'email': email.email,
'_session_id': self.app.cookies['_session_id'],
})
hash = user.get_tool_data('AuthPasswordReset', 'hash')
assert hash is None
p_sendlink.assert_called_once()
p_sendpwd.assert_not_called()
@patch('allura.tasks.mail_tasks.sendmail')
@patch('allura.lib.helpers.gen_message_id')
def test_user_disabled(self, gen_message_id, sendmail):
user = M.User.query.get(username='test-admin')
email = M.EmailAddress.find(
{'claimed_by_user_id': user._id}).first()
user.disabled = True
ThreadLocalODMSession.flush_all()
self.app.get('/').follow() # establish session
self.app.post('/auth/password_recovery_hash', {'email': email.email,
'_session_id': self.app.cookies['_session_id'],
})
hash = user.get_tool_data('AuthPasswordReset', 'hash')
assert hash is None
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_only_primary_email_reset_allowed(self, gen_message_id, sendmail):
self.app.get('/').follow() # establish session
user = M.User.query.get(username='test-admin')
user.claim_address(self.test_primary_email)
user.set_pref('email_address', self.test_primary_email)
email = M.EmailAddress.find({'email': self.test_primary_email}).first()
email.confirmed = True
ThreadLocalODMSession.flush_all()
with h.push_config(config, **{'auth.allow_non_primary_email_password_reset': 'false'}):
self.app.post('/auth/password_recovery_hash', {'email': self.test_primary_email,
'_session_id': self.app.cookies['_session_id'],
})
hash = user.get_tool_data('AuthPasswordReset', 'hash')
assert hash is not None
args, kwargs = sendmail.post.call_args
assert kwargs['toaddr'] == self.test_primary_email
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_non_primary_email_reset_allowed(self, gen_message_id, sendmail):
self.app.get('/').follow() # establish session
user = M.User.query.get(username='test-admin')
email1 = M.EmailAddress.find({'claimed_by_user_id': user._id}).first()
user.claim_address(self.test_primary_email)
user.set_pref('email_address', self.test_primary_email)
email = M.EmailAddress.find({'email': self.test_primary_email}).first()
email.confirmed = True
ThreadLocalODMSession.flush_all()
with h.push_config(config, **{'auth.allow_non_primary_email_password_reset': 'true'}):
self.app.post('/auth/password_recovery_hash', {'email': email1.email,
'_session_id': self.app.cookies['_session_id'],
})
hash = user.get_tool_data('AuthPasswordReset', 'hash')
assert hash is not None
args, kwargs = sendmail.post.call_args
assert kwargs['toaddr'] == email1.email
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_password_reset(self, gen_message_id, sendsimplemail):
self.app.get('/').follow() # establish session
user = M.User.query.get(username='test-admin')
email = M.EmailAddress.find({'claimed_by_user_id': user._id}).first()
email.confirmed = True
ThreadLocalODMSession.flush_all()
old_pw_hash = user.password
# request a reset
with td.audits('Password recovery link sent to: ' + email.email, user=True):
r = self.app.post('/auth/password_recovery_hash', {'email': email.email,
'_session_id': self.app.cookies['_session_id'],
})
# confirm some fields
hash = user.get_tool_data('AuthPasswordReset', 'hash')
hash_expiry = user.get_tool_data('AuthPasswordReset', 'hash_expiry')
assert hash is not None
assert hash_expiry is not None
# confirm email sent
text = '''Your username is test-admin
To update your password on %s, please visit the following URL:
%s/auth/forgotten_password/%s''' % (config['site_name'], config['base_url'], hash)
sendsimplemail.post.assert_called_once_with(
sender='noreply@localhost',
toaddr=email.email,
fromaddr='"{}" <{}>'.format(config['site_name'], config['forgemail.return_path']),
reply_to=config['forgemail.return_path'],
subject='Allura Password recovery',
message_id=gen_message_id(),
text=text)
# load reset form and fill it out
r = self.app.get('/auth/forgotten_password/%s' % hash)
assert 'Enter a new password for: test-admin' in r
assert 'New Password:' in r
assert 'New Password (again):' in r
form = r.forms[0]
form['pw'] = form['pw2'] = new_password = '154321'
with td.audits(r'Password changed \(through recovery process\)', user=True):
# escape parentheses, so they would not be treated as regex group
r = form.submit()
# verify 'Password Changed' email sent
args, kwargs = sendsimplemail.post.call_args
assert kwargs['toaddr'] == user._id
assert kwargs['subject'] == 'Password Changed'
# confirm password changed and works
user = M.User.query.get(username='test-admin')
assert old_pw_hash != user.password
provider = plugin.LocalAuthenticationProvider(None)
assert provider._validate_password(user, new_password)
# confirm reset fields cleared
user = M.User.query.get(username='test-admin')
hash = user.get_tool_data('AuthPasswordReset', 'hash')
hash_expiry = user.get_tool_data('AuthPasswordReset', 'hash_expiry')
assert hash == ''
assert hash_expiry == ''
# confirm can log in now in same session
r = r.follow()
assert 'Log Out' not in r, r
form = r.forms[0]
encoded = self.app.antispam_field_names(r.form)
form[encoded['username']] = 'test-admin'
form[encoded['password']] = new_password
r = form.submit(status=302)
r = r.follow().follow()
assert 'Log Out' in r, r
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_capitalized_email_entered(self, gen_message_id, sendmail):
self.app.get('/').follow() # establish session
user = M.User.query.get(username='test-admin')
email = M.EmailAddress.find({'claimed_by_user_id': user._id}).first()
email.confirmed = True
ThreadLocalODMSession.flush_all()
# request a reset
with td.audits('Password recovery link sent to: ' + email.email, user=True):
r = self.app.post('/auth/password_recovery_hash', {'email': email.email.capitalize(), # NOTE THIS
'_session_id': self.app.cookies['_session_id'],
})
# confirm it worked
hash = user.get_tool_data('AuthPasswordReset', 'hash')
assert hash is not None
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_hash_expired(self, gen_message_id, sendmail):
user = M.User.query.get(username='test-admin')
email = M.EmailAddress.find(
{'claimed_by_user_id': user._id}).first()
email.confirmed = True
ThreadLocalODMSession.flush_all()
self.app.get('/').follow() # establish session
r = self.app.post('/auth/password_recovery_hash', {'email': email.email,
'_session_id': self.app.cookies['_session_id'],
})
user = M.User.by_username('test-admin')
hash = user.get_tool_data('AuthPasswordReset', 'hash')
user.set_tool_data('AuthPasswordReset',
hash_expiry=datetime(2000, 10, 10))
r = self.app.get('/auth/forgotten_password/%s' % hash)
assert 'Password reset link is invalid or expired' in r.follow().follow().text
r = self.app.post('/auth/set_new_password/%s' %
hash.encode('utf-8'), {'pw': '154321', 'pw2': '154321',
'_session_id': self.app.cookies['_session_id'],
})
assert 'Unable to process password reset' in r.follow().follow().text
def test_hash_invalid(self):
r = self.app.get('/auth/forgotten_password/123412341234', status=302)
assert 'Unable to process password reset' in r.follow().follow().text
@patch('allura.lib.plugin.AuthenticationProvider')
def test_provider_disabled(self, AP):
user = M.User.query.get(username='test-admin')
ap = AP.get()
ap.forgotten_password_process = False
ap.authenticate_request()._id = user._id
ap.by_username().username = user.username
self.app.get('/auth/forgotten_password', status=404)
self.app.get('/').follow() # establish session
self.app.post('/auth/set_new_password',
{'pw': 'foo', 'pw2': 'foo', '_session_id': self.app.cookies['_session_id']},
status=404)
self.app.post('/auth/password_recovery_hash',
{'email': 'foo', '_session_id': self.app.cookies['_session_id']},
status=404)
@patch('allura.lib.plugin.AuthenticationProvider.hibp_password_check_enabled', Mock(return_value=True))
@patch('allura.tasks.mail_tasks.sendsimplemail')
@patch('allura.lib.helpers.gen_message_id')
def test_pwd_reset_hibp_check(self, gen_message_id, sendmail):
self.app.get('/').follow() # establish session
user = M.User.query.get(username='test-admin')
email = M.EmailAddress.find({'claimed_by_user_id': user._id}).first()
email.confirmed = True
ThreadLocalODMSession.flush_all()
# request a reset
r = self.app.post('/auth/password_recovery_hash', {'email': email.email,
'_session_id': self.app.cookies['_session_id'],
})
hash = user.get_tool_data('AuthPasswordReset', 'hash')
# load reset form and fill it out with weak password
r = self.app.get('/auth/forgotten_password/%s' % hash)
form = r.forms[0]
form['pw'] = form['pw2'] = new_password = 'password'
r = form.submit()
assert 'Unsafe' in str(r.headers)
# fill it out again, with a stronger password
r = r.follow()
form = r.forms[0]
form['pw'] = form['pw2'] = new_password = 'oj35h9u34280j924hnuiw' # something unlikely to trip at hibp
r = form.submit()
assert 'Unsafe' not in str(r.headers)
# confirm password changed and works
user = M.User.query.get(username='test-admin')
provider = plugin.LocalAuthenticationProvider(None)
assert provider._validate_password(user, new_password)
# confirm can log in now in same session
r = r.follow()
assert 'Log Out' not in r, r
form = r.forms[0]
encoded = self.app.antispam_field_names(r.form)
form[encoded['username']] = 'test-admin'
form[encoded['password']] = new_password
r = form.submit(status=302)
r = r.follow().follow()
assert 'Log Out' in r, r
class TestOAuth(TestController):
def test_register_deregister_app(self):
# register
r = self.app.get('/auth/oauth/')
r = self.app.post('/auth/oauth/register',
params={'application_name': 'oautstapp', 'application_description': 'Oauth rulez',
'_session_id': self.app.cookies['_session_id'],
}).follow()
assert 'oautstapp' in r
# deregister
assert r.forms[0].action == 'deregister'
r.forms[0].submit()
r = self.app.get('/auth/oauth/')
assert 'oautstapp' not in r
def test_generate_revoke_access_token(self):
# generate
self.app.get('/').follow() # establish session
r = self.app.post('/auth/oauth/register',
params={'application_name': 'oautstapp', 'application_description': 'Oauth rulez',
'_session_id': self.app.cookies['_session_id'],
}, status=302)
r = self.app.get('/auth/oauth/')
assert r.forms[1].action == 'generate_access_token'
r = r.forms[1].submit(extra_environ={'username': 'test-user'}) # not the right user
assert "Invalid app ID" in self.webflash(r) # gets an error
r = self.app.get('/auth/oauth/') # do it again
r = r.forms[1].submit() # as correct user
assert '' == self.webflash(r)
r = self.app.get('/auth/oauth/')
assert 'Bearer Token:' in r
assert (
M.OAuthAccessToken.for_user(M.User.by_username('test-admin')) != [])
# revoke
assert r.forms[0].action == 'revoke_access_token'
r.forms[0].submit()
r = self.app.get('/auth/oauth/')
assert r.forms[0].action != 'revoke_access_token'
assert (
M.OAuthAccessToken.for_user(M.User.by_username('test-admin')) == [])
def test_interactive(self):
user = M.User.by_username('test-admin')
M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
secret_key='test-client-secret',
user_id=user._id,
description='ctok_desc',
)
ThreadLocalODMSession.flush_all()
oauth_params = dict(
client_key='api_key_api_key_12345',
client_secret='test-client-secret',
callback_uri='http://my.domain.com/callback',
)
r = self.app.post(*oauth1_webtest('/rest/oauth/request_token', oauth_params, method='POST'))
rtok = parse_qs(r.text)['oauth_token'][0]
rsecr = parse_qs(r.text)['oauth_token_secret'][0]
assert rtok
assert rsecr
r = self.app.post('/rest/oauth/authorize',
params={'oauth_token': rtok})
r = r.forms[0].submit('yes')
assert r.location.startswith('http://my.domain.com/callback')
pin = parse_qs(urlparse(r.location).query)['oauth_verifier'][0]
assert pin
oauth_params = dict(
client_key='api_key_api_key_12345',
client_secret='test-client-secret',
resource_owner_key=rtok,
resource_owner_secret=rsecr,
verifier=pin,
)
r = self.app.get(*oauth1_webtest('/rest/oauth/access_token', oauth_params))
atok = parse_qs(r.text)
assert len(atok['oauth_token']) == 1
assert len(atok['oauth_token_secret']) == 1
# now use the tokens & secrets to make a full OAuth request:
oauth_token = atok['oauth_token'][0]
oauth_secret = atok['oauth_token_secret'][0]
oaurl, oaparams, oahdrs, oaextraenv = oauth1_webtest('/rest/p/test/', dict(
client_key='api_key_api_key_12345',
client_secret='test-client-secret',
resource_owner_key=oauth_token,
resource_owner_secret=oauth_secret,
signature_type='query'
))
resp = self.app.get(oaurl, oaparams, oahdrs, oaextraenv, status=200)
for tool in resp.json['tools']:
if tool['name'] == 'admin':
break # good, found Admin
else:
raise AssertionError(f"No 'admin' tool in response, maybe authorizing as correct user failed. {resp.json}")
# definitely bad request
self.app.get(oaurl.replace('oauth_signature=', 'removed='), oaparams, oahdrs, oaextraenv, status=401)
def test_authorize_ok(self):
user = M.User.by_username('test-admin')
ctok = M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
user_id=user._id,
description='ctok_desc',
)
M.OAuthRequestToken(
api_key='api_key_reqtok_12345',
consumer_token_id=ctok._id,
callback='oob',
user_id=user._id,
)
ThreadLocalODMSession.flush_all()
r = self.app.post('/rest/oauth/authorize', params={'oauth_token': 'api_key_reqtok_12345'})
assert 'ctok_desc' in r.text
assert 'api_key_reqtok_12345' in r.text
def test_authorize_invalid(self):
resp = self.app.post('/rest/oauth/authorize', params={'oauth_token': 'api_key_reqtok_12345'}, status=400)
resp.mustcontain('error=invalid_client')
def test_do_authorize_no(self):
user = M.User.by_username('test-admin')
ctok = M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
user_id=user._id,
description='ctok_desc',
)
M.OAuthRequestToken(
api_key='api_key_reqtok_12345',
consumer_token_id=ctok._id,
callback='oob',
user_id=user._id,
)
ThreadLocalODMSession.flush_all()
self.app.post('/rest/oauth/do_authorize',
params={'no': '1', 'oauth_token': 'api_key_reqtok_12345'})
assert M.OAuthRequestToken.query.get(api_key='api_key_reqtok_12345') is None
def test_do_authorize_oob(self):
user = M.User.by_username('test-admin')
ctok = M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
user_id=user._id,
description='ctok_desc',
)
M.OAuthRequestToken(
api_key='api_key_reqtok_12345',
consumer_token_id=ctok._id,
callback='oob',
user_id=user._id,
)
ThreadLocalODMSession.flush_all()
r = self.app.post('/rest/oauth/do_authorize', params={'yes': '1', 'oauth_token': 'api_key_reqtok_12345'})
assert r.html.find(text=re.compile('^PIN: ')) is not None
def test_do_authorize_cb(self):
user = M.User.by_username('test-admin')
ctok = M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
user_id=user._id,
description='ctok_desc',
)
M.OAuthRequestToken(
api_key='api_key_reqtok_12345',
consumer_token_id=ctok._id,
callback='http://my.domain.com/callback',
user_id=user._id,
)
ThreadLocalODMSession.flush_all()
r = self.app.post('/rest/oauth/do_authorize', params={'yes': '1', 'oauth_token': 'api_key_reqtok_12345'})
assert r.location.startswith('http://my.domain.com/callback?oauth_token=api_key_reqtok_12345&oauth_verifier=')
def test_do_authorize_cb_params(self):
user = M.User.by_username('test-admin')
ctok = M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
user_id=user._id,
description='ctok_desc',
)
M.OAuthRequestToken(
api_key='api_key_reqtok_12345',
consumer_token_id=ctok._id,
callback='http://my.domain.com/callback?myparam=foo',
user_id=user._id,
)
ThreadLocalODMSession.flush_all()
r = self.app.post('/rest/oauth/do_authorize', params={'yes': '1', 'oauth_token': 'api_key_reqtok_12345'})
url = 'http://my.domain.com/callback?myparam=foo&oauth_token=api_key_reqtok_12345&oauth_verifier='
assert r.location.startswith(url)
class TestOAuth2(TestController):
@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_register_deregister_client(self):
#register
r = self.app.get('/auth/oauth2/')
r = self.app.post('/auth/oauth2/register',
params={'application_name': 'testoauth2', 'application_description': 'Oauth2 Test',
'redirect_url': '', '_session_id': self.app.cookies['_session_id'],
}).follow()
assert 'testoauth2' in r
#deregister
assert r.forms[0].action == 'do_client_action'
r.forms[0].submit('deregister')
r = self.app.get('/auth/oauth2/')
assert 'testoauth2' not in r
@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_authorize(self):
user = M.User.by_username('test-admin')
M.OAuth2ClientApp(
client_id='client_12345',
owner_id=user._id,
name='testoauth2',
description='test client',
response_type='code',
redirect_uris=['https://localhost/']
)
ThreadLocalODMSession.flush_all()
r = self.app.get('/rest/oauth2/authorize/', params={'client_id': 'client_12345', 'response_type': 'code'})
assert 'testoauth2' in r.text
assert 'client_12345' in r.text
@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_do_authorize_no(self):
user = M.User.by_username('test-admin')
M.OAuth2ClientApp(
client_id='client_12345',
owner_id=user._id,
name='testoauth2',
description='test client',
response_type='code',
redirect_uris=['https://localhost/']
)
ThreadLocalODMSession.flush_all()
r = self.app.post('/rest/oauth2/do_authorize', params={'no': '1', 'client_id': 'client_12345', 'response_type': 'code'})
assert M.OAuth2AuthorizationCode.query.get(client_id='client_12345') is None
@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_do_authorize(self):
user = M.User.by_username('test-admin')
M.OAuth2ClientApp(
client_id='client_12345',
owner_id=user._id,
name='testoauth2',
description='test client',
response_type='code',
redirect_uris=['https://localhost/']
)
ThreadLocalODMSession.flush_all()
# First navigate to the authorization page for the backend to validate the authorization request
r = self.app.get('/rest/oauth2/authorize', params={'client_id': 'client_12345', 'response_type': 'code', 'redirect_uri': 'https://localhost/'})
# The submit authorization for the authorization code to be created
r = self.app.post('/rest/oauth2/do_authorize', params={'yes': '1', 'client_id': 'client_12345', 'response_type': 'code', 'redirect_uri': 'https://localhost/'})
q = M.OAuth2AuthorizationCode.query.get(client_id='client_12345')
assert q is not None
r = self.app.get('/auth/oauth2/')
assert 'Authorization Code:' in r
@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_create_access_token(self):
user = M.User.by_username('test-admin')
M.OAuth2ClientApp(
client_id='client_12345',
owner_id=user._id,
name='testoauth2',
description='test client',
response_type='code',
redirect_uris=['https://localhost/']
)
ThreadLocalODMSession.flush_all()
# First navigate to the authorization page for the backend to validate the authorization request
r = self.app.get('/rest/oauth2/authorize', params={'client_id': 'client_12345', 'response_type': 'code', 'redirect_uri': 'https://localhost/'})
# The submit authorization for the authorization code to be created
r = self.app.post('/rest/oauth2/do_authorize', params={'yes': '1', 'client_id': 'client_12345', 'response_type': 'code', 'redirect_uri': 'https://localhost/'})
ac = M.OAuth2AuthorizationCode.query.get(client_id='client_12345')
assert ac is not None
r = self.app.get('/auth/oauth2/')
assert 'Authorization Code:' in r
# Create the authorization token
oauth2_params = dict(
client_id='client_12345',
code=ac.authorization_code,
grant_type='authorization_code'
)
r = self.app.post_json('/rest/oauth2/token', oauth2_params)
t = M.OAuth2AccessToken.query.get(client_id='client_12345')
assert t is not None
assert t.access_token is not None and t.refresh_token is not None
r = self.app.get('/auth/oauth2/')
assert 'Access Token:' in r
assert 'Refresh Token:' in r
@mock.patch.dict(config, {'auth.oauth2.enabled': True})
def test_revoke_tokens(self):
user = M.User.by_username('test-admin')
M.OAuth2ClientApp(
client_id='client_12345',
owner_id=user._id,
name='testoauth2',
description='test client',
response_type='code',
redirect_uris=['https://localhost/']
)
M.OAuth2AuthorizationCode(
client_id='client_12345',
authotization_code='authcode_12345',
expires_at=datetime.utcnow() + timedelta(minutes=10),
owner_id=user._id,
)
M.OAuth2AccessToken(
client_id='client_12345',
access_token='12345',
refresh_token='54321',
expires_at=datetime.utcnow() + timedelta(minutes=20),
owner_id=user._id,
)
ThreadLocalODMSession.flush_all()
r = self.app.get('/auth/oauth2/')
assert 'authorization code' in r
assert 'access token' in r
assert r.forms[0].action == 'do_client_action'
r.forms[0].submit('revoke')
r = self.app.get('/auth/oauth2/')
assert 'testoauth2' in r
assert 'Authorization Code:' not in r
assert 'Access Token:' not in r
class TestOAuthRequestToken(TestController):
oauth_params = dict(
client_key='api_key_api_key_12345',
client_secret='test-client-secret',
)
def setup_method(self, method):
super().setup_method(method)
dummy_oauths()
def test_request_token_valid(self):
user = M.User.by_username('test-user')
consumer_token = M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
secret_key='test-client-secret',
user_id=user._id,
)
ThreadLocalODMSession.flush_all()
r = self.app.post(*oauth1_webtest('/rest/oauth/request_token', self.oauth_params, method='POST'))
r.mustcontain('oauth_token=')
r.mustcontain('oauth_token_secret=')
request_token = M.OAuthRequestToken.query.get(consumer_token_id=consumer_token._id)
assert request_token is not None
def test_request_token_no_consumer_token_matching(self):
self.app.post(*oauth1_webtest('/rest/oauth/request_token', self.oauth_params), status=401)
def test_request_token_no_consumer_token_given(self):
oauth_params = self.oauth_params.copy()
oauth_params['signature_type'] = 'query' # so we can more easily remove a param next
url, params, hdrs, extraenv = oauth1_webtest('/rest/oauth/request_token', oauth_params)
url = url.replace('oauth_consumer_key', 'gone')
resp = self.app.post(url, params, hdrs, extraenv, status=400)
resp.mustcontain('error_description=Missing+mandatory+OAuth+parameters')
def test_request_token_invalid(self):
user = M.User.by_username('test-user')
M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
user_id=user._id,
secret_key='test-client-secret--INVALID',
)
ThreadLocalODMSession.flush_all()
self.app.post(*oauth1_webtest('/rest/oauth/request_token', self.oauth_params, method='POST'),
status=401)
class TestOAuthAccessToken(TestController):
oauth_params = dict(
client_key='api_key_api_key_12345',
client_secret='test-client-secret',
resource_owner_key='api_key_reqtok_12345',
resource_owner_secret='test-token-secret',
verifier='good_verifier_123456',
)
def setup_method(self, method):
super().setup_method(method)
dummy_oauths()
def test_access_token_no_consumer(self):
self.app.get(*oauth1_webtest('/rest/oauth/access_token', self.oauth_params), status=401)
def test_access_token_no_request(self):
user = M.User.by_username('test-admin')
M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
user_id=user._id,
description='ctok_desc',
)
ThreadLocalODMSession.flush_all()
self.app.get(*oauth1_webtest('/rest/oauth/access_token', self.oauth_params), status=401)
def test_access_token_bad_pin(self):
user = M.User.by_username('test-admin')
ctok = M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
user_id=user._id,
description='ctok_desc',
)
M.OAuthRequestToken(
api_key='api_key_reqtok_12345',
consumer_token_id=ctok._id,
callback='http://my.domain.com/callback?myparam=foo',
user_id=user._id,
validation_pin='good_verifier_123456',
)
ThreadLocalODMSession.flush_all()
oauth_params = self.oauth_params.copy()
oauth_params['verifier'] = 'bad_verifier_1234567'
self.app.get(*oauth1_webtest('/rest/oauth/access_token', oauth_params),
status=401)
def test_access_token_bad_sig(self):
user = M.User.by_username('test-admin')
ctok = M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
user_id=user._id,
description='ctok_desc',
secret_key='test-client-secret',
)
M.OAuthRequestToken(
api_key='api_key_reqtok_12345',
consumer_token_id=ctok._id,
callback='http://my.domain.com/callback?myparam=foo',
user_id=user._id,
validation_pin='good_verifier_123456',
secret_key='test-token-secret--INVALID',
)
ThreadLocalODMSession.flush_all()
self.app.get(*oauth1_webtest('/rest/oauth/access_token', self.oauth_params), status=401)
def test_access_token_ok(self, signature_type='auth_header'):
user = M.User.by_username('test-admin')
ctok = M.OAuthConsumerToken(
api_key='api_key_api_key_12345',
secret_key='test-client-secret',
user_id=user._id,
description='ctok_desc',
)
req_tok = M.OAuthRequestToken(
api_key='api_key_reqtok_12345',
secret_key='test-token-secret',
consumer_token_id=ctok._id,
callback='http://my.domain.com/callback?myparam=foo',
user_id=user._id,
validation_pin='good_verifier_123456',
)
ThreadLocalODMSession.flush_all()
oauth_params = dict(self.oauth_params, signature_type=signature_type)
r = self.app.get(*oauth1_webtest('/rest/oauth/access_token', self.oauth_params))
atok = parse_qs(r.text)
assert len(atok['oauth_token']) == 1
assert len(atok['oauth_token_secret']) == 1
def test_access_token_ok_by_query(self):
self.test_access_token_ok(signature_type='query')
class TestDisableAccount(TestController):
def test_not_authenticated(self):
r = self.app.get(
'/auth/disable/',
extra_environ={'username': '*anonymous'})
assert r.status_int == 302
assert (r.location ==
'http://localhost/auth/?return_to=%2Fauth%2Fdisable%2F')
def test_lists_user_projects(self):
r = self.app.get('/auth/disable/')
user = M.User.by_username('test-admin')
for p in user.my_projects_by_role_name('Admin'):
if p.name == 'u/test-admin':
continue
assert p.name in r
assert p.url() in r
def test_has_asks_password(self):
r = self.app.get('/auth/disable/')
form = r.html.find('form', {'action': 'do_disable'})
assert form is not None
def test_bad_password(self):
self.app.get('/').follow() # establish session
r = self.app.post('/auth/disable/do_disable', {'password': 'bad',
'_session_id': self.app.cookies['_session_id'], })
assert 'Invalid password' in r
user = M.User.by_username('test-admin')
assert user.disabled is False
def test_disable(self):
self.app.get('/').follow() # establish session
r = self.app.post('/auth/disable/do_disable', {'password': 'foo',
'_session_id': self.app.cookies['_session_id'], })
assert r.status_int == 302
assert r.location == 'http://localhost/'
flash = json.loads(self.webflash(r))
assert flash['status'] == 'ok'
assert flash['message'] == 'Your account was successfully disabled!'
user = M.User.by_username('test-admin')
assert user.disabled is True
class TestPasswordExpire(TestController):
def login(self, username='test-user', pwd='foo', query_string=''):
extra = {'username': '*anonymous', 'REMOTE_ADDR': '127.0.0.1'}
r = self.app.get('/auth/' + query_string, extra_environ=extra)
f = r.forms[0]
encoded = self.app.antispam_field_names(f)
f[encoded['username']] = username
f[encoded['password']] = pwd
return f.submit(extra_environ={'username': '*anonymous'})
def assert_redirects(self, where='/'):
resp = self.app.get(where, extra_environ={'username': 'test-user'}, status=302)
assert resp.location == 'http://localhost/auth/pwd_expired?' + urlencode({'return_to': where})
def assert_not_redirects(self, where='/neighborhood'):
self.app.get(where, extra_environ={'username': 'test-user'}, status=200)
def test_disabled(self):
r = self.login()
assert not r.session.get('pwd-expired')
self.assert_not_redirects()
def expired(self, r):
return r.session.get('pwd-expired')
def set_expire_for_user(self, username='test-user', days=100):
user = M.User.by_username(username)
user.last_password_updated = datetime.utcnow() - timedelta(days=days)
session(user).flush(user)
return user
def test_days(self):
self.set_expire_for_user()
with h.push_config(config, **{'auth.pwdexpire.days': 180}):
r = self.login()
assert not self.expired(r)
self.assert_not_redirects()
with h.push_config(config, **{'auth.pwdexpire.days': 90}):
r = self.login()
assert self.expired(r)
self.assert_redirects()
def test_before(self):
self.set_expire_for_user()
before = datetime.utcnow() - timedelta(days=180)
before = calendar.timegm(before.timetuple())
with h.push_config(config, **{'auth.pwdexpire.before': before}):
r = self.login()
assert not self.expired(r)
self.assert_not_redirects()
before = datetime.utcnow() - timedelta(days=90)
before = calendar.timegm(before.timetuple())
with h.push_config(config, **{'auth.pwdexpire.before': before}):
r = self.login()
assert self.expired(r)
self.assert_redirects()
def test_logout(self):
self.set_expire_for_user()
with h.push_config(config, **{'auth.pwdexpire.days': 90}):
r = self.login()
assert self.expired(r)
self.assert_redirects()
r = self.app.get('/auth/logout', extra_environ={'username': 'test-user'})
assert not self.expired(r)
self.assert_not_redirects()
def test_change_pwd(self):
self.set_expire_for_user()
with h.push_config(config, **{'auth.pwdexpire.days': 90}):
r = self.login()
assert self.expired(r)
self.assert_redirects()
user = M.User.by_username('test-user')
old_update_time = user.last_password_updated
old_password = user.password
r = self.app.get('/auth/pwd_expired', extra_environ={'username': 'test-user'})
f = r.forms[0]
f['oldpw'] = 'foo'
f['pw'] = 'qwerty'
f['pw2'] = 'qwerty'
r = f.submit(extra_environ={'username': 'test-user'}, status=302)
assert r.location == 'http://localhost/'
assert not self.expired(r)
user = M.User.by_username('test-user')
assert user.last_password_updated > old_update_time
assert user.password != old_password
# Can log in with new password and change isn't required anymore
r = self.login(pwd='qwerty').follow()
assert r.location == 'http://localhost/dashboard'
assert 'Invalid login' not in r
assert not self.expired(r)
self.assert_not_redirects()
# and can't log in with old password
r = self.login(pwd='foo')
assert 'Invalid login' in r
def test_expired_pwd_change_invalidates_token(self):
self.set_expire_for_user()
with h.push_config(config, **{'auth.pwdexpire.days': 90}):
r = self.login()
assert self.expired(r)
self.assert_redirects()
user = M.User.by_username('test-user')
user.set_tool_data('AuthPasswordReset',
hash="generated_hash_value",
hash_expiry="04-08-2020")
hash = user.get_tool_data('AuthPasswordReset', 'hash')
hash_expiry = user.get_tool_data('AuthPasswordReset', 'hash_expiry')
assert hash == 'generated_hash_value'
assert hash_expiry == '04-08-2020'
session(user).flush(user)
# Change expired password
r = self.app.get('/auth/pwd_expired', extra_environ={'username': 'test-user'})
f = r.forms[0]
f['oldpw'] = 'foo'
f['pw'] = 'qwerty'
f['pw2'] = 'qwerty'
r = f.submit(extra_environ={'username': 'test-user'}, status=302)
assert r.location == 'http://localhost/'
user = M.User.by_username('test-user')
hash = user.get_tool_data('AuthPasswordReset', 'hash')
hash_expiry = user.get_tool_data('AuthPasswordReset', 'hash_expiry')
assert hash == ''
assert hash_expiry == ''
def check_validation(self, oldpw, pw, pw2):
user = M.User.by_username('test-user')
old_update_time = user.last_password_updated
old_password = user.password
r = self.app.get('/auth/pwd_expired', extra_environ={'username': 'test-user'})
f = r.forms[0]
f['oldpw'] = oldpw
f['pw'] = pw
f['pw2'] = pw2
r = f.submit(extra_environ={'username': 'test-user'})
assert self.expired(r)
user = M.User.by_username('test-user')
assert user.last_password_updated == old_update_time
assert user.password == old_password
return r
def test_change_pwd_validation(self):
self.set_expire_for_user()
with h.push_config(config, **{'auth.pwdexpire.days': 90}):
r = self.login()
assert self.expired(r)
self.assert_redirects()
r = self.check_validation('', '', '')
assert 'Please enter a value' in r
r = self.check_validation('', 'qwe', 'qwerty')
assert 'Enter a value 6 characters long or more' in r
r = self.check_validation('bad', 'qwerty1', 'qwerty')
assert 'Passwords must match' in r
r = self.check_validation('bad', 'qwerty', 'qwerty')
assert 'Incorrect password' in self.webflash(r)
assert r.location == 'http://localhost/auth/pwd_expired?return_to='
with h.push_config(config, **{'auth.min_password_len': 3}):
r = self.check_validation('foo', 'foo', 'foo')
assert 'Your old and new password should not be the same' in r
def test_return_to(self):
return_to = '/p/test/tickets/?milestone=1.0&page=2'
self.set_expire_for_user()
with h.push_config(config, **{'auth.pwdexpire.days': 90}):
r = self.login(query_string='?' + urlencode({'return_to': return_to}))
# don't go to the return_to yet
assert r.location == 'http://localhost/auth/pwd_expired?' + urlencode({'return_to': return_to})
# but if user tries to go directly there anyway, intercept and redirect back
self.assert_redirects(where=return_to)
r = self.app.get('/auth/pwd_expired', extra_environ={'username': 'test-user'})
f = r.forms[0]
f['oldpw'] = 'foo'
f['pw'] = 'qwerty'
f['pw2'] = 'qwerty'
f['return_to'] = return_to
r = f.submit(extra_environ={'username': 'test-user'}, status=302)
assert r.location == 'http://localhost/p/test/tickets/?milestone=1.0&page=2'
class TestCSRFProtection(TestController):
def test_blocks_invalid(self):
# so test-admin isn't automatically logged in for all requests
self.app.extra_environ = {'disable_auth_magic': 'True', 'REMOTE_ADDR': '127.0.0.1'}
# regular login
r = self.app.get('/auth/')
r = self.app.post('/auth/do_login', params=dict(
username='test-admin', password='foo',
_session_id=self.app.cookies['_session_id']),
antispam=True)
# regular form submit
r = self.app.get('/admin/overview')
r = r.form.submit()
assert r.location == 'http://localhost/admin/overview'
# invalid form submit
r = self.app.get('/admin/overview')
r.form['_session_id'] = 'bogus'
r = r.form.submit()
assert r.location == 'http://localhost/auth/'
def test_blocks_invalid_on_login(self):
r = self.app.get('/auth/')
r.form['_session_id'] = 'bogus'
r.form.submit(status=403)
def test_token_present_on_first_request(self):
r = self.app.get('/auth/')
assert r.form['_session_id'].value
class TestTwoFactor(TestController):
sample_key = b'\x00K\xda\xbfv\xc2B\xaa\x1a\xbe\xa5\x96b\xb2\xa0Z:\xc9\xcf\x8a'
sample_b32 = 'ABF5VP3WYJBKUGV6UWLGFMVALI5MTT4K'
def _init_totp(self, username='test-admin'):
user = M.User.query.get(username=username)
totp_srv = TotpService().get()
totp_srv.set_secret_key(user, self.sample_key)
user.set_pref('multifactor', True)
def test_settings_on(self):
r = self.app.get('/auth/preferences/')
assert r.html.find(attrs={'class': 'preferences multifactor'})
def test_settings_off(self):
with h.push_config(config, **{'auth.multifactor.totp': 'false'}):
r = self.app.get('/auth/preferences/')
assert not r.html.find(attrs={'class': 'preferences multifactor'})
for url in ['/auth/preferences/totp_new',
'/auth/preferences/totp_view',
'/auth/preferences/totp_set',
'/auth/preferences/totp_send_link',
'/auth/preferences/multifactor_disable',
'/auth/preferences/multifactor_recovery',
'/auth/preferences/multifactor_recovery_regen',
'/auth/multifactor',
'/auth/do_multifactor',
]:
self.app.post(url,
{'password': 'foo', '_session_id': self.app.cookies['_session_id']},
status=404)
def test_user_disabled(self):
r = self.app.get('/auth/preferences/')
info_html = str(r.html.find(attrs={'class': 'preferences multifactor'}))
assert 'disabled' in info_html
def test_user_enabled(self):
self._init_totp()
r = self.app.get('/auth/preferences/')
info_html = str(r.html.find(attrs={'class': 'preferences multifactor'}))
assert 'enabled' in info_html
def test_reconfirm_auth(self):
from datetime import datetime as real_datetime
with patch('allura.lib.decorators.datetime') as datetime:
datetime.min = real_datetime.min
# reconfirm required at first
datetime.utcnow.return_value = real_datetime(2016, 1, 1, 0, 0, 0)
r = self.app.get('/auth/preferences/totp_new')
assert 'Password Confirmation' in r
# submit form, and its not required
r.form['password'] = 'foo'
r = r.form.submit()
assert 'Password Confirmation' not in r
# still not required
datetime.utcnow.return_value = real_datetime(2016, 1, 1, 0, 1, 45)
r = self.app.get('/auth/preferences/totp_new')
assert 'Password Confirmation' not in r
# required later
datetime.utcnow.return_value = real_datetime(2016, 1, 1, 0, 2, 3)
r = self.app.get('/auth/preferences/totp_new')
assert 'Password Confirmation' in r
def test_enable_totp(self):
# create a separate session, for later use in the test
other_session = TestController()
other_session.setup_method(None)
other_session.app.get('/auth/preferences/')
with out_audits(user=True):
r = self.app.get('/auth/preferences/totp_new')
assert 'Password Confirmation' in r
with audits('Visited multifactor new TOTP page', user=True):
r.form['password'] = 'foo'
r = r.form.submit()
assert 'Scan this' in r
assert 'Or enter setup key: ' in r
first_key_shown = r.session['totp_new_key']
with audits(r'Failed to set up multifactor TOTP \(wrong code\)', user=True):
form = r.forms['totp_set']
form['code'] = ''
r = form.submit()
assert 'Invalid' in r
assert f'Or enter setup key: {b32encode(first_key_shown).decode()}' in r
assert first_key_shown == r.session['totp_new_key'] # different keys on each pageload would be bad!
new_totp = TotpService().Totp(r.session['totp_new_key'])
code = new_totp.generate(time_time())
form = r.forms['totp_set']
form['code'] = code
with audits('Set up multifactor TOTP', user=True):
r = form.submit()
msg = 'Two factor authentication has now been set up.'
assert msg == json.loads(self.webflash(r))['message'], self.webflash(r)
tasks = M.MonQTask.query.find(dict(task_name='allura.tasks.mail_tasks.sendsimplemail')).all()
assert len(tasks) == 1
assert tasks[0].kwargs['subject'] == 'Two-Factor Authentication Enabled'
assert 'new two-factor authentication' in tasks[0].kwargs['text']
r = r.follow()
assert 'Recovery Codes' in r
# Confirm any pre-existing sessions have to re-authenticate
r = other_session.app.get('/auth/preferences/')
assert '/auth/?return_to' in r.headers['Location']
other_session.teardown_method(None)
def test_reset_totp(self):
self._init_totp()
# access page
r = self.app.get('/auth/preferences/totp_new')
assert 'Password Confirmation' in r
# reconfirm password to get to it
r.form['password'] = 'foo'
r = r.form.submit()
# confirm warning message, and key is not changed yet
assert 'Scan this' in r
assert 'Or enter setup key: ' in r
assert 'this will invalidate your previous' in r
current_key = TotpService.get().get_secret_key(M.User.query.get(username='test-admin'))
assert self.sample_key == current_key
# incorrect submission
form = r.forms['totp_set']
form['code'] = ''
r = form.submit()
assert 'Invalid' in r
# still unchanged key
current_key = TotpService.get().get_secret_key(M.User.query.get(username='test-admin'))
assert self.sample_key == current_key
# valid submission
new_key = r.session['totp_new_key']
new_totp = TotpService().Totp(new_key)
code = new_totp.generate(time_time())
form = r.forms['totp_set']
form['code'] = code
r = form.submit()
msg = 'Two factor authentication has now been set up.'
assert msg == json.loads(self.webflash(r))['message'], self.webflash(r)
# new key in place
current_key = TotpService.get().get_secret_key(M.User.query.get(username='test-admin'))
assert new_key == current_key
assert self.sample_key != current_key
def test_disable(self):
self._init_totp()
self.app.get('/auth/preferences/multifactor_disable', status=405) # GET not allowed
# get form and submit
r = self.app.get('/auth/preferences/')
form = r.forms['multifactor_disable']
r = form.submit()
# confirm first, no change
assert 'Password Confirmation' in r
user = M.User.query.get(username='test-admin')
assert user.get_pref('multifactor') is True
# confirm submit, everything goes off
r.form['password'] = 'foo'
with audits('Disabled multifactor TOTP', user=True):
r = r.form.submit()
msg = 'Multifactor authentication has now been disabled.'
assert msg == json.loads(self.webflash(r))['message'], self.webflash(r)
user = M.User.query.get(username='test-admin')
assert user.get_pref('multifactor') is False
assert TotpService().get().get_secret_key(user) is None
assert RecoveryCodeService().get().get_codes(user) == []
# email confirmation
tasks = M.MonQTask.query.find(dict(task_name='allura.tasks.mail_tasks.sendsimplemail')).all()
assert len(tasks) == 1
assert tasks[0].kwargs['subject'] == 'Two-Factor Authentication Disabled'
assert 'disabled two-factor authentication' in tasks[0].kwargs['text']
def test_login_totp(self):
self._init_totp()
# so test-admin isn't automatically logged in for all requests
self.app.extra_environ = {'disable_auth_magic': 'True'}
# regular login
r = self.app.get('/auth/?return_to=/p/foo')
encoded = self.app.antispam_field_names(r.form)
r.form[encoded['username']] = 'test-admin'
r.form[encoded['password']] = 'foo'
with audits('Multifactor login - password ok, code not entered yet', user=True):
r = r.form.submit()
# check results
assert r.location.endswith('/auth/multifactor?return_to=%2Fp%2Ffoo'), r
r = r.follow()
assert not r.session.get('username')
# try an invalid code
r.form['code'] = 'invalid-code'
with audits('Multifactor login - invalid code', user=True):
r = r.form.submit()
assert 'Invalid code' in r
assert not r.session.get('username')
# use a valid code
totp = TotpService().Totp(self.sample_key)
code = totp.generate(time_time())
r.form['code'] = code
with audits('Successful login', user=True):
r = r.form.submit()
# confirm login and final page
assert r.session['username'] == 'test-admin'
assert r.location.endswith('/p/foo'), r
def test_login_rate_limit(self):
self._init_totp()
# so test-admin isn't automatically logged in for all requests
self.app.extra_environ = {'disable_auth_magic': 'True'}
# regular login
r = self.app.get('/auth/?return_to=/p/foo')
encoded = self.app.antispam_field_names(r.form)
r.form[encoded['username']] = 'test-admin'
r.form[encoded['password']] = 'foo'
r = r.form.submit()
r = r.follow()
# try some invalid codes
for i in range(3):
r.form['code'] = 'invalid-code'
r = r.form.submit()
assert 'Invalid code' in r
# use a valid code, but it'll hit rate limit
totp = TotpService().Totp(self.sample_key)
code = totp.generate(time_time())
r.form['code'] = code
with audits('Multifactor login - rate limit', user=True):
r = r.form.submit()
assert 'rate limit exceeded' in r
assert not r.session.get('username')
def test_login_totp_disrupted(self):
self._init_totp()
# so test-admin isn't automatically logged in for all requests
self.app.extra_environ = {'disable_auth_magic': 'True'}
# regular login
r = self.app.get('/auth/')
encoded = self.app.antispam_field_names(r.form)
r.form[encoded['username']] = 'test-admin'
r.form[encoded['password']] = 'foo'
r = r.form.submit()
r = r.follow()
# go to some other page instead of filling out the 2FA code
other_r = self.app.get('/')
# then try to complete the 2FA form
totp = TotpService().Totp(self.sample_key)
code = totp.generate(time_time())
r.form['code'] = code
r = r.form.submit()
# sent back to regular login
assert ('Your multifactor login was disrupted, please start over.' ==
json.loads(self.webflash(r))['message']), self.webflash(r)
r = r.follow()
assert 'Password Login' in r
def test_login_recovery_code(self):
self._init_totp()
# so test-admin isn't automatically logged in for all requests
self.app.extra_environ = {'disable_auth_magic': 'True'}
# regular login
r = self.app.get('/auth/?return_to=/p/foo')
encoded = self.app.antispam_field_names(r.form)
r.form[encoded['username']] = 'test-admin'
r.form[encoded['password']] = 'foo'
r = r.form.submit()
# check results
assert r.location.endswith('/auth/multifactor?return_to=%2Fp%2Ffoo'), r
r = r.follow()
assert not r.session.get('username')
# change login mode
r.form['mode'] = 'recovery'
# try an invalid code
r.form['code'] = 'invalid-code'
r = r.form.submit()
assert 'Invalid code' in r
assert not r.session.get('username')
# use a valid code
user = M.User.by_username('test-admin')
recovery = RecoveryCodeService().get()
recovery.regenerate_codes(user)
recovery_code = recovery.get_codes(user)[0]
r.form['code'] = recovery_code
with audits('Logged in using a multifactor recovery code', user=True):
r = r.form.submit()
# confirm login and final page
assert r.session['username'] == 'test-admin'
assert r.location.endswith('/p/foo'), r
# confirm code used up
assert recovery_code not in RecoveryCodeService().get().get_codes(user)
@patch('allura.lib.plugin.AuthenticationProvider.hibp_password_check_enabled', Mock(return_value=True))
def test_login_totp_with_hibp(self):
# this is essentially the same as regular TOTP test, just making sure that HIBP doesn't get in the way
# or cause any problems. It shouldn't even run since a password isn't present when the final login happens
self._init_totp()
# so test-admin isn't automatically logged in for all requests
self.app.extra_environ = {'disable_auth_magic': 'True'}
# regular login
r = self.app.get('/auth/?return_to=/p/foo')
encoded = self.app.antispam_field_names(r.form)
r.form[encoded['username']] = 'test-admin'
r.form[encoded['password']] = 'foo'
with audits('Multifactor login - password ok, code not entered yet', user=True):
r = r.form.submit()
# check results
assert r.location.endswith('/auth/multifactor?return_to=%2Fp%2Ffoo'), r
r = r.follow()
assert not r.session.get('username')
# use a valid code
totp = TotpService().Totp(self.sample_key)
code = totp.generate(time_time())
r.form['code'] = code
with audits('Successful login', user=True):
r = r.form.submit()
# confirm login and final page
assert r.session['username'] == 'test-admin'
assert r.location.endswith('/p/foo'), r
def test_view_key(self):
self._init_totp()
with out_audits(user=True):
r = self.app.get('/auth/preferences/totp_view')
assert 'Password Confirmation' in r
with audits('Viewed multifactor TOTP config page', user=True):
r.form['password'] = 'foo'
r = r.form.submit()
assert 'Scan this' in r
assert f'Or enter setup key: {self.sample_b32}' in r
def test_view_recovery_codes_and_regen(self):
self._init_totp()
# reconfirm password
with out_audits(user=True):
r = self.app.get('/auth/preferences/multifactor_recovery')
assert 'Password Confirmation' in r
# actual visit
with audits('Viewed multifactor recovery codes', user=True):
r.form['password'] = 'foo'
r = r.form.submit()
assert 'Download' in r
assert 'Print' in r
# regenerate codes
with audits('Regenerated multifactor recovery codes', user=True):
r = r.forms['multifactor_recovery_regen'].submit()
# email confirmation
tasks = M.MonQTask.query.find(dict(task_name='allura.tasks.mail_tasks.sendsimplemail')).all()
assert len(tasks) == 1
assert tasks[0].kwargs['subject'] == 'Two-Factor Recovery Codes Regenerated'
assert 'regenerated' in tasks[0].kwargs['text']
def test_send_links(self):
r = self.app.get('/auth/preferences/totp_new')
r.form['password'] = 'foo'
r = r.form.submit()
r = r.forms['totp_send_link'].submit()
tasks = M.MonQTask.query.find(dict(task_name='allura.tasks.mail_tasks.sendsimplemail')).all()
assert len(tasks) == 1
assert tasks[0].kwargs['subject'] == 'Two-Factor Authentication Apps'
assert 'itunes.apple.com' in tasks[0].kwargs['text']
assert 'play.google.com' in tasks[0].kwargs['text']