Skip to content

Commit

Permalink
Allow custom policies for 'style' attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabor Garancsi committed Oct 29, 2021
1 parent b493617 commit 0310016
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/main/java/org/owasp/html/HtmlPolicyBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -874,7 +874,7 @@ private HtmlTagSkipType getHtmlTagSkipType(String elementName) {
*/
public final class AttributeBuilder {
private final List<String> attributeNames;
private AttributePolicy policy = AttributePolicy.IDENTITY_ATTRIBUTE_POLICY;
private AttributePolicy policy;

AttributeBuilder(List<? extends String> attributeNames) {
this.attributeNames = ImmutableList.copyOf(attributeNames);
Expand All @@ -888,7 +888,11 @@ public final class AttributeBuilder {
* transformation by a previous policy.
*/
public AttributeBuilder matching(AttributePolicy attrPolicy) {
this.policy = AttributePolicy.Util.join(this.policy, attrPolicy);
if (this.policy == null) {
this.policy = attrPolicy;
} else {
this.policy = AttributePolicy.Util.join(this.policy, attrPolicy);
}
return this;
}

Expand Down Expand Up @@ -968,8 +972,11 @@ public AttributeBuilder matching(
*/
@SuppressWarnings("synthetic-access")
public HtmlPolicyBuilder globally() {
if (attributeNames.contains("style")) {
allowStyling();
if (attributeNames.contains("style") && policy == null) {
allowStyling();
}
if (this.policy == null) {
this.policy = AttributePolicy.IDENTITY_ATTRIBUTE_POLICY;
}
return HtmlPolicyBuilder.this.allowAttributesGlobally(policy,
attributeNames);
Expand Down
13 changes: 13 additions & 0 deletions src/test/java/org/owasp/html/SanitizersTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;

import junit.framework.TestCase;

Expand Down Expand Up @@ -511,6 +512,18 @@ public static final void testStyleWithOtherAttributesGlobally() {
String want = "<h1 style=\"color:green\" align=\"center\">This is some green centered text</h1>";
assertEquals(want, policyBuilder.sanitize(input));
}

@Test
public static final void testStyleGloballyWithCustomPolicy() {
PolicyFactory policyBuilder = new HtmlPolicyBuilder()
.allowAttributes("style")
.matching(AttributePolicy.IDENTITY_ATTRIBUTE_POLICY).globally()
.allowElements("a", "label", "h1", "h2", "h3", "h4", "h5", "h6")
.toFactory();
String input = "<h1 style=\"color:green; display: grid;\">This is some green centered text</h1>";
String want = "<h1 style=\"color:green; display: grid;\">This is some green centered text</h1>";
assertEquals(want, policyBuilder.sanitize(input));
}

static int fac(int n) {
int ifac = 1;
Expand Down

0 comments on commit 0310016

Please sign in to comment.