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
// Copyright (C) Michael Howell and others // this library is released under the same terms as Rust itself. #![forbid(unsafe_code)] #![forbid(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" use html5ever::interface::Attribute; use html5ever::rcdom::{Handle, NodeData, RcDom}; use html5ever::serialize::{serialize, SerializeOpts}; use html5ever::tree_builder::{NodeOrText, TreeSink}; use html5ever::{driver as html, local_name, namespace_url, ns, QualName}; use lazy_static::lazy_static; use maplit::{hashmap, hashset}; use matches::matches; use std::borrow::{Borrow, Cow}; use std::cmp::max; use std::collections::{HashMap, HashSet}; use std::fmt; use std::io; use std::iter::IntoIterator as IntoIter; use std::mem::replace; use std::rc::Rc; use std::str::FromStr; use tendril::format_tendril; use tendril::stream::TendrilSink; use tendril::StrTendril; pub use url::Url; pub use url; lazy_static! { static ref AMMONIA: Builder<'static> = Builder::default(); } /// Clean HTML with a conservative set of defaults. /// /// * [tags](struct.Builder.html#defaults) /// * [attributes on specific tags](struct.Builder.html#defaults-1) /// * [attributes on all tags](struct.Builder.html#defaults-2) /// * [url schemes](struct.Builder.html#defaults-3) /// * [relative URLs are passed through, unchanged, by default](struct.Builder.html#defaults-4) /// * [links are marked `noopener noreferrer` by default](struct.Builder.html#defaults-5) /// * [all `class=""` settings are blocked by default](struct.Builder.html#defaults-6) /// * [comments are stripped by default](struct.Builder.html#defaults-7) /// /// [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 maximally strict on purpose, encoding every character that has special meaning to the /// HTML parser. /// /// This function cannot be used to package strings into a `<script>` or `<style>` tag; /// you need a JavaScript or CSS escaper to do that. /// /// 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' => " ", '\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 } /// 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>>>, generic_attributes: HashSet<&'a str>, url_schemes: HashSet<&'a str>, url_relative: UrlRelative, 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>, } impl<'a> Default for Builder<'a> { fn default() -> Self { #[cfg_attr(rustfmt, 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", "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 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, generic_attributes, url_schemes, url_relative: UrlRelative::PassThrough, attribute_filter: None, link_rel: Some("noopener noreferrer"), allowed_classes, strip_comments: true, id_prefix: 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, 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 /// /// No tags have content removed by default. 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_insert_with(|| HashSet::new()) .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_insert_with(HashMap::new) .entry(attribute.borrow()) .or_insert_with(HashSet::new) .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 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) -> &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.clone() } /// 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_insert_with(|| HashSet::new()) .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<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() } /// 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<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<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, _classes) in &self.allowed_classes { 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 url_base = if let UrlRelative::RewriteWithBase(ref base) = self.url_relative { Some(base) } else { None }; let body = { let children = dom.document.children.borrow(); children[0].clone() }; stack.extend( replace(&mut *body.children.borrow_mut(), Vec::new()) .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 = self.clean_child(&mut node); if pass { self.adjust_node_attributes(&mut node, &link_rel, url_base, 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( replace(&mut *node.children.borrow_mut(), Vec::new()) .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(&replace(&mut *node.children.borrow_mut(), Vec::new())[..]); } 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 .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 } } } } /// 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>, url_base: Option<&Url>, id_prefix: Option<&'a str>, ) { if let NodeData::Element { ref name, ref attrs, .. } = child.data { 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" { if !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); } } if let Some(ref base) = url_base { for attr in &mut *attrs.borrow_mut() { if is_url_attr(&*name.local, &*attr.name.local) { let url = base .join(&*attr.value) .expect("invalid URLs should be stripped earlier"); attr.value = format_tendril!("{}", url); } } } else if let UrlRelative::Custom(ref evaluate) = self.url_relative { 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 = evaluate .evaluate(&*attr.value) .as_ref() .map(Cow::as_ref) .map(StrTendril::from_str) .and_then(Result::ok); 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![]; for class in attr.value.split(' ') { 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") } 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. pub enum UrlRelative { /// 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), /// Rewrite URLs with a custom function. Custom(Box<dyn UrlRelativeEvaluate>), // Do not allow the user to exhaustively match on UrlRelative, // because we may add new items to it later. #[doc(hidden)] __NonExhaustive, } impl fmt::Debug for UrlRelative { 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::Custom(_) => write!(f, "UrlRelative::Custom"), UrlRelative::__NonExhaustive => unreachable!(), } } } /// 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: Send + Sync { /// Return `None` to remove the attribute. Return `Some(str)` to replace it with a new string. fn evaluate<'a>(&self, _: &'a str) -> Option<Cow<'a, str>>; } impl<T> UrlRelativeEvaluate for T where T: Fn(&str) -> Option<Cow<'_, str>> + Send + Sync, { fn evaluate<'a>(&self, url: &'a str) -> Option<Cow<'a, 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. Currently, `Document` /// is backed by an [`html5ever::rcdom::Node`] object. /// /// [`String`]: https://doc.rust-lang.org/nightly/std/string/struct.String.html /// [`Write`]: https://doc.rust-lang.org/nightly/std/io/trait.Write.html /// [`html5ever::rcdom::Node`]: ../markup5ever/rcdom/struct.Node.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 `String`. /// /// This method returns a [`String`] with the sanitized HTML. This is the simplest way to use /// `ammonia`. /// /// [`String`]: https://doc.rust-lang.org/nightly/std/string/struct.String.html /// /// # 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); pub fn to_string(&self) -> String { let opts = Self::serialize_opts(); let mut ret_val = Vec::new(); serialize(&mut ret_val, &self.0.document.children.borrow()[0], opts) .expect("Writing to a string shouldn't fail (expect on OOM)"); String::from_utf8(ret_val).expect("html5ever only supports UTF8") } /// 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(); serialize(writer, &self.0.document.children.borrow()[0], opts) } /// Exposes the `Document` instance as an [`html5ever::rcdom::Handle`][h]. /// /// 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: /// /// [h]: ../markup5ever/rcdom/type.Handle.html /// /// ```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<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) } } impl fmt::Display for Document { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_string()) } } impl fmt::Debug for Document { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Document({})", self.to_string()) } } 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 attribute_filter_nop() { let fragment = "<a href=test>Test</a>"; let result = Builder::new() .attribute_filter(|elem, attr, value| { assert_eq!("a", elem); assert!( match (attr, value) { ("href", "test") => true, ("rel", "noopener noreferrer") => true, _ => false, }, 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 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 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.get(0) == Some(&b'/') && u.get(1) != Some(&b'/') } fn is_banned(url: &str) -> bool { let u = url.as_bytes(); u.get(0) == 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.get(0) == Some(&b'/') && u.get(1) != Some(&b'/') } fn is_banned(url: &str) -> bool { let u = url.as_bytes(); u.get(0) == 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" ); } }