File: password_manager_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (4698 lines) | stat: -rw-r--r-- 208,352 bytes parent folder | download | duplicates (3)
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
// Copyright 2013 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>
#include <string_view>
#include <utility>

#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_samples.h"
#include "base/metrics/statistics_recorder.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "build/buildflag.h"
#include "chrome/browser/password_manager/chrome_password_manager_client.h"
#include "chrome/browser/password_manager/password_manager_test_base.h"
#include "chrome/browser/password_manager/password_manager_uitest_util.h"
#include "chrome/browser/password_manager/passwords_navigation_observer.h"
#include "chrome/browser/password_manager/profile_password_store_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/autofill/chrome_autofill_client.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_navigator_params.h"
#include "chrome/browser/ui/login/login_handler.h"
#include "chrome/browser/ui/passwords/manage_passwords_ui_controller.h"
#include "chrome/browser/ui/tabs/tab_enums.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/test/test_browser_dialog.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/autofill/content/browser/content_autofill_client.h"
#include "components/autofill/content/browser/content_autofill_driver.h"
#include "components/autofill/content/browser/content_autofill_driver_factory.h"
#include "components/autofill/content/browser/test_autofill_client_injector.h"
#include "components/autofill/content/common/mojom/autofill_driver.mojom-test-utils.h"
#include "components/autofill/content/common/mojom/autofill_driver.mojom.h"
#include "components/autofill/core/browser/field_types.h"
#include "components/autofill/core/browser/proto/api_v1.pb.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/autofill/core/common/mojom/autofill_types.mojom-shared.h"
#include "components/autofill/core/common/unique_ids.h"
#include "components/input/native_web_keyboard_event.h"
#include "components/password_manager/content/browser/content_password_manager_driver.h"
#include "components/password_manager/content/browser/content_password_manager_driver_factory.h"
#include "components/password_manager/core/browser/features/password_features.h"
#include "components/password_manager/core/browser/form_parsing/password_field_prediction.h"
#include "components/password_manager/core/browser/http_auth_manager.h"
#include "components/password_manager/core/browser/http_auth_observer.h"
#include "components/password_manager/core/browser/password_form.h"
#include "components/password_manager/core/browser/password_form_manager.h"
#include "components/password_manager/core/browser/password_manager_client.h"
#include "components/password_manager/core/browser/password_manager_driver.h"
#include "components/password_manager/core/browser/password_store/password_store_interface.h"
#include "components/password_manager/core/browser/password_store/test_password_store.h"
#include "components/signin/public/base/signin_buildflags.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "google_apis/gaia/gaia_id.h"
#include "google_apis/gaia/gaia_switches.h"
#include "net/base/filename_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "services/network/public/cpp/is_potentially_trustworthy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/input/web_keyboard_event.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/geometry/point.h"

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
#include "chrome/browser/password_manager/password_manager_signin_intercept_test_helper.h"
#include "chrome/browser/signin/dice_web_signin_interceptor.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/primary_account_mutator.h"
#endif  // BUIDLFLAG(ENABLE_DICE_SUPPORT)

using autofill::ParsingResult;
using base::ASCIIToUTF16;
using base::Feature;
using testing::_;
using testing::ElementsAre;
using testing::Field;
using testing::Pair;
using testing::SizeIs;

namespace password_manager {
namespace {

class PasswordManagerBrowserTest : public PasswordManagerBrowserTestBase {
 public:
  PasswordManagerBrowserTest() {
    // Turn off waiting for server predictions before filing. It makes filling
    // behaviour more deterministic. Filling with server predictions is tested
    // in PasswordFormManager unit tests.
    password_manager::PasswordFormManager::
        set_wait_for_server_predictions_for_filling(false);
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    PasswordManagerBrowserTestBase::SetUpCommandLine(command_line);

    // For the password form to be treated as the Gaia signin page.
    command_line->AppendSwitchASCII(
        switches::kGaiaUrl,
        https_test_server().GetURL("accounts.google.com", "/").spec());
  }

  ~PasswordManagerBrowserTest() override = default;
};

// A test fixture that injects an `ObservingAutofillClient` into newly created
// tabs to allow waiting for an Autofill popup to open.
class PasswordManagerAutofillPopupBrowserTest
    : public PasswordManagerBrowserTest {
 protected:
  ObservingAutofillClient& autofill_client() {
    return *autofill_client_injector_[WebContents()];
  }

 private:
  autofill::TestAutofillClientInjector<ObservingAutofillClient>
      autofill_client_injector_;
};

// This fixture enables communication to the Autofill crowdsourcing server, but
// denies any such requests.
class PasswordManagerVotingBrowserTest : public PasswordManagerBrowserTest {
 public:
  void SetUpOnMainThread() override {
    PasswordManagerBrowserTest::SetUpOnMainThread();
    url_loader_interceptor_ =
        std::make_unique<content::URLLoaderInterceptor>(base::BindRepeating(
            [](content::URLLoaderInterceptor::RequestParams* params) {
              bool is_autofill_request =
                  params->url_request.url.spec().find(
                      "https://content-autofill.googleapis.com/") !=
                  std::string::npos;
              return is_autofill_request;
            }));
  }

  void TearDownOnMainThread() override {
    url_loader_interceptor_.reset();
    PasswordManagerBrowserTest::TearDownOnMainThread();
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_{
      autofill::features::test::kAutofillServerCommunication};
  std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor_;
};

// Test class for testing password manager with the BackForwardCache feature
// enabled. More info about the BackForwardCache, see:
// http://doc/1YrBKX_eFMA9KoYof-eVThT35jcTqWcH_rRxYbR5RapU
class PasswordManagerBackForwardCacheBrowserTest
    : public PasswordManagerBrowserTest {
 public:
  void SetUpOnMainThread() override {
    // TODO(crbug.com/40737060): Remove this and below after confirming
    // whether setup is completing.
    LOG(INFO) << "SetUpOnMainThread started.";
    host_resolver()->AddRule("*", "127.0.0.1");
    PasswordManagerBrowserTest ::SetUpOnMainThread();
    LOG(INFO) << "SetUpOnMainThread complete.";
  }

  bool IsGetCredentialsSuccessful() {
    return "success" ==
           content::EvalJs(WebContents()->GetPrimaryMainFrame(), R"(
      new Promise(resolve => {
        navigator.credentials.get({password: true, unmediated: true })
          .then(m => { resolve("success"); })
          .catch(()=> { resolve("error"); });
        });
    )");
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    scoped_feature_list_.InitWithFeaturesAndParameters(
        content::GetDefaultEnabledBackForwardCacheFeaturesForTesting(),
        content::GetDefaultDisabledBackForwardCacheFeaturesForTesting());
    PasswordManagerBrowserTest::SetUpCommandLine(command_line);
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

class MockHttpAuthObserver : public password_manager::HttpAuthObserver {
 public:
  MOCK_METHOD(void,
              OnAutofillDataAvailable,
              (std::u16string_view username, std::u16string_view password),
              (override));

  MOCK_METHOD(void, OnLoginModelDestroying, (), (override));
};

GURL GetFileURL(const char* filename) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::FilePath path;
  base::PathService::Get(chrome::DIR_TEST_DATA, &path);
  path = path.AppendASCII("password").AppendASCII(filename);
  CHECK(base::PathExists(path));
  return net::FilePathToFileURL(path);
}

// Handles |request| to "/basic_auth". If "Authorization" header is present,
// responds with a non-empty HTTP 200 page (regardless of its value). Otherwise
// serves a Basic Auth challenge.
std::unique_ptr<net::test_server::HttpResponse> HandleTestAuthRequest(
    const net::test_server::HttpRequest& request) {
  if (!base::StartsWith(request.relative_url, "/basic_auth",
                        base::CompareCase::SENSITIVE)) {
    return nullptr;
  }
  auto http_response = std::make_unique<net::test_server::BasicHttpResponse>();
  if (base::Contains(request.headers, "Authorization")) {
    http_response->set_code(net::HTTP_OK);
    http_response->set_content("Success!");
  } else {
    http_response->set_code(net::HTTP_UNAUTHORIZED);
    std::string realm = base::EndsWith(request.relative_url, "/empty_realm",
                                       base::CompareCase::SENSITIVE)
                            ? "\"\""
                            : "\"test realm\"";
    http_response->AddCustomHeader("WWW-Authenticate", "Basic realm=" + realm);
  }
  return http_response;
}

void TestPromptNotShown(const char* failure_message,
                        content::WebContents* web_contents) {
  SCOPED_TRACE(testing::Message(failure_message));

  PasswordsNavigationObserver observer(web_contents);
  std::string fill_and_submit =
      "document.getElementById('username_failed').value = 'temp';"
      "document.getElementById('password_failed').value = 'random';"
      "document.getElementById('failed_form').submit()";

  ASSERT_TRUE(content::ExecJs(web_contents, fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(BubbleObserver(web_contents).IsSavePromptShownAutomatically());
}

// Generate HTML for a simple password form with the specified action URL.
std::string GeneratePasswordFormForAction(const GURL& action_url) {
  return "<form method='POST' action='" + action_url.spec() +
         "'"
         "      onsubmit='return true;' id='testform'>"
         "  <input type='password' id='password_field'>"
         "</form>";
}

// Inject an about:blank frame with a password form that uses the specified
// action URL into |web_contents|.
void InjectBlankFrameWithPasswordForm(content::WebContents* web_contents,
                                      const GURL& action_url) {
  std::string form_html = GeneratePasswordFormForAction(action_url);
  std::string inject_blank_frame_with_password_form =
      "var frame = document.createElement('iframe');"
      "frame.id = 'iframe';"
      "document.body.appendChild(frame);"
      "frame.contentDocument.body.innerHTML = \"" +
      form_html + "\"";
  ASSERT_TRUE(
      content::ExecJs(web_contents, inject_blank_frame_with_password_form));
}

// Inject an iframe with a password form that uses the specified action URL into
// |web_contents|.
void InjectFrameWithPasswordForm(content::WebContents* web_contents,
                                 const GURL& action_url) {
  std::string form_html = GeneratePasswordFormForAction(action_url);
  std::string inject_blank_frame_with_password_form =
      "var ifr = document.createElement('iframe');"
      "ifr.setAttribute('id', 'iframeResult');"
      "document.body.appendChild(ifr);"
      "ifr.contentWindow.document.open();"
      "ifr.contentWindow.document.write(\"" +
      form_html +
      "\");"
      "ifr.contentWindow.document.close();";
  ASSERT_TRUE(
      content::ExecJs(web_contents, inject_blank_frame_with_password_form));
}

// Fills in a fake password and submits the form in |frame|, waiting for the
// submit navigation to finish.  |action_url| is the form action URL to wait
// for.
void SubmitInjectedPasswordForm(content::WebContents* web_contents,
                                content::RenderFrameHost* frame,
                                const GURL& action_url) {
  std::string submit_form =
      "document.getElementById('password_field').value = 'pa55w0rd';"
      "document.getElementById('testform').submit();";
  PasswordsNavigationObserver observer(web_contents);
  observer.SetPathToWaitFor(action_url.path());
  ASSERT_TRUE(content::ExecJs(frame, submit_form));
  ASSERT_TRUE(observer.Wait());
}

void SetUrlAsTrustworthy(const std::string& url) {
  std::vector<std::string> rejected_patterns;
  network::SecureOriginAllowlist::GetInstance().SetAuxiliaryAllowlist(
      url, &rejected_patterns);
  // Check that the url was not rejected.
  EXPECT_THAT(rejected_patterns, testing::IsEmpty());
}

// Actual tests ---------------------------------------------------------------

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForNormalSubmit) {
  NavigateToFile("/password/password_form.html");

  // Fill a form and submit through a <input type="submit"> button. Nothing
  // special.
  PasswordsNavigationObserver observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());

  // Save the password and check the store.
  BubbleObserver bubble_observer(WebContents());
  bubble_observer.WaitForAutomaticSavePrompt();
  bubble_observer.AcceptSavePrompt();
  WaitForPasswordStore();

  CheckThatCredentialsStored("temp", "random");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptIfFormReappeared) {
  NavigateToFile("/password/failed.html");
  TestPromptNotShown("normal form", WebContents());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptIfChangePasswordFormReappearedEmpty) {
  NavigateToFile("/password/update_form_empty_fields.html");
  // Fill a form and submit through a <input type="submit"> button. Nothing
  // special.
  PasswordsNavigationObserver observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('password').value = 'old_pass';"
      "document.getElementById('new_password_1').value = 'new_pass';"
      "document.getElementById('new_password_2').value = 'new_pass';"
      "document.getElementById('chg_submit_wo_username_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  BubbleObserver(WebContents()).WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoPromptIfFormReappearedWithPartsHidden) {
  NavigateToFile("/password/failed_partly_visible.html");
  TestPromptNotShown("partly visible form", WebContents());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoPromptIfFormReappearedInputOutsideFor) {
  NavigateToFile("/password/failed_input_outside.html");
  TestPromptNotShown("form with input outside", WebContents());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoPromptAfterCredentialsAPIPasswordStore) {
  NavigateToFile("/password/password_form.html");
  // Simulate the Credential Management API function store() is called and
  // PasswordManager instance is notified about that.
  ChromePasswordManagerClient::FromWebContents(WebContents())
      ->NotifyStorePasswordCalled();

  // Fill a form and submit through a <input type="submit"> button. The
  // renderer should not send "PasswordFormsParsed" messages after the page
  // was loaded.
  PasswordsNavigationObserver observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  BubbleObserver prompt_observer(WebContents());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForSubmitWithSameDocumentNavigation) {
  NavigateToFile("/password/password_navigate_before_submit.html");

  // Fill a form and submit through a <input type="submit"> button. Nothing
  // special. The form does an in-page navigation before submitting.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       LoginSuccessWithUnrelatedForm) {
  // Log in, see a form on the landing page. That form is not related to the
  // login form (=has different input fields), so we should offer saving the
  // password.
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_unrelated').value = 'temp';"
      "document.getElementById('password_unrelated').value = 'random';"
      "document.getElementById('submit_unrelated').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, LoginFailed) {
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_failed').value = 'temp';"
      "document.getElementById('password_failed').value = 'random';"
      "document.getElementById('submit_failed').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForSubmitUsingJavaScript) {
  NavigateToFile("/password/password_form.html");

  // Fill a form and submit using <button> that calls submit() on the form.
  // This should work regardless of the type of element, as long as submit() is
  // called.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForDynamicForm) {
  // Adding a PSL matching form is a workaround explained later.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  GURL psl_orogin = embedded_test_server()->GetURL("psl.example.com", "/");
  signin_form.signon_realm = psl_orogin.spec();
  signin_form.url = psl_orogin;
  signin_form.username_value = u"unused_username";
  signin_form.password_value = u"unused_password";
  password_store->AddLogin(signin_form);

  // Show the dynamic form.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(
                     "example.com", "/password/dynamic_password_form.html")));
  ASSERT_TRUE(content::ExecJs(
      WebContents(), "document.getElementById('create_form_button').click();"));

  // Blink has a timer for 0.3 seconds before it updates the browser with the
  // new dynamic form. We wait for the form being detected by observing the UI
  // state. The state changes due to the matching credential saved above. Later
  // the form submission is definitely noticed by the browser.
  BubbleObserver(WebContents()).WaitForManagementState();

  // Fill the dynamic password form and submit.
  PasswordsNavigationObserver observer(WebContents());
  std::string fill_and_submit =
      "document.dynamic_form.username.value = 'tempro';"
      "document.dynamic_form.password.value = 'random';"
      "document.dynamic_form.submit()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());

