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.

DefaultScannerWsClient.java 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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.google.gson.JsonArray;
  22. import com.google.gson.JsonElement;
  23. import com.google.gson.JsonObject;
  24. import com.google.gson.JsonParser;
  25. import java.time.ZoneOffset;
  26. import java.time.ZonedDateTime;
  27. import java.time.format.DateTimeFormatter;
  28. import java.util.ArrayList;
  29. import java.util.HashSet;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.Set;
  33. import javax.annotation.CheckForNull;
  34. import org.apache.commons.lang3.StringUtils;
  35. import org.sonar.api.CoreProperties;
  36. import org.sonar.api.notifications.AnalysisWarnings;
  37. import org.sonar.api.utils.MessageException;
  38. import org.sonar.api.utils.log.Logger;
  39. import org.sonar.api.utils.log.Loggers;
  40. import org.sonar.api.utils.log.Profiler;
  41. import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
  42. import org.sonarqube.ws.client.HttpException;
  43. import org.sonarqube.ws.client.WsClient;
  44. import org.sonarqube.ws.client.WsConnector;
  45. import org.sonarqube.ws.client.WsRequest;
  46. import org.sonarqube.ws.client.WsResponse;
  47. import static java.lang.String.format;
  48. import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
  49. import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
  50. import static java.net.HttpURLConnection.HTTP_OK;
  51. import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
  52. import static org.sonar.api.utils.DateUtils.DATETIME_FORMAT;
  53. import static org.sonar.api.utils.Preconditions.checkState;
  54. public class DefaultScannerWsClient implements ScannerWsClient {
  55. private static final int MAX_ERROR_MSG_LEN = 128;
  56. private static final String SQ_TOKEN_EXPIRATION_HEADER = "SonarQube-Authentication-Token-Expiration";
  57. private static final DateTimeFormatter USER_FRIENDLY_DATETIME_FORMAT = DateTimeFormatter.ofPattern("MMMM dd, yyyy");
  58. private static final Logger LOG = Loggers.get(DefaultScannerWsClient.class);
  59. private final Set<String> warningMessages = new HashSet<>();
  60. private final WsClient target;
  61. private final boolean hasCredentials;
  62. private final GlobalAnalysisMode globalMode;
  63. private final AnalysisWarnings analysisWarnings;
  64. public DefaultScannerWsClient(WsClient target, boolean hasCredentials, GlobalAnalysisMode globalMode, AnalysisWarnings analysisWarnings) {
  65. this.target = target;
  66. this.hasCredentials = hasCredentials;
  67. this.globalMode = globalMode;
  68. this.analysisWarnings = analysisWarnings;
  69. }
  70. /**
  71. * If an exception is not thrown, the response needs to be closed by either calling close() directly, or closing the
  72. * body content's stream/reader.
  73. *
  74. * @throws IllegalStateException if the request could not be executed due to a connectivity problem or timeout. Because networks can
  75. * fail during an exchange, it is possible that the remote server accepted the request before the failure
  76. * @throws MessageException if there was a problem with authentication or if a error message was parsed from the response.
  77. * @throws HttpException if the response code is not in range [200..300). Consider using {@link #createErrorMessage(HttpException)} to create more relevant messages for the users.
  78. */
  79. public WsResponse call(WsRequest request) {
  80. checkState(!globalMode.isMediumTest(), "No WS call should be made in medium test mode");
  81. Profiler profiler = Profiler.createIfDebug(LOG).start();
  82. WsResponse response = target.wsConnector().call(request);
  83. profiler.stopDebug(format("%s %d %s", request.getMethod(), response.code(), response.requestUrl()));
  84. failIfUnauthorized(response);
  85. checkAuthenticationWarnings(response);
  86. return response;
  87. }
  88. public String baseUrl() {
  89. return target.wsConnector().baseUrl();
  90. }
  91. WsConnector wsConnector() {
  92. return target.wsConnector();
  93. }
  94. private void failIfUnauthorized(WsResponse response) {
  95. int code = response.code();
  96. if (code == HTTP_UNAUTHORIZED) {
  97. logResponseDetailsIfDebug(response);
  98. response.close();
  99. if (hasCredentials) {
  100. // credentials are not valid
  101. throw MessageException.of(format("Not authorized. Please check the user token in the property '%s' or the credentials in the properties '%s' and '%s'.",
  102. ScannerWsClientProvider.TOKEN_PROPERTY, CoreProperties.LOGIN, CoreProperties.PASSWORD));
  103. }
  104. // not authenticated - see https://jira.sonarsource.com/browse/SONAR-4048
  105. throw MessageException.of(format("Not authorized. Analyzing this project requires authentication. " +
  106. "Please check the user token in the property '%s' or the credentials in the properties '%s' and '%s'.",
  107. ScannerWsClientProvider.TOKEN_PROPERTY, CoreProperties.LOGIN, CoreProperties.PASSWORD));
  108. }
  109. if (code == HTTP_FORBIDDEN) {
  110. logResponseDetailsIfDebug(response);
  111. throw MessageException.of("You're not authorized to analyze this project or the project doesn't exist on SonarQube" +
  112. " and you're not authorized to create it. Please contact an administrator.");
  113. }
  114. if (code == HTTP_BAD_REQUEST) {
  115. String jsonMsg = tryParseAsJsonError(response.content());
  116. if (jsonMsg != null) {
  117. throw MessageException.of(jsonMsg);
  118. }
  119. }
  120. // if failed, throws an HttpException
  121. response.failIfNotSuccessful();
  122. }
  123. private static void logResponseDetailsIfDebug(WsResponse response) {
  124. if (!LOG.isDebugEnabled()) {
  125. return;
  126. }
  127. String content = response.hasContent() ? response.content() : "<no content>";
  128. Map<String, List<String>> headers = response.headers();
  129. LOG.debug("Error response content: {}, headers: {}", content, headers);
  130. }
  131. private void checkAuthenticationWarnings(WsResponse response) {
  132. if (response.code() == HTTP_OK) {
  133. response.header(SQ_TOKEN_EXPIRATION_HEADER).ifPresent(expirationDate -> {
  134. var datetimeInUTC = ZonedDateTime.from(DateTimeFormatter.ofPattern(DATETIME_FORMAT)
  135. .parse(expirationDate)).withZoneSameInstant(ZoneOffset.UTC);
  136. if (isTokenExpiringInOneWeek(datetimeInUTC)) {
  137. addAnalysisWarning(datetimeInUTC);
  138. }
  139. });
  140. }
  141. }
  142. private static boolean isTokenExpiringInOneWeek(ZonedDateTime expirationDate) {
  143. ZonedDateTime localDateTime = ZonedDateTime.now(ZoneOffset.UTC);
  144. ZonedDateTime headerDateTime = expirationDate.minusDays(7);
  145. return localDateTime.isAfter(headerDateTime);
  146. }
  147. private void addAnalysisWarning(ZonedDateTime tokenExpirationDate) {
  148. String warningMessage = "The token used for this analysis will expire on: " + tokenExpirationDate.format(USER_FRIENDLY_DATETIME_FORMAT);
  149. if (!warningMessages.contains(warningMessage)) {
  150. warningMessages.add(warningMessage);
  151. LOG.warn(warningMessage);
  152. LOG.warn("Analysis executed with this token will fail after the expiration date.");
  153. }
  154. analysisWarnings.addUnique(warningMessage + "\nAfter this date, the token can no longer be used to execute the analysis. "
  155. + "Please consider generating a new token and updating it in the locations where it is in use.");
  156. }
  157. /**
  158. * Tries to form a short and relevant error message from the exception, to be displayed in the console.
  159. */
  160. public static String createErrorMessage(HttpException exception) {
  161. String json = tryParseAsJsonError(exception.content());
  162. if (json != null) {
  163. return json;
  164. }
  165. String msg = "HTTP code " + exception.code();
  166. if (isHtml(exception.content())) {
  167. return msg;
  168. }
  169. return msg + ": " + StringUtils.left(exception.content(), MAX_ERROR_MSG_LEN);
  170. }
  171. @CheckForNull
  172. private static String tryParseAsJsonError(String responseContent) {
  173. try {
  174. JsonObject obj = JsonParser.parseString(responseContent).getAsJsonObject();
  175. JsonArray errors = obj.getAsJsonArray("errors");
  176. List<String> errorMessages = new ArrayList<>();
  177. for (JsonElement e : errors) {
  178. errorMessages.add(e.getAsJsonObject().get("msg").getAsString());
  179. }
  180. return String.join(", ", errorMessages);
  181. } catch (Exception e) {
  182. return null;
  183. }
  184. }
  185. private static boolean isHtml(String responseContent) {
  186. return StringUtils.stripToEmpty(responseContent).startsWith("<!DOCTYPE html>");
  187. }
  188. }