James Moger
2012-10-22 eba89539a29deba954035056437279088c3e047b
commit | author | age
8c9a20 1 /*
JM 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;
17
18 import java.io.IOException;
19 import java.text.MessageFormat;
20
21 import javax.servlet.FilterChain;
22 import javax.servlet.ServletException;
23 import javax.servlet.ServletRequest;
24 import javax.servlet.ServletResponse;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27
28 import com.gitblit.models.RepositoryModel;
29 import com.gitblit.models.UserModel;
30 import com.gitblit.utils.StringUtils;
31
32 /**
ca9d0f 33  * The AccessRestrictionFilter is an AuthenticationFilter that confirms that the
JM 34  * requested repository can be accessed by the anonymous or named user.
892570 35  * 
JM 36  * The filter extracts the name of the repository from the url and determines if
37  * the requested action for the repository requires a Basic authentication
38  * prompt. If authentication is required and no credentials are stored in the
39  * "Authorization" header, then a basic authentication challenge is issued.
8c9a20 40  * 
JM 41  * http://en.wikipedia.org/wiki/Basic_access_authentication
892570 42  * 
JM 43  * @author James Moger
44  * 
8c9a20 45  */
ca9d0f 46 public abstract class AccessRestrictionFilter extends AuthenticationFilter {
8c9a20 47
892570 48     /**
JM 49      * Extract the repository name from the url.
50      * 
51      * @param url
52      * @return repository name
53      */
8c9a20 54     protected abstract String extractRepositoryName(String url);
JM 55
892570 56     /**
JM 57      * Analyze the url and returns the action of the request.
58      * 
59      * @param url
60      * @return action of the request
61      */
62     protected abstract String getUrlRequestAction(String url);
8c9a20 63
892570 64     /**
72cb19 65      * Determine if a non-existing repository can be created using this filter.
JM 66      *  
67      * @return true if the filter allows repository creation
68      */
69     protected abstract boolean isCreationAllowed();
70     
71     /**
b74031 72      * Determine if the action may be executed on the repository.
JM 73      * 
74      * @param repository
75      * @param action
76      * @return true if the action may be performed
77      */
78     protected abstract boolean isActionAllowed(RepositoryModel repository, String action);
79
80     /**
892570 81      * Determine if the repository requires authentication.
JM 82      * 
83      * @param repository
3f8cd4 84      * @param action
892570 85      * @return true if authentication required
JM 86      */
3f8cd4 87     protected abstract boolean requiresAuthentication(RepositoryModel repository, String action);
8c9a20 88
892570 89     /**
JM 90      * Determine if the user can access the repository and perform the specified
91      * action.
92      * 
93      * @param repository
94      * @param user
95      * @param action
96      * @return true if user may execute the action on the repository
97      */
98     protected abstract boolean canAccess(RepositoryModel repository, UserModel user, String action);
8c9a20 99
892570 100     /**
72cb19 101      * Allows a filter to create a repository, if one does not exist.
JM 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     /**
892570 113      * doFilter does the actual work of preprocessing the request to ensure that
JM 114      * the user may proceed.
115      * 
88598b 116      * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
JM 117      *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
892570 118      */
8c9a20 119     @Override
JM 120     public void doFilter(final ServletRequest request, final ServletResponse response,
121             final FilterChain chain) throws IOException, ServletException {
122
123         HttpServletRequest httpRequest = (HttpServletRequest) request;
124         HttpServletResponse httpResponse = (HttpServletResponse) response;
125
ca9d0f 126         String fullUrl = getFullUrl(httpRequest);
78753b 127         String repository = extractRepositoryName(fullUrl);
8c9a20 128
JM 129         // Determine if the request URL is restricted
130         String fullSuffix = fullUrl.substring(repository.length());
892570 131         String urlRequestType = getUrlRequestAction(fullSuffix);
8c9a20 132
72cb19 133         UserModel user = getUser(httpRequest);
JM 134
8c9a20 135         // Load the repository model
JM 136         RepositoryModel model = GitBlit.self().getRepositoryModel(repository);
137         if (model == null) {
72cb19 138             if (isCreationAllowed()) {
JM 139                 if (user == null) {
140                     // challenge client to provide credentials for creation. send 401.
141                     if (GitBlit.isDebugMode()) {
142                         logger.info(MessageFormat.format("ARF: CREATE CHALLENGE {0}", fullUrl));
143                     }
144                     httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
145                     httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
146                     return;
147                 } else {
148                     // see if we can create a repository for this request
149                     model = createRepository(user, repository, urlRequestType);
150                 }
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             }
8c9a20 160         }
b74031 161         
JM 162         // Confirm that the action may be executed on the repository
163         if (!isActionAllowed(model, urlRequestType)) {
164             logger.info(MessageFormat.format("ARF: action {0} on {1} forbidden ({2})",
165                     urlRequestType, model, HttpServletResponse.SC_FORBIDDEN));
166             httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
167             return;
168         }
8c9a20 169
ca9d0f 170         // Wrap the HttpServletRequest with the AccessRestrictionRequest which
JM 171         // overrides the servlet container user principal methods.
172         // JGit requires either:
173         //
174         // 1. servlet container authenticated user
175         // 2. http.receivepack = true in each repository's config
176         //
177         // Gitblit must conditionally authenticate users per-repository so just
178         // enabling http.receivepack is insufficient.
179         AuthenticatedRequest authenticatedRequest = new AuthenticatedRequest(httpRequest);
180         if (user != null) {
181             authenticatedRequest.setUser(user);
182         }
183
8c9a20 184         // BASIC authentication challenge and response processing
3f8cd4 185         if (!StringUtils.isEmpty(urlRequestType) && requiresAuthentication(model, urlRequestType)) {
ca9d0f 186             if (user == null) {
JM 187                 // challenge client to provide credentials. send 401.
8c9a20 188                 if (GitBlit.isDebugMode()) {
ca9d0f 189                     logger.info(MessageFormat.format("ARF: CHALLENGE {0}", fullUrl));
8c9a20 190                 }
ca9d0f 191                 httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
JM 192                 httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
193                 return;
194             } else {
195                 // check user access for request
7f7051 196                 if (user.canAdmin() || canAccess(model, user, urlRequestType)) {
ca9d0f 197                     // authenticated request permitted.
JM 198                     // pass processing to the restricted servlet.
199                     newSession(authenticatedRequest, httpResponse);
200                     logger.info(MessageFormat.format("ARF: {0} ({1}) authenticated", fullUrl,
201                             HttpServletResponse.SC_CONTINUE));
202                     chain.doFilter(authenticatedRequest, httpResponse);
203                     return;
204                 }
205                 // valid user, but not for requested access. send 403.
206                 if (GitBlit.isDebugMode()) {
207                     logger.info(MessageFormat.format("ARF: {0} forbidden to access {1}",
208                             user.username, fullUrl));
209                 }
210                 httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
211                 return;
8c9a20 212             }
JM 213         }
214
215         if (GitBlit.isDebugMode()) {
ca9d0f 216             logger.info(MessageFormat.format("ARF: {0} ({1}) unauthenticated", fullUrl,
JM 217                     HttpServletResponse.SC_CONTINUE));
8c9a20 218         }
JM 219         // unauthenticated request permitted.
220         // pass processing to the restricted servlet.
ca9d0f 221         chain.doFilter(authenticatedRequest, httpResponse);
8c9a20 222     }
JM 223 }