Skip to content

Commit 91780e2

Browse files
committed
Merge pull request #7 from plm/protect_refs_hook
Pre-commit hook to protect ref paths from non-FF updates or deletes
2 parents 9c7a360 + 4e7813c commit 91780e2

File tree

2 files changed

+199
-0
lines changed

2 files changed

+199
-0
lines changed

groovy/protect-refs.groovy

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/*
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:
60+
* gitblit Gitblit Server com.gitblit.GitBlit
61+
* repository Gitblit Repository com.gitblit.models.RepositoryModel
62+
* user Gitblit User com.gitblit.models.UserModel
63+
* commands JGit commands Collection<org.eclipse.jgit.transport.ReceiveCommand>
64+
* url Base url for Gitblit String
65+
* logger Logger instance org.slf4j.Logger
66+
*
67+
*/
68+
69+
// map of protected command types to returned results type
70+
// commands not included will skip authz check
71+
def protectedCmds = [
72+
UPDATE_NONFASTFORWARD: Result.REJECTED_NONFASTFORWARD,
73+
DELETE: Result.REJECTED_NODELETE
74+
]
75+
76+
// list of regex patterns for protected refs
77+
def protectedRefs = [
78+
"refs/heads/master",
79+
"refs/tags/.+"
80+
]
81+
82+
// teams which are authorized to perform protected commands on protected refs
83+
def authorizedTeams = [ "admins" ]
84+
85+
for (ReceiveCommand command : commands) {
86+
def updateType = command.type
87+
def updatedRef = command.refName
88+
89+
// find first regex which matches updated ref, if any
90+
def refPattern = protectedRefs.find { updatedRef.matches ~it }
91+
92+
// find rejection result for update type, if any
93+
def result = protectedCmds[updateType.name()]
94+
95+
// command requires authz if ref is protected and has a mapped rejection result
96+
if (refPattern && result) {
97+
98+
// verify user is a member of any authorized team
99+
def team = authorizedTeams.find { user.isTeamMember it }
100+
if (team) {
101+
// don't adjust command result
102+
logger.info "${user.username} authorized for ${updateType} of protected ref ${repository.name}:${updatedRef} (${command.oldId.name} -> ${command.newId.name})"
103+
} else {
104+
// mark command result as rejected
105+
command.setResult(result, "${user.username} cannot ${updateType} protected ref ${repository.name}:${updatedRef} matching pattern ${refPattern}")
106+
}
107+
}
108+
}

tests/com/gitblit/tests/GroovyScriptTest.java

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,97 @@ public void testSendMail() throws Exception {
8888
assertTrue(m.message.contains("BIT"));
8989
}
9090

91+
@Test
92+
public void testProtectRefsCreateBranch() throws Exception {
93+
MockGitblit gitblit = new MockGitblit();
94+
MockLogger logger = new MockLogger();
95+
List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
96+
commands.add(new ReceiveCommand(ObjectId.zeroId(), ObjectId
97+
.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/heads/master"));
98+
99+
RepositoryModel repository = new RepositoryModel("ex@mple.git", "", "admin", new Date());
100+
101+
test("protect-refs.groovy", gitblit, logger, commands, repository);
102+
}
103+
104+
@Test
105+
public void testProtectRefsCreateTag() throws Exception {
106+
MockGitblit gitblit = new MockGitblit();
107+
MockLogger logger = new MockLogger();
108+
List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
109+
commands.add(new ReceiveCommand(ObjectId.zeroId(), ObjectId
110+
.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/tags/v1.0"));
111+
112+
RepositoryModel repository = new RepositoryModel("ex@mple.git", "", "admin", new Date());
113+
114+
test("protect-refs.groovy", gitblit, logger, commands, repository);
115+
assertEquals(0, logger.messages.size());
116+
}
117+
118+
@Test
119+
public void testProtectRefsFastForward() throws Exception {
120+
MockGitblit gitblit = new MockGitblit();
121+
MockLogger logger = new MockLogger();
122+
List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
123+
commands.add(new ReceiveCommand(ObjectId
124+
.fromString("c18877690322dfc6ae3e37bb7f7085a24e94e887"), ObjectId
125+
.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/heads/master"));
126+
127+
RepositoryModel repository = new RepositoryModel("ex@mple.git", "", "admin", new Date());
128+
129+
test("protect-refs.groovy", gitblit, logger, commands, repository);
130+
assertEquals(0, logger.messages.size());
131+
}
132+
133+
@Test
134+
public void testProtectRefsDeleteMasterBranch() throws Exception {
135+
MockGitblit gitblit = new MockGitblit();
136+
MockLogger logger = new MockLogger();
137+
List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
138+
ReceiveCommand command = new ReceiveCommand(ObjectId
139+
.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), ObjectId.zeroId(),
140+
"refs/heads/master");
141+
commands.add(command);
142+
143+
RepositoryModel repository = new RepositoryModel("ex@mple.git", "", "admin", new Date());
144+
145+
test("protect-refs.groovy", gitblit, logger, commands, repository);
146+
assertEquals(ReceiveCommand.Result.REJECTED_NODELETE, command.getResult());
147+
assertEquals(0, logger.messages.size());
148+
}
149+
150+
@Test
151+
public void testProtectRefsDeleteOtherBranch() throws Exception {
152+
MockGitblit gitblit = new MockGitblit();
153+
MockLogger logger = new MockLogger();
154+
List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
155+
commands.add(new ReceiveCommand(ObjectId
156+
.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), ObjectId.zeroId(),
157+
"refs/heads/other"));
158+
159+
RepositoryModel repository = new RepositoryModel("ex@mple.git", "", "admin", new Date());
160+
161+
test("protect-refs.groovy", gitblit, logger, commands, repository);
162+
assertEquals(0, logger.messages.size());
163+
}
164+
165+
@Test
166+
public void testProtectRefsDeleteTag() throws Exception {
167+
MockGitblit gitblit = new MockGitblit();
168+
MockLogger logger = new MockLogger();
169+
List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
170+
ReceiveCommand command = new ReceiveCommand(ObjectId
171+
.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), ObjectId.zeroId(),
172+
"refs/tags/v1.0");
173+
commands.add(command);
174+
175+
RepositoryModel repository = new RepositoryModel("ex@mple.git", "", "admin", new Date());
176+
177+
test("protect-refs.groovy", gitblit, logger, commands, repository);
178+
assertEquals(ReceiveCommand.Result.REJECTED_NODELETE, command.getResult());
179+
assertEquals(0, logger.messages.size());
180+
}
181+
91182
@Test
92183
public void testBlockPush() throws Exception {
93184
MockGitblit gitblit = new MockGitblit();

0 commit comments

Comments
 (0)