Skip to main content

Archenstack — Normative Specification

  • Spec version: 0.6.0
  • Wire version: 1
  • Status: Normative. This document is the single source of truth every implementation MUST satisfy — the Python, Node, Go, Rust and Java cores, the Django adapter, the TypeScript client, and any future language.
  • License: All rights reserved. License TBD.

The key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT, MAY, and OPTIONAL in this document are to be interpreted as described in RFC 2119 / RFC 8174.

Where this prose and the machine-readable artefacts in schema/, vectors/, and wire-golden/ disagree, this document governs the intended contract and the artefact is a bug to be fixed. Implementations MUST pass every conformance vector and reproduce every wire-golden byte-for-byte (see the README).


1. Overview & scope​

Archenstack is a role-based access-control model expressed as a matrix: a grid of feature × role cells, each holding an ordered access level from NONE to FULL. On top of the grid sit a small number of resolution rules (superusers, aliases, overrides) and an OPTIONAL write scope that narrows a PARTIAL write to a caller-owned subset of objects.

The core answers exactly one question: "given a role and a feature, what is the effective access level, and — if that level is PARTIAL — what scope constrains a write?" Everything else (storage, caching, transport, HTTP, authentication, object filtering) is an adapter concern outside the core.

1.1 What the core covers​

  • The AccessLevel scale and its ordering.
  • The shape of a matrix snapshot (roles, groups, features, defaults, overrides, aliases, superusers, default_partial_scope).
  • The resolution algorithm that maps (role, feature) to an effective level and an OPTIONAL scope.
  • The ScopeExpr grammar and its pure evaluator eval_scope.
  • The write-scope binding rule (scope constrains writes only).
  • Override delta semantics.
  • The lock-out invariant (check_no_lockout).
  • Canonical JSON, the wire envelope, the error shape, slug rules, and the ErrorCode enumeration.

1.2 What the core does NOT cover (v1)​

  • Read filtering. The core authorizes reads at the feature level only (level >= VIEW). Object-level and list-level read filtering — deciding which rows a VIEW/PARTIAL caller sees — is an app/adapter queryset concern and is explicitly out of core for v1 (see §9).
  • Object-predicate evaluation. Whether a specific object is "own record" or "own department" comes from an app-supplied predicate (the adapter), never by the core and never on the wire (see §8.4).
  • Authentication, identity, sessions, transport, storage, caching.

1.3 Terminology​

TermMeaning
FeatureA unit of protected functionality, addressed by a dotted key (e.g. reports.export). A matrix row.
RoleA named principal class, addressed by a slug (e.g. director). A matrix column (unless super/alias).
CellThe (feature, role) intersection; holds an integer AccessLevel.
DefaultThe catalogue/seed level for a cell, compiled into the snapshot. Not editable at runtime.
OverrideA persisted runtime edit of a cell; the sole editable layer (see §10).
ScopeA ScopeExpr that narrows a PARTIAL write to owned objects.
SnapshotThe full serialized matrix (kind: "matrix"), loaded whole (see §15, §18).
AdapterHost-language glue: storage, HTTP, and the object-ownership predicate.

2. Versioning contract (READ THIS FIRST)​

Every wire payload carries an integer wire_version (§15). Version 1 is the first published version.

2.1 Client-side resolution is allowed​

The resolution algorithm (§7) is deliberately simple and total so that it MAY run on the client (e.g. the TypeScript implementation ships a real resolving engine, not just a thin display layer). A client that has a matrix snapshot MAY compute effective levels locally without a server round-trip.

2.2 Resolution semantics are pinned to the wire MAJOR version​

Because clients resolve locally, the resolution semantics are part of the wire contract. A server and a client that disagree on how a snapshot resolves would silently reach different access decisions.

Therefore:

Any change to resolution semantics is BREAKING and MUST bump wire_version.

"Resolution semantics" includes, without limitation:

  • The role hierarchy / precedence order (super → alias → override → default → fallback, §7).
  • The meaning or precedence of explicit deny, superusers, or aliases.
  • The ScopeExpr grammar, eval_scope edge identities, or fail-closed rule (§8).
  • Whether a scoped read changes a decision (it does not, in v1 — moving read scoping into the core would be such a change).
  • The canonical-JSON algorithm (§13), the wire envelope (§15), or the AccessLevel integer mapping (§3).

Such changes MUST NOT be shipped under wire_version: 1. They require a new MAJOR wire version and a migration note in changelog.

2.3 What MAY change additively within wire_version: 1​

Additive changes that cannot alter the decision a v1 resolver reaches for an existing snapshot:

  • Adding new roles, features, groups, or overrides to a snapshot.
  • Adding new OPTIONAL fields that a v1 reader ignores, PROVIDED a v1 reader that ignores them still resolves identically (e.g. the reserved per-cell scope slot in §5.4, or new UI-hint metadata).
  • Adding new ErrorCode members used only in error payloads (a reader that does not recognize a code MUST treat it as a generic failure).
  • Adding a new envelope kind that a client only receives in response to a request it opted into (e.g. policy-batch, §15.1) — a client that never sends the new request never sees the new kind, so old readers resolve identically.

An implementation MUST reject a payload whose wire_version it does not support rather than best-effort parse it.


3. AccessLevel​

AccessLevel is a frozen, closed, ordered enumeration. On the wire it is always an integer.

NameIntegerMeaning
NONE0No access.
VIEW1Read only.
PARTIAL2Write, but scoped (see §8).
FULL3Unrestricted read + write.

Rules:

  • The set is closed. No implementation MAY define levels outside 0..3 under wire_version: 1.
  • Levels are totally ordered by their integer value. All intent is expressed by comparison:
    • can_read ⇔ level >= VIEW (i.e. >= 1).
    • can_write ⇔ level >= PARTIAL (i.e. >= 2).
    • is_full ⇔ level == FULL.
  • A cell value MUST serialize as the bare integer 0, 1, 2, or 3 — never a float, string, or boolean.
  • An unknown or absent (feature, role) cell resolves to the matrix fallback, which is NONE unless the snapshot declares otherwise (§5.5).

3.1 Functional (action) permissions (NON-NORMATIVE)​

