Skip to content

Commit

Permalink
Fix repeatedly adding rel values (#307)
Browse files Browse the repository at this point in the history
* Don't allow duplicates in rel attribute for links

Signed-off-by: Sven Strickroth <[email protected]>

* Use lower case link rel attribute words

---------

Signed-off-by: Sven Strickroth <[email protected]>
Co-authored-by: Mike Samuel <[email protected]>
  • Loading branch information
csware and mikesamuel authored Feb 2, 2024
1 parent 58fac00 commit 2901ef0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/main/java/org/owasp/html/HtmlPolicyBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -1045,12 +1045,11 @@ public String apply(String elementName, List<String> attrs) {
for (int i = 0; i <= n; ++i) {
if (i == n || Strings.isHtmlSpace(rels.charAt(i))) {
if (left < i) {
if (skip.isEmpty()
|| !skip.contains(
Strings.toLowerCase(rels.substring(left, i)))) {
String rel = rels.substring(left, i);
present.add(rel);
sb.append(rel).append(' ');
final String rel = rels.substring(left, i);
final String lowerCaseRel = Strings.toLowerCase(rel);
if ((skip.isEmpty() || !skip.contains(lowerCaseRel)) && !present.contains(lowerCaseRel)) {
present.add(lowerCaseRel);
sb.append(lowerCaseRel).append(' ');
}
}
left = i + 1;
Expand Down
25 changes: 25 additions & 0 deletions src/test/java/org/owasp/html/HtmlPolicyBuilderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -924,6 +924,31 @@ public final void testRelLinksWhenRelIsPartOfData() {
assertEquals(toSanitize, pf.sanitize(toSanitize));
}

@Test
public static final void testRelLinksWithDuplicateRels() {
PolicyFactory pf = new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href").onElements("a")
.allowAttributes("rel").onElements("a")
.allowAttributes("target").onElements("a")
.allowStandardUrlProtocols()
.toFactory();
assertEquals("<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://google.com\">test</a>", pf.sanitize("<a target=\"_blank\" rel=\"noopener noreferrer noreferrer\" href=\"https://google.com\">test</a>"));
}

@Test
public static final void testRelLinksWithDuplicateRelsRequired() {
PolicyFactory pf = new HtmlPolicyBuilder()
.allowElements("a")
.allowAttributes("href").onElements("a")
.allowAttributes("rel").onElements("a")
.allowAttributes("target").onElements("a")
.allowStandardUrlProtocols()
.requireRelsOnLinks("noreferrer")
.toFactory();
assertEquals("<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://google.com\">test</a>", pf.sanitize("<a target=\"_blank\" rel=\"noopener noreferrer noreferrer\" href=\"https://google.com\">test</a>"));
}

@Test
public static final void testFailFastOnSpaceSeparatedStrings() {
boolean failed;
Expand Down

0 comments on commit 2901ef0

Please sign in to comment.