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.

AccessRestrictionFilter.java 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /*
  2. * Copyright 2011 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.servlet;
  17. import java.io.IOException;
  18. import java.text.MessageFormat;
  19. import javax.servlet.FilterChain;
  20. import javax.servlet.ServletException;
  21. import javax.servlet.ServletRequest;
  22. import javax.servlet.ServletResponse;
  23. import javax.servlet.http.HttpServletRequest;
  24. import javax.servlet.http.HttpServletResponse;
  25. import com.gitblit.manager.IRepositoryManager;
  26. import com.gitblit.manager.IRuntimeManager;
  27. import com.gitblit.manager.IAuthenticationManager;
  28. import com.gitblit.models.RepositoryModel;
  29. import com.gitblit.models.UserModel;
  30. import com.gitblit.utils.StringUtils;
  31. /**
  32. * The AccessRestrictionFilter is an AuthenticationFilter that confirms that the
  33. * requested repository can be accessed by the anonymous or named user.
  34. *
  35. * The filter extracts the name of the repository from the url and determines if
  36. * the requested action for the repository requires a Basic authentication
  37. * prompt. If authentication is required and no credentials are stored in the
  38. * "Authorization" header, then a basic authentication challenge is issued.
  39. *
  40. * http://en.wikipedia.org/wiki/Basic_access_authentication
  41. *
  42. * @author James Moger
  43. *
  44. */
  45. public abstract class AccessRestrictionFilter extends AuthenticationFilter {
  46. protected final IRuntimeManager runtimeManager;
  47. protected final IRepositoryManager repositoryManager;
  48. protected AccessRestrictionFilter(
  49. IRuntimeManager runtimeManager,
  50. IAuthenticationManager authenticationManager,
  51. IRepositoryManager repositoryManager) {
  52. super(authenticationManager);
  53. this.runtimeManager = runtimeManager;
  54. this.repositoryManager = repositoryManager;
  55. }
  56. /**
  57. * Extract the repository name from the url.
  58. *
  59. * @param url
  60. * @return repository name
  61. */
  62. protected abstract String extractRepositoryName(String url);
  63. /**
  64. * Analyze the url and returns the action of the request.
  65. *
  66. * @param url
  67. * @return action of the request
  68. */
  69. protected abstract String getUrlRequestAction(String url);
  70. /**
  71. * Determine if a non-existing repository can be created using this filter.
  72. *
  73. * @return true if the filter allows repository creation
  74. */
  75. protected abstract boolean isCreationAllowed();
  76. /**
  77. * Determine if the action may be executed on the repository.
  78. *
  79. * @param repository
  80. * @param action
  81. * @return true if the action may be performed
  82. */
  83. protected abstract boolean isActionAllowed(RepositoryModel repository, String action);
  84. /**
  85. * Determine if the repository requires authentication.
  86. *
  87. * @param repository
  88. * @param action
  89. * @return true if authentication required
  90. */
  91. protected abstract boolean requiresAuthentication(RepositoryModel repository, String action);
  92. /**
  93. * Determine if the user can access the repository and perform the specified
  94. * action.
  95. *
  96. * @param repository
  97. * @param user
  98. * @param action
  99. * @return true if user may execute the action on the repository
  100. */
  101. protected abstract boolean canAccess(RepositoryModel repository, UserModel user, String action);
  102. /**
  103. * Allows a filter to create a repository, if one does not exist.
  104. *
  105. * @param user
  106. * @param repository
  107. * @param action
  108. * @return the repository model, if it is created, null otherwise
  109. */
  110. protected RepositoryModel createRepository(UserModel user, String repository, String action) {
  111. return null;
  112. }
  113. /**
  114. * doFilter does the actual work of preprocessing the request to ensure that
  115. * the user may proceed.
  116. *
  117. * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
  118. * javax.servlet.ServletResponse, javax.servlet.FilterChain)
  119. */
  120. @Override
  121. public void doFilter(final ServletRequest request, final ServletResponse response,
  122. final FilterChain chain) throws IOException, ServletException {
  123. HttpServletRequest httpRequest = (HttpServletRequest) request;
  124. HttpServletResponse httpResponse = (HttpServletResponse) response;
  125. String fullUrl = getFullUrl(httpRequest);
  126. String repository = extractRepositoryName(fullUrl);
  127. if (repositoryManager.isCollectingGarbage(repository)) {
  128. logger.info(MessageFormat.format("ARF: Rejecting request for {0}, busy collecting garbage!", repository));
  129. httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
  130. return;
  131. }
  132. // Determine if the request URL is restricted
  133. String fullSuffix = fullUrl.substring(repository.length());
  134. String urlRequestType = getUrlRequestAction(fullSuffix);
  135. UserModel user = getUser(httpRequest);
  136. // Load the repository model
  137. RepositoryModel model = repositoryManager.getRepositoryModel(repository);
  138. if (model == null) {
  139. if (isCreationAllowed()) {
  140. if (user == null) {
  141. // challenge client to provide credentials for creation. send 401.
  142. if (runtimeManager.isDebugMode()) {
  143. logger.info(MessageFormat.format("ARF: CREATE CHALLENGE {0}", fullUrl));
  144. }
  145. httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
  146. httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
  147. return;
  148. } else {
  149. // see if we can create a repository for this request
  150. model = createRepository(user, repository, urlRequestType);
  151. }
  152. }
  153. if (model == null) {
  154. // repository not found. send 404.
  155. logger.info(MessageFormat.format("ARF: {0} ({1})", fullUrl,
  156. HttpServletResponse.SC_NOT_FOUND));
  157. httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
  158. return;
  159. }
  160. }
  161. // Confirm that the action may be executed on the repository
  162. if (!isActionAllowed(model, urlRequestType)) {
  163. logger.info(MessageFormat.format("ARF: action {0} on {1} forbidden ({2})",
  164. urlRequestType, model, HttpServletResponse.SC_FORBIDDEN));
  165. httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
  166. return;
  167. }
  168. // Wrap the HttpServletRequest with the AccessRestrictionRequest which
  169. // overrides the servlet container user principal methods.
  170. // JGit requires either:
  171. //
  172. // 1. servlet container authenticated user
  173. // 2. http.receivepack = true in each repository's config
  174. //
  175. // Gitblit must conditionally authenticate users per-repository so just
  176. // enabling http.receivepack is insufficient.
  177. AuthenticatedRequest authenticatedRequest = new AuthenticatedRequest(httpRequest);
  178. if (user != null) {
  179. authenticatedRequest.setUser(user);
  180. }
  181. // BASIC authentication challenge and response processing
  182. if (!StringUtils.isEmpty(urlRequestType) && requiresAuthentication(model, urlRequestType)) {
  183. if (user == null) {
  184. // challenge client to provide credentials. send 401.
  185. if (runtimeManager.isDebugMode()) {
  186. logger.info(MessageFormat.format("ARF: CHALLENGE {0}", fullUrl));
  187. }
  188. httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
  189. httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
  190. return;
  191. } else {
  192. // check user access for request
  193. if (user.canAdmin() || canAccess(model, user, urlRequestType)) {
  194. // authenticated request permitted.
  195. // pass processing to the restricted servlet.
  196. newSession(authenticatedRequest, httpResponse);
  197. logger.info(MessageFormat.format("ARF: {0} ({1}) authenticated", fullUrl,
  198. HttpServletResponse.SC_CONTINUE));
  199. chain.doFilter(authenticatedRequest, httpResponse);
  200. return;
  201. }
  202. // valid user, but not for requested access. send 403.
  203. if (runtimeManager.isDebugMode()) {
  204. logger.info(MessageFormat.format("ARF: {0} forbidden to access {1}",
  205. user.username, fullUrl));
  206. }
  207. httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
  208. return;
  209. }
  210. }
  211. if (runtimeManager.isDebugMode()) {
  212. logger.info(MessageFormat.format("ARF: {0} ({1}) unauthenticated", fullUrl,
  213. HttpServletResponse.SC_CONTINUE));
  214. }
  215. // unauthenticated request permitted.
  216. // pass processing to the restricted servlet.
  217. chain.doFilter(authenticatedRequest, httpResponse);
  218. }
  219. }