The graded scale also expresses functional / action permissions — "Send email", "View settings page" — which are not CRUD on a resource but a single capability a caller either has or not. Model such a feature as an ordinary matrix row and treat authorization as a threshold on the resolved level: the action is permitted when level >= grant, where grant is the minimum level you assign it — typically FULL for a "do" action, or VIEW for a "may see" action. Cells for an action feature are conventionally set to NONE (0) or the grant level; intermediate values simply resolve below or at the threshold.

This is an idiom, not new wire surface — nothing about the enum, the resolver, or the schema changes. Implementations MAY offer a convenience such as allows_action(decision, grant=FULL) (a named level >= grant), but a caller is free to write the comparison directly.


4. The matrix snapshot — top-level shape​

A matrix snapshot is a wire payload with kind: "matrix". Its logical shape (field names are normative; see schema/ for the machine-readable JSON Schema):

matrix := {
wire_version: 1,
kind: "matrix",
fallback: int, // AccessLevel; default 0 (NONE) if omitted
default_partial_scope: ScopeExpr | null,
groups: Group[],
roles: Role[],
features: Feature[],
overrides: Override[] // the sole editable layer (§10)
// defaults are carried INSIDE each Feature (§5.3); they are seed-owned (§11)
}

Ordering of the arrays is presentation metadata; resolution MUST NOT depend on array order. (Canonical serialization does impose an ordering — see §13.)

4.1 Group​

A group is a display bucket for roles (columns) and MAY be referenced by features for row grouping. Groups carry no authorization semantics.

Group := {
slug: string, // slug rules, §14
label: string,
order: int
}

4.2 Role​

Role := {
slug: string, // slug rules, §14
label: string,
group: string, // Group.slug, or ""
kind: "standard" | "super" | "alias",
alias_target: string | null, // REQUIRED iff kind == "alias"; else null
is_system: boolean, // built-in; non-deletable, non-deactivatable (§12)
is_active: boolean,
order: int
}
  • kind: "standard" — an ordinary matrix column. Its cells come from defaults and overrides.
  • kind: "super" — a superuser. Always resolves to FULL for every feature, with scope = null. A super role is never stored in the grid and its cells (if any appear) MUST be ignored. A super role MUST have alias_target == null and MUST NOT be the target of any alias (§7.3 invariant).
  • kind: "alias" — a mirror of another role. alias_target names the role it resolves as. Aliases are single-hop and non-transitive: the target MUST be kind: "standard" (see §7.3). Aliases are not columns; author cells on the target.

4.3 Feature​

Feature := {
key: string, // feature-key rules, §14
label: string,
group: string, // Group.slug for row grouping, or ""
defaults: { role_slug: int }, // seed defaults per role (§5.3)
partial_scope: ScopeExpr | null, // per-feature scope override (§8.3)
write_hint: int | null, // NON-AUTHORITATIVE UI hint only (§12.3)
cell_scope: null // RESERVED per-cell scope slot (§5.4); MUST be null in v1
}

4.4 Override​

Override := {
feature: string, // Feature.key
role: string, // Role.slug, kind == "standard"
level: int // AccessLevel
}

An override MUST reference a declared feature and a standard role. An override that references an undeclared feature is ErrorCode.unknown_feature; one that references an undeclared role is ErrorCode.unknown_role; one that references a declared but super- or alias-kind role is ErrorCode.validation (see the mapping in §7.3.1). Two overrides on the same (feature, role) are a ErrorCode.duplicate_key. Override delta semantics are defined in §10.

4.5 default_partial_scope​

The snapshot-wide fallback scope applied to a PARTIAL cell when the feature itself declares no partial_scope. MAY be null (meaning: a PARTIAL write is scoped by nothing at the core level, i.e. the adapter receives a null scope and decides its own policy). A representative value:

{"any_of": [{"atom": "own_department"}, {"atom": "own_record"}]}

5. Defaults, cells, and reserved slots​

5.1 A cell is a plain integer level​

Grid cells are plain integers 0..3. Scope does not live in a cell in v1; it is bound at the feature level (§8.3). This keeps the grid a dense integer matrix suitable for spreadsheet-style editing.

5.2 Effective cell resolution​

The effective level of (feature, role) is, in order: override, else default, else fallback — subject to the super/alias rules of §7. This is specified precisely in §7.

5.3 Defaults are carried inside each Feature​

A feature's defaults map holds { role_slug: level } for standard roles. A role absent from the map takes the matrix fallback (§5.5). Defaults are seed-owned and compiled into the snapshot; they are NOT a persisted, runtime-editable table (§11).

5.4 Reserved: per-cell scope (cell_scope)​

Per-cell scope granularity is RESERVED, not built in v1. The wire slot Feature.cell_scope exists to keep the format forward-compatible and MUST be null under wire_version: 1. A v1 reader MUST ignore it (treating a non-null value as it would any unknown data is NOT permitted — v1 producers MUST emit null). A stored snapshot whose Feature.cell_scope is non-null MUST be rejected by validate with ErrorCode.validation. Introducing per-cell scope resolution is a resolution-semantics change and therefore a MAJOR bump (§2.2).

5.5 Fallback​

The matrix fallback (top-level, §4) is the level returned for any (feature, role) with neither an override nor a default. It defaults to NONE (0). Implementations SHOULD keep it NONE; a non-NONE fallback is a fail-open posture and is discouraged.


6. AccessLevel scope binding — writes only (summary)​

Scope constrains WRITES only. A scope is consulted only when a caller's effective level is exactly PARTIAL and the operation is a write whose per-call minimum_write is PARTIAL. VIEW (read) and FULL (unrestricted) are never scoped by the core.

The full binding rule is §8.3. The honest boundary on reads is §9.


7. Resolution algorithm (NORMATIVE, exact)​

Given a matrix M, a role slug R, and a feature key Fe, resolve(M, R, Fe) returns { level: AccessLevel, scope: ScopeExpr | null }.

The steps MUST be evaluated in exactly this order. Note especially that the super check is performed on the ORIGINAL role, BEFORE any alias resolution, so an alias can never demote a superuser.

7.1 Precedence (canonical)​

resolve(M, R, Fe):
role := M.roles[R]
if role is undefined:
# Unknown role: fail closed.
return { level: NONE, scope: null }

# (1) SUPER — checked on the ORIGINAL role, before alias resolution.
if role.kind == "super":
return { level: FULL, scope: null }

