From ddfa65fae64663cda51a7b9dd7b45eeebbd10eda Mon Sep 17 00:00:00 2001 From: Ian Hopkins Date: Wed, 2 Oct 2013 11:28:24 -0400 Subject: [PATCH] [FIXED JENKINS-10675] use X-Forwarded-Proto if present --- core/src/main/java/jenkins/model/Jenkins.java | 7 ++++- .../jenkins/model/JenkinsGetRootUrlTest.java | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/jenkins/model/Jenkins.java b/core/src/main/java/jenkins/model/Jenkins.java index cef8d964d5..b20ba525d3 100755 --- a/core/src/main/java/jenkins/model/Jenkins.java +++ b/core/src/main/java/jenkins/model/Jenkins.java @@ -1916,7 +1916,12 @@ public class Jenkins extends AbstractCIBase implements ModifiableTopLevelItemGro public String getRootUrlFromRequest() { StaplerRequest req = Stapler.getCurrentRequest(); StringBuilder buf = new StringBuilder(); - buf.append(req.getScheme()+"://"); + String scheme = req.getScheme(); + String forwardedScheme = req.getHeader("X-Forwarded-Proto"); + if (forwardedScheme != null) { + scheme = forwardedScheme; + } + buf.append(scheme+"://"); buf.append(req.getServerName()); if(req.getServerPort()!=80) buf.append(':').append(req.getServerPort()); diff --git a/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java b/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java index 721ae53f2c..67095ede32 100644 --- a/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java +++ b/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java @@ -102,6 +102,30 @@ public class JenkinsGetRootUrlTest { accessing("http://localhost:8080/"); rootUrlIs("https://ci/jenkins/"); } + + @Bug(10675) + @Test + public void useForwardedProtoWhenPresent() { + configured("https://ci/jenkins/"); + + // Without a forwarded protocol, it should use the request protocol + accessing("http://ci/jenkins/"); + rootUrlFromRequestIs("http://ci/jenkins/"); + + // With a forwarded protocol, it should use the forwarded protocol + accessing("http://ci/jenkins/"); + withHeader("X-Forwarded-Proto", "https"); + rootUrlFromRequestIs("https://ci/jenkins/"); + + accessing("https://ci/jenkins/"); + withHeader("X-Forwarded-Proto", "http"); + rootUrlFromRequestIs("http://ci/jenkins/"); + } + + private void rootUrlFromRequestIs(final String expectedRootUrl) { + + assertThat(jenkins.getRootUrlFromRequest(), equalTo(expectedRootUrl)); + } private void rootUrlIs(final String expectedRootUrl) { @@ -112,6 +136,11 @@ public class JenkinsGetRootUrlTest { when(config.getUrl()).thenReturn(configuredHost); } + + private void withHeader(String name, String value) { + final StaplerRequest req = Stapler.getCurrentRequest(); + when(req.getHeader(name)).thenReturn(value); + } private void accessing(final String realUrl) { -- GitLab