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.server.authentication.event.AuthenticationEvent;
37 import org.sonar.server.authentication.event.AuthenticationException;
38 import org.sonar.server.user.ThreadLocalUserSession;
40 import static org.assertj.core.api.Assertions.assertThat;
41 import static org.mockito.ArgumentMatchers.eq;
42 import static org.mockito.Mockito.mock;
43 import static org.mockito.Mockito.verify;
44 import static org.mockito.Mockito.verifyZeroInteractions;
45 import static org.mockito.Mockito.when;
46 import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
48 public class OAuth2CallbackFilterTest {
50 private static final String OAUTH2_PROVIDER_KEY = "github";
51 private static final String LOGIN = "foo";
54 public LogTester logTester = new LogTester();
56 public ExpectedException thrown = ExpectedException.none();
58 public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule();
60 private OAuth2ContextFactory oAuth2ContextFactory = mock(OAuth2ContextFactory.class);
62 private HttpServletRequest request = mock(HttpServletRequest.class);
63 private HttpServletResponse response = mock(HttpServletResponse.class);
64 private FilterChain chain = mock(FilterChain.class);
66 private FakeOAuth2IdentityProvider oAuth2IdentityProvider = new WellbehaveFakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true, LOGIN);
67 private AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
68 private OAuth2AuthenticationParameters oAuthRedirection = mock(OAuth2AuthenticationParameters.class);
69 private ThreadLocalUserSession threadLocalUserSession = mock(ThreadLocalUserSession.class);
71 private ArgumentCaptor<AuthenticationException> authenticationExceptionCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
72 private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
74 private OAuth2CallbackFilter underTest = new OAuth2CallbackFilter(identityProviderRepository, oAuth2ContextFactory, authenticationEvent, oAuthRedirection,
75 threadLocalUserSession);
79 when(oAuth2ContextFactory.newCallback(request, response, oAuth2IdentityProvider)).thenReturn(mock(OAuth2IdentityProvider.CallbackContext.class));
80 when(request.getContextPath()).thenReturn("");
84 public void do_get_pattern() {
85 assertThat(underTest.doGetPattern()).isNotNull();
89 public void do_filter_with_context() {
90 when(request.getContextPath()).thenReturn("/sonarqube");
91 when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
92 identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
93 when(threadLocalUserSession.hasSession()).thenReturn(true);
94 when(threadLocalUserSession.getLogin()).thenReturn(LOGIN);
96 underTest.doFilter(request, response, chain);
98 assertCallbackCalled(oAuth2IdentityProvider);
99 verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
103 public void do_filter_with_context_no_log_if_provider_did_not_call_authenticate_on_context() {
104 when(request.getContextPath()).thenReturn("/sonarqube");
105 when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
106 FakeOAuth2IdentityProvider identityProvider = new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true);
107 identityProviderRepository.addIdentityProvider(identityProvider);
109 underTest.doFilter(request, response, chain);
111 assertCallbackCalled(identityProvider);
112 verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture());
113 AuthenticationException authenticationException = authenticationExceptionCaptor.getValue();
114 assertThat(authenticationException).hasMessage("Plugin did not call authenticate");
115 assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider));
116 assertThat(authenticationException.getLogin()).isNull();
117 assertThat(authenticationException.getPublicMessage()).isNull();
121 public void do_filter_on_auth2_identity_provider() {
122 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
123 identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
124 when(threadLocalUserSession.hasSession()).thenReturn(true);
125 when(threadLocalUserSession.getLogin()).thenReturn(LOGIN);
127 underTest.doFilter(request, response, chain);
129 assertCallbackCalled(oAuth2IdentityProvider);
130 verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
134 public void fail_on_not_oauth2_provider() throws Exception {
135 String providerKey = "openid";
136 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + providerKey);
137 identityProviderRepository.addIdentityProvider(new FakeBasicIdentityProvider(providerKey, true));
139 underTest.doFilter(request, response, chain);
141 assertError("Not an OAuth2IdentityProvider: class org.sonar.server.authentication.FakeBasicIdentityProvider");
142 verifyZeroInteractions(authenticationEvent);
146 public void fail_on_disabled_provider() throws Exception {
147 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
148 identityProviderRepository.addIdentityProvider(new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, false));
150 underTest.doFilter(request, response, chain);
152 assertError("Failed to retrieve IdentityProvider for key 'github'");
153 verifyZeroInteractions(authenticationEvent);
157 public void redirect_when_failing_because_of_UnauthorizedExceptionException() throws Exception {
158 FailWithUnauthorizedExceptionIdProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider();
159 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
160 identityProviderRepository.addIdentityProvider(identityProvider);
162 underTest.doFilter(request, response, chain);
164 verify(response).sendRedirect("/sessions/unauthorized");
165 verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture());
166 AuthenticationException authenticationException = authenticationExceptionCaptor.getValue();
167 assertThat(authenticationException).hasMessage("Email john@email.com is already used");
168 assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider));
169 assertThat(authenticationException.getLogin()).isNull();
170 assertThat(authenticationException.getPublicMessage()).isEqualTo("Email john@email.com is already used");
171 verify(oAuthRedirection).delete(eq(request), eq(response));
173 verify(response).addCookie(cookieArgumentCaptor.capture());
174 Cookie cookie = cookieArgumentCaptor.getValue();
175 assertThat(cookie.getName()).isEqualTo("AUTHENTICATION-ERROR");
176 assertThat(cookie.getValue()).isEqualTo("Email%20john%40email.com%20is%20already%20used");
177 assertThat(cookie.getPath()).isEqualTo("/");
178 assertThat(cookie.isHttpOnly()).isFalse();
179 assertThat(cookie.getMaxAge()).isEqualTo(300);
180 assertThat(cookie.getSecure()).isFalse();
184 public void redirect_with_context_path_when_failing_because_of_UnauthorizedExceptionException() throws Exception {
185 when(request.getContextPath()).thenReturn("/sonarqube");
186 FailWithUnauthorizedExceptionIdProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider();
187 when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + identityProvider.getKey());
188 identityProviderRepository.addIdentityProvider(identityProvider);
190 underTest.doFilter(request, response, chain);
192 verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
193 verify(oAuthRedirection).delete(eq(request), eq(response));
197 public void redirect_when_failing_because_of_Exception() throws Exception {
198 FailWithIllegalStateException identityProvider = new FailWithIllegalStateException();
199 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
200 identityProviderRepository.addIdentityProvider(identityProvider);
202 underTest.doFilter(request, response, chain);
204 verify(response).sendRedirect("/sessions/unauthorized");
205 assertThat(logTester.logs(LoggerLevel.WARN)).containsExactlyInAnyOrder("Fail to callback authentication with 'failing'");
206 verify(oAuthRedirection).delete(eq(request), eq(response));
210 public void redirect_with_context_when_failing_because_of_Exception() throws Exception {
211 when(request.getContextPath()).thenReturn("/sonarqube");
212 FailWithIllegalStateException identityProvider = new FailWithIllegalStateException();
213 when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
214 identityProviderRepository.addIdentityProvider(identityProvider);
216 underTest.doFilter(request, response, chain);
218 verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
222 public void fail_when_no_oauth2_provider_provided() throws Exception {
223 when(request.getRequestURI()).thenReturn("/oauth2/callback");
225 underTest.doFilter(request, response, chain);
227 assertError("No provider key found in URI");
228 verifyZeroInteractions(authenticationEvent);
231 private void assertCallbackCalled(FakeOAuth2IdentityProvider oAuth2IdentityProvider) {
232 assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
233 assertThat(oAuth2IdentityProvider.isCallbackCalled()).isTrue();
236 private void assertError(String expectedError) throws Exception {
237 assertThat(logTester.logs(LoggerLevel.WARN)).contains(expectedError);
238 verify(response).sendRedirect("/sessions/unauthorized");
239 assertThat(oAuth2IdentityProvider.isInitCalled()).isFalse();
242 private static class FailWithUnauthorizedExceptionIdProvider extends FailingIdentityProvider {
244 public void callback(CallbackContext context) {
245 throw new UnauthorizedException("Email john@email.com is already used");
249 private static class FailWithIllegalStateException extends FailingIdentityProvider {
251 public void callback(CallbackContext context) {
252 throw new IllegalStateException("Failure !");
256 private static abstract class FailingIdentityProvider extends TestIdentityProvider implements OAuth2IdentityProvider {
257 FailingIdentityProvider() {
258 this.setKey("failing");
259 this.setName("Failing");
260 this.setEnabled(true);
264 public void init(InitContext context) {
270 * An extension of {@link FakeOAuth2IdentityProvider} that actually call {@link org.sonar.api.server.authentication.OAuth2IdentityProvider.CallbackContext#authenticate(UserIdentity)}.
272 private static class WellbehaveFakeOAuth2IdentityProvider extends FakeOAuth2IdentityProvider {
273 private final String login;
275 public WellbehaveFakeOAuth2IdentityProvider(String key, boolean enabled, String login) {
281 public void callback(CallbackContext context) {
282 super.callback(context);
283 context.authenticate(UserIdentity.builder()
284 .setProviderLogin(login)
285 .setEmail(login + "@toto.com")
286 .setName("name of " + login)