]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-17579 Absolute links from user input should open in a new tab
authorZipeng WU <zipeng.wu@sonarsource.com>
Fri, 16 Dec 2022 16:52:16 +0000 (17:52 +0100)
committersonartech <sonartech@sonarsource.com>
Mon, 19 Dec 2022 20:02:46 +0000 (20:02 +0000)
sonar-markdown/src/main/java/org/sonar/markdown/HtmlLinkChannel.java
sonar-markdown/src/main/java/org/sonar/markdown/HtmlUrlChannel.java
sonar-markdown/src/test/java/org/sonar/markdown/MarkdownTest.java

index 66e88e15c5f882fb8c7b32876b14bdeb2fa210c0..00370b2fea3dbe28e8ffd7db004f111f2860378d 100644 (file)
@@ -47,9 +47,10 @@ class HtmlLinkChannel extends RegexChannel<MarkdownOutput> {
     matcher.matches();
     String content = matcher.group(1);
     String url = matcher.group(2);
+    boolean isRelativeUrl = !url.contains("://");
     output.append("<a href=\"");
     output.append(url);
-    output.append("\" target=\"_blank\" rel=\"noopener noreferrer\">");
+    output.append(isRelativeUrl ? "\">" : "\" target=\"_blank\" rel=\"noopener noreferrer\">");
     output.append(content);
     output.append("</a>");
   }
index 50424d4b0c3628e5048c2fd47486cfd284c9442e..1d34ecdcf3cf4cf44740671c292bea859541afd2 100644 (file)
@@ -33,10 +33,12 @@ class HtmlUrlChannel extends RegexChannel<MarkdownOutput> {
 
   @Override
   protected void consume(CharSequence token, MarkdownOutput output) {
+    String url = token.toString();
+    boolean isRelativeUrl = !url.contains("://");
     output.append("<a href=\"");
-    output.append(token);
-    output.append("\" target=\"_blank\" rel=\"noopener noreferrer\">");
-    output.append(token);
+    output.append(url);
+    output.append(isRelativeUrl ? "\">" : "\" target=\"_blank\" rel=\"noopener noreferrer\">");
+    output.append(url);
     output.append("</a>");
   }
 }
index b4838a12d8db2cb9d66d1a89ab80538bce1d1713..461b61230f272ff14d512ab8b652af8f9014bab7 100644 (file)
@@ -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("<a href=\"http://google.com\" target=\"_blank\" rel=\"noopener noreferrer\">http://google.com</a>");
   }
 
+  @Test
+  public void shouldDecorateRelativeUrl() {
+    assertThat(Markdown.convertToHtml("[Google](/google/com)"))
+      .isEqualTo("<a href=\"/google/com\">Google</a>");
+  }
+
   @Test
   public void shouldDecorateDocumentedLink() {
     assertThat(Markdown.convertToHtml("For more details, please [check online documentation](http://docs.sonarqube.org/display/SONAR)."))