Skip to main content

archenstack-rbac-django

archenstack-rbac-django is the Django/DRF adapter and persistence layer over the pure archenstack-rbac core. It gives your Django app the storage, migrations, management commands, and REST management API that turn the abstract access-matrix model into a live, editable policy — while handing every rule off to the core.

What it is (and isn't)​

The core (archenstack_rbac) owns the model and the resolution algorithm — access levels, snapshot shape, decide/resolve, eval_scope, validate, the anti-lock-out check, and canonical JSON. This adapter never re-implements any of that. All it does is:

  • persist a matrix snapshot in Django ORM tables, and
  • compile those rows into a validated archenstack_rbac.MatrixSnapshot via build_matrix(), running the core's validate on the way.

It speaks wire_version 1. Everything host-app-specific — owner FK field names, the department relation, the catalogue — is configured through Django settings, so no product- or domain-specific names are baked into the package.

Package names

The distribution is archenstack-rbac-django; you import archenstack_rbac_django. It depends on the pure core distribution archenstack-rbac (imported as archenstack_rbac), which pip resolves from the same registry — see Installation.

Install​

Installing the adapter pulls in the core (archenstack-rbac) plus Django and DRF:

pip install archenstack-rbac-django

Point pip at Archenstack's package registry first — see Installation. Developing against a checkout instead? pip install -e ../archenstack-rbac-python then pip install -e ..

Add the app to your project, run its migrations, then seed the catalogue:

# settings.py
INSTALLED_APPS = [
# ...
"rest_framework",
"archenstack_rbac_django",
]
python manage.py migrate
python manage.py rbac_seed # idempotent; --prune for a full reseed

rbac_seed writes the configured catalogue (groups, roles, features, defaults, matrix config) into the ORM tables. It's safe to re-run.

Data model​

The adapter stores the policy across these tables. Defaults live on Feature; the override layer is the only part you edit at runtime. Every policy-bearing row carries an org FK, so each organization owns an isolated matrix (uniqueness is scoped to (org, …)).

TablePurpose
OrganizationThe tenant anchor; unique slug, label, is_active.
GroupDisplay grouping for roles/features; unique (org, slug).
RoleMatrix column; kind = standard | super | alias; unique (org, slug).
FeatureMatrix row; seed-owned defaults JSON + partial_scope; unique (org, key).
PermissionOverrideThe sole editable layer; delta from default, unique (org, feature, role).
PermissionChangeLogAppend-only audit of override edits, per org.
MatrixStampOne per org: version counter + seed-owned fallback / default_partial_scope.
Defaults are seed-owned

A feature's defaults are stored as JSON on the Feature row and are not editable through the matrix — they change only by re-seeding or importing a new policy. PermissionOverride is the only runtime-editable layer: every matrix edit is a delta from a default, never a mutation of the default itself. See the model concepts.

Configuration​

Everything host-specific is configured through a single ARCHENSTACK_RBAC settings dict — never hardcoded in the models or the builder:

# settings.py
ARCHENSTACK_RBAC = {
"CATALOGUE": "myapp.rbac_catalogue.CATALOGUE", # dict or dotted path
"SCOPE_OWNER_FIELDS": ["owner", "created_by"], # owner FK names tried in order
"SCOPE_DEPARTMENT_FIELD": "department", # object's department FK name
"SCOPE_INCLUDE_SUBTREE": True, # opt into the own_subtree atom
"SCOPE_SUBTREE_FIELD": "org_unit", # object's unit FK name
"SCOPE_SUBTREE_RESOLVER": "myapp.rbac.subtree", # callable(subject) -> unit pks
"CHECK_BATCH_MAX": 200, # max items per batch /check/
}

Every host-shaped key has a spec-faithful default, so a minimal deployment only overrides CATALOGUE (which otherwise defaults to the bundled SAMPLE_CATALOGUE). The operator-tunable knobs are the exception — the cache TTL, the batch cap, and the audit-page bounds carry no code fallback and are read from the environment (single source of truth, fail loud: an unset value raises ImproperlyConfigured rather than silently substituting a hardcoded default). See Environment variables. The scope-pack knobs (SCOPE_OWNER_FIELDS, SCOPE_DEPARTMENT_FIELD, and the opt-in SCOPE_SUBTREE_* chain-of-command trio) feed the write-scope predicate; see resolution & scopes and object scopes.

Multi-tenancy: the org resolver

For a multi-tenant deployment, SCOPE_ORG_RESOLVER (a dotted callable(user) -> org-slug) or SCOPE_SUBJECT_ORG_ATTR (an attribute off the user) tells the adapter which org a request belongs to — the org-shaped sibling of SCOPE_SUBJECT_RESOLVER. It fails closed: no org resolved ⇒ the caller is denied. The dev/seed/backfill org comes from the ARCHENSTACK_RBAC_DEFAULT_ORG environment variable and is never a runtime fallback. See Wiring multi-tenancy.

Identity resolvers (fail closed)​

The adapter is fail-closed on identity: it ships no header- or bearer-trusting default resolver. With none of the identity resolvers wired, every caller resolves to no subject (and no org), so every authenticated route denies — a header can never be trusted as an identity. Django was fail-closed from the first release; there was never an insecure default to relocate (the Node/Go/Rust adapters moved theirs to a dev-only surface in 0.2.x).

A host wires one resolver, and it supplies identity, not a role:

  • SCOPE_SUBJECT_RESOLVER (required) — a dotted callable(user) -> OIDC 'sub'. The caller's role is then read from Archenstack's own (org, sub) RoleAssignment table on every request.

A caller who resolves to no subject — or to a subject with no assignment in the active org — has no role and is denied (kind: "error", not_found), never represented with an empty role.

Archenstack owns roles

The adapter reads the caller's role from its own per-(org, subject) assignment table, never from a host callable or a token claim: a subject can belong to several orgs (which one role claim can't express), the anti-lockout check counts admin-capable subjects, and a per-request assignment read makes revocation take effect on the next call. Wire SCOPE_SUBJECT_RESOLVER (a dotted callable(user) -> the OIDC sub) and assign roles over /permissions/assignments/.

