##// END OF EJS Templates
auth: re-use the get_current_request in fetching request in decorators....
marcink -
r1775:f25110de default
parent child Browse files
Show More
@@ -1,1993 +1,2007 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 authentication and permission libraries
22 authentication and permission libraries
23 """
23 """
24
24
25 import os
25 import os
26 import inspect
26 import inspect
27 import collections
27 import collections
28 import fnmatch
28 import fnmatch
29 import hashlib
29 import hashlib
30 import itertools
30 import itertools
31 import logging
31 import logging
32 import random
32 import random
33 import traceback
33 import traceback
34 from functools import wraps
34 from functools import wraps
35
35
36 import ipaddress
36 import ipaddress
37 from pyramid.httpexceptions import HTTPForbidden, HTTPFound
37 from pyramid.httpexceptions import HTTPForbidden, HTTPFound
38 from pylons import url, request
38 from pylons import url, request
39 from pylons.controllers.util import abort, redirect
39 from pylons.controllers.util import abort, redirect
40 from pylons.i18n.translation import _
40 from pylons.i18n.translation import _
41 from sqlalchemy.orm.exc import ObjectDeletedError
41 from sqlalchemy.orm.exc import ObjectDeletedError
42 from sqlalchemy.orm import joinedload
42 from sqlalchemy.orm import joinedload
43 from zope.cachedescriptors.property import Lazy as LazyProperty
43 from zope.cachedescriptors.property import Lazy as LazyProperty
44
44
45 import rhodecode
45 import rhodecode
46 from rhodecode.model import meta
46 from rhodecode.model import meta
47 from rhodecode.model.meta import Session
47 from rhodecode.model.meta import Session
48 from rhodecode.model.user import UserModel
48 from rhodecode.model.user import UserModel
49 from rhodecode.model.db import (
49 from rhodecode.model.db import (
50 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
50 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
51 UserIpMap, UserApiKeys, RepoGroup)
51 UserIpMap, UserApiKeys, RepoGroup)
52 from rhodecode.lib import caches
52 from rhodecode.lib import caches
53 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
53 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
54 from rhodecode.lib.utils import (
54 from rhodecode.lib.utils import (
55 get_repo_slug, get_repo_group_slug, get_user_group_slug)
55 get_repo_slug, get_repo_group_slug, get_user_group_slug)
56 from rhodecode.lib.caching_query import FromCache
56 from rhodecode.lib.caching_query import FromCache
57
57
58
58
59 if rhodecode.is_unix:
59 if rhodecode.is_unix:
60 import bcrypt
60 import bcrypt
61
61
62 log = logging.getLogger(__name__)
62 log = logging.getLogger(__name__)
63
63
64 csrf_token_key = "csrf_token"
64 csrf_token_key = "csrf_token"
65
65
66
66
67 class PasswordGenerator(object):
67 class PasswordGenerator(object):
68 """
68 """
69 This is a simple class for generating password from different sets of
69 This is a simple class for generating password from different sets of
70 characters
70 characters
71 usage::
71 usage::
72
72
73 passwd_gen = PasswordGenerator()
73 passwd_gen = PasswordGenerator()
74 #print 8-letter password containing only big and small letters
74 #print 8-letter password containing only big and small letters
75 of alphabet
75 of alphabet
76 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
76 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
77 """
77 """
78 ALPHABETS_NUM = r'''1234567890'''
78 ALPHABETS_NUM = r'''1234567890'''
79 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
79 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
80 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
80 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
81 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
81 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
82 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
82 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
83 + ALPHABETS_NUM + ALPHABETS_SPECIAL
83 + ALPHABETS_NUM + ALPHABETS_SPECIAL
84 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
84 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
85 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
85 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
86 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
86 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
87 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
87 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
88
88
89 def __init__(self, passwd=''):
89 def __init__(self, passwd=''):
90 self.passwd = passwd
90 self.passwd = passwd
91
91
92 def gen_password(self, length, type_=None):
92 def gen_password(self, length, type_=None):
93 if type_ is None:
93 if type_ is None:
94 type_ = self.ALPHABETS_FULL
94 type_ = self.ALPHABETS_FULL
95 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
95 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
96 return self.passwd
96 return self.passwd
97
97
98
98
99 class _RhodeCodeCryptoBase(object):
99 class _RhodeCodeCryptoBase(object):
100 ENC_PREF = None
100 ENC_PREF = None
101
101
102 def hash_create(self, str_):
102 def hash_create(self, str_):
103 """
103 """
104 hash the string using
104 hash the string using
105
105
106 :param str_: password to hash
106 :param str_: password to hash
107 """
107 """
108 raise NotImplementedError
108 raise NotImplementedError
109
109
110 def hash_check_with_upgrade(self, password, hashed):
110 def hash_check_with_upgrade(self, password, hashed):
111 """
111 """
112 Returns tuple in which first element is boolean that states that
112 Returns tuple in which first element is boolean that states that
113 given password matches it's hashed version, and the second is new hash
113 given password matches it's hashed version, and the second is new hash
114 of the password, in case this password should be migrated to new
114 of the password, in case this password should be migrated to new
115 cipher.
115 cipher.
116 """
116 """
117 checked_hash = self.hash_check(password, hashed)
117 checked_hash = self.hash_check(password, hashed)
118 return checked_hash, None
118 return checked_hash, None
119
119
120 def hash_check(self, password, hashed):
120 def hash_check(self, password, hashed):
121 """
121 """
122 Checks matching password with it's hashed value.
122 Checks matching password with it's hashed value.
123
123
124 :param password: password
124 :param password: password
125 :param hashed: password in hashed form
125 :param hashed: password in hashed form
126 """
126 """
127 raise NotImplementedError
127 raise NotImplementedError
128
128
129 def _assert_bytes(self, value):
129 def _assert_bytes(self, value):
130 """
130 """
131 Passing in an `unicode` object can lead to hard to detect issues
131 Passing in an `unicode` object can lead to hard to detect issues
132 if passwords contain non-ascii characters. Doing a type check
132 if passwords contain non-ascii characters. Doing a type check
133 during runtime, so that such mistakes are detected early on.
133 during runtime, so that such mistakes are detected early on.
134 """
134 """
135 if not isinstance(value, str):
135 if not isinstance(value, str):
136 raise TypeError(
136 raise TypeError(
137 "Bytestring required as input, got %r." % (value, ))
137 "Bytestring required as input, got %r." % (value, ))
138
138
139
139
140 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
140 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
141 ENC_PREF = ('$2a$10', '$2b$10')
141 ENC_PREF = ('$2a$10', '$2b$10')
142
142
143 def hash_create(self, str_):
143 def hash_create(self, str_):
144 self._assert_bytes(str_)
144 self._assert_bytes(str_)
145 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
145 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
146
146
147 def hash_check_with_upgrade(self, password, hashed):
147 def hash_check_with_upgrade(self, password, hashed):
148 """
148 """
149 Returns tuple in which first element is boolean that states that
149 Returns tuple in which first element is boolean that states that
150 given password matches it's hashed version, and the second is new hash
150 given password matches it's hashed version, and the second is new hash
151 of the password, in case this password should be migrated to new
151 of the password, in case this password should be migrated to new
152 cipher.
152 cipher.
153
153
154 This implements special upgrade logic which works like that:
154 This implements special upgrade logic which works like that:
155 - check if the given password == bcrypted hash, if yes then we
155 - check if the given password == bcrypted hash, if yes then we
156 properly used password and it was already in bcrypt. Proceed
156 properly used password and it was already in bcrypt. Proceed
157 without any changes
157 without any changes
158 - if bcrypt hash check is not working try with sha256. If hash compare
158 - if bcrypt hash check is not working try with sha256. If hash compare
159 is ok, it means we using correct but old hashed password. indicate
159 is ok, it means we using correct but old hashed password. indicate
160 hash change and proceed
160 hash change and proceed
161 """
161 """
162
162
163 new_hash = None
163 new_hash = None
164
164
165 # regular pw check
165 # regular pw check
166 password_match_bcrypt = self.hash_check(password, hashed)
166 password_match_bcrypt = self.hash_check(password, hashed)
167
167
168 # now we want to know if the password was maybe from sha256
168 # now we want to know if the password was maybe from sha256
169 # basically calling _RhodeCodeCryptoSha256().hash_check()
169 # basically calling _RhodeCodeCryptoSha256().hash_check()
170 if not password_match_bcrypt:
170 if not password_match_bcrypt:
171 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
171 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
172 new_hash = self.hash_create(password) # make new bcrypt hash
172 new_hash = self.hash_create(password) # make new bcrypt hash
173 password_match_bcrypt = True
173 password_match_bcrypt = True
174
174
175 return password_match_bcrypt, new_hash
175 return password_match_bcrypt, new_hash
176
176
177 def hash_check(self, password, hashed):
177 def hash_check(self, password, hashed):
178 """
178 """
179 Checks matching password with it's hashed value.
179 Checks matching password with it's hashed value.
180
180
181 :param password: password
181 :param password: password
182 :param hashed: password in hashed form
182 :param hashed: password in hashed form
183 """
183 """
184 self._assert_bytes(password)
184 self._assert_bytes(password)
185 try:
185 try:
186 return bcrypt.hashpw(password, hashed) == hashed
186 return bcrypt.hashpw(password, hashed) == hashed
187 except ValueError as e:
187 except ValueError as e:
188 # we're having a invalid salt here probably, we should not crash
188 # we're having a invalid salt here probably, we should not crash
189 # just return with False as it would be a wrong password.
189 # just return with False as it would be a wrong password.
190 log.debug('Failed to check password hash using bcrypt %s',
190 log.debug('Failed to check password hash using bcrypt %s',
191 safe_str(e))
191 safe_str(e))
192
192
193 return False
193 return False
194
194
195
195
196 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
196 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
197 ENC_PREF = '_'
197 ENC_PREF = '_'
198
198
199 def hash_create(self, str_):
199 def hash_create(self, str_):
200 self._assert_bytes(str_)
200 self._assert_bytes(str_)
201 return hashlib.sha256(str_).hexdigest()
201 return hashlib.sha256(str_).hexdigest()
202
202
203 def hash_check(self, password, hashed):
203 def hash_check(self, password, hashed):
204 """
204 """
205 Checks matching password with it's hashed value.
205 Checks matching password with it's hashed value.
206
206
207 :param password: password
207 :param password: password
208 :param hashed: password in hashed form
208 :param hashed: password in hashed form
209 """
209 """
210 self._assert_bytes(password)
210 self._assert_bytes(password)
211 return hashlib.sha256(password).hexdigest() == hashed
211 return hashlib.sha256(password).hexdigest() == hashed
212
212
213
213
214 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
214 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
215 ENC_PREF = '_'
215 ENC_PREF = '_'
216
216
217 def hash_create(self, str_):
217 def hash_create(self, str_):
218 self._assert_bytes(str_)
218 self._assert_bytes(str_)
219 return hashlib.md5(str_).hexdigest()
219 return hashlib.md5(str_).hexdigest()
220
220
221 def hash_check(self, password, hashed):
221 def hash_check(self, password, hashed):
222 """
222 """
223 Checks matching password with it's hashed value.
223 Checks matching password with it's hashed value.
224
224
225 :param password: password
225 :param password: password
226 :param hashed: password in hashed form
226 :param hashed: password in hashed form
227 """
227 """
228 self._assert_bytes(password)
228 self._assert_bytes(password)
229 return hashlib.md5(password).hexdigest() == hashed
229 return hashlib.md5(password).hexdigest() == hashed
230
230
231
231
232 def crypto_backend():
232 def crypto_backend():
233 """
233 """
234 Return the matching crypto backend.
234 Return the matching crypto backend.
235
235
236 Selection is based on if we run tests or not, we pick md5 backend to run
236 Selection is based on if we run tests or not, we pick md5 backend to run
237 tests faster since BCRYPT is expensive to calculate
237 tests faster since BCRYPT is expensive to calculate
238 """
238 """
239 if rhodecode.is_test:
239 if rhodecode.is_test:
240 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
240 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
241 else:
241 else:
242 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
242 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
243
243
244 return RhodeCodeCrypto
244 return RhodeCodeCrypto
245
245
246
246
247 def get_crypt_password(password):
247 def get_crypt_password(password):
248 """
248 """
249 Create the hash of `password` with the active crypto backend.
249 Create the hash of `password` with the active crypto backend.
250
250
251 :param password: The cleartext password.
251 :param password: The cleartext password.
252 :type password: unicode
252 :type password: unicode
253 """
253 """
254 password = safe_str(password)
254 password = safe_str(password)
255 return crypto_backend().hash_create(password)
255 return crypto_backend().hash_create(password)
256
256
257
257
258 def check_password(password, hashed):
258 def check_password(password, hashed):
259 """
259 """
260 Check if the value in `password` matches the hash in `hashed`.
260 Check if the value in `password` matches the hash in `hashed`.
261
261
262 :param password: The cleartext password.
262 :param password: The cleartext password.
263 :type password: unicode
263 :type password: unicode
264
264
265 :param hashed: The expected hashed version of the password.
265 :param hashed: The expected hashed version of the password.
266 :type hashed: The hash has to be passed in in text representation.
266 :type hashed: The hash has to be passed in in text representation.
267 """
267 """
268 password = safe_str(password)
268 password = safe_str(password)
269 return crypto_backend().hash_check(password, hashed)
269 return crypto_backend().hash_check(password, hashed)
270
270
271
271
272 def generate_auth_token(data, salt=None):
272 def generate_auth_token(data, salt=None):
273 """
273 """
274 Generates API KEY from given string
274 Generates API KEY from given string
275 """
275 """
276
276
277 if salt is None:
277 if salt is None:
278 salt = os.urandom(16)
278 salt = os.urandom(16)
279 return hashlib.sha1(safe_str(data) + salt).hexdigest()
279 return hashlib.sha1(safe_str(data) + salt).hexdigest()
280
280
281
281
282 class CookieStoreWrapper(object):
282 class CookieStoreWrapper(object):
283
283
284 def __init__(self, cookie_store):
284 def __init__(self, cookie_store):
285 self.cookie_store = cookie_store
285 self.cookie_store = cookie_store
286
286
287 def __repr__(self):
287 def __repr__(self):
288 return 'CookieStore<%s>' % (self.cookie_store)
288 return 'CookieStore<%s>' % (self.cookie_store)
289
289
290 def get(self, key, other=None):
290 def get(self, key, other=None):
291 if isinstance(self.cookie_store, dict):
291 if isinstance(self.cookie_store, dict):
292 return self.cookie_store.get(key, other)
292 return self.cookie_store.get(key, other)
293 elif isinstance(self.cookie_store, AuthUser):
293 elif isinstance(self.cookie_store, AuthUser):
294 return self.cookie_store.__dict__.get(key, other)
294 return self.cookie_store.__dict__.get(key, other)
295
295
296
296
297 def _cached_perms_data(user_id, scope, user_is_admin,
297 def _cached_perms_data(user_id, scope, user_is_admin,
298 user_inherit_default_permissions, explicit, algo):
298 user_inherit_default_permissions, explicit, algo):
299
299
300 permissions = PermissionCalculator(
300 permissions = PermissionCalculator(
301 user_id, scope, user_is_admin, user_inherit_default_permissions,
301 user_id, scope, user_is_admin, user_inherit_default_permissions,
302 explicit, algo)
302 explicit, algo)
303 return permissions.calculate()
303 return permissions.calculate()
304
304
305 class PermOrigin:
305 class PermOrigin:
306 ADMIN = 'superadmin'
306 ADMIN = 'superadmin'
307
307
308 REPO_USER = 'user:%s'
308 REPO_USER = 'user:%s'
309 REPO_USERGROUP = 'usergroup:%s'
309 REPO_USERGROUP = 'usergroup:%s'
310 REPO_OWNER = 'repo.owner'
310 REPO_OWNER = 'repo.owner'
311 REPO_DEFAULT = 'repo.default'
311 REPO_DEFAULT = 'repo.default'
312 REPO_PRIVATE = 'repo.private'
312 REPO_PRIVATE = 'repo.private'
313
313
314 REPOGROUP_USER = 'user:%s'
314 REPOGROUP_USER = 'user:%s'
315 REPOGROUP_USERGROUP = 'usergroup:%s'
315 REPOGROUP_USERGROUP = 'usergroup:%s'
316 REPOGROUP_OWNER = 'group.owner'
316 REPOGROUP_OWNER = 'group.owner'
317 REPOGROUP_DEFAULT = 'group.default'
317 REPOGROUP_DEFAULT = 'group.default'
318
318
319 USERGROUP_USER = 'user:%s'
319 USERGROUP_USER = 'user:%s'
320 USERGROUP_USERGROUP = 'usergroup:%s'
320 USERGROUP_USERGROUP = 'usergroup:%s'
321 USERGROUP_OWNER = 'usergroup.owner'
321 USERGROUP_OWNER = 'usergroup.owner'
322 USERGROUP_DEFAULT = 'usergroup.default'
322 USERGROUP_DEFAULT = 'usergroup.default'
323
323
324
324
325 class PermOriginDict(dict):
325 class PermOriginDict(dict):
326 """
326 """
327 A special dict used for tracking permissions along with their origins.
327 A special dict used for tracking permissions along with their origins.
328
328
329 `__setitem__` has been overridden to expect a tuple(perm, origin)
329 `__setitem__` has been overridden to expect a tuple(perm, origin)
330 `__getitem__` will return only the perm
330 `__getitem__` will return only the perm
331 `.perm_origin_stack` will return the stack of (perm, origin) set per key
331 `.perm_origin_stack` will return the stack of (perm, origin) set per key
332
332
333 >>> perms = PermOriginDict()
333 >>> perms = PermOriginDict()
334 >>> perms['resource'] = 'read', 'default'
334 >>> perms['resource'] = 'read', 'default'
335 >>> perms['resource']
335 >>> perms['resource']
336 'read'
336 'read'
337 >>> perms['resource'] = 'write', 'admin'
337 >>> perms['resource'] = 'write', 'admin'
338 >>> perms['resource']
338 >>> perms['resource']
339 'write'
339 'write'
340 >>> perms.perm_origin_stack
340 >>> perms.perm_origin_stack
341 {'resource': [('read', 'default'), ('write', 'admin')]}
341 {'resource': [('read', 'default'), ('write', 'admin')]}
342 """
342 """
343
343
344
344
345 def __init__(self, *args, **kw):
345 def __init__(self, *args, **kw):
346 dict.__init__(self, *args, **kw)
346 dict.__init__(self, *args, **kw)
347 self.perm_origin_stack = {}
347 self.perm_origin_stack = {}
348
348
349 def __setitem__(self, key, (perm, origin)):
349 def __setitem__(self, key, (perm, origin)):
350 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
350 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
351 dict.__setitem__(self, key, perm)
351 dict.__setitem__(self, key, perm)
352
352
353
353
354 class PermissionCalculator(object):
354 class PermissionCalculator(object):
355
355
356 def __init__(
356 def __init__(
357 self, user_id, scope, user_is_admin,
357 self, user_id, scope, user_is_admin,
358 user_inherit_default_permissions, explicit, algo):
358 user_inherit_default_permissions, explicit, algo):
359 self.user_id = user_id
359 self.user_id = user_id
360 self.user_is_admin = user_is_admin
360 self.user_is_admin = user_is_admin
361 self.inherit_default_permissions = user_inherit_default_permissions
361 self.inherit_default_permissions = user_inherit_default_permissions
362 self.explicit = explicit
362 self.explicit = explicit
363 self.algo = algo
363 self.algo = algo
364
364
365 scope = scope or {}
365 scope = scope or {}
366 self.scope_repo_id = scope.get('repo_id')
366 self.scope_repo_id = scope.get('repo_id')
367 self.scope_repo_group_id = scope.get('repo_group_id')
367 self.scope_repo_group_id = scope.get('repo_group_id')
368 self.scope_user_group_id = scope.get('user_group_id')
368 self.scope_user_group_id = scope.get('user_group_id')
369
369
370 self.default_user_id = User.get_default_user(cache=True).user_id
370 self.default_user_id = User.get_default_user(cache=True).user_id
371
371
372 self.permissions_repositories = PermOriginDict()
372 self.permissions_repositories = PermOriginDict()
373 self.permissions_repository_groups = PermOriginDict()
373 self.permissions_repository_groups = PermOriginDict()
374 self.permissions_user_groups = PermOriginDict()
374 self.permissions_user_groups = PermOriginDict()
375 self.permissions_global = set()
375 self.permissions_global = set()
376
376
377 self.default_repo_perms = Permission.get_default_repo_perms(
377 self.default_repo_perms = Permission.get_default_repo_perms(
378 self.default_user_id, self.scope_repo_id)
378 self.default_user_id, self.scope_repo_id)
379 self.default_repo_groups_perms = Permission.get_default_group_perms(
379 self.default_repo_groups_perms = Permission.get_default_group_perms(
380 self.default_user_id, self.scope_repo_group_id)
380 self.default_user_id, self.scope_repo_group_id)
381 self.default_user_group_perms = \
381 self.default_user_group_perms = \
382 Permission.get_default_user_group_perms(
382 Permission.get_default_user_group_perms(
383 self.default_user_id, self.scope_user_group_id)
383 self.default_user_id, self.scope_user_group_id)
384
384
385 def calculate(self):
385 def calculate(self):
386 if self.user_is_admin:
386 if self.user_is_admin:
387 return self._admin_permissions()
387 return self._admin_permissions()
388
388
389 self._calculate_global_default_permissions()
389 self._calculate_global_default_permissions()
390 self._calculate_global_permissions()
390 self._calculate_global_permissions()
391 self._calculate_default_permissions()
391 self._calculate_default_permissions()
392 self._calculate_repository_permissions()
392 self._calculate_repository_permissions()
393 self._calculate_repository_group_permissions()
393 self._calculate_repository_group_permissions()
394 self._calculate_user_group_permissions()
394 self._calculate_user_group_permissions()
395 return self._permission_structure()
395 return self._permission_structure()
396
396
397 def _admin_permissions(self):
397 def _admin_permissions(self):
398 """
398 """
399 admin user have all default rights for repositories
399 admin user have all default rights for repositories
400 and groups set to admin
400 and groups set to admin
401 """
401 """
402 self.permissions_global.add('hg.admin')
402 self.permissions_global.add('hg.admin')
403 self.permissions_global.add('hg.create.write_on_repogroup.true')
403 self.permissions_global.add('hg.create.write_on_repogroup.true')
404
404
405 # repositories
405 # repositories
406 for perm in self.default_repo_perms:
406 for perm in self.default_repo_perms:
407 r_k = perm.UserRepoToPerm.repository.repo_name
407 r_k = perm.UserRepoToPerm.repository.repo_name
408 p = 'repository.admin'
408 p = 'repository.admin'
409 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
409 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
410
410
411 # repository groups
411 # repository groups
412 for perm in self.default_repo_groups_perms:
412 for perm in self.default_repo_groups_perms:
413 rg_k = perm.UserRepoGroupToPerm.group.group_name
413 rg_k = perm.UserRepoGroupToPerm.group.group_name
414 p = 'group.admin'
414 p = 'group.admin'
415 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
415 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
416
416
417 # user groups
417 # user groups
418 for perm in self.default_user_group_perms:
418 for perm in self.default_user_group_perms:
419 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
419 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
420 p = 'usergroup.admin'
420 p = 'usergroup.admin'
421 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
421 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
422
422
423 return self._permission_structure()
423 return self._permission_structure()
424
424
425 def _calculate_global_default_permissions(self):
425 def _calculate_global_default_permissions(self):
426 """
426 """
427 global permissions taken from the default user
427 global permissions taken from the default user
428 """
428 """
429 default_global_perms = UserToPerm.query()\
429 default_global_perms = UserToPerm.query()\
430 .filter(UserToPerm.user_id == self.default_user_id)\
430 .filter(UserToPerm.user_id == self.default_user_id)\
431 .options(joinedload(UserToPerm.permission))
431 .options(joinedload(UserToPerm.permission))
432
432
433 for perm in default_global_perms:
433 for perm in default_global_perms:
434 self.permissions_global.add(perm.permission.permission_name)
434 self.permissions_global.add(perm.permission.permission_name)
435
435
436 def _calculate_global_permissions(self):
436 def _calculate_global_permissions(self):
437 """
437 """
438 Set global system permissions with user permissions or permissions
438 Set global system permissions with user permissions or permissions
439 taken from the user groups of the current user.
439 taken from the user groups of the current user.
440
440
441 The permissions include repo creating, repo group creating, forking
441 The permissions include repo creating, repo group creating, forking
442 etc.
442 etc.
443 """
443 """
444
444
445 # now we read the defined permissions and overwrite what we have set
445 # now we read the defined permissions and overwrite what we have set
446 # before those can be configured from groups or users explicitly.
446 # before those can be configured from groups or users explicitly.
447
447
448 # TODO: johbo: This seems to be out of sync, find out the reason
448 # TODO: johbo: This seems to be out of sync, find out the reason
449 # for the comment below and update it.
449 # for the comment below and update it.
450
450
451 # In case we want to extend this list we should be always in sync with
451 # In case we want to extend this list we should be always in sync with
452 # User.DEFAULT_USER_PERMISSIONS definitions
452 # User.DEFAULT_USER_PERMISSIONS definitions
453 _configurable = frozenset([
453 _configurable = frozenset([
454 'hg.fork.none', 'hg.fork.repository',
454 'hg.fork.none', 'hg.fork.repository',
455 'hg.create.none', 'hg.create.repository',
455 'hg.create.none', 'hg.create.repository',
456 'hg.usergroup.create.false', 'hg.usergroup.create.true',
456 'hg.usergroup.create.false', 'hg.usergroup.create.true',
457 'hg.repogroup.create.false', 'hg.repogroup.create.true',
457 'hg.repogroup.create.false', 'hg.repogroup.create.true',
458 'hg.create.write_on_repogroup.false',
458 'hg.create.write_on_repogroup.false',
459 'hg.create.write_on_repogroup.true',
459 'hg.create.write_on_repogroup.true',
460 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
460 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
461 ])
461 ])
462
462
463 # USER GROUPS comes first user group global permissions
463 # USER GROUPS comes first user group global permissions
464 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
464 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
465 .options(joinedload(UserGroupToPerm.permission))\
465 .options(joinedload(UserGroupToPerm.permission))\
466 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
466 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
467 UserGroupMember.users_group_id))\
467 UserGroupMember.users_group_id))\
468 .filter(UserGroupMember.user_id == self.user_id)\
468 .filter(UserGroupMember.user_id == self.user_id)\
469 .order_by(UserGroupToPerm.users_group_id)\
469 .order_by(UserGroupToPerm.users_group_id)\
470 .all()
470 .all()
471
471
472 # need to group here by groups since user can be in more than
472 # need to group here by groups since user can be in more than
473 # one group, so we get all groups
473 # one group, so we get all groups
474 _explicit_grouped_perms = [
474 _explicit_grouped_perms = [
475 [x, list(y)] for x, y in
475 [x, list(y)] for x, y in
476 itertools.groupby(user_perms_from_users_groups,
476 itertools.groupby(user_perms_from_users_groups,
477 lambda _x: _x.users_group)]
477 lambda _x: _x.users_group)]
478
478
479 for gr, perms in _explicit_grouped_perms:
479 for gr, perms in _explicit_grouped_perms:
480 # since user can be in multiple groups iterate over them and
480 # since user can be in multiple groups iterate over them and
481 # select the lowest permissions first (more explicit)
481 # select the lowest permissions first (more explicit)
482 # TODO: marcink: do this^^
482 # TODO: marcink: do this^^
483
483
484 # group doesn't inherit default permissions so we actually set them
484 # group doesn't inherit default permissions so we actually set them
485 if not gr.inherit_default_permissions:
485 if not gr.inherit_default_permissions:
486 # NEED TO IGNORE all previously set configurable permissions
486 # NEED TO IGNORE all previously set configurable permissions
487 # and replace them with explicitly set from this user
487 # and replace them with explicitly set from this user
488 # group permissions
488 # group permissions
489 self.permissions_global = self.permissions_global.difference(
489 self.permissions_global = self.permissions_global.difference(
490 _configurable)
490 _configurable)
491 for perm in perms:
491 for perm in perms:
492 self.permissions_global.add(perm.permission.permission_name)
492 self.permissions_global.add(perm.permission.permission_name)
493
493
494 # user explicit global permissions
494 # user explicit global permissions
495 user_perms = Session().query(UserToPerm)\
495 user_perms = Session().query(UserToPerm)\
496 .options(joinedload(UserToPerm.permission))\
496 .options(joinedload(UserToPerm.permission))\
497 .filter(UserToPerm.user_id == self.user_id).all()
497 .filter(UserToPerm.user_id == self.user_id).all()
498
498
499 if not self.inherit_default_permissions:
499 if not self.inherit_default_permissions:
500 # NEED TO IGNORE all configurable permissions and
500 # NEED TO IGNORE all configurable permissions and
501 # replace them with explicitly set from this user permissions
501 # replace them with explicitly set from this user permissions
502 self.permissions_global = self.permissions_global.difference(
502 self.permissions_global = self.permissions_global.difference(
503 _configurable)
503 _configurable)
504 for perm in user_perms:
504 for perm in user_perms:
505 self.permissions_global.add(perm.permission.permission_name)
505 self.permissions_global.add(perm.permission.permission_name)
506
506
507 def _calculate_default_permissions(self):
507 def _calculate_default_permissions(self):
508 """
508 """
509 Set default user permissions for repositories, repository groups
509 Set default user permissions for repositories, repository groups
510 taken from the default user.
510 taken from the default user.
511
511
512 Calculate inheritance of object permissions based on what we have now
512 Calculate inheritance of object permissions based on what we have now
513 in GLOBAL permissions. We check if .false is in GLOBAL since this is
513 in GLOBAL permissions. We check if .false is in GLOBAL since this is
514 explicitly set. Inherit is the opposite of .false being there.
514 explicitly set. Inherit is the opposite of .false being there.
515
515
516 .. note::
516 .. note::
517
517
518 the syntax is little bit odd but what we need to check here is
518 the syntax is little bit odd but what we need to check here is
519 the opposite of .false permission being in the list so even for
519 the opposite of .false permission being in the list so even for
520 inconsistent state when both .true/.false is there
520 inconsistent state when both .true/.false is there
521 .false is more important
521 .false is more important
522
522
523 """
523 """
524 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
524 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
525 in self.permissions_global)
525 in self.permissions_global)
526
526
527 # defaults for repositories, taken from `default` user permissions
527 # defaults for repositories, taken from `default` user permissions
528 # on given repo
528 # on given repo
529 for perm in self.default_repo_perms:
529 for perm in self.default_repo_perms:
530 r_k = perm.UserRepoToPerm.repository.repo_name
530 r_k = perm.UserRepoToPerm.repository.repo_name
531 o = PermOrigin.REPO_DEFAULT
531 o = PermOrigin.REPO_DEFAULT
532 if perm.Repository.private and not (
532 if perm.Repository.private and not (
533 perm.Repository.user_id == self.user_id):
533 perm.Repository.user_id == self.user_id):
534 # disable defaults for private repos,
534 # disable defaults for private repos,
535 p = 'repository.none'
535 p = 'repository.none'
536 o = PermOrigin.REPO_PRIVATE
536 o = PermOrigin.REPO_PRIVATE
537 elif perm.Repository.user_id == self.user_id:
537 elif perm.Repository.user_id == self.user_id:
538 # set admin if owner
538 # set admin if owner
539 p = 'repository.admin'
539 p = 'repository.admin'
540 o = PermOrigin.REPO_OWNER
540 o = PermOrigin.REPO_OWNER
541 else:
541 else:
542 p = perm.Permission.permission_name
542 p = perm.Permission.permission_name
543 # if we decide this user isn't inheriting permissions from
543 # if we decide this user isn't inheriting permissions from
544 # default user we set him to .none so only explicit
544 # default user we set him to .none so only explicit
545 # permissions work
545 # permissions work
546 if not user_inherit_object_permissions:
546 if not user_inherit_object_permissions:
547 p = 'repository.none'
547 p = 'repository.none'
548 self.permissions_repositories[r_k] = p, o
548 self.permissions_repositories[r_k] = p, o
549
549
550 # defaults for repository groups taken from `default` user permission
550 # defaults for repository groups taken from `default` user permission
551 # on given group
551 # on given group
552 for perm in self.default_repo_groups_perms:
552 for perm in self.default_repo_groups_perms:
553 rg_k = perm.UserRepoGroupToPerm.group.group_name
553 rg_k = perm.UserRepoGroupToPerm.group.group_name
554 o = PermOrigin.REPOGROUP_DEFAULT
554 o = PermOrigin.REPOGROUP_DEFAULT
555 if perm.RepoGroup.user_id == self.user_id:
555 if perm.RepoGroup.user_id == self.user_id:
556 # set admin if owner
556 # set admin if owner
557 p = 'group.admin'
557 p = 'group.admin'
558 o = PermOrigin.REPOGROUP_OWNER
558 o = PermOrigin.REPOGROUP_OWNER
559 else:
559 else:
560 p = perm.Permission.permission_name
560 p = perm.Permission.permission_name
561
561
562 # if we decide this user isn't inheriting permissions from default
562 # if we decide this user isn't inheriting permissions from default
563 # user we set him to .none so only explicit permissions work
563 # user we set him to .none so only explicit permissions work
564 if not user_inherit_object_permissions:
564 if not user_inherit_object_permissions:
565 p = 'group.none'
565 p = 'group.none'
566 self.permissions_repository_groups[rg_k] = p, o
566 self.permissions_repository_groups[rg_k] = p, o
567
567
568 # defaults for user groups taken from `default` user permission
568 # defaults for user groups taken from `default` user permission
569 # on given user group
569 # on given user group
570 for perm in self.default_user_group_perms:
570 for perm in self.default_user_group_perms:
571 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
571 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
572 o = PermOrigin.USERGROUP_DEFAULT
572 o = PermOrigin.USERGROUP_DEFAULT
573 if perm.UserGroup.user_id == self.user_id:
573 if perm.UserGroup.user_id == self.user_id:
574 # set admin if owner
574 # set admin if owner
575 p = 'usergroup.admin'
575 p = 'usergroup.admin'
576 o = PermOrigin.USERGROUP_OWNER
576 o = PermOrigin.USERGROUP_OWNER
577 else:
577 else:
578 p = perm.Permission.permission_name
578 p = perm.Permission.permission_name
579
579
580 # if we decide this user isn't inheriting permissions from default
580 # if we decide this user isn't inheriting permissions from default
581 # user we set him to .none so only explicit permissions work
581 # user we set him to .none so only explicit permissions work
582 if not user_inherit_object_permissions:
582 if not user_inherit_object_permissions:
583 p = 'usergroup.none'
583 p = 'usergroup.none'
584 self.permissions_user_groups[u_k] = p, o
584 self.permissions_user_groups[u_k] = p, o
585
585
586 def _calculate_repository_permissions(self):
586 def _calculate_repository_permissions(self):
587 """
587 """
588 Repository permissions for the current user.
588 Repository permissions for the current user.
589
589
590 Check if the user is part of user groups for this repository and
590 Check if the user is part of user groups for this repository and
591 fill in the permission from it. `_choose_permission` decides of which
591 fill in the permission from it. `_choose_permission` decides of which
592 permission should be selected based on selected method.
592 permission should be selected based on selected method.
593 """
593 """
594
594
595 # user group for repositories permissions
595 # user group for repositories permissions
596 user_repo_perms_from_user_group = Permission\
596 user_repo_perms_from_user_group = Permission\
597 .get_default_repo_perms_from_user_group(
597 .get_default_repo_perms_from_user_group(
598 self.user_id, self.scope_repo_id)
598 self.user_id, self.scope_repo_id)
599
599
600 multiple_counter = collections.defaultdict(int)
600 multiple_counter = collections.defaultdict(int)
601 for perm in user_repo_perms_from_user_group:
601 for perm in user_repo_perms_from_user_group:
602 r_k = perm.UserGroupRepoToPerm.repository.repo_name
602 r_k = perm.UserGroupRepoToPerm.repository.repo_name
603 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
603 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
604 multiple_counter[r_k] += 1
604 multiple_counter[r_k] += 1
605 p = perm.Permission.permission_name
605 p = perm.Permission.permission_name
606 o = PermOrigin.REPO_USERGROUP % ug_k
606 o = PermOrigin.REPO_USERGROUP % ug_k
607
607
608 if perm.Repository.user_id == self.user_id:
608 if perm.Repository.user_id == self.user_id:
609 # set admin if owner
609 # set admin if owner
610 p = 'repository.admin'
610 p = 'repository.admin'
611 o = PermOrigin.REPO_OWNER
611 o = PermOrigin.REPO_OWNER
612 else:
612 else:
613 if multiple_counter[r_k] > 1:
613 if multiple_counter[r_k] > 1:
614 cur_perm = self.permissions_repositories[r_k]
614 cur_perm = self.permissions_repositories[r_k]
615 p = self._choose_permission(p, cur_perm)
615 p = self._choose_permission(p, cur_perm)
616 self.permissions_repositories[r_k] = p, o
616 self.permissions_repositories[r_k] = p, o
617
617
618 # user explicit permissions for repositories, overrides any specified
618 # user explicit permissions for repositories, overrides any specified
619 # by the group permission
619 # by the group permission
620 user_repo_perms = Permission.get_default_repo_perms(
620 user_repo_perms = Permission.get_default_repo_perms(
621 self.user_id, self.scope_repo_id)
621 self.user_id, self.scope_repo_id)
622 for perm in user_repo_perms:
622 for perm in user_repo_perms:
623 r_k = perm.UserRepoToPerm.repository.repo_name
623 r_k = perm.UserRepoToPerm.repository.repo_name
624 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
624 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
625 # set admin if owner
625 # set admin if owner
626 if perm.Repository.user_id == self.user_id:
626 if perm.Repository.user_id == self.user_id:
627 p = 'repository.admin'
627 p = 'repository.admin'
628 o = PermOrigin.REPO_OWNER
628 o = PermOrigin.REPO_OWNER
629 else:
629 else:
630 p = perm.Permission.permission_name
630 p = perm.Permission.permission_name
631 if not self.explicit:
631 if not self.explicit:
632 cur_perm = self.permissions_repositories.get(
632 cur_perm = self.permissions_repositories.get(
633 r_k, 'repository.none')
633 r_k, 'repository.none')
634 p = self._choose_permission(p, cur_perm)
634 p = self._choose_permission(p, cur_perm)
635 self.permissions_repositories[r_k] = p, o
635 self.permissions_repositories[r_k] = p, o
636
636
637 def _calculate_repository_group_permissions(self):
637 def _calculate_repository_group_permissions(self):
638 """
638 """
639 Repository group permissions for the current user.
639 Repository group permissions for the current user.
640
640
641 Check if the user is part of user groups for repository groups and
641 Check if the user is part of user groups for repository groups and
642 fill in the permissions from it. `_choose_permmission` decides of which
642 fill in the permissions from it. `_choose_permmission` decides of which
643 permission should be selected based on selected method.
643 permission should be selected based on selected method.
644 """
644 """
645 # user group for repo groups permissions
645 # user group for repo groups permissions
646 user_repo_group_perms_from_user_group = Permission\
646 user_repo_group_perms_from_user_group = Permission\
647 .get_default_group_perms_from_user_group(
647 .get_default_group_perms_from_user_group(
648 self.user_id, self.scope_repo_group_id)
648 self.user_id, self.scope_repo_group_id)
649
649
650 multiple_counter = collections.defaultdict(int)
650 multiple_counter = collections.defaultdict(int)
651 for perm in user_repo_group_perms_from_user_group:
651 for perm in user_repo_group_perms_from_user_group:
652 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
652 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
653 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
653 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
654 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
654 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
655 multiple_counter[g_k] += 1
655 multiple_counter[g_k] += 1
656 p = perm.Permission.permission_name
656 p = perm.Permission.permission_name
657 if perm.RepoGroup.user_id == self.user_id:
657 if perm.RepoGroup.user_id == self.user_id:
658 # set admin if owner, even for member of other user group
658 # set admin if owner, even for member of other user group
659 p = 'group.admin'
659 p = 'group.admin'
660 o = PermOrigin.REPOGROUP_OWNER
660 o = PermOrigin.REPOGROUP_OWNER
661 else:
661 else:
662 if multiple_counter[g_k] > 1:
662 if multiple_counter[g_k] > 1:
663 cur_perm = self.permissions_repository_groups[g_k]
663 cur_perm = self.permissions_repository_groups[g_k]
664 p = self._choose_permission(p, cur_perm)
664 p = self._choose_permission(p, cur_perm)
665 self.permissions_repository_groups[g_k] = p, o
665 self.permissions_repository_groups[g_k] = p, o
666
666
667 # user explicit permissions for repository groups
667 # user explicit permissions for repository groups
668 user_repo_groups_perms = Permission.get_default_group_perms(
668 user_repo_groups_perms = Permission.get_default_group_perms(
669 self.user_id, self.scope_repo_group_id)
669 self.user_id, self.scope_repo_group_id)
670 for perm in user_repo_groups_perms:
670 for perm in user_repo_groups_perms:
671 rg_k = perm.UserRepoGroupToPerm.group.group_name
671 rg_k = perm.UserRepoGroupToPerm.group.group_name
672 u_k = perm.UserRepoGroupToPerm.user.username
672 u_k = perm.UserRepoGroupToPerm.user.username
673 o = PermOrigin.REPOGROUP_USER % u_k
673 o = PermOrigin.REPOGROUP_USER % u_k
674
674
675 if perm.RepoGroup.user_id == self.user_id:
675 if perm.RepoGroup.user_id == self.user_id:
676 # set admin if owner
676 # set admin if owner
677 p = 'group.admin'
677 p = 'group.admin'
678 o = PermOrigin.REPOGROUP_OWNER
678 o = PermOrigin.REPOGROUP_OWNER
679 else:
679 else:
680 p = perm.Permission.permission_name
680 p = perm.Permission.permission_name
681 if not self.explicit:
681 if not self.explicit:
682 cur_perm = self.permissions_repository_groups.get(
682 cur_perm = self.permissions_repository_groups.get(
683 rg_k, 'group.none')
683 rg_k, 'group.none')
684 p = self._choose_permission(p, cur_perm)
684 p = self._choose_permission(p, cur_perm)
685 self.permissions_repository_groups[rg_k] = p, o
685 self.permissions_repository_groups[rg_k] = p, o
686
686
687 def _calculate_user_group_permissions(self):
687 def _calculate_user_group_permissions(self):
688 """
688 """
689 User group permissions for the current user.
689 User group permissions for the current user.
690 """
690 """
691 # user group for user group permissions
691 # user group for user group permissions
692 user_group_from_user_group = Permission\
692 user_group_from_user_group = Permission\
693 .get_default_user_group_perms_from_user_group(
693 .get_default_user_group_perms_from_user_group(
694 self.user_id, self.scope_user_group_id)
694 self.user_id, self.scope_user_group_id)
695
695
696 multiple_counter = collections.defaultdict(int)
696 multiple_counter = collections.defaultdict(int)
697 for perm in user_group_from_user_group:
697 for perm in user_group_from_user_group:
698 g_k = perm.UserGroupUserGroupToPerm\
698 g_k = perm.UserGroupUserGroupToPerm\
699 .target_user_group.users_group_name
699 .target_user_group.users_group_name
700 u_k = perm.UserGroupUserGroupToPerm\
700 u_k = perm.UserGroupUserGroupToPerm\
701 .user_group.users_group_name
701 .user_group.users_group_name
702 o = PermOrigin.USERGROUP_USERGROUP % u_k
702 o = PermOrigin.USERGROUP_USERGROUP % u_k
703 multiple_counter[g_k] += 1
703 multiple_counter[g_k] += 1
704 p = perm.Permission.permission_name
704 p = perm.Permission.permission_name
705
705
706 if perm.UserGroup.user_id == self.user_id:
706 if perm.UserGroup.user_id == self.user_id:
707 # set admin if owner, even for member of other user group
707 # set admin if owner, even for member of other user group
708 p = 'usergroup.admin'
708 p = 'usergroup.admin'
709 o = PermOrigin.USERGROUP_OWNER
709 o = PermOrigin.USERGROUP_OWNER
710 else:
710 else:
711 if multiple_counter[g_k] > 1:
711 if multiple_counter[g_k] > 1:
712 cur_perm = self.permissions_user_groups[g_k]
712 cur_perm = self.permissions_user_groups[g_k]
713 p = self._choose_permission(p, cur_perm)
713 p = self._choose_permission(p, cur_perm)
714 self.permissions_user_groups[g_k] = p, o
714 self.permissions_user_groups[g_k] = p, o
715
715
716 # user explicit permission for user groups
716 # user explicit permission for user groups
717 user_user_groups_perms = Permission.get_default_user_group_perms(
717 user_user_groups_perms = Permission.get_default_user_group_perms(
718 self.user_id, self.scope_user_group_id)
718 self.user_id, self.scope_user_group_id)
719 for perm in user_user_groups_perms:
719 for perm in user_user_groups_perms:
720 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
720 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
721 u_k = perm.UserUserGroupToPerm.user.username
721 u_k = perm.UserUserGroupToPerm.user.username
722 o = PermOrigin.USERGROUP_USER % u_k
722 o = PermOrigin.USERGROUP_USER % u_k
723
723
724 if perm.UserGroup.user_id == self.user_id:
724 if perm.UserGroup.user_id == self.user_id:
725 # set admin if owner
725 # set admin if owner
726 p = 'usergroup.admin'
726 p = 'usergroup.admin'
727 o = PermOrigin.USERGROUP_OWNER
727 o = PermOrigin.USERGROUP_OWNER
728 else:
728 else:
729 p = perm.Permission.permission_name
729 p = perm.Permission.permission_name
730 if not self.explicit:
730 if not self.explicit:
731 cur_perm = self.permissions_user_groups.get(
731 cur_perm = self.permissions_user_groups.get(
732 ug_k, 'usergroup.none')
732 ug_k, 'usergroup.none')
733 p = self._choose_permission(p, cur_perm)
733 p = self._choose_permission(p, cur_perm)
734 self.permissions_user_groups[ug_k] = p, o
734 self.permissions_user_groups[ug_k] = p, o
735
735
736 def _choose_permission(self, new_perm, cur_perm):
736 def _choose_permission(self, new_perm, cur_perm):
737 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
737 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
738 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
738 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
739 if self.algo == 'higherwin':
739 if self.algo == 'higherwin':
740 if new_perm_val > cur_perm_val:
740 if new_perm_val > cur_perm_val:
741 return new_perm
741 return new_perm
742 return cur_perm
742 return cur_perm
743 elif self.algo == 'lowerwin':
743 elif self.algo == 'lowerwin':
744 if new_perm_val < cur_perm_val:
744 if new_perm_val < cur_perm_val:
745 return new_perm
745 return new_perm
746 return cur_perm
746 return cur_perm
747
747
748 def _permission_structure(self):
748 def _permission_structure(self):
749 return {
749 return {
750 'global': self.permissions_global,
750 'global': self.permissions_global,
751 'repositories': self.permissions_repositories,
751 'repositories': self.permissions_repositories,
752 'repositories_groups': self.permissions_repository_groups,
752 'repositories_groups': self.permissions_repository_groups,
753 'user_groups': self.permissions_user_groups,
753 'user_groups': self.permissions_user_groups,
754 }
754 }
755
755
756
756
757 def allowed_auth_token_access(controller_name, whitelist=None, auth_token=None):
757 def allowed_auth_token_access(controller_name, whitelist=None, auth_token=None):
758 """
758 """
759 Check if given controller_name is in whitelist of auth token access
759 Check if given controller_name is in whitelist of auth token access
760 """
760 """
761 if not whitelist:
761 if not whitelist:
762 from rhodecode import CONFIG
762 from rhodecode import CONFIG
763 whitelist = aslist(
763 whitelist = aslist(
764 CONFIG.get('api_access_controllers_whitelist'), sep=',')
764 CONFIG.get('api_access_controllers_whitelist'), sep=',')
765 log.debug(
765 log.debug(
766 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,))
766 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,))
767
767
768 auth_token_access_valid = False
768 auth_token_access_valid = False
769 for entry in whitelist:
769 for entry in whitelist:
770 if fnmatch.fnmatch(controller_name, entry):
770 if fnmatch.fnmatch(controller_name, entry):
771 auth_token_access_valid = True
771 auth_token_access_valid = True
772 break
772 break
773
773
774 if auth_token_access_valid:
774 if auth_token_access_valid:
775 log.debug('controller:%s matches entry in whitelist'
775 log.debug('controller:%s matches entry in whitelist'
776 % (controller_name,))
776 % (controller_name,))
777 else:
777 else:
778 msg = ('controller: %s does *NOT* match any entry in whitelist'
778 msg = ('controller: %s does *NOT* match any entry in whitelist'
779 % (controller_name,))
779 % (controller_name,))
780 if auth_token:
780 if auth_token:
781 # if we use auth token key and don't have access it's a warning
781 # if we use auth token key and don't have access it's a warning
782 log.warning(msg)
782 log.warning(msg)
783 else:
783 else:
784 log.debug(msg)
784 log.debug(msg)
785
785
786 return auth_token_access_valid
786 return auth_token_access_valid
787
787
788
788
789 class AuthUser(object):
789 class AuthUser(object):
790 """
790 """
791 A simple object that handles all attributes of user in RhodeCode
791 A simple object that handles all attributes of user in RhodeCode
792
792
793 It does lookup based on API key,given user, or user present in session
793 It does lookup based on API key,given user, or user present in session
794 Then it fills all required information for such user. It also checks if
794 Then it fills all required information for such user. It also checks if
795 anonymous access is enabled and if so, it returns default user as logged in
795 anonymous access is enabled and if so, it returns default user as logged in
796 """
796 """
797 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
797 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
798
798
799 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
799 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
800
800
801 self.user_id = user_id
801 self.user_id = user_id
802 self._api_key = api_key
802 self._api_key = api_key
803
803
804 self.api_key = None
804 self.api_key = None
805 self.feed_token = ''
805 self.feed_token = ''
806 self.username = username
806 self.username = username
807 self.ip_addr = ip_addr
807 self.ip_addr = ip_addr
808 self.name = ''
808 self.name = ''
809 self.lastname = ''
809 self.lastname = ''
810 self.email = ''
810 self.email = ''
811 self.is_authenticated = False
811 self.is_authenticated = False
812 self.admin = False
812 self.admin = False
813 self.inherit_default_permissions = False
813 self.inherit_default_permissions = False
814 self.password = ''
814 self.password = ''
815
815
816 self.anonymous_user = None # propagated on propagate_data
816 self.anonymous_user = None # propagated on propagate_data
817 self.propagate_data()
817 self.propagate_data()
818 self._instance = None
818 self._instance = None
819 self._permissions_scoped_cache = {} # used to bind scoped calculation
819 self._permissions_scoped_cache = {} # used to bind scoped calculation
820
820
821 @LazyProperty
821 @LazyProperty
822 def permissions(self):
822 def permissions(self):
823 return self.get_perms(user=self, cache=False)
823 return self.get_perms(user=self, cache=False)
824
824
825 def permissions_with_scope(self, scope):
825 def permissions_with_scope(self, scope):
826 """
826 """
827 Call the get_perms function with scoped data. The scope in that function
827 Call the get_perms function with scoped data. The scope in that function
828 narrows the SQL calls to the given ID of objects resulting in fetching
828 narrows the SQL calls to the given ID of objects resulting in fetching
829 Just particular permission we want to obtain. If scope is an empty dict
829 Just particular permission we want to obtain. If scope is an empty dict
830 then it basically narrows the scope to GLOBAL permissions only.
830 then it basically narrows the scope to GLOBAL permissions only.
831
831
832 :param scope: dict
832 :param scope: dict
833 """
833 """
834 if 'repo_name' in scope:
834 if 'repo_name' in scope:
835 obj = Repository.get_by_repo_name(scope['repo_name'])
835 obj = Repository.get_by_repo_name(scope['repo_name'])
836 if obj:
836 if obj:
837 scope['repo_id'] = obj.repo_id
837 scope['repo_id'] = obj.repo_id
838 _scope = {
838 _scope = {
839 'repo_id': -1,
839 'repo_id': -1,
840 'user_group_id': -1,
840 'user_group_id': -1,
841 'repo_group_id': -1,
841 'repo_group_id': -1,
842 }
842 }
843 _scope.update(scope)
843 _scope.update(scope)
844 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
844 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
845 _scope.items())))
845 _scope.items())))
846 if cache_key not in self._permissions_scoped_cache:
846 if cache_key not in self._permissions_scoped_cache:
847 # store in cache to mimic how the @LazyProperty works,
847 # store in cache to mimic how the @LazyProperty works,
848 # the difference here is that we use the unique key calculated
848 # the difference here is that we use the unique key calculated
849 # from params and values
849 # from params and values
850 res = self.get_perms(user=self, cache=False, scope=_scope)
850 res = self.get_perms(user=self, cache=False, scope=_scope)
851 self._permissions_scoped_cache[cache_key] = res
851 self._permissions_scoped_cache[cache_key] = res
852 return self._permissions_scoped_cache[cache_key]
852 return self._permissions_scoped_cache[cache_key]
853
853
854 def get_instance(self):
854 def get_instance(self):
855 return User.get(self.user_id)
855 return User.get(self.user_id)
856
856
857 def update_lastactivity(self):
857 def update_lastactivity(self):
858 if self.user_id:
858 if self.user_id:
859 User.get(self.user_id).update_lastactivity()
859 User.get(self.user_id).update_lastactivity()
860
860
861 def propagate_data(self):
861 def propagate_data(self):
862 """
862 """
863 Fills in user data and propagates values to this instance. Maps fetched
863 Fills in user data and propagates values to this instance. Maps fetched
864 user attributes to this class instance attributes
864 user attributes to this class instance attributes
865 """
865 """
866 log.debug('starting data propagation for new potential AuthUser')
866 log.debug('starting data propagation for new potential AuthUser')
867 user_model = UserModel()
867 user_model = UserModel()
868 anon_user = self.anonymous_user = User.get_default_user(cache=True)
868 anon_user = self.anonymous_user = User.get_default_user(cache=True)
869 is_user_loaded = False
869 is_user_loaded = False
870
870
871 # lookup by userid
871 # lookup by userid
872 if self.user_id is not None and self.user_id != anon_user.user_id:
872 if self.user_id is not None and self.user_id != anon_user.user_id:
873 log.debug('Trying Auth User lookup by USER ID: `%s`' % self.user_id)
873 log.debug('Trying Auth User lookup by USER ID: `%s`' % self.user_id)
874 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
874 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
875
875
876 # try go get user by api key
876 # try go get user by api key
877 elif self._api_key and self._api_key != anon_user.api_key:
877 elif self._api_key and self._api_key != anon_user.api_key:
878 log.debug('Trying Auth User lookup by API KEY: `%s`' % self._api_key)
878 log.debug('Trying Auth User lookup by API KEY: `%s`' % self._api_key)
879 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
879 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
880
880
881 # lookup by username
881 # lookup by username
882 elif self.username:
882 elif self.username:
883 log.debug('Trying Auth User lookup by USER NAME: `%s`' % self.username)
883 log.debug('Trying Auth User lookup by USER NAME: `%s`' % self.username)
884 is_user_loaded = user_model.fill_data(self, username=self.username)
884 is_user_loaded = user_model.fill_data(self, username=self.username)
885 else:
885 else:
886 log.debug('No data in %s that could been used to log in' % self)
886 log.debug('No data in %s that could been used to log in' % self)
887
887
888 if not is_user_loaded:
888 if not is_user_loaded:
889 log.debug('Failed to load user. Fallback to default user')
889 log.debug('Failed to load user. Fallback to default user')
890 # if we cannot authenticate user try anonymous
890 # if we cannot authenticate user try anonymous
891 if anon_user.active:
891 if anon_user.active:
892 user_model.fill_data(self, user_id=anon_user.user_id)
892 user_model.fill_data(self, user_id=anon_user.user_id)
893 # then we set this user is logged in
893 # then we set this user is logged in
894 self.is_authenticated = True
894 self.is_authenticated = True
895 else:
895 else:
896 # in case of disabled anonymous user we reset some of the
896 # in case of disabled anonymous user we reset some of the
897 # parameters so such user is "corrupted", skipping the fill_data
897 # parameters so such user is "corrupted", skipping the fill_data
898 for attr in ['user_id', 'username', 'admin', 'active']:
898 for attr in ['user_id', 'username', 'admin', 'active']:
899 setattr(self, attr, None)
899 setattr(self, attr, None)
900 self.is_authenticated = False
900 self.is_authenticated = False
901
901
902 if not self.username:
902 if not self.username:
903 self.username = 'None'
903 self.username = 'None'
904
904
905 log.debug('Auth User is now %s' % self)
905 log.debug('Auth User is now %s' % self)
906
906
907 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
907 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
908 cache=False):
908 cache=False):
909 """
909 """
910 Fills user permission attribute with permissions taken from database
910 Fills user permission attribute with permissions taken from database
911 works for permissions given for repositories, and for permissions that
911 works for permissions given for repositories, and for permissions that
912 are granted to groups
912 are granted to groups
913
913
914 :param user: instance of User object from database
914 :param user: instance of User object from database
915 :param explicit: In case there are permissions both for user and a group
915 :param explicit: In case there are permissions both for user and a group
916 that user is part of, explicit flag will defiine if user will
916 that user is part of, explicit flag will defiine if user will
917 explicitly override permissions from group, if it's False it will
917 explicitly override permissions from group, if it's False it will
918 make decision based on the algo
918 make decision based on the algo
919 :param algo: algorithm to decide what permission should be choose if
919 :param algo: algorithm to decide what permission should be choose if
920 it's multiple defined, eg user in two different groups. It also
920 it's multiple defined, eg user in two different groups. It also
921 decides if explicit flag is turned off how to specify the permission
921 decides if explicit flag is turned off how to specify the permission
922 for case when user is in a group + have defined separate permission
922 for case when user is in a group + have defined separate permission
923 """
923 """
924 user_id = user.user_id
924 user_id = user.user_id
925 user_is_admin = user.is_admin
925 user_is_admin = user.is_admin
926
926
927 # inheritance of global permissions like create repo/fork repo etc
927 # inheritance of global permissions like create repo/fork repo etc
928 user_inherit_default_permissions = user.inherit_default_permissions
928 user_inherit_default_permissions = user.inherit_default_permissions
929
929
930 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
930 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
931 compute = caches.conditional_cache(
931 compute = caches.conditional_cache(
932 'short_term', 'cache_desc',
932 'short_term', 'cache_desc',
933 condition=cache, func=_cached_perms_data)
933 condition=cache, func=_cached_perms_data)
934 result = compute(user_id, scope, user_is_admin,
934 result = compute(user_id, scope, user_is_admin,
935 user_inherit_default_permissions, explicit, algo)
935 user_inherit_default_permissions, explicit, algo)
936
936
937 result_repr = []
937 result_repr = []
938 for k in result:
938 for k in result:
939 result_repr.append((k, len(result[k])))
939 result_repr.append((k, len(result[k])))
940
940
941 log.debug('PERMISSION tree computed %s' % (result_repr,))
941 log.debug('PERMISSION tree computed %s' % (result_repr,))
942 return result
942 return result
943
943
944 @property
944 @property
945 def is_default(self):
945 def is_default(self):
946 return self.username == User.DEFAULT_USER
946 return self.username == User.DEFAULT_USER
947
947
948 @property
948 @property
949 def is_admin(self):
949 def is_admin(self):
950 return self.admin
950 return self.admin
951
951
952 @property
952 @property
953 def is_user_object(self):
953 def is_user_object(self):
954 return self.user_id is not None
954 return self.user_id is not None
955
955
956 @property
956 @property
957 def repositories_admin(self):
957 def repositories_admin(self):
958 """
958 """
959 Returns list of repositories you're an admin of
959 Returns list of repositories you're an admin of
960 """
960 """
961 return [
961 return [
962 x[0] for x in self.permissions['repositories'].iteritems()
962 x[0] for x in self.permissions['repositories'].iteritems()
963 if x[1] == 'repository.admin']
963 if x[1] == 'repository.admin']
964
964
965 @property
965 @property
966 def repository_groups_admin(self):
966 def repository_groups_admin(self):
967 """
967 """
968 Returns list of repository groups you're an admin of
968 Returns list of repository groups you're an admin of
969 """
969 """
970 return [
970 return [
971 x[0] for x in self.permissions['repositories_groups'].iteritems()
971 x[0] for x in self.permissions['repositories_groups'].iteritems()
972 if x[1] == 'group.admin']
972 if x[1] == 'group.admin']
973
973
974 @property
974 @property
975 def user_groups_admin(self):
975 def user_groups_admin(self):
976 """
976 """
977 Returns list of user groups you're an admin of
977 Returns list of user groups you're an admin of
978 """
978 """
979 return [
979 return [
980 x[0] for x in self.permissions['user_groups'].iteritems()
980 x[0] for x in self.permissions['user_groups'].iteritems()
981 if x[1] == 'usergroup.admin']
981 if x[1] == 'usergroup.admin']
982
982
983 @property
983 @property
984 def ip_allowed(self):
984 def ip_allowed(self):
985 """
985 """
986 Checks if ip_addr used in constructor is allowed from defined list of
986 Checks if ip_addr used in constructor is allowed from defined list of
987 allowed ip_addresses for user
987 allowed ip_addresses for user
988
988
989 :returns: boolean, True if ip is in allowed ip range
989 :returns: boolean, True if ip is in allowed ip range
990 """
990 """
991 # check IP
991 # check IP
992 inherit = self.inherit_default_permissions
992 inherit = self.inherit_default_permissions
993 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
993 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
994 inherit_from_default=inherit)
994 inherit_from_default=inherit)
995 @property
995 @property
996 def personal_repo_group(self):
996 def personal_repo_group(self):
997 return RepoGroup.get_user_personal_repo_group(self.user_id)
997 return RepoGroup.get_user_personal_repo_group(self.user_id)
998
998
999 @classmethod
999 @classmethod
1000 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1000 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1001 allowed_ips = AuthUser.get_allowed_ips(
1001 allowed_ips = AuthUser.get_allowed_ips(
1002 user_id, cache=True, inherit_from_default=inherit_from_default)
1002 user_id, cache=True, inherit_from_default=inherit_from_default)
1003 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1003 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1004 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1004 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1005 return True
1005 return True
1006 else:
1006 else:
1007 log.info('Access for IP:%s forbidden, '
1007 log.info('Access for IP:%s forbidden, '
1008 'not in %s' % (ip_addr, allowed_ips))
1008 'not in %s' % (ip_addr, allowed_ips))
1009 return False
1009 return False
1010
1010
1011 def __repr__(self):
1011 def __repr__(self):
1012 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1012 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1013 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1013 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1014
1014
1015 def set_authenticated(self, authenticated=True):
1015 def set_authenticated(self, authenticated=True):
1016 if self.user_id != self.anonymous_user.user_id:
1016 if self.user_id != self.anonymous_user.user_id:
1017 self.is_authenticated = authenticated
1017 self.is_authenticated = authenticated
1018
1018
1019 def get_cookie_store(self):
1019 def get_cookie_store(self):
1020 return {
1020 return {
1021 'username': self.username,
1021 'username': self.username,
1022 'password': md5(self.password),
1022 'password': md5(self.password),
1023 'user_id': self.user_id,
1023 'user_id': self.user_id,
1024 'is_authenticated': self.is_authenticated
1024 'is_authenticated': self.is_authenticated
1025 }
1025 }
1026
1026
1027 @classmethod
1027 @classmethod
1028 def from_cookie_store(cls, cookie_store):
1028 def from_cookie_store(cls, cookie_store):
1029 """
1029 """
1030 Creates AuthUser from a cookie store
1030 Creates AuthUser from a cookie store
1031
1031
1032 :param cls:
1032 :param cls:
1033 :param cookie_store:
1033 :param cookie_store:
1034 """
1034 """
1035 user_id = cookie_store.get('user_id')
1035 user_id = cookie_store.get('user_id')
1036 username = cookie_store.get('username')
1036 username = cookie_store.get('username')
1037 api_key = cookie_store.get('api_key')
1037 api_key = cookie_store.get('api_key')
1038 return AuthUser(user_id, api_key, username)
1038 return AuthUser(user_id, api_key, username)
1039
1039
1040 @classmethod
1040 @classmethod
1041 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1041 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1042 _set = set()
1042 _set = set()
1043
1043
1044 if inherit_from_default:
1044 if inherit_from_default:
1045 default_ips = UserIpMap.query().filter(
1045 default_ips = UserIpMap.query().filter(
1046 UserIpMap.user == User.get_default_user(cache=True))
1046 UserIpMap.user == User.get_default_user(cache=True))
1047 if cache:
1047 if cache:
1048 default_ips = default_ips.options(
1048 default_ips = default_ips.options(
1049 FromCache("sql_cache_short", "get_user_ips_default"))
1049 FromCache("sql_cache_short", "get_user_ips_default"))
1050
1050
1051 # populate from default user
1051 # populate from default user
1052 for ip in default_ips:
1052 for ip in default_ips:
1053 try:
1053 try:
1054 _set.add(ip.ip_addr)
1054 _set.add(ip.ip_addr)
1055 except ObjectDeletedError:
1055 except ObjectDeletedError:
1056 # since we use heavy caching sometimes it happens that
1056 # since we use heavy caching sometimes it happens that
1057 # we get deleted objects here, we just skip them
1057 # we get deleted objects here, we just skip them
1058 pass
1058 pass
1059
1059
1060 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1060 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1061 if cache:
1061 if cache:
1062 user_ips = user_ips.options(
1062 user_ips = user_ips.options(
1063 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1063 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1064
1064
1065 for ip in user_ips:
1065 for ip in user_ips:
1066 try:
1066 try:
1067 _set.add(ip.ip_addr)
1067 _set.add(ip.ip_addr)
1068 except ObjectDeletedError:
1068 except ObjectDeletedError:
1069 # since we use heavy caching sometimes it happens that we get
1069 # since we use heavy caching sometimes it happens that we get
1070 # deleted objects here, we just skip them
1070 # deleted objects here, we just skip them
1071 pass
1071 pass
1072 return _set or set(['0.0.0.0/0', '::/0'])
1072 return _set or set(['0.0.0.0/0', '::/0'])
1073
1073
1074
1074
1075 def set_available_permissions(config):
1075 def set_available_permissions(config):
1076 """
1076 """
1077 This function will propagate pylons globals with all available defined
1077 This function will propagate pylons globals with all available defined
1078 permission given in db. We don't want to check each time from db for new
1078 permission given in db. We don't want to check each time from db for new
1079 permissions since adding a new permission also requires application restart
1079 permissions since adding a new permission also requires application restart
1080 ie. to decorate new views with the newly created permission
1080 ie. to decorate new views with the newly created permission
1081
1081
1082 :param config: current pylons config instance
1082 :param config: current pylons config instance
1083
1083
1084 """
1084 """
1085 log.info('getting information about all available permissions')
1085 log.info('getting information about all available permissions')
1086 try:
1086 try:
1087 sa = meta.Session
1087 sa = meta.Session
1088 all_perms = sa.query(Permission).all()
1088 all_perms = sa.query(Permission).all()
1089 config['available_permissions'] = [x.permission_name for x in all_perms]
1089 config['available_permissions'] = [x.permission_name for x in all_perms]
1090 except Exception:
1090 except Exception:
1091 log.error(traceback.format_exc())
1091 log.error(traceback.format_exc())
1092 finally:
1092 finally:
1093 meta.Session.remove()
1093 meta.Session.remove()
1094
1094
1095
1095
1096 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1096 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1097 """
1097 """
1098 Return the current authentication token, creating one if one doesn't
1098 Return the current authentication token, creating one if one doesn't
1099 already exist and the save_if_missing flag is present.
1099 already exist and the save_if_missing flag is present.
1100
1100
1101 :param session: pass in the pylons session, else we use the global ones
1101 :param session: pass in the pylons session, else we use the global ones
1102 :param force_new: force to re-generate the token and store it in session
1102 :param force_new: force to re-generate the token and store it in session
1103 :param save_if_missing: save the newly generated token if it's missing in
1103 :param save_if_missing: save the newly generated token if it's missing in
1104 session
1104 session
1105 """
1105 """
1106 if not session:
1106 if not session:
1107 from pylons import session
1107 from pylons import session
1108
1108
1109 if (csrf_token_key not in session and save_if_missing) or force_new:
1109 if (csrf_token_key not in session and save_if_missing) or force_new:
1110 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1110 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1111 session[csrf_token_key] = token
1111 session[csrf_token_key] = token
1112 if hasattr(session, 'save'):
1112 if hasattr(session, 'save'):
1113 session.save()
1113 session.save()
1114 return session.get(csrf_token_key)
1114 return session.get(csrf_token_key)
1115
1115
1116
1116
1117 # CHECK DECORATORS
1117 # CHECK DECORATORS
1118 class CSRFRequired(object):
1118 class CSRFRequired(object):
1119 """
1119 """
1120 Decorator for authenticating a form
1120 Decorator for authenticating a form
1121
1121
1122 This decorator uses an authorization token stored in the client's
1122 This decorator uses an authorization token stored in the client's
1123 session for prevention of certain Cross-site request forgery (CSRF)
1123 session for prevention of certain Cross-site request forgery (CSRF)
1124 attacks (See
1124 attacks (See
1125 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1125 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1126 information).
1126 information).
1127
1127
1128 For use with the ``webhelpers.secure_form`` helper functions.
1128 For use with the ``webhelpers.secure_form`` helper functions.
1129
1129
1130 """
1130 """
1131 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1131 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1132 except_methods=None):
1132 except_methods=None):
1133 self.token = token
1133 self.token = token
1134 self.header = header
1134 self.header = header
1135 self.except_methods = except_methods or []
1135 self.except_methods = except_methods or []
1136
1136
1137 def __call__(self, func):
1137 def __call__(self, func):
1138 return get_cython_compat_decorator(self.__wrapper, func)
1138 return get_cython_compat_decorator(self.__wrapper, func)
1139
1139
1140 def _get_csrf(self, _request):
1140 def _get_csrf(self, _request):
1141 return _request.POST.get(self.token, _request.headers.get(self.header))
1141 return _request.POST.get(self.token, _request.headers.get(self.header))
1142
1142
1143 def check_csrf(self, _request, cur_token):
1143 def check_csrf(self, _request, cur_token):
1144 supplied_token = self._get_csrf(_request)
1144 supplied_token = self._get_csrf(_request)
1145 return supplied_token and supplied_token == cur_token
1145 return supplied_token and supplied_token == cur_token
1146
1146
1147 def __wrapper(self, func, *fargs, **fkwargs):
1147 def __wrapper(self, func, *fargs, **fkwargs):
1148 if request.method in self.except_methods:
1148 if request.method in self.except_methods:
1149 return func(*fargs, **fkwargs)
1149 return func(*fargs, **fkwargs)
1150
1150
1151 cur_token = get_csrf_token(save_if_missing=False)
1151 cur_token = get_csrf_token(save_if_missing=False)
1152 if self.check_csrf(request, cur_token):
1152 if self.check_csrf(request, cur_token):
1153 if request.POST.get(self.token):
1153 if request.POST.get(self.token):
1154 del request.POST[self.token]
1154 del request.POST[self.token]
1155 return func(*fargs, **fkwargs)
1155 return func(*fargs, **fkwargs)
1156 else:
1156 else:
1157 reason = 'token-missing'
1157 reason = 'token-missing'
1158 supplied_token = self._get_csrf(request)
1158 supplied_token = self._get_csrf(request)
1159 if supplied_token and cur_token != supplied_token:
1159 if supplied_token and cur_token != supplied_token:
1160 reason = 'token-mismatch [%s:%s]' % (cur_token or ''[:6],
1160 reason = 'token-mismatch [%s:%s]' % (cur_token or ''[:6],
1161 supplied_token or ''[:6])
1161 supplied_token or ''[:6])
1162
1162
1163 csrf_message = \
1163 csrf_message = \
1164 ("Cross-site request forgery detected, request denied. See "
1164 ("Cross-site request forgery detected, request denied. See "
1165 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1165 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1166 "more information.")
1166 "more information.")
1167 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1167 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1168 'REMOTE_ADDR:%s, HEADERS:%s' % (
1168 'REMOTE_ADDR:%s, HEADERS:%s' % (
1169 request, reason, request.remote_addr, request.headers))
1169 request, reason, request.remote_addr, request.headers))
1170
1170
1171 raise HTTPForbidden(explanation=csrf_message)
1171 raise HTTPForbidden(explanation=csrf_message)
1172
1172
1173
1173
1174 class LoginRequired(object):
1174 class LoginRequired(object):
1175 """
1175 """
1176 Must be logged in to execute this function else
1176 Must be logged in to execute this function else
1177 redirect to login page
1177 redirect to login page
1178
1178
1179 :param api_access: if enabled this checks only for valid auth token
1179 :param api_access: if enabled this checks only for valid auth token
1180 and grants access based on valid token
1180 and grants access based on valid token
1181 """
1181 """
1182 def __init__(self, auth_token_access=None):
1182 def __init__(self, auth_token_access=None):
1183 self.auth_token_access = auth_token_access
1183 self.auth_token_access = auth_token_access
1184
1184
1185 def __call__(self, func):
1185 def __call__(self, func):
1186 return get_cython_compat_decorator(self.__wrapper, func)
1186 return get_cython_compat_decorator(self.__wrapper, func)
1187
1187
1188 def _get_request(self):
1189 from pyramid.threadlocal import get_current_request
1190 pyramid_request = get_current_request()
1191 if not pyramid_request:
1192 # return global request of pylons in case pyramid isn't available
1193 return request
1194 return pyramid_request
1195
1188 def __wrapper(self, func, *fargs, **fkwargs):
1196 def __wrapper(self, func, *fargs, **fkwargs):
1189 from rhodecode.lib import helpers as h
1197 from rhodecode.lib import helpers as h
1190 cls = fargs[0]
1198 cls = fargs[0]
1191 user = cls._rhodecode_user
1199 user = cls._rhodecode_user
1200 request = self._get_request()
1201
1192 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1202 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1193 log.debug('Starting login restriction checks for user: %s' % (user,))
1203 log.debug('Starting login restriction checks for user: %s' % (user,))
1194 # check if our IP is allowed
1204 # check if our IP is allowed
1195 ip_access_valid = True
1205 ip_access_valid = True
1196 if not user.ip_allowed:
1206 if not user.ip_allowed:
1197 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1207 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1198 category='warning')
1208 category='warning')
1199 ip_access_valid = False
1209 ip_access_valid = False
1200
1210
1201 # check if we used an APIKEY and it's a valid one
1211 # check if we used an APIKEY and it's a valid one
1202 # defined white-list of controllers which API access will be enabled
1212 # defined white-list of controllers which API access will be enabled
1203 _auth_token = request.GET.get(
1213 _auth_token = request.GET.get(
1204 'auth_token', '') or request.GET.get('api_key', '')
1214 'auth_token', '') or request.GET.get('api_key', '')
1205 auth_token_access_valid = allowed_auth_token_access(
1215 auth_token_access_valid = allowed_auth_token_access(
1206 loc, auth_token=_auth_token)
1216 loc, auth_token=_auth_token)
1207
1217
1208 # explicit controller is enabled or API is in our whitelist
1218 # explicit controller is enabled or API is in our whitelist
1209 if self.auth_token_access or auth_token_access_valid:
1219 if self.auth_token_access or auth_token_access_valid:
1210 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1220 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1211 db_user = user.get_instance()
1221 db_user = user.get_instance()
1212
1222
1213 if db_user:
1223 if db_user:
1214 if self.auth_token_access:
1224 if self.auth_token_access:
1215 roles = self.auth_token_access
1225 roles = self.auth_token_access
1216 else:
1226 else:
1217 roles = [UserApiKeys.ROLE_HTTP]
1227 roles = [UserApiKeys.ROLE_HTTP]
1218 token_match = db_user.authenticate_by_token(
1228 token_match = db_user.authenticate_by_token(
1219 _auth_token, roles=roles)
1229 _auth_token, roles=roles)
1220 else:
1230 else:
1221 log.debug('Unable to fetch db instance for auth user: %s', user)
1231 log.debug('Unable to fetch db instance for auth user: %s', user)
1222 token_match = False
1232 token_match = False
1223
1233
1224 if _auth_token and token_match:
1234 if _auth_token and token_match:
1225 auth_token_access_valid = True
1235 auth_token_access_valid = True
1226 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1236 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1227 else:
1237 else:
1228 auth_token_access_valid = False
1238 auth_token_access_valid = False
1229 if not _auth_token:
1239 if not _auth_token:
1230 log.debug("AUTH TOKEN *NOT* present in request")
1240 log.debug("AUTH TOKEN *NOT* present in request")
1231 else:
1241 else:
1232 log.warning(
1242 log.warning(
1233 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1243 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1234
1244
1235 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1245 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1236 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1246 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1237 else 'AUTH_TOKEN_AUTH'
1247 else 'AUTH_TOKEN_AUTH'
1238
1248
1239 if ip_access_valid and (
1249 if ip_access_valid and (
1240 user.is_authenticated or auth_token_access_valid):
1250 user.is_authenticated or auth_token_access_valid):
1241 log.info(
1251 log.info(
1242 'user %s authenticating with:%s IS authenticated on func %s'
1252 'user %s authenticating with:%s IS authenticated on func %s'
1243 % (user, reason, loc))
1253 % (user, reason, loc))
1244
1254
1245 # update user data to check last activity
1255 # update user data to check last activity
1246 user.update_lastactivity()
1256 user.update_lastactivity()
1247 Session().commit()
1257 Session().commit()
1248 return func(*fargs, **fkwargs)
1258 return func(*fargs, **fkwargs)
1249 else:
1259 else:
1250 log.warning(
1260 log.warning(
1251 'user %s authenticating with:%s NOT authenticated on '
1261 'user %s authenticating with:%s NOT authenticated on '
1252 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1262 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1253 % (user, reason, loc, ip_access_valid,
1263 % (user, reason, loc, ip_access_valid,
1254 auth_token_access_valid))
1264 auth_token_access_valid))
1255 # we preserve the get PARAM
1265 # we preserve the get PARAM
1256 came_from = request.path_qs
1266 came_from = request.path_qs
1257 log.debug('redirecting to login page with %s' % (came_from,))
1267 log.debug('redirecting to login page with %s' % (came_from,))
1258 return redirect(
1268 return redirect(
1259 h.route_path('login', _query={'came_from': came_from}))
1269 h.route_path('login', _query={'came_from': came_from}))
1260
1270
1261
1271
1262 class NotAnonymous(object):
1272 class NotAnonymous(object):
1263 """
1273 """
1264 Must be logged in to execute this function else
1274 Must be logged in to execute this function else
1265 redirect to login page"""
1275 redirect to login page
1276 """
1266
1277
1267 def __call__(self, func):
1278 def __call__(self, func):
1268 return get_cython_compat_decorator(self.__wrapper, func)
1279 return get_cython_compat_decorator(self.__wrapper, func)
1269
1280
1270 def __wrapper(self, func, *fargs, **fkwargs):
1281 def __wrapper(self, func, *fargs, **fkwargs):
1271 import rhodecode.lib.helpers as h
1282 import rhodecode.lib.helpers as h
1272 cls = fargs[0]
1283 cls = fargs[0]
1273 self.user = cls._rhodecode_user
1284 self.user = cls._rhodecode_user
1274
1285
1275 log.debug('Checking if user is not anonymous @%s' % cls)
1286 log.debug('Checking if user is not anonymous @%s' % cls)
1276
1287
1277 anonymous = self.user.username == User.DEFAULT_USER
1288 anonymous = self.user.username == User.DEFAULT_USER
1278
1289
1279 if anonymous:
1290 if anonymous:
1280 came_from = request.path_qs
1291 came_from = request.path_qs
1281 h.flash(_('You need to be a registered user to '
1292 h.flash(_('You need to be a registered user to '
1282 'perform this action'),
1293 'perform this action'),
1283 category='warning')
1294 category='warning')
1284 return redirect(
1295 return redirect(
1285 h.route_path('login', _query={'came_from': came_from}))
1296 h.route_path('login', _query={'came_from': came_from}))
1286 else:
1297 else:
1287 return func(*fargs, **fkwargs)
1298 return func(*fargs, **fkwargs)
1288
1299
1289
1300
1290 class XHRRequired(object):
1301 class XHRRequired(object):
1302 # TODO(marcink): remove this in favor of the predicates in pyramid routes
1303
1291 def __call__(self, func):
1304 def __call__(self, func):
1292 return get_cython_compat_decorator(self.__wrapper, func)
1305 return get_cython_compat_decorator(self.__wrapper, func)
1293
1306
1294 def __wrapper(self, func, *fargs, **fkwargs):
1307 def __wrapper(self, func, *fargs, **fkwargs):
1295 log.debug('Checking if request is XMLHttpRequest (XHR)')
1308 log.debug('Checking if request is XMLHttpRequest (XHR)')
1296 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1309 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1297 if not request.is_xhr:
1310 if not request.is_xhr:
1298 abort(400, detail=xhr_message)
1311 abort(400, detail=xhr_message)
1299
1312
1300 return func(*fargs, **fkwargs)
1313 return func(*fargs, **fkwargs)
1301
1314
1302
1315
1303 class HasAcceptedRepoType(object):
1316 class HasAcceptedRepoType(object):
1304 """
1317 """
1305 Check if requested repo is within given repo type aliases
1318 Check if requested repo is within given repo type aliases
1319 """
1306
1320
1307 TODO: anderson: not sure where to put this decorator
1321 # TODO(marcink): remove this in favor of the predicates in pyramid routes
1308 """
1309
1322
1310 def __init__(self, *repo_type_list):
1323 def __init__(self, *repo_type_list):
1311 self.repo_type_list = set(repo_type_list)
1324 self.repo_type_list = set(repo_type_list)
1312
1325
1313 def __call__(self, func):
1326 def __call__(self, func):
1314 return get_cython_compat_decorator(self.__wrapper, func)
1327 return get_cython_compat_decorator(self.__wrapper, func)
1315
1328
1316 def __wrapper(self, func, *fargs, **fkwargs):
1329 def __wrapper(self, func, *fargs, **fkwargs):
1317 import rhodecode.lib.helpers as h
1330 import rhodecode.lib.helpers as h
1318 cls = fargs[0]
1331 cls = fargs[0]
1319 rhodecode_repo = cls.rhodecode_repo
1332 rhodecode_repo = cls.rhodecode_repo
1320
1333
1321 log.debug('%s checking repo type for %s in %s',
1334 log.debug('%s checking repo type for %s in %s',
1322 self.__class__.__name__,
1335 self.__class__.__name__,
1323 rhodecode_repo.alias, self.repo_type_list)
1336 rhodecode_repo.alias, self.repo_type_list)
1324
1337
1325 if rhodecode_repo.alias in self.repo_type_list:
1338 if rhodecode_repo.alias in self.repo_type_list:
1326 return func(*fargs, **fkwargs)
1339 return func(*fargs, **fkwargs)
1327 else:
1340 else:
1328 h.flash(h.literal(
1341 h.flash(h.literal(
1329 _('Action not supported for %s.' % rhodecode_repo.alias)),
1342 _('Action not supported for %s.' % rhodecode_repo.alias)),
1330 category='warning')
1343 category='warning')
1331 return redirect(
1344 return redirect(
1332 url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name))
1345 url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name))
1333
1346
1334
1347
1335 class PermsDecorator(object):
1348 class PermsDecorator(object):
1336 """
1349 """
1337 Base class for controller decorators, we extract the current user from
1350 Base class for controller decorators, we extract the current user from
1338 the class itself, which has it stored in base controllers
1351 the class itself, which has it stored in base controllers
1339 """
1352 """
1340
1353
1341 def __init__(self, *required_perms):
1354 def __init__(self, *required_perms):
1342 self.required_perms = set(required_perms)
1355 self.required_perms = set(required_perms)
1343
1356
1344 def __call__(self, func):
1357 def __call__(self, func):
1345 return get_cython_compat_decorator(self.__wrapper, func)
1358 return get_cython_compat_decorator(self.__wrapper, func)
1346
1359
1347 def _get_request(self):
1360 def _get_request(self):
1348 from pyramid.threadlocal import get_current_request
1361 from pyramid.threadlocal import get_current_request
1349 pyramid_request = get_current_request()
1362 pyramid_request = get_current_request()
1350 if not pyramid_request:
1363 if not pyramid_request:
1351 # return global request of pylons in case pyramid isn't available
1364 # return global request of pylons in case pyramid isn't available
1352 return request
1365 return request
1353 return pyramid_request
1366 return pyramid_request
1354
1367
1355 def _get_came_from(self):
1368 def _get_came_from(self):
1356 _request = self._get_request()
1369 _request = self._get_request()
1357
1370
1358 # both pylons/pyramid has this attribute
1371 # both pylons/pyramid has this attribute
1359 return _request.path_qs
1372 return _request.path_qs
1360
1373
1361 def __wrapper(self, func, *fargs, **fkwargs):
1374 def __wrapper(self, func, *fargs, **fkwargs):
1362 import rhodecode.lib.helpers as h
1375 import rhodecode.lib.helpers as h
1363 cls = fargs[0]
1376 cls = fargs[0]
1364 _user = cls._rhodecode_user
1377 _user = cls._rhodecode_user
1365
1378
1366 log.debug('checking %s permissions %s for %s %s',
1379 log.debug('checking %s permissions %s for %s %s',
1367 self.__class__.__name__, self.required_perms, cls, _user)
1380 self.__class__.__name__, self.required_perms, cls, _user)
1368
1381
1369 if self.check_permissions(_user):
1382 if self.check_permissions(_user):
1370 log.debug('Permission granted for %s %s', cls, _user)
1383 log.debug('Permission granted for %s %s', cls, _user)
1371 return func(*fargs, **fkwargs)
1384 return func(*fargs, **fkwargs)
1372
1385
1373 else:
1386 else:
1374 log.debug('Permission denied for %s %s', cls, _user)
1387 log.debug('Permission denied for %s %s', cls, _user)
1375 anonymous = _user.username == User.DEFAULT_USER
1388 anonymous = _user.username == User.DEFAULT_USER
1376
1389
1377 if anonymous:
1390 if anonymous:
1378 came_from = self._get_came_from()
1391 came_from = self._get_came_from()
1379 h.flash(_('You need to be signed in to view this page'),
1392 h.flash(_('You need to be signed in to view this page'),
1380 category='warning')
1393 category='warning')
1381 raise HTTPFound(
1394 raise HTTPFound(
1382 h.route_path('login', _query={'came_from': came_from}))
1395 h.route_path('login', _query={'came_from': came_from}))
1383
1396
1384 else:
1397 else:
1385 # redirect with forbidden ret code
1398 # redirect with forbidden ret code
1386 raise HTTPForbidden()
1399 raise HTTPForbidden()
1387
1400
1388 def check_permissions(self, user):
1401 def check_permissions(self, user):
1389 """Dummy function for overriding"""
1402 """Dummy function for overriding"""
1390 raise NotImplementedError(
1403 raise NotImplementedError(
1391 'You have to write this function in child class')
1404 'You have to write this function in child class')
1392
1405
1393
1406
1394 class HasPermissionAllDecorator(PermsDecorator):
1407 class HasPermissionAllDecorator(PermsDecorator):
1395 """
1408 """
1396 Checks for access permission for all given predicates. All of them
1409 Checks for access permission for all given predicates. All of them
1397 have to be meet in order to fulfill the request
1410 have to be meet in order to fulfill the request
1398 """
1411 """
1399
1412
1400 def check_permissions(self, user):
1413 def check_permissions(self, user):
1401 perms = user.permissions_with_scope({})
1414 perms = user.permissions_with_scope({})
1402 if self.required_perms.issubset(perms['global']):
1415 if self.required_perms.issubset(perms['global']):
1403 return True
1416 return True
1404 return False
1417 return False
1405
1418
1406
1419
1407 class HasPermissionAnyDecorator(PermsDecorator):
1420 class HasPermissionAnyDecorator(PermsDecorator):
1408 """
1421 """
1409 Checks for access permission for any of given predicates. In order to
1422 Checks for access permission for any of given predicates. In order to
1410 fulfill the request any of predicates must be meet
1423 fulfill the request any of predicates must be meet
1411 """
1424 """
1412
1425
1413 def check_permissions(self, user):
1426 def check_permissions(self, user):
1414 perms = user.permissions_with_scope({})
1427 perms = user.permissions_with_scope({})
1415 if self.required_perms.intersection(perms['global']):
1428 if self.required_perms.intersection(perms['global']):
1416 return True
1429 return True
1417 return False
1430 return False
1418
1431
1419
1432
1420 class HasRepoPermissionAllDecorator(PermsDecorator):
1433 class HasRepoPermissionAllDecorator(PermsDecorator):
1421 """
1434 """
1422 Checks for access permission for all given predicates for specific
1435 Checks for access permission for all given predicates for specific
1423 repository. All of them have to be meet in order to fulfill the request
1436 repository. All of them have to be meet in order to fulfill the request
1424 """
1437 """
1425 def _get_repo_name(self):
1438 def _get_repo_name(self):
1426 _request = self._get_request()
1439 _request = self._get_request()
1427 return get_repo_slug(_request)
1440 return get_repo_slug(_request)
1428
1441
1429 def check_permissions(self, user):
1442 def check_permissions(self, user):
1430 perms = user.permissions
1443 perms = user.permissions
1431 repo_name = self._get_repo_name()
1444 repo_name = self._get_repo_name()
1432
1445
1433 try:
1446 try:
1434 user_perms = set([perms['repositories'][repo_name]])
1447 user_perms = set([perms['repositories'][repo_name]])
1435 except KeyError:
1448 except KeyError:
1436 log.debug('cannot locate repo with name: `%s` in permissions defs',
1449 log.debug('cannot locate repo with name: `%s` in permissions defs',
1437 repo_name)
1450 repo_name)
1438 return False
1451 return False
1439
1452
1440 log.debug('checking `%s` permissions for repo `%s`',
1453 log.debug('checking `%s` permissions for repo `%s`',
1441 user_perms, repo_name)
1454 user_perms, repo_name)
1442 if self.required_perms.issubset(user_perms):
1455 if self.required_perms.issubset(user_perms):
1443 return True
1456 return True
1444 return False
1457 return False
1445
1458
1446
1459
1447 class HasRepoPermissionAnyDecorator(PermsDecorator):
1460 class HasRepoPermissionAnyDecorator(PermsDecorator):
1448 """
1461 """
1449 Checks for access permission for any of given predicates for specific
1462 Checks for access permission for any of given predicates for specific
1450 repository. In order to fulfill the request any of predicates must be meet
1463 repository. In order to fulfill the request any of predicates must be meet
1451 """
1464 """
1452 def _get_repo_name(self):
1465 def _get_repo_name(self):
1453 _request = self._get_request()
1466 _request = self._get_request()
1454 return get_repo_slug(_request)
1467 return get_repo_slug(_request)
1455
1468
1456 def check_permissions(self, user):
1469 def check_permissions(self, user):
1457 perms = user.permissions
1470 perms = user.permissions
1458 repo_name = self._get_repo_name()
1471 repo_name = self._get_repo_name()
1459
1472
1460 try:
1473 try:
1461 user_perms = set([perms['repositories'][repo_name]])
1474 user_perms = set([perms['repositories'][repo_name]])
1462 except KeyError:
1475 except KeyError:
1463 log.debug('cannot locate repo with name: `%s` in permissions defs',
1476 log.debug('cannot locate repo with name: `%s` in permissions defs',
1464 repo_name)
1477 repo_name)
1465 return False
1478 return False
1466
1479
1467 log.debug('checking `%s` permissions for repo `%s`',
1480 log.debug('checking `%s` permissions for repo `%s`',
1468 user_perms, repo_name)
1481 user_perms, repo_name)
1469 if self.required_perms.intersection(user_perms):
1482 if self.required_perms.intersection(user_perms):
1470 return True
1483 return True
1471 return False
1484 return False
1472
1485
1473
1486
1474 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1487 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1475 """
1488 """
1476 Checks for access permission for all given predicates for specific
1489 Checks for access permission for all given predicates for specific
1477 repository group. All of them have to be meet in order to
1490 repository group. All of them have to be meet in order to
1478 fulfill the request
1491 fulfill the request
1479 """
1492 """
1480 def _get_repo_group_name(self):
1493 def _get_repo_group_name(self):
1481 _request = self._get_request()
1494 _request = self._get_request()
1482 return get_repo_group_slug(_request)
1495 return get_repo_group_slug(_request)
1483
1496
1484 def check_permissions(self, user):
1497 def check_permissions(self, user):
1485 perms = user.permissions
1498 perms = user.permissions
1486 group_name = self._get_repo_group_name()
1499 group_name = self._get_repo_group_name()
1487 try:
1500 try:
1488 user_perms = set([perms['repositories_groups'][group_name]])
1501 user_perms = set([perms['repositories_groups'][group_name]])
1489 except KeyError:
1502 except KeyError:
1490 log.debug('cannot locate repo group with name: `%s` in permissions defs',
1503 log.debug('cannot locate repo group with name: `%s` in permissions defs',
1491 group_name)
1504 group_name)
1492 return False
1505 return False
1493
1506
1494 log.debug('checking `%s` permissions for repo group `%s`',
1507 log.debug('checking `%s` permissions for repo group `%s`',
1495 user_perms, group_name)
1508 user_perms, group_name)
1496 if self.required_perms.issubset(user_perms):
1509 if self.required_perms.issubset(user_perms):
1497 return True
1510 return True
1498 return False
1511 return False
1499
1512
1500
1513
1501 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1514 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1502 """
1515 """
1503 Checks for access permission for any of given predicates for specific
1516 Checks for access permission for any of given predicates for specific
1504 repository group. In order to fulfill the request any
1517 repository group. In order to fulfill the request any
1505 of predicates must be met
1518 of predicates must be met
1506 """
1519 """
1507 def _get_repo_group_name(self):
1520 def _get_repo_group_name(self):
1508 _request = self._get_request()
1521 _request = self._get_request()
1509 return get_repo_group_slug(_request)
1522 return get_repo_group_slug(_request)
1510
1523
1511 def check_permissions(self, user):
1524 def check_permissions(self, user):
1512 perms = user.permissions
1525 perms = user.permissions
1513 group_name = self._get_repo_group_name()
1526 group_name = self._get_repo_group_name()
1514
1527
1515 try:
1528 try:
1516 user_perms = set([perms['repositories_groups'][group_name]])
1529 user_perms = set([perms['repositories_groups'][group_name]])
1517 except KeyError:
1530 except KeyError:
1518 log.debug('cannot locate repo group with name: `%s` in permissions defs',
1531 log.debug('cannot locate repo group with name: `%s` in permissions defs',
1519 group_name)
1532 group_name)
1520 return False
1533 return False
1521
1534
1522 log.debug('checking `%s` permissions for repo group `%s`',
1535 log.debug('checking `%s` permissions for repo group `%s`',
1523 user_perms, group_name)
1536 user_perms, group_name)
1524 if self.required_perms.intersection(user_perms):
1537 if self.required_perms.intersection(user_perms):
1525 return True
1538 return True
1526 return False
1539 return False
1527
1540
1528
1541
1529 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1542 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1530 """
1543 """
1531 Checks for access permission for all given predicates for specific
1544 Checks for access permission for all given predicates for specific
1532 user group. All of them have to be meet in order to fulfill the request
1545 user group. All of them have to be meet in order to fulfill the request
1533 """
1546 """
1534 def _get_user_group_name(self):
1547 def _get_user_group_name(self):
1535 _request = self._get_request()
1548 _request = self._get_request()
1536 return get_user_group_slug(_request)
1549 return get_user_group_slug(_request)
1537
1550
1538 def check_permissions(self, user):
1551 def check_permissions(self, user):
1539 perms = user.permissions
1552 perms = user.permissions
1540 group_name = self._get_user_group_name()
1553 group_name = self._get_user_group_name()
1541 try:
1554 try:
1542 user_perms = set([perms['user_groups'][group_name]])
1555 user_perms = set([perms['user_groups'][group_name]])
1543 except KeyError:
1556 except KeyError:
1544 return False
1557 return False
1545
1558
1546 if self.required_perms.issubset(user_perms):
1559 if self.required_perms.issubset(user_perms):
1547 return True
1560 return True
1548 return False
1561 return False
1549
1562
1550
1563
1551 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1564 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1552 """
1565 """
1553 Checks for access permission for any of given predicates for specific
1566 Checks for access permission for any of given predicates for specific
1554 user group. In order to fulfill the request any of predicates must be meet
1567 user group. In order to fulfill the request any of predicates must be meet
1555 """
1568 """
1556 def _get_user_group_name(self):
1569 def _get_user_group_name(self):
1557 _request = self._get_request()
1570 _request = self._get_request()
1558 return get_user_group_slug(_request)
1571 return get_user_group_slug(_request)
1559
1572
1560 def check_permissions(self, user):
1573 def check_permissions(self, user):
1561 perms = user.permissions
1574 perms = user.permissions
1562 group_name = self._get_user_group_name()
1575 group_name = self._get_user_group_name()
1563 try:
1576 try:
1564 user_perms = set([perms['user_groups'][group_name]])
1577 user_perms = set([perms['user_groups'][group_name]])
1565 except KeyError:
1578 except KeyError:
1566 return False
1579 return False
1567
1580
1568 if self.required_perms.intersection(user_perms):
1581 if self.required_perms.intersection(user_perms):
1569 return True
1582 return True
1570 return False
1583 return False
1571
1584
1572
1585
1573 # CHECK FUNCTIONS
1586 # CHECK FUNCTIONS
1574 class PermsFunction(object):
1587 class PermsFunction(object):
1575 """Base function for other check functions"""
1588 """Base function for other check functions"""
1576
1589
1577 def __init__(self, *perms):
1590 def __init__(self, *perms):
1578 self.required_perms = set(perms)
1591 self.required_perms = set(perms)
1579 self.repo_name = None
1592 self.repo_name = None
1580 self.repo_group_name = None
1593 self.repo_group_name = None
1581 self.user_group_name = None
1594 self.user_group_name = None
1582
1595
1583 def __bool__(self):
1596 def __bool__(self):
1584 frame = inspect.currentframe()
1597 frame = inspect.currentframe()
1585 stack_trace = traceback.format_stack(frame)
1598 stack_trace = traceback.format_stack(frame)
1586 log.error('Checking bool value on a class instance of perm '
1599 log.error('Checking bool value on a class instance of perm '
1587 'function is not allowed: %s' % ''.join(stack_trace))
1600 'function is not allowed: %s' % ''.join(stack_trace))
1588 # rather than throwing errors, here we always return False so if by
1601 # rather than throwing errors, here we always return False so if by
1589 # accident someone checks truth for just an instance it will always end
1602 # accident someone checks truth for just an instance it will always end
1590 # up in returning False
1603 # up in returning False
1591 return False
1604 return False
1592 __nonzero__ = __bool__
1605 __nonzero__ = __bool__
1593
1606
1594 def __call__(self, check_location='', user=None):
1607 def __call__(self, check_location='', user=None):
1595 if not user:
1608 if not user:
1596 log.debug('Using user attribute from global request')
1609 log.debug('Using user attribute from global request')
1597 # TODO: remove this someday,put as user as attribute here
1610 # TODO: remove this someday,put as user as attribute here
1611 request = self._get_request()
1598 user = request.user
1612 user = request.user
1599
1613
1600 # init auth user if not already given
1614 # init auth user if not already given
1601 if not isinstance(user, AuthUser):
1615 if not isinstance(user, AuthUser):
1602 log.debug('Wrapping user %s into AuthUser', user)
1616 log.debug('Wrapping user %s into AuthUser', user)
1603 user = AuthUser(user.user_id)
1617 user = AuthUser(user.user_id)
1604
1618
1605 cls_name = self.__class__.__name__
1619 cls_name = self.__class__.__name__
1606 check_scope = self._get_check_scope(cls_name)
1620 check_scope = self._get_check_scope(cls_name)
1607 check_location = check_location or 'unspecified location'
1621 check_location = check_location or 'unspecified location'
1608
1622
1609 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1623 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1610 self.required_perms, user, check_scope, check_location)
1624 self.required_perms, user, check_scope, check_location)
1611 if not user:
1625 if not user:
1612 log.warning('Empty user given for permission check')
1626 log.warning('Empty user given for permission check')
1613 return False
1627 return False
1614
1628
1615 if self.check_permissions(user):
1629 if self.check_permissions(user):
1616 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1630 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1617 check_scope, user, check_location)
1631 check_scope, user, check_location)
1618 return True
1632 return True
1619
1633
1620 else:
1634 else:
1621 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1635 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1622 check_scope, user, check_location)
1636 check_scope, user, check_location)
1623 return False
1637 return False
1624
1638
1625 def _get_request(self):
1639 def _get_request(self):
1626 from pyramid.threadlocal import get_current_request
1640 from pyramid.threadlocal import get_current_request
1627 pyramid_request = get_current_request()
1641 pyramid_request = get_current_request()
1628 if not pyramid_request:
1642 if not pyramid_request:
1629 # return global request of pylons incase pyramid one isn't available
1643 # return global request of pylons incase pyramid one isn't available
1630 return request
1644 return request
1631 return pyramid_request
1645 return pyramid_request
1632
1646
1633 def _get_check_scope(self, cls_name):
1647 def _get_check_scope(self, cls_name):
1634 return {
1648 return {
1635 'HasPermissionAll': 'GLOBAL',
1649 'HasPermissionAll': 'GLOBAL',
1636 'HasPermissionAny': 'GLOBAL',
1650 'HasPermissionAny': 'GLOBAL',
1637 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1651 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1638 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1652 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1639 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1653 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1640 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1654 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1641 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1655 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1642 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1656 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1643 }.get(cls_name, '?:%s' % cls_name)
1657 }.get(cls_name, '?:%s' % cls_name)
1644
1658
1645 def check_permissions(self, user):
1659 def check_permissions(self, user):
1646 """Dummy function for overriding"""
1660 """Dummy function for overriding"""
1647 raise Exception('You have to write this function in child class')
1661 raise Exception('You have to write this function in child class')
1648
1662
1649
1663
1650 class HasPermissionAll(PermsFunction):
1664 class HasPermissionAll(PermsFunction):
1651 def check_permissions(self, user):
1665 def check_permissions(self, user):
1652 perms = user.permissions_with_scope({})
1666 perms = user.permissions_with_scope({})
1653 if self.required_perms.issubset(perms.get('global')):
1667 if self.required_perms.issubset(perms.get('global')):
1654 return True
1668 return True
1655 return False
1669 return False
1656
1670
1657
1671
1658 class HasPermissionAny(PermsFunction):
1672 class HasPermissionAny(PermsFunction):
1659 def check_permissions(self, user):
1673 def check_permissions(self, user):
1660 perms = user.permissions_with_scope({})
1674 perms = user.permissions_with_scope({})
1661 if self.required_perms.intersection(perms.get('global')):
1675 if self.required_perms.intersection(perms.get('global')):
1662 return True
1676 return True
1663 return False
1677 return False
1664
1678
1665
1679
1666 class HasRepoPermissionAll(PermsFunction):
1680 class HasRepoPermissionAll(PermsFunction):
1667 def __call__(self, repo_name=None, check_location='', user=None):
1681 def __call__(self, repo_name=None, check_location='', user=None):
1668 self.repo_name = repo_name
1682 self.repo_name = repo_name
1669 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1683 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1670
1684
1671 def _get_repo_name(self):
1685 def _get_repo_name(self):
1672 if not self.repo_name:
1686 if not self.repo_name:
1673 _request = self._get_request()
1687 _request = self._get_request()
1674 self.repo_name = get_repo_slug(_request)
1688 self.repo_name = get_repo_slug(_request)
1675 return self.repo_name
1689 return self.repo_name
1676
1690
1677 def check_permissions(self, user):
1691 def check_permissions(self, user):
1678 self.repo_name = self._get_repo_name()
1692 self.repo_name = self._get_repo_name()
1679 perms = user.permissions
1693 perms = user.permissions
1680 try:
1694 try:
1681 user_perms = set([perms['repositories'][self.repo_name]])
1695 user_perms = set([perms['repositories'][self.repo_name]])
1682 except KeyError:
1696 except KeyError:
1683 return False
1697 return False
1684 if self.required_perms.issubset(user_perms):
1698 if self.required_perms.issubset(user_perms):
1685 return True
1699 return True
1686 return False
1700 return False
1687
1701
1688
1702
1689 class HasRepoPermissionAny(PermsFunction):
1703 class HasRepoPermissionAny(PermsFunction):
1690 def __call__(self, repo_name=None, check_location='', user=None):
1704 def __call__(self, repo_name=None, check_location='', user=None):
1691 self.repo_name = repo_name
1705 self.repo_name = repo_name
1692 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1706 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1693
1707
1694 def _get_repo_name(self):
1708 def _get_repo_name(self):
1695 if not self.repo_name:
1709 if not self.repo_name:
1696 self.repo_name = get_repo_slug(request)
1710 self.repo_name = get_repo_slug(request)
1697 return self.repo_name
1711 return self.repo_name
1698
1712
1699 def check_permissions(self, user):
1713 def check_permissions(self, user):
1700 self.repo_name = self._get_repo_name()
1714 self.repo_name = self._get_repo_name()
1701 perms = user.permissions
1715 perms = user.permissions
1702 try:
1716 try:
1703 user_perms = set([perms['repositories'][self.repo_name]])
1717 user_perms = set([perms['repositories'][self.repo_name]])
1704 except KeyError:
1718 except KeyError:
1705 return False
1719 return False
1706 if self.required_perms.intersection(user_perms):
1720 if self.required_perms.intersection(user_perms):
1707 return True
1721 return True
1708 return False
1722 return False
1709
1723
1710
1724
1711 class HasRepoGroupPermissionAny(PermsFunction):
1725 class HasRepoGroupPermissionAny(PermsFunction):
1712 def __call__(self, group_name=None, check_location='', user=None):
1726 def __call__(self, group_name=None, check_location='', user=None):
1713 self.repo_group_name = group_name
1727 self.repo_group_name = group_name
1714 return super(HasRepoGroupPermissionAny, self).__call__(
1728 return super(HasRepoGroupPermissionAny, self).__call__(
1715 check_location, user)
1729 check_location, user)
1716
1730
1717 def check_permissions(self, user):
1731 def check_permissions(self, user):
1718 perms = user.permissions
1732 perms = user.permissions
1719 try:
1733 try:
1720 user_perms = set(
1734 user_perms = set(
1721 [perms['repositories_groups'][self.repo_group_name]])
1735 [perms['repositories_groups'][self.repo_group_name]])
1722 except KeyError:
1736 except KeyError:
1723 return False
1737 return False
1724 if self.required_perms.intersection(user_perms):
1738 if self.required_perms.intersection(user_perms):
1725 return True
1739 return True
1726 return False
1740 return False
1727
1741
1728
1742
1729 class HasRepoGroupPermissionAll(PermsFunction):
1743 class HasRepoGroupPermissionAll(PermsFunction):
1730 def __call__(self, group_name=None, check_location='', user=None):
1744 def __call__(self, group_name=None, check_location='', user=None):
1731 self.repo_group_name = group_name
1745 self.repo_group_name = group_name
1732 return super(HasRepoGroupPermissionAll, self).__call__(
1746 return super(HasRepoGroupPermissionAll, self).__call__(
1733 check_location, user)
1747 check_location, user)
1734
1748
1735 def check_permissions(self, user):
1749 def check_permissions(self, user):
1736 perms = user.permissions
1750 perms = user.permissions
1737 try:
1751 try:
1738 user_perms = set(
1752 user_perms = set(
1739 [perms['repositories_groups'][self.repo_group_name]])
1753 [perms['repositories_groups'][self.repo_group_name]])
1740 except KeyError:
1754 except KeyError:
1741 return False
1755 return False
1742 if self.required_perms.issubset(user_perms):
1756 if self.required_perms.issubset(user_perms):
1743 return True
1757 return True
1744 return False
1758 return False
1745
1759
1746
1760
1747 class HasUserGroupPermissionAny(PermsFunction):
1761 class HasUserGroupPermissionAny(PermsFunction):
1748 def __call__(self, user_group_name=None, check_location='', user=None):
1762 def __call__(self, user_group_name=None, check_location='', user=None):
1749 self.user_group_name = user_group_name
1763 self.user_group_name = user_group_name
1750 return super(HasUserGroupPermissionAny, self).__call__(
1764 return super(HasUserGroupPermissionAny, self).__call__(
1751 check_location, user)
1765 check_location, user)
1752
1766
1753 def check_permissions(self, user):
1767 def check_permissions(self, user):
1754 perms = user.permissions
1768 perms = user.permissions
1755 try:
1769 try:
1756 user_perms = set([perms['user_groups'][self.user_group_name]])
1770 user_perms = set([perms['user_groups'][self.user_group_name]])
1757 except KeyError:
1771 except KeyError:
1758 return False
1772 return False
1759 if self.required_perms.intersection(user_perms):
1773 if self.required_perms.intersection(user_perms):
1760 return True
1774 return True
1761 return False
1775 return False
1762
1776
1763
1777
1764 class HasUserGroupPermissionAll(PermsFunction):
1778 class HasUserGroupPermissionAll(PermsFunction):
1765 def __call__(self, user_group_name=None, check_location='', user=None):
1779 def __call__(self, user_group_name=None, check_location='', user=None):
1766 self.user_group_name = user_group_name
1780 self.user_group_name = user_group_name
1767 return super(HasUserGroupPermissionAll, self).__call__(
1781 return super(HasUserGroupPermissionAll, self).__call__(
1768 check_location, user)
1782 check_location, user)
1769
1783
1770 def check_permissions(self, user):
1784 def check_permissions(self, user):
1771 perms = user.permissions
1785 perms = user.permissions
1772 try:
1786 try:
1773 user_perms = set([perms['user_groups'][self.user_group_name]])
1787 user_perms = set([perms['user_groups'][self.user_group_name]])
1774 except KeyError:
1788 except KeyError:
1775 return False
1789 return False
1776 if self.required_perms.issubset(user_perms):
1790 if self.required_perms.issubset(user_perms):
1777 return True
1791 return True
1778 return False
1792 return False
1779
1793
1780
1794
1781 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1795 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1782 class HasPermissionAnyMiddleware(object):
1796 class HasPermissionAnyMiddleware(object):
1783 def __init__(self, *perms):
1797 def __init__(self, *perms):
1784 self.required_perms = set(perms)
1798 self.required_perms = set(perms)
1785
1799
1786 def __call__(self, user, repo_name):
1800 def __call__(self, user, repo_name):
1787 # repo_name MUST be unicode, since we handle keys in permission
1801 # repo_name MUST be unicode, since we handle keys in permission
1788 # dict by unicode
1802 # dict by unicode
1789 repo_name = safe_unicode(repo_name)
1803 repo_name = safe_unicode(repo_name)
1790 user = AuthUser(user.user_id)
1804 user = AuthUser(user.user_id)
1791 log.debug(
1805 log.debug(
1792 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1806 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1793 self.required_perms, user, repo_name)
1807 self.required_perms, user, repo_name)
1794
1808
1795 if self.check_permissions(user, repo_name):
1809 if self.check_permissions(user, repo_name):
1796 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1810 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1797 repo_name, user, 'PermissionMiddleware')
1811 repo_name, user, 'PermissionMiddleware')
1798 return True
1812 return True
1799
1813
1800 else:
1814 else:
1801 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1815 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1802 repo_name, user, 'PermissionMiddleware')
1816 repo_name, user, 'PermissionMiddleware')
1803 return False
1817 return False
1804
1818
1805 def check_permissions(self, user, repo_name):
1819 def check_permissions(self, user, repo_name):
1806 perms = user.permissions_with_scope({'repo_name': repo_name})
1820 perms = user.permissions_with_scope({'repo_name': repo_name})
1807
1821
1808 try:
1822 try:
1809 user_perms = set([perms['repositories'][repo_name]])
1823 user_perms = set([perms['repositories'][repo_name]])
1810 except Exception:
1824 except Exception:
1811 log.exception('Error while accessing user permissions')
1825 log.exception('Error while accessing user permissions')
1812 return False
1826 return False
1813
1827
1814 if self.required_perms.intersection(user_perms):
1828 if self.required_perms.intersection(user_perms):
1815 return True
1829 return True
1816 return False
1830 return False
1817
1831
1818
1832
1819 # SPECIAL VERSION TO HANDLE API AUTH
1833 # SPECIAL VERSION TO HANDLE API AUTH
1820 class _BaseApiPerm(object):
1834 class _BaseApiPerm(object):
1821 def __init__(self, *perms):
1835 def __init__(self, *perms):
1822 self.required_perms = set(perms)
1836 self.required_perms = set(perms)
1823
1837
1824 def __call__(self, check_location=None, user=None, repo_name=None,
1838 def __call__(self, check_location=None, user=None, repo_name=None,
1825 group_name=None, user_group_name=None):
1839 group_name=None, user_group_name=None):
1826 cls_name = self.__class__.__name__
1840 cls_name = self.__class__.__name__
1827 check_scope = 'global:%s' % (self.required_perms,)
1841 check_scope = 'global:%s' % (self.required_perms,)
1828 if repo_name:
1842 if repo_name:
1829 check_scope += ', repo_name:%s' % (repo_name,)
1843 check_scope += ', repo_name:%s' % (repo_name,)
1830
1844
1831 if group_name:
1845 if group_name:
1832 check_scope += ', repo_group_name:%s' % (group_name,)
1846 check_scope += ', repo_group_name:%s' % (group_name,)
1833
1847
1834 if user_group_name:
1848 if user_group_name:
1835 check_scope += ', user_group_name:%s' % (user_group_name,)
1849 check_scope += ', user_group_name:%s' % (user_group_name,)
1836
1850
1837 log.debug(
1851 log.debug(
1838 'checking cls:%s %s %s @ %s'
1852 'checking cls:%s %s %s @ %s'
1839 % (cls_name, self.required_perms, check_scope, check_location))
1853 % (cls_name, self.required_perms, check_scope, check_location))
1840 if not user:
1854 if not user:
1841 log.debug('Empty User passed into arguments')
1855 log.debug('Empty User passed into arguments')
1842 return False
1856 return False
1843
1857
1844 # process user
1858 # process user
1845 if not isinstance(user, AuthUser):
1859 if not isinstance(user, AuthUser):
1846 user = AuthUser(user.user_id)
1860 user = AuthUser(user.user_id)
1847 if not check_location:
1861 if not check_location:
1848 check_location = 'unspecified'
1862 check_location = 'unspecified'
1849 if self.check_permissions(user.permissions, repo_name, group_name,
1863 if self.check_permissions(user.permissions, repo_name, group_name,
1850 user_group_name):
1864 user_group_name):
1851 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1865 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1852 check_scope, user, check_location)
1866 check_scope, user, check_location)
1853 return True
1867 return True
1854
1868
1855 else:
1869 else:
1856 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1870 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1857 check_scope, user, check_location)
1871 check_scope, user, check_location)
1858 return False
1872 return False
1859
1873
1860 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1874 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1861 user_group_name=None):
1875 user_group_name=None):
1862 """
1876 """
1863 implement in child class should return True if permissions are ok,
1877 implement in child class should return True if permissions are ok,
1864 False otherwise
1878 False otherwise
1865
1879
1866 :param perm_defs: dict with permission definitions
1880 :param perm_defs: dict with permission definitions
1867 :param repo_name: repo name
1881 :param repo_name: repo name
1868 """
1882 """
1869 raise NotImplementedError()
1883 raise NotImplementedError()
1870
1884
1871
1885
1872 class HasPermissionAllApi(_BaseApiPerm):
1886 class HasPermissionAllApi(_BaseApiPerm):
1873 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1887 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1874 user_group_name=None):
1888 user_group_name=None):
1875 if self.required_perms.issubset(perm_defs.get('global')):
1889 if self.required_perms.issubset(perm_defs.get('global')):
1876 return True
1890 return True
1877 return False
1891 return False
1878
1892
1879
1893
1880 class HasPermissionAnyApi(_BaseApiPerm):
1894 class HasPermissionAnyApi(_BaseApiPerm):
1881 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1895 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1882 user_group_name=None):
1896 user_group_name=None):
1883 if self.required_perms.intersection(perm_defs.get('global')):
1897 if self.required_perms.intersection(perm_defs.get('global')):
1884 return True
1898 return True
1885 return False
1899 return False
1886
1900
1887
1901
1888 class HasRepoPermissionAllApi(_BaseApiPerm):
1902 class HasRepoPermissionAllApi(_BaseApiPerm):
1889 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1903 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1890 user_group_name=None):
1904 user_group_name=None):
1891 try:
1905 try:
1892 _user_perms = set([perm_defs['repositories'][repo_name]])
1906 _user_perms = set([perm_defs['repositories'][repo_name]])
1893 except KeyError:
1907 except KeyError:
1894 log.warning(traceback.format_exc())
1908 log.warning(traceback.format_exc())
1895 return False
1909 return False
1896 if self.required_perms.issubset(_user_perms):
1910 if self.required_perms.issubset(_user_perms):
1897 return True
1911 return True
1898 return False
1912 return False
1899
1913
1900
1914
1901 class HasRepoPermissionAnyApi(_BaseApiPerm):
1915 class HasRepoPermissionAnyApi(_BaseApiPerm):
1902 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1916 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1903 user_group_name=None):
1917 user_group_name=None):
1904 try:
1918 try:
1905 _user_perms = set([perm_defs['repositories'][repo_name]])
1919 _user_perms = set([perm_defs['repositories'][repo_name]])
1906 except KeyError:
1920 except KeyError:
1907 log.warning(traceback.format_exc())
1921 log.warning(traceback.format_exc())
1908 return False
1922 return False
1909 if self.required_perms.intersection(_user_perms):
1923 if self.required_perms.intersection(_user_perms):
1910 return True
1924 return True
1911 return False
1925 return False
1912
1926
1913
1927
1914 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1928 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1915 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1929 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1916 user_group_name=None):
1930 user_group_name=None):
1917 try:
1931 try:
1918 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1932 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1919 except KeyError:
1933 except KeyError:
1920 log.warning(traceback.format_exc())
1934 log.warning(traceback.format_exc())
1921 return False
1935 return False
1922 if self.required_perms.intersection(_user_perms):
1936 if self.required_perms.intersection(_user_perms):
1923 return True
1937 return True
1924 return False
1938 return False
1925
1939
1926
1940
1927 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1941 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1928 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1942 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1929 user_group_name=None):
1943 user_group_name=None):
1930 try:
1944 try:
1931 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1945 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1932 except KeyError:
1946 except KeyError:
1933 log.warning(traceback.format_exc())
1947 log.warning(traceback.format_exc())
1934 return False
1948 return False
1935 if self.required_perms.issubset(_user_perms):
1949 if self.required_perms.issubset(_user_perms):
1936 return True
1950 return True
1937 return False
1951 return False
1938
1952
1939
1953
1940 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1954 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1941 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1955 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1942 user_group_name=None):
1956 user_group_name=None):
1943 try:
1957 try:
1944 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1958 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1945 except KeyError:
1959 except KeyError:
1946 log.warning(traceback.format_exc())
1960 log.warning(traceback.format_exc())
1947 return False
1961 return False
1948 if self.required_perms.intersection(_user_perms):
1962 if self.required_perms.intersection(_user_perms):
1949 return True
1963 return True
1950 return False
1964 return False
1951
1965
1952
1966
1953 def check_ip_access(source_ip, allowed_ips=None):
1967 def check_ip_access(source_ip, allowed_ips=None):
1954 """
1968 """
1955 Checks if source_ip is a subnet of any of allowed_ips.
1969 Checks if source_ip is a subnet of any of allowed_ips.
1956
1970
1957 :param source_ip:
1971 :param source_ip:
1958 :param allowed_ips: list of allowed ips together with mask
1972 :param allowed_ips: list of allowed ips together with mask
1959 """
1973 """
1960 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1974 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1961 source_ip_address = ipaddress.ip_address(source_ip)
1975 source_ip_address = ipaddress.ip_address(source_ip)
1962 if isinstance(allowed_ips, (tuple, list, set)):
1976 if isinstance(allowed_ips, (tuple, list, set)):
1963 for ip in allowed_ips:
1977 for ip in allowed_ips:
1964 try:
1978 try:
1965 network_address = ipaddress.ip_network(ip, strict=False)
1979 network_address = ipaddress.ip_network(ip, strict=False)
1966 if source_ip_address in network_address:
1980 if source_ip_address in network_address:
1967 log.debug('IP %s is network %s' %
1981 log.debug('IP %s is network %s' %
1968 (source_ip_address, network_address))
1982 (source_ip_address, network_address))
1969 return True
1983 return True
1970 # for any case we cannot determine the IP, don't crash just
1984 # for any case we cannot determine the IP, don't crash just
1971 # skip it and log as error, we want to say forbidden still when
1985 # skip it and log as error, we want to say forbidden still when
1972 # sending bad IP
1986 # sending bad IP
1973 except Exception:
1987 except Exception:
1974 log.error(traceback.format_exc())
1988 log.error(traceback.format_exc())
1975 continue
1989 continue
1976 return False
1990 return False
1977
1991
1978
1992
1979 def get_cython_compat_decorator(wrapper, func):
1993 def get_cython_compat_decorator(wrapper, func):
1980 """
1994 """
1981 Creates a cython compatible decorator. The previously used
1995 Creates a cython compatible decorator. The previously used
1982 decorator.decorator() function seems to be incompatible with cython.
1996 decorator.decorator() function seems to be incompatible with cython.
1983
1997
1984 :param wrapper: __wrapper method of the decorator class
1998 :param wrapper: __wrapper method of the decorator class
1985 :param func: decorated function
1999 :param func: decorated function
1986 """
2000 """
1987 @wraps(func)
2001 @wraps(func)
1988 def local_wrapper(*args, **kwds):
2002 def local_wrapper(*args, **kwds):
1989 return wrapper(func, *args, **kwds)
2003 return wrapper(func, *args, **kwds)
1990 local_wrapper.__wrapped__ = func
2004 local_wrapper.__wrapped__ = func
1991 return local_wrapper
2005 return local_wrapper
1992
2006
1993
2007
General Comments 0
You need to be logged in to leave comments. Login now