From 2a07b98e9cfac77f9e1a4eacf7393e620a5aaf20 Mon Sep 17 00:00:00 2001 From: Jesse Glick Date: Wed, 20 Sep 2023 14:42:26 -0400 Subject: [PATCH] `StringIndexOutOfBoundsException` in `AbstractItem.getUrl` (#8481) --- core/src/main/java/hudson/model/AbstractItem.java | 12 +++++++++--- .../java/jenkins/widgets/BuildListTableTest.java | 4 ++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/hudson/model/AbstractItem.java b/core/src/main/java/hudson/model/AbstractItem.java index 92900e678445..ef9b97319053 100644 --- a/core/src/main/java/hudson/model/AbstractItem.java +++ b/core/src/main/java/hudson/model/AbstractItem.java @@ -555,9 +555,15 @@ public final String getUrl() { View view = (View) last.getObject(); if (view.getOwner().getItemGroup() == getParent() && !view.isDefault()) { // Showing something inside a view, so should use that as the base URL. - String base = last.getUrl().substring(req.getContextPath().length() + 1) + '/'; - LOGGER.log(Level.FINER, "using {0}{1} for {2} from {3}", new Object[] {base, shortUrl, this, uri}); - return base + shortUrl; + String prefix = req.getContextPath() + "/"; + String url = last.getUrl(); + if (url.startsWith(prefix)) { + String base = url.substring(prefix.length()) + '/'; + LOGGER.log(Level.FINER, "using {0}{1} for {2} from {3} given {4}", new Object[] {base, shortUrl, this, uri, prefix}); + return base + shortUrl; + } else { + LOGGER.finer(() -> url + " does not start with " + prefix + " as expected"); + } } else { LOGGER.log(Level.FINER, "irrelevant {0} for {1} from {2}", new Object[] {view.getViewName(), this, uri}); } diff --git a/test/src/test/java/jenkins/widgets/BuildListTableTest.java b/test/src/test/java/jenkins/widgets/BuildListTableTest.java index ce53249e4c7c..e9a1b473e1ef 100644 --- a/test/src/test/java/jenkins/widgets/BuildListTableTest.java +++ b/test/src/test/java/jenkins/widgets/BuildListTableTest.java @@ -26,21 +26,25 @@ import static org.junit.Assert.assertEquals; +import hudson.model.AbstractItem; import hudson.model.FreeStyleProject; import hudson.model.ListView; import java.net.URI; import java.net.URL; +import java.util.logging.Level; import org.htmlunit.html.HtmlAnchor; import org.htmlunit.html.HtmlPage; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.LoggerRule; import org.jvnet.hudson.test.MockFolder; public class BuildListTableTest { @Rule public JenkinsRule r = new JenkinsRule(); + @Rule public LoggerRule logging = new LoggerRule().record(AbstractItem.class, Level.FINER); @Issue("JENKINS-19310") @Test public void linksFromFolders() throws Exception {