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 com.google.common.base.Strings;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.reflect.TypeToken;
26 import java.io.UnsupportedEncodingException;
27 import java.nio.file.Path;
28 import java.util.HashMap;
30 import java.util.Optional;
31 import java.util.regex.Pattern;
32 import javax.annotation.Nullable;
33 import org.sonar.api.server.http.Cookie;
34 import org.sonar.api.server.http.HttpRequest;
35 import org.sonar.api.server.http.HttpResponse;
37 import static java.net.URLDecoder.decode;
38 import static java.nio.charset.StandardCharsets.UTF_8;
39 import static java.util.Optional.empty;
40 import static org.sonar.server.authentication.AuthenticationRedirection.encodeMessage;
41 import static org.sonar.server.authentication.Cookies.findCookie;
42 import static org.sonar.server.authentication.Cookies.newCookieBuilder;
44 public class OAuth2AuthenticationParametersImpl implements OAuth2AuthenticationParameters {
46 private static final String AUTHENTICATION_COOKIE_NAME = "AUTH-PARAMS";
47 private static final int FIVE_MINUTES_IN_SECONDS = 5 * 60;
48 private static final Pattern VALID_RETURN_TO = Pattern.compile("^/\\w.*");
51 * The HTTP parameter that contains the path where the user should be redirect to.
52 * Please note that the web context is included.
54 private static final String RETURN_TO_PARAMETER = "return_to";
56 private static final TypeToken<Map<String, String>> JSON_MAP_TYPE = new TypeToken<>() {
60 public void init(HttpRequest request, HttpResponse response) {
61 String returnTo = request.getParameter(RETURN_TO_PARAMETER);
62 Map<String, String> parameters = new HashMap<>();
63 Optional<String> sanitizeRedirectUrl = sanitizeRedirectUrl(returnTo);
64 sanitizeRedirectUrl.ifPresent(s -> parameters.put(RETURN_TO_PARAMETER, s));
65 if (parameters.isEmpty()) {
68 response.addCookie(newCookieBuilder(request)
69 .setName(AUTHENTICATION_COOKIE_NAME)
70 .setValue(toJson(parameters))
72 .setExpiry(FIVE_MINUTES_IN_SECONDS)
77 public Optional<String> getReturnTo(HttpRequest request) {
78 return getParameter(request, RETURN_TO_PARAMETER)
79 .flatMap(OAuth2AuthenticationParametersImpl::sanitizeRedirectUrl);
82 private static Optional<String> getParameter(HttpRequest request, String parameterKey) {
83 Optional<Cookie> cookie = findCookie(AUTHENTICATION_COOKIE_NAME, request);
84 if (cookie.isEmpty()) {
88 Map<String, String> parameters = fromJson(cookie.get().getValue());
89 if (parameters.isEmpty()) {
92 return Optional.ofNullable(parameters.get(parameterKey));
96 public void delete(HttpRequest request, HttpResponse response) {
97 response.addCookie(newCookieBuilder(request)
98 .setName(AUTHENTICATION_COOKIE_NAME)
105 private static String toJson(Map<String, String> map) {
106 Gson gson = new GsonBuilder().create();
107 return encodeMessage(gson.toJson(map));
110 private static Map<String, String> fromJson(String json) {
111 Gson gson = new GsonBuilder().create();
113 return gson.fromJson(decode(json, UTF_8.name()), JSON_MAP_TYPE);
114 } catch (UnsupportedEncodingException e) {
115 throw new IllegalStateException(e);
120 * This sanitization has been inspired by 'IsUrlLocalToHost()' method in
121 * https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/preventing-open-redirection-attacks
123 private static Optional<String> sanitizeRedirectUrl(@Nullable String url) {
124 if (Strings.isNullOrEmpty(url)) {
128 String trimmedUrl = url.trim();
129 boolean isValidUrl = VALID_RETURN_TO.matcher(trimmedUrl).matches();
134 Path sanitizedPath = escapePathTraversalChars(trimmedUrl);
135 return Optional.of(sanitizedPath.toString());
138 private static Path escapePathTraversalChars(String sanitizedUrl) {
139 return Path.of(sanitizedUrl).normalize();