1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif
#include "components/autofill/content/renderer/password_autofill_agent.h"
#include <vector>
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/numerics/safe_conversions.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "build/build_config.h"
#include "chrome/renderer/autofill/fake_mojo_password_manager_driver.h"
#include "chrome/renderer/autofill/fake_password_generation_driver.h"
#include "chrome/renderer/autofill/password_generation_test_utils.h"
#include "chrome/test/base/chrome_render_view_test.h"
#include "components/autofill/content/renderer/autofill_agent.h"
#include "components/autofill/content/renderer/autofill_agent_test_api.h"
#include "components/autofill/content/renderer/form_autofill_util.h"
#include "components/autofill/content/renderer/form_tracker.h"
#include "components/autofill/content/renderer/password_generation_agent.h"
#include "components/autofill/content/renderer/test_password_autofill_agent.h"
#include "components/autofill/core/common/autofill_constants.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/autofill/core/common/mojom/autofill_types.mojom.h"
#include "components/autofill/core/common/password_form_fill_data.h"
#include "components/autofill/core/common/unique_ids.h"
#include "components/password_manager/core/common/password_manager_constants.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/safe_browsing/buildflags.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/test/browser_test_utils.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "testing/gtest/include/gtest/gtest-param-test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_form_element.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_input_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
#include "ui/events/keycodes/keyboard_codes.h"
#if BUILDFLAG(IS_WIN)
#include "third_party/blink/public/web/win/web_font_rendering.h"
#endif
namespace autofill {
namespace {
using autofill::FormRendererId;
using autofill::FormTracker;
using autofill::mojom::FocusedFieldType;
using autofill::mojom::SubmissionIndicatorEvent;
using base::ASCIIToUTF16;
using base::UTF16ToUTF8;
using blink::WebAutofillState;
using blink::WebDocument;
using blink::WebElement;
using blink::WebFormElement;
using blink::WebFrame;
using blink::WebInputElement;
using blink::WebLocalFrame;
using blink::WebString;
using testing::_;
using testing::AllOf;
using testing::AtMost;
using testing::Eq;
using testing::Field;
using testing::Truly;
// The name of the username/password element in the form.
const char kUsernameName[] = "username";
const char kPasswordName[] = "password";
const char kSearchField[] = "search";
const char kSocialMediaTextArea[] = "new_chirp";
const char kAliceUsername[] = "alice";
const char16_t kAliceUsername16[] = u"alice";
const char kAlicePassword[] = "password";
const char16_t kAlicePassword16[] = u"password";
const char kBobUsername[] = "bob";
const char16_t kBobUsername16[] = u"bob";
const char kBobPassword[] = "secret";
const char16_t kBobPassword16[] = u"secret";
const char16_t kCarolUsername16[] = u"Carol";
const char kCarolPassword[] = "test";
const char16_t kCarolPassword16[] = u"test";
const char16_t kCarolAlternateUsername16[] = u"RealCarolUsername";
const char kFormHTML[] =
"<FORM id='LoginTestForm' action='http://www.bidule.com'>"
" <INPUT type='text' id='random_field'/>"
" <INPUT type='text' id='username'/>"
" <INPUT type='password' id='password'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
const char kSocialNetworkPostFormHTML[] =
"<FORM id='SocialMediaPostForm' action='http://www.chirper.com'>"
" <TEXTAREA id='new_chirp'>"
" </TEXTAREA>"
" <INPUT type='submit' value='Chirp'/>"
"</FORM>";
const char kSearchFieldHTML[] =
"<FORM id='SearchFieldForm' action='http://www.gewgle.de'>"
" <INPUT type='search' id='search'/>"
" <INPUT type='submit' value='Chirp'/>"
"</FORM>";
const char kWebAutnFieldHTML[] =
"<FORM id='WebAuthnFieldForm' action='http://www.gewgle.de'>"
" <INPUT type='text' id='username' autocomplete='webauthn'/>"
" <INPUT type='password' id='password' autocomplete='webauthn'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
const char kVisibleFormWithNoUsernameHTML[] =
"<head> <style> form {display: inline;} </style> </head>"
"<body>"
" <form name='LoginTestForm' action='http://www.bidule.com'>"
" <div>"
" <input type='password' id='password'/>"
" </div>"
" </form>"
"</body>";
const char kSingleUsernameFormHTML[] =
"<FORM name='LoginTestForm' action='http://www.bidule.com'>"
" <INPUT type='text' id='username' autocomplete='username'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
const char kSingleTextInputFormHTML[] =
"<FORM name='LoginTestForm' action='http://www.bidule.com'>"
" <INPUT type='text' id='username'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
const char kEmptyFormHTML[] =
"<head> <style> form {display: inline;} </style> </head>"
"<body> <form> </form> </body>";
const char kFormWithoutPasswordsHTML[] =
"<FORM>"
" <INPUT type='text' id='username'/>"
" <INPUT type='text' id='random_field'/>"
"</FORM>";
const char kNonVisibleFormHTML[] =
"<head> <style> form {visibility: hidden;} </style> </head>"
"<body>"
" <form>"
" <div>"
" <input type='password' id='password'/>"
" </div>"
" </form>"
"</body>";
const char kNonDisplayedFormHTML[] =
"<head> <style> form {display: none;} </style> </head>"
"<body>"
" <form>"
" <div>"
" <input type='password' id='password'/>"
" </div>"
" </form>"
"</body>";
const char kSignupFormHTML[] =
"<FORM id='LoginTestForm' name='LoginTestForm' "
" action='http://www.bidule.com'>"
" <INPUT type='text' id='random_info'/>"
" <INPUT type='password' id='new_password'/>"
" <INPUT type='password' id='confirm_password'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
const char kEmptyWebpage[] =
"<html>"
" <head>"
" </head>"
" <body>"
" </body>"
"</html>";
const char kRedirectionWebpage[] =
"<html>"
" <head>"
" <meta http-equiv='Content-Type' content='text/html'>"
" <title>Redirection page</title>"
" <script></script>"
" </head>"
" <body>"
" <script type='text/javascript'>"
" function test(){}"
" </script>"
" </body>"
"</html>";
const char kSimpleWebpage[] =
"<html>"
" <head>"
" <meta charset='utf-8' />"
" <title>Title</title>"
" </head>"
" <body>"
" <form name='LoginTestForm'>"
" <input type='text' id='username'/>"
" <input type='checkbox' id='accept-tc'>"
" <input type='password' id='password'/>"
" <input type='checkbox' id='remember-me'>"
" <input type='submit' value='Login'/>"
" </form>"
" </body>"
"</html>";
const char kWebpageWithDynamicContent[] =
"<html>"
" <head>"
" <meta charset='utf-8' />"
" <title>Title</title>"
" </head>"
" <body>"
" <script type='text/javascript'>"
" function addParagraph() {"
" var p = document.createElement('p');"
" document.body.appendChild(p);"
" }"
" window.onload = addParagraph;"
" </script>"
" </body>"
"</html>";
const char kJavaScriptClick[] =
"var event = new MouseEvent('click', {"
" 'view': window,"
" 'bubbles': true,"
" 'cancelable': true"
"});"
"var form = document.getElementById('myform1');"
"form.dispatchEvent(event);"
"console.log('clicked!');";
const char kPasswordChangeFormHTML[] =
"<FORM name='ChangeWithUsernameForm' action='http://www.bidule.com'>"
" <INPUT type='text' id='username'/>"
" <INPUT type='password' id='password'/>"
" <INPUT type='password' id='newpassword'/>"
" <INPUT type='password' id='confirmpassword'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
const char kPasswordChangeWithoutFormHTML[] =
"<DIV>"
" <INPUT type='text' id='username'/>"
" <INPUT type='password' id='password'/>"
" <INPUT type='password' id='newpassword'/>"
" <INPUT type='password' id='confirmpassword'/>"
" <INPUT type='submit' value='Change pwd'/>"
"</DIV>";
const char kPasswordChangeFormWithoutSubmitHTML[] =
"<DIV>"
" <INPUT type='text' id='username'/>"
" <INPUT type='password' id='password'/>"
" <INPUT type='password' id='newpassword'/>"
" <INPUT type='password' id='confirmpassword'/>"
"</DIV>";
const char kPasswordChangeFormSubmitDisabledHTML[] =
"<DIV>"
" <INPUT type='text' id='username'/>"
" <INPUT type='password' id='password'/>"
" <INPUT type='password' id='newpassword'/>"
" <INPUT type='password' id='confirmpassword'/>"
" <INPUT type='submit' value='Change pwd' disabled/>"
"</DIV>";
const char kCreditCardFormHTML[] =
"<FORM name='ChangeWithUsernameForm' action='http://www.bidule.com'>"
" <INPUT type='text' id='creditcardowner'/>"
" <INPUT type='text' id='creditcardnumber'/>"
" <INPUT type='password' id='cvc'/>"
" <INPUT type='submit' value='Submit'/>"
"</FORM>";
const char kNoFormHTML[] =
"<script>"
" function on_keypress(event) {"
" if (event.which === 13) {"
" var field = document.getElementById('password');"
" field.parentElement.removeChild(field);"
" }"
" }"
"</script>"
"<INPUT type='text' id='username'/>"
"<INPUT type='password' id='password' onkeypress='on_keypress(event)'/>";
const char kTwoNoUsernameFormsHTML[] =
"<FORM name='form1' action='http://www.bidule.com'>"
" <INPUT type='password' id='password1' name='password'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>"
"<FORM name='form2' action='http://www.bidule.com'>"
" <INPUT type='password' id='password2' name='password'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
const char kDivWrappedFormHTML[] =
"<DIV id='outer'>"
" <DIV id='inner'>"
" <FORM id='form' action='http://www.bidule.com'>"
" <INPUT type='text' id='username'/>"
" <INPUT type='password' id='password'/>"
" </FORM>"
" </DIV>"
"</DIV>";
const char kJavaScriptRemoveForm[] =
"var form = document.getElementById('LoginTestForm');"
"form.parentNode.removeChild(form);";
const char kFormTagHostsShadowDomInputs[] =
"<script>"
" function addShadowFields() {"
" const un_host = document.getElementById('un_host');"
" const un_shadow = un_host.attachShadow({ mode: 'open'});"
" const un = document.createElement('input');"
" un_shadow.appendChild(un);"
" const pw_host = document.getElementById('pw_host');"
" const pw_shadow = pw_host.attachShadow({ mode: 'open'});"
" const pw = document.createElement('input');"
" pw.type = 'password';"
" pw_shadow.appendChild(pw);"
"}"
"</script>"
"<body onload='addShadowFields();'>"
"<form method='POST' action='done.html' id='shadyform'>"
"<div id='un_host'></div>"
"<div id='pw_host'></div>"
"<input type='submit' id='input_submit_button'>"
"</form>"
"</body>";
constexpr std::string_view kUnownedFieldsWithPasswordDisabled =
"<input type='text' id='username'>"
"<input type='password' disabled id='password'>";
// Sets the "readonly" attribute of `element` to the value given by `read_only`.
void SetElementReadOnly(WebInputElement& element, bool read_only) {
element.SetAttribute(WebString::FromUTF8("readonly"),
read_only ? WebString::FromUTF8("true") : WebString());
}
bool FormHasFieldWithValue(const autofill::FormData& form,
const std::u16string& value) {
for (const auto& field : form.fields()) {
if (field.value() == value) {
return true;
}
if (field.user_input() == value) {
return true;
}
}
return false;
}
enum PasswordFormSourceType {
PasswordFormSubmitted,
PasswordFormSameDocumentNavigation,
};
enum class FieldChangeSource {
USER,
AUTOFILL_SINGLE_FIELD,
USER_AUTOFILL_SINGLE_FIELD,
AUTOFILL_FORM,
USER_AUTOFILL_FORM
};
// Returns the expected number of calls to AskForValuesToFill. On Android,
// a redundant call may be made when the focus changes to the field.
//
// Since test cases simulate multiple clicks, some of which lead to focus
// changes while others do not, finding the exact number of expected calls on
// Android is tedious. Using GMock's checkpoint pattern would help with that.
auto NumShowSuggestionsCalls() {
if constexpr (BUILDFLAG(IS_ANDROID)) {
return base::FeatureList::IsEnabled(
features::kAutofillAndroidDisableSuggestionsOnJSFocus)
// Called solely by
// `AutofillAgent::DidReceiveLeftMouseDownOrGestureTapInNode`.
? testing::Exactly(1)
// Potentially also by `AutofillAgent::FocusedElementChanged`.
: testing::AtLeast(1);
}
// Called solely by `AutofillAgent::DidCompleteFocusChangeInFrame`.
return testing::Exactly(1);
}
class PasswordAutofillAgentTest : public ChromeRenderViewTest {
public:
PasswordAutofillAgentTest() = default;
PasswordAutofillAgentTest(const PasswordAutofillAgentTest&) = delete;
PasswordAutofillAgentTest& operator=(const PasswordAutofillAgentTest&) =
delete;
// Simulates the fill password form message being sent to the renderer.
// We use that so we don't have to make RenderView::OnFillPasswordForm()
// protected.
void SimulateOnFillPasswordForm(const PasswordFormFillData& fill_data) {
password_autofill_agent_->ApplyFillDataOnParsingCompletion(fill_data);
}
void SendVisiblePasswordForms() {
static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
->DidFinishLoad();
}
void SetUp() override {
ChromeRenderViewTest::SetUp();
#if BUILDFLAG(IS_WIN)
// Autofill uses the system font to render suggestion previews. On Windows
// an extra step is required to ensure that the system font is configured.
blink::WebFontRendering::SetMenuFontMetrics(
blink::WebString::FromASCII("Arial"), 12);
#endif
// TODO(crbug.com/41401202): Remove workaround preventing non-test classes
// to bind fake_driver_ or fake_pw_client_.
password_autofill_agent_->GetPasswordManagerDriver();
password_generation_->RequestPasswordManagerClientForTesting();
base::RunLoop().RunUntilIdle(); // Executes binding the interfaces.
// Reject all requests to bind driver/client to anything but the test class:
GetMainRenderFrame()
->GetRemoteAssociatedInterfaces()
->OverrideBinderForTesting(
mojom::PasswordGenerationDriver::Name_,
base::BindRepeating([](mojo::ScopedInterfaceEndpointHandle handle) {
handle.reset();
}));
GetMainRenderFrame()
->GetRemoteAssociatedInterfaces()
->OverrideBinderForTesting(
mojom::PasswordManagerDriver::Name_,
base::BindRepeating([](mojo::ScopedInterfaceEndpointHandle handle) {
handle.reset();
}));
// Add a preferred login and an additional login to the FillData.
username1_ = kAliceUsername16;
password1_ = kAlicePassword16;
username2_ = kBobUsername16;
password2_ = kBobPassword16;
username3_ = kCarolUsername16;
password3_ = kCarolPassword16;
alternate_username3_ = kCarolAlternateUsername16;
fill_data_.preferred_login.username_value = username1_;
fill_data_.preferred_login.password_value = password1_;
PasswordAndMetadata password2;
password2.password_value = password2_;
password2.username_value = username2_;
fill_data_.additional_logins.push_back(std::move(password2));
PasswordAndMetadata password3;
password3.password_value = password3_;
password3.username_value = username3_;
fill_data_.additional_logins.push_back(std::move(password3));
// We need to set the origin so it matches the frame URL, otherwise we won't
// autocomplete.
UpdateUrlForHTML(kFormHTML);
LoadHTML(kFormHTML);
// Necessary for SimulateElementClick() to work correctly.
GetWebFrameWidget()->Resize(gfx::Size(500, 500));
GetWebFrameWidget()->SetFocus(true);
// Now retrieve the input elements so the test can access them.
UpdateUsernameAndPasswordElements();
}
void TearDown() override {
username_element_.Reset();
password_element_.Reset();
ChromeRenderViewTest::TearDown();
}
void RegisterMainFrameRemoteInterfaces() override {
// Because the test cases only involve the main frame in this test,
// the fake password client and the fake driver is only used on main frame.
blink::AssociatedInterfaceProvider* remote_associated_interfaces =
GetMainRenderFrame()->GetRemoteAssociatedInterfaces();
remote_associated_interfaces->OverrideBinderForTesting(
mojom::PasswordGenerationDriver::Name_,
base::BindRepeating(
&PasswordAutofillAgentTest::BindPasswordManagerClient,
base::Unretained(this)));
remote_associated_interfaces->OverrideBinderForTesting(
mojom::PasswordManagerDriver::Name_,
base::BindRepeating(
&PasswordAutofillAgentTest::BindPasswordManagerDriver,
base::Unretained(this)));
}
void FocusElement(const std::string& element_id) {
std::string script =
"document.getElementById('" + element_id + "').focus()";
ExecuteJavaScriptForTests(script.c_str());
GetMainFrame()->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kTest);
GetMainFrame()->Client()->FocusedElementChanged(GetElementByID(element_id));
GetMainFrame()->AutofillClient()->DidCompleteFocusChangeInFrame();
}
// A workaround to focus an element that doesn't have an id attribute.
void FocusFirstInputElement() {
ExecuteJavaScriptForTests("document.forms[0].elements[0].focus();");
GetMainFrame()->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kTest);
auto first_form_element =
GetMainFrame()->GetDocument().GetTopLevelForms()[0];
GetMainFrame()->Client()->FocusedElementChanged(
first_form_element.GetFormControlElements()[0]);
GetMainFrame()->AutofillClient()->DidCompleteFocusChangeInFrame();
}
void BlurElement(const std::string& element_id) {
std::string script = "document.getElementById('" + element_id + "').blur()";
ExecuteJavaScriptForTests(script.c_str());
ChangeFocusToNull(GetMainFrame()->GetDocument());
}
void ConfigurePasswordSuggestionFiltering(bool enabled) {
if (enabled) {
scoped_feature_list_.InitAndEnableFeature(
password_manager::features::kNoPasswordSuggestionFiltering);
} else {
scoped_feature_list_.InitAndDisableFeature(
password_manager::features::kNoPasswordSuggestionFiltering);
}
}
void EnableShowAutofillSignatures() {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kShowAutofillSignatures);
}
void UpdateUrlForHTML(const std::string& html) {
std::string url = "data:text/html;charset=utf-8," + html;
fill_data_.url = GURL(url);
}
void UpdateRendererIDsInFillData() {
fill_data_.username_element_renderer_id =
username_element_
? autofill::form_util::GetFieldRendererId(username_element_)
: autofill::FieldRendererId();
fill_data_.password_element_renderer_id =
password_element_
? autofill::form_util::GetFieldRendererId(password_element_)
: autofill::FieldRendererId();
ASSERT_TRUE(username_element_ || password_element_);
WebFormElement form =
password_element_ ? password_element_.Form() : username_element_.Form();
fill_data_.form_renderer_id = form_util::GetFormRendererId(form);
}
void UpdateUsernameAndPasswordElements() {
username_element_ = GetInputElementByID(kUsernameName);
password_element_ = GetInputElementByID(kPasswordName);
UpdateRendererIDsInFillData();
}
void UpdateOnlyUsernameElement() {
username_element_ = GetInputElementByID(kUsernameName);
password_element_.Reset();
UpdateRendererIDsInFillData();
}
void UpdateOnlyPasswordElement() {
username_element_.Reset();
password_element_ = GetInputElementByID(kPasswordName);
UpdateRendererIDsInFillData();
}
WebElement GetElementByID(const std::string& id) {
WebDocument document = GetMainFrame()->GetDocument();
WebElement element =
document.GetElementById(WebString::FromUTF8(id.c_str()));
EXPECT_TRUE(element);
return element;
}
WebInputElement GetInputElementByID(const std::string& id) {
WebInputElement input_element = GetElementByID(id).To<WebInputElement>();
EXPECT_TRUE(input_element);
return input_element;
}
void ClearUsernameAndPasswordFieldValues() {
if (username_element_) {
username_element_.SetValue(WebString());
username_element_.SetSuggestedValue(WebString());
username_element_.SetAutofillState(WebAutofillState::kNotFilled);
}
if (password_element_) {
password_element_.SetValue(WebString());
password_element_.SetSuggestedValue(WebString());
password_element_.SetAutofillState(WebAutofillState::kNotFilled);
}
}
void SimulateElementClick(const WebElement element) {
SimulatePointClick(element.BoundsInWidget().CenterPoint());
}
using ChromeRenderViewTest::SimulateElementClick;
void SimulateSuggestionChoice(WebInputElement& username_input) {
std::u16string username(kAliceUsername16);
std::u16string password(kAlicePassword16);
SimulateSuggestionChoiceOfUsernameAndPassword(username_input, username,
password);
}
void SimulateSuggestionChoiceOfUsernameAndPassword(
WebInputElement& input,
const std::u16string& username,
const std::u16string& password) {
// This call is necessary to setup the autofill agent appropriate for the
// user selection; simulates the menu actually popping up.
SimulatePointClick(gfx::Point(1, 1));
SimulateElementClick(input);
password_autofill_agent_->FillPasswordSuggestion(username, password,
base::DoNothing());
}
void SimulateUsernameTyping(const std::string& username) {
SimulatePointClick(gfx::Point(1, 1));
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/40820173): User typing doesn't send focus events properly.
FocusElement(kUsernameName);
#endif
SimulateUserInputChangeForElement(username_element_, username);
}
void SimulatePasswordTyping(const std::string& password) {
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/40820173): User typing doesn't send focus events properly.
FocusElement(kPasswordName);
#endif
SimulateUserInputChangeForElement(password_element_, password);
}
void SimulateUsernameSingleFieldAutofill(const std::u16string& text) {
FocusElement(kUsernameName);
autofill_agent_->ApplyFieldAction(
mojom::FieldActionType::kReplaceAll, mojom::ActionPersistence::kFill,
form_util::GetFieldRendererId(username_element_), text);
}
void SimulateUsernameFormAutofill(const std::u16string& text) {
FocusElement(kUsernameName);
// Fill the form.
std::vector<autofill::FormFieldData::FillData> fields;
FormFieldData::FillData field;
field.value = text;
field.is_autofilled = true;
field.renderer_id = form_util::GetFieldRendererId(username_element_);
field.host_form_id = form_util::GetFormRendererId(username_element_.Form());
fields.push_back(field);
autofill_agent_->ApplyFieldsAction(mojom::FormActionType::kFill,
mojom::ActionPersistence::kFill, fields);
}
void SimulateUsernameFieldChange(FieldChangeSource change_source) {
switch (change_source) {
case FieldChangeSource::USER:
SimulateUsernameTyping("Alice");
break;
case FieldChangeSource::AUTOFILL_SINGLE_FIELD:
SimulateUsernameSingleFieldAutofill(u"Alice");
break;
case FieldChangeSource::USER_AUTOFILL_SINGLE_FIELD:
SimulateUsernameTyping("A");
SimulateUsernameSingleFieldAutofill(u"Alice");
break;
case FieldChangeSource::AUTOFILL_FORM:
SimulateUsernameFormAutofill(u"Alice");
break;
case FieldChangeSource::USER_AUTOFILL_FORM:
SimulateUsernameTyping("A");
SimulateUsernameFormAutofill(u"Alice");
break;
}
}
// Helper to simulate that KeyboardReplacingSurface was closed in order to
// test regular popups, e.g. `ShowPasswordSuggestions`.
void SimulateClosingKeyboardReplacingSurfaceIfAndroid(
const std::string& element_id) {
#if BUILDFLAG(IS_ANDROID)
FocusElement(element_id);
#endif // BUILDFLAG(IS_ANDROID)
}
// TODO(crbug.com/40278548): Only expect one of IsPreviewed()/IsAutofilled().
void CheckTextFieldsStateForElements(const WebInputElement& username_element,
const std::string& username,
bool username_autofilled,
const WebInputElement& password_element,
const std::string& password,
bool password_autofilled,
bool check_suggested_username,
bool check_suggested_password) {
if (username_element) {
EXPECT_EQ(username, check_suggested_username
? username_element.SuggestedValue().Utf8()
: username_element.Value().Utf8())
<< "check_suggested_username == " << check_suggested_username;
EXPECT_EQ(username_autofilled, username_element.IsPreviewed() ||
username_element.IsAutofilled());
}
if (password_element) {
EXPECT_EQ(password, check_suggested_password
? password_element.SuggestedValue().Utf8()
: password_element.Value().Utf8())
<< "check_suggested_password == " << check_suggested_password;
EXPECT_EQ(password_autofilled, password_element.IsAutofilled() ||
password_element.IsPreviewed());
}
}
// Checks the DOM-accessible value of the username element and the
// *suggested* value of the password element.
void CheckUsernameDOMStatePasswordSuggestedState(const std::string& username,
bool username_autofilled,
const std::string& password,
bool password_autofilled) {
CheckTextFieldsStateForElements(
username_element_, username, username_autofilled, password_element_,
password, password_autofilled, false /* check_suggested_username */,
true /* check_suggested_password */);
}
// Checks the DOM-accessible value of the username element and the
// DOM-accessible value of the password element.
void CheckTextFieldsDOMState(const std::string& username,
bool username_autofilled,
const std::string& password,
bool password_autofilled) {
CheckTextFieldsStateForElements(
username_element_, username, username_autofilled, password_element_,
password, password_autofilled, false /* check_suggested_username */,
false /* check_suggested_password */);
}
// Checks the suggested values of the `username` and `password` elements.
void CheckTextFieldsSuggestedState(const std::string& username,
bool username_autofilled,
const std::string& password,
bool password_autofilled) {
CheckTextFieldsStateForElements(
username_element_, username, username_autofilled, password_element_,
password, password_autofilled, true /* check_suggested_username */,
true /* check_suggested_password */);
}
void ResetFieldState(
WebInputElement* element,
const std::string& value = std::string(),
blink::WebAutofillState is_autofilled = WebAutofillState::kNotFilled) {
element->SetValue(WebString::FromUTF8(value));
element->SetSuggestedValue(WebString());
element->SetAutofillState(is_autofilled);
element->SetSelectionRange(value.size(), value.size());
}
void CheckUsernameSelection(unsigned start, unsigned end) {
EXPECT_EQ(start, username_element_.SelectionStart());
EXPECT_EQ(end, username_element_.SelectionEnd());
}
// Checks the message sent to PasswordAutofillManager to build the suggestion
// list. `typed_username` is the expected username field value, and `show_all`
// is the expected flag for the PasswordAutofillManager, whether to show all
// suggestions, or only those starting with `typed_username`.
void CheckSuggestions(const std::u16string& typed_username,
bool show_all,
base::Location location = FROM_HERE) {
std::u16string expected_username = show_all ? u"" : typed_username;
SCOPED_TRACE(testing::Message()
<< __func__ << " called from " << location.ToString());
EXPECT_CALL(fake_driver_,
ShowPasswordSuggestions(AllOf(
Field(&autofill::PasswordSuggestionRequest::field,
Field(&autofill::TriggeringField::typed_username,
expected_username)))))
.Times(NumShowSuggestionsCalls());
base::RunLoop().RunUntilIdle();
}
void CheckSuggestionsNotShown() {
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions).Times(0);
base::RunLoop().RunUntilIdle();
}
void ExpectFieldPropertiesMasks(
PasswordFormSourceType expected_type,
const std::map<std::u16string, FieldPropertiesMask>&
expected_properties_masks,
autofill::mojom::SubmissionIndicatorEvent expected_submission_event) {
base::RunLoop().RunUntilIdle();
autofill::FormData form_data;
if (expected_type == PasswordFormSubmitted) {
ASSERT_TRUE(fake_driver_.called_password_form_submitted());
ASSERT_TRUE(static_cast<bool>(fake_driver_.form_data_submitted()));
form_data = *(fake_driver_.form_data_submitted());
} else {
ASSERT_EQ(PasswordFormSameDocumentNavigation, expected_type);
ASSERT_TRUE(fake_driver_.called_dynamic_form_submission());
ASSERT_TRUE(static_cast<bool>(fake_driver_.form_data_maybe_submitted()));
form_data = *(fake_driver_.form_data_maybe_submitted());
EXPECT_EQ(expected_submission_event, form_data.submission_event());
}
size_t unchecked_masks = expected_properties_masks.size();
for (const FormFieldData& field : form_data.fields()) {
const auto& it = expected_properties_masks.find(field.name());
if (it == expected_properties_masks.end())
continue;
EXPECT_EQ(field.properties_mask(), it->second)
<< "Wrong mask for the field " << field.name();
unchecked_masks--;
}
EXPECT_TRUE(unchecked_masks == 0)
<< "Some expected masks are missed in FormData";
}
FormRendererId GetFormUniqueRendererId(const WebString& form_id) {
WebLocalFrame* frame = GetMainFrame();
if (!frame)
return FormRendererId();
WebFormElement web_form =
frame->GetDocument().GetElementById(form_id).To<WebFormElement>();
return form_util::GetFormRendererId(web_form);
}
void ExpectFormDataWithUsernameAndPasswordsAndEvent(
const autofill::FormData& form_data,
FormRendererId form_renderer_id,
base::optional_ref<const std::u16string> username_value,
base::optional_ref<const std::u16string> password_value,
base::optional_ref<const std::u16string> new_password_value,
SubmissionIndicatorEvent event) {
EXPECT_EQ(form_renderer_id, form_data.renderer_id());
if (username_value) {
EXPECT_TRUE(FormHasFieldWithValue(form_data, *username_value));
}
if (password_value) {
EXPECT_TRUE(FormHasFieldWithValue(form_data, *password_value));
}
if (new_password_value) {
EXPECT_TRUE(FormHasFieldWithValue(form_data, *new_password_value));
}
EXPECT_EQ(form_data.submission_event(), event);
}
void ExpectFormSubmittedWithUsernameAndPasswords(
FormRendererId form_renderer_id,
std::optional<std::u16string> username_value,
std::optional<std::u16string> password_value,
std::optional<std::u16string> new_password_value = std::nullopt) {
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(fake_driver_.called_password_form_submitted());
ASSERT_TRUE(static_cast<bool>(fake_driver_.form_data_submitted()));
ExpectFormDataWithUsernameAndPasswordsAndEvent(
*(fake_driver_.form_data_submitted()), form_renderer_id, username_value,
password_value, new_password_value,
SubmissionIndicatorEvent::HTML_FORM_SUBMISSION);
}
void ExpectDynamicFormSubmissionWithUsernameAndPasswords(
FormRendererId form_renderer_id,
const std::u16string& username_value,
const std::u16string& password_value,
SubmissionIndicatorEvent event) {
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(fake_driver_.called_dynamic_form_submission());
ASSERT_TRUE(static_cast<bool>(fake_driver_.form_data_maybe_submitted()));
ExpectFormDataWithUsernameAndPasswordsAndEvent(
*(fake_driver_.form_data_maybe_submitted()), form_renderer_id,
username_value, password_value, std::nullopt, event);
}
void CheckIfEventsAreCalled(const std::vector<std::u16string>& checkers,
bool expected) {
for (const std::u16string& variable : checkers) {
int value;
EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(variable, &value))
<< variable;
EXPECT_EQ(expected, value == 1) << variable;
}
}
void BindPasswordManagerDriver(mojo::ScopedInterfaceEndpointHandle handle) {
fake_driver_.BindReceiver(
mojo::PendingAssociatedReceiver<mojom::PasswordManagerDriver>(
std::move(handle)));
}
void BindPasswordManagerClient(mojo::ScopedInterfaceEndpointHandle handle) {
fake_pw_client_.BindReceiver(
mojo::PendingAssociatedReceiver<mojom::PasswordGenerationDriver>(
std::move(handle)));
}
void SaveAndSubmitForm() { SaveAndSubmitForm(username_element_.Form()); }
void SaveAndSubmitForm(const WebFormElement& form_element) {
FormTracker& tracker = test_api(*autofill_agent_).form_tracker();
static_cast<blink::WebLocalFrameObserver&>(tracker).WillSendSubmitEvent(
form_element);
static_cast<content::RenderFrameObserver&>(tracker).WillSubmitForm(
form_element);
}
void CheckFirstFillingResult(FillingResult result) {
histogram_tester_.ExpectUniqueSample(
"PasswordManager.FirstRendererFillingResult", result, 1);
}
void SubmitForm() {
FormTracker& tracker = test_api(*autofill_agent_).form_tracker();
static_cast<content::RenderFrameObserver&>(tracker).WillSubmitForm(
username_element_.Form());
}
void FireAjaxSucceeded() {
FormTracker& tracker = test_api(*autofill_agent_).form_tracker();
tracker.AjaxSucceeded();
}
void FireDidFinishSameDocumentNavigation() {
FormTracker& tracker = test_api(*autofill_agent_).form_tracker();
static_cast<content::RenderFrameObserver&>(tracker)
.DidFinishSameDocumentNavigation();
}
::testing::AssertionResult UpdateFormElementsForFormHostingShadowDom() {
username_element_ = GetElementByID("un_host")
.ShadowRoot()
.FirstChild()
.To<WebInputElement>();
if (!username_element_) {
return ::testing::AssertionFailure() << "Username element is null.";
}
password_element_ = GetElementByID("pw_host")
.ShadowRoot()
.FirstChild()
.To<WebInputElement>();
if (!password_element_) {
return ::testing::AssertionFailure() << "Password element is null.";
}
return ::testing::AssertionSuccess();
}
// This triggers a layout update to apply JS changes like display = 'none'.
void ForceLayoutUpdate() {
GetWebFrameWidget()->UpdateAllLifecyclePhases(
blink::DocumentUpdateReason::kTest);
}
FakeMojoPasswordManagerDriver fake_driver_;
testing::NiceMock<FakePasswordGenerationDriver> fake_pw_client_;
std::u16string username1_;
std::u16string username2_;
std::u16string username3_;
std::u16string password1_;
std::u16string password2_;
std::u16string password3_;
std::u16string alternate_username3_;
PasswordFormFillData fill_data_;
WebInputElement username_element_;
WebInputElement password_element_;
base::test::ScopedFeatureList scoped_feature_list_;
protected:
base::HistogramTester histogram_tester_;
};
// Tests that the password login is autocompleted as expected when the browser
// sends back the password info.
TEST_F(PasswordAutofillAgentTest, InitialAutocomplete) {
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
// The username and password should have been autocompleted.
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
CheckFirstFillingResult(FillingResult::kSuccess);
}
// Tests that we correctly fill forms having an empty 'action' attribute.
TEST_F(PasswordAutofillAgentTest, InitialAutocompleteForEmptyAction) {
const char kEmptyActionFormHTML[] =
"<FORM name='LoginTestForm'>"
" <INPUT type='text' id='username'/>"
" <INPUT type='password' id='password'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
LoadHTML(kEmptyActionFormHTML);
// Retrieve the input elements so the test can access them.
UpdateUsernameAndPasswordElements();
// Set the expected form origin.
UpdateUrlForHTML(kEmptyActionFormHTML);
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
// The username and password should have been autocompleted.
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
}
// Tests that if a password is marked as readonly, neither field is autofilled
// on page load.
TEST_F(PasswordAutofillAgentTest, NoInitialAutocompleteForReadOnlyPassword) {
SetElementReadOnly(password_element_, true);
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState(std::string(), false, std::string(), false);
CheckFirstFillingResult(FillingResult::kPasswordElementIsNotAutocompleteable);
}
// Can still fill a password field if the username is set to a value that
// matches.
TEST_F(PasswordAutofillAgentTest,
AutocompletePasswordForReadonlyUsernameMatched) {
username_element_.SetValue(WebString::FromUTF16(username3_));
SetElementReadOnly(username_element_, true);
// Filled even though username is not the preferred match.
SimulateOnFillPasswordForm(fill_data_);
CheckUsernameDOMStatePasswordSuggestedState(UTF16ToUTF8(username3_), false,
UTF16ToUTF8(password3_), true);
CheckFirstFillingResult(FillingResult::kSuccess);
}
// Fill username and password fields when username field contains a prefilled
// value that matches the list of known possible prefilled values usually used
// as placeholders.
TEST_F(PasswordAutofillAgentTest, AutocompleteForPrefilledUsernameValue) {
// Set the username element to a value from the prefilled values list.
// Comparison should be insensitive to leading and trailing whitespaces.
username_element_.SetValue(WebString::FromUTF16(u" User Name "));
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
// The username and password should both have suggested values.
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
// Simulate a user click so that the password field's real value is filled.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
// The username and password should have been autocompleted.
CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
CheckFirstFillingResult(FillingResult::kSuccess);
}
// Tests that if filling is invoked twice for the same autofill agent the
// first filling metrics are only logged once.
TEST_F(PasswordAutofillAgentTest, MetricsOnlyLoggedOnce) {
// Set the username element to a value from the prefilled values list.
// Comparison should be insensitive to leading and trailing whitespaces.
username_element_.SetValue(WebString::FromUTF16(u" User Name "));
// Simulate the browser sending back the login info multiple times.
// This triggers the autocomplete.
SimulateOnFillPasswordForm(fill_data_);
SimulateOnFillPasswordForm(fill_data_);
CheckFirstFillingResult(FillingResult::kSuccess);
}
// Fill a password field if the stored username is a prefix of username in
// read-only field.
TEST_F(PasswordAutofillAgentTest,
AutocompletePasswordForReadonlyUsernamePrefixMatched) {
std::u16string username_at = username3_ + u"@example.com";
username_element_.SetValue(WebString::FromUTF16(username_at));
SetElementReadOnly(username_element_, true);
// Filled even though the username in the form is only a proper prefix of the
// stored username.
SimulateOnFillPasswordForm(fill_data_);
CheckUsernameDOMStatePasswordSuggestedState(UTF16ToUTF8(username_at), false,
UTF16ToUTF8(password3_), true);
}
// Credentials are sent to the renderer even for sign-up forms as these may be
// eligible for filling via manual fall back. In this case, the username_field
// and password_field are not set. This test verifies that no failures are
// recorded in PasswordManager.FirstRendererFillingResult.
TEST_F(PasswordAutofillAgentTest, NoFillingOnSignupForm_NoMetrics) {
LoadHTML(kSignupFormHTML);
WebDocument document = GetMainFrame()->GetDocument();
WebElement element =
document.GetElementById(WebString::FromUTF8("random_info"));
ASSERT_TRUE(element);
username_element_ = element.To<WebInputElement>();
fill_data_.username_element_renderer_id = autofill::FieldRendererId();
fill_data_.password_element_renderer_id = autofill::FieldRendererId();
WebFormElement form_element =
document.GetElementById("LoginTestForm").To<WebFormElement>();
fill_data_.form_renderer_id = form_util::GetFormRendererId(form_element);
SimulateOnFillPasswordForm(fill_data_);
histogram_tester_.ExpectTotalCount(
"PasswordManager.FirstRendererFillingResult", 0);
}
// Do not fill a password field if the stored username is a prefix without @
// of username in read-only field.
TEST_F(PasswordAutofillAgentTest,
DontAutocompletePasswordForReadonlyUsernamePrefixMatched) {
std::u16string prefilled_username = username3_ + u"example.com";
username_element_.SetValue(WebString::FromUTF16(prefilled_username));
SetElementReadOnly(username_element_, true);
// Filled even though the username in the form is only a proper prefix of the
// stored username.
SimulateOnFillPasswordForm(fill_data_);
CheckUsernameDOMStatePasswordSuggestedState(UTF16ToUTF8(prefilled_username),
false, std::string(), false);
CheckFirstFillingResult(
FillingResult::kUsernamePrefilledWithIncompatibleValue);
}
// Do not fill a password field if the field isn't readonly despite the stored
// username is a prefix without @ of username in read-only field.
TEST_F(
PasswordAutofillAgentTest,
DontAutocompletePasswordForNotReadonlyUsernameFieldEvenWhenPrefixMatched) {
std::u16string prefilled_username = username3_ + u"@example.com";
username_element_.SetValue(WebString::FromUTF16(prefilled_username));
// Filled even though the username in the form is only a proper prefix of the
// stored username.
SimulateOnFillPasswordForm(fill_data_);
CheckUsernameDOMStatePasswordSuggestedState(UTF16ToUTF8(prefilled_username),
false, std::string(), false);
}
// If a username field is empty and readonly, don't autofill.
TEST_F(PasswordAutofillAgentTest,
NoAutocompletePasswordForReadonlyUsernameUnmatched) {
username_element_.SetValue(WebString::FromUTF8(""));
SetElementReadOnly(username_element_, true);
SimulateOnFillPasswordForm(fill_data_);
CheckUsernameDOMStatePasswordSuggestedState(std::string(), false,
std::string(), false);
CheckFirstFillingResult(FillingResult::kFoundNoPasswordForUsername);
}
// Tests that having a non-matching username precludes the autocomplete.
TEST_F(PasswordAutofillAgentTest, NoAutocompleteForFilledFieldUnmatched) {
username_element_.SetValue(WebString::FromUTF8("bogus"));
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
// Neither field should be autocompleted.
CheckUsernameDOMStatePasswordSuggestedState("bogus", false, std::string(),
false);
CheckFirstFillingResult(
FillingResult::kUsernamePrefilledWithIncompatibleValue);
}
// Don't try to complete a prefilled value that is a partial match
// to a username if the prefilled value isn't on the list of known values
// used as placeholders.
TEST_F(PasswordAutofillAgentTest, NoPartialMatchForPrefilledUsername) {
username_element_.SetValue(WebString::FromUTF8("ali"));
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState("", false, std::string(), false);
CheckUsernameDOMStatePasswordSuggestedState("ali", false, std::string(),
false);
}
// Tests that having a matching username precludes the autofill.
TEST_F(PasswordAutofillAgentTest, InitialAutocompleteForMatchingFilledField) {
username_element_.SetValue(WebString::FromUTF16(kAliceUsername16));
// Simulate the browser sending back the login info, it triggers the
// autofill.
SimulateOnFillPasswordForm(fill_data_);
// The password should have been autofilled, but the username field should
// have been left alone, since it contained the correct value already.
CheckUsernameDOMStatePasswordSuggestedState(kAliceUsername, false,
kAlicePassword, true);
CheckFirstFillingResult(FillingResult::kSuccess);
}
TEST_F(PasswordAutofillAgentTest, PasswordNotClearedOnEdit) {
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
// Simulate the user changing the username to some unknown username.
SimulateUsernameTyping("alicia");
// The password should not have been cleared.
CheckTextFieldsDOMState("alicia", false, kAlicePassword, true);
}
// Tests that lost focus does not trigger filling when `wait_for_username` is
// true.
TEST_F(PasswordAutofillAgentTest, WaitUsername) {
// Simulate the browser sending back the login info.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// No auto-fill should have taken place.
CheckTextFieldsSuggestedState(
/*username=*/std::string(),
/*username_autofilled=*/false,
/*password=*/std::string(),
/*password_autofilled=*/false);
SimulateUsernameTyping(kAliceUsername);
// Change focus in between to make sure blur events don't trigger filling.
SetFocused(password_element_);
SetFocused(username_element_);
// No autocomplete should happen when text is entered in the username.
CheckUsernameDOMStatePasswordSuggestedState(
/*username=*/kAliceUsername,
/*username_autofilled=*/false,
/*password=*/std::string(),
/*password_autofilled=*/false);
CheckFirstFillingResult(FillingResult::kWaitForUsername);
}
TEST_F(PasswordAutofillAgentTest, IsWebElementVisibleTest) {
blink::WebLocalFrame* frame;
LoadHTML(kVisibleFormWithNoUsernameHTML);
frame = GetMainFrame();
std::vector<WebFormElement> forms = frame->GetDocument().GetTopLevelForms();
ASSERT_EQ(1u, forms.size());
std::vector<blink::WebFormControlElement> web_control_elements =
forms[0].GetFormControlElements();
ASSERT_EQ(1u, web_control_elements.size());
EXPECT_TRUE(web_control_elements[0].IsFocusable());
LoadHTML(kNonVisibleFormHTML);
frame = GetMainFrame();
forms = frame->GetDocument().GetTopLevelForms();
ASSERT_EQ(1u, forms.size());
web_control_elements = forms[0].GetFormControlElements();
ASSERT_EQ(1u, web_control_elements.size());
EXPECT_FALSE(web_control_elements[0].IsFocusable());
LoadHTML(kNonDisplayedFormHTML);
frame = GetMainFrame();
forms = frame->GetDocument().GetTopLevelForms();
ASSERT_EQ(1u, forms.size());
web_control_elements = forms[0].GetFormControlElements();
ASSERT_EQ(1u, web_control_elements.size());
EXPECT_FALSE(web_control_elements[0].IsFocusable());
}
TEST_F(PasswordAutofillAgentTest,
SendPasswordFormsTest_VisibleFormWithNoUsername) {
fake_driver_.reset_password_forms_calls();
LoadHTML(kVisibleFormWithNoUsernameHTML);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_parsed());
ASSERT_TRUE(fake_driver_.form_data_parsed());
EXPECT_FALSE(fake_driver_.form_data_parsed()->empty());
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
ASSERT_TRUE(fake_driver_.form_data_rendered());
EXPECT_FALSE(fake_driver_.form_data_rendered()->empty());
}
TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest_EmptyForm) {
base::RunLoop().RunUntilIdle();
fake_driver_.reset_password_forms_calls();
LoadHTML(kEmptyFormHTML);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_password_forms_parsed());
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
ASSERT_TRUE(fake_driver_.form_data_rendered());
EXPECT_TRUE(fake_driver_.form_data_rendered()->empty());
}
TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest_FormWithoutPasswords) {
base::RunLoop().RunUntilIdle();
fake_driver_.reset_password_forms_calls();
LoadHTML(kFormWithoutPasswordsHTML);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_password_forms_parsed());
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
ASSERT_TRUE(fake_driver_.form_data_rendered());
EXPECT_TRUE(fake_driver_.form_data_rendered()->empty());
}
TEST_F(PasswordAutofillAgentTest,
SendPasswordFormsTest_UndetectedPasswordField) {
base::RunLoop().RunUntilIdle();
fake_driver_.reset_password_forms_calls();
LoadHTML(kFormWithoutPasswordsHTML);
// Emulate that a password field appears but we don't detect that.
std::string script =
"document.getElementById('random_field').type = 'password';";
ExecuteJavaScriptForTests(script.c_str());
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_password_forms_parsed());
// When the user clicks on the field, a request to the store will be sent.
EXPECT_TRUE(SimulateElementClick("random_field"));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_parsed());
ASSERT_TRUE(fake_driver_.form_data_parsed());
EXPECT_FALSE(fake_driver_.form_data_parsed()->empty());
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
ASSERT_TRUE(fake_driver_.form_data_rendered());
EXPECT_TRUE(fake_driver_.form_data_rendered()->empty());
}
TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest_NonDisplayedForm) {
fake_driver_.reset_password_forms_calls();
LoadHTML(kNonDisplayedFormHTML);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_parsed());
ASSERT_TRUE(fake_driver_.form_data_parsed());
EXPECT_FALSE(fake_driver_.form_data_parsed()->empty());
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
ASSERT_TRUE(fake_driver_.form_data_rendered());
EXPECT_TRUE(fake_driver_.form_data_rendered()->empty());
}
TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest_NonVisibleForm) {
fake_driver_.reset_password_forms_calls();
LoadHTML(kNonVisibleFormHTML);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_parsed());
ASSERT_TRUE(fake_driver_.form_data_parsed());
EXPECT_FALSE(fake_driver_.form_data_parsed()->empty());
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
ASSERT_TRUE(fake_driver_.form_data_rendered());
EXPECT_TRUE(fake_driver_.form_data_rendered()->empty());
}
TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest_PasswordChangeForm) {
fake_driver_.reset_password_forms_calls();
LoadHTML(kPasswordChangeFormHTML);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_parsed());
ASSERT_TRUE(fake_driver_.form_data_parsed());
EXPECT_FALSE(fake_driver_.form_data_parsed()->empty());
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
ASSERT_TRUE(fake_driver_.form_data_rendered());
EXPECT_FALSE(fake_driver_.form_data_rendered()->empty());
}
TEST_F(PasswordAutofillAgentTest,
SendPasswordFormsTest_CannotCreatePasswordForm) {
// This test checks that a request to the store is sent even if it is a credit
// card form.
fake_driver_.reset_password_forms_calls();
LoadHTML(kCreditCardFormHTML);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_parsed());
ASSERT_TRUE(fake_driver_.form_data_parsed());
EXPECT_FALSE(fake_driver_.form_data_parsed()->empty());
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
ASSERT_TRUE(fake_driver_.form_data_rendered());
EXPECT_FALSE(fake_driver_.form_data_rendered()->empty());
}
TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest_ReloadTab) {
// PasswordAutofillAgent::sent_request_to_store_ disables duplicate requests
// to the store. This test checks that new request will be sent if the frame
// has been reloaded.
fake_driver_.reset_password_forms_calls();
LoadHTML(kNonVisibleFormHTML);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_parsed());
fake_driver_.reset_password_forms_calls();
std::string url_string = "data:text/html;charset=utf-8,";
url_string.append(kNonVisibleFormHTML);
Reload(GURL(url_string));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_parsed());
ASSERT_TRUE(fake_driver_.form_data_parsed());
EXPECT_FALSE(fake_driver_.form_data_parsed()->empty());
}
TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest_Redirection) {
base::RunLoop().RunUntilIdle();
fake_driver_.reset_password_forms_calls();
LoadHTML(kEmptyWebpage);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_password_forms_rendered());
fake_driver_.reset_password_forms_calls();
LoadHTML(kRedirectionWebpage);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_password_forms_rendered());
fake_driver_.reset_password_forms_calls();
LoadHTML(kSimpleWebpage);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
fake_driver_.reset_password_forms_calls();
LoadHTML(kWebpageWithDynamicContent);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_password_forms_rendered());
}
// Tests that fields that are not under a <form> tag are only sent to
// PasswordManager if they contain a password field.
TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest_UnownedtextInputs) {
fake_driver_.reset_password_forms_calls();
const char kFormlessFieldsNonPasswordHTML[] =
" <INPUT type='text' name='email'>"
" <INPUT type='submit' value='Login'/>";
LoadHTML(kFormlessFieldsNonPasswordHTML);
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(fake_driver_.called_password_forms_parsed());
fake_driver_.reset_password_forms_calls();
const char kFormlessFieldsPasswordHTML[] =
" <INPUT type='text' name='email'>"
" <INPUT type='password' name='pw'>"
" <INPUT type='submit' value='Login'/>";
LoadHTML(kFormlessFieldsPasswordHTML);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(fake_driver_.called_password_forms_parsed());
}
// Tests that a password will only be filled as a suggested and will not be
// accessible by the DOM until a user gesture has occurred.
TEST_F(PasswordAutofillAgentTest, GestureRequiredTest) {
// Trigger the initial autocomplete.
SimulateOnFillPasswordForm(fill_data_);
// The username and password should have been autocompleted.
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
// However, it should only have completed with the suggested value, as tested
// above, and it should not have completed into the DOM accessible value for
// the password field.
CheckTextFieldsDOMState(std::string(), true, std::string(), true);
// Simulate a user click so that the password field's real value is filled.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
}
// Verifies that a DOM-activated UI event will not cause an autofill.
TEST_F(PasswordAutofillAgentTest, NoDOMActivationTest) {
// Trigger the initial autocomplete.
SimulateOnFillPasswordForm(fill_data_);
ExecuteJavaScriptForTests(kJavaScriptClick);
CheckTextFieldsDOMState("", true, "", true);
}
// Verifies that password autofill triggers events in JavaScript for forms that
// are filled on page load.
TEST_F(PasswordAutofillAgentTest,
PasswordAutofillTriggersOnChangeEventsOnLoad) {
std::vector<std::u16string> username_event_checkers;
std::vector<std::u16string> password_event_checkers;
std::string events_registration_script =
CreateScriptToRegisterListeners(kUsernameName, &username_event_checkers) +
CreateScriptToRegisterListeners(kPasswordName, &password_event_checkers);
std::string html = std::string(kFormHTML) + events_registration_script;
LoadHTML(html.c_str());
UpdateUrlForHTML(html);
UpdateUsernameAndPasswordElements();
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
// The username and password should have been autocompleted...
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
// ... but since there hasn't been a user gesture yet, the autocompleted
// username and password should only be visible to the user.
CheckTextFieldsDOMState(std::string(), true, std::string(), true);
// JavaScript events shouldn't have been triggered for the username and the
// password yet.
CheckIfEventsAreCalled(username_event_checkers, false);
CheckIfEventsAreCalled(password_event_checkers, false);
// Simulate a user click so that the password field's real value is filled.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
// Now, JavaScript events should have been triggered.
CheckIfEventsAreCalled(username_event_checkers, true);
CheckIfEventsAreCalled(password_event_checkers, true);
}
// Verifies that password autofill triggers events in JavaScript for forms that
// are filled after page load.
TEST_F(PasswordAutofillAgentTest,
PasswordAutofillTriggersOnChangeEventsWaitForUsername) {
std::vector<std::u16string> event_checkers;
std::string events_registration_script =
CreateScriptToRegisterListeners(kUsernameName, &event_checkers) +
CreateScriptToRegisterListeners(kPasswordName, &event_checkers);
std::string html = std::string(kFormHTML) + events_registration_script;
LoadHTML(html.c_str());
UpdateUrlForHTML(html);
UpdateUsernameAndPasswordElements();
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// The username and password should not yet have been autocompleted.
CheckTextFieldsSuggestedState(std::string(), false, std::string(), false);
// Simulate a click just to force a user gesture, since the username value is
// set directly.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
// Simulate the user entering the first letter of their username and selecting
// the matching autofill from the dropdown.
SimulateUsernameTyping("a");
// Since the username element has focus, blur event will be not triggered.
std::erase(event_checkers, u"username_blur_event");
SimulateSuggestionChoice(username_element_);
// The username and password should now have been autocompleted.
CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
// JavaScript events should have been triggered both for the username and for
// the password.
CheckIfEventsAreCalled(event_checkers, true);
}
// Tests that `FillSuggestion` properly fills the username and password on
// focused `username_element_`.
TEST_F(PasswordAutofillAgentTest, FillSuggestionOnUsernameField) {
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
SimulateElementClick(username_element_);
// Neither field should be autocompleted.
CheckTextFieldsDOMState(/*username=*/std::string(),
/*username_autofilled=*/false,
/*password=*/std::string(),
/*password_autofilled=*/false);
// If the username field is not autocompletable, no element will be filled.
SetElementReadOnly(username_element_, /*read_only=*/true);
base::MockCallback<base::OnceCallback<void(bool)>> mock_reply;
EXPECT_CALL(mock_reply, Run(false));
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, mock_reply.Get());
CheckTextFieldsDOMState(/*username=*/std::string(),
/*username_autofilled=*/false,
/*password=*/std::string(),
/*password_autofilled=*/false);
SetElementReadOnly(username_element_, /*read_only=*/false);
// If the password field is not autocompletable, only username will be filled.
SetElementReadOnly(password_element_, /*read_only=*/true);
EXPECT_CALL(mock_reply, Run(false));
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, mock_reply.Get());
CheckTextFieldsDOMState(kAliceUsername, /*username_autofilled=*/true,
/*password=*/std::string(),
/*password_autofilled=*/false);
size_t username_length = strlen(kAliceUsername);
CheckUsernameSelection(username_length, username_length);
SetElementReadOnly(password_element_, /*read_only=*/false);
ResetFieldState(&username_element_);
// After filling with the suggestion, both fields should be autocompleted.
EXPECT_CALL(mock_reply, Run(true));
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, mock_reply.Get());
CheckTextFieldsDOMState(kAliceUsername, /*username_autofilled=*/true,
kAlicePassword, /*password_autofilled=*/true);
username_length = strlen(kAliceUsername);
CheckUsernameSelection(username_length, username_length);
// Try filling with a suggestion with password different from the one that
// was initially sent to the renderer.
EXPECT_CALL(mock_reply, Run(true));
password_autofill_agent_->FillPasswordSuggestion(
kBobUsername16, kCarolPassword16, mock_reply.Get());
CheckTextFieldsDOMState(kBobUsername, /*username_autofilled=*/true,
kCarolPassword, /*password_autofilled=*/true);
username_length = strlen(kBobUsername);
CheckUsernameSelection(username_length, username_length);
}
// Avoid filling suggestion on username if the password field is disabled and
// there is no <form> tag.
TEST_F(PasswordAutofillAgentTest,
NoFillSuggestionOnNoFormTagAndPasswordDisabled) {
LoadHTML(kUnownedFieldsWithPasswordDisabled);
UpdateUsernameAndPasswordElements();
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
SimulateElementClick(username_element_);
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
// Neither field should be autocompleted.
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
}
// Tests that `FillSuggestion` properly fills the username and password on
// focused `password_element_`.
TEST_F(PasswordAutofillAgentTest, FillSuggestionOnPasswordField) {
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
SimulateElementClick(password_element_);
// Neither field should be autocompleted.
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
// If the password field is not autocompletable, no filling will be made.
SetElementReadOnly(password_element_, /*read_only=*/true);
base::MockCallback<base::OnceCallback<void(bool)>> reply_call;
EXPECT_CALL(reply_call, Run(false));
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, reply_call.Get());
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
SetElementReadOnly(password_element_, /*read_only=*/false);
// If the username field is not autocompletable, only password field will be
// filled.
SetElementReadOnly(username_element_, /*read_only=*/true);
EXPECT_CALL(reply_call, Run(false));
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, reply_call.Get());
CheckTextFieldsDOMState(/*username=*/std::string(),
/*username_autofilled=*/false, kAlicePassword,
/*password_autofilled=*/true);
SetElementReadOnly(username_element_, /*read_only=*/false);
ResetFieldState(&username_element_);
// After filling with the suggestion, both fields should be autocompleted.
EXPECT_CALL(reply_call, Run(true));
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, reply_call.Get());
CheckTextFieldsDOMState(kAliceUsername, /*username_autofilled=*/true,
kAlicePassword, /*password_autofilled=*/true);
size_t username_length = strlen(kAliceUsername);
CheckUsernameSelection(username_length, username_length);
// Try filling with a suggestion with password different from the one that
// was initially sent to the renderer.
EXPECT_CALL(reply_call, Run(true));
password_autofill_agent_->FillPasswordSuggestion(
kBobUsername16, kCarolPassword16, reply_call.Get());
CheckTextFieldsDOMState(kBobUsername, /*username_autofilled=*/true,
kCarolPassword, /*password_autofilled=*/true);
username_length = strlen(kBobUsername);
CheckUsernameSelection(username_length, username_length);
}
// Tests that `FillSuggestion` properly fills the username and password when the
// username field is created dynamically in JavaScript.
TEST_F(PasswordAutofillAgentTest, FillSuggestionWithDynamicUsernameField) {
LoadHTML(kVisibleFormWithNoUsernameHTML);
UpdateOnlyPasswordElement();
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
constexpr const char* kAddUsernameToFormScript =
"var new_input = document.createElement('input');"
"new_input.setAttribute('type', 'text');"
"new_input.setAttribute('id', 'username');"
"password_field = document.getElementById('password');"
"password_field.parentNode.insertBefore(new_input, password_field);";
ExecuteJavaScriptForTests(kAddUsernameToFormScript);
UpdateUsernameAndPasswordElements();
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
// After filling with the suggestion, both fields should be autocompleted.
SimulateElementClick(password_element_);
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
CheckFirstFillingResult(FillingResult::kWaitForUsername);
}
// Tests that `FillSuggestion` doesn't change non-empty non-autofilled username
// when interacting with the password field.
TEST_F(PasswordAutofillAgentTest,
FillSuggestionFromPasswordFieldWithUsernameManuallyFilled) {
username_element_.SetValue(WebString::FromUTF8("user1"));
// Simulate the browser sending the login info, but set `wait_for_username` to
// prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Neither field should have been autocompleted.
CheckTextFieldsDOMState("user1", false, std::string(), false);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, fake_driver_.called_inform_about_user_input_count());
// Only password field should be autocompleted.
SimulateElementClick(password_element_);
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
CheckTextFieldsDOMState("user1", false, kAlicePassword, true);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, fake_driver_.called_inform_about_user_input_count());
// Try Filling with a different password. Only password should be changed.
password_autofill_agent_->FillPasswordSuggestion(
kBobUsername16, kCarolPassword16, base::DoNothing());
CheckTextFieldsDOMState("user1", false, kCarolPassword, true);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, fake_driver_.called_inform_about_user_input_count());
}
// Tests that `PreviewSuggestion` properly previews the username and password on
// `username_element_` focus.
TEST_F(PasswordAutofillAgentTest, PreviewSuggestionOnUsernameField) {
// Simulate the browser sending the login info, but set `wait_for_username` to
// prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Neither field should be autocompleted.
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
// If the password field is not autocompletable, the preview must be available
// only on username.
SetElementReadOnly(password_element_, /*read_only=*/true);
ASSERT_TRUE(SimulateElementClick(kUsernameName));
password_autofill_agent_->PreviewSuggestion(
username_element_, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(kAliceUsername, /*username_autofilled=*/true,
/*password=*/std::string(),
/*password_autofilled=*/false);
SetElementReadOnly(password_element_, /*read_only=*/false);
password_autofill_agent_->ClearPreviewedForm();
// If the username field is not autocompletable, the preview must not be shown
// on any field.
SetElementReadOnly(username_element_, /*read_only=*/true);
password_autofill_agent_->PreviewSuggestion(
username_element_, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
SetElementReadOnly(username_element_, /*read_only=*/false);
// After selecting the preview, both fields should be previewed with
// suggested values.
password_autofill_agent_->PreviewSuggestion(
username_element_, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(kAliceUsername, /*username_autofilled=*/true,
kAlicePassword, /*password_autofilled=*/true);
// Since the suggestion is previewed as a placeholder, there should be no
// selected text.
CheckUsernameSelection(/*start=*/0, /*end=*/0);
// Try previewing with a password different from the one that was initially
// sent to the renderer.
password_autofill_agent_->PreviewSuggestion(username_element_, kBobUsername16,
kCarolPassword16);
CheckTextFieldsSuggestedState(kBobUsername, /*username_autofilled=*/true,
kCarolPassword, /*password_autofilled=*/true);
// Since the suggestion is previewed as a placeholder, there should be no
// selected text.
CheckUsernameSelection(/*start=*/0, /*end=*/0);
}
// Tests that `PreviewSuggestion` properly previews the username and password on
// `password_element_` focus.
TEST_F(PasswordAutofillAgentTest, PreviewSuggestionOnPasswordField) {
// Simulate the browser sending the login info, but set `wait_for_username` to
// prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Neither field should be autocompleted.
CheckTextFieldsDOMState(/*username=*/std::string(),
/*username_autofilled=*/false,
/*password=*/std::string(),
/*password_autofilled=*/false);
// If the password field is not autocompletable, there must be no preview
// available.
SetElementReadOnly(password_element_, /*read_only=*/true);
ASSERT_TRUE(SimulateElementClick(kUsernameName));
password_autofill_agent_->PreviewSuggestion(
password_element_, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
SetElementReadOnly(password_element_, /*read_only=*/false);
// If the username field is not autocompletable, the preview must be shown
// only on the password field.
SetElementReadOnly(username_element_, /*read_only=*/true);
password_autofill_agent_->PreviewSuggestion(
password_element_, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(/*username=*/std::string(),
/*username_autofilled=*/false, kAlicePassword,
/*password_autofilled=*/true);
SetElementReadOnly(username_element_, /*read_only=*/false);
// After previewing the suggestion, both fields should be previewed with
// suggested values.
password_autofill_agent_->PreviewSuggestion(
password_element_, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(kAliceUsername, /*username_autofilled=*/true,
kAlicePassword, /*password_autofilled=*/true);
// Since the suggestion is previewed as a placeholder, there should be no
// selected text.
CheckUsernameSelection(/*start=*/0, /*end=*/0);
// Try previewing with a password different from the one that was initially
// sent to the renderer.
password_autofill_agent_->PreviewSuggestion(password_element_, kBobUsername16,
kCarolPassword16);
CheckTextFieldsSuggestedState(kBobUsername, /*username_autofilled=*/true,
kCarolPassword, /*password_autofilled=*/true);
// Since the suggestion is previewed as a placeholder, there should be no
// selected text.
CheckUsernameSelection(/*start=*/0, /*end=*/0);
}
// Tests that `PreviewSuggestion` doesn't change non-empty non-autofilled
// username when previewing autofills on interacting with the password field.
TEST_F(PasswordAutofillAgentTest,
PreviewSuggestionFromPasswordFieldWithUsernameManuallyFilled) {
username_element_.SetValue(WebString::FromUTF8("user1"));
// Simulate the browser sending the login info, but set `wait_for_username` to
// prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Neither field should have been autocompleted.
CheckTextFieldsDOMState("user1", false, std::string(), false);
// Only password field should be autocompleted.
ASSERT_TRUE(SimulateElementClick("password"));
password_autofill_agent_->PreviewSuggestion(
password_element_, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(std::string(), false, kAlicePassword, true);
CheckTextFieldsDOMState("user1", false, std::string(), true);
// Try previewing with a different password. Only password should be changed.
password_autofill_agent_->PreviewSuggestion(password_element_, kBobUsername16,
kCarolPassword16);
CheckTextFieldsSuggestedState(std::string(), false, kCarolPassword, true);
CheckTextFieldsDOMState("user1", false, std::string(), true);
}
// Tests that `PreviewSuggestion` properly sets the username selection range.
TEST_F(PasswordAutofillAgentTest, PreviewSuggestionSelectionRange) {
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
for (const auto& selected_element : {username_element_, password_element_}) {
ASSERT_TRUE(
SimulateElementClick(selected_element.GetAttribute("id").Ascii()));
ResetFieldState(&username_element_, "ali", WebAutofillState::kPreviewed);
ResetFieldState(&password_element_);
password_autofill_agent_->PreviewSuggestion(
selected_element, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
// The selection should be set after the third character.
CheckUsernameSelection(3, 3);
}
}
// Tests that `ClearPreview` properly clears previewed username and password
// with password being previously autofilled.
TEST_F(PasswordAutofillAgentTest, ClearPreviewWithPasswordAutofilled) {
ResetFieldState(&password_element_, "sec", WebAutofillState::kPreviewed);
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsDOMState(std::string(), false, "sec", true);
for (const auto& selected_element : {username_element_, password_element_}) {
ASSERT_TRUE(
SimulateElementClick(selected_element.GetAttribute("id").Ascii()));
password_autofill_agent_->PreviewSuggestion(
selected_element, kAliceUsername16, kAlicePassword16);
password_autofill_agent_->ClearPreviewedForm();
EXPECT_TRUE(username_element_.SuggestedValue().IsEmpty());
EXPECT_TRUE(password_element_.SuggestedValue().IsEmpty());
CheckTextFieldsDOMState(std::string(), false, "sec", true);
CheckUsernameSelection(0, 0);
}
}
// Tests that `ClearPreview` properly clears previewed username and password
// with username being previously autofilled.
TEST_F(PasswordAutofillAgentTest, ClearPreviewWithUsernameAutofilled) {
ResetFieldState(&username_element_, "ali", WebAutofillState::kPreviewed);
username_element_.SetSelectionRange(3, 3);
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsDOMState("ali", true, std::string(), false);
for (const auto& selected_element : {username_element_, password_element_}) {
ASSERT_TRUE(
SimulateElementClick(selected_element.GetAttribute("id").Ascii()));
password_autofill_agent_->PreviewSuggestion(
selected_element, kAliceUsername16, kAlicePassword16);
password_autofill_agent_->ClearPreviewedForm();
EXPECT_TRUE(username_element_.SuggestedValue().IsEmpty());
EXPECT_TRUE(password_element_.SuggestedValue().IsEmpty());
CheckTextFieldsDOMState("ali", true, std::string(), false);
CheckUsernameSelection(3, 3);
}
}
// Tests that `PreviewField` correctly previews fields.
TEST_F(PasswordAutofillAgentTest, PreviewField) {
WebInputElement random_element = GetInputElementByID("random_field");
std::vector<WebInputElement> elements{username_element_, password_element_,
random_element};
for (WebInputElement& element : elements) {
SetElementReadOnly(element, true);
password_autofill_agent_->PreviewField(
form_util::GetFieldRendererId(element), kAliceUsername16);
EXPECT_TRUE(element.SuggestedValue().IsEmpty());
SetElementReadOnly(element, false);
password_autofill_agent_->PreviewField(
form_util::GetFieldRendererId(element), kAliceUsername16);
EXPECT_EQ(kAliceUsername, element.SuggestedValue().Utf8());
}
}
// Tests that the field state is correctly reset after preview.
TEST_F(PasswordAutofillAgentTest, PreviewField_ClearPreviewedForm) {
WebInputElement random_element = GetInputElementByID("random_field");
std::vector<WebInputElement> elements{username_element_, password_element_,
random_element};
for (WebInputElement& element : elements) {
// Simulate autofilling the field with "ali".
ResetFieldState(&element, "ali", WebAutofillState::kAutofilled);
element.SetSelectionRange(0u, 0u);
password_autofill_agent_->PreviewField(
form_util::GetFieldRendererId(element), kAliceUsername16);
EXPECT_EQ(kAliceUsername, element.SuggestedValue().Utf8());
EXPECT_TRUE(element.IsPreviewed());
password_autofill_agent_->ClearPreviewedForm();
EXPECT_TRUE(element.SuggestedValue().IsEmpty());
EXPECT_TRUE(element.IsAutofilled());
// The selection must stay intact.
EXPECT_EQ(0u, element.SelectionStart());
EXPECT_EQ(0u, element.SelectionEnd());
}
}
// Tests that `ClearPreview` properly clears previewed username and password
// with username and password being previously autofilled.
TEST_F(PasswordAutofillAgentTest,
ClearPreviewWithAutofilledUsernameAndPassword) {
ResetFieldState(&username_element_, "ali", WebAutofillState::kPreviewed);
ResetFieldState(&password_element_, "sec", WebAutofillState::kPreviewed);
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsDOMState("ali", true, "sec", true);
for (const auto& selected_element : {username_element_, password_element_}) {
ASSERT_TRUE(
SimulateElementClick(selected_element.GetAttribute("id").Ascii()));
password_autofill_agent_->PreviewSuggestion(
selected_element, kAliceUsername16, kAlicePassword16);
password_autofill_agent_->ClearPreviewedForm();
EXPECT_TRUE(username_element_.SuggestedValue().IsEmpty());
EXPECT_TRUE(password_element_.SuggestedValue().IsEmpty());
CheckTextFieldsDOMState("ali", true, "sec", true);
CheckUsernameSelection(3, 3);
}
}
// Test that preview is cleared before the suggestion is filled.
TEST_F(PasswordAutofillAgentTest, ClearPreviewBeforeFillingSuggestion) {
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsDOMState(/*username=*/"", /*username_autofilled=*/false,
/*password=*/"", /*password_autofilled=*/false);
for (const auto& selected_element : {username_element_, password_element_}) {
SetFocused(selected_element);
password_autofill_agent_->PreviewSuggestion(
selected_element, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(
/*username=*/kAliceUsername, /*username_autofilled=*/true,
/*password=*/kAlicePassword, /*password_autofilled=*/true);
CheckTextFieldsDOMState(/*username=*/"", /*username_autofilled=*/true,
/*password=*/"", /*password_autofilled=*/true);
EXPECT_TRUE(username_element_.IsPreviewed());
EXPECT_TRUE(password_element_.IsPreviewed());
password_autofill_agent_->FillPasswordSuggestion(
kBobUsername16, kBobPassword16, base::DoNothing());
CheckTextFieldsSuggestedState(
/*username=*/"", /*username_autofilled=*/true, /*password=*/"",
/*password_autofilled=*/true);
CheckTextFieldsDOMState(
/*username=*/kBobUsername, /*username_autofilled=*/true,
/*password=*/kBobPassword, /*password_autofilled=*/true);
EXPECT_TRUE(username_element_.IsAutofilled());
EXPECT_TRUE(password_element_.IsAutofilled());
password_autofill_agent_->ClearPreviewedForm();
CheckTextFieldsSuggestedState(
/*username=*/"", /*username_autofilled=*/true, /*password=*/"",
/*password_autofilled=*/true);
CheckTextFieldsDOMState(
/*username=*/kBobUsername, /*username_autofilled=*/true,
/*password=*/kBobPassword, /*password_autofilled=*/true);
EXPECT_TRUE(username_element_.IsAutofilled());
EXPECT_TRUE(password_element_.IsAutofilled());
ClearUsernameAndPasswordFieldValues();
}
}
// Tests that `FillIntoFocusedField` doesn't fill read-only text fields.
TEST_F(PasswordAutofillAgentTest, FillIntoFocusedReadonlyTextField) {
// Neither field should be autocompleted.
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
// If the field is readonly, it should not be affected.
SetElementReadOnly(username_element_, true);
ASSERT_TRUE(SimulateElementClick(kUsernameName));
password_autofill_agent_->FillIntoFocusedField(
/*is_password=*/false, kAliceUsername16);
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
}
// Tests that `FillIntoFocusedField` properly fills user-provided credentials.
TEST_F(PasswordAutofillAgentTest, FillIntoFocusedWritableTextField) {
// Neither field should be autocompleted.
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
// The same field should be filled if it is writable.
FocusElement(kUsernameName);
SetElementReadOnly(username_element_, false);
password_autofill_agent_->FillIntoFocusedField(
/*is_password=*/false, kAliceUsername16);
CheckTextFieldsDOMState(kAliceUsername, true, std::string(), false);
CheckUsernameSelection(strlen(kAliceUsername), strlen(kAliceUsername));
}
// Tests that `FillIntoFocusedField` doesn't fill passwords in user fields.
TEST_F(PasswordAutofillAgentTest, FillIntoFocusedFieldOnlyIntoPasswordFields) {
// Neither field should be autocompleted.
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
// Filling a password into a username field doesn't work.
FocusElement(kUsernameName);
password_autofill_agent_->FillIntoFocusedField(
/*is_password=*/true, kAlicePassword16);
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
// When a password field is focus, the filling works.
FocusElement(kPasswordName);
password_autofill_agent_->FillIntoFocusedField(
/*is_password=*/true, kAlicePassword16);
CheckTextFieldsDOMState(std::string(), false, kAlicePassword, true);
}
// Tests that `FillIntoFocusedField` fills last focused, not last clicked field.
TEST_F(PasswordAutofillAgentTest, FillIntoFocusedFieldForNonClickFocus) {
// Neither field should be autocompleted.
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
// Click the username but shift the focus without click to the password.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
FocusElement(kPasswordName);
// The completion should now affect ONLY the password field. Don't fill a
// password so the error on failure shows where the filling happened.
// (see FillIntoFocusedFieldOnlyIntoPasswordFields).
password_autofill_agent_->FillIntoFocusedField(
/*is_password=*/false, u"TextToFill");
CheckTextFieldsDOMState(std::string(), false, "TextToFill", true);
}
// Tests that `FillInfoField` doesn't fill read-only text fields.
TEST_F(PasswordAutofillAgentTest, FillIntoReadonlyTextField) {
// Neither field should be autocompleted.
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
// If the field is readonly, it should not be affected.
SetElementReadOnly(username_element_, true);
password_autofill_agent_->FillField(
form_util::GetFieldRendererId(username_element_), kAliceUsername16,
AutofillSuggestionTriggerSource::kUnspecified);
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
}
// Tests that `FillInfoField` correctly fills the username field.
TEST_F(PasswordAutofillAgentTest, FillIntoUsernameField) {
// Neither field should be autocompleted.
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
password_autofill_agent_->FillField(
form_util::GetFieldRendererId(username_element_), kAliceUsername16,
AutofillSuggestionTriggerSource::kUnspecified);
CheckTextFieldsDOMState(
/*username=*/kAliceUsername, /*username_autofilled=*/true,
/*password=*/std::string(), /*password_autofilled=*/false);
}
// Tests that `FillInfoField` correctly fills the password field.
TEST_F(PasswordAutofillAgentTest, FillIntoPasswordField) {
// Neither field should be autocompleted.
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
password_autofill_agent_->FillField(
form_util::GetFieldRendererId(password_element_), kAlicePassword16,
AutofillSuggestionTriggerSource::kUnspecified);
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/kAlicePassword, /*password_autofilled=*/true);
}
// Tests that `FillInfoField` can fill into a random field.
TEST_F(PasswordAutofillAgentTest, FillIntoRandomField) {
WebInputElement random_element = GetInputElementByID("random_field");
// The field should not be autocompleted.
EXPECT_EQ(std::string(), random_element.Value().Utf8());
password_autofill_agent_->FillField(
form_util::GetFieldRendererId(random_element), kAliceUsername16,
AutofillSuggestionTriggerSource::kUnspecified);
EXPECT_EQ(kAliceUsername, random_element.Value().Utf8());
}
// Tests that `FillInfoField` doesn't fill non-existent fields.
TEST_F(PasswordAutofillAgentTest, FillIntoNonExistingField) {
WebInputElement random_element = GetInputElementByID("random_field");
// Neither field should be autocompleted.
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
EXPECT_EQ(std::string(), random_element.Value().Utf8());
password_autofill_agent_->FillField(
FieldRendererId(), kAliceUsername16,
AutofillSuggestionTriggerSource::kUnspecified);
// Neither field should be autocompleted.
CheckTextFieldsDOMState(
/*username=*/std::string(), /*username_autofilled=*/false,
/*password=*/std::string(), /*password_autofilled=*/false);
EXPECT_EQ(std::string(), random_element.Value().Utf8());
}
// Tests that `ClearPreview` properly clears previewed username and password
// with neither username nor password being previously autofilled.
TEST_F(PasswordAutofillAgentTest,
ClearPreviewWithNotAutofilledUsernameAndPassword) {
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
for (const auto& selected_element : {username_element_, password_element_}) {
ASSERT_TRUE(
SimulateElementClick(selected_element.GetAttribute("id").Ascii()));
password_autofill_agent_->PreviewSuggestion(
selected_element, kAliceUsername16, kAlicePassword16);
password_autofill_agent_->ClearPreviewedForm();
EXPECT_TRUE(username_element_.SuggestedValue().IsEmpty());
EXPECT_TRUE(password_element_.SuggestedValue().IsEmpty());
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
CheckUsernameSelection(0, 0);
}
}
// Tests that logging is off by default.
TEST_F(PasswordAutofillAgentTest, OnChangeLoggingState_NoMessage) {
SendVisiblePasswordForms();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_record_save_progress());
}
// Test that logging can be turned on by a message.
TEST_F(PasswordAutofillAgentTest, OnChangeLoggingState_Activated) {
// Turn the logging on.
password_autofill_agent_->SetLoggingState(true);
SendVisiblePasswordForms();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(fake_driver_.called_record_save_progress());
}
// Test that logging can be turned off by a message.
TEST_F(PasswordAutofillAgentTest, OnChangeLoggingState_Deactivated) {
// Turn the logging on and then off.
password_autofill_agent_->SetLoggingState(true);
password_autofill_agent_->SetLoggingState(false);
SendVisiblePasswordForms();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_record_save_progress());
}
// Tests that one user click on a username field is sufficient to bring up a
// credential suggestion popup, and the user can autocomplete the password by
// selecting the credential from the popup.
TEST_F(PasswordAutofillAgentTest, ClickAndSelect) {
FocusElement(kUsernameName);
// SimulateElementClick() is called so that a user gesture is actually made
// and the password can be filled. However, SimulateElementClick() does not
// actually lead to the AutofillAgent's InputElementClicked() method being
// called, so SimulateSuggestionChoice has to manually call
// InputElementClicked().
ClearUsernameAndPasswordFieldValues();
SimulateOnFillPasswordForm(fill_data_);
ASSERT_TRUE(SimulateElementClick(kUsernameName));
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions);
base::RunLoop().RunUntilIdle();
histogram_tester_.ExpectUniqueSample(
"PasswordManager.SuggestionPopupTriggerSource",
static_cast<int>(autofill::AutofillSuggestionTriggerSource::
kFormControlElementClicked),
1);
SimulateSuggestionChoice(username_element_);
CheckSuggestions(kAliceUsername16, true);
CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
}
// Tests that password suggestions are prefix matched against typed username.
// TODO(b:322923603): Clean up when the feature is launched.
TEST_F(PasswordAutofillAgentTest, SuggestionsPrefixMatchedByTypedUsername) {
ConfigurePasswordSuggestionFiltering(/*enabled=*/false);
ClearUsernameAndPasswordFieldValues();
// Make sure there's password data to fill in the field.
SimulateOnFillPasswordForm(fill_data_);
// Enter the value manually.
SimulateUsernameTyping("ali");
// Simulate a user clicking on the username element. This should produce a
// message with all the usernames.
SimulateElementClick(username_element_);
CheckSuggestions(u"ali", /*show_all=*/false);
base::RunLoop().RunUntilIdle();
}
// Tests that all password suggestiona are shown when suggestion filtering is
// disabled.
TEST_F(PasswordAutofillAgentTest,
SuggestionsNotPrefixMatchedWhenFeatureEnabled) {
ConfigurePasswordSuggestionFiltering(/*enabled=*/true);
ClearUsernameAndPasswordFieldValues();
// Make sure there's password data to fill in the field.
SimulateOnFillPasswordForm(fill_data_);
// Enter the value manually.
SimulateUsernameTyping("ali");
// Simulate a user clicking on the username element. This should produce a
// message with all the usernames.
SimulateElementClick(username_element_);
CheckSuggestions(u"ali", /*show_all=*/true);
base::RunLoop().RunUntilIdle();
}
// Tests that the popup is suppressed when the user selects address or payments
// fallback even when the triggering field that is classified as password.
TEST_F(PasswordAutofillAgentTest,
NoPopupOnPasswordFieldWhereAddressOrPaymentsManualFallbackWasSelected) {
SimulateOnFillPasswordForm(fill_data_);
// This call is necessary to setup the autofill agent appropriate for the
// user selection; simulates the menu actually popping up.
SimulatePointClick(gfx::Point(1, 1));
// No popup request when using address/payment/plus address manual fallback.
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions).Times(0);
autofill_agent_->TriggerSuggestions(
form_util::GetFieldRendererId(username_element_),
AutofillSuggestionTriggerSource::kManualFallbackPlusAddresses);
// However, the popup is requested for password manual fallback.
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions);
autofill_agent_->TriggerSuggestions(
form_util::GetFieldRendererId(username_element_),
AutofillSuggestionTriggerSource::kManualFallbackPasswords);
}
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
// Users in pending state are shown a suggestion to "verify it's you" even when
// there are no passwords.
TEST_F(
PasswordAutofillAgentTest,
NoPopupOnPasswordFieldWithoutSuggestionsByDefaultWhenNotEligibleForPromo) {
ClearUsernameAndPasswordFieldValues();
UpdateRendererIDsInFillData();
password_autofill_agent_->InformNoSavedCredentials(false);
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions).Times(0);
ASSERT_TRUE(SimulateElementClick(kPasswordName));
}
TEST_F(PasswordAutofillAgentTest,
PopupOnPasswordFieldWithoutSuggestionsWhenEligibleForPromo) {
ClearUsernameAndPasswordFieldValues();
UpdateRendererIDsInFillData();
password_autofill_agent_->InformNoSavedCredentials(
/*should_show_popup_without_passwords=*/true);
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions)
.Times(NumShowSuggestionsCalls());
ASSERT_TRUE(SimulateElementClick(kPasswordName));
}
#endif // BUILDFLAG(ENABLE_DICE_SUPPORT)
// Tests the autosuggestions that are given when the element is clicked.
// Specifically, tests when the user clicks on the username element after page
// load and the element is autofilled, when the user clicks on an element that
// has a matching username.
TEST_F(PasswordAutofillAgentTest, CredentialsOnClick) {
// Simulate the browser sending back the login info.
SimulateOnFillPasswordForm(fill_data_);
// Clear the text fields to start fresh.
ClearUsernameAndPasswordFieldValues();
// Call SimulateElementClick() to produce a user gesture on the page so
// autofill will actually fill.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions)
.Times(NumShowSuggestionsCalls());
base::RunLoop().RunUntilIdle();
// Simulate a user clicking on the username element. This should produce a
// message with all the usernames.
SimulateElementClick(username_element_);
CheckSuggestions(std::u16string(), true);
// Now simulate a user typing in a saved username. The list is filtered.
EXPECT_CALL(fake_driver_,
ShowPasswordSuggestions(Field(
&autofill::PasswordSuggestionRequest::field,
Field(&autofill::TriggeringField::element_id,
form_util::GetFieldRendererId(username_element_)))))
.Times(NumShowSuggestionsCalls());
SimulateUsernameTyping(kAliceUsername);
}
// Tests that there is an autosuggestion from the password manager when the
// user clicks on the password field.
TEST_F(PasswordAutofillAgentTest, NoCredentialsOnPasswordClick) {
SimulateClosingKeyboardReplacingSurfaceIfAndroid(kUsernameName);
// Simulate the browser sending back the login info.
SimulateOnFillPasswordForm(fill_data_);
// Clear the text fields to start fresh.
ClearUsernameAndPasswordFieldValues();
// Call SimulateElementClick() to produce a user gesture on the page so
// autofill will actually fill.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions);
base::RunLoop().RunUntilIdle();
// Simulate a user clicking on the password element. This should produce no
// message.
SimulateElementClick(password_element_);
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions)
.Times(NumShowSuggestionsCalls());
base::RunLoop().RunUntilIdle();
}
// The user types in a username and a password, but then just before sending
// the form off, a script clears them. This test checks that
// PasswordAutofillAgent can still remember the username and the password
// typed by the user.
TEST_F(PasswordAutofillAgentTest,
RememberLastNonEmptyUsernameAndPasswordOnSubmit_ScriptCleared) {
LoadHTML(kSignupFormHTML);
WebInputElement username_element = GetInputElementByID("random_info");
ASSERT_TRUE(username_element);
SimulateUserInputChangeForElement(username_element, "username");
WebInputElement new_password_element = GetInputElementByID("new_password");
ASSERT_TRUE(new_password_element);
SimulateUserInputChangeForElement(new_password_element, "random");
WebInputElement confirmation_password_element =
GetInputElementByID("confirm_password");
ASSERT_TRUE(confirmation_password_element);
SimulateUserInputChangeForElement(confirmation_password_element, "random");
// Simulate that the username and the password values were cleared by the
// site's JavaScript before submit.
username_element.SetValue(WebString());
new_password_element.SetValue(WebString());
confirmation_password_element.SetValue(WebString());
// Submit form.
FormTracker& tracker = test_api(*autofill_agent_).form_tracker();
static_cast<content::RenderFrameObserver&>(tracker).WillSubmitForm(
username_element.Form());
// Observe that the PasswordAutofillAgent still remembered the last non-empty
// username and password and sent that to the browser.
ExpectFormSubmittedWithUsernameAndPasswords(
form_util::GetFormRendererId(username_element.Form()), u"username",
/*password_value=*/std::nullopt, u"random");
fake_driver_.form_data_submitted();
}
// Similar to RememberLastNonEmptyPasswordOnSubmit_ScriptCleared, but this time
// it's the user who clears the username and the password. This test checks
// that in that case, the last non-empty username and password are not
// remembered.
TEST_F(PasswordAutofillAgentTest,
RememberLastNonEmptyUsernameAndPasswordOnSubmit_UserCleared) {
SimulateUsernameTyping("temp");
SimulatePasswordTyping("random");
// Simulate that the user actually cleared the username and password again.
SimulateUsernameTyping("");
SimulatePasswordTyping("");
SubmitForm();
// Observe that the PasswordAutofillAgent respects the user having cleared the
// password.
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), /*username_value=*/u"",
/*password_value=*/u"");
}
// Similar to RememberLastNonEmptyPasswordOnSubmit_ScriptCleared, but uses the
// new password instead of the current password.
TEST_F(PasswordAutofillAgentTest,
RememberLastNonEmptyUsernameAndPasswordOnSubmit_New) {
const char kNewPasswordFormHTML[] =
"<FORM name='LoginTestForm' action='http://www.bidule.com'>"
" <INPUT type='text' id='username' autocomplete='username'/>"
" <INPUT type='password' id='password' autocomplete='new-password'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
LoadHTML(kNewPasswordFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("temp");
SimulatePasswordTyping("random");
// Simulate that the username and the password value was cleared by
// the site's JavaScript before submit.
username_element_.SetValue(WebString());
password_element_.SetValue(WebString());
SubmitForm();
// Observe that the PasswordAutofillAgent still remembered the last non-empty
// password and sent that to the browser.
ExpectFormSubmittedWithUsernameAndPasswords(
form_util::GetFormRendererId(username_element_.Form()), u"temp",
/*password_value=*/std::nullopt, u"random");
}
// Similar to RememberLastNonEmptyUsernameAndPasswordOnSubmit_New, but uses
// no password fields on single username form
TEST_F(PasswordAutofillAgentTest, RememberLastNonEmptySingleUsername) {
LoadHTML(kSingleUsernameFormHTML);
UpdateOnlyUsernameElement();
SimulateUsernameTyping("temp");
SubmitForm();
// Observe that the PasswordAutofillAgent still remembered the last non-empty
// password and sent that to the browser.
ExpectFormSubmittedWithUsernameAndPasswords(
form_util::GetFormRendererId(username_element_.Form()), u"temp",
/*password_value=*/u"");
}
// The user first accepts a suggestion, but then overwrites the password. This
// test checks that the overwritten password is not reverted back.
TEST_F(PasswordAutofillAgentTest,
NoopEditingDoesNotOverwriteManuallyEditedPassword) {
fill_data_.wait_for_username = true;
SimulateUsernameTyping(kAliceUsername);
SimulateOnFillPasswordForm(fill_data_);
SimulateSuggestionChoice(username_element_);
const std::string old_username(username_element_.Value().Utf8());
const std::string old_password(password_element_.Value().Utf8());
const std::string new_password(old_password + "modify");
// The user changes the password.
SimulatePasswordTyping(new_password);
// Change focus in between to make sure blur events don't trigger filling.
SetFocused(password_element_);
SetFocused(username_element_);
// The password should have stayed as the user changed it.
// The username should not be autofilled, because it was typed by the user.
CheckTextFieldsDOMState(old_username, false, new_password, false);
// The password should not have a suggested value.
CheckUsernameDOMStatePasswordSuggestedState(old_username, false,
std::string(), false);
}
// The user types the username, then accepts a suggestion. This test checks
// that autofilling does not rewrite the username, if the value is already
// there.
TEST_F(PasswordAutofillAgentTest, AcceptingSuggestionDoesntRewriteUsername) {
fill_data_.wait_for_username = true;
SimulateUsernameTyping(kAliceUsername);
SimulateOnFillPasswordForm(fill_data_);
SimulateSuggestionChoice(username_element_);
const std::string username(username_element_.Value().Utf8());
const std::string password(password_element_.Value().Utf8());
// The password was autofilled. The username was not.
CheckTextFieldsDOMState(username, false, password, true);
}
// The user types in a username and a password, but then just before sending
// the form off, a script changes them. This test checks that
// PasswordAutofillAgent can still remember the username and the password
// typed by the user.
TEST_F(PasswordAutofillAgentTest,
RememberLastTypedUsernameAndPasswordOnSubmit_ScriptChanged) {
SimulateUsernameTyping("temp");
SimulatePasswordTyping("random");
// Simulate that the username and the password value was changed by the
// site's JavaScript before submit.
username_element_.SetValue(WebString("new username"));
password_element_.SetValue(WebString("new password"));
SaveAndSubmitForm();
// Observe that the PasswordAutofillAgent still remembered the last typed
// username and password and sent that to the browser.
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), u"temp", u"random");
}
TEST_F(PasswordAutofillAgentTest, RememberFieldPropertiesOnSubmit) {
FocusElement("random_field");
SimulateUsernameTyping("typed_username");
SimulatePasswordTyping("typed_password");
// Simulate that the username and the password value was changed by the
// site's JavaScript before submit.
username_element_.SetValue(WebString("new username"));
password_element_.SetValue(WebString("new password"));
SaveAndSubmitForm();
std::map<std::u16string, FieldPropertiesMask> expected_properties_masks;
expected_properties_masks[u"random_field"] = FieldPropertiesFlags::kHadFocus;
expected_properties_masks[u"username"] =
FieldPropertiesFlags::kUserTyped | FieldPropertiesFlags::kHadFocus;
expected_properties_masks[u"password"] =
FieldPropertiesFlags::kUserTyped | FieldPropertiesFlags::kHadFocus;
ExpectFieldPropertiesMasks(PasswordFormSubmitted, expected_properties_masks,
SubmissionIndicatorEvent::HTML_FORM_SUBMISSION);
}
TEST_F(PasswordAutofillAgentTest, FixEmptyFieldPropertiesOnSubmit) {
SimulateOnFillPasswordForm(fill_data_);
// Simulate a user click so that the password field's real value is filled.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
// Simulate replacing the username and password field.
static constexpr char kJavaScript[] =
"const old_username = document.getElementById('username');"
"const old_password = document.getElementById('password');"
"const new_username = document.createElement('input');"
"new_username.value = old_username.value;"
"new_username.id = 'new_username';"
"const new_password = document.createElement('input');"
"new_password.value = old_password.value;"
"new_password.id = 'new_password';"
"const form = document.getElementById('LoginTestForm');"
"form.appendChild(new_username);"
"form.appendChild(new_password);"
"form.removeChild(old_username);"
"form.removeChild(old_password);";
ExecuteJavaScriptForTests(kJavaScript);
auto form_element = GetMainFrame()
->GetDocument()
.GetElementById(WebString::FromUTF8("LoginTestForm"))
.To<WebFormElement>();
SaveAndSubmitForm(form_element);
std::map<std::u16string, FieldPropertiesMask> expected_properties_masks;
expected_properties_masks[u"new_username"] =
FieldPropertiesFlags::kAutofilledOnPageLoad;
expected_properties_masks[u"new_password"] =
FieldPropertiesFlags::kAutofilledOnPageLoad;
ExpectFieldPropertiesMasks(PasswordFormSubmitted, expected_properties_masks,
SubmissionIndicatorEvent::HTML_FORM_SUBMISSION);
}
TEST_F(PasswordAutofillAgentTest,
RememberFieldPropertiesOnSameDocumentNavigation) {
LoadHTML(kNoFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
std::string hide_elements =
"var password = document.getElementById('password');"
"password.style = 'display:none';"
"var username = document.getElementById('username');"
"username.style = 'display:none';";
ExecuteJavaScriptForTests(hide_elements.c_str());
FireAjaxSucceeded();
std::map<std::u16string, FieldPropertiesMask> expected_properties_masks;
expected_properties_masks[u"username"] =
FieldPropertiesFlags::kUserTyped | FieldPropertiesFlags::kHadFocus;
expected_properties_masks[u"password"] =
FieldPropertiesFlags::kUserTyped | FieldPropertiesFlags::kHadFocus;
ExpectFieldPropertiesMasks(PasswordFormSameDocumentNavigation,
expected_properties_masks,
SubmissionIndicatorEvent::XHR_SUCCEEDED);
}
TEST_F(PasswordAutofillAgentTest,
RememberFieldPropertiesOnSameDocumentNavigation_2) {
LoadHTML(kNoFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
FireAjaxSucceeded();
std::string hide_elements =
"var password = document.getElementById('password');"
"password.style = 'display:none';"
"var username = document.getElementById('username');"
"username.style = 'display:none';";
ExecuteJavaScriptForTests(hide_elements.c_str());
ForceLayoutUpdate();
base::RunLoop().RunUntilIdle();
std::map<std::u16string, FieldPropertiesMask> expected_properties_masks;
expected_properties_masks[u"username"] =
FieldPropertiesFlags::kUserTyped | FieldPropertiesFlags::kHadFocus;
expected_properties_masks[u"password"] =
FieldPropertiesFlags::kUserTyped | FieldPropertiesFlags::kHadFocus;
ExpectFieldPropertiesMasks(PasswordFormSameDocumentNavigation,
expected_properties_masks,
SubmissionIndicatorEvent::XHR_SUCCEEDED);
}
// The username/password is autofilled by password manager then just before
// sending the form off, a script changes them. This test checks that
// PasswordAutofillAgent can still get the username and the password autofilled.
TEST_F(PasswordAutofillAgentTest,
RememberLastAutofilledUsernameAndPasswordOnSubmit_ScriptChanged) {
SimulateOnFillPasswordForm(fill_data_);
// Simulate that the username and the password value was changed by the
// site's JavaScript before submit.
username_element_.SetValue(WebString("new username"));
password_element_.SetValue(WebString("new password"));
SaveAndSubmitForm();
// Observe that the PasswordAutofillAgent still remembered the autofilled
// username and password and sent that to the browser.
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), kAliceUsername16,
kAlicePassword16);
}
// The username/password is autofilled by password manager then user types in a
// username and a password. Then just before sending the form off, a script
// changes them. This test checks that PasswordAutofillAgent can still remember
// the username and the password typed by the user.
TEST_F(
PasswordAutofillAgentTest,
RememberLastTypedAfterAutofilledUsernameAndPasswordOnSubmit_ScriptChanged) {
SimulateOnFillPasswordForm(fill_data_);
SimulateUsernameTyping("temp");
SimulatePasswordTyping("random");
// Simulate that the username and the password value was changed by the
// site's JavaScript before submit.
username_element_.SetValue(WebString("new username"));
password_element_.SetValue(WebString("new password"));
SaveAndSubmitForm();
// Observe that the PasswordAutofillAgent still remembered the last typed
// username and password and sent that to the browser.
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), u"temp", u"random");
}
// The user starts typing username then it is autofilled.
// PasswordAutofillAgent should remember the username that was autofilled,
// not last typed.
TEST_F(PasswordAutofillAgentTest, RememberAutofilledUsername) {
SimulateUsernameTyping("Te");
// Simulate that the username was changed by autofilling.
username_element_.SetValue(WebString("temp"));
SimulatePasswordTyping("random");
SaveAndSubmitForm();
// Observe that the PasswordAutofillAgent still remembered the last typed
// username and password and sent that to the browser.
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), u"temp", u"random");
}
// The user starts typing username then javascript suggests to select another
// username that was generated based on typed field value (e.g. surname field).
// PasswordAutofillAgent should remember the username that was selected,
// not last typed.
TEST_F(PasswordAutofillAgentTest,
RememberUsernameGeneratedBasingOnTypedFields) {
SimulateUsernameTyping("Temp");
SimulatePasswordTyping("random");
// Suppose that "random_field" contains surname.
WebInputElement surname_element = GetInputElementByID("random_field");
SimulateUserInputChangeForElement(surname_element, "Smith");
// Simulate that the user selected username that was generated by script.
username_element_.SetValue(WebString("foo.smith"));
SaveAndSubmitForm();
// Observe that the PasswordAutofillAgent still remembered the last typed
// username and password and sent that to the browser.
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), u"foo.smith", u"random");
}
// If credentials contain username+password but the form contains only a
// password field, we don't autofill on page load.
TEST_F(PasswordAutofillAgentTest, DontFillFormWithNoUsername) {
// Load a form with no username and update test data.
LoadHTML(kVisibleFormWithNoUsernameHTML);
UpdateOnlyPasswordElement();
SimulateOnFillPasswordForm(fill_data_);
// As the credential contains a username, but the form does not, the
// credential is not filled.
CheckFirstFillingResult(FillingResult::kFoundNoPasswordForUsername);
}
// Tests the standard behavior of the filling a suggestions by passing the IDs
// of the elements to be filled along with the values to fill.
TEST_F(PasswordAutofillAgentTest, FillPasswordSuggestionById) {
ASSERT_TRUE(SimulateElementClick(kUsernameName));
password_autofill_agent_->PreviewPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_),
form_util::GetFieldRendererId(password_element_), kAliceUsername16,
kAlicePassword16);
EXPECT_EQ(username_element_.SuggestedValue().Utf16(), kAliceUsername16);
EXPECT_TRUE(username_element_.IsPreviewed());
EXPECT_EQ(password_element_.SuggestedValue().Utf16(), kAlicePassword16);
EXPECT_TRUE(password_element_.IsPreviewed());
password_autofill_agent_->FillPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_),
form_util::GetFieldRendererId(password_element_), kAliceUsername16,
kAlicePassword16, AutofillSuggestionTriggerSource::kUnspecified);
EXPECT_EQ(username_element_.SelectionStart(), 5u);
EXPECT_EQ(username_element_.SelectionEnd(), 5u);
EXPECT_EQ(username_element_.Value().Utf16(), kAliceUsername16);
EXPECT_TRUE(username_element_.IsAutofilled());
EXPECT_EQ(password_element_.Value().Utf16(), kAlicePassword16);
EXPECT_TRUE(password_element_.IsAutofilled());
}
// Tests the behavior of FillPasswordSuggestionById when the elements to be
// filled are read-only.
TEST_F(PasswordAutofillAgentTest, FillPasswordSuggestionById_ReadOnlyElements) {
ASSERT_TRUE(SimulateElementClick(kUsernameName));
SetElementReadOnly(username_element_, true);
SetElementReadOnly(password_element_, true);
password_autofill_agent_->PreviewPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_),
form_util::GetFieldRendererId(password_element_), kAliceUsername16,
kAlicePassword16);
EXPECT_EQ(username_element_.SuggestedValue().Utf16(), u"");
EXPECT_FALSE(username_element_.IsPreviewed());
EXPECT_EQ(password_element_.SuggestedValue().Utf16(), u"");
EXPECT_FALSE(password_element_.IsPreviewed());
password_autofill_agent_->FillPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_),
form_util::GetFieldRendererId(password_element_), kAliceUsername16,
kAlicePassword16, AutofillSuggestionTriggerSource::kUnspecified);
EXPECT_EQ(username_element_.Value().Utf16(), u"");
EXPECT_FALSE(username_element_.IsAutofilled());
EXPECT_EQ(password_element_.Value().Utf16(), u"");
EXPECT_FALSE(password_element_.IsAutofilled());
}
// Tests the behavior of FillPasswordSuggestionById when no username value is
// present in the passed credentials.
TEST_F(PasswordAutofillAgentTest, FillPasswordSuggestionById_NoUsernameValue) {
username_element_.SetValue(WebString(kBobUsername16));
ASSERT_TRUE(SimulateElementClick(kPasswordName));
password_autofill_agent_->PreviewPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_),
form_util::GetFieldRendererId(password_element_), u"", kAlicePassword16);
EXPECT_EQ(username_element_.SuggestedValue().Utf16(), u"");
EXPECT_FALSE(username_element_.IsPreviewed());
EXPECT_EQ(password_element_.SuggestedValue().Utf16(), kAlicePassword16);
EXPECT_TRUE(password_element_.IsPreviewed());
password_autofill_agent_->FillPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_),
form_util::GetFieldRendererId(password_element_), u"", kAlicePassword16,
AutofillSuggestionTriggerSource::kUnspecified);
EXPECT_EQ(username_element_.Value().Utf16(), kBobUsername16);
EXPECT_FALSE(username_element_.IsAutofilled());
EXPECT_EQ(password_element_.Value().Utf16(), kAlicePassword16);
EXPECT_TRUE(password_element_.IsAutofilled());
}
// Tests the behavior of FillPasswordSuggestionById when the form contains no
// username element.
TEST_F(PasswordAutofillAgentTest, FillPasswordSuggestionById_NoUsername) {
LoadHTML(kVisibleFormWithNoUsernameHTML);
password_element_ = GetInputElementByID(kPasswordName);
ASSERT_TRUE(SimulateElementClick(kPasswordName));
password_autofill_agent_->PreviewPasswordSuggestionById(
FieldRendererId(), form_util::GetFieldRendererId(password_element_),
kAliceUsername16, kAlicePassword16);
EXPECT_EQ(password_element_.SuggestedValue().Utf16(), kAlicePassword16);
EXPECT_TRUE(password_element_.Value().IsEmpty());
EXPECT_TRUE(password_element_.IsPreviewed());
password_autofill_agent_->FillPasswordSuggestionById(
FieldRendererId(), form_util::GetFieldRendererId(password_element_),
kAliceUsername16, kAlicePassword16,
AutofillSuggestionTriggerSource::kUnspecified);
EXPECT_TRUE(password_element_.SuggestedValue().IsEmpty());
EXPECT_EQ(password_element_.Value().Utf16(), kAlicePassword16);
EXPECT_TRUE(password_element_.IsAutofilled());
}
// Tests the behavior of FillPasswordSuggestionById when the form contains no
// password element.
TEST_F(PasswordAutofillAgentTest, FillPasswordSuggestionById_NoPassword) {
LoadHTML(kSingleUsernameFormHTML);
username_element_ = GetInputElementByID(kUsernameName);
ASSERT_TRUE(SimulateElementClick(kUsernameName));
password_autofill_agent_->PreviewPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_), FieldRendererId(),
kAliceUsername16, kAlicePassword16);
EXPECT_EQ(username_element_.SuggestedValue().Utf16(), kAliceUsername16);
EXPECT_TRUE(username_element_.Value().IsEmpty());
EXPECT_TRUE(username_element_.IsPreviewed());
password_autofill_agent_->FillPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_), FieldRendererId(),
kAliceUsername16, kAlicePassword16,
AutofillSuggestionTriggerSource::kUnspecified);
EXPECT_TRUE(username_element_.SuggestedValue().IsEmpty());
EXPECT_EQ(username_element_.Value().Utf16(), kAliceUsername16);
EXPECT_TRUE(username_element_.IsAutofilled());
}
// Tests the behavior of FillPasswordSuggestionById when neither of the passed
// elements are focused.
TEST_F(PasswordAutofillAgentTest, FillPasswordSuggestionById_NoFocusedElement) {
ASSERT_TRUE(SimulateElementClick("random_field"));
password_autofill_agent_->PreviewPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_),
form_util::GetFieldRendererId(password_element_), kAliceUsername16,
kAlicePassword16);
EXPECT_EQ(username_element_.SuggestedValue().Utf16(), kAliceUsername16);
EXPECT_TRUE(username_element_.IsPreviewed());
EXPECT_EQ(password_element_.SuggestedValue().Utf16(), kAlicePassword16);
EXPECT_TRUE(password_element_.IsPreviewed());
password_autofill_agent_->FillPasswordSuggestionById(
form_util::GetFieldRendererId(username_element_),
form_util::GetFieldRendererId(password_element_), kAliceUsername16,
kAlicePassword16, AutofillSuggestionTriggerSource::kUnspecified);
EXPECT_EQ(username_element_.Value().Utf16(), kAliceUsername16);
EXPECT_TRUE(username_element_.IsAutofilled());
EXPECT_EQ(password_element_.Value().Utf16(), kAlicePassword16);
EXPECT_TRUE(password_element_.IsAutofilled());
}
TEST_F(PasswordAutofillAgentTest, ShowPopupOnEmptyPasswordField) {
// Load a form with no username and update test data.
LoadHTML(kVisibleFormWithNoUsernameHTML);
UpdateUrlForHTML(kVisibleFormWithNoUsernameHTML);
UpdateOnlyPasswordElement();
fill_data_.preferred_login.username_value.clear();
fill_data_.additional_logins.clear();
password_element_.SetValue("");
password_element_.SetAutofillState(WebAutofillState::kNotFilled);
// Simulate the browser sending back the login info for an initial page load.
SimulateOnFillPasswordForm(fill_data_);
// Show popup suggestion when the password field is empty.
password_element_.SetValue("");
password_element_.SetAutofillState(WebAutofillState::kNotFilled);
SimulateSuggestionChoiceOfUsernameAndPassword(
password_element_, std::u16string(), kAlicePassword16);
CheckSuggestions(std::u16string(), true);
EXPECT_EQ(kAlicePassword16, password_element_.Value().Utf16());
EXPECT_TRUE(password_element_.IsAutofilled());
}
TEST_F(PasswordAutofillAgentTest, ShowPopupOnAutofilledPasswordField) {
// Load a form with no username and update test data.
LoadHTML(kVisibleFormWithNoUsernameHTML);
UpdateUrlForHTML(kVisibleFormWithNoUsernameHTML);
UpdateOnlyPasswordElement();
fill_data_.preferred_login.username_value.clear();
fill_data_.additional_logins.clear();
password_element_.SetValue("");
password_element_.SetAutofillState(WebAutofillState::kNotFilled);
// Simulate the browser sending back the login info for an initial page load.
SimulateOnFillPasswordForm(fill_data_);
// Show popup suggestion when the password field is autofilled.
password_element_.SetValue("123");
password_element_.SetAutofillState(WebAutofillState::kAutofilled);
SimulateSuggestionChoiceOfUsernameAndPassword(
password_element_, std::u16string(), kAlicePassword16);
CheckSuggestions(std::u16string(), true);
EXPECT_EQ(kAlicePassword16, password_element_.Value().Utf16());
EXPECT_TRUE(password_element_.IsAutofilled());
}
TEST_F(PasswordAutofillAgentTest, NotShowPopupPasswordField) {
// Load a form with no username and update test data.
LoadHTML(kVisibleFormWithNoUsernameHTML);
UpdateUrlForHTML(kVisibleFormWithNoUsernameHTML);
UpdateOnlyPasswordElement();
fill_data_.preferred_login.username_value.clear();
fill_data_.additional_logins.clear();
password_element_.SetValue("");
password_element_.SetAutofillState(WebAutofillState::kNotFilled);
// Simulate the browser sending back the login info for an initial page load.
SimulateOnFillPasswordForm(fill_data_);
// Do not show popup suggestion when the password field is not-empty and not
// autofilled.
password_element_.SetValue("123");
password_element_.SetAutofillState(WebAutofillState::kNotFilled);
SimulateSuggestionChoiceOfUsernameAndPassword(
password_element_, std::u16string(), kAlicePassword16);
CheckSuggestionsNotShown();
}
// Tests with fill-on-account-select enabled that if the username element is
// read-only and filled with an unknown username, then the password field is not
// highlighted as autofillable (regression test for https://crbug.com/442564).
TEST_F(PasswordAutofillAgentTest,
FillOnAccountSelectOnlyReadonlyUnknownUsername) {
ClearUsernameAndPasswordFieldValues();
username_element_.SetValue("foobar");
SetElementReadOnly(username_element_, true);
CheckUsernameDOMStatePasswordSuggestedState(std::string("foobar"), false,
std::string(), false);
}
// The user types in a username and a password. Then JavaScript changes password
// field to readonly state before submit. PasswordAutofillAgent can correctly
// process readonly password field. This test models behaviour of gmail.com.
TEST_F(PasswordAutofillAgentTest, ReadonlyPasswordFieldOnSubmit) {
SimulateUsernameTyping("temp");
SimulatePasswordTyping("random");
// Simulate that JavaScript makes password field readonly.
SetElementReadOnly(password_element_, true);
SubmitForm();
// Observe that the PasswordAutofillAgent can correctly process submitted
// form.
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), u"temp", u"random");
}
// Verify that typed passwords are saved correctly when autofill and generation
// both trigger. Regression test for https://crbug.com/493455
TEST_F(PasswordAutofillAgentTest, PasswordGenerationTriggered_TypedPassword) {
SimulateOnFillPasswordForm(fill_data_);
SetFoundFormEligibleForGeneration(
password_generation_, GetMainFrame()->GetDocument(),
/*new_password_id=*/"password", /*confirm_password_id=*/nullptr);
// Generation event is triggered due to focus events.
#if !BUILDFLAG(IS_ANDROID)
EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus())
.Times(testing::AnyNumber());
#endif // !BUILDFLAG(IS_ANDROID)
SimulateUsernameTyping("NewGuy");
SimulatePasswordTyping("NewPassword");
SaveAndSubmitForm();
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), u"NewGuy", u"NewPassword");
}
// Verify that generated passwords are saved correctly when autofill and
// generation both trigger. Regression test for https://crbug.com/493455.
TEST_F(PasswordAutofillAgentTest,
PasswordGenerationTriggered_GeneratedPassword) {
SimulateOnFillPasswordForm(fill_data_);
SetFoundFormEligibleForGeneration(
password_generation_, GetMainFrame()->GetDocument(),
/*new_password_id=*/"password", /*confirm_password_id=*/nullptr);
// Simulate the user clicks on a password field, that leads to showing
// generation pop-up. GeneratedPasswordAccepted can't be called without it.
ASSERT_TRUE(SimulateElementClick(kPasswordName));
std::u16string password = u"NewPass22";
EXPECT_CALL(fake_pw_client_, PresaveGeneratedPassword(_, Eq(password)));
password_generation_->GeneratedPasswordAccepted(password);
SaveAndSubmitForm();
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), kAliceUsername16, u"NewPass22");
}
// TODO(crbug.com/40100455): Figure out whether this test is simulating a
// realistic sequence of events.
TEST_F(PasswordAutofillAgentTest,
ResetPasswordGenerationWhenFieldIsAutofilled) {
// A user generates password.
SetFoundFormEligibleForGeneration(
password_generation_, GetMainFrame()->GetDocument(),
/*new_password_id=*/"password", /*confirm_password_id=*/nullptr);
// Simulate the user clicks on a password field, that leads to showing
// generation pop-up. GeneratedPasswordAccepted can't be called without it.
ASSERT_TRUE(SimulateElementClick(kPasswordName));
std::u16string password = u"NewPass22";
EXPECT_CALL(fake_pw_client_, PresaveGeneratedPassword(_, Eq(password)));
password_generation_->GeneratedPasswordAccepted(password);
// The form should not be autofilled on the next call of FillPasswordForm
EXPECT_CALL(fake_pw_client_, PasswordNoLongerGenerated);
SimulateOnFillPasswordForm(fill_data_);
base::RunLoop().RunUntilIdle();
// The password field shouldn't reveal the value on focusing.
WebDocument document = GetMainFrame()->GetDocument();
WebElement element = document.GetElementById(WebString::FromUTF8("password"));
ASSERT_TRUE(element);
WebInputElement password_element = element.To<WebInputElement>();
EXPECT_FALSE(password_element.ShouldRevealPassword());
EXPECT_FALSE(password_element.IsAutofilled());
SaveAndSubmitForm();
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), kAliceUsername16, u"NewPass22");
// Then user selects another account on Fill On Account Select
SimulateSuggestionChoiceOfUsernameAndPassword(username_element_,
kBobUsername16, kBobPassword16);
base::RunLoop().RunUntilIdle();
// The password field still shouldn't reveal the value on focusing.
EXPECT_FALSE(password_element.ShouldRevealPassword());
EXPECT_TRUE(password_element.IsAutofilled());
test_api(*autofill_agent_).OnFormNoLongerSubmittable();
SaveAndSubmitForm();
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), kBobUsername16, kBobPassword16);
}
// If password generation is enabled for a field, password autofill should not
// show UI.
TEST_F(PasswordAutofillAgentTest, PasswordGenerationSupersedesAutofill) {
LoadHTML(kSignupFormHTML);
// Update password_element_;
WebDocument document = GetMainFrame()->GetDocument();
WebElement element =
document.GetElementById(WebString::FromUTF8("new_password"));
ASSERT_TRUE(element);
password_element_ = element.To<WebInputElement>();
// Update fill_data_ for the new form and simulate filling. Pretend as if
// the password manager didn't detect a username field so it will try to
// show UI when the password field is focused.
fill_data_.wait_for_username = true;
fill_data_.preferred_login.username_value.clear();
fill_data_.username_element_renderer_id = FieldRendererId();
UpdateUrlForHTML(kSignupFormHTML);
SimulateOnFillPasswordForm(fill_data_);
// Simulate generation triggering.
SetFoundFormEligibleForGeneration(password_generation_,
GetMainFrame()->GetDocument(),
/*new_password_id=*/"new_password",
/*confirm_password_id=*/"confirm_password");
// Simulate the field being clicked to start typing. This should trigger
// generation but not password autofill.
ASSERT_TRUE(SimulateElementClick("new_password"));
// TODO(crbug.com/40279043): Expect the call precisely once.
EXPECT_CALL(fake_pw_client_, AutomaticGenerationAvailable)
.Times(NumShowSuggestionsCalls());
base::RunLoop().RunUntilIdle();
testing::Mock::VerifyAndClearExpectations(&fake_pw_client_);
CheckSuggestionsNotShown();
// On destruction the state is updated.
#if !BUILDFLAG(IS_ANDROID)
EXPECT_CALL(fake_pw_client_, GenerationElementLostFocus())
.Times(testing::AnyNumber());
#endif // !BUILDFLAG(IS_ANDROID)
}
// Tests the following scenario: 1) user triggers manual generation, 2) user
// erases the generated password from the field, 3) password suggestions should
// be displayed when available after the field is focused again.
// Regression test for crbug/1495325.
TEST_F(PasswordAutofillAgentTest, CanShowSuggestionsAfterManualGeneration) {
// Simulate receiving credentials for filling from the browser.
SimulateOnFillPasswordForm(fill_data_);
// Focus `password_element_` and verify that suggestions are shown to the
// user.
ASSERT_TRUE(SimulateElementClick(kPasswordName));
CheckSuggestions(/*typed_username=*/u"", true);
// Simulate manual generation triggering.
base::test::TestFuture<const std::optional<
::autofill::password_generation::PasswordGenerationUIData>&>
future_for_waiting;
password_generation_->TriggeredGeneratePassword(
future_for_waiting.GetCallback());
EXPECT_TRUE(future_for_waiting.Wait());
const std::u16string kPassword = u"NewPass24";
EXPECT_CALL(fake_pw_client_, PresaveGeneratedPassword(_, Eq(kPassword)));
password_generation_->GeneratedPasswordAccepted(kPassword);
ASSERT_EQ(password_element_.Value().Utf16(), kPassword);
// Clear the password field value.
password_element_.SetValue(WebString());
password_generation_->TextDidChangeInTextField(password_element_,
/*form_cache=*/{});
// Focus the password element again and verify that suggestions are shown to
// the user.
ASSERT_TRUE(SimulateElementClick(kPasswordName));
CheckSuggestions(/*typed_username=*/u"", true);
}
// Tests that a password change form is properly filled with the username and
// password.
TEST_F(PasswordAutofillAgentTest, FillSuggestionPasswordChangeForms) {
LoadHTML(kPasswordChangeFormHTML);
UpdateUrlForHTML(kPasswordChangeFormHTML);
UpdateUsernameAndPasswordElements();
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
for (const auto& selected_element : {username_element_, password_element_}) {
SimulateElementClick(selected_element);
// Neither field should be autocompleted.
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
ClearUsernameAndPasswordFieldValues();
}
}
// Tests that one user click on a username field is sufficient to bring up a
// credential suggestion popup on a change password form.
TEST_F(PasswordAutofillAgentTest,
SuggestionsOnUsernameFieldOfChangePasswordForm) {
LoadHTML(kPasswordChangeFormHTML);
UpdateUrlForHTML(kPasswordChangeFormHTML);
UpdateUsernameAndPasswordElements();
ClearUsernameAndPasswordFieldValues();
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Simulate a user clicking on the username element. This should produce a
// message.
SimulateElementClick(username_element_);
CheckSuggestions(u"", true);
}
// Tests that one user click on a password field is sufficient to bring up a
// credential suggestion popup on a change password form.
TEST_F(PasswordAutofillAgentTest,
SuggestionsOnPasswordFieldOfChangePasswordForm) {
LoadHTML(kPasswordChangeFormHTML);
UpdateUrlForHTML(kPasswordChangeFormHTML);
UpdateUsernameAndPasswordElements();
ClearUsernameAndPasswordFieldValues();
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Simulate a user clicking on the password element. This should produce a
// message.
SimulateElementClick(password_element_);
CheckSuggestions(u"", true);
}
// Tests that only the password field is autocompleted when the browser sends
// back data with only one credentials and empty username.
TEST_F(PasswordAutofillAgentTest, NotAutofillNoUsername) {
fill_data_.preferred_login.username_value.clear();
fill_data_.username_element_renderer_id = autofill::FieldRendererId();
fill_data_.additional_logins.clear();
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState("", false, kAlicePassword, true);
}
// Tests that the username field is not marked as autofilled when fill data has
// the empty username.
TEST_F(PasswordAutofillAgentTest,
AutofillNoUsernameWhenOtherCredentialsStored) {
fill_data_.preferred_login.username_value.clear();
ASSERT_FALSE(fill_data_.additional_logins.empty());
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState("", false, kAlicePassword, true);
}
TEST_F(PasswordAutofillAgentTest, NoForm_PromptForAJAXSubmitWithoutNavigation) {
LoadHTML(kNoFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
std::string hide_elements =
"var password = document.getElementById('password');"
"password.style = 'display:none';"
"var username = document.getElementById('username');"
"username.style = 'display:none';";
ExecuteJavaScriptForTests(hide_elements.c_str());
FireAjaxSucceeded();
ExpectDynamicFormSubmissionWithUsernameAndPasswords(
FormRendererId(), u"Bob", u"mypassword",
SubmissionIndicatorEvent::XHR_SUCCEEDED);
}
TEST_F(PasswordAutofillAgentTest,
NoForm_PromptForAJAXSubmitWithoutNavigation_2) {
LoadHTML(kNoFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
FireAjaxSucceeded();
std::string hide_elements =
"var password = document.getElementById('password');"
"password.style = 'display:none';"
"var username = document.getElementById('username');"
"username.style = 'display:none';";
ExecuteJavaScriptForTests(hide_elements.c_str());
ForceLayoutUpdate();
base::RunLoop().RunUntilIdle();
ExpectDynamicFormSubmissionWithUsernameAndPasswords(
FormRendererId(), u"Bob", u"mypassword",
SubmissionIndicatorEvent::XHR_SUCCEEDED);
}
// In this test, a <div> wrapping a form is hidden via display:none after an
// Ajax request. The test verifies that we offer to save the password, as hiding
// the <div> also hiding the <form>.
TEST_F(PasswordAutofillAgentTest, PromptForAJAXSubmitAfterHidingParentElement) {
LoadHTML(kDivWrappedFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
FireAjaxSucceeded();
std::string hide_element =
"var outerDiv = document.getElementById('outer');"
"outerDiv.style = 'display:none';";
ExecuteJavaScriptForTests(hide_element.c_str());
ForceLayoutUpdate();
base::RunLoop().RunUntilIdle();
ExpectDynamicFormSubmissionWithUsernameAndPasswords(
GetFormUniqueRendererId("form"), u"Bob", u"mypassword",
SubmissionIndicatorEvent::XHR_SUCCEEDED);
}
// In this test, a <div> wrapping a form is removed from the DOM after an Ajax
// request. The test verifies that we offer to save the password, as removing
// the <div> also removes the <form>.
TEST_F(PasswordAutofillAgentTest,
PromptForAJAXSubmitAfterDeletingParentElement) {
LoadHTML(kDivWrappedFormHTML);
UpdateUsernameAndPasswordElements();
FormRendererId renderer_id = GetFormUniqueRendererId("form");
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
FireAjaxSucceeded();
std::string delete_element =
"var outerDiv = document.getElementById('outer');"
"var innerDiv = document.getElementById('inner');"
"outerDiv.removeChild(innerDiv);";
ExecuteJavaScriptForTests(delete_element.c_str());
base::RunLoop().RunUntilIdle();
ExpectDynamicFormSubmissionWithUsernameAndPasswords(
renderer_id, u"Bob", u"mypassword",
SubmissionIndicatorEvent::XHR_SUCCEEDED);
}
TEST_F(PasswordAutofillAgentTest,
NoForm_NoPromptForAJAXSubmitWithoutNavigationAndElementsVisible) {
LoadHTML(kNoFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
FireAjaxSucceeded();
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(fake_driver_.called_password_form_submitted());
}
// Tests that no save prompt is shown when an unowned form is changed and AJAX
// completed but the form is still visible.
TEST_F(PasswordAutofillAgentTest,
NoForm_NoPromptForAJAXSubmitWithoutNavigationAndNewElementAppeared) {
const char kNoFormHTMLWithHiddenField[] =
"<INPUT type='text' id='username'/>"
"<INPUT type='password' id='password'/>"
"<INPUT type='text' id='captcha' style='display:none'/>";
LoadHTML(kNoFormHTMLWithHiddenField);
UpdateUsernameAndPasswordElements();
WebElement captcha_element = GetMainFrame()->GetDocument().GetElementById(
WebString::FromUTF8("captcha"));
ASSERT_TRUE(captcha_element);
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
// Simulate captcha element show up right before AJAX completed.
std::string show_captcha =
"var captcha = document.getElementById('captcha');"
"captcha.style = 'display:inline';";
ExecuteJavaScriptForTests(show_captcha.c_str());
FireAjaxSucceeded();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_dynamic_form_submission());
EXPECT_FALSE(fake_driver_.called_password_form_submitted());
}
TEST_F(PasswordAutofillAgentTest,
NoForm_NoPromptForAJAXSubmitWithoutNavigationAndNewElementAppeared_2) {
const char kNoFormHTMLWithHiddenField[] =
"<INPUT type='text' id='username'/>"
"<INPUT type='password' id='password'/>"
"<INPUT type='text' id='captcha' style='display:none'/>";
LoadHTML(kNoFormHTMLWithHiddenField);
UpdateUsernameAndPasswordElements();
WebElement captcha_element = GetMainFrame()->GetDocument().GetElementById(
WebString::FromUTF8("captcha"));
ASSERT_TRUE(captcha_element);
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
FireAjaxSucceeded();
// Simulate captcha element show up right after AJAX completed.
std::string show_captcha =
"var captcha = document.getElementById('captcha');"
"captcha.style = 'display:inline';";
ExecuteJavaScriptForTests(show_captcha.c_str());
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_dynamic_form_submission());
EXPECT_FALSE(fake_driver_.called_password_form_submitted());
}
// Tests that no save prompt is shown when a form with empty action URL is
// changed and AJAX completed but the form is still visible.
TEST_F(PasswordAutofillAgentTest,
NoAction_NoPromptForAJAXSubmitWithoutNavigationAndNewElementAppeared) {
// Form without an action URL.
const char kHTMLWithHiddenField[] =
"<FORM name='LoginTestForm'>"
" <INPUT type='text' id='username'/>"
" <INPUT type='password' id='password'/>"
" <INPUT type='text' id='captcha' style='display:none'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
// Set the valid URL so the form action URL can be generated properly.
LoadHTMLWithUrlOverride(kHTMLWithHiddenField, "https://www.example.com");
UpdateUsernameAndPasswordElements();
WebElement captcha_element = GetMainFrame()->GetDocument().GetElementById(
WebString::FromUTF8("captcha"));
ASSERT_TRUE(captcha_element);
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
// Simulate captcha element show up right before AJAX completed.
captcha_element.SetAttribute("style", "display:inline;");
FireAjaxSucceeded();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_dynamic_form_submission());
EXPECT_FALSE(fake_driver_.called_password_form_submitted());
}
TEST_F(PasswordAutofillAgentTest,
NoAction_NoPromptForAJAXSubmitWithoutNavigationAndNewElementAppeared_2) {
// Form without an action URL.
const char kHTMLWithHiddenField[] =
"<FORM name='LoginTestForm'>"
" <INPUT type='text' id='username'/>"
" <INPUT type='password' id='password'/>"
" <INPUT type='text' id='captcha' style='display:none'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
// Set the valid URL so the form action URL can be generated properly.
LoadHTMLWithUrlOverride(kHTMLWithHiddenField, "https://www.example.com");
UpdateUsernameAndPasswordElements();
WebElement captcha_element = GetMainFrame()->GetDocument().GetElementById(
WebString::FromUTF8("captcha"));
ASSERT_TRUE(captcha_element);
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
FireAjaxSucceeded();
// Simulate captcha element show up right after AJAX completed.
captcha_element.SetAttribute("style", "display:inline;");
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(fake_driver_.called_dynamic_form_submission());
EXPECT_FALSE(fake_driver_.called_password_form_submitted());
}
TEST_F(PasswordAutofillAgentTest, DriverIsInformedAboutUnfillableField) {
EXPECT_EQ(FocusedFieldType::kUnknown, fake_driver_.last_focused_field_type());
FocusElement(kPasswordName);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillablePasswordField,
fake_driver_.last_focused_field_type());
// Even though the focused element is a username field, it should be treated
// as unfillable, since it is read-only.
SetElementReadOnly(username_element_, true);
FocusElement(kUsernameName);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kUnfillableElement,
fake_driver_.last_focused_field_type());
}
TEST_F(PasswordAutofillAgentTest, DriverIsInformedAboutFillableFields) {
FocusElement("random_field");
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillableNonSearchField,
fake_driver_.last_focused_field_type());
// A username field without fill data is indistinguishable from any other text
// field.
FocusElement(kUsernameName);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillableNonSearchField,
fake_driver_.last_focused_field_type());
FocusElement(kPasswordName);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillablePasswordField,
fake_driver_.last_focused_field_type());
// A username field with fill data should be detected.
SimulateOnFillPasswordForm(fill_data_);
FocusElement(kUsernameName);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillableUsernameField,
fake_driver_.last_focused_field_type());
}
TEST_F(PasswordAutofillAgentTest, DriverIsInformedAboutFillableSearchField) {
LoadHTML(kSearchFieldHTML);
FocusElement(kSearchField);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillableSearchField,
fake_driver_.last_focused_field_type());
}
TEST_F(PasswordAutofillAgentTest,
DriverInformedAboutWebAuthnIfNotPasswordOrUsername) {
LoadHTML(kWebAutnFieldHTML);
UpdateUrlForHTML(kWebAutnFieldHTML);
UpdateUsernameAndPasswordElements();
// Classify webauthn-tagged fields as webauthn if they aren't anything else.
FocusElement(kUsernameName);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillableWebauthnTaggedField,
fake_driver_.last_focused_field_type());
// Don't classify password fields as webauthn. Fallbacks are the
// same anyway.
FocusElement(kPasswordName);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillablePasswordField,
fake_driver_.last_focused_field_type());
// Once username fields are detectable, prefer username
// classification.
SimulateOnFillPasswordForm(fill_data_);
FocusElement(kUsernameName);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillableUsernameField,
fake_driver_.last_focused_field_type());
}
TEST_F(PasswordAutofillAgentTest, DriverIsInformedAboutFillableTextArea) {
LoadHTML(kSocialNetworkPostFormHTML);
FocusElement(kSocialMediaTextArea);
fake_driver_.Flush();
EXPECT_EQ(FocusedFieldType::kFillableTextArea,
fake_driver_.last_focused_field_type());
}
// Tests that credential suggestions are autofilled on a password (and change
// password) forms having either ambiguous or empty name.
TEST_F(PasswordAutofillAgentTest,
SuggestionsOnFormContainingAmbiguousOrEmptyNames) {
const char kEmpty[] = "";
const char kFormContainsEmptyNamesHTML[] =
"<FORM name='WithoutNameIdForm' action='http://www.bidule.com' >"
" <INPUT type='text' placeholder='username'/>"
" <INPUT type='password' placeholder='Password'/>"
" <INPUT type='submit' />"
"</FORM>";
const char kFormContainsAmbiguousNamesHTML[] =
"<FORM name='AmbiguousNameIdForm' action='http://www.bidule.com' >"
" <INPUT type='text' id='credentials' placeholder='username' />"
" <INPUT type='password' id='credentials' placeholder='Password' />"
" <INPUT type='submit' />"
"</FORM>";
const char kChangePasswordFormContainsEmptyNamesHTML[] =
"<FORM name='ChangePwd' action='http://www.bidule.com' >"
" <INPUT type='text' placeholder='username' />"
" <INPUT type='password' placeholder='Old Password' "
" autocomplete='current-password' />"
" <INPUT type='password' placeholder='New Password' "
" autocomplete='new-password' />"
" <INPUT type='submit' />"
"</FORM>";
const char kChangePasswordFormButNoUsername[] =
"<FORM name='ChangePwdButNoUsername' action='http://www.bidule.com' >"
" <INPUT type='password' placeholder='Old Password' "
" autocomplete='current-password' />"
" <INPUT type='password' placeholder='New Password' "
" autocomplete='new-password' />"
" <INPUT type='submit' />"
"</FORM>";
const char kChangePasswordFormButNoOldPassword[] =
"<FORM name='ChangePwdButNoOldPwd' action='http://www.bidule.com' >"
" <INPUT type='text' placeholder='username' />"
" <INPUT type='password' placeholder='New Password' "
" autocomplete='new-password' />"
" <INPUT type='password' placeholder='Retype Password' "
" autocomplete='new-password' />"
" <INPUT type='submit' />"
"</FORM>";
const char kChangePasswordFormButNoAutocompleteAttribute[] =
"<FORM name='ChangePwdButNoAutocomplete' action='http://www.bidule.com'>"
" <INPUT type='text' placeholder='username' />"
" <INPUT type='password' placeholder='Old Password' />"
" <INPUT type='password' placeholder='New Password' />"
" <INPUT type='submit' />"
"</FORM>";
const struct {
const char* html_form;
bool does_trigger_autocomplete_on_fill;
bool has_fillable_username;
const char* expected_username_suggestions;
const char* expected_password_suggestions;
bool expected_is_username_autofillable;
bool expected_is_password_autofillable;
} test_cases[] = {
// Password form without name or id attributes specified for the input
// fields.
{kFormContainsEmptyNamesHTML, true, true, kAliceUsername, kAlicePassword,
true, true},
// Password form with ambiguous name or id attributes specified for the
// input fields.
{kFormContainsAmbiguousNamesHTML, true, true, kAliceUsername,
kAlicePassword, true, true},
// Change password form without name or id attributes specified for the
// input fields and `autocomplete='current-password'` attribute for old
// password field.
{kChangePasswordFormContainsEmptyNamesHTML, true, true, kAliceUsername,
kAlicePassword, true, true},
// Change password form without username field.
{kChangePasswordFormButNoUsername, true, false, kEmpty, kAlicePassword,
false, true},
// Change password form without name or id attributes specified for the
// input fields and `autocomplete='new-password'` attribute for new
// password fields. This form *do not* trigger `OnFillPasswordForm` from
// browser.
{kChangePasswordFormButNoOldPassword, false, true, kEmpty, kEmpty, false,
false},
// Change password form without name or id attributes specified for the
// input fields but `autocomplete='current-password'` or
// `autocomplete='new-password'` attributes are missing for old and new
// password fields respectively.
{kChangePasswordFormButNoAutocompleteAttribute, true, true,
kAliceUsername, kAlicePassword, true, true},
};
for (const auto& test_case : test_cases) {
SCOPED_TRACE(testing::Message() << "html_form: " << test_case.html_form);
// Load a password form.
LoadHTML(test_case.html_form);
UpdateUrlForHTML(test_case.html_form);
// Get the username and password form input elements.
blink::WebDocument document = GetMainFrame()->GetDocument();
std::vector<WebFormElement> forms = document.GetTopLevelForms();
WebFormElement form_element = forms[0];
std::vector<blink::WebFormControlElement> control_elements =
form_util::GetOwnedAutofillableFormControls(document, form_element);
if (test_case.has_fillable_username) {
username_element_ = control_elements[0].To<WebInputElement>();
password_element_ = control_elements[1].To<WebInputElement>();
} else {
username_element_.Reset();
password_element_ = control_elements[0].To<WebInputElement>();
}
if (test_case.does_trigger_autocomplete_on_fill) {
// Prepare `fill_data_` to trigger autocomplete.
UpdateRendererIDsInFillData();
fill_data_.additional_logins.clear();
ClearUsernameAndPasswordFieldValues();
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
if (test_case.has_fillable_username) {
SimulateSuggestionChoice(username_element_);
} else {
SimulateSuggestionChoice(password_element_);
}
// The username and password should now have been autocompleted.
CheckTextFieldsDOMState(test_case.expected_username_suggestions,
test_case.expected_is_username_autofillable,
test_case.expected_password_suggestions,
test_case.expected_is_password_autofillable);
}
}
}
// The password manager autofills credentials, the user chooses another
// credentials option from a suggestion dropdown and then the user submits a
// form. This test verifies that the browser process receives submitted
// username/password from the renderer process.
TEST_F(PasswordAutofillAgentTest, RememberChosenUsernamePassword) {
SimulateOnFillPasswordForm(fill_data_);
SimulateSuggestionChoiceOfUsernameAndPassword(username_element_,
kBobUsername16, kBobPassword16);
SaveAndSubmitForm();
// Observe that the PasswordAutofillAgent sends to the browser selected
// credentials.
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), kBobUsername16, kBobPassword16);
}
// Tests that we can correctly suggest to autofill two forms without username
// fields.
TEST_F(PasswordAutofillAgentTest, ShowSuggestionForNonUsernameFieldForms) {
LoadHTML(kTwoNoUsernameFormsHTML);
fill_data_.preferred_login.username_value.clear();
UpdateUrlForHTML(kTwoNoUsernameFormsHTML);
SimulateOnFillPasswordForm(fill_data_);
ASSERT_TRUE(SimulateElementClick("password1"));
CheckSuggestions(std::u16string(), true);
ASSERT_TRUE(SimulateElementClick("password2"));
CheckSuggestions(std::u16string(), true);
}
// Tests that password manager sees both autofill assisted and user entered
// data on saving that is triggered by AJAX succeeded.
TEST_F(PasswordAutofillAgentTest,
UsernameChangedAfterPasswordInput_AJAXSucceeded) {
for (auto change_source :
{FieldChangeSource::USER, FieldChangeSource::AUTOFILL_SINGLE_FIELD,
FieldChangeSource::USER_AUTOFILL_SINGLE_FIELD,
FieldChangeSource::AUTOFILL_FORM,
FieldChangeSource::USER_AUTOFILL_FORM}) {
LoadHTML(kNoFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
SimulateUsernameFieldChange(change_source);
// Hide form elements to simulate successful login.
std::string hide_elements =
"var password = document.getElementById('password');"
"password.style = 'display:none';"
"var username = document.getElementById('username');"
"username.style = 'display:none';";
ExecuteJavaScriptForTests(hide_elements.c_str());
FireAjaxSucceeded();
ExpectDynamicFormSubmissionWithUsernameAndPasswords(
FormRendererId(), u"Alice", u"mypassword",
SubmissionIndicatorEvent::XHR_SUCCEEDED);
}
}
TEST_F(PasswordAutofillAgentTest,
UsernameChangedAfterPasswordInput_AJAXSucceeded_2) {
LoadHTML(kNoFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
SimulateUsernameTyping("Alice");
FireAjaxSucceeded();
// Hide form elements to simulate successful login.
std::string hide_elements =
"var password = document.getElementById('password');"
"password.style = 'display:none';"
"var username = document.getElementById('username');"
"username.style = 'display:none';";
ExecuteJavaScriptForTests(hide_elements.c_str());
ForceLayoutUpdate();
base::RunLoop().RunUntilIdle();
ExpectDynamicFormSubmissionWithUsernameAndPasswords(
FormRendererId(), u"Alice", u"mypassword",
SubmissionIndicatorEvent::XHR_SUCCEEDED);
}
// Tests that password manager sees both autofill assisted and user entered
// data on saving that is triggered by form submission.
TEST_F(PasswordAutofillAgentTest,
UsernameChangedAfterPasswordInput_FormSubmitted) {
for (auto change_source :
{FieldChangeSource::USER, FieldChangeSource::AUTOFILL_SINGLE_FIELD,
FieldChangeSource::USER_AUTOFILL_SINGLE_FIELD,
FieldChangeSource::AUTOFILL_FORM,
FieldChangeSource::USER_AUTOFILL_FORM}) {
LoadHTML(kFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
SimulateUsernameFieldChange(change_source);
SaveAndSubmitForm();
ExpectFormSubmittedWithUsernameAndPasswords(
GetFormUniqueRendererId("LoginTestForm"), u"Alice", u"mypassword");
}
}
// Tests that a suggestion dropdown is shown on a password field even if a
// username field is present.
TEST_F(PasswordAutofillAgentTest, SuggestPasswordFieldSignInForm) {
SimulateClosingKeyboardReplacingSurfaceIfAndroid(kUsernameName);
// Simulate the browser sending back the login info.
SimulateOnFillPasswordForm(fill_data_);
// Call SimulateElementClick() to produce a user gesture on the page so
// autofill will actually fill.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions);
base::RunLoop().RunUntilIdle();
// Simulate a user clicking on the password element. This should produce a
// dropdown with suggestion of all available usernames.
SimulateElementClick(password_element_);
CheckSuggestions(u"", true);
}
// Tests that filling is suggested in a form with read-only username and that
// username field index is passed to the driver.
TEST_F(PasswordAutofillAgentTest, SuggestPasswordWhenUsernameFieldDisabled) {
SimulateClosingKeyboardReplacingSurfaceIfAndroid(kPasswordName);
// Simulate that the username was pre-filled by website and the username field
// is readonly.
username_element_.SetValue(WebString::FromUTF16(username1_));
SetElementReadOnly(username_element_, true);
// Simulate the browser sending back the login info.
SimulateOnFillPasswordForm(fill_data_);
PasswordSuggestionRequest suggestion_request;
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions)
.WillOnce(testing::SaveArg<0>(&suggestion_request));
base::RunLoop().RunUntilIdle();
// Simulate a user clicking on the password element. This should produce a
// dropdown with suggestion of all available usernames.
SimulateElementClick(password_element_);
fake_driver_.Flush();
const FormData& form = *fake_driver_.form_data_parsed()->begin();
uint64_t username_index = std::distance(
form.fields().begin(),
std::ranges::find(form.fields(),
form_util::GetFieldRendererId(username_element_),
&autofill::FormFieldData::renderer_id));
uint64_t password_index = std::distance(
form.fields().begin(),
std::ranges::find(form.fields(),
form_util::GetFieldRendererId(password_element_),
&autofill::FormFieldData::renderer_id));
EXPECT_EQ(suggestion_request.username_field_index, username_index);
EXPECT_EQ(suggestion_request.password_field_index, password_index);
}
// TODO(crbug.com/40819370): Amend the test to port it on Android if possible.
// Otherwise, remove the TODO and add the reason why it is excluded.
#if !BUILDFLAG(IS_ANDROID)
// Tests that a suggestion dropdown is shown on each password field. But when a
// user chose one of the fields to autofill, a suggestion dropdown will be shown
// only on this field.
TEST_F(PasswordAutofillAgentTest, SuggestMultiplePasswordFields) {
LoadHTML(kPasswordChangeFormHTML);
UpdateUrlForHTML(kPasswordChangeFormHTML);
UpdateUsernameAndPasswordElements();
// Simulate the browser sending back the login info.
SimulateOnFillPasswordForm(fill_data_);
// Call SimulateElementClick() to produce a user gesture on the page so
// autofill will actually fill.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions);
base::RunLoop().RunUntilIdle();
// Simulate a user clicking on the password elements. This should produce
// dropdowns with suggestion of all available usernames.
ASSERT_TRUE(SimulateElementClick("password"));
CheckSuggestions(u"", true);
ASSERT_TRUE(SimulateElementClick("newpassword"));
CheckSuggestions(u"", true);
ASSERT_TRUE(SimulateElementClick("confirmpassword"));
CheckSuggestions(u"", true);
// The user chooses to autofill the current password field.
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions)
.Times(NumShowSuggestionsCalls());
SimulateElementClick(password_element_);
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
base::RunLoop().RunUntilIdle();
// Simulate a user clicking on not autofilled password fields. This should
// produce no suggestion dropdowns.
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions).Times(0);
ASSERT_TRUE(SimulateElementClick("newpassword"));
ASSERT_TRUE(SimulateElementClick("confirmpassword"));
base::RunLoop().RunUntilIdle();
// But when the user clicks on the autofilled password field again it should
// still produce a suggestion dropdown.
ASSERT_TRUE(SimulateElementClick("password"));
CheckSuggestions(u"", true);
}
#endif // !BUILDFLAG(IS_ANDROID)
TEST_F(PasswordAutofillAgentTest, ShowAutofillSignaturesFlag) {
// Tests that form signature is set iff the flag is enabled.
const bool kFalseTrue[] = {false, true};
for (bool show_signatures : kFalseTrue) {
if (show_signatures)
EnableShowAutofillSignatures();
// An empty DOMSubtreeModified event listener is added for
// https://crbug.com/1219852.
std::string dom_with_dom_subtree_modified_listener =
base::StrCat({"<SCRIPT>"
"window.addEventListener('DOMSubtreeModified', () => {});"
"</SCRIPT>",
kFormHTML});
LoadHTML(dom_with_dom_subtree_modified_listener.c_str());
WebDocument document = GetMainFrame()->GetDocument();
WebFormElement form_element =
document.GetElementById(WebString::FromASCII("LoginTestForm"))
.To<WebFormElement>();
ASSERT_TRUE(form_element);
// Check only form signature attribute. The full test is in
// "PasswordGenerationAgentTestForHtmlAnnotation.*".
WebString form_signature_attribute = WebString::FromASCII("form_signature");
EXPECT_EQ(form_element.HasAttribute(form_signature_attribute),
show_signatures);
}
}
// Checks that a same-document navigation form submission could have an empty
// username.
TEST_F(PasswordAutofillAgentTest,
SameDocumentNavigationSubmissionUsernameIsEmpty) {
username_element_.SetValue(WebString());
SimulatePasswordTyping("random");
FormRendererId renderer_id = GetFormUniqueRendererId("LoginTestForm");
// Simulate that JavaScript removes the submitted form from DOM. That means
// that a submission was successful.
ExecuteJavaScriptForTests(kJavaScriptRemoveForm);
FireDidFinishSameDocumentNavigation();
ExpectDynamicFormSubmissionWithUsernameAndPasswords(
renderer_id, std::u16string(), u"random",
SubmissionIndicatorEvent::SAME_DOCUMENT_NAVIGATION);
}
#if BUILDFLAG(SAFE_BROWSING_DB_LOCAL)
// Verify CheckSafeBrowsingReputation() is called when user starts filling
// a password field, and that this function is only called once.
TEST_F(PasswordAutofillAgentTest,
CheckSafeBrowsingReputationWhenUserStartsFillingUsernamePassword) {
ASSERT_EQ(0, fake_driver_.called_check_safe_browsing_reputation_cnt());
// Simulate a click on password field to set its on focus,
// CheckSafeBrowsingReputation() should be called.
ASSERT_TRUE(SimulateElementClick(kPasswordName));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, fake_driver_.called_check_safe_browsing_reputation_cnt());
// Subsequent editing will not trigger CheckSafeBrowsingReputation.
SimulatePasswordTyping("modify");
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, fake_driver_.called_check_safe_browsing_reputation_cnt());
// No CheckSafeBrowsingReputation() call on username field click.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, fake_driver_.called_check_safe_browsing_reputation_cnt());
ASSERT_TRUE(SimulateElementClick(kPasswordName));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, fake_driver_.called_check_safe_browsing_reputation_cnt());
// Navigate to another page and click on password field,
// CheckSafeBrowsingReputation() should be triggered again.
LoadHTML(kFormHTML);
ASSERT_TRUE(SimulateElementClick(kPasswordName));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, fake_driver_.called_check_safe_browsing_reputation_cnt());
}
#endif
// Tests that username/password are autofilled when JavaScript is changing url
// between discovering a form and receiving credentials from the browser
// process.
TEST_F(PasswordAutofillAgentTest, AutocompleteWhenPageUrlIsChanged) {
// Simulate that JavaScript changes url.
fill_data_.url = GURL(fill_data_.url.possibly_invalid_spec() + "/path");
SimulateOnFillPasswordForm(fill_data_);
// The username and password should have been autocompleted.
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
}
// Regression test for https://crbug.com/728028.
TEST_F(PasswordAutofillAgentTest, NoForm_MultipleAJAXEventsWithoutSubmission) {
LoadHTML(kNoFormHTML);
UpdateUsernameAndPasswordElements();
SimulateUsernameTyping("Bob");
SimulatePasswordTyping("mypassword");
FireAjaxSucceeded();
base::RunLoop().RunUntilIdle();
// Repeatedly occurring AJAX events without removing the input elements
// shouldn't be treated as a password submission.
FireAjaxSucceeded();
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(fake_driver_.called_password_form_submitted());
ASSERT_FALSE(static_cast<bool>(fake_driver_.form_data_submitted()));
}
TEST_F(PasswordAutofillAgentTest, ManualFallbackForSaving) {
EXPECT_CALL(fake_pw_client_, PresaveGeneratedPassword).Times(0);
// The users enters a username. Inform the driver regardless.
SimulateUsernameTyping(kUsernameName);
EXPECT_EQ(1, fake_driver_.called_inform_about_user_input_count());
// The user enters a password.
SimulatePasswordTyping(kPasswordName);
// SimulateUsernameTyping/SimulatePasswordTyping calls
// PasswordAutofillAgent::UpdateStateForTextChange only once.
EXPECT_EQ(2, fake_driver_.called_inform_about_user_input_count());
// Remove one character from the password value.
SimulateUserTypingASCIICharacter(ui::VKEY_BACK, true);
EXPECT_EQ(3, fake_driver_.called_inform_about_user_input_count());
// Add one character to the username value.
SetFocused(username_element_);
SimulateUserTypingASCIICharacter('a', true);
EXPECT_EQ(4, fake_driver_.called_inform_about_user_input_count());
// Remove username value.
SimulateUsernameTyping("");
EXPECT_EQ(5, fake_driver_.called_inform_about_user_input_count());
// Change the password.
SetFocused(password_element_);
SimulateUserTypingASCIICharacter('a', true);
EXPECT_EQ(6, fake_driver_.called_inform_about_user_input_count());
// Remove password value. Inform the driver too.
SimulatePasswordTyping("");
EXPECT_EQ(7, fake_driver_.called_inform_about_user_input_count());
// The user enters new password.
SimulateUserTypingASCIICharacter('a', true);
EXPECT_EQ(8, fake_driver_.called_inform_about_user_input_count());
}
TEST_F(PasswordAutofillAgentTest, ManualFallbackForSaving_PasswordChangeForm) {
LoadHTML(kPasswordChangeFormHTML);
UpdateUrlForHTML(kPasswordChangeFormHTML);
UpdateUsernameAndPasswordElements();
// No password to save yet - still we should inform the driver.
SimulateUsernameTyping(kUsernameName);
EXPECT_EQ(1, fake_driver_.called_inform_about_user_input_count());
// The user enters in the current password field. The fallback should be
// available to save the entered value.
SimulatePasswordTyping(kPasswordName);
// SimulateUsernameTyping/SimulatePasswordTyping calls
// PasswordAutofillAgent::UpdateStateForTextChange only once.
EXPECT_EQ(2, fake_driver_.called_inform_about_user_input_count());
// The user types into the new password field. Inform the driver.
WebInputElement new_password = GetInputElementByID("newpassword");
ASSERT_TRUE(new_password);
SetFocused(new_password);
SimulateUserTypingASCIICharacter('a', true);
EXPECT_EQ(3, fake_driver_.called_inform_about_user_input_count());
// Edits of the confirmation password field trigger informing the driver.
WebInputElement confirmation_password =
GetInputElementByID("confirmpassword");
ASSERT_TRUE(confirmation_password);
SetFocused(confirmation_password);
SimulateUserTypingASCIICharacter('a', true);
EXPECT_EQ(4, fake_driver_.called_inform_about_user_input_count());
// Clear all password fields. The driver should be informed.
SimulatePasswordTyping("");
SimulateUserInputChangeForElement(new_password, "");
SimulateUserInputChangeForElement(confirmation_password, "");
EXPECT_EQ(5, fake_driver_.called_inform_about_user_input_count());
}
// Tests that information about Gaia reauthentication form is sent to the
// browser with information that the password should not be saved.
TEST_F(PasswordAutofillAgentTest, GaiaReauthenticationFormIgnored) {
// HTML is already loaded in test SetUp method, so information about password
// forms was already sent to the `fake_driver_`. Hence it should be reset.
fake_driver_.reset_password_forms_calls();
const char kGaiaReauthenticationFormHTML[] =
"<FORM id='ReauthenticationForm'>"
" <INPUT type='hidden' name='continue' "
"value='https://passwords.google.com/'>"
" <INPUT type='hidden' name='rart'>"
" <INPUT type='password' id='password'/>"
" <INPUT type='submit' value='Login'/>"
"</FORM>";
LoadHTMLWithUrlOverride(kGaiaReauthenticationFormHTML,
"https://accounts.google.com");
UpdateOnlyPasswordElement();
// Simulate a user clicking on the password element.
SimulateElementClick(password_element_);
fake_driver_.Flush();
// Check that information about Gaia reauthentication is sent to the browser.
ASSERT_TRUE(fake_driver_.called_password_forms_parsed());
const std::vector<autofill::FormData>& parsed_form_data =
fake_driver_.form_data_parsed().value();
ASSERT_EQ(1u, parsed_form_data.size());
EXPECT_TRUE(parsed_form_data[0].is_gaia_with_skip_save_password_form());
}
TEST_F(PasswordAutofillAgentTest,
UpdateSuggestionsIfNewerCredentialsAreSupplied) {
// Supply old fill data
password_autofill_agent_->ApplyFillDataOnParsingCompletion(fill_data_);
// The username and password should have been autocompleted.
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
// Change fill data
fill_data_.preferred_login.password_value = u"a-changed-password";
// Supply changed fill data
password_autofill_agent_->ApplyFillDataOnParsingCompletion(fill_data_);
CheckTextFieldsSuggestedState(kAliceUsername, true, "a-changed-password",
true);
}
TEST_F(PasswordAutofillAgentTest, SuggestLatestCredentials) {
password_autofill_agent_->ApplyFillDataOnParsingCompletion(fill_data_);
ASSERT_TRUE(SimulateElementClick(kPasswordName));
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions)
.Times(NumShowSuggestionsCalls());
base::RunLoop().RunUntilIdle();
// Change fill data
fill_data_.preferred_login.username_value = u"a-changed-username";
password_autofill_agent_->ApplyFillDataOnParsingCompletion(fill_data_);
ASSERT_TRUE(SimulateElementClick(kPasswordName));
// Empty value because nothing was typed into the field.
CheckSuggestions(u"", true);
}
// Tests that PSL matched password is not autofilled even when there is
// a prefilled username.
TEST_F(PasswordAutofillAgentTest, PSLMatchedPasswordIsNotAutofill) {
const char kFormWithPrefilledUsernameHTML[] =
"<FORM id='LoginTestForm' action='http://www.bidule.com'>"
" <INPUT type='text' id='username' value='prefilledusername'/>"
" <INPUT type='password' id='password'/>"
"</FORM>";
LoadHTML(kFormWithPrefilledUsernameHTML);
// Retrieve the input elements so the test can access them.
UpdateUsernameAndPasswordElements();
// Set the expected form origin and action URLs.
UpdateUrlForHTML(kFormWithPrefilledUsernameHTML);
// Add PSL matched credentials with username equal to prefilled one.
PasswordAndMetadata psl_credentials;
psl_credentials.password_value = u"pslpassword";
// Non-empty realm means PSL matched credentials.
psl_credentials.realm = "example.com";
psl_credentials.username_value = u"prefilledusername";
fill_data_.additional_logins.push_back(std::move(psl_credentials));
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
// Test that PSL matched password is not autofilled.
CheckUsernameDOMStatePasswordSuggestedState("prefilledusername", false, "",
false);
}
// Tests that the password form is filled as expected on load.
TEST_F(PasswordAutofillAgentTest, FillOnLoadWith) {
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
CheckFirstFillingResult(FillingResult::kSuccess);
}
TEST_F(PasswordAutofillAgentTest, FillOnLoadNoForm) {
LoadHTML(kNoFormHTML);
UpdateUsernameAndPasswordElements();
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
}
TEST_F(PasswordAutofillAgentTest, FillOnLoadNoUsername) {
LoadHTML(kTwoNoUsernameFormsHTML);
username_element_.Reset();
fill_data_.preferred_login.username_value.clear();
password_element_ = GetInputElementByID("password2");
UpdateRendererIDsInFillData();
SimulateOnFillPasswordForm(fill_data_);
EXPECT_EQ(kAlicePassword, password_element_.SuggestedValue().Utf8());
}
TEST_F(PasswordAutofillAgentTest, FormToFillIsPrefilled) {
username_element_.SetValue(WebString::FromUTF8("prefilled_placeholder"));
SimulateOnFillPasswordForm(fill_data_);
// Check that the prefilled value was not overwritten.
CheckTextFieldsDOMState(/*username=*/"prefilled_placeholder",
/*username_autofilled=*/false, /*password=*/"",
/*password_autofilled=*/false);
}
TEST_F(PasswordAutofillAgentTest, RestoresAfterJavaScriptModification) {
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
fake_driver_.reset_password_forms_calls();
static const char script[] = "document.getElementById('username').value = ''";
ExecuteJavaScriptForTests(script);
CheckTextFieldsSuggestedState("", false, kAlicePassword, true);
password_autofill_agent_->OnDynamicFormsSeen(/*form_cache=*/{});
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
EXPECT_FALSE(fake_driver_.called_password_forms_parsed());
EXPECT_FALSE(fake_driver_.called_password_forms_rendered());
}
TEST_F(PasswordAutofillAgentTest, DoNotRestoreWhenFormStructureWasChanged) {
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
static const char clear_username_script[] =
"document.getElementById('username').value = ''";
ExecuteJavaScriptForTests(clear_username_script);
static const char add_input_element_script[] =
"document.getElementById('LoginTestForm').appendChild(document."
"createElement('input'))";
ExecuteJavaScriptForTests(add_input_element_script);
CheckTextFieldsSuggestedState("", false, kAlicePassword, true);
password_autofill_agent_->OnDynamicFormsSeen(/*form_cache=*/{});
CheckTextFieldsSuggestedState("", false, kAlicePassword, true);
}
// Tests that a single username is filled and is exposed to JavaScript only
// after user gesture.
TEST_F(PasswordAutofillAgentTest, FillOnLoadSingleUsername) {
// Simulate filling single username by clearing password fill data.
fill_data_.preferred_login.password_value.clear();
fill_data_.password_element_renderer_id = autofill::FieldRendererId();
SimulateOnFillPasswordForm(fill_data_);
// The username should have been autofilled.
CheckTextFieldsSuggestedState(kAliceUsername, true, std::string(), false);
// However, it should have filled with the suggested value, it should not have
// filled with DOM accessible value.
CheckTextFieldsDOMState(std::string(), true, std::string(), false);
// Simulate a user click so that the username field's real value is filled.
ASSERT_TRUE(SimulateElementClick(kUsernameName));
CheckTextFieldsDOMState(kAliceUsername, true, std::string(), false);
}
// Tests that `PreviewSuggestion` properly previews the single username.
TEST_F(PasswordAutofillAgentTest, SingleUsernamePreviewSuggestion) {
fill_data_.preferred_login.password_value.clear();
fill_data_.password_element_renderer_id = autofill::FieldRendererId();
// Simulate the browser sending the login info, but set `wait_for_username` to
// prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Neither field should be autocompleted.
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
ASSERT_TRUE(SimulateElementClick(kUsernameName));
password_autofill_agent_->PreviewSuggestion(
username_element_, kAliceUsername16, kAlicePassword16);
CheckTextFieldsSuggestedState(kAliceUsername, true, std::string(), false);
// Try previewing with a username different from the one that was initially
// sent to the renderer.
password_autofill_agent_->PreviewSuggestion(username_element_, kBobUsername16,
kCarolPassword16);
CheckTextFieldsSuggestedState(kBobUsername, true, std::string(), false);
}
// Tests that `FillSuggestion` properly fills the single username.
TEST_F(PasswordAutofillAgentTest, SingleUsernameFillSuggestion) {
fill_data_.preferred_login.password_value.clear();
fill_data_.password_element_renderer_id = autofill::FieldRendererId();
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Neither field should be autocompleted.
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
// After filling with the suggestion, the username field should be filled.
SimulateElementClick(username_element_);
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
CheckTextFieldsDOMState(kAliceUsername, true, std::string(), false);
int username_length = strlen(kAliceUsername);
CheckUsernameSelection(username_length, username_length);
// Try Filling with a suggestion with a username different from the one that
// was initially sent to the renderer.
password_autofill_agent_->FillPasswordSuggestion(
kBobUsername16, kCarolPassword16, base::DoNothing());
CheckTextFieldsDOMState(kBobUsername, true, std::string(), false);
username_length = strlen(kBobUsername);
CheckUsernameSelection(username_length, username_length);
}
// Tests that `ClearPreview` properly clears previewed single username. The
// original selection range should stay untouched.
TEST_F(PasswordAutofillAgentTest, SingleUsernameClearPreview) {
fill_data_.preferred_login.password_value.clear();
fill_data_.password_element_renderer_id = autofill::FieldRendererId();
ResetFieldState(&username_element_, "ali", WebAutofillState::kPreviewed);
ASSERT_TRUE(SimulateElementClick(kUsernameName));
username_element_.SetSelectionRange(0, 0);
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsDOMState("ali", true, std::string(), false);
password_autofill_agent_->PreviewSuggestion(
username_element_, kAliceUsername16, kAlicePassword16);
password_autofill_agent_->ClearPreviewedForm();
EXPECT_TRUE(username_element_.SuggestedValue().IsEmpty());
CheckTextFieldsDOMState("ali", true, std::string(), false);
CheckUsernameSelection(0, 0);
}
// Fill on account select for credentials with empty usernames:
// Do not refill usernames if non-empty username is already selected.
TEST_F(PasswordAutofillAgentTest, NoUsernameCredential) {
const char kPasswordForEmptyUsernameCredential[] = "empty";
const char16_t kPasswordForEmptyUsernameCredential16[] = u"empty";
// Add a credential with an empty username.
PasswordAndMetadata empty_username_credential;
empty_username_credential.password_value =
kPasswordForEmptyUsernameCredential16;
empty_username_credential.username_value = u"";
fill_data_.additional_logins.push_back(std::move(empty_username_credential));
SimulateOnFillPasswordForm(fill_data_);
ClearUsernameAndPasswordFieldValues();
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions)
.Times(NumShowSuggestionsCalls());
SimulateSuggestionChoiceOfUsernameAndPassword(
password_element_, kAliceUsername16, kAlicePassword16);
CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
base::RunLoop().RunUntilIdle();
EXPECT_CALL(fake_driver_, ShowPasswordSuggestions)
.Times(NumShowSuggestionsCalls());
SimulateSuggestionChoiceOfUsernameAndPassword(
password_element_, u"", kPasswordForEmptyUsernameCredential16);
CheckTextFieldsDOMState(kAliceUsername, true,
kPasswordForEmptyUsernameCredential, true);
}
// Tests that any fields that have user input are not refilled on the next
// call of FillPasswordForm.
TEST_F(PasswordAutofillAgentTest, NoRefillOfUserInput) {
ClearUsernameAndPasswordFieldValues();
SimulateOnFillPasswordForm(fill_data_);
ASSERT_TRUE(SimulateElementClick(kPasswordName));
SimulatePasswordTyping("newpwd");
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsStateForElements(username_element_, kAliceUsername, true,
password_element_, "newpwd", false, false,
false);
}
// Tests that a JavaScript submission (e.g. via removing the form from a DOM)
// gets registered following a autofill after user trigger.
TEST_F(PasswordAutofillAgentTest, XhrSubmissionAfterFillingSuggestion) {
SimulateOnFillPasswordForm(fill_data_);
SimulateSuggestionChoiceOfUsernameAndPassword(username_element_,
kBobUsername16, kBobPassword16);
// Simulate that JavaScript removes the submitted form from DOM. That means
// that a submission was successful.
ExecuteJavaScriptForTests(kJavaScriptRemoveForm);
ExpectDynamicFormSubmissionWithUsernameAndPasswords(
fill_data_.form_renderer_id, kBobUsername16, kBobPassword16,
SubmissionIndicatorEvent::DOM_MUTATION_AFTER_AUTOFILL);
}
// Tests that a JavaScript submission (e.g. via removing the form from a DOM)
// does not get registered following a mere autofill on page load. This is
// necessary, because we potentially fill many forms on pageload, which the user
// likely won't interact with.
TEST_F(PasswordAutofillAgentTest, NoXhrSubmissionAfterFillingOnPageload) {
SimulateOnFillPasswordForm(fill_data_);
// Simulate that JavaScript removes the submitted form from DOM. That means
// that a submission was successful.
ExecuteJavaScriptForTests(kJavaScriptRemoveForm);
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(fake_driver_.called_dynamic_form_submission());
}
// Tests that user modifying the text field value results in notifying the
// browser.
TEST_F(PasswordAutofillAgentTest, ModifyNonPasswordField) {
LoadHTML(kSingleUsernameFormHTML);
UpdateOnlyUsernameElement();
EXPECT_CALL(fake_driver_,
UserModifiedNonPasswordField(
form_util::GetFieldRendererId(username_element_),
std::u16string(kAliceUsername16),
/*autocomplete_attribute_has_username=*/true,
/*is_likely_otp=*/false));
SimulateUsernameTyping(kAliceUsername);
}
// Tests that inputting 1 symbol value into a non-password field does not notify
// the browser.
TEST_F(PasswordAutofillAgentTest, ModifyNonPasswordFieldOneSymbol) {
LoadHTML(kSingleUsernameFormHTML);
UpdateOnlyUsernameElement();
EXPECT_CALL(fake_driver_, UserModifiedNonPasswordField).Times(0);
SimulateUsernameTyping("1");
}
// Tests that inputting 101 symbols into a non-password field does not notify
// the browser.
TEST_F(PasswordAutofillAgentTest, ModifyNonPasswordFieldTooManySymbols) {
LoadHTML(kSingleUsernameFormHTML);
UpdateOnlyUsernameElement();
EXPECT_CALL(fake_driver_, UserModifiedNonPasswordField).Times(0);
std::string not_username(101, 'a');
SimulateUsernameTyping(not_username);
}
// Tests that user modifying a text field with an OTP autocomplete attribute
// results in notifying the browser correspondingly.
TEST_F(PasswordAutofillAgentTest, ModifyNonPasswordFieldOTPAutocomplete) {
LoadHTML(kSingleUsernameFormHTML);
UpdateOnlyUsernameElement();
username_element_.SetAttribute(
"autocomplete",
password_manager::constants::kAutocompleteOneTimePassword);
EXPECT_CALL(fake_driver_,
UserModifiedNonPasswordField(
form_util::GetFieldRendererId(username_element_),
std::u16string(kAliceUsername16),
/*autocomplete_attribute_has_username=*/false,
/*is_likely_otp=*/true));
SimulateUsernameTyping(kAliceUsername);
}
// Tests that user modifying a text field with a name suggesting it's an OTP
// field results in notifying the browser correspondingly.
TEST_F(PasswordAutofillAgentTest, ModifyNonPasswordFieldOTPName) {
LoadHTML(kSingleUsernameFormHTML);
UpdateOnlyUsernameElement();
username_element_.SetAttribute("name", "test-one-time-pass");
EXPECT_CALL(fake_driver_,
UserModifiedNonPasswordField(
form_util::GetFieldRendererId(username_element_),
std::u16string(kAliceUsername16),
/*autocomplete_attribute_has_username=*/true,
/*is_likely_otp=*/true));
SimulateUsernameTyping(kAliceUsername);
}
// Tests that user modifying the text field value does not notify the browser if
// the field has name shorter than kMinInputNameLengthForSingleUsername symbols.
TEST_F(PasswordAutofillAgentTest, ModifyNonPasswordFieldShortName) {
LoadHTML(kSingleUsernameFormHTML);
UpdateOnlyUsernameElement();
username_element_.SetAttribute("name", "i");
username_element_.SetAttribute("id", "i");
ASSERT_TRUE(username_element_.NameForAutofill().length() == 1);
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/40820173): User typing doesn't send focus events properly.
FocusFirstInputElement();
#endif
EXPECT_CALL(fake_driver_, UserModifiedNonPasswordField).Times(0);
SimulateUserInputChangeForElement(username_element_, kAliceUsername);
}
// Tests that user modifying the text field value does not notify the browser if
// the field is labeled as a search field.
TEST_F(PasswordAutofillAgentTest, ModifySearchField) {
LoadHTML(kSingleUsernameFormHTML);
UpdateOnlyUsernameElement();
username_element_.SetAttribute("name", "thesearchfield");
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/40820173): User typing doesn't send focus events properly.
FocusFirstInputElement();
#endif
EXPECT_CALL(fake_driver_, UserModifiedNonPasswordField).Times(0);
SimulateUserInputChangeForElement(username_element_, kAliceUsername);
}
// Tests that filling presaved password manually by the user results in
// notifying the browser about explicit user field edit.
TEST_F(PasswordAutofillAgentTest, ModifyFieldsByManualFillingNotifiesBrowser) {
// Propagate fill data for filling on manual fallback.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
SimulateElementClick(username_element_);
EXPECT_CALL(fake_driver_,
UserModifiedNonPasswordField(
form_util::GetFieldRendererId(username_element_),
std::u16string(kAliceUsername16),
/*autocomplete_attribute_has_username=*/false,
/*is_likely_otp=*/false));
EXPECT_CALL(fake_driver_, UserModifiedPasswordField);
// Trigger manual filling and check filled values.
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
}
// Tests that filling on pageload does not notify the browser about explicit
// user field edits.
TEST_F(PasswordAutofillAgentTest,
ModifyFieldsByFillingOnPageloadDoesNotNotifyBrowser) {
// Propagate fill data should trigger filling on pageload.
EXPECT_CALL(fake_driver_, UserModifiedNonPasswordField).Times(0);
EXPECT_CALL(fake_driver_, UserModifiedPasswordField).Times(0);
SimulateOnFillPasswordForm(fill_data_);
// Simulate a click on the page to not only preview, but actually fill fields.
SimulateElementClick(username_element_);
// Make sure that fields were filled on the pageload.
CheckTextFieldsDOMState(kAliceUsername, /*username_autofilled=*/true,
kAlicePassword, /*password_autofilled=*/true);
}
// Tests that user inputs are propagated to the browser properly when a Shadow
// DOM tree starts between the <form> and <input> tags.
TEST_F(PasswordAutofillAgentTest,
ProvisionalPasswordSavingWhenFormTagHostsShadowDom) {
LoadHTML(kFormTagHostsShadowDomInputs);
// Identify username and password elements.
username_element_ =
GetElementByID("un_host").ShadowRoot().FirstChild().To<WebInputElement>();
ASSERT_TRUE(username_element_);
password_element_ =
GetElementByID("pw_host").ShadowRoot().FirstChild().To<WebInputElement>();
ASSERT_TRUE(password_element_);
// Simulate user modifying field values and ensure they are propagated to the
// browser.
username_element_.SetValue(WebString::FromUTF8(kAliceUsername));
password_autofill_agent_->UpdatePasswordStateForTextChange(username_element_,
/*form_cache=*/{});
fake_driver_.Flush();
EXPECT_EQ(fake_driver_.called_inform_about_user_input_count(), 1);
password_element_.SetValue(WebString::FromUTF8(kAlicePassword));
password_autofill_agent_->UpdatePasswordStateForTextChange(password_element_,
/*form_cache=*/{});
fake_driver_.Flush();
EXPECT_EQ(fake_driver_.called_inform_about_user_input_count(), 2);
ASSERT_TRUE(fake_driver_.form_data_maybe_submitted().has_value());
FormData submitted_form = fake_driver_.form_data_maybe_submitted().value();
EXPECT_EQ(submitted_form.name(), u"shadyform");
EXPECT_TRUE(FormHasFieldWithValue(submitted_form, kAliceUsername16));
EXPECT_TRUE(FormHasFieldWithValue(submitted_form, kAlicePassword16));
}
// Tests that passwords are filled properly on manual fallback when a Shadow
// DOM tree starts between the <form> and <input> tags.
TEST_F(PasswordAutofillAgentTest,
PasswordSuggestionFillingWhenFormTagHostsShadowDom) {
LoadHTML(kFormTagHostsShadowDomInputs);
ASSERT_TRUE(UpdateFormElementsForFormHostingShadowDom());
// Propagate fill data for filling on manual fallback.
UpdateRendererIDsInFillData();
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
SimulateElementClick(password_element_);
// Ensure that field are not filled on page load.
CheckTextFieldsDOMState(std::string(), false, std::string(), false);
// Trigger filling and check filled values.
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
}
// Tests that password generation works when a Shadow DOM tree starts between
// the <form> and <input> tags.
TEST_F(PasswordAutofillAgentTest, PasswordGenerationWhenFormTagHostsShadowDom) {
LoadHTML(kFormTagHostsShadowDomInputs);
ASSERT_TRUE(UpdateFormElementsForFormHostingShadowDom());
// Propagate fill data for filling on manual fallback.
UpdateRendererIDsInFillData();
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Simulate focusing the field and triggering password generation.
SimulateElementClick(password_element_);
base::test::TestFuture<const std::optional<
::autofill::password_generation::PasswordGenerationUIData>&>
future_for_waiting;
password_generation_->TriggeredGeneratePassword(
future_for_waiting.GetCallback());
EXPECT_TRUE(future_for_waiting.Wait());
const std::u16string kPassword = u"GeneratedPass24";
EXPECT_CALL(fake_pw_client_, PresaveGeneratedPassword(_, Eq(kPassword)));
password_generation_->GeneratedPasswordAccepted(kPassword);
// Check that the generated password is filled into form.
EXPECT_EQ(password_element_.Value().Utf16(), kPassword);
}
// Test that password manager gets notified about JS inputs in password fields.
TEST_F(PasswordAutofillAgentTest, JSFieldModificationPasswordForm) {
ASSERT_EQ(fake_driver_.called_inform_about_user_input_count(), 0);
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
const std::string kJsUsername = "js-set-username";
const std::string kJsPassword = "js-set-password";
ExecuteJavaScriptForTests(R"(document.getElementById('username').value = ')" +
kJsUsername + R"(';
document.getElementById('password').value = ')" +
kJsPassword + "';");
fake_driver_.Flush();
EXPECT_EQ(fake_driver_.called_inform_about_user_input_count(), 2);
ASSERT_TRUE(fake_driver_.form_data_maybe_submitted().has_value());
FormData form_data = fake_driver_.form_data_maybe_submitted().value();
ASSERT_EQ(form_data.fields().size(), 3u);
EXPECT_EQ(form_data.fields()[1].value(), base::ASCIIToUTF16(kJsUsername));
EXPECT_EQ(form_data.fields()[2].value(), base::ASCIIToUTF16(kJsPassword));
}
// Test that password manager is not notified about JS inputs in non
// password related fields.
TEST_F(PasswordAutofillAgentTest, JSFieldModificationUnrelatedField) {
ASSERT_EQ(fake_driver_.called_inform_about_user_input_count(), 0);
// First field in `kFormHTML` is unrelated to passwords.
ExecuteJavaScriptForTests(
R"(document.getElementById('random_field').value = 'js-set-whatever';)");
fake_driver_.Flush();
EXPECT_EQ(fake_driver_.called_inform_about_user_input_count(), 0);
}
// Test that password manager is not notified about JS inputs in fields that are
// no longer text inputs.
TEST_F(PasswordAutofillAgentTest, JSFieldModificationNonTextInput) {
ASSERT_EQ(fake_driver_.called_inform_about_user_input_count(), 0);
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Simulate JS changing the field type to hide the field from the user.
ExecuteJavaScriptForTests(
R"(document.getElementById('username').type = 'hidden';)");
ExecuteJavaScriptForTests(
R"(document.getElementById('username').value = 'js-set-whatever';)");
fake_driver_.Flush();
EXPECT_EQ(fake_driver_.called_inform_about_user_input_count(), 0);
}
// Tests that the metric for the number of times form fill data is stored
// for a form is recorded correctly.
TEST_F(PasswordAutofillAgentTest, TimesReceivedFillDataForFormMetric) {
// Simulate the browser sending back the login info, it triggers the
// autocomplete.
SimulateOnFillPasswordForm(fill_data_);
// Simulate form fill data changing after form reparsing.
fill_data_.username_element_renderer_id = FieldRendererId();
SimulateOnFillPasswordForm(fill_data_);
// Simulate receiving form fill data that cannot be used, e.g. because
// the fields are not present on the page.
// Simulate form fill data changing after form reparsing.
fill_data_.username_element_renderer_id = FieldRendererId(404);
fill_data_.password_element_renderer_id = FieldRendererId(40404);
SimulateOnFillPasswordForm(fill_data_);
// Simulate navigating to a new document.
password_autofill_agent_->ReadyToCommitNavigation(nullptr);
// The histogram should be recorded only for the form present on a
// page.
histogram_tester_.ExpectUniqueSample(
"PasswordManager.TimesReceivedFillDataForForm", 2, 1);
}
// Tests that if a password form was focused before parsing happened,
// suggestions are shown to the user once the form is parsed on Desktop,
// but not on Android.
TEST_F(PasswordAutofillAgentTest,
ShowSuggestionsOnParsingAutofocusedPasswordForm) {
scoped_feature_list_.InitAndEnableFeature(
password_manager::features::kShowSuggestionsOnAutofocus);
#if BUILDFLAG(IS_ANDROID)
// The method above leaves the field focused, which is not needed for this
// test.
BlurElement(kUsernameName);
#endif // BUILDFLAG(IS_ANDROID)
FocusElement(kUsernameName);
CheckSuggestionsNotShown();
// Simulate receiving credentials for filling from the browser and verify that
// suggestions are shown to the user.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
#if BUILDFLAG(IS_ANDROID)
CheckSuggestionsNotShown();
#else
CheckSuggestions(/*typed_username=*/u"", true);
#endif // BUILDFLAG(IS_ANDROID)
}
// Tests that if a password form supporting WebAuthn was focused before parsing
// happened, suggestions are shown to the user once the form is parsed on all
// platforms.
TEST_F(PasswordAutofillAgentTest,
ShowSuggestionsOnParsingAutofocusedWebAuthnForm) {
scoped_feature_list_.InitAndEnableFeature(
password_manager::features::kShowSuggestionsOnAutofocus);
LoadHTML(kWebAutnFieldHTML);
UpdateUsernameAndPasswordElements();
UpdateRendererIDsInFillData();
#if BUILDFLAG(IS_ANDROID)
// The method above leaves the field focused, which is not needed for this
// test.
BlurElement(kUsernameName);
#endif // BUILDFLAG(IS_ANDROID)
FocusElement(kUsernameName);
CheckSuggestionsNotShown();
// Simulate receiving credentials for filling from the browser and verify that
// suggestions are shown to the user.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
CheckSuggestions(/*typed_username=*/u"", true);
}
// Tests that if a password form is reparsed, suggestions are not shown
// automatically.
TEST_F(PasswordAutofillAgentTest,
DoNotShowSuggestionsOnParsingFocusedFormSecondTime) {
scoped_feature_list_.InitAndEnableFeature(
password_manager::features::kShowSuggestionsOnAutofocus);
#if BUILDFLAG(IS_ANDROID)
// The method above leaves the field focused, which is not needed for this
// test.
BlurElement(kUsernameName);
#endif // BUILDFLAG(IS_ANDROID)
// Simulate receiving fill data from the browser and user focusing the field
// to see suggestions.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
SimulateElementClick(kUsernameName);
CheckSuggestions(/*typed_username=*/u"", true);
// Simulate receiving new fill data from the browser and check that
// suggestions are not shown.
fill_data_.preferred_login.username_value = u"new_username";
SimulateOnFillPasswordForm(fill_data_);
CheckSuggestionsNotShown();
}
// Tests that if a password form is not focused, suggestions are not shown to
// the user once the form is parsed.
TEST_F(PasswordAutofillAgentTest,
DoNotShowSuggestionsOnParsingFormWithoutFocus) {
scoped_feature_list_.InitAndEnableFeature(
password_manager::features::kShowSuggestionsOnAutofocus);
#if BUILDFLAG(IS_ANDROID)
// The method above leaves the field focused, which is not needed for this
// test.
BlurElement(kUsernameName);
#endif // BUILDFLAG(IS_ANDROID)
// Simulate receiving credentials for filling from the browser.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
CheckSuggestionsNotShown();
}
TEST_F(PasswordAutofillAgentTest, InformingBrowserAboutUsernameTextFields) {
LoadHTML(kSingleTextInputFormHTML);
UpdateOnlyUsernameElement();
// Simulate the browser parsing the text field as username and sending the
// correspondent fill data.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
SimulateUsernameTyping(kUsernameName);
EXPECT_EQ(1, fake_driver_.called_inform_about_user_input_count());
}
TEST_F(PasswordAutofillAgentTest, InformingBrowserAboutIrrelevantTextFields) {
LoadHTML(kSingleTextInputFormHTML);
UpdateOnlyUsernameElement();
// The users types into a field that was not parsed as username.
SimulateUsernameTyping(kUsernameName);
EXPECT_EQ(0, fake_driver_.called_inform_about_user_input_count());
}
// Tests that fields with banned fields do not show password suggestions.
TEST_F(PasswordAutofillAgentTest, NoFillingFallbackForBannedFields) {
// Form consists both of credential and credit card fields.
LoadHTML(
R"(
<input type="text" id="username-field" name="username-field">
<input type="password" id="password-field" name="password-field">
<input type="text" id="credit-card-full-name"
name="credit-card-full-name" placeholder="Full Name">
<input type="password" id="credit-card-number"
name="credit-card-number" placeholder="Card number">
<input type="password" id="credit-card-cvc" name="credit-card-cvc"
placeholder="CVC">
)");
WebInputElement username_field = GetInputElementByID("username-field");
WebInputElement password_field = GetInputElementByID("username-field");
WebInputElement credit_card_full_name_field =
GetInputElementByID("credit-card-full-name");
WebInputElement credit_card_number_field =
GetInputElementByID("credit-card-number");
WebInputElement credit_card_cvc_field =
GetInputElementByID("credit-card-cvc");
// Password Manager found credential fields and has saved credentials.
PasswordFormFillData form_data;
form_data.form_renderer_id = FormRendererId();
form_data.username_element_renderer_id = FieldRef(username_field).GetId();
form_data.password_element_renderer_id = FieldRef(password_field).GetId();
form_data.preferred_login.username_value = kAliceUsername16;
form_data.preferred_login.password_value = kAlicePassword16;
form_data.suggestion_banned_fields = {
FieldRef(credit_card_full_name_field).GetId(),
FieldRef(credit_card_number_field).GetId(),
FieldRef(credit_card_cvc_field).GetId()};
password_autofill_agent_->ApplyFillDataOnParsingCompletion(form_data);
// Expect filling suggestion on credential forms.
EXPECT_TRUE(
password_autofill_agent_
->CreateRequestForDomain(
username_field,
AutofillSuggestionTriggerSource::kFormControlElementClicked,
/*form_cache=*/{})
.has_value());
EXPECT_TRUE(
password_autofill_agent_
->CreateRequestForDomain(
password_field,
AutofillSuggestionTriggerSource::kFormControlElementClicked,
/*form_cache=*/{})
.has_value());
// Expect no filling suggestion on credit card forms.
EXPECT_FALSE(
password_autofill_agent_
->CreateRequestForDomain(
credit_card_full_name_field,
AutofillSuggestionTriggerSource::kFormControlElementClicked,
/*form_cache=*/{})
.has_value());
EXPECT_FALSE(
password_autofill_agent_
->CreateRequestForDomain(
credit_card_number_field,
AutofillSuggestionTriggerSource::kFormControlElementClicked,
/*form_cache=*/{})
.has_value());
EXPECT_FALSE(
password_autofill_agent_
->CreateRequestForDomain(
credit_card_cvc_field,
AutofillSuggestionTriggerSource::kFormControlElementClicked,
/*form_cache=*/{})
.has_value());
}
// Tests that `FillChangePasswordForm` fills change password form.
TEST_F(PasswordAutofillAgentTest, FillChangePasswordForm) {
std::vector<std::string> htms_to_test = {kPasswordChangeFormHTML,
kPasswordChangeWithoutFormHTML};
for (const std::string& html : htms_to_test) {
SCOPED_TRACE(testing::Message() << "Running for the page: " << html);
LoadHTML(html);
UpdateUrlForHTML(html);
WebInputElement password = GetInputElementByID("password"),
new_password = GetInputElementByID("newpassword"),
confirmation_password =
GetInputElementByID("confirmpassword");
auto password_id = autofill::form_util::GetFieldRendererId(password),
new_password_id =
autofill::form_util::GetFieldRendererId(new_password),
password_confirmation =
autofill::form_util::GetFieldRendererId(confirmation_password);
const std::vector<autofill::FormData>& parsed_form_data =
fake_driver_.form_data_parsed().value();
EXPECT_EQ(1u, parsed_form_data.size());
base::MockCallback<
base::OnceCallback<void(const std::optional<autofill::FormData>&)>>
mock_reply;
EXPECT_CALL(mock_reply, Run(testing::Optional(parsed_form_data[0])));
password_autofill_agent_->FillChangePasswordForm(
password_id, new_password_id, password_confirmation, u"qwerty",
u"Pa$sw0rD", mock_reply.Get());
EXPECT_EQ(u"qwerty", password.Value().Utf16());
EXPECT_EQ(u"Pa$sw0rD", new_password.Value().Utf16());
EXPECT_EQ(u"Pa$sw0rD", confirmation_password.Value().Utf16());
}
}
// Tests that `FillChangePasswordForm` invokes callback with std::nullopt when
// form wasn't filled.
TEST_F(PasswordAutofillAgentTest, FillChangePasswordFormFailed) {
LoadHTML(kPasswordChangeFormHTML);
UpdateUrlForHTML(kPasswordChangeFormHTML);
WebInputElement password = GetInputElementByID("password"),
new_password = GetInputElementByID("newpassword"),
confirmation_password =
GetInputElementByID("confirmpassword");
base::MockCallback<
base::OnceCallback<void(const std::optional<autofill::FormData>&)>>
mock_reply;
EXPECT_CALL(mock_reply, Run(Eq(std::nullopt)));
password_autofill_agent_->FillChangePasswordForm(
autofill::FieldRendererId(0), autofill::FieldRendererId(0),
autofill::FieldRendererId(0), u"qwerty", u"Pa$sw0rD", mock_reply.Get());
EXPECT_EQ(u"", password.Value().Utf16());
EXPECT_EQ(u"", new_password.Value().Utf16());
EXPECT_EQ(u"", confirmation_password.Value().Utf16());
}
TEST_F(PasswordAutofillAgentTest, SubmitChangePassword) {
LoadHTML(kPasswordChangeFormHTML);
UpdateUrlForHTML(kPasswordChangeFormHTML);
WebInputElement password = GetInputElementByID("password");
base::MockCallback<base::OnceCallback<void(bool)>> mock_reply;
EXPECT_CALL(mock_reply, Run(true));
ASSERT_FALSE(fake_driver_.called_password_form_submitted());
password_autofill_agent_->SubmitFormWithEnter(
autofill::form_util::GetFieldRendererId(password), mock_reply.Get());
// Wait for submission event.
EXPECT_TRUE(base::test::RunUntil(
[&]() { return fake_driver_.called_password_form_submitted(); }));
}
TEST_F(PasswordAutofillAgentTest,
SubmitChangePasswordFailedWhenNoElementFound) {
LoadHTML(kPasswordChangeFormHTML);
UpdateUrlForHTML(kPasswordChangeFormHTML);
WebInputElement password = GetInputElementByID("password");
base::MockCallback<base::OnceCallback<void(bool)>> mock_reply;
EXPECT_CALL(mock_reply, Run(false));
ASSERT_FALSE(fake_driver_.called_password_form_submitted());
password_autofill_agent_->SubmitFormWithEnter(autofill::FieldRendererId(0),
mock_reply.Get());
EXPECT_FALSE(fake_driver_.called_password_form_submitted());
}
TEST_F(PasswordAutofillAgentTest, SubmitChangePasswordFailedWhenNoFormTag) {
LoadHTML(kPasswordChangeWithoutFormHTML);
UpdateUrlForHTML(kPasswordChangeWithoutFormHTML);
WebInputElement password = GetInputElementByID("password");
base::MockCallback<base::OnceCallback<void(bool)>> mock_reply;
EXPECT_CALL(mock_reply, Run(false));
ASSERT_FALSE(fake_driver_.called_password_form_submitted());
password_autofill_agent_->SubmitFormWithEnter(
autofill::form_util::GetFieldRendererId(password), mock_reply.Get());
EXPECT_FALSE(fake_driver_.called_password_form_submitted());
}
TEST_F(PasswordAutofillAgentTest,
SubmitChangePasswordFailedWhenNoSubmitElement) {
LoadHTML(kPasswordChangeFormWithoutSubmitHTML);
UpdateUrlForHTML(kPasswordChangeFormWithoutSubmitHTML);
WebInputElement password = GetInputElementByID("password");
base::MockCallback<base::OnceCallback<void(bool)>> mock_reply;
EXPECT_CALL(mock_reply, Run(false));
ASSERT_FALSE(fake_driver_.called_password_form_submitted());
password_autofill_agent_->SubmitFormWithEnter(
autofill::form_util::GetFieldRendererId(password), mock_reply.Get());
EXPECT_FALSE(fake_driver_.called_password_form_submitted());
}
TEST_F(PasswordAutofillAgentTest,
SubmitChangePasswordFailedWhenSubmitElementDisabled) {
LoadHTML(kPasswordChangeFormSubmitDisabledHTML);
UpdateUrlForHTML(kPasswordChangeFormSubmitDisabledHTML);
WebInputElement password = GetInputElementByID("password");
base::MockCallback<base::OnceCallback<void(bool)>> mock_reply;
EXPECT_CALL(mock_reply, Run(false));
ASSERT_FALSE(fake_driver_.called_password_form_submitted());
password_autofill_agent_->SubmitFormWithEnter(
autofill::form_util::GetFieldRendererId(password), mock_reply.Get());
EXPECT_FALSE(fake_driver_.called_password_form_submitted());
}
// Check that a dynamic form submission can be detected after the form is
// filled on a page load.
TEST_F(PasswordAutofillAgentTest,
DynamicFormSubmissionDetectedAfterFillingOnPageLoad) {
LoadHTML(kDivWrappedFormHTML);
UpdateUsernameAndPasswordElements();
FormRendererId renderer_id = GetFormUniqueRendererId("form");
// Fill the form on pageload with change password supported flag.
fill_data_.notify_browser_of_successful_filling = true;
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
CheckFirstFillingResult(FillingResult::kSuccess);
// Simulate website removing the change password form from the DOM after a
// successful submission.
FireAjaxSucceeded();
constexpr char kDeleteElement[] = "document.getElementById('inner').remove()";
ExecuteJavaScriptForTests(kDeleteElement);
ExpectDynamicFormSubmissionWithUsernameAndPasswords(
renderer_id, kAliceUsername16, kAlicePassword16,
SubmissionIndicatorEvent::DOM_MUTATION_AFTER_AUTOFILL);
}
// Check that a dynamic form submission is not detected after on page load.
TEST_F(PasswordAutofillAgentTest, DynamicFormSubmissionNotDetected) {
LoadHTML(kDivWrappedFormHTML);
UpdateUsernameAndPasswordElements();
fill_data_.notify_browser_of_successful_filling = false;
SimulateOnFillPasswordForm(fill_data_);
CheckTextFieldsSuggestedState(kAliceUsername, true, kAlicePassword, true);
CheckFirstFillingResult(FillingResult::kSuccess);
// Simulate website removing the change password form from the DOM after a
// successful submission.
FireAjaxSucceeded();
constexpr char kDeleteElement[] = "document.getElementById('inner').remove()";
ExecuteJavaScriptForTests(kDeleteElement);
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(fake_driver_.called_dynamic_form_submission());
ASSERT_FALSE(fake_driver_.form_data_maybe_submitted());
}
#if BUILDFLAG(IS_ANDROID)
// If a password field is hidden, the field unlikely has an Enter listener. So,
// trigger a form submission on the username field.
TEST_F(PasswordAutofillAgentTest, TriggerFormSubmission_HiddenPasswordField) {
const char kUsernameFirstFormHTML[] =
"<script>"
" function on_keypress(event) {"
" if (event.which === 13) {"
" var field = document.getElementById('password');"
" field.parentElement.removeChild(field);"
" }"
" }"
"</script>"
"<INPUT type='text' id='username' onkeypress='on_keypress(event)'/>"
"<INPUT type='password' id='password' style='display:none'/>";
LoadHTML(kUsernameFirstFormHTML);
base::RunLoop().RunUntilIdle();
UpdateUsernameAndPasswordElements();
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled because the test
// simulates filling with `FillSuggestion`, the function that
// KeyboardReplacingSurface uses.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Fill the form.
SimulateElementClick(username_element_);
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
base::RunLoop().RunUntilIdle();
// Trigger a form submission.
password_autofill_agent_->TriggerFormSubmission();
base::RunLoop().RunUntilIdle();
// Verify that the driver actually has seen a submission.
EXPECT_TRUE(fake_driver_.called_dynamic_form_submission());
}
class PasswordAutofillAgentFormPresenceVariationTest
: public PasswordAutofillAgentTest,
public testing::WithParamInterface<bool> {};
TEST_P(PasswordAutofillAgentFormPresenceVariationTest, TriggerFormSubmission) {
bool has_form_tag = GetParam();
LoadHTML(has_form_tag ? kFormHTML : kNoFormHTML);
base::RunLoop().RunUntilIdle();
UpdateUsernameAndPasswordElements();
// Simulate the browser sending the login info, but set `wait_for_username`
// to prevent the form from being immediately filled because the test
// simulates filling with `FillSuggestion`, the function that
// KeyboardReplacingSurface uses.
fill_data_.wait_for_username = true;
SimulateOnFillPasswordForm(fill_data_);
// Fill the form.
SimulateElementClick(username_element_);
password_autofill_agent_->FillPasswordSuggestion(
kAliceUsername16, kAlicePassword16, base::DoNothing());
base::RunLoop().RunUntilIdle();
// Trigger a form submission.
password_autofill_agent_->TriggerFormSubmission();
base::RunLoop().RunUntilIdle();
// Verify that the driver actually has seen a submission.
if (has_form_tag)
EXPECT_TRUE(fake_driver_.called_password_form_submitted());
else
EXPECT_TRUE(fake_driver_.called_dynamic_form_submission());
fake_driver_.reset_password_forms_calls();
}
INSTANTIATE_TEST_SUITE_P(FormPresenceVariation,
PasswordAutofillAgentFormPresenceVariationTest,
testing::Bool());
#endif // BUILDFLAG(IS_ANDROID)
} // namespace
} // namespace autofill
|