  BubbleObserver(WebContents()).WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForNavigation) {
  NavigateToFile("/password/password_form.html");

  // Don't fill the password form, just navigate away. Shouldn't prompt.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  ASSERT_TRUE(content::ExecJs(RenderFrameHost(),
                              "window.location.href = 'done.html';",
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoPromptForSubFrameNavigation) {
  NavigateToFile("/password/multi_frames.html");

  // If you are filling out a password form in one frame and a different frame
  // navigates, this should not trigger the infobar.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  observer.SetPathToWaitFor("/password/done.html");
  std::string fill =
      "var first_frame = document.getElementById('first_frame');"
      "var frame_doc = first_frame.contentDocument;"
      "frame_doc.getElementById('username_field').value = 'temp';"
      "frame_doc.getElementById('password_field').value = 'random';";
  std::string navigate_frame =
      "var second_iframe = document.getElementById('second_frame');"
      "second_iframe.contentWindow.location.href = 'done.html';";

  ASSERT_TRUE(content::ExecJs(WebContents(), fill));
  ASSERT_TRUE(content::ExecJs(WebContents(), navigate_frame));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoPromptForSameFormWithDifferentAction) {
  // Log in, see a form on the landing page. That form is related to the login
  // form (has a different action but has same input fields), so we should not
  // offer saving the password.
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_different_action').value = 'temp';"
      "document.getElementById('password_different_action').value = 'random';"
      "document.getElementById('submit_different_action').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForActionMutation) {
  NavigateToFile("/password/password_form_action_mutation.html");

  // Need to pay attention for a message that XHR has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_action_mutation').value = 'temp';"
      "document.getElementById('password_action_mutation').value = 'random';"
      "document.getElementById('submit_action_mutation').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  std::string message;
  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"XHR_FINISHED\"") {
      break;
    }
  }
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoPromptForFormWithEnteredUsername) {
  // Log in, see a form on the landing page. That form is not related to the
  // login form but has the same username as was entered previously, so we
  // should not offer saving the password.
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_contains_username').value = 'temp';"
      "document.getElementById('password_contains_username').value = 'random';"
      "document.getElementById('submit_contains_username').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForDifferentFormWithEmptyAction) {
  // Log in, see a form on the landing page. That form is not related to the
  // signin form. The signin and the form on the landing page have empty
  // actions, so we should offer saving the password.
  NavigateToFile("/password/navigate_to_same_url_empty_actions.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username').value = 'temp';"
      "document.getElementById('password').value = 'random';"
      "document.getElementById('submit-button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptAfterSubmitWithSubFrameNavigation) {
  NavigateToFile("/password/multi_frames.html");

  // Make sure that we prompt to save password even if a sub-frame navigation
  // happens first.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  observer.SetPathToWaitFor("/password/done.html");
  std::string navigate_frame =
      "var second_iframe = document.getElementById('second_frame');"
      "second_iframe.contentWindow.location.href = 'other.html';";
  std::string fill_and_submit =
      "var first_frame = document.getElementById('first_frame');"
      "var frame_doc = first_frame.contentDocument;"
      "frame_doc.getElementById('username_field').value = 'temp';"
      "frame_doc.getElementById('password_field').value = 'random';"
      "frame_doc.getElementById('input_submit_button').click();";

  ASSERT_TRUE(content::ExecJs(WebContents(), navigate_frame));
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    NoPromptForFailedLoginFromMainFrameWithMultiFramesSameDocument) {
  NavigateToFile("/password/multi_frames.html");

  // Make sure that we don't prompt to save the password for a failed login
  // from the main frame with multiple frames in the same page.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_failed').value = 'temp';"
      "document.getElementById('password_failed').value = 'random';"
      "document.getElementById('submit_failed').click();";

  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    NoPromptForFailedLoginFromSubFrameWithMultiFramesSameDocument) {
  NavigateToFile("/password/multi_frames.html");

  // Make sure that we don't prompt to save the password for a failed login
  // from a sub-frame with multiple frames in the same page.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "var first_frame = document.getElementById('first_frame');"
      "var frame_doc = first_frame.contentDocument;"
      "frame_doc.getElementById('username_failed').value = 'temp';"
      "frame_doc.getElementById('password_failed').value = 'random';"
      "frame_doc.getElementById('submit_failed').click();";

  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  observer.SetPathToWaitFor("/password/failed.html");
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForXHRSubmit) {
  NavigateToFile("/password/password_xhr_submit.html");

  // Verify that we show the save password prompt if a form returns false
  // in its onsubmit handler but instead logs in/navigates via XHR.
  // Note that calling 'submit()' on a form with javascript doesn't call
  // the onsubmit handler, so we click the submit button instead.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForXHRSubmitWithoutNavigation) {
  NavigateToFile("/password/password_xhr_submit.html");

  // Need to pay attention for a message that XHR has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());

  // Verify that if XHR without navigation occurs and the form has been filled
  // out we try and save the password. Note that in general the submission
  // doesn't need to be via form.submit(), but for testing purposes it's
  // necessary since we otherwise ignore changes made to the value of these
  // fields by script.
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "navigate = false;"
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  std::string message;
  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"XHR_FINISHED\"") {
      break;
    }
  }

  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForXHRSubmitWithoutNavigation_SignupForm) {
  NavigateToFile("/password/password_xhr_submit.html");

  // Need to pay attention for a message that XHR has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());

  // Verify that if XHR without navigation occurs and the form has been filled
  // out we try and save the password. Note that in general the submission
  // doesn't need to be via form.submit(), but for testing purposes it's
  // necessary since we otherwise ignore changes made to the value of these
  // fields by script.
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "navigate = false;"
      "document.getElementById('signup_username_field').value = 'temp';"
      "document.getElementById('signup_password_field').value = 'random';"
      "document.getElementById('confirmation_password_field').value = 'random';"
      "document.getElementById('signup_submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  std::string message;
  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"XHR_FINISHED\"") {
      break;
    }
  }

  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoPromptForXHRSubmitWithoutNavigationWithUnfilledForm) {
  NavigateToFile("/password/password_xhr_submit.html");

  // Need to pay attention for a message that XHR has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());

  // Verify that if XHR without navigation occurs and the form has NOT been
  // filled out we don't prompt.
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "navigate = false;"
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  std::string message;
  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"XHR_FINISHED\"") {
      break;
    }
  }

  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    NoPromptForXHRSubmitWithoutNavigationWithUnfilledForm_SignupForm) {
  NavigateToFile("/password/password_xhr_submit.html");

  // Need to pay attention for a message that XHR has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());

  // Verify that if XHR without navigation occurs and the form has NOT been
  // filled out we don't prompt.
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "navigate = false;"
      "document.getElementById('signup_username_field').value = 'temp';"
      "document.getElementById('signup_submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  std::string message;
  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"XHR_FINISHED\"") {
      break;
    }
  }

  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForFetchSubmit) {
  NavigateToFile("/password/password_fetch_submit.html");

  // Verify that we show the save password prompt if a form returns false
  // in its onsubmit handler but instead logs in/navigates via Fetch.
  // Note that calling 'submit()' on a form with javascript doesn't call
  // the onsubmit handler, so we click the submit button instead.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForFetchSubmitWithoutNavigation) {
  NavigateToFile("/password/password_fetch_submit.html");

  // Need to pay attention for a message that XHR has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());

  // Verify that if XHR without navigation occurs and the form has been filled
  // out we try and save the password. Note that in general the submission
  // doesn't need to be via form.submit(), but for testing purposes it's
  // necessary since we otherwise ignore changes made to the value of these
  // fields by script.
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "navigate = false;"
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  // This forces layout update.
  RunUntilInputProcessed(RenderFrameHost()->GetRenderWidgetHost());

  std::string message;
  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"FETCH_FINISHED\"") {
      break;
    }
  }
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForFetchSubmitWithoutNavigation_SignupForm) {
  NavigateToFile("/password/password_fetch_submit.html");

  // Need to pay attention for a message that Fetch has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());

  // Verify that if Fetch without navigation occurs and the form has been filled
  // out we try and save the password. Note that in general the submission
  // doesn't need to be via form.submit(), but for testing purposes it's
  // necessary since we otherwise ignore changes made to the value of these
  // fields by script.
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "navigate = false;"
      "document.getElementById('signup_username_field').value = 'temp';"
      "document.getElementById('signup_password_field').value = 'random';"
      "document.getElementById('confirmation_password_field').value = 'random';"
      "document.getElementById('signup_submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  // This forces layout update.
  RunUntilInputProcessed(RenderFrameHost()->GetRenderWidgetHost());
  std::string message;

  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"FETCH_FINISHED\"") {
      break;
    }
  }
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    NoPromptForFetchSubmitWithoutNavigationWithUnfilledForm) {
  NavigateToFile("/password/password_fetch_submit.html");

  // Need to pay attention for a message that Fetch has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());

  // Verify that if Fetch without navigation occurs and the form has NOT been
  // filled out we don't prompt.
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "navigate = false;"
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  // This forces layout update.
  RunUntilInputProcessed(RenderFrameHost()->GetRenderWidgetHost());

  std::string message;
  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"FETCH_FINISHED\"") {
      break;
    }
  }
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    NoPromptForFetchSubmitWithoutNavigationWithUnfilledForm_SignupForm) {
  NavigateToFile("/password/password_fetch_submit.html");

  // Need to pay attention for a message that Fetch has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());

  // Verify that if Fetch without navigation occurs and the form has NOT been
  // filled out we don't prompt.
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "navigate = false;"
      "document.getElementById('signup_username_field').value = 'temp';"
      "document.getElementById('signup_submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  // This forces layout update.
  RunUntilInputProcessed(RenderFrameHost()->GetRenderWidgetHost());

  std::string message;
  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"FETCH_FINISHED\"") {
      break;
    }
  }
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptIfLinkClicked) {
  NavigateToFile("/password/password_form.html");

  // Verify that if the user takes a direct action to leave the page, we don't
  // prompt to save the password even if the form is already filled out.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_click_link =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('link').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_click_link));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerVotingBrowserTest,
                       VerifyPasswordGenerationUpload) {
  // The form should not be hosted on localhost to enable sending
  // crowdsourcing votes.
  const std::string kTestSignonRealm = "example.com";
  // This fixture is needed to allow password filling on page load.
  SetUrlAsTrustworthy(
      embedded_test_server()->GetURL(kTestSignonRealm, "/").spec());

  // Visit a signup form.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kTestSignonRealm,
                                                "/password/signup_form.html")));

  // Enter a password and save it.
  PasswordsNavigationObserver first_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('other_info').value = 'stuff';"
      "document.getElementById('username_field').value = 'my_username';"
      "document.getElementById('password_field').value = 'password';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));

  ASSERT_TRUE(first_observer.Wait());
  {
    base::HistogramTester histograms;
    BubbleObserver prompt_observer(WebContents());
    prompt_observer.WaitForAutomaticSavePrompt();
    prompt_observer.AcceptSavePrompt();
    // One vote on saving a password.
    histograms.ExpectUniqueSample("Autofill.UploadEvent", 1, 1);
  }

  // Now navigate to a login form that has similar HTML markup.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(
                     kTestSignonRealm, "/password/password_form.html")));

  // Simulate a user click to force an autofill of the form's DOM value, not
  // just the suggested value.
  content::SimulateMouseClick(WebContents(), 0,
                              blink::WebMouseEvent::Button::kLeft);
  WaitForElementValue("username_field", "my_username");
  WaitForElementValue("password_field", "password");

  // Submit the form and verify that there is no infobar (as the password
  // has already been saved).
  PasswordsNavigationObserver second_observer(WebContents());
  BubbleObserver second_prompt_observer(WebContents());
  std::string submit_form =
      "document.getElementById('input_submit_button').click()";
  {
    base::HistogramTester histograms;
    ASSERT_TRUE(content::ExecJs(WebContents(), submit_form));
    ASSERT_TRUE(second_observer.Wait());
    // One vote for credential reuse, one vote for first time login.
    EXPECT_TRUE(base::test::RunUntil([&histograms]() {
      return histograms.GetBucketCount("Autofill.UploadEvent", 1) == 2;
    }));
  }
  EXPECT_FALSE(second_prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, PromptForSubmitFromIframe) {
  NavigateToFile("/password/password_submit_from_iframe.html");

  // Submit a form in an iframe, then cause the whole page to navigate without a
  // user gesture. We expect the save password prompt to be shown here, because
  // some pages use such iframes for login forms.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "var iframe = document.getElementById('test_iframe');"
      "var iframe_doc = iframe.contentDocument;"
      "iframe_doc.getElementById('username_field').value = 'temp';"
      "iframe_doc.getElementById('password_field').value = 'random';"
      "iframe_doc.getElementById('submit_button').click()";

  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForInputElementWithoutName) {
  // Check that the prompt is shown for forms where input elements lack the
  // "name" attribute but the "id" is present.
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field_no_name').value = 'temp';"
      "document.getElementById('password_field_no_name').value = 'random';"
      "document.getElementById('input_submit_button_no_name').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForInputElementWithoutId) {
  // Check that the prompt is shown for forms where input elements lack the
  // "id" attribute but the "name" attribute is present.
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementsByName('username_field_no_id')[0].value = 'temp';"
      "document.getElementsByName('password_field_no_id')[0].value = 'random';"
      "document.getElementsByName('input_submit_button_no_id')[0].click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForInputElementWithoutIdAndName) {
  // Check that prompt is shown for forms where the input fields lack both
  // the "id" and the "name" attributes.
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "var form = document.getElementById('testform_elements_no_id_no_name');"
      "var username = form.children[0];"
      "username.value = 'temp';"
      "var password = form.children[1];"
      "password.value = 'random';"
      "form.children[2].click()";  // form.children[2] is the submit button.
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
  prompt_observer.AcceptSavePrompt();

  // Check that credentials are stored.
  WaitForPasswordStore();
  CheckThatCredentialsStored("temp", "random");
}

// Test for checking that no prompt is shown for URLs with file: scheme.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptForFileSchemeURLs) {
  GURL url = GetFileURL("password_form.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoPromptForLandingPageWithHTTPErrorStatusCode) {
  // Check that no prompt is shown for forms where the landing page has
  // HTTP status 404.
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field_http_error').value = 'temp';"
      "document.getElementById('password_field_http_error').value = 'random';"
      "document.getElementById('input_submit_button_http_error').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, DeleteFrameBeforeSubmit) {
  NavigateToFile("/password/multi_frames.html");

  PasswordsNavigationObserver observer(WebContents());
  // Make sure we save some password info from an iframe and then destroy it.
  std::string save_and_remove =
      "var first_frame = document.getElementById('first_frame');"
      "var frame_doc = first_frame.contentDocument;"
      "frame_doc.getElementById('username_field').value = 'temp';"
      "frame_doc.getElementById('password_field').value = 'random';"
      "frame_doc.getElementById('input_submit_button').click();"
      "first_frame.parentNode.removeChild(first_frame);";
  // Submit from the main frame, but without navigating through the onsubmit
  // handler.
  std::string navigate_frame =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click();"
      "window.location.href = 'done.html';";

  ASSERT_TRUE(content::ExecJs(WebContents(), save_and_remove));
  ASSERT_TRUE(content::ExecJs(WebContents(), navigate_frame));
  ASSERT_TRUE(observer.Wait());
  // The only thing we check here is that there is no use-after-free reported.
}

// Tests that we do not override username and password values in the
// form on the pageload.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoFillOnPageloadIfUsernameAndPasswordAreNonEmpty) {
  // Add credentials to the password store.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm saved_form;
  const std::string kTestSignonRealm =
      embedded_test_server()->GetURL("example.com", "/").spec();
  saved_form.signon_realm = kTestSignonRealm;
  const GURL kFormUrl = embedded_test_server()->GetURL(
      "example.com", "/password/prefilled_username.html");
  saved_form.url = kFormUrl;
  saved_form.username_value = u"saved_username";
  saved_form.password_value = u"saved_password";
  password_store->AddLogin(saved_form);

  // This fixture is needed to allow filling on page load.
  SetUrlAsTrustworthy(kTestSignonRealm);

  // User navigates to the page.
  PasswordsNavigationObserver observer(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), kFormUrl));
  ASSERT_TRUE(observer.Wait());

  // Password Manager does not autofill on page load until user interacted with
  // the page.
  CheckElementValue("username_field", "some_username");
  CheckElementValue("password_field", "some_password");
  // After user clicks on the webpage, password manager will still not fill.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));
  WaitForElementValue("username_field", "some_username");
  WaitForElementValue("password_field", "some_password");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       UsernameAndPasswordValueAccessible) {
  // At first let us save a credential to the password store.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.url = embedded_test_server()->base_url();
  signin_form.action = embedded_test_server()->base_url();
  signin_form.username_value = u"admin";
  signin_form.password_value = u"12345";
  password_store->AddLogin(signin_form);

  // Steps from https://crbug.com/337429#c37.
  // Navigate to the page, click a link that opens a second tab, reload the
  // first tab and observe that the password is accessible.
  NavigateToFile("/password/form_and_link.html");

  // Click on a link to open a new tab, then switch back to the first one.
  EXPECT_EQ(1, browser()->tab_strip_model()->count());
  std::string click = "document.getElementById('testlink').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), click));
  EXPECT_EQ(2, browser()->tab_strip_model()->count());
  browser()->tab_strip_model()->ActivateTabAt(0);

  // Reload the original page to have the saved credentials autofilled.
  PasswordsNavigationObserver reload_observer(WebContents());
  NavigateToFile("/password/form_and_link.html");
  ASSERT_TRUE(reload_observer.Wait());

  // Now check that the username and the password are not accessible yet.
  CheckElementValue("username_field", "");
  CheckElementValue("password_field", "");
  // Let the user interact with the page.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));
  // Wait until that interaction causes the username and the password value to
  // be revealed.
  WaitForElementValue("username_field", "admin");
  WaitForElementValue("password_field", "12345");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PasswordValueAccessibleOnSubmit) {
  // At first let us save a credential to the password store.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.url = embedded_test_server()->base_url();
  signin_form.action = embedded_test_server()->base_url();
  signin_form.username_value = u"admin";
  signin_form.password_value = u"random_secret";
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/form_and_link.html");

  PasswordsNavigationObserver submit_observer(WebContents());
  // Submit the form via a tap on the submit button.
  content::SimulateMouseClickOrTapElementWithId(WebContents(),
                                                "input_submit_button");
  ASSERT_TRUE(submit_observer.Wait());
  std::string query = WebContents()->GetLastCommittedURL().query();
  EXPECT_THAT(query, testing::HasSubstr("random_secret"));
}

// Test fix for crbug.com/338650.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       DontPromptForPasswordFormWithDefaultValue) {
  NavigateToFile("/password/password_form_with_default_value.html");

  // Don't prompt if we navigate away even if there is a password value since
  // it's not coming from the user.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  NavigateToFile("/password/done.html");
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       DontPromptForPasswordFormWithReadonlyPasswordField) {
  NavigateToFile("/password/password_form_with_password_readonly.html");

  // Fill a form and submit through a <input type="submit"> button. Nothing
  // special.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptWhenEnableAutomaticPasswordSavingSwitchIsNotSet) {
  NavigateToFile("/password/password_form.html");

  // Fill a form and submit through a <input type="submit"> button.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

// Test fix for crbug.com/368690.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptWhenReloading) {
  NavigateToFile("/password/password_form.html");

  std::string fill =
      "document.getElementById('username_redirect').value = 'temp';"
      "document.getElementById('password_redirect').value = 'random';";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill));

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  GURL url = embedded_test_server()->GetURL("/password/password_form.html");
  NavigateParams params(browser(), url, ::ui::PAGE_TRANSITION_RELOAD);
  ui_test_utils::NavigateToURL(&params);
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

// Test that if a form gets dynamically added between the form parsing and
// rendering, and while the main frame still loads, it still is registered, and
// thus saving passwords from it works.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       FormsAddedBetweenParsingAndRendering) {
  NavigateToFile("/password/between_parsing_and_rendering.html");

  PasswordsNavigationObserver observer(WebContents());
  std::string submit =
      "document.getElementById('username').value = 'temp';"
      "document.getElementById('password').value = 'random';"
      "document.getElementById('submit-button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), submit));
  ASSERT_TRUE(observer.Wait());
  BubbleObserver(WebContents()).WaitForAutomaticSavePrompt();
}

// Test that if a hidden form gets dynamically added between the form parsing
// and rendering, it still is registered, and autofilling works.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       HiddenFormAddedBetweenParsingAndRendering) {
  // At first let us save a credential to the password store.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.url = embedded_test_server()->base_url();
  signin_form.action = embedded_test_server()->base_url();
  signin_form.username_value = u"admin";
  signin_form.password_value = u"12345";
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/between_parsing_and_rendering.html?hidden");

  std::string show_form =
      "document.getElementsByTagName('form')[0].style.display = 'block'";
  ASSERT_TRUE(content::ExecJs(WebContents(), show_form));

  // Wait until the username is filled, to make sure autofill kicked in.
  WaitForElementValue("username", "admin");
  WaitForElementValue("password", "12345");
}

