James Moger
2012-02-03 fe7c01a8bd76dff240e74bb770212911e227ba59
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     /**
JM 65      * Determine if the repository requires authentication.
66      * 
67      * @param repository
68      * @return true if authentication required
69      */
8c9a20 70     protected abstract boolean requiresAuthentication(RepositoryModel repository);
JM 71
892570 72     /**
JM 73      * Determine if the user can access the repository and perform the specified
74      * action.
75      * 
76      * @param repository
77      * @param user
78      * @param action
79      * @return true if user may execute the action on the repository
80      */
81     protected abstract boolean canAccess(RepositoryModel repository, UserModel user, String action);
8c9a20 82
892570 83     /**
JM 84      * doFilter does the actual work of preprocessing the request to ensure that
85      * the user may proceed.
86      * 
88598b 87      * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
JM 88      *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
892570 89      */
8c9a20 90     @Override
JM 91     public void doFilter(final ServletRequest request, final ServletResponse response,
92             final FilterChain chain) throws IOException, ServletException {
93
94         HttpServletRequest httpRequest = (HttpServletRequest) request;
95         HttpServletResponse httpResponse = (HttpServletResponse) response;
96
ca9d0f 97         String fullUrl = getFullUrl(httpRequest);
78753b 98         String repository = extractRepositoryName(fullUrl);
8c9a20 99
JM 100         // Determine if the request URL is restricted
101         String fullSuffix = fullUrl.substring(repository.length());
892570 102         String urlRequestType = getUrlRequestAction(fullSuffix);
8c9a20 103
JM 104         // Load the repository model
105         RepositoryModel model = GitBlit.self().getRepositoryModel(repository);
106         if (model == null) {
107             // repository not found. send 404.
ca9d0f 108             logger.info(MessageFormat.format("ARF: {0} ({1})", fullUrl,
JM 109                     HttpServletResponse.SC_NOT_FOUND));
8c9a20 110             httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
JM 111             return;
112         }
113
ca9d0f 114         // Wrap the HttpServletRequest with the AccessRestrictionRequest which
JM 115         // overrides the servlet container user principal methods.
116         // JGit requires either:
117         //
118         // 1. servlet container authenticated user
119         // 2. http.receivepack = true in each repository's config
120         //
121         // Gitblit must conditionally authenticate users per-repository so just
122         // enabling http.receivepack is insufficient.
123         AuthenticatedRequest authenticatedRequest = new AuthenticatedRequest(httpRequest);
124         UserModel user = getUser(httpRequest);
125         if (user != null) {
126             authenticatedRequest.setUser(user);
127         }
128
8c9a20 129         // BASIC authentication challenge and response processing
JM 130         if (!StringUtils.isEmpty(urlRequestType) && requiresAuthentication(model)) {
ca9d0f 131             if (user == null) {
JM 132                 // challenge client to provide credentials. send 401.
8c9a20 133                 if (GitBlit.isDebugMode()) {
ca9d0f 134                     logger.info(MessageFormat.format("ARF: CHALLENGE {0}", fullUrl));
8c9a20 135                 }
ca9d0f 136                 httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
JM 137                 httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
138                 return;
139             } else {
140                 // check user access for request
141                 if (user.canAdmin || canAccess(model, user, urlRequestType)) {
142                     // authenticated request permitted.
143                     // pass processing to the restricted servlet.
144                     newSession(authenticatedRequest, httpResponse);
145                     logger.info(MessageFormat.format("ARF: {0} ({1}) authenticated", fullUrl,
146                             HttpServletResponse.SC_CONTINUE));
147                     chain.doFilter(authenticatedRequest, httpResponse);
148                     return;
149                 }
150                 // valid user, but not for requested access. send 403.
151                 if (GitBlit.isDebugMode()) {
152                     logger.info(MessageFormat.format("ARF: {0} forbidden to access {1}",
153                             user.username, fullUrl));
154                 }
155                 httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
156                 return;
8c9a20 157             }
JM 158         }
159
160         if (GitBlit.isDebugMode()) {
ca9d0f 161             logger.info(MessageFormat.format("ARF: {0} ({1}) unauthenticated", fullUrl,
JM 162                     HttpServletResponse.SC_CONTINUE));
8c9a20 163         }
JM 164         // unauthenticated request permitted.
165         // pass processing to the restricted servlet.
ca9d0f 166         chain.doFilter(authenticatedRequest, httpResponse);
8c9a20 167     }
JM 168 }