3 * Copyright (C) 2009-2021 SonarSource SA
4 * mailto:info AT sonarsource DOT com
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.
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.
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.
20 package org.sonar.server.authentication;
22 import javax.servlet.FilterChain;
23 import javax.servlet.http.Cookie;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26 import org.junit.Before;
27 import org.junit.Rule;
28 import org.junit.Test;
29 import org.junit.rules.ExpectedException;
30 import org.mockito.ArgumentCaptor;
31 import org.sonar.api.server.authentication.OAuth2IdentityProvider;
32 import org.sonar.api.server.authentication.UnauthorizedException;
33 import org.sonar.api.server.authentication.UserIdentity;
34 import org.sonar.api.utils.log.LogTester;
35 import org.sonar.api.utils.log.LoggerLevel;
36 import org.sonar.db.user.UserDto;
37 import org.sonar.server.authentication.event.AuthenticationEvent;
38 import org.sonar.server.authentication.event.AuthenticationException;
39 import org.sonar.server.authentication.exception.EmailAlreadyExistsRedirectionException;
40 import org.sonar.server.user.ThreadLocalUserSession;
42 import static org.assertj.core.api.Assertions.assertThat;
43 import static org.mockito.ArgumentMatchers.eq;
44 import static org.mockito.Mockito.mock;
45 import static org.mockito.Mockito.verify;
46 import static org.mockito.Mockito.verifyZeroInteractions;
47 import static org.mockito.Mockito.when;
48 import static org.sonar.db.user.UserTesting.newUserDto;
49 import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
51 public class OAuth2CallbackFilterTest {
53 private static final String OAUTH2_PROVIDER_KEY = "github";
54 private static final String LOGIN = "foo";
57 public LogTester logTester = new LogTester();
59 public ExpectedException thrown = ExpectedException.none();
61 public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule();
63 private OAuth2ContextFactory oAuth2ContextFactory = mock(OAuth2ContextFactory.class);
65 private HttpServletRequest request = mock(HttpServletRequest.class);
66 private HttpServletResponse response = mock(HttpServletResponse.class);
67 private FilterChain chain = mock(FilterChain.class);
69 private FakeOAuth2IdentityProvider oAuth2IdentityProvider = new WellbehaveFakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true, LOGIN);
70 private AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
71 private OAuth2AuthenticationParameters oAuthRedirection = mock(OAuth2AuthenticationParameters.class);
72 private ThreadLocalUserSession threadLocalUserSession = mock(ThreadLocalUserSession.class);
74 private ArgumentCaptor<AuthenticationException> authenticationExceptionCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
75 private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
77 private OAuth2CallbackFilter underTest = new OAuth2CallbackFilter(identityProviderRepository, oAuth2ContextFactory, authenticationEvent, oAuthRedirection,
78 threadLocalUserSession);
82 when(oAuth2ContextFactory.newCallback(request, response, oAuth2IdentityProvider)).thenReturn(mock(OAuth2IdentityProvider.CallbackContext.class));
83 when(request.getContextPath()).thenReturn("");
87 public void do_get_pattern() {
88 assertThat(underTest.doGetPattern()).isNotNull();
92 public void do_filter_with_context() {
93 when(request.getContextPath()).thenReturn("/sonarqube");
94 when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
95 identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
96 when(threadLocalUserSession.hasSession()).thenReturn(true);
97 when(threadLocalUserSession.getLogin()).thenReturn(LOGIN);
99 underTest.doFilter(request, response, chain);
101 assertCallbackCalled(oAuth2IdentityProvider);
102 verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
106 public void do_filter_with_context_no_log_if_provider_did_not_call_authenticate_on_context() {
107 when(request.getContextPath()).thenReturn("/sonarqube");
108 when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
109 FakeOAuth2IdentityProvider identityProvider = new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true);
110 identityProviderRepository.addIdentityProvider(identityProvider);
112 underTest.doFilter(request, response, chain);
114 assertCallbackCalled(identityProvider);
115 verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture());
116 AuthenticationException authenticationException = authenticationExceptionCaptor.getValue();
117 assertThat(authenticationException).hasMessage("Plugin did not call authenticate");
118 assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider));
119 assertThat(authenticationException.getLogin()).isNull();
120 assertThat(authenticationException.getPublicMessage()).isNull();
124 public void do_filter_on_auth2_identity_provider() {
125 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
126 identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
127 when(threadLocalUserSession.hasSession()).thenReturn(true);
128 when(threadLocalUserSession.getLogin()).thenReturn(LOGIN);
130 underTest.doFilter(request, response, chain);
132 assertCallbackCalled(oAuth2IdentityProvider);
133 verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
137 public void fail_on_not_oauth2_provider() throws Exception {
138 String providerKey = "openid";
139 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + providerKey);
140 identityProviderRepository.addIdentityProvider(new FakeBasicIdentityProvider(providerKey, true));
142 underTest.doFilter(request, response, chain);
144 assertError("Not an OAuth2IdentityProvider: class org.sonar.server.authentication.FakeBasicIdentityProvider");
145 verifyZeroInteractions(authenticationEvent);
149 public void fail_on_disabled_provider() throws Exception {
150 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
151 identityProviderRepository.addIdentityProvider(new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, false));
153 underTest.doFilter(request, response, chain);
155 assertError("Failed to retrieve IdentityProvider for key 'github'");
156 verifyZeroInteractions(authenticationEvent);
160 public void redirect_when_failing_because_of_UnauthorizedExceptionException() throws Exception {
161 FailWithUnauthorizedExceptionIdProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider();
162 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
163 identityProviderRepository.addIdentityProvider(identityProvider);
165 underTest.doFilter(request, response, chain);
167 verify(response).sendRedirect("/sessions/unauthorized");
168 verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture());
169 AuthenticationException authenticationException = authenticationExceptionCaptor.getValue();
170 assertThat(authenticationException).hasMessage("Email john@email.com is already used");
171 assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider));
172 assertThat(authenticationException.getLogin()).isNull();
173 assertThat(authenticationException.getPublicMessage()).isEqualTo("Email john@email.com is already used");
174 verify(oAuthRedirection).delete(eq(request), eq(response));
176 verify(response).addCookie(cookieArgumentCaptor.capture());
177 Cookie cookie = cookieArgumentCaptor.getValue();
178 assertThat(cookie.getName()).isEqualTo("AUTHENTICATION-ERROR");
179 assertThat(cookie.getValue()).isEqualTo("Email%20john%40email.com%20is%20already%20used");
180 assertThat(cookie.getPath()).isEqualTo("/");
181 assertThat(cookie.isHttpOnly()).isFalse();
182 assertThat(cookie.getMaxAge()).isEqualTo(300);
183 assertThat(cookie.getSecure()).isFalse();
187 public void redirect_with_context_path_when_failing_because_of_UnauthorizedExceptionException() throws Exception {
188 when(request.getContextPath()).thenReturn("/sonarqube");
189 FailWithUnauthorizedExceptionIdProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider();
190 when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + identityProvider.getKey());
191 identityProviderRepository.addIdentityProvider(identityProvider);
193 underTest.doFilter(request, response, chain);
195 verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
196 verify(oAuthRedirection).delete(eq(request), eq(response));
200 public void redirect_when_failing_because_of_Exception() throws Exception {
201 FailWithIllegalStateException identityProvider = new FailWithIllegalStateException();
202 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
203 identityProviderRepository.addIdentityProvider(identityProvider);
205 underTest.doFilter(request, response, chain);
207 verify(response).sendRedirect("/sessions/unauthorized");
208 assertThat(logTester.logs(LoggerLevel.WARN)).containsExactlyInAnyOrder("Fail to callback authentication with 'failing'");
209 verify(oAuthRedirection).delete(eq(request), eq(response));
213 public void redirect_with_context_when_failing_because_of_Exception() throws Exception {
214 when(request.getContextPath()).thenReturn("/sonarqube");
215 FailWithIllegalStateException identityProvider = new FailWithIllegalStateException();
216 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
217 identityProviderRepository.addIdentityProvider(identityProvider);
219 underTest.doFilter(request, response, chain);
221 verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
225 public void redirect_when_failing_because_of_EmailAlreadyExistException() throws Exception {
226 UserDto existingUser = newUserDto().setEmail("john@email.com").setExternalLogin("john.bitbucket").setExternalIdentityProvider("bitbucket");
227 FailWithEmailAlreadyExistException identityProvider = new FailWithEmailAlreadyExistException(existingUser);
228 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
229 identityProviderRepository.addIdentityProvider(identityProvider);
231 underTest.doFilter(request, response, chain);
233 verify(response).sendRedirect("/sessions/email_already_exists");
234 verify(oAuthRedirection).delete(eq(request), eq(response));
235 verify(response).addCookie(cookieArgumentCaptor.capture());
236 Cookie cookie = cookieArgumentCaptor.getValue();
237 assertThat(cookie.getName()).isEqualTo("AUTHENTICATION-ERROR");
238 assertThat(cookie.getValue()).contains("john%40email.com");
239 assertThat(cookie.getPath()).isEqualTo("/");
240 assertThat(cookie.isHttpOnly()).isFalse();
241 assertThat(cookie.getMaxAge()).isEqualTo(300);
242 assertThat(cookie.getSecure()).isFalse();
246 public void fail_when_no_oauth2_provider_provided() throws Exception {
247 when(request.getRequestURI()).thenReturn("/oauth2/callback");
249 underTest.doFilter(request, response, chain);
251 assertError("No provider key found in URI");
252 verifyZeroInteractions(authenticationEvent);
255 private void assertCallbackCalled(FakeOAuth2IdentityProvider oAuth2IdentityProvider) {
256 assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
257 assertThat(oAuth2IdentityProvider.isCallbackCalled()).isTrue();
260 private void assertError(String expectedError) throws Exception {
261 assertThat(logTester.logs(LoggerLevel.WARN)).contains(expectedError);
262 verify(response).sendRedirect("/sessions/unauthorized");
263 assertThat(oAuth2IdentityProvider.isInitCalled()).isFalse();
266 private static class FailWithUnauthorizedExceptionIdProvider extends FailingIdentityProvider {
268 public void callback(CallbackContext context) {
269 throw new UnauthorizedException("Email john@email.com is already used");
273 private static class FailWithIllegalStateException extends FailingIdentityProvider {
275 public void callback(CallbackContext context) {
276 throw new IllegalStateException("Failure !");
280 private static class FailWithEmailAlreadyExistException extends FailingIdentityProvider {
282 private final UserDto existingUser;
284 public FailWithEmailAlreadyExistException(UserDto existingUser) {
285 this.existingUser = existingUser;
289 public void callback(CallbackContext context) {
290 throw new EmailAlreadyExistsRedirectionException(existingUser.getEmail(), existingUser, UserIdentity.builder()
291 .setProviderLogin("john.github")
292 .setName(existingUser.getName())
293 .setEmail(existingUser.getEmail())
298 private static abstract class FailingIdentityProvider extends TestIdentityProvider implements OAuth2IdentityProvider {
299 FailingIdentityProvider() {
300 this.setKey("failing");
301 this.setName("Failing");
302 this.setEnabled(true);
306 public void init(InitContext context) {
312 * An extension of {@link FakeOAuth2IdentityProvider} that actually call {@link org.sonar.api.server.authentication.OAuth2IdentityProvider.CallbackContext#authenticate(UserIdentity)}.
314 private static class WellbehaveFakeOAuth2IdentityProvider extends FakeOAuth2IdentityProvider {
315 private final String login;
317 public WellbehaveFakeOAuth2IdentityProvider(String key, boolean enabled, String login) {
323 public void callback(CallbackContext context) {
324 super.callback(context);
325 context.authenticate(UserIdentity.builder()
326 .setProviderLogin(login)
327 .setEmail(login + "@toto.com")
328 .setName("name of " + login)