// https://crbug.com/713645
// Navigate to a page that can't load some of the subresources. Create a hidden
// form when the body is loaded. Make the form visible. Chrome should autofill
// the form.
// The fact that the form is hidden isn't super important but reproduces the
// actual bug.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, SlowPageFill) {
  // At first let us save a credential to the password store.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.url = embedded_test_server()->base_url();
  signin_form.action = embedded_test_server()->base_url();
  signin_form.username_value = u"admin";
  signin_form.password_value = u"12345";
  password_store->AddLogin(signin_form);

  GURL url =
      embedded_test_server()->GetURL("/password/infinite_password_form.html");
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), url, WindowOpenDisposition::CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_NO_WAIT);

  // Wait for autofill.
  BubbleObserver bubble_observer(WebContents());
  bubble_observer.WaitForManagementState();

  // Show the form and make sure that the password was autofilled.
  std::string show_form =
      "document.getElementsByTagName('form')[0].style.display = 'block'";
  ASSERT_TRUE(content::ExecJs(WebContents(), show_form));

  CheckElementValue("username", "admin");
  CheckElementValue("password", "12345");
}

// Test that if there was no previous page load then the PasswordManagerDriver
// does not think that there were SSL errors on the current page. The test opens
// a new tab with a URL for which the embedded test server issues a basic auth
// challenge.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoLastLoadGoodLastLoad) {
  // We must use a new test server here because embedded_test_server() is
  // already started at this point and adding the request handler to it would
  // not be thread safe.
  net::EmbeddedTestServer http_test_server;

  // Teach the embedded server to handle requests by issuing the basic auth
  // challenge.
  http_test_server.RegisterRequestHandler(
      base::BindRepeating(&HandleTestAuthRequest));
  ASSERT_TRUE(http_test_server.Start());

  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());
  ASSERT_TRUE(password_store->IsEmpty());

  // Navigate to a page requiring HTTP auth.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), http_test_server.GetURL("/basic_auth")));
  ASSERT_TRUE(base::test::RunUntil(
      []() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));

  // Offer valid credentials on the auth challenge.
  ASSERT_EQ(1u, LoginHandler::GetAllLoginHandlersForTest().size());
  LoginHandler* handler = LoginHandler::GetAllLoginHandlersForTest().front();
  ASSERT_TRUE(handler);
  PasswordsNavigationObserver nav_observer(WebContents());
  // Any username/password will work.
  handler->SetAuth(u"user", u"pwd");

  // The password manager should be working correctly.
  ASSERT_TRUE(nav_observer.Wait());
  WaitForPasswordStore();
  BubbleObserver bubble_observer(WebContents());
  EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically());
  bubble_observer.AcceptSavePrompt();

  // Spin the message loop to make sure the password store had a chance to save
  // the password.
  WaitForPasswordStore();
  EXPECT_FALSE(password_store->IsEmpty());
}

// Fill out a form and click a button. The Javascript removes the form, creates
// a similar one with another action, fills it out and submits. Chrome can
// manage to detect the new one and create a complete matching
// PasswordFormManager. Otherwise, the all-but-action matching PFM should be
// used. Regardless of the internals the user sees the bubble in 100% cases.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PreferPasswordFormManagerWhichFinishedMatching) {
  NavigateToFile("/password/create_form_copy_on_submit.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string submit =
      "document.getElementById('username').value = 'overwrite_me';"
      "document.getElementById('password').value = 'random';"
      "document.getElementById('non-form-button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), submit));
  ASSERT_TRUE(observer.Wait());

  WaitForPasswordStore();
  prompt_observer.WaitForAutomaticSavePrompt();
}

// Tests whether a attempted submission of a malicious credentials gets blocked.
// This simulates a case which is described in http://crbug.com/571580.
IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    NoPromptForSeparateLoginFormWhenSwitchingFromHttpsToHttp) {
  std::string path = "/password/password_form.html";
  GURL https_url(https_test_server().GetURL(path));
  ASSERT_TRUE(https_url.SchemeIs(url::kHttpsScheme));

  PasswordsNavigationObserver form_observer(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), https_url));
  ASSERT_TRUE(form_observer.Wait());

  std::string fill_and_submit_redirect =
      "document.getElementById('username_redirect').value = 'user';"
      "document.getElementById('password_redirect').value = 'password';"
      "document.getElementById('submit_redirect').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit_redirect));

  PasswordsNavigationObserver redirect_observer(WebContents());
  redirect_observer.SetPathToWaitFor("/password/redirect.html");
  ASSERT_TRUE(redirect_observer.Wait());

  BubbleObserver prompt_observer(WebContents());
  prompt_observer.WaitForAutomaticSavePrompt();

  // Normally the redirect happens to done.html. Here an attack is simulated
  // that hijacks the redirect to a attacker controlled page.
  GURL http_url(
      embedded_test_server()->GetURL("/password/simple_password.html"));
  std::string attacker_redirect =
      "window.location.href = '" + http_url.spec() + "';";
  ASSERT_TRUE(content::ExecJs(RenderFrameHost(), attacker_redirect,
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));

  PasswordsNavigationObserver attacker_observer(WebContents());
  attacker_observer.SetPathToWaitFor("/password/simple_password.html");
  ASSERT_TRUE(attacker_observer.Wait());

  prompt_observer.WaitForAutomaticSavePrompt();

  std::string fill_and_submit_attacker_form =
      "document.getElementById('username_field').value = 'attacker_username';"
      "document.getElementById('password_field').value = 'attacker_password';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit_attacker_form));

  PasswordsNavigationObserver done_observer(WebContents());
  done_observer.SetPathToWaitFor("/password/done.html");
  ASSERT_TRUE(done_observer.Wait());

  prompt_observer.WaitForAutomaticSavePrompt();
  prompt_observer.AcceptSavePrompt();

  // Wait for password store and check that credentials are stored.
  WaitForPasswordStore();
  CheckThatCredentialsStored("user", "password");
}

// Tests that after HTTP -> HTTPS migration the credential is autofilled.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       HttpMigratedCredentialAutofilled) {
  // Add an http credential to the password store.
  GURL https_origin = https_test_server().base_url();
  ASSERT_TRUE(https_origin.SchemeIs(url::kHttpsScheme));
  GURL::Replacements rep;
  rep.SetSchemeStr(url::kHttpScheme);
  GURL http_origin = https_origin.ReplaceComponents(rep);
  password_manager::PasswordForm http_form;
  http_form.signon_realm = http_origin.spec();
  http_form.url = http_origin;
  // Assume that the previous action was already HTTPS one matching the current
  // page.
  http_form.action = https_origin;
  http_form.username_value = u"user";
  http_form.password_value = u"12345";
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_store->AddLogin(http_form);

  PasswordsNavigationObserver form_observer(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), https_test_server().GetURL("/password/password_form.html")));
  ASSERT_TRUE(form_observer.Wait());
  WaitForPasswordStore();

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling fields.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));
  WaitForElementValue("username_field", "user");
  WaitForElementValue("password_field", "12345");
}

// Tests that obsolete HTTP credentials are moved when a site migrated to HTTPS
// and has HSTS enabled.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       ObsoleteHttpCredentialMovedOnMigrationToHstsSite) {
  // Add an http credential to the password store.
  GURL https_origin = https_test_server().base_url();
  ASSERT_TRUE(https_origin.SchemeIs(url::kHttpsScheme));
  GURL::Replacements rep;
  rep.SetSchemeStr(url::kHttpScheme);
  GURL http_origin = https_origin.ReplaceComponents(rep);
  password_manager::PasswordForm http_form;
  http_form.signon_realm = http_origin.spec();
  http_form.url = http_origin;
  http_form.username_value = u"user";
  http_form.password_value = u"12345";
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());
  password_store->AddLogin(http_form);

  // Treat the host of the HTTPS test server as HSTS.
  AddHSTSHost(https_test_server().host_port_pair().host());

  // Navigate to HTTPS page and trigger the migration.
  PasswordsNavigationObserver form_observer(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), https_test_server().GetURL("/password/password_form.html")));
  ASSERT_TRUE(form_observer.Wait());

  // Issue the query for HTTPS credentials.
  WaitForPasswordStore();

  // Realize there are no HTTPS credentials and issue the query for HTTP
  // credentials instead.
  WaitForPasswordStore();

  // Sync with IO thread before continuing. This is necessary, because the
  // credential migration triggers a query for the HSTS state which gets
  // executed on the IO thread. The actual task is empty, because only the reply
  // is relevant. By the time the reply is executed it is guaranteed that the
  // migration is completed.
  base::RunLoop run_loop;
  content::GetIOThreadTaskRunner({})->PostTaskAndReply(
      FROM_HERE, base::BindOnce([]() {}), run_loop.QuitClosure());
  run_loop.Run();

  // Migration updates should touch the password store.
  WaitForPasswordStore();
  // Only HTTPS passwords should be present.
  EXPECT_THAT(password_store->stored_passwords(),
              ElementsAre(Pair(https_origin.spec(), SizeIs(1))));
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptWhenPasswordFormWithoutUsernameFieldSubmitted) {
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());

  EXPECT_TRUE(password_store->IsEmpty());

  NavigateToFile("/password/form_with_only_password_field.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string submit =
      "document.getElementById('password').value = 'password';"
      "document.getElementById('submit-button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), submit));
  ASSERT_TRUE(observer.Wait());

  prompt_observer.WaitForAutomaticSavePrompt();
  prompt_observer.AcceptSavePrompt();

  WaitForPasswordStore();
  EXPECT_FALSE(password_store->IsEmpty());
}

// Test that if a form gets autofilled, then it gets autofilled on re-creation
// as well.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ReCreatedFormsGetFilled) {
  // At first let us save a credential to the password store.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.url = embedded_test_server()->base_url();
  signin_form.action = embedded_test_server()->base_url();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"random";
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/dynamic_password_form.html");
  const std::string create_form =
      "document.getElementById('create_form_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), create_form));
  // Wait until the username is filled, to make sure autofill kicked in.
  WaitForElementValue("username_id", "temp");

  // Now the form gets deleted and created again. It should get autofilled
  // again.
  const std::string delete_form =
      "var form = document.getElementById('dynamic_form_id');"
      "form.parentNode.removeChild(form);";
  ASSERT_TRUE(content::ExecJs(WebContents(), delete_form));
  ASSERT_TRUE(content::ExecJs(WebContents(), create_form));
  WaitForElementValue("username_id", "temp");
}

// Test that if the same dynamic form is created multiple times then all of them
// are autofilled.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, DuplicateFormsGetFilled) {
  // At first let us save a credential to the password store.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.url = embedded_test_server()->base_url();
  signin_form.action = embedded_test_server()->base_url();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"random";
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/recurring_dynamic_form.html");
  ASSERT_TRUE(content::ExecJs(WebContents(), "addForm();"));
  // Wait until the username is filled, to make sure autofill kicked in.
  WaitForJsElementValue("document.body.children[0].children[0]", "temp");
  WaitForJsElementValue("document.body.children[0].children[1]", "random");

  // Add one more form.
  ASSERT_TRUE(content::ExecJs(WebContents(), "addForm();"));
  // Wait until the username is filled, to make sure autofill kicked in.
  WaitForJsElementValue("document.body.children[1].children[0]", "temp");
  WaitForJsElementValue("document.body.children[1].children[1]", "random");
}

