Skip to main content

archenstack-rbac

archenstack-rbac is a tiny, framework-agnostic access-control matrix — roles × features → level — with no web framework, no database, and no runtime dependencies. It's the reference implementation of the Archenstack contract: you bring your own storage, cache, and HTTP layer, and the library takes care of the rules.

The package gives you two layers to work with:

  • an ergonomic Matrix facade for defining a grid in code and querying it;
  • the normative snapshot core (MatrixSnapshot, resolve_decision, eval_scope, validate, canonical JSON, and the policy diff / prune_orphans helpers) that implements the specification exactly and is what the conformance corpus is checked against.

Reach for the facade in everyday application code, and drop down to the core when you need the wire snapshot shape or the exact resolution algorithm every implementation has to agree on. To author a full seed catalogue — display groups, role kinds, per-feature write scopes — reach for the fluent catalogue() builder that sits between them (below). This library speaks wire_version 1.

Install​

pip install archenstack-rbac

Point pip at Archenstack's package registry first — see Installation. Working on the library itself? Install it editable from the package directory instead: pip install -e ".[dev]".

Distribution name vs. import name

The distribution is archenstack-rbac (hyphens — what pip sees), but the import package is archenstack_rbac (underscore — what you import):

from archenstack_rbac import Matrix, N, V, P, F

The model in brief​

Every cell of the grid resolves to one of four ordered levels:

LevelValueMeaning
NONE0no access
VIEW1read only
PARTIAL2write, but scoped (e.g. own records / own department)
FULL3unrestricted read + write

Because the levels are ordered, intent is just a comparison: level >= VIEW means "can read", and level >= PARTIAL means "can write".

Two layers decide a cell's value, and two rules sit above the grid:

  • Defaults — the policy that ships in your source code.
  • Overrides — edits applied at runtime (from an admin UI, a database, …). The effective level is the override if one exists, else the default, else a conservative NONE fallback.
  • Superusers always resolve to FULL and are never a column.
  • Aliases let one role mirror another.
Learn the model once

This page keeps the model short on purpose. For the full treatment of the levels and how they compose, see the model concept page; for the ordered precedence (superuser → alias → override → default → fallback) and scoped writes, see resolution & scopes.

Quickstart​

Construct a matrix, declare its code defaults, and query it. The facade methods return self, so calls chain nicely.

from archenstack_rbac import Matrix, N, V, P, F

matrix = Matrix(
roles=["director", "manager", "staff"],
features={
"reports.view": "View reports",
"reports.export": "Export reports",
},
superusers={"admin"}, # always FULL, never a column
aliases={"lead": "manager"}, # 'lead' resolves as 'manager'
)

# Define the code defaults, spreadsheet-style (columns + one row per feature):
matrix.define_rows(
["director", "manager", "staff"],
{
"reports.view": [V, F, V],
"reports.export": [V, F, N],
},
)

matrix.can_write("reports.export", "staff") # False
matrix.can_write("reports.export", "lead") # True (mirrors manager)
matrix.level("reports.export", "admin").name # 'FULL' (superuser)

# Layer a runtime override:
matrix.override("reports.export", "staff", F)
matrix.can_write("reports.export", "staff") # True
matrix.is_overridden("reports.export", "staff") # True

# Setting a cell back to its default clears the override:
matrix.override("reports.export", "staff", N)
matrix.is_overridden("reports.export", "staff") # False
Declaration validates, querying never raises

Declaring a default or override validates the role and feature names (raising UnknownRole / UnknownFeature). Querying — level, can_write, and friends — never raises: an unknown pair just returns the conservative fallback, so callers can probe freely.

Use it with any Python web framework​

Archenstack is just a library — no framework, no database — so it drops into FastAPI, Flask, aiohttp, Starlette, or a plain WSGI/ASGI app. Build the matrix once, then restrict a route by resolving the caller's role:

from fastapi import Depends, HTTPException

