Security

Pyramid provides an optional, declarative security system. The system determines the identity of the current user (authentication) and whether or not the user has access to certain resources (authorization).

The Pyramid security system can prevent a view from being invoked based on the security policy. Before a view is invoked, the authorization system can use the credentials in the request along with the context resource to determine if access will be allowed. Here's how it works at a high level:

  • A user may or may not have previously visited the application and supplied authentication credentials, including a userid. If so, the application may have called pyramid.security.remember() to remember these.

  • A request is generated when a user visits the application.

  • Based on the request, a context resource is located through resource location. A context is located differently depending on whether the application uses traversal or URL dispatch, but a context is ultimately found in either case. See the URL Dispatch chapter for more information.

  • A view callable is located by view lookup using the context as well as other attributes of the request.

  • If a security policy is in effect and the view configuration associated with the view callable that was found has a permission associated with it, the policy is passed request, the context, and the permission associated with the view; it will allow or deny access.

  • If the security policy allows access, the view callable is invoked.

  • If the security policy denies access, the view callable is not invoked. Instead the forbidden view is invoked.

The security system is enabled by modifying your application to include a security policy. Pyramid comes with a variety of helpers to assist in the creation of this policy.

Writing a Security Policy

Pyramid does not enable any security policy by default. All views are accessible by completely anonymous users. In order to begin protecting views from execution based on security settings, you need to write a security policy.

Security policies are simple classes implementing pyramid.interfaces.ISecurityPolicy. A simple security policy might look like the following:

 1from pyramid.security import Allowed, Denied
 2
 3class SessionSecurityPolicy:
 4    def identity(self, request):
 5        """ Return app-specific user object. """
 6        userid = request.session.get('userid')
 7        if userid is None:
 8            return None
 9        return load_identity_from_db(request, userid)
10
11    def authenticated_userid(self, request):
12        """ Return a string ID for the user. """
13        identity = self.identity(request)
14        if identity is None:
15            return None
16        return string(identity.id)
17
18    def permits(self, request, context, permission):
19        """ Allow access to everything if signed in. """
20        identity = self.identity(request)
21        if identity is not None:
22            return Allowed('User is signed in.')
23        else:
24            return Denied('User is not signed in.')
25
26    def remember(request, userid, **kw):
27        request.session['userid'] = userid
28        return []
29
30    def forget(request, **kw):
31        del request.session['userid']
32        return []

Use the set_security_policy() method of the Configurator to enforce the security policy on your application.

See also

For more information on implementing the permits method, see Allowing and Denying Access With a Security Policy.

Writing a Security Policy Using Helpers

To assist in writing common security policies, Pyramid provides several helpers. The following authentication helpers assist with implementing identity, remember, and forget.

Use Case

Helper

Store the userid in the session.

pyramid.authentication.SessionAuthenticationHelper

Store the userid with an "auth ticket" cookie.

pyramid.authentication.AuthTktCookieHelper

Retrieve user credentials using HTTP Basic Auth.

Use pyramid.authentication.extract_http_basic_credentials() to retrieve credentials.

Retrieve the userid from REMOTE_USER in the WSGI environment.

REMOTE_USER can be accessed with request.environ.get('REMOTE_USER').

For example, our above security policy can leverage these helpers like so:

 1from pyramid.security import Allowed, Denied
 2from pyramid.authentication import SessionAuthenticationHelper
 3
 4class SessionSecurityPolicy:
 5    def __init__(self):
 6        self.helper = SessionAuthenticationHelper()
 7
 8    def identity(self, request):
 9        """ Return app-specific user object. """
