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
|
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/credentialmanagement/authentication_credentials_container.h"
#include <memory>
#include <optional>
#include <utility>
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "build/build_config.h"
#include "services/network/public/cpp/is_potentially_trustworthy.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/sms/webotp_constants.h"
#include "third_party/blink/public/mojom/credentialmanagement/credential_manager.mojom-blink.h"
#include "third_party/blink/public/mojom/credentialmanagement/credential_type_flags.mojom-blink.h"
#include "third_party/blink/public/mojom/payments/secure_payment_confirmation_service.mojom-blink.h"
#include "third_party/blink/public/mojom/sms/webotp_service.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_union_arraybuffer_arraybufferview.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_all_accepted_credentials_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_client_inputs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_client_outputs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_large_blob_inputs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_large_blob_outputs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_payment_inputs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_prf_inputs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_prf_outputs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_prf_values.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_supplemental_pub_keys_inputs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authentication_extensions_supplemental_pub_keys_outputs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_authenticator_selection_criteria.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_credential_creation_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_credential_properties_output.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_credential_request_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_current_user_details_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_federated_credential_request_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_identity_credential_request_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_identity_provider_config.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_identity_provider_request_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_otp_credential_request_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_public_key_credential_creation_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_public_key_credential_descriptor.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_public_key_credential_parameters.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_public_key_credential_request_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_public_key_credential_rp_entity.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_public_key_credential_user_entity.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_union_htmlformelement_passwordcredentialdata.h"
#include "third_party/blink/renderer/core/dom/abort_signal.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/scoped_abort_state.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/frame.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/navigator.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/page/frame_tree.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_piece.h"
#include "third_party/blink/renderer/modules/credentialmanagement/authenticator_assertion_response.h"
#include "third_party/blink/renderer/modules/credentialmanagement/authenticator_attestation_response.h"
#include "third_party/blink/renderer/modules/credentialmanagement/credential.h"
#include "third_party/blink/renderer/modules/credentialmanagement/credential_manager_proxy.h"
#include "third_party/blink/renderer/modules/credentialmanagement/credential_manager_type_converters.h" // IWYU pragma: keep
#include "third_party/blink/renderer/modules/credentialmanagement/credential_metrics.h"
#include "third_party/blink/renderer/modules/credentialmanagement/credential_utils.h"
#include "third_party/blink/renderer/modules/credentialmanagement/digital_identity_credential.h"
#include "third_party/blink/renderer/modules/credentialmanagement/federated_credential.h"
#include "third_party/blink/renderer/modules/credentialmanagement/identity_credential.h"
#include "third_party/blink/renderer/modules/credentialmanagement/identity_credential_error.h"
#include "third_party/blink/renderer/modules/credentialmanagement/otp_credential.h"
#include "third_party/blink/renderer/modules/credentialmanagement/password_credential.h"
#include "third_party/blink/renderer/modules/credentialmanagement/public_key_credential.h"
#include "third_party/blink/renderer/modules/credentialmanagement/scoped_promise_resolver.h"
#include "third_party/blink/renderer/platform/bindings/exception_code.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/text/base64.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/wtf_size_t.h"
namespace blink {
namespace {
using mojom::blink::AttestationConveyancePreference;
using mojom::blink::AuthenticationExtensionsClientOutputsPtr;
using mojom::blink::AuthenticatorAttachment;
using mojom::blink::AuthenticatorStatus;
using mojom::blink::CredentialInfo;
using mojom::blink::CredentialInfoPtr;
using mojom::blink::CredentialManagerError;
using mojom::blink::CredentialMediationRequirement;
using mojom::blink::WebAuthnDOMExceptionDetailsPtr;
using MojoPublicKeyCredentialCreationOptions =
mojom::blink::PublicKeyCredentialCreationOptions;
using mojom::blink::MakeCredentialAuthenticatorResponsePtr;
using MojoPublicKeyCredentialRequestOptions =
mojom::blink::PublicKeyCredentialRequestOptions;
using mojom::blink::GetAssertionAuthenticatorResponsePtr;
using mojom::blink::Mediation;
using mojom::blink::RequestTokenStatus;
using payments::mojom::blink::PaymentCredentialStorageStatus;
constexpr size_t kMaxLargeBlobSize = 2048; // 2kb.
// RequiredOriginType enumerates the requirements on the environment to perform
// an operation.
enum class RequiredOriginType {
// Must be a secure origin.
kSecure,
// Must be a secure origin and be same-origin with all ancestor frames.
kSecureAndSameWithAncestors,
// Must be a secure origin and the "publickey-credentials-get" permissions
// policy must be enabled. By default "publickey-credentials-get" is not
// inherited by cross-origin child frames, so if that policy is not
// explicitly enabled, behavior is the same as that of
// |kSecureAndSameWithAncestors|. Note that permissions policies can be
// expressed in various ways, e.g.: |allow| iframe attribute and/or
// permissions-policy header, and may be inherited from parent browsing
// contexts. See Permissions Policy spec.
kSecureAndPermittedByWebAuthGetAssertionPermissionsPolicy,
// Must be a secure origin and the "publickey-credentials-create" permissions
// policy must be enabled. By default "publickey-credentials-create" is not
// inherited by cross-origin child frames, so if that policy is not
// explicitly enabled, behavior is the same as that of
// |kSecureAndSameWithAncestors|. Note that permissions policies can be
// expressed in various ways, e.g.: |allow| iframe attribute and/or
// permissions-policy header, and may be inherited from parent browsing
// contexts. See Permissions Policy spec.
kSecureAndPermittedByWebAuthCreateCredentialPermissionsPolicy,
// Similar to the enum above, checks the "otp-credentials" permissions policy.
kSecureAndPermittedByWebOTPAssertionPermissionsPolicy,
// Similar to the enum above, checks the "identity-credentials-get"
// permissions policy.
kSecureAndPermittedByFederatedPermissionsPolicy,
// Must be a secure origin with either the "payment" or
// "publickey-credentials-create" permission policy.
kSecureWithPaymentOrCreateCredentialPermissionPolicy,
};
// Returns whether the number of unique origins in the ancestor chain, including
// the current origin are less or equal to |max_unique_origins|.
//
// Examples:
// A.com = 1 unique origin
// A.com -> A.com = 1 unique origin
// A.com -> A.com -> B.com = 2 unique origins
// A.com -> B.com -> B.com = 2 unique origins
// A.com -> B.com -> A.com = 3 unique origins
bool AreUniqueOriginsLessOrEqualTo(const Frame* frame, int max_unique_origins) {
const SecurityOrigin* current_origin =
frame->GetSecurityContext()->GetSecurityOrigin();
int num_unique_origins = 1;
const Frame* parent = frame->Tree().Parent();
while (parent) {
auto* parent_origin = parent->GetSecurityContext()->GetSecurityOrigin();
if (!parent_origin->IsSameOriginWith(current_origin)) {
++num_unique_origins;
current_origin = parent_origin;
}
if (num_unique_origins > max_unique_origins) {
return false;
}
parent = parent->Tree().Parent();
}
return true;
}
const SecurityOrigin* GetSecurityOrigin(const Frame* frame) {
const SecurityContext* frame_security_context = frame->GetSecurityContext();
if (!frame_security_context) {
return nullptr;
}
return frame_security_context->GetSecurityOrigin();
}
bool IsSameSecurityOriginWithAncestors(const Frame* frame) {
const Frame* current = frame;
const SecurityOrigin* frame_origin = GetSecurityOrigin(frame);
if (!frame_origin) {
return false;
}
while (current->Tree().Parent()) {
current = current->Tree().Parent();
const SecurityOrigin* current_security_origin = GetSecurityOrigin(current);
if (!current_security_origin ||
!frame_origin->IsSameOriginWith(current_security_origin)) {
return false;
}
}
return true;
}
bool IsAncestorChainValidForWebOTP(const Frame* frame) {
return AreUniqueOriginsLessOrEqualTo(
frame, kMaxUniqueOriginInAncestorChainForWebOTP);
}
bool CheckSecurityRequirementsBeforeRequest(
ScriptPromiseResolverBase* resolver,
RequiredOriginType required_origin_type) {
if (!CheckGenericSecurityRequirementsForCredentialsContainerRequest(
resolver)) {
return false;
}
switch (required_origin_type) {
case RequiredOriginType::kSecure:
// This has already been checked.
break;
case RequiredOriginType::kSecureAndSameWithAncestors:
if (!IsSameSecurityOriginWithAncestors(
To<LocalDOMWindow>(resolver->GetExecutionContext())
->GetFrame())) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The following credential operations can only occur in a document "
"which is same-origin with all of its ancestors: storage/retrieval "
"of 'PasswordCredential' and 'FederatedCredential', storage of "
"'PublicKeyCredential'."));
return false;
}
break;
case RequiredOriginType::
kSecureAndPermittedByWebAuthGetAssertionPermissionsPolicy:
// The 'publickey-credentials-get' feature's "default allowlist" is
// "self", which means the webauthn feature is allowed by default in
// same-origin child browsing contexts.
if (!resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::
kPublicKeyCredentialsGet)) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The 'publickey-credentials-get' feature is not enabled in this "
"document. Permissions Policy may be used to delegate Web "
"Authentication capabilities to cross-origin child frames."));
return false;
} else if (!IsSameSecurityOriginWithAncestors(
To<LocalDOMWindow>(resolver->GetExecutionContext())
->GetFrame())) {
UseCounter::Count(
resolver->GetExecutionContext(),
WebFeature::kCredentialManagerCrossOriginPublicKeyGetRequest);
}
break;
case RequiredOriginType::
kSecureAndPermittedByWebAuthCreateCredentialPermissionsPolicy:
// The 'publickey-credentials-create' feature's "default allowlist" is
// "self", which means the webauthn feature is allowed by default in
// same-origin child browsing contexts.
if (!resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::
kPublicKeyCredentialsCreate)) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The 'publickey-credentials-create' feature is not enabled in this "
"document. Permissions Policy may be used to delegate Web "
"Authentication capabilities to cross-origin child frames."));
return false;
} else if (!IsSameSecurityOriginWithAncestors(
To<LocalDOMWindow>(resolver->GetExecutionContext())
->GetFrame())) {
UseCounter::Count(
resolver->GetExecutionContext(),
WebFeature::kCredentialManagerCrossOriginPublicKeyCreateRequest);
}
break;
case RequiredOriginType::
kSecureAndPermittedByWebOTPAssertionPermissionsPolicy:
if (!resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::kOTPCredentials)) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The 'otp-credentials' feature is not enabled in this document."));
return false;
}
if (!IsAncestorChainValidForWebOTP(
To<LocalDOMWindow>(resolver->GetExecutionContext())
->GetFrame())) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"More than two unique origins are detected in the origin chain."));
return false;
}
break;
case RequiredOriginType::kSecureAndPermittedByFederatedPermissionsPolicy:
if (!resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::
kIdentityCredentialsGet)) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The 'identity-credentials-get' feature is not enabled in this "
"document."));
return false;
}
break;
case RequiredOriginType::
kSecureWithPaymentOrCreateCredentialPermissionPolicy:
// For backwards compatibility, SPC credentials (that is, credentials with
// the "payment" extension set) can be created in a cross-origin iframe
// with either the 'payment' or 'publickey-credentials-create' permission
// set.
//
// Note that SPC only goes through the credentials API for creation and
// not authentication. Authentication flows via the Payment Request API,
// which checks for the 'payment' permission separately.
if (!resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::kPayment) &&
!resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::
kPublicKeyCredentialsCreate)) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The 'payment' or 'publickey-credentials-create' features are not "
"enabled in this document. Permissions Policy may be used to "
"delegate Web Payment capabilities to cross-origin child frames."));
return false;
}
break;
}
return true;
}
void AssertSecurityRequirementsBeforeResponse(
ScriptPromiseResolverBase* resolver,
RequiredOriginType require_origin) {
// The |resolver| will blanket ignore Reject/Resolve calls if the context is
// gone -- nevertheless, call Reject() to be on the safe side.
if (!resolver->GetExecutionContext()) {
resolver->Reject();
return;
}
SECURITY_CHECK(To<LocalDOMWindow>(resolver->GetExecutionContext()));
SECURITY_CHECK(resolver->GetExecutionContext()->IsSecureContext());
switch (require_origin) {
case RequiredOriginType::kSecure:
// This has already been checked.
break;
case RequiredOriginType::kSecureAndSameWithAncestors:
SECURITY_CHECK(IsSameSecurityOriginWithAncestors(
To<LocalDOMWindow>(resolver->GetExecutionContext())->GetFrame()));
break;
case RequiredOriginType::
kSecureAndPermittedByWebAuthGetAssertionPermissionsPolicy:
SECURITY_CHECK(resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::kPublicKeyCredentialsGet));
break;
case RequiredOriginType::
kSecureAndPermittedByWebAuthCreateCredentialPermissionsPolicy:
SECURITY_CHECK(resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::
kPublicKeyCredentialsCreate));
break;
case RequiredOriginType::
kSecureAndPermittedByWebOTPAssertionPermissionsPolicy:
SECURITY_CHECK(
resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::kOTPCredentials) &&
IsAncestorChainValidForWebOTP(
To<LocalDOMWindow>(resolver->GetExecutionContext())->GetFrame()));
break;
case RequiredOriginType::kSecureAndPermittedByFederatedPermissionsPolicy:
SECURITY_CHECK(resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::kIdentityCredentialsGet));
break;
case RequiredOriginType::
kSecureWithPaymentOrCreateCredentialPermissionPolicy:
SECURITY_CHECK(resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::kPayment) ||
resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::
kPublicKeyCredentialsCreate));
break;
}
}
// Checks if the icon URL is an a-priori authenticated URL.
// https://w3c.github.io/webappsec-credential-management/#dom-credentialuserdata-iconurl
bool IsIconURLNullOrSecure(const KURL& url) {
if (url.IsNull()) {
return true;
}
if (!url.IsValid()) {
return false;
}
return network::IsUrlPotentiallyTrustworthy(GURL(url));
}
// Checks if the size of the supplied ArrayBuffer or ArrayBufferView is at most
// the maximum size allowed.
bool IsArrayBufferOrViewBelowSizeLimit(
const V8UnionArrayBufferOrArrayBufferView* buffer_or_view) {
if (!buffer_or_view) {
return true;
}
return base::CheckedNumeric<wtf_size_t>(
DOMArrayPiece(buffer_or_view).ByteLength())
.IsValid();
}
bool IsCredentialDescriptorListBelowSizeLimit(
const HeapVector<Member<PublicKeyCredentialDescriptor>>& list) {
return list.size() <= mojom::blink::kPublicKeyCredentialDescriptorListMaxSize;
}
DOMException* CredentialManagerErrorToDOMException(
CredentialManagerError reason) {
switch (reason) {
case CredentialManagerError::PENDING_REQUEST:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError,
"A request is already pending.");
case CredentialManagerError::PASSWORD_STORE_UNAVAILABLE:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The password store is unavailable.");
case CredentialManagerError::UNKNOWN:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotReadableError,
"An unknown error occurred while talking "
"to the credential manager.");
case CredentialManagerError::SUCCESS:
NOTREACHED();
}
return nullptr;
}
// Abort an ongoing IdentityCredential request. This will only be called before
// the request finishes due to `scoped_abort_state`.
void AbortIdentityCredentialRequest(ScriptState* script_state) {
if (!script_state->ContextIsValid()) {
return;
}
auto* auth_request =
CredentialManagerProxy::From(script_state)->FederatedAuthRequest();
auth_request->CancelTokenRequest();
}
void OnRequestToken(std::unique_ptr<ScopedPromiseResolver> scoped_resolver,
std::unique_ptr<ScopedAbortState> scoped_abort_state,
const CredentialRequestOptions* options,
RequestTokenStatus status,
const std::optional<KURL>& selected_idp_config_url,
const WTF::String& token,
mojom::blink::TokenErrorPtr error,
bool is_auto_selected) {
auto* resolver =
scoped_resolver->Release()->DowncastTo<IDLNullable<Credential>>();
switch (status) {
case RequestTokenStatus::kErrorTooManyRequests: {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"Only one navigator.credentials.get request may be outstanding at "
"one time."));
return;
}
case RequestTokenStatus::kErrorCanceled: {
AbortSignal* signal =
scoped_abort_state ? scoped_abort_state->Signal() : nullptr;
if (signal && signal->aborted()) {
auto* script_state = resolver->GetScriptState();
ScriptState::Scope script_state_scope(script_state);
resolver->Reject(signal->reason(script_state));
} else {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kAbortError, "The request has been aborted."));
}
return;
}
case RequestTokenStatus::kError: {
if (!error) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNetworkError, "Error retrieving a token."));
return;
}
resolver->Reject(MakeGarbageCollected<IdentityCredentialError>(
"Error retrieving a token.", error->code, error->url));
return;
}
case RequestTokenStatus::kSuccess: {
CHECK(selected_idp_config_url);
IdentityCredential* credential = IdentityCredential::Create(
token, is_auto_selected, *selected_idp_config_url);
resolver->Resolve(credential);
return;
}
default: {
NOTREACHED();
}
}
}
void OnStoreComplete(std::unique_ptr<ScopedPromiseResolver> scoped_resolver) {
auto* resolver = scoped_resolver->Release()->DowncastTo<Credential>();
AssertSecurityRequirementsBeforeResponse(
resolver, RequiredOriginType::kSecureAndSameWithAncestors);
resolver->Resolve();
}
void OnPreventSilentAccessComplete(
std::unique_ptr<ScopedPromiseResolver> scoped_resolver) {
auto* resolver = scoped_resolver->Release()->DowncastTo<IDLUndefined>();
const auto required_origin_type = RequiredOriginType::kSecure;
AssertSecurityRequirementsBeforeResponse(resolver, required_origin_type);
resolver->Resolve();
}
void OnGetComplete(std::unique_ptr<ScopedPromiseResolver> scoped_resolver,
RequiredOriginType required_origin_type,
Mediation mediation,
CredentialManagerError error,
CredentialInfoPtr credential_info) {
auto* resolver =
scoped_resolver->Release()->DowncastTo<IDLNullable<Credential>>();
AssertSecurityRequirementsBeforeResponse(resolver, required_origin_type);
if (error != CredentialManagerError::SUCCESS) {
DCHECK(!credential_info);
if (mediation == Mediation::IMMEDIATE) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialsGetImmediateMediationFailure);
}
resolver->Reject(CredentialManagerErrorToDOMException(error));
return;
}
DCHECK(credential_info);
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialManagerGetReturnedCredential);
if (mediation == Mediation::IMMEDIATE) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialsGetImmediateMediationPasswordSuccess);
}
resolver->Resolve(mojo::ConvertTo<Credential*>(std::move(credential_info)));
}
DOMArrayBuffer* VectorToDOMArrayBuffer(const Vector<uint8_t> buffer) {
return DOMArrayBuffer::Create(buffer);
}
AuthenticationExtensionsPRFValues* GetPRFExtensionResults(
const mojom::blink::PRFValuesPtr& prf_results) {
auto* values = AuthenticationExtensionsPRFValues::Create();
values->setFirst(MakeGarbageCollected<V8UnionArrayBufferOrArrayBufferView>(
VectorToDOMArrayBuffer(std::move(prf_results->first))));
if (prf_results->second) {
values->setSecond(MakeGarbageCollected<V8UnionArrayBufferOrArrayBufferView>(
VectorToDOMArrayBuffer(std::move(prf_results->second.value()))));
}
return values;
}
void OnMakePublicKeyCredentialComplete(
std::unique_ptr<ScopedPromiseResolver> scoped_resolver,
std::unique_ptr<ScopedAbortState> scoped_abort_state,
FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle feature_handle,
RequiredOriginType required_origin_type,
bool is_rk_required,
AuthenticatorStatus status,
MakeCredentialAuthenticatorResponsePtr credential,
WebAuthnDOMExceptionDetailsPtr dom_exception_details) {
auto* resolver =
scoped_resolver->Release()->DowncastTo<IDLNullable<Credential>>();
AssertSecurityRequirementsBeforeResponse(resolver, required_origin_type);
if (status != AuthenticatorStatus::SUCCESS) {
DCHECK(!credential);
AbortSignal* signal =
scoped_abort_state ? scoped_abort_state->Signal() : nullptr;
if (signal && signal->aborted()) {
auto* script_state = resolver->GetScriptState();
ScriptState::Scope script_state_scope(script_state);
resolver->Reject(signal->reason(script_state));
} else {
resolver->Reject(
AuthenticatorStatusToDOMException(status, dom_exception_details));
}
return;
}
DCHECK(credential);
DCHECK(!credential->info->client_data_json.empty());
DCHECK(!credential->attestation_object.empty());
UseCounter::Count(
resolver->GetExecutionContext(),
WebFeature::kCredentialManagerMakePublicKeyCredentialSuccess);
if (is_rk_required) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kWebAuthnRkRequiredCreationSuccess);
}
DOMArrayBuffer* client_data_buffer =
VectorToDOMArrayBuffer(std::move(credential->info->client_data_json));
DOMArrayBuffer* raw_id =
VectorToDOMArrayBuffer(std::move(credential->info->raw_id));
DOMArrayBuffer* attestation_buffer =
VectorToDOMArrayBuffer(std::move(credential->attestation_object));
DOMArrayBuffer* authenticator_data =
VectorToDOMArrayBuffer(std::move(credential->info->authenticator_data));
DOMArrayBuffer* public_key_der = nullptr;
if (credential->public_key_der) {
public_key_der =
VectorToDOMArrayBuffer(std::move(credential->public_key_der.value()));
}
auto* authenticator_response =
MakeGarbageCollected<AuthenticatorAttestationResponse>(
client_data_buffer, attestation_buffer, credential->transports,
authenticator_data, public_key_der, credential->public_key_algo);
AuthenticationExtensionsClientOutputs* extension_outputs =
AuthenticationExtensionsClientOutputs::Create();
if (credential->echo_hmac_create_secret) {
extension_outputs->setHmacCreateSecret(credential->hmac_create_secret);
}
if (credential->echo_cred_props) {
CredentialPropertiesOutput* cred_props_output =
CredentialPropertiesOutput::Create();
if (credential->has_cred_props_rk) {
cred_props_output->setRk(credential->cred_props_rk);
}
extension_outputs->setCredProps(cred_props_output);
}
if (credential->echo_cred_blob) {
extension_outputs->setCredBlob(credential->cred_blob);
}
if (credential->echo_large_blob) {
AuthenticationExtensionsLargeBlobOutputs* large_blob_outputs =
AuthenticationExtensionsLargeBlobOutputs::Create();
large_blob_outputs->setSupported(credential->supports_large_blob);
extension_outputs->setLargeBlob(large_blob_outputs);
}
if (credential->supplemental_pub_keys) {
extension_outputs->setSupplementalPubKeys(
ConvertTo<AuthenticationExtensionsSupplementalPubKeysOutputs*>(
credential->supplemental_pub_keys));
}
if (credential->payment) {
CHECK(base::FeatureList::IsEnabled(
blink::features::kSecurePaymentConfirmationBrowserBoundKeys));
extension_outputs->setPayment(
ConvertTo<blink::AuthenticationExtensionsPaymentOutputs*>(
credential->payment));
}
if (credential->echo_prf) {
auto* prf_outputs = AuthenticationExtensionsPRFOutputs::Create();
prf_outputs->setEnabled(credential->prf);
if (credential->prf_results) {
prf_outputs->setResults(GetPRFExtensionResults(credential->prf_results));
}
extension_outputs->setPrf(prf_outputs);
}
resolver->Resolve(MakeGarbageCollected<PublicKeyCredential>(
credential->info->id, raw_id, authenticator_response,
credential->authenticator_attachment, extension_outputs));
}
bool IsForPayment(const CredentialCreationOptions* options,
ExecutionContext* context) {
return RuntimeEnabledFeatures::SecurePaymentConfirmationEnabled(context) &&
options->hasPublicKey() && options->publicKey()->hasExtensions() &&
options->publicKey()->extensions()->hasPayment() &&
options->publicKey()->extensions()->payment()->hasIsPayment() &&
options->publicKey()->extensions()->payment()->isPayment();
}
void OnSaveCredentialIdForPaymentExtension(
std::unique_ptr<ScopedPromiseResolver> scoped_resolver,
std::unique_ptr<ScopedAbortState> scoped_abort_state,
FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle feature_handle,
MakeCredentialAuthenticatorResponsePtr credential,
PaymentCredentialStorageStatus storage_status) {
auto status = AuthenticatorStatus::SUCCESS;
if (storage_status != PaymentCredentialStorageStatus::SUCCESS) {
status =
AuthenticatorStatus::FAILED_TO_SAVE_CREDENTIAL_ID_FOR_PAYMENT_EXTENSION;
credential = nullptr;
}
OnMakePublicKeyCredentialComplete(
std::move(scoped_resolver), std::move(scoped_abort_state),
std::move(feature_handle),
RequiredOriginType::kSecureWithPaymentOrCreateCredentialPermissionPolicy,
/*is_rk_required=*/false, status, std::move(credential),
/*dom_exception_details=*/nullptr);
}
void OnMakePublicKeyCredentialWithPaymentExtensionComplete(
std::unique_ptr<ScopedPromiseResolver> scoped_resolver,
std::unique_ptr<ScopedAbortState> scoped_abort_state,
FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle feature_handle,
const String& rp_id_for_payment_extension,
const WTF::Vector<uint8_t>& user_id_for_payment_extension,
AuthenticatorStatus status,
MakeCredentialAuthenticatorResponsePtr credential,
WebAuthnDOMExceptionDetailsPtr dom_exception_details) {
auto* resolver =
scoped_resolver->Release()->DowncastTo<IDLNullable<Credential>>();
AssertSecurityRequirementsBeforeResponse(
resolver,
RequiredOriginType::kSecureWithPaymentOrCreateCredentialPermissionPolicy);
if (status != AuthenticatorStatus::SUCCESS) {
DCHECK(!credential);
AbortSignal* signal =
scoped_abort_state ? scoped_abort_state->Signal() : nullptr;
if (signal && signal->aborted()) {
auto* script_state = resolver->GetScriptState();
ScriptState::Scope script_state_scope(script_state);
resolver->Reject(signal->reason(script_state));
} else {
resolver->Reject(
AuthenticatorStatusToDOMException(status, dom_exception_details));
}
return;
}
Vector<uint8_t> credential_id = credential->info->raw_id;
auto* spc_service = CredentialManagerProxy::From(resolver->GetScriptState())
->SecurePaymentConfirmationService();
spc_service->StorePaymentCredential(
std::move(credential_id), rp_id_for_payment_extension,
std::move(user_id_for_payment_extension),
WTF::BindOnce(&OnSaveCredentialIdForPaymentExtension,
std::make_unique<ScopedPromiseResolver>(resolver),
std::move(scoped_abort_state), std::move(feature_handle),
std::move(credential)));
}
void OnGetAssertionComplete(
std::unique_ptr<ScopedPromiseResolver> scoped_resolver,
std::unique_ptr<ScopedAbortState> scoped_abort_state,
FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle feature_handle,
Mediation mediation,
AuthenticatorStatus status,
GetAssertionAuthenticatorResponsePtr credential,
WebAuthnDOMExceptionDetailsPtr dom_exception_details) {
auto* resolver =
scoped_resolver->Release()->DowncastTo<IDLNullable<Credential>>();
const auto required_origin_type = RequiredOriginType::kSecure;
AssertSecurityRequirementsBeforeResponse(resolver, required_origin_type);
if (status == AuthenticatorStatus::SUCCESS) {
DCHECK(credential);
DCHECK(!credential->signature.empty());
DCHECK(!credential->info->authenticator_data.empty());
UseCounter::Count(
resolver->GetExecutionContext(),
WebFeature::kCredentialManagerGetPublicKeyCredentialSuccess);
if (mediation == Mediation::CONDITIONAL) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kWebAuthnConditionalUiGetSuccess);
} else if (mediation == Mediation::IMMEDIATE) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialsGetImmediateMediationPublicKeySuccess);
}
auto* authenticator_response =
MakeGarbageCollected<AuthenticatorAssertionResponse>(
std::move(credential->info->client_data_json),
std::move(credential->info->authenticator_data),
std::move(credential->signature), credential->user_handle);
AuthenticationExtensionsClientOutputs* extension_outputs =
ConvertTo<AuthenticationExtensionsClientOutputs*>(
credential->extensions);
#if BUILDFLAG(IS_ANDROID)
if (credential->extensions->echo_user_verification_methods) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialManagerGetSuccessWithUVM);
}
#endif
resolver->Resolve(MakeGarbageCollected<PublicKeyCredential>(
credential->info->id,
VectorToDOMArrayBuffer(std::move(credential->info->raw_id)),
authenticator_response, credential->authenticator_attachment,
extension_outputs));
return;
}
if (mediation == Mediation::IMMEDIATE) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialsGetImmediateMediationFailure);
}
DCHECK(!credential);
AbortSignal* signal =
scoped_abort_state ? scoped_abort_state->Signal() : nullptr;
if (signal && signal->aborted()) {
auto* script_state = resolver->GetScriptState();
ScriptState::Scope script_state_scope(script_state);
resolver->Reject(signal->reason(script_state));
} else {
resolver->Reject(
AuthenticatorStatusToDOMException(status, dom_exception_details));
}
}
void OnAuthenticatorGetCredentialComplete(
std::unique_ptr<ScopedPromiseResolver> scoped_resolver,
std::unique_ptr<ScopedAbortState> scoped_abort_state,
FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle feature_handle,
Mediation mediation,
mojom::blink::GetCredentialResponsePtr get_credential_response) {
if (!get_credential_response) {
return;
}
if (get_credential_response->is_get_assertion_response()) {
auto get_assertion_response =
std::move(get_credential_response->get_get_assertion_response());
OnGetAssertionComplete(
std::move(scoped_resolver), std::move(scoped_abort_state),
std::move(feature_handle), mediation,
std::move(get_assertion_response->status),
std::move(get_assertion_response->credential),
std::move(get_assertion_response->dom_exception_details));
return;
}
auto password_response =
std::move(get_credential_response->get_password_response());
OnGetComplete(std::move(scoped_resolver), RequiredOriginType::kSecure,
mediation, CredentialManagerError::SUCCESS, std::move(password_response));
}
void OnSmsReceive(ScriptPromiseResolver<IDLNullable<Credential>>* resolver,
std::unique_ptr<ScopedAbortState> scoped_abort_state,
base::TimeTicks start_time,
mojom::blink::SmsStatus status,
const String& otp) {
AssertSecurityRequirementsBeforeResponse(
resolver, resolver->GetExecutionContext()->IsFeatureEnabled(
network::mojom::PermissionsPolicyFeature::kOTPCredentials)
? RequiredOriginType::
kSecureAndPermittedByWebOTPAssertionPermissionsPolicy
: RequiredOriginType::kSecureAndSameWithAncestors);
if (status == mojom::blink::SmsStatus::kUnhandledRequest) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError,
"OTP retrieval request not handled."));
return;
}
if (status == mojom::blink::SmsStatus::kAborted) {
AbortSignal* signal =
scoped_abort_state ? scoped_abort_state->Signal() : nullptr;
if (signal && signal->aborted()) {
auto* script_state = resolver->GetScriptState();
ScriptState::Scope script_state_scope(script_state);
resolver->Reject(signal->reason(script_state));
} else {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kAbortError, "OTP retrieval was aborted."));
}
return;
}
if (status == mojom::blink::SmsStatus::kCancelled) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kAbortError, "OTP retrieval was cancelled."));
return;
}
if (status == mojom::blink::SmsStatus::kTimeout) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError, "OTP retrieval timed out."));
return;
}
if (status == mojom::blink::SmsStatus::kBackendNotAvailable) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError, "OTP backend unavailable."));
return;
}
resolver->Resolve(MakeGarbageCollected<OTPCredential>(otp));
}
// Validates the "payment" extension for public key credential creation. The
// function rejects the promise before returning in this case.
bool IsPaymentExtensionValid(const CredentialCreationOptions* options,
ScriptPromiseResolverBase* resolver) {
const auto* payment = options->publicKey()->extensions()->payment();
if (!payment->hasIsPayment() || !payment->isPayment()) {
return true;
}
const auto* context = resolver->GetExecutionContext();
DCHECK(RuntimeEnabledFeatures::SecurePaymentConfirmationEnabled(context));
if (RuntimeEnabledFeatures::SecurePaymentConfirmationDebugEnabled()) {
return true;
}
if (!options->publicKey()->hasAuthenticatorSelection()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"A user verifying platform authenticator with resident key support is "
"required for 'payment' extension."));
return false;
}
const auto* authenticator = options->publicKey()->authenticatorSelection();
if (!authenticator->hasUserVerification() ||
authenticator->userVerification() != "required") {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"User verification is required for 'payment' extension."));
return false;
}
if ((!authenticator->hasResidentKey() &&
!authenticator->hasRequireResidentKey()) ||
(authenticator->hasResidentKey() &&
authenticator->residentKey() == "discouraged") ||
(!authenticator->hasResidentKey() &&
authenticator->hasRequireResidentKey() &&
!authenticator->requireResidentKey())) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"A resident key must be 'preferred' or 'required' for 'payment' "
"extension."));
return false;
}
if (!authenticator->hasAuthenticatorAttachment() ||
authenticator->authenticatorAttachment() != "platform") {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"A platform authenticator is required for 'payment' extension."));
return false;
}
return true;
}
const char* validatePRFInputs(
const blink::AuthenticationExtensionsPRFValues& values) {
constexpr size_t kMaxInputSize = 256;
if (DOMArrayPiece(values.first()).ByteLength() > kMaxInputSize ||
(values.hasSecond() &&
DOMArrayPiece(values.second()).ByteLength() > kMaxInputSize)) {
return "'prf' extension contains excessively large input";
}
return nullptr;
}
const char* validateCreatePublicKeyCredentialPRFExtension(
const AuthenticationExtensionsPRFInputs& prf) {
if (prf.hasEval()) {
const char* error = validatePRFInputs(*prf.eval());
if (error != nullptr) {
return error;
}
}
if (prf.hasEvalByCredential()) {
return "The 'evalByCredential' field cannot be set when creating a "
"credential.";
}
return nullptr;
}
const char* validateGetPublicKeyCredentialPRFExtension(
const AuthenticationExtensionsPRFInputs& prf,
const HeapVector<Member<PublicKeyCredentialDescriptor>>&
allow_credentials) {
std::vector<base::span<const uint8_t>> cred_ids;
cred_ids.reserve(allow_credentials.size());
for (const auto cred : allow_credentials) {
DOMArrayPiece piece(cred->id());
cred_ids.emplace_back(piece.Bytes(), piece.ByteLength());
}
const auto compare = [](base::span<const uint8_t> a,
base::span<const uint8_t> b) {
return std::ranges::lexicographical_compare(a, b);
};
std::ranges::sort(cred_ids, compare);
if (prf.hasEval()) {
const char* error = validatePRFInputs(*prf.eval());
if (error != nullptr) {
return error;
}
}
if (prf.hasEvalByCredential()) {
for (const auto& pair : prf.evalByCredential()) {
Vector<uint8_t> cred_id;
if (!pair.first.Is8Bit() ||
!Base64UnpaddedURLDecode(pair.first, cred_id)) {
return "'prf' extension contains invalid base64url data in "
"'evalByCredential'";
}
if (cred_id.empty()) {
return "'prf' extension contains an empty credential ID in "
"'evalByCredential'";
}
if (!std::ranges::binary_search(cred_ids, base::as_byte_span(cred_id),
compare)) {
return "'prf' extension contains 'evalByCredential' key that doesn't "
"match any in allowedCredentials";
}
const char* error = validatePRFInputs(*pair.second);
if (error != nullptr) {
return error;
}
}
}
return nullptr;
}
void EmitImmediateMediationUseCounters(
ExecutionContext* context,
const CredentialRequestOptions* options) {
CHECK(options->hasMediation() && options->mediation() == "immediate");
if (options->hasPublicKey() && options->password()) {
UseCounter::Count(
context,
WebFeature::kCredentialsGetImmediateMediationWithWebAuthnAndPasswords);
} else if (options->hasPublicKey()) {
UseCounter::Count(
context, WebFeature::kCredentialsGetImmediateMediationWithWebAuthnOnly);
}
// TODO(crbug.com/392549444): Add other combinations.
}
} // namespace
const char AuthenticationCredentialsContainer::kSupplementName[] =
"AuthenticationCredentialsContainer";
DOMException* AuthenticatorStatusToDOMException(
AuthenticatorStatus status,
const WebAuthnDOMExceptionDetailsPtr& dom_exception_details) {
DCHECK_EQ(status != AuthenticatorStatus::ERROR_WITH_DOM_EXCEPTION_DETAILS,
dom_exception_details.is_null());
switch (status) {
case AuthenticatorStatus::SUCCESS:
NOTREACHED();
case AuthenticatorStatus::PENDING_REQUEST:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kOperationError, "A request is already pending.");
case AuthenticatorStatus::NOT_ALLOWED_ERROR:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The operation either timed out or was not allowed. See: "
"https://www.w3.org/TR/webauthn-2/"
"#sctn-privacy-considerations-client.");
case AuthenticatorStatus::INVALID_DOMAIN:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError, "This is an invalid domain.");
case AuthenticatorStatus::CREDENTIAL_EXCLUDED:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError,
"The user attempted to register an authenticator that contains one "
"of the credentials already registered with the relying party.");
case AuthenticatorStatus::NOT_IMPLEMENTED:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError, "Not implemented");
case AuthenticatorStatus::NOT_FOCUSED:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The operation is not allowed at this time "
"because the page does not have focus.");
case AuthenticatorStatus::RESIDENT_CREDENTIALS_UNSUPPORTED:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Resident credentials or empty "
"'allowCredentials' lists are not supported "
"at this time.");
case AuthenticatorStatus::USER_VERIFICATION_UNSUPPORTED:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The specified `userVerification` "
"requirement cannot be fulfilled by "
"this device unless the device is secured "
"with a screen lock.");
case AuthenticatorStatus::ALGORITHM_UNSUPPORTED:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"None of the algorithms specified in "
"`pubKeyCredParams` are supported by "
"this device.");
case AuthenticatorStatus::EMPTY_ALLOW_CREDENTIALS:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Use of an empty `allowCredentials` list is "
"not supported on this device.");
case AuthenticatorStatus::ANDROID_NOT_SUPPORTED_ERROR:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Either the device has received unexpected "
"request parameters, or the device "
"cannot support this request.");
case AuthenticatorStatus::PROTECTION_POLICY_INCONSISTENT:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Requested protection policy is inconsistent or incongruent with "
"other requested parameters.");
case AuthenticatorStatus::ABORT_ERROR:
return MakeGarbageCollected<DOMException>(DOMExceptionCode::kAbortError,
"Request has been aborted.");
case AuthenticatorStatus::OPAQUE_DOMAIN:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The current origin is an opaque origin and hence not allowed to "
"access 'PublicKeyCredential' objects.");
case AuthenticatorStatus::INVALID_PROTOCOL:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"Public-key credentials are only available to HTTPS origins with "
"valid certificates, HTTP origins that fall under 'localhost', or "
"pages served from an extension. See "
"https://chromium.googlesource.com/chromium/src/+/main/content/"
"browser/webauth/origins.md for details");
case AuthenticatorStatus::BAD_RELYING_PARTY_ID:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"The relying party ID is not a registrable domain suffix of, nor "
"equal to the current domain.");
case AuthenticatorStatus::BAD_RELYING_PARTY_ID_ATTEMPTED_FETCH:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"The relying party ID is not a registrable domain suffix of, nor "
"equal to the current domain. Subsequently, an attempt to fetch the "
".well-known/webauthn resource of the claimed RP ID failed.");
case AuthenticatorStatus::BAD_RELYING_PARTY_ID_WRONG_CONTENT_TYPE:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"The relying party ID is not a registrable domain suffix of, nor "
"equal to the current domain. Subsequently, the "
".well-known/webauthn resource of the claimed RP ID had the "
"wrong content-type. (It should be application/json.)");
case AuthenticatorStatus::BAD_RELYING_PARTY_ID_JSON_PARSE_ERROR:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"The relying party ID is not a registrable domain suffix of, nor "
"equal to the current domain. Subsequently, fetching the "
".well-known/webauthn resource of the claimed RP ID resulted "
"in a JSON parse error.");
case AuthenticatorStatus::BAD_RELYING_PARTY_ID_NO_JSON_MATCH:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"The relying party ID is not a registrable domain suffix of, nor "
"equal to the current domain. Subsequently, fetching the "
".well-known/webauthn resource of the claimed RP ID was "
"successful, but no listed origin matched the caller.");
case AuthenticatorStatus::BAD_RELYING_PARTY_ID_NO_JSON_MATCH_HIT_LIMITS:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"The relying party ID is not a registrable domain suffix of, nor "
"equal to the current domain. Subsequently, fetching the "
".well-known/webauthn resource of the claimed RP ID was "
"successful, but no listed origin matched the caller. Note that a "
"match may have been found but the limit on the number of eTLD+1 "
"labels was reached, causing some entries to be ignored.");
case AuthenticatorStatus::CANNOT_READ_AND_WRITE_LARGE_BLOB:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Only one of the 'largeBlob' extension's 'read' and 'write' "
"parameters is allowed at a time");
case AuthenticatorStatus::INVALID_ALLOW_CREDENTIALS_FOR_LARGE_BLOB:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The 'largeBlob' extension's 'write' parameter can only be used "
"with a single credential present on 'allowCredentials'");
case AuthenticatorStatus::
FAILED_TO_SAVE_CREDENTIAL_ID_FOR_PAYMENT_EXTENSION:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotReadableError,
"Failed to save the credential identifier for the 'payment' "
"extension.");
case AuthenticatorStatus::REMOTE_DESKTOP_CLIENT_OVERRIDE_NOT_AUTHORIZED:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"This origin is not permitted to use the "
"'remoteDesktopClientOverride' extension.");
case AuthenticatorStatus::CERTIFICATE_ERROR:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"WebAuthn is not supported on sites with TLS certificate errors.");
case AuthenticatorStatus::ERROR_WITH_DOM_EXCEPTION_DETAILS:
return DOMException::Create(
/*message=*/dom_exception_details->message,
/*name=*/dom_exception_details->name);
case AuthenticatorStatus::DEVICE_PUBLIC_KEY_ATTESTATION_REJECTED:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The authenticator responded with an invalid message");
case AuthenticatorStatus::UNKNOWN_ERROR:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotReadableError,
"An unknown error occurred while talking "
"to the credential manager.");
case AuthenticatorStatus::IMMEDIATE_NOT_FOUND:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"No immediate discoverable credentials are found.");
}
return nullptr;
}
class AuthenticationCredentialsContainer::OtpRequestAbortAlgorithm final
: public AbortSignal::Algorithm {
public:
explicit OtpRequestAbortAlgorithm(ScriptState* script_state)
: script_state_(script_state) {}
~OtpRequestAbortAlgorithm() override = default;
// Abort an ongoing OtpCredential get() operation.
void Run() override {
if (!script_state_->ContextIsValid()) {
return;
}
auto* webotp_service =
CredentialManagerProxy::From(script_state_)->WebOTPService();
webotp_service->Abort();
}
void Trace(Visitor* visitor) const override {
visitor->Trace(script_state_);
Algorithm::Trace(visitor);
}
private:
Member<ScriptState> script_state_;
};
class AuthenticationCredentialsContainer::PublicKeyRequestAbortAlgorithm final
: public AbortSignal::Algorithm {
public:
explicit PublicKeyRequestAbortAlgorithm(ScriptState* script_state)
: script_state_(script_state) {}
~PublicKeyRequestAbortAlgorithm() override = default;
// Abort an ongoing PublicKeyCredential create() or get() operation.
void Run() override {
if (!script_state_->ContextIsValid()) {
return;
}
auto* authenticator =
CredentialManagerProxy::From(script_state_)->Authenticator();
authenticator->Cancel();
}
void Trace(Visitor* visitor) const override {
visitor->Trace(script_state_);
Algorithm::Trace(visitor);
}
private:
Member<ScriptState> script_state_;
};
CredentialsContainer* AuthenticationCredentialsContainer::credentials(
Navigator& navigator) {
AuthenticationCredentialsContainer* credentials =
Supplement<Navigator>::From<AuthenticationCredentialsContainer>(
navigator);
if (!credentials) {
credentials =
MakeGarbageCollected<AuthenticationCredentialsContainer>(navigator);
ProvideTo(navigator, credentials);
}
return credentials;
}
AuthenticationCredentialsContainer::AuthenticationCredentialsContainer(
Navigator& navigator)
: Supplement<Navigator>(navigator) {}
ScriptPromise<IDLNullable<Credential>> AuthenticationCredentialsContainer::get(
ScriptState* script_state,
const CredentialRequestOptions* options,
ExceptionState& exception_state) {
if (!script_state->ContextIsValid()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Context is detached");
return ScriptPromise<IDLNullable<Credential>>();
}
auto* resolver =
MakeGarbageCollected<ScriptPromiseResolver<IDLNullable<Credential>>>(
script_state, exception_state.GetContext());
auto promise = resolver->Promise();
ExecutionContext* context = ExecutionContext::From(script_state);
if (options->hasSignal() && options->signal()->aborted()) {
resolver->Reject(options->signal()->reason(script_state));
return promise;
}
if (RuntimeEnabledFeatures::WebIdentityDigitalCredentialsEnabled(
resolver->GetExecutionContext()) &&
IsDigitalIdentityCredentialType(*options)) {
DiscoverDigitalIdentityCredentialFromExternalSource(resolver, *options,
exception_state);
return promise;
}
if (options->hasPublicKey() && !options->publicKey()->hasChallenge()) {
if (!blink::RuntimeEnabledFeatures::
WebAuthenticationChallengeUrlEnabled()) {
resolver->RejectWithTypeError(
"Failed to read the 'challenge' property from "
"'PublicKeyCredentialRequestOptions'");
return promise;
} else if (!options->publicKey()->hasChallengeUrl()) {
resolver->RejectWithTypeError(
"Failed to read 'challenge' or 'challengeUrl' property from "
"'PublicKeyCredentialRequestOptions'");
return promise;
}
// Relative URLs have to be turned to absolute URLs before the type
// converter builds the mojo struct.
options->publicKey()->setChallengeUrl(
context->CompleteURL(options->publicKey()->challengeUrl()));
}
auto required_origin_type = RequiredOriginType::kSecureAndSameWithAncestors;
// hasPublicKey() implies that this is a WebAuthn request.
if (options->hasPublicKey()) {
required_origin_type = RequiredOriginType::
kSecureAndPermittedByWebAuthGetAssertionPermissionsPolicy;
} else if (options->hasOtp() &&
RuntimeEnabledFeatures::WebOTPAssertionFeaturePolicyEnabled()) {
required_origin_type = RequiredOriginType::
kSecureAndPermittedByWebOTPAssertionPermissionsPolicy;
} else if (options->hasIdentity() && options->identity()->hasProviders() &&
options->identity()->providers().size() == 1) {
required_origin_type =
RequiredOriginType::kSecureAndPermittedByFederatedPermissionsPolicy;
}
if (!CheckSecurityRequirementsBeforeRequest(resolver, required_origin_type)) {
return promise;
}
uint32_t requested_credential_types =
static_cast<int>(mojom::blink::CredentialTypeFlags::kNone);
// TODO(cbiesinger): Consider removing the hasIdentity() check after FedCM
// ships. Before then, it is useful for RPs to pass both identity and
// federated while transitioning from the older to the new API.
if (options->hasFederated() && options->federated()->hasProviders() &&
options->federated()->providers().size() > 0 && !options->hasIdentity()) {
UseCounter::Count(
context, WebFeature::kCredentialManagerGetLegacyFederatedCredential);
}
if (options->hasPublicKey()) {
requested_credential_types |=
static_cast<int>(mojom::blink::CredentialTypeFlags::kPublicKey);
}
if (options->hasPassword() && options->password()) {
UseCounter::Count(context,
WebFeature::kCredentialManagerGetPasswordCredential);
requested_credential_types |=
static_cast<int>(mojom::blink::CredentialTypeFlags::kPassword);
}
// TODO(crbug.com/358119268): For prototyping, any conditionally-mediated
// request that contains both password and publicKey credential types is
// assumed to be ambient, when the flag is on. This will change.
if (RuntimeEnabledFeatures::WebAuthenticationAmbientEnabled() &&
options->hasPublicKey() && options->hasPassword() &&
options->password() && options->mediation() == "conditional") {
// Unsupported ambient credential types:
if (options->hasOtp() || options->hasIdentity() ||
(options->publicKey()->hasExtensions() &&
options->publicKey()->extensions()->hasPayment()) ||
options->hasFederated()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Unsupported combination of credential types requested."));
return promise;
}
}
if (options->hasPublicKey()) {
UseCounter::Count(context,
WebFeature::kCredentialManagerGetPublicKeyCredential);
#if BUILDFLAG(IS_ANDROID)
if (options->publicKey()->hasExtensions() &&
options->publicKey()->extensions()->hasUvm()) {
UseCounter::Count(context, WebFeature::kCredentialManagerGetWithUVM);
}
#endif
if (options->publicKey()->hasChallenge() &&
!IsArrayBufferOrViewBelowSizeLimit(options->publicKey()->challenge())) {
resolver->Reject(DOMException::Create(
"The `challenge` attribute exceeds the maximum allowed size.",
"RangeError"));
return promise;
}
if (!IsCredentialDescriptorListBelowSizeLimit(
options->publicKey()->allowCredentials())) {
resolver->Reject(
DOMException::Create("The `allowCredentials` attribute exceeds the "
"maximum allowed size (64).",
"RangeError"));
return promise;
}
if (options->publicKey()->hasExtensions()) {
if (options->publicKey()->extensions()->hasAppid()) {
const auto& appid = options->publicKey()->extensions()->appid();
if (!appid.empty()) {
KURL appid_url(appid);
if (!appid_url.IsValid()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSyntaxError,
"The `appid` extension value is neither "
"empty/null nor a valid URL"));
return promise;
}
}
}
if (options->publicKey()->extensions()->credProps()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The 'credProps' extension is only valid when creating "
"a credential"));
return promise;
}
if (options->publicKey()->extensions()->hasLargeBlob()) {
if (options->publicKey()->extensions()->largeBlob()->hasSupport()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The 'largeBlob' extension's 'support' parameter is only valid "
"when creating a credential"));
return promise;
}
if (options->publicKey()->extensions()->largeBlob()->hasWrite()) {
const size_t write_size =
DOMArrayPiece(
options->publicKey()->extensions()->largeBlob()->write())
.ByteLength();
if (write_size > kMaxLargeBlobSize) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The 'largeBlob' extension's 'write' parameter exceeds the "
"maximum allowed size (2kb)"));
return promise;
}
}
}
if (options->publicKey()->extensions()->hasPrf()) {
if (options->publicKey()->extensions()->prf()->hasEvalByCredential() &&
options->publicKey()->allowCredentials().empty()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"'prf' extension has 'evalByCredential' with an empty allow "
"list"));
return promise;
}
const char* error = validateGetPublicKeyCredentialPRFExtension(
*options->publicKey()->extensions()->prf(),
options->publicKey()->allowCredentials());
if (error != nullptr) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSyntaxError, error));
return promise;
}
// Prohibiting uv=preferred is omitted. See
// https://github.com/w3c/webauthn/pull/1836.
}
if (RuntimeEnabledFeatures::SecurePaymentConfirmationEnabled(context) &&
options->publicKey()->extensions()->hasPayment()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"The 'payment' extension is only valid when creating a "
"credential"));
return promise;
}
}
if (options->publicKey()->hasUserVerification() &&
!mojo::ConvertTo<
std::optional<mojom::blink::UserVerificationRequirement>>(
options->publicKey()->userVerification())) {
resolver->GetExecutionContext()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kJavaScript,
mojom::blink::ConsoleMessageLevel::kWarning,
"Ignoring unknown publicKey.userVerification value"));
}
std::unique_ptr<ScopedAbortState> scoped_abort_state = nullptr;
if (auto* signal = options->getSignalOr(nullptr)) {
auto* handle = signal->AddAlgorithm(
MakeGarbageCollected<PublicKeyRequestAbortAlgorithm>(script_state));
scoped_abort_state = std::make_unique<ScopedAbortState>(signal, handle);
}
Mediation mediation = Mediation::MODAL;
if (options->mediation() == "conditional") {
UseCounter::Count(context, WebFeature::kWebAuthnConditionalUiGet);
CredentialMetrics::From(script_state).RecordWebAuthnConditionalUiCall();
mediation = Mediation::CONDITIONAL;
} else if (options->mediation() == "immediate") {
if (RuntimeEnabledFeatures::WebAuthenticationImmediateGetEnabled(
context)) {
mediation = Mediation::IMMEDIATE;
EmitImmediateMediationUseCounters(context, options);
} else {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Immediate mediation not implemented"));
return promise;
}
}
if (mediation == Mediation::IMMEDIATE) {
if (!options->publicKey()->allowCredentials().empty()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"An allowCredentials is not allowed with immediate mediation."));
return promise;
}
if (!LocalFrame::ConsumeTransientUserActivation(
To<LocalDOMWindow>(resolver->GetExecutionContext())->GetFrame(),
UserActivationUpdateSource::kRenderer)) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"A user activation is required to request immediate credentials."));
return promise;
}
}
auto mojo_options =
MojoPublicKeyCredentialRequestOptions::From(*options->publicKey());
if (mojo_options) {
mojo_options->mediation = mediation;
if (!mojo_options->relying_party_id) {
mojo_options->relying_party_id = context->GetSecurityOrigin()->Domain();
}
mojo_options->requested_credential_type_flags =
requested_credential_types;
auto* authenticator =
CredentialManagerProxy::From(script_state)->Authenticator();
authenticator->GetCredential(
std::move(mojo_options),
WTF::BindOnce(
&OnAuthenticatorGetCredentialComplete,
std::make_unique<ScopedPromiseResolver>(resolver),
std::move(scoped_abort_state),
RuntimeEnabledFeatures::
WebAuthenticationNewBfCacheHandlingBlinkEnabled()
? ExecutionContext::From(script_state)
->GetScheduler()
->RegisterFeature(
SchedulingPolicy::Feature::kWebAuthentication,
SchedulingPolicy::DisableBackForwardCache())
: FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle(),
mediation));
} else {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Required parameters missing in 'options.publicKey'."));
}
return promise;
}
if (options->hasOtp() && options->otp()->hasTransport()) {
if (!options->otp()->transport().Contains("sms")) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Unsupported transport type for OTP Credentials"));
return promise;
}
std::unique_ptr<ScopedAbortState> scoped_abort_state = nullptr;
if (auto* signal = options->getSignalOr(nullptr)) {
auto* handle = signal->AddAlgorithm(
MakeGarbageCollected<OtpRequestAbortAlgorithm>(script_state));
scoped_abort_state = std::make_unique<ScopedAbortState>(signal, handle);
}
auto* webotp_service =
CredentialManagerProxy::From(script_state)->WebOTPService();
webotp_service->Receive(
WTF::BindOnce(&OnSmsReceive, WrapPersistent(resolver),
std::move(scoped_abort_state), base::TimeTicks::Now()));
UseCounter::Count(context, WebFeature::kWebOTP);
return promise;
}
if (options->hasIdentity() && options->identity()->hasProviders()) {
GetForIdentity(script_state, resolver, *options, *options->identity());
return promise;
}
Vector<KURL> providers;
if (options->hasFederated() && options->federated()->hasProviders()) {
for (const auto& provider : options->federated()->providers()) {
KURL url = KURL(NullURL(), provider);
if (url.IsValid()) {
providers.push_back(std::move(url));
}
}
}
CredentialMediationRequirement requirement;
if (options->mediation() == "conditional") {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Conditional mediation is not supported for this credential type"));
return promise;
}
if (options->mediation() == "immediate") {
if (RuntimeEnabledFeatures::WebAuthenticationImmediateGetEnabled(context)) {
if (options->password()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Immediate mediation is not yet implemented for requests that do "
"not accept PublicKeyCredential. An Immediate request for "
"passwords must also include a request for passkeys."));
} else {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Immediate mediation is not supported for this credential type"));
}
} else {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Immediate mediation not implemented"));
}
return promise;
}
if (options->mediation() == "silent") {
UseCounter::Count(context,
WebFeature::kCredentialManagerGetMediationSilent);
requirement = CredentialMediationRequirement::kSilent;
} else if (options->mediation() == "optional") {
UseCounter::Count(context,
WebFeature::kCredentialManagerGetMediationOptional);
requirement = CredentialMediationRequirement::kOptional;
} else {
CHECK_EQ("required", options->mediation());
UseCounter::Count(context,
WebFeature::kCredentialManagerGetMediationRequired);
requirement = CredentialMediationRequirement::kRequired;
}
auto* credential_manager =
CredentialManagerProxy::From(script_state)->CredentialManager();
credential_manager->Get(
requirement, options->password(), std::move(providers),
WTF::BindOnce(&OnGetComplete,
std::make_unique<ScopedPromiseResolver>(resolver),
required_origin_type, Mediation::MODAL));
return promise;
}
ScriptPromise<Credential> AuthenticationCredentialsContainer::store(
ScriptState* script_state,
Credential* credential,
ExceptionState& exception_state) {
if (!script_state->ContextIsValid()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Context is detached");
return EmptyPromise();
}
auto* resolver =
MakeGarbageCollected<ScriptPromiseResolver<Credential>>(script_state);
auto promise = resolver->Promise();
if (!(credential->IsFederatedCredential() ||
credential->IsPasswordCredential())) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Store operation not permitted for this credential type."));
return promise;
}
if (!CheckSecurityRequirementsBeforeRequest(
resolver, RequiredOriginType::kSecureAndSameWithAncestors)) {
return promise;
}
if (credential->IsFederatedCredential()) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialManagerStoreFederatedCredential);
} else if (credential->IsPasswordCredential()) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialManagerStorePasswordCredential);
}
const KURL& url =
credential->IsFederatedCredential()
? static_cast<const FederatedCredential*>(credential)->iconURL()
: static_cast<const PasswordCredential*>(credential)->iconURL();
if (!IsIconURLNullOrSecure(url)) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError, "'iconURL' should be a secure URL"));
return promise;
}
auto* credential_manager =
CredentialManagerProxy::From(script_state)->CredentialManager();
DCHECK_NE(mojom::blink::CredentialType::EMPTY,
CredentialInfo::From(credential)->type);
credential_manager->Store(
CredentialInfo::From(credential),
WTF::BindOnce(&OnStoreComplete,
std::make_unique<ScopedPromiseResolver>(resolver)));
return promise;
}
ScriptPromise<IDLNullable<Credential>>
AuthenticationCredentialsContainer::create(
ScriptState* script_state,
const CredentialCreationOptions* options,
ExceptionState& exception_state) {
if (!script_state->ContextIsValid()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Context is detached");
return ScriptPromise<IDLNullable<Credential>>();
}
auto* resolver =
MakeGarbageCollected<ScriptPromiseResolver<IDLNullable<Credential>>>(
script_state);
auto promise = resolver->Promise();
if (RuntimeEnabledFeatures::WebIdentityDigitalCredentialsCreationEnabled(
resolver->GetExecutionContext()) &&
IsDigitalIdentityCredentialType(*options)) {
CreateDigitalIdentityCredentialInExternalSource(resolver, *options,
exception_state);
return promise;
}
RequiredOriginType required_origin_type;
if (IsForPayment(options, resolver->GetExecutionContext())) {
required_origin_type = RequiredOriginType::
kSecureWithPaymentOrCreateCredentialPermissionPolicy;
} else if (options->hasPublicKey()) {
// hasPublicKey() implies that this is a WebAuthn request.
required_origin_type = RequiredOriginType::
kSecureAndPermittedByWebAuthCreateCredentialPermissionsPolicy;
} else {
required_origin_type = RequiredOriginType::kSecure;
}
if (!CheckSecurityRequirementsBeforeRequest(resolver, required_origin_type)) {
return promise;
}
if ((options->hasPassword() + options->hasFederated() +
options->hasPublicKey()) != 1) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Only exactly one of 'password', 'federated', and 'publicKey' "
"credential types are currently supported."));
return promise;
}
if (options->hasPassword()) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialManagerCreatePasswordCredential);
resolver->Resolve(
options->password()->IsPasswordCredentialData()
? PasswordCredential::Create(
options->password()->GetAsPasswordCredentialData(),
exception_state)
: PasswordCredential::Create(
options->password()->GetAsHTMLFormElement(),
exception_state));
return promise;
}
if (options->hasFederated()) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialManagerCreateFederatedCredential);
resolver->Resolve(
FederatedCredential::Create(options->federated(), exception_state));
return promise;
}
DCHECK(options->hasPublicKey());
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialManagerCreatePublicKeyCredential);
if (!IsArrayBufferOrViewBelowSizeLimit(options->publicKey()->challenge())) {
resolver->Reject(DOMException::Create(
"The `challenge` attribute exceeds the maximum allowed size.",
"RangeError"));
return promise;
}
if (!IsArrayBufferOrViewBelowSizeLimit(options->publicKey()->user()->id())) {
resolver->Reject(DOMException::Create(
"The `user.id` attribute exceeds the maximum allowed size.",
"RangeError"));
return promise;
}
if (!IsCredentialDescriptorListBelowSizeLimit(
options->publicKey()->excludeCredentials())) {
resolver->Reject(
DOMException::Create("The `excludeCredentials` attribute exceeds the "
"maximum allowed size (64).",
"RangeError"));
return promise;
}
for (const auto& credential : options->publicKey()->excludeCredentials()) {
if (!IsArrayBufferOrViewBelowSizeLimit(credential->id())) {
resolver->Reject(DOMException::Create(
"The `excludeCredentials.id` attribute exceeds the maximum "
"allowed size.",
"RangeError"));
return promise;
}
}
if (options->publicKey()->hasExtensions()) {
if (options->publicKey()->extensions()->hasAppid()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The 'appid' extension is only valid when requesting an assertion "
"for a pre-existing credential that was registered using the "
"legacy FIDO U2F API."));
return promise;
}
if (options->publicKey()->extensions()->hasAppidExclude()) {
const auto& appid_exclude =
options->publicKey()->extensions()->appidExclude();
if (!appid_exclude.empty()) {
KURL appid_exclude_url(appid_exclude);
if (!appid_exclude_url.IsValid()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSyntaxError,
"The `appidExclude` extension value is neither "
"empty/null nor a valid URL."));
return promise;
}
}
}
if (options->publicKey()->extensions()->hasCableAuthentication()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The 'cableAuthentication' extension is only valid when requesting "
"an assertion"));
return promise;
}
if (options->publicKey()->extensions()->hasLargeBlob()) {
if (options->publicKey()->extensions()->largeBlob()->hasRead()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The 'largeBlob' extension's 'read' parameter is only valid when "
"requesting an assertion"));
return promise;
}
if (options->publicKey()->extensions()->largeBlob()->hasWrite()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"The 'largeBlob' extension's 'write' parameter is only valid "
"when requesting an assertion"));
return promise;
}
}
if (options->publicKey()->extensions()->hasPayment() &&
!IsPaymentExtensionValid(options, resolver)) {
return promise;
}
if (options->publicKey()->extensions()->hasPrf()) {
const char* error = validateCreatePublicKeyCredentialPRFExtension(
*options->publicKey()->extensions()->prf());
if (error != nullptr) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError, error));
return promise;
}
}
}
// In the case of create() in a cross-origin iframe, the spec requires that
// the caller must have transient user activation (which is consumed).
// https://w3c.github.io/webauthn/#sctn-createCredential, step 2.
if (!IsSameSecurityOriginWithAncestors(
To<LocalDOMWindow>(resolver->GetExecutionContext())->GetFrame())) {
bool has_user_activation = LocalFrame::ConsumeTransientUserActivation(
To<LocalDOMWindow>(resolver->GetExecutionContext())->GetFrame(),
UserActivationUpdateSource::kRenderer);
if (!has_user_activation) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError,
"A user activation is required to create a credential in a "
"cross-origin iframe."));
return promise;
}
}
std::unique_ptr<ScopedAbortState> scoped_abort_state = nullptr;
if (auto* signal = options->getSignalOr(nullptr)) {
if (signal->aborted()) {
resolver->Reject(signal->reason(script_state));
return promise;
}
auto* handle = signal->AddAlgorithm(
MakeGarbageCollected<PublicKeyRequestAbortAlgorithm>(script_state));
scoped_abort_state = std::make_unique<ScopedAbortState>(signal, handle);
}
if (options->publicKey()->hasAttestation() &&
!mojo::ConvertTo<std::optional<AttestationConveyancePreference>>(
options->publicKey()->attestation())) {
resolver->GetExecutionContext()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kJavaScript,
mojom::blink::ConsoleMessageLevel::kWarning,
"Ignoring unknown publicKey.attestation value"));
}
if (options->publicKey()->hasAuthenticatorSelection() &&
options->publicKey()
->authenticatorSelection()
->hasAuthenticatorAttachment()) {
std::optional<String> attachment = options->publicKey()
->authenticatorSelection()
->authenticatorAttachment();
if (!mojo::ConvertTo<std::optional<AuthenticatorAttachment>>(attachment)) {
resolver->GetExecutionContext()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kJavaScript,
mojom::blink::ConsoleMessageLevel::kWarning,
"Ignoring unknown "
"publicKey.authenticatorSelection.authnticatorAttachment value"));
}
}
if (options->publicKey()->hasAuthenticatorSelection() &&
options->publicKey()->authenticatorSelection()->hasUserVerification() &&
!mojo::ConvertTo<
std::optional<mojom::blink::UserVerificationRequirement>>(
options->publicKey()->authenticatorSelection()->userVerification())) {
resolver->GetExecutionContext()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kJavaScript,
mojom::blink::ConsoleMessageLevel::kWarning,
"Ignoring unknown "
"publicKey.authenticatorSelection.userVerification value"));
}
bool is_rk_required = false;
if (options->publicKey()->hasAuthenticatorSelection() &&
options->publicKey()->authenticatorSelection()->hasResidentKey()) {
auto rk_requirement =
mojo::ConvertTo<std::optional<mojom::blink::ResidentKeyRequirement>>(
options->publicKey()->authenticatorSelection()->residentKey());
if (!rk_requirement) {
resolver->GetExecutionContext()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kJavaScript,
mojom::blink::ConsoleMessageLevel::kWarning,
"Ignoring unknown publicKey.authenticatorSelection.residentKey "
"value"));
} else {
is_rk_required =
(rk_requirement == mojom::blink::ResidentKeyRequirement::REQUIRED);
}
}
// An empty list uses default algorithm identifiers.
if (options->publicKey()->pubKeyCredParams().size() != 0) {
WTF::HashSet<int16_t> algorithm_set;
for (const auto& param : options->publicKey()->pubKeyCredParams()) {
// 0 and -1 are special values that cannot be inserted into the HashSet.
if (param->alg() != 0 && param->alg() != -1) {
algorithm_set.insert(param->alg());
}
}
if (!algorithm_set.Contains(-7) || !algorithm_set.Contains(-257)) {
resolver->GetExecutionContext()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kJavaScript,
mojom::blink::ConsoleMessageLevel::kWarning,
"publicKey.pubKeyCredParams is missing at least one of the "
"default algorithm identifiers: ES256 and RS256. This can "
"result in registration failures on incompatible "
"authenticators. See "
"https://chromium.googlesource.com/chromium/src/+/main/"
"content/browser/webauth/pub_key_cred_params.md for details"));
}
}
auto mojo_options =
MojoPublicKeyCredentialCreationOptions::From(*options->publicKey());
if (!mojo_options) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Required parameters missing in `options.publicKey`."));
return promise;
}
if (mojo_options->user->id.size() > 64) {
// https://www.w3.org/TR/webauthn/#user-handle
v8::Isolate* isolate = resolver->GetScriptState()->GetIsolate();
resolver->Reject(V8ThrowException::CreateTypeError(
isolate, "User handle exceeds 64 bytes."));
return promise;
}
if (!mojo_options->relying_party->id) {
mojo_options->relying_party->id =
resolver->GetExecutionContext()->GetSecurityOrigin()->Domain();
}
auto* authenticator =
CredentialManagerProxy::From(script_state)->Authenticator();
FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle feature_handle =
RuntimeEnabledFeatures::WebAuthenticationNewBfCacheHandlingBlinkEnabled()
? ExecutionContext::From(script_state)
->GetScheduler()
->RegisterFeature(SchedulingPolicy::Feature::kWebAuthentication,
SchedulingPolicy::DisableBackForwardCache())
: FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle();
if (mojo_options->is_payment_credential_creation) {
String rp_id_for_payment_extension = mojo_options->relying_party->id;
WTF::Vector<uint8_t> user_id_for_payment_extension = mojo_options->user->id;
if (base::FeatureList::IsEnabled(
blink::features::kSecurePaymentConfirmationBrowserBoundKeys)) {
auto* spc_service =
CredentialManagerProxy::From(resolver->GetScriptState())
->SecurePaymentConfirmationService();
spc_service->MakePaymentCredential(
std::move(mojo_options),
WTF::BindOnce(&OnMakePublicKeyCredentialWithPaymentExtensionComplete,
std::make_unique<ScopedPromiseResolver>(resolver),
std::move(scoped_abort_state),
std::move(feature_handle), rp_id_for_payment_extension,
std::move(user_id_for_payment_extension)));
} else {
authenticator->MakeCredential(
std::move(mojo_options),
WTF::BindOnce(&OnMakePublicKeyCredentialWithPaymentExtensionComplete,
std::make_unique<ScopedPromiseResolver>(resolver),
std::move(scoped_abort_state),
std::move(feature_handle), rp_id_for_payment_extension,
std::move(user_id_for_payment_extension)));
}
} else {
if (RuntimeEnabledFeatures::WebAuthenticationConditionalCreateEnabled()) {
mojo_options->is_conditional = options->mediation() == "conditional";
}
authenticator->MakeCredential(
std::move(mojo_options),
WTF::BindOnce(&OnMakePublicKeyCredentialComplete,
std::make_unique<ScopedPromiseResolver>(resolver),
std::move(scoped_abort_state), std::move(feature_handle),
required_origin_type, is_rk_required));
}
return promise;
}
ScriptPromise<IDLUndefined>
AuthenticationCredentialsContainer::preventSilentAccess(
ScriptState* script_state) {
if (!script_state->ContextIsValid()) {
return ScriptPromise<IDLUndefined>::RejectWithDOMException(
script_state,
MakeGarbageCollected<DOMException>(DOMExceptionCode::kInvalidStateError,
"Context is detached"));
}
auto* resolver =
MakeGarbageCollected<ScriptPromiseResolver<IDLUndefined>>(script_state);
auto promise = resolver->Promise();
const auto required_origin_type = RequiredOriginType::kSecure;
if (!CheckSecurityRequirementsBeforeRequest(resolver, required_origin_type)) {
return promise;
}
auto* credential_manager =
CredentialManagerProxy::From(script_state)->CredentialManager();
credential_manager->PreventSilentAccess(
WTF::BindOnce(&OnPreventSilentAccessComplete,
std::make_unique<ScopedPromiseResolver>(resolver)));
// TODO(https://crbug.com/1441075): Unify the implementation for
// different CredentialTypes and avoid the duplication eventually.
auto* auth_request =
CredentialManagerProxy::From(script_state)->FederatedAuthRequest();
auth_request->PreventSilentAccess(
WTF::BindOnce(&OnPreventSilentAccessComplete,
std::make_unique<ScopedPromiseResolver>(resolver)));
return promise;
}
void AuthenticationCredentialsContainer::Trace(Visitor* visitor) const {
Supplement<Navigator>::Trace(visitor);
CredentialsContainer::Trace(visitor);
}
void AuthenticationCredentialsContainer::GetForIdentity(
ScriptState* script_state,
ScriptPromiseResolver<IDLNullable<Credential>>* resolver,
const CredentialRequestOptions& options,
const IdentityCredentialRequestOptions& identity_options) {
// Common errors for FedCM and WebIdentityDigitalCredential.
if (identity_options.providers().size() == 0) {
resolver->RejectWithTypeError("Need at least one identity provider.");
return;
}
ExecutionContext* context = ExecutionContext::From(script_state);
// TODO(https://crbug.com/1441075): Ideally the logic should be handled in
// CredentialManager via Get. However currently it's only for password
// management and we should refactor the logic to make it generic.
ContentSecurityPolicy* policy =
resolver->GetExecutionContext()
->GetContentSecurityPolicyForCurrentWorld();
if (identity_options.providers().size() > 1) {
if (RuntimeEnabledFeatures::FedCmMultipleIdentityProvidersEnabled(
context)) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kFedCmMultipleIdentityProviders);
if (identity_options.providers().size() > 10u) {
resolver->RejectWithTypeError(
"More than 10 providers are not allowed.");
return;
}
} else {
resolver->RejectWithTypeError(
"Multiple providers specified but FedCmMultipleIdentityProviders "
"flag is disabled.");
return;
}
}
// Log the UseCounter only when the WebID flag is enabled.
UseCounter::Count(context, WebFeature::kFedCm);
if (!To<LocalDOMWindow>(resolver->GetExecutionContext())
->GetFrame()
->IsMainFrame()) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kFedCmIframe);
}
int provider_index = 0;
Vector<mojom::blink::IdentityProviderRequestOptionsPtr>
identity_provider_ptrs;
for (const auto& provider : identity_options.providers()) {
if (provider->hasLoginHint()) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kFedCmLoginHint);
}
if (provider->hasDomainHint()) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kFedCmDomainHint);
}
mojom::blink::IdentityProviderRequestOptionsPtr identity_provider;
{
// It is possible that serializing the custom parameters to JSON fails
// due to a JS exception, e.g. a custom getter throwing an exception.
// Catch it here and rethrow so the caller knows what went wrong.
v8::TryCatch try_catch(script_state->GetIsolate());
identity_provider =
blink::mojom::blink::IdentityProviderRequestOptions::From(*provider);
if (!identity_provider) {
DCHECK(try_catch.HasCaught())
<< "Converting to mojo should only fail due to JS exception";
resolver->Reject(try_catch.Exception());
return;
}
}
if (blink::RuntimeEnabledFeatures::FedCmIdPRegistrationEnabled() &&
blink::RuntimeEnabledFeatures::FedCmMultipleIdentityProvidersEnabled(
context) &&
provider->configURL() == "any") {
identity_provider_ptrs.push_back(std::move(identity_provider));
continue;
}
// TODO(kenrb): Add some renderer-side validation here, such as
// validating |provider|, and making sure the calling context is legal.
// Some of this has not been spec'd yet.
KURL provider_url(provider->configURL());
if (!provider->hasClientId()) {
resolver->RejectWithTypeError("Missing the provider's clientId.");
return;
}
String client_id = provider->clientId();
++provider_index;
if (!provider_url.IsValid() || client_id.empty()) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError,
String::Format("Provider %i information is incomplete.",
provider_index)));
return;
}
// We disallow redirects (in idp_network_request_manager.cc), so it is
// enough to check the initial URL here.
if (IdentityCredential::IsRejectingPromiseDueToCSP(policy, resolver,
provider_url)) {
return;
}
identity_provider_ptrs.push_back(std::move(identity_provider));
}
mojom::blink::RpContext rp_context = mojom::blink::RpContext::kSignIn;
if (identity_options.hasContext()) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kFedCmRpContext);
rp_context =
mojo::ConvertTo<mojom::blink::RpContext>(identity_options.context());
}
base::UmaHistogramEnumeration("Blink.FedCm.RpContext", rp_context);
CredentialMediationRequirement mediation_requirement;
if (options.mediation() == "conditional") {
if (RuntimeEnabledFeatures::FedCmAutofillEnabled()) {
mediation_requirement = CredentialMediationRequirement::kConditional;
} else {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"Conditional mediation is not supported for this credential type"));
return;
}
} else if (options.mediation() == "silent") {
mediation_requirement = CredentialMediationRequirement::kSilent;
} else if (options.mediation() == "required") {
mediation_requirement = CredentialMediationRequirement::kRequired;
} else {
DCHECK_EQ("optional", options.mediation());
mediation_requirement = CredentialMediationRequirement::kOptional;
}
if (identity_options.hasMediation()) {
resolver->GetExecutionContext()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kJavaScript,
mojom::blink::ConsoleMessageLevel::kWarning,
"The 'mediation' parameter should be used outside of 'identity' in "
"the FedCM API call."));
}
mojom::blink::RpMode rp_mode = mojom::blink::RpMode::kPassive;
auto v8_rp_mode = identity_options.mode();
rp_mode = mojo::ConvertTo<mojom::blink::RpMode>(v8_rp_mode);
if (rp_mode == mojom::blink::RpMode::kActive) {
if (identity_provider_ptrs.size() > 1u) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError,
"Active mode is not currently supported with multiple identity "
"providers."));
return;
}
if (mediation_requirement == CredentialMediationRequirement::kSilent) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError,
"mediation:silent is not supported in active mode"));
return;
}
}
std::unique_ptr<ScopedAbortState> scoped_abort_state;
if (auto* signal = options.getSignalOr(nullptr)) {
// Checked signal->aborted() at the top of get().
auto callback = WTF::BindOnce(&AbortIdentityCredentialRequest,
WrapPersistent(script_state));
auto* handle = signal->AddAlgorithm(std::move(callback));
scoped_abort_state = std::make_unique<ScopedAbortState>(signal, handle);
}
Vector<mojom::blink::IdentityProviderGetParametersPtr> idp_get_params;
mojom::blink::IdentityProviderGetParametersPtr get_params =
mojom::blink::IdentityProviderGetParameters::New(
std::move(identity_provider_ptrs), rp_context, rp_mode);
idp_get_params.push_back(std::move(get_params));
auto* auth_request =
CredentialManagerProxy::From(script_state)->FederatedAuthRequest();
auth_request->RequestToken(
std::move(idp_get_params), mediation_requirement,
WTF::BindOnce(&OnRequestToken,
std::make_unique<ScopedPromiseResolver>(resolver),
std::move(scoped_abort_state), WrapPersistent(&options)));
}
} // namespace blink
|