# (2) ALIAS — single hop to a standard target.
lookup_role := R
if role.kind == "alias":
target := role.alias_target
# Validator guarantees target exists and is kind=="standard"
# (never alias, never super). If violated, fail closed.
if target is undefined
or M.roles[target] is undefined
or M.roles[target].kind != "standard":
return { level: NONE, scope: null }
lookup_role := target

feature := M.features[Fe]
if feature is undefined:
# Unknown feature: fail closed.
return { level: NONE, scope: null }

# (3) EFFECTIVE LEVEL = override ?? default ?? fallback
level := override_level(M, Fe, lookup_role) # may be undefined
?? feature.defaults[lookup_role] # may be undefined
?? M.fallback # defaults to NONE

# (4) SCOPE — only meaningful when level == PARTIAL
if level == PARTIAL:
scope := feature.partial_scope ?? M.default_partial_scope # may be null
else:
scope := null

return { level: level, scope: scope }

Where override_level(M, Fe, role) returns the level of the unique override matching (Fe, role) if one exists, else undefined. There is at most one override per (feature, role) (duplicate ⇒ ErrorCode.duplicate_key).

7.2 Notes​

  • The lookup for step (3) always uses lookup_role — the alias target for an alias, otherwise R itself.
  • ?? is null/undefined-coalescing: the first defined value wins. A default of NONE (0) is a defined value and does NOT fall through to fallback.
  • A super role short-circuits at step (1); its defaults/overrides (if any) are irrelevant and MUST NOT be consulted.
  • Resolution is total: it returns a result for every input and never raises. Unknown role, unknown feature, and malformed alias all fail closed (NONE, scope: null).
  • resolve does NOT consult is_active. A deactivated role (is_active == false) still resolves to its effective grid level exactly as an active role would; deactivation never changes the {level, scope} a role resolves to. is_active affects only the lock-out invariant (§12) and role assignment, both of which are outside resolve.
  • resolve is unchanged under multi-org tenancy (§Organizations). Its signature is still resolve(M, R, Fe) over a single matrix M. The organization is not an argument to resolve and is never part of the matrix body — it only selects which org's snapshot M the caller loads before calling resolve (M := provider.get_snapshot(org)). Every org owns exactly one snapshot, so isolation is a property of snapshot selection, not of the resolver; the kernel, Cell = (feature, role), and canonical JSON are byte-for-byte identical to the single-org case.

7.3 INVARIANT — super is never an alias source or target​

A validator MUST enforce, and a producer MUST guarantee:

A super-kind role MUST NOT be an alias alias_target, and MUST NOT itself carry kind == "alias". An alias_target MUST reference a standard role.

Consequences:

  • An alias can never resolve to a superuser (so aliasing can never escalate to super by indirection), and a super can never be re-pointed through an alias (so aliasing can never demote a superuser).
  • Alias chains are impossible: the target is always standard, so resolution is strictly single-hop and terminating.

A snapshot violating this invariant MUST be rejected at validation. The exact ErrorCode depends on the specific violation and is given normatively in §7.3.1: a non-standard alias target, or a super carrying an alias_target, is ErrorCode.validation; an alias_target that names an undeclared role is ErrorCode.unknown_role (a referential-integrity failure). A conformance vector MUST exercise exactly these cases (an alias whose target is a super role, and a super role marked as an alias) and assert rejection. Additionally, a positive vector MUST show that a super role resolves to FULL even when an (invalidly authored, or dynamically attempted) alias points at it is refused — i.e. the super grant is never demoted.

7.3.1 Alias / super / override validation → ErrorCode (NORMATIVE)​

validate MUST return exactly the following ErrorCode for each alias/super/override consistency violation. This table is normative and MUST agree with the conformance vectors (a spec-faithful validator returns the same code the vectors assert):

ViolationErrorCode
alias_target names a role not declared in the snapshot (dangling reference)unknown_role
alias_target names a non-standard role (a super- or alias-kind role)validation
A super-kind role carries a non-null alias_targetvalidation
A role with kind == "alias" has a null or missing alias_targetvalidation
An overrides[] entry references a super- or alias-kind role (§4.4)validation

Rationale: a dangling reference is a referential-integrity failure — the named role does not exist — so it surfaces as unknown_role, exactly as an override that names an undeclared role does (§16). Every other case is a consistency failure over roles that do exist, and surfaces as the catch-all validation.


8. ScopeExpr grammar & eval_scope​

8.1 Grammar (snake_case wire form)​

A ScopeExpr is a JSON object of exactly one of these shapes:

ScopeExpr :=
{ "const": boolean } // literal true/false
| { "atom": string, "args"?: object } // an app predicate
| { "any_of": ScopeExpr[] } // logical OR
| { "all_of": ScopeExpr[] } // logical AND
  • Exactly one of the keys const, atom, any_of, all_of MUST be present. An object with zero or multiple of these keys is invalid (ErrorCode.unknown_scope).
  • args is RESERVED NOW. The OPTIONAL args object on an atom is part of the v1 wire type: producers MAY emit it and the wire/schema MUST permit it. A v1 evaluator MAY ignore args entirely (treating {atom:"x"} and {atom:"x", args:{...}} identically) — but MUST NOT reject a payload for carrying args. Assigning meaning to args is a future, additive-only step only if it does not change decisions for args-free snapshots.
  • There is no not in v1. Negation is deferred (§17); adding it is a MAJOR bump.

8.2 eval_scope — pure recursive tree-walk​

eval_scope(expr, predicate) returns a boolean. predicate(atom, args) is the app-supplied function that decides whether the named atom holds for the current subject/object (§8.4). eval_scope itself is pure: it performs no I/O and depends only on expr and predicate.

eval_scope(expr, predicate):
if expr has key "const":
return expr.const == true # coerce to strict boolean

if expr has key "atom":
name := expr.atom
args := expr.args if present else {} # {} when omitted
if name is not a recognized atom:
return false # FAIL CLOSED (unknown atom)
return predicate(name, args) == true

if expr has key "any_of":
for child in expr.any_of: # empty => loop body never runs
if eval_scope(child, predicate) == true:
return true
return false # EMPTY any_of => false

if expr has key "all_of":
for child in expr.all_of: # empty => loop body never runs
if eval_scope(child, predicate) == false:
return false
return true # EMPTY all_of => true

# Malformed / unrecognized node:
return false # FAIL CLOSED

