Skip to main content

django_scoped_rbac

https://gitlab.com/openteams/django-scoped-rbac/badges/master/pipeline.svg

A rich and flexible Django application for role-based access control within distinct access control scopes, serving Semantic HTTP 0.1 through two first-class front ends: Django REST framework and django-ninja, which answer the same request the same way.

Motivation

  • Support multiple security contexts within an application, rather than having the application serve as the single security context.

  • Support a model of security context that can be enforced at the query level within the database. For example - list all resources within the contexts the user is authorized to list resources.

  • Support assignment of roles within a security context.

  • Support an extensible mechanism for conditional policy expressions for permissions.

  • Support a JSON representation of the total permissions granted to a user for all security contexts that can be shared with browser and other clients to enable permissions-informed disclosure UI and UX

Support multiple security contexts within an application

Most RBAC systems provide a simple permission model to answer permissions. For example, is the user authorized to POST a comment. In an application that supports multiple security contexts the relevant context is an additional parameter required to determine if the user is authorised; that is is the user authorized to POST a comment to this project vs another project. A user may be authorized to POST a comment to one project, but not another.

Support for security contexts at the query level

If every object has a security context property it’s possible to always secure the queries executed for a user request by adding the user’s authorized security contexts as an “IN” condition restricting the scope of the query.

Support assignment of roles within a security context

In most RBAC systems a user is assigned a role that is applicable across the entire application. For example, a user may have a Commenter role granting the user the permission to post comments anywhere comments may be posted within the application. An application that supports the assignment of a role within the scope of a specific security context can restrict the assignment of the Commenter role to specific areas of an application. For example, a user may be assigned the Commenter role in Project 1 but not Project 2.

Support an extensible mechanism for conditional policy expressions

Another limitation of most RBAC systems is the simplicity of their permissions - you are either authorized to perform an action or not. Supporting an extensible mechanism for conditional policy expression means that a permission may be conditionally granted dependant upon a variety of factors. For example, you may be granted the permission to comment within a project only when a target resource within the scope of that project is “open for community comments” vs “open for drafter comments”.

Support JSON representation of total permissions granted

If a user has permission to perform an action, such as update a resource, it should be possible for a client to determine that this is the case and be able to decide whether to disclose editing capabilty for the resource to the user. That is, if I’m not authorised to edit a resource the UI shouldn’t offer me the opportunity to edit the resource.

Providing a JSON representation of the user’s total permissions, and a Javascript implementation of the permissions policy engine, can provide a much richer user experience.

Installation

Requires Python 3.11+ and Django 5.2+. Install a front end, or both:

uv add 'django-scoped-rbac[drf]'     # Django REST framework 3.15+
uv add 'django-scoped-rbac[ninja]'   # django-ninja 1.7.0 to 1.7.3
# or: pip install 'django-scoped-rbac[drf,ninja]'

Add "scoped_rbac" to INSTALLED_APPS, configure policies with the SCOPED_RBAC setting, and include scoped_rbac.semantic_urls once, which serves the JSON Schemas and JSON-LD contexts that responses link to:

path("api/semantic/", include("scoped_rbac.semantic_urls"))

Every response also links to an HTTP Schema Resource, which scrudful builds without a request and serves by GET. Set the public base URL its links resolve against and, for the DRF front end, include scrudful’s HSR route in the root URLconf:

# settings.py
SCRUDFUL = {"BASE_URL": "https://api.example.com"}

# the root urls.py
from scrudful.rest_framework import hsr_urls

urlpatterns = [
    ...,
    path("", include(hsr_urls())),  # DRF only
]

The guides (docs/drf.rst, docs/ninja.rst, docs/semantic_http.rst) have a worked Project example for each front end and the full contract.

Upgrading from 0.11

0.12 adopts scrudful 0.10 (Semantic HTTP 0.1 at spec commit 37ec1ce), which is breaking. Check each item (CHANGELOG.rst has the details):

  • OPTIONS is a 204 without content, with one Link to the HTTP Schema Resource (HSR), served by GET. A client reading the OPTIONS body must GET the HSR instead. Allow lists the methods this requester may use, per their grants (on roles and role assignments, an anonymous user or one without grants gets OPTIONS alone).

  • Set SCRUDFUL["BASE_URL"] (the HSR is built without a request; its relative links, scoped-rbac’s schemas and contexts, resolve against it).

  • DRF: include path("", include(scrudful.rest_framework.hsr_urls())) in the root URLconf (or set SCRUDFUL["HSR_URL"]). Without it every request of a scoped-rbac view raises ImproperlyConfigured, and manage.py check reports scrudful.E003.

  • DRF: a viewset whose resource_type_iri depends on the request can’t have its HSR built (scrudful.E005, as without BASE_URL): set its Links on Meta.

  • ninja: every operation on a ScrudfulRouter needs an entity: decorate a plain operation with @described(Entity(...)) (scrudful.ninja). The [ninja] extra needs django-ninja 1.7.0 to 1.7.3.

  • Run migrate (0008_collectionlock). Lists now send ETag and Last-Modified, and a POST to a list evaluates its If-Match, If-None-Match and If-Unmodified-Since against them (412, 400): a client sending a stray one with a create can now get a 412 or 400. Migrate on every database that stores an access-controlled model (the lock’s table lives beside the model’s), and keep READ COMMITTED (Django’s default).

