You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ScannerWsClientProviderTest.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.scanner.http;
  21. import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
  22. import java.net.URISyntaxException;
  23. import java.net.URL;
  24. import java.nio.charset.StandardCharsets;
  25. import java.nio.file.Path;
  26. import java.nio.file.Paths;
  27. import java.util.Base64;
  28. import java.util.Collections;
  29. import java.util.HashMap;
  30. import java.util.Map;
  31. import java.util.Properties;
  32. import org.junit.jupiter.api.BeforeEach;
  33. import org.junit.jupiter.api.Nested;
  34. import org.junit.jupiter.api.Tag;
  35. import org.junit.jupiter.api.Test;
  36. import org.junit.jupiter.api.TestInfo;
  37. import org.junit.jupiter.api.extension.RegisterExtension;
  38. import org.junit.jupiter.api.io.TempDir;
  39. import org.junitpioneer.jupiter.RestoreSystemProperties;
  40. import org.sonar.api.notifications.AnalysisWarnings;
  41. import org.sonar.api.utils.System2;
  42. import org.sonar.batch.bootstrapper.EnvironmentInformation;
  43. import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
  44. import org.sonar.scanner.bootstrap.ScannerProperties;
  45. import org.sonar.scanner.bootstrap.SonarUserHome;
  46. import org.sonarqube.ws.client.GetRequest;
  47. import org.sonarqube.ws.client.HttpConnector;
  48. import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
  49. import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
  50. import static com.github.tomakehurst.wiremock.client.WireMock.get;
  51. import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
  52. import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
  53. import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
  54. import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
  55. import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;
  56. import static java.util.Objects.requireNonNull;
  57. import static org.assertj.core.api.Assertions.assertThat;
  58. import static org.junit.Assert.assertThrows;
  59. import static org.mockito.Mockito.mock;
  60. import static org.mockito.Mockito.when;
  61. class ScannerWsClientProviderTest {
  62. private static final GlobalAnalysisMode GLOBAL_ANALYSIS_MODE = new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap()));
  63. private static final AnalysisWarnings ANALYSIS_WARNINGS = warning -> {
  64. };
  65. private SonarUserHome sonarUserHome = mock(SonarUserHome.class);
  66. private final Map<String, String> scannerProps = new HashMap<>();
  67. private final ScannerWsClientProvider underTest = new ScannerWsClientProvider();
  68. private final EnvironmentInformation env = new EnvironmentInformation("Maven Plugin", "2.3");
  69. private final System2 system2 = mock(System2.class);
  70. private final Properties systemProps = new Properties();
  71. @BeforeEach
  72. void configureMocks(@TempDir Path sonarUserHomeDir) {
  73. when(system2.properties()).thenReturn(systemProps);
  74. sonarUserHome = new SonarUserHome(sonarUserHomeDir);
  75. }
  76. @Test
  77. void provide_client_with_default_settings() {
  78. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  79. assertThat(client).isNotNull();
  80. assertThat(client.baseUrl()).isEqualTo("http://localhost:9000/");
  81. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  82. assertThat(httpConnector.baseUrl()).isEqualTo("http://localhost:9000/");
  83. assertThat(httpConnector.okHttpClient().proxy()).isNull();
  84. assertThat(httpConnector.okHttpClient().connectTimeoutMillis()).isEqualTo(5_000);
  85. assertThat(httpConnector.okHttpClient().readTimeoutMillis()).isEqualTo(60_000);
  86. }
  87. @Test
  88. void provide_client_with_custom_settings() {
  89. scannerProps.put("sonar.host.url", "https://here/sonarqube");
  90. scannerProps.put("sonar.token", "testToken");
  91. scannerProps.put("sonar.ws.timeout", "42");
  92. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  93. assertThat(client).isNotNull();
  94. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  95. assertThat(httpConnector.baseUrl()).isEqualTo("https://here/sonarqube/");
  96. assertThat(httpConnector.okHttpClient().proxy()).isNull();
  97. }
  98. @Nested
  99. class WithMockHttpSonarQube {
  100. @RegisterExtension
  101. static WireMockExtension sonarqubeMock = WireMockExtension.newInstance()
  102. .options(wireMockConfig().dynamicPort())
  103. .build();
  104. @Test
  105. void it_should_timeout_on_long_response() {
  106. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  107. scannerProps.put("sonar.scanner.responseTimeout", "PT0.2S");
  108. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  109. sonarqubeMock.stubFor(get("/api/plugins/installed")
  110. .willReturn(aResponse().withStatus(200)
  111. .withFixedDelay(2000)
  112. .withBody("Success")));
  113. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  114. var getRequest = new GetRequest("api/plugins/installed");
  115. var thrown = assertThrows(IllegalStateException.class, () -> httpConnector.call(getRequest));
  116. assertThat(thrown).hasStackTraceContaining("timeout");
  117. }
  118. @Test
  119. void it_should_timeout_on_slow_response() {
  120. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  121. scannerProps.put("sonar.scanner.socketTimeout", "PT0.2S");
  122. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  123. sonarqubeMock.stubFor(get("/api/plugins/installed")
  124. .willReturn(aResponse().withStatus(200)
  125. .withChunkedDribbleDelay(2, 2000)
  126. .withBody("Success")));
  127. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  128. var getRequest = new GetRequest("api/plugins/installed");
  129. var thrown = assertThrows(IllegalStateException.class, () -> httpConnector.call(getRequest));
  130. assertThat(thrown).hasStackTraceContaining("timeout");
  131. }
  132. @Test
  133. void it_should_throw_if_invalid_proxy_port() {
  134. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  135. scannerProps.put("sonar.scanner.proxyHost", "localhost");
  136. scannerProps.put("sonar.scanner.proxyPort", "not_a_number");
  137. var scannerPropertiesBean = new ScannerProperties(scannerProps);
  138. assertThrows(IllegalArgumentException.class, () -> underTest.provide(scannerPropertiesBean, env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome));
  139. }
  140. @Nested
  141. class WithProxy {
  142. private static final String PROXY_AUTH_ENABLED = "proxy-auth";
  143. @RegisterExtension
  144. static WireMockExtension proxyMock = WireMockExtension.newInstance()
  145. .options(wireMockConfig().dynamicPort())
  146. .build();
  147. @BeforeEach
  148. void configureMocks(TestInfo info) {
  149. if (info.getTags().contains(PROXY_AUTH_ENABLED)) {
  150. proxyMock.stubFor(get(urlMatching("/api/plugins/.*"))
  151. .inScenario("Proxy Auth")
  152. .whenScenarioStateIs(STARTED)
  153. .willReturn(aResponse()
  154. .withStatus(407)
  155. .withHeader("Proxy-Authenticate", "Basic realm=\"Access to the proxy\""))
  156. .willSetStateTo("Challenge returned"));
  157. proxyMock.stubFor(get(urlMatching("/api/plugins/.*"))
  158. .inScenario("Proxy Auth")
  159. .whenScenarioStateIs("Challenge returned")
  160. .willReturn(aResponse().proxiedFrom(sonarqubeMock.baseUrl())));
  161. } else {
  162. proxyMock.stubFor(get(urlMatching("/api/plugins/.*")).willReturn(aResponse().proxiedFrom(sonarqubeMock.baseUrl())));
  163. }
  164. }
  165. @Test
  166. void it_should_honor_scanner_proxy_settings() {
  167. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  168. scannerProps.put("sonar.scanner.proxyHost", "localhost");
  169. scannerProps.put("sonar.scanner.proxyPort", "" + proxyMock.getPort());
  170. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  171. sonarqubeMock.stubFor(get("/api/plugins/installed")
  172. .willReturn(aResponse().withStatus(200).withBody("Success")));
  173. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  174. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  175. assertThat(r.code()).isEqualTo(200);
  176. assertThat(r.content()).isEqualTo("Success");
  177. }
  178. proxyMock.verify(getRequestedFor(urlEqualTo("/api/plugins/installed")));
  179. }
  180. @Test
  181. @Tag(PROXY_AUTH_ENABLED)
  182. void it_should_honor_scanner_proxy_settings_with_auth() {
  183. var proxyLogin = "proxyLogin";
  184. var proxyPassword = "proxyPassword";
  185. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  186. scannerProps.put("sonar.scanner.proxyHost", "localhost");
  187. scannerProps.put("sonar.scanner.proxyPort", "" + proxyMock.getPort());
  188. scannerProps.put("sonar.scanner.proxyUser", proxyLogin);
  189. scannerProps.put("sonar.scanner.proxyPassword", proxyPassword);
  190. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  191. sonarqubeMock.stubFor(get("/api/plugins/installed")
  192. .willReturn(aResponse().withStatus(200).withBody("Success")));
  193. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  194. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  195. assertThat(r.code()).isEqualTo(200);
  196. assertThat(r.content()).isEqualTo("Success");
  197. }
  198. proxyMock.verify(getRequestedFor(urlEqualTo("/api/plugins/installed"))
  199. .withHeader("Proxy-Authorization", equalTo("Basic " + Base64.getEncoder().encodeToString((proxyLogin + ":" + proxyPassword).getBytes(StandardCharsets.UTF_8)))));
  200. }
  201. @Test
  202. @Tag(PROXY_AUTH_ENABLED)
  203. void it_should_honor_old_jvm_proxy_auth_properties() {
  204. var proxyLogin = "proxyLogin";
  205. var proxyPassword = "proxyPassword";
  206. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  207. scannerProps.put("sonar.scanner.proxyHost", "localhost");
  208. scannerProps.put("sonar.scanner.proxyPort", "" + proxyMock.getPort());
  209. systemProps.put("http.proxyUser", proxyLogin);
  210. systemProps.put("http.proxyPassword", proxyPassword);
  211. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  212. sonarqubeMock.stubFor(get("/api/plugins/installed")
  213. .willReturn(aResponse().withStatus(200).withBody("Success")));
  214. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  215. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  216. assertThat(r.code()).isEqualTo(200);
  217. assertThat(r.content()).isEqualTo("Success");
  218. }
  219. proxyMock.verify(getRequestedFor(urlEqualTo("/api/plugins/installed"))
  220. .withHeader("Proxy-Authorization", equalTo("Basic " + Base64.getEncoder().encodeToString((proxyLogin + ":" + proxyPassword).getBytes(StandardCharsets.UTF_8)))));
  221. }
  222. }
  223. }
  224. @Nested
  225. class WithMockHttpsSonarQube {
  226. public static final String KEYSTORE_PWD = "pwdServerP12";
  227. @RegisterExtension
  228. static WireMockExtension sonarqubeMock = WireMockExtension.newInstance()
  229. .options(wireMockConfig().dynamicHttpsPort().httpDisabled(true)
  230. .keystoreType("pkcs12")
  231. .keystorePath(toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/server.p12"))).toString())
  232. .keystorePassword(KEYSTORE_PWD)
  233. .keyManagerPassword(KEYSTORE_PWD))
  234. .build();
  235. @BeforeEach
  236. void mockResponse() {
  237. sonarqubeMock.stubFor(get("/api/plugins/installed")
  238. .willReturn(aResponse().withStatus(200).withBody("Success")));
  239. }
  240. @Test
  241. void it_should_not_trust_server_self_signed_certificate_by_default() {
  242. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  243. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  244. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  245. var getRequest = new GetRequest("api/plugins/installed");
  246. var thrown = assertThrows(IllegalStateException.class, () -> httpConnector.call(getRequest));
  247. assertThat(thrown).hasStackTraceContaining("CertificateException");
  248. }
  249. @Test
  250. void it_should_trust_server_self_signed_certificate_when_certificate_is_in_truststore() {
  251. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  252. scannerProps.put("sonar.scanner.truststorePath", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client-truststore.p12"))).toString());
  253. scannerProps.put("sonar.scanner.truststorePassword", "pwdClientWithServerCA");
  254. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  255. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  256. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  257. assertThat(r.code()).isEqualTo(200);
  258. assertThat(r.content()).isEqualTo("Success");
  259. }
  260. }
  261. }
  262. @Nested
  263. class WithMockHttpsSonarQubeAndClientCertificates {
  264. public static final String KEYSTORE_PWD = "pwdServerP12";
  265. @RegisterExtension
  266. static WireMockExtension sonarqubeMock = WireMockExtension.newInstance()
  267. .options(wireMockConfig().dynamicHttpsPort().httpDisabled(true)
  268. .keystoreType("pkcs12")
  269. .keystorePath(toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/server.p12"))).toString())
  270. .keystorePassword(KEYSTORE_PWD)
  271. .keyManagerPassword(KEYSTORE_PWD)
  272. .needClientAuth(true)
  273. .trustStoreType("pkcs12")
  274. .trustStorePath(toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/server-with-client-ca.p12"))).toString())
  275. .trustStorePassword("pwdServerWithClientCA"))
  276. .build();
  277. @BeforeEach
  278. void mockResponse() {
  279. sonarqubeMock.stubFor(get("/api/plugins/installed")
  280. .willReturn(aResponse().withStatus(200).withBody("Success")));
  281. }
  282. @Test
  283. void it_should_fail_if_client_certificate_not_provided() {
  284. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  285. scannerProps.put("sonar.scanner.truststorePath", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client-truststore.p12"))).toString());
  286. scannerProps.put("sonar.scanner.truststorePassword", "pwdClientWithServerCA");
  287. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  288. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  289. var getRequest = new GetRequest("api/plugins/installed");
  290. var thrown = assertThrows(IllegalStateException.class, () -> httpConnector.call(getRequest));
  291. assertThat(thrown).satisfiesAnyOf(
  292. e -> assertThat(e).hasStackTraceContaining("SSLHandshakeException"),
  293. // Exception is flaky because of https://bugs.openjdk.org/browse/JDK-8172163
  294. e -> assertThat(e).hasStackTraceContaining("Broken pipe"));
  295. }
  296. @Test
  297. void it_should_authenticate_using_certificate_in_keystore() {
  298. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  299. scannerProps.put("sonar.scanner.truststorePath", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client-truststore.p12"))).toString());
  300. scannerProps.put("sonar.scanner.truststorePassword", "pwdClientWithServerCA");
  301. scannerProps.put("sonar.scanner.keystorePath", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client.p12"))).toString());
  302. scannerProps.put("sonar.scanner.keystorePassword", "pwdClientCertP12");
  303. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  304. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  305. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  306. assertThat(r.code()).isEqualTo(200);
  307. assertThat(r.content()).isEqualTo("Success");
  308. }
  309. }
  310. @RestoreSystemProperties
  311. @Test
  312. void it_should_support_jvm_system_properties() {
  313. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  314. System.setProperty("javax.net.ssl.trustStore", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client-truststore.p12"))).toString());
  315. System.setProperty("javax.net.ssl.trustStorePassword", "pwdClientWithServerCA");
  316. System.setProperty("javax.net.ssl.keyStore", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client.p12"))).toString());
  317. systemProps.setProperty("javax.net.ssl.keyStore", "any value is fine here");
  318. System.setProperty("javax.net.ssl.keyStorePassword", "pwdClientCertP12");
  319. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  320. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  321. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  322. assertThat(r.code()).isEqualTo(200);
  323. assertThat(r.content()).isEqualTo("Success");
  324. }
  325. }
  326. }
  327. private static Path toPath(URL url) {
  328. try {
  329. return Paths.get(url.toURI());
  330. } catch (URISyntaxException e) {
  331. throw new RuntimeException(e);
  332. }
  333. }
  334. }