// Test that an autofilled credential is deleted then the password manager
// doesn't try to resurrect it on navigation.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       DeletedPasswordIsNotRevived) {
  // At first let us save a credential to the password store.
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.url = embedded_test_server()->base_url();
  signin_form.action = embedded_test_server()->base_url();
  signin_form.username_value = u"admin";
  signin_form.password_value = u"1234";
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/password_form.html");
  // Let the user interact with the page.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));
  // Wait until that interaction causes the username and the password value to
  // be revealed.
  WaitForElementValue("username_field", "admin");

  // Now the credential is removed via the settings or the bubble.
  password_store->RemoveLogin(FROM_HERE, signin_form);
  WaitForPasswordStore();

  // Submit the form. It shouldn't revive the credential in the store.
  PasswordsNavigationObserver observer(WebContents());
  ASSERT_TRUE(content::ExecJs(
      WebContents(), "document.getElementById('input_submit_button').click()"));
  ASSERT_TRUE(observer.Wait());

  WaitForPasswordStore();
  EXPECT_TRUE(password_store->IsEmpty());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForPushStateWhenFormDisappears) {
  NavigateToFile("/password/password_push_state.html");

  // Verify that we show the save password prompt if 'history.pushState()'
  // is called after form submission is suppressed by, for example, calling
  // preventDefault() in a form's submit event handler.
  // Note that calling 'submit()' on a form with javascript doesn't call
  // the onsubmit handler, so we click the submit button instead.
  // Also note that the prompt will only show up if the form disappers
  // after submission
  PasswordsNavigationObserver observer(WebContents());
  observer.set_quit_on_entry_committed(true);
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

// Similar to the case above, but this time the form persists after
// 'history.pushState()'. And save password prompt should not show up
// in this case.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoPromptForPushStateWhenFormPersists) {
  NavigateToFile("/password/password_push_state.html");

  // Set |should_delete_testform| to false to keep submitted form visible after
  // history.pushsTate();
  PasswordsNavigationObserver observer(WebContents());
  observer.set_quit_on_entry_committed(true);
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "should_delete_testform = false;"
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

// The password manager should distinguish forms with empty actions. After
// successful login, the login form disappears, but the another one shouldn't be
// recognized as the login form. The save prompt should appear.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForPushStateWhenFormWithEmptyActionDisappears) {
  NavigateToFile("/password/password_push_state.html");

  PasswordsNavigationObserver observer(WebContents());
  observer.set_quit_on_entry_committed(true);
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('ea_username_field').value = 'temp';"
      "document.getElementById('ea_password_field').value = 'random';"
      "document.getElementById('ea_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

// Similar to the case above, but this time the form persists after
// 'history.pushState()'. The password manager should find the login form even
// if the action of the form is empty. Save password prompt should not show up.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForPushStateWhenFormWithEmptyActionPersists) {
  NavigateToFile("/password/password_push_state.html");

  PasswordsNavigationObserver observer(WebContents());
  observer.set_quit_on_entry_committed(true);
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "should_delete_testform = false;"
      "document.getElementById('ea_username_field').value = 'temp';"
      "document.getElementById('ea_password_field').value = 'random';"
      "document.getElementById('ea_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

// Current and target URLs contain different parameters and references. This
// test checks that parameters and references in origins are ignored for
// form origin comparison.
IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    PromptForPushStateWhenFormDisappears_ParametersInOrigins) {
  NavigateToFile("/password/password_push_state.html?login#r");

  PasswordsNavigationObserver observer(WebContents());
  observer.set_quit_on_entry_committed(true);
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "add_parameters_to_target_url = true;"
      "document.getElementById('pa_username_field').value = 'temp';"
      "document.getElementById('pa_password_field').value = 'random';"
      "document.getElementById('pa_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

// Similar to the case above, but this time the form persists after
// 'history.pushState()'. The password manager should find the login form even
// if target and current URLs contain different parameters or references.
// Save password prompt should not show up.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForPushStateWhenFormPersists_ParametersInOrigins) {
  NavigateToFile("/password/password_push_state.html?login#r");

  PasswordsNavigationObserver observer(WebContents());
  observer.set_quit_on_entry_committed(true);
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "should_delete_testform = false;"
      "add_parameters_to_target_url = true;"
      "document.getElementById('pa_username_field').value = 'temp';"
      "document.getElementById('pa_password_field').value = 'random';"
      "document.getElementById('pa_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerAutofillPopupBrowserTest,
                       InFrameNavigationDoesNotClearPopupState) {
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"random123";
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/password_form.html");
  // Trigger in page navigation.
  std::string in_page_navigate = "location.hash = '#blah';";
  ASSERT_TRUE(content::ExecJs(RenderFrameHost(), in_page_navigate,
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));

  // Click on the username field to display the popup.
  content::SimulateMouseClickOrTapElementWithId(WebContents(),
                                                "username_field");
  // Make sure that the popup is showing.
  autofill_client().WaitForAutofillPopup();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ChangePwdFormBubbleShown) {
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('chg_username_field').value = 'temp';"
      "document.getElementById('chg_password_field').value = 'random';"
      "document.getElementById('chg_new_password_1').value = 'random1';"
      "document.getElementById('chg_new_password_2').value = 'random1';"
      "document.getElementById('chg_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       ChangePwdFormPushStateBubbleShown) {
  NavigateToFile("/password/password_push_state.html");

  PasswordsNavigationObserver observer(WebContents());
  observer.set_quit_on_entry_committed(true);
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('chg_username_field').value = 'temp';"
      "document.getElementById('chg_password_field').value = 'random';"
      "document.getElementById('chg_new_password_1').value = 'random1';"
      "document.getElementById('chg_new_password_2').value = 'random1';"
      "document.getElementById('chg_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, NoPromptOnBack) {
  // Go to a successful landing page through submitting first, so that it is
  // reachable through going back, and the remembered page transition is form
  // submit. There is no need to submit non-empty strings.
  NavigateToFile("/password/password_form.html");

  PasswordsNavigationObserver dummy_submit_observer(WebContents());
  std::string just_submit =
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), just_submit));
  ASSERT_TRUE(dummy_submit_observer.Wait());

  // Now go to a page with a form again, fill the form, and go back instead of
  // submitting it.
  NavigateToFile("/password/dummy_submit.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  // The (dummy) submit is necessary to provisionally save the typed password.
  // A user typing in the password field would not need to submit to
  // provisionally save it, but the script cannot trigger that just by
  // assigning to the field's value.
  std::string fill_and_back =
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click();"
      "window.history.back();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_back));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}

// Regression test for http://crbug.com/452306
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       ChangingTextToPasswordFieldOnSignupForm) {
  NavigateToFile("/password/signup_form.html");

  // In this case, pretend that username_field is actually a password field
  // that starts as a text field to simulate placeholder.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string change_and_submit =
      "document.getElementById('other_info').value = 'username';"
      "document.getElementById('username_field').type = 'password';"
      "document.getElementById('username_field').value = 'mypass';"
      "document.getElementById('password_field').value = 'mypass';"
      "document.getElementById('testform').submit();";
  ASSERT_TRUE(content::ExecJs(WebContents(), change_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

// Regression test for http://crbug.com/451631
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       SavingOnManyPasswordFieldsTest) {
  // Simulate Macy's registration page, which contains the normal 2 password
  // fields for confirming the new password plus 2 more fields for security
  // questions and credit card. Make sure that saving works correctly for such
  // sites.
  NavigateToFile("/password/many_password_signup_form.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'username';"
      "document.getElementById('password_field').value = 'mypass';"
      "document.getElementById('confirm_field').value = 'mypass';"
      "document.getElementById('security_answer').value = 'hometown';"
      "document.getElementById('SSN').value = '1234';"
      "document.getElementById('testform').submit();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       SaveWhenIFrameDestroyedOnFormSubmit) {
  NavigateToFile("/password/frame_detached_on_submit.html");

  // Need to pay attention for a message that XHR has finished since there
  // is no navigation to wait for.
  content::DOMMessageQueue message_queue(WebContents());

  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "var iframe = document.getElementById('login_iframe');"
      "var frame_doc = iframe.contentDocument;"
      "frame_doc.getElementById('username_field').value = 'temp';"
      "frame_doc.getElementById('password_field').value = 'random';"
      "frame_doc.getElementById('submit_button').click();";

  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  std::string message;
  while (message_queue.WaitForMessage(&message)) {
    if (message == "\"SUBMISSION_FINISHED\"") {
      break;
    }
  }

  prompt_observer.WaitForAutomaticSavePrompt();
}

// TODO(crbug.com/360035859): Fix and re-enable.
IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    DISABLED_IFrameDetachedRightAfterFormSubmission_UpdateBubbleShown) {
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.password_value = u"pw";
  signin_form.username_value = u"temp";
  password_store->AddLogin(signin_form);
  WaitForPasswordStore();

  NavigateToFile("/password/frame_detached_after_submit.html");

  content::RenderFrameHost* iframe_rfh = nullptr;
  RenderFrameHost()->ForEachRenderFrameHost([&](content::RenderFrameHost* rfh) {
    if (!rfh->IsInPrimaryMainFrame()) {
      iframe_rfh = rfh;
      return;
    }
  });
  ASSERT_TRUE(iframe_rfh);

  BubbleObserver prompt_observer(WebContents());
  content::RenderFrameDeletedObserver iframe_observer(iframe_rfh);
  std::string fill_and_submit =
      "var iframe = document.getElementById('password_reset_iframe');"
      "var frame_doc = iframe.contentDocument;"
      "frame_doc.getElementById('password_field').value = 'random';"
      "frame_doc.getElementById('confirm_password_field').value = 'random';"
      "frame_doc.getElementById('input_submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(iframe_observer.WaitUntilDeleted());

  prompt_observer.WaitForAutomaticUpdatePrompt();
  prompt_observer.WaitForAutomaticUpdatePrompt();
}

// Check that a username and password are filled into forms in iframes
// that don't share the security origin with the main frame, but have PSL
// matched origins.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PSLMatchedCrossSiteFillTest) {
  GURL main_frame_url = embedded_test_server()->GetURL(
      "www.foo.com", "/password/password_form_in_crosssite_iframe.html");
  PasswordsNavigationObserver observer(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url));
  ASSERT_TRUE(observer.Wait());

  // Create an iframe and navigate cross-site.
  PasswordsNavigationObserver iframe_observer(WebContents());
  iframe_observer.SetPathToWaitFor("/password/crossite_iframe_content.html");
  GURL iframe_url = embedded_test_server()->GetURL(
      "abc.foo.com", "/password/crossite_iframe_content.html");
  std::string create_iframe =
      base::StringPrintf("create_iframe('%s');", iframe_url.spec().c_str());
  ASSERT_TRUE(content::ExecJs(RenderFrameHost(), create_iframe,
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  ASSERT_TRUE(iframe_observer.Wait());

  // Store a password for autofill later.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = iframe_url.DeprecatedGetOriginAsURL().spec();
  signin_form.url = iframe_url;
  signin_form.username_value = u"temp";
  signin_form.password_value = u"pa55w0rd";
  password_store->AddLogin(signin_form);
  WaitForPasswordStore();

  // Visit the form again.
  PasswordsNavigationObserver reload_observer(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url));
  ASSERT_TRUE(reload_observer.Wait());

  PasswordsNavigationObserver iframe_observer_2(WebContents());
  iframe_observer_2.SetPathToWaitFor("/password/crossite_iframe_content.html");
  ASSERT_TRUE(content::ExecJs(RenderFrameHost(), create_iframe,
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  ASSERT_TRUE(iframe_observer_2.Wait());

  // Simulate the user interaction in the iframe which should trigger autofill.
  // Click in the middle of the frame to avoid the border.
  content::SimulateMouseClickOrTapElementWithId(WebContents(), "iframe");

  // Verify username and password have not been autofilled due to an insecure
  // origin.
  EXPECT_TRUE(content::EvalJs(RenderFrameHost(), "sendMessage('get_username');",
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE)
                  .ExtractString()
                  .empty());

  EXPECT_TRUE(content::EvalJs(RenderFrameHost(), "sendMessage('get_password');",
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE)
                  .ExtractString()
                  .empty());
}

// Check that a username and password are not filled in forms in iframes
// that don't have PSL matched origins.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PSLUnMatchedCrossSiteFillTest) {
  GURL main_frame_url = embedded_test_server()->GetURL(
      "www.foo.com", "/password/password_form_in_crosssite_iframe.html");
  PasswordsNavigationObserver observer(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url));
  ASSERT_TRUE(observer.Wait());

  // Create an iframe and navigate cross-site.
  PasswordsNavigationObserver iframe_observer(WebContents());
  iframe_observer.SetPathToWaitFor("/password/crossite_iframe_content.html");
  GURL iframe_url = embedded_test_server()->GetURL(
      "www.bar.com", "/password/crossite_iframe_content.html");
  std::string create_iframe =
      base::StringPrintf("create_iframe('%s');", iframe_url.spec().c_str());
  ASSERT_TRUE(content::ExecJs(RenderFrameHost(), create_iframe,
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  ASSERT_TRUE(iframe_observer.Wait());

  // Store a password for autofill later.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = iframe_url.DeprecatedGetOriginAsURL().spec();
  signin_form.url = iframe_url;
  signin_form.username_value = u"temp";
  signin_form.password_value = u"pa55w0rd";
  password_store->AddLogin(signin_form);
  WaitForPasswordStore();

  // Visit the form again.
  PasswordsNavigationObserver reload_observer(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url));
  ASSERT_TRUE(reload_observer.Wait());

  PasswordsNavigationObserver iframe_observer_2(WebContents());
  iframe_observer_2.SetPathToWaitFor("/password/crossite_iframe_content.html");
  ASSERT_TRUE(content::ExecJs(RenderFrameHost(), create_iframe,
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  ASSERT_TRUE(iframe_observer_2.Wait());

  // Simulate the user interaction in the iframe which should trigger autofill.
  // Click in the middle of the frame to avoid the border.
  content::SimulateMouseClickOrTapElementWithId(WebContents(), "iframe");

  // Verify username is not autofilled
  EXPECT_EQ("",
            content::EvalJs(RenderFrameHost(), "sendMessage('get_username');",
                            content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  // Verify password is not autofilled
  EXPECT_EQ("",
            content::EvalJs(RenderFrameHost(), "sendMessage('get_password');",
                            content::EXECUTE_SCRIPT_NO_USER_GESTURE));
}

// Check that a password form in an iframe of same origin will not be
// filled in until user interact with the iframe.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       SameOriginIframeAutoFillTest) {
  // Visit the sign-up form to store a password for autofill later
  NavigateToFile("/password/password_form_in_same_origin_iframe.html");
  PasswordsNavigationObserver observer(WebContents());
  observer.SetPathToWaitFor("/password/done.html");

  std::string submit =
      "var ifrmDoc = document.getElementById('iframe').contentDocument;"
      "ifrmDoc.getElementById('username_field').value = 'temp';"
      "ifrmDoc.getElementById('password_field').value = 'pa55w0rd';"
      "ifrmDoc.getElementById('input_submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), submit));
  ASSERT_TRUE(observer.Wait());
  BubbleObserver prompt_observer(WebContents());
  prompt_observer.WaitForAutomaticSavePrompt();
  prompt_observer.AcceptSavePrompt();

  // Visit the form again
  PasswordsNavigationObserver reload_observer(WebContents());
  NavigateToFile("/password/password_form_in_same_origin_iframe.html");
  ASSERT_TRUE(reload_observer.Wait());

  // Verify password and username are not accessible yet.
  CheckElementValue("iframe", "username_field", "");
  CheckElementValue("iframe", "password_field", "");

  // Simulate the user interaction in the iframe which should trigger autofill.
  // Click in the middle of the username to avoid the border.
  ASSERT_TRUE(content::ExecJs(
      RenderFrameHost(),
      "var usernameRect = document.getElementById("
      "'iframe').contentDocument.getElementById('username_field')"
      ".getBoundingClientRect();",
      content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  int y =
      content::EvalJs(RenderFrameHost(),
                      "Math.floor(usernameRect.top + usernameRect.height / 2)",
                      content::EXECUTE_SCRIPT_NO_USER_GESTURE)
          .ExtractInt();
  int x =
      content::EvalJs(RenderFrameHost(),
                      "Math.floor(usernameRect.left + usernameRect.width / 2)",
                      content::EXECUTE_SCRIPT_NO_USER_GESTURE)
          .ExtractInt();

  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(x, y));
  // Verify username and password have been autofilled
  WaitForElementValue("iframe", "username_field", "temp");
  WaitForElementValue("iframe", "password_field", "pa55w0rd");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ChangePwdNoAccountStored) {
  NavigateToFile("/password/password_form.html");

  // Fill a form and submit through a <input type="submit"> button.
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());

  std::string fill_and_submit =
      "document.getElementById('chg_password_wo_username_field').value = "
      "'old_pw';"
      "document.getElementById('chg_new_password_wo_username_1').value = "
      "'new_pw';"
      "document.getElementById('chg_new_password_wo_username_2').value = "
      "'new_pw';"
      "document.getElementById('chg_submit_wo_username_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  // No credentials stored before, so save bubble is shown.
  prompt_observer.WaitForAutomaticSavePrompt();
  prompt_observer.AcceptSavePrompt();

  // Check that credentials are stored.
  WaitForPasswordStore();
  CheckThatCredentialsStored("", "new_pw");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ChangePwd1AccountStored) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.password_value = u"pw";
  signin_form.username_value = u"temp";
  password_store->AddLogin(signin_form);

  // Check that password update bubble is shown.
  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit_change_password =
      "document.getElementById('chg_password_wo_username_field').value = "
      "'random';"
      "document.getElementById('chg_new_password_wo_username_1').value = "
      "'new_pw';"
      "document.getElementById('chg_new_password_wo_username_2').value = "
      "'new_pw';"
      "document.getElementById('chg_submit_wo_username_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit_change_password));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticUpdatePrompt();

  // We emulate that the user clicks "Update" button.
  prompt_observer.AcceptUpdatePrompt();

  WaitForPasswordStore();
  CheckThatCredentialsStored("temp", "new_pw");
}

// This fixture disable autofill. If a password is autofilled, then all the
// Javascript changes are discarded and test below would not be able to feed a
// new password to the form.
class PasswordManagerBrowserTestWithAutofillDisabled
    : public PasswordManagerBrowserTest {
 public:
  PasswordManagerBrowserTestWithAutofillDisabled() {
    feature_list_.InitAndEnableFeature(features::kFillOnAccountSelect);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithAutofillDisabled,
                       PasswordOverriddenUpdateBubbleShown) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"pw";
  password_store->AddLogin(signin_form);

  // Check that password update bubble is shown.
  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'new_pw';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  // The stored password "pw" was overridden with "new_pw", so update prompt is
  // expected.
  prompt_observer.WaitForAutomaticUpdatePrompt();

  prompt_observer.AcceptUpdatePrompt();
  WaitForPasswordStore();
  CheckThatCredentialsStored("temp", "new_pw");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PasswordNotOverriddenUpdateBubbleNotShown) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"pw";
  password_store->AddLogin(signin_form);

  // Check that password update bubble is shown.
  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'pw';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  // The stored password "pw" was not overridden, so update prompt is not
  // expected.
  EXPECT_FALSE(prompt_observer.IsUpdatePromptShownAutomatically());
  CheckThatCredentialsStored("temp", "pw");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       MultiplePasswordsWithPasswordSelectionEnabled) {
  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  // It is important that these 3 passwords are different. Because if two of
  // them are the same, it is going to be treated as a password update and the
  // dropdown will not be shown.
  std::string fill_and_submit =
      "document.getElementById('chg_password_wo_username_field').value = "
      "'pass1';"
      "document.getElementById('chg_new_password_wo_username_1').value = "
      "'pass2';"
      "document.getElementById('chg_new_password_wo_username_2').value = "
      "'pass3';"
      "document.getElementById('chg_submit_wo_username_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  // 3 possible passwords are going to be shown in a dropdown when the password
  // selection feature is enabled. The first one will be selected as the main
  // password by default. All three will be in the |all_alternative_passwords|
  // list. The save password prompt is expected.
  BubbleObserver bubble_observer(WebContents());
  bubble_observer.WaitForAutomaticSavePrompt();
  EXPECT_EQ(u"pass1",
            ManagePasswordsUIController::FromWebContents(WebContents())
                ->GetPendingPassword()
                .password_value);
  EXPECT_THAT(
      ManagePasswordsUIController::FromWebContents(WebContents())
          ->GetPendingPassword()
          .all_alternative_passwords,
      ElementsAre(AllOf(Field("value", &AlternativeElement::value, u"pass1"),
                        Field("name", &AlternativeElement::name,
                              u"chg_password_wo_username_field")),
                  AllOf(Field("value", &AlternativeElement::value, u"pass2"),
                        Field("name", &AlternativeElement::name,
                              u"chg_new_password_wo_username_1")),
                  AllOf(Field("value", &AlternativeElement::value, u"pass3"),
                        Field("name", &AlternativeElement::name,
                              u"chg_new_password_wo_username_2"))));
  bubble_observer.AcceptSavePrompt();
  WaitForPasswordStore();
  CheckThatCredentialsStored("", "pass1");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       ChangePwdWhenTheFormContainNotUsernameTextfield) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.password_value = u"pw";
  signin_form.username_value = u"temp";
  password_store->AddLogin(signin_form);

  // Check that password update bubble is shown.
  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit_change_password =
      "document.getElementById('chg_text_field').value = '3';"
      "document.getElementById('chg_password_withtext_field').value"
      " = 'random';"
      "document.getElementById('chg_new_password_withtext_username_1').value"
      " = 'new_pw';"
      "document.getElementById('chg_new_password_withtext_username_2').value"
      " = 'new_pw';"
      "document.getElementById('chg_submit_withtext_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit_change_password));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticUpdatePrompt();

  prompt_observer.AcceptUpdatePrompt();
  WaitForPasswordStore();
  CheckThatCredentialsStored("temp", "new_pw");
}

// Test whether the password form with the username and password fields having
// ambiguity in id attribute gets autofilled correctly.
IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    AutofillSuggestionsForPasswordFormWithAmbiguousIdAttribute) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm login_form;
  login_form.signon_realm = embedded_test_server()->base_url().spec();
  login_form.action = embedded_test_server()->GetURL("/password/done.html");
  login_form.username_value = u"myusername";
  login_form.password_value = u"mypassword";
  password_store->AddLogin(login_form);

  // Now, navigate to the password form having ambiguous Ids for username and
  // password fields and verify whether username and password is autofilled.
  NavigateToFile("/password/ambiguous_password_form.html");

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling fields.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  WaitForElementValue("ambiguous_form", 0 /* elements_index */, "myusername");
  WaitForElementValue("ambiguous_form", 1 /* elements_index */, "mypassword");
}

// Test whether the password form having username and password fields without
// name and id attribute gets autofilled correctly.
IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    AutofillSuggestionsForPasswordFormWithoutNameOrIdAttribute) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm login_form;
  login_form.signon_realm = embedded_test_server()->base_url().spec();
  login_form.action = embedded_test_server()->GetURL("/password/done.html");
  login_form.username_value = u"myusername";
  login_form.password_value = u"mypassword";
  password_store->AddLogin(login_form);

  // Now, navigate to the password form having no Ids for username and password
  // fields and verify whether username and password is autofilled.
  NavigateToFile("/password/ambiguous_password_form.html");

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling fields.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  WaitForElementValue("no_name_id_form", 0 /* elements_index */, "myusername");
  WaitForElementValue("no_name_id_form", 1 /* elements_index */, "mypassword");
}

// Test whether the change password form having username and password fields
// without name and id attribute gets autofilled correctly.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       AutofillSuggestionsForChangePwdWithEmptyNames) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm login_form;
  login_form.signon_realm = embedded_test_server()->base_url().spec();
  login_form.action = embedded_test_server()->GetURL("/password/done.html");
  login_form.username_value = u"myusername";
  login_form.password_value = u"mypassword";
  password_store->AddLogin(login_form);

  // Now, navigate to the password form having no Ids for username and password
  // fields and verify whether username and password is autofilled.
  NavigateToFile("/password/ambiguous_password_form.html");

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling fields.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  WaitForElementValue("change_pwd_but_no_autocomplete", 0 /* elements_index */,
                      "myusername");
  WaitForElementValue("change_pwd_but_no_autocomplete", 1 /* elements_index */,
                      "mypassword");

  std::string get_new_password =
      "document.getElementById("
      "  'change_pwd_but_no_autocomplete').elements[2].value;";
  EXPECT_EQ("", content::EvalJs(RenderFrameHost(), get_new_password,
                                content::EXECUTE_SCRIPT_NO_USER_GESTURE));
}

// Test whether the change password form having username and password fields
// with empty names but having |autocomplete='current-password'| gets autofilled
// correctly.
IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    AutofillSuggestionsForChangePwdWithEmptyNamesAndAutocomplete) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm login_form;
  login_form.signon_realm = embedded_test_server()->base_url().spec();
  login_form.action = embedded_test_server()->GetURL("/password/done.html");
  login_form.username_value = u"myusername";
  login_form.password_value = u"mypassword";
  password_store->AddLogin(login_form);

  // Now, navigate to the password form having no Ids for username and password
  // fields and verify whether username and password is autofilled.
  NavigateToFile("/password/ambiguous_password_form.html");

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling fields.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  WaitForElementValue("change_pwd", 0 /* elements_index */, "myusername");
  WaitForElementValue("change_pwd", 1 /* elements_index */, "mypassword");

  std::string get_new_password =
      "document.getElementById('change_pwd').elements[2].value;";
  EXPECT_EQ("", content::EvalJs(RenderFrameHost(), get_new_password,
                                content::EXECUTE_SCRIPT_NO_USER_GESTURE));
}