Upgrading from 0.10

0.11 is a breaking release. Check each item (CHANGELOG.rst has the details):

  • Install the DRF extra: django-scoped-rbac[drf] (DRF is optional now). The [ninja] extra needs django-ninja 1.7.x; both need scrudful 0.8 (>=0.8,<0.9).

  • ninja: a list operation of your own passes scrudful_list(**list_check(iri, queryset)) and returns checked_list(request), so it checks before the throttles and filters after them, before its page / page_size, as DRF does (crud_router does this for you).

  • ninja: an item or create operation of your own passes **item_check(iri, load=its_rbac_load) (a create: **item_check(iri)) to @scrudful / @scrudful_create, so its request-level check comes before the throttles, as in DRF, and validates its body in the handler, not as a typed parameter (crud_router does this for you).

  • Include scoped_rbac.semantic_urls once in the URLconf. Without it the system check scoped_rbac.E002 fails, which stops manage.py commands.

  • Set REST_FRAMEWORK["EXCEPTION_HANDLER"] = "scoped_rbac.rest.exception_handler" for RFC 9457 problem details (an unauthenticated denial is a 401).

  • Clients: lists use the scrud envelope (content, not results); PUT, PATCH and DELETE need If-Match or If-Unmodified-Since (428); ETags issued by 0.10 no longer match (412): refetch before writing.

  • Role and RoleAssignment have new shapes: {"url", "rbac_context", "definition"} and {"url", "rbac_context", "user", "role"}, where role is the role’s absolute IRI on the serving front end and user an IRI (default urn:scoped-rbac:user:<pk>, see SCOPED_RBAC["USER_IRI"]), not a pk or a user-detail link.

  • Request bodies are JSON only (415 otherwise; override parser_classes to accept forms), and responses are JSON whatever Accept or ?format= asks for: DRF’s browsable API is off on scoped-rbac’s views (set renderer_classes and content_negotiation_class to bring it back).

  • IsAuthorized denies views with no resource type IRI: non-RBAC DRF views need permission_classes = [AllowAny] (use scoped_rbac.urls.OpenRouter for an open API root).

  • An object the user cannot read is a 404 for every method, the anonymous user included.

  • Mounting the DRF viewsets more than once (or beside the ninja front end): give each mount a URL namespace and use NamespaceVersioning, so that url, Location and href are reversed under the mount a request came through.

Conditional policy expressions

Policy conditions are written in the Common Expression Language and evaluated with Google’s cel-expr-python runtime. Each top-level key of the resource being authorized is available as a variable, for example content.status == "open". An expression that fails to evaluate denies access.

Custom functions are registered with CEL_FUNCTIONS. Because the CEL runtime dispatches on argument types, each function’s parameters must be annotated with bool, int, float, str, bytes, dict or list; a function that needs several signatures can be given as a cel_expr_python.cel.FunctionDecl instead:

# myapp/workflow.py
def is_allowed_transition(current: str, proposed: str) -> bool:
    ...

# settings.py
SCOPED_RBAC = {
    "CEL_FUNCTIONS": {
        "is_allowed_transition": "myapp.workflow.is_allowed_transition",
    },
}

Development

The project is managed with uv:

uv sync                              # create .venv with the dev dependencies
uv run pytest                        # run the tests with coverage
uv run ruff check && uv run ruff format --check
uv run --group docs make -C docs html   # build the docs into build/sphinx/html

Metadata

Release files for django-scoped-rbac 0.12.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-scoped-rbac 0.12.1
File Size Uploaded Provenance Actions
django_scoped_rbac-0.12.1.tar.gz 120.3 kB Without provenance Details for django_scoped_rbac-0.12.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-scoped-rbac 0.12.1
File Interpreter ABI Platform Actions
django_scoped_rbac-0.12.1-py3-none-any.whl Python 3 none any Details for django_scoped_rbac-0.12.1-py3-none-any.whl

Total release size: 260.6 kB

Release files / django_scoped_rbac-0.12.1.tar.gz

Download URL django_scoped_rbac-0.12.1.tar.gz
Size 120.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b00093c2d96bf9c44bee9345dbd152aef48a523b11e5a0fe2b6f8959ada0e906
BLAKE2b-256 checksum
How to use checksums
3b4dec4750520478581c7ae3f885184d6e024d5bbcb4164e7de22eb106b2efce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / django_scoped_rbac-0.12.1-py3-none-any.whl

Download URL django_scoped_rbac-0.12.1-py3-none-any.whl
Size 140.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
182b95cdf1e09e588dbda71aa68536533b207a39c6d412de2d98e30d60715ef0
BLAKE2b-256 checksum
How to use checksums
0a4b8254e170abe8d90e0b1eb034a5612675601db35f7e80410eb54b4122649a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for django-scoped-rbac 0.12.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page