zanzibar.schema

Parsing, converting and compiling schemas. Both backends use this layer. The language it accepts is described on the Schema language page, and the shapes it refuses on the Refused schema shapes page.

Parsing a schema

parse_openfga_schema is importable from both zanzibar and zanzibar.schema; it is documented here under its top-level name.

zanzibar.parse_openfga_schema(schema, object_wildcard_shapes=frozenset({}), *, enable_boolean=True)

Parse + compile an OpenFGA-style schema (see parse_schema_ast) into a graph-index RuleSet.

Pipeline: parse_schema_ast -> derive_schema_info -> compile_ruleset. object_wildcard_shapes are (object_type, relation) pairs enabling wildcard objects (e.g. folder:*), a deliberate extension beyond OpenFGA that has no DSL syntax and so must be declared here.

Boolean (and / but not) schemas compile into derived predicates maintained by the delta processor. Pass enable_boolean=False for the historical refusal behavior.

Parameters:
Return type:

RuleSet

zanzibar.schema.parse_schema_ast(schema)

Parse OpenFGA DSL text into a SchemaAST, without compiling it. The accepted language is described on the Schema language page. A schema with a syntax error, a reference to an undeclared relation or type, or a cycle of computed or tuple-to-userset references raises SchemaError or a subclass (see Refused schema shapes). and and but not are accepted here.

zanzibar.schema.unparse_schema_ast(ast)

Render a SchemaAST back to DSL text (a str), such that parse_schema_ast(unparse_schema_ast(a)) == a for every AST that parse_schema_ast() can produce. The empty AST renders as "", which the parser refuses. Both operands of but not are parenthesised when they are operators (Exclusion(Union(a, b), c) renders as (a or b) but not c), and every type that is used in a restriction but has no relations gets its own type line first, sorted.

OpenFGA JSON models

zanzibar.schema.parse_openfga_json(model)

Parse an OpenFGA authorization model (JSON string or dict) into a SchemaAST.

Supports schema_version 1.1: this (with directly_related_user_types metadata), computedUserset, tupleToUserset, union, intersection, difference. Conditions are rejected.

The result is refused unless the DSL openfga_json_to_dsl renders from it parses back to the same AST. Duplicate JSON keys are refused only for JSON TEXT input: a dict has already lost them.

A malformed model – a field of the wrong JSON kind, or a required key missing – raises SchemaError (a ValueError) naming the field, never a bare AttributeError / TypeError / KeyError. An optional object or array given as null reads as absent.

Return type:

dict[tuple[str, str], Union | Intersection | Exclusion | Direct | Computed | TTU]

zanzibar.schema.openfga_json_to_dsl(model)

OpenFGA JSON -> canonical DSL text (the persistable schema source): parse to the shared AST, render through the round-trip-safe unparser.

Return type:

str

Compiling for the graph index

zanzibar.schema.compile_ruleset(ast, schema_info, *, enable_boolean=True, declared_types=frozenset()) → RuleSet

Compile a SchemaAST into a RuleSet. Most programs call zanzibar.parse_openfga_schema(), which parses, derives schema_info and calls this function. Relations that use and or but not compile into derived relations, maintained by the graph index’s delta processor; with enable_boolean=False the first such operator raises UnsupportedByGraphIndex instead. A cycle among derived relations raises CyclicDerivedDependency. declared_types (the schema’s type lines) changes only the wording of a later admission refusal.

class zanzibar.schema.RuleSet

A compiled schema, as returned by zanzibar.parse_openfga_schema(). A dataclass. Pass it as ruleset= to SetEngine or TupleSource to skip compiling the same schema again.

schema_info: SchemaInfo

The wildcard and derived-relation facts the graph index needs. Pass it to WildcardIndex.

compiled: CompiledBooleans | None

The compiled and / but not relations, or None. Pass it to DeltaProcessor. A schema needs a delta processor when compiled is not None and compiled.plans is not empty.

rules_and_filters

The compiled routing rules, in order.

apply(relational_triple)

Route one raw tuple through the schema: yield every edge the graph index must store for it. A tuple the schema does not admit raises AdmissionRejected. It takes a RelationalTriple; see Use the backends directly.

The types that appear in RuleSet’s fields and apply are public since 0.1.0, so a type checker can name them. Take SchemaInfo and CompiledBooleans from a compiled RuleSet rather than building them; build a RelationalTriple from two Entity values when you drive the graph index yourself.

