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 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. @TempDir
  66. private Path sonarUserHomeDir;
  67. private final SonarUserHome sonarUserHome = mock(SonarUserHome.class);
  68. private final Map<String, String> scannerProps = new HashMap<>();
  69. private final ScannerWsClientProvider underTest = new ScannerWsClientProvider();
  70. private final EnvironmentInformation env = new EnvironmentInformation("Maven Plugin", "2.3");
  71. private final System2 system2 = mock(System2.class);
  72. private final Properties systemProps = new Properties();
  73. @BeforeEach
  74. void configureMocks() {
  75. when(system2.properties()).thenReturn(systemProps);
  76. when(sonarUserHome.getPath()).thenReturn(sonarUserHomeDir);
  77. }
  78. @Test
  79. void provide_client_with_default_settings() {
  80. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  81. assertThat(client).isNotNull();
  82. assertThat(client.baseUrl()).isEqualTo("http://localhost:9000/");
  83. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  84. assertThat(httpConnector.baseUrl()).isEqualTo("http://localhost:9000/");
  85. assertThat(httpConnector.okHttpClient().proxy()).isNull();
  86. assertThat(httpConnector.okHttpClient().connectTimeoutMillis()).isEqualTo(5_000);
  87. assertThat(httpConnector.okHttpClient().readTimeoutMillis()).isEqualTo(60_000);
  88. }
  89. @Test
  90. void provide_client_with_custom_settings() {
  91. scannerProps.put("sonar.host.url", "https://here/sonarqube");
  92. scannerProps.put("sonar.token", "testToken");
  93. scannerProps.put("sonar.ws.timeout", "42");
  94. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  95. assertThat(client).isNotNull();
  96. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  97. assertThat(httpConnector.baseUrl()).isEqualTo("https://here/sonarqube/");
  98. assertThat(httpConnector.okHttpClient().proxy()).isNull();
  99. }
  100. @Nested
  101. class WithMockHttpSonarQube {
  102. @RegisterExtension
  103. static WireMockExtension sonarqubeMock = WireMockExtension.newInstance()
  104. .options(wireMockConfig().dynamicPort())
  105. .build();
  106. @Test
  107. void it_should_timeout_on_long_response() {
  108. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  109. scannerProps.put("sonar.scanner.responseTimeout", "PT0.2S");
  110. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  111. sonarqubeMock.stubFor(get("/api/plugins/installed")
  112. .willReturn(aResponse().withStatus(200)
  113. .withFixedDelay(2000)
  114. .withBody("Success")));
  115. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  116. var getRequest = new GetRequest("api/plugins/installed");
  117. var thrown = assertThrows(IllegalStateException.class, () -> httpConnector.call(getRequest));
  118. assertThat(thrown).hasStackTraceContaining("timeout");
  119. }
  120. @Test
  121. void it_should_timeout_on_slow_response() {
  122. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  123. scannerProps.put("sonar.scanner.socketTimeout", "PT0.2S");
  124. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  125. sonarqubeMock.stubFor(get("/api/plugins/installed")
  126. .willReturn(aResponse().withStatus(200)
  127. .withChunkedDribbleDelay(2, 2000)
  128. .withBody("Success")));
  129. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  130. var getRequest = new GetRequest("api/plugins/installed");
  131. var thrown = assertThrows(IllegalStateException.class, () -> httpConnector.call(getRequest));
  132. assertThat(thrown).hasStackTraceContaining("timeout");
  133. }
  134. @Test
  135. void it_should_throw_if_invalid_proxy_port() {
  136. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  137. scannerProps.put("sonar.scanner.proxyHost", "localhost");
  138. scannerProps.put("sonar.scanner.proxyPort", "not_a_number");
  139. var scannerPropertiesBean = new ScannerProperties(scannerProps);
  140. assertThrows(IllegalArgumentException.class, () -> underTest.provide(scannerPropertiesBean, env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome));
  141. }
  142. @Nested
  143. class WithProxy {
  144. private static final String PROXY_AUTH_ENABLED = "proxy-auth";
  145. @RegisterExtension
  146. static WireMockExtension proxyMock = WireMockExtension.newInstance()
  147. .options(wireMockConfig().dynamicPort())
  148. .build();
  149. @BeforeEach
  150. void configureMocks(TestInfo info) {
  151. if (info.getTags().contains(PROXY_AUTH_ENABLED)) {
  152. proxyMock.stubFor(get(urlMatching("/api/plugins/.*"))
  153. .inScenario("Proxy Auth")
  154. .whenScenarioStateIs(STARTED)
  155. .willReturn(aResponse()
  156. .withStatus(407)
  157. .withHeader("Proxy-Authenticate", "Basic realm=\"Access to the proxy\""))
  158. .willSetStateTo("Challenge returned"));
  159. proxyMock.stubFor(get(urlMatching("/api/plugins/.*"))
  160. .inScenario("Proxy Auth")
  161. .whenScenarioStateIs("Challenge returned")
  162. .willReturn(aResponse().proxiedFrom(sonarqubeMock.baseUrl())));
  163. } else {
  164. proxyMock.stubFor(get(urlMatching("/api/plugins/.*")).willReturn(aResponse().proxiedFrom(sonarqubeMock.baseUrl())));
  165. }
  166. }
  167. @Test
  168. void it_should_honor_scanner_proxy_settings() {
  169. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  170. scannerProps.put("sonar.scanner.proxyHost", "localhost");
  171. scannerProps.put("sonar.scanner.proxyPort", "" + proxyMock.getPort());
  172. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  173. sonarqubeMock.stubFor(get("/api/plugins/installed")
  174. .willReturn(aResponse().withStatus(200).withBody("Success")));
  175. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  176. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  177. assertThat(r.code()).isEqualTo(200);
  178. assertThat(r.content()).isEqualTo("Success");
  179. }
  180. proxyMock.verify(getRequestedFor(urlEqualTo("/api/plugins/installed")));
  181. }
  182. @Test
  183. @Tag(PROXY_AUTH_ENABLED)
  184. void it_should_honor_scanner_proxy_settings_with_auth() {
  185. var proxyLogin = "proxyLogin";
  186. var proxyPassword = "proxyPassword";
  187. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  188. scannerProps.put("sonar.scanner.proxyHost", "localhost");
  189. scannerProps.put("sonar.scanner.proxyPort", "" + proxyMock.getPort());
  190. scannerProps.put("sonar.scanner.proxyUser", proxyLogin);
  191. scannerProps.put("sonar.scanner.proxyPassword", proxyPassword);
  192. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  193. sonarqubeMock.stubFor(get("/api/plugins/installed")
  194. .willReturn(aResponse().withStatus(200).withBody("Success")));
  195. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  196. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  197. assertThat(r.code()).isEqualTo(200);
  198. assertThat(r.content()).isEqualTo("Success");
  199. }
  200. proxyMock.verify(getRequestedFor(urlEqualTo("/api/plugins/installed"))
  201. .withHeader("Proxy-Authorization", equalTo("Basic " + Base64.getEncoder().encodeToString((proxyLogin + ":" + proxyPassword).getBytes(StandardCharsets.UTF_8)))));
  202. }
  203. @Test
  204. @Tag(PROXY_AUTH_ENABLED)
  205. void it_should_honor_old_jvm_proxy_auth_properties() {
  206. var proxyLogin = "proxyLogin";
  207. var proxyPassword = "proxyPassword";
  208. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  209. scannerProps.put("sonar.scanner.proxyHost", "localhost");
  210. scannerProps.put("sonar.scanner.proxyPort", "" + proxyMock.getPort());
  211. systemProps.put("http.proxyUser", proxyLogin);
  212. systemProps.put("http.proxyPassword", proxyPassword);
  213. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  214. sonarqubeMock.stubFor(get("/api/plugins/installed")
  215. .willReturn(aResponse().withStatus(200).withBody("Success")));
  216. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  217. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  218. assertThat(r.code()).isEqualTo(200);
  219. assertThat(r.content()).isEqualTo("Success");
  220. }
  221. proxyMock.verify(getRequestedFor(urlEqualTo("/api/plugins/installed"))
  222. .withHeader("Proxy-Authorization", equalTo("Basic " + Base64.getEncoder().encodeToString((proxyLogin + ":" + proxyPassword).getBytes(StandardCharsets.UTF_8)))));
  223. }
  224. }
  225. }
  226. @Nested
  227. class WithMockHttpsSonarQube {
  228. public static final String KEYSTORE_PWD = "pwdServerP12";
  229. @RegisterExtension
  230. static WireMockExtension sonarqubeMock = WireMockExtension.newInstance()
  231. .options(wireMockConfig().dynamicHttpsPort().httpDisabled(true)
  232. .keystoreType("pkcs12")
  233. .keystorePath(toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/server.p12"))).toString())
  234. .keystorePassword(KEYSTORE_PWD)
  235. .keyManagerPassword(KEYSTORE_PWD))
  236. .build();
  237. @BeforeEach
  238. void mockResponse() {
  239. sonarqubeMock.stubFor(get("/api/plugins/installed")
  240. .willReturn(aResponse().withStatus(200).withBody("Success")));
  241. }
  242. @Test
  243. void it_should_not_trust_server_self_signed_certificate_by_default() {
  244. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  245. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  246. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  247. var getRequest = new GetRequest("api/plugins/installed");
  248. var thrown = assertThrows(IllegalStateException.class, () -> httpConnector.call(getRequest));
  249. assertThat(thrown).hasStackTraceContaining("CertificateException");
  250. }
  251. @Test
  252. void it_should_trust_server_self_signed_certificate_when_certificate_is_in_truststore() {
  253. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  254. scannerProps.put("sonar.scanner.truststorePath", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client-truststore.p12"))).toString());
  255. scannerProps.put("sonar.scanner.truststorePassword", "pwdClientWithServerCA");
  256. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  257. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  258. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  259. assertThat(r.code()).isEqualTo(200);
  260. assertThat(r.content()).isEqualTo("Success");
  261. }
  262. }
  263. }
  264. @Nested
  265. class WithMockHttpsSonarQubeAndClientCertificates {
  266. public static final String KEYSTORE_PWD = "pwdServerP12";
  267. @RegisterExtension
  268. static WireMockExtension sonarqubeMock = WireMockExtension.newInstance()
  269. .options(wireMockConfig().dynamicHttpsPort().httpDisabled(true)
  270. .keystoreType("pkcs12")
  271. .keystorePath(toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/server.p12"))).toString())
  272. .keystorePassword(KEYSTORE_PWD)
  273. .keyManagerPassword(KEYSTORE_PWD)
  274. .needClientAuth(true)
  275. .trustStoreType("pkcs12")
  276. .trustStorePath(toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/server-with-client-ca.p12"))).toString())
  277. .trustStorePassword("pwdServerWithClientCA"))
  278. .build();
  279. @BeforeEach
  280. void mockResponse() {
  281. sonarqubeMock.stubFor(get("/api/plugins/installed")
  282. .willReturn(aResponse().withStatus(200).withBody("Success")));
  283. }
  284. @Test
  285. void it_should_fail_if_client_certificate_not_provided() {
  286. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  287. scannerProps.put("sonar.scanner.truststorePath", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client-truststore.p12"))).toString());
  288. scannerProps.put("sonar.scanner.truststorePassword", "pwdClientWithServerCA");
  289. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  290. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  291. var getRequest = new GetRequest("api/plugins/installed");
  292. var thrown = assertThrows(IllegalStateException.class, () -> httpConnector.call(getRequest));
  293. assertThat(thrown).satisfiesAnyOf(
  294. e -> assertThat(e).hasStackTraceContaining("SSLHandshakeException"),
  295. // Exception is flaky because of https://bugs.openjdk.org/browse/JDK-8172163
  296. e -> assertThat(e).hasStackTraceContaining("Broken pipe"));
  297. }
  298. @Test
  299. void it_should_authenticate_using_certificate_in_keystore() {
  300. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  301. scannerProps.put("sonar.scanner.truststorePath", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client-truststore.p12"))).toString());
  302. scannerProps.put("sonar.scanner.truststorePassword", "pwdClientWithServerCA");
  303. scannerProps.put("sonar.scanner.keystorePath", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client.p12"))).toString());
  304. scannerProps.put("sonar.scanner.keystorePassword", "pwdClientCertP12");
  305. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  306. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  307. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  308. assertThat(r.code()).isEqualTo(200);
  309. assertThat(r.content()).isEqualTo("Success");
  310. }
  311. }
  312. @RestoreSystemProperties
  313. @Test
  314. void it_should_support_jvm_system_properties() {
  315. scannerProps.put("sonar.host.url", sonarqubeMock.baseUrl());
  316. System.setProperty("javax.net.ssl.trustStore", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client-truststore.p12"))).toString());
  317. System.setProperty("javax.net.ssl.trustStorePassword", "pwdClientWithServerCA");
  318. System.setProperty("javax.net.ssl.keyStore", toPath(requireNonNull(ScannerWsClientProviderTest.class.getResource("/ssl/client.p12"))).toString());
  319. systemProps.setProperty("javax.net.ssl.keyStore", "any value is fine here");
  320. System.setProperty("javax.net.ssl.keyStorePassword", "pwdClientCertP12");
  321. DefaultScannerWsClient client = underTest.provide(new ScannerProperties(scannerProps), env, GLOBAL_ANALYSIS_MODE, system2, ANALYSIS_WARNINGS, sonarUserHome);
  322. HttpConnector httpConnector = (HttpConnector) client.wsConnector();
  323. try (var r = httpConnector.call(new GetRequest("api/plugins/installed"))) {
  324. assertThat(r.code()).isEqualTo(200);
  325. assertThat(r.content()).isEqualTo("Success");
  326. }
  327. }
  328. }
  329. private static Path toPath(URL url) {
  330. try {
  331. return Paths.get(url.toURI());
  332. } catch (URISyntaxException e) {
  333. throw new RuntimeException(e);
  334. }
  335. }
  336. }