10        userid = self.helper.authenticated_userid(request)
11        if userid is None:
12            return None
13        return load_identity_from_db(request, userid)
14
15    def authenticated_userid(self, request):
16        """ Return a string ID for the user. """
17        identity = self.identity(request)
18        if identity is None:
19            return None
20        return str(identity.id)
21
22    def permits(self, request, context, permission):
23        """ Allow access to everything if signed in. """
24        identity = self.identity(request)
25        if identity is not None:
26            return Allowed('User is signed in.')
27        else:
28            return Denied('User is not signed in.')
29
30    def remember(request, userid, **kw):
31        return self.helper.remember(request, userid, **kw)
32
33    def forget(request, **kw):
34        return self.helper.forget(request, **kw)

Helpers are intended to be used with application-specific code. Notice how the above code takes the userid from the helper and uses it to load the identity from the database. authenticated_userid pulls the userid from the identity in order to guarantee that the user ID stored in the session exists in the database ("authenticated").

Protecting Views with Permissions

To protect a view callable from invocation based on a user's security settings when a particular type of resource becomes the context, you must pass a permission to view configuration. Permissions are usually just strings, and they have no required composition: you can name permissions whatever you like.

For example, the following view declaration protects the view named add_entry.html when the context resource is of type Blog with the add permission using the pyramid.config.Configurator.add_view() API:

1# config is an instance of pyramid.config.Configurator
2
3config.add_view('mypackage.views.blog_entry_add_view',
4                name='add_entry.html',
5                context='mypackage.resources.Blog',
6                permission='add')

The equivalent view registration including the add permission name may be performed via the @view_config decorator:

1from pyramid.view import view_config
2from resources import Blog
3
4@view_config(context=Blog, name='add_entry.html', permission='add')
5def blog_entry_add_view(request):
6    """ Add blog entry code goes here """
7    pass

As a result of any of these various view configuration statements, if an security policy is in place when the view callable is found during normal application operations, the security policy will be queried to see if the requesting user is allowed the add permission within the current context. If the policy allows access, blog_entry_add_view will be invoked. If not, the Forbidden view will be invoked.

Allowing and Denying Access With a Security Policy

To determine whether access is allowed to a view with an attached permission, Pyramid calls the permits method of the security policy. permits should return an instance of pyramid.security.Allowed or pyramid.security.Denied. Both classes accept a string as an argument, which should detail why access was allowed or denied.

A simple permits implementation that grants access based on a user role might look like so:

 1from pyramid.security import Allowed, Denied
 2
 3class SecurityPolicy:
 4    def permits(self, request, context, permission):
 5        identity = self.identity(request)
 6
 7        if identity is None:
 8            return Denied('User is not signed in.')
 9        if identity.role == 'admin':
10            allowed = ['read', 'write', 'delete']
11        elif identity.role == 'editor':
12            allowed = ['read', 'write']
13        else:
14            allowed = ['read']
15
16        if permission in allowed:
17            return Allowed(
18                'Access granted for user %s with role %s.',
19                identity,
20                identity.role,
21            )
22        else:
23            return Denied(
24                'Access denied for user %s with role %s.',
25                identity,
26                identity.role,
27            )

Setting a Default Permission

If a permission is not supplied to a view configuration, the registered view will always be executable by entirely anonymous users: any security policy in effect is ignored.

In support of making it easier to configure applications which are "secure by default", Pyramid allows you to configure a default permission. If supplied, the default permission is used as the permission string to all view registrations which don't otherwise name a permission argument.

The pyramid.config.Configurator.set_default_permission() method supports configuring a default permission for an application.

When a default permission is registered:

  • If a view configuration names an explicit permission, the default permission is ignored for that view registration, and the view-configuration-named permission is used.

  • If a view configuration names the permission pyramid.security.NO_PERMISSION_REQUIRED, the default permission is ignored, and the view is registered without a permission (making it available to all callers regardless of their credentials).

Warning

When you register a default permission, all views (even exception view views) are protected by a permission. For all views which are truly meant to be anonymously accessible, you will need to associate the view's configuration with the pyramid.security.NO_PERMISSION_REQUIRED permission.

Implementing ACL Authorization

