1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
|
/*
* SonarQube
* Copyright (C) 2009-2025 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.auth.bitbucket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import jakarta.servlet.http.HttpServletRequest;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.utils.System2;
import org.sonar.server.http.JakartaHttpRequest;
import static java.lang.String.format;
import static java.net.URLEncoder.encode;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
public class IntegrationTest {
private static final String CALLBACK_URL = "http://localhost/oauth/callback/bitbucket";
@Rule
public MockWebServer bitbucket = new MockWebServer();
// load settings with default values
private final MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, BitbucketSettings.definitions()));
private final BitbucketSettings bitbucketSettings = spy(new BitbucketSettings(settings.asConfig()));
private final UserIdentityFactory userIdentityFactory = new UserIdentityFactory();
private final BitbucketScribeApi scribeApi = new BitbucketScribeApi(bitbucketSettings);
private final BitbucketIdentityProvider underTest = new BitbucketIdentityProvider(bitbucketSettings, userIdentityFactory, scribeApi);
@Before
public void setUp() {
settings.setProperty("sonar.auth.bitbucket.clientId.secured", "the_id");
settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", "the_secret");
settings.setProperty("sonar.auth.bitbucket.enabled", true);
when(bitbucketSettings.webURL()).thenReturn(format("http://%s:%d/", bitbucket.getHostName(), bitbucket.getPort()));
when(bitbucketSettings.apiURL()).thenReturn(format("http://%s:%d/", bitbucket.getHostName(), bitbucket.getPort()));
}
/**
* First phase: SonarQube redirects browser to Bitbucket authentication form, requesting the
* minimal access rights ("scope") to get user profile.
*/
@Test
public void redirect_browser_to_bitbucket_authentication_form() throws Exception {
DumbInitContext context = new DumbInitContext("the-csrf-state");
underTest.init(context);
assertThat(context.redirectedTo)
.startsWith(bitbucket.url("site/oauth2/authorize").toString())
.contains("scope=" + encode("account", StandardCharsets.UTF_8.name()));
}
/**
* Second phase: Bitbucket redirects browser to SonarQube at /oauth/callback/bitbucket?code={the verifier code}.
* This SonarQube web service sends three requests to Bitbucket:
* <ul>
* <li>get an access token</li>
* <li>get the profile (login, name) of the authenticated user</li>
* <li>get the emails of the authenticated user</li>
* </ul>
*/
@Test
public void authenticate_successfully() throws Exception {
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
HttpServletRequest request = newRequest("the-verifier-code");
DumbCallbackContext callbackContext = new DumbCallbackContext(request);
underTest.callback(callbackContext);
assertThat(callbackContext.csrfStateVerified.get()).isTrue();
assertThat(callbackContext.userIdentity.getName()).isEqualTo("John");
assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("john@bitbucket.org");
assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue();
// Verify the requests sent to Bitbucket
RecordedRequest accessTokenRequest = bitbucket.takeRequest();
assertThat(accessTokenRequest.getPath()).startsWith("/site/oauth2/access_token");
RecordedRequest userRequest = bitbucket.takeRequest();
assertThat(userRequest.getPath()).startsWith("/2.0/user");
RecordedRequest emailRequest = bitbucket.takeRequest();
assertThat(emailRequest.getPath()).startsWith("/2.0/user/emails");
// do not request user workspaces, workspace restriction is disabled by default
assertThat(bitbucket.getRequestCount()).isEqualTo(3);
}
@Test
public void callback_throws_ISE_if_error_when_requesting_user_profile() {
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
// https://api.bitbucket.org/2.0/user fails
bitbucket.enqueue(new MockResponse().setResponseCode(500).setBody("{error}"));
DumbCallbackContext callbackContext = new DumbCallbackContext(newRequest("the-verifier-code"));
assertThatThrownBy(() -> underTest.callback(callbackContext))
.hasMessage("Can not get Bitbucket user profile. HTTP code: 500, response: {error}")
.isInstanceOf(IllegalStateException.class);
assertThat(callbackContext.csrfStateVerified.get()).isTrue();
assertThat(callbackContext.userIdentity).isNull();
assertThat(callbackContext.redirectedToRequestedPage.get()).isFalse();
}
@Test
public void allow_authentication_if_user_is_member_of_one_restricted_workspace() {
settings.setProperty("sonar.auth.bitbucket.workspaces", new String[] {"workspace1", "workspace2"});
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
bitbucket.enqueue(newWorkspacesResponse("workspace3", "workspace2"));
HttpServletRequest request = newRequest("the-verifier-code");
DumbCallbackContext callbackContext = new DumbCallbackContext(request);
underTest.callback(callbackContext);
assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("john@bitbucket.org");
assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("john");
assertThat(callbackContext.userIdentity.getProviderId()).isEqualTo("john-uuid");
assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue();
}
@Test
public void forbid_authentication_if_user_is_not_member_of_one_restricted_workspace() {
settings.setProperty("sonar.auth.bitbucket.workspaces", new String[] {"workspace1", "workspace2"});
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
bitbucket.enqueue(newWorkspacesResponse("workspace3"));
DumbCallbackContext context = new DumbCallbackContext(newRequest("the-verifier-code"));
assertThatThrownBy(() -> underTest.callback(context))
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void forbid_authentication_if_user_is_not_member_of_any_workspace() {
settings.setProperty("sonar.auth.bitbucket.workspaces", new String[] {"workspace1", "workspace2"});
bitbucket.enqueue(newSuccessfulAccessTokenResponse());
bitbucket.enqueue(newUserResponse("john", "John", "john-uuid"));
bitbucket.enqueue(newPrimaryEmailResponse("john@bitbucket.org"));
bitbucket.enqueue(newWorkspacesResponse(/* no workspaces */));
DumbCallbackContext context = new DumbCallbackContext(newRequest("the-verifier-code"));
assertThatThrownBy(() -> underTest.callback(context))
.isInstanceOf(UnauthorizedException.class);
}
/**
* Response sent by Bitbucket to SonarQube when generating an access token
*/
private static MockResponse newSuccessfulAccessTokenResponse() {
return new MockResponse().setBody("{\"access_token\":\"e72e16c7e42f292c6912e7710c838347ae178b4a\",\"scope\":\"user\"}");
}
/**
* Response of https://api.bitbucket.org/2.0/user
*/
private static MockResponse newUserResponse(String login, String name, String uuid) {
return new MockResponse().setBody("{\"username\":\"" + login + "\", \"display_name\":\"" + name + "\", \"uuid\":\"" + uuid + "\"}");
}
/**
* Response of https://api.bitbucket.org/2.0/user/permissions/workspaces?q=permission="member"
*/
private static MockResponse newWorkspacesResponse(String... workspaces) {
String s = Arrays.stream(workspaces)
.map(w -> "{\"workspace\":{\"name\":\"" + w + "\",\"slug\":\"" + w + "\"}}")
.collect(Collectors.joining(","));
return new MockResponse().setBody("{\"values\":[" + s + "]}");
}
/**
* Response of https://api.bitbucket.org/2.0/user/emails
*/
private static MockResponse newPrimaryEmailResponse(String email) {
return new MockResponse().setBody("{\"values\":[{\"active\": true,\"email\":\"" + email + "\",\"is_primary\": true}]}");
}
private static HttpServletRequest newRequest(String verifierCode) {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getParameter("code")).thenReturn(verifierCode);
return request;
}
private static class DumbCallbackContext implements OAuth2IdentityProvider.CallbackContext {
final HttpServletRequest request;
final AtomicBoolean csrfStateVerified = new AtomicBoolean(true);
final AtomicBoolean redirectedToRequestedPage = new AtomicBoolean(false);
UserIdentity userIdentity = null;
public DumbCallbackContext(HttpServletRequest request) {
this.request = request;
}
@Override
public void verifyCsrfState() {
this.csrfStateVerified.set(true);
}
@Override
public void verifyCsrfState(String s) {
}
@Override
public void redirectToRequestedPage() {
redirectedToRequestedPage.set(true);
}
@Override
public void authenticate(UserIdentity userIdentity) {
this.userIdentity = userIdentity;
}
@Override
public String getCallbackUrl() {
return CALLBACK_URL;
}
@Override
public HttpRequest getHttpRequest() {
return new JakartaHttpRequest(request);
}
@Override
public HttpResponse getHttpResponse() {
throw new UnsupportedOperationException("not used");
}
}
private static class DumbInitContext implements OAuth2IdentityProvider.InitContext {
String redirectedTo = null;
private final String generatedCsrfState;
public DumbInitContext(String generatedCsrfState) {
this.generatedCsrfState = generatedCsrfState;
}
@Override
public String generateCsrfState() {
return generatedCsrfState;
}
@Override
public void redirectTo(String url) {
this.redirectedTo = url;
}
@Override
public String getCallbackUrl() {
return CALLBACK_URL;
}
@Override
public HttpRequest getHttpRequest() {
return null;
}
@Override
public HttpResponse getHttpResponse() {
return null;
}
}
}
|