8.3 Edge identities & fail-closed (NORMATIVE)​

  • Empty any_of → false (the identity of OR).
  • Empty all_of → true (the identity of AND).
  • Unknown / unrecognized atom → false (fail closed).
  • Missing / malformed node (no recognized key, or multiple keys) → evaluation is false; validation of a stored snapshot SHOULD reject it as ErrorCode.unknown_scope, but any evaluator that encounters one at runtime MUST fail closed.
  • const MUST be a JSON boolean; a non-boolean is invalid (ErrorCode.unknown_scope) and fails closed at eval time.

Fail-closed means: when in doubt, deny. A scope that cannot be understood MUST NOT grant a write.

8.4 The atom→object predicate is app-supplied​

An atom names a predicate the application knows how to evaluate against a concrete object and subject — e.g. own_department, own_record, own_team, own_region. The mapping from atom name (and OPTIONAL args) to a boolean is supplied by the adapter and is:

  • never on the wire (the snapshot carries only atom names, never their implementation), and
  • never in the core (eval_scope receives predicate as a parameter).

Reference example of an adapter predicate (host app, not core): "an object is own_department if its department_id — directly or via its parent — equals the subject's department_id; it is own_record if any known ownership foreign key on the object points at the subject." The core neither knows nor cares how this is computed; it only calls predicate("own_department", {}).

The own_* atom names above are an OPTIONAL reference pack, not a normative set — an atom name means only what a host's registered predicate makes it mean. Adapters SHOULD keep their built-in defaults domain-neutral: the reference adapters ship own_record on by default and treat own_department as an opt-in example, since not every app has a "department". A registered atom is the single source for both the object predicate and the write filter; an atom name absent from the registry MUST resolve fail-closed (deny the object; select no rows).

8.5 Feature scope binding (writes only)​

The scope returned by resolve (§7 step 4) is consulted only for writes, and only when the effective level is exactly PARTIAL:

authorize_write(M, R, Fe, obj, subject, minimum_write, predicate):
{ level, scope } := resolve(M, R, Fe)
if level < minimum_write:
return DENY # insufficient level for this call
if level >= FULL:
return ALLOW # FULL is never scoped
# here level == PARTIAL and minimum_write == PARTIAL
if scope is null:
# No core scope; adapter policy decides (commonly: DENY object write,
# or defer to its own ownership rule). The core imposes nothing.
return DEFER_TO_ADAPTER
return ALLOW if eval_scope(scope, predicate_bound_to(obj, subject)) else DENY

Reads (minimum_write not applicable; the requirement is level >= VIEW) are never scoped by the core (§9).

8.6 Where the object comes from — advisory checks vs enforcement (NORMATIVE)​

authorize_write above is only as trustworthy as obj. Everything in this section turns on who supplied that object, and an implementation MUST keep the two cases apart.

Advisory. The caller-facing check endpoint (POST /permissions/check/, §15.1) takes its object from the request body. The caller therefore chooses the attributes the predicate reads, and can describe an object it does not own:

POST /permissions/check/ { "feature": "records.edit",
"object": { "owner": "<the caller's own subject>" } }
→ { "kind": "policy", "allowed": true }

That answer is correct — the described object would indeed be writable — and it is not authorization. Its purpose is to let a client decide what to render. Accordingly:

  • An implementation MUST NOT present the check endpoint as an enforcement mechanism, and its documentation MUST state that the object is caller-supplied.
  • A host MUST NOT authorize a mutation or a data load on the strength of a check response.

Enforcement. Authorization MUST re-evaluate the same scope against an object the server loaded from its own store, never one that arrived from the client. To make that the easy path rather than an exercise for the reader, an adapter that exposes the check endpoint MUST also expose a scope authorizer: a server-side API taking (caller, feature, host_loaded_object) and returning an allow/deny (or raising), evaluating the identical ScopeExpr through the identical atom predicates.

The authorizer and the endpoint MUST NOT diverge: both resolve (role, feature) through resolve (§7) and both evaluate scope through eval_scope (§8.2) with the adapter's registered atoms (§8.4). The only difference is the provenance of the object — and that difference is the whole security boundary.

An adapter shipping the endpoint without the authorizer leaves a host no supported way to enforce object-level access, which in practice means hosts enforce with the endpoint. See security model §2.6.


9. Read scoping is OUT OF CORE (honest boundary)​

The core authorizes reads at the feature level only: a caller may read a feature iff their effective level is >= VIEW. The core does NOT decide which objects or list rows a reader sees.

Object- and list-level read filtering — e.g. "a PARTIAL reader sees only their own department's rows" — is a legitimate application need, but in v1 it is an adapter/queryset concern, not a core responsibility. Accordingly, v1:

  • Does not include a view_scope field in the wire or the core.
  • Does not include a to_filter / queryset-projection operation in the core.
  • Binds ScopeExpr to writes only (§8.5).

Adapters that need read filtering implement it themselves (e.g. a Django get_queryset that narrows by department). This keeps the core's decisions total and side-effect-free. Moving read scoping into the core later is a resolution-semantics change and therefore a MAJOR wire bump (§2.2, §17).


10. Override delta semantics​

Overrides are the sole persisted, editable layer (§11). They are stored as a delta from the default, not as an absolute snapshot of the cell.

Rule for applying an edit that sets cell (Fe, role) to level L:

apply_override(M, Fe, role, L):
d := effective_default(M, Fe, role) # feature.defaults[role] ?? M.fallback
if L == d:
delete any override for (Fe, role) # setting to default CLEARS the override
else:
upsert override (Fe, role) = L

