-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathHtmlPolicyBuilderTest.java
More file actions
2280 lines (2086 loc) · 81.5 KB
/
Copy pathHtmlPolicyBuilderTest.java
File metadata and controls
2280 lines (2086 loc) · 81.5 KB
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) 2011, Mike Samuel
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0 OR BSD-2-Clause
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package org.owasp.html;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.owasp.shim.Java8Shim.j8;
@SuppressWarnings({"HttpUrlsUsage", "RedundantSuppression", "UnnecessaryUnicodeEscape"})
class HtmlPolicyBuilderTest {
static final String EXAMPLE = String.join(
"\n",
"<h1 id='foo'>Header</h1>",
"<p onclick='alert(42)'>Paragraph 1<script>evil()</script></p>",
("<p><a href='java\0script:bad()'>Click</a> <a href='foo.html'>me</a>"
+ " <a href='http://outside.org/'>out</a></p>"),
("<p><img src=canary.png alt=local-canary>" +
"<img src='http://canaries.org/canary.png'></p>"),
"<p><b style=font-size:bigger>Fancy</b> with <i><b>soupy</i> tags</b>.",
"<p style='color: expression(foo()); text-align: center;",
" /* direction: ltr */; font-weight: bold'>Stylish Para 1</p>",
"<p style='color: red; font-weight; expression(foo());",
" direction: rtl; font-weight: bold'>Stylish Para 2</p>",
"");
/**
* allowAttributes("style").globally() installs a default schema so that
* styling is sanitized at all, but it must not overrule a schema the caller
* named -- in either order. Unioning silently handed back CssSchema.DEFAULT
* to a caller who asked for something narrower.
*/
@Test
void testGloballyDoesNotWidenAnExplicitStylingSchema() {
CssSchema colorOnly = CssSchema.withProperties(Arrays.asList("color"));
String css = "color:red;font-weight:bold;width:10px";
PolicyFactory globallyFirst = new HtmlPolicyBuilder()
.allowElements("div")
.allowAttributes("style").globally()
.allowStyling(colorOnly)
.toFactory();
assertEquals(
"<div style=\"color:red\">x</div>",
globallyFirst.sanitize("<div style=\"" + css + "\">x</div>"));
PolicyFactory stylingFirst = new HtmlPolicyBuilder()
.allowElements("div")
.allowStyling(colorOnly)
.allowAttributes("style").globally()
.toFactory();
assertEquals(
"<div style=\"color:red\">x</div>",
stylingFirst.sanitize("<div style=\"" + css + "\">x</div>"));
}
/** With no explicit schema, allowing style globally still sanitizes it. */
@Test
void testGloballyStillInstallsADefaultStylingSchema() {
PolicyFactory p = new HtmlPolicyBuilder()
.allowElements("div")
.allowAttributes("style").globally()
.toFactory();
assertEquals(
"<div style=\"color:red\">x</div>",
p.sanitize("<div style=\"color:red;position:fixed\">x</div>"));
}
/** Two explicit schemas still combine, which is the documented behaviour. */
@Test
void testTwoExplicitStylingSchemasStillUnion() {
PolicyFactory p = new HtmlPolicyBuilder()
.allowElements("div")
.allowAttributes("style").onElements("div")
.allowStyling(CssSchema.withProperties(Arrays.asList("color")))
.allowStyling(CssSchema.withProperties(Arrays.asList("font-weight")))
.toFactory();
assertEquals(
"<div style=\"color:red;font-weight:bold\">x</div>",
p.sanitize("<div style=\"color:red;font-weight:bold;width:10px\">x</div>"));
}
@Test
void testTextFilter() {
assertEquals(
String.join(
"\n",
"Header",
"Paragraph 1",
"Click me out",
"",
"Fancy with soupy tags.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()));
}
@Test
void testCannedFormattingTagFilter() {
assertEquals(
String.join(
"\n",
"Header",
"Paragraph 1",
"Click me out",
"",
"<b>Fancy</b> with <i><b>soupy</b></i><b> tags</b>.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()
.allowCommonInlineFormattingElements()));
}
@Test
void testCannedFormattingTagFilterNoItalics() {
assertEquals(
String.join(
"\n",
"Header",
"Paragraph 1",
"Click me out",
"",
"<b>Fancy</b> with <b>soupy</b><b> tags</b>.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()
.allowCommonInlineFormattingElements()
.disallowElements("I")));
}
@Test
void testSimpleTagFilter() {
assertEquals(
String.join(
"\n",
"<h1>Header</h1>",
"Paragraph 1",
"Click me out",
"",
"Fancy with <i>soupy</i> tags.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()
.allowElements("h1", "i")));
}
@Test
void testLinksAllowed() {
assertEquals(
String.join(
"\n",
"Header",
"Paragraph 1",
// We haven't allowed any protocols so only relative URLs are OK.
"Click <a href=\"foo.html\">me</a> out",
"",
"Fancy with soupy tags.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href").onElements("a")));
}
@Test
void testExternalLinksAllowed() {
assertEquals(
String.join(
"\n",
"Header",
"Paragraph 1",
"Click <a href=\"foo.html\">me</a>"
+ " <a href=\"http://outside.org/\">out</a>",
"",
"Fancy with soupy tags.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()
.allowElements("a")
// Allows http.
.allowStandardUrlProtocols()
.allowAttributes("href").onElements("a")));
}
@Test
void testLinksWithNofollow() {
assertEquals(
String.join(
"\n",
"Header",
"Paragraph 1",
"Click <a href=\"foo.html\" rel=\"nofollow\">me</a> out",
"",
"Fancy with soupy tags.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()
.allowElements("a")
// Allows http.
.allowAttributes("href").onElements("a")
.requireRelNofollowOnLinks()));
}
@Test
void testLinksWithNofollowAlreadyPresent() {
assertEquals(
"html <a href=\"/\" rel=\"nofollow\">link</a>",
apply(
new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href").onElements("a")
.requireRelNofollowOnLinks(),
"html <a href='/' rel='nofollow'>link</a>"));
}
@Test
void testImagesAllowed() {
assertEquals(
String.join(
"\n",
"Header",
"Paragraph 1",
"Click me out",
"<img src=\"canary.png\" alt=\"local-canary\" />",
// HTTP img not output because only HTTPS allowed.
"Fancy with soupy tags.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()
.allowElements("img")
.allowAttributes("src", "alt").onElements("img")
.allowUrlProtocols("https")));
}
@Test
void testStyleFiltering() {
assertEquals(
String.join(
"\n",
"<h1>Header</h1>",
"<p>Paragraph 1</p>",
"<p>Click me out</p>",
"<p></p>",
"<p><b>Fancy</b> with <i><b>soupy</b></i><b> tags</b>.",
("</p><p style=\"text-align:center;font-weight:bold\">"
+ "Stylish Para 1</p>"),
("<p style=\"color:red;direction:rtl;font-weight:bold\">"
+ "Stylish Para 2</p>"),
""),
apply(new HtmlPolicyBuilder()
.allowCommonInlineFormattingElements()
.allowCommonBlockElements()
.allowStyling()
.allowStandardUrlProtocols()));
}
@Test
void testSpecificStyleFilterung() {
assertEquals(
String.join(
"\n",
"<h1>Header</h1>",
"<p>Paragraph 1</p>",
"<p>Click me out</p>",
"<p></p>",
"<p><b>Fancy</b> with <i><b>soupy</b></i><b> tags</b>.",
"</p><p style=\"text-align:center\">Stylish Para 1</p>",
"<p style=\"color:red\">Stylish Para 2</p>",
""),
apply(new HtmlPolicyBuilder()
.allowCommonInlineFormattingElements()
.allowCommonBlockElements()
.allowStyling(CssSchema.withProperties(
j8().listOf("color", "text-align", "font-size")))
.allowStandardUrlProtocols()));
}
@Test
void testCustomPropertyStyleFiltering() {
assertEquals(
String.join(
"\n",
"<h1>Header</h1>",
"<p>Paragraph 1</p>",
"<p>Click me out</p>",
"<p></p>",
"<p><b>Fancy</b> with <i><b>soupy</b></i><b> tags</b>.",
"</p><p style=\"text-align:center\">Stylish Para 1</p>",
"<p>Stylish Para 2</p>",
""),
apply(new HtmlPolicyBuilder()
.allowCommonInlineFormattingElements()
.allowCommonBlockElements()
.allowStyling(
CssSchema.withProperties(
j8().mapOfEntries(
j8().mapEntry("text-align",
new CssSchema.Property(0,
j8().setOf("center"),
j8().mapOfEntries())))))
.allowStandardUrlProtocols()));
}
@Test
void testUnionStyleFiltering() {
assertEquals(
String.join(
"\n",
"<h1>Header</h1>",
"<p>Paragraph 1</p>",
"<p>Click me out</p>",
"<p></p>",
"<p><b>Fancy</b> with <i><b>soupy</b></i><b> tags</b>.",
"</p><p style=\"text-align:center\">Stylish Para 1</p>",
"<p style=\"color:red\">Stylish Para 2</p>",
""),
apply(new HtmlPolicyBuilder()
.allowCommonInlineFormattingElements()
.allowCommonBlockElements()
.allowStyling(CssSchema.withProperties(
j8().listOf("color", "text-align")))
.allowStyling( // union allowed style properties
CssSchema.withProperties(j8().listOf("font-size")))
.allowStandardUrlProtocols()));
}
@Test
void testCustomPropertyStyleFilteringDisallowed() {
assertEquals(
String.join(
"\n",
"<h1>Header</h1>",
"<p>Paragraph 1</p>",
"<p>Click me out</p>",
"<p></p>",
"<p><b>Fancy</b> with <i><b>soupy</b></i><b> tags</b>.",
"</p><p>Stylish Para 1</p>",
"<p>Stylish Para 2</p>",
""),
apply(new HtmlPolicyBuilder()
.allowCommonInlineFormattingElements()
.allowCommonBlockElements()
.allowStyling(
CssSchema.withProperties(
j8().mapOfEntries(
j8().mapEntry("text-align",
new CssSchema.Property(0,
j8().setOf("left", "right"),
j8().mapOfEntries())))))
.allowStandardUrlProtocols()));
}
@Test
void testElementTransforming() {
assertEquals(
String.join(
"\n",
"<div class=\"header-h1\">Header</div>",
"<p>Paragraph 1</p>",
"<p>Click me out</p>",
"<p></p>",
"<p>Fancy with soupy tags.",
"</p><p>Stylish Para 1</p>",
"<p>Stylish Para 2</p>",
""),
apply(new HtmlPolicyBuilder()
.allowElements("h1", "p", "div")
.allowElements(
(elementName, attrs) -> {
attrs.add("class");
attrs.add("header-" + elementName);
return "div";
},
"h1")));
}
@Test
void testBodyTransforming() {
assertEquals(
"<div>foo</div>",
apply(
new HtmlPolicyBuilder()
.allowElements(
(elementName, attrs) -> "div",
"body")
.allowElements("div"),
"<body>foo</body>"));
}
@Test
void testAllowUrlProtocols() {
assertEquals(
String.join(
"\n",
"Header",
"Paragraph 1",
"Click me out",
"<img src=\"canary.png\" alt=\"local-canary\" />"
+ "<img src=\"http://canaries.org/canary.png\" />",
"Fancy with soupy tags.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()
.allowElements("img")
.allowAttributes("src", "alt").onElements("img")
.allowUrlProtocols("http")));
}
@Test
void testDisallowUrlProtocols() {
assertEquals(
String.join(
"\n",
"Header",
"Paragraph 1",
"Click me out",
"<img src=\"canary.png\" alt=\"local-canary\" />",
"Fancy with soupy tags.",
"Stylish Para 1",
"Stylish Para 2",
""),
apply(new HtmlPolicyBuilder()
.allowElements("img")
.allowAttributes("src", "alt").onElements("img")
.allowUrlProtocols("http", "https")
.disallowUrlProtocols("http")));
}
@Test
void testPossibleFalloutFromIssue5() {
assertEquals(
"Bad",
apply(
new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href").onElements("a")
.allowUrlProtocols("http"),
"<a href='javascript:alert(1337)//:http'>Bad</a>"));
}
@Test
void testTextInOption() {
assertEquals(
"<select><option>1</option><option>2</option></select>",
apply(
new HtmlPolicyBuilder()
.allowElements("select", "option"),
"<select>\n <option>1</option>\n <option>2</option>\n</select>"));
}
@Test
void testEntities() {
assertEquals(
"(Foo)\u00a0(Bar)\u2666\u2666\u2666\u2666(Baz)"
+ "𔠴𔠴𔠴(Boo)",
apply(
new HtmlPolicyBuilder(),
"(Foo) (Bar)♦♦♦♦(Baz)"
+ "\ud812\udc34𔠴𔠴(Boo)"));
}
@Test
void testImageTag() {
assertEquals(
""
+ "<img src=\"http://example.com/foo.png\" />"
+ "<img src=\"http://example.com/bar.png\" />"
+ "<img />", // OK if this isn't here too.
apply(
new HtmlPolicyBuilder()
.allowElements("img")
.allowElements((elementName, attrs) -> "img", "image")
.allowAttributes("src").onElements("img", "image")
.allowStandardUrlProtocols(),
""
+ "<image src=\"http://example.com/foo.png\" />"
+ "<Image src=\"http://example.com/bar.png\">"
+ "<IMAGE>"));
}
@Test
void testImgSrcsetSyntax() {
assertEquals(
""
+ "<img srcset=\"http://example.com/foo.png\" />\n"
+ "<img srcset=\"http://example.com/foo.png 640w\" />\n"
+ "<img srcset=\"http://example.com/foo.png 48x\" />\n"
+ "<img srcset=\"http://example.com/foo.png .123x\" />\n"
+ "<img srcset=\"http://example.com/foo.png .123e2x\" />\n"
+ "<img srcset=\"http://example.com/foo.png 123.456E-1x\" />\n"
+ "<img srcset=\"http://example.com/foo.png -123x\" />\n"
+ "no float: \n"
+ "no fraction: \n"
+ "no exponent: \n"
+ "<img srcset=\"/big.png 64w , /little.png\" />\n"
+ "<img srcset=\"/big.png 64w , /little.png\" />\n"
+ "<img srcset=\"/big.png 64w , /little.png\" />\n"
+ "<img srcset=\"foo%2cbar.png\" />\n"
+ "empty: \n"
+ "only space: \n"
+ "only comma: \n"
+ "comma at end: <img srcset=\"foo.png\" />\n"
+ "comma stuck to url: \n"
+ "commas inside: <img srcset=\"foo.png%2c%2cbar.png\" />\n"
+ "double commas 1: \n"
+ "double commas 2: \n"
+ "bad url: <img srcset=\"foo.png 1w\" />\n",
apply(
new HtmlPolicyBuilder()
.allowElements("img")
.allowAttributes("srcset").onElements("img")
.allowStandardUrlProtocols(),
""
+ "<img srcset=\"http://example.com/foo.png\" />\n"
+ "<img srcset=\"http://example.com/foo.png 640w\" />\n"
+ "<img srcset=\"http://example.com/foo.png 48x\" />\n"
+ "<img srcset=\"http://example.com/foo.png .123x\" />\n"
+ "<img srcset=\"http://example.com/foo.png .123e2x\" />\n"
+ "<img srcset=\"http://example.com/foo.png 123.456E-1x\" />\n"
+ "<img srcset=\"http://example.com/foo.png -123x\" />\n"
+ "no float: <img srcset=\"http://example.com/foo.png -x\" />\n"
+ "no fraction: <img srcset=\"http://example.com/foo.png -.e1\" />\n"
+ "no exponent: <img srcset=\"http://example.com/foo.png -1e+x\" />\n"
+ "<img srcset=\"/big.png 64w, /little.png\" />\n"
+ "<img srcset=\" /big.png 64w , /little.png\" />\n"
+ "<img srcset=\"\t\t/big.png 64w\r\n,/little.png\t\t\" />\n"
+ "<img srcset=\"foo,bar.png\" />\n"
+ "empty: <img srcset=\"\" />\n"
+ "only space: <img srcset=\" \" />\n"
+ "only comma: <img srcset=\",\" />\n"
+ "comma at end: <img srcset=\"foo.png ,\" />\n" // ok
+ "comma stuck to url: <img srcset=\"bar.png,\" />\n" // not ok
+ "commas inside: <img srcset=\"foo.png,,bar.png\" />\n" // escaped
+ "double commas 1: <img srcset=\"a ,, b\" />\n" // not ok
+ "double commas 2: <img srcset=\"a , , b\" />\n" // not ok
+ "bad url: <img srcset=\"foo.png 1w, javascript:evil()\" />\n"
));
}
@Test
void testUrlChecksLayer() {
assertEquals(
""
+ "<img src=\"http://example.com/OK.png\" />\n"
+ "\n"
+ "<img srcset=\"http://example.com/bar.png#OK 1w\" />",
apply(
new HtmlPolicyBuilder()
.allowElements("img")
.allowAttributes("src", "srcset")
.matching(Pattern.compile(".*OK.*"))
.onElements("img")
.allowStandardUrlProtocols(),
""
+ "<img src=\"http://example.com/OK.png\" />\n"
+ "<img src=\"http://example.com/\" />\n"
+ "<img srcset=\"http://example.com/bar.png#OK 1w, javascript:alert%28%27OK%27%29\">"
)
);
}
/**
* disallowAttributes rejects every value, and joining a policy onto one that
* already rejects everything cannot widen it, so a matching call after
* disallowAttributes does nothing. Pinned because it reads as though it
* should reject only the matching values.
*/
@Test
void testMatchingAfterDisallowAttributesHasNoEffect() {
String withMatching = apply(
new HtmlPolicyBuilder()
.allowUrlProtocols("http", "https")
.allowElements("img")
.allowAttributes("src").onElements("img")
.disallowAttributes("src")
.matching(Pattern.compile(".*example.*")).onElements("img"),
"<img src=\"http://other.example/a.png\">");
assertEquals("", withMatching, "the non-matching src is dropped too");
}
/**
* The URL protocol guard runs after the policies an author attaches with
* matching, so it vets what they produce: a rewrite cannot hand the output
* a protocol the builder did not allow, while a rewrite to an allowed one
* survives.
*/
@Test
void testUrlProtocolGuardVetsWhatAMatchingPolicyProduces() {
assertEquals(
"x",
apply(
new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href")
.matching((elementName, attributeName, value) ->
"javascript:" + value)
.onElements("a")
.allowUrlProtocols("http"),
"<a href='/x'>x</a>"));
assertEquals(
"<a href=\"http://example.com/x\">x</a>",
apply(
new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href")
.matching((elementName, attributeName, value) ->
"http://example.com" + value)
.onElements("a")
.allowUrlProtocols("http"),
"<a href='/x'>x</a>"));
}
/**
* Issue #454. A matching policy on a URL attribute runs before the
* protocol guard, so it sees the value as written, after entity decoding
* but before the guard trims whitespace and percent-encodes parentheses,
* and before the guard has rejected anything. A pattern that expects the
* normalized form rejects the raw one, which fails closed.
*/
@Test
void testMatchingPoliciesSeeTheUrlAsWrittenBeforeTheProtocolGuard() {
List<String> seen = new ArrayList<>();
AttributePolicy record = (elementName, attributeName, value) -> {
seen.add(value);
return value;
};
String links =
"<a href=\" http://example.com/a(b) \">x</a>"
+ "<a href=\"javascript:alert(1)\">y</a>";
assertEquals(
"<a href=\"http://example.com/a%28b%29\">x</a>y",
apply(
new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href").matching(record).onElements("a")
.allowUrlProtocols("http"),
links));
assertEquals(
Arrays.asList(" http://example.com/a(b) ", "javascript:alert(1)"),
seen);
Pattern normalized = Pattern.compile("http://example\\.com/a%28b%29");
Pattern asWritten = Pattern.compile(" http://example\\.com/a\\(b\\) ");
assertEquals(
"xy",
apply(
new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href").matching(normalized).onElements("a")
.allowUrlProtocols("http"),
links));
assertEquals(
"<a href=\"http://example.com/a%28b%29\">x</a>y",
apply(
new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href").matching(asWritten).onElements("a")
.allowUrlProtocols("http"),
links));
}
/**
* Issue #454. A policy that rewrites one URL into another is handed the
* unvetted value, so a redirector that wraps it produces an allowed URL
* that carries a protocol the builder never allowed. The guard passes
* that, as it should, so the rewriter has to vet the protocol itself,
* which putting a FilterUrlByProtocolAttributePolicy ahead of it does.
*/
@Test
void testARewritingPolicyMustVetTheProtocolItself() {
AttributePolicy redirector = (elementName, attributeName, url) ->
"https://example.com/go?u=" + url;
String links =
"<a href=\"javascript:alert(1)\">x</a>"
+ "<a href=\"https://other.example/p\">y</a>";
assertEquals(
"<a href=\"https://example.com/go?u=javascript:alert%281%29\">x</a>"
+ "<a href=\"https://example.com/go?u=https://other.example/p\">"
+ "y</a>",
apply(
new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href").matching(redirector).onElements("a")
.allowUrlProtocols("https"),
links));
assertEquals(
"x"
+ "<a href=\"https://example.com/go?u=https://other.example/p\">"
+ "y</a>",
apply(
new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href")
.matching(new FilterUrlByProtocolAttributePolicy(
Arrays.asList("https")))
.matching(redirector)
.onElements("a")
.allowUrlProtocols("https"),
links));
}
/**
* Issue #454. The policy given to allowUrlsInStyles runs before the
* protocol guard too, so it is consulted even when no protocol was
* allowed, sees a javascript: URL the guard goes on to drop, and on its
* own admits only relative URLs.
*/
@Test
void testStyleUrlPolicyRunsBeforeTheProtocolGuard() {
List<String> seen = new ArrayList<>();
AttributePolicy record = (elementName, attributeName, value) -> {
seen.add(value);
return value;
};
CssSchema images =
CssSchema.withProperties(Arrays.asList("background-image"));
assertEquals(
"<div>x</div>"
+ "<div style=\"background-image:url('/i.png')\">y</div>",
apply(
new HtmlPolicyBuilder()
.allowElements("div")
.allowAttributes("style").onElements("div")
.allowStyling(images)
.allowUrlsInStyles(record),
"<div style=\"background-image: url(javascript:alert%281%29)\">"
+ "x</div>"
+ "<div style=\"background-image: url(/i.png)\">y</div>"));
assertEquals(
Arrays.asList("javascript:alert%281%29", "/i.png"), seen);
}
/** Rejecting only some values means allowing the rest. */
@Test
void testAnInvertedAllowRejectsOnlyTheMatchingValues() {
HtmlPolicyBuilder b = new HtmlPolicyBuilder()
.allowUrlProtocols("http", "https")
.allowElements("img")
.allowAttributes("src")
.matching((elementName, attributeName, value) ->
value.contains("example") ? null : value)
.onElements("img");
assertEquals(
"<img src=\"http://other.test/a.png\" />",
apply(b, "<img src=\"http://other.test/a.png\">"));
assertEquals(
"", apply(b, "<img src=\"http://other.example/a.png\">"));
}
/**
* The {@link Predicate} overload of {@code matching} keeps the values the
* predicate accepts and drops the rest, just as the {@link Pattern} one
* does.
*/
@Test
void testMatchingPredicateKeepsOnlyAcceptedValues() {
Predicate<String> isNote = value -> value.startsWith("note-");
HtmlPolicyBuilder b = new HtmlPolicyBuilder()
.allowElements("p")
.allowAttributes("class")
.matching(isNote)
.onElements("p");
assertEquals(
"<p class=\"note-aside\">Hi</p>",
apply(b, "<p class=\"note-aside\">Hi</p>"));
assertEquals(
"<p>Hi</p>", apply(b, "<p class=\"warning\">Hi</p>"),
"the attribute goes, the element stays");
}
/**
* That overload takes a {@code Predicate<? super String>}, so a predicate
* written against a supertype fits as well. Only the wildcard makes this
* compile.
*/
@Test
void testMatchingAcceptsAPredicateOverASupertypeOfString() {
Predicate<CharSequence> isNotEmpty = value -> value.length() != 0;
HtmlPolicyBuilder b = new HtmlPolicyBuilder()
.allowElements("p")
.allowAttributes("title")
.matching(isNotEmpty)
.onElements("p");
assertEquals("<p title=\"t\">Hi</p>", apply(b, "<p title=\"t\">Hi</p>"));
assertEquals("<p>Hi</p>", apply(b, "<p title=\"\">Hi</p>"));
}
/**
* The {@code ignoreCase} flag of the value-set overloads picks whether the
* value is lower-cased before it is looked up. Every caller in the suite
* passed {@code true}, so the case-sensitive arm -- the one that compares
* the value as written -- went unexercised.
*/
@Test
void testMatchingComparesValuesAsWrittenUnlessIgnoringCase() {
HtmlPolicyBuilder caseSensitive = new HtmlPolicyBuilder()
.allowElements("p")
.allowAttributes("class")
.matching(false, "Note")
.onElements("p");
assertEquals(
"<p class=\"Note\">Hi</p>",
apply(caseSensitive, "<p class=\"Note\">Hi</p>"));
assertEquals(
"<p>Hi</p>", apply(caseSensitive, "<p class=\"note\">Hi</p>"),
"a value that differs in case is not one of the allowed values");
HtmlPolicyBuilder ignoringCase = new HtmlPolicyBuilder()
.allowElements("p")
.allowAttributes("class")
.matching(true, "note")
.onElements("p");
assertEquals(
"<p class=\"note\">Hi</p>",
apply(ignoringCase, "<p class=\"Note\">Hi</p>"),
"ignoring case keeps the lower-cased value, not the one written");
}
/**
* {@code ignoreCase} lower-cases the value it looks up but not the values it
* looks them up in, so an allowed value that is not already lower-case can
* never be matched and the policy rejects everything. It fails closed, but
* silently: pinned so the asymmetry is visible to anyone changing it.
*/
@Test
void testMatchingIgnoringCaseNeverMatchesAnUpperCaseAllowedValue() {
HtmlPolicyBuilder b = new HtmlPolicyBuilder()
.allowElements("p")
.allowAttributes("class")
.matching(true, "Note")
.onElements("p");
for (String written : new String[] { "Note", "note", "NOTE" }) {
assertEquals(
"<p>Hi</p>", apply(b, "<p class=\"" + written + "\">Hi</p>"),
"nothing matches the allowed value `Note`");
}
}
/**
* The duplicate-attribute scan walks a flat list of alternating names and
* values, so it has to compare names against names. It used to compare
* against values too, which dropped an attribute whose name matched an
* earlier attribute's value.
* <p>
* Reaching that comparison takes three attributes, not two: the scan only
* runs once the attribute's first letter has already been seen on the tag,
* so {@code sizes} is here to put {@code s} in play and send {@code src}
* down the scan path, where it used to collide with {@code alt}'s value.
* Without an attribute in that role the test passes either way.
*/
@Test
void testAttributeNameMatchingAnEarlierValueIsNotADuplicate() {
assertEquals(
"<img sizes=\"100vw\" alt=\"src\""
+ " src=\"http://example.com/a.png\" />",
apply(
new HtmlPolicyBuilder()
.allowElements("img")
.allowAttributes("sizes", "alt", "src").onElements("img")
.allowUrlProtocols("http", "https"),
"<img sizes=\"100vw\" alt=\"src\""
+ " src=\"http://example.com/a.png\">")
);
}
/** Genuine repeats are still dropped, keeping the first. */
@Test
void testRepeatedAttributeNamesStillCollapseToTheFirst() {
assertEquals(
"<img alt=\"first\" />",
apply(
new HtmlPolicyBuilder()
.allowElements("img")
.allowAttributes("alt").onElements("img"),
"<img alt=\"first\" ALT=\"second\" alt=\"third\">")
);
}
@Test
void testDuplicateAttributesDoNotReachElementPolicy() {
final int[] idCount = new int[1];
assertEquals(
// The id that is emitted is the first that passes the attribute
// starts-with-b filter.
// The attribute policy sees 3 id elements, hence id-count=3.
// The element policy sees 2 attributes, one "id" and one "href",
// hence attr-count=2.
"<a href=\"foo\" id=\"bar\" attr-count=\"2\" id-count=\"3\">link</a>",
apply(
new HtmlPolicyBuilder()
.allowElements(
(elementName, attrs) -> {
int nAttrs = attrs.size() / 2;
attrs.add("attr-count");
attrs.add("" + nAttrs);
attrs.add("id-count");
attrs.add("" + idCount[0]);
return elementName;
},
"a")
.allowAttributes("id").matching(
(elementName, attributeName, value) -> {
++idCount[0];
return value.startsWith("b") ? value : null;
})
.onElements("a")
.allowAttributes("href").onElements("a"),
"<a href=\"foo\" id='far' id=\"bar\" href=baz id=boo>link</a>")
);
}
@Test
void testPreprocessors() {
String input =
"<h1 title='foo'>one</h1> <h2>Two!</h2> <h3>three</h3>"
+ " <h4>Four</h4> <h5>5</h5> <h6>seis</h6>";
// We upper-case all text nodes and increment all header elements.
// Since h7 is not white-listed, the incremented version of <h6> is dropped.
// The title attribute value is not upper-cased.
String expected =
"<h2 title=\"foo\">ONE</h2> <h3>TWO!</h3> <h4>THREE</h4>"
+ " <h5>FOUR</h5> <h6>5</h6> SEIS";
assertEquals(
expected,
apply(
new HtmlPolicyBuilder()
.allowElements("h1", "h2", "h3", "h4", "h5", "h6")
.allowAttributes("title").globally()
.withPreprocessor(r -> new HtmlStreamEventReceiverWrapper(r) {
@Override