matrix = build_matrix() # your factory: roles, features, defaults, overrides

def require(feature: str, write: bool = True):
def dep(role: str = Depends(current_role)): # your auth → a role slug
ok = matrix.can_write(feature, role) if write else matrix.can_read(feature, role)
if not ok:
raise HTTPException(403, "forbidden")
return dep

@app.post("/records", dependencies=[Depends(require("records.edit"))])
def edit_record(...):
...

The matrix is plain in-memory state you build however you like — from a config file, a database, or the wire snapshot. To serve the full management API (/me/, /check/, an editable matrix) from your framework, persist a snapshot and compile it through the core, exactly as the Django adapter does.

Django gets a batteries-included adapter

Django has a dedicated adapter — archenstack-rbac-django — that persists the matrix in ORM tables and serves the whole management API for you. It's a separate, optional package; on any other framework you use this core directly, as shown above.

Persisting overrides​

The core keeps overrides in memory. Persist them however you like — the matrix exports and re-imports a plain, JSON-serialisable snapshot:

rows = matrix.export_overrides()
# [{"feature": "reports.export", "role": "staff", "level": 3}]
# … store rows in your DB …

fresh = build_matrix() # your factory that sets the defaults
fresh.load_overrides(load_from_db()) # re-apply the saved overrides

Only the overrides travel in this snapshot; the defaults always come from your code, so build_matrix() must re-establish them before you load.

Rendering an editor grid​

to_grid() returns a render-ready payload — one entry per feature, with cells keyed by role, each carrying its effective level and an overridden flag. Feed it straight to an admin editor UI:

matrix.to_grid()
# [{"feature": "reports.view", "label": "View reports",
# "cells": {"director": {"level": 1, "overridden": False},
# "manager": {"level": 3, "overridden": False},
# "staff": {"level": 1, "overridden": False}}}, ...]

Matrix API​

CallDoes
Matrix(roles=, features=, superusers=, aliases=, default=)construct
add_role(r) / add_feature(k, label="")declare more columns / rows (dynamic roles)
set_default(f, r, level) / define({f: {r: level}}) / define_rows(cols, rows)set code defaults
level(f, r)effective AccessLevel
can_read / can_write / is_full / is_partial / allows(f, r, min)threshold checks
override(f, r, level) / clear_override(f, r) / reset() / is_overridden(f, r)runtime edits
export_overrides() / load_overrides(rows)persistence snapshot
roles / features / label(f) / roles_with_at_least(f, min)introspection
to_grid()render-ready UI payload

The spec-conformant core​

Alongside the facade, the package exports the normative model — the same shapes and algorithm every Archenstack implementation must satisfy. Reach for these when you need the wire snapshot, the exact resolution precedence, or deterministic canonical bytes.

ExportPurpose (see the specification)
MatrixSnapshot, Role, Feature, Groupthe wire snapshot shape
resolve_decision → Decisionordered precedence super → alias → override → default → fallback
eval_scope, is_valid_scope, predicate_from_true_atomsScopeExpr tree-walk, fail-closed on unknown/malformed
validate, is_valid_slug, is_valid_feature_keysnapshot validation + ErrorCode
canonical_json, canonical_bytesdeterministic canonical JSON
diff, orphaned_overrides, prune_orphanspure policy-lifecycle helpers
AccessLevel, ErrorCode, RbacError, …the level enum + error taxonomy
Conformance is defined by the corpus

tests/test_conformance.py binds these exports to the spec's vectors/ and wire-golden/ corpus, so a green test run is this repo's definition of conformance. See the wire protocol for the shapes on the wire.

Assembling a seed catalogue​

The facade is a flat roles × features grid, but the seed catalogue an adapter compiles into a snapshot — the seed-owned baseline (spec §11) — carries more than that: display groups, role kinds (super / alias), per-feature write scopes and write_hints, and a matrix-wide fallback / default_partial_scope. Rather than hand-write that nested kind: "matrix" wire dict — easy to get subtly wrong — chain the fluent, typed catalogue() builder, which emits a MatrixSnapshot ready to hand to an adapter's seeder:

