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.

BitbucketCloudRestClient.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2022 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.alm.client.bitbucket.bitbucketcloud;
  21. import com.google.gson.Gson;
  22. import com.google.gson.GsonBuilder;
  23. import com.google.gson.JsonParseException;
  24. import java.io.IOException;
  25. import java.util.Objects;
  26. import java.util.function.Function;
  27. import java.util.function.UnaryOperator;
  28. import javax.annotation.Nullable;
  29. import okhttp3.Credentials;
  30. import okhttp3.FormBody;
  31. import okhttp3.HttpUrl;
  32. import okhttp3.MediaType;
  33. import okhttp3.OkHttpClient;
  34. import okhttp3.Request;
  35. import okhttp3.RequestBody;
  36. import okhttp3.Response;
  37. import okhttp3.ResponseBody;
  38. import org.sonar.api.server.ServerSide;
  39. import org.sonar.api.utils.log.Logger;
  40. import org.sonar.api.utils.log.Loggers;
  41. import org.sonar.server.exceptions.NotFoundException;
  42. import static org.sonar.api.internal.apachecommons.lang.StringUtils.removeEnd;
  43. @ServerSide
  44. public class BitbucketCloudRestClient {
  45. private static final Logger LOG = Loggers.get(BitbucketCloudRestClient.class);
  46. private static final String AUTHORIZATION = "Authorization";
  47. private static final String GET = "GET";
  48. private static final String ENDPOINT = "https://api.bitbucket.org";
  49. private static final String ACCESS_TOKEN_ENDPOINT = "https://bitbucket.org/site/oauth2/access_token";
  50. private static final String VERSION = "2.0";
  51. private static final String UNABLE_TO_CONTACT_BBC_SERVERS = "Unable to contact Bitbucket Cloud servers";
  52. private static final String ERROR_BBC_SERVERS = "Error returned by Bitbucket Cloud";
  53. protected static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
  54. private final OkHttpClient client;
  55. private final String bitbucketCloudEndpoint;
  56. private final String accessTokenEndpoint;
  57. public BitbucketCloudRestClient(OkHttpClient okHttpClient) {
  58. this(okHttpClient, ENDPOINT, ACCESS_TOKEN_ENDPOINT);
  59. }
  60. protected BitbucketCloudRestClient(OkHttpClient okHttpClient, String bitbucketCloudEndpoint, String accessTokenEndpoint) {
  61. this.client = okHttpClient;
  62. this.bitbucketCloudEndpoint = bitbucketCloudEndpoint;
  63. this.accessTokenEndpoint = accessTokenEndpoint;
  64. }
  65. /**
  66. * Validate parameters provided.
  67. */
  68. public void validate(String clientId, String clientSecret, String workspace) {
  69. Token token = validateAccessToken(clientId, clientSecret);
  70. if (token.getScopes() == null || !token.getScopes().contains("pullrequest")) {
  71. String msg = "The OAuth consumer in the Bitbucket workspace is not configured with the permission to read pull requests";
  72. LOG.info("Validation failed. {}}: {}", msg, token.getScopes());
  73. throw new IllegalArgumentException(ERROR_BBC_SERVERS + ": " + msg);
  74. }
  75. try {
  76. doGet(token.getAccessToken(), buildUrl("/repositories/" + workspace), r -> null);
  77. } catch (NotFoundException | IllegalStateException e) {
  78. throw new IllegalArgumentException(e.getMessage());
  79. }
  80. }
  81. /**
  82. * Validate parameters provided.
  83. */
  84. public void validateAppPassword(String encodedCredentials, String workspace) {
  85. try {
  86. doGetWithBasicAuth(encodedCredentials, buildUrl("/repositories/" + workspace), r -> null);
  87. } catch (NotFoundException | IllegalStateException e) {
  88. throw new IllegalArgumentException(e.getMessage());
  89. }
  90. }
  91. private Token validateAccessToken(String clientId, String clientSecret) {
  92. Request request = createAccessTokenRequest(clientId, clientSecret);
  93. try (Response response = client.newCall(request).execute()) {
  94. if (response.isSuccessful()) {
  95. return buildGson().fromJson(response.body().charStream(), Token.class);
  96. }
  97. ErrorDetails errorMsg = getTokenError(response.body());
  98. if (errorMsg.body != null) {
  99. switch (errorMsg.body) {
  100. case "invalid_grant":
  101. throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS +
  102. ": Configure the OAuth consumer in the Bitbucket workspace to be a private consumer");
  103. case "unauthorized_client":
  104. throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS + ": Check your credentials");
  105. default:
  106. if (errorMsg.parsedErrorMsg != null) {
  107. LOG.info("Validation failed: " + errorMsg.parsedErrorMsg);
  108. throw new IllegalArgumentException(ERROR_BBC_SERVERS + ": " + errorMsg.parsedErrorMsg);
  109. } else {
  110. LOG.info("Validation failed: " + errorMsg.body);
  111. throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS);
  112. }
  113. }
  114. } else {
  115. LOG.info("Validation failed");
  116. }
  117. throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS);
  118. } catch (IOException e) {
  119. throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS, e);
  120. }
  121. }
  122. public RepositoryList searchRepos(String encodedCredentials, String workspace, @Nullable String repoName, Integer page, Integer pageSize) {
  123. String filterQuery = String.format("q=name~\"%s\"", repoName != null ? repoName : "");
  124. HttpUrl url = buildUrl(String.format("/repositories/%s?%s&page=%s&pagelen=%s", workspace, filterQuery, page, pageSize));
  125. return doGetWithBasicAuth(encodedCredentials, url, r -> buildGson().fromJson(r.body().charStream(), RepositoryList.class));
  126. }
  127. public Repository getRepo(String encodedCredentials, String workspace, String slug) {
  128. HttpUrl url = buildUrl(String.format("/repositories/%s/%s", workspace, slug));
  129. return doGetWithBasicAuth(encodedCredentials, url, r -> buildGson().fromJson(r.body().charStream(), Repository.class));
  130. }
  131. public String createAccessToken(String clientId, String clientSecret) {
  132. Request request = createAccessTokenRequest(clientId, clientSecret);
  133. return doCall(request, r -> buildGson().fromJson(r.body().charStream(), Token.class)).getAccessToken();
  134. }
  135. private Request createAccessTokenRequest(String clientId, String clientSecret) {
  136. RequestBody body = new FormBody.Builder()
  137. .add("grant_type", "client_credentials")
  138. .build();
  139. HttpUrl url = HttpUrl.parse(accessTokenEndpoint);
  140. String credential = Credentials.basic(clientId, clientSecret);
  141. return prepareRequestWithBasicAuthCredentials(credential, "POST", url, body);
  142. }
  143. protected HttpUrl buildUrl(String relativeUrl) {
  144. return HttpUrl.parse(removeEnd(bitbucketCloudEndpoint, "/") + "/" + VERSION + relativeUrl);
  145. }
  146. protected <G> G doGet(String accessToken, HttpUrl url, Function<Response, G> handler) {
  147. Request request = prepareRequestWithAccessToken(accessToken, GET, url, null);
  148. return doCall(request, handler);
  149. }
  150. protected <G> G doGetWithBasicAuth(String encodedCredentials, HttpUrl url, Function<Response, G> handler) {
  151. Request request = prepareRequestWithBasicAuthCredentials("Basic " + encodedCredentials, GET, url, null);
  152. return doCall(request, handler);
  153. }
  154. protected <G> G doCall(Request request, Function<Response, G> handler) {
  155. try (Response response = client.newCall(request).execute()) {
  156. if (!response.isSuccessful()) {
  157. handleError(response);
  158. }
  159. return handler.apply(response);
  160. } catch (IOException e) {
  161. throw new IllegalStateException(ERROR_BBC_SERVERS, e);
  162. }
  163. }
  164. private static void handleError(Response response) throws IOException {
  165. int responseCode = response.code();
  166. ErrorDetails error = getError(response.body());
  167. LOG.info(ERROR_BBC_SERVERS + ": {} {}", responseCode, error.parsedErrorMsg != null ? error.parsedErrorMsg : error.body);
  168. if (error.parsedErrorMsg != null) {
  169. throw new IllegalStateException(ERROR_BBC_SERVERS + ": " + error.parsedErrorMsg);
  170. } else {
  171. throw new IllegalStateException(UNABLE_TO_CONTACT_BBC_SERVERS);
  172. }
  173. }
  174. private static ErrorDetails getError(@Nullable ResponseBody body) throws IOException {
  175. return getErrorDetails(body, s -> {
  176. Error gsonError = buildGson().fromJson(s, Error.class);
  177. if (gsonError != null && gsonError.errorMsg != null && gsonError.errorMsg.message != null) {
  178. return gsonError.errorMsg.message;
  179. }
  180. return null;
  181. });
  182. }
  183. private static ErrorDetails getTokenError(@Nullable ResponseBody body) throws IOException {
  184. if (body == null) {
  185. return new ErrorDetails(null, null);
  186. }
  187. String bodyStr = body.string();
  188. if (body.contentType() != null && Objects.equals(JSON_MEDIA_TYPE.type(), body.contentType().type())) {
  189. try {
  190. TokenError gsonError = buildGson().fromJson(bodyStr, TokenError.class);
  191. if (gsonError != null && gsonError.error != null) {
  192. return new ErrorDetails(gsonError.error, gsonError.errorDescription);
  193. }
  194. } catch (JsonParseException e) {
  195. // ignore
  196. }
  197. }
  198. return new ErrorDetails(bodyStr, null);
  199. }
  200. private static class ErrorDetails {
  201. @Nullable
  202. private final String body;
  203. @Nullable
  204. private final String parsedErrorMsg;
  205. public ErrorDetails(@Nullable String body, @Nullable String parsedErrorMsg) {
  206. this.body = body;
  207. this.parsedErrorMsg = parsedErrorMsg;
  208. }
  209. }
  210. private static ErrorDetails getErrorDetails(@Nullable ResponseBody body, UnaryOperator<String> parser) throws IOException {
  211. if (body == null) {
  212. return new ErrorDetails("", null);
  213. }
  214. String bodyStr = body.string();
  215. if (body.contentType() != null && Objects.equals(JSON_MEDIA_TYPE.type(), body.contentType().type())) {
  216. try {
  217. return new ErrorDetails(bodyStr, parser.apply(bodyStr));
  218. } catch (JsonParseException e) {
  219. // ignore
  220. }
  221. }
  222. return new ErrorDetails(bodyStr, null);
  223. }
  224. protected static Request prepareRequestWithAccessToken(String accessToken, String method, HttpUrl url, @Nullable RequestBody body) {
  225. return new Request.Builder()
  226. .method(method, body)
  227. .url(url)
  228. .header(AUTHORIZATION, "Bearer " + accessToken)
  229. .build();
  230. }
  231. protected static Request prepareRequestWithBasicAuthCredentials(String encodedCredentials, String method,
  232. HttpUrl url, @Nullable RequestBody body) {
  233. return new Request.Builder()
  234. .method(method, body)
  235. .url(url)
  236. .header(AUTHORIZATION, encodedCredentials)
  237. .build();
  238. }
  239. public static Gson buildGson() {
  240. return new GsonBuilder().create();
  241. }
  242. }