// Test whether the change password form having username and password fields
// with empty names but having only new password fields having
// |autocomplete='new-password'| atrribute do not get autofilled.
IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    AutofillSuggestionsForChangePwdWithEmptyNamesButOnlyNewPwdField) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm login_form;
  login_form.signon_realm = embedded_test_server()->base_url().spec();
  login_form.action = embedded_test_server()->GetURL("/password/done.html");
  login_form.username_value = u"myusername";
  login_form.password_value = u"mypassword";
  password_store->AddLogin(login_form);

  // Now, navigate to the password form having no Ids for username and password
  // fields and verify whether username and password is autofilled.
  NavigateToFile("/password/ambiguous_password_form.html");

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling fields.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  std::string get_username =
      "document.getElementById("
      "  'change_pwd_but_no_old_pwd').elements[0].value;";
  EXPECT_EQ("", content::EvalJs(RenderFrameHost(), get_username,
                                content::EXECUTE_SCRIPT_NO_USER_GESTURE));

  std::string get_new_password =
      "document.getElementById("
      "  'change_pwd_but_no_old_pwd').elements[1].value;";
  EXPECT_EQ("", content::EvalJs(RenderFrameHost(), get_new_password,
                                content::EXECUTE_SCRIPT_NO_USER_GESTURE));

  std::string get_retype_password =
      "document.getElementById("
      "  'change_pwd_but_no_old_pwd').elements[2].value;";
  EXPECT_EQ("", content::EvalJs(RenderFrameHost(), get_retype_password,
                                content::EXECUTE_SCRIPT_NO_USER_GESTURE));
}

// When there are multiple HttpAuthObservers (e.g., multiple HTTP auth dialogs
// as in http://crbug.com/537823), ensure that credentials from PasswordStore
// distributed to them are filtered by the realm.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, BasicAuthSeparateRealms) {
  // We must use a new test server here because embedded_test_server() is
  // already started at this point and adding the request handler to it would
  // not be thread safe.
  net::EmbeddedTestServer http_test_server;
  http_test_server.RegisterRequestHandler(
      base::BindRepeating(&HandleTestAuthRequest));
  ASSERT_TRUE(http_test_server.Start());

  // Save credentials for "test realm" in the store.
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());
  password_manager::PasswordForm creds;
  creds.scheme = password_manager::PasswordForm::Scheme::kBasic;
  creds.signon_realm = http_test_server.base_url().spec() + "test realm";
  creds.password_value = u"pw";
  creds.username_value = u"temp";
  password_store->AddLogin(creds);
  WaitForPasswordStore();
  ASSERT_FALSE(password_store->IsEmpty());

  // In addition to the HttpAuthObserver created automatically for the HTTP
  // auth dialog, also create a mock observer, for a different realm.
  MockHttpAuthObserver mock_login_model_observer;
  HttpAuthManager* httpauth_manager =
      ChromePasswordManagerClient::FromWebContents(WebContents())
          ->GetHttpAuthManager();
  password_manager::PasswordForm other_form(creds);
  other_form.signon_realm = "https://example.com/other realm";
  httpauth_manager->SetObserverAndDeliverCredentials(&mock_login_model_observer,
                                                     other_form);
  // The mock observer should not receive the stored credentials.
  EXPECT_CALL(mock_login_model_observer, OnAutofillDataAvailable(_, _))
      .Times(0);

  // Now wait until the navigation to the test server causes a HTTP auth dialog
  // to appear.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), http_test_server.GetURL("/basic_auth")));
  ASSERT_TRUE(base::test::RunUntil(
      []() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));

  // The auth dialog caused a query to PasswordStore, make sure it was
  // processed.
  WaitForPasswordStore();

  httpauth_manager->DetachObserver(&mock_login_model_observer);
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ProxyAuthFilling) {
  GURL test_page = embedded_test_server()->GetURL("/auth-basic");

  // Save credentials for "testrealm" in the store.
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());
  password_manager::PasswordForm creds;
  creds.scheme = password_manager::PasswordForm::Scheme::kBasic;
  creds.url = test_page;
  creds.signon_realm = embedded_test_server()->base_url().spec() + "testrealm";
  creds.password_value = u"pw";
  creds.username_value = u"temp";
  password_store->AddLogin(creds);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page));
  ASSERT_TRUE(base::test::RunUntil(
      []() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));

  BubbleObserver(WebContents()).WaitForManagementState();
}

// Test whether the password form which is loaded as hidden is autofilled
// correctly. This happens very often in situations when in order to sign-in the
// user clicks a sign-in button and a hidden passsword form becomes visible.
// This test differs from AutofillSuggestionsForProblematicPasswordForm in that
// the form is hidden and in that test only some fields are hidden.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       AutofillSuggestionsHiddenPasswordForm) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm login_form;
  login_form.signon_realm = embedded_test_server()->base_url().spec();
  login_form.action = embedded_test_server()->GetURL("/password/done.html");
  login_form.username_value = u"myusername";
  login_form.password_value = u"mypassword";
  password_store->AddLogin(login_form);

  // Now, navigate to the hidden password form and verify whether username and
  // password is autofilled.
  NavigateToFile("/password/password_form.html");

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling the password.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  WaitForElementValue("hidden_password_form_username", "myusername");
  WaitForElementValue("hidden_password_form_password", "mypassword");
}

// Test whether the password form with the problematic invisible password field
// gets autofilled correctly.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       AutofillSuggestionsForProblematicPasswordForm) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm login_form;
  login_form.signon_realm = embedded_test_server()->base_url().spec();
  login_form.action = embedded_test_server()->GetURL("/password/done.html");
  login_form.username_value = u"myusername";
  login_form.password_value = u"mypassword";
  password_store->AddLogin(login_form);

  // Now, navigate to the password form with a hidden password field and verify
  // whether username and password is autofilled.
  NavigateToFile("/password/password_form.html");

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling the password.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  WaitForElementValue("form_with_hidden_password_username", "myusername");
  WaitForElementValue("form_with_hidden_password_password", "mypassword");
}

// Test whether the password form with the problematic invisible password field
// in ambiguous password form gets autofilled correctly.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       AutofillSuggestionsForProblematicAmbiguousPasswordForm) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm login_form;
  login_form.signon_realm = embedded_test_server()->base_url().spec();
  login_form.action = embedded_test_server()->GetURL("/password/done.html");
  login_form.username_value = u"myusername";
  login_form.password_value = u"mypassword";
  password_store->AddLogin(login_form);

  // Now, navigate to the password form having ambiguous Ids for username and
  // password fields and verify whether username and password is autofilled.
  NavigateToFile("/password/ambiguous_password_form.html");

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling fields.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  WaitForElementValue("hidden_password_form", 0 /* elements_index */,
                      "myusername");
  WaitForElementValue("hidden_password_form", 2 /* elements_index */,
                      "mypassword");
}

// Check that the internals page contains logs from the renderer.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       DISABLED_InternalsPage_Renderer) {
  // The test is flaky with same-site back/forward cache (which is enabled by
  // default).
  // TODO(crbug.com/40808799): Investigate and fix this.
  content::DisableBackForwardCacheForTesting(
      WebContents(), content::BackForwardCache::TEST_REQUIRES_NO_CACHING);

  // Open the internals page.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL("chrome://password-manager-internals"),
      WindowOpenDisposition::CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  content::WebContents* internals_web_contents = WebContents();

  // The renderer is supposed to ask whether logging is available. To avoid
  // race conditions between the answer "Logging is available" arriving from
  // the browser and actual logging callsites reached in the renderer, open
  // first an arbitrary page to ensure that the renderer queries the
  // availability of logging and has enough time to receive the answer.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), embedded_test_server()->GetURL("/password/done.html"),
      WindowOpenDisposition::NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  content::WebContents* forms_web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Now navigate to another page, containing some forms, so that the renderer
  // attempts to log. It should be a different page than the current one,
  // because just reloading the current one sometimes confused the Wait() call
  // and lead to timeouts (https://crbug.com/804398).
  PasswordsNavigationObserver observer(forms_web_contents);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), embedded_test_server()->GetURL("/password/password_form.html"),
      WindowOpenDisposition::CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  ASSERT_TRUE(observer.Wait());

  std::string find_logs =
      "var text = document.getElementById('log-entries').innerText;"
      "var logs_found = /PasswordAutofillAgent::/.test(text);"
      "logs_found;";
  EXPECT_EQ(true, content::EvalJs(internals_web_contents->GetPrimaryMainFrame(),
                                  find_logs,
                                  content::EXECUTE_SCRIPT_NO_USER_GESTURE));
}

// Check that the internals page contains logs from the browser.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, InternalsPage_Browser) {
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL("chrome://password-manager-internals"),
      WindowOpenDisposition::CURRENT_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  content::WebContents* internals_web_contents = WebContents();

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), embedded_test_server()->GetURL("/password/password_form.html"),
      WindowOpenDisposition::NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  std::string find_logs =
      "var text = document.getElementById('log-entries').innerText;"
      "var logs_found = /PasswordManager::/.test(text);"
      "logs_found;";
  EXPECT_EQ(true, content::EvalJs(internals_web_contents->GetPrimaryMainFrame(),
                                  find_logs,
                                  content::EXECUTE_SCRIPT_NO_USER_GESTURE));
}

// Tests that submitted credentials are saved on a password form without
// username element when there are no stored credentials.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PasswordRetryFormSaveNoUsernameCredentials) {
  // Check that password save bubble is shown.
  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('retry_password_field').value = 'pw';"
      "document.getElementById('retry_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
  prompt_observer.AcceptSavePrompt();

  WaitForPasswordStore();
  CheckThatCredentialsStored("", "pw");
}

// Tests that no bubble shown when a password form without username submitted
// and there is stored credentials with the same password.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PasswordRetryFormNoBubbleWhenPasswordTheSame) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"pw";
  password_store->AddLogin(signin_form);
  signin_form.username_value = u"temp1";
  signin_form.password_value = u"pw1";
  password_store->AddLogin(signin_form);

  // Check that no password bubble is shown when the submitted password is the
  // same in one of the stored credentials.
  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('retry_password_field').value = 'pw';"
      "document.getElementById('retry_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
  EXPECT_FALSE(prompt_observer.IsUpdatePromptShownAutomatically());
}

// Tests that the update bubble shown when a password form without username is
// submitted and there are stored credentials but with different password.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PasswordRetryFormUpdateBubbleShown) {
  // At first let us save credentials to the PasswordManager.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"pw";
  password_store->AddLogin(signin_form);

  // Check that password update bubble is shown.
  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('retry_password_field').value = 'new_pw';"
      "document.getElementById('retry_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  // The new password "new_pw" is used, so update prompt is expected.
  prompt_observer.WaitForAutomaticUpdatePrompt();

  prompt_observer.AcceptUpdatePrompt();

  WaitForPasswordStore();
  CheckThatCredentialsStored("temp", "new_pw");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoCrashWhenNavigatingWithOpenAccountPicker) {
  // Save credentials with 'skip_zero_click'.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.password_value = u"password";
  signin_form.username_value = u"user";
  signin_form.url = embedded_test_server()->base_url();
  signin_form.skip_zero_click = true;
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/password_form.html");

  // Call the API to trigger the notification to the client, which raises the
  // account picker dialog.
  ASSERT_TRUE(content::ExecJs(WebContents(),
                              "navigator.credentials.get({password: true})",
                              content::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));

  // Navigate while the picker is open.
  NavigateToFile("/password/password_form.html");

  // No crash!
}

// Tests that the prompt to save the password is still shown if the fields have
// the "autocomplete" attribute set off.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       PromptForSubmitWithAutocompleteOff) {
  NavigateToFile("/password/password_autocomplete_off_test.html");

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username').value = 'temp';"
      "document.getElementById('password').value = 'random';"
      "document.getElementById('submit').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(
    PasswordManagerBrowserTest,
    SkipZeroClickNotToggledAfterSuccessfulSubmissionWithAPI) {
  // Save credentials with 'skip_zero_click'
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.password_value = u"password";
  signin_form.username_value = u"user";
  signin_form.url = embedded_test_server()->base_url();
  signin_form.skip_zero_click = true;
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/password_form.html");

  // Call the API to trigger the notification to the client.
  ASSERT_TRUE(content::ExecJs(
      WebContents(),
      "navigator.credentials.get({password: true, unmediated: true })",
      content::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit_change_password =
      "document.getElementById('username_field').value = 'user';"
      "document.getElementById('password_field').value = 'password';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit_change_password));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());

  // Verify that the form's 'skip_zero_click' is not updated.
  auto& passwords_map = password_store->stored_passwords();
  ASSERT_EQ(1u, passwords_map.size());
  auto& passwords_vector = passwords_map.begin()->second;
  ASSERT_EQ(1u, passwords_vector.size());
  const password_manager::PasswordForm& form = passwords_vector[0];
  EXPECT_EQ(u"user", form.username_value);
  EXPECT_EQ(u"password", form.password_value);
  EXPECT_TRUE(form.skip_zero_click);
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       SkipZeroClickNotToggledAfterSuccessfulAutofill) {
  // Save credentials with 'skip_zero_click'
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.password_value = u"password";
  signin_form.username_value = u"user";
  signin_form.url = embedded_test_server()->base_url();
  signin_form.skip_zero_click = true;
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/password_form.html");

  // No API call.

  PasswordsNavigationObserver observer(WebContents());
  BubbleObserver prompt_observer(WebContents());
  std::string fill_and_submit_change_password =
      "document.getElementById('username_field').value = 'user';"
      "document.getElementById('password_field').value = 'password';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit_change_password));
  ASSERT_TRUE(observer.Wait());
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());

  // Verify that the form's 'skip_zero_click' is not updated.
  auto& passwords_map = password_store->stored_passwords();
  ASSERT_EQ(1u, passwords_map.size());
  auto& passwords_vector = passwords_map.begin()->second;
  ASSERT_EQ(1u, passwords_vector.size());
  const password_manager::PasswordForm& form = passwords_vector[0];
  EXPECT_EQ(u"user", form.username_value);
  EXPECT_EQ(u"password", form.password_value);
  EXPECT_TRUE(form.skip_zero_click);
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ReattachWebContents) {
  auto detached_web_contents = content::WebContents::Create(
      content::WebContents::CreateParams(WebContents()->GetBrowserContext()));
  PasswordsNavigationObserver observer(detached_web_contents.get());
  detached_web_contents->GetController().LoadURL(
      embedded_test_server()->GetURL("/password/multi_frames.html"),
      content::Referrer(), ::ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string());
  ASSERT_TRUE(observer.Wait());
  // Ensure that there is at least one more frame created than just the main
  // frame.
  EXPECT_LT(1u,
            CollectAllRenderFrameHosts(detached_web_contents->GetPrimaryPage())
                .size());

  auto* tab_strip_model = browser()->tab_strip_model();
  // Check that the autofill and password manager driver factories are notified
  // about all frames, not just the main one. The factories should receive
  // messages for non-main frames, in particular
  // AutofillHostMsg_PasswordFormsParsed. If that were the first time the
  // factories hear about such frames, this would crash.
  tab_strip_model->AddWebContents(std::move(detached_web_contents), -1,
                                  ::ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
                                  AddTabTypes::ADD_ACTIVE);
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       FillWhenFormWithHiddenUsername) {
  // At first let us save a credential to the password store.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.url = embedded_test_server()->base_url();
  signin_form.username_value = u"current_username";
  signin_form.password_value = u"current_username_password";
  password_store->AddLogin(signin_form);
  signin_form.username_value = u"last_used_username";
  signin_form.password_value = u"last_used_password";
  signin_form.date_last_used = base::Time::Now();
  password_store->AddLogin(signin_form);

  NavigateToFile("/password/hidden_username.html");

  // Let the user interact with the page.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  // current_username is hardcoded in the invisible text on the page so
  // current_username_password should be filled rather than last_used_password.
  WaitForElementValue("password", "current_username_password");
}

// Harness for showing dialogs as part of the DialogBrowserTest suite.
// Test params:
//  - bool popup_views_enabled: whether feature AutofillExpandedPopupViews
//        is enabled for testing.
class PasswordManagerDialogBrowserTest
    : public SupportsTestDialog<PasswordManagerBrowserTestBase> {
 public:
  PasswordManagerDialogBrowserTest() = default;

  PasswordManagerDialogBrowserTest(const PasswordManagerDialogBrowserTest&) =
      delete;
  PasswordManagerDialogBrowserTest& operator=(
      const PasswordManagerDialogBrowserTest&) = delete;

  void ShowUi(const std::string& name) override {
    // Note regarding flakiness: LocationBarBubbleDelegateView::ShowForReason()
    // uses ShowInactive() unless the bubble is invoked with reason ==
    // USER_GESTURE. This means that, so long as these dialogs are not triggered
    // by gesture, the dialog does not attempt to take focus, and so should
    // never _lose_ focus in the test, which could cause flakes when tests are
    // run in parallel. LocationBarBubbles also dismiss on other events, but
    // only events in the WebContents. E.g. Rogue mouse clicks should not cause
    // the dialog to dismiss since they won't be sent via WebContents.
    // A user gesture is determined in browser_commands.cc by checking
    // ManagePasswordsUIController::IsAutomaticallyOpeningBubble(), but that's
    // set and cleared immediately while showing the bubble, so it can't be
    // checked here.
    NavigateToFile("/password/password_form.html");
    PasswordsNavigationObserver observer(WebContents());
    std::string fill_and_submit =
        "document.getElementById('username_field').value = 'temp';"
        "document.getElementById('password_field').value = 'random';"
        "document.getElementById('input_submit_button').click()";
    ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
    ASSERT_TRUE(observer.Wait());
  }
};

IN_PROC_BROWSER_TEST_F(PasswordManagerDialogBrowserTest, InvokeUi_normal) {
  ShowAndVerifyUi();
}

// Verify that password manager ignores passwords on forms injected into
// about:blank frames.  See https://crbug.com/756587.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, AboutBlankFramesAreIgnored) {
  // Start from a page without a password form.
  NavigateToFile("/password/other.html");

  // Add a blank iframe and then inject a password form into it.
  BubbleObserver prompt_observer(WebContents());
  GURL submit_url(embedded_test_server()->GetURL("/password/done.html"));
  InjectBlankFrameWithPasswordForm(WebContents(), submit_url);
  content::RenderFrameHost* frame =
      ChildFrameAt(WebContents()->GetPrimaryMainFrame(), 0);
  EXPECT_EQ(GURL(url::kAboutBlankURL), frame->GetLastCommittedURL());
  EXPECT_TRUE(frame->IsRenderFrameLive());
  EXPECT_FALSE(prompt_observer.IsSavePromptAvailable());

  // Fill in the password and submit the form.  This shouldn't bring up a save
  // password prompt and shouldn't result in a renderer kill.
  SubmitInjectedPasswordForm(WebContents(), frame, submit_url);
  EXPECT_TRUE(frame->IsRenderFrameLive());
  EXPECT_EQ(submit_url, frame->GetLastCommittedURL());
  EXPECT_FALSE(prompt_observer.IsSavePromptAvailable());
}