Ready-made JWT-claims resolvers (archenstack_rbac_django.jwt_claims)

Most deployments authenticate with an OIDC JWT that their auth layer has already validated against the issuer's JWKS and attached to the request. For that case the adapter ships a resolver module you point those settings at (opt-in — parity with Spring's archenstack-rbac.jwt-resolver.enabled):

ARCHENSTACK_RBAC = {
"SCOPE_SUBJECT_RESOLVER": "archenstack_rbac_django.jwt_claims.jwt_subject_resolver",
"SCOPE_ORG_RESOLVER": "archenstack_rbac_django.jwt_claims.jwt_org_resolver",
"SCOPE_PLATFORM_RESOLVER": "archenstack_rbac_django.jwt_claims.jwt_platform_resolver",
# also available: jwt_email_resolver (member reconciliation)
}

Each callable reads the identity off the already-validated claims — preferring a claims mapping on the JWT_CLAIMS_ATTR attribute (default rbac_claims, e.g. what a DRF auth class attaches), else a mapping principal, else a same-named attribute. Archenstack never validates the token itself and never trusts a raw header. Every accessor is fail-closed: a missing principal, mapping, or claim resolves to None (deny). The claim names are structural knobs (not operator-tuned), configured in the ARCHENSTACK_RBAC dict:

SettingDefaultReads
JWT_CLAIMS_ATTRrbac_claimswhere the validated claims mapping lives on the principal
JWT_SUBJECT_CLAIMsubthe stable subject id (the assignment key)
JWT_ORG_CLAIMorgthe active org slug
JWT_EMAIL_CLAIMemailthe member-reconciliation attribute
JWT_PLATFORM_CLAIM"" (empty)the platform-admin signal; empty ⇒ no platform claim consulted (fail closed)
JWT_PLATFORM_VALUE"" (empty)when set, a membership test — asserted when the claim (a roles/groups array or space-delimited scope string) contains this value; empty ⇒ the claim is a plain boolean flag

jwt_platform_resolver reads the platform claim off the validated token (request.auth) when present, else request.user.

Environment variables​

Operator-tunable knobs are read from ARCHENSTACK_RBAC_* environment variables (single source of truth). For the tuning knobs the precedence is: an explicit ARCHENSTACK_RBAC[...] setting wins, then the env var, then — for the four required knobs — nothing: an unset value raises ImproperlyConfigured at first use (fail loud, no packaged default). Every key ships in the adapter's .env.example.

