From cebbb10a17eae9927a120a749a83522c97ccd24a Mon Sep 17 00:00:00 2001 From: Zipeng WU Date: Fri, 16 Dec 2022 17:52:16 +0100 Subject: SONAR-17579 Absolute links from user input should open in a new tab --- .../src/main/java/org/sonar/markdown/HtmlLinkChannel.java | 3 ++- .../src/main/java/org/sonar/markdown/HtmlUrlChannel.java | 8 +++++--- sonar-markdown/src/test/java/org/sonar/markdown/MarkdownTest.java | 8 +++++++- 3 files changed, 14 insertions(+), 5 deletions(-) (limited to 'sonar-markdown') diff --git a/sonar-markdown/src/main/java/org/sonar/markdown/HtmlLinkChannel.java b/sonar-markdown/src/main/java/org/sonar/markdown/HtmlLinkChannel.java index 66e88e15c5f..00370b2fea3 100644 --- a/sonar-markdown/src/main/java/org/sonar/markdown/HtmlLinkChannel.java +++ b/sonar-markdown/src/main/java/org/sonar/markdown/HtmlLinkChannel.java @@ -47,9 +47,10 @@ class HtmlLinkChannel extends RegexChannel { matcher.matches(); String content = matcher.group(1); String url = matcher.group(2); + boolean isRelativeUrl = !url.contains("://"); output.append(""); + output.append(isRelativeUrl ? "\">" : "\" target=\"_blank\" rel=\"noopener noreferrer\">"); output.append(content); output.append(""); } diff --git a/sonar-markdown/src/main/java/org/sonar/markdown/HtmlUrlChannel.java b/sonar-markdown/src/main/java/org/sonar/markdown/HtmlUrlChannel.java index 50424d4b0c3..1d34ecdcf3c 100644 --- a/sonar-markdown/src/main/java/org/sonar/markdown/HtmlUrlChannel.java +++ b/sonar-markdown/src/main/java/org/sonar/markdown/HtmlUrlChannel.java @@ -33,10 +33,12 @@ class HtmlUrlChannel extends RegexChannel { @Override protected void consume(CharSequence token, MarkdownOutput output) { + String url = token.toString(); + boolean isRelativeUrl = !url.contains("://"); output.append(""); - output.append(token); + output.append(url); + output.append(isRelativeUrl ? "\">" : "\" target=\"_blank\" rel=\"noopener noreferrer\">"); + output.append(url); output.append(""); } } diff --git a/sonar-markdown/src/test/java/org/sonar/markdown/MarkdownTest.java b/sonar-markdown/src/test/java/org/sonar/markdown/MarkdownTest.java index b4838a12d8d..461b61230f2 100644 --- a/sonar-markdown/src/test/java/org/sonar/markdown/MarkdownTest.java +++ b/sonar-markdown/src/test/java/org/sonar/markdown/MarkdownTest.java @@ -26,11 +26,17 @@ import static org.assertj.core.api.Assertions.assertThat; public class MarkdownTest { @Test - public void shouldDecorateUrl() { + public void shouldDecorateAbsoluteUrl() { assertThat(Markdown.convertToHtml("http://google.com")) .isEqualTo("http://google.com"); } + @Test + public void shouldDecorateRelativeUrl() { + assertThat(Markdown.convertToHtml("[Google](/google/com)")) + .isEqualTo("Google"); + } + @Test public void shouldDecorateDocumentedLink() { assertThat(Markdown.convertToHtml("For more details, please [check online documentation](http://docs.sonarqube.org/display/SONAR).")) -- cgit v1.2.3