3 * Copyright (C) 2009-2024 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 java.util.Objects;
23 import java.util.Optional;
26 import org.sonar.api.config.Configuration;
27 import org.sonar.api.impl.ws.StaticResources;
28 import org.sonar.api.server.ServerSide;
29 import org.sonar.api.server.http.HttpRequest;
30 import org.sonar.api.server.http.HttpResponse;
31 import org.sonar.api.web.UrlPattern;
32 import org.sonar.db.user.UserTokenDto;
33 import org.sonar.server.authentication.event.AuthenticationEvent;
34 import org.sonar.server.authentication.event.AuthenticationEvent.Source;
35 import org.sonar.server.authentication.event.AuthenticationException;
36 import org.sonar.server.user.ThreadLocalUserSession;
37 import org.sonar.server.user.TokenUserSession;
38 import org.sonar.server.user.UserSession;
40 import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
41 import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE;
42 import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY;
43 import static org.sonar.api.utils.DateUtils.formatDateTime;
44 import static org.sonar.server.authentication.AuthenticationError.handleAuthenticationError;
47 public class UserSessionInitializer {
50 * Key of attribute to be used for displaying user login
51 * in logs/access.log. The pattern to be configured
52 * in property sonar.web.accessLogs.pattern is "%reqAttribute{LOGIN}"
54 private static final String ACCESS_LOG_LOGIN = "LOGIN";
56 public static final String USER_LOGIN_MDC_KEY = "LOGIN";
58 private static final String SQ_AUTHENTICATION_TOKEN_EXPIRATION = "SonarQube-Authentication-Token-Expiration";
60 // SONAR-6546 these urls should be get from WebService
61 private static final Set<String> SKIPPED_URLS = Set.of(
62 "/batch/index", "/batch/file",
63 "/maintenance/*", "/setup/*",
64 "/sessions/*", "/oauth2/callback/*",
65 "/api/system/db_migration_status", "/api/system/status", "/api/system/migrate_db",
66 "/api/server/version",
67 "/api/users/identity_providers", "/api/l10n/index",
68 "/api/authentication/login", "/api/authentication/logout", "/api/authentication/validate",
69 "/api/project_badges/measure", "/api/project_badges/quality_gate",
70 "/api/settings/login_message");
72 private static final Set<String> URL_USING_PASSCODE = Set.of(
73 "/api/ce/info", "/api/ce/pause",
74 "/api/ce/resume", "/api/system/health",
75 "/api/system/analytics", "/api/system/migrate_es",
76 "/api/system/liveness",
77 "/api/monitoring/metrics");
79 private static final UrlPattern URL_PATTERN = UrlPattern.builder()
81 .excludes(StaticResources.patterns())
82 .excludes(SKIPPED_URLS)
85 private static final UrlPattern PASSCODE_URLS = UrlPattern.builder()
86 .includes(URL_USING_PASSCODE)
89 private final Configuration config;
90 private final ThreadLocalUserSession threadLocalSession;
91 private final AuthenticationEvent authenticationEvent;
92 private final RequestAuthenticator requestAuthenticator;
94 public UserSessionInitializer(Configuration config, ThreadLocalUserSession threadLocalSession, AuthenticationEvent authenticationEvent,
95 RequestAuthenticator requestAuthenticator) {
97 this.threadLocalSession = threadLocalSession;
98 this.authenticationEvent = authenticationEvent;
99 this.requestAuthenticator = requestAuthenticator;
102 public boolean initUserSession(HttpRequest request, HttpResponse response) {
103 MDC.put(USER_LOGIN_MDC_KEY, "-");
104 String path = request.getRequestURI().replaceFirst(request.getContextPath(), "");
106 // Do not set user session when url is excluded
107 if (URL_PATTERN.matches(path)) {
108 loadUserSession(request, response, PASSCODE_URLS.matches(path));
111 } catch (AuthenticationException e) {
112 authenticationEvent.loginFailure(request, e);
114 response.setStatus(HTTP_UNAUTHORIZED);
117 if (isNotLocalOrJwt(e.getSource())) {
118 // redirect to Unauthorized error page
119 handleAuthenticationError(e, request, response);
122 // Web pages should redirect to the index.html file
127 private static boolean isNotLocalOrJwt(Source source) {
128 AuthenticationEvent.Provider provider = source.getProvider();
129 return provider != AuthenticationEvent.Provider.LOCAL && provider != AuthenticationEvent.Provider.JWT;
132 private void loadUserSession(HttpRequest request, HttpResponse response, boolean urlSupportsSystemPasscode) {
133 UserSession session = requestAuthenticator.authenticate(request, response);
134 if (!session.isLoggedIn() && !urlSupportsSystemPasscode && config.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE)) {
135 // authentication is required
136 throw AuthenticationException.newBuilder()
137 .setSource(Source.local(AuthenticationEvent.Method.BASIC))
138 .setMessage("User must be authenticated")
141 threadLocalSession.set(session);
142 checkTokenUserSession(response, session);
143 request.setAttribute(ACCESS_LOG_LOGIN, Objects.toString(session.getLogin(), "-"));
144 MDC.put(USER_LOGIN_MDC_KEY, Objects.toString(session.getLogin(), "-"));
147 private static void checkTokenUserSession(HttpResponse response, UserSession session) {
148 if (session instanceof TokenUserSession tokenUserSession) {
149 UserTokenDto userTokenDto = tokenUserSession.getUserToken();
150 Optional.ofNullable(userTokenDto.getExpirationDate()).ifPresent(expirationDate -> response.addHeader(SQ_AUTHENTICATION_TOKEN_EXPIRATION, formatDateTime(expirationDate)));
154 public void removeUserSession() {
155 MDC.remove(USER_LOGIN_MDC_KEY);
156 threadLocalSession.unload();
159 private static boolean isWsUrl(String path) {
160 return path.startsWith("/batch/") || path.startsWith("/api/");