Model application authorization as relationships, then let the selected backend answer the question that matters: may this subject perform this action on this object?
zanzibar is a typed Rust API for schemas, relationship tuples, consistency,
and permission checks. It suits applications whose access rules grow beyond a
role column: shared documents, nested teams, delegated administration, tenant
resources, public objects, and other relationship-based policies. The same
RebacEngine API has a Keldra 0.27 backend and an optional PostgreSQL
backend.
With Keldra, Keldra remains the durable authority and evaluates permissions server-side. With PostgreSQL, this crate stores and evaluates the graph in the application's selected PostgreSQL schema. Both backends use the same schema, tuple, and permission-check types. PostgreSQL supports revision-based consistency and exposes transaction-aware tuple mutation and batch-check methods for applications that need domain records and authorization tuples to commit in one PostgreSQL transaction.
| Capability | Available |
|---|---|
| Direct relations and derived permissions | Yes |
| Entity, userset, same-resource, exact, and public subject selectors | Yes |
| Nested userset evaluation | Yes |
| Opaque and exact-path identities, including mixed tuples and schema selectors | Yes |
| Atomic add/remove batches | Yes, up to 1,000 mutations |
| Single and ordered batch permission checks | Yes, up to 1,000 checks |
Current-state permission checks (Consistency::Latest) |
Yes |
| Single-page filtered tuple reads | Yes, up to 1,000 tuples |
| Automatic client-credential exchange and bearer refresh | Yes |
cargo add zanzibar@0.9
cargo add tokio --features macros,rt-multi-thread
cargo add serde_jsonThe adapter uses the Keldra 0.27.1 SDK with Keldra 0.27 servers. Start Keldra and provision a tenant owner by following Keldra's five-minute setup. Configure the endpoint, the exact tenant name and the file containing the provisioned tenant credential JSON:
export KELDRA_ENDPOINT=http://127.0.0.1:50051
export KELDRA_STORAGE_TENANT=example
export KELDRA_CREDENTIALS_FILE=/secure/path/example-credentials.jsonUse the HTTP endpoint only for loopback development. For networked deployments,
put Keldra behind a TLS terminator and configure its https:// endpoint before
sending application credentials.
Applications exchange a tenant client secret for a short-lived access token.
KeldraRebacEngine refreshes the token before it expires and checks that the
authenticated tenant matches KeldraRebacConfig.storage_tenant.
The PostgreSQL backend is enabled by the default postgres feature. It uses the
same typed RebacEngine operations as Keldra and requires a PostgreSQL pool and
an isolated schema name. Call prepare only from an explicit migration or
bootstrap command; normal service attachment should use the already prepared
schema.
use sqlx::postgres::PgPoolOptions;
use zanzibar::postgres::PostgresRebacEngine;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let pool = PgPoolOptions::new()
.max_connections(8)
.connect(&std::env::var("DATABASE_URL")?)
.await?;
let engine = PostgresRebacEngine::<String>::new(pool, "worka_authz")?;
engine.prepare().await?;
Ok(())
}Disable default features to omit the PostgreSQL adapter and its SQLx dependency:
zanzibar = { version = "0.9", default-features = false }The PostgreSQL integration tests use PostgreSQL 19. In Worka's repository, run
docker compose -f tests/persistence/compose.yaml up -d before cargo test;
the test suite then exercises the adapter against that disposable service.
Zanzibar 0.9.0 was tested against the Linux AMD64 Keldra 0.27.0 image with ID
sha256:ba1bc1bf11d37667e165b7dba8b7b2acc45afa173c2a2ed75886602f8ac5f161.
It was built from Keldra revision 2c9df68635d64474b651dda4c7e9f97324c46282.
Configure a disposable node from that local image, run keldra init with its
configuration and signing key, and start keldra-server. Publish the gRPC port
on 127.0.0.1 and use the fresh bootstrap credential to provision a test tenant.
Save only that tenant's client_secret in a mode-0600 file.
export KELDRA_E2E_GRPC=http://127.0.0.1:50051
export KELDRA_E2E_TENANT=zanzibar-test
export KELDRA_E2E_CLIENT_SECRET_FILE=/secure/path/test-client-secret
cargo test --test keldra_backend --test exact_path_backend -- --ignored --test-threads=1To run the same tests on GitHub Actions, dispatch the PR workflow with a registry image reference for an accessible Keldra 0.27 image. Use a digest to pin the supplied image. Ordinary PR runs test the crate and PostgreSQL backend.
This complete example declares a writable viewer relation and a derived
can_read permission. It binds the schema to one authorization realm, grants
Alice access, and checks the permission after committing the mutation.
use std::collections::BTreeSet;
use zanzibar::keldra::{KeldraRebacConfig, KeldraRebacEngine};
use zanzibar::{
AuthzScope, CheckRequest, Consistency, MutateTuplesRequest,
NamespaceDefinition, Object, PermissionRule, RebacEngine,
RelationDefinition, SchemaBuilder, SchemaId, Subject, SubjectSelector,
Tuple, TupleUpdate, put_and_bind_schema,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let<
B90E
/span> tenant = std::env::var("KELDRA_STORAGE_TENANT")?;
let credentials = std::fs::read(std::env::var("KELDRA_CREDENTIALS_FILE")?)?;
let mut credentials: serde_json::Value = serde_json::from_slice(&credentials)?;
let serde_json::Value::String(client_secret) = credentials["client_secret"].take() else {
return Err("credential file is missing client_secret".into());
};
let engine = KeldraRebacEngine::connect(KeldraRebacConfig {
endpoint: std::env::var("KELDRA_ENDPOINT")?,
storage_tenant: tenant.clone().into(),
client_secret,
})
.await?;
let schema = SchemaBuilder::new()
.namespace(
"document",
NamespaceDefinition::new()
.relation(
"viewer",
RelationDefinition::Direct {
allowed_subjects: BTreeSet::from([SubjectSelector::AnyObject {
namespace: "user".into(),
}]),
},
)
.relation(
"can_read",
RelationDefinition::Permission {
rules: BTreeSet::from([PermissionRule::Inherit {
relation: "viewer".into(),
}]),
},
),
)
.build();
// A realm is an independent authorization graph inside this storage tenant.
let scope = AuthzScope::new(tenant, "documents");
put_and_bind_schema(
&engine,
&scope,
SchemaId("document-access".into()),
schema,
None,
)
.await?;
let alice = Subject::Entity(Object {
namespace: "user".into(),
id: "alice".into(),
});
let roadmap = Object {
namespace: "document".into(),
id: "roadmap".into(),
};
engine
.mutate_tuples(MutateTuplesRequest::new(
scope.clone(),
vec![TupleUpdate::Add(Tuple {
object: roadmap.clone(),
relation: "viewer".into(),
subject: alice.clone(),
})],
)?)
.await?;
let decision = engine
.check(
&scope,
CheckRequest {
subject: alice,
relation: "can_read".into(),
object: roadmap,
},
Consistency::Latest,
)
.await?;
assert!(decision.allowed);
println!("Alice can read the roadmap");
Ok(())
}The tenant credential needs Keldra's manage_authz permission to manage
schemas, bindings and tuples for the tenant.
Existing top-level models and keldra::KeldraRebacEngine keep their opaque
String IDs. Use the additive exact_path models and engine when a graph
contains path-addressed resources. This API supports both identity kinds in
one graph; paths are sent as Keldra's native ExactPath, never opaque strings.
The existing model names are now concrete aliases of the shared typed models.
Struct literals and qualified variants (Subject::Entity, TupleUpdate::Add)
are unchanged. Rust cannot import enum variants through a type alias: callers
using use zanzibar::Subject::{Entity, Public} must instead use qualified
variants, or import variants from zanzibar::TypedSubject. No identity or
serialization conversion is needed for existing opaque-ID values.
use zanzibar::{AuthzScope, Consistency, ObjectId, RebacEngine};
use zanzibar::exact_path::{CheckRequest, KeldraRebacEngine, Object, Subject};
async fn can_read(engine: &KeldraRebacEngine) -> Result<bool, zanzibar::RebacError> {
let scope = AuthzScope::new("example", "documents");
let decision = engine.check(&scope, CheckRequest {
subject: Subject::Entity(Object {
namespace: "user".into(),
id: ObjectId::Opaque("alice".into()),
}),
relation: "can_read".into(),
object: Object {
namespace: "document".into(),
id: ObjectId::ExactPath {
tenant: "example".into(),
bucket: "documents".into(),
path: "folders/report.json".into(),
},
},
}, Consistency::Latest).await?;
Ok(decision.allowed)
}Connect this engine using the same KeldraRebacConfig and connect method.
Use exact_path aliases consistently for schemas, tuples, reads and checks.
Exact addresses retain tenant, bucket and relative path, including in usersets
and exact subject selectors. The adapter verifies the address belongs to the
authenticated tenant and sends its bucket and path using Keldra's native
address type. The opaque-only reader reports an error if a response contains
an exact path. To commit object and tuple changes together, stage both with the
same explicit transaction using the keldra SDK before committing.
A direct relation accepts stored tuples. Its selectors say which typed subjects are legal. A permission is derived from direct relations or other permissions:
Inheritincludes another relation or permission on the same object.TupleToUsersetfollows a related object and evaluates a relation there.AnyUsersetpermits subjects such asgroup:engineering#member, enabling nested group and delegation models.Publicpermits Keldra's reserved anonymous principal as a tuple subject; access is granted only when that tuple is written, and protected resources remain private by default.
Schemas are immutable and content-addressed by their returned SchemaRef.
Publishing identical content returns the existing schema reference. Binding uses a generation
check, so schema changes cannot silently overwrite a concurrent update.
Keldra 0.27 returns no reusable authorization revision. The adapter returns
None for authorization revisions and accepts Consistency::Latest for
reads and permission checks. It rejects Consistency::AtLeast and
Consistency::Exact. Schema reference revisions and binding generations keep
their existing meaning. For an existing binding, pass its generation when
updating it.
MutateTuplesRequest requires a non-empty batch of up to 1,000 changes.
Keldra commits the batch atomically. The adapter rejects authorization revision
conditions and operation IDs before sending the mutation. If a response is
uncertain, read current state before retrying. check_many evaluates up to
1,000 checks together and returns decisions in request order.
Tuple reads support an exact object or object namespace, relation, subject and
subject namespace. The adapter returns a complete single page or an error. For
more than 1,000 matches or when several pages are required, use the keldra
SDK with an explicitly started transaction. Pass that transaction ID and the
same filters to every request before closing the transaction. This continuation
is tied to a transaction, and the token cannot be used as an authorization
revision.
Object and subject discovery and ordered tuple watches are outside the adapter.
Apache-2.0