Tres Seaver
2017-06-05 f70edbef15c8065c4f72d617012dea11f62cd1bb
commit | author | age
0184b5 1 from zope.deprecation import deprecated
6b6e43 2 from zope.interface import providedBy
4ac0ff 3
0c1c39 4 from pyramid.interfaces import (
CM 5     IAuthenticationPolicy,
6     IAuthorizationPolicy,
7     ISecuredView,
4b552e 8     IView,
0c1c39 9     IViewClassifier,
CM 10     )
d75fe7 11
475532 12 from pyramid.compat import map_
b60bdb 13 from pyramid.threadlocal import get_current_registry
2466f6 14
CM 15 Everyone = 'system.Everyone'
16 Authenticated = 'system.Authenticated'
17 Allow = 'Allow'
18 Deny = 'Deny'
226b49 19
7a2b72 20 _marker = object()
MM 21
226b49 22 class AllPermissionsList(object):
CM 23     """ Stand in 'permission list' to represent all permissions """
f70edb 24
226b49 25     def __iter__(self):
f70edb 26         return iter(())
TS 27
226b49 28     def __contains__(self, other):
CM 29         return True
f70edb 30
226b49 31     def __eq__(self, other):
CM 32         return isinstance(other, self.__class__)
33
34 ALL_PERMISSIONS = AllPermissionsList()
35 DENY_ALL = (Deny, Everyone, ALL_PERMISSIONS)
2466f6 36
feceff 37 NO_PERMISSION_REQUIRED = '__no_permission_required__'
MM 38
3c2f95 39 def _get_registry(request):
MR 40     try:
41         reg = request.registry
42     except AttributeError:
43         reg = get_current_registry() # b/c
44     return reg
45
0dcd56 46 def _get_authentication_policy(request):
CM 47     registry = _get_registry(request)
48     return registry.queryUtility(IAuthenticationPolicy)
49
4ac0ff 50 def has_permission(permission, context, request):
0184b5 51     """
2033ee 52     A function that calls :meth:`pyramid.request.Request.has_permission`
SP 53     and returns its result.
0184b5 54     
CM 55     .. deprecated:: 1.5
2033ee 56         Use :meth:`pyramid.request.Request.has_permission` instead.
4ac0ff 57
0184b5 58     .. versionchanged:: 1.5a3
2033ee 59         If context is None, then attempt to use the context attribute of self;
SP 60         if not set, then the AttributeError is propagated.
3c2f95 61     """    
MR 62     return request.has_permission(permission, context)
a1a9fb 63
0184b5 64 deprecated(
CM 65     'has_permission',
66     'As of Pyramid 1.5 the "pyramid.security.has_permission" API is now '
71ad60 67     'deprecated.  It will be removed in Pyramid 1.8.  Use the '
0184b5 68     '"has_permission" method of the Pyramid request instead.'
CM 69     )
a1a9fb 70
0184b5 71
CM 72 def authenticated_userid(request):
73     """
74     A function that returns the value of the property
75     :attr:`pyramid.request.Request.authenticated_userid`.
76     
77     .. deprecated:: 1.5
78        Use :attr:`pyramid.request.Request.authenticated_userid` instead.
3c2f95 79     """        
MR 80     return request.authenticated_userid
b54cdb 81
0184b5 82 deprecated(
CM 83     'authenticated_userid',
84     'As of Pyramid 1.5 the "pyramid.security.authenticated_userid" API is now '
71ad60 85     'deprecated.  It will be removed in Pyramid 1.8.  Use the '
0184b5 86     '"authenticated_userid" attribute of the Pyramid request instead.'
CM 87     )
2526d8 88
0184b5 89 def unauthenticated_userid(request):
CM 90     """ 
91     A function that returns the value of the property
92     :attr:`pyramid.request.Request.unauthenticated_userid`.
93     
94     .. deprecated:: 1.5
2033ee 95         Use :attr:`pyramid.request.Request.unauthenticated_userid` instead.
3c2f95 96     """        
MR 97     return request.unauthenticated_userid
2526d8 98
0184b5 99 deprecated(
CM 100     'unauthenticated_userid',
101     'As of Pyramid 1.5 the "pyramid.security.unauthenticated_userid" API is '
71ad60 102     'now deprecated.  It will be removed in Pyramid 1.8.  Use the '
0184b5 103     '"unauthenticated_userid" attribute of the Pyramid request instead.'
CM 104     )
a1a9fb 105
0184b5 106 def effective_principals(request):
CM 107     """
108     A function that returns the value of the property
109     :attr:`pyramid.request.Request.effective_principals`.
110     
111     .. deprecated:: 1.5
2033ee 112         Use :attr:`pyramid.request.Request.effective_principals` instead.
3c2f95 113     """            
MR 114     return request.effective_principals
115
0184b5 116 deprecated(
CM 117     'effective_principals',
118     'As of Pyramid 1.5 the "pyramid.security.effective_principals" API is '
71ad60 119     'now deprecated.  It will be removed in Pyramid 1.8.  Use the '
0184b5 120     '"effective_principals" attribute of the Pyramid request instead.'
CM 121     )
3c2f95 122
7a2b72 123 def remember(request, userid=_marker, **kw):
0184b5 124     """
0dcd56 125     Returns a sequence of header tuples (e.g. ``[('Set-Cookie', 'foo=abc')]``)
CM 126     on this request's response.
0184b5 127     These headers are suitable for 'remembering' a set of credentials
c7afe4 128     implied by the data passed as ``userid`` and ``*kw`` using the
0184b5 129     current :term:`authentication policy`.  Common usage might look
CM 130     like so within the body of a view function (``response`` is
131     assumed to be a :term:`WebOb` -style :term:`response` object
06ecaf 132     computed previously by the view code):
0184b5 133
06ecaf 134     .. code-block:: python
0184b5 135
CM 136        from pyramid.security import remember
137        headers = remember(request, 'chrism', password='123', max_age='86400')
0dcd56 138        response = request.response
0184b5 139        response.headerlist.extend(headers)
CM 140        return response
141
142     If no :term:`authentication policy` is in use, this function will
072a2c 143     always return an empty sequence. If used, the composition and
0184b5 144     meaning of ``**kw`` must be agreed upon by the calling code and
CM 145     the effective authentication policy.
7a2b72 146     
MM 147     .. deprecated:: 1.6
148         Renamed the ``principal`` argument to ``userid`` to clarify its
149         purpose.
0184b5 150     """
7a2b72 151     if userid is _marker:
MM 152         principal = kw.pop('principal', _marker)
153         if principal is _marker:
154             raise TypeError(
155                 'remember() missing 1 required positional argument: '
156                 '\'userid\'')
157         else:
158             deprecated(
159                 'principal',
160                 'The "principal" argument was deprecated in Pyramid 1.6. '
161                 'It will be removed in Pyramid 1.9. Use the "userid" '
162                 'argument instead.')
163             userid = principal
0dcd56 164     policy = _get_authentication_policy(request)
CM 165     if policy is None:
166         return []
c7afe4 167     return policy.remember(request, userid, **kw)
3c2f95 168
0184b5 169 def forget(request):
CM 170     """
171     Return a sequence of header tuples (e.g. ``[('Set-Cookie',
172     'foo=abc')]``) suitable for 'forgetting' the set of credentials
173     possessed by the currently authenticated user.  A common usage
174     might look like so within the body of a view function
175     (``response`` is assumed to be an :term:`WebOb` -style
620bde 176     :term:`response` object computed previously by the view code):
0184b5 177
620bde 178     .. code-block:: python
MM 179
180        from pyramid.security import forget
181        headers = forget(request)
182        response.headerlist.extend(headers)
183        return response
0184b5 184
CM 185     If no :term:`authentication policy` is in use, this function will
186     always return an empty sequence.
3c2f95 187     """            
0dcd56 188     policy = _get_authentication_policy(request)
CM 189     if policy is None:
190         return []
191     return policy.forget(request)
64ea2e 192
CM 193 def principals_allowed_by_permission(context, permission):
3e2f12 194     """ Provided a ``context`` (a resource object), and a ``permission``
8b1f6e 195     (a string or unicode object), if a :term:`authorization policy` is
CM 196     in effect, return a sequence of :term:`principal` ids that possess
197     the permission in the ``context``.  If no authorization policy is
198     in effect, this will return a sequence with the single value
c81aad 199     :mod:`pyramid.security.Everyone` (the special principal
c6895b 200     identifier representing all principals).
a1a9fb 201
012b97 202     .. note::
M 203
204        even if an :term:`authorization policy` is in effect,
8b1f6e 205        some (exotic) authorization policies may not implement the
CM 206        required machinery for this function; those will cause a
c6895b 207        :exc:`NotImplementedError` exception to be raised when this
a1a9fb 208        function is invoked.
CM 209     """
41723e 210     reg = get_current_registry()
CM 211     policy = reg.queryUtility(IAuthorizationPolicy)
64ea2e 212     if policy is None:
CM 213         return [Everyone]
214     return policy.principals_allowed_by_permission(context, permission)
b54cdb 215
a1a9fb 216 def view_execution_permitted(context, request, name=''):
CM 217     """ If the view specified by ``context`` and ``name`` is protected
8b1f6e 218     by a :term:`permission`, check the permission associated with the
CM 219     view using the effective authentication/authorization policies and
220     the ``request``.  Return a boolean result.  If no
221     :term:`authorization policy` is in effect, or if the view is not
6e9640 222     protected by a permission, return ``True``. If no view can view found,
MM 223     an exception will be raised.
224
225     .. versionchanged:: 1.4a4
226        An exception is raised if no view is found.
227
228     """
3c2f95 229     reg = _get_registry(request)
475532 230     provides = [IViewClassifier] + map_(providedBy, (request, context))
2a842e 231     # XXX not sure what to do here about using _find_views or analogue;
CM 232     # for now let's just keep it as-is
41723e 233     view = reg.adapters.lookup(provides, ISecuredView, name=name)
d66bfb 234     if view is None:
4b552e 235         view = reg.adapters.lookup(provides, IView, name=name)
MM 236         if view is None:
237             raise TypeError('No registered view satisfies the constraints. '
238                             'It would not make sense to claim that this view '
239                             '"is" or "is not" permitted.')
a1a9fb 240         return Allowed(
CM 241             'Allowed: view name %r in context %r (no permission defined)' %
242             (name, context))
d66bfb 243     return view.__permitted__(context, request)
157721 244
012b97 245
7292d4 246 class PermitsResult(int):
CM 247     def __new__(cls, s, *args):
248         inst = int.__new__(cls, cls.boolval)
249         inst.s = s
250         inst.args = args
251         return inst
012b97 252
7292d4 253     @property
CM 254     def msg(self):
255         return self.s % self.args
256
2466f6 257     def __str__(self):
17ce57 258         return self.msg
CM 259
260     def __repr__(self):
261         return '<%s instance at %s with msg %r>' % (self.__class__.__name__,
262                                                     id(self),
263                                                     self.msg)
2466f6 264
CM 265 class Denied(PermitsResult):
a1a9fb 266     """ An instance of ``Denied`` is returned when a security-related
fd5ae9 267     API or other :app:`Pyramid` code denies an action unrelated to
c6895b 268     an ACL check.  It evaluates equal to all boolean false types.  It
CM 269     has an attribute named ``msg`` describing the circumstances for
270     the deny."""
7292d4 271     boolval = 0
2466f6 272
CM 273 class Allowed(PermitsResult):
a1a9fb 274     """ An instance of ``Allowed`` is returned when a security-related
fd5ae9 275     API or other :app:`Pyramid` code allows an action unrelated to
c6895b 276     an ACL check.  It evaluates equal to all boolean true types.  It
CM 277     has an attribute named ``msg`` describing the circumstances for
278     the allow."""
7292d4 279     boolval = 1
f66290 280
7292d4 281 class ACLPermitsResult(int):
CM 282     def __new__(cls, ace, acl, permission, principals, context):
283         inst = int.__new__(cls, cls.boolval)
284         inst.permission = permission
285         inst.ace = ace
286         inst.acl = acl
287         inst.principals = principals
288         inst.context = context
289         return inst
f66290 290
CM 291     @property
292     def msg(self):
293         s = ('%s permission %r via ACE %r in ACL %r on context %r for '
294              'principals %r')
295         return s % (self.__class__.__name__,
296                     self.permission,
297                     self.ace,
298                     self.acl,
299                     self.context,
300                     self.principals)
17ce57 301
7292d4 302     def __str__(self):
CM 303         return self.msg
304
305     def __repr__(self):
306         return '<%s instance at %s with msg %r>' % (self.__class__.__name__,
307                                                     id(self),
308                                                     self.msg)
309
310 class ACLDenied(ACLPermitsResult):
b32552 311     """ An instance of ``ACLDenied`` represents that a security check made
CM 312     explicitly against ACL was denied.  It evaluates equal to all boolean
313     false types.  It also has the following attributes: ``acl``, ``ace``,
314     ``permission``, ``principals``, and ``context``.  These attributes
315     indicate the security values involved in the request.  Its __str__ method
316     prints a summary of these attributes for debugging purposes.  The same
317     summary is available as the ``msg`` attribute."""
7292d4 318     boolval = 0
17ce57 319
7292d4 320 class ACLAllowed(ACLPermitsResult):
b32552 321     """ An instance of ``ACLAllowed`` represents that a security check made
CM 322     explicitly against ACL was allowed.  It evaluates equal to all boolean
323     true types.  It also has the following attributes: ``acl``, ``ace``,
324     ``permission``, ``principals``, and ``context``.  These attributes
325     indicate the security values involved in the request.  Its __str__ method
326     prints a summary of these attributes for debugging purposes.  The same
327     summary is available as the ``msg`` attribute."""
7292d4 328     boolval = 1
7d1da8 329
3c2f95 330 class AuthenticationAPIMixin(object):
MR 331
332     def _get_authentication_policy(self):
333         reg = _get_registry(self)
334         return reg.queryUtility(IAuthenticationPolicy)
335
336     @property
337     def authenticated_userid(self):
338         """ Return the userid of the currently authenticated user or
339         ``None`` if there is no :term:`authentication policy` in effect or
0184b5 340         there is no currently authenticated user.
CM 341
342         .. versionadded:: 1.5
343         """
3c2f95 344         policy = self._get_authentication_policy()
MR 345         if policy is None:
346             return None
347         return policy.authenticated_userid(self)
348
349     @property
350     def unauthenticated_userid(self):
351         """ Return an object which represents the *claimed* (not verified) user
352         id of the credentials present in the request. ``None`` if there is no
353         :term:`authentication policy` in effect or there is no user data
354         associated with the current request.  This differs from
e18385 355         :attr:`~pyramid.request.Request.authenticated_userid`, because the
CM 356         effective authentication policy will not ensure that a record
357         associated with the userid exists in persistent storage.
0184b5 358
CM 359         .. versionadded:: 1.5
360         """
3c2f95 361         policy = self._get_authentication_policy()
MR 362         if policy is None:
363             return None
364         return policy.unauthenticated_userid(self)
365
366     @property
367     def effective_principals(self):
368         """ Return the list of 'effective' :term:`principal` identifiers
82ec99 369         for the ``request``. If no :term:`authentication policy` is in effect,
MM 370         this will return a one-element list containing the
371         :data:`pyramid.security.Everyone` principal.
0184b5 372
CM 373         .. versionadded:: 1.5
374         """
3c2f95 375         policy = self._get_authentication_policy()
MR 376         if policy is None:
377             return [Everyone]
378         return policy.effective_principals(self)
dd1523 379
3c2f95 380 class AuthorizationAPIMixin(object):
MR 381
382     def has_permission(self, permission, context=None):
e0d1af 383         """ Given a permission and an optional context, returns an instance of
CM 384         :data:`pyramid.security.Allowed` if the permission is granted to this
385         request with the provided context, or the context already associated
386         with the request.  Otherwise, returns an instance of
387         :data:`pyramid.security.Denied`.  This method delegates to the current
388         authentication and authorization policies.  Returns
389         :data:`pyramid.security.Allowed` unconditionally if no authentication
390         policy has been registered for this request.  If ``context`` is not
391         supplied or is supplied as ``None``, the context used is the
392         ``request.context`` attribute.
3c2f95 393
MR 394         :param permission: Does this request have the given permission?
395         :type permission: unicode, str
c12603 396         :param context: A resource object or ``None``
3c2f95 397         :type context: object
MR 398         :returns: `pyramid.security.PermitsResult`
0184b5 399
CM 400         .. versionadded:: 1.5
401
3c2f95 402         """
MR 403         if context is None:
404             context = self.context
405         reg = _get_registry(self)
406         authn_policy = reg.queryUtility(IAuthenticationPolicy)
407         if authn_policy is None:
408             return Allowed('No authentication policy in use.')
409         authz_policy = reg.queryUtility(IAuthorizationPolicy)
410         if authz_policy is None:
411             raise ValueError('Authentication policy registered without '
412                              'authorization policy') # should never happen
413         principals = authn_policy.effective_principals(self)
414         return authz_policy.permits(context, principals, permission)