James Moger
2012-11-30 d7f4a1baf51f3cb869518d133a882c99dddf021b
commit | author | age
dafc19 1 /*
PLM 2  * Copyright 2012 Philip L. McMahon.
3  *
4  * Derived from blockpush.groovy, copyright 2011 gitblit.com.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 import com.gitblit.GitBlit
19 import com.gitblit.models.RepositoryModel
20 import com.gitblit.models.UserModel
21
22 import org.eclipse.jgit.transport.ReceiveCommand
23 import org.eclipse.jgit.transport.ReceiveCommand.Result
24 import org.slf4j.Logger
25
26 /**
27  * Sample Gitblit Pre-Receive Hook: protect-refs
28  * 
29  * This script provides basic authorization of receive command types for a list
30  * of known ref patterns. Command types and unmatched ref patterns will be
31  * ignored, meaning this script has an "allow by default" policy.
32  *
33  * This script works best when a repository requires authentication on push, but
34  * can be used to enforce fast-forward commits or prohibit ref deletion by
35  * setting the *authorizedTeams* variable to an empty list and adding a ".+"
36  * entry to the *protectedRefs* list.
37  *
38  * The Pre-Receive hook is executed after an incoming push has been parsed,
39  * validated, and objects have been written but BEFORE the refs are updated.
40  * This is the appropriate point to block a push for some reason.
41  *
42  * This script is only executed when pushing to *Gitblit*, not to other Git
43  * tooling you may be using.
44  * 
45  * If this script is specified in *groovy.preReceiveScripts* of gitblit.properties
46  * or web.xml then it will be executed by any repository when it receives a
47  * push.  If you choose to share your script then you may have to consider
48  * tailoring control-flow based on repository access restrictions.
49  * 
50  * Scripts may also be specified per-repository in the repository settings page.
51  * Shared scripts will be excluded from this list of available scripts.
52  *
53  * This script is dynamically reloaded and it is executed within it's own
54  * exception handler so it will not crash another script nor crash Gitblit.
55  * 
56  * This script may reject one or more commands, but will never return false.
57  * Subsequent scripts, if any, will always be invoked.
58  *
59  * Bound Variables:
2f5d15 60  *  gitblit            Gitblit Server                 com.gitblit.GitBlit
JM 61  *  repository        Gitblit Repository            com.gitblit.models.RepositoryModel
6bb3b2 62  *  receivePack        JGit Receive Pack            org.eclipse.jgit.transport.ReceivePack
2f5d15 63  *  user            Gitblit User                com.gitblit.models.UserModel
JM 64  *  commands        JGit commands                 Collection<org.eclipse.jgit.transport.ReceiveCommand>
65  *    url                Base url for Gitblit        String
66  *  logger            Logs messages to Gitblit     org.slf4j.Logger
67  *  clientLogger    Logs messages to Git client    com.gitblit.utils.ClientLogger
7c1cdc 68  *
JM 69  * Accessing Gitblit Custom Fields:
70  *   def myCustomField = repository.customFields.myCustomField
dafc19 71  *  
PLM 72  */
73
74 // map of protected command types to returned results type
75 // commands not included will skip authz check
76 def protectedCmds = [
77     UPDATE_NONFASTFORWARD:    Result.REJECTED_NONFASTFORWARD,
78     DELETE:                    Result.REJECTED_NODELETE
79 ]
80
81 // list of regex patterns for protected refs
82 def protectedRefs = [
83     "refs/heads/master",
84     "refs/tags/.+"
85 ]
86
87 // teams which are authorized to perform protected commands on protected refs
88 def authorizedTeams = [ "admins" ]
89
90 for (ReceiveCommand command : commands) {
91     def updateType = command.type
92     def updatedRef = command.refName
93     
94     // find first regex which matches updated ref, if any
95     def refPattern = protectedRefs.find { updatedRef.matches ~it }
96     
97     // find rejection result for update type, if any
98     def result = protectedCmds[updateType.name()]
99     
100     // command requires authz if ref is protected and has a mapped rejection result
101     if (refPattern && result) {
102     
103         // verify user is a member of any authorized team
104         def team = authorizedTeams.find { user.isTeamMember it }
105         if (team) {
106             // don't adjust command result
107             logger.info "${user.username} authorized for ${updateType} of protected ref ${repository.name}:${updatedRef} (${command.oldId.name} -> ${command.newId.name})"
108         } else {
109             // mark command result as rejected
110             command.setResult(result, "${user.username} cannot ${updateType} protected ref ${repository.name}:${updatedRef} matching pattern ${refPattern}")
111         }
112     }
113 }