class zanzibar.schema.Entity(type, name)

One object or subject: a type and a name, printed type:name. A frozen dataclass, hashable and ordered. name may be '*', the wildcard sentinel.

type: str
name: str
property wildcard: bool

True when name is '*'.

class zanzibar.schema.RelationalTriple(subject, relation, object, subject_predicate=Ellipsis)

One relation tuple as RuleSet.apply() takes it: subject (an Entity) has relation on object (an Entity). subject_predicate is ... (Ellipsis, the default) for a bare subject such as user:alice, or a relation name for a userset subject such as group:eng#member. It prints as object#relation@subject#predicate. A frozen dataclass.

class zanzibar.schema.SchemaInfo

The wildcard and derived-relation facts a compiled schema carries, as RuleSet.schema_info. You do not build one: zanzibar.parse_openfga_schema() and compile_ruleset() put it on the rule set, and WildcardIndex takes it. Treat it as read-only; its fields describe the schema and are not a configuration surface.

class zanzibar.schema.CompiledBooleans

The compiled form of a schema’s and / but not relations, as RuleSet.compiled (None when the schema has none), and the second argument of DeltaProcessor. An opaque value: pass it through. Its fields are compiler internals and may change in any release.

The schema AST

parse_schema_ast() returns a SchemaAST. Each relation’s definition is an expression built from the node classes below. All the node classes are frozen dataclasses, so they are hashable and compare by value.

zanzibar.schema.SchemaAST = dict[tuple[str, str], Expr]

A parsed schema: a plain dict mapping (object_type, relation) to the Expr that defines that relation. It is a type alias, not a class.

zanzibar.schema.Expr = Union | Intersection | Exclusion | Direct | Computed | TTU

The type of one relation definition: any of the node classes below. Direct, Computed and TTU are leaves; Union (or), Intersection (and) and Exclusion (but not) combine other expressions.

class zanzibar.schema.Direct(restrictions)

A [...] direct type-restriction list, for example [user, group#member, user:*].

restrictions: tuple[Restriction, ...]
class zanzibar.schema.Restriction(type, predicate, wildcard)

One entry of a [...] type-restriction list.

type: str
predicate: str

'...' for a bare entity ([user]), or a relation name for a userset ([group#member]).

wildcard: bool

True for T:* and T:*#P.

class zanzibar.schema.Computed(relation)

A computed userset: define viewer: editor is Computed('editor').

relation: str
class zanzibar.schema.TTU(target_rel, tupleset_rel)

Tuple-to-userset: define viewer: viewer from parent is TTU('viewer', 'parent').

target_rel: str
tupleset_rel: str
class zanzibar.schema.Union(children)

a or b or ....

children

A tuple of Expr.

class zanzibar.schema.Intersection(children)

a and b and ....

children

A tuple of Expr.

class zanzibar.schema.Exclusion(base, subtract)

base but not subtract.

base

An Expr.

subtract

An Expr.

from zanzibar.schema import Computed, Direct, Exclusion, Restriction, parse_schema_ast

ast = parse_schema_ast("""
model
  schema 1.1
type user
type doc
  relations
    define owner: [user]
    define banned: [user]
    define viewer: owner but not banned
""")
print(ast[("doc", "owner")] == Direct((Restriction("user", "...", False),)))  # -> True
print(ast[("doc", "viewer")] == Exclusion(Computed("owner"), Computed("banned")))  # -> True

Identifiers

The identifier rules are described on the Tuple strings and identifiers page.

zanzibar.schema.IDENTIFIER_CHARSET: str = 'A-Za-z0-9_./@+=-'

The characters an identifier may use, written as the inside of a regular-expression character class. An identifier is 1 to 256 of these characters.

zanzibar.schema.is_valid_identifier(value) → bool

True if value is a string of 1 to 256 characters from IDENTIFIER_CHARSET, and False for anything else, including a non-string. It checks the characters only: '*' returns False, and '...' returns True because . is in the character set. Where the reserved names * and ... are accepted is described on the Tuple strings and identifiers page.

zanzibar.schema.validate_store_id(store_id, label='store_id') → None

Raise AdmissionRejected unless store_id is a str with at least one non-whitespace character. The identifier character set does not apply to store ids. label names the argument in the error message.

Exceptions

zanzibar.schema exports no exceptions or warnings. Import them from zanzibar; they are documented on the Exceptions page.