Env varPurposeUnset
ARCHENSTACK_RBAC_DEFAULT_ORGThe dev / seed / migration-backfill org slug. Seed/backfill target only — the request path never substitutes it for a missing org claim.required for seed/backfill
ARCHENSTACK_RBAC_CACHE_TTLCompiled-matrix cache TTL in seconds; 0/empty ⇒ never expire (rely on version-stamped invalidation).raises (no code default)
ARCHENSTACK_RBAC_CHECK_BATCH_MAXMax items a single batch POST /check/ may carry (was 200).raises (no code default)
ARCHENSTACK_RBAC_AUDIT_DEFAULT_PAGE_SIZEDefault GET /audit/ page size when ?page_size= is omitted.raises (no code default)
ARCHENSTACK_RBAC_AUDIT_MAX_PAGE_SIZEHard cap on a single GET /audit/ page size.raises (no code default)
ARCHENSTACK_RBAC_BOOTSTRAP_ADMIN_SUBJECTFirst-admin startup bind — see First-admin bootstrap.empty ⇒ off (opt-in; no raise)
ARCHENSTACK_RBAC_BOOTSTRAP_ADMIN_ROLERole the bootstrap subject is bound to.empty ⇒ the seeded administrator
ARCHENSTACK_RBAC_PLATFORM_SUBJECTSPlatform-admin sub allowlist (comma-separated).empty ⇒ no platform-admin operator (fail closed)
Audit page bounds

GET /audit/ chooses its page size per request via ?page_size=N, defaulting to ARCHENSTACK_RBAC_AUDIT_DEFAULT_PAGE_SIZE and capped at ARCHENSTACK_RBAC_AUDIT_MAX_PAGE_SIZE. Both are required (no code fallback) — like the cache TTL and batch cap, an unset value is a loud boot-time error, not a silent default.

Building a catalogue (CatalogueBuilder)​

The catalogue you point ARCHENSTACK_RBAC["CATALOGUE"] at is a plain seed dict — groups, roles (with their kind), per-feature defaults + partial_scope + write_hint, and the matrix-wide fallback / default_partial_scope. Rather than hand-author that nested literal, assemble it fluently with the typed CatalogueBuilder:

from archenstack_rbac_django.catalogue import catalogue
from archenstack_rbac import F, P # AccessLevel.FULL / PARTIAL shorthands

CATALOGUE = (
catalogue(default_partial_scope={"atom": "own_record"})
.group("administration", "Administration")
.group("operations", "Operations")
.super_role("owner", "Owner", group="administration", is_system=True)
.role("administrator", "Administrator", group="administration", is_system=True)
.role("staff", "Staff", group="operations")
.alias_role("supervisor", "administrator", label="Supervisor", group="operations")
.feature("rbac.manage", "Manage access matrix", group="administration",
defaults={"administrator": F}, write_hint=F)
.feature("records.edit", "Edit records", group="operations",
defaults={"administrator": F, "staff": "PARTIAL"}, write_hint=P)
.build()
)

catalogue(...) is the entry point (mirroring the core's archenstack_rbac.catalogue); every declaration returns self for chaining, and order defaults to declaration order unless you pass an explicit order. Access levels accept an AccessLevel, its int (0–3), or its case-insensitive name (coerced via AccessLevel.coerce; bool is rejected). build() returns exactly the dict shape rbac_seed and rbac_import consume — so you can assign it to ARCHENSTACK_RBAC["CATALOGUE"] (or a dotted path to it) and seed.

The builder doesn't validate — seeding does

CatalogueBuilder only assembles the dict; it does not run the core's rules. Validation happens when the rows are compiled — build_matrix() runs the core's validate (anti-lock-out check included) and raises MatrixValidationError on a bad snapshot. Distinct from the pure core's archenstack_rbac.SnapshotBuilder, which emits a compiled MatrixSnapshot directly; this adapter builds the intermediate seed dict because it persists rows before compiling. See the Python core.

Policy IO (management commands)​

Three management commands move policy between the live DB and canonical JSON. The wire format is the core's kind: "matrix" snapshot, so an export from one deployment imports cleanly into another.

# Seed the configured catalogue into the ORM (idempotent).
python manage.py rbac_seed # --prune for a full reseed

# Dump the live policy as canonical JSON (stdout by default).
python manage.py rbac_export -o policy.json

# Validate + apply a policy transactionally.
python manage.py rbac_import policy.json
python manage.py rbac_import --dry-run policy.json # show the core diff, apply nothing

rbac_import validates the policy through the core, then upserts groups/roles/features + matrix config and fully syncs the override layer inside one unit of work — bumping the version, invalidating the cache, writing an audit row per change, and enforcing the anti-lock-out check.

Transactional, idempotent, prunes by default

A bad or lock-out-inducing policy rolls the whole import back — nothing is partially applied. Re-importing the same policy is a clean no-op. By default rbac_import prunes entities absent from the policy; pass --no-prune for an additive upsert. Export → import into a fresh DB reproduces the same snapshot.

Compiling the snapshot (build_matrix())​

To resolve decisions in your own code, compile the persisted rows into a validated core snapshot:

from archenstack_rbac_django.build import build_matrix

matrix = build_matrix() # a validated archenstack_rbac.MatrixSnapshot
matrix.decide("records.edit", "manager") # -> Decision(level, scope)

build_matrix() runs the core's validate on the compiled rows and raises MatrixValidationError (carrying the core's ErrorCode list) if the persisted snapshot is invalid. In request-handling code you rarely call it directly — the DRF permission classes resolve through a cached, version-stamped provider instead.