Consequences (all NORMATIVE):

  • Setting a cell to its current default clears the override. There is never a stored override whose level equals the current default. This is what powers a correct "reset to default" action and an accurate "overridden" badge: a cell is overridden iff an override row exists for it.
  • Reseeding defaults intentionally moves matching cells. Because an override is a delta, if a new catalogue seed changes a cell's default from d1 to d2, any cell that had no override tracks the new default (d2), and any cell whose override happened to equal the new default d2 is — on the next normalize — indistinguishable from "not overridden" and SHOULD be cleared. Producers MUST document that reseeding can shift the effective value of un-overridden cells; this is intended, not a bug.
  • The "overridden" flag surfaced in render models (e.g. a grid cell's overridden boolean) MUST be computed as "an override row exists for this (feature, role)", evaluated against the alias-resolved role for display consistency.

11. Defaults vs. overrides — ownership​

  • Defaults are catalogue/seed-owned. They are compiled into the snapshot from code/seed data (Feature.defaults, §5.3). They are NOT a persisted, runtime-editable table. To change a default, change the seed and re-emit the snapshot.
  • Overrides are the only persisted, runtime-editable layer. They are the delta on top of defaults (§10). All runtime matrix editing manipulates overrides.

This split is deliberate: the seed is the reproducible baseline (versioned with code), and overrides are the auditable, revertible operational adjustments.


12. Lock-out invariant — check_no_lockout​

A portable invariant that prevents the matrix from being edited into a state where nobody can administer it.

12.1 Definitions​

  • manage_feature — a designated "manage the matrix" feature. Its generic slug is rbac.manage. This is the feature that governs editing the matrix itself.
  • min_level — the level a role needs on manage_feature to administer the matrix: FULL. Global matrix edits require a global grant; PARTIAL is insufficient to manage the matrix.

12.2 The invariant​

After any change, there MUST remain at least one active, non-super role whose effective level on manage_feature is FULL.

check_no_lockout(M_after) MUST be evaluated before committing any of the following mutations, and the mutation MUST be rejected with ErrorCode.lockout if the resulting state would violate the invariant:

  • an override edit (including one that lowers a role's manage_feature level),
  • a role deactivation (is_active → false),
  • an alias edit (re-pointing or converting a role that was a manage_feature FULL holder),
  • a group delete (if it cascades to removing/deactivating its roles),
  • any other mutation that changes the set of manage_feature-FULL holders.
check_no_lockout(M):
holders := {
role in M.roles
where role.kind == "standard"
and role.is_active == true
and resolve(M, role.slug, manage_feature).level == FULL
}
return NOT empty(holders) # true == safe; false == would lock out

Note resolve is used, so the check honors overrides and defaults exactly as a live decision would. Super roles are excluded from holders by design (they are the escape hatch, not the guarantee).

12.3 Escape hatch & assumptions​

  • A super role always resolves to FULL on every feature (including manage_feature), independent of the grid, so a superuser can always recover a locked matrix. Super and built-in (is_system) roles are non-deactivatable and non-deletable — a mutation attempting to deactivate or delete one MUST be rejected (ErrorCode.immutable_field).
  • The invariant deliberately counts only non-super roles so that the operational (non-superuser) administration path can never be silently severed.
  • Assumption: the deployment has at least one active user holding a super role. check_no_lockout guarantees a non-super manage_feature-FULL holder exists; the super escape hatch is only useful if a human actually holds it. Deployments MUST ensure this out of band; the core cannot verify user assignments (they are outside the snapshot).
  • The invariant is PER ORGANIZATION (§Organizations). Because each org owns exactly one snapshot, check_no_lockout(M) runs on exactly one org's matrix and applies only to that org's mutations — no org's edit can affect another org's manage_feature-FULL holders. Every org MUST independently retain an active, non-super manage_feature-FULL holder (and, out of band, an active super), so security model's "≥1 active super per deployment" reads as "≥1 active super per org." Each org's seed/provisioning MUST establish this baseline; a root-org seed does not satisfy any other org.

13. Canonical JSON (wire-golden)​

To let a third, independent language reproduce byte-identical wire-golden fixtures, canonical serialization is specified exactly. A canonical JSON encoder MUST:

  1. Encoding. Emit UTF-8 bytes. No byte-order mark.

  2. Object key order. Sort each object's keys ascending by UTF-16 code unit (i.e. compare keys as UTF-16 code-unit sequences; the lexicographic order of their code-unit values). This is applied recursively to every object. Duplicate keys are forbidden (a producer MUST never emit them).

  3. Whitespace. No insignificant whitespace. Use compact separators: , between elements and : between key and value, with no spaces around either. No leading/trailing whitespace; no newlines.

  4. Integers. Emit integer AccessLevels and all integer fields as JSON integers — no decimal point, no exponent, no trailing zeros (e.g. 3, never 3.0 or 3e0). Negative zero MUST NOT appear (emit 0).

  5. Numbers generally. v1 wire values are integers, booleans, strings, null, arrays, and objects only. Non-integer numbers MUST NOT appear on the v1 wire.

  6. Strings. UTF-8 text. Escape only the characters JSON strictly requires, and escape each exactly one way:

    • " (U+0022) becomes \"
    • \ (U+005C) becomes \\
    • every control character in U+0000-U+001F becomes a lowercase six-character escape \u00XX (e.g. NUL becomes \u0000, tab becomes \u0009, newline becomes \u000a).

    Canonical form uses no two-character short escapes: do not emit \b, \f, \n, \r, or \t; the corresponding control characters MUST use their \u00XX form instead. Do not escape / (solidus). Every character >= U+0020 other than " and \ — including all non-ASCII printable text — is emitted as raw UTF-8, not escaped (no \uXXXX for code points at or above U+0020; no surrogate-pair escaping). In particular, U+007F (DEL) — although a control character in Unicode — is >= U+0020 and therefore MUST be emitted as raw UTF-8, never escaped; only the C0 controls U+0000-U+001F are escaped. Hex digits in a \u00XX escape are lowercase (a-f).

  7. Booleans / null. true, false, null lowercase literals.

  8. Arrays. Element order is preserved as given by the model (arrays are not reordered — only object keys are). Producers are responsible for emitting arrays in a deterministic order (see §4 / §13.1).

13.1 Deterministic array ordering (producer responsibility)​

Canonical JSON does not reorder arrays, so producers MUST emit snapshot arrays in a stable, reproducible order to match wire-golden:

  • groups, roles, features: ascending by (order, slug/key) — order first, then the slug/key as a UTF-16 code-unit tiebreak.
  • overrides: ascending by (feature, role) as a UTF-16 code-unit compare.
  • defaults is an object, so its keys are sorted by rule (2) automatically.

13.2 Algorithm (reference)​

canonical(value):
if value is object:
keys := sort(value.keys, by UTF-16 code units, ascending)
return "{" + join(",", [ quote(k) + ":" + canonical(value[k]) for k in keys ]) + "}"
if value is array:
return "[" + join(",", [ canonical(e) for e in value ]) + "]"
if value is string: return quote(value) # per rule 6
if value is integer: return decimal_no_frac(value) # per rule 4
if value is boolean: return "true" | "false"
if value is null: return "null"

quote(s) wraps s in ", escaping per rule 6.


14. Slug & feature-key rules​

14.1 Role & group slugs​

  • Pattern: ^[a-z][a-z0-9_-]*$
  • Max length: 64 characters.
  • Lowercase ASCII; MUST start with a letter; may contain digits, underscore, and hyphen thereafter.
  • A slug violating this MUST be rejected with ErrorCode.invalid_slug.

14.2 Feature keys (dotted namespaces allowed)​

  • Pattern: ^[a-z][a-z0-9_]*(\.[a-z0-9_]+)*$
  • Max length: 128 characters.
  • A dotted namespace (e.g. reports.export, projects.tasks, rbac.manage) is a sequence of segments joined by .; the first segment MUST start with a letter; subsequent segments are [a-z0-9_]+. Hyphens are NOT allowed in feature keys (only underscores), unlike slugs.
  • A key violating this MUST be rejected with ErrorCode.invalid_slug.

14.3 Uniqueness is PER ORGANIZATION​

The slug/key grammar above is unchanged under multi-org tenancy (§Organizations) — org is a first-class dimension, never encoded as a slug or feature-key prefix. What changes is scope of uniqueness: role/group slugs and feature keys are unique per organization, not globally. Two organizations may each independently own a manager role or a reports.export feature; they never collide and never see each other, because each org compiles its own snapshot from its own rows. Cross-org references (an override, alias target, or group ref that would bridge two orgs) are structurally impossible in-resolution and MUST be rejected at the adapter/validator layer (unknown_org — unknown within this org's snapshot). This is an adapter-persistence invariant; the pure core still validates uniqueness per snapshot, which now means per org.


15. Wire envelope​

Every payload is a JSON object carrying:

  • wire_version: integer, starts at 1 (§2).
  • kind: string, one of: "matrix" | "me" | "policy" | "policy-batch" | "role" | "feature" | "group" | "overrides" | "members" | "apps" | "error".

The remaining fields depend on kind:

kindPayload carries
matrixThe full snapshot (§4).
meThe caller's role and their resolved permission map ({ feature: {level, can_read, can_write} }); OPTIONALLY an is_platform_admin boolean (§15.3).
policyA resolved policy view (levels per feature for a given role) — a resolution result, not the editable matrix.
policy-batchPositional allowed results for a BATCH of checks — results[i] ↔ the i-th request item; permissions carries each distinct feature's resolved cell once (§15.1).
roleA single Role (§4.2).
featureA single Feature (§4.3).
groupA single Group (§4.1).
overridesThe overrides layer alone (Override[], §4.4) — for persistence/round-trip.
membersOne org's member registry — the subject-picker source (results: [{subject, email, display, status}], §15.3).
appsOne org's registered OIDC clients (results: [{client_id, audience, label, redirect_uris, is_active}], §15.3).
errorThe error shape (§16 below).

A reader MUST reject a payload whose wire_version it does not support, and SHOULD reject a payload whose kind it does not recognize.

15.1 Batch check (policy-batch)​

The caller-facing check endpoint (POST /permissions/check/, whose single-item response is the policy envelope plus an allowed boolean) additionally accepts a BATCH form, so a client rendering a list of PARTIAL-scoped objects resolves every row in ONE round-trip instead of N. This is additive (§2.3): a client that never sends a batch never receives a policy-batch, so the single form is unchanged.

Request. The single form is { "feature": <key>, "object"?: <dict> }. The batch form is a checks array of those same items:

{ "checks": [ { "feature": <key>, "object"?: <dict> }, ... ] }

A body carrying checks is a batch; a body carrying feature is a single check; a body carrying BOTH or NEITHER is rejected with ErrorCode.validation.

object is caller-supplied, in the single form and every batch item alike, so allowed is ADVISORY (§8.6). It answers "would the object you described be writable?", not "may you write the row you are about to touch". Enforce with the adapter's scope authorizer against a server-loaded object; see §8.6 and security model §2.6.

Response — the policy-batch envelope:

{
"wire_version": 1,
"kind": "policy-batch",
"role": <slug>,
"permissions": { <feature>: { "level": <0..3>, "scope": <ScopeExpr|null> }, ... },
"results": [ <bool>, ... ]
}
  • results is positional: results[i] is the decision for checks[i], and results.length == checks.length. This ordering is the contract a client relies on to map a decision back to its row.
  • Each results[i] is computed EXACTLY as the single form's allowed: with an object, the object-level write check via eval_scope (§8); without one, feature-level read eligibility (level >= VIEW). Reads are never scope-filtered (§9).
  • permissions carries each DISTINCT feature's resolved { level, scope } once (the same shape as the policy envelope's permissions), so a same-feature list does not repeat the cell per row.

Per-item fail-closed vs. malformed. A checks item that is structurally malformed — not an object, missing/blank feature, or a non-object object — makes the WHOLE request fail with ErrorCode.validation (a client-contract violation, surfaced loudly). A structurally-valid item naming an unknown/undeclared feature resolves to level NONE, so results[i] == false — a per-item fail-closed deny, never a batch error (matching the single form). A caller with no assigned role gets the error envelope (not_found), as with the single form.

Bounded size. A server MUST bound the number of items it evaluates in one batch and MUST reject an over-limit batch with ErrorCode.validation naming the limit (the reference adapters default to 200, tunable via config — ARCHENSTACK_RBAC["CHECK_BATCH_MAX"] / archenstack-rbac.check-batch-max). An empty checks: [] is a valid no-op returning results: []. Bounding batch size keeps one request from resolving an unbounded amount of work.

15.2 Organizations (out-of-band snapshot-selection dimension)​

Added in spec 0.2.0; additive, wire_version stays 1.

One deployment MAY serve many organizations (tenants), each owning its own groups, roles, features, overrides, matrix version, and audit log — with no shared mutable state between orgs. An organization is identified by a slug that obeys the role/group slug grammar (§14.1).

Org is a persistence + routing + transport dimension, not a resolution input. It selects which MatrixSnapshot a caller loads and resolves; it is never an argument to resolve (§7) and never part of the canonical, byte-hashed matrix body (§4, §13). Because a MatrixSnapshot already is exactly one policy world, isolation falls out of selecting the right snapshot: the resolution kernel, Cell = (feature, role), and canonical JSON are byte-for-byte unchanged, and the entire wire_version: 1 conformance corpus stays valid (the existing vectors and wire-golden fixtures are declared to belong to an implicit root org).

Where org appears on the wire.

  • The matrix snapshot body carries NO org key. matrix.schema.json and wire-golden/matrix-snapshot.json are unchanged; a loaded snapshot is byte-identical whether or not the deployment is multi-org. Org is transport metadata, not snapshot content.
  • The resolved-view envelopes me / policy / policy-batch gain an OPTIONAL org field (the org slug; me.schema.json, policy.schema.json, policy-batch.schema.json). It is not in any required[]; omitted ⇒ treated as the root org by a legacy reader. Optional ⇒ additive per §2.3, so the existing org-less goldens stay valid and new org-bearing goldens round-trip alongside them.
  • Which org a request targets is resolved out-of-band — server-side from the authenticated principal's org claim (ambient; no client change), or, for a cross-org administrator, an X-Archenstack-Org transport header. It is not a /orgs/{org}/… path prefix (paths, methods, and the matrix envelope shape are unchanged; only which org's data a response carries changes).
  • Error code unknown_org (§16) is added additively for an org that does not exist or a reference that bridges two orgs.

Snapshot selection & fail-closed posture. Selection happens before resolve: M := provider.get_snapshot(org). Missing org (no claim) is treated like a role-less caller — deny (NONE); the root org is never silently substituted at request time. Unknown org (a claim naming an org absent from the registry/table) raises unknown_org and denies rather than compiling an empty matrix. The root org is a migration-backfill and dev-seed target only, never a runtime default.

Per-org invariants. Anti-lockout (§12) is enforced per org; slug/feature-key uniqueness (§14.3) is per org; supers and aliases are strictly per org. See those sections for detail. Cross-org isolation is verified at the adapter layer (snapshot-per-org has no shared state for a core vector to exercise).

15.3 Control plane (org & app lifecycle, members, platform capability)​

Added in spec 0.3.0; additive, wire_version stays 1.

Above a single org (§15.2) sits a thin control plane that creates orgs and apps, binds the first human admin, and knows who an org's real members are. Like org itself, none of this touches resolve (§7), Cell, the canonical matrix body (§4, §13), or the anti-lockout kernel (§12): the control plane is persistence + identity state, exactly like assignments, so the entire wire_version: 1 conformance corpus (vectors + wire-golden) is unchanged.

Org & app lifecycle. An org is the authorization tenant (§15.2): it owns the matrix, membership, and isolation. An app is a registered OIDC client bound to exactly one org — an application identity / audience (a client_id), not a second tenancy dimension and not a per-app matrix. Multiple apps under one org authorize against that org's single snapshot; genuine per-product isolation is modeled as multiple orgs, never a new app dimension. An org is provisioned by one idempotent primitive — create (born inactive) → seed a lockout-safe catalogue → bind a first rbac.manage-FULL admin → activate, atomically — so an org is never both active and lockout-unsafe; an adminless org stays inactive and denies at the resolver (§15.2 fail-closed posture).

Platform capability (above per-org rbac.manage). A cross-org authority, orthogonal to any org's matrix and never consulted by resolve, controls org creation/deactivation. It is asserted by the IdP as a token scope/claim and read fail-closed by the adapter (absent ⇒ denied), with an environment platform-subject (ARCHENSTACK_RBAC_PLATFORM_SUBJECTS, no code fallback) for the first platform admin. It is distinct from an org admin (who holds rbac.manage FULL within one org): a platform admin creates orgs but gains no in-matrix authority; an org admin edits their org but cannot create orgs. App registration is PLATFORM-OR-ADMIN — an org's own admin (rbac.manage FULL) registers and manages that org's apps, and a platform caller whose grant reaches that org MAY do so too. The platform tier is REQUIRED for the provisioning case: an org's first app is registered before any org admin exists to register it.

The org listing is not a tenant directory: an adapter MUST scope it to the organizations the caller may legitimately see — the tenants they belong to, or, for a platform caller, exactly the orgs its grant reaches. Returning every org to any authenticated caller discloses the deployment's tenant roster across the isolation boundary.

A platform grant MAY be bounded to a set of org slugs — the shape a parent organization needs to govern exactly its own subsidiaries and no other tenant in the deployment. An adapter that supports bounding MUST check the operation's target org against the bound on every control-plane route, and MUST treat an empty bound as no authority (fail closed). An unbounded grant (the default when a host asserts no bound) reaches every org. The environment platform-subject is always unbounded, since the first platform admin must be able to create the first org. Bounding only ever NARROWS authority: it never grants authority a caller lacks, so a host that asserts no bound is unaffected.

The bound is a SUBTREE, not a list (NORMATIVE)​

Organizations MAY form a tree: an OPTIONAL parent names the tenant an org sits beneath. A bounded grant reaches every org it names and every descendant of those orgs, transitively.

This is not a convenience. A grant expressed as an enumeration of slugs can authorize operations on orgs that already exist, but it can never authorize creating one — the new slug is in no grant until after it exists, and a self-service provisioner derives slugs (from a subscription id, say) that nobody can enumerate in advance. Provisioning is the operation platform authority exists for, so a flat bound is absent from precisely the place it matters. Naming a parent is what makes "may open subsidiaries under this company" expressible.

Accordingly, for a create:

  • when the request names a parent, authority MUST be checked against the parent, not the org being created;
  • when it does not, the target is the new slug itself, so only a grant naming that slug (or an unbounded one) may create it — a bounded principal MUST NOT be able to mint arbitrary root tenants.

Governance flows downward only. A grant over a child MUST NOT confer authority over its parent or its siblings, or a single subsidiary's governor would escalate to the whole family. An org the deployment does not know MUST be treated as out-of-bound unless the grant names it outright: an unknown slug has no ancestry to walk. Implementations MUST terminate the ancestry walk on a cycle rather than loop.

The tree bounds control-plane authority only. It is emphatically NOT a resolution dimension: a child does NOT inherit its parent's matrix, roles, assignments, or overrides, resolve never sees parent, and the canonical snapshot is unchanged. An adapter with no control plane has nothing to bound and so needs no tree.

The identity provider names governed roots; the adapter expands them. Which tenants sit beneath which is the application's fact, not the IdP's, so a claim carrying the bound SHOULD name orgs whose lifecycle the subject governs and MUST NOT be derived from the subject's membership of those orgs — a membership-derived claim cannot name a tenant that does not exist yet, and forcing a governor into each tenant to bound them grants administration inside tenants they govern only from outside (security model §2.7).

Members are the subject source of truth. An org's member registry is the sole source for the Assignments subject picker — populated JIT on first authenticated login (upsert (org, sub)), by invite-by-email (a pending member whose subject is reconciled email → sub on first login), and optionally by SCIM reconcile. There is no free-text subject entry: an assignment targets a member the org has actually seen.

Wire. Two additive collection envelopes mirror the shipped orgs / assignments list envelopes (a plural kind marking a management collection; no separate list schema, same as orgs/assignments):

{ "wire_version": 1, "kind": "members",
"results": [ { "subject": <sub|null>, "email": <str>, "display": <str>,
"status": "active"|"pending"|"revoked",
"principal_kind": "human"|"service_account" }, ... ] }

{ "wire_version": 1, "kind": "apps",
"results": [ { "client_id": <str>, "audience": <str>, "label": <str>,
"redirect_uris": <array|null>, "is_active": <bool> }, ... ] }

principal_kind distinguishes a machine principal from a person: "human" (the default when a member row carries no kind) or "service_account" for an integration credential. Authorization is identical for both — it is a display and filtering hint, never an input to resolve. A reader that does not recognize the field MUST ignore it.

Both are org-scoped and require rbac.manage FULL; one org's members/apps are never visible to another (cross-org isolation). The me envelope (§15) gains an OPTIONAL is_platform_admin boolean (me.schema.json; not in required[]) surfacing the platform capability so a UI can reveal control-plane affordances; omitted ⇒ a legacy reader treats the caller as non-platform and resolves identically (§2.3). No canonical matrix change; matrix.schema.json required[] is untouched; wire_version stays 1.


16. Error shape & ErrorCode​

An error payload:

Error := {
wire_version: 1,
kind: "error",
code: ErrorCode, // string, see below
detail: string, // human-readable, non-localized default
field?: string // OPTIONAL: the offending field/slug/key
}

ErrorCode is a closed enumeration of lowercase snake_case strings:

CodeMeaning
unknown_roleReferenced a role slug that is not declared.
unknown_featureReferenced a feature key that is not declared.
unknown_groupReferenced a group slug that is not declared.
unknown_scopeA ScopeExpr node is malformed (zero/many keys, non-boolean const, etc.) — including a malformed default_partial_scope or partial_scope.
invalid_slugA slug or feature key failed the pattern/length rules (§14).
immutable_fieldA mutation attempted to modify a field that MUST NOT change — deactivating or alias_edit-converting a system/super role (§12.3). (A static override that references a super/alias role in a snapshot is validation, not this code — see §4.4, §7.3.1.)
lockoutThe mutation would violate the lock-out invariant (§12).
duplicate_keyA duplicate declaration (two overrides for one (feature, role), duplicate slug, etc.).
not_foundA referenced entity does not exist (generic).
validationA structural/consistency violation not covered by a more specific code: e.g. alias→super, alias→alias, a super carrying an alias_target, an alias with a null target, an override referencing a super/alias role (§4.4), or a non-null Feature.cell_scope (§5.4).
unknown_orgThe caller named an organization (via the org claim/header, §Organizations) that does not exist, or a cross-org reference bridged two organizations. Fail closed: deny. Added additively in spec 0.2.0 (wire_version stays 1); a v1 reader that does not recognize it treats it as a generic failure.

A reader that receives an error payload with a code it does not recognize MUST treat it as a generic failure (do not crash; do not best-effort proceed). Adding new ErrorCode members is additive (§2.3). For the exact code returned by each alias/super/override consistency check, see the normative mapping in §7.3.1.


17. Deferred / out-of-scope for v1 (BREAKING when added)​

The following are intentionally not in v1. Each, when introduced, changes resolution semantics or the wire type and therefore requires a MAJOR wire_version bump (§2.2) unless explicitly noted as additive.

Deferred itemDispositionWhy breaking / next step
Read scoping in core (view_scope, to_filter)DROPPED for v1 — handled by adapters (§9).Would let a scoped read change a decision → resolution-semantics change → MAJOR bump. Next step: design a read-scope model that a client resolver can apply identically to a server.
Per-cell scope (cell_scope)RESERVED — wire slot present, MUST be null (§5.4).Activating per-cell resolution changes how scope binds → MAJOR bump. The slot is already forward-compatible.
not in ScopeExprDROPPED for v1 (§8.1).Adds a new grammar node a v1 evaluator cannot interpret → MAJOR bump.
Meaningful atom.argsRESERVED — wire permits args; v1 evaluators MAY ignore (§8.1).Assigning semantics is additive only if args-free snapshots resolve identically; otherwise MAJOR.
Transitive / multi-hop aliasesDROPPED — aliases are single-hop to a standard target (§7.3).Chained resolution changes the algorithm → MAJOR bump.
Lazy / partial snapshot loadNEEDS A DEDICATED SESSION (adapter concern).v1 targets full-snapshot load (§18). A lazy-load adapter is additive at the transport layer and need not touch resolution, but its own contract must be specified.
Localized error detailDROPPED for v1.detail is a non-localized default string; localization is an adapter/UI concern.

No deferred item above is BLOCKED; each is either DROPPED (deliberate v1 non-goal) or RESERVED (wire slot present, semantics postponed to a MAJOR version).


18. Scale envelope​

  • v1 targets O(10³–10⁴) cells (features × roles) served as a single full snapshot loaded whole by the client, which then resolves locally (§2.1).
  • At this scale a full-snapshot fetch and an in-memory resolver are appropriate; no pagination or lazy loading is required by the core.
  • Lazy / partial loading (fetching feature groups on demand) is a future adapter concern (§17), not a core responsibility. It MUST NOT change resolution semantics; a lazily-assembled snapshot MUST resolve identically to the equivalent full snapshot.

19. Conformance​

An implementation is conformant iff:

  1. It reproduces the resolution result ({level, scope}) for every vector in vectors/ (§7, §8).
  2. It rejects every negative vector with the specified ErrorCode (§16), and accepts every positive vector.
  3. It serializes each wire-golden/ fixture byte-for-byte under canonical JSON (§13).
  4. It honors the lock-out invariant (§12) and override delta semantics (§10) on the mutation vectors.
  5. It fails closed on every malformed/unknown input (§7.2, §8.3).

See README.md for how each language wires its test harness to the corpus.