Skip to content

Commit f1541bf

Browse files
author
Gabor Garancsi
committed
Allow custom policies for 'style' attribute
1 parent b493617 commit f1541bf

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

src/main/java/org/owasp/html/HtmlPolicyBuilder.java

+11-4
Original file line numberDiff line numberDiff line change
@@ -874,7 +874,7 @@ private HtmlTagSkipType getHtmlTagSkipType(String elementName) {
874874
*/
875875
public final class AttributeBuilder {
876876
private final List<String> attributeNames;
877-
private AttributePolicy policy = AttributePolicy.IDENTITY_ATTRIBUTE_POLICY;
877+
private AttributePolicy policy;
878878

879879
AttributeBuilder(List<? extends String> attributeNames) {
880880
this.attributeNames = ImmutableList.copyOf(attributeNames);
@@ -888,7 +888,11 @@ public final class AttributeBuilder {
888888
* transformation by a previous policy.
889889
*/
890890
public AttributeBuilder matching(AttributePolicy attrPolicy) {
891-
this.policy = AttributePolicy.Util.join(this.policy, attrPolicy);
891+
if (this.policy == null) {
892+
this.policy = attrPolicy;
893+
} else {
894+
this.policy = AttributePolicy.Util.join(this.policy, attrPolicy);
895+
}
892896
return this;
893897
}
894898

@@ -968,8 +972,11 @@ public AttributeBuilder matching(
968972
*/
969973
@SuppressWarnings("synthetic-access")
970974
public HtmlPolicyBuilder globally() {
971-
if (attributeNames.contains("style")) {
972-
allowStyling();
975+
if (attributeNames.contains("style") && policy == null) {
976+
allowStyling();
977+
}
978+
if (this.policy == null) {
979+
this.policy = AttributePolicy.IDENTITY_ATTRIBUTE_POLICY;
973980
}
974981
return HtmlPolicyBuilder.this.allowAttributesGlobally(policy,
975982
attributeNames);

src/test/java/org/owasp/html/SanitizersTest.java

+12
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,18 @@ public static final void testStyleWithOtherAttributesGlobally() {
511511
String want = "<h1 style=\"color:green\" align=\"center\">This is some green centered text</h1>";
512512
assertEquals(want, policyBuilder.sanitize(input));
513513
}
514+
515+
@Test
516+
public static final void testStyleGloballyWithCustomPolicy() {
517+
PolicyFactory policyBuilder = new HtmlPolicyBuilder()
518+
.allowAttributes("style")
519+
.matching(AttributePolicy.IDENTITY_ATTRIBUTE_POLICY).globally()
520+
.allowElements("a", "label", "h1", "h2", "h3", "h4", "h5", "h6")
521+
.toFactory();
522+
String input = "<h1 style=\"color:green; display: grid;\">This is some green centered text</h1>";
523+
String want = "<h1 style=\"color:green; display: grid;\">This is some green centered text</h1>";
524+
assertEquals(want, policyBuilder.sanitize(input));
525+
}
514526

515527
static int fac(int n) {
516528
int ifac = 1;

0 commit comments

Comments
 (0)