A common way to implement authorization is using an ACL. An ACL is a context-specific list of access control entries, which allow or deny access to permissions based on a user's principals.

Pyramid provides pyramid.authorization.ACLHelper to assist with an ACL-based implementation of permits. Application-specific code should construct a list of principals for the user and call pyramid.authorization.ACLHelper.permits(), which will return an pyramid.authorization.ACLAllowed or pyramid.authorization.ACLDenied object. An implementation might look like this:

 1from pyramid.authorization import ACLHelper, Everyone, Authenticated
 2
 3class SecurityPolicy:
 4    def permits(self, request, context, permission):
 5        principals = [Everyone]
 6        if identity is not None:
 7            principals.append(Authenticated)
 8            principals.append('user:' + identity.id)
 9            principals.append('group:' + identity.group)
10        return ACLHelper().permits(context, principals, permission)

To associate an ACL with a resource, add an __acl__ attribute to the resource object. This attribute can be defined on the resource instance if you need instance-level security, or it can be defined on the resource class if you just need type-level security.

For example, an ACL might be attached to the resource for a blog via its class:

1from pyramid.authorization import Allow
2from pyramid.authorization import Everyone
3
4class Blog(object):
5    __acl__ = [
6        (Allow, Everyone, 'view'),
7        (Allow, 'group:editors', 'add'),
8        (Allow, 'group:editors', 'edit'),
9    ]

Or, if your resources are persistent, an ACL might be specified via the __acl__ attribute of an instance of a resource:

 1from pyramid.authorization import Allow
 2from pyramid.authorization import Everyone
 3
 4class Blog(object):
 5    pass
 6
 7blog = Blog()
 8
 9blog.__acl__ = [
10    (Allow, Everyone, 'view'),
11    (Allow, 'group:editors', 'add'),
12    (Allow, 'group:editors', 'edit'),
13]

Whether an ACL is attached to a resource's class or an instance of the resource itself, the effect is the same. It is useful to decorate individual resource instances with an ACL (as opposed to just decorating their class) in applications such as content management systems where fine-grained access is required on an object-by-object basis.

Dynamic ACLs are also possible by turning the ACL into a callable on the resource. This may allow the ACL to dynamically generate rules based on properties of the instance.

 1from pyramid.authorization import Allow
 2from pyramid.authorization import Everyone
 3
 4class Blog(object):
 5    def __acl__(self):
 6        return [
 7            (Allow, Everyone, 'view'),
 8            (Allow, self.owner, 'edit'),
 9            (Allow, 'group:editors', 'edit'),
10        ]
11
12    def __init__(self, owner):
13        self.owner = owner

Warning

Writing __acl__ as properties is discouraged because an AttributeError occurring in fget or fset will be silently dismissed (this is consistent with Python getattr and hasattr behaviors). For dynamic ACLs, simply use callables, as documented above.

Elements of an ACL

Here's an example ACL:

1from pyramid.authorization import Allow
2from pyramid.authorization import Everyone
3
4__acl__ = [
5    (Allow, Everyone, 'view'),
6    (Allow, 'group:editors', 'add'),
7    (Allow, 'group:editors', 'edit'),
8]

The example ACL indicates that the pyramid.authorization.Everyone principal—a special system-defined principal indicating, literally, everyone—is allowed to view the blog, and the group:editors principal is allowed to add to and edit the blog.

Each element of an ACL is an ACE, or access control entry. For example, in the above code block, there are three ACEs: (Allow, Everyone, 'view'), (Allow, 'group:editors', 'add'), and (Allow, 'group:editors', 'edit').

The first element of any ACE is either pyramid.authorization.Allow, or pyramid.authorization.Deny, representing the action to take when the ACE matches. The second element is a principal. The third argument is a permission or sequence of permission names.

A principal is usually a user id, however it also may be a group id if your authentication system provides group information.

Each ACE in an ACL is processed by the ACL helper in the order dictated by the ACL. So if you have an ACL like this:

