You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OAuth2CallbackFilterTest.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. import javax.servlet.FilterChain;
  22. import javax.servlet.http.Cookie;
  23. import javax.servlet.http.HttpServletRequest;
  24. import javax.servlet.http.HttpServletResponse;
  25. import org.junit.Before;
  26. import org.junit.Rule;
  27. import org.junit.Test;
  28. import org.junit.rules.ExpectedException;
  29. import org.mockito.ArgumentCaptor;
  30. import org.sonar.api.server.authentication.OAuth2IdentityProvider;
  31. import org.sonar.api.server.authentication.UnauthorizedException;
  32. import org.sonar.api.server.authentication.UserIdentity;
  33. import org.sonar.api.utils.log.LogTester;
  34. import org.sonar.api.utils.log.LoggerLevel;
  35. import org.sonar.server.authentication.event.AuthenticationEvent;
  36. import org.sonar.server.authentication.event.AuthenticationException;
  37. import org.sonar.server.user.ThreadLocalUserSession;
  38. import static org.assertj.core.api.Assertions.assertThat;
  39. import static org.mockito.ArgumentMatchers.eq;
  40. import static org.mockito.Mockito.mock;
  41. import static org.mockito.Mockito.verify;
  42. import static org.mockito.Mockito.verifyZeroInteractions;
  43. import static org.mockito.Mockito.when;
  44. import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
  45. public class OAuth2CallbackFilterTest {
  46. private static final String OAUTH2_PROVIDER_KEY = "github";
  47. private static final String LOGIN = "foo";
  48. @Rule
  49. public LogTester logTester = new LogTester();
  50. @Rule
  51. public ExpectedException thrown = ExpectedException.none();
  52. @Rule
  53. public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule();
  54. private OAuth2ContextFactory oAuth2ContextFactory = mock(OAuth2ContextFactory.class);
  55. private HttpServletRequest request = mock(HttpServletRequest.class);
  56. private HttpServletResponse response = mock(HttpServletResponse.class);
  57. private FilterChain chain = mock(FilterChain.class);
  58. private FakeOAuth2IdentityProvider oAuth2IdentityProvider = new WellbehaveFakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true, LOGIN);
  59. private AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
  60. private OAuth2AuthenticationParameters oAuthRedirection = mock(OAuth2AuthenticationParameters.class);
  61. private ThreadLocalUserSession threadLocalUserSession = mock(ThreadLocalUserSession.class);
  62. private ArgumentCaptor<AuthenticationException> authenticationExceptionCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
  63. private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
  64. private OAuth2CallbackFilter underTest = new OAuth2CallbackFilter(identityProviderRepository, oAuth2ContextFactory, authenticationEvent, oAuthRedirection,
  65. threadLocalUserSession);
  66. @Before
  67. public void setUp() {
  68. when(oAuth2ContextFactory.newCallback(request, response, oAuth2IdentityProvider)).thenReturn(mock(OAuth2IdentityProvider.CallbackContext.class));
  69. when(request.getContextPath()).thenReturn("");
  70. }
  71. @Test
  72. public void do_get_pattern() {
  73. assertThat(underTest.doGetPattern()).isNotNull();
  74. }
  75. @Test
  76. public void do_filter_with_context() {
  77. when(request.getContextPath()).thenReturn("/sonarqube");
  78. when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
  79. identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
  80. when(threadLocalUserSession.hasSession()).thenReturn(true);
  81. when(threadLocalUserSession.getLogin()).thenReturn(LOGIN);
  82. underTest.doFilter(request, response, chain);
  83. assertCallbackCalled(oAuth2IdentityProvider);
  84. verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
  85. }
  86. @Test
  87. public void do_filter_with_context_no_log_if_provider_did_not_call_authenticate_on_context() {
  88. when(request.getContextPath()).thenReturn("/sonarqube");
  89. when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
  90. FakeOAuth2IdentityProvider identityProvider = new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true);
  91. identityProviderRepository.addIdentityProvider(identityProvider);
  92. underTest.doFilter(request, response, chain);
  93. assertCallbackCalled(identityProvider);
  94. verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture());
  95. AuthenticationException authenticationException = authenticationExceptionCaptor.getValue();
  96. assertThat(authenticationException).hasMessage("Plugin did not call authenticate");
  97. assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider));
  98. assertThat(authenticationException.getLogin()).isNull();
  99. assertThat(authenticationException.getPublicMessage()).isNull();
  100. }
  101. @Test
  102. public void do_filter_on_auth2_identity_provider() {
  103. when(request.getRequestURI()).thenReturn("/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
  104. identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
  105. when(threadLocalUserSession.hasSession()).thenReturn(true);
  106. when(threadLocalUserSession.getLogin()).thenReturn(LOGIN);
  107. underTest.doFilter(request, response, chain);
  108. assertCallbackCalled(oAuth2IdentityProvider);
  109. verify(authenticationEvent).loginSuccess(request, LOGIN, Source.oauth2(oAuth2IdentityProvider));
  110. }
  111. @Test
  112. public void fail_on_not_oauth2_provider() throws Exception {
  113. String providerKey = "openid";
  114. when(request.getRequestURI()).thenReturn("/oauth2/callback/" + providerKey);
  115. identityProviderRepository.addIdentityProvider(new FakeBasicIdentityProvider(providerKey, true));
  116. underTest.doFilter(request, response, chain);
  117. assertError("Not an OAuth2IdentityProvider: class org.sonar.server.authentication.FakeBasicIdentityProvider");
  118. verifyZeroInteractions(authenticationEvent);
  119. }
  120. @Test
  121. public void fail_on_disabled_provider() throws Exception {
  122. when(request.getRequestURI()).thenReturn("/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
  123. identityProviderRepository.addIdentityProvider(new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, false));
  124. underTest.doFilter(request, response, chain);
  125. assertError("Failed to retrieve IdentityProvider for key 'github'");
  126. verifyZeroInteractions(authenticationEvent);
  127. }
  128. @Test
  129. public void redirect_when_failing_because_of_UnauthorizedExceptionException() throws Exception {
  130. FailWithUnauthorizedExceptionIdProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider();
  131. when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
  132. identityProviderRepository.addIdentityProvider(identityProvider);
  133. underTest.doFilter(request, response, chain);
  134. verify(response).sendRedirect("/sessions/unauthorized");
  135. verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture());
  136. AuthenticationException authenticationException = authenticationExceptionCaptor.getValue();
  137. assertThat(authenticationException).hasMessage("Email john@email.com is already used");
  138. assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider));
  139. assertThat(authenticationException.getLogin()).isNull();
  140. assertThat(authenticationException.getPublicMessage()).isEqualTo("Email john@email.com is already used");
  141. verify(oAuthRedirection).delete(request, response);
  142. verify(response).addCookie(cookieArgumentCaptor.capture());
  143. Cookie cookie = cookieArgumentCaptor.getValue();
  144. assertThat(cookie.getName()).isEqualTo("AUTHENTICATION-ERROR");
  145. assertThat(cookie.getValue()).isEqualTo("Email%20john%40email.com%20is%20already%20used");
  146. assertThat(cookie.getPath()).isEqualTo("/");
  147. assertThat(cookie.isHttpOnly()).isFalse();
  148. assertThat(cookie.getMaxAge()).isEqualTo(300);
  149. assertThat(cookie.getSecure()).isFalse();
  150. }
  151. @Test
  152. public void redirect_with_context_path_when_failing_because_of_UnauthorizedExceptionException() throws Exception {
  153. when(request.getContextPath()).thenReturn("/sonarqube");
  154. FailWithUnauthorizedExceptionIdProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider();
  155. when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + identityProvider.getKey());
  156. identityProviderRepository.addIdentityProvider(identityProvider);
  157. underTest.doFilter(request, response, chain);
  158. verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
  159. verify(oAuthRedirection).delete(request, response);
  160. }
  161. @Test
  162. public void redirect_when_failing_because_of_Exception() throws Exception {
  163. FailWithIllegalStateException identityProvider = new FailWithIllegalStateException();
  164. when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
  165. identityProviderRepository.addIdentityProvider(identityProvider);
  166. underTest.doFilter(request, response, chain);
  167. verify(response).sendRedirect("/sessions/unauthorized");
  168. assertThat(logTester.logs(LoggerLevel.WARN)).containsExactlyInAnyOrder("Fail to callback authentication with 'failing'");
  169. verify(oAuthRedirection).delete(request, response);
  170. }
  171. @Test
  172. public void redirect_with_context_when_failing_because_of_Exception() throws Exception {
  173. when(request.getContextPath()).thenReturn("/sonarqube");
  174. FailWithIllegalStateException identityProvider = new FailWithIllegalStateException();
  175. when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
  176. identityProviderRepository.addIdentityProvider(identityProvider);
  177. underTest.doFilter(request, response, chain);
  178. verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
  179. }
  180. @Test
  181. public void fail_when_no_oauth2_provider_provided() throws Exception {
  182. when(request.getRequestURI()).thenReturn("/oauth2/callback");
  183. underTest.doFilter(request, response, chain);
  184. assertError("No provider key found in URI");
  185. verifyZeroInteractions(authenticationEvent);
  186. }
  187. private void assertCallbackCalled(FakeOAuth2IdentityProvider oAuth2IdentityProvider) {
  188. assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
  189. assertThat(oAuth2IdentityProvider.isCallbackCalled()).isTrue();
  190. }
  191. private void assertError(String expectedError) throws Exception {
  192. assertThat(logTester.logs(LoggerLevel.WARN)).contains(expectedError);
  193. verify(response).sendRedirect("/sessions/unauthorized");
  194. assertThat(oAuth2IdentityProvider.isInitCalled()).isFalse();
  195. }
  196. private static class FailWithUnauthorizedExceptionIdProvider extends FailingIdentityProvider {
  197. @Override
  198. public void callback(CallbackContext context) {
  199. throw new UnauthorizedException("Email john@email.com is already used");
  200. }
  201. }
  202. private static class FailWithIllegalStateException extends FailingIdentityProvider {
  203. @Override
  204. public void callback(CallbackContext context) {
  205. throw new IllegalStateException("Failure !");
  206. }
  207. }
  208. private static abstract class FailingIdentityProvider extends TestIdentityProvider implements OAuth2IdentityProvider {
  209. FailingIdentityProvider() {
  210. this.setKey("failing");
  211. this.setName("Failing");
  212. this.setEnabled(true);
  213. }
  214. @Override
  215. public void init(InitContext context) {
  216. // Nothing to do
  217. }
  218. }
  219. /**
  220. * An extension of {@link FakeOAuth2IdentityProvider} that actually call {@link org.sonar.api.server.authentication.OAuth2IdentityProvider.CallbackContext#authenticate(UserIdentity)}.
  221. */
  222. private static class WellbehaveFakeOAuth2IdentityProvider extends FakeOAuth2IdentityProvider {
  223. private final String login;
  224. public WellbehaveFakeOAuth2IdentityProvider(String key, boolean enabled, String login) {
  225. super(key, enabled);
  226. this.login = login;
  227. }
  228. @Override
  229. public void callback(CallbackContext context) {
  230. super.callback(context);
  231. context.authenticate(UserIdentity.builder()
  232. .setProviderLogin(login)
  233. .setEmail(login + "@toto.com")
  234. .setName("name of " + login)
  235. .build());
  236. }
  237. }
  238. }