// Verify that password manager ignores passwords on forms injected into
// about:blank popups.  See https://crbug.com/756587.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, AboutBlankPopupsAreIgnored) {
  // Start from a page without a password form.
  NavigateToFile("/password/other.html");

  // Open an about:blank popup and inject the password form into it.
  ui_test_utils::TabAddedWaiter tab_add(browser());
  GURL submit_url(embedded_test_server()->GetURL("/password/done.html"));
  std::string form_html = GeneratePasswordFormForAction(submit_url);
  std::string open_blank_popup_with_password_form =
      "var w = window.open('about:blank');"
      "w.document.body.innerHTML = \"" +
      form_html + "\";";
  ASSERT_TRUE(
      content::ExecJs(WebContents(), open_blank_popup_with_password_form));
  tab_add.Wait();
  ASSERT_EQ(2, browser()->tab_strip_model()->count());
  content::WebContents* newtab =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Submit the password form and check that there was no renderer kill and no
  BubbleObserver prompt_observer(WebContents());
  SubmitInjectedPasswordForm(newtab, newtab->GetPrimaryMainFrame(), submit_url);
  EXPECT_FALSE(prompt_observer.IsSavePromptAvailable());
  EXPECT_TRUE(newtab->GetPrimaryMainFrame()->IsRenderFrameLive());
  EXPECT_EQ(submit_url, newtab->GetPrimaryMainFrame()->GetLastCommittedURL());
}

// Verify that previously saved passwords for about:blank frames are not used
// for autofill.  See https://crbug.com/756587.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       ExistingAboutBlankPasswordsAreNotUsed) {
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.url = GURL(url::kAboutBlankURL);
  signin_form.signon_realm = "about:";
  GURL submit_url(embedded_test_server()->GetURL("/password/done.html"));
  signin_form.action = submit_url;
  signin_form.password_value = u"pa55w0rd";
  password_store->AddLogin(signin_form);

  // Start from a page without a password form.
  NavigateToFile("/password/other.html");

  // Inject an about:blank frame with password form.
  InjectBlankFrameWithPasswordForm(WebContents(), submit_url);
  content::RenderFrameHost* frame =
      ChildFrameAt(WebContents()->GetPrimaryMainFrame(), 0);
  EXPECT_EQ(GURL(url::kAboutBlankURL), frame->GetLastCommittedURL());

  // Simulate user interaction in the iframe which normally triggers
  // autofill. Click in the middle of the frame to avoid the border.
  content::SimulateMouseClickOrTapElementWithId(WebContents(), "iframe");

  // Verify password is not autofilled.  Blink has a timer for 0.3 seconds
  // before it updates the browser with the new dynamic form, so wait long
  // enough for this timer to fire before checking the password.  Note that we
  // can't wait for any other events here, because when the test passes, there
  // should be no password manager IPCs sent from the renderer to browser.
  EXPECT_EQ(
      "",
      content::EvalJs(
          frame,
          "new Promise(resolve => {"
          "    setTimeout(function() {"
          "        resolve(document.getElementById('password_field').value);"
          "    }, 1000);"
          "});",
          content::EXECUTE_SCRIPT_NO_USER_GESTURE));

  EXPECT_TRUE(frame->IsRenderFrameLive());
}

// Verify that there is no renderer kill when filling out a password on a
// subframe with a data: URL.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoRendererKillWithDataURLFrames) {
  // Start from a page without a password form.
  NavigateToFile("/password/other.html");

  // Add a iframe with a data URL that has a password form.
  BubbleObserver prompt_observer(WebContents());
  GURL submit_url(embedded_test_server()->GetURL("/password/done.html"));
  std::string form_html = GeneratePasswordFormForAction(submit_url);
  std::string inject_data_frame_with_password_form =
      "var frame = document.createElement('iframe');\n"
      "frame.src = \"data:text/html," +
      form_html +
      "\";\n"
      "document.body.appendChild(frame);\n";
  ASSERT_TRUE(
      content::ExecJs(WebContents(), inject_data_frame_with_password_form));
  EXPECT_TRUE(content::WaitForLoadStop(WebContents()));
  content::RenderFrameHost* frame =
      ChildFrameAt(WebContents()->GetPrimaryMainFrame(), 0);
  EXPECT_TRUE(frame->GetLastCommittedURL().SchemeIs(url::kDataScheme));
  EXPECT_TRUE(frame->IsRenderFrameLive());
  EXPECT_FALSE(prompt_observer.IsSavePromptAvailable());

  // Fill in the password and submit the form.  This shouldn't bring up a save
  // password prompt and shouldn't result in a renderer kill.
  SubmitInjectedPasswordForm(WebContents(), frame, submit_url);
  // After navigation, the RenderFrameHost may change.
  frame = ChildFrameAt(WebContents()->GetPrimaryMainFrame(), 0);
  EXPECT_TRUE(frame->IsRenderFrameLive());
  EXPECT_EQ(submit_url, frame->GetLastCommittedURL());
  EXPECT_FALSE(prompt_observer.IsSavePromptAvailable());
}

// Verify that there is no renderer kill when filling out a password on a
// blob: URL.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoRendererKillWithBlobURLFrames) {
  // Start from a page without a password form.
  NavigateToFile("/password/other.html");

  GURL submit_url(embedded_test_server()->GetURL("/password/done.html"));
  std::string form_html = GeneratePasswordFormForAction(submit_url);
  std::string navigate_to_blob_url =
      "location.href = URL.createObjectURL(new Blob([\"" + form_html +
      "\"], { type: 'text/html' }));";
  PasswordsNavigationObserver observer(WebContents());
  ASSERT_TRUE(content::ExecJs(WebContents(), navigate_to_blob_url));
  ASSERT_TRUE(observer.Wait());

  // Fill in the password and submit the form.  This shouldn't bring up a save
  // password prompt and shouldn't result in a renderer kill.
  std::string fill_and_submit =
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('testform').submit();";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  EXPECT_FALSE(BubbleObserver(WebContents()).IsSavePromptAvailable());
}

// Test that for HTTP auth (i.e., credentials not put through web forms) the
// password manager works even though it should be disabled on the previous
// page.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, CorrectEntryForHttpAuth) {
  // The embedded_test_server() is already started at this point and adding
  // the request handler to it would not be thread safe. Therefore, use a new
  // server.
  net::EmbeddedTestServer http_test_server;

  // Teach the embedded server to handle requests by issuing the basic auth
  // challenge.
  http_test_server.RegisterRequestHandler(
      base::BindRepeating(&HandleTestAuthRequest));
  ASSERT_TRUE(http_test_server.Start());

  // Navigate to about:blank first. This is a page where password manager
  // should not work.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));

  // Navigate to a page requiring HTTP auth
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), http_test_server.GetURL("/basic_auth")));
  ASSERT_TRUE(base::test::RunUntil(
      []() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));

  PasswordsNavigationObserver nav_observer(WebContents());
  // Offer valid credentials on the auth challenge.
  ASSERT_EQ(1u, LoginHandler::GetAllLoginHandlersForTest().size());
  LoginHandler* handler = *LoginHandler::GetAllLoginHandlersForTest().begin();
  ASSERT_TRUE(handler);
  // Any username/password will work.
  handler->SetAuth(u"user", u"pwd");

  // The password manager should be working correctly.
  ASSERT_TRUE(nav_observer.Wait());
  WaitForPasswordStore();
  BubbleObserver bubble_observer(WebContents());
  EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically());
}

// Test that if HTTP auth login (i.e., credentials not put through web forms)
// succeeds, and there is a blocklisted entry with the HTML PasswordForm::Scheme
// for that origin, then the bubble is shown.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       HTTPAuthRealmAfterHTMLBlocklistedIsNotBlocked) {
  // The embedded_test_server() is already started at this point and adding
  // the request handler to it would not be thread safe. Therefore, use a new
  // server.
  net::EmbeddedTestServer http_test_server;

  // Teach the embedded server to handle requests by issuing the basic auth
  // challenge.
  http_test_server.RegisterRequestHandler(
      base::BindRepeating(&HandleTestAuthRequest));
  ASSERT_TRUE(http_test_server.Start());

  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();

  password_manager::PasswordForm blocked_form;
  blocked_form.scheme = password_manager::PasswordForm::Scheme::kHtml;
  blocked_form.signon_realm = http_test_server.base_url().spec();
  blocked_form.url = http_test_server.base_url();
  blocked_form.blocked_by_user = true;
  password_store->AddLogin(blocked_form);

  // Navigate to a page requiring HTTP auth.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), http_test_server.GetURL("/basic_auth")));
  ASSERT_TRUE(base::test::RunUntil(
      []() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));

  PasswordsNavigationObserver nav_observer(WebContents());

  ASSERT_EQ(1u, LoginHandler::GetAllLoginHandlersForTest().size());
  LoginHandler* handler = *LoginHandler::GetAllLoginHandlersForTest().begin();
  ASSERT_TRUE(handler);
  // Any username/password will work.
  handler->SetAuth(u"user", u"pwd");
  ASSERT_TRUE(nav_observer.Wait());
  WaitForPasswordStore();
  EXPECT_TRUE(BubbleObserver(WebContents()).IsSavePromptShownAutomatically());
}

// Test that if HTML login succeeds, and there is a blocklisted entry
// with the HTTP auth PasswordForm::Scheme (i.e., credentials not put
// through web forms) for that origin, then the bubble is shown.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       HTMLLoginAfterHTTPAuthBlocklistedIsNotBlocked) {
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();

  password_manager::PasswordForm blocked_form;
  blocked_form.scheme = password_manager::PasswordForm::Scheme::kBasic;
  blocked_form.signon_realm =
      embedded_test_server()->base_url().spec() + "test realm";
  blocked_form.url = embedded_test_server()->base_url();
  blocked_form.blocked_by_user = true;
  password_store->AddLogin(blocked_form);

  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'pw';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  BubbleObserver bubble_observer(WebContents());
  bubble_observer.WaitForAutomaticSavePrompt();
}

// Tests that "blocklist site" feature works for the basic scenario.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       HTMLLoginAfterHTMLBlocklistedIsBlocklisted) {
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();

  password_manager::PasswordForm blocked_form;
  blocked_form.scheme = password_manager::PasswordForm::Scheme::kHtml;
  blocked_form.signon_realm = embedded_test_server()->base_url().spec();
  blocked_form.url = embedded_test_server()->base_url();
  blocked_form.blocked_by_user = true;
  password_store->AddLogin(blocked_form);

  NavigateToFile("/password/password_form.html");
  PasswordsNavigationObserver observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'pw';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());
  BubbleObserver bubble_observer(WebContents());
  EXPECT_FALSE(bubble_observer.IsSavePromptShownAutomatically());
  EXPECT_TRUE(bubble_observer.IsSavePromptAvailable());
}

// This test emulates what was observed in https://crbug.com/856543: Imagine the
// user stores a single username/password pair on origin A, and later submits a
// username-less password-reset form on origin B. In the bug, A and B were
// PSL-matches (different, but with the same eTLD+1), and Chrome ended up
// overwriting the old password with the new one. This test checks that update
// bubble is shown instead of silent update.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoSilentOverwriteOnPSLMatch) {
  // Store a password at origin A.
  const GURL url_A = embedded_test_server()->GetURL("abc.foo.com", "/");
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = url_A.DeprecatedGetOriginAsURL().spec();
  signin_form.url = url_A;
  signin_form.username_value = u"user";
  signin_form.password_value = u"oldpassword";
  password_store->AddLogin(signin_form);
  WaitForPasswordStore();

  // Visit origin B with a form only containing new- and confirmation-password
  // fields.
  GURL url_B = embedded_test_server()->GetURL(
      "www.foo.com", "/password/new_password_form.html");
  PasswordsNavigationObserver observer_B(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_B));
  ASSERT_TRUE(observer_B.Wait());

  // Fill in the new password and submit.
  GURL url_done =
      embedded_test_server()->GetURL("www.foo.com", "/password/done.html");
  PasswordsNavigationObserver observer_done(WebContents());
  observer_done.SetPathToWaitFor("/password/done.html");
  ASSERT_TRUE(content::ExecJs(
      RenderFrameHost(),
      "document.getElementById('new_p').value = 'new password';"
      "document.getElementById('conf_p').value = 'new password';"
      "document.getElementById('testform').submit();",
      content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  ASSERT_TRUE(observer_done.Wait());

  // Check that the password for origin A was not updated automatically and the
  // update bubble is shown instead.
  WaitForPasswordStore();  // Let the navigation take its effect on storing.
  ASSERT_THAT(password_store->stored_passwords(),
              ElementsAre(testing::Key(url_A.DeprecatedGetOriginAsURL())));
  CheckThatCredentialsStored("user", "oldpassword");
  BubbleObserver prompt_observer(WebContents());
  prompt_observer.WaitForAutomaticUpdatePrompt();

  // Check that the password is updated correctly if the user clicks Update.
  prompt_observer.AcceptUpdatePrompt();

  WaitForPasswordStore();
  // The stored credential has been updated with the new password.
  const auto& passwords_map = password_store->stored_passwords();
  ASSERT_THAT(passwords_map,
              ElementsAre(testing::Key(url_A.DeprecatedGetOriginAsURL())));
  for (const auto& credentials : passwords_map) {
    ASSERT_THAT(credentials.second, testing::SizeIs(1));
    EXPECT_EQ(u"user", credentials.second[0].username_value);
    EXPECT_EQ(u"new password", credentials.second[0].password_value);
  }
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoFillGaiaReauthenticationForm) {
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());

  // Visit Gaia reath page.
  const GURL url = https_test_server().GetURL("accounts.google.com",
                                              "/password/gaia_reath_form.html");
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = url.GetWithEmptyPath().spec();
  signin_form.url = url.GetWithEmptyPath();
  signin_form.username_value = u"user";
  signin_form.password_value = u"password123";
  password_store->AddLogin(signin_form);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  // Check that no autofill happened.
  content::SimulateMouseClick(WebContents(), 0,
                              blink::WebMouseEvent::Button::kLeft);
  CheckElementValue("identifier", "");
  CheckElementValue("password", "");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       NoFillGaiaWithSkipSavePasswordForm) {
  password_manager::TestPasswordStore* password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());

  // Visit Gaia form with ssp=1 as query (ssp stands for Skip Save Password).
  const GURL url = https_test_server().GetURL(
      "accounts.google.com", "/password/password_form.html?ssp=1");

  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = url.GetWithEmptyPath().spec();
  signin_form.url = url.GetWithEmptyPath();
  signin_form.username_value = u"user";
  signin_form.password_value = u"password123";
  password_store->AddLogin(signin_form);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  // Check that no autofill happened.
  content::SimulateMouseClick(WebContents(), 0,
                              blink::WebMouseEvent::Button::kLeft);
  CheckElementValue("username_field", "");
  CheckElementValue("password_field", "");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, FormDynamicallyChanged) {
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"pw";
  password_store->AddLogin(signin_form);

  // Check that password update bubble is shown.
  NavigateToFile("/password/simple_password.html");

  // Simulate that a script removes username/password elements and adds the
  // elements identical to them.
  ASSERT_TRUE(content::ExecJs(RenderFrameHost(),
                              "function replaceElement(id) {"
                              "  var elem = document.getElementById(id);"
                              "  var parent = elem.parentElement;"
                              "  var cloned_elem = elem.cloneNode();"
                              "  cloned_elem.value = '';"
                              "  parent.removeChild(elem);"
                              "  parent.appendChild(cloned_elem);"
                              "}"
                              "replaceElement('username_field');"
                              "replaceElement('password_field');",
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));

  // Let the user interact with the page, so that DOM gets modification events,
  // needed for autofilling fields.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft, gfx::Point(1, 1));

  WaitForElementValue("username_field", "temp");
  WaitForElementValue("password_field", "pw");
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, ParserAnnotations) {
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      autofill::switches::kShowAutofillSignatures);
  NavigateToFile("/password/password_form.html");
  const char kGetAnnotation[] =
      "document.getElementById('%s').getAttribute('pm_parser_annotation');";

  EXPECT_EQ(
      "username_element",
      content::EvalJs(RenderFrameHost(),
                      base::StringPrintf(kGetAnnotation, "username_field"),
                      content::EXECUTE_SCRIPT_NO_USER_GESTURE));

  EXPECT_EQ(
      "password_element",
      content::EvalJs(RenderFrameHost(),
                      base::StringPrintf(kGetAnnotation, "password_field"),
                      content::EXECUTE_SCRIPT_NO_USER_GESTURE));

  EXPECT_EQ(
      "new_password_element",
      content::EvalJs(RenderFrameHost(),
                      base::StringPrintf(kGetAnnotation, "chg_new_password_1"),
                      content::EXECUTE_SCRIPT_NO_USER_GESTURE));

  EXPECT_EQ(
      "confirmation_password_element",
      content::EvalJs(RenderFrameHost(),
                      base::StringPrintf(kGetAnnotation, "chg_new_password_2"),
                      content::EXECUTE_SCRIPT_NO_USER_GESTURE));
}

// Test if |PasswordManager.FormVisited.PerProfileType| metrics are recorded as
// expected.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       ProfileTypeMetricSubmission) {
  base::HistogramTester histogram_tester;

  NavigateToFile("/password/simple_password.html");

  // Test if visit is properly recorded and submission is not marked.
  histogram_tester.ExpectUniqueSample(
      "PasswordManager.FormVisited.PerProfileType",
      profile_metrics::BrowserProfileType::kRegular, 1);

  // Fill a form and submit through a <input type="submit"> button. Nothing
  // special.
  PasswordsNavigationObserver observer(WebContents());
  constexpr char kFillAndSubmit[] =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), kFillAndSubmit));
  ASSERT_TRUE(observer.Wait());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBackForwardCacheBrowserTest,
                       SavePasswordOnRestoredPage) {
  // Navigate to a page with a password form.
  NavigateToFile("/password/password_form.html");
  content::RenderFrameHostWrapper rfh(WebContents()->GetPrimaryMainFrame());

  // Navigate away so that the password form page is stored in the cache.
  ASSERT_TRUE(NavigateToURL(
      WebContents(), embedded_test_server()->GetURL("a.com", "/title1.html")));
  ASSERT_EQ(rfh->GetLifecycleState(),
            content::RenderFrameHost::LifecycleState::kInBackForwardCache);

  // Restore the cached page.
  ASSERT_TRUE(content::HistoryGoBack(WebContents()));
  ASSERT_EQ(rfh.get(), WebContents()->GetPrimaryMainFrame());

  // Fill out and submit the password form.
  PasswordsNavigationObserver observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());

  // Save the password and check the store.
  BubbleObserver bubble_observer(WebContents());
  bubble_observer.WaitForAutomaticSavePrompt();
  bubble_observer.AcceptSavePrompt();
  WaitForPasswordStore();

  CheckThatCredentialsStored("temp", "random");
}