1from pyramid.authorization import Allow
2from pyramid.authorization import Deny
3from pyramid.authorization import Everyone
4
5__acl__ = [
6    (Allow, Everyone, 'view'),
7    (Deny, Everyone, 'view'),
8]

The ACL helper will allow everyone the view permission, even though later in the ACL you have an ACE that denies everyone the view permission. On the other hand, if you have an ACL like this:

1from pyramid.authorization import Everyone
2from pyramid.authorization import Allow
3from pyramid.authorization import Deny
4
5__acl__ = [
6    (Deny, Everyone, 'view'),
7    (Allow, Everyone, 'view'),
8]

The ACL helper will deny everyone the view permission, even though later in the ACL, there is an ACE that allows everyone.

The third argument in an ACE can also be a sequence of permission names instead of a single permission name. So instead of creating multiple ACEs representing a number of different permission grants to a single group:editors group, we can collapse this into a single ACE, as below.

1from pyramid.authorization import Allow
2from pyramid.authorization import Everyone
3
4__acl__ = [
5    (Allow, Everyone, 'view'),
6    (Allow, 'group:editors', ('add', 'edit')),
7]

Special Principal Names

Special principal names exist in the pyramid.authorization module. They can be imported for use in your own code to populate ACLs, e.g., pyramid.authorization.Everyone.

pyramid.authorization.Everyone

Literally, everyone, no matter what. This object is actually a string under the hood (system.Everyone). Every user is the principal named "Everyone" during every request, even if a security policy is not in use.

pyramid.authorization.Authenticated

Any user with credentials as determined by the current security policy. You might think of it as any user that is "logged in". This object is actually a string under the hood (system.Authenticated).

Special Permissions

Special permission names exist in the pyramid.authorization module. These can be imported for use in ACLs.

pyramid.authorization.ALL_PERMISSIONS

An object representing, literally, all permissions. Useful in an ACL like so: (Allow, 'fred', ALL_PERMISSIONS). The ALL_PERMISSIONS object is actually a stand-in object that has a __contains__ method that always returns True, which, for all known authorization policies, has the effect of indicating that a given principal has any permission asked for by the system.

Special ACEs

A convenience ACE is defined representing a deny to everyone of all permissions in pyramid.authorization.DENY_ALL. This ACE is often used as the last ACE of an ACL to explicitly cause inheriting authorization policies to "stop looking up the traversal tree" (effectively breaking any inheritance). For example, an ACL which allows only fred the view permission for a particular resource, despite what inherited ACLs may say, might look like so:

1from pyramid.authorization import Allow
2from pyramid.authorization import DENY_ALL
3
4__acl__ = [ (Allow, 'fred', 'view'), DENY_ALL ]

Under the hood, the pyramid.authorization.DENY_ALL ACE equals the following:

1from pyramid.authorization import ALL_PERMISSIONS
2__acl__ = [ (Deny, Everyone, ALL_PERMISSIONS) ]

ACL Inheritance and Location-Awareness

While the ACL helper is in place, if a resource object does not have an ACL when it is the context, its parent is consulted for an ACL. If that object does not have an ACL, its parent is consulted for an ACL, ad infinitum, until we've reached the root and there are no more parents left.

In order to allow the security machinery to perform ACL inheritance, resource objects must provide location-awareness. Providing location-awareness means two things: the root object in the resource tree must have a __name__ attribute and a __parent__ attribute.

1class Blog(object):
2    __name__ = ''
3    __parent__ = None

An object with a __parent__ attribute and a __name__ attribute is said to be location-aware. Location-aware objects define a __parent__ attribute which points at their parent object. The root object's __parent__ is None.

See also

See also pyramid.location for documentations of functions which use location-awareness.

See also

See also Location-Aware Resources.

Changing the Forbidden View

