Debian Codegraph @

pecan/secure.py

raw
1 from functools import wraps
2 from inspect import getmembers, isfunction
3 from webob import exc
4
5 from .compat import is_bound_method as ismethod
6 from .decorators import expose
7 from .util import _cfg, iscontroller
8
9 __all__ = ['unlocked', 'secure', 'SecureController']
10
11
12 class _SecureState(object):
13 def __init__(self, desc, boolean_value):
14 self.description = desc
15 self.boolean_value = boolean_value
16
17 def __repr__(self):
18 return '<SecureState %s>' % self.description
19
20 def __nonzero__(self):
21 return self.boolean_value
22
23 def __bool__(self):
24 return self.__nonzero__()
25
26
27 Any = _SecureState('Any', False)
28 Protected = _SecureState('Protected', True)
29
30
31 # security method decorators
32 def _unlocked_method(func):
33 _cfg(func)['secured'] = Any
34 return func
35
36
37 def _secure_method(check_permissions_func):
38 def wrap(func):
39 cfg = _cfg(func)
40 cfg['secured'] = Protected
41 cfg['check_permissions'] = check_permissions_func
42 return func
43 return wrap
44
45
46 # classes to assist with wrapping attributes
47 class _UnlockedAttribute(object):
48 def __init__(self, obj):
49 self.obj = obj
50
51 @_unlocked_method
52 @expose()
53 def _lookup(self, *remainder):
54 return self.obj, remainder
55
56
57 class _SecuredAttribute(object):
58 def __init__(self, obj, check_permissions):
59 self.obj = obj
60 self.check_permissions = check_permissions
61 self._parent = None
62
63 def _check_permissions(self):
64 if isinstance(self.check_permissions, str):
65 return getattr(self.parent, self.check_permissions)()
66 else:
67 return self.check_permissions()
68
69 def __get_parent(self):
70 return self._parent
71
72 def __set_parent(self, parent):
73 if ismethod(parent):
74 self._parent = parent.__self__
75 else:
76 self._parent = parent
77 parent = property(__get_parent, __set_parent)
78
79 @_secure_method('_check_permissions')
80 @expose()
81 def _lookup(self, *remainder):
82 return self.obj, list(remainder)
83
84
85 # helper for secure decorator
86 def _allowed_check_permissions_types(x):
87 return (
88 ismethod(x) or
89 isfunction(x) or
90 isinstance(x, str)
91 )
92
93
94 # methods that can either decorate functions or wrap classes
95 # these should be the main methods used for securing or unlocking
96 def unlocked(func_or_obj):
97 """
98 This method unlocks method or class attribute on a SecureController. Can
99 be used to decorate or wrap an attribute
100 """
101 if ismethod(func_or_obj) or isfunction(func_or_obj):
102 return _unlocked_method(func_or_obj)
103 else:
104 return _UnlockedAttribute(func_or_obj)
105
106
107 def secure(func_or_obj, check_permissions_for_obj=None):
108 """
109 This method secures a method or class depending on invocation.
110
111 To decorate a method use one argument:
112 @secure(<check_permissions_method>)
113
114 To secure a class, invoke with two arguments:
115 secure(<obj instance>, <check_permissions_method>)
116 """
117 if _allowed_check_permissions_types(func_or_obj):
118 return _secure_method(func_or_obj)
119 else:
120 if not _allowed_check_permissions_types(check_permissions_for_obj):
121 msg = "When securing an object, secure() requires the " + \
122 "second argument to be method"
123 raise TypeError(msg)
124 return _SecuredAttribute(func_or_obj, check_permissions_for_obj)
125
126
127 class SecureControllerMeta(type):
128 """
129 Used to apply security to a controller.
130 Implementations of SecureController should extend the
131 `check_permissions` method to return a True or False
132 value (depending on whether or not the user has permissions
133 to the controller).
134 """
135 def __init__(cls, name, bases, dict_):
136 cls._pecan = dict(
137 secured=Protected,
138 check_permissions=cls.check_permissions,
139 unlocked=[]
140 )
141
142 for name, value in getmembers(cls)[:]:
143 if isfunction(value):
144 if iscontroller(value) and value._pecan.get(
145 'secured'
146 ) is None:
147 # Wrap the function so that the security context is
148 # local to this class definition. This works around
149 # the fact that unbound method attributes are shared
150 # across classes with the same bases.
151 wrapped = _make_wrapper(value)
152 wrapped._pecan['secured'] = Protected
153 wrapped._pecan['check_permissions'] = \
154 cls.check_permissions
155 setattr(cls, name, wrapped)
156 elif hasattr(value, '__class__'):
157 if name.startswith('__') and name.endswith('__'):
158 continue
159 if isinstance(value, _UnlockedAttribute):
160 # mark it as unlocked and remove wrapper
161 cls._pecan['unlocked'].append(value.obj)
162 setattr(cls, name, value.obj)
163 elif isinstance(value, _SecuredAttribute):
164 # The user has specified a different check_permissions
165 # than the class level version. As far as the class
166 # is concerned, this method is unlocked because
167 # it is using a check_permissions function embedded in
168 # the _SecuredAttribute wrapper
169 cls._pecan['unlocked'].append(value)
170
171
172 class SecureControllerBase(object):
173
174 @classmethod
175 def check_permissions(cls):
176 """
177 Returns `True` or `False` to grant access. Implemented in subclasses
178 of :class:`SecureController`.
179 """
180 return False
181
182
183 SecureController = SecureControllerMeta(
184 'SecureController',
185 (SecureControllerBase,),
186 {'__doc__': SecureControllerMeta.__doc__}
187 )
188
189
190 def _make_wrapper(f):
191 """return a wrapped function with a copy of the _pecan context"""
192 @wraps(f)
193 def wrapper(*args, **kwargs):
194 return f(*args, **kwargs)
195 wrapper._pecan = f._pecan.copy()
196 return wrapper
197
198
199 # methods to evaluate security during routing
200 def handle_security(controller, im_self=None):
201 """ Checks the security of a controller. """
202 if controller._pecan.get('secured', False):
203 check_permissions = controller._pecan['check_permissions']
204
205 if isinstance(check_permissions, str):
206 check_permissions = getattr(
207 im_self or controller.__self__,
208 check_permissions
209 )
210
211 if not check_permissions():
212 raise exc.HTTPUnauthorized
213
214
215 def cross_boundary(prev_obj, obj):
216 """ Check permissions as we move between object instances. """
217 if prev_obj is None:
218 return
219
220 if isinstance(obj, _SecuredAttribute):
221 # a secure attribute can live in unsecure class so we have to set
222 # while we walk the route
223 obj.parent = prev_obj
224
225 if hasattr(prev_obj, '_pecan'):
226 if obj not in prev_obj._pecan.get('unlocked', []):
227 handle_security(prev_obj)