##// END OF EJS Templates
core: properly handle new redirections set in decorators....
marcink -
r1499:d130151d default
parent child Browse files
Show More
@@ -1,495 +1,495 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 Pylons middleware initialization
22 Pylons middleware initialization
23 """
23 """
24 import logging
24 import logging
25 from collections import OrderedDict
25 from collections import OrderedDict
26
26
27 from paste.registry import RegistryManager
27 from paste.registry import RegistryManager
28 from paste.gzipper import make_gzip_middleware
28 from paste.gzipper import make_gzip_middleware
29 from pylons.wsgiapp import PylonsApp
29 from pylons.wsgiapp import PylonsApp
30 from pyramid.authorization import ACLAuthorizationPolicy
30 from pyramid.authorization import ACLAuthorizationPolicy
31 from pyramid.config import Configurator
31 from pyramid.config import Configurator
32 from pyramid.settings import asbool, aslist
32 from pyramid.settings import asbool, aslist
33 from pyramid.wsgi import wsgiapp
33 from pyramid.wsgi import wsgiapp
34 from pyramid.httpexceptions import (
34 from pyramid.httpexceptions import (
35 HTTPError, HTTPInternalServerError, HTTPFound)
35 HTTPException, HTTPError, HTTPInternalServerError, HTTPFound)
36 from pyramid.events import ApplicationCreated
36 from pyramid.events import ApplicationCreated
37 from pyramid.renderers import render_to_response
37 from pyramid.renderers import render_to_response
38 from routes.middleware import RoutesMiddleware
38 from routes.middleware import RoutesMiddleware
39 import routes.util
39 import routes.util
40
40
41 import rhodecode
41 import rhodecode
42 from rhodecode.model import meta
42 from rhodecode.model import meta
43 from rhodecode.config import patches
43 from rhodecode.config import patches
44 from rhodecode.config.routing import STATIC_FILE_PREFIX
44 from rhodecode.config.routing import STATIC_FILE_PREFIX
45 from rhodecode.config.environment import (
45 from rhodecode.config.environment import (
46 load_environment, load_pyramid_environment)
46 load_environment, load_pyramid_environment)
47 from rhodecode.lib.middleware import csrf
47 from rhodecode.lib.middleware import csrf
48 from rhodecode.lib.middleware.appenlight import wrap_in_appenlight_if_enabled
48 from rhodecode.lib.middleware.appenlight import wrap_in_appenlight_if_enabled
49 from rhodecode.lib.middleware.error_handling import (
49 from rhodecode.lib.middleware.error_handling import (
50 PylonsErrorHandlingMiddleware)
50 PylonsErrorHandlingMiddleware)
51 from rhodecode.lib.middleware.https_fixup import HttpsFixup
51 from rhodecode.lib.middleware.https_fixup import HttpsFixup
52 from rhodecode.lib.middleware.vcs import VCSMiddleware
52 from rhodecode.lib.middleware.vcs import VCSMiddleware
53 from rhodecode.lib.plugins.utils import register_rhodecode_plugin
53 from rhodecode.lib.plugins.utils import register_rhodecode_plugin
54 from rhodecode.lib.utils2 import aslist as rhodecode_aslist
54 from rhodecode.lib.utils2 import aslist as rhodecode_aslist
55 from rhodecode.subscribers import (
55 from rhodecode.subscribers import (
56 scan_repositories_if_enabled, write_metadata_if_needed)
56 scan_repositories_if_enabled, write_metadata_if_needed)
57
57
58
58
59 log = logging.getLogger(__name__)
59 log = logging.getLogger(__name__)
60
60
61
61
62 # this is used to avoid avoid the route lookup overhead in routesmiddleware
62 # this is used to avoid avoid the route lookup overhead in routesmiddleware
63 # for certain routes which won't go to pylons to - eg. static files, debugger
63 # for certain routes which won't go to pylons to - eg. static files, debugger
64 # it is only needed for the pylons migration and can be removed once complete
64 # it is only needed for the pylons migration and can be removed once complete
65 class SkippableRoutesMiddleware(RoutesMiddleware):
65 class SkippableRoutesMiddleware(RoutesMiddleware):
66 """ Routes middleware that allows you to skip prefixes """
66 """ Routes middleware that allows you to skip prefixes """
67
67
68 def __init__(self, *args, **kw):
68 def __init__(self, *args, **kw):
69 self.skip_prefixes = kw.pop('skip_prefixes', [])
69 self.skip_prefixes = kw.pop('skip_prefixes', [])
70 super(SkippableRoutesMiddleware, self).__init__(*args, **kw)
70 super(SkippableRoutesMiddleware, self).__init__(*args, **kw)
71
71
72 def __call__(self, environ, start_response):
72 def __call__(self, environ, start_response):
73 for prefix in self.skip_prefixes:
73 for prefix in self.skip_prefixes:
74 if environ['PATH_INFO'].startswith(prefix):
74 if environ['PATH_INFO'].startswith(prefix):
75 # added to avoid the case when a missing /_static route falls
75 # added to avoid the case when a missing /_static route falls
76 # through to pylons and causes an exception as pylons is
76 # through to pylons and causes an exception as pylons is
77 # expecting wsgiorg.routingargs to be set in the environ
77 # expecting wsgiorg.routingargs to be set in the environ
78 # by RoutesMiddleware.
78 # by RoutesMiddleware.
79 if 'wsgiorg.routing_args' not in environ:
79 if 'wsgiorg.routing_args' not in environ:
80 environ['wsgiorg.routing_args'] = (None, {})
80 environ['wsgiorg.routing_args'] = (None, {})
81 return self.app(environ, start_response)
81 return self.app(environ, start_response)
82
82
83 return super(SkippableRoutesMiddleware, self).__call__(
83 return super(SkippableRoutesMiddleware, self).__call__(
84 environ, start_response)
84 environ, start_response)
85
85
86
86
87 def make_app(global_conf, static_files=True, **app_conf):
87 def make_app(global_conf, static_files=True, **app_conf):
88 """Create a Pylons WSGI application and return it
88 """Create a Pylons WSGI application and return it
89
89
90 ``global_conf``
90 ``global_conf``
91 The inherited configuration for this application. Normally from
91 The inherited configuration for this application. Normally from
92 the [DEFAULT] section of the Paste ini file.
92 the [DEFAULT] section of the Paste ini file.
93
93
94 ``app_conf``
94 ``app_conf``
95 The application's local configuration. Normally specified in
95 The application's local configuration. Normally specified in
96 the [app:<name>] section of the Paste ini file (where <name>
96 the [app:<name>] section of the Paste ini file (where <name>
97 defaults to main).
97 defaults to main).
98
98
99 """
99 """
100 # Apply compatibility patches
100 # Apply compatibility patches
101 patches.kombu_1_5_1_python_2_7_11()
101 patches.kombu_1_5_1_python_2_7_11()
102 patches.inspect_getargspec()
102 patches.inspect_getargspec()
103
103
104 # Configure the Pylons environment
104 # Configure the Pylons environment
105 config = load_environment(global_conf, app_conf)
105 config = load_environment(global_conf, app_conf)
106
106
107 # The Pylons WSGI app
107 # The Pylons WSGI app
108 app = PylonsApp(config=config)
108 app = PylonsApp(config=config)
109 if rhodecode.is_test:
109 if rhodecode.is_test:
110 app = csrf.CSRFDetector(app)
110 app = csrf.CSRFDetector(app)
111
111
112 expected_origin = config.get('expected_origin')
112 expected_origin = config.get('expected_origin')
113 if expected_origin:
113 if expected_origin:
114 # The API can be accessed from other Origins.
114 # The API can be accessed from other Origins.
115 app = csrf.OriginChecker(app, expected_origin,
115 app = csrf.OriginChecker(app, expected_origin,
116 skip_urls=[routes.util.url_for('api')])
116 skip_urls=[routes.util.url_for('api')])
117
117
118 # Establish the Registry for this application
118 # Establish the Registry for this application
119 app = RegistryManager(app)
119 app = RegistryManager(app)
120
120
121 app.config = config
121 app.config = config
122
122
123 return app
123 return app
124
124
125
125
126 def make_pyramid_app(global_config, **settings):
126 def make_pyramid_app(global_config, **settings):
127 """
127 """
128 Constructs the WSGI application based on Pyramid and wraps the Pylons based
128 Constructs the WSGI application based on Pyramid and wraps the Pylons based
129 application.
129 application.
130
130
131 Specials:
131 Specials:
132
132
133 * We migrate from Pylons to Pyramid. While doing this, we keep both
133 * We migrate from Pylons to Pyramid. While doing this, we keep both
134 frameworks functional. This involves moving some WSGI middlewares around
134 frameworks functional. This involves moving some WSGI middlewares around
135 and providing access to some data internals, so that the old code is
135 and providing access to some data internals, so that the old code is
136 still functional.
136 still functional.
137
137
138 * The application can also be integrated like a plugin via the call to
138 * The application can also be integrated like a plugin via the call to
139 `includeme`. This is accompanied with the other utility functions which
139 `includeme`. This is accompanied with the other utility functions which
140 are called. Changing this should be done with great care to not break
140 are called. Changing this should be done with great care to not break
141 cases when these fragments are assembled from another place.
141 cases when these fragments are assembled from another place.
142
142
143 """
143 """
144 # The edition string should be available in pylons too, so we add it here
144 # The edition string should be available in pylons too, so we add it here
145 # before copying the settings.
145 # before copying the settings.
146 settings.setdefault('rhodecode.edition', 'Community Edition')
146 settings.setdefault('rhodecode.edition', 'Community Edition')
147
147
148 # As long as our Pylons application does expect "unprepared" settings, make
148 # As long as our Pylons application does expect "unprepared" settings, make
149 # sure that we keep an unmodified copy. This avoids unintentional change of
149 # sure that we keep an unmodified copy. This avoids unintentional change of
150 # behavior in the old application.
150 # behavior in the old application.
151 settings_pylons = settings.copy()
151 settings_pylons = settings.copy()
152
152
153 sanitize_settings_and_apply_defaults(settings)
153 sanitize_settings_and_apply_defaults(settings)
154 config = Configurator(settings=settings)
154 config = Configurator(settings=settings)
155 add_pylons_compat_data(config.registry, global_config, settings_pylons)
155 add_pylons_compat_data(config.registry, global_config, settings_pylons)
156
156
157 load_pyramid_environment(global_config, settings)
157 load_pyramid_environment(global_config, settings)
158
158
159 includeme_first(config)
159 includeme_first(config)
160 includeme(config)
160 includeme(config)
161 pyramid_app = config.make_wsgi_app()
161 pyramid_app = config.make_wsgi_app()
162 pyramid_app = wrap_app_in_wsgi_middlewares(pyramid_app, config)
162 pyramid_app = wrap_app_in_wsgi_middlewares(pyramid_app, config)
163 pyramid_app.config = config
163 pyramid_app.config = config
164
164
165 # creating the app uses a connection - return it after we are done
165 # creating the app uses a connection - return it after we are done
166 meta.Session.remove()
166 meta.Session.remove()
167
167
168 return pyramid_app
168 return pyramid_app
169
169
170
170
171 def make_not_found_view(config):
171 def make_not_found_view(config):
172 """
172 """
173 This creates the view which should be registered as not-found-view to
173 This creates the view which should be registered as not-found-view to
174 pyramid. Basically it contains of the old pylons app, converted to a view.
174 pyramid. Basically it contains of the old pylons app, converted to a view.
175 Additionally it is wrapped by some other middlewares.
175 Additionally it is wrapped by some other middlewares.
176 """
176 """
177 settings = config.registry.settings
177 settings = config.registry.settings
178 vcs_server_enabled = settings['vcs.server.enable']
178 vcs_server_enabled = settings['vcs.server.enable']
179
179
180 # Make pylons app from unprepared settings.
180 # Make pylons app from unprepared settings.
181 pylons_app = make_app(
181 pylons_app = make_app(
182 config.registry._pylons_compat_global_config,
182 config.registry._pylons_compat_global_config,
183 **config.registry._pylons_compat_settings)
183 **config.registry._pylons_compat_settings)
184 config.registry._pylons_compat_config = pylons_app.config
184 config.registry._pylons_compat_config = pylons_app.config
185
185
186 # Appenlight monitoring.
186 # Appenlight monitoring.
187 pylons_app, appenlight_client = wrap_in_appenlight_if_enabled(
187 pylons_app, appenlight_client = wrap_in_appenlight_if_enabled(
188 pylons_app, settings)
188 pylons_app, settings)
189
189
190 # The pylons app is executed inside of the pyramid 404 exception handler.
190 # The pylons app is executed inside of the pyramid 404 exception handler.
191 # Exceptions which are raised inside of it are not handled by pyramid
191 # Exceptions which are raised inside of it are not handled by pyramid
192 # again. Therefore we add a middleware that invokes the error handler in
192 # again. Therefore we add a middleware that invokes the error handler in
193 # case of an exception or error response. This way we return proper error
193 # case of an exception or error response. This way we return proper error
194 # HTML pages in case of an error.
194 # HTML pages in case of an error.
195 reraise = (settings.get('debugtoolbar.enabled', False) or
195 reraise = (settings.get('debugtoolbar.enabled', False) or
196 rhodecode.disable_error_handler)
196 rhodecode.disable_error_handler)
197 pylons_app = PylonsErrorHandlingMiddleware(
197 pylons_app = PylonsErrorHandlingMiddleware(
198 pylons_app, error_handler, reraise)
198 pylons_app, error_handler, reraise)
199
199
200 # The VCSMiddleware shall operate like a fallback if pyramid doesn't find a
200 # The VCSMiddleware shall operate like a fallback if pyramid doesn't find a
201 # view to handle the request. Therefore it is wrapped around the pylons
201 # view to handle the request. Therefore it is wrapped around the pylons
202 # app. It has to be outside of the error handling otherwise error responses
202 # app. It has to be outside of the error handling otherwise error responses
203 # from the vcsserver are converted to HTML error pages. This confuses the
203 # from the vcsserver are converted to HTML error pages. This confuses the
204 # command line tools and the user won't get a meaningful error message.
204 # command line tools and the user won't get a meaningful error message.
205 if vcs_server_enabled:
205 if vcs_server_enabled:
206 pylons_app = VCSMiddleware(
206 pylons_app = VCSMiddleware(
207 pylons_app, settings, appenlight_client, registry=config.registry)
207 pylons_app, settings, appenlight_client, registry=config.registry)
208
208
209 # Convert WSGI app to pyramid view and return it.
209 # Convert WSGI app to pyramid view and return it.
210 return wsgiapp(pylons_app)
210 return wsgiapp(pylons_app)
211
211
212
212
213 def add_pylons_compat_data(registry, global_config, settings):
213 def add_pylons_compat_data(registry, global_config, settings):
214 """
214 """
215 Attach data to the registry to support the Pylons integration.
215 Attach data to the registry to support the Pylons integration.
216 """
216 """
217 registry._pylons_compat_global_config = global_config
217 registry._pylons_compat_global_config = global_config
218 registry._pylons_compat_settings = settings
218 registry._pylons_compat_settings = settings
219
219
220
220
221 def error_handler(exception, request):
221 def error_handler(exception, request):
222 import rhodecode
222 import rhodecode
223 from rhodecode.lib.utils2 import AttributeDict
223 from rhodecode.lib.utils2 import AttributeDict
224
224
225 rhodecode_title = rhodecode.CONFIG.get('rhodecode_title') or 'RhodeCode'
225 rhodecode_title = rhodecode.CONFIG.get('rhodecode_title') or 'RhodeCode'
226
226
227 base_response = HTTPInternalServerError()
227 base_response = HTTPInternalServerError()
228 # prefer original exception for the response since it may have headers set
228 # prefer original exception for the response since it may have headers set
229 if isinstance(exception, HTTPError):
229 if isinstance(exception, HTTPException):
230 base_response = exception
230 base_response = exception
231
231
232 def is_http_error(response):
232 def is_http_error(response):
233 # error which should have traceback
233 # error which should have traceback
234 return response.status_code > 499
234 return response.status_code > 499
235
235
236 if is_http_error(base_response):
236 if is_http_error(base_response):
237 log.exception(
237 log.exception(
238 'error occurred handling this request for path: %s', request.path)
238 'error occurred handling this request for path: %s', request.path)
239
239
240 c = AttributeDict()
240 c = AttributeDict()
241 c.error_message = base_response.status
241 c.error_message = base_response.status
242 c.error_explanation = base_response.explanation or str(base_response)
242 c.error_explanation = base_response.explanation or str(base_response)
243 c.visual = AttributeDict()
243 c.visual = AttributeDict()
244
244
245 c.visual.rhodecode_support_url = (
245 c.visual.rhodecode_support_url = (
246 request.registry.settings.get('rhodecode_support_url') or
246 request.registry.settings.get('rhodecode_support_url') or
247 request.route_url('rhodecode_support')
247 request.route_url('rhodecode_support')
248 )
248 )
249 c.redirect_time = 0
249 c.redirect_time = 0
250 c.rhodecode_name = rhodecode_title
250 c.rhodecode_name = rhodecode_title
251 if not c.rhodecode_name:
251 if not c.rhodecode_name:
252 c.rhodecode_name = 'Rhodecode'
252 c.rhodecode_name = 'Rhodecode'
253
253
254 c.causes = []
254 c.causes = []
255 if hasattr(base_response, 'causes'):
255 if hasattr(base_response, 'causes'):
256 c.causes = base_response.causes
256 c.causes = base_response.causes
257
257
258 response = render_to_response(
258 response = render_to_response(
259 '/errors/error_document.mako', {'c': c}, request=request,
259 '/errors/error_document.mako', {'c': c}, request=request,
260 response=base_response)
260 response=base_response)
261
261
262 return response
262 return response
263
263
264
264
265 def includeme(config):
265 def includeme(config):
266 settings = config.registry.settings
266 settings = config.registry.settings
267
267
268 # plugin information
268 # plugin information
269 config.registry.rhodecode_plugins = OrderedDict()
269 config.registry.rhodecode_plugins = OrderedDict()
270
270
271 config.add_directive(
271 config.add_directive(
272 'register_rhodecode_plugin', register_rhodecode_plugin)
272 'register_rhodecode_plugin', register_rhodecode_plugin)
273
273
274 if asbool(settings.get('appenlight', 'false')):
274 if asbool(settings.get('appenlight', 'false')):
275 config.include('appenlight_client.ext.pyramid_tween')
275 config.include('appenlight_client.ext.pyramid_tween')
276
276
277 # Includes which are required. The application would fail without them.
277 # Includes which are required. The application would fail without them.
278 config.include('pyramid_mako')
278 config.include('pyramid_mako')
279 config.include('pyramid_beaker')
279 config.include('pyramid_beaker')
280 config.include('rhodecode.channelstream')
280 config.include('rhodecode.channelstream')
281 config.include('rhodecode.admin')
281 config.include('rhodecode.admin')
282 config.include('rhodecode.authentication')
282 config.include('rhodecode.authentication')
283 config.include('rhodecode.integrations')
283 config.include('rhodecode.integrations')
284 config.include('rhodecode.login')
284 config.include('rhodecode.login')
285 config.include('rhodecode.tweens')
285 config.include('rhodecode.tweens')
286 config.include('rhodecode.api')
286 config.include('rhodecode.api')
287 config.include('rhodecode.svn_support')
287 config.include('rhodecode.svn_support')
288 config.add_route(
288 config.add_route(
289 'rhodecode_support', 'https://rhodecode.com/help/', static=True)
289 'rhodecode_support', 'https://rhodecode.com/help/', static=True)
290
290
291 config.add_translation_dirs('rhodecode:i18n/')
291 config.add_translation_dirs('rhodecode:i18n/')
292 settings['default_locale_name'] = settings.get('lang', 'en')
292 settings['default_locale_name'] = settings.get('lang', 'en')
293
293
294 # Add subscribers.
294 # Add subscribers.
295 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
295 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
296 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
296 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
297
297
298 # Set the authorization policy.
298 # Set the authorization policy.
299 authz_policy = ACLAuthorizationPolicy()
299 authz_policy = ACLAuthorizationPolicy()
300 config.set_authorization_policy(authz_policy)
300 config.set_authorization_policy(authz_policy)
301
301
302 # Set the default renderer for HTML templates to mako.
302 # Set the default renderer for HTML templates to mako.
303 config.add_mako_renderer('.html')
303 config.add_mako_renderer('.html')
304
304
305 # include RhodeCode plugins
305 # include RhodeCode plugins
306 includes = aslist(settings.get('rhodecode.includes', []))
306 includes = aslist(settings.get('rhodecode.includes', []))
307 for inc in includes:
307 for inc in includes:
308 config.include(inc)
308 config.include(inc)
309
309
310 # This is the glue which allows us to migrate in chunks. By registering the
310 # This is the glue which allows us to migrate in chunks. By registering the
311 # pylons based application as the "Not Found" view in Pyramid, we will
311 # pylons based application as the "Not Found" view in Pyramid, we will
312 # fallback to the old application each time the new one does not yet know
312 # fallback to the old application each time the new one does not yet know
313 # how to handle a request.
313 # how to handle a request.
314 config.add_notfound_view(make_not_found_view(config))
314 config.add_notfound_view(make_not_found_view(config))
315
315
316 if not settings.get('debugtoolbar.enabled', False):
316 if not settings.get('debugtoolbar.enabled', False):
317 # if no toolbar, then any exception gets caught and rendered
317 # if no toolbar, then any exception gets caught and rendered
318 config.add_view(error_handler, context=Exception)
318 config.add_view(error_handler, context=Exception)
319
319
320 config.add_view(error_handler, context=HTTPError)
320 config.add_view(error_handler, context=HTTPError)
321
321
322
322
323 def includeme_first(config):
323 def includeme_first(config):
324 # redirect automatic browser favicon.ico requests to correct place
324 # redirect automatic browser favicon.ico requests to correct place
325 def favicon_redirect(context, request):
325 def favicon_redirect(context, request):
326 return HTTPFound(
326 return HTTPFound(
327 request.static_path('rhodecode:public/images/favicon.ico'))
327 request.static_path('rhodecode:public/images/favicon.ico'))
328
328
329 config.add_view(favicon_redirect, route_name='favicon')
329 config.add_view(favicon_redirect, route_name='favicon')
330 config.add_route('favicon', '/favicon.ico')
330 config.add_route('favicon', '/favicon.ico')
331
331
332 def robots_redirect(context, request):
332 def robots_redirect(context, request):
333 return HTTPFound(
333 return HTTPFound(
334 request.static_path('rhodecode:public/robots.txt'))
334 request.static_path('rhodecode:public/robots.txt'))
335
335
336 config.add_view(robots_redirect, route_name='robots')
336 config.add_view(robots_redirect, route_name='robots')
337 config.add_route('robots', '/robots.txt')
337 config.add_route('robots', '/robots.txt')
338
338
339 config.add_static_view(
339 config.add_static_view(
340 '_static/deform', 'deform:static')
340 '_static/deform', 'deform:static')
341 config.add_static_view(
341 config.add_static_view(
342 '_static/rhodecode', path='rhodecode:public', cache_max_age=3600 * 24)
342 '_static/rhodecode', path='rhodecode:public', cache_max_age=3600 * 24)
343
343
344
344
345 def wrap_app_in_wsgi_middlewares(pyramid_app, config):
345 def wrap_app_in_wsgi_middlewares(pyramid_app, config):
346 """
346 """
347 Apply outer WSGI middlewares around the application.
347 Apply outer WSGI middlewares around the application.
348
348
349 Part of this has been moved up from the Pylons layer, so that the
349 Part of this has been moved up from the Pylons layer, so that the
350 data is also available if old Pylons code is hit through an already ported
350 data is also available if old Pylons code is hit through an already ported
351 view.
351 view.
352 """
352 """
353 settings = config.registry.settings
353 settings = config.registry.settings
354
354
355 # enable https redirects based on HTTP_X_URL_SCHEME set by proxy
355 # enable https redirects based on HTTP_X_URL_SCHEME set by proxy
356 pyramid_app = HttpsFixup(pyramid_app, settings)
356 pyramid_app = HttpsFixup(pyramid_app, settings)
357
357
358 # Add RoutesMiddleware to support the pylons compatibility tween during
358 # Add RoutesMiddleware to support the pylons compatibility tween during
359 # migration to pyramid.
359 # migration to pyramid.
360 pyramid_app = SkippableRoutesMiddleware(
360 pyramid_app = SkippableRoutesMiddleware(
361 pyramid_app, config.registry._pylons_compat_config['routes.map'],
361 pyramid_app, config.registry._pylons_compat_config['routes.map'],
362 skip_prefixes=(STATIC_FILE_PREFIX, '/_debug_toolbar'))
362 skip_prefixes=(STATIC_FILE_PREFIX, '/_debug_toolbar'))
363
363
364 pyramid_app, _ = wrap_in_appenlight_if_enabled(pyramid_app, settings)
364 pyramid_app, _ = wrap_in_appenlight_if_enabled(pyramid_app, settings)
365
365
366 if settings['gzip_responses']:
366 if settings['gzip_responses']:
367 pyramid_app = make_gzip_middleware(
367 pyramid_app = make_gzip_middleware(
368 pyramid_app, settings, compress_level=1)
368 pyramid_app, settings, compress_level=1)
369
369
370 # this should be the outer most middleware in the wsgi stack since
370 # this should be the outer most middleware in the wsgi stack since
371 # middleware like Routes make database calls
371 # middleware like Routes make database calls
372 def pyramid_app_with_cleanup(environ, start_response):
372 def pyramid_app_with_cleanup(environ, start_response):
373 try:
373 try:
374 return pyramid_app(environ, start_response)
374 return pyramid_app(environ, start_response)
375 finally:
375 finally:
376 # Dispose current database session and rollback uncommitted
376 # Dispose current database session and rollback uncommitted
377 # transactions.
377 # transactions.
378 meta.Session.remove()
378 meta.Session.remove()
379
379
380 # In a single threaded mode server, on non sqlite db we should have
380 # In a single threaded mode server, on non sqlite db we should have
381 # '0 Current Checked out connections' at the end of a request,
381 # '0 Current Checked out connections' at the end of a request,
382 # if not, then something, somewhere is leaving a connection open
382 # if not, then something, somewhere is leaving a connection open
383 pool = meta.Base.metadata.bind.engine.pool
383 pool = meta.Base.metadata.bind.engine.pool
384 log.debug('sa pool status: %s', pool.status())
384 log.debug('sa pool status: %s', pool.status())
385
385
386
386
387 return pyramid_app_with_cleanup
387 return pyramid_app_with_cleanup
388
388
389
389
390 def sanitize_settings_and_apply_defaults(settings):
390 def sanitize_settings_and_apply_defaults(settings):
391 """
391 """
392 Applies settings defaults and does all type conversion.
392 Applies settings defaults and does all type conversion.
393
393
394 We would move all settings parsing and preparation into this place, so that
394 We would move all settings parsing and preparation into this place, so that
395 we have only one place left which deals with this part. The remaining parts
395 we have only one place left which deals with this part. The remaining parts
396 of the application would start to rely fully on well prepared settings.
396 of the application would start to rely fully on well prepared settings.
397
397
398 This piece would later be split up per topic to avoid a big fat monster
398 This piece would later be split up per topic to avoid a big fat monster
399 function.
399 function.
400 """
400 """
401
401
402 # Pyramid's mako renderer has to search in the templates folder so that the
402 # Pyramid's mako renderer has to search in the templates folder so that the
403 # old templates still work. Ported and new templates are expected to use
403 # old templates still work. Ported and new templates are expected to use
404 # real asset specifications for the includes.
404 # real asset specifications for the includes.
405 mako_directories = settings.setdefault('mako.directories', [
405 mako_directories = settings.setdefault('mako.directories', [
406 # Base templates of the original Pylons application
406 # Base templates of the original Pylons application
407 'rhodecode:templates',
407 'rhodecode:templates',
408 ])
408 ])
409 log.debug(
409 log.debug(
410 "Using the following Mako template directories: %s",
410 "Using the following Mako template directories: %s",
411 mako_directories)
411 mako_directories)
412
412
413 # Default includes, possible to change as a user
413 # Default includes, possible to change as a user
414 pyramid_includes = settings.setdefault('pyramid.includes', [
414 pyramid_includes = settings.setdefault('pyramid.includes', [
415 'rhodecode.lib.middleware.request_wrapper',
415 'rhodecode.lib.middleware.request_wrapper',
416 ])
416 ])
417 log.debug(
417 log.debug(
418 "Using the following pyramid.includes: %s",
418 "Using the following pyramid.includes: %s",
419 pyramid_includes)
419 pyramid_includes)
420
420
421 # TODO: johbo: Re-think this, usually the call to config.include
421 # TODO: johbo: Re-think this, usually the call to config.include
422 # should allow to pass in a prefix.
422 # should allow to pass in a prefix.
423 settings.setdefault('rhodecode.api.url', '/_admin/api')
423 settings.setdefault('rhodecode.api.url', '/_admin/api')
424
424
425 # Sanitize generic settings.
425 # Sanitize generic settings.
426 _list_setting(settings, 'default_encoding', 'UTF-8')
426 _list_setting(settings, 'default_encoding', 'UTF-8')
427 _bool_setting(settings, 'is_test', 'false')
427 _bool_setting(settings, 'is_test', 'false')
428 _bool_setting(settings, 'gzip_responses', 'false')
428 _bool_setting(settings, 'gzip_responses', 'false')
429
429
430 # Call split out functions that sanitize settings for each topic.
430 # Call split out functions that sanitize settings for each topic.
431 _sanitize_appenlight_settings(settings)
431 _sanitize_appenlight_settings(settings)
432 _sanitize_vcs_settings(settings)
432 _sanitize_vcs_settings(settings)
433
433
434 return settings
434 return settings
435
435
436
436
437 def _sanitize_appenlight_settings(settings):
437 def _sanitize_appenlight_settings(settings):
438 _bool_setting(settings, 'appenlight', 'false')
438 _bool_setting(settings, 'appenlight', 'false')
439
439
440
440
441 def _sanitize_vcs_settings(settings):
441 def _sanitize_vcs_settings(settings):
442 """
442 """
443 Applies settings defaults and does type conversion for all VCS related
443 Applies settings defaults and does type conversion for all VCS related
444 settings.
444 settings.
445 """
445 """
446 _string_setting(settings, 'vcs.svn.compatible_version', '')
446 _string_setting(settings, 'vcs.svn.compatible_version', '')
447 _string_setting(settings, 'git_rev_filter', '--all')
447 _string_setting(settings, 'git_rev_filter', '--all')
448 _string_setting(settings, 'vcs.hooks.protocol', 'http')
448 _string_setting(settings, 'vcs.hooks.protocol', 'http')
449 _string_setting(settings, 'vcs.scm_app_implementation', 'http')
449 _string_setting(settings, 'vcs.scm_app_implementation', 'http')
450 _string_setting(settings, 'vcs.server', '')
450 _string_setting(settings, 'vcs.server', '')
451 _string_setting(settings, 'vcs.server.log_level', 'debug')
451 _string_setting(settings, 'vcs.server.log_level', 'debug')
452 _string_setting(settings, 'vcs.server.protocol', 'http')
452 _string_setting(settings, 'vcs.server.protocol', 'http')
453 _bool_setting(settings, 'startup.import_repos', 'false')
453 _bool_setting(settings, 'startup.import_repos', 'false')
454 _bool_setting(settings, 'vcs.hooks.direct_calls', 'false')
454 _bool_setting(settings, 'vcs.hooks.direct_calls', 'false')
455 _bool_setting(settings, 'vcs.server.enable', 'true')
455 _bool_setting(settings, 'vcs.server.enable', 'true')
456 _bool_setting(settings, 'vcs.start_server', 'false')
456 _bool_setting(settings, 'vcs.start_server', 'false')
457 _list_setting(settings, 'vcs.backends', 'hg, git, svn')
457 _list_setting(settings, 'vcs.backends', 'hg, git, svn')
458 _int_setting(settings, 'vcs.connection_timeout', 3600)
458 _int_setting(settings, 'vcs.connection_timeout', 3600)
459
459
460 # Support legacy values of vcs.scm_app_implementation. Legacy
460 # Support legacy values of vcs.scm_app_implementation. Legacy
461 # configurations may use 'rhodecode.lib.middleware.utils.scm_app_http'
461 # configurations may use 'rhodecode.lib.middleware.utils.scm_app_http'
462 # which is now mapped to 'http'.
462 # which is now mapped to 'http'.
463 scm_app_impl = settings['vcs.scm_app_implementation']
463 scm_app_impl = settings['vcs.scm_app_implementation']
464 if scm_app_impl == 'rhodecode.lib.middleware.utils.scm_app_http':
464 if scm_app_impl == 'rhodecode.lib.middleware.utils.scm_app_http':
465 settings['vcs.scm_app_implementation'] = 'http'
465 settings['vcs.scm_app_implementation'] = 'http'
466
466
467
467
468 def _int_setting(settings, name, default):
468 def _int_setting(settings, name, default):
469 settings[name] = int(settings.get(name, default))
469 settings[name] = int(settings.get(name, default))
470
470
471
471
472 def _bool_setting(settings, name, default):
472 def _bool_setting(settings, name, default):
473 input = settings.get(name, default)
473 input = settings.get(name, default)
474 if isinstance(input, unicode):
474 if isinstance(input, unicode):
475 input = input.encode('utf8')
475 input = input.encode('utf8')
476 settings[name] = asbool(input)
476 settings[name] = asbool(input)
477
477
478
478
479 def _list_setting(settings, name, default):
479 def _list_setting(settings, name, default):
480 raw_value = settings.get(name, default)
480 raw_value = settings.get(name, default)
481
481
482 old_separator = ','
482 old_separator = ','
483 if old_separator in raw_value:
483 if old_separator in raw_value:
484 # If we get a comma separated list, pass it to our own function.
484 # If we get a comma separated list, pass it to our own function.
485 settings[name] = rhodecode_aslist(raw_value, sep=old_separator)
485 settings[name] = rhodecode_aslist(raw_value, sep=old_separator)
486 else:
486 else:
487 # Otherwise we assume it uses pyramids space/newline separation.
487 # Otherwise we assume it uses pyramids space/newline separation.
488 settings[name] = aslist(raw_value)
488 settings[name] = aslist(raw_value)
489
489
490
490
491 def _string_setting(settings, name, default, lower=True):
491 def _string_setting(settings, name, default, lower=True):
492 value = settings.get(name, default)
492 value = settings.get(name, default)
493 if lower:
493 if lower:
494 value = value.lower()
494 value = value.lower()
495 settings[name] = value
495 settings[name] = value
@@ -1,1972 +1,1973 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'
141 ENC_PREF = '$2a$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(FromCache("sql_cache_short",
1048 default_ips = default_ips.options(FromCache("sql_cache_short",
1049 "get_user_ips_default"))
1049 "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(FromCache("sql_cache_short",
1062 user_ips = user_ips.options(FromCache("sql_cache_short",
1063 "get_user_ips_%s" % user_id))
1063 "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 __wrapper(self, func, *fargs, **fkwargs):
1188 def __wrapper(self, func, *fargs, **fkwargs):
1189 from rhodecode.lib import helpers as h
1189 from rhodecode.lib import helpers as h
1190 cls = fargs[0]
1190 cls = fargs[0]
1191 user = cls._rhodecode_user
1191 user = cls._rhodecode_user
1192 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1192 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1193 log.debug('Starting login restriction checks for user: %s' % (user,))
1193 log.debug('Starting login restriction checks for user: %s' % (user,))
1194 # check if our IP is allowed
1194 # check if our IP is allowed
1195 ip_access_valid = True
1195 ip_access_valid = True
1196 if not user.ip_allowed:
1196 if not user.ip_allowed:
1197 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1197 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1198 category='warning')
1198 category='warning')
1199 ip_access_valid = False
1199 ip_access_valid = False
1200
1200
1201 # check if we used an APIKEY and it's a valid one
1201 # check if we used an APIKEY and it's a valid one
1202 # defined white-list of controllers which API access will be enabled
1202 # defined white-list of controllers which API access will be enabled
1203 _auth_token = request.GET.get(
1203 _auth_token = request.GET.get(
1204 'auth_token', '') or request.GET.get('api_key', '')
1204 'auth_token', '') or request.GET.get('api_key', '')
1205 auth_token_access_valid = allowed_auth_token_access(
1205 auth_token_access_valid = allowed_auth_token_access(
1206 loc, auth_token=_auth_token)
1206 loc, auth_token=_auth_token)
1207
1207
1208 # explicit controller is enabled or API is in our whitelist
1208 # explicit controller is enabled or API is in our whitelist
1209 if self.auth_token_access or auth_token_access_valid:
1209 if self.auth_token_access or auth_token_access_valid:
1210 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1210 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1211 db_user = user.get_instance()
1211 db_user = user.get_instance()
1212
1212
1213 if db_user:
1213 if db_user:
1214 if self.auth_token_access:
1214 if self.auth_token_access:
1215 roles = self.auth_token_access
1215 roles = self.auth_token_access
1216 else:
1216 else:
1217 roles = [UserApiKeys.ROLE_HTTP]
1217 roles = [UserApiKeys.ROLE_HTTP]
1218 token_match = db_user.authenticate_by_token(
1218 token_match = db_user.authenticate_by_token(
1219 _auth_token, roles=roles)
1219 _auth_token, roles=roles)
1220 else:
1220 else:
1221 log.debug('Unable to fetch db instance for auth user: %s', user)
1221 log.debug('Unable to fetch db instance for auth user: %s', user)
1222 token_match = False
1222 token_match = False
1223
1223
1224 if _auth_token and token_match:
1224 if _auth_token and token_match:
1225 auth_token_access_valid = True
1225 auth_token_access_valid = True
1226 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1226 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1227 else:
1227 else:
1228 auth_token_access_valid = False
1228 auth_token_access_valid = False
1229 if not _auth_token:
1229 if not _auth_token:
1230 log.debug("AUTH TOKEN *NOT* present in request")
1230 log.debug("AUTH TOKEN *NOT* present in request")
1231 else:
1231 else:
1232 log.warning(
1232 log.warning(
1233 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1233 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1234
1234
1235 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1235 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1236 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1236 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1237 else 'AUTH_TOKEN_AUTH'
1237 else 'AUTH_TOKEN_AUTH'
1238
1238
1239 if ip_access_valid and (
1239 if ip_access_valid and (
1240 user.is_authenticated or auth_token_access_valid):
1240 user.is_authenticated or auth_token_access_valid):
1241 log.info(
1241 log.info(
1242 'user %s authenticating with:%s IS authenticated on func %s'
1242 'user %s authenticating with:%s IS authenticated on func %s'
1243 % (user, reason, loc))
1243 % (user, reason, loc))
1244
1244
1245 # update user data to check last activity
1245 # update user data to check last activity
1246 user.update_lastactivity()
1246 user.update_lastactivity()
1247 Session().commit()
1247 Session().commit()
1248 return func(*fargs, **fkwargs)
1248 return func(*fargs, **fkwargs)
1249 else:
1249 else:
1250 log.warning(
1250 log.warning(
1251 'user %s authenticating with:%s NOT authenticated on '
1251 'user %s authenticating with:%s NOT authenticated on '
1252 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1252 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1253 % (user, reason, loc, ip_access_valid,
1253 % (user, reason, loc, ip_access_valid,
1254 auth_token_access_valid))
1254 auth_token_access_valid))
1255 # we preserve the get PARAM
1255 # we preserve the get PARAM
1256 came_from = request.path_qs
1256 came_from = request.path_qs
1257 log.debug('redirecting to login page with %s' % (came_from,))
1257 log.debug('redirecting to login page with %s' % (came_from,))
1258 return redirect(
1258 return redirect(
1259 h.route_path('login', _query={'came_from': came_from}))
1259 h.route_path('login', _query={'came_from': came_from}))
1260
1260
1261
1261
1262 class NotAnonymous(object):
1262 class NotAnonymous(object):
1263 """
1263 """
1264 Must be logged in to execute this function else
1264 Must be logged in to execute this function else
1265 redirect to login page"""
1265 redirect to login page"""
1266
1266
1267 def __call__(self, func):
1267 def __call__(self, func):
1268 return get_cython_compat_decorator(self.__wrapper, func)
1268 return get_cython_compat_decorator(self.__wrapper, func)
1269
1269
1270 def __wrapper(self, func, *fargs, **fkwargs):
1270 def __wrapper(self, func, *fargs, **fkwargs):
1271 import rhodecode.lib.helpers as h
1271 cls = fargs[0]
1272 cls = fargs[0]
1272 self.user = cls._rhodecode_user
1273 self.user = cls._rhodecode_user
1273
1274
1274 log.debug('Checking if user is not anonymous @%s' % cls)
1275 log.debug('Checking if user is not anonymous @%s' % cls)
1275
1276
1276 anonymous = self.user.username == User.DEFAULT_USER
1277 anonymous = self.user.username == User.DEFAULT_USER
1277
1278
1278 if anonymous:
1279 if anonymous:
1279 came_from = request.path_qs
1280 came_from = request.path_qs
1280
1281 import rhodecode.lib.helpers as h
1282 h.flash(_('You need to be a registered user to '
1281 h.flash(_('You need to be a registered user to '
1283 'perform this action'),
1282 'perform this action'),
1284 category='warning')
1283 category='warning')
1285 return redirect(
1284 return redirect(
1286 h.route_path('login', _query={'came_from': came_from}))
1285 h.route_path('login', _query={'came_from': came_from}))
1287 else:
1286 else:
1288 return func(*fargs, **fkwargs)
1287 return func(*fargs, **fkwargs)
1289
1288
1290
1289
1291 class XHRRequired(object):
1290 class XHRRequired(object):
1292 def __call__(self, func):
1291 def __call__(self, func):
1293 return get_cython_compat_decorator(self.__wrapper, func)
1292 return get_cython_compat_decorator(self.__wrapper, func)
1294
1293
1295 def __wrapper(self, func, *fargs, **fkwargs):
1294 def __wrapper(self, func, *fargs, **fkwargs):
1296 log.debug('Checking if request is XMLHttpRequest (XHR)')
1295 log.debug('Checking if request is XMLHttpRequest (XHR)')
1297 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1296 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1298 if not request.is_xhr:
1297 if not request.is_xhr:
1299 abort(400, detail=xhr_message)
1298 abort(400, detail=xhr_message)
1300
1299
1301 return func(*fargs, **fkwargs)
1300 return func(*fargs, **fkwargs)
1302
1301
1303
1302
1304 class HasAcceptedRepoType(object):
1303 class HasAcceptedRepoType(object):
1305 """
1304 """
1306 Check if requested repo is within given repo type aliases
1305 Check if requested repo is within given repo type aliases
1307
1306
1308 TODO: anderson: not sure where to put this decorator
1307 TODO: anderson: not sure where to put this decorator
1309 """
1308 """
1310
1309
1311 def __init__(self, *repo_type_list):
1310 def __init__(self, *repo_type_list):
1312 self.repo_type_list = set(repo_type_list)
1311 self.repo_type_list = set(repo_type_list)
1313
1312
1314 def __call__(self, func):
1313 def __call__(self, func):
1315 return get_cython_compat_decorator(self.__wrapper, func)
1314 return get_cython_compat_decorator(self.__wrapper, func)
1316
1315
1317 def __wrapper(self, func, *fargs, **fkwargs):
1316 def __wrapper(self, func, *fargs, **fkwargs):
1317 import rhodecode.lib.helpers as h
1318 cls = fargs[0]
1318 cls = fargs[0]
1319 rhodecode_repo = cls.rhodecode_repo
1319 rhodecode_repo = cls.rhodecode_repo
1320
1320
1321 log.debug('%s checking repo type for %s in %s',
1321 log.debug('%s checking repo type for %s in %s',
1322 self.__class__.__name__,
1322 self.__class__.__name__,
1323 rhodecode_repo.alias, self.repo_type_list)
1323 rhodecode_repo.alias, self.repo_type_list)
1324
1324
1325 if rhodecode_repo.alias in self.repo_type_list:
1325 if rhodecode_repo.alias in self.repo_type_list:
1326 return func(*fargs, **fkwargs)
1326 return func(*fargs, **fkwargs)
1327 else:
1327 else:
1328 import rhodecode.lib.helpers as h
1329 h.flash(h.literal(
1328 h.flash(h.literal(
1330 _('Action not supported for %s.' % rhodecode_repo.alias)),
1329 _('Action not supported for %s.' % rhodecode_repo.alias)),
1331 category='warning')
1330 category='warning')
1332 return redirect(
1331 return redirect(
1333 url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name))
1332 url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name))
1334
1333
1335
1334
1336 class PermsDecorator(object):
1335 class PermsDecorator(object):
1337 """
1336 """
1338 Base class for controller decorators, we extract the current user from
1337 Base class for controller decorators, we extract the current user from
1339 the class itself, which has it stored in base controllers
1338 the class itself, which has it stored in base controllers
1340 """
1339 """
1341
1340
1342 def __init__(self, *required_perms):
1341 def __init__(self, *required_perms):
1343 self.required_perms = set(required_perms)
1342 self.required_perms = set(required_perms)
1344
1343
1345 def __call__(self, func):
1344 def __call__(self, func):
1346 return get_cython_compat_decorator(self.__wrapper, func)
1345 return get_cython_compat_decorator(self.__wrapper, func)
1347
1346
1348 def _get_request(self):
1347 def _get_request(self):
1349 from pyramid.threadlocal import get_current_request
1348 from pyramid.threadlocal import get_current_request
1350 pyramid_request = get_current_request()
1349 pyramid_request = get_current_request()
1351 if not pyramid_request:
1350 if not pyramid_request:
1352 # return global request of pylons incase pyramid one isn't available
1351 # return global request of pylons in case pyramid isn't available
1353 return request
1352 return request
1354 return pyramid_request
1353 return pyramid_request
1355
1354
1356 def _get_came_from(self):
1355 def _get_came_from(self):
1357 _request = self._get_request()
1356 _request = self._get_request()
1358
1357
1359 # both pylons/pyramid has this attribute
1358 # both pylons/pyramid has this attribute
1360 return _request.path_qs
1359 return _request.path_qs
1361
1360
1362 def __wrapper(self, func, *fargs, **fkwargs):
1361 def __wrapper(self, func, *fargs, **fkwargs):
1362 import rhodecode.lib.helpers as h
1363 cls = fargs[0]
1363 cls = fargs[0]
1364 _user = cls._rhodecode_user
1364 _user = cls._rhodecode_user
1365
1365
1366 log.debug('checking %s permissions %s for %s %s',
1366 log.debug('checking %s permissions %s for %s %s',
1367 self.__class__.__name__, self.required_perms, cls, _user)
1367 self.__class__.__name__, self.required_perms, cls, _user)
1368
1368
1369 if self.check_permissions(_user):
1369 if self.check_permissions(_user):
1370 log.debug('Permission granted for %s %s', cls, _user)
1370 log.debug('Permission granted for %s %s', cls, _user)
1371 return func(*fargs, **fkwargs)
1371 return func(*fargs, **fkwargs)
1372
1372
1373 else:
1373 else:
1374 log.debug('Permission denied for %s %s', cls, _user)
1374 log.debug('Permission denied for %s %s', cls, _user)
1375 anonymous = _user.username == User.DEFAULT_USER
1375 anonymous = _user.username == User.DEFAULT_USER
1376
1376
1377 if anonymous:
1377 if anonymous:
1378 import rhodecode.lib.helpers as h
1379 came_from = self._get_came_from()
1378 came_from = self._get_came_from()
1380 h.flash(_('You need to be signed in to view this page'),
1379 h.flash(_('You need to be signed in to view this page'),
1381 category='warning')
1380 category='warning')
1382 raise HTTPFound(
1381 raise HTTPFound(
1383 h.route_path('login', _query={'came_from': came_from}))
1382 h.route_path('login', _query={'came_from': came_from}))
1384
1383
1385 else:
1384 else:
1386 # redirect with forbidden ret code
1385 # redirect with forbidden ret code
1387 raise HTTPForbidden()
1386 raise HTTPForbidden()
1388
1387
1389 def check_permissions(self, user):
1388 def check_permissions(self, user):
1390 """Dummy function for overriding"""
1389 """Dummy function for overriding"""
1391 raise NotImplementedError(
1390 raise NotImplementedError(
1392 'You have to write this function in child class')
1391 'You have to write this function in child class')
1393
1392
1394
1393
1395 class HasPermissionAllDecorator(PermsDecorator):
1394 class HasPermissionAllDecorator(PermsDecorator):
1396 """
1395 """
1397 Checks for access permission for all given predicates. All of them
1396 Checks for access permission for all given predicates. All of them
1398 have to be meet in order to fulfill the request
1397 have to be meet in order to fulfill the request
1399 """
1398 """
1400
1399
1401 def check_permissions(self, user):
1400 def check_permissions(self, user):
1402 perms = user.permissions_with_scope({})
1401 perms = user.permissions_with_scope({})
1403 if self.required_perms.issubset(perms['global']):
1402 if self.required_perms.issubset(perms['global']):
1404 return True
1403 return True
1405 return False
1404 return False
1406
1405
1407
1406
1408 class HasPermissionAnyDecorator(PermsDecorator):
1407 class HasPermissionAnyDecorator(PermsDecorator):
1409 """
1408 """
1410 Checks for access permission for any of given predicates. In order to
1409 Checks for access permission for any of given predicates. In order to
1411 fulfill the request any of predicates must be meet
1410 fulfill the request any of predicates must be meet
1412 """
1411 """
1413
1412
1414 def check_permissions(self, user):
1413 def check_permissions(self, user):
1415 perms = user.permissions_with_scope({})
1414 perms = user.permissions_with_scope({})
1416 if self.required_perms.intersection(perms['global']):
1415 if self.required_perms.intersection(perms['global']):
1417 return True
1416 return True
1418 return False
1417 return False
1419
1418
1420
1419
1421 class HasRepoPermissionAllDecorator(PermsDecorator):
1420 class HasRepoPermissionAllDecorator(PermsDecorator):
1422 """
1421 """
1423 Checks for access permission for all given predicates for specific
1422 Checks for access permission for all given predicates for specific
1424 repository. All of them have to be meet in order to fulfill the request
1423 repository. All of them have to be meet in order to fulfill the request
1425 """
1424 """
1426 def _get_repo_name(self):
1425 def _get_repo_name(self):
1427 _request = self._get_request()
1426 _request = self._get_request()
1428 return get_repo_slug(_request)
1427 return get_repo_slug(_request)
1429
1428
1430 def check_permissions(self, user):
1429 def check_permissions(self, user):
1431 perms = user.permissions
1430 perms = user.permissions
1432 repo_name = self._get_repo_name()
1431 repo_name = self._get_repo_name()
1433 try:
1432 try:
1434 user_perms = set([perms['repositories'][repo_name]])
1433 user_perms = set([perms['repositories'][repo_name]])
1435 except KeyError:
1434 except KeyError:
1436 return False
1435 return False
1437 if self.required_perms.issubset(user_perms):
1436 if self.required_perms.issubset(user_perms):
1438 return True
1437 return True
1439 return False
1438 return False
1440
1439
1441
1440
1442 class HasRepoPermissionAnyDecorator(PermsDecorator):
1441 class HasRepoPermissionAnyDecorator(PermsDecorator):
1443 """
1442 """
1444 Checks for access permission for any of given predicates for specific
1443 Checks for access permission for any of given predicates for specific
1445 repository. In order to fulfill the request any of predicates must be meet
1444 repository. In order to fulfill the request any of predicates must be meet
1446 """
1445 """
1447 def _get_repo_name(self):
1446 def _get_repo_name(self):
1448 _request = self._get_request()
1447 _request = self._get_request()
1449 return get_repo_slug(_request)
1448 return get_repo_slug(_request)
1450
1449
1451 def check_permissions(self, user):
1450 def check_permissions(self, user):
1452 perms = user.permissions
1451 perms = user.permissions
1453 repo_name = self._get_repo_name()
1452 repo_name = self._get_repo_name()
1454 try:
1453 try:
1455 user_perms = set([perms['repositories'][repo_name]])
1454 user_perms = set([perms['repositories'][repo_name]])
1456 except KeyError:
1455 except KeyError:
1457 return False
1456 return False
1458
1457
1459 if self.required_perms.intersection(user_perms):
1458 if self.required_perms.intersection(user_perms):
1460 return True
1459 return True
1461 return False
1460 return False
1462
1461
1463
1462
1464 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1463 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1465 """
1464 """
1466 Checks for access permission for all given predicates for specific
1465 Checks for access permission for all given predicates for specific
1467 repository group. All of them have to be meet in order to
1466 repository group. All of them have to be meet in order to
1468 fulfill the request
1467 fulfill the request
1469 """
1468 """
1470 def _get_repo_group_name(self):
1469 def _get_repo_group_name(self):
1471 _request = self._get_request()
1470 _request = self._get_request()
1472 return get_repo_group_slug(_request)
1471 return get_repo_group_slug(_request)
1473
1472
1474 def check_permissions(self, user):
1473 def check_permissions(self, user):
1475 perms = user.permissions
1474 perms = user.permissions
1476 group_name = self._get_repo_group_name()
1475 group_name = self._get_repo_group_name()
1477 try:
1476 try:
1478 user_perms = set([perms['repositories_groups'][group_name]])
1477 user_perms = set([perms['repositories_groups'][group_name]])
1479 except KeyError:
1478 except KeyError:
1480 return False
1479 return False
1481
1480
1482 if self.required_perms.issubset(user_perms):
1481 if self.required_perms.issubset(user_perms):
1483 return True
1482 return True
1484 return False
1483 return False
1485
1484
1486
1485
1487 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1486 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1488 """
1487 """
1489 Checks for access permission for any of given predicates for specific
1488 Checks for access permission for any of given predicates for specific
1490 repository group. In order to fulfill the request any
1489 repository group. In order to fulfill the request any
1491 of predicates must be met
1490 of predicates must be met
1492 """
1491 """
1493 def _get_repo_group_name(self):
1492 def _get_repo_group_name(self):
1494 _request = self._get_request()
1493 _request = self._get_request()
1495 return get_repo_group_slug(_request)
1494 return get_repo_group_slug(_request)
1496
1495
1497 def check_permissions(self, user):
1496 def check_permissions(self, user):
1498 perms = user.permissions
1497 perms = user.permissions
1499 group_name = self._get_repo_group_name()
1498 group_name = self._get_repo_group_name()
1500 try:
1499 try:
1501 user_perms = set([perms['repositories_groups'][group_name]])
1500 user_perms = set([perms['repositories_groups'][group_name]])
1502 except KeyError:
1501 except KeyError:
1503 return False
1502 return False
1504
1503
1505 if self.required_perms.intersection(user_perms):
1504 if self.required_perms.intersection(user_perms):
1506 return True
1505 return True
1507 return False
1506 return False
1508
1507
1509
1508
1510 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1509 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1511 """
1510 """
1512 Checks for access permission for all given predicates for specific
1511 Checks for access permission for all given predicates for specific
1513 user group. All of them have to be meet in order to fulfill the request
1512 user group. All of them have to be meet in order to fulfill the request
1514 """
1513 """
1515 def _get_user_group_name(self):
1514 def _get_user_group_name(self):
1516 _request = self._get_request()
1515 _request = self._get_request()
1517 return get_user_group_slug(_request)
1516 return get_user_group_slug(_request)
1518
1517
1519 def check_permissions(self, user):
1518 def check_permissions(self, user):
1520 perms = user.permissions
1519 perms = user.permissions
1521 group_name = self._get_user_group_name()
1520 group_name = self._get_user_group_name()
1522 try:
1521 try:
1523 user_perms = set([perms['user_groups'][group_name]])
1522 user_perms = set([perms['user_groups'][group_name]])
1524 except KeyError:
1523 except KeyError:
1525 return False
1524 return False
1526
1525
1527 if self.required_perms.issubset(user_perms):
1526 if self.required_perms.issubset(user_perms):
1528 return True
1527 return True
1529 return False
1528 return False
1530
1529
1531
1530
1532 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1531 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1533 """
1532 """
1534 Checks for access permission for any of given predicates for specific
1533 Checks for access permission for any of given predicates for specific
1535 user group. In order to fulfill the request any of predicates must be meet
1534 user group. In order to fulfill the request any of predicates must be meet
1536 """
1535 """
1537 def _get_user_group_name(self):
1536 def _get_user_group_name(self):
1538 _request = self._get_request()
1537 _request = self._get_request()
1539 return get_user_group_slug(_request)
1538 return get_user_group_slug(_request)
1540
1539
1541 def check_permissions(self, user):
1540 def check_permissions(self, user):
1542 perms = user.permissions
1541 perms = user.permissions
1543 group_name = self._get_user_group_name()
1542 group_name = self._get_user_group_name()
1544 try:
1543 try:
1545 user_perms = set([perms['user_groups'][group_name]])
1544 user_perms = set([perms['user_groups'][group_name]])
1546 except KeyError:
1545 except KeyError:
1547 return False
1546 return False
1548
1547
1549 if self.required_perms.intersection(user_perms):
1548 if self.required_perms.intersection(user_perms):
1550 return True
1549 return True
1551 return False
1550 return False
1552
1551
1553
1552
1554 # CHECK FUNCTIONS
1553 # CHECK FUNCTIONS
1555 class PermsFunction(object):
1554 class PermsFunction(object):
1556 """Base function for other check functions"""
1555 """Base function for other check functions"""
1557
1556
1558 def __init__(self, *perms):
1557 def __init__(self, *perms):
1559 self.required_perms = set(perms)
1558 self.required_perms = set(perms)
1560 self.repo_name = None
1559 self.repo_name = None
1561 self.repo_group_name = None
1560 self.repo_group_name = None
1562 self.user_group_name = None
1561 self.user_group_name = None
1563
1562
1564 def __bool__(self):
1563 def __bool__(self):
1565 frame = inspect.currentframe()
1564 frame = inspect.currentframe()
1566 stack_trace = traceback.format_stack(frame)
1565 stack_trace = traceback.format_stack(frame)
1567 log.error('Checking bool value on a class instance of perm '
1566 log.error('Checking bool value on a class instance of perm '
1568 'function is not allowed: %s' % ''.join(stack_trace))
1567 'function is not allowed: %s' % ''.join(stack_trace))
1569 # rather than throwing errors, here we always return False so if by
1568 # rather than throwing errors, here we always return False so if by
1570 # accident someone checks truth for just an instance it will always end
1569 # accident someone checks truth for just an instance it will always end
1571 # up in returning False
1570 # up in returning False
1572 return False
1571 return False
1573 __nonzero__ = __bool__
1572 __nonzero__ = __bool__
1574
1573
1575 def __call__(self, check_location='', user=None):
1574 def __call__(self, check_location='', user=None):
1576 if not user:
1575 if not user:
1577 log.debug('Using user attribute from global request')
1576 log.debug('Using user attribute from global request')
1578 # TODO: remove this someday,put as user as attribute here
1577 # TODO: remove this someday,put as user as attribute here
1579 user = request.user
1578 user = request.user
1580
1579
1581 # init auth user if not already given
1580 # init auth user if not already given
1582 if not isinstance(user, AuthUser):
1581 if not isinstance(user, AuthUser):
1583 log.debug('Wrapping user %s into AuthUser', user)
1582 log.debug('Wrapping user %s into AuthUser', user)
1584 user = AuthUser(user.user_id)
1583 user = AuthUser(user.user_id)
1585
1584
1586 cls_name = self.__class__.__name__
1585 cls_name = self.__class__.__name__
1587 check_scope = self._get_check_scope(cls_name)
1586 check_scope = self._get_check_scope(cls_name)
1588 check_location = check_location or 'unspecified location'
1587 check_location = check_location or 'unspecified location'
1589
1588
1590 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1589 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1591 self.required_perms, user, check_scope, check_location)
1590 self.required_perms, user, check_scope, check_location)
1592 if not user:
1591 if not user:
1593 log.warning('Empty user given for permission check')
1592 log.warning('Empty user given for permission check')
1594 return False
1593 return False
1595
1594
1596 if self.check_permissions(user):
1595 if self.check_permissions(user):
1597 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1596 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1598 check_scope, user, check_location)
1597 check_scope, user, check_location)
1599 return True
1598 return True
1600
1599
1601 else:
1600 else:
1602 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1601 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1603 check_scope, user, check_location)
1602 check_scope, user, check_location)
1604 return False
1603 return False
1605
1604
1606 def _get_request(self):
1605 def _get_request(self):
1607 from pyramid.threadlocal import get_current_request
1606 from pyramid.threadlocal import get_current_request
1608 pyramid_request = get_current_request()
1607 pyramid_request = get_current_request()
1609 if not pyramid_request:
1608 if not pyramid_request:
1610 # return global request of pylons incase pyramid one isn't available
1609 # return global request of pylons incase pyramid one isn't available
1611 return request
1610 return request
1612 return pyramid_request
1611 return pyramid_request
1613
1612
1614 def _get_check_scope(self, cls_name):
1613 def _get_check_scope(self, cls_name):
1615 return {
1614 return {
1616 'HasPermissionAll': 'GLOBAL',
1615 'HasPermissionAll': 'GLOBAL',
1617 'HasPermissionAny': 'GLOBAL',
1616 'HasPermissionAny': 'GLOBAL',
1618 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1617 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1619 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1618 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1620 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1619 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1621 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1620 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1622 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1621 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1623 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1622 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1624 }.get(cls_name, '?:%s' % cls_name)
1623 }.get(cls_name, '?:%s' % cls_name)
1625
1624
1626 def check_permissions(self, user):
1625 def check_permissions(self, user):
1627 """Dummy function for overriding"""
1626 """Dummy function for overriding"""
1628 raise Exception('You have to write this function in child class')
1627 raise Exception('You have to write this function in child class')
1629
1628
1630
1629
1631 class HasPermissionAll(PermsFunction):
1630 class HasPermissionAll(PermsFunction):
1632 def check_permissions(self, user):
1631 def check_permissions(self, user):
1633 perms = user.permissions_with_scope({})
1632 perms = user.permissions_with_scope({})
1634 if self.required_perms.issubset(perms.get('global')):
1633 if self.required_perms.issubset(perms.get('global')):
1635 return True
1634 return True
1636 return False
1635 return False
1637
1636
1638
1637
1639 class HasPermissionAny(PermsFunction):
1638 class HasPermissionAny(PermsFunction):
1640 def check_permissions(self, user):
1639 def check_permissions(self, user):
1641 perms = user.permissions_with_scope({})
1640 perms = user.permissions_with_scope({})
1642 if self.required_perms.intersection(perms.get('global')):
1641 if self.required_perms.intersection(perms.get('global')):
1643 return True
1642 return True
1644 return False
1643 return False
1645
1644
1646
1645
1647 class HasRepoPermissionAll(PermsFunction):
1646 class HasRepoPermissionAll(PermsFunction):
1648 def __call__(self, repo_name=None, check_location='', user=None):
1647 def __call__(self, repo_name=None, check_location='', user=None):
1649 self.repo_name = repo_name
1648 self.repo_name = repo_name
1650 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1649 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1651
1650
1652 def _get_repo_name(self):
1651 def _get_repo_name(self):
1653 if not self.repo_name:
1652 if not self.repo_name:
1654 _request = self._get_request()
1653 _request = self._get_request()
1655 self.repo_name = get_repo_slug(_request)
1654 self.repo_name = get_repo_slug(_request)
1656 return self.repo_name
1655 return self.repo_name
1657
1656
1658 def check_permissions(self, user):
1657 def check_permissions(self, user):
1659 self.repo_name = self._get_repo_name()
1658 self.repo_name = self._get_repo_name()
1660 perms = user.permissions
1659 perms = user.permissions
1661 try:
1660 try:
1662 user_perms = set([perms['repositories'][self.repo_name]])
1661 user_perms = set([perms['repositories'][self.repo_name]])
1663 except KeyError:
1662 except KeyError:
1664 return False
1663 return False
1665 if self.required_perms.issubset(user_perms):
1664 if self.required_perms.issubset(user_perms):
1666 return True
1665 return True
1667 return False
1666 return False
1668
1667
1669
1668
1670 class HasRepoPermissionAny(PermsFunction):
1669 class HasRepoPermissionAny(PermsFunction):
1671 def __call__(self, repo_name=None, check_location='', user=None):
1670 def __call__(self, repo_name=None, check_location='', user=None):
1672 self.repo_name = repo_name
1671 self.repo_name = repo_name
1673 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1672 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1674
1673
1675 def _get_repo_name(self):
1674 def _get_repo_name(self):
1676 if not self.repo_name:
1675 if not self.repo_name:
1677 self.repo_name = get_repo_slug(request)
1676 self.repo_name = get_repo_slug(request)
1678 return self.repo_name
1677 return self.repo_name
1679
1678
1680 def check_permissions(self, user):
1679 def check_permissions(self, user):
1681 self.repo_name = self._get_repo_name()
1680 self.repo_name = self._get_repo_name()
1682 perms = user.permissions
1681 perms = user.permissions
1683 try:
1682 try:
1684 user_perms = set([perms['repositories'][self.repo_name]])
1683 user_perms = set([perms['repositories'][self.repo_name]])
1685 except KeyError:
1684 except KeyError:
1686 return False
1685 return False
1687 if self.required_perms.intersection(user_perms):
1686 if self.required_perms.intersection(user_perms):
1688 return True
1687 return True
1689 return False
1688 return False
1690
1689
1691
1690
1692 class HasRepoGroupPermissionAny(PermsFunction):
1691 class HasRepoGroupPermissionAny(PermsFunction):
1693 def __call__(self, group_name=None, check_location='', user=None):
1692 def __call__(self, group_name=None, check_location='', user=None):
1694 self.repo_group_name = group_name
1693 self.repo_group_name = group_name
1695 return super(HasRepoGroupPermissionAny, self).__call__(
1694 return super(HasRepoGroupPermissionAny, self).__call__(
1696 check_location, user)
1695 check_location, user)
1697
1696
1698 def check_permissions(self, user):
1697 def check_permissions(self, user):
1699 perms = user.permissions
1698 perms = user.permissions
1700 try:
1699 try:
1701 user_perms = set(
1700 user_perms = set(
1702 [perms['repositories_groups'][self.repo_group_name]])
1701 [perms['repositories_groups'][self.repo_group_name]])
1703 except KeyError:
1702 except KeyError:
1704 return False
1703 return False
1705 if self.required_perms.intersection(user_perms):
1704 if self.required_perms.intersection(user_perms):
1706 return True
1705 return True
1707 return False
1706 return False
1708
1707
1709
1708
1710 class HasRepoGroupPermissionAll(PermsFunction):
1709 class HasRepoGroupPermissionAll(PermsFunction):
1711 def __call__(self, group_name=None, check_location='', user=None):
1710 def __call__(self, group_name=None, check_location='', user=None):
1712 self.repo_group_name = group_name
1711 self.repo_group_name = group_name
1713 return super(HasRepoGroupPermissionAll, self).__call__(
1712 return super(HasRepoGroupPermissionAll, self).__call__(
1714 check_location, user)
1713 check_location, user)
1715
1714
1716 def check_permissions(self, user):
1715 def check_permissions(self, user):
1717 perms = user.permissions
1716 perms = user.permissions
1718 try:
1717 try:
1719 user_perms = set(
1718 user_perms = set(
1720 [perms['repositories_groups'][self.repo_group_name]])
1719 [perms['repositories_groups'][self.repo_group_name]])
1721 except KeyError:
1720 except KeyError:
1722 return False
1721 return False
1723 if self.required_perms.issubset(user_perms):
1722 if self.required_perms.issubset(user_perms):
1724 return True
1723 return True
1725 return False
1724 return False
1726
1725
1727
1726
1728 class HasUserGroupPermissionAny(PermsFunction):
1727 class HasUserGroupPermissionAny(PermsFunction):
1729 def __call__(self, user_group_name=None, check_location='', user=None):
1728 def __call__(self, user_group_name=None, check_location='', user=None):
1730 self.user_group_name = user_group_name
1729 self.user_group_name = user_group_name
1731 return super(HasUserGroupPermissionAny, self).__call__(
1730 return super(HasUserGroupPermissionAny, self).__call__(
1732 check_location, user)
1731 check_location, user)
1733
1732
1734 def check_permissions(self, user):
1733 def check_permissions(self, user):
1735 perms = user.permissions
1734 perms = user.permissions
1736 try:
1735 try:
1737 user_perms = set([perms['user_groups'][self.user_group_name]])
1736 user_perms = set([perms['user_groups'][self.user_group_name]])
1738 except KeyError:
1737 except KeyError:
1739 return False
1738 return False
1740 if self.required_perms.intersection(user_perms):
1739 if self.required_perms.intersection(user_perms):
1741 return True
1740 return True
1742 return False
1741 return False
1743
1742
1744
1743
1745 class HasUserGroupPermissionAll(PermsFunction):
1744 class HasUserGroupPermissionAll(PermsFunction):
1746 def __call__(self, user_group_name=None, check_location='', user=None):
1745 def __call__(self, user_group_name=None, check_location='', user=None):
1747 self.user_group_name = user_group_name
1746 self.user_group_name = user_group_name
1748 return super(HasUserGroupPermissionAll, self).__call__(
1747 return super(HasUserGroupPermissionAll, self).__call__(
1749 check_location, user)
1748 check_location, user)
1750
1749
1751 def check_permissions(self, user):
1750 def check_permissions(self, user):
1752 perms = user.permissions
1751 perms = user.permissions
1753 try:
1752 try:
1754 user_perms = set([perms['user_groups'][self.user_group_name]])
1753 user_perms = set([perms['user_groups'][self.user_group_name]])
1755 except KeyError:
1754 except KeyError:
1756 return False
1755 return False
1757 if self.required_perms.issubset(user_perms):
1756 if self.required_perms.issubset(user_perms):
1758 return True
1757 return True
1759 return False
1758 return False
1760
1759
1761
1760
1762 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1761 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1763 class HasPermissionAnyMiddleware(object):
1762 class HasPermissionAnyMiddleware(object):
1764 def __init__(self, *perms):
1763 def __init__(self, *perms):
1765 self.required_perms = set(perms)
1764 self.required_perms = set(perms)
1766
1765
1767 def __call__(self, user, repo_name):
1766 def __call__(self, user, repo_name):
1768 # repo_name MUST be unicode, since we handle keys in permission
1767 # repo_name MUST be unicode, since we handle keys in permission
1769 # dict by unicode
1768 # dict by unicode
1770 repo_name = safe_unicode(repo_name)
1769 repo_name = safe_unicode(repo_name)
1771 user = AuthUser(user.user_id)
1770 user = AuthUser(user.user_id)
1772 log.debug(
1771 log.debug(
1773 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1772 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1774 self.required_perms, user, repo_name)
1773 self.required_perms, user, repo_name)
1775
1774
1776 if self.check_permissions(user, repo_name):
1775 if self.check_permissions(user, repo_name):
1777 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1776 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1778 repo_name, user, 'PermissionMiddleware')
1777 repo_name, user, 'PermissionMiddleware')
1779 return True
1778 return True
1780
1779
1781 else:
1780 else:
1782 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1781 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1783 repo_name, user, 'PermissionMiddleware')
1782 repo_name, user, 'PermissionMiddleware')
1784 return False
1783 return False
1785
1784
1786 def check_permissions(self, user, repo_name):
1785 def check_permissions(self, user, repo_name):
1787 perms = user.permissions_with_scope({'repo_name': repo_name})
1786 perms = user.permissions_with_scope({'repo_name': repo_name})
1788
1787
1789 try:
1788 try:
1790 user_perms = set([perms['repositories'][repo_name]])
1789 user_perms = set([perms['repositories'][repo_name]])
1791 except Exception:
1790 except Exception:
1792 log.exception('Error while accessing user permissions')
1791 log.exception('Error while accessing user permissions')
1793 return False
1792 return False
1794
1793
1795 if self.required_perms.intersection(user_perms):
1794 if self.required_perms.intersection(user_perms):
1796 return True
1795 return True
1797 return False
1796 return False
1798
1797
1799
1798
1800 # SPECIAL VERSION TO HANDLE API AUTH
1799 # SPECIAL VERSION TO HANDLE API AUTH
1801 class _BaseApiPerm(object):
1800 class _BaseApiPerm(object):
1802 def __init__(self, *perms):
1801 def __init__(self, *perms):
1803 self.required_perms = set(perms)
1802 self.required_perms = set(perms)
1804
1803
1805 def __call__(self, check_location=None, user=None, repo_name=None,
1804 def __call__(self, check_location=None, user=None, repo_name=None,
1806 group_name=None, user_group_name=None):
1805 group_name=None, user_group_name=None):
1807 cls_name = self.__class__.__name__
1806 cls_name = self.__class__.__name__
1808 check_scope = 'global:%s' % (self.required_perms,)
1807 check_scope = 'global:%s' % (self.required_perms,)
1809 if repo_name:
1808 if repo_name:
1810 check_scope += ', repo_name:%s' % (repo_name,)
1809 check_scope += ', repo_name:%s' % (repo_name,)
1811
1810
1812 if group_name:
1811 if group_name:
1813 check_scope += ', repo_group_name:%s' % (group_name,)
1812 check_scope += ', repo_group_name:%s' % (group_name,)
1814
1813
1815 if user_group_name:
1814 if user_group_name:
1816 check_scope += ', user_group_name:%s' % (user_group_name,)
1815 check_scope += ', user_group_name:%s' % (user_group_name,)
1817
1816
1818 log.debug(
1817 log.debug(
1819 'checking cls:%s %s %s @ %s'
1818 'checking cls:%s %s %s @ %s'
1820 % (cls_name, self.required_perms, check_scope, check_location))
1819 % (cls_name, self.required_perms, check_scope, check_location))
1821 if not user:
1820 if not user:
1822 log.debug('Empty User passed into arguments')
1821 log.debug('Empty User passed into arguments')
1823 return False
1822 return False
1824
1823
1825 # process user
1824 # process user
1826 if not isinstance(user, AuthUser):
1825 if not isinstance(user, AuthUser):
1827 user = AuthUser(user.user_id)
1826 user = AuthUser(user.user_id)
1828 if not check_location:
1827 if not check_location:
1829 check_location = 'unspecified'
1828 check_location = 'unspecified'
1830 if self.check_permissions(user.permissions, repo_name, group_name,
1829 if self.check_permissions(user.permissions, repo_name, group_name,
1831 user_group_name):
1830 user_group_name):
1832 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1831 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1833 check_scope, user, check_location)
1832 check_scope, user, check_location)
1834 return True
1833 return True
1835
1834
1836 else:
1835 else:
1837 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1836 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1838 check_scope, user, check_location)
1837 check_scope, user, check_location)
1839 return False
1838 return False
1840
1839
1841 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1840 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1842 user_group_name=None):
1841 user_group_name=None):
1843 """
1842 """
1844 implement in child class should return True if permissions are ok,
1843 implement in child class should return True if permissions are ok,
1845 False otherwise
1844 False otherwise
1846
1845
1847 :param perm_defs: dict with permission definitions
1846 :param perm_defs: dict with permission definitions
1848 :param repo_name: repo name
1847 :param repo_name: repo name
1849 """
1848 """
1850 raise NotImplementedError()
1849 raise NotImplementedError()
1851
1850
1852
1851
1853 class HasPermissionAllApi(_BaseApiPerm):
1852 class HasPermissionAllApi(_BaseApiPerm):
1854 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1853 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1855 user_group_name=None):
1854 user_group_name=None):
1856 if self.required_perms.issubset(perm_defs.get('global')):
1855 if self.required_perms.issubset(perm_defs.get('global')):
1857 return True
1856 return True
1858 return False
1857 return False
1859
1858
1860
1859
1861 class HasPermissionAnyApi(_BaseApiPerm):
1860 class HasPermissionAnyApi(_BaseApiPerm):
1862 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1861 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1863 user_group_name=None):
1862 user_group_name=None):
1864 if self.required_perms.intersection(perm_defs.get('global')):
1863 if self.required_perms.intersection(perm_defs.get('global')):
1865 return True
1864 return True
1866 return False
1865 return False
1867
1866
1868
1867
1869 class HasRepoPermissionAllApi(_BaseApiPerm):
1868 class HasRepoPermissionAllApi(_BaseApiPerm):
1870 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1869 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1871 user_group_name=None):
1870 user_group_name=None):
1872 try:
1871 try:
1873 _user_perms = set([perm_defs['repositories'][repo_name]])
1872 _user_perms = set([perm_defs['repositories'][repo_name]])
1874 except KeyError:
1873 except KeyError:
1875 log.warning(traceback.format_exc())
1874 log.warning(traceback.format_exc())
1876 return False
1875 return False
1877 if self.required_perms.issubset(_user_perms):
1876 if self.required_perms.issubset(_user_perms):
1878 return True
1877 return True
1879 return False
1878 return False
1880
1879
1881
1880
1882 class HasRepoPermissionAnyApi(_BaseApiPerm):
1881 class HasRepoPermissionAnyApi(_BaseApiPerm):
1883 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1882 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1884 user_group_name=None):
1883 user_group_name=None):
1885 try:
1884 try:
1886 _user_perms = set([perm_defs['repositories'][repo_name]])
1885 _user_perms = set([perm_defs['repositories'][repo_name]])
1887 except KeyError:
1886 except KeyError:
1888 log.warning(traceback.format_exc())
1887 log.warning(traceback.format_exc())
1889 return False
1888 return False
1890 if self.required_perms.intersection(_user_perms):
1889 if self.required_perms.intersection(_user_perms):
1891 return True
1890 return True
1892 return False
1891 return False
1893
1892
1894
1893
1895 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1894 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1896 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,
1897 user_group_name=None):
1896 user_group_name=None):
1898 try:
1897 try:
1899 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1898 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1900 except KeyError:
1899 except KeyError:
1901 log.warning(traceback.format_exc())
1900 log.warning(traceback.format_exc())
1902 return False
1901 return False
1903 if self.required_perms.intersection(_user_perms):
1902 if self.required_perms.intersection(_user_perms):
1904 return True
1903 return True
1905 return False
1904 return False
1906
1905
1907
1906
1908 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1907 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1909 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1908 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1910 user_group_name=None):
1909 user_group_name=None):
1911 try:
1910 try:
1912 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1911 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1913 except KeyError:
1912 except KeyError:
1914 log.warning(traceback.format_exc())
1913 log.warning(traceback.format_exc())
1915 return False
1914 return False
1916 if self.required_perms.issubset(_user_perms):
1915 if self.required_perms.issubset(_user_perms):
1917 return True
1916 return True
1918 return False
1917 return False
1919
1918
1920
1919
1921 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1920 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1922 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1921 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1923 user_group_name=None):
1922 user_group_name=None):
1924 try:
1923 try:
1925 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1924 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1926 except KeyError:
1925 except KeyError:
1927 log.warning(traceback.format_exc())
1926 log.warning(traceback.format_exc())
1928 return False
1927 return False
1929 if self.required_perms.intersection(_user_perms):
1928 if self.required_perms.intersection(_user_perms):
1930 return True
1929 return True
1931 return False
1930 return False
1932
1931
1933
1932
1934 def check_ip_access(source_ip, allowed_ips=None):
1933 def check_ip_access(source_ip, allowed_ips=None):
1935 """
1934 """
1936 Checks if source_ip is a subnet of any of allowed_ips.
1935 Checks if source_ip is a subnet of any of allowed_ips.
1937
1936
1938 :param source_ip:
1937 :param source_ip:
1939 :param allowed_ips: list of allowed ips together with mask
1938 :param allowed_ips: list of allowed ips together with mask
1940 """
1939 """
1941 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1940 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1942 source_ip_address = ipaddress.ip_address(source_ip)
1941 source_ip_address = ipaddress.ip_address(source_ip)
1943 if isinstance(allowed_ips, (tuple, list, set)):
1942 if isinstance(allowed_ips, (tuple, list, set)):
1944 for ip in allowed_ips:
1943 for ip in allowed_ips:
1945 try:
1944 try:
1946 network_address = ipaddress.ip_network(ip, strict=False)
1945 network_address = ipaddress.ip_network(ip, strict=False)
1947 if source_ip_address in network_address:
1946 if source_ip_address in network_address:
1948 log.debug('IP %s is network %s' %
1947 log.debug('IP %s is network %s' %
1949 (source_ip_address, network_address))
1948 (source_ip_address, network_address))
1950 return True
1949 return True
1951 # for any case we cannot determine the IP, don't crash just
1950 # for any case we cannot determine the IP, don't crash just
1952 # skip it and log as error, we want to say forbidden still when
1951 # skip it and log as error, we want to say forbidden still when
1953 # sending bad IP
1952 # sending bad IP
1954 except Exception:
1953 except Exception:
1955 log.error(traceback.format_exc())
1954 log.error(traceback.format_exc())
1956 continue
1955 continue
1957 return False
1956 return False
1958
1957
1959
1958
1960 def get_cython_compat_decorator(wrapper, func):
1959 def get_cython_compat_decorator(wrapper, func):
1961 """
1960 """
1962 Creates a cython compatible decorator. The previously used
1961 Creates a cython compatible decorator. The previously used
1963 decorator.decorator() function seems to be incompatible with cython.
1962 decorator.decorator() function seems to be incompatible with cython.
1964
1963
1965 :param wrapper: __wrapper method of the decorator class
1964 :param wrapper: __wrapper method of the decorator class
1966 :param func: decorated function
1965 :param func: decorated function
1967 """
1966 """
1968 @wraps(func)
1967 @wraps(func)
1969 def local_wrapper(*args, **kwds):
1968 def local_wrapper(*args, **kwds):
1970 return wrapper(func, *args, **kwds)
1969 return wrapper(func, *args, **kwds)
1971 local_wrapper.__wrapped__ = func
1970 local_wrapper.__wrapped__ = func
1972 return local_wrapper
1971 return local_wrapper
1972
1973
@@ -1,98 +1,108 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2017 RhodeCode GmbH
3 # Copyright (C) 2016-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 import logging
22 import logging
23 from pyramid import httpexceptions
23 from pyramid import httpexceptions
24 from pyramid.httpexceptions import HTTPError, HTTPInternalServerError
24 from pyramid.httpexceptions import (
25 HTTPRedirection, HTTPError, HTTPInternalServerError)
25 from pyramid.threadlocal import get_current_request
26 from pyramid.threadlocal import get_current_request
26
27
27 from rhodecode.lib.exceptions import VCSServerUnavailable
28 from rhodecode.lib.exceptions import VCSServerUnavailable
28 from rhodecode.lib.vcs.exceptions import VCSCommunicationError
29 from rhodecode.lib.vcs.exceptions import VCSCommunicationError
29
30
30
31
31 log = logging.getLogger(__name__)
32 log = logging.getLogger(__name__)
32
33
33
34
34 class PylonsErrorHandlingMiddleware(object):
35 class PylonsErrorHandlingMiddleware(object):
35 """
36 """
36 This middleware is wrapped around the old pylons application to catch
37 This middleware is wrapped around the old pylons application to catch
37 errors and invoke our error handling view to return a proper error page.
38 errors and invoke our error handling view to return a proper error page.
38 """
39 """
39 def __init__(self, app, error_view, reraise=False):
40 def __init__(self, app, error_view, reraise=False):
40 self.app = app
41 self.app = app
41 self.error_view = error_view
42 self.error_view = error_view
42 self._reraise = reraise
43 self._reraise = reraise
43
44
44 def __call__(self, environ, start_response):
45 def __call__(self, environ, start_response):
45 # We need to use the pyramid request here instead of creating a custom
46 # We need to use the pyramid request here instead of creating a custom
46 # instance from the environ because this request maybe passed to the
47 # instance from the environ because this request maybe passed to the
47 # error handler view which is a pyramid view and expects a pyramid
48 # error handler view which is a pyramid view and expects a pyramid
48 # request which has been processed by the pyramid router.
49 # request which has been processed by the pyramid router.
49 request = get_current_request()
50 request = get_current_request()
50
51
51 response = self.handle_request(request)
52 response = self.handle_request(request)
52 return response(environ, start_response)
53 return response(environ, start_response)
53
54
54 def is_http_error(self, response):
55 def is_http_error(self, response):
55 # webob type error responses
56 # webob type error responses
56 return (400 <= response.status_int <= 599)
57 return 400 <= response.status_int <= 599
57
58
58 def reraise(self):
59 def reraise(self):
59 return self._reraise
60 return self._reraise
60
61
61 def handle_request(self, request):
62 def handle_request(self, request):
62 """
63 """
63 Calls the underlying WSGI app (typically the old RhodeCode pylons app)
64 Calls the underlying WSGI app (typically the old RhodeCode pylons app)
64 and returns the response if no error happened. In case of an error it
65 and returns the response if no error happened. In case of an error it
65 invokes the error handling view to return a proper error page as
66 invokes the error handling view to return a proper error page as
66 response.
67 response.
67
68
68 - old webob type exceptions get converted to pyramid exceptions
69 - old webob type exceptions get converted to pyramid exceptions
69 - pyramid exceptions are passed to the error handler view
70 - pyramid exceptions are passed to the error handler view
70 """
71 """
71 try:
72 try:
72 response = request.get_response(self.app)
73 response = request.get_response(self.app)
73 if self.is_http_error(response):
74 if self.is_http_error(response):
74 response = webob_to_pyramid_http_response(response)
75 response = webob_to_pyramid_http_response(response)
75 return self.error_view(response, request)
76 return self.error_view(response, request)
76 except HTTPError as e: # pyramid type exceptions
77 except HTTPRedirection as e:
78 # pyramid type redirection, with status codes in the 300s
79 log.debug('Handling pyramid HTTPRedirection: %s', e)
80 return e
81 except HTTPError as e:
82 # pyramid type exceptions, with status codes in the 400s and 500s
83 log.debug('Handling pyramid HTTPError: %s', e)
77 return self.error_view(e, request)
84 return self.error_view(e, request)
78 except Exception as e:
85 except Exception as e:
86 log.debug('Handling general error: %s', e)
79
87
80 if self.reraise():
88 if self.reraise():
81 raise
89 raise
82
90
83 if isinstance(e, VCSCommunicationError):
91 if isinstance(e, VCSCommunicationError):
84 return self.error_view(VCSServerUnavailable(), request)
92 return self.error_view(VCSServerUnavailable(), request)
85
93
86 return self.error_view(HTTPInternalServerError(), request)
94 return self.error_view(HTTPInternalServerError(), request)
87
95
88 return response
96 return response
89
97
90
98
91 def webob_to_pyramid_http_response(webob_response):
99 def webob_to_pyramid_http_response(webob_response):
100 log.debug('response is webob http error[%s], handling now...',
101 webob_response.status_int)
92 ResponseClass = httpexceptions.status_map[webob_response.status_int]
102 ResponseClass = httpexceptions.status_map[webob_response.status_int]
93 pyramid_response = ResponseClass(webob_response.status)
103 pyramid_response = ResponseClass(webob_response.status)
94 pyramid_response.status = webob_response.status
104 pyramid_response.status = webob_response.status
95 pyramid_response.headers.update(webob_response.headers)
105 pyramid_response.headers.update(webob_response.headers)
96 if pyramid_response.headers['content-type'] == 'text/html':
106 if pyramid_response.headers['content-type'] == 'text/html':
97 pyramid_response.headers['content-type'] = 'text/html; charset=UTF-8'
107 pyramid_response.headers['content-type'] = 'text/html; charset=UTF-8'
98 return pyramid_response
108 return pyramid_response
General Comments 0
You need to be logged in to leave comments. Login now