Debian Codegraph @

hgext/acl.py

raw
1 # acl.py - changeset access control for mercurial
2 #
3 # Copyright 2006 Vadim Gelfer <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 '''hooks for controlling repository access
9
10 This hook makes it possible to allow or deny write access to given
11 branches and paths of a repository when receiving incoming changesets
12 via pretxnchangegroup and pretxncommit.
13
14 The authorization is matched based on the local user name on the
15 system where the hook runs, and not the committer of the original
16 changeset (since the latter is merely informative).
17
18 The acl hook is best used along with a restricted shell like hgsh,
19 preventing authenticating users from doing anything other than pushing
20 or pulling. The hook is not safe to use if users have interactive
21 shell access, as they can then disable the hook. Nor is it safe if
22 remote users share an account, because then there is no way to
23 distinguish them.
24
25 The order in which access checks are performed is:
26
27 1) Deny list for branches (section ``acl.deny.branches``)
28 2) Allow list for branches (section ``acl.allow.branches``)
29 3) Deny list for paths (section ``acl.deny``)
30 4) Allow list for paths (section ``acl.allow``)
31
32 The allow and deny sections take key-value pairs.
33
34 Branch-based Access Control
35 ---------------------------
36
37 Use the ``acl.deny.branches`` and ``acl.allow.branches`` sections to
38 have branch-based access control. Keys in these sections can be
39 either:
40
41 - a branch name, or
42 - an asterisk, to match any branch;
43
44 The corresponding values can be either:
45
46 - a comma-separated list containing users and groups, or
47 - an asterisk, to match anyone;
48
49 You can add the "!" prefix to a user or group name to invert the sense
50 of the match.
51
52 Path-based Access Control
53 -------------------------
54
55 Use the ``acl.deny`` and ``acl.allow`` sections to have path-based
56 access control. Keys in these sections accept a subtree pattern (with
57 a glob syntax by default). The corresponding values follow the same
58 syntax as the other sections above.
59
60 Bookmark-based Access Control
61 -----------------------------
62
63 Use the ``acl.deny.bookmarks`` and ``acl.allow.bookmarks`` sections to
64 have bookmark-based access control. Keys in these sections can be
65 either:
66
67 - a bookmark name, or
68 - an asterisk, to match any bookmark;
69
70 The corresponding values can be either:
71
72 - a comma-separated list containing users and groups, or
73 - an asterisk, to match anyone;
74
75 You can add the "!" prefix to a user or group name to invert the sense
76 of the match.
77
78 Note: for interactions between clients and servers using Mercurial 3.6+
79 a rejection will generally reject the entire push, for interactions
80 involving older clients, the commit transactions will already be accepted,
81 and only the bookmark movement will be rejected.
82
83 Groups
84 ------
85
86 Group names must be prefixed with an ``@`` symbol. Specifying a group
87 name has the same effect as specifying all the users in that group.
88
89 You can define group members in the ``acl.groups`` section.
90 If a group name is not defined there, and Mercurial is running under
91 a Unix-like system, the list of users will be taken from the OS.
92 Otherwise, an exception will be raised.
93
94 Example Configuration
95 ---------------------
96
97 ::
98
99 [hooks]
100
101 # Use this if you want to check access restrictions at commit time
102 pretxncommit.acl = python:hgext.acl.hook
103
104 # Use this if you want to check access restrictions for pull, push,
105 # bundle and serve.
106 pretxnchangegroup.acl = python:hgext.acl.hook
107
108 [acl]
109 # Allow or deny access for incoming changes only if their source is
110 # listed here, let them pass otherwise. Source is "serve" for all
111 # remote access (http or ssh), "push", "pull" or "bundle" when the
112 # related commands are run locally.
113 # Default: serve
114 sources = serve
115
116 [acl.deny.branches]
117
118 # Everyone is denied to the frozen branch:
119 frozen-branch = *
120
121 # A bad user is denied on all branches:
122 * = bad-user
123
124 [acl.allow.branches]
125
126 # A few users are allowed on branch-a:
127 branch-a = user-1, user-2, user-3
128
129 # Only one user is allowed on branch-b:
130 branch-b = user-1
131
132 # The super user is allowed on any branch:
133 * = super-user
134
135 # Everyone is allowed on branch-for-tests:
136 branch-for-tests = *
137
138 [acl.deny]
139 # This list is checked first. If a match is found, acl.allow is not
140 # checked. All users are granted access if acl.deny is not present.
141 # Format for both lists: glob pattern = user, ..., @group, ...
142
143 # To match everyone, use an asterisk for the user:
144 # my/glob/pattern = *
145
146 # user6 will not have write access to any file:
147 ** = user6
148
149 # Group "hg-denied" will not have write access to any file:
150 ** = @hg-denied
151
152 # Nobody will be able to change "DONT-TOUCH-THIS.txt", despite
153 # everyone being able to change all other files. See below.
154 src/main/resources/DONT-TOUCH-THIS.txt = *
155
156 [acl.allow]
157 # if acl.allow is not present, all users are allowed by default
158 # empty acl.allow = no users allowed
159
160 # User "doc_writer" has write access to any file under the "docs"
161 # folder:
162 docs/** = doc_writer
163
164 # User "jack" and group "designers" have write access to any file
165 # under the "images" folder:
166 images/** = jack, @designers
167
168 # Everyone (except for "user6" and "@hg-denied" - see acl.deny above)
169 # will have write access to any file under the "resources" folder
170 # (except for 1 file. See acl.deny):
171 src/main/resources/** = *
172
173 .hgtags = release_engineer
174
175 Examples using the "!" prefix
176 .............................
177
178 Suppose there's a branch that only a given user (or group) should be able to
179 push to, and you don't want to restrict access to any other branch that may
180 be created.
181
182 The "!" prefix allows you to prevent anyone except a given user or group to
183 push changesets in a given branch or path.
184
185 In the examples below, we will:
186 1) Deny access to branch "ring" to anyone but user "gollum"
187 2) Deny access to branch "lake" to anyone but members of the group "hobbit"
188 3) Deny access to a file to anyone but user "gollum"
189
190 ::
191
192 [acl.allow.branches]
193 # Empty
194
195 [acl.deny.branches]
196
197 # 1) only 'gollum' can commit to branch 'ring';
198 # 'gollum' and anyone else can still commit to any other branch.
199 ring = !gollum
200
201 # 2) only members of the group 'hobbit' can commit to branch 'lake';
202 # 'hobbit' members and anyone else can still commit to any other branch.
203 lake = !@hobbit
204
205 # You can also deny access based on file paths:
206
207 [acl.allow]
208 # Empty
209
210 [acl.deny]
211 # 3) only 'gollum' can change the file below;
212 # 'gollum' and anyone else can still change any other file.
213 /misty/mountains/cave/ring = !gollum
214
215 '''
216
217 from __future__ import annotations
218
219 from mercurial.i18n import _
220 from mercurial import (
221 error,
222 extensions,
223 match,
224 registrar,
225 util,
226 )
227 from mercurial.utils import procutil
228
229 urlreq = util.urlreq
230
231 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
232 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
233 # be specifying the version(s) of Mercurial they are tested with, or
234 # leave the attribute unspecified.
235 testedwith = b'ships-with-hg-core'
236
237 configtable = {}
238 configitem = registrar.configitem(configtable)
239
240 # deprecated config: acl.config
241 configitem(
242 b'acl',
243 b'config',
244 default=None,
245 )
246 configitem(
247 b'acl.groups',
248 b'.*',
249 default=None,
250 generic=True,
251 )
252 configitem(
253 b'acl.deny.branches',
254 b'.*',
255 default=None,
256 generic=True,
257 )
258 configitem(
259 b'acl.allow.branches',
260 b'.*',
261 default=None,
262 generic=True,
263 )
264 configitem(
265 b'acl.deny',
266 b'.*',
267 default=None,
268 generic=True,
269 )
270 configitem(
271 b'acl.allow',
272 b'.*',
273 default=None,
274 generic=True,
275 )
276 configitem(
277 b'acl',
278 b'sources',
279 default=lambda: [b'serve'],
280 )
281
282
283 def _getusers(ui, group):
284 # First, try to use group definition from section [acl.groups]
285 hgrcusers = ui.configlist(b'acl.groups', group)
286 if hgrcusers:
287 return hgrcusers
288
289 ui.debug(b'acl: "%s" not defined in [acl.groups]\n' % group)
290 # If no users found in group definition, get users from OS-level group
291 try:
292 return util.groupmembers(group)
293 except KeyError:
294 raise error.Abort(_(b"group '%s' is undefined") % group)
295
296
297 def _usermatch(ui, user, usersorgroups):
298 if usersorgroups == b'*':
299 return True
300
301 for ug in usersorgroups.replace(b',', b' ').split():
302 if ug.startswith(b'!'):
303 # Test for excluded user or group. Format:
304 # if ug is a user name: !username
305 # if ug is a group name: !@groupname
306 ug = ug[1:]
307 if (
308 not ug.startswith(b'@')
309 and user != ug
310 or ug.startswith(b'@')
311 and user not in _getusers(ui, ug[1:])
312 ):
313 return True
314
315 # Test for user or group. Format:
316 # if ug is a user name: username
317 # if ug is a group name: @groupname
318 elif (
319 user == ug or ug.startswith(b'@') and user in _getusers(ui, ug[1:])
320 ):
321 return True
322
323 return False
324
325
326 def buildmatch(ui, repo, user, key):
327 '''return tuple of (match function, list enabled).'''
328 if not ui.has_section(key):
329 ui.debug(b'acl: %s not enabled\n' % key)
330 return None
331
332 pats = [
333 pat for pat, users in ui.configitems(key) if _usermatch(ui, user, users)
334 ]
335 ui.debug(
336 b'acl: %s enabled, %d entries for user %s\n' % (key, len(pats), user)
337 )
338
339 # Branch-based ACL
340 if not repo:
341 if pats:
342 # If there's an asterisk (meaning "any branch"), always return True;
343 # Otherwise, test if b is in pats
344 if b'*' in pats:
345 return util.always
346 return lambda b: b in pats
347 return util.never
348
349 # Path-based ACL
350 if pats:
351 return match.match(repo.root, b'', pats)
352 return util.never
353
354
355 def ensureenabled(ui):
356 """make sure the extension is enabled when used as hook
357
358 When acl is used through hooks, the extension is never formally loaded and
359 enabled. This has some side effect, for example the config declaration is
360 never loaded. This function ensure the extension is enabled when running
361 hooks.
362 """
363 if b'acl' in ui._knownconfig:
364 return
365 ui.setconfig(b'extensions', b'acl', b'', source=b'internal')
366 extensions.loadall(ui, [b'acl'])
367
368
369 def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
370 ensureenabled(ui)
371
372 if hooktype not in [b'pretxnchangegroup', b'pretxncommit', b'prepushkey']:
373 raise error.Abort(
374 _(
375 b'config error - hook type "%s" cannot stop '
376 b'incoming changesets, commits, nor bookmarks'
377 )
378 % hooktype
379 )
380 if hooktype == b'pretxnchangegroup' and source not in ui.configlist(
381 b'acl', b'sources'
382 ):
383 ui.debug(b'acl: changes have source "%s" - skipping\n' % source)
384 return
385
386 user = None
387 if source == b'serve' and 'url' in kwargs:
388 url = kwargs['url'].split(b':')
389 if url[0] == b'remote' and url[1].startswith(b'http'):
390 user = urlreq.unquote(url[3])
391
392 if user is None:
393 user = procutil.getuser()
394
395 ui.debug(b'acl: checking access for user "%s"\n' % user)
396
397 if hooktype == b'prepushkey':
398 _pkhook(ui, repo, hooktype, node, source, user, **kwargs)
399 else:
400 _txnhook(ui, repo, hooktype, node, source, user, **kwargs)
401
402
403 def _pkhook(ui, repo, hooktype, node, source, user, **kwargs):
404 if kwargs['namespace'] == b'bookmarks':
405 bookmark = kwargs['key']
406 ctx = kwargs['new']
407 allowbookmarks = buildmatch(ui, None, user, b'acl.allow.bookmarks')
408 denybookmarks = buildmatch(ui, None, user, b'acl.deny.bookmarks')
409
410 if denybookmarks and denybookmarks(bookmark):
411 raise error.Abort(
412 _(
413 b'acl: user "%s" denied on bookmark "%s"'
414 b' (changeset "%s")'
415 )
416 % (user, bookmark, ctx)
417 )
418 if allowbookmarks and not allowbookmarks(bookmark):
419 raise error.Abort(
420 _(
421 b'acl: user "%s" not allowed on bookmark "%s"'
422 b' (changeset "%s")'
423 )
424 % (user, bookmark, ctx)
425 )
426 ui.debug(
427 b'acl: bookmark access granted: "%s" on bookmark "%s"\n'
428 % (ctx, bookmark)
429 )
430
431
432 def _txnhook(ui, repo, hooktype, node, source, user, **kwargs):
433 # deprecated config: acl.config
434 cfg = ui.config(b'acl', b'config')
435 if cfg:
436 ui.readconfig(
437 cfg,
438 sections=[
439 b'acl.groups',
440 b'acl.allow.branches',
441 b'acl.deny.branches',
442 b'acl.allow',
443 b'acl.deny',
444 ],
445 )
446
447 allowbranches = buildmatch(ui, None, user, b'acl.allow.branches')
448 denybranches = buildmatch(ui, None, user, b'acl.deny.branches')
449 allow = buildmatch(ui, repo, user, b'acl.allow')
450 deny = buildmatch(ui, repo, user, b'acl.deny')
451
452 for rev in range(repo[node].rev(), len(repo)):
453 ctx = repo[rev]
454 branch = ctx.branch()
455 if denybranches and denybranches(branch):
456 raise error.Abort(
457 _(b'acl: user "%s" denied on branch "%s" (changeset "%s")')
458 % (user, branch, ctx)
459 )
460 if allowbranches and not allowbranches(branch):
461 raise error.Abort(
462 _(
463 b'acl: user "%s" not allowed on branch "%s"'
464 b' (changeset "%s")'
465 )
466 % (user, branch, ctx)
467 )
468 ui.debug(
469 b'acl: branch access granted: "%s" on branch "%s"\n' % (ctx, branch)
470 )
471
472 for f in ctx.files():
473 if deny and deny(f):
474 raise error.Abort(
475 _(b'acl: user "%s" denied on "%s" (changeset "%s")')
476 % (user, f, ctx)
477 )
478 if allow and not allow(f):
479 raise error.Abort(
480 _(
481 b'acl: user "%s" not allowed on "%s"'
482 b' (changeset "%s")'
483 )
484 % (user, f, ctx)
485 )
486 ui.debug(b'acl: path access granted: "%s"\n' % ctx)