zanzibar-index
Zanzibar-style relationship-based access control (ReBAC) for Python, on top of SQLModel.
Schemas are written in a subset of the OpenFGA modelling DSL
(schema 1.1, including the and / but not operators; no conditions or modules), plus a
few extensions listed under "Schema shapes" below. The package is not affiliated with Google or OpenFGA.
Two evaluation backends give the same answers with opposite cost models:
zanzibar.setenginestores only the raw tuples and computes memberships on the fly with bitmap algebra (roaring bitmaps). Writes are cheap, reads do the work.zanzibar.graphindexmaterializes the transitive closure as reference-counted edges, socheckis a single indexed lookup. Writes do the work, reads are cheap.
zanzibar.connectedstore composes them: an append-only tuple log is the source of truth,
the graph index is a materialized view over it, and reads fall back to the set engine
when the index is behind.
Status: alpha, research code, no support promised
This is a personal research project. It is tested heavily: a differential suite checks both backends against an independent reference oracle, there is property-based fuzzing, and the core algorithms have machine-checked Lean proofs. It has never run in production, there is no performance target, and the API may change between 0.x releases. Issues and pull requests are welcome, but answers are best-effort.
Install
pip install zanzibar-index # SQLite
pip install "zanzibar-index[postgres]" # adds psycopg2-binary for PostgreSQL
Python 3.13 or later. The import name is zanzibar.
Quickstart
from sqlmodel import SQLModel, Session, create_engine, select
from zanzibar.connectedstore import ConnectedStore
from zanzibar.graphindex import Node
SCHEMA = """
model
schema 1.1
type user
type group
relations
define member: [user, group#member]
type doc
relations
define banned: [user]
define viewer: [user, group#member] but not banned
"""
engine = create_engine("sqlite:///perms.db")
SQLModel.metadata.create_all(engine) # creates the zanzibar_* tables (see below)
with Session(engine) as session:
store = ConnectedStore(session, "my-app", schema=SCHEMA)
# add_tuple(subject_predicate, subject_type, subject_name, relation, object_type, object_name)
store.add_tuple("...", "user", "alice", "member", "group", "eng") # "..." = the bare user
store.add_tuple("member", "group", "eng", "viewer", "doc", "d1") # group#member is a viewer
store.check("...", "user", "alice", "viewer", "doc", "d1") # True
store.add_tuple("...", "user", "alice", "banned", "doc", "d1")
store.check("...", "user", "alice", "viewer", "doc", "d1") # False
# lookup returns graph-index node ids; resolve them to (type, name, relation)
found = store.lookup("...", "user", "alice")
nodes = session.exec(select(Node).where(Node.id.in_(found.node_ids))).all()
assert sorted((n.type, n.name, n.predicate) for n in nodes) == [
("doc", "d1", "banned"), ("group", "eng", "member")] # no longer doc:d1#viewer
Each write commits and returns a log id. Pass it back as check(..., at_least=token) to
read your own writes when the index is maintained asynchronously (sync=False).
Reopening a store with ConnectedStore(session, "my-app") reads its persisted schema;
a store's schema is write-once.
Reading lookup results
lookup (what can this subject reach?) and lookup_reverse (who can reach this
object's relation?) return a LookupResult with three fields:
node_ids: ids ofzanzibar.graphindex.Noderows. Resolve them as above. A node is a(type, name, predicate)triple, wherepredicateis the relation, or"..."for a bare subject such as a user. Results cover every relation the subject reaches, usersets on the way included: alice above reachesgroup:eng#memberanddoc:d1#banned.markers: wildcard grants, as(type, predicate, variant)triples. Fromlookup_reverse,("user", "...", "any")means "every user", from a[user:*]tuple.excluded_node_ids: subjects a marker would cover but who are refused (for example bybut not banned). Subtract them from the marker yourself: "every user except mallory".
A standalone zanzibar.setengine.SetEngine returns the same three fields, in its own id
space: markers are (type, predicate) pairs, and an id is an in-memory handle that
engine.interner.key(id) turns into (type, name, predicate). Translate ids before they
leave the process: engine.result_keys(res) for node_ids and engine.excluded_keys(res)
for excluded_node_ids. Send both with the markers, and subtract the exclusions exactly as
above; markers without their exclusions grant too much.
Things to know before you use it
- Tables. The library declares its tables on SQLModel's default metadata, all named
zanzibar_*, soSQLModel.metadata.create_all(engine)creates them next to your own. A table of yours that reuses one of those names is a loudInvalidRequestError, whichever is declared first; the two are never silently merged. - One write path per store id. Write a
ConnectedStore's store through theConnectedStoreonly. A standaloneSetEngineopened on the same id can read it, but itsadd_tuple/remove_tupleraiseUnloggedWriteRefused, and it must be given the store's own schema (zanzibar.connectedstore.open_set_engine(session, id)loads it); a different one raisesSchemaMismatch. AConnectedStorewill not take over an id that a standaloneSetEnginealready wrote to (UnloggedTuplesPresent). To adopt such a store, callsave_schema(session, id, schema), commit, thenbuild_index(session, id), then openConnectedStore(session, id). - Databases. SQLite and PostgreSQL only. On PostgreSQL the session must use
READ COMMITTED; any other isolation level is refused at construction. - Runtime checks.
ConnectedStore(..., paranoia="residue")or theZANZIBAR_PARANOIA=residueenvironment variable turns on a cheap runtime corruption detector for the index. It is off by default and recommended for anything security-sensitive. - Schema shapes. Conditions (
with) and modules are not supported. Refused shapes come with an explanation of what to write instead; for example, as in OpenFGA, afromtupleset must be a direct relation. Only schema 1.1 is implemented: the header is optional, but aschemaline naming any other version (schema 1.2included) is refused. That is stricter than OpenFGA, which also accepts1.2. As in OpenFGA, amodel/schema 1.1/relationsline must stand alone (a comment goes on its own line), every type a restriction names must be declared with atypeline, andbut notmay not share a level withor/and: write(a or b) but not cora but not (b or c), nevera or b but not c. Wildcard usersets ([group:*#member]), wildcard tuplesets (parent: [folder:*]) and object wildcards go beyond OpenFGA. They work, but they are outside the proved fragment and emitUnprovenExtensionWarning. Also beyond OpenFGA's DSL syntax, and accepted here: more than one[...]block in a definition ([user] or [group#member]), a[...]block that is not the first operand (editor or [user],viewer but not [user:*]), nomodel/schema 1.1header, and adefinewith norelationsline above it. A schema using them may not load in OpenFGA's own tools. - "All" does not imply "some" when there are none. A grant on every instance of a
type reaches a grant on "any" instance only through an instance that exists. With
object_wildcard_shapes=frozenset({("folder", "viewer")})(sofolder:*can hold a viewer grant),docdeclaringdefine parent: [folder, folder:*]anddefine viewer: viewer from parent, and the tuplesalice viewer folder:*andfolder:* parent doc:1: while no folder is stored, alice cannot viewdoc:1. Once any folder exists, she can. This strict reading is the current mode on both backends; a lenient mode may come later. - No recursion through
and/but not. A relation that reaches itself through an operator, such asdefine viewer: ([user] or viewer from parent) but not blocked, is refused by the graph index and so byConnectedStore(CyclicDerivedDependency), while a standalonezanzibar.setengine.SetEngineaccepts it. The usual rewrite recurses on a plain relation and applies the operator on top:define viewer_base: [user] or viewer_base from parentthendefine viewer: viewer_base but not blocked. It is not the same schema:blockedthen applies only at the object you query, not at every folder above it. - Tuple data must be acyclic. A write that would close a cycle, such as group
ainside groupbinside groupa, a group inside itself, or a folder that is its own ancestor, is refused withAdmissionRejectedby both backends. OpenFGA accepts such tuples, so check imported data for cycles first. - A userset is not a member of itself. OpenFGA counts
doc:1#bannedas a member ofdoc:1#banned, and so of anything built on it; this library does not (except through afromparent). Withdefine vx: [user, doc#banned] but not bannedand the tupledoc:1#banned vx doc:1, checkingdoc:1#bannedforvxondoc:1is allowed here and denied by OpenFGA. Only userset subjects are affected; plain users anduser:*are not. - Reads are lenient; writes are strict. A write naming an undeclared type or relation,
or a malformed name, raises
AdmissionRejected. Acheckwith the same mistake returnsFalsewith no error, so a typo in a relation name reads as "denied". A typo in the SCHEMA, such asdefine viewer: [usr]with notype usr, is refused when the schema is parsed (ValueError), before any write. - Write cap. A single write that would add more than
ZANZIBAR_MAX_CLOSURE_FANOUTclosure edges (default 100,000;0disables) is refused withClosureFanoutExceeded. The write then lands in neither backend. - Public API. Each subpackage's
__all__is the public surface. Underscore-prefixed names that happen to be re-exported are internal.
Documentation
Design docs, the correctness argument and the Lean proofs live in the repository:
https://github.com/averykhoo/graph-reachability-zanzibar-index. Start at
docs/architecture/overview.md.
License
Apache-2.0. See LICENSE.
Metadata
Release files for zanzibar-index 0.0.5
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| zanzibar_index-0.0.5.tar.gz | 269.8 kB | With provenance | Details for zanzibar_index-0.0.5.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| zanzibar_index-0.0.5-py3-none-any.whl | Python 3 | none | any | Details for zanzibar_index-0.0.5-py3-none-any.whl |
Total release size: 536.1 kB
Release files / zanzibar_index-0.0.5.tar.gz
| Download URL | zanzibar_index-0.0.5.tar.gz |
|---|---|
| Size | 269.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
76c6522cca41115b01d6245b810bb1e25cb8f36d52febe4ec8aaaf6ca6f5598a
|
|
BLAKE2b-256 checksum How to use checksums |
9aa47577a5c74abb425e84b8c2ed5657d186bfa8e05238f3e965a5c7cc2ac854
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 15, 2026.
Transparency logRelease files / zanzibar_index-0.0.5-py3-none-any.whl
| Download URL | zanzibar_index-0.0.5-py3-none-any.whl |
|---|---|
| Size | 266.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
dc29e2b8fc5090d8ef661f4a4130d3719d8636f754f2b7a150663f0d6f4ae32c
|
|
BLAKE2b-256 checksum How to use checksums |
8042194dce2bce94486f5fcddd833ab84c0481048d9bef3d06793894efcdd736
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 15, 2026.
Transparency logSecurity for zanzibar-index 0.0.5
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for zanzibar_index-0.0.5.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 15, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.