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.

IntegrationTest.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 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.auth.bitbucket;
  21. import java.nio.charset.StandardCharsets;
  22. import java.util.Arrays;
  23. import java.util.concurrent.atomic.AtomicBoolean;
  24. import java.util.stream.Collectors;
  25. import javax.servlet.http.HttpServletRequest;
  26. import javax.servlet.http.HttpServletResponse;
  27. import okhttp3.mockwebserver.MockResponse;
  28. import okhttp3.mockwebserver.MockWebServer;
  29. import okhttp3.mockwebserver.RecordedRequest;
  30. import org.junit.Before;
  31. import org.junit.Rule;
  32. import org.junit.Test;
  33. import org.sonar.api.config.PropertyDefinitions;
  34. import org.sonar.api.config.internal.MapSettings;
  35. import org.sonar.api.server.authentication.OAuth2IdentityProvider;
  36. import org.sonar.api.server.authentication.UnauthorizedException;
  37. import org.sonar.api.server.authentication.UserIdentity;
  38. import org.sonar.api.utils.System2;
  39. import static java.lang.String.format;
  40. import static java.net.URLEncoder.encode;
  41. import static org.assertj.core.api.Assertions.assertThat;
  42. import static org.assertj.core.api.Assertions.assertThatThrownBy;
  43. import static org.mockito.Mockito.mock;
  44. import static org.mockito.Mockito.spy;
  45. import static org.mockito.Mockito.when;
  46. public class IntegrationTest {
  47. private static final String CALLBACK_URL = "http://localhost/oauth/callback/bitbucket";
  48. @Rule
  49. public MockWebServer bitbucket = new MockWebServer();
  50. // load settings with default values
  51. private final MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, BitbucketSettings.definitions()));
  52. private final BitbucketSettings bitbucketSettings = spy(new BitbucketSettings(settings.asConfig()));
  53. private final UserIdentityFactory userIdentityFactory = new UserIdentityFactory();
  54. private final BitbucketScribeApi scribeApi = new BitbucketScribeApi(bitbucketSettings);
  55. private final BitbucketIdentityProvider underTest = new BitbucketIdentityProvider(bitbucketSettings, userIdentityFactory, scribeApi);
  56. @Before
  57. public void setUp() {
  58. settings.setProperty("sonar.auth.bitbucket.clientId.secured", "the_id");
  59. settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", "the_secret");
  60. settings.setProperty("sonar.auth.bitbucket.enabled", true);
  61. when(bitbucketSettings.webURL()).thenReturn(format("http://%s:%d/", bitbucket.getHostName(), bitbucket.getPort()));
  62. when(bitbucketSettings.apiURL()).thenReturn(format("http://%s:%d/", bitbucket.getHostName(), bitbucket.getPort()));
  63. }
  64. /**
  65. * First phase: SonarQube redirects browser to Bitbucket authentication form, requesting the
  66. * minimal access rights ("scope") to get user profile.
  67. */
  68. @Test
  69. public void redirect_browser_to_bitbucket_authentication_form() throws Exception {
  70. DumbInitContext context = new DumbInitContext("the-csrf-state");
  71. underTest.init(context);
  72. assertThat(context.redirectedTo)
  73. .startsWith(bitbucket.url("site/oauth2/authorize").toString())
  74. .contains("scope=" + encode("account", StandardCharsets.UTF_8.name()));
  75. }
  76. /**
  77. * Second phase: Bitbucket redirects browser to SonarQube at /oauth/callback/bitbucket?code={the verifier code}.
  78. * This SonarQube web service sends three requests to Bitbucket:
  79. * <ul>
  80. * <li>get an access token</li>
  81. * <li>get the profile (login, name) of the authenticated user</li>
  82. * <li>get the emails of the authenticated user</li>
  83. * </ul>
  84. */
  85. @Test
  86. public void authenticate_successfully() throws Exception {
  87. bitbucket.enqueue(newSuccessfulAccessTokenResponse());
  88. bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
  89. bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
  90. HttpServletRequest request = newRequest("the-verifier-code");
  91. DumbCallbackContext callbackContext = new DumbCallbackContext(request);
  92. underTest.callback(callbackContext);
  93. assertThat(callbackContext.csrfStateVerified.get()).isTrue();
  94. assertThat(callbackContext.userIdentity.getName()).isEqualTo("John");
  95. assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("john@bitbucket.org");
  96. assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue();
  97. // Verify the requests sent to Bitbucket
  98. RecordedRequest accessTokenRequest = bitbucket.takeRequest();
  99. assertThat(accessTokenRequest.getPath()).startsWith("/site/oauth2/access_token");
  100. RecordedRequest userRequest = bitbucket.takeRequest();
  101. assertThat(userRequest.getPath()).startsWith("/2.0/user");
  102. RecordedRequest emailRequest = bitbucket.takeRequest();
  103. assertThat(emailRequest.getPath()).startsWith("/2.0/user/emails");
  104. // do not request user workspaces, workspace restriction is disabled by default
  105. assertThat(bitbucket.getRequestCount()).isEqualTo(3);
  106. }
  107. @Test
  108. public void callback_throws_ISE_if_error_when_requesting_user_profile() {
  109. bitbucket.enqueue(newSuccessfulAccessTokenResponse());
  110. // https://api.bitbucket.org/2.0/user fails
  111. bitbucket.enqueue(new MockResponse().setResponseCode(500).setBody("{error}"));
  112. DumbCallbackContext callbackContext = new DumbCallbackContext(newRequest("the-verifier-code"));
  113. assertThatThrownBy(() -> underTest.callback(callbackContext))
  114. .hasMessage("Can not get Bitbucket user profile. HTTP code: 500, response: {error}")
  115. .isInstanceOf(IllegalStateException.class);
  116. assertThat(callbackContext.csrfStateVerified.get()).isTrue();
  117. assertThat(callbackContext.userIdentity).isNull();
  118. assertThat(callbackContext.redirectedToRequestedPage.get()).isFalse();
  119. }
  120. @Test
  121. public void allow_authentication_if_user_is_member_of_one_restricted_workspace() {
  122. settings.setProperty("sonar.auth.bitbucket.workspaces", new String[] {"workspace1", "workspace2"});
  123. bitbucket.enqueue(newSuccessfulAccessTokenResponse());
  124. bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
  125. bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
  126. bitbucket.enqueue(newWorkspacesResponse("workspace3", "workspace2"));
  127. HttpServletRequest request = newRequest("the-verifier-code");
  128. DumbCallbackContext callbackContext = new DumbCallbackContext(request);
  129. underTest.callback(callbackContext);
  130. assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("john@bitbucket.org");
  131. assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("john");
  132. assertThat(callbackContext.userIdentity.getProviderId()).isEqualTo("john-uuid");
  133. assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue();
  134. }
  135. @Test
  136. public void forbid_authentication_if_user_is_not_member_of_one_restricted_workspace() {
  137. settings.setProperty("sonar.auth.bitbucket.workspaces", new String[] {"workspace1", "workspace2"});
  138. bitbucket.enqueue(newSuccessfulAccessTokenResponse());
  139. bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
  140. bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
  141. bitbucket.enqueue(newWorkspacesResponse("workspace3"));
  142. DumbCallbackContext context = new DumbCallbackContext(newRequest("the-verifier-code"));
  143. assertThatThrownBy(() -> underTest.callback(context))
  144. .isInstanceOf(UnauthorizedException.class);
  145. }
  146. @Test
  147. public void forbid_authentication_if_user_is_not_member_of_any_workspace() {
  148. settings.setProperty("sonar.auth.bitbucket.workspaces", new String[] {"workspace1", "workspace2"});
  149. bitbucket.enqueue(newSuccessfulAccessTokenResponse());
  150. bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
  151. bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
  152. bitbucket.enqueue(newWorkspacesResponse(/* no workspaces */));
  153. DumbCallbackContext context = new DumbCallbackContext(newRequest("the-verifier-code"));
  154. assertThatThrownBy(() -> underTest.callback(context))
  155. .isInstanceOf(UnauthorizedException.class);
  156. }
  157. /**
  158. * Response sent by Bitbucket to SonarQube when generating an access token
  159. */
  160. private static MockResponse newSuccessfulAccessTokenResponse() {
  161. return new MockResponse().setBody("{\"access_token\":\"e72e16c7e42f292c6912e7710c838347ae178b4a\",\"scope\":\"user\"}");
  162. }
  163. /**
  164. * Response of https://api.bitbucket.org/2.0/user
  165. */
  166. private static MockResponse newUserResponse(String login, String name, String uuid) {
  167. return new MockResponse().setBody("{\"username\":\"" + login + "\", \"display_name\":\"" + name + "\", \"uuid\":\"" + uuid + "\"}");
  168. }
  169. /**
  170. * Response of https://api.bitbucket.org/2.0/user/permissions/workspaces?q=permission="member"
  171. */
  172. private static MockResponse newWorkspacesResponse(String... workspaces) {
  173. String s = Arrays.stream(workspaces)
  174. .map(w -> "{\"workspace\":{\"name\":\"" + w + "\",\"slug\":\"" + w + "\"}}")
  175. .collect(Collectors.joining(","));
  176. return new MockResponse().setBody("{\"values\":[" + s + "]}");
  177. }
  178. /**
  179. * Response of https://api.bitbucket.org/2.0/user/emails
  180. */
  181. private static MockResponse newPrimaryEmailResponse(String email) {
  182. return new MockResponse().setBody("{\"values\":[{\"active\": true,\"email\":\"" + email + "\",\"is_primary\": true}]}");
  183. }
  184. private static HttpServletRequest newRequest(String verifierCode) {
  185. HttpServletRequest request = mock(HttpServletRequest.class);
  186. when(request.getParameter("code")).thenReturn(verifierCode);
  187. return request;
  188. }
  189. private static class DumbCallbackContext implements OAuth2IdentityProvider.CallbackContext {
  190. final HttpServletRequest request;
  191. final AtomicBoolean csrfStateVerified = new AtomicBoolean(true);
  192. final AtomicBoolean redirectedToRequestedPage = new AtomicBoolean(false);
  193. UserIdentity userIdentity = null;
  194. public DumbCallbackContext(HttpServletRequest request) {
  195. this.request = request;
  196. }
  197. @Override
  198. public void verifyCsrfState() {
  199. this.csrfStateVerified.set(true);
  200. }
  201. @Override
  202. public void verifyCsrfState(String s) {
  203. }
  204. @Override
  205. public void redirectToRequestedPage() {
  206. redirectedToRequestedPage.set(true);
  207. }
  208. @Override
  209. public void authenticate(UserIdentity userIdentity) {
  210. this.userIdentity = userIdentity;
  211. }
  212. @Override
  213. public String getCallbackUrl() {
  214. return CALLBACK_URL;
  215. }
  216. @Override
  217. public HttpServletRequest getRequest() {
  218. return request;
  219. }
  220. @Override
  221. public HttpServletResponse getResponse() {
  222. throw new UnsupportedOperationException("not used");
  223. }
  224. }
  225. private static class DumbInitContext implements OAuth2IdentityProvider.InitContext {
  226. String redirectedTo = null;
  227. private final String generatedCsrfState;
  228. public DumbInitContext(String generatedCsrfState) {
  229. this.generatedCsrfState = generatedCsrfState;
  230. }
  231. @Override
  232. public String generateCsrfState() {
  233. return generatedCsrfState;
  234. }
  235. @Override
  236. public void redirectTo(String url) {
  237. this.redirectedTo = url;
  238. }
  239. @Override
  240. public String getCallbackUrl() {
  241. return CALLBACK_URL;
  242. }
  243. @Override
  244. public HttpServletRequest getRequest() {
  245. return null;
  246. }
  247. @Override
  248. public HttpServletResponse getResponse() {
  249. return null;
  250. }
  251. }
  252. }