Skip to main content

Object scopes & departments

A PARTIAL cell means "you can write, but only some objects." A scope decides which objects — a small expression over named atoms that the server evaluates against the caller and the object. This guide covers the built-in own_record and own_assignment, the opt-in own_department and own_subtree, exactly what each one reads, how to narrow a whole queryset with them, and how to add your own atom.

For the concept in brief, see Resolution, scopes & the authorizer; this is the hands-on developer guide.

How a scope is evaluated​

An object-level check (POST /check/ with an object) resolves like this:

  1. Resolve the caller's (role, feature) level.
  2. FULL → allowed (unscoped). NONE/VIEW → denied (not a write).
  3. PARTIAL → evaluate the cell's scope against a (subject, object) pair:
    • subject = attributes of the authenticated caller (their pk, their department, …), supplied by the adapter;
    • object = the attribute dict you send in the request.

Each atom in the scope is an app-supplied predicate — the server owns what it means, and a client can never evaluate it. Evaluation is fail-closed: an atom the server doesn't recognize denies.

own_record — built in, on by default​

This is the one domain-neutral atom: "the object belongs to you." It compares the caller's pk against the object's owner fields, and it ships on in every adapter.

Owner fields are configurable (the object may carry any of them, or the raw <field>_id):

# settings.py — these are the defaults
ARCHENSTACK_RBAC = {
"SCOPE_OWNER_FIELDS": ["owner", "created_by", "user"],
}

So the object you send to /check/ must carry one of those owner attributes:

{ "feature": "records.edit", "object": { "id": 42, "owner": 7 } }

own_assignment — built in, on by default​

The self-service atom: "the row belongs to you by identity." Where own_record keys on a configurable owner field of an app record, own_assignment keys on the caller's own identity via fixed, conventional fields — so a PARTIAL holder may act only on rows that are theirs: their own role assignment, their own membership, a task assigned to them. It needs no configuration and, like own_record, ships on in every adapter.

It handles both a single assignee and a multi-assignee collection. The singular fields subject / assignee hold one identity; the plural fields subjects / assignees hold a collection, and the caller matches when they are a member of it (a task shared across a team, a document assigned to several people). A singular field holding a list is honoured too.

// single assignee
{ "feature": "assignments.edit", "object": { "id": 9, "assignee": "sub-me" } }

// multi-assignee — matches if you are in the set
{ "feature": "tasks.edit", "object": { "id": 4, "assignees": ["sub-you", "sub-me"] } }

On the query side, the Django to_filter / Java WriteScope narrowing follows suit: a plural field maps to the collection membership (an M2M / @ElementCollection), so a write-eligible queryset includes the rows you share. An M2M join can repeat a row, so call .distinct() (Django) when you materialise it.

own_department — opt-in​

own_department means "the object is in your department." It's off by default, on purpose: it assumes your domain has a department concept, and plenty of apps don't. You turn it on once your model actually has departments.

It reads two things:

  • the object's department, via a configurable FK field; and
  • the subject's department, via a configurable (dotted) attribute path on the authenticated caller.

Enable it in Django​

# settings.py
ARCHENSTACK_RBAC = {
"SCOPE_INCLUDE_DEPARTMENT": True, # (1) turn the atom on
"SCOPE_DEPARTMENT_FIELD": "department", # (2) the FK on the OBJECT
"SCOPE_SUBJECT_DEPARTMENT_ATTR": "profile.department", # (3) path on the CALLER
}
  1. own_department now appears in the scope dropdown and resolves in /check/.
  2. The object matches when its department (or department_id) equals the caller's.
  3. The caller's department is read by walking SCOPE_SUBJECT_DEPARTMENT_ATTR on the authenticated user (here user.profile.department).

Enable it in Java / Spring​