When Pyramid denies a view invocation due to an authorization denial, the special forbidden view is invoked. Out of the box, this forbidden view is very plain. See Changing the Forbidden View within Using Hooks for instructions on how to create a custom forbidden view and arrange for it to be called when view authorization is denied.

Debugging View Authorization Failures

If your application in your judgment is allowing or denying view access inappropriately, start your application under a shell using the PYRAMID_DEBUG_AUTHORIZATION environment variable set to 1. For example:

PYRAMID_DEBUG_AUTHORIZATION=1 $VENV/bin/pserve myproject.ini

When any authorization takes place during a top-level view rendering, a message will be logged to the console (to stderr) about what ACE in which ACL permitted or denied the authorization based on authentication information.

This behavior can also be turned on in the application .ini file by setting the pyramid.debug_authorization key to true within the application's configuration section, e.g.:

1[app:main]
2use = egg:MyProject
3pyramid.debug_authorization = true

With this debug flag turned on, the response sent to the browser will also contain security debugging information in its body.

Debugging Imperative Authorization Failures

The pyramid.request.Request.has_permission() API is used to check security within view functions imperatively. It returns instances of objects that are effectively booleans. But these objects are not raw True or False objects, and have information attached to them about why the permission was allowed or denied. The object will be one of pyramid.authorization.ACLAllowed, pyramid.authorization.ACLDenied, pyramid.security.Allowed, or pyramid.security.Denied, as documented in pyramid.security. At the very minimum, these objects will have a msg attribute, which is a string indicating why the permission was denied or allowed. Introspecting this information in the debugger or via print statements when a call to has_permission() fails is often useful.

Admonishment Against Secret-Sharing

A "secret" is required by various components of Pyramid. For example, the helper below might be used for a security policy and uses a secret value seekrit:

helper = AuthTktCookieHelper('seekrit')

A session factory also requires a secret:

my_session_factory = SignedCookieSessionFactory('itsaseekreet')

It is tempting to use the same secret for multiple Pyramid subsystems. For example, you might be tempted to use the value seekrit as the secret for both the helper and the session factory defined above. This is a bad idea, because in both cases, these secrets are used to sign the payload of the data.

If you use the same secret for two different parts of your application for signing purposes, it may allow an attacker to get his chosen plaintext signed, which would allow the attacker to control the content of the payload. Re-using a secret across two different subsystems might drop the security of signing to zero. Keys should not be re-used across different contexts where an attacker has the possibility of providing a chosen plaintext.

Preventing Cross-Site Request Forgery Attacks

Cross-site request forgery attacks are a phenomenon whereby a user who is logged in to your website might inadvertently load a URL because it is linked from, or embedded in, an attacker's website. If the URL is one that may modify or delete data, the consequences can be dire.

You can avoid most of these attacks by issuing a unique token to the browser and then requiring that it be present in all potentially unsafe requests. Pyramid provides facilities to create and check CSRF tokens.

By default Pyramid comes with a session-based CSRF implementation pyramid.csrf.SessionCSRFStoragePolicy. To use it, you must first enable a session factory as described in Using the Default Session Factory or Using Alternate Session Factories. Alternatively, you can use a cookie-based implementation pyramid.csrf.CookieCSRFStoragePolicy which gives some additional flexibility as it does not require a session for each user. You can also define your own implementation of pyramid.interfaces.ICSRFStoragePolicy and register it with the pyramid.config.Configurator.set_csrf_storage_policy() directive.

For example:

from pyramid.config import Configurator

config = Configurator()
config.set_csrf_storage_policy(MyCustomCSRFPolicy())

Using the csrf.get_csrf_token Method

To get the current CSRF token, use the pyramid.csrf.get_csrf_token method.

from pyramid.csrf import get_csrf_token
token = get_csrf_token(request)

The get_csrf_token() method accepts a single argument: the request. It returns a CSRF token string. If get_csrf_token() or new_csrf_token() was invoked previously for this user, then the existing token will be returned. If no CSRF token previously existed for this user, then a new token will be set into the session and returned. The newly created token will be opaque and randomized.

