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.

DefaultScannerWsClientTest.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 java.time.LocalDateTime;
  22. import java.time.ZoneOffset;
  23. import java.time.format.DateTimeFormatter;
  24. import java.util.Collections;
  25. import java.util.List;
  26. import org.apache.commons.lang3.StringUtils;
  27. import org.junit.Rule;
  28. import org.junit.Test;
  29. import org.mockito.Mockito;
  30. import org.slf4j.event.Level;
  31. import org.sonar.api.notifications.AnalysisWarnings;
  32. import org.sonar.api.testfixtures.log.LogTester;
  33. import org.sonar.api.utils.MessageException;
  34. import org.sonar.api.utils.log.LoggerLevel;
  35. import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
  36. import org.sonar.scanner.bootstrap.ScannerProperties;
  37. import org.sonarqube.ws.client.GetRequest;
  38. import org.sonarqube.ws.client.HttpException;
  39. import org.sonarqube.ws.client.MockWsResponse;
  40. import org.sonarqube.ws.client.WsClient;
  41. import org.sonarqube.ws.client.WsRequest;
  42. import org.sonarqube.ws.client.WsResponse;
  43. import static org.assertj.core.api.Assertions.assertThat;
  44. import static org.assertj.core.api.Assertions.assertThatThrownBy;
  45. import static org.mockito.Mockito.mock;
  46. import static org.mockito.Mockito.when;
  47. import static org.sonar.api.utils.DateUtils.DATETIME_FORMAT;
  48. public class DefaultScannerWsClientTest {
  49. @Rule
  50. public LogTester logTester = new LogTester();
  51. private final WsClient wsClient = mock(WsClient.class, Mockito.RETURNS_DEEP_STUBS);
  52. private final AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class);
  53. @Test
  54. public void call_whenDebugLevel_shouldLogAndProfileRequest() {
  55. WsRequest request = newRequest();
  56. WsResponse response = newResponse().setRequestUrl("https://local/api/issues/search");
  57. when(wsClient.wsConnector().call(request)).thenReturn(response);
  58. logTester.setLevel(LoggerLevel.DEBUG);
  59. DefaultScannerWsClient underTest = new DefaultScannerWsClient(wsClient, false, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
  60. WsResponse result = underTest.call(request);
  61. // do not fail the execution -> interceptor returns the response
  62. assertThat(result).isSameAs(response);
  63. // check logs
  64. List<String> debugLogs = logTester.logs(Level.DEBUG);
  65. assertThat(debugLogs).hasSize(1);
  66. assertThat(debugLogs.get(0)).contains("GET 200 https://local/api/issues/search | time=");
  67. }
  68. @Test
  69. public void createErrorMessage_whenJsonError_shouldCreateErrorMsg() {
  70. String content = "{\"errors\":[{\"msg\":\"missing scan permission\"}, {\"msg\":\"missing another permission\"}]}";
  71. assertThat(DefaultScannerWsClient.createErrorMessage(new HttpException("url", 400, content))).isEqualTo("missing scan permission, missing another permission");
  72. }
  73. @Test
  74. public void createErrorMessage_whenHtml_shouldCreateErrorMsg() {
  75. String content = "<!DOCTYPE html><html>something</html>";
  76. assertThat(DefaultScannerWsClient.createErrorMessage(new HttpException("url", 400, content))).isEqualTo("HTTP code 400");
  77. }
  78. @Test
  79. public void createErrorMessage_whenLongContent_shouldCreateErrorMsg() {
  80. String content = StringUtils.repeat("mystring", 1000);
  81. assertThat(DefaultScannerWsClient.createErrorMessage(new HttpException("url", 400, content))).hasSize(15 + 128);
  82. }
  83. @Test
  84. public void call_whenUnauthorizedAndDebugEnabled_shouldLogResponseDetails() {
  85. WsRequest request = newRequest();
  86. WsResponse response = newResponse()
  87. .setContent("Missing credentials")
  88. .setHeader("Authorization: ", "Bearer ImNotAValidToken")
  89. .setCode(403);
  90. logTester.setLevel(LoggerLevel.DEBUG);
  91. when(wsClient.wsConnector().call(request)).thenReturn(response);
  92. DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, false,
  93. new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
  94. assertThatThrownBy(() -> client.call(request))
  95. .isInstanceOf(MessageException.class)
  96. .hasMessage(
  97. "You're not authorized to analyze this project or the project doesn't exist on SonarQube and you're not authorized to create it. Please contact an administrator.");
  98. List<String> debugLogs = logTester.logs(Level.DEBUG);
  99. assertThat(debugLogs).hasSize(2);
  100. assertThat(debugLogs.get(1)).contains("Error response content: Missing credentials, headers: {Authorization: =[Bearer ImNotAValidToken]}");
  101. }
  102. @Test
  103. public void call_whenUnauthenticatedAndDebugEnabled_shouldLogResponseDetails() {
  104. WsRequest request = newRequest();
  105. WsResponse response = newResponse()
  106. .setContent("Missing authentication")
  107. .setHeader("X-Test-Header: ", "ImATestHeader")
  108. .setCode(401);
  109. logTester.setLevel(LoggerLevel.DEBUG);
  110. when(wsClient.wsConnector().call(request)).thenReturn(response);
  111. DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, false,
  112. new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
  113. assertThatThrownBy(() -> client.call(request))
  114. .isInstanceOf(MessageException.class)
  115. .hasMessage("Not authorized. Analyzing this project requires authentication. Please check the user token in the property 'sonar.token' " +
  116. "or the credentials in the properties 'sonar.login' and 'sonar.password'.");
  117. List<String> debugLogs = logTester.logs(Level.DEBUG);
  118. assertThat(debugLogs).hasSize(2);
  119. assertThat(debugLogs.get(1)).contains("Error response content: Missing authentication, headers: {X-Test-Header: =[ImATestHeader]}");
  120. }
  121. @Test
  122. public void call_whenMissingCredentials_shouldFailWithMsg() {
  123. WsRequest request = newRequest();
  124. WsResponse response = newResponse()
  125. .setContent("Missing authentication")
  126. .setCode(401);
  127. when(wsClient.wsConnector().call(request)).thenReturn(response);
  128. DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, false,
  129. new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
  130. assertThatThrownBy(() -> client.call(request))
  131. .isInstanceOf(MessageException.class)
  132. .hasMessage("Not authorized. Analyzing this project requires authentication. Please check the user token in the property 'sonar.token' " +
  133. "or the credentials in the properties 'sonar.login' and 'sonar.password'.");
  134. }
  135. @Test
  136. public void call_whenInvalidCredentials_shouldFailWithMsg() {
  137. WsRequest request = newRequest();
  138. WsResponse response = newResponse()
  139. .setContent("Invalid credentials")
  140. .setCode(401);
  141. when(wsClient.wsConnector().call(request)).thenReturn(response);
  142. DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, /* credentials are configured */true,
  143. new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
  144. assertThatThrownBy(() -> client.call(request))
  145. .isInstanceOf(MessageException.class)
  146. .hasMessage("Not authorized. Please check the user token in the property 'sonar.token' or the credentials in the properties 'sonar.login' and 'sonar.password'.");
  147. }
  148. @Test
  149. public void call_whenMissingPermissions_shouldFailWithMsg() {
  150. WsRequest request = newRequest();
  151. WsResponse response = newResponse()
  152. .setContent("Unauthorized")
  153. .setCode(403);
  154. when(wsClient.wsConnector().call(request)).thenReturn(response);
  155. DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, true,
  156. new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
  157. assertThatThrownBy(() -> client.call(request))
  158. .isInstanceOf(MessageException.class)
  159. .hasMessage(
  160. "You're not authorized to analyze this project or the project doesn't exist on SonarQube and you're not authorized to create it. Please contact an administrator.");
  161. }
  162. @Test
  163. public void call_whenTokenExpirationApproaches_shouldLogWarnings() {
  164. WsRequest request = newRequest();
  165. var fiveDaysLatter = LocalDateTime.now().atZone(ZoneOffset.UTC).plusDays(5);
  166. String expirationDate = DateTimeFormatter
  167. .ofPattern(DATETIME_FORMAT)
  168. .format(fiveDaysLatter);
  169. WsResponse response = newResponse()
  170. .setCode(200)
  171. .setExpirationDate(expirationDate);
  172. when(wsClient.wsConnector().call(request)).thenReturn(response);
  173. logTester.setLevel(LoggerLevel.DEBUG);
  174. DefaultScannerWsClient underTest = new DefaultScannerWsClient(wsClient, false, new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
  175. underTest.call(request);
  176. // the second call should not add the same warning twice
  177. underTest.call(request);
  178. // check logs
  179. List<String> warningLogs = logTester.logs(Level.WARN);
  180. assertThat(warningLogs).hasSize(2);
  181. assertThat(warningLogs.get(0)).contains("The token used for this analysis will expire on: " + fiveDaysLatter.format(DateTimeFormatter.ofPattern("MMMM dd, yyyy")));
  182. assertThat(warningLogs.get(1)).contains("Analysis executed with this token will fail after the expiration date.");
  183. }
  184. @Test
  185. public void call_whenBadRequest_shouldFailWithMessage() {
  186. WsRequest request = newRequest();
  187. WsResponse response = newResponse()
  188. .setCode(400)
  189. .setContent("{\"errors\":[{\"msg\":\"Boo! bad request! bad!\"}]}");
  190. when(wsClient.wsConnector().call(request)).thenReturn(response);
  191. DefaultScannerWsClient client = new DefaultScannerWsClient(wsClient, true,
  192. new GlobalAnalysisMode(new ScannerProperties(Collections.emptyMap())), analysisWarnings);
  193. assertThatThrownBy(() -> client.call(request))
  194. .isInstanceOf(MessageException.class)
  195. .hasMessage("Boo! bad request! bad!");
  196. }
  197. private MockWsResponse newResponse() {
  198. return new MockWsResponse().setRequestUrl("https://local/api/issues/search");
  199. }
  200. private WsRequest newRequest() {
  201. return new GetRequest("api/issues/search");
  202. }
  203. }