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.

UserSessionInitializer.java 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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 com.google.common.collect.ImmutableSet;
  22. import java.util.Set;
  23. import javax.servlet.http.HttpServletRequest;
  24. import javax.servlet.http.HttpServletResponse;
  25. import org.sonar.api.config.Configuration;
  26. import org.sonar.api.server.ServerSide;
  27. import org.sonar.api.web.ServletFilter.UrlPattern;
  28. import org.sonar.server.authentication.event.AuthenticationEvent;
  29. import org.sonar.server.authentication.event.AuthenticationEvent.Source;
  30. import org.sonar.server.authentication.event.AuthenticationException;
  31. import org.sonar.server.user.ThreadLocalUserSession;
  32. import org.sonar.server.user.UserSession;
  33. import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
  34. import static org.apache.commons.lang.StringUtils.defaultString;
  35. import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE;
  36. import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY;
  37. import static org.sonar.api.web.ServletFilter.UrlPattern.Builder.staticResourcePatterns;
  38. import static org.sonar.server.authentication.AuthenticationError.handleAuthenticationError;
  39. @ServerSide
  40. public class UserSessionInitializer {
  41. /**
  42. * Key of attribute to be used for displaying user login
  43. * in logs/access.log. The pattern to be configured
  44. * in property sonar.web.accessLogs.pattern is "%reqAttribute{LOGIN}"
  45. */
  46. private static final String ACCESS_LOG_LOGIN = "LOGIN";
  47. // SONAR-6546 these urls should be get from WebService
  48. private static final Set<String> SKIPPED_URLS = ImmutableSet.of(
  49. "/batch/index", "/batch/file",
  50. "/maintenance/*", "/setup/*",
  51. "/sessions/*", "/oauth2/callback/*",
  52. "/api/system/db_migration_status", "/api/system/status", "/api/system/migrate_db",
  53. "/api/server/version",
  54. "/api/users/identity_providers", "/api/l10n/index",
  55. "/api/authentication/login", "/api/authentication/logout", "/api/authentication/validate");
  56. private static final Set<String> URL_USING_PASSCODE = ImmutableSet.of(
  57. "/api/ce/info", "/api/ce/pause", "/api/ce/resume", "/api/system/health", "/api/system/analytics", "/api/system/migrate_es");
  58. private static final UrlPattern URL_PATTERN = UrlPattern.builder()
  59. .includes("/*")
  60. .excludes(staticResourcePatterns())
  61. .excludes(SKIPPED_URLS)
  62. .build();
  63. private static final UrlPattern PASSCODE_URLS = UrlPattern.builder()
  64. .includes(URL_USING_PASSCODE)
  65. .build();
  66. private final Configuration config;
  67. private final ThreadLocalUserSession threadLocalSession;
  68. private final AuthenticationEvent authenticationEvent;
  69. private final RequestAuthenticator requestAuthenticator;
  70. public UserSessionInitializer(Configuration config, ThreadLocalUserSession threadLocalSession, AuthenticationEvent authenticationEvent,
  71. RequestAuthenticator requestAuthenticator) {
  72. this.config = config;
  73. this.threadLocalSession = threadLocalSession;
  74. this.authenticationEvent = authenticationEvent;
  75. this.requestAuthenticator = requestAuthenticator;
  76. }
  77. public boolean initUserSession(HttpServletRequest request, HttpServletResponse response) {
  78. String path = request.getRequestURI().replaceFirst(request.getContextPath(), "");
  79. try {
  80. // Do not set user session when url is excluded
  81. if (URL_PATTERN.matches(path)) {
  82. loadUserSession(request, response, PASSCODE_URLS.matches(path));
  83. }
  84. return true;
  85. } catch (AuthenticationException e) {
  86. authenticationEvent.loginFailure(request, e);
  87. if (isWsUrl(path)) {
  88. response.setStatus(HTTP_UNAUTHORIZED);
  89. return false;
  90. }
  91. if (isNotLocalOrJwt(e.getSource())) {
  92. // redirect to Unauthorized error page
  93. handleAuthenticationError(e, request, response);
  94. return false;
  95. }
  96. // Web pages should redirect to the index.html file
  97. return true;
  98. }
  99. }
  100. private static boolean isNotLocalOrJwt(Source source) {
  101. AuthenticationEvent.Provider provider = source.getProvider();
  102. return provider != AuthenticationEvent.Provider.LOCAL && provider != AuthenticationEvent.Provider.JWT;
  103. }
  104. private void loadUserSession(HttpServletRequest request, HttpServletResponse response, boolean urlSupportsSystemPasscode) {
  105. UserSession session = requestAuthenticator.authenticate(request, response);
  106. if (!session.isLoggedIn() && !urlSupportsSystemPasscode && config.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE)) {
  107. // authentication is required
  108. throw AuthenticationException.newBuilder()
  109. .setSource(Source.local(AuthenticationEvent.Method.BASIC))
  110. .setMessage("User must be authenticated")
  111. .build();
  112. }
  113. threadLocalSession.set(session);
  114. request.setAttribute(ACCESS_LOG_LOGIN, defaultString(session.getLogin(), "-"));
  115. }
  116. public void removeUserSession() {
  117. threadLocalSession.unload();
  118. }
  119. private static boolean isWsUrl(String path) {
  120. return path.startsWith("/batch/") || path.startsWith("/api/");
  121. }
  122. }