-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathlib.rs
3822 lines (3711 loc) · 129 KB
/
lib.rs
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
// 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::new();
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_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 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_insert_with(HashMap::new)
.insert(attribute.borrow(), value.borrow());
self
}
/// Remove existing tag-specific attribute values to be set.
///
/// Does nothing if the attribute is already gone.