Using the get_csrf_token global in templates

Templates have a get_csrf_token() method inserted into their globals, which allows you to get the current token without modifying the view code. This method takes no arguments and returns a CSRF token string. You can use the returned token as the value of a hidden field in a form that posts to a method that requires elevated privileges, or supply it as a request header in AJAX requests.

For example, include the CSRF token as a hidden field:

<form method="post" action="/myview">
  <input type="hidden" name="csrf_token" value="${get_csrf_token()}">
  <input type="submit" value="Delete Everything">
</form>

Or include it as a header in a jQuery AJAX request:

var csrfToken = "${get_csrf_token()}";
$.ajax({
  type: "POST",
  url: "/myview",
  headers: { 'X-CSRF-Token': csrfToken }
}).done(function() {
  alert("Deleted");
});

The handler for the URL that receives the request should then require that the correct CSRF token is supplied.

Using the csrf.new_csrf_token Method

To explicitly create a new CSRF token, use the csrf.new_csrf_token() method. This differs only from csrf.get_csrf_token() inasmuch as it clears any existing CSRF token, creates a new CSRF token, sets the token into the user, and returns the token.

from pyramid.csrf import new_csrf_token
token = new_csrf_token(request)

Note

It is not possible to force a new CSRF token from a template. If you want to regenerate your CSRF token then do it in the view code and return the new token as part of the context.

Checking CSRF Tokens Manually

In request handling code, you can check the presence and validity of a CSRF token with pyramid.csrf.check_csrf_token(). If the token is valid, it will return True, otherwise it will raise HTTPBadRequest. Optionally, you can specify raises=False to have the check return False instead of raising an exception.

By default, it checks for a POST parameter named csrf_token or a header named X-CSRF-Token.

from pyramid.csrf import check_csrf_token

def myview(request):
    # Require CSRF Token
    check_csrf_token(request)

    # ...

Checking CSRF Tokens Automatically

New in version 1.7.

Pyramid supports automatically checking CSRF tokens on requests with an unsafe method as defined by RFC2616. Any other request may be checked manually. This feature can be turned on globally for an application using the pyramid.config.Configurator.set_default_csrf_options() directive. For example:

from pyramid.config import Configurator

config = Configurator()
config.set_default_csrf_options(require_csrf=True)

CSRF checking may be explicitly enabled or disabled on a per-view basis using the require_csrf view option. A value of True or False will override the default set by set_default_csrf_options. For example:

@view_config(route_name='hello', require_csrf=False)
def myview(request):
    # ...

When CSRF checking is active, the token and header used to find the supplied CSRF token will be csrf_token and X-CSRF-Token, respectively, unless otherwise overridden by set_default_csrf_options. The token is checked against the value in request.POST which is the submitted form body. If this value is not present, then the header will be checked.

In addition to token based CSRF checks, if the request is using HTTPS then the automatic CSRF checking will also check the referrer of the request to ensure that it matches one of the trusted origins. By default the only trusted origin is the current host, however additional origins may be configured by setting pyramid.csrf_trusted_origins to a list of domain names (and ports if they are non-standard). If a host in the list of domains starts with a . then that will allow all subdomains as well as the domain without the .. If no Referer or Origin header is present in an HTTPS request, the CSRF check will fail unless allow_no_origin is set. The special Origin: null can be allowed by adding null to the pyramid.csrf_trusted_origins list.

It is possible to opt out of checking the origin by passing check_origin=False. This is useful if the CSRF storage policy is known to be secure such that the token cannot be easily used by an attacker.

If CSRF checks fail then a pyramid.exceptions.BadCSRFToken or pyramid.exceptions.BadCSRFOrigin exception will be raised. This exception may be caught and handled by an exception view but, by default, will result in a 400 Bad Request response being sent to the client.