// Test that if the credentials API is used, it makes the page ineligible for
// caching in the BackForwardCache.
//
// See where BackForwardCache::DisableForRenderFrameHost is called in
// chrome_password_manager_client.cc for explanation.
IN_PROC_BROWSER_TEST_F(PasswordManagerBackForwardCacheBrowserTest,
                       NotCachedIfCredentialsAPIUsed) {
  // Navigate to a page with a password form.
  NavigateToFile("/password/password_form.html");
  content::RenderFrameHostWrapper rfh(WebContents()->GetPrimaryMainFrame());

  // Use the password manager API, this should make the page uncacheable.
  ASSERT_TRUE(IsGetCredentialsSuccessful());

  // Navigate away.
  ASSERT_TRUE(NavigateToURL(
      WebContents(), embedded_test_server()->GetURL("a.com", "/title1.html")));
  // The page should not have been cached.
  ASSERT_TRUE(rfh.WaitUntilRenderFrameDeleted());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBackForwardCacheBrowserTest,
                       CredentialsAPIOnlyCalledOnRestoredPage) {
  // Navigate to a page with a password form.
  NavigateToFile("/password/password_form.html");
  content::RenderFrameHostWrapper rfh(WebContents()->GetPrimaryMainFrame());

  // Navigate away.
  ASSERT_TRUE(NavigateToURL(
      WebContents(), embedded_test_server()->GetURL("b.com", "/title1.html")));
  ASSERT_EQ(rfh->GetLifecycleState(),
            content::RenderFrameHost::LifecycleState::kInBackForwardCache);

  // Restore the cached page.
  ASSERT_TRUE(content::HistoryGoBack(WebContents()));
  ASSERT_EQ(rfh.get(), WebContents()->GetPrimaryMainFrame());

  // Make sure the password manager API works. Since it was never connected, it
  // shouldn't have been affected by the
  // ContentCredentialManager::DisconnectBinding call in
  // ChromePasswordManagerClient::DidFinishNavigation, (this GetCredentials call
  // will establish the mojo connection for the first time).
  ASSERT_TRUE(IsGetCredentialsSuccessful());
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       DetectFormSubmissionOnIframe) {
  // Start from a page without a password form.
  NavigateToFile("/password/other.html");

  // Add a blank iframe and then inject a password form into it.
  BubbleObserver prompt_observer(WebContents());
  GURL current_url(embedded_test_server()->GetURL("/password/other.html"));
  GURL submit_url(embedded_test_server()->GetURL("/password/done.html"));
  InjectFrameWithPasswordForm(WebContents(), submit_url);
  content::RenderFrameHost* frame =
      ChildFrameAt(WebContents()->GetPrimaryMainFrame(), 0);
  EXPECT_EQ(GURL(url::kAboutBlankURL), frame->GetLastCommittedURL());
  EXPECT_EQ(submit_url.DeprecatedGetOriginAsURL(),
            frame->GetLastCommittedOrigin().GetURL());
  EXPECT_TRUE(frame->IsRenderFrameLive());
  EXPECT_FALSE(prompt_observer.IsSavePromptAvailable());

  // Fill in the password and submit the form. This should bring up a save
  // password prompt and shouldn't result in a renderer kill.
  SubmitInjectedPasswordForm(WebContents(), frame, submit_url);
  EXPECT_TRUE(frame->IsRenderFrameLive());
  prompt_observer.WaitForAutomaticSavePrompt();
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest,
                       ShowPasswordManagerNoBrowser) {
  // Create a WebContent without tab helpers so it has no associated browser.
  std::unique_ptr<content::WebContents> new_web_contents =
      content::WebContents::Create(
          content::WebContents::CreateParams(browser()->profile()));

  // Verify that there is no browser.
  ASSERT_FALSE(chrome::FindBrowserWithTab(new_web_contents.get()));

  // Create ChromePasswordManagerClient for newly created web_contents.
  autofill::ChromeAutofillClient::CreateForWebContents(new_web_contents.get());
  ChromePasswordManagerClient::CreateForWebContents(new_web_contents.get());

  ChromePasswordManagerClient* client =
      ChromePasswordManagerClient::FromWebContents(new_web_contents.get());
  ASSERT_TRUE(client);
  ASSERT_NO_FATAL_FAILURE(client->NavigateToManagePasswordsPage(
      password_manager::ManagePasswordsReferrer::kPasswordsGoogleWebsite));
}

IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTest, FormWithoutTextInputs) {
  base::HistogramTester histogram_tester;

  // Navigate to a page with a form without text inputs.
  NavigateToFile("/password/no_text_inputs.html");

  // Submit the form.
  PasswordsNavigationObserver observer(WebContents());
  std::string submit_pw_form =
      "document.getElementById('input_submit_button').click();";
  ASSERT_TRUE(content::ExecJs(WebContents(), submit_pw_form));
  ASSERT_TRUE(observer.Wait());

  // Verify that no form was seen on the browser side.
  histogram_tester.ExpectTotalCount(
      "PasswordManager.FormVisited.PerProfileType", 0);
}

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
// This test suite only applies to Gaia signin page, and checks that the
// signin interception bubble and the password bubbles never conflict.
class PasswordManagerBrowserTestWithSigninInterception
    : public PasswordManagerBrowserTest {
 public:
  PasswordManagerBrowserTestWithSigninInterception()
      : helper_(&https_test_server()) {}

  void SetUpCommandLine(base::CommandLine* command_line) override {
    PasswordManagerBrowserTest::SetUpCommandLine(command_line);
    helper_.SetUpCommandLine(command_line);
  }

  void SetUpOnMainThread() override {
    helper_.SetUpOnMainThread();
    PasswordManagerBrowserTest::SetUpOnMainThread();
  }

  void FillAndSubmitGaiaPassword() {
    PasswordsNavigationObserver observer(WebContents());
    std::string fill_and_submit = base::StringPrintf(
        "document.getElementById('username_field').value = '%s';"
        "document.getElementById('password_field').value = 'new_pw';"
        "document.getElementById('input_submit_button').click()",
        helper_.gaia_username().c_str());
    ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
    ASSERT_TRUE(observer.Wait());
  }

  // Gaia passwords can only be saved if they are a secondary account. Add
  // another dummy account in Chrome that acts as the primary.
  void SetupAccountsForSavingGaiaPassword() {
    CoreAccountId dummy_account = helper_.AddGaiaAccountToProfile(
        browser()->profile(), "dummy_email@example.com",
        GaiaId("dummy_gaia_id"));
    IdentityManagerFactory::GetForProfile(browser()->profile())
        ->GetPrimaryAccountMutator()
        ->SetPrimaryAccount(dummy_account, signin::ConsentLevel::kSignin);
  }

 protected:
  PasswordManagerSigninInterceptTestHelper helper_;
};

// Checks that password update suppresses signin interception.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithSigninInterception,
                       InterceptionBubbleSuppressedByPasswordUpdate) {
  Profile* profile = browser()->profile();
  helper_.SetupProfilesForInterception(profile);
  // Prepopulate Gaia credentials to trigger an update bubble.
  scoped_refptr<password_manager::TestPasswordStore> password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              profile, ServiceAccessType::IMPLICIT_ACCESS)
              .get());
  helper_.StoreGaiaCredentials(password_store);

  helper_.NavigateToGaiaSigninPage(WebContents());

  // The stored password "pw" was overridden with "new_pw", so update prompt is
  // expected. Use the retry form, to avoid autofill.
  BubbleObserver prompt_observer(WebContents());

  PasswordsNavigationObserver observer(WebContents());
  std::string fill_and_submit =
      "document.getElementById('retry_password_field').value = 'new_pw';"
      "document.getElementById('retry_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());

  prompt_observer.WaitForAutomaticUpdatePrompt();

  // Complete the Gaia signin.
  CoreAccountId account_id = helper_.AddGaiaAccountToProfile(
      profile, helper_.gaia_email(), helper_.gaia_id());

  // Check that interception does not happen.
  base::HistogramTester histogram_tester;
  DiceWebSigninInterceptor* signin_interceptor =
      helper_.GetSigninInterceptor(profile);
  signin_interceptor->MaybeInterceptWebSignin(
      WebContents(), account_id, signin_metrics::AccessPoint::kUnknown,
      /*is_new_account=*/true,
      /*is_sync_signin=*/false);
  EXPECT_FALSE(signin_interceptor->is_interception_in_progress());
  histogram_tester.ExpectUniqueSample(
      "Signin.Intercept.HeuristicOutcome",
      SigninInterceptionHeuristicOutcome::kAbortPasswordUpdate, 1);
}

// Checks that Gaia password can be saved when there is no interception.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithSigninInterception,
                       SaveGaiaPassword) {
  SetupAccountsForSavingGaiaPassword();
  helper_.NavigateToGaiaSigninPage(WebContents());

  // Add the new password: triggers the save bubble.
  BubbleObserver prompt_observer(WebContents());
  FillAndSubmitGaiaPassword();
  prompt_observer.WaitForAutomaticSavePrompt();

  // Complete the Gaia signin.
  Profile* profile = browser()->profile();
  CoreAccountId account_id = helper_.AddGaiaAccountToProfile(
      profile, helper_.gaia_email(), helper_.gaia_id());

  // Check that interception does not happen.
  base::HistogramTester histogram_tester;
  DiceWebSigninInterceptor* signin_interceptor =
      helper_.GetSigninInterceptor(profile);
  signin_interceptor->MaybeInterceptWebSignin(
      WebContents(), account_id, signin_metrics::AccessPoint::kUnknown,
      /*is_new_account=*/true,
      /*is_sync_signin=*/false);
  EXPECT_FALSE(signin_interceptor->is_interception_in_progress());
  histogram_tester.ExpectUniqueSample(
      "Signin.Intercept.HeuristicOutcome",
      SigninInterceptionHeuristicOutcome::kAbortProfileCreationDisallowed, 1);
}

// Checks that signin interception suppresses password save, if the form is
// processed before the signin completes.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithSigninInterception,
                       SavePasswordSuppressedBeforeSignin) {
  Profile* profile = browser()->profile();
  helper_.SetupProfilesForInterception(profile);
  SetupAccountsForSavingGaiaPassword();
  helper_.NavigateToGaiaSigninPage(WebContents());

  // Add the new password, password bubble not triggered.
  BubbleObserver prompt_observer(WebContents());
  FillAndSubmitGaiaPassword();
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());

  // Complete the Gaia signin.
  CoreAccountId account_id = helper_.AddGaiaAccountToProfile(
      profile, helper_.gaia_email(), helper_.gaia_id());

  // Check that interception happens.
  base::HistogramTester histogram_tester;
  DiceWebSigninInterceptor* signin_interceptor =
      helper_.GetSigninInterceptor(profile);
  signin_interceptor->MaybeInterceptWebSignin(
      WebContents(), account_id, signin_metrics::AccessPoint::kUnknown,
      /*is_new_account=*/true,
      /*is_sync_signin=*/false);
  EXPECT_TRUE(signin_interceptor->is_interception_in_progress());
}

// Checks that signin interception suppresses password save, if the form is
// processed after the signin completes.
IN_PROC_BROWSER_TEST_F(PasswordManagerBrowserTestWithSigninInterception,
                       SavePasswordSuppressedAfterSignin) {
  Profile* profile = browser()->profile();
  helper_.SetupProfilesForInterception(profile);
  SetupAccountsForSavingGaiaPassword();
  helper_.NavigateToGaiaSigninPage(WebContents());

  // Complete the Gaia signin.
  CoreAccountId account_id = helper_.AddGaiaAccountToProfile(
      profile, helper_.gaia_email(), helper_.gaia_id());

  // Check that interception happens.
  base::HistogramTester histogram_tester;
  DiceWebSigninInterceptor* signin_interceptor =
      helper_.GetSigninInterceptor(profile);
  signin_interceptor->MaybeInterceptWebSignin(
      WebContents(), account_id, signin_metrics::AccessPoint::kUnknown,
      /*is_new_account=*/true,
      /*is_sync_signin=*/false);
  EXPECT_TRUE(signin_interceptor->is_interception_in_progress());

  // Add the new password, password bubble not triggered.
  BubbleObserver prompt_observer(WebContents());
  FillAndSubmitGaiaPassword();
  EXPECT_FALSE(prompt_observer.IsSavePromptShownAutomatically());
}
#endif  // BUIDLFLAG(ENABLE_DICE_SUPPORT)

// This is for checking that we don't make unexpected calls to the password
// manager driver prior to activation and to permit checking that expected calls
// do happen after activation.
class MockPrerenderPasswordManagerDriver
    : public autofill::mojom::PasswordManagerDriverInterceptorForTesting {
 public:
  explicit MockPrerenderPasswordManagerDriver(
      password_manager::ContentPasswordManagerDriver* driver)
      : impl_(driver->ReceiverForTesting().SwapImplForTesting(this)) {
    DelegateToImpl();
  }
  MockPrerenderPasswordManagerDriver(
      const MockPrerenderPasswordManagerDriver&) = delete;
  MockPrerenderPasswordManagerDriver& operator=(
      const MockPrerenderPasswordManagerDriver&) = delete;
  ~MockPrerenderPasswordManagerDriver() override = default;

  autofill::mojom::PasswordManagerDriver* GetForwardingInterface() override {
    return impl_;
  }

  // autofill::mojom::PasswordManagerDriver
  MOCK_METHOD(void,
              PasswordFormsParsed,
              (const std::vector<autofill::FormData>& form_data),
              (override));
  MOCK_METHOD(void,
              PasswordFormsRendered,
              (const std::vector<autofill::FormData>& visible_form_data),
              (override));
  MOCK_METHOD(void,
              PasswordFormSubmitted,
              (const autofill::FormData& form_data),
              (override));
  MOCK_METHOD(void,
              InformAboutUserInput,
              (const autofill::FormData& form_data),
              (override));
  MOCK_METHOD(
      void,
      DynamicFormSubmission,
      (autofill::mojom::SubmissionIndicatorEvent submission_indication_event),
      (override));
  MOCK_METHOD(void,
              PasswordFormCleared,
              (const autofill::FormData& form_Data),
              (override));
  MOCK_METHOD(void,
              RecordSavePasswordProgress,
              (const std::string& log),
              (override));
  MOCK_METHOD(void, UserModifiedPasswordField, (), (override));
  MOCK_METHOD(void,
              UserModifiedNonPasswordField,
              (autofill::FieldRendererId renderer_id,
               const std::u16string& value,
               bool autocomplete_attribute_has_username,
               bool is_likely_otp),
              (override));
  MOCK_METHOD(void,
              ShowPasswordSuggestions,
              (const autofill::PasswordSuggestionRequest&),
              (override));
  MOCK_METHOD(void,
              CheckSafeBrowsingReputation,
              (const GURL& form_action, const GURL& frame_url),
              (override));
  MOCK_METHOD(void,
              FocusedInputChanged,
              (autofill::FieldRendererId focused_field_id,
               autofill::mojom::FocusedFieldType focused_field_type),
              (override));
  MOCK_METHOD(void,
              LogFirstFillingResult,
              (autofill::FormRendererId form_renderer_id, int32_t result),
              (override));

  void DelegateToImpl() {
    ON_CALL(*this, PasswordFormsParsed)
        .WillByDefault(
            [this](const std::vector<autofill::FormData>& form_data) {
              impl_->PasswordFormsParsed(form_data);
              RemoveWaitType(WAIT_FOR_PASSWORD_FORMS::WAIT_FOR_PARSED);
            });
    ON_CALL(*this, PasswordFormsRendered)
        .WillByDefault(
            [this](const std::vector<autofill::FormData>& visible_form_data) {
              impl_->PasswordFormsRendered(visible_form_data);
              RemoveWaitType(WAIT_FOR_PASSWORD_FORMS::WAIT_FOR_RENDERED);
            });
    ON_CALL(*this, PasswordFormSubmitted)
        .WillByDefault([this](const autofill::FormData& form_data) {
          impl_->PasswordFormSubmitted(form_data);
        });
    ON_CALL(*this, InformAboutUserInput)
        .WillByDefault([this](const autofill::FormData& form_data) {
          impl_->InformAboutUserInput(form_data);
        });
    ON_CALL(*this, DynamicFormSubmission)
        .WillByDefault([this](autofill::mojom::SubmissionIndicatorEvent
                                  submission_indication_event) {
          impl_->DynamicFormSubmission(submission_indication_event);
        });
    ON_CALL(*this, PasswordFormCleared)
        .WillByDefault([this](const autofill::FormData& form_Data) {
          impl_->PasswordFormCleared(form_Data);
        });
    ON_CALL(*this, RecordSavePasswordProgress)
        .WillByDefault([this](const std::string& log) {
          impl_->RecordSavePasswordProgress(log);
        });
    ON_CALL(*this, UserModifiedPasswordField).WillByDefault([this]() {
      impl_->UserModifiedPasswordField();
    });
    ON_CALL(*this, UserModifiedNonPasswordField)
        .WillByDefault([this](autofill::FieldRendererId renderer_id,
                              const std::u16string& value,
                              bool autocomplete_attribute_has_username,
                              bool is_likely_otp) {
          impl_->UserModifiedNonPasswordField(
              renderer_id, value, autocomplete_attribute_has_username,
              is_likely_otp);
        });
    ON_CALL(*this, ShowPasswordSuggestions)
        .WillByDefault(
            [this](const autofill::PasswordSuggestionRequest& request) {
              autofill::PasswordSuggestionRequest copy = request;
              copy.form_data = autofill::FormData();
              copy.username_field_index = 0;
              copy.password_field_index = 0;
              impl_->ShowPasswordSuggestions(copy);
            });
    ON_CALL(*this, CheckSafeBrowsingReputation)
        .WillByDefault([this](const GURL& form_action, const GURL& frame_url) {
          impl_->CheckSafeBrowsingReputation(form_action, frame_url);
        });
    ON_CALL(*this, FocusedInputChanged)
        .WillByDefault(
            [this](autofill::FieldRendererId focused_field_id,
                   autofill::mojom::FocusedFieldType focused_field_type) {
              impl_->FocusedInputChanged(focused_field_id, focused_field_type);
            });
    ON_CALL(*this, LogFirstFillingResult)
        .WillByDefault(
            [this](autofill::FormRendererId form_renderer_id, int32_t result) {
              impl_->LogFirstFillingResult(form_renderer_id, result);
            });
  }

  void WaitFor(uint32_t wait_type) {
    base::RunLoop run_loop;
    quit_closure_ = run_loop.QuitClosure();
    wait_type_ = wait_type;
    run_loop.Run();
  }

  void WaitForPasswordFormParsedAndRendered() {
    WaitFor(WAIT_FOR_PASSWORD_FORMS::WAIT_FOR_PARSED |
            WAIT_FOR_PASSWORD_FORMS::WAIT_FOR_RENDERED);
  }

  enum WAIT_FOR_PASSWORD_FORMS {
    WAIT_FOR_NOTHING = 0,
    WAIT_FOR_PARSED = 1 << 0,    // Waits for PasswordFormsParsed().
    WAIT_FOR_RENDERED = 1 << 1,  // Waits for PasswordFormsRendered().
  };

 private:
  void RemoveWaitType(uint32_t arrived) {
    wait_type_ &= ~arrived;
    if (wait_type_ == WAIT_FOR_NOTHING && quit_closure_) {
      std::move(quit_closure_).Run();
    }
  }
  base::OnceClosure quit_closure_;
  uint32_t wait_type_ = WAIT_FOR_NOTHING;
  raw_ptr<autofill::mojom::PasswordManagerDriver, AcrossTasksDanglingUntriaged>
      impl_ = nullptr;
};

