James Moger
2011-10-02 f762b160efd5cafd919a6fd7f9587f578eceb454
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
ca9d0f 28 import com.gitblit.AuthenticationFilter.AuthenticatedRequest;
8c9a20 29 import com.gitblit.models.RepositoryModel;
JM 30 import com.gitblit.models.UserModel;
31 import com.gitblit.utils.StringUtils;
32
33 /**
ca9d0f 34  * The AccessRestrictionFilter is an AuthenticationFilter that confirms that the
JM 35  * requested repository can be accessed by the anonymous or named user.
892570 36  * 
JM 37  * The filter extracts the name of the repository from the url and determines if
38  * the requested action for the repository requires a Basic authentication
39  * prompt. If authentication is required and no credentials are stored in the
40  * "Authorization" header, then a basic authentication challenge is issued.
8c9a20 41  * 
JM 42  * http://en.wikipedia.org/wiki/Basic_access_authentication
892570 43  * 
JM 44  * @author James Moger
45  * 
8c9a20 46  */
ca9d0f 47 public abstract class AccessRestrictionFilter extends AuthenticationFilter {
8c9a20 48
892570 49     /**
JM 50      * Extract the repository name from the url.
51      * 
52      * @param url
53      * @return repository name
54      */
8c9a20 55     protected abstract String extractRepositoryName(String url);
JM 56
892570 57     /**
JM 58      * Analyze the url and returns the action of the request.
59      * 
60      * @param url
61      * @return action of the request
62      */
63     protected abstract String getUrlRequestAction(String url);
8c9a20 64
892570 65     /**
JM 66      * Determine if the repository requires authentication.
67      * 
68      * @param repository
69      * @return true if authentication required
70      */
8c9a20 71     protected abstract boolean requiresAuthentication(RepositoryModel repository);
JM 72
892570 73     /**
JM 74      * Determine if the user can access the repository and perform the specified
75      * action.
76      * 
77      * @param repository
78      * @param user
79      * @param action
80      * @return true if user may execute the action on the repository
81      */
82     protected abstract boolean canAccess(RepositoryModel repository, UserModel user, String action);
8c9a20 83
892570 84     /**
JM 85      * doFilter does the actual work of preprocessing the request to ensure that
86      * the user may proceed.
87      * 
88598b 88      * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
JM 89      *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
892570 90      */
8c9a20 91     @Override
JM 92     public void doFilter(final ServletRequest request, final ServletResponse response,
93             final FilterChain chain) throws IOException, ServletException {
94
95         HttpServletRequest httpRequest = (HttpServletRequest) request;
96         HttpServletResponse httpResponse = (HttpServletResponse) response;
97
ca9d0f 98         String fullUrl = getFullUrl(httpRequest);
78753b 99         String repository = extractRepositoryName(fullUrl);
8c9a20 100
JM 101         // Determine if the request URL is restricted
102         String fullSuffix = fullUrl.substring(repository.length());
892570 103         String urlRequestType = getUrlRequestAction(fullSuffix);
8c9a20 104
JM 105         // Load the repository model
106         RepositoryModel model = GitBlit.self().getRepositoryModel(repository);
107         if (model == null) {
108             // repository not found. send 404.
ca9d0f 109             logger.info(MessageFormat.format("ARF: {0} ({1})", fullUrl,
JM 110                     HttpServletResponse.SC_NOT_FOUND));
8c9a20 111             httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
JM 112             return;
113         }
114
ca9d0f 115         // Wrap the HttpServletRequest with the AccessRestrictionRequest which
JM 116         // overrides the servlet container user principal methods.
117         // JGit requires either:
118         //
119         // 1. servlet container authenticated user
120         // 2. http.receivepack = true in each repository's config
121         //
122         // Gitblit must conditionally authenticate users per-repository so just
123         // enabling http.receivepack is insufficient.
124         AuthenticatedRequest authenticatedRequest = new AuthenticatedRequest(httpRequest);
125         UserModel user = getUser(httpRequest);
126         if (user != null) {
127             authenticatedRequest.setUser(user);
128         }
129
8c9a20 130         // BASIC authentication challenge and response processing
JM 131         if (!StringUtils.isEmpty(urlRequestType) && requiresAuthentication(model)) {
ca9d0f 132             if (user == null) {
JM 133                 // challenge client to provide credentials. send 401.
8c9a20 134                 if (GitBlit.isDebugMode()) {
ca9d0f 135                     logger.info(MessageFormat.format("ARF: CHALLENGE {0}", fullUrl));
8c9a20 136                 }
ca9d0f 137                 httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
JM 138                 httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
139                 return;
140             } else {
141                 // check user access for request
142                 if (user.canAdmin || canAccess(model, user, urlRequestType)) {
143                     // authenticated request permitted.
144                     // pass processing to the restricted servlet.
145                     newSession(authenticatedRequest, httpResponse);
146                     logger.info(MessageFormat.format("ARF: {0} ({1}) authenticated", fullUrl,
147                             HttpServletResponse.SC_CONTINUE));
148                     chain.doFilter(authenticatedRequest, httpResponse);
149                     return;
150                 }
151                 // valid user, but not for requested access. send 403.
152                 if (GitBlit.isDebugMode()) {
153                     logger.info(MessageFormat.format("ARF: {0} forbidden to access {1}",
154                             user.username, fullUrl));
155                 }
156                 httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
157                 return;
8c9a20 158             }
JM 159         }
160
161         if (GitBlit.isDebugMode()) {
ca9d0f 162             logger.info(MessageFormat.format("ARF: {0} ({1}) unauthenticated", fullUrl,
JM 163                     HttpServletResponse.SC_CONTINUE));
8c9a20 164         }
JM 165         // unauthenticated request permitted.
166         // pass processing to the restricted servlet.
ca9d0f 167         chain.doFilter(authenticatedRequest, httpResponse);
8c9a20 168     }
JM 169 }