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_shapesare(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=Falsefor the historical refusal behavior.
- 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 raisesSchemaErroror a subclass (see Refused schema shapes).andandbut notare accepted here.
- zanzibar.schema.unparse_schema_ast(ast)¶
Render a
SchemaASTback to DSL text (astr), such thatparse_schema_ast(unparse_schema_ast(a)) == afor every AST thatparse_schema_ast()can produce. The empty AST renders as"", which the parser refuses. Both operands ofbut notare 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 owntypeline 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(withdirectly_related_user_typesmetadata),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
dicthas already lost them.A malformed model – a field of the wrong JSON kind, or a required key missing – raises
SchemaError(aValueError) naming the field, never a bareAttributeError/TypeError/KeyError. An optional object or array given asnullreads as absent.
Compiling for the graph index¶
- zanzibar.schema.compile_ruleset(ast, schema_info, *, enable_boolean=True, declared_types=frozenset()) RuleSet¶
Compile a
SchemaASTinto aRuleSet. Most programs callzanzibar.parse_openfga_schema(), which parses, derivesschema_infoand calls this function. Relations that useandorbut notcompile into derived relations, maintained by the graph index’s delta processor; withenable_boolean=Falsethe first such operator raisesUnsupportedByGraphIndexinstead. A cycle among derived relations raisesCyclicDerivedDependency.declared_types(the schema’stypelines) 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 asruleset=toSetEngineorTupleSourceto 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 notrelations, orNone. Pass it toDeltaProcessor. A schema needs a delta processor whencompiledis notNoneandcompiled.plansis 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 aRelationalTriple; 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.namemay be'*', the wildcard sentinel.
- class zanzibar.schema.RelationalTriple(subject, relation, object, subject_predicate=Ellipsis)¶
One relation tuple as
RuleSet.apply()takes it:subject(anEntity) hasrelationonobject(anEntity).subject_predicateis...(Ellipsis, the default) for a bare subject such asuser:alice, or a relation name for a userset subject such asgroup:eng#member. It prints asobject#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()andcompile_ruleset()put it on the rule set, andWildcardIndextakes 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 notrelations, asRuleSet.compiled(Nonewhen the schema has none), and the second argument ofDeltaProcessor. 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
dictmapping(object_type, relation)to theExprthat 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,ComputedandTTUare leaves;Union(or),Intersection(and) andExclusion(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.
- class zanzibar.schema.Computed(relation)¶
A computed userset:
define viewer: editorisComputed('editor').
- class zanzibar.schema.TTU(target_rel, tupleset_rel)¶
Tuple-to-userset:
define viewer: viewer from parentisTTU('viewer', 'parent').
- class zanzibar.schema.Exclusion(base, subtract)¶
base but not subtract.
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¶
Trueifvalueis a string of 1 to 256 characters fromIDENTIFIER_CHARSET, andFalsefor anything else, including a non-string. It checks the characters only:'*'returnsFalse, and'...'returnsTruebecause.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
AdmissionRejectedunlessstore_idis astrwith at least one non-whitespace character. The identifier character set does not apply to store ids.labelnames 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.