]> source.dussan.org Git - sonarqube.git/blob
6c45615d3bfdf7b87cf616ad4b436e09dbc1d315
[sonarqube.git] /
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.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.server.authentication.event.AuthenticationEvent;
37 import org.sonar.server.authentication.event.AuthenticationException;
38 import org.sonar.server.user.ThreadLocalUserSession;
39
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;
47
48 public class OAuth2CallbackFilterTest {
49
50   private static final String OAUTH2_PROVIDER_KEY = "github";
51   private static final String LOGIN = "foo";
52
53   @Rule
54   public LogTester logTester = new LogTester();
55   @Rule
56   public ExpectedException thrown = ExpectedException.none();
57   @Rule
58   public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule();
59
60   private OAuth2ContextFactory oAuth2ContextFactory = mock(OAuth2ContextFactory.class);
61
62   private HttpServletRequest request = mock(HttpServletRequest.class);
63   private HttpServletResponse response = mock(HttpServletResponse.class);
64   private FilterChain chain = mock(FilterChain.class);
65
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);
70
71   private ArgumentCaptor<AuthenticationException> authenticationExceptionCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
72   private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
73
74   private OAuth2CallbackFilter underTest = new OAuth2CallbackFilter(identityProviderRepository, oAuth2ContextFactory, authenticationEvent, oAuthRedirection,
75     threadLocalUserSession);
76
77   @Before
78   public void setUp() {
79     when(oAuth2ContextFactory.newCallback(request, response, oAuth2IdentityProvider)).thenReturn(mock(OAuth2IdentityProvider.CallbackContext.class));
80     when(request.getContextPath()).thenReturn("");
81   }
82
83   @Test
84   public void do_get_pattern() {
85     assertThat(underTest.doGetPattern()).isNotNull();
86   }
87
88   @Test
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);
95
96     underTest.doFilter(request, response, chain);
97
98     assertCallbackCalled(oAuth2IdentityProvider);
99     verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
100   }
101
102   @Test
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);
108
109     underTest.doFilter(request, response, chain);
110
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();
118   }
119
120   @Test
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);
126
127     underTest.doFilter(request, response, chain);
128
129     assertCallbackCalled(oAuth2IdentityProvider);
130     verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
131   }
132
133   @Test
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));
138
139     underTest.doFilter(request, response, chain);
140
141     assertError("Not an OAuth2IdentityProvider: class org.sonar.server.authentication.FakeBasicIdentityProvider");
142     verifyZeroInteractions(authenticationEvent);
143   }
144
145   @Test
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));
149
150     underTest.doFilter(request, response, chain);
151
152     assertError("Failed to retrieve IdentityProvider for key 'github'");
153     verifyZeroInteractions(authenticationEvent);
154   }
155
156   @Test
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);
161
162     underTest.doFilter(request, response, chain);
163
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));
172
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();
181   }
182
183   @Test
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);
189
190     underTest.doFilter(request, response, chain);
191
192     verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
193     verify(oAuthRedirection).delete(eq(request), eq(response));
194   }
195
196   @Test
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);
201
202     underTest.doFilter(request, response, chain);
203
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));
207   }
208
209   @Test
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);
215
216     underTest.doFilter(request, response, chain);
217
218     verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
219   }
220
221   @Test
222   public void fail_when_no_oauth2_provider_provided() throws Exception {
223     when(request.getRequestURI()).thenReturn("/oauth2/callback");
224
225     underTest.doFilter(request, response, chain);
226
227     assertError("No provider key found in URI");
228     verifyZeroInteractions(authenticationEvent);
229   }
230
231   private void assertCallbackCalled(FakeOAuth2IdentityProvider oAuth2IdentityProvider) {
232     assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
233     assertThat(oAuth2IdentityProvider.isCallbackCalled()).isTrue();
234   }
235
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();
240   }
241
242   private static class FailWithUnauthorizedExceptionIdProvider extends FailingIdentityProvider {
243     @Override
244     public void callback(CallbackContext context) {
245       throw new UnauthorizedException("Email john@email.com is already used");
246     }
247   }
248
249   private static class FailWithIllegalStateException extends FailingIdentityProvider {
250     @Override
251     public void callback(CallbackContext context) {
252       throw new IllegalStateException("Failure !");
253     }
254   }
255
256   private static abstract class FailingIdentityProvider extends TestIdentityProvider implements OAuth2IdentityProvider {
257     FailingIdentityProvider() {
258       this.setKey("failing");
259       this.setName("Failing");
260       this.setEnabled(true);
261     }
262
263     @Override
264     public void init(InitContext context) {
265       // Nothing to do
266     }
267   }
268
269   /**
270    * An extension of {@link FakeOAuth2IdentityProvider} that actually call {@link org.sonar.api.server.authentication.OAuth2IdentityProvider.CallbackContext#authenticate(UserIdentity)}.
271    */
272   private static class WellbehaveFakeOAuth2IdentityProvider extends FakeOAuth2IdentityProvider {
273     private final String login;
274
275     public WellbehaveFakeOAuth2IdentityProvider(String key, boolean enabled, String login) {
276       super(key, enabled);
277       this.login = login;
278     }
279
280     @Override
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)
287         .build());
288     }
289   }
290 }