First-admin bootstrap​

Every management route requires rbac.manage at FULL, so a freshly deployed org faces a chicken-and-egg problem: the very first admin assignment is the one grant nobody can create from inside the matrix. The bootstrap closes that gap by binding a configured subject to the admin role at startup — the Django analogue of the Spring adapter's BootstrapAdminRunner.

Two env keys drive it (see Environment variables):

  • ARCHENSTACK_RBAC_BOOTSTRAP_ADMIN_SUBJECT — the stable OIDC sub to bind. Empty is the explicit "off" state (the default): no subject ⇒ no bootstrap, and it does not raise. Set it to enable the startup bind.
  • ARCHENSTACK_RBAC_BOOTSTRAP_ADMIN_ROLE — the role slug to bind the subject to. Empty ⇒ the seeded administrator management-FULL holder (the standard role that resolves rbac.manage FULL).

The subject is bound in the ARCHENSTACK_RBAC_DEFAULT_ORG org on Django's post_migrate signal — after the schema (and any seed) exist, which is why the bind runs there rather than in AppConfig.ready(). The bind is:

  • idempotent — a re-run where the subject already holds the target role is a no-op, so it is safe on every deploy;
  • lock-out-safe — on a bare deployment it reuses the atomic provision_org primitive (create inactive → seed → bind first admin → activate); on an existing org it binds only a subject that holds no role yet, so it can never remove the last admin-capable holder. A subject who already has a role in that org keeps it, and the configured role is logged as not applied — this binds a first admin, and changing an existing one is an /assignments/ write, which enforces the anti-lockout rule. An inactive org is flipped live only once the bound subject actually resolves the management feature FULL;
  • custom-role-safe — a ARCHENSTACK_RBAC_BOOTSTRAP_ADMIN_ROLE the org's seeded catalogue doesn't define is warned about and skipped, never overwritten with the sample. If ARCHENSTACK_RBAC_BOOTSTRAP_ADMIN_SUBJECT is set but ARCHENSTACK_RBAC_DEFAULT_ORG is not, the bootstrap logs a warning and skips.

The subject and role values are never logged; only the role slug and org are.

Why a real bind here

Django and Spring back the bind with an assignment store, so this is a genuine startup insert. The in-memory Node/Go/Rust adapters have no assignment store, so their equivalent is a verify-not-insert check (assert the configured admin resolves FULL) rather than a persisted binding.

Management API​

Mount the DRF views in your host URLconf. The adapter ships prefix-relative patterns, so you own the mount point:

# urls.py
from django.urls import include, path

urlpatterns = [
path("permissions/", include("archenstack_rbac_django.urls")),
]

Every response carries wire_version + kind and validates against the authoritative archenstack-rbac-spec JSON Schemas; failures return the standard kind: "error" envelope. See the wire protocol.

Auth model​

SurfaceRequirement
Matrix / groups / roles / auditrbac.manage at FULL — a read of the editable matrix is as sensitive as a write, so FULL is demanded for every method (GET included).
Features (/features/…)A developer (a super role) — features are developer-defined, restricted more tightly than the matrix.
/me/ and /check/Any authenticated user with an assigned role — never read-scoped.
/me/ and /check/ require an assigned role

Their me / policy bodies pin role to a non-empty slug, so a caller who resolves to no role can't be represented — the host is responsible for assigning every authenticated user a role. A role-less caller gets the standard kind: "error" envelope (not_found, HTTP 404), never an invalid body.

Endpoints​

