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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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.models.RepositoryModel;
  28. import com.gitblit.models.UserModel;
  29. import com.gitblit.utils.StringUtils;
  30. import dagger.ObjectGraph;
  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 IRuntimeManager runtimeManager;
  47. protected IRepositoryManager repositoryManager;
  48. @Override
  49. protected void inject(ObjectGraph dagger) {
  50. super.inject(dagger);
  51. this.runtimeManager = dagger.get(IRuntimeManager.class);
  52. this.repositoryManager = dagger.get(IRepositoryManager.class);
  53. }
  54. /**
  55. * Extract the repository name from the url.
  56. *
  57. * @param url
  58. * @return repository name
  59. */
  60. protected abstract String extractRepositoryName(String url);
  61. /**
  62. * Analyze the url and returns the action of the request.
  63. *
  64. * @param url
  65. * @return action of the request
  66. */
  67. protected abstract String getUrlRequestAction(String url);
  68. /**
  69. * Determine if a non-existing repository can be created using this filter.
  70. *
  71. * @return true if the filter allows repository creation
  72. */
  73. protected abstract boolean isCreationAllowed();
  74. /**
  75. * Determine if the action may be executed on the repository.
  76. *
  77. * @param repository
  78. * @param action
  79. * @return true if the action may be performed
  80. */
  81. protected abstract boolean isActionAllowed(RepositoryModel repository, String action);
  82. /**
  83. * Determine if the repository requires authentication.
  84. *
  85. * @param repository
  86. * @param action
  87. * @return true if authentication required
  88. */
  89. protected abstract boolean requiresAuthentication(RepositoryModel repository, String action);
  90. /**
  91. * Determine if the user can access the repository and perform the specified
  92. * action.
  93. *
  94. * @param repository
  95. * @param user
  96. * @param action
  97. * @return true if user may execute the action on the repository
  98. */
  99. protected abstract boolean canAccess(RepositoryModel repository, UserModel user, String action);
  100. /**
  101. * Allows a filter to create a repository, if one does not exist.
  102. *
  103. * @param user
  104. * @param repository
  105. * @param action
  106. * @return the repository model, if it is created, null otherwise
  107. */
  108. protected RepositoryModel createRepository(UserModel user, String repository, String action) {
  109. return null;
  110. }
  111. /**
  112. * doFilter does the actual work of preprocessing the request to ensure that
  113. * the user may proceed.
  114. *
  115. * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
  116. * javax.servlet.ServletResponse, javax.servlet.FilterChain)
  117. */
  118. @Override
  119. public void doFilter(final ServletRequest request, final ServletResponse response,
  120. final FilterChain chain) throws IOException, ServletException {
  121. HttpServletRequest httpRequest = (HttpServletRequest) request;
  122. HttpServletResponse httpResponse = (HttpServletResponse) response;
  123. String fullUrl = getFullUrl(httpRequest);
  124. String repository = extractRepositoryName(fullUrl);
  125. if (repositoryManager.isCollectingGarbage(repository)) {
  126. logger.info(MessageFormat.format("ARF: Rejecting request for {0}, busy collecting garbage!", repository));
  127. httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
  128. return;
  129. }
  130. // Determine if the request URL is restricted
  131. String fullSuffix = fullUrl.substring(repository.length());
  132. String urlRequestType = getUrlRequestAction(fullSuffix);
  133. UserModel user = getUser(httpRequest);
  134. // Load the repository model
  135. RepositoryModel model = repositoryManager.getRepositoryModel(repository);
  136. if (model == null) {
  137. if (isCreationAllowed()) {
  138. if (user == null) {
  139. // challenge client to provide credentials for creation. send 401.
  140. if (runtimeManager.isDebugMode()) {
  141. logger.info(MessageFormat.format("ARF: CREATE CHALLENGE {0}", fullUrl));
  142. }
  143. httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
  144. httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
  145. return;
  146. } else {
  147. // see if we can create a repository for this request
  148. model = createRepository(user, repository, urlRequestType);
  149. }
  150. }
  151. if (model == null) {
  152. // repository not found. send 404.
  153. logger.info(MessageFormat.format("ARF: {0} ({1})", fullUrl,
  154. HttpServletResponse.SC_NOT_FOUND));
  155. httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
  156. return;
  157. }
  158. }
  159. // Confirm that the action may be executed on the repository
  160. if (!isActionAllowed(model, urlRequestType)) {
  161. logger.info(MessageFormat.format("ARF: action {0} on {1} forbidden ({2})",
  162. urlRequestType, model, HttpServletResponse.SC_FORBIDDEN));
  163. httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
  164. return;
  165. }
  166. // Wrap the HttpServletRequest with the AccessRestrictionRequest which
  167. // overrides the servlet container user principal methods.
  168. // JGit requires either:
  169. //
  170. // 1. servlet container authenticated user
  171. // 2. http.receivepack = true in each repository's config
  172. //
  173. // Gitblit must conditionally authenticate users per-repository so just
  174. // enabling http.receivepack is insufficient.
  175. AuthenticatedRequest authenticatedRequest = new AuthenticatedRequest(httpRequest);
  176. if (user != null) {
  177. authenticatedRequest.setUser(user);
  178. }
  179. // BASIC authentication challenge and response processing
  180. if (!StringUtils.isEmpty(urlRequestType) && requiresAuthentication(model, urlRequestType)) {
  181. if (user == null) {
  182. // challenge client to provide credentials. send 401.
  183. if (runtimeManager.isDebugMode()) {
  184. logger.info(MessageFormat.format("ARF: CHALLENGE {0}", fullUrl));
  185. }
  186. httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
  187. httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
  188. return;
  189. } else {
  190. // check user access for request
  191. if (user.canAdmin() || canAccess(model, user, urlRequestType)) {
  192. // authenticated request permitted.
  193. // pass processing to the restricted servlet.
  194. newSession(authenticatedRequest, httpResponse);
  195. logger.info(MessageFormat.format("ARF: {0} ({1}) authenticated", fullUrl,
  196. HttpServletResponse.SC_CONTINUE));
  197. chain.doFilter(authenticatedRequest, httpResponse);
  198. return;
  199. }
  200. // valid user, but not for requested access. send 403.
  201. if (runtimeManager.isDebugMode()) {
  202. logger.info(MessageFormat.format("ARF: {0} forbidden to access {1}",
  203. user.username, fullUrl));
  204. }
  205. httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
  206. return;
  207. }
  208. }
  209. if (runtimeManager.isDebugMode()) {
  210. logger.info(MessageFormat.format("ARF: {0} ({1}) unauthenticated", fullUrl,
  211. HttpServletResponse.SC_CONTINUE));
  212. }
  213. // unauthenticated request permitted.
  214. // pass processing to the restricted servlet.
  215. chain.doFilter(authenticatedRequest, httpResponse);
  216. }
  217. }