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.

GitFilter.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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.text.MessageFormat;
  18. import com.google.inject.Inject;
  19. import com.google.inject.Singleton;
  20. import javax.servlet.http.HttpServletRequest;
  21. import com.gitblit.Constants.AccessRestrictionType;
  22. import com.gitblit.Constants.AuthorizationControl;
  23. import com.gitblit.GitBlitException;
  24. import com.gitblit.IStoredSettings;
  25. import com.gitblit.Keys;
  26. import com.gitblit.manager.IAuthenticationManager;
  27. import com.gitblit.manager.IFederationManager;
  28. import com.gitblit.manager.IRepositoryManager;
  29. import com.gitblit.manager.IRuntimeManager;
  30. import com.gitblit.models.RepositoryModel;
  31. import com.gitblit.models.UserModel;
  32. import com.gitblit.utils.StringUtils;
  33. /**
  34. * The GitFilter is an AccessRestrictionFilter which ensures that Git client
  35. * requests for push, clone, or view restricted repositories are authenticated
  36. * and authorized.
  37. *
  38. * @author James Moger
  39. *
  40. */
  41. @Singleton
  42. public class GitFilter extends AccessRestrictionFilter {
  43. static final String GIT_RECEIVE_PACK = "/git-receive-pack";
  44. static final String GIT_UPLOAD_PACK = "/git-upload-pack";
  45. static final String CLONE_BUNDLE = "/clone.bundle";
  46. static final String GIT_LFS = "/info/lfs";
  47. static final String[] SUFFIXES = {GIT_RECEIVE_PACK, GIT_UPLOAD_PACK, "/info/refs", "/HEAD",
  48. "/objects", GIT_LFS, CLONE_BUNDLE};
  49. private IStoredSettings settings;
  50. private IFederationManager federationManager;
  51. @Inject
  52. public GitFilter(
  53. IStoredSettings settings,
  54. IRuntimeManager runtimeManager,
  55. IAuthenticationManager authenticationManager,
  56. IRepositoryManager repositoryManager,
  57. IFederationManager federationManager) {
  58. super(runtimeManager, authenticationManager, repositoryManager);
  59. this.settings = settings;
  60. this.federationManager = federationManager;
  61. }
  62. /**
  63. * Extract the repository name from the url.
  64. *
  65. * @param url
  66. * Request URL with repository name in it
  67. * @return repository name
  68. */
  69. public static String getRepositoryName(String url) {
  70. String repository = url;
  71. // strip off parameters from the URL
  72. if (repository.contains("?")) {
  73. repository = repository.substring(0, repository.indexOf("?"));
  74. }
  75. // get the repository name from the url by finding a known url suffix
  76. for (String urlSuffix : SUFFIXES) {
  77. if (repository.indexOf(urlSuffix) > -1) {
  78. repository = repository.substring(0, repository.indexOf(urlSuffix));
  79. }
  80. }
  81. return repository;
  82. }
  83. /**
  84. * Extract the repository name from the url.
  85. *
  86. * @param url
  87. * @return repository name
  88. */
  89. @Override
  90. protected String extractRepositoryName(String url) {
  91. return GitFilter.getRepositoryName(url);
  92. }
  93. /**
  94. * Analyze the url and returns the action of the request. Return values are:
  95. * "/git-receive-pack", "/git-upload-pack" or "/info/lfs".
  96. *
  97. * @param serverUrl
  98. * @return action of the request
  99. */
  100. @Override
  101. protected String getUrlRequestAction(String suffix) {
  102. if (!StringUtils.isEmpty(suffix)) {
  103. if (suffix.startsWith(GIT_RECEIVE_PACK)) {
  104. return GIT_RECEIVE_PACK;
  105. } else if (suffix.startsWith(GIT_UPLOAD_PACK)) {
  106. return GIT_UPLOAD_PACK;
  107. } else if (suffix.contains("?service=git-receive-pack")) {
  108. return GIT_RECEIVE_PACK;
  109. } else if (suffix.contains("?service=git-upload-pack")) {
  110. return GIT_UPLOAD_PACK;
  111. } else if (suffix.startsWith(GIT_LFS)) {
  112. return GIT_LFS;
  113. } else if (suffix.startsWith(CLONE_BUNDLE)) {
  114. return CLONE_BUNDLE;
  115. } else {
  116. return GIT_UPLOAD_PACK;
  117. }
  118. }
  119. return null;
  120. }
  121. /**
  122. * Returns the user making the request, if the user has authenticated.
  123. *
  124. * @param httpRequest
  125. * @return user
  126. */
  127. @Override
  128. protected UserModel getUser(HttpServletRequest httpRequest) {
  129. UserModel user = authenticationManager.authenticate(httpRequest, requiresClientCertificate());
  130. if (user == null) {
  131. user = federationManager.authenticate(httpRequest);
  132. }
  133. return user;
  134. }
  135. /**
  136. * Determine if a non-existing repository can be created using this filter.
  137. *
  138. * @return true if the server allows repository creation on-push
  139. */
  140. @Override
  141. protected boolean isCreationAllowed(String action) {
  142. // Unknown action, don't allow creation
  143. if (action == null) return false;
  144. //Repository must already exist before large files can be deposited
  145. if (GIT_LFS.equals(action)) {
  146. return false;
  147. }
  148. // Action is not implemened.
  149. if (CLONE_BUNDLE.equals(action)) {
  150. return false;
  151. }
  152. return settings.getBoolean(Keys.git.allowCreateOnPush, true);
  153. }
  154. /**
  155. * Determine if the repository can receive pushes.
  156. *
  157. * @param repository
  158. * @param action
  159. * @return true if the action may be performed
  160. */
  161. @Override
  162. protected boolean isActionAllowed(RepositoryModel repository, String action, String method) {
  163. // the log here has been moved into ReceiveHook to provide clients with
  164. // error messages
  165. if (GIT_LFS.equals(action)) {
  166. if (!method.matches("GET|POST|PUT|HEAD")) {
  167. return false;
  168. }
  169. }
  170. return true;
  171. }
  172. @Override
  173. protected boolean requiresClientCertificate() {
  174. return settings.getBoolean(Keys.git.requiresClientCertificate, false);
  175. }
  176. /**
  177. * Determine if the repository requires authentication.
  178. *
  179. * @param repository
  180. * @param action
  181. * @param method
  182. * @return true if authentication required
  183. */
  184. @Override
  185. protected boolean requiresAuthentication(RepositoryModel repository, String action, String method) {
  186. if (GIT_UPLOAD_PACK.equals(action)) {
  187. // send to client
  188. return repository.accessRestriction.atLeast(AccessRestrictionType.CLONE);
  189. } else if (GIT_RECEIVE_PACK.equals(action)) {
  190. // receive from client
  191. return repository.accessRestriction.atLeast(AccessRestrictionType.PUSH);
  192. } else if (GIT_LFS.equals(action)) {
  193. if (method.matches("GET|HEAD")) {
  194. return repository.accessRestriction.atLeast(AccessRestrictionType.CLONE);
  195. } else {
  196. //NOTE: Treat POST as PUT as as without reading message type cannot determine
  197. return repository.accessRestriction.atLeast(AccessRestrictionType.PUSH);
  198. }
  199. }
  200. return false;
  201. }
  202. /**
  203. * Determine if the user can access the repository and perform the specified
  204. * action.
  205. *
  206. * @param repository
  207. * @param user
  208. * @param action
  209. * @return true if user may execute the action on the repository
  210. */
  211. @Override
  212. protected boolean canAccess(RepositoryModel repository, UserModel user, String action) {
  213. if (!settings.getBoolean(Keys.git.enableGitServlet, true)) {
  214. // Git Servlet disabled
  215. return false;
  216. }
  217. if (GIT_RECEIVE_PACK.equals(action)) {
  218. // push permissions are enforced in the receive pack
  219. return true;
  220. } else if (GIT_UPLOAD_PACK.equals(action)) {
  221. // Clone request
  222. if (user.canClone(repository)) {
  223. return true;
  224. } else {
  225. // user is unauthorized to clone this repository
  226. logger.warn(MessageFormat.format("user {0} is not authorized to clone {1}",
  227. user.username, repository));
  228. return false;
  229. }
  230. }
  231. return true;
  232. }
  233. /**
  234. * An authenticated user with the CREATE role can create a repository on
  235. * push.
  236. *
  237. * @param user
  238. * @param repository
  239. * @param action
  240. * @return the repository model, if it is created, null otherwise
  241. */
  242. @Override
  243. protected RepositoryModel createRepository(UserModel user, String repository, String action) {
  244. boolean isPush = !StringUtils.isEmpty(action) && GIT_RECEIVE_PACK.equals(action);
  245. if (GIT_LFS.equals(action)) {
  246. //Repository must already exist for any filestore actions
  247. return null;
  248. }
  249. if (isPush) {
  250. if (user.canCreate(repository)) {
  251. // user is pushing to a new repository
  252. // validate name
  253. if (repository.startsWith("../")) {
  254. logger.error(MessageFormat.format("Illegal relative path in repository name! {0}", repository));
  255. return null;
  256. }
  257. if (repository.contains("/../")) {
  258. logger.error(MessageFormat.format("Illegal relative path in repository name! {0}", repository));
  259. return null;
  260. }
  261. // confirm valid characters in repository name
  262. Character c = StringUtils.findInvalidCharacter(repository);
  263. if (c != null) {
  264. logger.error(MessageFormat.format("Invalid character '{0}' in repository name {1}!", c, repository));
  265. return null;
  266. }
  267. // create repository
  268. RepositoryModel model = new RepositoryModel();
  269. model.name = repository;
  270. model.addOwner(user.username);
  271. model.projectPath = StringUtils.getFirstPathElement(repository);
  272. if (model.isUsersPersonalRepository(user.username)) {
  273. // personal repository, default to private for user
  274. model.authorizationControl = AuthorizationControl.NAMED;
  275. model.accessRestriction = AccessRestrictionType.VIEW;
  276. } else {
  277. // common repository, user default server settings
  278. model.authorizationControl = AuthorizationControl.fromName(settings.getString(Keys.git.defaultAuthorizationControl, ""));
  279. model.accessRestriction = AccessRestrictionType.fromName(settings.getString(Keys.git.defaultAccessRestriction, "PUSH"));
  280. }
  281. // create the repository
  282. try {
  283. repositoryManager.updateRepositoryModel(model.name, model, true);
  284. logger.info(MessageFormat.format("{0} created {1} ON-PUSH", user.username, model.name));
  285. return repositoryManager.getRepositoryModel(model.name);
  286. } catch (GitBlitException e) {
  287. logger.error(MessageFormat.format("{0} failed to create repository {1} ON-PUSH!", user.username, model.name), e);
  288. }
  289. } else {
  290. logger.warn(MessageFormat.format("{0} is not permitted to create repository {1} ON-PUSH!", user.username, repository));
  291. }
  292. }
  293. // repository could not be created or action was not a push
  294. return null;
  295. }
  296. /**
  297. * Git lfs action uses an alternative authentication header,
  298. * dependent on the viewing method.
  299. *
  300. * @param httpRequest
  301. * @param action
  302. * @return
  303. */
  304. @Override
  305. protected String getAuthenticationHeader(HttpServletRequest httpRequest, String action) {
  306. if (GIT_LFS.equals(action)) {
  307. if (hasContentInRequestHeader(httpRequest, "Accept", FilestoreServlet.GIT_LFS_META_MIME)) {
  308. return "LFS-Authenticate";
  309. }
  310. }
  311. return super.getAuthenticationHeader(httpRequest, action);
  312. }
  313. /**
  314. * Interrogates the request headers based on the action
  315. * @param action
  316. * @param request
  317. * @return
  318. */
  319. @Override
  320. protected boolean hasValidRequestHeader(String action,
  321. HttpServletRequest request) {
  322. if (GIT_LFS.equals(action) && request.getMethod().equals("POST")) {
  323. if ( !hasContentInRequestHeader(request, "Accept", FilestoreServlet.GIT_LFS_META_MIME)
  324. || !hasContentInRequestHeader(request, "Content-Type", FilestoreServlet.GIT_LFS_META_MIME)) {
  325. return false;
  326. }
  327. }
  328. return super.hasValidRequestHeader(action, request);
  329. }
  330. }