Method + pathPurpose
GET /permissions/matrix/The extended editable matrix (snapshot + editor conveniences).
PUT /permissions/matrix/Bulk cell-override edits — cell-only, delta semantics, validated against the lock-out invariant.
POST /permissions/matrix/reset/Clear the whole override layer back to seed defaults.
GET/POST /permissions/features/List / create features.
GET/PATCH /permissions/features/{key}/Read / update a feature (deactivate via is_active=false; no delete).
POST /permissions/features/reorder/Reorder feature rows ({"order": [...]}).
GET/POST/PATCH /permissions/groups/… + reorder/Group CRUD + reorder (the dropdown data source).
GET/POST/PATCH /permissions/roles/… + reorder/Role CRUD + reorder; slug + kind immutable; referential-integrity + anti-lock-out checks.
GET /permissions/me/The caller's own effective feature -> {level, can_read, can_write}.
POST /permissions/check/Single {feature, object?} → kind: "policy" (allowed + Decision), or batch {checks: [{feature, object?}, …]} → kind: "policy-batch" with positional results.
GET /permissions/audit/The change log, newest first, paginated (?page=&page_size=).
GET /permissions/orgs/ · GET /permissions/orgs/{slug}/List / read organizations — the multi-tenant picker source.
POST /permissions/orgs/Provision an organization — create it inactive, seed its catalogue, bind its first admin, activate. Requires a platform principal (an IdP-asserted platform scope, or a subject named in ARCHENSTACK_RBAC_PLATFORM_SUBJECTS), never an org admin. This is how a standalone deployment creates tenants without a provisioning orchestrator.
GET/POST /permissions/orgs/{slug}/apps/List / register an org's OIDC clients (client_id ↔ org binding). Register accepts the org's own admin or a platform principal.

Every request selects the caller's org snapshot server-side before it resolves, so /matrix/, /me/, /check/, /audit/, and the management routes all return that org's data. A missing or unknown org denies (fail closed) — see Wiring multi-tenancy.

Batch /check/

A batch resolves a whole list in one round-trip: results[i] maps to checks[i] and results.length == checks.length. It fails closed per item (an unknown feature denies), rejects a structurally malformed item or a mixed feature+checks body with validation, and bounds the batch at CHECK_BATCH_MAX (default 200). With an object ref, each item is an object-level write check via the scope evaluator; otherwise it's feature-level read eligibility (level >= VIEW).

DRF permission classes​

To protect your own endpoints with the compiled matrix, use the two DRF adapters. Both route every decision through the core decide served by a cached, version-stamped snapshot provider — never a re-implemented rule.

from rest_framework.viewsets import ModelViewSet
from archenstack_rbac_django.permissions import MatrixPermission, MatrixQuerysetMixin

class DocumentViewSet(MatrixQuerysetMixin, ModelViewSet):
rbac_feature = "records.edit"
permission_classes = [MatrixPermission]
# ...
  • MatrixPermission — a feature-bound BasePermission. Safe (read) methods need >= VIEW; unsafe (write) methods need >= the view's rbac_minimum_write (default PARTIAL) at the feature level, then a per-object scope check (FULL writes anything; PARTIAL requires the object to match the decision's scope; less denies). Bind the feature with rbac_feature on the view or MatrixPermission.for_feature("records.edit").
  • MatrixQuerysetMixin — narrows a write-eligible queryset via get_write_eligible_queryset() (FULL → all rows; PARTIAL → scope-filtered; below PARTIAL → none). Reads stay unscoped — row filtering is a write-only concern.

The scope pack ships two always-on atoms — own_record (the object's owner FK, tried across SCOPE_OWNER_FIELDS) and own_assignment (the object's subject/assignee is the caller, or they are a member of its subjects/assignees collection — a scalar FK or an M2M, for self-service) — plus the opt-in own_department and own_subtree, all resolved from the ARCHENSTACK_RBAC settings. Seeding a catalogue whose scope names an atom the evaluator can't resolve raises ImproperlyConfigured up front. ARCHENSTACK_RBAC["ENFORCEMENT_MODE"] = "shadow" makes the authorizer and MatrixPermission log a would-be denial and allow it through (instead of blocking), so you can stage enforcement onto a live app — see enforcement mode. See object scopes for the atoms and the atom grammar.

Development / testing​

pip install pytest pytest-django
pytest

Tests run against an in-memory SQLite database with a locmem cache (production wires Redis via env). The bundled test project mounts archenstack_rbac_django.urls under /permissions/ over a placeholder host app with an ownable Document model.

Releasing​

Same tag-driven CI flow as the core: bump version, then push a archenstack-rbac-django/vX.Y.Z tag and the pipeline builds and uploads the package.

Because dependencies = ["archenstack-rbac"], release the core first — publish (or bump) archenstack-rbac before the adapter, so pip install archenstack-rbac-django can resolve it from the registry.

See also​