Skip to content
worka-aiPublic

About

ReBAC

Resources

Stars

3 stars

Watchers

0 watching

Forks

Latest commit

 

History

80 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Zanzibar for Rust

Model application authorization as relationships, then let Keldra 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 backed by Keldra 0.25.0. 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.

Keldra remains the durable authority and evaluates permissions server-side. The crate provides the application-facing model, authenticated connection, token refresh, exact schema bindings, atomic tuple mutations, and typed results.

Capabilities

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
Latest, at-least, and exact-revision consistency Yes
Filtered, revision-pinned tuple pagination Yes
Automatic client-credential exchange and bearer refresh Yes

Install

cargo add zanzibar@0.8.7
cargo add tokio --features macros,rt-multi-thread

The adapter targets Keldra 0.25.0. Start Keldra and provision a tenant owner by following Keldra's five-minute setup. That flow gives the application three values:

export KELDRA_ENDPOINT=http://127.0.0.1:50051
export KELDRA_STORAGE_TENANT=example
export KELDRA_CLIENT_ID=example-client
export KELDRA_CLIENT_SECRET='the-secret-selected-during-provisioning'

Use 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 authenticate with the client ID and secret. Keldra exchanges them for short-lived bearer credentials; KeldraRebacEngine refreshes those credentials before they expire.

Define, bind, grant, and check

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 at or after the mutation's revision.

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 tenant = std::env::var("KELDRA_STORAGE_TENANT")?;
    let engine = KeldraRebacEngine::connect(KeldraRebacConfig {
        endpoint: std::env::var("KELDRA_ENDPOINT")?,
        storage_tenant: tenant.clone().into(),
        client_id: std::env::var("KELDRA_CLIENT_ID")?,
        client_secret: std::env::var("KELDRA_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(),
    };
    let written = 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::AtLeast(written.revision),
        )
        .await?;

    assert!(decision.allowed);
    println!("allowed at authorization revision {}", decision.revision.0);
    Ok(())
}

The application that performs a realm's first schema binding becomes that realm's owner. Later calls are authorised by Keldra's Zanzibar policy just like the data being protected.

Schemas and relationships

Exact-path resources

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 explicitly retain tenant, bucket and relative path, including in usersets and exact subject selectors. Keldra enforces its existing scope and address rules; this adapter does not reinterpret or redirect an address. The legacy opaque-only reader reports an error if a response contains an exact path it cannot represent. For object-plus-tuple atomic writes, use the official keldra client's existing AtomicWrite API.

A direct relation accepts stored tuples. Its selectors say which typed subjects are legal. A permission is derived from direct relations or other permissions:

  • Inherit includes another relation or permission on the same object.
  • TupleToUserset follows a related object and evaluates a relation there.
  • AnyUserset permits subjects such as group:engineering#member, enabling nested group and delegation models.
  • Public permits 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.

Consistency, batching, and retries

Every tuple mutation and permission decision returns an AuthzRevision:

  • Consistency::Latest evaluates current authoritative state.
  • Consistency::AtLeast(revision) requires state that includes a known write; if the serving state is still behind, Keldra returns RevisionUnavailable.
  • Consistency::Exact(revision) evaluates only that current revision and fails if it is no longer retained.

MutateTuplesRequest requires a non-empty batch. Keldra applies up to 1,000 mutations atomically. An expected revision can protect changes against concurrent updates. An optional with_operation_id enables five-minute, RAM-only retry deduplication; it does not survive server restart. Without an ID or after that window, read current state after an uncertain response before retrying. check_many evaluates up to 1,000 checks at one revision while preserving request order.

Tuple reads are filtered and paginated. A continuation token pins its filters and revision, preventing a multi-page result from drifting silently.

Current scope

Both opaque and exact-path authorization object IDs are supported through the models described above. Object/subject discovery and ordered tuple watches are outside the API; applications can use paged tuple reads for bounded inspection.

With Keldra 0.25.0, create and bind new custom realms while one cluster node is active, then expand the cluster. Existing bound realms continue to operate across the cluster.

License

Apache-2.0

About

ReBAC

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages