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
|
<?php
/**
* Authentication (and possibly Authorization in the future) system entry point
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Auth
*/
namespace MediaWiki\Auth;
use InvalidArgumentException;
use LogicException;
use MediaWiki\Auth\Hook\AuthManagerVerifyAuthenticationHook;
use MediaWiki\Block\BlockManager;
use MediaWiki\Config\Config;
use MediaWiki\Context\RequestContext;
use MediaWiki\Deferred\DeferredUpdates;
use MediaWiki\Deferred\SiteStatsUpdate;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\HookContainer\HookRunner;
use MediaWiki\Language\Language;
use MediaWiki\Languages\LanguageConverterFactory;
use MediaWiki\MainConfigNames;
use MediaWiki\MediaWikiServices;
use MediaWiki\Page\PageIdentity;
use MediaWiki\Permissions\Authority;
use MediaWiki\Permissions\PermissionStatus;
use MediaWiki\Request\WebRequest;
use MediaWiki\SpecialPage\SpecialPage;
use MediaWiki\Status\Status;
use MediaWiki\StubObject\StubGlobalUser;
use MediaWiki\User\BotPasswordStore;
use MediaWiki\User\Options\UserOptionsManager;
use MediaWiki\User\TempUser\TempUserCreator;
use MediaWiki\User\User;
use MediaWiki\User\UserFactory;
use MediaWiki\User\UserIdentity;
use MediaWiki\User\UserIdentityLookup;
use MediaWiki\User\UserNameUtils;
use MediaWiki\User\UserRigorOptions;
use MediaWiki\Watchlist\WatchlistManager;
use MWExceptionHandler;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use StatusValue;
use Wikimedia\NormalizedException\NormalizedException;
use Wikimedia\ObjectFactory\ObjectFactory;
use Wikimedia\Rdbms\IDBAccessObject;
use Wikimedia\Rdbms\ILoadBalancer;
use Wikimedia\Rdbms\ReadOnlyMode;
use Wikimedia\ScopedCallback;
/**
* This serves as the entry point to the authentication system.
*
* In the future, it may also serve as the entry point to the authorization
* system.
*
* If you are looking at this because you are working on an extension that creates its own
* login or signup page, then 1) you really shouldn't do that, 2) if you feel you absolutely
* have to, subclass AuthManagerSpecialPage or build it on the client side using the clientlogin
* or the createaccount API. Trying to call this class directly will very likely end up in
* security vulnerabilities or broken UX in edge cases.
*
* If you are working on an extension that needs to integrate with the authentication system
* (e.g. by providing a new login method, or doing extra permission checks), you'll probably
* need to write an AuthenticationProvider.
*
* If you want to create a "reserved" user programmatically, User::newSystemUser() might be what
* you are looking for. If you want to change user data, use User::changeAuthenticationData().
* Code that is related to some SessionProvider or PrimaryAuthenticationProvider can
* create a (non-reserved) user by calling AuthManager::autoCreateUser(); it is then the provider's
* responsibility to ensure that the user can authenticate somehow (see especially
* PrimaryAuthenticationProvider::autoCreatedAccount()). The same functionality can also be used
* from Maintenance scripts such as createAndPromote.php.
* If you are writing code that is not associated with such a provider and needs to create accounts
* programmatically for real users, you should rethink your architecture. There is no good way to
* do that as such code has no knowledge of what authentication methods are enabled on the wiki and
* cannot provide any means for users to access the accounts it would create.
*
* The two main control flows when using this class are as follows:
* * Login, user creation or account linking code will call getAuthenticationRequests(), populate
* the requests with data (by using them to build a HTMLForm and have the user fill it, or by
* exposing a form specification via the API, so that the client can build it), and pass them to
* the appropriate begin* method. That will return either a success/failure response, or more
* requests to fill (either by building a form or by redirecting the user to some external
* provider which will send the data back), in which case they need to be submitted to the
* appropriate continue* method and that step has to be repeated until the response is a success
* or failure response. AuthManager will use the session to maintain internal state during the
* process.
* * Code doing an authentication data change will call getAuthenticationRequests(), select
* a single request, populate it, and pass it to allowsAuthenticationDataChange() and then
* changeAuthenticationData(). If the data change is user-initiated, the whole process needs
* to be preceded by a call to securitySensitiveOperationStatus() and aborted if that returns
* a non-OK status.
*
* @ingroup Auth
* @since 1.27
* @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
*/
class AuthManager implements LoggerAwareInterface {
/**
* @internal
* Key in the user's session data for storing login state.
*/
public const AUTHN_STATE = 'AuthManager::authnState';
/**
* @internal
* Key in the user's session data for storing account creation state.
*/
public const ACCOUNT_CREATION_STATE = 'AuthManager::accountCreationState';
/**
* @internal
* Key in the user's session data for storing account linking state.
*/
public const ACCOUNT_LINK_STATE = 'AuthManager::accountLinkState';
/**
* @internal
* Key in the user's session data for storing autocreation failures,
* to avoid re-attempting expensive autocreation checks on every request.
*/
public const AUTOCREATE_BLOCKLIST = 'AuthManager::AutoCreateBlacklist';
/** Log in with an existing (not necessarily local) user */
public const ACTION_LOGIN = 'login';
/** Continue a login process that was interrupted by the need for user input or communication
* with an external provider
*/
public const ACTION_LOGIN_CONTINUE = 'login-continue';
/** Create a new user */
public const ACTION_CREATE = 'create';
/** Continue a user creation process that was interrupted by the need for user input or
* communication with an external provider
*/
public const ACTION_CREATE_CONTINUE = 'create-continue';
/** Link an existing user to a third-party account */
public const ACTION_LINK = 'link';
/** Continue a user linking process that was interrupted by the need for user input or
* communication with an external provider
*/
public const ACTION_LINK_CONTINUE = 'link-continue';
/** Change a user's credentials */
public const ACTION_CHANGE = 'change';
/** Remove a user's credentials */
public const ACTION_REMOVE = 'remove';
/** Like ACTION_REMOVE but for linking providers only */
public const ACTION_UNLINK = 'unlink';
/** Security-sensitive operations are ok. */
public const SEC_OK = 'ok';
/** Security-sensitive operations should re-authenticate. */
public const SEC_REAUTH = 'reauth';
/** Security-sensitive should not be performed. */
public const SEC_FAIL = 'fail';
/** Auto-creation is due to SessionManager */
public const AUTOCREATE_SOURCE_SESSION = \MediaWiki\Session\SessionManager::class;
/** Auto-creation is due to a Maintenance script */
public const AUTOCREATE_SOURCE_MAINT = '::Maintenance::';
/** Auto-creation is due to temporary account creation on page save */
public const AUTOCREATE_SOURCE_TEMP = TempUserCreator::class;
/**
* @internal To be used by primary authentication providers only.
* @var string "Remember me" status flag shared between auth providers
*/
public const REMEMBER_ME = 'rememberMe';
/**
* @internal To be used by primary authentication providers only.
* @var string Primary providers can set this to false after login to prevent the
* login from being considered user interaction. This is important for some security
* features which generally interpret a recent login as proof of account ownership
* (vs. a stolen session).
*/
public const LOGIN_WAS_INTERACTIVE = 'loginWasInteractive';
/** Call pre-authentication providers */
private const CALL_PRE = 1;
/** Call primary authentication providers */
private const CALL_PRIMARY = 2;
/** Call secondary authentication providers */
private const CALL_SECONDARY = 4;
/** Call all authentication providers */
private const CALL_ALL = self::CALL_PRE | self::CALL_PRIMARY | self::CALL_SECONDARY;
/** @var WebRequest */
private $request;
/** @var Config */
private $config;
/** @var ObjectFactory */
private $objectFactory;
/** @var LoggerInterface */
private $logger;
/** @var UserNameUtils */
private $userNameUtils;
/** @var AuthenticationProvider[] */
private $allAuthenticationProviders = [];
/** @var PreAuthenticationProvider[] */
private $preAuthenticationProviders = null;
/** @var PrimaryAuthenticationProvider[] */
private $primaryAuthenticationProviders = null;
/** @var SecondaryAuthenticationProvider[] */
private $secondaryAuthenticationProviders = null;
/** @var CreatedAccountAuthenticationRequest[] */
private $createdAccountAuthenticationRequests = [];
/** @var HookContainer */
private $hookContainer;
/** @var HookRunner */
private $hookRunner;
/** @var ReadOnlyMode */
private $readOnlyMode;
/** @var BlockManager */
private $blockManager;
/** @var WatchlistManager */
private $watchlistManager;
/** @var ILoadBalancer */
private $loadBalancer;
/** @var Language */
private $contentLanguage;
/** @var LanguageConverterFactory */
private $languageConverterFactory;
/** @var BotPasswordStore */
private $botPasswordStore;
/** @var UserFactory */
private $userFactory;
/** @var UserIdentityLookup */
private $userIdentityLookup;
/** @var UserOptionsManager */
private $userOptionsManager;
/**
* @param WebRequest $request
* @param Config $config
* @param ObjectFactory $objectFactory
* @param HookContainer $hookContainer
* @param ReadOnlyMode $readOnlyMode
* @param UserNameUtils $userNameUtils
* @param BlockManager $blockManager
* @param WatchlistManager $watchlistManager
* @param ILoadBalancer $loadBalancer
* @param Language $contentLanguage
* @param LanguageConverterFactory $languageConverterFactory
* @param BotPasswordStore $botPasswordStore
* @param UserFactory $userFactory
* @param UserIdentityLookup $userIdentityLookup
* @param UserOptionsManager $userOptionsManager
*
*/
public function __construct(
WebRequest $request,
Config $config,
ObjectFactory $objectFactory,
HookContainer $hookContainer,
ReadOnlyMode $readOnlyMode,
UserNameUtils $userNameUtils,
BlockManager $blockManager,
WatchlistManager $watchlistManager,
ILoadBalancer $loadBalancer,
Language $contentLanguage,
LanguageConverterFactory $languageConverterFactory,
BotPasswordStore $botPasswordStore,
UserFactory $userFactory,
UserIdentityLookup $userIdentityLookup,
UserOptionsManager $userOptionsManager
) {
$this->request = $request;
$this->config = $config;
$this->objectFactory = $objectFactory;
$this->hookContainer = $hookContainer;
$this->hookRunner = new HookRunner( $hookContainer );
$this->setLogger( new NullLogger() );
$this->readOnlyMode = $readOnlyMode;
$this->userNameUtils = $userNameUtils;
$this->blockManager = $blockManager;
$this->watchlistManager = $watchlistManager;
$this->loadBalancer = $loadBalancer;
$this->contentLanguage = $contentLanguage;
$this->languageConverterFactory = $languageConverterFactory;
$this->botPasswordStore = $botPasswordStore;
$this->userFactory = $userFactory;
$this->userIdentityLookup = $userIdentityLookup;
$this->userOptionsManager = $userOptionsManager;
}
/**
* @param LoggerInterface $logger
*/
public function setLogger( LoggerInterface $logger ) {
$this->logger = $logger;
}
/**
* @return WebRequest
*/
public function getRequest() {
return $this->request;
}
/**
* Force certain PrimaryAuthenticationProviders
*
* @deprecated since 1.43; for backwards compatibility only
* @param PrimaryAuthenticationProvider[] $providers
* @param string $why
*/
public function forcePrimaryAuthenticationProviders( array $providers, $why ) {
wfDeprecated( __METHOD__, '1.43' );
$this->logger->warning( "Overriding AuthManager primary authn because $why" );
if ( $this->primaryAuthenticationProviders !== null ) {
$this->logger->warning(
'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
);
$this->allAuthenticationProviders = array_diff_key(
$this->allAuthenticationProviders,
$this->primaryAuthenticationProviders
);
$session = $this->request->getSession();
$session->remove( self::AUTHN_STATE );
$session->remove( self::ACCOUNT_CREATION_STATE );
$session->remove( self::ACCOUNT_LINK_STATE );
$this->createdAccountAuthenticationRequests = [];
}
$this->primaryAuthenticationProviders = [];
foreach ( $providers as $provider ) {
if ( !$provider instanceof AbstractPrimaryAuthenticationProvider ) {
throw new \RuntimeException(
'Expected instance of MediaWiki\\Auth\\AbstractPrimaryAuthenticationProvider, got ' .
get_class( $provider )
);
}
$provider->init( $this->logger, $this, $this->hookContainer, $this->config, $this->userNameUtils );
$id = $provider->getUniqueId();
if ( isset( $this->allAuthenticationProviders[$id] ) ) {
throw new \RuntimeException(
"Duplicate specifications for id $id (classes " .
get_class( $provider ) . ' and ' .
get_class( $this->allAuthenticationProviders[$id] ) . ')'
);
}
$this->allAuthenticationProviders[$id] = $provider;
$this->primaryAuthenticationProviders[$id] = $provider;
}
}
/***************************************************************************/
// region Authentication
/** @name Authentication */
/**
* Indicate whether user authentication is possible
*
* It may not be if the session is provided by something like OAuth
* for which each individual request includes authentication data.
*
* @return bool
*/
public function canAuthenticateNow() {
return $this->request->getSession()->canSetUser();
}
/**
* Start an authentication flow
*
* In addition to the AuthenticationRequests returned by
* $this->getAuthenticationRequests(), a client might include a
* CreateFromLoginAuthenticationRequest from a previous login attempt to
* preserve state.
*
* Instead of the AuthenticationRequests returned by
* $this->getAuthenticationRequests(), a client might pass a
* CreatedAccountAuthenticationRequest from an account creation that just
* succeeded to log in to the just-created account.
*
* @param AuthenticationRequest[] $reqs
* @param string $returnToUrl Url that REDIRECT responses should eventually
* return to.
* @return AuthenticationResponse See self::continueAuthentication()
*/
public function beginAuthentication( array $reqs, $returnToUrl ) {
$session = $this->request->getSession();
if ( !$session->canSetUser() ) {
// Caller should have called canAuthenticateNow()
$session->remove( self::AUTHN_STATE );
throw new LogicException( 'Authentication is not possible now' );
}
$guessUserName = null;
foreach ( $reqs as $req ) {
$req->returnToUrl = $returnToUrl;
// @codeCoverageIgnoreStart
if ( $req->username !== null && $req->username !== '' ) {
if ( $guessUserName === null ) {
$guessUserName = $req->username;
} elseif ( $guessUserName !== $req->username ) {
$guessUserName = null;
break;
}
}
// @codeCoverageIgnoreEnd
}
// Check for special-case login of a just-created account
$req = AuthenticationRequest::getRequestByClass(
$reqs, CreatedAccountAuthenticationRequest::class
);
if ( $req ) {
if ( !in_array( $req, $this->createdAccountAuthenticationRequests, true ) ) {
throw new LogicException(
'CreatedAccountAuthenticationRequests are only valid on ' .
'the same AuthManager that created the account'
);
}
$user = $this->userFactory->newFromName( (string)$req->username );
// @codeCoverageIgnoreStart
if ( !$user ) {
throw new \UnexpectedValueException(
"CreatedAccountAuthenticationRequest had invalid username \"{$req->username}\""
);
} elseif ( $user->getId() != $req->id ) {
throw new \UnexpectedValueException(
"ID for \"{$req->username}\" was {$user->getId()}, expected {$req->id}"
);
}
// @codeCoverageIgnoreEnd
$this->logger->info( 'Logging in {user} after account creation', [
'user' => $user->getName(),
] );
$ret = AuthenticationResponse::newPass( $user->getName() );
$performer = $session->getUser();
$this->setSessionDataForUser( $user );
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $ret ] );
$session->remove( self::AUTHN_STATE );
$this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
$ret, $user, $user->getName(), [
'performer' => $performer
] );
return $ret;
}
$this->removeAuthenticationSessionData( null );
foreach ( $this->getPreAuthenticationProviders() as $provider ) {
$status = $provider->testForAuthentication( $reqs );
if ( !$status->isGood() ) {
$this->logger->debug( 'Login failed in pre-authentication by ' . $provider->getUniqueId() );
$ret = AuthenticationResponse::newFail(
Status::wrap( $status )->getMessage()
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
[ $this->userFactory->newFromName( (string)$guessUserName ), $ret ]
);
$this->getHookRunner()->onAuthManagerLoginAuthenticateAudit( $ret, null, $guessUserName, [
'performer' => $session->getUser()
] );
return $ret;
}
}
$state = [
'reqs' => $reqs,
'returnToUrl' => $returnToUrl,
'guessUserName' => $guessUserName,
'providerIds' => $this->getProviderIds(),
'primary' => null,
'primaryResponse' => null,
'secondary' => [],
'maybeLink' => [],
'continueRequests' => [],
];
// Preserve state from a previous failed login
$req = AuthenticationRequest::getRequestByClass(
$reqs, CreateFromLoginAuthenticationRequest::class
);
if ( $req ) {
$state['maybeLink'] = $req->maybeLink;
}
$session = $this->request->getSession();
$session->setSecret( self::AUTHN_STATE, $state );
$session->persist();
return $this->continueAuthentication( $reqs );
}
/**
* Continue an authentication flow
*
* Return values are interpreted as follows:
* - status FAIL: Authentication failed. If $response->createRequest is
* set, that may be passed to self::beginAuthentication() or to
* self::beginAccountCreation() to preserve state.
* - status REDIRECT: The client should be redirected to the contained URL,
* new AuthenticationRequests should be made (if any), then
* AuthManager::continueAuthentication() should be called.
* - status UI: The client should be presented with a user interface for
* the fields in the specified AuthenticationRequests, then new
* AuthenticationRequests should be made, then
* AuthManager::continueAuthentication() should be called.
* - status RESTART: The user logged in successfully with a third-party
* service, but the third-party credentials aren't attached to any local
* account. This could be treated as a UI or a FAIL.
* - status PASS: Authentication was successful.
*
* @param AuthenticationRequest[] $reqs
* @return AuthenticationResponse
*/
public function continueAuthentication( array $reqs ) {
$session = $this->request->getSession();
try {
if ( !$session->canSetUser() ) {
// Caller should have called canAuthenticateNow()
// @codeCoverageIgnoreStart
throw new LogicException( 'Authentication is not possible now' );
// @codeCoverageIgnoreEnd
}
$state = $session->getSecret( self::AUTHN_STATE );
if ( !is_array( $state ) ) {
return AuthenticationResponse::newFail(
wfMessage( 'authmanager-authn-not-in-progress' )
);
}
if ( $state['providerIds'] !== $this->getProviderIds() ) {
// An inconsistent AuthManagerFilterProviders hook, or site configuration changed
// while the user was in the middle of authentication. The first is a bug, the
// second is rare but expected when deploying a config change. Try handle in a way
// that's useful for both cases.
// @codeCoverageIgnoreStart
MWExceptionHandler::logException( new NormalizedException(
'Authentication failed because of inconsistent provider array',
[ 'old' => json_encode( $state['providerIds'] ), 'new' => json_encode( $this->getProviderIds() ) ]
) );
$response = AuthenticationResponse::newFail(
wfMessage( 'authmanager-authn-not-in-progress' )
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
[ $this->userFactory->newFromName( (string)$state['guessUserName'] ), $response ]
);
$session->remove( self::AUTHN_STATE );
return $response;
// @codeCoverageIgnoreEnd
}
$state['continueRequests'] = [];
$guessUserName = $state['guessUserName'];
foreach ( $reqs as $req ) {
$req->returnToUrl = $state['returnToUrl'];
}
// Step 1: Choose a primary authentication provider, and call it until it succeeds.
if ( $state['primary'] === null ) {
// We haven't picked a PrimaryAuthenticationProvider yet
// @codeCoverageIgnoreStart
$guessUserName = null;
foreach ( $reqs as $req ) {
if ( $req->username !== null && $req->username !== '' ) {
if ( $guessUserName === null ) {
$guessUserName = $req->username;
} elseif ( $guessUserName !== $req->username ) {
$guessUserName = null;
break;
}
}
}
$state['guessUserName'] = $guessUserName;
// @codeCoverageIgnoreEnd
$state['reqs'] = $reqs;
foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
$res = $provider->beginPrimaryAuthentication( $reqs );
switch ( $res->status ) {
case AuthenticationResponse::PASS:
$state['primary'] = $id;
$state['primaryResponse'] = $res;
$this->logger->debug( "Primary login with $id succeeded" );
break 2;
case AuthenticationResponse::FAIL:
$this->logger->debug( "Login failed in primary authentication by $id" );
if ( $res->createRequest || $state['maybeLink'] ) {
$res->createRequest = new CreateFromLoginAuthenticationRequest(
$res->createRequest, $state['maybeLink']
);
}
$this->callMethodOnProviders(
self::CALL_ALL,
'postAuthentication',
[
$this->userFactory->newFromName( (string)$guessUserName ),
$res
]
);
$session->remove( self::AUTHN_STATE );
$this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
$res, null, $guessUserName, [
'performer' => $session->getUser()
] );
return $res;
case AuthenticationResponse::ABSTAIN:
// Continue loop
break;
case AuthenticationResponse::REDIRECT:
case AuthenticationResponse::UI:
$this->logger->debug( "Primary login with $id returned $res->status" );
$this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
$state['primary'] = $id;
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( self::AUTHN_STATE, $state );
return $res;
// @codeCoverageIgnoreStart
default:
throw new \DomainException(
get_class( $provider ) . "::beginPrimaryAuthentication() returned $res->status"
);
// @codeCoverageIgnoreEnd
}
}
// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in loop before, if passed
if ( $state['primary'] === null ) {
$this->logger->debug( 'Login failed in primary authentication because no provider accepted' );
$response = AuthenticationResponse::newFail(
wfMessage( 'authmanager-authn-no-primary' )
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
[ $this->userFactory->newFromName( (string)$guessUserName ), $response ]
);
$session->remove( self::AUTHN_STATE );
return $response;
}
} elseif ( $state['primaryResponse'] === null ) {
$provider = $this->getAuthenticationProvider( $state['primary'] );
if ( !$provider instanceof PrimaryAuthenticationProvider ) {
// Configuration changed? Force them to start over.
// @codeCoverageIgnoreStart
$response = AuthenticationResponse::newFail(
wfMessage( 'authmanager-authn-not-in-progress' )
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
[ $this->userFactory->newFromName( (string)$guessUserName ), $response ]
);
$session->remove( self::AUTHN_STATE );
return $response;
// @codeCoverageIgnoreEnd
}
$id = $provider->getUniqueId();
$res = $provider->continuePrimaryAuthentication( $reqs );
switch ( $res->status ) {
case AuthenticationResponse::PASS:
$state['primaryResponse'] = $res;
$this->logger->debug( "Primary login with $id succeeded" );
break;
case AuthenticationResponse::FAIL:
$this->logger->debug( "Login failed in primary authentication by $id" );
if ( $res->createRequest || $state['maybeLink'] ) {
$res->createRequest = new CreateFromLoginAuthenticationRequest(
$res->createRequest, $state['maybeLink']
);
}
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
[ $this->userFactory->newFromName( (string)$guessUserName ), $res ]
);
$session->remove( self::AUTHN_STATE );
$this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
$res, null, $guessUserName, [
'performer' => $session->getUser()
] );
return $res;
case AuthenticationResponse::REDIRECT:
case AuthenticationResponse::UI:
$this->logger->debug( "Primary login with $id returned $res->status" );
$this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( self::AUTHN_STATE, $state );
return $res;
default:
throw new \DomainException(
get_class( $provider ) . "::continuePrimaryAuthentication() returned $res->status"
);
}
}
// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in loop before, if passed
$res = $state['primaryResponse'];
if ( $res->username === null ) {
$provider = $this->getAuthenticationProvider( $state['primary'] );
if ( !$provider instanceof PrimaryAuthenticationProvider ) {
// Configuration changed? Force them to start over.
// @codeCoverageIgnoreStart
$response = AuthenticationResponse::newFail(
wfMessage( 'authmanager-authn-not-in-progress' )
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
[ $this->userFactory->newFromName( (string)$guessUserName ), $response ]
);
$session->remove( self::AUTHN_STATE );
return $response;
// @codeCoverageIgnoreEnd
}
if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK &&
$res->linkRequest &&
// don't confuse the user with an incorrect message if linking is disabled
$this->getAuthenticationProvider( ConfirmLinkSecondaryAuthenticationProvider::class )
) {
$state['maybeLink'][$res->linkRequest->getUniqueId()] = $res->linkRequest;
$msg = 'authmanager-authn-no-local-user-link';
} else {
$msg = 'authmanager-authn-no-local-user';
}
$this->logger->debug(
"Primary login with {$provider->getUniqueId()} succeeded, but returned no user"
);
$response = AuthenticationResponse::newRestart( wfMessage( $msg ) );
$response->neededRequests = $this->getAuthenticationRequestsInternal(
self::ACTION_LOGIN,
[],
$this->getPrimaryAuthenticationProviders() + $this->getSecondaryAuthenticationProviders()
);
if ( $res->createRequest || $state['maybeLink'] ) {
$response->createRequest = new CreateFromLoginAuthenticationRequest(
$res->createRequest, $state['maybeLink']
);
$response->neededRequests[] = $response->createRequest;
}
$this->fillRequests( $response->neededRequests, self::ACTION_LOGIN, null, true );
$session->setSecret( self::AUTHN_STATE, [
'reqs' => [], // Will be filled in later
'primary' => null,
'primaryResponse' => null,
'secondary' => [],
'continueRequests' => $response->neededRequests,
] + $state );
// Give the AuthManagerVerifyAuthentication hook a chance to interrupt - even though
// RESTART does not immediately result in a successful login, the response and session
// state can hold information identifying a (remote) user, and that could be turned
// into access to that user's account in a follow-up request.
if ( !$this->runVerifyHook( self::ACTION_LOGIN, null, $response, $state['primary'] ) ) {
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ null, $response ] );
$session->remove( self::AUTHN_STATE );
$this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
$response, null, null, [ 'performer' => $session->getUser() ]
);
return $response;
}
return $response;
}
// Step 2: Primary authentication succeeded, create the User object
// (and add the user locally if necessary)
$user = $this->userFactory->newFromName(
(string)$res->username,
UserRigorOptions::RIGOR_USABLE
);
if ( !$user ) {
$provider = $this->getAuthenticationProvider( $state['primary'] );
throw new \DomainException(
get_class( $provider ) . " returned an invalid username: {$res->username}"
);
}
if ( !$user->isRegistered() ) {
// User doesn't exist locally. Create it.
$this->logger->info( 'Auto-creating {user} on login', [
'user' => $user->getName(),
] );
// Also use $user as performer, because the performer will be used for permission
// checks and global rights extensions might add rights based on the username,
// even if the user doesn't exist at this point.
$status = $this->autoCreateUser( $user, $state['primary'], false, true, $user );
if ( !$status->isGood() ) {
$response = AuthenticationResponse::newFail(
Status::wrap( $status )->getMessage( 'authmanager-authn-autocreate-failed' )
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $response ] );
$session->remove( self::AUTHN_STATE );
$this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
$response, $user, $user->getName(), [
'performer' => $session->getUser()
] );
return $response;
}
}
// Step 3: Iterate over all the secondary authentication providers.
$beginReqs = $state['reqs'];
foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
if ( !isset( $state['secondary'][$id] ) ) {
// This provider isn't started yet, so we pass it the set
// of reqs from beginAuthentication instead of whatever
// might have been used by a previous provider in line.
$func = 'beginSecondaryAuthentication';
$res = $provider->beginSecondaryAuthentication( $user, $beginReqs );
} elseif ( !$state['secondary'][$id] ) {
$func = 'continueSecondaryAuthentication';
$res = $provider->continueSecondaryAuthentication( $user, $reqs );
} else {
continue;
}
switch ( $res->status ) {
case AuthenticationResponse::PASS:
$this->logger->debug( "Secondary login with $id succeeded" );
// fall through
case AuthenticationResponse::ABSTAIN:
$state['secondary'][$id] = true;
break;
case AuthenticationResponse::FAIL:
$this->logger->debug( "Login failed in secondary authentication by $id" );
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $res ] );
$session->remove( self::AUTHN_STATE );
$this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
$res, $user, $user->getName(), [
'performer' => $session->getUser()
] );
return $res;
case AuthenticationResponse::REDIRECT:
case AuthenticationResponse::UI:
$this->logger->debug( "Secondary login with $id returned " . $res->status );
$this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $user->getName() );
$state['secondary'][$id] = false;
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( self::AUTHN_STATE, $state );
return $res;
// @codeCoverageIgnoreStart
default:
throw new \DomainException(
get_class( $provider ) . "::{$func}() returned $res->status"
);
// @codeCoverageIgnoreEnd
}
}
// Step 4: Authentication complete! Give hook handlers a chance to interrupt, then
// set the user in the session and clean up.
$response = AuthenticationResponse::newPass( $user->getName() );
if ( !$this->runVerifyHook( self::ACTION_LOGIN, $user, $response, $state['primary'] ) ) {
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $response ] );
$session->remove( self::AUTHN_STATE );
$this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
$response, $user, $user->getName(), [
'performer' => $session->getUser(),
] );
return $response;
}
$this->logger->info( 'Login for {user} succeeded from {clientip}', [
'user' => $user->getName(),
'clientip' => $this->request->getIP(),
] );
$rememberMeConfig = $this->config->get( MainConfigNames::RememberMe );
if ( $rememberMeConfig === RememberMeAuthenticationRequest::ALWAYS_REMEMBER ) {
$rememberMe = true;
} elseif ( $rememberMeConfig === RememberMeAuthenticationRequest::NEVER_REMEMBER ) {
$rememberMe = false;
} else {
/** @var RememberMeAuthenticationRequest $req */
$req = AuthenticationRequest::getRequestByClass(
$beginReqs, RememberMeAuthenticationRequest::class
);
// T369668: Before we conclude, let's make sure the user hasn't specified
// that they want their login remembered elsewhere like in the central domain.
// If the user clicked "remember me" in the central domain, then we should
// prioritise that when we call continuePrimaryAuthentication() in the provider
// that makes calls continuePrimaryAuthentication(). NOTE: It is the responsibility
// of the provider to refresh the "remember me" state that will be applied to
// the local wiki.
$rememberMe = ( $req && $req->rememberMe ) ||
$this->getAuthenticationSessionData( self::REMEMBER_ME );
}
$loginWasInteractive = $this->getAuthenticationSessionData( self::LOGIN_WAS_INTERACTIVE, true );
$this->setSessionDataForUser( $user, $rememberMe, $loginWasInteractive );
$this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $response ] );
$performer = $session->getUser();
$session->remove( self::AUTHN_STATE );
$this->removeAuthenticationSessionData( null );
$this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
$response, $user, $user->getName(), [
'performer' => $performer
] );
return $response;
} catch ( \Exception $ex ) {
$session->remove( self::AUTHN_STATE );
throw $ex;
}
}
/**
* Whether security-sensitive operations should proceed.
*
* A "security-sensitive operation" is something like a password or email
* change, that would normally have a "reenter your password to confirm"
* box if we only supported password-based authentication.
*
* @param string $operation Operation being checked. This should be a
* message-key-like string such as 'change-password' or 'change-email'.
* @return string One of the SEC_* constants.
*/
public function securitySensitiveOperationStatus( $operation ) {
$status = self::SEC_OK;
$this->logger->debug( __METHOD__ . ": Checking $operation" );
$session = $this->request->getSession();
$aId = $session->getUser()->getId();
if ( $aId === 0 ) {
// User isn't authenticated. DWIM?
$status = $this->canAuthenticateNow() ? self::SEC_REAUTH : self::SEC_FAIL;
$this->logger->info( __METHOD__ . ": Not logged in! $operation is $status" );
return $status;
}
if ( $session->canSetUser() ) {
$id = $session->get( 'AuthManager:lastAuthId' );
$last = $session->get( 'AuthManager:lastAuthTimestamp' );
if ( $id !== $aId || $last === null ) {
$timeSinceLogin = PHP_INT_MAX; // Forever ago
} else {
$timeSinceLogin = max( 0, time() - $last );
}
$thresholds = $this->config->get( MainConfigNames::ReauthenticateTime );
if ( isset( $thresholds[$operation] ) ) {
$threshold = $thresholds[$operation];
} elseif ( isset( $thresholds['default'] ) ) {
$threshold = $thresholds['default'];
} else {
throw new \UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
}
if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
$status = self::SEC_REAUTH;
}
} else {
$timeSinceLogin = -1;
$pass = $this->config->get(
MainConfigNames::AllowSecuritySensitiveOperationIfCannotReauthenticate );
if ( isset( $pass[$operation] ) ) {
$status = $pass[$operation] ? self::SEC_OK : self::SEC_FAIL;
} elseif ( isset( $pass['default'] ) ) {
$status = $pass['default'] ? self::SEC_OK : self::SEC_FAIL;
} else {
throw new \UnexpectedValueException(
'$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
);
}
}
$this->getHookRunner()->onSecuritySensitiveOperationStatus(
$status, $operation, $session, $timeSinceLogin );
// If authentication is not possible, downgrade from "REAUTH" to "FAIL".
if ( !$this->canAuthenticateNow() && $status === self::SEC_REAUTH ) {
$status = self::SEC_FAIL;
}
$this->logger->info( __METHOD__ . ": $operation is $status for '{user}'",
[
'user' => $session->getUser()->getName(),
'clientip' => $this->getRequest()->getIP(),
]
);
return $status;
}
/**
* Determine whether a username can authenticate
*
* This is mainly for internal purposes and only takes authentication data into account,
* not things like blocks that can change without the authentication system being aware.
*
* @param string $username MediaWiki username
* @return bool
*/
public function userCanAuthenticate( $username ) {
foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
if ( $provider->testUserCanAuthenticate( $username ) ) {
return true;
}
}
return false;
}
/**
* Provide normalized versions of the username for security checks
*
* Since different providers can normalize the input in different ways,
* this returns an array of all the different ways the name might be
* normalized for authentication.
*
* The returned strings should not be revealed to the user, as that might
* leak private information (e.g. an email address might be normalized to a
* username).
*
* @param string $username
* @return string[]
*/
public function normalizeUsername( $username ) {
$ret = [];
foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
$normalized = $provider->providerNormalizeUsername( $username );
if ( $normalized !== null ) {
$ret[$normalized] = true;
}
}
return array_keys( $ret );
}
/**
* Call this method to set the request context user for the current request
* from the context session user.
*
* Useful in cases where we need to make sure that a MediaWiki request outputs
* correct context data for a user who has just been logged-in.
*
* The method will also update the global language variable based on the
* session's user's context language.
*
* This won't affect objects which already made a copy of the user or the
* context, so it shouldn't be relied on too heavily, but can help to make the
* UI more consistent after changing the user. Typically used after a successful
* AuthManager action that changed the session user (e.g.
* AuthManager::autoCreateUser() with the login flag set).
*/
public function setRequestContextUserFromSessionUser(): void {
$context = RequestContext::getMain();
$user = $context->getRequest()->getSession()->getUser();
StubGlobalUser::setUser( $user );
$context->setUser( $user );
// phpcs:ignore MediaWiki.Usage.ExtendClassUsage.FunctionVarUsage
global $wgLang;
// phpcs:ignore MediaWiki.Usage.ExtendClassUsage.FunctionVarUsage
$wgLang = $context->getLanguage();
}
// endregion -- end of Authentication
/***************************************************************************/
// region Authentication data changing
/** @name Authentication data changing */
/**
* Revoke any authentication credentials for a user
*
* After this, the user should no longer be able to log in.
*
* @param string $username
*/
public function revokeAccessForUser( $username ) {
$this->logger->info( 'Revoking access for {user}', [
'user' => $username,
] );
$this->callMethodOnProviders( self::CALL_PRIMARY | self::CALL_SECONDARY, 'providerRevokeAccessForUser',
[ $username ]
);
}
/**
* Validate a change of authentication data (e.g. passwords)
* @param AuthenticationRequest $req
* @param bool $checkData If false, $req hasn't been loaded from the
* submission so checks on user-submitted fields should be skipped. $req->username is
* considered user-submitted for this purpose, even if it cannot be changed via
* $req->loadFromSubmission.
* @return Status
*/
public function allowsAuthenticationDataChange( AuthenticationRequest $req, $checkData = true ) {
$any = false;
$providers = $this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders();
foreach ( $providers as $provider ) {
$status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
if ( !$status->isGood() ) {
// If status is not good because reset email password last attempt was within
// $wgPasswordReminderResendTime then return good status with throttled-mailpassword value;
// otherwise, return the $status wrapped.
return $status->hasMessage( 'throttled-mailpassword' )
? Status::newGood( 'throttled-mailpassword' )
: Status::wrap( $status );
}
$any = $any || $status->value !== 'ignored';
}
if ( !$any ) {
return Status::newGood( 'ignored' )
->warning( 'authmanager-change-not-supported' );
}
return Status::newGood();
}
/**
* Change authentication data (e.g. passwords)
*
* If $req was returned for AuthManager::ACTION_CHANGE, using $req should
* result in a successful login in the future.
*
* If $req was returned for AuthManager::ACTION_REMOVE, using $req should
* no longer result in a successful login.
*
* This method should only be called if allowsAuthenticationDataChange( $req, true )
* returned success.
*
* @param AuthenticationRequest $req
* @param bool $isAddition Set true if this represents an addition of
* credentials rather than a change. The main difference is that additions
* should not invalidate BotPasswords. If you're not sure, leave it false.
*/
public function changeAuthenticationData( AuthenticationRequest $req, $isAddition = false ) {
$this->logger->info( 'Changing authentication data for {user} class {what}', [
'user' => is_string( $req->username ) ? $req->username : '<no name>',
'what' => get_class( $req ),
] );
$this->callMethodOnProviders( self::CALL_PRIMARY | self::CALL_SECONDARY, 'providerChangeAuthenticationData',
[ $req ]
);
// When the main account's authentication data is changed, invalidate
// all BotPasswords too.
if ( !$isAddition ) {
$this->botPasswordStore->invalidateUserPasswords( (string)$req->username );
}
}
// endregion -- end of Authentication data changing
/***************************************************************************/
// region Account creation
/** @name Account creation */
/**
* Determine whether accounts can be created
* @return bool
*/
public function canCreateAccounts() {
foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
switch ( $provider->accountCreationType() ) {
case PrimaryAuthenticationProvider::TYPE_CREATE:
case PrimaryAuthenticationProvider::TYPE_LINK:
return true;
}
}
return false;
}
/**
* Determine whether a particular account can be created
* @param string $username MediaWiki username
* @param array $options
* - flags: (int) Bitfield of IDBAccessObject::READ_* constants, default IDBAccessObject::READ_NORMAL
* - creating: (bool) For internal use only. Never specify this.
* @return Status
*/
public function canCreateAccount( $username, $options = [] ) {
// Back compat
if ( is_int( $options ) ) {
$options = [ 'flags' => $options ];
}
$options += [
'flags' => IDBAccessObject::READ_NORMAL,
'creating' => false,
];
// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
$flags = $options['flags'];
if ( !$this->canCreateAccounts() ) {
return Status::newFatal( 'authmanager-create-disabled' );
}
if ( $this->userExists( $username, $flags ) ) {
return Status::newFatal( 'userexists' );
}
$user = $this->userFactory->newFromName( (string)$username, UserRigorOptions::RIGOR_CREATABLE );
if ( !is_object( $user ) ) {
return Status::newFatal( 'noname' );
} else {
$user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
if ( $user->isRegistered() ) {
return Status::newFatal( 'userexists' );
}
}
// Denied by providers?
$providers = $this->getPreAuthenticationProviders() +
$this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders();
foreach ( $providers as $provider ) {
$status = $provider->testUserForCreation( $user, false, $options );
if ( !$status->isGood() ) {
return Status::wrap( $status );
}
}
return Status::newGood();
}
/**
* @param callable $authorizer ( string $action, PageIdentity $target, PermissionStatus $status )
* @param string $action
* @return StatusValue
*/
private function authorizeInternal(
callable $authorizer,
string $action
): StatusValue {
// Wiki is read-only?
if ( $this->readOnlyMode->isReadOnly() ) {
return StatusValue::newFatal( wfMessage( 'readonlytext', $this->readOnlyMode->getReason() ) );
}
$permStatus = new PermissionStatus();
if ( !$authorizer(
$action,
SpecialPage::getTitleFor( 'CreateAccount' ),
$permStatus
) ) {
return $permStatus;
}
$ip = $this->getRequest()->getIP();
if ( $this->blockManager->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
return StatusValue::newFatal( 'sorbs_create_account_reason' );
}
return StatusValue::newGood();
}
/**
* Check whether $creator can create accounts.
*
* @note this method does not guarantee full permissions check, so it should only
* be used to to decide whether to show a form. To authorize the account creation
* action use {@link self::authorizeCreateAccount} instead.
*
* @since 1.39
* @param Authority $creator
* @return StatusValue
*/
public function probablyCanCreateAccount( Authority $creator ): StatusValue {
return $this->authorizeInternal(
static function (
string $action,
PageIdentity $target,
PermissionStatus $status
) use ( $creator ) {
return $creator->probablyCan( $action, $target, $status );
},
'createaccount'
);
}
/**
* Authorize the account creation by $creator
*
* @note this method should be used right before the account is created.
* To check whether a current performer has the potential to create accounts,
* use {@link self::probablyCanCreateAccount} instead.
*
* @since 1.39
* @param Authority $creator
* @return StatusValue
*/
public function authorizeCreateAccount( Authority $creator ): StatusValue {
return $this->authorizeInternal(
static function (
string $action,
PageIdentity $target,
PermissionStatus $status
) use ( $creator ) {
return $creator->authorizeWrite( $action, $target, $status );
},
'createaccount'
);
}
/**
* Start an account creation flow
*
* In addition to the AuthenticationRequests returned by
* $this->getAuthenticationRequests(), a client might include a
* CreateFromLoginAuthenticationRequest from a previous login attempt. If
* <code>
* $createFromLoginAuthenticationRequest->hasPrimaryStateForAction( AuthManager::ACTION_CREATE )
* </code>
* returns true, any AuthenticationRequest::PRIMARY_REQUIRED requests
* should be omitted. If the CreateFromLoginAuthenticationRequest has a
* username set, that username must be used for all other requests.
*
* @param Authority $creator User doing the account creation
* @param AuthenticationRequest[] $reqs
* @param string $returnToUrl Url that REDIRECT responses should eventually
* return to.
* @return AuthenticationResponse
*/
public function beginAccountCreation( Authority $creator, array $reqs, $returnToUrl ) {
$session = $this->request->getSession();
if ( $creator->isTemp() ) {
// For a temp account creating a permanent account, we do not want the temporary
// account to be associated with the created permanent account. To avoid this,
// set the session user to a new anonymous user, save it, and set the request
// context from the new session user account. (T393628)
$creator = $this->userFactory->newAnonymous();
$session->setUser( $creator );
// Ensure the temporary account username is also cleared from the session, this is set
// in TempUserCreator::acquireAndStashName
$session->remove( 'TempUser:name' );
$session->save();
$this->setRequestContextUserFromSessionUser();
}
if ( !$this->canCreateAccounts() ) {
// Caller should have called canCreateAccounts()
$session->remove( self::ACCOUNT_CREATION_STATE );
throw new LogicException( 'Account creation is not possible' );
}
try {
$username = AuthenticationRequest::getUsernameFromRequests( $reqs );
} catch ( \UnexpectedValueException $ex ) {
$username = null;
}
if ( $username === null ) {
$this->logger->debug( __METHOD__ . ': No username provided' );
return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
}
// Permissions check
$status = Status::wrap( $this->authorizeCreateAccount( $creator ) );
if ( !$status->isGood() ) {
$this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
'user' => $username,
'creator' => $creator->getUser()->getName(),
'reason' => $status->getWikiText( false, false, 'en' )
] );
return AuthenticationResponse::newFail( $status->getMessage() );
}
$status = $this->canCreateAccount(
$username, [ 'flags' => IDBAccessObject::READ_LOCKING, 'creating' => true ]
);
if ( !$status->isGood() ) {
$this->logger->debug( __METHOD__ . ': {user} cannot be created: {reason}', [
'user' => $username,
'creator' => $creator->getUser()->getName(),
'reason' => $status->getWikiText( false, false, 'en' )
] );
return AuthenticationResponse::newFail( $status->getMessage() );
}
$user = $this->userFactory->newFromName( (string)$username, UserRigorOptions::RIGOR_CREATABLE );
foreach ( $reqs as $req ) {
$req->username = $username;
$req->returnToUrl = $returnToUrl;
if ( $req instanceof UserDataAuthenticationRequest ) {
// @phan-suppress-next-line PhanTypeMismatchArgumentNullable user should be checked and valid here
$status = $req->populateUser( $user );
if ( !$status->isGood() ) {
$status = Status::wrap( $status );
$session->remove( self::ACCOUNT_CREATION_STATE );
$this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
'user' => $user->getName(),
'creator' => $creator->getUser()->getName(),
'reason' => $status->getWikiText( false, false, 'en' ),
] );
return AuthenticationResponse::newFail( $status->getMessage() );
}
}
}
$this->removeAuthenticationSessionData( null );
$state = [
'username' => $username,
'userid' => 0,
'creatorid' => $creator->getUser()->getId(),
'creatorname' => $creator->getUser()->getName(),
'reqs' => $reqs,
'returnToUrl' => $returnToUrl,
'providerIds' => $this->getProviderIds(),
'primary' => null,
'primaryResponse' => null,
'secondary' => [],
'continueRequests' => [],
'maybeLink' => [],
'ranPreTests' => false,
];
// Special case: converting a login to an account creation
$req = AuthenticationRequest::getRequestByClass(
$reqs, CreateFromLoginAuthenticationRequest::class
);
if ( $req ) {
$state['maybeLink'] = $req->maybeLink;
if ( $req->createRequest ) {
$reqs[] = $req->createRequest;
$state['reqs'][] = $req->createRequest;
}
}
$session->setSecret( self::ACCOUNT_CREATION_STATE, $state );
$session->persist();
$this->logger->debug( __METHOD__ . ': Proceeding with account creation for {username} by {creator}', [
'username' => $user->getName(),
'creator' => $creator->getUser()->getName(),
] );
return $this->continueAccountCreation( $reqs );
}
/**
* Continue an account creation flow
* @param AuthenticationRequest[] $reqs
* @return AuthenticationResponse
*/
public function continueAccountCreation( array $reqs ) {
$session = $this->request->getSession();
try {
if ( !$this->canCreateAccounts() ) {
// Caller should have called canCreateAccounts()
$session->remove( self::ACCOUNT_CREATION_STATE );
throw new LogicException( 'Account creation is not possible' );
}
$state = $session->getSecret( self::ACCOUNT_CREATION_STATE );
if ( !is_array( $state ) ) {
return AuthenticationResponse::newFail(
wfMessage( 'authmanager-create-not-in-progress' )
);
}
$state['continueRequests'] = [];
// Step 0: Prepare and validate the input
$user = $this->userFactory->newFromName(
(string)$state['username'],
UserRigorOptions::RIGOR_CREATABLE
);
if ( !is_object( $user ) ) {
$session->remove( self::ACCOUNT_CREATION_STATE );
$this->logger->debug( __METHOD__ . ': Invalid username', [
'user' => $state['username'],
] );
return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
}
if ( $state['creatorid'] ) {
$creator = $this->userFactory->newFromId( (int)$state['creatorid'] );
} else {
$creator = $this->userFactory->newAnonymous();
$creator->setName( $state['creatorname'] );
}
if ( $state['providerIds'] !== $this->getProviderIds() ) {
// An inconsistent AuthManagerFilterProviders hook, or site configuration changed
// while the user was in the middle of authentication. The first is a bug, the
// second is rare but expected when deploying a config change. Try handle in a way
// that's useful for both cases.
// @codeCoverageIgnoreStart
MWExceptionHandler::logException( new NormalizedException(
'Authentication failed because of inconsistent provider array',
[ 'old' => json_encode( $state['providerIds'] ), 'new' => json_encode( $this->getProviderIds() ) ]
) );
$ret = AuthenticationResponse::newFail(
wfMessage( 'authmanager-create-not-in-progress' )
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
$session->remove( self::ACCOUNT_CREATION_STATE );
return $ret;
// @codeCoverageIgnoreEnd
}
// Avoid account creation races on double submissions
$cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
$lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $user->getName() ) ) );
if ( !$lock ) {
// Don't clear AuthManager::accountCreationState for this code
// path because the process that won the race owns it.
$this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
return AuthenticationResponse::newFail( wfMessage( 'usernameinprogress' ) );
}
// Permissions check
$status = Status::wrap( $this->authorizeCreateAccount( $creator ) );
if ( !$status->isGood() ) {
$this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
'user' => $user->getName(),
'creator' => $creator->getName(),
'reason' => $status->getWikiText( false, false, 'en' )
] );
$ret = AuthenticationResponse::newFail( $status->getMessage() );
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
$session->remove( self::ACCOUNT_CREATION_STATE );
return $ret;
}
// Load from primary DB for existence check
$user->load( IDBAccessObject::READ_LOCKING );
if ( $state['userid'] === 0 ) {
if ( $user->isRegistered() ) {
$this->logger->debug( __METHOD__ . ': User exists locally', [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$ret = AuthenticationResponse::newFail( wfMessage( 'userexists' ) );
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
$session->remove( self::ACCOUNT_CREATION_STATE );
return $ret;
}
} else {
if ( !$user->isRegistered() ) {
$this->logger->debug( __METHOD__ . ': User does not exist locally when it should', [
'user' => $user->getName(),
'creator' => $creator->getName(),
'expected_id' => $state['userid'],
] );
throw new \UnexpectedValueException(
"User \"{$state['username']}\" should exist now, but doesn't!"
);
}
if ( $user->getId() !== $state['userid'] ) {
$this->logger->debug( __METHOD__ . ': User ID/name mismatch', [
'user' => $user->getName(),
'creator' => $creator->getName(),
'expected_id' => $state['userid'],
'actual_id' => $user->getId(),
] );
throw new \UnexpectedValueException(
"User \"{$state['username']}\" exists, but " .
"ID {$user->getId()} !== {$state['userid']}!"
);
}
}
foreach ( $state['reqs'] as $req ) {
if ( $req instanceof UserDataAuthenticationRequest ) {
$status = $req->populateUser( $user );
if ( !$status->isGood() ) {
// This should never happen...
$status = Status::wrap( $status );
$this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
'user' => $user->getName(),
'creator' => $creator->getName(),
'reason' => $status->getWikiText( false, false, 'en' ),
] );
$ret = AuthenticationResponse::newFail( $status->getMessage() );
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
[ $user, $creator, $ret ]
);
$session->remove( self::ACCOUNT_CREATION_STATE );
return $ret;
}
}
}
foreach ( $reqs as $req ) {
$req->returnToUrl = $state['returnToUrl'];
$req->username = $state['username'];
}
// Run pre-creation tests, if we haven't already
if ( !$state['ranPreTests'] ) {
$providers = $this->getPreAuthenticationProviders() +
$this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders();
foreach ( $providers as $id => $provider ) {
$status = $provider->testForAccountCreation( $user, $creator, $reqs );
if ( !$status->isGood() ) {
$this->logger->debug( __METHOD__ . ": Fail in pre-authentication by $id", [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$ret = AuthenticationResponse::newFail(
Status::wrap( $status )->getMessage()
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
[ $user, $creator, $ret ]
);
$session->remove( self::ACCOUNT_CREATION_STATE );
return $ret;
}
}
$state['ranPreTests'] = true;
}
// Step 1: Choose a primary authentication provider and call it until it succeeds.
if ( $state['primary'] === null ) {
// We haven't picked a PrimaryAuthenticationProvider yet
foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_NONE ) {
continue;
}
$res = $provider->beginPrimaryAccountCreation( $user, $creator, $reqs );
switch ( $res->status ) {
case AuthenticationResponse::PASS:
$this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$state['primary'] = $id;
$state['primaryResponse'] = $res;
break 2;
case AuthenticationResponse::FAIL:
$this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
[ $user, $creator, $res ]
);
$session->remove( self::ACCOUNT_CREATION_STATE );
return $res;
case AuthenticationResponse::ABSTAIN:
// Continue loop
break;
case AuthenticationResponse::REDIRECT:
case AuthenticationResponse::UI:
$this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
$state['primary'] = $id;
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( self::ACCOUNT_CREATION_STATE, $state );
return $res;
// @codeCoverageIgnoreStart
default:
throw new \DomainException(
get_class( $provider ) . "::beginPrimaryAccountCreation() returned $res->status"
);
// @codeCoverageIgnoreEnd
}
}
// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in loop before, if passed
if ( $state['primary'] === null ) {
$this->logger->debug( __METHOD__ . ': Primary creation failed because no provider accepted', [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$ret = AuthenticationResponse::newFail(
wfMessage( 'authmanager-create-no-primary' )
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
$session->remove( self::ACCOUNT_CREATION_STATE );
return $ret;
}
} elseif ( $state['primaryResponse'] === null ) {
$provider = $this->getAuthenticationProvider( $state['primary'] );
if ( !$provider instanceof PrimaryAuthenticationProvider ) {
// Configuration changed? Force them to start over.
// @codeCoverageIgnoreStart
$ret = AuthenticationResponse::newFail(
wfMessage( 'authmanager-create-not-in-progress' )
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
$session->remove( self::ACCOUNT_CREATION_STATE );
return $ret;
// @codeCoverageIgnoreEnd
}
$id = $provider->getUniqueId();
$res = $provider->continuePrimaryAccountCreation( $user, $creator, $reqs );
switch ( $res->status ) {
case AuthenticationResponse::PASS:
$this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$state['primaryResponse'] = $res;
break;
case AuthenticationResponse::FAIL:
$this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
[ $user, $creator, $res ]
);
$session->remove( self::ACCOUNT_CREATION_STATE );
return $res;
case AuthenticationResponse::REDIRECT:
case AuthenticationResponse::UI:
$this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( self::ACCOUNT_CREATION_STATE, $state );
return $res;
default:
throw new \DomainException(
get_class( $provider ) . "::continuePrimaryAccountCreation() returned $res->status"
);
}
}
// Step 2: Primary authentication succeeded. Give hook handlers a chance to interrupt,
// then create the User object and add the user locally.
if ( $state['userid'] === 0 ) {
// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set if we passed step 1
$response = $state['primaryResponse'];
if ( !$this->runVerifyHook( self::ACTION_CREATE, $user, $response, $state['primary'] ) ) {
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
[ $user, $creator, $response ]
);
$session->remove( self::ACCOUNT_CREATION_STATE );
return $response;
}
$this->logger->info( 'Creating user {user} during account creation', [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$status = $user->addToDatabase();
if ( !$status->isOK() ) {
// @codeCoverageIgnoreStart
$ret = AuthenticationResponse::newFail( $status->getMessage() );
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
$session->remove( self::ACCOUNT_CREATION_STATE );
return $ret;
// @codeCoverageIgnoreEnd
}
$this->setDefaultUserOptions( $user, $creator->isAnon() );
$this->getHookRunner()->onLocalUserCreated( $user, false );
$user->saveSettings();
$state['userid'] = $user->getId();
// Update user count
DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'users' => 1 ] ) );
// Watch user's userpage and talk page
$this->watchlistManager->addWatchIgnoringRights( $user, $user->getUserPage() );
// Inform the provider
// @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in loop before, if passed
$logSubtype = $provider->finishAccountCreation( $user, $creator, $state['primaryResponse'] );
// Log the creation
if ( $this->config->get( MainConfigNames::NewUserLog ) ) {
$isNamed = $creator->isNamed();
$logEntry = new \ManualLogEntry(
'newusers',
$logSubtype ?: ( $isNamed ? 'create2' : 'create' )
);
$logEntry->setPerformer( $isNamed ? $creator : $user );
$logEntry->setTarget( $user->getUserPage() );
/** @var CreationReasonAuthenticationRequest $req */
$req = AuthenticationRequest::getRequestByClass(
$state['reqs'], CreationReasonAuthenticationRequest::class
);
$logEntry->setComment( $req ? $req->reason : '' );
$logEntry->setParameters( [
'4::userid' => $user->getId(),
] );
$logid = $logEntry->insert();
$logEntry->publish( $logid );
}
}
// Step 3: Iterate over all the secondary authentication providers.
$beginReqs = $state['reqs'];
foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
if ( !isset( $state['secondary'][$id] ) ) {
// This provider isn't started yet, so we pass it the set
// of reqs from beginAuthentication instead of whatever
// might have been used by a previous provider in line.
$func = 'beginSecondaryAccountCreation';
$res = $provider->beginSecondaryAccountCreation( $user, $creator, $beginReqs );
} elseif ( !$state['secondary'][$id] ) {
$func = 'continueSecondaryAccountCreation';
$res = $provider->continueSecondaryAccountCreation( $user, $creator, $reqs );
} else {
continue;
}
switch ( $res->status ) {
case AuthenticationResponse::PASS:
$this->logger->debug( __METHOD__ . ": Secondary creation passed by $id", [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
// fall through
case AuthenticationResponse::ABSTAIN:
$state['secondary'][$id] = true;
break;
case AuthenticationResponse::REDIRECT:
case AuthenticationResponse::UI:
$this->logger->debug( __METHOD__ . ": Secondary creation $res->status by $id", [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
$state['secondary'][$id] = false;
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( self::ACCOUNT_CREATION_STATE, $state );
return $res;
case AuthenticationResponse::FAIL:
throw new \DomainException(
get_class( $provider ) . "::{$func}() returned $res->status." .
' Secondary providers are not allowed to fail account creation, that' .
' should have been done via testForAccountCreation().'
);
// @codeCoverageIgnoreStart
default:
throw new \DomainException(
get_class( $provider ) . "::{$func}() returned $res->status"
);
// @codeCoverageIgnoreEnd
}
}
$id = $user->getId();
$name = $user->getName();
$req = new CreatedAccountAuthenticationRequest( $id, $name );
$ret = AuthenticationResponse::newPass( $name );
$ret->loginRequest = $req;
$this->createdAccountAuthenticationRequests[] = $req;
$this->logger->info( __METHOD__ . ': Account creation succeeded for {user}', [
'user' => $user->getName(),
'creator' => $creator->getName(),
] );
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
$session->remove( self::ACCOUNT_CREATION_STATE );
$this->removeAuthenticationSessionData( null );
return $ret;
} catch ( \Exception $ex ) {
$session->remove( self::ACCOUNT_CREATION_STATE );
throw $ex;
}
}
/**
* Auto-create an account, and optionally log into that account
*
* PrimaryAuthenticationProviders can invoke this method by returning a PASS from
* beginPrimaryAuthentication/continuePrimaryAuthentication with the username of a
* non-existing user. SessionProviders can invoke it by returning a SessionInfo with
* the username of a non-existing user from provideSessionInfo(). Calling this method
* explicitly (e.g. from a maintenance script) is also fine.
*
* @param User $user User to auto-create
* @param string $source What caused the auto-creation? This must be one of:
* - the ID of a PrimaryAuthenticationProvider,
* - one of the self::AUTOCREATE_SOURCE_* constants
* @param bool $login Whether to also log the user in
* @param bool $log Whether to generate a user creation log entry (since 1.36)
* @param Authority|null $performer The performer of the action to use for user rights
* checking. Normally null to indicate an anonymous performer. Added in 1.42 for
* Special:CreateLocalAccount (T234371).
*
* @return Status Good if user was created, Ok if user already existed, otherwise Fatal
*/
public function autoCreateUser(
User $user,
$source,
$login = true,
$log = true,
?Authority $performer = null
) {
$validSources = [
self::AUTOCREATE_SOURCE_SESSION,
self::AUTOCREATE_SOURCE_MAINT,
self::AUTOCREATE_SOURCE_TEMP
];
if ( !in_array( $source, $validSources, true )
&& !$this->getAuthenticationProvider( $source ) instanceof PrimaryAuthenticationProvider
) {
throw new InvalidArgumentException( "Unknown auto-creation source: $source" );
}
$username = $user->getName();
// Try the local user from the replica DB, then fall back to the primary.
$localUserIdentity = $this->userIdentityLookup->getUserIdentityByName( $username );
// @codeCoverageIgnoreStart
if ( ( !$localUserIdentity || !$localUserIdentity->isRegistered() )
&& $this->loadBalancer->getReaderIndex() !== 0
) {
$localUserIdentity = $this->userIdentityLookup->getUserIdentityByName(
$username, IDBAccessObject::READ_LATEST
);
}
// @codeCoverageIgnoreEnd
$localId = ( $localUserIdentity && $localUserIdentity->isRegistered() )
? $localUserIdentity->getId()
: null;
if ( $localId ) {
$this->logger->debug( __METHOD__ . ': {username} already exists locally', [
'username' => $username,
] );
$user->setId( $localId );
// Can't rely on a replica read, not even when getUserIdentityByName() used
// READ_NORMAL, because that method has an in-process cache not shared
// with loadFromId.
$user->loadFromId( IDBAccessObject::READ_LATEST );
if ( $login ) {
$remember = $source === self::AUTOCREATE_SOURCE_TEMP;
$this->setSessionDataForUser( $user, $remember, false );
}
return Status::newGood()->warning( 'userexists' );
}
// Wiki is read-only?
if ( $this->readOnlyMode->isReadOnly() ) {
$reason = $this->readOnlyMode->getReason();
$this->logger->debug( __METHOD__ . ': denied because of read only mode: {reason}', [
'username' => $username,
'reason' => $reason,
] );
$user->setId( 0 );
$user->loadFromId();
return Status::newFatal( wfMessage( 'readonlytext', $reason ) );
}
// If there is a non-anonymous performer, don't use their session
$session = null;
if ( !$performer || $performer->getUser()->equals( $user ) ) {
$session = $this->request->getSession();
}
// Check the session, if we tried to create this user already there's
// no point in retrying.
if ( $session && $session->get( self::AUTOCREATE_BLOCKLIST ) ) {
$this->logger->debug( __METHOD__ . ': blacklisted in session {sessionid}', [
'username' => $username,
'sessionid' => $session->getId(),
] );
$user->setId( 0 );
$user->loadFromId();
$reason = $session->get( self::AUTOCREATE_BLOCKLIST );
if ( $reason instanceof StatusValue ) {
return Status::wrap( $reason );
} else {
return Status::newFatal( $reason );
}
}
// Is the username usable? (Previously isCreatable() was checked here but
// that doesn't work with auto-creation of TempUser accounts by CentralAuth)
if ( !$this->userNameUtils->isUsable( $username ) ) {
$this->logger->debug( __METHOD__ . ': name "{username}" is not usable', [
'username' => $username,
] );
if ( $session ) {
$session->set( self::AUTOCREATE_BLOCKLIST, 'noname' );
}
$user->setId( 0 );
$user->loadFromId();
return Status::newFatal( 'noname' );
}
// Is the IP user able to create accounts?
$performer ??= $this->userFactory->newAnonymous();
$bypassAuthorization = $session ? $session->getProvider()->canAlwaysAutocreate() : false;
if ( $source !== self::AUTOCREATE_SOURCE_MAINT && !$bypassAuthorization ) {
$status = $this->authorizeAutoCreateAccount( $performer );
if ( !$status->isOK() ) {
$this->logger->debug( __METHOD__ . ': cannot create or autocreate accounts', [
'username' => $username,
'creator' => $performer->getUser()->getName(),
] );
if ( $session ) {
$session->set( self::AUTOCREATE_BLOCKLIST, $status );
$session->persist();
}
$user->setId( 0 );
$user->loadFromId();
return Status::wrap( $status );
}
}
// Avoid account creation races on double submissions
$cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
$lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
if ( !$lock ) {
$this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
'user' => $username,
] );
$user->setId( 0 );
$user->loadFromId();
return Status::newFatal( 'usernameinprogress' );
}
// Denied by providers?
$options = [
'flags' => IDBAccessObject::READ_LATEST,
'creating' => true,
'canAlwaysAutocreate' => $session && $session->getProvider()->canAlwaysAutocreate(),
];
$providers = $this->getPreAuthenticationProviders() +
$this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders();
foreach ( $providers as $provider ) {
$status = $provider->testUserForCreation( $user, $source, $options );
if ( !$status->isGood() ) {
$ret = Status::wrap( $status );
$this->logger->debug( __METHOD__ . ': Provider denied creation of {username}: {reason}', [
'username' => $username,
'reason' => $ret->getWikiText( false, false, 'en' ),
] );
if ( $session ) {
$session->set( self::AUTOCREATE_BLOCKLIST, $status );
}
$user->setId( 0 );
$user->loadFromId();
return $ret;
}
}
$backoffKey = $cache->makeKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
if ( $cache->get( $backoffKey ) ) {
$this->logger->debug( __METHOD__ . ': {username} denied by prior creation attempt failures', [
'username' => $username,
] );
$user->setId( 0 );
$user->loadFromId();
return Status::newFatal( 'authmanager-autocreate-exception' );
}
// Checks passed, create the user...
$from = $_SERVER['REQUEST_URI'] ?? 'CLI';
$this->logger->info( __METHOD__ . ': creating new user ({username}) - from: {from}', [
'username' => $username,
'from' => $from,
] );
// Ignore warnings about primary connections/writes...hard to avoid here
$trxProfiler = \Profiler::instance()->getTransactionProfiler();
$scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
try {
$status = $user->addToDatabase();
if ( !$status->isOK() ) {
// Double-check for a race condition (T70012). We make use of the fact that when
// addToDatabase fails due to the user already existing, the user object gets loaded.
if ( $user->getId() ) {
$this->logger->info( __METHOD__ . ': {username} already exists locally (race)', [
'username' => $username,
] );
if ( $login ) {
$remember = $source === self::AUTOCREATE_SOURCE_TEMP;
$this->setSessionDataForUser( $user, $remember, false );
}
$status = Status::newGood()->warning( 'userexists' );
} else {
$this->logger->error( __METHOD__ . ': {username} failed with message {msg}', [
'username' => $username,
'msg' => $status->getWikiText( false, false, 'en' )
] );
$user->setId( 0 );
$user->loadFromId();
}
return $status;
}
} catch ( \Exception $ex ) {
$this->logger->error( __METHOD__ . ': {username} failed with exception {exception}', [
'username' => $username,
'exception' => $ex,
] );
// Do not keep throwing errors for a while
$cache->set( $backoffKey, 1, 600 );
// Bubble up error; which should normally trigger DB rollbacks
throw $ex;
}
$this->setDefaultUserOptions( $user, false );
// Inform the providers
$this->callMethodOnProviders( self::CALL_PRIMARY | self::CALL_SECONDARY, 'autoCreatedAccount',
[ $user, $source ]
);
$this->getHookRunner()->onLocalUserCreated( $user, true );
$user->saveSettings();
// Update user count
DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'users' => 1 ] ) );
// Watch user's userpage and talk page (except temp users)
if ( $source !== self::AUTOCREATE_SOURCE_TEMP ) {
DeferredUpdates::addCallableUpdate( function () use ( $user ) {
$this->watchlistManager->addWatchIgnoringRights( $user, $user->getUserPage() );
} );
}
// Log the creation
if ( $this->config->get( MainConfigNames::NewUserLog ) && $log ) {
$logEntry = new \ManualLogEntry( 'newusers', 'autocreate' );
$logEntry->setPerformer( $user );
$logEntry->setTarget( $user->getUserPage() );
$logEntry->setComment( '' );
$logEntry->setParameters( [
'4::userid' => $user->getId(),
] );
$logEntry->insert();
}
ScopedCallback::consume( $scope );
if ( $login ) {
$remember = $source === self::AUTOCREATE_SOURCE_TEMP;
$this->setSessionDataForUser( $user, $remember, false );
}
return Status::newGood();
}
/**
* Authorize automatic account creation. This is like account creation but
* checks the autocreateaccount right instead of the createaccount right.
*
* @param Authority $creator
* @return StatusValue
*/
private function authorizeAutoCreateAccount( Authority $creator ) {
return $this->authorizeInternal(
static function (
string $action,
PageIdentity $target,
PermissionStatus $status
) use ( $creator ) {
return $creator->authorizeWrite( $action, $target, $status );
},
'autocreateaccount'
);
}
// endregion -- end of Account creation
/***************************************************************************/
// region Account linking
/** @name Account linking */
/**
* Determine whether accounts can be linked
* @return bool
*/
public function canLinkAccounts() {
foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK ) {
return true;
}
}
return false;
}
/**
* Start an account linking flow
*
* @param User $user User being linked
* @param AuthenticationRequest[] $reqs
* @param string $returnToUrl Url that REDIRECT responses should eventually
* return to.
* @return AuthenticationResponse
*/
public function beginAccountLink( User $user, array $reqs, $returnToUrl ) {
$session = $this->request->getSession();
$session->remove( self::ACCOUNT_LINK_STATE );
if ( !$this->canLinkAccounts() ) {
// Caller should have called canLinkAccounts()
throw new LogicException( 'Account linking is not possible' );
}
if ( !$user->isRegistered() ) {
if ( !$this->userNameUtils->isUsable( $user->getName() ) ) {
$msg = wfMessage( 'noname' );
} else {
$msg = wfMessage( 'authmanager-userdoesnotexist', $user->getName() );
}
return AuthenticationResponse::newFail( $msg );
}
foreach ( $reqs as $req ) {
$req->username = $user->getName();
$req->returnToUrl = $returnToUrl;
}
$this->removeAuthenticationSessionData( null );
$providers = $this->getPreAuthenticationProviders();
foreach ( $providers as $id => $provider ) {
$status = $provider->testForAccountLink( $user );
if ( !$status->isGood() ) {
$this->logger->debug( __METHOD__ . ": Account linking pre-check failed by $id", [
'user' => $user->getName(),
] );
$ret = AuthenticationResponse::newFail(
Status::wrap( $status )->getMessage()
);
$this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink', [ $user, $ret ] );
return $ret;
}
}
$state = [
'username' => $user->getName(),
'userid' => $user->getId(),
'returnToUrl' => $returnToUrl,
'providerIds' => $this->getProviderIds(),
'primary' => null,
'continueRequests' => [],
];
$providers = $this->getPrimaryAuthenticationProviders();
foreach ( $providers as $id => $provider ) {
if ( $provider->accountCreationType() !== PrimaryAuthenticationProvider::TYPE_LINK ) {
continue;
}
$res = $provider->beginPrimaryAccountLink( $user, $reqs );
switch ( $res->status ) {
case AuthenticationResponse::PASS:
$this->logger->info( "Account linked to {user} by $id", [
'user' => $user->getName(),
] );
$this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink',
[ $user, $res ]
);
return $res;
case AuthenticationResponse::FAIL:
$this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
'user' => $user->getName(),
] );
$this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink',
[ $user, $res ]
);
return $res;
case AuthenticationResponse::ABSTAIN:
// Continue loop
break;
case AuthenticationResponse::REDIRECT:
case AuthenticationResponse::UI:
$this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
'user' => $user->getName(),
] );
$this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
$state['primary'] = $id;
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( self::ACCOUNT_LINK_STATE, $state );
$session->persist();
return $res;
// @codeCoverageIgnoreStart
default:
throw new \DomainException(
get_class( $provider ) . "::beginPrimaryAccountLink() returned $res->status"
);
// @codeCoverageIgnoreEnd
}
}
$this->logger->debug( __METHOD__ . ': Account linking failed because no provider accepted', [
'user' => $user->getName(),
] );
$ret = AuthenticationResponse::newFail(
wfMessage( 'authmanager-link-no-primary' )
);
$this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink', [ $user, $ret ] );
return $ret;
}
/**
* Continue an account linking flow
* @param AuthenticationRequest[] $reqs
* @return AuthenticationResponse
*/
public function continueAccountLink( array $reqs ) {
$session = $this->request->getSession();
try {
if ( !$this->canLinkAccounts() ) {
// Caller should have called canLinkAccounts()
$session->remove( self::ACCOUNT_LINK_STATE );
throw new LogicException( 'Account linking is not possible' );
}
$state = $session->getSecret( self::ACCOUNT_LINK_STATE );
if ( !is_array( $state ) ) {
return AuthenticationResponse::newFail(
wfMessage( 'authmanager-link-not-in-progress' )
);
}
$state['continueRequests'] = [];
// Step 0: Prepare and validate the input
$user = $this->userFactory->newFromName(
(string)$state['username'],
UserRigorOptions::RIGOR_USABLE
);
if ( !is_object( $user ) ) {
$session->remove( self::ACCOUNT_LINK_STATE );
return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
}
if ( $user->getId() !== $state['userid'] ) {
throw new \UnexpectedValueException(
"User \"{$state['username']}\" is valid, but " .
"ID {$user->getId()} !== {$state['userid']}!"
);
}
if ( $state['providerIds'] !== $this->getProviderIds() ) {
// An inconsistent AuthManagerFilterProviders hook, or site configuration changed
// while the user was in the middle of authentication. The first is a bug, the
// second is rare but expected when deploying a config change. Try handle in a way
// that's useful for both cases.
// @codeCoverageIgnoreStart
MWExceptionHandler::logException( new NormalizedException(
'Authentication failed because of inconsistent provider array',
[ 'old' => json_encode( $state['providerIds'] ), 'new' => json_encode( $this->getProviderIds() ) ]
) );
$ret = AuthenticationResponse::newFail(
wfMessage( 'authmanager-link-not-in-progress' )
);
$this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $ret ] );
$session->remove( self::ACCOUNT_LINK_STATE );
return $ret;
// @codeCoverageIgnoreEnd
}
foreach ( $reqs as $req ) {
$req->username = $state['username'];
$req->returnToUrl = $state['returnToUrl'];
}
// Step 1: Call the primary again until it succeeds
$provider = $this->getAuthenticationProvider( $state['primary'] );
if ( !$provider instanceof PrimaryAuthenticationProvider ) {
// Configuration changed? Force them to start over.
// @codeCoverageIgnoreStart
$ret = AuthenticationResponse::newFail(
wfMessage( 'authmanager-link-not-in-progress' )
);
$this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink', [ $user, $ret ] );
$session->remove( self::ACCOUNT_LINK_STATE );
return $ret;
// @codeCoverageIgnoreEnd
}
$id = $provider->getUniqueId();
$res = $provider->continuePrimaryAccountLink( $user, $reqs );
switch ( $res->status ) {
case AuthenticationResponse::PASS:
$this->logger->info( "Account linked to {user} by $id", [
'user' => $user->getName(),
] );
$this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink',
[ $user, $res ]
);
$session->remove( self::ACCOUNT_LINK_STATE );
return $res;
case AuthenticationResponse::FAIL:
$this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
'user' => $user->getName(),
] );
$this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink',
[ $user, $res ]
);
$session->remove( self::ACCOUNT_LINK_STATE );
return $res;
case AuthenticationResponse::REDIRECT:
case AuthenticationResponse::UI:
$this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
'user' => $user->getName(),
] );
$this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( self::ACCOUNT_LINK_STATE, $state );
return $res;
default:
throw new \DomainException(
get_class( $provider ) . "::continuePrimaryAccountLink() returned $res->status"
);
}
} catch ( \Exception $ex ) {
$session->remove( self::ACCOUNT_LINK_STATE );
throw $ex;
}
}
// endregion -- end of Account linking
/***************************************************************************/
// region Information methods
/** @name Information methods */
/**
* Return the applicable list of AuthenticationRequests
*
* Possible values for $action:
* - ACTION_LOGIN: Valid for passing to beginAuthentication
* - ACTION_LOGIN_CONTINUE: Valid for passing to continueAuthentication in the current state
* - ACTION_CREATE: Valid for passing to beginAccountCreation
* - ACTION_CREATE_CONTINUE: Valid for passing to continueAccountCreation in the current state
* - ACTION_LINK: Valid for passing to beginAccountLink
* - ACTION_LINK_CONTINUE: Valid for passing to continueAccountLink in the current state
* - ACTION_CHANGE: Valid for passing to changeAuthenticationData to change credentials
* - ACTION_REMOVE: Valid for passing to changeAuthenticationData to remove credentials.
* - ACTION_UNLINK: Same as ACTION_REMOVE, but limited to linked accounts.
*
* @param string $action One of the AuthManager::ACTION_* constants
* @param UserIdentity|null $user User being acted on, instead of the current user.
* @return AuthenticationRequest[]
*/
public function getAuthenticationRequests( $action, ?UserIdentity $user = null ) {
$options = [];
$providerAction = $action;
// Figure out which providers to query
switch ( $action ) {
case self::ACTION_LOGIN:
case self::ACTION_CREATE:
$providers = $this->getPreAuthenticationProviders() +
$this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders();
break;
case self::ACTION_LOGIN_CONTINUE:
$state = $this->request->getSession()->getSecret( self::AUTHN_STATE );
return is_array( $state ) ? $state['continueRequests'] : [];
case self::ACTION_CREATE_CONTINUE:
$state = $this->request->getSession()->getSecret( self::ACCOUNT_CREATION_STATE );
return is_array( $state ) ? $state['continueRequests'] : [];
case self::ACTION_LINK:
$providers = [];
foreach ( $this->getPrimaryAuthenticationProviders() as $p ) {
if ( $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK ) {
$providers[] = $p;
}
}
break;
case self::ACTION_UNLINK:
$providers = [];
foreach ( $this->getPrimaryAuthenticationProviders() as $p ) {
if ( $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK ) {
$providers[] = $p;
}
}
// To providers, unlink and remove are identical.
$providerAction = self::ACTION_REMOVE;
break;
case self::ACTION_LINK_CONTINUE:
$state = $this->request->getSession()->getSecret( self::ACCOUNT_LINK_STATE );
return is_array( $state ) ? $state['continueRequests'] : [];
case self::ACTION_CHANGE:
case self::ACTION_REMOVE:
$providers = $this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders();
break;
// @codeCoverageIgnoreStart
default:
throw new \DomainException( __METHOD__ . ": Invalid action \"$action\"" );
}
// @codeCoverageIgnoreEnd
return $this->getAuthenticationRequestsInternal( $providerAction, $options, $providers, $user );
}
/**
* Internal request lookup for self::getAuthenticationRequests
*
* @param string $providerAction Action to pass to providers
* @param array $options Options to pass to providers
* @param AuthenticationProvider[] $providers
* @param UserIdentity|null $user being acted on
* @return AuthenticationRequest[]
*/
private function getAuthenticationRequestsInternal(
$providerAction, array $options, array $providers, ?UserIdentity $user = null
) {
$user = $user ?: RequestContext::getMain()->getUser();
$options['username'] = $user->isRegistered() ? $user->getName() : null;
// Query them and merge results
$reqs = [];
foreach ( $providers as $provider ) {
$isPrimary = $provider instanceof PrimaryAuthenticationProvider;
foreach ( $provider->getAuthenticationRequests( $providerAction, $options ) as $req ) {
$id = $req->getUniqueId();
// If a required request if from a Primary, mark it as "primary-required" instead
if ( $isPrimary && $req->required ) {
$req->required = AuthenticationRequest::PRIMARY_REQUIRED;
}
if (
!isset( $reqs[$id] )
|| $req->required === AuthenticationRequest::REQUIRED
|| $reqs[$id] === AuthenticationRequest::OPTIONAL
) {
$reqs[$id] = $req;
}
}
}
// AuthManager has its own req for some actions
switch ( $providerAction ) {
case self::ACTION_LOGIN:
$reqs[] = new RememberMeAuthenticationRequest(
$this->config->get( MainConfigNames::RememberMe ) );
$options['username'] = null; // Don't fill in the username below
break;
case self::ACTION_CREATE:
$reqs[] = new UsernameAuthenticationRequest;
$reqs[] = new UserDataAuthenticationRequest;
// Registered users should be prompted to provide a rationale for account creations,
// except for the case of a temporary user registering a full account (T328718).
if (
$options['username'] !== null &&
!$this->userNameUtils->isTemp( $options['username'] )
) {
$reqs[] = new CreationReasonAuthenticationRequest;
$options['username'] = null; // Don't fill in the username below
}
break;
}
// Fill in reqs data
$this->fillRequests( $reqs, $providerAction, $options['username'], true );
// For self::ACTION_CHANGE, filter out any that something else *doesn't* allow changing
if ( $providerAction === self::ACTION_CHANGE || $providerAction === self::ACTION_REMOVE ) {
$reqs = array_filter( $reqs, function ( $req ) {
return $this->allowsAuthenticationDataChange( $req, false )->isGood();
} );
}
return array_values( $reqs );
}
/**
* Set values in an array of requests
* @param AuthenticationRequest[] &$reqs
* @param string $action
* @param string|null $username
* @param bool $forceAction
*/
private function fillRequests( array &$reqs, $action, $username, $forceAction = false ) {
foreach ( $reqs as $req ) {
if ( !$req->action || $forceAction ) {
$req->action = $action;
}
$req->username ??= $username;
}
}
/**
* Determine whether a username exists
* @param string $username
* @param int $flags Bitfield of IDBAccessObject::READ_* constants
* @return bool
*/
public function userExists( $username, $flags = IDBAccessObject::READ_NORMAL ) {
foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
if ( $provider->testUserExists( $username, $flags ) ) {
return true;
}
}
return false;
}
/**
* Determine whether a user property should be allowed to be changed.
*
* Supported properties are:
* - emailaddress
* - realname
* - nickname
*
* @param string $property
* @return bool
*/
public function allowsPropertyChange( $property ) {
$providers = $this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders();
foreach ( $providers as $provider ) {
if ( !$provider->providerAllowsPropertyChange( $property ) ) {
return false;
}
}
return true;
}
/**
* Get a provider by ID
* @note This is public so extensions can check whether their own provider
* is installed and so they can read its configuration if necessary.
* Other uses are not recommended.
* @param string $id
* @return AuthenticationProvider|null
*/
public function getAuthenticationProvider( $id ) {
// Fast version
if ( isset( $this->allAuthenticationProviders[$id] ) ) {
return $this->allAuthenticationProviders[$id];
}
// Slow version: instantiate each kind and check
$providers = $this->getPrimaryAuthenticationProviders();
if ( isset( $providers[$id] ) ) {
return $providers[$id];
}
$providers = $this->getSecondaryAuthenticationProviders();
if ( isset( $providers[$id] ) ) {
return $providers[$id];
}
$providers = $this->getPreAuthenticationProviders();
if ( isset( $providers[$id] ) ) {
return $providers[$id];
}
return null;
}
// endregion -- end of Information methods
/***************************************************************************/
// region Internal methods
/** @name Internal methods */
/**
* Store authentication in the current session
* @note For use by AuthenticationProviders only
* @param string $key
* @param mixed $data Must be serializable
*/
public function setAuthenticationSessionData( $key, $data ) {
$session = $this->request->getSession();
$arr = $session->getSecret( 'authData' );
if ( !is_array( $arr ) ) {
$arr = [];
}
$arr[$key] = $data;
$session->setSecret( 'authData', $arr );
}
/**
* Fetch authentication data from the current session
* @note For use by AuthenticationProviders only
* @param string $key
* @param mixed|null $default
* @return mixed
*/
public function getAuthenticationSessionData( $key, $default = null ) {
$arr = $this->request->getSession()->getSecret( 'authData' );
if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
return $arr[$key];
} else {
return $default;
}
}
/**
* Remove authentication data
* @note For use by AuthenticationProviders
* @param string|null $key If null, all data is removed
*/
public function removeAuthenticationSessionData( $key ) {
$session = $this->request->getSession();
if ( $key === null ) {
$session->remove( 'authData' );
} else {
$arr = $session->getSecret( 'authData' );
if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
unset( $arr[$key] );
$session->setSecret( 'authData', $arr );
}
}
}
/**
* Create an array of AuthenticationProviders from an array of ObjectFactory specs
* @param string $class
* @param array[] $specs
* @return AuthenticationProvider[]
*/
protected function providerArrayFromSpecs( $class, array $specs ) {
$i = 0;
foreach ( $specs as &$spec ) {
$spec = [ 'sort2' => $i++ ] + $spec + [ 'sort' => 0 ];
}
unset( $spec );
// Sort according to the 'sort' field, and if they are equal, according to 'sort2'
usort( $specs, static function ( $a, $b ) {
return $a['sort'] <=> $b['sort']
?: $a['sort2'] <=> $b['sort2'];
} );
$ret = [];
foreach ( $specs as $spec ) {
/** @var AbstractAuthenticationProvider $provider */
$provider = $this->objectFactory->createObject( $spec, [ 'assertClass' => $class ] );
$provider->init( $this->logger, $this, $this->getHookContainer(), $this->config, $this->userNameUtils );
$id = $provider->getUniqueId();
if ( isset( $this->allAuthenticationProviders[$id] ) ) {
throw new \RuntimeException(
"Duplicate specifications for id $id (classes " .
get_class( $provider ) . ' and ' .
get_class( $this->allAuthenticationProviders[$id] ) . ')'
);
}
$this->allAuthenticationProviders[$id] = $provider;
$ret[$id] = $provider;
}
return $ret;
}
/**
* Get the list of PreAuthenticationProviders
* @return PreAuthenticationProvider[]
*/
protected function getPreAuthenticationProviders() {
if ( $this->preAuthenticationProviders === null ) {
$this->initializeAuthenticationProviders();
}
return $this->preAuthenticationProviders;
}
/**
* Get the list of PrimaryAuthenticationProviders
* @return PrimaryAuthenticationProvider[]
*/
protected function getPrimaryAuthenticationProviders() {
if ( $this->primaryAuthenticationProviders === null ) {
$this->initializeAuthenticationProviders();
}
return $this->primaryAuthenticationProviders;
}
/**
* Get the list of SecondaryAuthenticationProviders
* @return SecondaryAuthenticationProvider[]
*/
protected function getSecondaryAuthenticationProviders() {
if ( $this->secondaryAuthenticationProviders === null ) {
$this->initializeAuthenticationProviders();
}
return $this->secondaryAuthenticationProviders;
}
private function getProviderIds(): array {
return [
'preauth' => array_keys( $this->getPreAuthenticationProviders() ),
'primaryauth' => array_keys( $this->getPrimaryAuthenticationProviders() ),
'secondaryauth' => array_keys( $this->getSecondaryAuthenticationProviders() ),
];
}
private function initializeAuthenticationProviders() {
$conf = $this->config->get( MainConfigNames::AuthManagerConfig )
?: $this->config->get( MainConfigNames::AuthManagerAutoConfig );
$providers = array_map( fn ( $stepConf ) => array_fill_keys( array_keys( $stepConf ), true ), $conf );
$this->getHookRunner()->onAuthManagerFilterProviders( $providers );
foreach ( $conf as $step => $stepConf ) {
$conf[$step] = array_intersect_key( $stepConf, array_filter( $providers[$step] ) );
}
$this->preAuthenticationProviders = $this->providerArrayFromSpecs(
PreAuthenticationProvider::class, $conf['preauth']
);
$this->primaryAuthenticationProviders = $this->providerArrayFromSpecs(
PrimaryAuthenticationProvider::class, $conf['primaryauth']
);
$this->secondaryAuthenticationProviders = $this->providerArrayFromSpecs(
SecondaryAuthenticationProvider::class, $conf['secondaryauth']
);
}
/**
* Log the user in
* @param User $user
* @param bool|null $remember The "remember me" flag.
* @param bool $isReauthentication Whether creating this session should count as a recent
* authentication for $wgReauthenticateTime checks.
*/
private function setSessionDataForUser( $user, $remember = null, $isReauthentication = true ) {
$session = $this->request->getSession();
$delay = $session->delaySave();
$session->resetId();
$session->resetAllTokens();
if ( $session->canSetUser() ) {
$session->setUser( $user );
}
if ( $remember !== null ) {
$session->setRememberUser( $remember );
}
if ( $isReauthentication ) {
$session->set( 'AuthManager:lastAuthId', $user->getId() );
$session->set( 'AuthManager:lastAuthTimestamp', time() );
}
$session->persist();
\Wikimedia\ScopedCallback::consume( $delay );
$this->getHookRunner()->onUserLoggedIn( $user );
}
/**
* @param User $user
* @param bool $useContextLang Use 'uselang' to set the user's language
*/
private function setDefaultUserOptions( User $user, $useContextLang ) {
$user->setToken();
$lang = $useContextLang ? RequestContext::getMain()->getLanguage() : $this->contentLanguage;
$this->userOptionsManager->setOption(
$user,
'language',
$this->languageConverterFactory->getLanguageConverter( $lang )->getPreferredVariant()
);
$contLangConverter = $this->languageConverterFactory->getLanguageConverter( $this->contentLanguage );
if ( $contLangConverter->hasVariants() ) {
$this->userOptionsManager->setOption(
$user,
'variant',
$contLangConverter->getPreferredVariant()
);
}
}
/**
* @see AuthManagerVerifyAuthenticationHook::onAuthManagerVerifyAuthentication()
*/
private function runVerifyHook(
string $action,
?UserIdentity $user,
AuthenticationResponse &$response,
string $primaryId
): bool {
$oldResponse = $response;
$info = [
'action' => $action,
'primaryId' => $primaryId,
];
$proceed = $this->getHookRunner()->onAuthManagerVerifyAuthentication( $user, $response, $this, $info );
if ( !( $response instanceof AuthenticationResponse ) ) {
throw new LogicException( '$response must be an AuthenticationResponse' );
} elseif ( $proceed && $response !== $oldResponse ) {
throw new LogicException(
'AuthManagerVerifyAuthenticationHook must not modify the response unless it returns false' );
} elseif ( !$proceed && $response->status !== AuthenticationResponse::FAIL ) {
throw new LogicException(
'AuthManagerVerifyAuthenticationHook must set the response to FAIL if it returns false' );
}
if ( !$proceed ) {
$this->logger->info(
$action . ' action for {user} from {clientip} prevented by '
. 'AuthManagerVerifyAuthentication hook: {reason}',
[
'user' => $user ? $user->getName() : '<null>',
'clientip' => $this->request->getIP(),
'reason' => $response->message->getKey(),
'primaryId' => $primaryId,
]
);
}
return $proceed;
}
/**
* @param int $which Bitmask of values of the self::CALL_* constants
* @param string $method
* @param array $args
*/
private function callMethodOnProviders( $which, $method, array $args ) {
$providers = [];
if ( $which & self::CALL_PRE ) {
$providers += $this->getPreAuthenticationProviders();
}
if ( $which & self::CALL_PRIMARY ) {
$providers += $this->getPrimaryAuthenticationProviders();
}
if ( $which & self::CALL_SECONDARY ) {
$providers += $this->getSecondaryAuthenticationProviders();
}
foreach ( $providers as $provider ) {
$provider->$method( ...$args );
}
}
/**
* @return HookContainer
*/
private function getHookContainer() {
return $this->hookContainer;
}
/**
* @return HookRunner
*/
private function getHookRunner() {
return $this->hookRunner;
}
// endregion -- end of Internal methods
}
/*
* This file uses VisualStudio style region/endregion fold markers which are
* recognised by PHPStorm. If modelines are enabled, the following editor
* configuration will also enable folding in vim, if it is in the last 5 lines
* of the file. We also use "@name" which creates sections in Doxygen.
*
* vim: foldmarker=//\ region,//\ endregion foldmethod=marker
*/
|