class MockPrerenderPasswordManagerDriverInjector
    : public content::WebContentsObserver {
 public:
  explicit MockPrerenderPasswordManagerDriverInjector(
      content::WebContents* web_contents)
      : WebContentsObserver(web_contents) {}
  ~MockPrerenderPasswordManagerDriverInjector() override = default;

  MockPrerenderPasswordManagerDriver* GetMockForFrame(
      content::RenderFrameHost* rfh) {
    return static_cast<MockPrerenderPasswordManagerDriver*>(
        GetDriverForFrame(rfh)->ReceiverForTesting().impl());
  }

 private:
  password_manager::ContentPasswordManagerDriver* GetDriverForFrame(
      content::RenderFrameHost* rfh) {
    return password_manager::ContentPasswordManagerDriver::
        GetForRenderFrameHost(rfh);
  }

  // content::WebContentsObserver:
  void ReadyToCommitNavigation(
      content::NavigationHandle* navigation_handle) override {
    auto* rfh = navigation_handle->GetRenderFrameHost();
    if (navigation_handle->IsPrerenderedPageActivation() ||
        navigation_handle->IsSameDocument() ||
        rfh->GetLifecycleState() !=
            content::RenderFrameHost::LifecycleState::kPrerendering) {
      return;
    }
    mocks_.push_back(std::make_unique<
                     testing::StrictMock<MockPrerenderPasswordManagerDriver>>(
        GetDriverForFrame(navigation_handle->GetRenderFrameHost())));
  }

  std::vector<
      std::unique_ptr<testing::StrictMock<MockPrerenderPasswordManagerDriver>>>
      mocks_;
};

class PasswordManagerPrerenderBrowserTest : public PasswordManagerBrowserTest {
 public:
  PasswordManagerPrerenderBrowserTest()
      : prerender_helper_(base::BindRepeating(
            &PasswordManagerPrerenderBrowserTest::web_contents,
            base::Unretained(this))) {}
  ~PasswordManagerPrerenderBrowserTest() override = default;

  void SetUp() override {
    prerender_helper_.RegisterServerRequestMonitor(embedded_test_server());
    PasswordManagerBrowserTest::SetUp();
  }

  void SetUpOnMainThread() override {
    // Register requests handler before the server is started.
    embedded_test_server()->RegisterRequestHandler(
        base::BindRepeating(&HandleTestAuthRequest));

    PasswordManagerBrowserTest::SetUpOnMainThread();
  }

  content::test::PrerenderTestHelper* prerender_helper() {
    return &prerender_helper_;
  }

  void SendKey(::ui::KeyboardCode key,
               content::RenderFrameHost* render_frame_host) {
    blink::WebKeyboardEvent web_event(
        blink::WebKeyboardEvent::Type::kRawKeyDown,
        blink::WebInputEvent::kNoModifiers,
        blink::WebInputEvent::GetStaticTimeStampForTests());

    input::NativeWebKeyboardEvent event(web_event, gfx::NativeView());
    event.windows_key_code = key;
    render_frame_host->GetRenderWidgetHost()->ForwardKeyboardEvent(event);
  }

  // Adds a tab with ChromePasswordManagerClient.
  // Note that it doesn't use CustomManagePasswordsUIController and it's not
  // useful to test UI. After calling this,
  // PasswordManagerBrowserTest::WebContents() is not available.
  void GetNewTabWithPasswordManagerClient() {
    content::WebContents* preexisting_tab =
        browser()->tab_strip_model()->GetActiveWebContents();
    std::unique_ptr<content::WebContents> owned_web_contents =
        content::WebContents::Create(
            content::WebContents::CreateParams(browser()->profile()));
    ASSERT_TRUE(owned_web_contents.get());

    // ManagePasswordsUIController needs ChromePasswordManagerClient for
    // logging.
    autofill::ChromeAutofillClient::CreateForWebContents(
        owned_web_contents.get());
    ChromePasswordManagerClient::CreateForWebContents(owned_web_contents.get());
    ASSERT_TRUE(
        ChromePasswordManagerClient::FromWebContents(owned_web_contents.get()));
    ManagePasswordsUIController::CreateForWebContents(owned_web_contents.get());
    ASSERT_TRUE(
        ManagePasswordsUIController::FromWebContents(owned_web_contents.get()));
    ASSERT_FALSE(owned_web_contents.get()->IsLoading());
    browser()->tab_strip_model()->AppendWebContents(
        std::move(owned_web_contents), true);
    if (preexisting_tab) {
      ClearWebContentsPtr();
      browser()->tab_strip_model()->CloseWebContentsAt(
          0, TabCloseTypes::CLOSE_NONE);
    }
  }

  content::WebContents* web_contents() {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

 private:
  content::test::PrerenderTestHelper prerender_helper_;
};

// Tests that the prerender doesn't proceed HTTP auth login and once the page
// is loaded as the primary page the prompt is shown. As the page is
// not loaded from the prerender, it also checks if it's not activated from the
// prerender.
IN_PROC_BROWSER_TEST_F(PasswordManagerPrerenderBrowserTest,
                       ChromePasswordManagerClientInPrerender) {
  MockPrerenderPasswordManagerDriverInjector injector(WebContents());

  GURL url = embedded_test_server()->GetURL("/empty.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::test::PrerenderHostRegistryObserver registry_observer(
      *WebContents());
  auto prerender_url = embedded_test_server()->GetURL("/basic_auth");

  // Loads a page requiring HTTP auth in the prerender.
  prerender_helper()->AddPrerenderAsync(prerender_url);

  // Ensure that the prerender has started.
  registry_observer.WaitForTrigger(prerender_url);
  content::FrameTreeNodeId prerender_id =
      prerender_helper()->GetHostForUrl(prerender_url);
  EXPECT_TRUE(prerender_id);
  content::test::PrerenderHostObserver host_observer(*WebContents(),
                                                     prerender_id);
  // PrerenderHost is destroyed by net::INVALID_AUTH_CREDENTIALS and it stops
  // prerendering.
  host_observer.WaitForDestroyed();

  BubbleObserver bubble_observer(WebContents());
  EXPECT_FALSE(bubble_observer.IsSavePromptShownAutomatically());

  // Navigates the primary page to the URL.
  prerender_helper()->NavigatePrimaryPage(prerender_url);
  ASSERT_TRUE(base::test::RunUntil(
      []() { return LoginHandler::GetAllLoginHandlersForTest().size() == 1; }));

  PasswordsNavigationObserver nav_observer(WebContents());
  // Offer valid credentials on the auth challenge.
  ASSERT_EQ(1u, LoginHandler::GetAllLoginHandlersForTest().size());
  LoginHandler* handler = *LoginHandler::GetAllLoginHandlersForTest().begin();
  EXPECT_TRUE(handler);
  // Any username/password will work.
  handler->SetAuth(u"user", u"pwd");

  // The password manager should be working correctly.
  ASSERT_TRUE(nav_observer.Wait());
  WaitForPasswordStore();
  EXPECT_TRUE(bubble_observer.IsSavePromptShownAutomatically());

  // Make sure that the prerender was not activated.
  EXPECT_FALSE(host_observer.was_activated());
}

// Tests that saving password doesn't work in the prerendering.
IN_PROC_BROWSER_TEST_F(PasswordManagerPrerenderBrowserTest,
                       SavePasswordInPrerender) {
  MockPrerenderPasswordManagerDriverInjector injector(WebContents());
  GURL url = embedded_test_server()->GetURL("/empty.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  auto prerender_url =
      embedded_test_server()->GetURL("/password/password_form.html");
  // Loads a page in the prerender.
  content::FrameTreeNodeId host_id =
      prerender_helper()->AddPrerender(prerender_url);
  content::test::PrerenderHostObserver host_observer(*WebContents(), host_id);
  content::RenderFrameHost* render_frame_host =
      prerender_helper()->GetPrerenderedMainFrameHost(host_id);
  // Fills a form and submits through a <input type="submit"> button.
  std::string fill_and_submit =
      "document.getElementById('username_field').value = 'temp';"
      "document.getElementById('password_field').value = 'random';"
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(render_frame_host, fill_and_submit));
  // Since navigation from a prerendering page is disallowed, prerendering is
  // canceled. This also means that we should never make any calls to the mocked
  // driver. Since we've already set an expectation of no calls, this will be
  // checked implicitly when the injector (and consequently, the mock) is
  // destroyed.
  host_observer.WaitForDestroyed();
  BubbleObserver bubble_observer(WebContents());
  EXPECT_FALSE(bubble_observer.IsSavePromptShownAutomatically());

  // Navigates the primary page to the URL.
  prerender_helper()->NavigatePrimaryPage(prerender_url);
  // Makes sure that the page is not from the prerendering.
  EXPECT_FALSE(host_observer.was_activated());

  // After loading the primary page, try to submit the password.
  PasswordsNavigationObserver observer(WebContents());
  ASSERT_TRUE(content::ExecJs(WebContents(), fill_and_submit));
  ASSERT_TRUE(observer.Wait());

  // Saves the password and checks the store.
  bubble_observer.WaitForAutomaticSavePrompt();
  bubble_observer.AcceptSavePrompt();

  WaitForPasswordStore();
  CheckThatCredentialsStored("temp", "random");
}

// Tests that Mojo messages in prerendering are deferred from the render to
// the PasswordManagerDriver until activation.
IN_PROC_BROWSER_TEST_F(PasswordManagerPrerenderBrowserTest,
                       MojoDeferringInPrerender) {
  GetNewTabWithPasswordManagerClient();
  MockPrerenderPasswordManagerDriverInjector injector(web_contents());

  GURL url = embedded_test_server()->GetURL("/empty.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  auto prerender_url =
      embedded_test_server()->GetURL("/password/password_form.html");
  // Loads a page in the prerender.
  content::FrameTreeNodeId host_id =
      prerender_helper()->AddPrerender(prerender_url);
  content::test::PrerenderHostObserver host_observer(*web_contents(), host_id);
  content::RenderFrameHost* render_frame_host =
      prerender_helper()->GetPrerenderedMainFrameHost(host_id);

  auto* mock = injector.GetMockForFrame(render_frame_host);
  testing::Mock::VerifyAndClearExpectations(mock);

  // We expect that messages will be sent to the driver, post-activation.
  EXPECT_CALL(*mock, PasswordFormsParsed).Times(1);
  EXPECT_CALL(*mock, PasswordFormsRendered).Times(1);

  // Navigates the primary page to the URL.
  prerender_helper()->NavigatePrimaryPage(prerender_url);
  // Makes sure that the page is activated from the prerendering.
  EXPECT_TRUE(host_observer.was_activated());

  mock->WaitForPasswordFormParsedAndRendered();
}

/// Inject the mock driver when navigation happens in main frame.
class MockPasswordManagerDriverInjector : public content::WebContentsObserver {
 public:
  explicit MockPasswordManagerDriverInjector(content::WebContents* web_contents)
      : WebContentsObserver(web_contents) {}
  ~MockPasswordManagerDriverInjector() override = default;

  MockPrerenderPasswordManagerDriver* GetMockForFrame(
      content::RenderFrameHost* rfh) {
    return static_cast<MockPrerenderPasswordManagerDriver*>(
        GetDriverForFrame(rfh)->ReceiverForTesting().impl());
  }

 private:
  password_manager::ContentPasswordManagerDriver* GetDriverForFrame(
      content::RenderFrameHost* rfh) {
    return password_manager::ContentPasswordManagerDriver::
        GetForRenderFrameHost(rfh);
  }

  // content::WebContentsObserver:
  void ReadyToCommitNavigation(
      content::NavigationHandle* navigation_handle) override {
    mocks_.push_back(std::make_unique<
                     testing::StrictMock<MockPrerenderPasswordManagerDriver>>(
        GetDriverForFrame(navigation_handle->GetRenderFrameHost())));
  }

  std::vector<std::unique_ptr<MockPrerenderPasswordManagerDriver>> mocks_;
};

// Test class for testing password manager with CredentiallessIframe enabled.
class PasswordManagerCredentiallessIframeTest
    : public PasswordManagerBrowserTest {
  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    PasswordManagerBrowserTest::SetUpOnMainThread();
  }
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(switches::kEnableBlinkTestFeatures);
    PasswordManagerBrowserTest::SetUpCommandLine(command_line);
  }
};

IN_PROC_BROWSER_TEST_F(PasswordManagerCredentiallessIframeTest, NoFormsSeen) {
  GURL main_frame_url = embedded_test_server()->GetURL(
      "/password/password_form_in_credentialless_iframe.html");
  MockPasswordManagerDriverInjector injector(WebContents());
  PasswordsNavigationObserver nav_observer(WebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url));
  ASSERT_TRUE(nav_observer.Wait());

  content::RenderFrameHost* main_rfh = WebContents()->GetPrimaryMainFrame();
  // Check behavior on a normal iframe:
  {
    ASSERT_TRUE(content::ExecJs(
        main_rfh, R"(create_iframe('/empty.html', 'iframe', false);)"));
    content::RenderFrameHost* child_rfh = ChildFrameAt(main_rfh, 0);
    ASSERT_NE(child_rfh, nullptr);
    MockPrerenderPasswordManagerDriver* mock =
        injector.GetMockForFrame(child_rfh);
    ASSERT_NE(mock, nullptr);
    EXPECT_CALL(*mock, PasswordFormsParsed).Times(1);
    ASSERT_TRUE(
        content::ExecJs(child_rfh, "window.parent.inject_form(document);"));
    mock->WaitFor(MockPrerenderPasswordManagerDriver::WAIT_FOR_PASSWORD_FORMS::
                      WAIT_FOR_PARSED);
  }

  // Check what happens when using a credentialless iframe instead:
  {
    ASSERT_TRUE(content::ExecJs(
        main_rfh, "create_iframe('/empty.html', 'iframe', true);"));
    content::RenderFrameHost* child_rfh =
        ChildFrameAt(WebContents()->GetPrimaryMainFrame(), 1);
    ASSERT_NE(child_rfh, nullptr);
    MockPrerenderPasswordManagerDriver* mock =
        injector.GetMockForFrame(child_rfh);
    ASSERT_NE(mock, nullptr);
    EXPECT_CALL(*mock, PasswordFormsParsed).Times(0);
    ASSERT_TRUE(
        content::ExecJs(child_rfh, "window.parent.inject_form(document);"));
    base::RunLoop().RunUntilIdle();
  }
}

IN_PROC_BROWSER_TEST_F(PasswordManagerCredentiallessIframeTest,
                       DisablePasswordManagerOnCredentiallessIframe) {
  GURL base_url = https_test_server().GetURL("a.test", "/");
  GURL main_frame_url = https_test_server().GetURL(
      "a.test", "/password/password_form_in_credentialless_iframe.html");
  GURL form_url = https_test_server().GetURL(
      "a.test", "/password/crossite_iframe_content.html");

  // 1. Store the username/password
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = base_url.spec();
  signin_form.url = base_url;
  signin_form.action = base_url;
  signin_form.username_value = u"temp";
  signin_form.password_value = u"pa55w0rd";
  password_store->AddLogin(signin_form);

  // 2. Load the form again, from a normal and a credentialless iframe.
  PasswordsNavigationObserver reload_observer(WebContents());
  reload_observer.SetPathToWaitFor(
      "/password/password_form_in_credentialless_iframe.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_frame_url));
  ASSERT_TRUE(reload_observer.Wait());
  EXPECT_TRUE(content::ExecJs(
      WebContents(),
      content::JsReplace("create_iframe($1, 'normal', false); ", form_url)));
  EXPECT_TRUE(content::ExecJs(
      WebContents(),
      content::JsReplace("create_iframe($1, 'credentialless', true); ",
                         form_url)));
  content::WaitForLoadStop(WebContents());
  content::RenderFrameHost* iframe_normal =
      ChildFrameAt(WebContents()->GetPrimaryMainFrame(), 0);
  content::RenderFrameHost* iframe_credentialless =
      ChildFrameAt(WebContents()->GetPrimaryMainFrame(), 1);

  EXPECT_EQ("pa55w0rd",
            content::EvalJs(iframe_normal,
                            "window.parent.check_password(document);"));
  EXPECT_EQ("not found",
            content::EvalJs(iframe_credentialless,
                            "window.parent.check_password(document);"));

  // 3. Navigate the normal iframe to be a credentialless iframe.
  EXPECT_TRUE(content::ExecJs(
      WebContents(),
      "document.getElementById('normal').credentialless = true"));
  EXPECT_TRUE(content::ExecJs(
      WebContents(),
      content::JsReplace("document.getElementById('normal').src = $1",
                         form_url)));
  content::WaitForLoadStop(WebContents());
  iframe_normal = ChildFrameAt(WebContents()->GetPrimaryMainFrame(), 0);
  EXPECT_EQ("not found",
            content::EvalJs(iframe_normal,
                            "window.parent.check_password(document);"));
}

}  // namespace

}  // namespace password_manager