]> source.dussan.org Git - sonarqube.git/blob
a42f29cf0595cee25d760079b781805bc50335b4
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2019 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.server.authentication;
21
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;
41
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;
50
51 public class OAuth2CallbackFilterTest {
52
53   private static final String OAUTH2_PROVIDER_KEY = "github";
54   private static final String LOGIN = "foo";
55
56   @Rule
57   public LogTester logTester = new LogTester();
58   @Rule
59   public ExpectedException thrown = ExpectedException.none();
60   @Rule
61   public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule();
62
63   private OAuth2ContextFactory oAuth2ContextFactory = mock(OAuth2ContextFactory.class);
64
65   private HttpServletRequest request = mock(HttpServletRequest.class);
66   private HttpServletResponse response = mock(HttpServletResponse.class);
67   private FilterChain chain = mock(FilterChain.class);
68
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);
73
74   private ArgumentCaptor<AuthenticationException> authenticationExceptionCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
75   private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
76
77   private OAuth2CallbackFilter underTest = new OAuth2CallbackFilter(identityProviderRepository, oAuth2ContextFactory, authenticationEvent, oAuthRedirection,
78     threadLocalUserSession);
79
80   @Before
81   public void setUp() throws Exception {
82     when(oAuth2ContextFactory.newCallback(request, response, oAuth2IdentityProvider)).thenReturn(mock(OAuth2IdentityProvider.CallbackContext.class));
83     when(request.getContextPath()).thenReturn("");
84   }
85
86   @Test
87   public void do_get_pattern() {
88     assertThat(underTest.doGetPattern()).isNotNull();
89   }
90
91   @Test
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);
98
99     underTest.doFilter(request, response, chain);
100
101     assertCallbackCalled(oAuth2IdentityProvider);
102     verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
103   }
104
105   @Test
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);
111
112     underTest.doFilter(request, response, chain);
113
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();
121   }
122
123   @Test
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);
129
130     underTest.doFilter(request, response, chain);
131
132     assertCallbackCalled(oAuth2IdentityProvider);
133     verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
134   }
135
136   @Test
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));
141
142     underTest.doFilter(request, response, chain);
143
144     assertError("Not an OAuth2IdentityProvider: class org.sonar.server.authentication.FakeBasicIdentityProvider");
145     verifyZeroInteractions(authenticationEvent);
146   }
147
148   @Test
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));
152
153     underTest.doFilter(request, response, chain);
154
155     assertError("Failed to retrieve IdentityProvider for key 'github'");
156     verifyZeroInteractions(authenticationEvent);
157   }
158
159   @Test
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);
164
165     underTest.doFilter(request, response, chain);
166
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));
175
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();
184   }
185
186   @Test
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);
192
193     underTest.doFilter(request, response, chain);
194
195     verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
196     verify(oAuthRedirection).delete(eq(request), eq(response));
197   }
198
199   @Test
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);
204
205     underTest.doFilter(request, response, chain);
206
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));
210   }
211
212   @Test
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);
218
219     underTest.doFilter(request, response, chain);
220
221     verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
222   }
223
224   @Test
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);
230
231     underTest.doFilter(request, response, chain);
232
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();
243   }
244
245   @Test
246   public void fail_when_no_oauth2_provider_provided() throws Exception {
247     when(request.getRequestURI()).thenReturn("/oauth2/callback");
248
249     underTest.doFilter(request, response, chain);
250
251     assertError("No provider key found in URI");
252     verifyZeroInteractions(authenticationEvent);
253   }
254
255   private void assertCallbackCalled(FakeOAuth2IdentityProvider oAuth2IdentityProvider) {
256     assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
257     assertThat(oAuth2IdentityProvider.isCallbackCalled()).isTrue();
258   }
259
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();
264   }
265
266   private static class FailWithUnauthorizedExceptionIdProvider extends FailingIdentityProvider {
267     @Override
268     public void callback(CallbackContext context) {
269       throw new UnauthorizedException("Email john@email.com is already used");
270     }
271   }
272
273   private static class FailWithIllegalStateException extends FailingIdentityProvider {
274     @Override
275     public void callback(CallbackContext context) {
276       throw new IllegalStateException("Failure !");
277     }
278   }
279
280   private static class FailWithEmailAlreadyExistException extends FailingIdentityProvider {
281
282     private final UserDto existingUser;
283
284     public FailWithEmailAlreadyExistException(UserDto existingUser) {
285       this.existingUser = existingUser;
286     }
287
288     @Override
289     public void callback(CallbackContext context) {
290       throw new EmailAlreadyExistsRedirectionException(existingUser.getEmail(), existingUser, UserIdentity.builder()
291         .setProviderLogin("john.github")
292         .setLogin("john.github")
293         .setName(existingUser.getName())
294         .setEmail(existingUser.getEmail())
295         .build(), this);
296     }
297   }
298
299   private static abstract class FailingIdentityProvider extends TestIdentityProvider implements OAuth2IdentityProvider {
300     FailingIdentityProvider() {
301       this.setKey("failing");
302       this.setName("Failing");
303       this.setEnabled(true);
304     }
305
306     @Override
307     public void init(InitContext context) {
308       // Nothing to do
309     }
310   }
311
312   /**
313    * An extension of {@link FakeOAuth2IdentityProvider} that actually call {@link org.sonar.api.server.authentication.OAuth2IdentityProvider.CallbackContext#authenticate(UserIdentity)}.
314    */
315   private static class WellbehaveFakeOAuth2IdentityProvider extends FakeOAuth2IdentityProvider {
316     private final String login;
317
318     public WellbehaveFakeOAuth2IdentityProvider(String key, boolean enabled, String login) {
319       super(key, enabled);
320       this.login = login;
321     }
322
323     @Override
324     public void callback(CallbackContext context) {
325       super.callback(context);
326       context.authenticate(UserIdentity.builder()
327         .setLogin(login)
328         .setProviderLogin(login)
329         .setEmail(login + "@toto.com")
330         .setName("name of " + login)
331         .build());
332     }
333   }
334 }