Allow target attribute for anchor tags in html-sanitizer

* Allow target attribute for anchor tags in html-sanitizer

Signed-off-by: Ayke Halder <rr-it@users.noreply.github.com>
Signed-off-by: Alexander Schwartz <aschwart@redhat.com>
Co-authored-by: Alexander Schwartz <aschwart@redhat.com>
This commit is contained in:
Ayke Halder
2025-09-19 11:53:11 +02:00
committed by GitHub
parent 3841fea16d
commit 0635bb68eb
2 changed files with 24 additions and 0 deletions

View File

@@ -62,6 +62,8 @@ public class KeycloakSanitizerPolicy {
private static final Pattern NAME = Pattern.compile("[a-zA-Z0-9\\-_\\$]+");
private static final Pattern TARGET = Pattern.compile("_blank");
private static final Pattern ALIGN = Pattern.compile(
"(?i)center|left|right|justify|char");
@@ -102,6 +104,7 @@ public class KeycloakSanitizerPolicy {
.allowStandardUrlProtocols()
.allowAttributes("nohref").onElements("a")
.allowAttributes("name").matching(NAME).onElements("a")
.allowAttributes("target").matching(TARGET).onElements("a")
.allowAttributes(
"onfocus", "onblur", "onclick", "onmousedown", "onmouseup")
.matching(HISTORY_BACK).onElements("a")

View File

@@ -60,6 +60,27 @@ public class KeycloakSanitizerTest {
assertResult(expectedResult, html);
}
@Test
public void testLinks() throws Exception {
List<String> html = new ArrayList<>();
html.add("<a href=\"https://www.example.org/sub-page\">Link text</a>");
String expectedResult = "<a href=\"https://www.example.org/sub-page\" rel=\"nofollow\">Link text</a>";
assertResult(expectedResult, html);
html.set(0, "<a href=\"https://www.example.org/terms-of-service\" target=\"_blank\">Link text</a>");
expectedResult = "<a href=\"https://www.example.org/terms-of-service\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Link text</a>";
assertResult(expectedResult, html);
html.set(0, "<a href=\"https://www.example.org/sub-page\" target=\"_top\">Link text</a>");
expectedResult = "<a href=\"https://www.example.org/sub-page\" rel=\"nofollow\">Link text</a>";
assertResult(expectedResult, html);
html.set(0, "<a href=\"https://www.example.org/sub-page\" target=\"someframe\">Link text</a>");
expectedResult = "<a href=\"https://www.example.org/sub-page\" rel=\"nofollow\">Link text</a>";
assertResult(expectedResult, html);
}
@Test
public void testUrls() throws Exception {
List<String> html = new ArrayList<>();