The Spring starter ships the exact same opt-in — flip one property and own_department joins the served scope pack (both the resolver and the editor's scope dropdown):

archenstack-rbac:
scope-include-department: true # turn the atom on (off by default)
scope-department-field: department # the FK on the OBJECT
scope-subject-department-attr: department # the attribute on the CALLER's subject

(or the ARCHENSTACK_RBAC_SCOPE_INCLUDE_DEPARTMENT env var). The caller's department comes from whatever your RbacSubjectResolver puts on the subject; the object carries department in the /check/ body. As always, own_record stays on; own_department is added only when you ask for it.

Using it​

Assign the scope to a feature (in the matrix editor, or a seed), and a PARTIAL holder can now edit only rows in their own department. The client sends the attribute the scope reads:

{ "feature": "records.edit", "object": { "id": 42, "department": 3 } }

own_subtree — opt-in, and transitive​

own_department is flat equality: your department, nothing else. own_subtree is the chain-of-command atom — "the object is in your unit, or in any unit below it." A ministry officer writes the ministry's records and every county and district beneath it; a county officer writes their county and its districts, but never up the chain and never a sibling county.

Archenstack stores no hierarchy of its own, so the traversal stays yours — however you model the tree (adjacency list + recursive CTE, closure table, materialized path). You hand the atom one callable:

# settings.py
ARCHENSTACK_RBAC = {
"SCOPE_INCLUDE_SUBTREE": True, # (1) turn the atom on
"SCOPE_SUBTREE_FIELD": "org_unit", # (2) the unit FK on the OBJECT
"SCOPE_SUBTREE_RESOLVER": "myapp.rbac.resolve_subtree", # (3) YOUR traversal
}
# myapp/rbac.py
def resolve_subtree(subject):
"""The unit pks at or beneath the caller's own unit. Empty ⇒ deny."""
unit = getattr(subject, "org_unit", None)
return unit.descendant_ids(include_self=True) if unit is not None else []
  1. own_subtree joins the served pack and the scope dropdown.
  2. The object matches when its org_unit (or org_unit_id) is in the caller's subtree.
  3. Your callable returns the subtree — Archenstack never walks a tree it doesn't own.

Both halves of the atom read that one resolver, so a single-object /check/ and a bulk write-eligible queryset can never disagree:

{ "feature": "records.edit", "object": { "id": 42, "org_unit": 7 } }
Fail-closed, and PARTIAL-only

No configured resolver, a subject with no unit, an empty result, or an object with no unit all resolve to no match — the atom can only ever narrow a PARTIAL write, never widen one. FULL bypasses scopes entirely, so it does not constrain a FULL holder. And because the /check/ object is caller-asserted, re-fetch the object server-side by id before trusting its position in the tree — otherwise the atom is an advisory UI hint. See Hierarchical organizations.

The frontend side​

An object check is only as good as the attributes you send. The object dict must carry every attribute the feature's scope reads — own_record needs the owner, own_department needs the department. Send the whole shape:

import { useCanObject } from "@archenstack/rbac-web/react";

<CanObject feature="records.edit" object={{ id: row.id, owner: row.owner_id, department: row.department_id }}>
<EditButton row={row} />
</CanObject>

Send too little and the server (correctly) fails closed, hiding the control from a user who should have it. See Checking permissions in your own UI.

Bulk write-scoping — one query, not a loop​

ScopeAuthorizer.require answers "may this caller write this row?" one object at a time. To narrow a list — a bulk edit, a "select all editable" — to the rows the caller may write, translate the same scope into a query. FULL selects every row, PARTIAL applies the scope predicate, below PARTIAL selects none — the exact ladder the object authorizer uses, so the two never disagree.

from archenstack_rbac_django.permissions import MatrixQuerysetMixin

class DocumentViewSet(MatrixQuerysetMixin, ...):
rbac_feature = "records.edit"
# rows this caller may WRITE (FULL → all, PARTIAL → scoped, below → none)
def perform_bulk(self):
for doc in self.get_write_eligible_queryset():
...

# or directly:
evaluator.to_filter(subject, decision.scope, model=Document) # a Q
This narrows writes, never reads

to_filter / WriteScope select the rows a caller may write. Reads are out of the core (see the rule below) — never use either to filter what a user may see. A custom host atom translates to SQL when you register its query half — a ScopeAtomSqlTranslator bean (Java) or a ScopeAtom with a to_q (Django); one without it selects nothing here (the safe direction), so register the translator or compose its criteria yourself.

Writing your own atom (advanced)​

An atom is just a named predicate, so you can add domain-specific ones — own_region, own_tenant, assigned_to_me. In Django, a ScopeAtom bundles the object predicate and a queryset Q builder, so the same rule filters one object or a whole write-eligible list:

from django.db.models import Q
from archenstack_rbac_django.scope import ScopeAtom, ScopeEvaluator, DEFAULT_ATOMS

own_region = ScopeAtom(
"own_region", "Own region",
predicate=lambda ev, subject, obj, args: getattr(obj, "region_id", None) == getattr(subject, "region_id", None),
to_q=lambda ev, subject, args, model: Q(region_id=getattr(subject, "region_id", None)),
)

evaluator = ScopeEvaluator(atoms={**DEFAULT_ATOMS, own_region.name: own_region})
evaluator.object_matches(subject, obj, decision) # one object
evaluator.to_filter(subject, decision.scope, model=Record) # a write-eligible queryset (never for reads!)

Registering an atom is the single source of truth for both the predicate and the scope-picker dropdown, so the two can never drift. The wire only ever carries the atom's name; its meaning lives entirely on the server.

Every adapter has this extension point, so a custom atom is not a Django-only capability — the form above is the same in each, under that language's type:

AdapterRegister a host atom via
DjangoScopeAtom(name, label, predicate, to_q) — the example above
Java / Springa ScopeAtom bean with an AtomPredicate (which receives the atom's args)
Nodea ScopePredicate passed as scopePredicate to the adapter
Goan adapter.ScopePredicate on the server Config
Rusta ScopePredicate via WebConfig::with_scope_predicate

In every case the predicate receives the atom's args, the shipped pack still owns own_record / own_assignment / own_department / own_subtree, and an atom the pack does not recognise falls through to your predicate — else fails closed.

Two rules that never bend
  • Reads are never scoped. Scopes narrow writes only. Filtering what a user may see is your queryset's job (use to_filter for write-eligibility, never to restrict a read).
  • Unknown atoms deny. An atom the server hasn't registered evaluates to false — a typo or a scope from a newer matrix can only ever remove access.
A granted scope must name a registered atom — checked at seed time

Because an unknown atom denies, a catalogue that grants a scope over an atom the adapter cannot resolve (say own_subtree while the subtree pack is off) used to seed quietly and then deny at runtime — a production-only mystery. As of 2.4.0 that mismatch is caught up front: Django and Java refuse to seed, naming the atom and the fix; Node, Go and Rust warn loudly at startup and keep running (their snapshot may be forward-compat with a newer wire version, and the runtime already fails such a grant closed). Wire the atom (turn on the built-in pack, or register your own) — or drop the scope.

Enforcement mode​

Enforcement mode is the library-wide switch for what a denial does. In the default enforce mode a denied call is blocked — the authorizer throws (403) and a check returns "not allowed". In shadow mode a would-be denial is instead logged and allowed through (the request proceeds as if permitted), and the decision itself is unchanged — only the blocking is suppressed.

Shadow exists for one job: turning Archenstack on over an existing, live app that already has its own ad-hoc checks, where a not-yet-correct matrix would otherwise wrongly deny real traffic. Run in shadow, watch the logs for the writes it would have blocked, correct the matrix (or backfill the missing role assignments), then flip to enforce with confidence. Set it with archenstack-rbac.enforcement-mode=shadow (Java), ARCHENSTACK_RBAC["ENFORCEMENT_MODE"]="shadow" (Django), { enforcementMode: "shadow" } on createScopeAuthorizer (Node), Config.EnforcementMode="shadow" (Go), or WebConfig::with_enforcement_mode(EnforcementMode::Shadow) (Rust).

Shadow applies to both layers, so you can stage a whole rollout: the object authorizer (ScopeAuthorizer.require) and the coarse feature check — Java's @Can and Django's MatrixPermission. The one carve-out (the single exception to the rule): the policy-admin feature rbac.manage is never shadowed, because shadowing the check that protects the matrix itself would defeat the rollout it exists to make safe. Shadow also never loosens Archenstack's own management endpoints.

See also​