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.

ServletFilter.java 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2018 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.api.web;
  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.Collection;
  24. import java.util.HashSet;
  25. import java.util.LinkedHashSet;
  26. import java.util.List;
  27. import java.util.Set;
  28. import java.util.function.Predicate;
  29. import java.util.stream.Collectors;
  30. import javax.servlet.Filter;
  31. import org.sonar.api.ExtensionPoint;
  32. import org.sonar.api.server.ServerSide;
  33. import static com.google.common.base.Preconditions.checkArgument;
  34. import static java.util.Arrays.asList;
  35. import static java.util.Collections.unmodifiableList;
  36. import static org.apache.commons.lang.StringUtils.substringBeforeLast;
  37. /**
  38. * @since 3.1
  39. */
  40. @ServerSide
  41. @ExtensionPoint
  42. public abstract class ServletFilter implements Filter {
  43. /**
  44. * Override to change URL. Default is /*
  45. */
  46. public UrlPattern doGetPattern() {
  47. return UrlPattern.builder().build();
  48. }
  49. public static final class UrlPattern {
  50. private static final String MATCH_ALL = "/*";
  51. private final List<String> inclusions;
  52. private final List<String> exclusions;
  53. private final Predicate<String>[] inclusionPredicates;
  54. private final Predicate<String>[] exclusionPredicates;
  55. private UrlPattern(Builder builder) {
  56. this.inclusions = unmodifiableList(new ArrayList<>(builder.inclusions));
  57. this.exclusions = unmodifiableList(new ArrayList<>(builder.exclusions));
  58. if (builder.inclusionPredicates.isEmpty()) {
  59. // because Stream#anyMatch() returns false if stream is empty
  60. this.inclusionPredicates = new Predicate[] {s -> true};
  61. } else {
  62. this.inclusionPredicates = builder.inclusionPredicates.stream().toArray(Predicate[]::new);
  63. }
  64. this.exclusionPredicates = builder.exclusionPredicates.stream().toArray(Predicate[]::new);
  65. }
  66. public boolean matches(String path) {
  67. return !Arrays.stream(exclusionPredicates).anyMatch(pattern -> pattern.test(path)) &&
  68. Arrays.stream(inclusionPredicates).anyMatch(pattern -> pattern.test(path));
  69. }
  70. /**
  71. * @since 6.0
  72. */
  73. public Collection<String> getInclusions() {
  74. return inclusions;
  75. }
  76. /**
  77. * @since 6.0
  78. */
  79. public Collection<String> getExclusions() {
  80. return exclusions;
  81. }
  82. /**
  83. * @deprecated replaced in version 6.0 by {@link #getInclusions()} and {@link #getExclusions()}
  84. * @throws IllegalStateException if at least one exclusion or more than one inclusions are defined
  85. */
  86. @Deprecated
  87. public String getUrl() {
  88. // Before 6.0, it was only possible to include one url
  89. if (exclusions.isEmpty() && inclusions.size() == 1) {
  90. return inclusions.get(0);
  91. }
  92. throw new IllegalStateException("this method is deprecated and should not be used anymore");
  93. }
  94. public String label() {
  95. return "UrlPattern{" +
  96. "inclusions=[" + convertPatternsToString(inclusions) + "]" +
  97. ", exclusions=[" + convertPatternsToString(exclusions) + "]" +
  98. '}';
  99. }
  100. private static String convertPatternsToString(List<String> input) {
  101. StringBuilder output = new StringBuilder();
  102. if (input.isEmpty()) {
  103. return "";
  104. }
  105. if (input.size() == 1) {
  106. return output.append(input.get(0)).toString();
  107. }
  108. return output.append(input.get(0)).append(", ...").toString();
  109. }
  110. /**
  111. * Defines only a single inclusion pattern. This is a shortcut for {@code builder().includes(inclusionPattern).build()}.
  112. */
  113. public static UrlPattern create(String inclusionPattern) {
  114. return builder().includes(inclusionPattern).build();
  115. }
  116. /**
  117. * @since 6.0
  118. */
  119. public static Builder builder() {
  120. return new Builder();
  121. }
  122. /**
  123. * @since 6.0
  124. */
  125. public static class Builder {
  126. private static final String WILDCARD_CHAR = "*";
  127. private static final Collection<String> STATIC_RESOURCES = unmodifiableList(asList(
  128. "*.css", "*.css.map", "*.ico", "*.png", "*.jpg", "*.jpeg", "*.gif", "*.svg", "*.js", "*.js.map", "*.pdf", "/json/*",
  129. "/static/*", "/robots.txt", "/favicon.ico", "/apple-touch-icon*", "/mstile*"));
  130. private final Set<String> inclusions = new LinkedHashSet<>();
  131. private final Set<String> exclusions = new LinkedHashSet<>();
  132. private final Set<Predicate<String>> inclusionPredicates = new HashSet<>();
  133. private final Set<Predicate<String>> exclusionPredicates = new HashSet<>();
  134. private Builder() {
  135. }
  136. public static Collection<String> staticResourcePatterns() {
  137. return STATIC_RESOURCES;
  138. }
  139. /**
  140. * Add inclusion patterns. Supported formats are:
  141. * <ul>
  142. * <li>path prefixed by / and ended by * or /*, for example "/api/foo/*", to match all paths "/api/foo" and "api/api/foo/something/else"</li>
  143. * <li>path prefixed by / and ended by .*, for example "/api/foo.*", to match exact path "/api/foo" with any suffix like "/api/foo.protobuf"</li>
  144. * <li>path prefixed by *, for example "*\/foo", to match all paths "/api/foo" and "something/else/foo"</li>
  145. * <li>path with leading slash and no wildcard, for example "/api/foo", to match exact path "/api/foo"</li>
  146. * </ul>
  147. */
  148. public Builder includes(String... includePatterns) {
  149. return includes(asList(includePatterns));
  150. }
  151. /**
  152. * Add exclusion patterns. See format described in {@link #includes(String...)}
  153. */
  154. public Builder includes(Collection<String> includePatterns) {
  155. this.inclusions.addAll(includePatterns);
  156. this.inclusionPredicates.addAll(includePatterns.stream()
  157. .filter(pattern -> !MATCH_ALL.equals(pattern))
  158. .map(Builder::compile)
  159. .collect(Collectors.toList()));
  160. return this;
  161. }
  162. public Builder excludes(String... excludePatterns) {
  163. return excludes(asList(excludePatterns));
  164. }
  165. public Builder excludes(Collection<String> excludePatterns) {
  166. this.exclusions.addAll(excludePatterns);
  167. this.exclusionPredicates.addAll(excludePatterns.stream()
  168. .map(Builder::compile)
  169. .collect(Collectors.toList()));
  170. return this;
  171. }
  172. public UrlPattern build() {
  173. return new UrlPattern(this);
  174. }
  175. private static Predicate<String> compile(String pattern) {
  176. int countStars = pattern.length() - pattern.replace(WILDCARD_CHAR, "").length();
  177. if (countStars == 0) {
  178. checkArgument(pattern.startsWith("/"), "URL pattern must start with slash '/': %s", pattern);
  179. return url -> url.equals(pattern);
  180. }
  181. checkArgument(countStars == 1, "URL pattern accepts only zero or one wildcard character '*': %s", pattern);
  182. if (pattern.charAt(0) == '/') {
  183. checkArgument(pattern.endsWith(WILDCARD_CHAR), "URL pattern must end with wildcard character '*': %s", pattern);
  184. if (pattern.endsWith("/*")) {
  185. String path = pattern.substring(0, pattern.length() - "/*".length());
  186. return url -> url.startsWith(path);
  187. }
  188. if (pattern.endsWith(".*")) {
  189. String path = pattern.substring(0, pattern.length() - ".*".length());
  190. return url -> substringBeforeLast(url, ".").equals(path);
  191. }
  192. String path = pattern.substring(0, pattern.length() - "*".length());
  193. return url -> url.startsWith(path);
  194. }
  195. checkArgument(pattern.startsWith(WILDCARD_CHAR), "URL pattern must start with wildcard character '*': %s", pattern);
  196. // remove the leading *
  197. String path = pattern.substring(1);
  198. return url -> url.endsWith(path);
  199. }
  200. }
  201. }
  202. }