from archenstack_rbac import catalogue, F, P, V, N

snapshot = (
catalogue(fallback=N, 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("manager", "Manager", group="operations")
.role("staff", "Staff", group="operations")
.alias_role("supervisor", "manager", label="Supervisor", group="operations")
.feature("rbac.manage", "Manage access matrix", group="administration",
defaults={"administrator": F}, write_hint=F)
.feature("records.view", "View records", group="operations",
defaults={"administrator": F, "manager": F, "staff": V})
.feature("records.edit", "Edit records", group="operations",
defaults={"administrator": F, "manager": P, "staff": P}, write_hint=P)
.build()
)

snapshot.decide("rbac.manage", "administrator").level.name # 'FULL'
snapshot.decide("records.view", "supervisor").level.name # 'FULL' (alias → manager)
snapshot.decide("records.view", "ghost").level.name # 'NONE' (unknown pair, fail closed)

wire = snapshot.to_snapshot() # the kind: "matrix" dict an adapter persists and serves

Every method returns self, so a catalogue reads top-to-bottom the way it's authored. order fields default to declaration order (pass an explicit order to override), and level values accept an AccessLevel, its int (0–3), or its case-insensitive name ("full") — bool is rejected, as everywhere.

CallDeclares
catalogue(fallback=N, default_partial_scope=None)start a builder (or construct SnapshotBuilder(...) directly)
.group(slug, label="", *, order=None)a display group — a grouping of roles, no authorization semantics
.role(slug, label="", *, group="", is_system=False, is_active=True, order=None)a standard column that carries per-feature defaults
.super_role(slug, label="", *, group="", is_system=True, …)a super role — always resolves FULL (the recovery escape hatch)
.alias_role(slug, target, *, label="", group="", …)an alias role — a single-hop mirror of a standard target
.feature(key, label="", *, group="", defaults={role: level}, partial_scope=None, write_hint=None)a feature row with seed-owned per-role defaults
.override(feature, role, level)seed an override row — fixtures only (a real baseline ships none)
.build() → MatrixSnapshotmaterialize; call the snapshot's own to_snapshot() for the kind: "matrix" wire dict
The builder never validates for you

build() assembles the shape but runs no well-formedness checks. Run validate on the emitted wire dict — validate(snapshot.to_snapshot()) returns [] when clean — for the full spec §14/§16 report before you seed.

Already have a flat Matrix?

Matrix.to_snapshot() lifts the ergonomic facade straight into a MatrixSnapshot, preserving every (feature, role) resolution. The facade carries no display groups or write scopes, though, so those come across empty — reach for catalogue() when you need a full catalogue rather than a bare grid.

Notes​

  • Pure Python, no runtime dependencies. Bring your own storage, cache, and HTTP layer.
  • Fully typed. Ships type hints and a py.typed marker.
  • Python 3.9+.
  • Published to Archenstack's GitLab registry (not PyPI yet). Install by name once your index points at the registry — see Installation.
  • Sibling implementations exist. The Django adapter persists and serves this core over HTTP; sibling cores in Node.js, Java, Go, and Rust — plus the TypeScript web client — ship a matching resolving engine, so the same matrix model backs services and clients across stacks.

Releasing​

Releases publish to Archenstack's GitLab Package Registry from CI. Bump version in pyproject.toml, then push a matching tag — archenstack-rbac-python/vX.Y.Z — and the pipeline builds the sdist + wheel (via Hatchling) and uploads them; consumers then pip install archenstack-rbac as in Installation.

The distribution name is archenstack-rbac (what pip install sees); the import package stays archenstack_rbac. Going public later means pointing the same release at PyPI and dropping the private index — no code or coordinate change.

See also​