1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829
// Copyright (C) Michael Howell and others
// this library is released under the same terms as Rust itself.
#![deny(unsafe_code)]
#![deny(missing_docs)]
//! Ammonia is a whitelist-based HTML sanitization library. It is designed to
//! prevent cross-site scripting, layout breaking, and clickjacking caused
//! by untrusted user-provided HTML being mixed into a larger web page.
//!
//! Ammonia uses [html5ever] to parse and serialize document fragments the same way browsers do,
//! so it is extremely resilient to syntactic obfuscation.
//!
//! Ammonia parses its input exactly according to the HTML5 specification;
//! it will not linkify bare URLs, insert line or paragraph breaks, or convert `(C)` into ©.
//! If you want that, use a markup processor before running the sanitizer, like [pulldown-cmark].
//!
//! # Examples
//!
//! ```
//! let result = ammonia::clean(
//! "<b><img src='' onerror=alert('hax')>I'm not trying to XSS you</b>"
//! );
//! assert_eq!(result, "<b><img src=\"\">I'm not trying to XSS you</b>");
//! ```
//!
//! [html5ever]: https://github.com/servo/html5ever "The HTML parser in Servo"
//! [pulldown-cmark]: https://github.com/google/pulldown-cmark "CommonMark parser"
#[cfg(ammonia_unstable)]
pub mod rcdom;
#[cfg(not(ammonia_unstable))]
mod rcdom;
use html5ever::interface::Attribute;
use html5ever::serialize::{serialize, SerializeOpts};
use html5ever::tree_builder::{NodeOrText, TreeSink};
use html5ever::{driver as html, local_name, namespace_url, ns, QualName};
use maplit::{hashmap, hashset};
use once_cell::sync::Lazy;
use rcdom::{Handle, NodeData, RcDom, SerializableHandle};
use std::borrow::{Borrow, Cow};
use std::cmp::max;
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Display};
use std::io;
use std::iter::IntoIterator as IntoIter;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use tendril::stream::TendrilSink;
use tendril::StrTendril;
use tendril::{format_tendril, ByteTendril};
pub use url::Url;
use html5ever::buffer_queue::BufferQueue;
use html5ever::tokenizer::{Token, TokenSink, TokenSinkResult, Tokenizer};
pub use url;
static AMMONIA: Lazy<Builder<'static>> = Lazy::new(Builder::default);
/// Clean HTML with a conservative set of defaults.
///
/// * [tags](struct.Builder.html#defaults)
/// * [`script` and `style` have their contents stripped](struct.Builder.html#defaults-1)
/// * [attributes on specific tags](struct.Builder.html#defaults-2)
/// * [attributes on all tags](struct.Builder.html#defaults-6)
/// * [url schemes](struct.Builder.html#defaults-7)
/// * [relative URLs are passed through, unchanged, by default](struct.Builder.html#defaults-8)
/// * [links are marked `noopener noreferrer` by default](struct.Builder.html#defaults-9)
/// * all `class=""` settings are blocked by default
/// * comments are stripped by default
/// * no generic attribute prefixes are turned on by default
/// * no specific tag-attribute-value settings are configured by default
///
/// [opener]: https://mathiasbynens.github.io/rel-noopener/
/// [referrer]: https://en.wikipedia.org/wiki/HTTP_referer
///
/// # Examples
///
/// assert_eq!(ammonia::clean("XSS<script>attack</script>"), "XSS")
pub fn clean(src: &str) -> String {
AMMONIA.clean(src).to_string()
}
/// Turn an arbitrary string into unformatted HTML.
///
/// This function is roughly equivalent to PHP's `htmlspecialchars` and `htmlentities`.
/// It is as strict as possible, encoding every character that has special meaning to the
/// HTML parser.
///
/// # Warnings
///
/// This function cannot be used to package strings into a `<script>` or `<style>` tag;
/// you need a JavaScript or CSS escaper to do that.
///
/// // DO NOT DO THIS
/// # use ammonia::clean_text;
/// let untrusted = "Robert\"); abuse();//";
/// let html = format!("<script>invoke(\"{}\")</script>", clean_text(untrusted));
///
/// `<textarea>` tags will strip the first newline, if present, even if that newline is encoded.
/// If you want to build an editor that works the way most folks expect them to, you should put a
/// newline at the beginning of the tag, like this:
///
/// # use ammonia::{Builder, clean_text};
/// let untrusted = "\n\nhi!";
/// let mut b = Builder::new();
/// b.add_tags(&["textarea"]);
/// // This is the bad version
/// // The user put two newlines at the beginning, but the first one was removed
/// let sanitized = b.clean(&format!("<textarea>{}</textarea>", clean_text(untrusted))).to_string();
/// assert_eq!("<textarea>\nhi!</textarea>", sanitized);
/// // This is a good version
/// // The user put two newlines at the beginning, and we add a third one,
/// // so the result still has two
/// let sanitized = b.clean(&format!("<textarea>\n{}</textarea>", clean_text(untrusted))).to_string();
/// assert_eq!("<textarea>\n\nhi!</textarea>", sanitized);
/// // This version is also often considered good
/// // For many applications, leading and trailing whitespace is probably unwanted
/// let sanitized = b.clean(&format!("<textarea>{}</textarea>", clean_text(untrusted.trim()))).to_string();
/// assert_eq!("<textarea>hi!</textarea>", sanitized);
///
/// It also does not make user text safe for HTML attribute microsyntaxes such as `class` or `id`.
/// Only use this function for places where HTML accepts unrestricted text such as `title` attributes
/// and paragraph contents.
pub fn clean_text(src: &str) -> String {
let mut ret_val = String::with_capacity(max(4, src.len()));
for c in src.chars() {
let replacement = match c {
// this character, when confronted, will start a tag
'<' => "<",
// in an unquoted attribute, will end the attribute value
'>' => ">",
// in an attribute surrounded by double quotes, this character will end the attribute value
'\"' => """,
// in an attribute surrounded by single quotes, this character will end the attribute value
'\'' => "'",
// in HTML5, returns a bogus parse error in an unquoted attribute, while in SGML/HTML, it will end an attribute value surrounded by backquotes
'`' => "`",
// in an unquoted attribute, this character will end the attribute
'/' => "/",
// starts an entity reference
'&' => "&",
// if at the beginning of an unquoted attribute, will get ignored
'=' => "=",
// will end an unquoted attribute
' ' => " ",
'\t' => "	",
'\n' => " ",
'\x0c' => "",
'\r' => " ",
// a spec-compliant browser will perform this replacement anyway, but the middleware might not
'\0' => "�",
// ALL OTHER CHARACTERS ARE PASSED THROUGH VERBATIM
_ => {
ret_val.push(c);
continue;
}
};
ret_val.push_str(replacement);
}
ret_val
}
/// Determine if a given string contains HTML
///
/// This function is parses the full string into HTML and checks if the input contained any
/// HTML syntax.
///
/// # Note
/// This function will return positively for strings that contain invalid HTML syntax like
/// `<g>` and even `Vec::<u8>::new()`.
pub fn is_html(input: &str) -> bool {
let santok = SanitizationTokenizer::new();
let mut chunk = ByteTendril::new();
chunk.push_slice(input.as_bytes());
let mut input = BufferQueue::default();
input.push_back(chunk.try_reinterpret().unwrap());
let mut tok = Tokenizer::new(santok, Default::default());
let _ = tok.feed(&mut input);
tok.end();
tok.sink.was_sanitized
}
#[derive(Copy, Clone)]
struct SanitizationTokenizer {
was_sanitized: bool,
}
impl SanitizationTokenizer {
pub fn new() -> SanitizationTokenizer {
SanitizationTokenizer {
was_sanitized: false,
}
}
}
impl TokenSink for SanitizationTokenizer {
type Handle = ();
fn process_token(&mut self, token: Token, _line_number: u64) -> TokenSinkResult<()> {
match token {
Token::CharacterTokens(_) | Token::EOFToken | Token::ParseError(_) => {}
_ => {
self.was_sanitized = true;
}
}
TokenSinkResult::Continue
}
fn end(&mut self) {}
}
/// An HTML sanitizer.
///
/// Given a fragment of HTML, Ammonia will parse it according to the HTML5
/// parsing algorithm and sanitize any disallowed tags or attributes. This
/// algorithm also takes care of things like unclosed and (some) misnested
/// tags.
///
/// # Examples
///
/// use ammonia::{Builder, UrlRelative};
///
/// let a = Builder::default()
/// .link_rel(None)
/// .url_relative(UrlRelative::PassThrough)
/// .clean("<a href=/>test")
/// .to_string();
/// assert_eq!(
/// a,
/// "<a href=\"/\">test</a>");
///
/// # Panics
///
/// Running [`clean`] or [`clean_from_reader`] may cause a panic if the builder is
/// configured with any of these (contradictory) settings:
///
/// * The `rel` attribute is added to [`generic_attributes`] or the
/// [`tag_attributes`] for the `<a>` tag, and [`link_rel`] is not set to `None`.
///
/// For example, this is going to panic, since [`link_rel`] is set to
/// `Some("noopener noreferrer")` by default,
/// and it makes no sense to simultaneously say that the user is allowed to
/// set their own `rel` attribute while saying that every link shall be set to
/// a particular value:
///
/// ```should_panic
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// Builder::default()
/// .generic_attributes(hashset!["rel"])
/// .clean("");
/// # }
/// ```
///
/// This, however, is perfectly valid:
///
/// ```
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// Builder::default()
/// .generic_attributes(hashset!["rel"])
/// .link_rel(None)
/// .clean("");
/// # }
/// ```
///
/// * The `class` attribute is in [`allowed_classes`] and is in the
/// corresponding [`tag_attributes`] or in [`generic_attributes`].
///
/// This is done both to line up with the treatment of `rel`,
/// and to prevent people from accidentally allowing arbitrary
/// classes on a particular element.
///
/// This will panic:
///
/// ```should_panic
/// use ammonia::Builder;
/// use maplit::{hashmap, hashset};
///
/// # fn main() {
/// Builder::default()
/// .generic_attributes(hashset!["class"])
/// .allowed_classes(hashmap!["span" => hashset!["hidden"]])
/// .clean("");
/// # }
/// ```
///
/// This, however, is perfectly valid:
///
/// ```
/// use ammonia::Builder;
/// use maplit::{hashmap, hashset};
///
/// # fn main() {
/// Builder::default()
/// .allowed_classes(hashmap!["span" => hashset!["hidden"]])
/// .clean("");
/// # }
/// ```
///
/// * A tag is in either [`tags`] or [`tag_attributes`] while also
/// being in [`clean_content_tags`].
///
/// Both [`tags`] and [`tag_attributes`] are whitelists but
/// [`clean_content_tags`] is a blacklist, so it doesn't make sense
/// to have the same tag in both.
///
/// For example, this will panic, since the `aside` tag is in
/// [`tags`] by default:
///
/// ```should_panic
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// Builder::default()
/// .clean_content_tags(hashset!["aside"])
/// .clean("");
/// # }
/// ```
///
/// This, however, is valid:
///
/// ```
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// Builder::default()
/// .rm_tags(&["aside"])
/// .clean_content_tags(hashset!["aside"])
/// .clean("");
/// # }
/// ```
///
/// [`clean`]: #method.clean
/// [`clean_from_reader`]: #method.clean_from_reader
/// [`generic_attributes`]: #method.generic_attributes
/// [`tag_attributes`]: #method.tag_attributes
/// [`generic_attributes`]: #method.generic_attributes
/// [`link_rel`]: #method.link_rel
/// [`allowed_classes`]: #method.allowed_classes
/// [`id_prefix`]: #method.id_prefix
/// [`tags`]: #method.tags
/// [`clean_content_tags`]: #method.clean_content_tags
#[derive(Debug)]
pub struct Builder<'a> {
tags: HashSet<&'a str>,
clean_content_tags: HashSet<&'a str>,
tag_attributes: HashMap<&'a str, HashSet<&'a str>>,
tag_attribute_values: HashMap<&'a str, HashMap<&'a str, HashSet<&'a str>>>,
set_tag_attribute_values: HashMap<&'a str, HashMap<&'a str, &'a str>>,
generic_attributes: HashSet<&'a str>,
url_schemes: HashSet<&'a str>,
url_relative: UrlRelative<'a>,
attribute_filter: Option<Box<dyn AttributeFilter>>,
link_rel: Option<&'a str>,
allowed_classes: HashMap<&'a str, HashSet<&'a str>>,
strip_comments: bool,
id_prefix: Option<&'a str>,
generic_attribute_prefixes: Option<HashSet<&'a str>>,
}
impl<'a> Default for Builder<'a> {
fn default() -> Self {
#[rustfmt::skip]
let tags = hashset![
"a", "abbr", "acronym", "area", "article", "aside", "b", "bdi",
"bdo", "blockquote", "br", "caption", "center", "cite", "code",
"col", "colgroup", "data", "dd", "del", "details", "dfn", "div",
"dl", "dt", "em", "figcaption", "figure", "footer", "h1", "h2",
"h3", "h4", "h5", "h6", "header", "hgroup", "hr", "i", "img",
"ins", "kbd", "li", "map", "mark", "nav", "ol", "p", "pre",
"q", "rp", "rt", "rtc", "ruby", "s", "samp", "small", "span",
"strike", "strong", "sub", "summary", "sup", "table", "tbody",
"td", "th", "thead", "time", "tr", "tt", "u", "ul", "var", "wbr"
];
let clean_content_tags = hashset!["script", "style"];
let generic_attributes = hashset!["lang", "title"];
let tag_attributes = hashmap![
"a" => hashset![
"href", "hreflang"
],
"bdo" => hashset![
"dir"
],
"blockquote" => hashset![
"cite"
],
"col" => hashset![
"align", "char", "charoff", "span"
],
"colgroup" => hashset![
"align", "char", "charoff", "span"
],
"del" => hashset![
"cite", "datetime"
],
"hr" => hashset![
"align", "size", "width"
],
"img" => hashset![
"align", "alt", "height", "src", "width"
],
"ins" => hashset![
"cite", "datetime"
],
"ol" => hashset![
"start"
],
"q" => hashset![
"cite"
],
"table" => hashset![
"align", "char", "charoff", "summary"
],
"tbody" => hashset![
"align", "char", "charoff"
],
"td" => hashset![
"align", "char", "charoff", "colspan", "headers", "rowspan"
],
"tfoot" => hashset![
"align", "char", "charoff"
],
"th" => hashset![
"align", "char", "charoff", "colspan", "headers", "rowspan", "scope"
],
"thead" => hashset![
"align", "char", "charoff"
],
"tr" => hashset![
"align", "char", "charoff"
],
];
let tag_attribute_values = hashmap![];
let set_tag_attribute_values = hashmap![];
let url_schemes = hashset![
"bitcoin",
"ftp",
"ftps",
"geo",
"http",
"https",
"im",
"irc",
"ircs",
"magnet",
"mailto",
"mms",
"mx",
"news",
"nntp",
"openpgp4fpr",
"sip",
"sms",
"smsto",
"ssh",
"tel",
"url",
"webcal",
"wtai",
"xmpp"
];
let allowed_classes = hashmap![];
Builder {
tags,
clean_content_tags,
tag_attributes,
tag_attribute_values,
set_tag_attribute_values,
generic_attributes,
url_schemes,
url_relative: UrlRelative::PassThrough,
attribute_filter: None,
link_rel: Some("noopener noreferrer"),
allowed_classes,
strip_comments: true,
id_prefix: None,
generic_attribute_prefixes: None,
}
}
}
impl<'a> Builder<'a> {
/// Sets the tags that are allowed.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// let tags = hashset!["my-tag"];
/// let a = Builder::new()
/// .tags(tags)
/// .clean("<my-tag>")
/// .to_string();
/// assert_eq!(a, "<my-tag></my-tag>");
/// # }
///
/// # Defaults
///
/// ```notest
/// a, abbr, acronym, area, article, aside, b, bdi,
/// bdo, blockquote, br, caption, center, cite, code,
/// col, colgroup, data, dd, del, details, dfn, div,
/// dl, dt, em, figcaption, figure, footer, h1, h2,
/// h3, h4, h5, h6, header, hgroup, hr, i, img,
/// ins, kbd, li, map, mark, nav, ol, p, pre,
/// q, rp, rt, rtc, ruby, s, samp, small, span,
/// strike, strong, sub, summary, sup, table, tbody,
/// td, th, thead, time, tr, tt, u, ul, var, wbr
/// ```
pub fn tags(&mut self, value: HashSet<&'a str>) -> &mut Self {
self.tags = value;
self
}
/// Add additonal whitelisted tags without overwriting old ones.
///
/// Does nothing if the tag is already there.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_tags(&["my-tag"])
/// .clean("<my-tag>test</my-tag> <span>mess</span>").to_string();
/// assert_eq!("<my-tag>test</my-tag> <span>mess</span>", a);
pub fn add_tags<T: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>(
&mut self,
it: I,
) -> &mut Self {
self.tags.extend(it.into_iter().map(Borrow::borrow));
self
}
/// Remove already-whitelisted tags.
///
/// Does nothing if the tags is already gone.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .rm_tags(&["span"])
/// .clean("<span></span>").to_string();
/// assert_eq!("", a);
pub fn rm_tags<'b, T: 'b + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>(
&mut self,
it: I,
) -> &mut Self {
for i in it {
self.tags.remove(i.borrow());
}
self
}
/// Returns a copy of the set of whitelisted tags.
///
/// # Examples
///
/// use maplit::hashset;
///
/// let tags = hashset!["my-tag-1", "my-tag-2"];
///
/// let mut b = ammonia::Builder::default();
/// b.tags(Clone::clone(&tags));
/// assert_eq!(tags, b.clone_tags());
pub fn clone_tags(&self) -> HashSet<&'a str> {
self.tags.clone()
}
/// Sets the tags whose contents will be completely removed from the output.
///
/// Adding tags which are whitelisted in `tags` or `tag_attributes` will cause
/// a panic.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// let tag_blacklist = hashset!["script", "style"];
/// let a = Builder::new()
/// .clean_content_tags(tag_blacklist)
/// .clean("<script>alert('hello')</script><style>a { background: #fff }</style>")
/// .to_string();
/// assert_eq!(a, "");
/// # }
///
/// # Defaults
///
/// ```notest
/// script, style
/// ```
pub fn clean_content_tags(&mut self, value: HashSet<&'a str>) -> &mut Self {
self.clean_content_tags = value;
self
}
/// Add additonal blacklisted clean-content tags without overwriting old ones.
///
/// Does nothing if the tag is already there.
///
/// Adding tags which are whitelisted in `tags` or `tag_attributes` will cause
/// a panic.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_clean_content_tags(&["my-tag"])
/// .clean("<my-tag>test</my-tag><span>mess</span>").to_string();
/// assert_eq!("<span>mess</span>", a);
pub fn add_clean_content_tags<T: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>(
&mut self,
it: I,
) -> &mut Self {
self.clean_content_tags
.extend(it.into_iter().map(Borrow::borrow));
self
}
/// Remove already-blacklisted clean-content tags.
///
/// Does nothing if the tags aren't blacklisted.
///
/// # Examples
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// let tag_blacklist = hashset!["script"];
/// let a = ammonia::Builder::default()
/// .clean_content_tags(tag_blacklist)
/// .rm_clean_content_tags(&["script"])
/// .clean("<script>XSS</script>").to_string();
/// assert_eq!("XSS", a);
/// # }
pub fn rm_clean_content_tags<'b, T: 'b + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>(
&mut self,
it: I,
) -> &mut Self {
for i in it {
self.clean_content_tags.remove(i.borrow());
}
self
}
/// Returns a copy of the set of blacklisted clean-content tags.
///
/// # Examples
/// # use maplit::hashset;
///
/// let tags = hashset!["my-tag-1", "my-tag-2"];
///
/// let mut b = ammonia::Builder::default();
/// b.clean_content_tags(Clone::clone(&tags));
/// assert_eq!(tags, b.clone_clean_content_tags());
pub fn clone_clean_content_tags(&self) -> HashSet<&'a str> {
self.clean_content_tags.clone()
}
/// Sets the HTML attributes that are allowed on specific tags.
///
/// The value is structured as a map from tag names to a set of attribute names.
///
/// If a tag is not itself whitelisted, adding entries to this map will do nothing.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::{hashmap, hashset};
///
/// # fn main() {
/// let tags = hashset!["my-tag"];
/// let tag_attributes = hashmap![
/// "my-tag" => hashset!["val"]
/// ];
/// let a = Builder::new().tags(tags).tag_attributes(tag_attributes)
/// .clean("<my-tag val=1>")
/// .to_string();
/// assert_eq!(a, "<my-tag val=\"1\"></my-tag>");
/// # }
///
/// # Defaults
///
/// ```notest
/// a =>
/// href, hreflang
/// bdo =>
/// dir
/// blockquote =>
/// cite
/// col =>
/// align, char, charoff, span
/// colgroup =>
/// align, char, charoff, span
/// del =>
/// cite, datetime
/// hr =>
/// align, size, width
/// img =>
/// align, alt, height, src, width
/// ins =>
/// cite, datetime
/// ol =>
/// start
/// q =>
/// cite
/// table =>
/// align, char, charoff, summary
/// tbody =>
/// align, char, charoff
/// td =>
/// align, char, charoff, colspan, headers, rowspan
/// tfoot =>
/// align, char, charoff
/// th =>
/// align, char, charoff, colspan, headers, rowspan, scope
/// thead =>
/// align, char, charoff
/// tr =>
/// align, char, charoff
/// ```
pub fn tag_attributes(&mut self, value: HashMap<&'a str, HashSet<&'a str>>) -> &mut Self {
self.tag_attributes = value;
self
}
/// Add additonal whitelisted tag-specific attributes without overwriting old ones.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_tags(&["my-tag"])
/// .add_tag_attributes("my-tag", &["my-attr"])
/// .clean("<my-tag my-attr>test</my-tag> <span>mess</span>").to_string();
/// assert_eq!("<my-tag my-attr=\"\">test</my-tag> <span>mess</span>", a);
pub fn add_tag_attributes<
T: 'a + ?Sized + Borrow<str>,
U: 'a + ?Sized + Borrow<str>,
I: IntoIter<Item = &'a T>,
>(
&mut self,
tag: &'a U,
it: I,
) -> &mut Self {
self.tag_attributes
.entry(tag.borrow())
.or_default()
.extend(it.into_iter().map(Borrow::borrow));
self
}
/// Remove already-whitelisted tag-specific attributes.
///
/// Does nothing if the attribute is already gone.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .rm_tag_attributes("a", &["href"])
/// .clean("<a href=\"/\"></a>").to_string();
/// assert_eq!("<a rel=\"noopener noreferrer\"></a>", a);
pub fn rm_tag_attributes<
'b,
'c,
T: 'b + ?Sized + Borrow<str>,
U: 'c + ?Sized + Borrow<str>,
I: IntoIter<Item = &'b T>,
>(
&mut self,
tag: &'c U,
it: I,
) -> &mut Self {
if let Some(tag) = self.tag_attributes.get_mut(tag.borrow()) {
for i in it {
tag.remove(i.borrow());
}
}
self
}
/// Returns a copy of the set of whitelisted tag-specific attributes.
///
/// # Examples
/// use maplit::{hashmap, hashset};
///
/// let tag_attributes = hashmap![
/// "my-tag" => hashset!["my-attr-1", "my-attr-2"]
/// ];
///
/// let mut b = ammonia::Builder::default();
/// b.tag_attributes(Clone::clone(&tag_attributes));
/// assert_eq!(tag_attributes, b.clone_tag_attributes());
pub fn clone_tag_attributes(&self) -> HashMap<&'a str, HashSet<&'a str>> {
self.tag_attributes.clone()
}
/// Sets the values of HTML attributes that are allowed on specific tags.
///
/// The value is structured as a map from tag names to a map from attribute names to a set of
/// attribute values.
///
/// If a tag is not itself whitelisted, adding entries to this map will do nothing.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::{hashmap, hashset};
///
/// # fn main() {
/// let tags = hashset!["my-tag"];
/// let tag_attribute_values = hashmap![
/// "my-tag" => hashmap![
/// "my-attr" => hashset!["val"],
/// ],
/// ];
/// let a = Builder::new().tags(tags).tag_attribute_values(tag_attribute_values)
/// .clean("<my-tag my-attr=val>")
/// .to_string();
/// assert_eq!(a, "<my-tag my-attr=\"val\"></my-tag>");
/// # }
///
/// # Defaults
///
/// None.
pub fn tag_attribute_values(
&mut self,
value: HashMap<&'a str, HashMap<&'a str, HashSet<&'a str>>>,
) -> &mut Self {
self.tag_attribute_values = value;
self
}
/// Add additonal whitelisted tag-specific attribute values without overwriting old ones.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_tags(&["my-tag"])
/// .add_tag_attribute_values("my-tag", "my-attr", &[""])
/// .clean("<my-tag my-attr>test</my-tag> <span>mess</span>").to_string();
/// assert_eq!("<my-tag my-attr=\"\">test</my-tag> <span>mess</span>", a);
pub fn add_tag_attribute_values<
T: 'a + ?Sized + Borrow<str>,
U: 'a + ?Sized + Borrow<str>,
V: 'a + ?Sized + Borrow<str>,
I: IntoIter<Item = &'a T>,
>(
&mut self,
tag: &'a U,
attribute: &'a V,
it: I,
) -> &mut Self {
self.tag_attribute_values
.entry(tag.borrow())
.or_default()
.entry(attribute.borrow())
.or_default()
.extend(it.into_iter().map(Borrow::borrow));
self
}
/// Remove already-whitelisted tag-specific attribute values.
///
/// Does nothing if the attribute or the value is already gone.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .rm_tag_attributes("a", &["href"])
/// .add_tag_attribute_values("a", "href", &["/"])
/// .rm_tag_attribute_values("a", "href", &["/"])
/// .clean("<a href=\"/\"></a>").to_string();
/// assert_eq!("<a rel=\"noopener noreferrer\"></a>", a);
pub fn rm_tag_attribute_values<
'b,
'c,
T: 'b + ?Sized + Borrow<str>,
U: 'c + ?Sized + Borrow<str>,
V: 'c + ?Sized + Borrow<str>,
I: IntoIter<Item = &'b T>,
>(
&mut self,
tag: &'c U,
attribute: &'c V,
it: I,
) -> &mut Self {
if let Some(attrs) = self
.tag_attribute_values
.get_mut(tag.borrow())
.and_then(|map| map.get_mut(attribute.borrow()))
{
for i in it {
attrs.remove(i.borrow());
}
}
self
}
/// Returns a copy of the set of whitelisted tag-specific attribute values.
///
/// # Examples
///
/// use maplit::{hashmap, hashset};
///
/// let attribute_values = hashmap![
/// "my-attr-1" => hashset!["foo"],
/// "my-attr-2" => hashset!["baz", "bar"],
/// ];
/// let tag_attribute_values = hashmap![
/// "my-tag" => attribute_values
/// ];
///
/// let mut b = ammonia::Builder::default();
/// b.tag_attribute_values(Clone::clone(&tag_attribute_values));
/// assert_eq!(tag_attribute_values, b.clone_tag_attribute_values());
pub fn clone_tag_attribute_values(
&self,
) -> HashMap<&'a str, HashMap<&'a str, HashSet<&'a str>>> {
self.tag_attribute_values.clone()
}
/// Sets the values of HTML attributes that are to be set on specific tags.
///
/// The value is structured as a map from tag names to a map from attribute names to an
/// attribute value.
///
/// If a tag is not itself whitelisted, adding entries to this map will do nothing.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::{hashmap, hashset};
///
/// # fn main() {
/// let tags = hashset!["my-tag"];
/// let set_tag_attribute_values = hashmap![
/// "my-tag" => hashmap![
/// "my-attr" => "val",
/// ],
/// ];
/// let a = Builder::new().tags(tags).set_tag_attribute_values(set_tag_attribute_values)
/// .clean("<my-tag>")
/// .to_string();
/// assert_eq!(a, "<my-tag my-attr=\"val\"></my-tag>");
/// # }
///
/// # Defaults
///
/// None.
pub fn set_tag_attribute_values(
&mut self,
value: HashMap<&'a str, HashMap<&'a str, &'a str>>,
) -> &mut Self {
self.set_tag_attribute_values = value;
self
}
/// Add an attribute value to set on a specific element.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_tags(&["my-tag"])
/// .set_tag_attribute_value("my-tag", "my-attr", "val")
/// .clean("<my-tag>test</my-tag> <span>mess</span>").to_string();
/// assert_eq!("<my-tag my-attr=\"val\">test</my-tag> <span>mess</span>", a);
pub fn set_tag_attribute_value<
T: 'a + ?Sized + Borrow<str>,
A: 'a + ?Sized + Borrow<str>,
V: 'a + ?Sized + Borrow<str>,
>(
&mut self,
tag: &'a T,
attribute: &'a A,
value: &'a V,
) -> &mut Self {
self.set_tag_attribute_values
.entry(tag.borrow())
.or_default()
.insert(attribute.borrow(), value.borrow());
self
}
/// Remove existing tag-specific attribute values to be set.
///
/// Does nothing if the attribute is already gone.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// // this does nothing, since no value is set for this tag attribute yet
/// .rm_set_tag_attribute_value("a", "target")
/// .set_tag_attribute_value("a", "target", "_blank")
/// .rm_set_tag_attribute_value("a", "target")
/// .clean("<a href=\"/\"></a>").to_string();
/// assert_eq!("<a href=\"/\" rel=\"noopener noreferrer\"></a>", a);
pub fn rm_set_tag_attribute_value<
T: 'a + ?Sized + Borrow<str>,
A: 'a + ?Sized + Borrow<str>,
>(
&mut self,
tag: &'a T,
attribute: &'a A,
) -> &mut Self {
if let Some(attributes) = self.set_tag_attribute_values.get_mut(tag.borrow()) {
attributes.remove(attribute.borrow());
}
self
}
/// Returns the value that will be set for the attribute on the element, if any.
///
/// # Examples
///
/// let mut b = ammonia::Builder::default();
/// b.set_tag_attribute_value("a", "target", "_blank");
/// let value = b.get_set_tag_attribute_value("a", "target");
/// assert_eq!(value, Some("_blank"));
pub fn get_set_tag_attribute_value<
T: 'a + ?Sized + Borrow<str>,
A: 'a + ?Sized + Borrow<str>,
>(
&self,
tag: &'a T,
attribute: &'a A,
) -> Option<&'a str> {
self.set_tag_attribute_values
.get(tag.borrow())
.and_then(|map| map.get(attribute.borrow()))
.copied()
}
/// Returns a copy of the set of tag-specific attribute values to be set.
///
/// # Examples
///
/// use maplit::{hashmap, hashset};
///
/// let attribute_values = hashmap![
/// "my-attr-1" => "foo",
/// "my-attr-2" => "bar",
/// ];
/// let set_tag_attribute_values = hashmap![
/// "my-tag" => attribute_values,
/// ];
///
/// let mut b = ammonia::Builder::default();
/// b.set_tag_attribute_values(Clone::clone(&set_tag_attribute_values));
/// assert_eq!(set_tag_attribute_values, b.clone_set_tag_attribute_values());
pub fn clone_set_tag_attribute_values(&self) -> HashMap<&'a str, HashMap<&'a str, &'a str>> {
self.set_tag_attribute_values.clone()
}
/// Sets the prefix of attributes that are allowed on any tag.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// let prefixes = hashset!["data-"];
/// let a = Builder::new()
/// .generic_attribute_prefixes(prefixes)
/// .clean("<b data-val=1>")
/// .to_string();
/// assert_eq!(a, "<b data-val=\"1\"></b>");
/// # }
///
/// # Defaults
///
/// No attribute prefixes are allowed by default.
pub fn generic_attribute_prefixes(&mut self, value: HashSet<&'a str>) -> &mut Self {
self.generic_attribute_prefixes = Some(value);
self
}
/// Add additional whitelisted attribute prefix without overwriting old ones.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_generic_attribute_prefixes(&["my-"])
/// .clean("<span my-attr>mess</span>").to_string();
/// assert_eq!("<span my-attr=\"\">mess</span>", a);
pub fn add_generic_attribute_prefixes<
T: 'a + ?Sized + Borrow<str>,
I: IntoIter<Item = &'a T>,
>(
&mut self,
it: I,
) -> &mut Self {
self.generic_attribute_prefixes
.get_or_insert_with(HashSet::new)
.extend(it.into_iter().map(Borrow::borrow));
self
}
/// Remove already-whitelisted attribute prefixes.
///
/// Does nothing if the attribute prefix is already gone.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_generic_attribute_prefixes(&["data-", "code-"])
/// .rm_generic_attribute_prefixes(&["data-"])
/// .clean("<span code-test=\"foo\" data-test=\"cool\"></span>").to_string();
/// assert_eq!("<span code-test=\"foo\"></span>", a);
pub fn rm_generic_attribute_prefixes<
'b,
T: 'b + ?Sized + Borrow<str>,
I: IntoIter<Item = &'b T>,
>(
&mut self,
it: I,
) -> &mut Self {
if let Some(true) = self.generic_attribute_prefixes.as_mut().map(|prefixes| {
for i in it {
let _ = prefixes.remove(i.borrow());
}
prefixes.is_empty()
}) {
self.generic_attribute_prefixes = None;
}
self
}
/// Returns a copy of the set of whitelisted attribute prefixes.
///
/// # Examples
///
/// use maplit::hashset;
///
/// let generic_attribute_prefixes = hashset!["my-prfx-1-", "my-prfx-2-"];
///
/// let mut b = ammonia::Builder::default();
/// b.generic_attribute_prefixes(Clone::clone(&generic_attribute_prefixes));
/// assert_eq!(Some(generic_attribute_prefixes), b.clone_generic_attribute_prefixes());
pub fn clone_generic_attribute_prefixes(&self) -> Option<HashSet<&'a str>> {
self.generic_attribute_prefixes.clone()
}
/// Sets the attributes that are allowed on any tag.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// let attributes = hashset!["data-val"];
/// let a = Builder::new()
/// .generic_attributes(attributes)
/// .clean("<b data-val=1>")
/// .to_string();
/// assert_eq!(a, "<b data-val=\"1\"></b>");
/// # }
///
/// # Defaults
///
/// ```notest
/// lang, title
/// ```
pub fn generic_attributes(&mut self, value: HashSet<&'a str>) -> &mut Self {
self.generic_attributes = value;
self
}
/// Add additonal whitelisted attributes without overwriting old ones.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_generic_attributes(&["my-attr"])
/// .clean("<span my-attr>mess</span>").to_string();
/// assert_eq!("<span my-attr=\"\">mess</span>", a);
pub fn add_generic_attributes<T: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>(
&mut self,
it: I,
) -> &mut Self {
self.generic_attributes
.extend(it.into_iter().map(Borrow::borrow));
self
}
/// Remove already-whitelisted attributes.
///
/// Does nothing if the attribute is already gone.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .rm_generic_attributes(&["title"])
/// .clean("<span title=\"cool\"></span>").to_string();
/// assert_eq!("<span></span>", a);
pub fn rm_generic_attributes<'b, T: 'b + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>(
&mut self,
it: I,
) -> &mut Self {
for i in it {
self.generic_attributes.remove(i.borrow());
}
self
}
/// Returns a copy of the set of whitelisted attributes.
///
/// # Examples
///
/// use maplit::hashset;
///
/// let generic_attributes = hashset!["my-attr-1", "my-attr-2"];
///
/// let mut b = ammonia::Builder::default();
/// b.generic_attributes(Clone::clone(&generic_attributes));
/// assert_eq!(generic_attributes, b.clone_generic_attributes());
pub fn clone_generic_attributes(&self) -> HashSet<&'a str> {
self.generic_attributes.clone()
}
/// Sets the URL schemes permitted on `href` and `src` attributes.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// let url_schemes = hashset![
/// "http", "https", "mailto", "magnet"
/// ];
/// let a = Builder::new().url_schemes(url_schemes)
/// .clean("<a href=\"magnet:?xt=urn:ed2k:31D6CFE0D16AE931B73C59D7E0C089C0&xl=0&dn=zero_len.fil&xt=urn:bitprint:3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ.LWPNACQDBZRYXW3VHJVCJ64QBZNGHOHHHZWCLNQ&xt=urn:md5:D41D8CD98F00B204E9800998ECF8427E\">zero-length file</a>")
/// .to_string();
///
/// // See `link_rel` for information on the rel="noopener noreferrer" attribute
/// // in the cleaned HTML.
/// assert_eq!(a,
/// "<a href=\"magnet:?xt=urn:ed2k:31D6CFE0D16AE931B73C59D7E0C089C0&xl=0&dn=zero_len.fil&xt=urn:bitprint:3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ.LWPNACQDBZRYXW3VHJVCJ64QBZNGHOHHHZWCLNQ&xt=urn:md5:D41D8CD98F00B204E9800998ECF8427E\" rel=\"noopener noreferrer\">zero-length file</a>");
/// # }
///
/// # Defaults
///
/// ```notest
/// bitcoin, ftp, ftps, geo, http, https, im, irc,
/// ircs, magnet, mailto, mms, mx, news, nntp,
/// openpgp4fpr, sip, sms, smsto, ssh, tel, url,
/// webcal, wtai, xmpp
/// ```
pub fn url_schemes(&mut self, value: HashSet<&'a str>) -> &mut Self {
self.url_schemes = value;
self
}
/// Add additonal whitelisted URL schemes without overwriting old ones.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_url_schemes(&["my-scheme"])
/// .clean("<a href=my-scheme:home>mess</span>").to_string();
/// assert_eq!("<a href=\"my-scheme:home\" rel=\"noopener noreferrer\">mess</a>", a);
pub fn add_url_schemes<T: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>(
&mut self,
it: I,
) -> &mut Self {
self.url_schemes.extend(it.into_iter().map(Borrow::borrow));
self
}
/// Remove already-whitelisted attributes.
///
/// Does nothing if the attribute is already gone.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .rm_url_schemes(&["ftp"])
/// .clean("<a href=\"ftp://ftp.mozilla.org/\"></a>").to_string();
/// assert_eq!("<a rel=\"noopener noreferrer\"></a>", a);
pub fn rm_url_schemes<'b, T: 'b + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>(
&mut self,
it: I,
) -> &mut Self {
for i in it {
self.url_schemes.remove(i.borrow());
}
self
}
/// Returns a copy of the set of whitelisted URL schemes.
///
/// # Examples
/// use maplit::hashset;
///
/// let url_schemes = hashset!["my-scheme-1", "my-scheme-2"];
///
/// let mut b = ammonia::Builder::default();
/// b.url_schemes(Clone::clone(&url_schemes));
/// assert_eq!(url_schemes, b.clone_url_schemes());
pub fn clone_url_schemes(&self) -> HashSet<&'a str> {
self.url_schemes.clone()
}
/// Configures the behavior for relative URLs: pass-through, resolve-with-base, or deny.
///
/// # Examples
///
/// use ammonia::{Builder, UrlRelative};
///
/// let a = Builder::new().url_relative(UrlRelative::PassThrough)
/// .clean("<a href=/>Home</a>")
/// .to_string();
///
/// // See `link_rel` for information on the rel="noopener noreferrer" attribute
/// // in the cleaned HTML.
/// assert_eq!(
/// a,
/// "<a href=\"/\" rel=\"noopener noreferrer\">Home</a>");
///
/// # Defaults
///
/// ```notest
/// UrlRelative::PassThrough
/// ```
pub fn url_relative(&mut self, value: UrlRelative<'a>) -> &mut Self {
self.url_relative = value;
self
}
/// Allows rewriting of all attributes using a callback.
///
/// The callback takes name of the element, attribute and its value.
/// Returns `None` to remove the attribute, or a value to use.
///
/// Rewriting of attributes with URLs is done before `url_relative()`.
///
/// # Panics
///
/// If more than one callback is set.
///
/// # Examples
///
/// ```rust
/// use ammonia::Builder;
/// let a = Builder::new()
/// .attribute_filter(|element, attribute, value| {
/// match (element, attribute) {
/// ("img", "src") => None,
/// _ => Some(value.into())
/// }
/// })
/// .link_rel(None)
/// .clean("<a href=/><img alt=Home src=foo></a>")
/// .to_string();
/// assert_eq!(a,
/// r#"<a href="/"><img alt="Home"></a>"#);
/// ```
pub fn attribute_filter<'cb, CallbackFn>(&mut self, callback: CallbackFn) -> &mut Self
where
CallbackFn: for<'u> Fn(&str, &str, &'u str) -> Option<Cow<'u, str>> + Send + Sync + 'static,
{
assert!(
self.attribute_filter.is_none(),
"attribute_filter can be set only once"
);
self.attribute_filter = Some(Box::new(callback));
self
}
/// Returns `true` if the relative URL resolver is set to `Deny`.
///
/// # Examples
///
/// use ammonia::{Builder, UrlRelative};
/// let mut a = Builder::default();
/// a.url_relative(UrlRelative::Deny);
/// assert!(a.is_url_relative_deny());
/// a.url_relative(UrlRelative::PassThrough);
/// assert!(!a.is_url_relative_deny());
pub fn is_url_relative_deny(&self) -> bool {
matches!(self.url_relative, UrlRelative::Deny)
}
/// Returns `true` if the relative URL resolver is set to `PassThrough`.
///
/// # Examples
///
/// use ammonia::{Builder, UrlRelative};
/// let mut a = Builder::default();
/// a.url_relative(UrlRelative::Deny);
/// assert!(!a.is_url_relative_pass_through());
/// a.url_relative(UrlRelative::PassThrough);
/// assert!(a.is_url_relative_pass_through());
pub fn is_url_relative_pass_through(&self) -> bool {
matches!(self.url_relative, UrlRelative::PassThrough)
}
/// Returns `true` if the relative URL resolver is set to `Custom`.
///
/// # Examples
///
/// use ammonia::{Builder, UrlRelative};
/// use std::borrow::Cow;
/// fn test(a: &str) -> Option<Cow<str>> { None }
/// # fn main() {
/// let mut a = Builder::default();
/// a.url_relative(UrlRelative::Custom(Box::new(test)));
/// assert!(a.is_url_relative_custom());
/// a.url_relative(UrlRelative::PassThrough);
/// assert!(!a.is_url_relative_custom());
/// a.url_relative(UrlRelative::Deny);
/// assert!(!a.is_url_relative_custom());
/// # }
pub fn is_url_relative_custom(&self) -> bool {
matches!(self.url_relative, UrlRelative::Custom(_))
}
/// Configures a `rel` attribute that will be added on links.
///
/// If `rel` is in the generic or tag attributes, this must be set to `None`.
/// Common `rel` values to include:
///
/// * `noopener`: This prevents [a particular type of XSS attack],
/// and should usually be turned on for untrusted HTML.
/// * `noreferrer`: This prevents the browser from [sending the source URL]
/// to the website that is linked to.
/// * `nofollow`: This prevents search engines from [using this link for
/// ranking], which disincentivizes spammers.
///
/// To turn on rel-insertion, call this function with a space-separated list.
/// Ammonia does not parse rel-attributes;
/// it just puts the given string into the attribute directly.
///
/// [a particular type of XSS attack]: https://mathiasbynens.github.io/rel-noopener/
/// [sending the source URL]: https://en.wikipedia.org/wiki/HTTP_referer
/// [using this link for ranking]: https://en.wikipedia.org/wiki/Nofollow
///
/// # Examples
///
/// use ammonia::Builder;
///
/// let a = Builder::new().link_rel(None)
/// .clean("<a href=https://rust-lang.org/>Rust</a>")
/// .to_string();
/// assert_eq!(
/// a,
/// "<a href=\"https://rust-lang.org/\">Rust</a>");
///
/// # Defaults
///
/// ```notest
/// Some("noopener noreferrer")
/// ```
pub fn link_rel(&mut self, value: Option<&'a str>) -> &mut Self {
self.link_rel = value;
self
}
/// Returns the settings for links' `rel` attribute, if one is set.
///
/// # Examples
///
/// use ammonia::{Builder, UrlRelative};
/// let mut a = Builder::default();
/// a.link_rel(Some("a b"));
/// assert_eq!(a.get_link_rel(), Some("a b"));
pub fn get_link_rel(&self) -> Option<&str> {
self.link_rel
}
/// Sets the CSS classes that are allowed on specific tags.
///
/// The values is structured as a map from tag names to a set of class names.
///
/// If the `class` attribute is itself whitelisted for a tag, then adding entries to
/// this map will cause a panic.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::{hashmap, hashset};
///
/// # fn main() {
/// let allowed_classes = hashmap![
/// "code" => hashset!["rs", "ex", "c", "cxx", "js"]
/// ];
/// let a = Builder::new()
/// .allowed_classes(allowed_classes)
/// .clean("<code class=rs>fn main() {}</code>")
/// .to_string();
/// assert_eq!(
/// a,
/// "<code class=\"rs\">fn main() {}</code>");
/// # }
///
/// # Defaults
///
/// The set of allowed classes is empty by default.
pub fn allowed_classes(&mut self, value: HashMap<&'a str, HashSet<&'a str>>) -> &mut Self {
self.allowed_classes = value;
self
}
/// Add additonal whitelisted classes without overwriting old ones.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_allowed_classes("a", &["onebox"])
/// .clean("<a href=/ class=onebox>mess</span>").to_string();
/// assert_eq!("<a href=\"/\" class=\"onebox\" rel=\"noopener noreferrer\">mess</a>", a);
pub fn add_allowed_classes<
T: 'a + ?Sized + Borrow<str>,
U: 'a + ?Sized + Borrow<str>,
I: IntoIter<Item = &'a T>,
>(
&mut self,
tag: &'a U,
it: I,
) -> &mut Self {
self.allowed_classes
.entry(tag.borrow())
.or_default()
.extend(it.into_iter().map(Borrow::borrow));
self
}
/// Remove already-whitelisted attributes.
///
/// Does nothing if the attribute is already gone.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_allowed_classes("span", &["active"])
/// .rm_allowed_classes("span", &["active"])
/// .clean("<span class=active>").to_string();
/// assert_eq!("<span class=\"\"></span>", a);
pub fn rm_allowed_classes<
'b,
'c,
T: 'b + ?Sized + Borrow<str>,
U: 'c + ?Sized + Borrow<str>,
I: IntoIter<Item = &'b T>,
>(
&mut self,
tag: &'c U,
it: I,
) -> &mut Self {
if let Some(tag) = self.allowed_classes.get_mut(tag.borrow()) {
for i in it {
tag.remove(i.borrow());
}
}
self
}
/// Returns a copy of the set of whitelisted class attributes.
///
/// # Examples
///
/// use maplit::{hashmap, hashset};
///
/// let allowed_classes = hashmap![
/// "my-tag" => hashset!["my-class-1", "my-class-2"]
/// ];
///
/// let mut b = ammonia::Builder::default();
/// b.allowed_classes(Clone::clone(&allowed_classes));
/// assert_eq!(allowed_classes, b.clone_allowed_classes());
pub fn clone_allowed_classes(&self) -> HashMap<&'a str, HashSet<&'a str>> {
self.allowed_classes.clone()
}
/// Configures the handling of HTML comments.
///
/// If this option is false, comments will be preserved.
///
/// # Examples
///
/// use ammonia::Builder;
///
/// let a = Builder::new().strip_comments(false)
/// .clean("<!-- yes -->")
/// .to_string();
/// assert_eq!(
/// a,
/// "<!-- yes -->");
///
/// # Defaults
///
/// `true`
pub fn strip_comments(&mut self, value: bool) -> &mut Self {
self.strip_comments = value;
self
}
/// Returns `true` if comment stripping is turned on.
///
/// # Examples
///
/// let mut a = ammonia::Builder::new();
/// a.strip_comments(true);
/// assert!(a.will_strip_comments());
/// a.strip_comments(false);
/// assert!(!a.will_strip_comments());
pub fn will_strip_comments(&self) -> bool {
self.strip_comments
}
/// Prefixes all "id" attribute values with a given string. Note that the tag and
/// attribute themselves must still be whitelisted.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::hashset;
///
/// # fn main() {
/// let attributes = hashset!["id"];
/// let a = Builder::new()
/// .generic_attributes(attributes)
/// .id_prefix(Some("safe-"))
/// .clean("<b id=42>")
/// .to_string();
/// assert_eq!(a, "<b id=\"safe-42\"></b>");
/// # }
///
/// # Defaults
///
/// `None`
pub fn id_prefix(&mut self, value: Option<&'a str>) -> &mut Self {
self.id_prefix = value;
self
}
/// Constructs a [`Builder`] instance configured with the [default options].
///
/// # Examples
///
/// use ammonia::{Builder, Url, UrlRelative};
/// # use std::error::Error;
///
/// # fn do_main() -> Result<(), Box<dyn Error>> {
/// let input = "<!-- comments will be stripped -->This is an <a href=.>Ammonia</a> example using <a href=struct.Builder.html#method.new onclick=xss>the <code onmouseover=xss>new()</code> function</a>.";
/// let output = "This is an <a href=\"https://docs.rs/ammonia/1.0/ammonia/\" rel=\"noopener noreferrer\">Ammonia</a> example using <a href=\"https://docs.rs/ammonia/1.0/ammonia/struct.Builder.html#method.new\" rel=\"noopener noreferrer\">the <code>new()</code> function</a>.";
///
/// let result = Builder::new() // <--
/// .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?))
/// .clean(input)
/// .to_string();
/// assert_eq!(result, output);
/// # Ok(())
/// # }
/// # fn main() { do_main().unwrap() }
///
/// [default options]: fn.clean.html
/// [`Builder`]: struct.Builder.html
pub fn new() -> Self {
Self::default()
}
/// Constructs a [`Builder`] instance configured with no allowed tags.
///
/// # Examples
///
/// use ammonia::{Builder, Url, UrlRelative};
/// # use std::error::Error;
///
/// # fn do_main() -> Result<(), Box<dyn Error>> {
/// let input = "<!-- comments will be stripped -->This is an <a href=.>Ammonia</a> example using <a href=struct.Builder.html#method.new onclick=xss>the <code onmouseover=xss>empty()</code> function</a>.";
/// let output = "This is an Ammonia example using the empty() function.";
///
/// let result = Builder::empty() // <--
/// .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?))
/// .clean(input)
/// .to_string();
/// assert_eq!(result, output);
/// # Ok(())
/// # }
/// # fn main() { do_main().unwrap() }
///
/// [default options]: fn.clean.html
/// [`Builder`]: struct.Builder.html
pub fn empty() -> Self {
Self {
tags: hashset![],
..Self::default()
}
}
/// Sanitizes an HTML fragment in a string according to the configured options.
///
/// # Examples
///
/// use ammonia::{Builder, Url, UrlRelative};
/// # use std::error::Error;
///
/// # fn do_main() -> Result<(), Box<dyn Error>> {
/// let input = "<!-- comments will be stripped -->This is an <a href=.>Ammonia</a> example using <a href=struct.Builder.html#method.new onclick=xss>the <code onmouseover=xss>new()</code> function</a>.";
/// let output = "This is an <a href=\"https://docs.rs/ammonia/1.0/ammonia/\" rel=\"noopener noreferrer\">Ammonia</a> example using <a href=\"https://docs.rs/ammonia/1.0/ammonia/struct.Builder.html#method.new\" rel=\"noopener noreferrer\">the <code>new()</code> function</a>.";
///
/// let result = Builder::new()
/// .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?))
/// .clean(input)
/// .to_string(); // <--
/// assert_eq!(result, output);
/// # Ok(())
/// # }
/// # fn main() { do_main().unwrap() }
pub fn clean(&self, src: &str) -> Document {
let parser = Self::make_parser();
let dom = parser.one(src);
self.clean_dom(dom)
}
/// Sanitizes an HTML fragment from a reader according to the configured options.
///
/// The input should be in UTF-8 encoding, otherwise the decoding is lossy, just
/// like when using [`String::from_utf8_lossy`].
///
/// To avoid consuming the reader, a mutable reference can be passed to this method.
///
/// # Examples
///
/// use ammonia::Builder;
/// # use std::error::Error;
///
/// # fn do_main() -> Result<(), Box<dyn Error>> {
/// let a = Builder::new()
/// .clean_from_reader(&b"<!-- no -->"[..])? // notice the `b`
/// .to_string();
/// assert_eq!(a, "");
/// # Ok(()) }
/// # fn main() { do_main().unwrap() }
///
/// [`String::from_utf8_lossy`]: https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8_lossy
pub fn clean_from_reader<R>(&self, mut src: R) -> io::Result<Document>
where
R: io::Read,
{
let parser = Self::make_parser().from_utf8();
let dom = parser.read_from(&mut src)?;
Ok(self.clean_dom(dom))
}
/// Clean a post-parsing DOM.
///
/// This is not a public API because RcDom isn't really stable.
/// We want to be able to take breaking changes to html5ever itself
/// without having to break Ammonia's API.
fn clean_dom(&self, mut dom: RcDom) -> Document {
let mut stack = Vec::new();
let mut removed = Vec::new();
let link_rel = self
.link_rel
.map(|link_rel| format_tendril!("{}", link_rel));
if link_rel.is_some() {
assert!(self.generic_attributes.get("rel").is_none());
assert!(self
.tag_attributes
.get("a")
.and_then(|a| a.get("rel"))
.is_none());
}
assert!(self.allowed_classes.is_empty() || !self.generic_attributes.contains("class"));
for tag_name in self.allowed_classes.keys() {
assert!(self
.tag_attributes
.get(tag_name)
.and_then(|a| a.get("class"))
.is_none());
}
for tag_name in &self.clean_content_tags {
assert!(!self.tags.contains(tag_name));
assert!(!self.tag_attributes.contains_key(tag_name));
}
let body = {
let children = dom.document.children.borrow();
children[0].clone()
};
stack.extend(
mem::take(&mut *body.children.borrow_mut())
.into_iter()
.rev(),
);
// This design approach is used to prevent pathological content from producing
// a stack overflow. The `stack` contains to-be-cleaned nodes, while `remove`,
// of course, contains nodes that need to be dropped (we can't just drop them,
// because they could have a very deep child tree).
while let Some(mut node) = stack.pop() {
let parent = node.parent
.replace(None).expect("a node in the DOM will have a parent, except the root, which is not processed")
.upgrade().expect("a node's parent will be pointed to by its parent (or the root pointer), and will not be dropped");
if self.clean_node_content(&node) {
removed.push(node);
continue;
}
let pass_clean = self.clean_child(&mut node);
let pass = pass_clean && self.check_expected_namespace(&parent, &node);
if pass {
self.adjust_node_attributes(&mut node, &link_rel, self.id_prefix);
dom.append(&parent.clone(), NodeOrText::AppendNode(node.clone()));
} else {
for sub in node.children.borrow_mut().iter_mut() {
sub.parent.replace(Some(Rc::downgrade(&parent)));
}
}
stack.extend(
mem::take(&mut *node.children.borrow_mut())
.into_iter()
.rev(),
);
if !pass {
removed.push(node);
}
}
// Now, imperatively clean up all of the child nodes.
// Otherwise, we could wind up with a DoS, either caused by a memory leak,
// or caused by a stack overflow.
while let Some(node) = removed.pop() {
removed.extend_from_slice(&mem::take(&mut *node.children.borrow_mut())[..]);
}
Document(dom)
}
/// Returns `true` if a node and all its content should be removed.
fn clean_node_content(&self, node: &Handle) -> bool {
match node.data {
NodeData::Text { .. }
| NodeData::Comment { .. }
| NodeData::Doctype { .. }
| NodeData::Document
| NodeData::ProcessingInstruction { .. } => false,
NodeData::Element { ref name, .. } => self.clean_content_tags.contains(&*name.local),
}
}
/// Remove unwanted attributes, and check if the node should be kept or not.
///
/// The root node doesn't need cleaning because we create the root node ourselves,
/// and it doesn't get serialized, and ... it just exists to give the parser
/// a context (in this case, a div-like block context).
fn clean_child(&self, child: &mut Handle) -> bool {
match child.data {
NodeData::Text { .. } => true,
NodeData::Comment { .. } => !self.strip_comments,
NodeData::Doctype { .. }
| NodeData::Document
| NodeData::ProcessingInstruction { .. } => false,
NodeData::Element {
ref name,
ref attrs,
..
} => {
if self.tags.contains(&*name.local) {
let attr_filter = |attr: &html5ever::Attribute| {
let whitelisted = self.generic_attributes.contains(&*attr.name.local)
|| self.generic_attribute_prefixes.as_ref().map(|prefixes| {
prefixes.iter().any(|&p| attr.name.local.starts_with(p))
}) == Some(true)
|| self
.tag_attributes
.get(&*name.local)
.map(|ta| ta.contains(&*attr.name.local))
== Some(true)
|| self
.tag_attribute_values
.get(&*name.local)
.and_then(|tav| tav.get(&*attr.name.local))
.map(|vs| {
let attr_val = attr.value.to_lowercase();
vs.iter().any(|v| v.to_lowercase() == attr_val)
})
== Some(true);
if !whitelisted {
// If the class attribute is not whitelisted,
// but there is a whitelisted set of allowed_classes,
// do not strip out the class attribute.
// Banned classes will be filtered later.
&*attr.name.local == "class"
&& self.allowed_classes.contains_key(&*name.local)
} else if is_url_attr(&name.local, &attr.name.local) {
let url = Url::parse(&attr.value);
if let Ok(url) = url {
self.url_schemes.contains(url.scheme())
} else if url == Err(url::ParseError::RelativeUrlWithoutBase) {
!matches!(self.url_relative, UrlRelative::Deny)
} else {
false
}
} else {
true
}
};
attrs.borrow_mut().retain(attr_filter);
true
} else {
false
}
}
}
}
// Check for unexpected namespace changes.
//
// The issue happens if developers added to the list of allowed tags any
// tag which is parsed in RCDATA state, PLAINTEXT state or RAWTEXT state,
// that is:
//
// * title
// * textarea
// * xmp
// * iframe
// * noembed
// * noframes
// * plaintext
// * noscript
// * style
// * script
//
// An example in the wild is Plume, that allows iframe [1]. So in next
// examples I'll assume the following policy:
//
// Builder::new()
// .add_tags(&["iframe"])
//
// In HTML namespace `<iframe>` is parsed specially; that is, its content is
// treated as text. For instance, the following html:
//
// <iframe><a>test
//
// Is parsed into the following DOM tree:
//
// iframe
// └─ #text: <a>test
//
// So iframe cannot have any children other than a text node.
//
// The same is not true, though, in "foreign content"; that is, within
// <svg> or <math> tags. The following html:
//
// <svg><iframe><a>test
//
// is parsed differently:
//
// svg
// └─ iframe
// └─ a
// └─ #text: test
//
// So in SVG namespace iframe can have children.
//
// Ammonia disallows <svg> but it keeps its content after deleting it. And
// the parser internally keeps track of the namespace of the element. So
// assume we have the following snippet:
//
// <svg><iframe><a title="</iframe><img src onerror=alert(1)>">test
//
// It is parsed into:
//
// svg
// └─ iframe
// └─ a title="</iframe><img src onerror=alert(1)>"
// └─ #text: test
//
// This DOM tree is harmless from ammonia point of view because the piece
// of code that looks like XSS is in a title attribute. Hence, the
// resulting "safe" HTML from ammonia would be:
//
// <iframe><a title="</iframe><img src onerror=alert(1)>" rel="noopener
// noreferrer">test</a></iframe>
//
// However, at this point, the information about namespace is lost, which
// means that the browser will parse this snippet into:
//
// ├─ iframe
// │ └─ #text: <a title="
// ├─ img src="" onerror="alert(1)"
// └─ #text: " rel="noopener noreferrer">test
//
// Leading to XSS.
//
// To solve this issue, check for unexpected namespace switches after cleanup.
// Elements which change namespace at an unexpected point are removed.
// This function returns `true` if `child` should be kept, and `false` if it
// should be removed.
//
// [1]: https://github.com/Plume-org/Plume/blob/main/plume-models/src/safe_string.rs#L21
fn check_expected_namespace(&self, parent: &Handle, child: &Handle) -> bool {
let (parent, child) = match (&parent.data, &child.data) {
(NodeData::Element { name: pn, .. }, NodeData::Element { name: cn, .. }) => (pn, cn),
_ => return true,
};
// The only way to switch from html to svg is with the <svg> tag
if parent.ns == ns!(html) && child.ns == ns!(svg) {
child.local == local_name!("svg")
// The only way to switch from html to mathml is with the <math> tag
} else if parent.ns == ns!(html) && child.ns == ns!(mathml) {
child.local == local_name!("math")
// The only way to switch from mathml to svg/html is with a text integration point
} else if parent.ns == ns!(mathml) && child.ns != ns!(mathml) {
// https://html.spec.whatwg.org/#mathml
matches!(
&*parent.local,
"mi" | "mo" | "mn" | "ms" | "mtext" | "annotation-xml"
)
// The only way to switch from svg to mathml/html is with an html integration point
} else if parent.ns == ns!(svg) && child.ns != ns!(svg) {
// https://html.spec.whatwg.org/#svg-0
matches!(&*parent.local, "foreignObject")
} else if child.ns == ns!(svg) {
is_svg_tag(&child.local)
} else if child.ns == ns!(mathml) {
is_mathml_tag(&child.local)
} else if child.ns == ns!(html) {
(!is_svg_tag(&child.local) && !is_mathml_tag(&child.local))
|| matches!(
&*child.local,
"title" | "style" | "font" | "a" | "script" | "span"
)
} else {
// There are no other supported ways to switch namespace
parent.ns == child.ns
}
}
/// Add and transform special-cased attributes and elements.
///
/// This function handles:
///
/// * relative URL rewriting
/// * adding `<a rel>` attributes
/// * filtering out banned classes
fn adjust_node_attributes(
&self,
child: &mut Handle,
link_rel: &Option<StrTendril>,
id_prefix: Option<&'a str>,
) {
if let NodeData::Element {
ref name,
ref attrs,
..
} = child.data
{
if let Some(set_attrs) = self.set_tag_attribute_values.get(&*name.local) {
let mut attrs = attrs.borrow_mut();
for (&set_name, &set_value) in set_attrs {
// set the value of the attribute if the attribute is already present
if let Some(attr) = attrs.iter_mut().find(|attr| &*attr.name.local == set_name)
{
if &*attr.value != set_value {
attr.value = set_value.into();
}
} else {
// otherwise, add the attribute
let attr = Attribute {
name: QualName::new(None, ns!(), set_name.into()),
value: set_value.into(),
};
attrs.push(attr);
}
}
}
if let Some(ref link_rel) = *link_rel {
if &*name.local == "a" {
attrs.borrow_mut().push(Attribute {
name: QualName::new(None, ns!(), local_name!("rel")),
value: link_rel.clone(),
})
}
}
if let Some(ref id_prefix) = id_prefix {
for attr in &mut *attrs.borrow_mut() {
if &attr.name.local == "id" && !attr.value.starts_with(id_prefix) {
attr.value = format_tendril!("{}{}", id_prefix, attr.value);
}
}
}
if let Some(ref attr_filter) = self.attribute_filter {
let mut drop_attrs = Vec::new();
let mut attrs = attrs.borrow_mut();
for (i, attr) in &mut attrs.iter_mut().enumerate() {
let replace_with = if let Some(new) =
attr_filter.filter(&name.local, &attr.name.local, &attr.value)
{
if *new != *attr.value {
Some(format_tendril!("{}", new))
} else {
None // no need to replace the attr if filter returned the same value
}
} else {
drop_attrs.push(i);
None
};
if let Some(replace_with) = replace_with {
attr.value = replace_with;
}
}
for i in drop_attrs.into_iter().rev() {
attrs.swap_remove(i);
}
}
{
let mut drop_attrs = Vec::new();
let mut attrs = attrs.borrow_mut();
for (i, attr) in attrs.iter_mut().enumerate() {
if is_url_attr(&name.local, &attr.name.local) && is_url_relative(&attr.value) {
let new_value = self.url_relative.evaluate(&attr.value);
if let Some(new_value) = new_value {
attr.value = new_value;
} else {
drop_attrs.push(i);
}
}
}
// Swap remove scrambles the vector after the current point.
// We will not do anything except with items before the current point.
// The `rev()` is, as such, necessary for correctness.
// We could use regular `remove(usize)` and a forward iterator,
// but that's slower.
for i in drop_attrs.into_iter().rev() {
attrs.swap_remove(i);
}
}
if let Some(allowed_values) = self.allowed_classes.get(&*name.local) {
for attr in &mut *attrs.borrow_mut() {
if &attr.name.local == "class" {
let mut classes = vec![];
// https://html.spec.whatwg.org/#global-attributes:classes-2
for class in attr.value.split_ascii_whitespace() {
if allowed_values.contains(class) {
classes.push(class.to_owned());
}
}
attr.value = format_tendril!("{}", classes.join(" "));
}
}
}
}
}
/// Initializes an HTML fragment parser.
///
/// Ammonia conforms to the HTML5 fragment parsing rules,
/// by parsing the given fragment as if it were included in a <div> tag.
fn make_parser() -> html::Parser<RcDom> {
html::parse_fragment(
RcDom::default(),
html::ParseOpts::default(),
QualName::new(None, ns!(html), local_name!("div")),
vec![],
)
}
}
/// Given an element name and attribute name, determine if the given attribute contains a URL.
fn is_url_attr(element: &str, attr: &str) -> bool {
attr == "href"
|| attr == "src"
|| (element == "form" && attr == "action")
|| (element == "object" && attr == "data")
|| ((element == "button" || element == "input") && attr == "formaction")
|| (element == "a" && attr == "ping")
|| (element == "video" && attr == "poster")
}
/// Given an element name, check if it's SVG
fn is_svg_tag(element: &str) -> bool {
// https://svgwg.org/svg2-draft/eltindex.html
matches!(
element,
"a" | "animate"
| "animateMotion"
| "animateTransform"
| "circle"
| "clipPath"
| "defs"
| "desc"
| "discard"
| "ellipse"
| "feBlend"
| "feColorMatrix"
| "feComponentTransfer"
| "feComposite"
| "feConvolveMatrix"
| "feDiffuseLighting"
| "feDisplacementMap"
| "feDistantLight"
| "feDropShadow"
| "feFlood"
| "feFuncA"
| "feFuncB"
| "feFuncG"
| "feFuncR"
| "feGaussianBlur"
| "feImage"
| "feMerge"
| "feMergeNode"
| "feMorphology"
| "feOffset"
| "fePointLight"
| "feSpecularLighting"
| "feSpotLight"
| "feTile"
| "feTurbulence"
| "filter"
| "foreignObject"
| "g"
| "image"
| "line"
| "linearGradient"
| "marker"
| "mask"
| "metadata"
| "mpath"
| "path"
| "pattern"
| "polygon"
| "polyline"
| "radialGradient"
| "rect"
| "script"
| "set"
| "stop"
| "style"
| "svg"
| "switch"
| "symbol"
| "text"
| "textPath"
| "title"
| "tspan"
| "use"
| "view"
)
}
/// Given an element name, check if it's Math
fn is_mathml_tag(element: &str) -> bool {
// https://svgwg.org/svg2-draft/eltindex.html
matches!(
element,
"abs"
| "and"
| "annotation"
| "annotation-xml"
| "apply"
| "approx"
| "arccos"
| "arccosh"
| "arccot"
| "arccoth"
| "arccsc"
| "arccsch"
| "arcsec"
| "arcsech"
| "arcsin"
| "arcsinh"
| "arctan"
| "arctanh"
| "arg"
| "bind"
| "bvar"
| "card"
| "cartesianproduct"
| "cbytes"
| "ceiling"
| "cerror"
| "ci"
| "cn"
| "codomain"
| "complexes"
| "compose"
| "condition"
| "conjugate"
| "cos"
| "cosh"
| "cot"
| "coth"
| "cs"
| "csc"
| "csch"
| "csymbol"
| "curl"
| "declare"
| "degree"
| "determinant"
| "diff"
| "divergence"
| "divide"
| "domain"
| "domainofapplication"
| "emptyset"
| "eq"
| "equivalent"
| "eulergamma"
| "exists"
| "exp"
| "exponentiale"
| "factorial"
| "factorof"
| "false"
| "floor"
| "fn"
| "forall"
| "gcd"
| "geq"
| "grad"
| "gt"
| "ident"
| "image"
| "imaginary"
| "imaginaryi"
| "implies"
| "in"
| "infinity"
| "int"
| "integers"
| "intersect"
| "interval"
| "inverse"
| "lambda"
| "laplacian"
| "lcm"
| "leq"
| "limit"
| "list"
| "ln"
| "log"
| "logbase"
| "lowlimit"
| "lt"
| "maction"
| "maligngroup"
| "malignmark"
| "math"
| "matrix"
| "matrixrow"
| "max"
| "mean"
| "median"
| "menclose"
| "merror"
| "mfenced"
| "mfrac"
| "mglyph"
| "mi"
| "min"
| "minus"
| "mlabeledtr"
| "mlongdiv"
| "mmultiscripts"
| "mn"
| "mo"
| "mode"
| "moment"
| "momentabout"
| "mover"
| "mpadded"
| "mphantom"
| "mprescripts"
| "mroot"
| "mrow"
| "ms"
| "mscarries"
| "mscarry"
| "msgroup"
| "msline"
| "mspace"
| "msqrt"
| "msrow"
| "mstack"
| "mstyle"
| "msub"
| "msubsup"
| "msup"
| "mtable"
| "mtd"
| "mtext"
| "mtr"
| "munder"
| "munderover"
| "naturalnumbers"
| "neq"
| "none"
| "not"
| "notanumber"
| "notin"
| "notprsubset"
| "notsubset"
| "or"
| "otherwise"
| "outerproduct"
| "partialdiff"
| "pi"
| "piece"
| "piecewise"
| "plus"
| "power"
| "primes"
| "product"
| "prsubset"
| "quotient"
| "rationals"
| "real"
| "reals"
| "reln"
| "rem"
| "root"
| "scalarproduct"
| "sdev"
| "sec"
| "sech"
| "selector"
| "semantics"
| "sep"
| "set"
| "setdiff"
| "share"
| "sin"
| "sinh"
| "span"
| "subset"
| "sum"
| "tan"
| "tanh"
| "tendsto"
| "times"
| "transpose"
| "true"
| "union"
| "uplimit"
| "variance"
| "vector"
| "vectorproduct"
| "xor"
)
}
fn is_url_relative(url: &str) -> bool {
matches!(
Url::parse(url),
Err(url::ParseError::RelativeUrlWithoutBase)
)
}
/// Policy for [relative URLs], that is, URLs that do not specify the scheme in full.
///
/// This policy kicks in, if set, for any attribute named `src` or `href`,
/// as well as the `data` attribute of an `object` tag.
///
/// [relative URLs]: struct.Builder.html#method.url_relative
///
/// # Examples
///
/// ## `Deny`
///
/// * `<a href="test">` is a file-relative URL, and will be removed
/// * `<a href="/test">` is a domain-relative URL, and will be removed
/// * `<a href="//example.com/test">` is a scheme-relative URL, and will be removed
/// * `<a href="http://example.com/test">` is an absolute URL, and will be kept
///
/// ## `PassThrough`
///
/// No changes will be made to any URLs, except if a disallowed scheme is used.
///
/// ## `RewriteWithBase`
///
/// If the base is set to `http://notriddle.com/some-directory/some-file`
///
/// * `<a href="test">` will be rewritten to `<a href="http://notriddle.com/some-directory/test">`
/// * `<a href="/test">` will be rewritten to `<a href="http://notriddle.com/test">`
/// * `<a href="//example.com/test">` will be rewritten to `<a href="http://example.com/test">`
/// * `<a href="http://example.com/test">` is an absolute URL, so it will be kept as-is
///
/// ## `Custom`
///
/// Pass the relative URL to a function.
/// If it returns `Some(string)`, then that one gets used.
/// Otherwise, it will remove the attribute (like `Deny` does).
///
/// use std::borrow::Cow;
/// fn is_absolute_path(url: &str) -> bool {
/// let u = url.as_bytes();
/// // `//a/b/c` is "protocol-relative", meaning "a" is a hostname
/// // `/a/b/c` is an absolute path, and what we want to do stuff to.
/// u.get(0) == Some(&b'/') && u.get(1) != Some(&b'/')
/// }
/// fn evaluate(url: &str) -> Option<Cow<str>> {
/// if is_absolute_path(url) {
/// Some(Cow::Owned(String::from("/root") + url))
/// } else {
/// Some(Cow::Borrowed(url))
/// }
/// }
/// fn main() {
/// let a = ammonia::Builder::new()
/// .url_relative(ammonia::UrlRelative::Custom(Box::new(evaluate)))
/// .clean("<a href=/test/path>fixed</a><a href=path>passed</a><a href=http://google.com/>skipped</a>")
/// .to_string();
/// assert_eq!(a, "<a href=\"/root/test/path\" rel=\"noopener noreferrer\">fixed</a><a href=\"path\" rel=\"noopener noreferrer\">passed</a><a href=\"http://google.com/\" rel=\"noopener noreferrer\">skipped</a>");
/// }
///
/// This function is only applied to relative URLs.
/// To filter all of the URLs,
/// use the not-yet-implemented Content Security Policy.
#[non_exhaustive]
pub enum UrlRelative<'a> {
/// Relative URLs will be completely stripped from the document.
Deny,
/// Relative URLs will be passed through unchanged.
PassThrough,
/// Relative URLs will be changed into absolute URLs, based on this base URL.
RewriteWithBase(Url),
/// Force absolute and relative paths into a particular directory.
///
/// Since the resolver does not affect fully-qualified URLs, it doesn't
/// prevent users from linking wherever they want. This feature only
/// serves to make content more portable.
///
/// # Examples
///
/// <table>
/// <thead>
/// <tr>
/// <th>root</th>
/// <th>path</th>
/// <th>url</th>
/// <th>result</th>
/// </tr>
/// </thead>
/// <tbody>
/// <tr>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/</td>
/// <td>README.md</td>
/// <td></td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/README.md</td>
/// </tr><tr>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/</td>
/// <td>README.md</td>
/// <td>/</td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/</td>
/// </tr><tr>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/</td>
/// <td>README.md</td>
/// <td>/CONTRIBUTING.md</td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/CONTRIBUTING.md</td>
/// </tr><tr>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master</td>
/// <td>README.md</td>
/// <td></td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/README.md</td>
/// </tr><tr>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master</td>
/// <td>README.md</td>
/// <td>/</td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/</td>
/// </tr><tr>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master</td>
/// <td>README.md</td>
/// <td>/CONTRIBUTING.md</td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/CONTRIBUTING.md</td>
/// </tr><tr>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/</td>
/// <td></td>
/// <td></td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/</td>
/// </tr><tr>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/</td>
/// <td></td>
/// <td>/</td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/</td>
/// </tr><tr>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/</td>
/// <td></td>
/// <td>/CONTRIBUTING.md</td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/CONTRIBUTING.md</td>
/// </tr><tr>
/// <td>https://github.com/</td>
/// <td>rust-ammonia/ammonia/blob/master/README.md</td>
/// <td></td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/README.md</td>
/// </tr><tr>
/// <td>https://github.com/</td>
/// <td>rust-ammonia/ammonia/blob/master/README.md</td>
/// <td>/</td>
/// <td>https://github.com/</td>
/// </tr><tr>
/// <td>https://github.com/</td>
/// <td>rust-ammonia/ammonia/blob/master/README.md</td>
/// <td>CONTRIBUTING.md</td>
/// <td>https://github.com/rust-ammonia/ammonia/blob/master/CONTRIBUTING.md</td>
/// </tr><tr>
/// <td>https://github.com/</td>
/// <td>rust-ammonia/ammonia/blob/master/README.md</td>
/// <td>/CONTRIBUTING.md</td>
/// <td>https://github.com/CONTRIBUTING.md</td>
/// </tr>
/// </tbody>
/// </table>
RewriteWithRoot {
/// The URL that is treated as the root by the resolver.
root: Url,
/// The "current path" used to resolve relative paths.
path: String,
},
/// Rewrite URLs with a custom function.
Custom(Box<dyn UrlRelativeEvaluate<'a>>),
}
impl<'a> UrlRelative<'a> {
fn evaluate(&self, url: &str) -> Option<tendril::StrTendril> {
match self {
UrlRelative::RewriteWithBase(ref url_base) => url_base
.join(url)
.ok()
.and_then(|x| StrTendril::from_str(x.as_str()).ok()),
UrlRelative::RewriteWithRoot { ref root, ref path } => {
(match url.as_bytes() {
// Scheme-relative URL
[b'/', b'/', ..] => root.join(url),
// Path-absolute URL
b"/" => root.join("."),
[b'/', ..] => root.join(&url[1..]),
// Path-relative URL
_ => root.join(path).and_then(|r| r.join(url)),
})
.ok()
.and_then(|x| StrTendril::from_str(x.as_str()).ok())
}
UrlRelative::Custom(ref evaluate) => evaluate
.evaluate(url)
.as_ref()
.map(Cow::as_ref)
.map(StrTendril::from_str)
.and_then(Result::ok),
UrlRelative::PassThrough => StrTendril::from_str(url).ok(),
UrlRelative::Deny => None,
}
}
}
impl<'a> fmt::Debug for UrlRelative<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
UrlRelative::Deny => write!(f, "UrlRelative::Deny"),
UrlRelative::PassThrough => write!(f, "UrlRelative::PassThrough"),
UrlRelative::RewriteWithBase(ref base) => {
write!(f, "UrlRelative::RewriteWithBase({})", base)
}
UrlRelative::RewriteWithRoot { ref root, ref path } => {
write!(
f,
"UrlRelative::RewriteWithRoot {{ root: {root}, path: {path} }}"
)
}
UrlRelative::Custom(_) => write!(f, "UrlRelative::Custom"),
}
}
}
/// Types that implement this trait can be used to convert a relative URL into an absolute URL.
///
/// This evaluator is only called when the URL is relative; absolute URLs are not evaluated.
///
/// See [`url_relative`][url_relative] for more details.
///
/// [url_relative]: struct.Builder.html#method.url_relative
pub trait UrlRelativeEvaluate<'a>: Send + Sync + 'a {
/// Return `None` to remove the attribute. Return `Some(str)` to replace it with a new string.
fn evaluate<'url>(&self, _: &'url str) -> Option<Cow<'url, str>>;
}
impl<'a, T> UrlRelativeEvaluate<'a> for T
where
T: Fn(&str) -> Option<Cow<'_, str>> + Send + Sync + 'a,
{
fn evaluate<'url>(&self, url: &'url str) -> Option<Cow<'url, str>> {
self(url)
}
}
impl fmt::Debug for dyn AttributeFilter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AttributeFilter")
}
}
/// Types that implement this trait can be used to remove or rewrite arbitrary attributes.
///
/// See [`attribute_filter`][attribute_filter] for more details.
///
/// [attribute_filter]: struct.Builder.html#method.attribute_filter
pub trait AttributeFilter: Send + Sync {
/// Return `None` to remove the attribute. Return `Some(str)` to replace it with a new string.
fn filter<'a>(&self, _: &str, _: &str, _: &'a str) -> Option<Cow<'a, str>>;
}
impl<T> AttributeFilter for T
where
T: for<'a> Fn(&str, &str, &'a str) -> Option<Cow<'a, str>> + Send + Sync + 'static,
{
fn filter<'a>(&self, element: &str, attribute: &str, value: &'a str) -> Option<Cow<'a, str>> {
self(element, attribute, value)
}
}
/// A sanitized HTML document.
///
/// The `Document` type is an opaque struct representing an HTML fragment that was sanitized by
/// `ammonia`. It can be converted to a [`String`] or written to a [`Write`] instance. This allows
/// users to avoid buffering the serialized representation to a [`String`] when desired.
///
/// This type is opaque to insulate the caller from breaking changes in the `html5ever` interface.
///
/// Note that this type wraps an `html5ever` DOM tree. `ammonia` does not support streaming, so
/// the complete fragment needs to be stored in memory during processing.
///
/// [`String`]: https://doc.rust-lang.org/nightly/std/string/struct.String.html
/// [`Write`]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html
///
/// # Examples
///
/// use ammonia::Builder;
///
/// let input = "<!-- comments will be stripped -->This is an Ammonia example.";
/// let output = "This is an Ammonia example.";
///
/// let document = Builder::new()
/// .clean(input);
/// assert_eq!(document.to_string(), output);
pub struct Document(RcDom);
impl Document {
/// Serializes a `Document` instance to a writer.
///
/// This method writes the sanitized HTML to a [`Write`] instance, avoiding a buffering step.
///
/// To avoid consuming the writer, a mutable reference can be passed, like in the example below.
///
/// Note that the in-memory representation of `Document` is larger than the serialized
/// `String`.
///
/// [`Write`]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html
///
/// # Examples
///
/// use ammonia::Builder;
///
/// let input = "Some <style></style>HTML here";
/// let expected = b"Some HTML here";
///
/// let document = Builder::new()
/// .clean(input);
///
/// let mut sanitized = Vec::new();
/// document.write_to(&mut sanitized)
/// .expect("Writing to a string should not fail (except on OOM)");
/// assert_eq!(sanitized, expected);
pub fn write_to<W>(&self, writer: W) -> io::Result<()>
where
W: io::Write,
{
let opts = Self::serialize_opts();
let inner: SerializableHandle = self.0.document.children.borrow()[0].clone().into();
serialize(writer, &inner, opts)
}
/// Exposes the `Document` instance as an [`rcdom::Handle`].
///
/// This method returns the inner object backing the `Document` instance. This allows
/// making further changes to the DOM without introducing redundant serialization and
/// parsing.
///
/// Note that this method should be considered unstable and sits outside of the semver
/// stability guarantees. It may change, break, or go away at any time, either because
/// of `html5ever` changes or `ammonia` implementation changes.
///
/// For this method to be accessible, a `cfg` flag is required. The easiest way is to
/// use the `RUSTFLAGS` environment variable:
///
/// ```text
/// RUSTFLAGS='--cfg ammonia_unstable' cargo build
/// ```
///
/// on Unix-like platforms, or
///
/// ```text
/// set RUSTFLAGS=--cfg ammonia_unstable
/// cargo build
/// ```
///
/// on Windows.
///
/// This requirement also applies to crates that transitively depend on crates that use
/// this flag.
///
/// # Examples
///
/// use ammonia::Builder;
/// use maplit::hashset;
/// use html5ever::serialize::{serialize, SerializeOpts};
///
/// # use std::error::Error;
/// # fn do_main() -> Result<(), Box<dyn Error>> {
/// let input = "<a>one link</a> and <a>one more</a>";
/// let expected = "<a>one more</a> and <a>one link</a>";
///
/// let document = Builder::new()
/// .link_rel(None)
/// .clean(input);
///
/// let mut node = document.to_dom_node();
/// node.children.borrow_mut().reverse();
///
/// let mut buf = Vec::new();
/// serialize(&mut buf, &node, SerializeOpts::default())?;
/// let output = String::from_utf8(buf)?;
///
/// assert_eq!(output, expected);
/// # Ok(())
/// # }
/// # fn main() { do_main().unwrap() }
#[cfg(ammonia_unstable)]
pub fn to_dom_node(&self) -> Handle {
self.0.document.children.borrow()[0].clone()
}
fn serialize_opts() -> SerializeOpts {
SerializeOpts::default()
}
}
impl Clone for Document {
fn clone(&self) -> Self {
let parser = Builder::make_parser();
let dom = parser.one(&self.to_string()[..]);
Document(dom)
}
}
/// Convert a `Document` to stringified HTML.
///
/// Since [`Document`] implements [`Display`], it can be converted to a [`String`] using the
/// standard [`ToString::to_string`] method. This is the simplest way to use `ammonia`.
///
/// [`Document`]: ammonia::Document
/// [`Display`]: std::fmt::Display
/// [`ToString::to_string`]: std::string::ToString
///
/// # Examples
///
/// use ammonia::Builder;
///
/// let input = "Some <style></style>HTML here";
/// let output = "Some HTML here";
///
/// let document = Builder::new()
/// .clean(input);
/// assert_eq!(document.to_string(), output);
impl Display for Document {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let opts = Self::serialize_opts();
let mut ret_val = Vec::new();
let inner: SerializableHandle = self.0.document.children.borrow()[0].clone().into();
serialize(&mut ret_val, &inner, opts)
.expect("Writing to a string shouldn't fail (expect on OOM)");
String::from_utf8(ret_val)
.expect("html5ever only supports UTF8")
.fmt(f)
}
}
impl fmt::Debug for Document {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Document({})", self)
}
}
impl From<Document> for String {
fn from(document: Document) -> Self {
document.to_string()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn deeply_nested_whitelisted() {
clean(&"<b>".repeat(60_000));
}
#[test]
fn deeply_nested_blacklisted() {
clean(&"<b-b>".repeat(60_000));
}
#[test]
fn deeply_nested_alternating() {
clean(&"<b-b>".repeat(35_000));
}
#[test]
fn included_angles() {
let fragment = "1 < 2";
let result = clean(fragment);
assert_eq!(result, "1 < 2");
}
#[test]
fn remove_script() {
let fragment = "an <script>evil()</script> example";
let result = clean(fragment);
assert_eq!(result, "an example");
}
#[test]
fn ignore_link() {
let fragment = "a <a href=\"http://www.google.com\">good</a> example";
let expected = "a <a href=\"http://www.google.com\" rel=\"noopener noreferrer\">\
good</a> example";
let result = clean(fragment);
assert_eq!(result, expected);
}
#[test]
fn remove_unsafe_link() {
let fragment = "an <a onclick=\"evil()\" href=\"http://www.google.com\">evil</a> example";
let result = clean(fragment);
assert_eq!(
result,
"an <a href=\"http://www.google.com\" rel=\"noopener noreferrer\">evil</a> example"
);
}
#[test]
fn remove_js_link() {
let fragment = "an <a href=\"javascript:evil()\">evil</a> example";
let result = clean(fragment);
assert_eq!(result, "an <a rel=\"noopener noreferrer\">evil</a> example");
}
#[test]
fn tag_rebalance() {
let fragment = "<b>AWESOME!";
let result = clean(fragment);
assert_eq!(result, "<b>AWESOME!</b>");
}
#[test]
fn allow_url_relative() {
let fragment = "<a href=test>Test</a>";
let result = Builder::new()
.url_relative(UrlRelative::PassThrough)
.clean(fragment)
.to_string();
assert_eq!(
result,
"<a href=\"test\" rel=\"noopener noreferrer\">Test</a>"
);
}
#[test]
fn rewrite_url_relative() {
let fragment = "<a href=test>Test</a>";
let result = Builder::new()
.url_relative(UrlRelative::RewriteWithBase(
Url::parse("http://example.com/").unwrap(),
))
.clean(fragment)
.to_string();
assert_eq!(
result,
"<a href=\"http://example.com/test\" rel=\"noopener noreferrer\">Test</a>"
);
}
#[test]
fn rewrite_url_relative_with_invalid_url() {
// Reduced from https://github.com/Bauke/ammonia-crash-test
let fragment = r##"<a href="\\"https://example.com\\"">test</a>"##;
let result = Builder::new()
.url_relative(UrlRelative::RewriteWithBase(
Url::parse("http://example.com/").unwrap(),
))
.clean(fragment)
.to_string();
assert_eq!(result, r##"<a rel="noopener noreferrer">test</a>"##);
}
#[test]
fn attribute_filter_nop() {
let fragment = "<a href=test>Test</a>";
let result = Builder::new()
.attribute_filter(|elem, attr, value| {
assert_eq!("a", elem);
assert!(
matches!(
(attr, value),
("href", "test") | ("rel", "noopener noreferrer")
),
"{}",
value.to_string()
);
Some(value.into())
})
.clean(fragment)
.to_string();
assert_eq!(
result,
"<a href=\"test\" rel=\"noopener noreferrer\">Test</a>"
);
}
#[test]
fn attribute_filter_drop() {
let fragment = "Test<img alt=test src=imgtest>";
let result = Builder::new()
.attribute_filter(|elem, attr, value| {
assert_eq!("img", elem);
match (attr, value) {
("src", "imgtest") => None,
("alt", "test") => Some(value.into()),
_ => panic!("unexpected"),
}
})
.clean(fragment)
.to_string();
assert_eq!(result, r#"Test<img alt="test">"#);
}
#[test]
fn url_filter_absolute() {
let fragment = "Test<img alt=test src=imgtest>";
let result = Builder::new()
.attribute_filter(|elem, attr, value| {
assert_eq!("img", elem);
match (attr, value) {
("src", "imgtest") => {
Some(format!("https://example.com/images/{}", value).into())
}
("alt", "test") => None,
_ => panic!("unexpected"),
}
})
.url_relative(UrlRelative::RewriteWithBase(
Url::parse("http://wrong.invalid/").unwrap(),
))
.clean(fragment)
.to_string();
assert_eq!(
result,
r#"Test<img src="https://example.com/images/imgtest">"#
);
}
#[test]
fn url_filter_relative() {
let fragment = "Test<img alt=test src=imgtest>";
let result = Builder::new()
.attribute_filter(|elem, attr, value| {
assert_eq!("img", elem);
match (attr, value) {
("src", "imgtest") => Some("rewrite".into()),
("alt", "test") => Some("altalt".into()),
_ => panic!("unexpected"),
}
})
.url_relative(UrlRelative::RewriteWithBase(
Url::parse("https://example.com/base/#").unwrap(),
))
.clean(fragment)
.to_string();
assert_eq!(
result,
r#"Test<img alt="altalt" src="https://example.com/base/rewrite">"#
);
}
#[test]
fn rewrite_url_relative_no_rel() {
let fragment = "<a href=test>Test</a>";
let result = Builder::new()
.url_relative(UrlRelative::RewriteWithBase(
Url::parse("http://example.com/").unwrap(),
))
.link_rel(None)
.clean(fragment)
.to_string();
assert_eq!(result, "<a href=\"http://example.com/test\">Test</a>");
}
#[test]
fn deny_url_relative() {
let fragment = "<a href=test>Test</a>";
let result = Builder::new()
.url_relative(UrlRelative::Deny)
.clean(fragment)
.to_string();
assert_eq!(result, "<a rel=\"noopener noreferrer\">Test</a>");
}
#[test]
fn replace_rel() {
let fragment = "<a href=test rel=\"garbage\">Test</a>";
let result = Builder::new()
.url_relative(UrlRelative::PassThrough)
.clean(fragment)
.to_string();
assert_eq!(
result,
"<a href=\"test\" rel=\"noopener noreferrer\">Test</a>"
);
}
#[test]
fn consider_rel_still_banned() {
let fragment = "<a href=test rel=\"garbage\">Test</a>";
let result = Builder::new()
.url_relative(UrlRelative::PassThrough)
.link_rel(None)
.clean(fragment)
.to_string();
assert_eq!(result, "<a href=\"test\">Test</a>");
}
#[test]
fn object_data() {
let fragment = "<span data=\"javascript:evil()\">Test</span>\
<object data=\"javascript:evil()\"></object>M";
let expected = r#"<span data="javascript:evil()">Test</span><object></object>M"#;
let result = Builder::new()
.tags(hashset!["span", "object"])
.generic_attributes(hashset!["data"])
.clean(fragment)
.to_string();
assert_eq!(result, expected);
}
#[test]
fn remove_attributes() {
let fragment = "<table border=\"1\"><tr></tr></table>";
let result = Builder::new().clean(fragment);
assert_eq!(
result.to_string(),
"<table><tbody><tr></tr></tbody></table>"
);
}
#[test]
fn quotes_in_attrs() {
let fragment = "<b title='\"'>contents</b>";
let result = clean(fragment);
assert_eq!(result, "<b title=\""\">contents</b>");
}
#[test]
#[should_panic]
fn panic_if_rel_is_allowed_and_replaced_generic() {
Builder::new()
.link_rel(Some("noopener noreferrer"))
.generic_attributes(hashset!["rel"])
.clean("something");
}
#[test]
#[should_panic]
fn panic_if_rel_is_allowed_and_replaced_a() {
Builder::new()
.link_rel(Some("noopener noreferrer"))
.tag_attributes(hashmap![
"a" => hashset!["rel"],
])
.clean("something");
}
#[test]
fn no_panic_if_rel_is_allowed_and_replaced_span() {
Builder::new()
.link_rel(Some("noopener noreferrer"))
.tag_attributes(hashmap![
"span" => hashset!["rel"],
])
.clean("<span rel=\"what\">s</span>");
}
#[test]
fn no_panic_if_rel_is_allowed_and_not_replaced_generic() {
Builder::new()
.link_rel(None)
.generic_attributes(hashset!["rel"])
.clean("<a rel=\"what\">s</a>");
}
#[test]
fn no_panic_if_rel_is_allowed_and_not_replaced_a() {
Builder::new()
.link_rel(None)
.tag_attributes(hashmap![
"a" => hashset!["rel"],
])
.clean("<a rel=\"what\">s</a>");
}
#[test]
fn dont_close_void_elements() {
let fragment = "<br>";
let result = clean(fragment);
assert_eq!(result.to_string(), "<br>");
}
#[should_panic]
#[test]
fn panic_on_allowed_classes_tag_attributes() {
let fragment = "<p class=\"foo bar\"><a class=\"baz bleh\">Hey</a></p>";
Builder::new()
.link_rel(None)
.tag_attributes(hashmap![
"p" => hashset!["class"],
"a" => hashset!["class"],
])
.allowed_classes(hashmap![
"p" => hashset!["foo", "bar"],
"a" => hashset!["baz"],
])
.clean(fragment);
}
#[should_panic]
#[test]
fn panic_on_allowed_classes_generic_attributes() {
let fragment = "<p class=\"foo bar\"><a class=\"baz bleh\">Hey</a></p>";
Builder::new()
.link_rel(None)
.generic_attributes(hashset!["class", "href", "some-foo"])
.allowed_classes(hashmap![
"p" => hashset!["foo", "bar"],
"a" => hashset!["baz"],
])
.clean(fragment);
}
#[test]
fn remove_non_allowed_classes() {
let fragment = "<p class=\"foo bar\"><a class=\"baz bleh\">Hey</a></p>";
let result = Builder::new()
.link_rel(None)
.allowed_classes(hashmap![
"p" => hashset!["foo", "bar"],
"a" => hashset!["baz"],
])
.clean(fragment);
assert_eq!(
result.to_string(),
"<p class=\"foo bar\"><a class=\"baz\">Hey</a></p>"
);
}
#[test]
fn remove_non_allowed_classes_with_tag_class() {
let fragment = "<p class=\"foo bar\"><a class=\"baz bleh\">Hey</a></p>";
let result = Builder::new()
.link_rel(None)
.tag_attributes(hashmap![
"div" => hashset!["class"],
])
.allowed_classes(hashmap![
"p" => hashset!["foo", "bar"],
"a" => hashset!["baz"],
])
.clean(fragment);
assert_eq!(
result.to_string(),
"<p class=\"foo bar\"><a class=\"baz\">Hey</a></p>"
);
}
#[test]
fn allowed_classes_ascii_whitespace() {
// According to https://infra.spec.whatwg.org/#ascii-whitespace,
// TAB (\t), LF (\n), FF (\x0C), CR (\x0D) and SPACE (\x20) are
// considered to be ASCII whitespace. Unicode whitespace characters
// and VT (\x0B) aren't ASCII whitespace.
let fragment = "<p class=\"a\tb\nc\x0Cd\re f\x0B g\u{2000}\">";
let result = Builder::new()
.allowed_classes(hashmap![
"p" => hashset!["a", "b", "c", "d", "e", "f", "g"],
])
.clean(fragment);
assert_eq!(result.to_string(), r#"<p class="a b c d e"></p>"#);
}
#[test]
fn remove_non_allowed_attributes_with_tag_attribute_values() {
let fragment = "<p data-label=\"baz\" name=\"foo\"></p>";
let result = Builder::new()
.tag_attribute_values(hashmap![
"p" => hashmap![
"data-label" => hashset!["bar"],
],
])
.tag_attributes(hashmap![
"p" => hashset!["name"],
])
.clean(fragment);
assert_eq!(result.to_string(), "<p name=\"foo\"></p>",);
}
#[test]
fn keep_allowed_attributes_with_tag_attribute_values() {
let fragment = "<p data-label=\"bar\" name=\"foo\"></p>";
let result = Builder::new()
.tag_attribute_values(hashmap![
"p" => hashmap![
"data-label" => hashset!["bar"],
],
])
.tag_attributes(hashmap![
"p" => hashset!["name"],
])
.clean(fragment);
assert_eq!(
result.to_string(),
"<p data-label=\"bar\" name=\"foo\"></p>",
);
}
#[test]
fn tag_attribute_values_case_insensitive() {
let fragment = "<input type=\"CHECKBOX\" name=\"foo\">";
let result = Builder::new()
.tags(hashset!["input"])
.tag_attribute_values(hashmap![
"input" => hashmap![
"type" => hashset!["checkbox"],
],
])
.tag_attributes(hashmap![
"input" => hashset!["name"],
])
.clean(fragment);
assert_eq!(result.to_string(), "<input type=\"CHECKBOX\" name=\"foo\">",);
}
#[test]
fn set_tag_attribute_values() {
let fragment = "<a href=\"https://example.com/\">Link</a>";
let result = Builder::new()
.link_rel(None)
.add_tag_attributes("a", &["target"])
.set_tag_attribute_value("a", "target", "_blank")
.clean(fragment);
assert_eq!(
result.to_string(),
"<a href=\"https://example.com/\" target=\"_blank\">Link</a>",
);
}
#[test]
fn update_existing_set_tag_attribute_values() {
let fragment = "<a target=\"bad\" href=\"https://example.com/\">Link</a>";
let result = Builder::new()
.link_rel(None)
.add_tag_attributes("a", &["target"])
.set_tag_attribute_value("a", "target", "_blank")
.clean(fragment);
assert_eq!(
result.to_string(),
"<a target=\"_blank\" href=\"https://example.com/\">Link</a>",
);
}
#[test]
fn unwhitelisted_set_tag_attribute_values() {
let fragment = "<span>hi</span><my-elem>";
let result = Builder::new()
.set_tag_attribute_value("my-elem", "my-attr", "val")
.clean(fragment);
assert_eq!(result.to_string(), "<span>hi</span>",);
}
#[test]
fn remove_entity_link() {
let fragment = "<a href=\"javascript:a\
lert('XSS')\">Click me!</a>";
let result = clean(fragment);
assert_eq!(
result.to_string(),
"<a rel=\"noopener noreferrer\">Click me!</a>"
);
}
#[test]
fn remove_relative_url_evaluate() {
fn is_absolute_path(url: &str) -> bool {
let u = url.as_bytes();
// `//a/b/c` is "protocol-relative", meaning "a" is a hostname
// `/a/b/c` is an absolute path, and what we want to do stuff to.
u.first() == Some(&b'/') && u.get(1) != Some(&b'/')
}
fn is_banned(url: &str) -> bool {
let u = url.as_bytes();
u.first() == Some(&b'b') && u.get(1) == Some(&b'a')
}
fn evaluate(url: &str) -> Option<Cow<'_, str>> {
if is_absolute_path(url) {
Some(Cow::Owned(String::from("/root") + url))
} else if is_banned(url) {
None
} else {
Some(Cow::Borrowed(url))
}
}
let a = Builder::new()
.url_relative(UrlRelative::Custom(Box::new(evaluate)))
.clean("<a href=banned>banned</a><a href=/test/path>fixed</a><a href=path>passed</a><a href=http://google.com/>skipped</a>")
.to_string();
assert_eq!(a, "<a rel=\"noopener noreferrer\">banned</a><a href=\"/root/test/path\" rel=\"noopener noreferrer\">fixed</a><a href=\"path\" rel=\"noopener noreferrer\">passed</a><a href=\"http://google.com/\" rel=\"noopener noreferrer\">skipped</a>");
}
#[test]
fn remove_relative_url_evaluate_b() {
fn is_absolute_path(url: &str) -> bool {
let u = url.as_bytes();
// `//a/b/c` is "protocol-relative", meaning "a" is a hostname
// `/a/b/c` is an absolute path, and what we want to do stuff to.
u.first() == Some(&b'/') && u.get(1) != Some(&b'/')
}
fn is_banned(url: &str) -> bool {
let u = url.as_bytes();
u.first() == Some(&b'b') && u.get(1) == Some(&b'a')
}
fn evaluate(url: &str) -> Option<Cow<'_, str>> {
if is_absolute_path(url) {
Some(Cow::Owned(String::from("/root") + url))
} else if is_banned(url) {
None
} else {
Some(Cow::Borrowed(url))
}
}
let a = Builder::new()
.url_relative(UrlRelative::Custom(Box::new(evaluate)))
.clean("<a href=banned>banned</a><a href=banned title=test>banned</a><a title=test href=banned>banned</a>")
.to_string();
assert_eq!(a, "<a rel=\"noopener noreferrer\">banned</a><a rel=\"noopener noreferrer\" title=\"test\">banned</a><a title=\"test\" rel=\"noopener noreferrer\">banned</a>");
}
#[test]
fn remove_relative_url_evaluate_c() {
// Don't run on absolute URLs.
fn evaluate(_: &str) -> Option<Cow<'_, str>> {
return Some(Cow::Owned(String::from("invalid")));
}
let a = Builder::new()
.url_relative(UrlRelative::Custom(Box::new(evaluate)))
.clean("<a href=\"https://www.google.com/\">google</a>")
.to_string();
assert_eq!(
a,
"<a href=\"https://www.google.com/\" rel=\"noopener noreferrer\">google</a>"
);
}
#[test]
fn clean_children_of_bad_element() {
let fragment = "<bad><evil>a</evil>b</bad>";
let result = Builder::new().clean(fragment);
assert_eq!(result.to_string(), "ab");
}
#[test]
fn reader_input() {
let fragment = b"an <script>evil()</script> example";
let result = Builder::new().clean_from_reader(&fragment[..]);
assert!(result.is_ok());
assert_eq!(result.unwrap().to_string(), "an example");
}
#[test]
fn reader_non_utf8() {
let fragment = b"non-utf8 \xF0\x90\x80string";
let result = Builder::new().clean_from_reader(&fragment[..]);
assert!(result.is_ok());
assert_eq!(result.unwrap().to_string(), "non-utf8 \u{fffd}string");
}
#[test]
fn display_impl() {
let fragment = r#"a <a>link</a>"#;
let result = Builder::new().link_rel(None).clean(fragment);
assert_eq!(format!("{}", result), "a <a>link</a>");
}
#[test]
fn debug_impl() {
let fragment = r#"a <a>link</a>"#;
let result = Builder::new().link_rel(None).clean(fragment);
assert_eq!(format!("{:?}", result), "Document(a <a>link</a>)");
}
#[cfg(ammonia_unstable)]
#[test]
fn to_dom_node() {
let fragment = r#"a <a>link</a>"#;
let result = Builder::new().link_rel(None).clean(fragment);
let _node = result.to_dom_node();
}
#[test]
fn string_from_document() {
let fragment = r#"a <a>link"#;
let result = String::from(Builder::new().link_rel(None).clean(fragment));
assert_eq!(format!("{}", result), "a <a>link</a>");
}
fn require_sync<T: Sync>(_: T) {}
fn require_send<T: Send>(_: T) {}
#[test]
fn require_sync_and_send() {
require_sync(Builder::new());
require_send(Builder::new());
}
#[test]
fn id_prefixed() {
let fragment = "<a id=\"hello\"></a><b id=\"hello\"></a>";
let result = String::from(
Builder::new()
.tag_attributes(hashmap![
"a" => hashset!["id"],
])
.id_prefix(Some("prefix-"))
.clean(fragment),
);
assert_eq!(
result.to_string(),
"<a id=\"prefix-hello\" rel=\"noopener noreferrer\"></a><b></b>"
);
}
#[test]
fn id_already_prefixed() {
let fragment = "<a id=\"prefix-hello\"></a>";
let result = String::from(
Builder::new()
.tag_attributes(hashmap![
"a" => hashset!["id"],
])
.id_prefix(Some("prefix-"))
.clean(fragment),
);
assert_eq!(
result.to_string(),
"<a id=\"prefix-hello\" rel=\"noopener noreferrer\"></a>"
);
}
#[test]
fn clean_content_tags() {
let fragment = "<script type=\"text/javascript\"><a>Hello!</a></script>";
let result = String::from(
Builder::new()
.clean_content_tags(hashset!["script"])
.clean(fragment),
);
assert_eq!(result.to_string(), "");
}
#[test]
fn only_clean_content_tags() {
let fragment = "<em>This is</em><script><a>Hello!</a></script><p>still here!</p>";
let result = String::from(
Builder::new()
.clean_content_tags(hashset!["script"])
.clean(fragment),
);
assert_eq!(result.to_string(), "<em>This is</em><p>still here!</p>");
}
#[test]
fn clean_removed_default_tag() {
let fragment = "<em>This is</em><script><a>Hello!</a></script><p>still here!</p>";
let result = String::from(
Builder::new()
.rm_tags(hashset!["a"])
.rm_tag_attributes("a", hashset!["href", "hreflang"])
.clean_content_tags(hashset!["script"])
.clean(fragment),
);
assert_eq!(result.to_string(), "<em>This is</em><p>still here!</p>");
}
#[test]
#[should_panic]
fn panic_on_clean_content_tag_attribute() {
Builder::new()
.rm_tags(std::iter::once("a"))
.clean_content_tags(hashset!["a"])
.clean("");
}
#[test]
#[should_panic]
fn panic_on_clean_content_tag() {
Builder::new().clean_content_tags(hashset!["a"]).clean("");
}
#[test]
fn clean_text_test() {
assert_eq!(
clean_text("<this> is <a test function"),
"<this> is <a test function"
);
}
#[test]
fn clean_text_spaces_test() {
assert_eq!(clean_text("\x09\x0a\x0c\x20"), "	  ");
}
#[test]
fn ns_svg() {
// https://github.com/cure53/DOMPurify/pull/495
let fragment = r##"<svg><iframe><a title="</iframe><img src onerror=alert(1)>">test"##;
let result = String::from(Builder::new().add_tags(&["iframe"]).clean(fragment));
assert_eq!(result.to_string(), "test");
let fragment = "<svg><iframe>remove me</iframe></svg><iframe>keep me</iframe>";
let result = String::from(Builder::new().add_tags(&["iframe"]).clean(fragment));
assert_eq!(result.to_string(), "remove me<iframe>keep me</iframe>");
let fragment = "<svg><a>remove me</a></svg><iframe>keep me</iframe>";
let result = String::from(Builder::new().add_tags(&["iframe"]).clean(fragment));
assert_eq!(result.to_string(), "remove me<iframe>keep me</iframe>");
let fragment = "<svg><a>keep me</a></svg><iframe>keep me</iframe>";
let result = String::from(Builder::new().add_tags(&["iframe", "svg"]).clean(fragment));
assert_eq!(
result.to_string(),
"<svg><a rel=\"noopener noreferrer\">keep me</a></svg><iframe>keep me</iframe>"
);
}
#[test]
fn ns_mathml() {
// https://github.com/cure53/DOMPurify/pull/495
let fragment = "<mglyph></mglyph>";
let result = String::from(
Builder::new()
.add_tags(&["math", "mtext", "mglyph"])
.clean(fragment),
);
assert_eq!(result.to_string(), "");
let fragment = "<math><mtext><div><mglyph>";
let result = String::from(
Builder::new()
.add_tags(&["math", "mtext", "mglyph"])
.clean(fragment),
);
assert_eq!(
result.to_string(),
"<math><mtext><div></div></mtext></math>"
);
let fragment = "<math><mtext><mglyph>";
let result = String::from(
Builder::new()
.add_tags(&["math", "mtext", "mglyph"])
.clean(fragment),
);
assert_eq!(
result.to_string(),
"<math><mtext><mglyph></mglyph></mtext></math>"
);
}
#[test]
fn generic_attribute_prefixes() {
let prefix_data = ["data-"];
let prefix_code = ["code-"];
let mut b = Builder::new();
let mut hs: HashSet<&'_ str> = HashSet::new();
hs.insert("data-");
assert!(b.generic_attribute_prefixes.is_none());
b.generic_attribute_prefixes(hs);
assert!(b.generic_attribute_prefixes.is_some());
assert_eq!(b.generic_attribute_prefixes.as_ref().unwrap().len(), 1);
b.add_generic_attribute_prefixes(&prefix_data);
assert_eq!(b.generic_attribute_prefixes.as_ref().unwrap().len(), 1);
b.add_generic_attribute_prefixes(&prefix_code);
assert_eq!(b.generic_attribute_prefixes.as_ref().unwrap().len(), 2);
b.rm_generic_attribute_prefixes(&prefix_code);
assert_eq!(b.generic_attribute_prefixes.as_ref().unwrap().len(), 1);
b.rm_generic_attribute_prefixes(&prefix_code);
assert_eq!(b.generic_attribute_prefixes.as_ref().unwrap().len(), 1);
b.rm_generic_attribute_prefixes(&prefix_data);
assert!(b.generic_attribute_prefixes.is_none());
}
#[test]
fn generic_attribute_prefixes_clean() {
let fragment = r#"<a data-1 data-2 code-1 code-2><a>Hello!</a></a>"#;
let result_cleaned = String::from(
Builder::new()
.add_tag_attributes("a", &["data-1"])
.clean(fragment),
);
assert_eq!(
result_cleaned,
r#"<a data-1="" rel="noopener noreferrer"></a><a rel="noopener noreferrer">Hello!</a>"#
);
let result_allowed = String::from(
Builder::new()
.add_tag_attributes("a", &["data-1"])
.add_generic_attribute_prefixes(&["data-"])
.clean(fragment),
);
assert_eq!(
result_allowed,
r#"<a data-1="" data-2="" rel="noopener noreferrer"></a><a rel="noopener noreferrer">Hello!</a>"#
);
let result_allowed = String::from(
Builder::new()
.add_tag_attributes("a", &["data-1", "code-1"])
.add_generic_attribute_prefixes(&["data-", "code-"])
.clean(fragment),
);
assert_eq!(
result_allowed,
r#"<a data-1="" data-2="" code-1="" code-2="" rel="noopener noreferrer"></a><a rel="noopener noreferrer">Hello!</a>"#
);
}
#[test]
fn lesser_than_isnt_html() {
let fragment = "1 < 2";
assert!(!is_html(fragment));
}
#[test]
fn dense_lesser_than_isnt_html() {
let fragment = "1<2";
assert!(!is_html(fragment));
}
#[test]
fn what_about_number_elements() {
let fragment = "foo<2>bar";
assert!(!is_html(fragment));
}
#[test]
fn turbofish_is_html_sadly() {
let fragment = "Vec::<u8>::new()";
assert!(is_html(fragment));
}
#[test]
fn stop_grinning() {
let fragment = "did you really believe me? <g>";
assert!(is_html(fragment));
}
#[test]
fn dont_be_bold() {
let fragment = "<b>";
assert!(is_html(fragment));
}
#[test]
fn rewrite_with_root() {
let tests = [
(
"https://github.com/rust-ammonia/ammonia/blob/master/",
"README.md",
"",
"https://github.com/rust-ammonia/ammonia/blob/master/README.md",
),
(
"https://github.com/rust-ammonia/ammonia/blob/master/",
"README.md",
"/",
"https://github.com/rust-ammonia/ammonia/blob/master/",
),
(
"https://github.com/rust-ammonia/ammonia/blob/master/",
"README.md",
"/CONTRIBUTING.md",
"https://github.com/rust-ammonia/ammonia/blob/master/CONTRIBUTING.md",
),
(
"https://github.com/rust-ammonia/ammonia/blob/master",
"README.md",
"",
"https://github.com/rust-ammonia/ammonia/blob/README.md",
),
(
"https://github.com/rust-ammonia/ammonia/blob/master",
"README.md",
"/",
"https://github.com/rust-ammonia/ammonia/blob/",
),
(
"https://github.com/rust-ammonia/ammonia/blob/master",
"README.md",
"/CONTRIBUTING.md",
"https://github.com/rust-ammonia/ammonia/blob/CONTRIBUTING.md",
),
(
"https://github.com/rust-ammonia/ammonia/blob/master/",
"",
"",
"https://github.com/rust-ammonia/ammonia/blob/master/",
),
(
"https://github.com/rust-ammonia/ammonia/blob/master/",
"",
"/",
"https://github.com/rust-ammonia/ammonia/blob/master/",
),
(
"https://github.com/rust-ammonia/ammonia/blob/master/",
"",
"/CONTRIBUTING.md",
"https://github.com/rust-ammonia/ammonia/blob/master/CONTRIBUTING.md",
),
(
"https://github.com/",
"rust-ammonia/ammonia/blob/master/README.md",
"",
"https://github.com/rust-ammonia/ammonia/blob/master/README.md",
),
(
"https://github.com/",
"rust-ammonia/ammonia/blob/master/README.md",
"/",
"https://github.com/",
),
(
"https://github.com/",
"rust-ammonia/ammonia/blob/master/README.md",
"CONTRIBUTING.md",
"https://github.com/rust-ammonia/ammonia/blob/master/CONTRIBUTING.md",
),
(
"https://github.com/",
"rust-ammonia/ammonia/blob/master/README.md",
"/CONTRIBUTING.md",
"https://github.com/CONTRIBUTING.md",
),
];
for (root, path, url, result) in tests {
let h = format!(r#"<a href="{url}">test</a>"#);
let r = format!(r#"<a href="{result}" rel="noopener noreferrer">test</a>"#);
let a = Builder::new()
.url_relative(UrlRelative::RewriteWithRoot {
root: Url::parse(root).unwrap(),
path: path.to_string(),
})
.clean(&h)
.to_string();
if r != a {
println!(
"failed to check ({root}, {path}, {url}, {result})\n{r} != {a}",
r = r
);
assert_eq!(r, a);
}
}
}
}