Reference

The public API of Strig: the Rust crates, the command line, the npm and Python packages, the Go and Java bindings, the Wasm ABI, the HTTP API, protocol 2 and the closed lists of error codes.

This page lists every name in the public surface, copied from the sources and the type snapshots of the release. Pick a name to see it in the bench with a real example and what it returns.

SurfaceInstallSection
strigstrig = "0.10" (default feature audit; dsl and dsl-fs add the policy language)Engine
strig-sync, strig-redis, strig-postgresstrig-sync = "0.10"Real-time
strig-axum, strig-server, strig-macrosstrig-server = "0.10"Server
strig-clicargo install strig-cliCommand line
npm packagenpm install @the-hades-organization/strignpm
strig-auth (Python), Go, Javapip install strig-authPython

Upgrading says what to change between releases and what 1.0 promises to keep. The repository's CHANGELOG.md records every change. Strig was called Themis until 0.5.0: themis-auth is now strig, and use themis:: becomes use strig::.

Engine#

The decision engine. Immutable once built, and shared between threads. It holds only configuration; the grants come with each call.

  • pub fn builder(catalog: impl Into<Arc<Catalog>>) -> EngineBuilder

    Starts an engine from a catalog. The default strategy is MostSpecific and the relation depth is 32.

  • EngineBuilder::build

    pub fn build(self) -> Result<Engine, EngineError>

    Builds the engine. Fails if an override exception names a permission outside the catalog.

Builder methodSignatureWhat it does
rolespub fn roles(mut self, roles: RoleGraph) -> SelfSets role inheritance.
relationspub fn relations(mut self, schema: RelationSchema) -> SelfTurns on ReBAC with this schema.
conditionspub fn conditions(mut self, registry: ConditionRegistry) -> SelfRegisters custom condition functions.
strategypub fn strategy(mut self, strategy: impl Strategy + 'static) -> SelfPicks how applicable grants combine.
override_withpub fn override_with(self, rule: impl Override + 'static) -> SelfAdds an override that decides before the grants.
override_exceptpub fn override_except<I, S>(mut self, rule: impl Override + 'static, except: I) -> SelfAdds an override that does not reach the listed permissions.
max_relation_depthpub fn max_relation_depth(mut self, depth: usize) -> SelfCaps ReBAC recursion.

From a policy file#

There is no direct call from a policy to an engine. Parse the text, take its EngineSpec, then build.

  • dsl::parse

    pub fn parse(file: &str, text: &str) -> Result<Parsed, Diagnostics>

    Reads and validates policy text. Parsed.policy is the Policy. Needs the dsl feature.

  • Policy::engine_spec

    pub fn engine_spec(&self) -> EngineSpec

    From a parsed policy to an EngineSpec.

  • EngineSpec::build

    pub fn build(&self) -> Result<Engine, SpecError>

    Builds an engine from JSON, TOML or YAML configuration.

  • EngineSpec::builder

    pub fn builder(&self) -> Result<EngineBuilder, SpecError>

    The same, but returns the builder so you can add what does not serialize, such as condition functions.

Deciding#

  • pub fn decide(&self, ctx: &Context<'_>, request: &Request<'_>) -> Decision

    Allows or denies the request and says why.

  • pub fn check(&self, ctx: &Context<'_>, request: &Request<'_>) -> bool

    decide(..).is_allowed(), nothing else.

  • pub fn explain(&self, ctx: &Context<'_>, request: &Request<'_>) -> Explanation

    The same decision as decide, plus the trace of every override and grant. Costs more.

  • Engine::decide_without_overrides

    pub fn decide_without_overrides(&self, ctx: &Context<'_>, request: &Request<'_>) -> Decision

    Decides by grants only, for overrides that depend on a permission. Prerequisites (depends_on) still apply.

  • Engine::capabilities

    pub fn capabilities(&self, ctx: &Context<'_>, subject: &Subject, scope: &Resource) -> CapabilitySet

    Preloads the grants that may hold for a subject in a scope. The result is a GrantSource for repeated decisions.

  • Engine::validate_grant

    pub fn validate_grant(&self, grant: &Grant) -> Result<(), GrantError>

    Checks a grant against the catalog and the configuration before you store it.

Queries#

These take a QueryContext, which carries limits as well as the grants.

  • pub fn check_for(&self, ctx: &QueryContext<'_>, resolver: &dyn SubjectResolver, subject: &SubjectRef, permission: &str, resource: &Resource) -> Result<CheckAnswer, QueryError>

    Decides for a subject reference loaded by resolver and names the path that decided. A subject it cannot load is an error, never an allow.

  • pub fn list(&self, ctx: &QueryContext<'_>, subject: &Subject, permission: &str, kind: &str) -> AccessFilter

    What of kind the subject reaches, as a filter. Its residual() must be checked row by row.

  • pub fn who_can_on(&self, ctx: &QueryContext<'_>, permission: &str, resource: &Resource) -> Result<WhoCan, QueryError>

    Who holds the permission on this resource, overrides included.

  • Engine::who_can

    pub fn who_can(&self, ctx: &QueryContext<'_>, permission: &str) -> Vec<SubjectRef>

    Parties named by an allow grant anywhere. It evaluates nothing.

  • Engine::access_of

    pub fn access_of(&self, ctx: &QueryContext<'_>, resource: &Resource) -> Result<Vec<PartyAccess>, QueryError>

    Who has access to the resource, with each party's permissions.

Decision#

There are no getters besides is_allowed: the reason, the deciding grant and the trail are public fields.

  • pub struct Decision { pub effect: Effect, pub reason: Reason, pub matched: Vec<String>, pub warnings: Vec<String> }

    Allow or deny, why, every grant id that applied in source order, and problems that did not stop the decision.

  • Decision::is_allowed

    pub fn is_allowed(&self) -> bool

    True only when effect == Effect::Allow.

  • pub enum Reason

    Why the decision came out that way. Serialized with the tag kind, in snake_case.

VariantIt means
Override { name: String }An override decided before the grants.
Grant { grant_id: String, permission: String, rank: usize, strategy: String }A grant decided; this is the deciding grant. rank 0 is the most specific step.
NoApplicableGrantNo grant applied: default deny.
UnknownPermissionThe permission is not in the catalog: deny.
MissingPrerequisite { permission: String, prerequisite: String }Would be allowed, but a depends_on prerequisite is not allowed on the same resource.
  • Effect

    pub enum Effect { Allow, Deny }

    The outcome of a decision or of a grant.

  • Explanation

    pub struct Explanation { pub subject: Subject, pub permission: String, pub resource: Resource, pub effective: Vec<String>, pub path: Vec<Anchor>, pub roles: Vec<String>, pub overrides: Vec<OverrideStep>, pub grants: Vec<GrantTrace>, pub strategy: String, pub prerequisites: Vec<PrerequisiteStep>, pub decision: Decision }

    The trail: the resource path, the roles in force, each override and each grant with its fate, then the decision. prerequisites holds the depends_on checks made once the permission was allowed.

Request types#

  • pub fn new(subject: &'a Subject, permission: &'a str, resource: &'a Resource) -> Self

    The question: can this subject do this permission on this resource.

  • Resource::new, Resource::within

    pub fn new(kind: impl Into<String>, id: impl Into<String>) -> Self
    pub fn within(mut self, kind: impl Into<String>, id: impl Into<String>) -> Self

    The resource itself, then each broader step. The path runs from most specific to broadest, with an implicit global at the end.

  • Subject::user

    pub fn user(id: impl Into<String>) -> Self

    A user by id. Add roles with with_role or with_role_in, attributes with with_attr.

  • Subject::with_role_in

    pub fn with_role_in(mut self, role: impl Into<String>, scope: Anchor) -> Self

    A role held only under that step of the path.

  • Context::new

    pub fn new(grants: &'a dyn GrantSource) -> Self

    The data of one decision, over a grant source. A Vec<Grant> works.

  • Context::at

    pub fn at(mut self, now: u64) -> Self

    The decision instant, in ms since the epoch. Without it, windowed allows are ignored and windowed denies hold.

Grants#

  • pub fn allow(id: impl Into<String>, subject: SubjectMatcher, permission: impl Into<String>, target: TargetSelector) -> Self

    An allow grant. Grant::deny takes the same arguments.

  • Grant::scoped, Grant::when

    pub fn scoped(mut self, scope: Anchor) -> Self
    pub fn when(mut self, condition: Condition) -> Self

    Only under a step of the path; only when the condition is true.

  • Grant::valid_between

    pub fn valid_between(self, from: u64, until: u64) -> Self

    A validity window [from, until) in ms. try_valid_between returns Result<Self, ValidityError>.

  • SubjectMatcher

    pub enum SubjectMatcher { User { id: String }, Role { id: String }, Principal { name: String }, Relation { relation: String }, Any }

    Whom the grant applies to. Constructors user, role, principal, relation; Any has none, so use the variant.

  • TargetSelector

    pub struct TargetSelector { pub kind: String, pub id: Option<String> }

    Where the grant sits on the path: global() everywhere, kind(..) any instance of a kind, exact(..) one instance.

Strategy#

  • pub trait Strategy: Send + Sync { fn name(&self) -> &'static str; fn combine(&self, candidates: &[Candidate]) -> Option<usize>; fn native(&self) -> Option<NativeStrategy> { None } }

    How applicable grants combine. A trait, with four unit structs. native says which of the four a strategy is, so a listing can reproduce it; with None, the default, the listing leaves a residue to check row by row.

Rust typeIn a policyThe deciding grant
MostSpecificmost_specificThe most specific step with any grant decides; on it, deny wins. The default.
DenyOverridesdeny_overridesAny deny wins.
PermitOverridespermit_overridesAny allow wins.
FirstApplicablefirst_applicableThe first grant in source order decides.

Errors#

A deny is never an error: decide always returns a Decision, and an unknown permission is Reason::UnknownPermission. Errors come from building and validating.

TypeVariantsFrom
EngineErrorUnknownPermission(String)EngineBuilder::build
GrantErrorEmptyId, UnknownPermission(String), UnknownTargetKind(String), TargetNotAllowed { permission, target }, OverrideOnly(String), RelationsDisabled, UnknownFunction(String), InvalidWindow(ValidityError), InvalidField(String), UnknownField { permission, field }Engine::validate_grant
SpecErrorCatalog(CatalogErrors), Roles(RbacError), Engine(EngineError)EngineSpec::build
QueryErrorUnknownSubject(SubjectRef), LimitExceeded { what, limit }, RelationDepthExceeded { grant_id }check_for, who_can_on, access_of
dsl::DiagnosticsA list of Diagnostic { location, message, hint, related }dsl::parse
VariantMessage
EngineError::UnknownPermissionexceção de override cita permissão fora do catálogo: {0}
GrantError::EmptyIdgrant sem id
GrantError::UnknownPermissionpermissão desconhecida: {0}
GrantError::UnknownTargetKindtipo de alvo não registrado: {0}
GrantError::TargetNotAlloweda permissão {permission} não aceita alvo {target}
GrantError::OverrideOnlya permissão {0} vale só por override e não pode ser citada em grant
GrantError::RelationsDisabledgrant por relação exige RelationSchema no motor
GrantError::UnknownFunctioncondição chama função não registrada: {0}
GrantError::InvalidWindowjanela de validade inválida: {0}
GrantError::InvalidFieldcampo inválido '{0}': use segmentos [A-Za-z_][A-Za-z0-9_]* separados por ponto
GrantError::UnknownFielda permissão {permission} não declara o campo {field}

The Rust core has no string error codes; the packages and the server map each variant to a closed error code. The deprecation policy says how a change to a variant is announced.

Fields and revisions#

A field permission narrows what a subject may use inside a resource; a revision pins a decision to a point in the history of a data scope. Walk-throughs: Field permissions and Consistency.

FieldSet

The fields of a resource a subject may use for a permission, as Engine::allowed_fields answers.

MethodSignature
containspub fn contains(&self, field: &str) -> bool
is_nonepub fn is_none(&self) -> bool
is_allpub fn is_all(&self) -> bool

FieldVerdict

Why one field came out allowed or denied.

FieldExplanation

The per-field trace of Engine::explain_fields.

Revision

A position in the history of one data scope.

MethodSignature
newpub fn new(scope: impl Into<String>, value: u64) -> Self
scopepub fn scope(&self) -> &str
valuepub fn value(&self) -> u64
reached_bypub fn reached_by(required: &Revision, have: Option<&Revision>) -> Reached
reachespub fn reaches(&self, required: &Revision) -> Reached
advancedpub fn advanced(&self, by: u64) -> Self

Reached

How a revision a holder has compares with the one a decision requires.

MethodSignature
is_reachedpub fn is_reached(self) -> bool

DEFAULT_SCOPE

The scope an empty one is read as.

RevisionParseError

The text did not read as a revision token.

RevisionSource

Where revisions come from: the store that persists the changes of one data scope.

MemoryRevisions

A RevisionSource that counts in memory, for the memory and file stores and for tests.

MethodSignature
newpub fn new(scope: impl Into<String>) -> Self
starting_atpub fn starting_at(scope: impl Into<String>, value: u64) -> Self

Revised

A value together with the revision its write was given.

MethodSignature
newpub fn new(value: T, revision: Option<Revision>) -> Self

Governance, impact and why-not#

Invariants that every change to grants must keep, the impact of a change before it lands, and the smallest changes that would turn a deny into an allow. Walk-throughs: Impact, Why not and Separation of duties.

Mutation

Proposed change to the grant set or to a subject's roles.

MethodSignature
role_changepub fn role_change(&self) -> Option<(&Subject, &RoleAssignment, bool)>
kindpub fn kind(&self) -> MutationKind
subject_afterpub fn subject_after(&self) -> Option<Subject>

MutationKind

The kind of a Mutation, without its payload.

MethodSignature
as_strpub fn as_str(self) -> &'static str

Proposal

What an invariant sees: who changes, what, and the set before and after.

MethodSignature
newpub fn new(actor: &'a Subject, mutation: &'a Mutation, before: &'a [Grant], after: &'a [Grant]) -> Self
with_tuplespub fn with_tuples(mut self, tuples: &'a dyn TupleStore) -> Self
with_nowpub fn with_now(mut self, now: u64) -> Self
grantpub fn grant(&self) -> Option<&'a Grant>
subject_afterpub fn subject_after<'s>(&self, subject: &'s Subject) -> Cow<'s, Subject>
before_contextpub fn before_context(&self) -> Context<'_>
after_contextpub fn after_context(&self) -> Context<'_>

Suggestion

Compensating change proposed with a Violation.

MethodSignature
into_mutationpub fn into_mutation(self, subject: Subject) -> Mutation
subject_idpub fn subject_id(&self) -> &str

Violation

MethodSignature
newpub fn new(invariant: impl Into<String>, message: impl Into<String>) -> Self

Invariant

Rule that every grant or role change must respect.

AppliedWithImpact

A change applied together with what it does to access, from Governance::apply_with_impact.

Governance

Applies grant and role changes only after they pass every invariant and, with the audit feature, after recording the decision.

MethodSignature
newpub fn new() -> Self
withpub fn with(mut self, invariant: impl Invariant + 'static) -> Self
auditedpub fn audited(mut self, auditor: Arc<Auditor>) -> Self
with_revisionspub fn with_revisions(mut self, source: Arc<dyn RevisionSource>) -> Self
apply_revisedpub fn apply_revised( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> Result<Revised<Vec<Grant>>, Vec<Violation>>
lenpub fn len(&self) -> usize
is_emptypub fn is_empty(&self) -> bool
applypub fn apply( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>) -> Result<Vec<Grant>, Vec<Violation>>
atpub fn at(&self, now: u64) -> GovernanceAt<'_>
apply_withpub fn apply_with( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> Result<Vec<Grant>, Vec<Violation>>
impactpub fn impact( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, options: &ImpactOptions<'_>) -> Result<Impact, Vec<Violation>>
apply_with_impactpub fn apply_with_impact( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes, options: &ImpactOptions<'_>) -> Result<AppliedWithImpact, Vec<Violation>>

GovernanceAt

Governance judging every change at one instant; see Governance::at.

MethodSignature
fail_modepub fn fail_mode(mut self, mode: FailMode) -> Self
apply_reportingpub fn apply_reporting( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> (Result<Vec<Grant>, Vec<Violation>>, Option<AuditStatus>)
applypub fn apply( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>) -> Result<Vec<Grant>, Vec<Violation>>
impactpub fn impact( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, options: &ImpactOptions<'_>) -> Result<Impact, Vec<Violation>>
apply_with_impactpub fn apply_with_impact( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes, options: &ImpactOptions<'_>) -> Result<AppliedWithImpact, Vec<Violation>>
apply_revisedpub fn apply_revised( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> Result<Revised<Vec<Grant>>, Vec<Violation>>
apply_withpub fn apply_with( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> Result<Vec<Grant>, Vec<Violation>>

CatalogConformance

The added grant exists in the catalog and targets a kind the permission accepts.

NoSelfManagement

Nobody changes a grant that applies to themselves: neither the user directly, nor a role they hold (direct or inherited).

RequirePermission

The actor must hold key on resource before the change.

MethodSignature
newpub fn new(key: impl Into<String>, resource: Resource) -> Self

NoLockout

After the change, each critical permission still has at least one member able to exercise it on resource.

MethodSignature
newpub fn new<I, S>(critical: I, members: Vec<Subject>, resource: Resource) -> Self where I: IntoIterator<Item = S>, S: Into<String>,
with_reservepub fn with_reserve<I>(mut self, admin_role: RoleAssignment, subjects: I) -> Self where I: IntoIterator<Item = Subject>,

Forbid

subject never receives allow on permissions or on any permission that grants them.

MethodSignature
newpub fn new<I, S>(subject: SubjectMatcher, permissions: I) -> Self where I: IntoIterator<Item = S>, S: Into<String>,

Prerequisites

Holding a permission requires holding its depends_on prerequisites on the same resource.

NonDelegable

A permission marked PermissionDef::non_delegable(crate::PermissionDef::non_delegable) is only granted by an actor who holds manager on the resource: having the permission is not enough to pass it on.

MethodSignature
newpub fn new(manager: impl Into<String>) -> Self

ManagementOnly

A permission marked PermissionDef::management_only(crate::PermissionDef::management_only) is only granted to the management roles: never straight to a user, a principal or an ordinary role.

MethodSignature
newpub fn new<I, S>(roles: I) -> Self where I: IntoIterator<Item = S>, S: Into<String>,

Bypass

Permission that exempts its holder from NoEscalation on resource.

MethodSignature
newpub fn new(permission: impl Into<String>, resource: Resource) -> Self

NoEscalation

The actor only hands out what they hold.

MethodSignature
newpub fn new() -> Self
bypasspub fn bypass(mut self, bypass: Bypass) -> Self

AUDIT_EXAMPLES

Most examples an audit record keeps.

SampleSpec

Subjects, resources and permissions to ask about, chosen by the caller.

MethodSignature
newpub fn new() -> Self
subjectpub fn subject(mut self, subject: Subject) -> Self
resourcepub fn resource(mut self, resource: Resource) -> Self
permissionpub fn permission(mut self, permission: impl Into<String>) -> Self
fieldpub fn field(mut self, field: impl Into<String>) -> Self

ImpactSource

How the subjects and the resources of an impact are found.

MethodSignature
derivedpub fn derived() -> Self
samplepub fn sample(spec: SampleSpec) -> Self

ImpactOptions

What the impact of a change is computed over.

MethodSignature
newpub fn new(source: ImpactSource) -> Self
with_tuplespub fn with_tuples(mut self, tuples: &'a dyn TupleIndex) -> Self
with_envpub fn with_env(mut self, env: &'a Attributes) -> Self
with_limitspub fn with_limits(mut self, limits: QueryLimits) -> Self
atpub fn at(mut self, now: u64) -> Self

Access

What one side of a question came out as.

AccessChange

One question whose answer the change moves.

Impact

Who gains and who loses access with a change.

MethodSignature
is_emptypub fn is_empty(&self) -> bool
summarypub fn summary(&self) -> ImpactSummary

PotentialClash

A separation clash the change would create, and who would hold it.

ImpactSummary

The impact of a change as the audit trail keeps it: counts and a bounded list of examples.

WhyNotOptions

Bounds of a Engine::why_not call.

MethodSignature
with_limitspub fn with_limits(mut self, limits: QueryLimits) -> Self
with_max_remediespub fn with_max_remedies(mut self, max_remedies: usize) -> Self

Cause

What denied the request.

Caveat

A known governance rule the remedy runs into.

Change

One change that, applied alone, makes the decision allow.

Remedy

A verified remedy.

Remedies

The answer of Engine::why_not: what denied and what would allow.

More on Engine

MethodSignature
why_notpub fn why_not(&self, ctx: &Context<'_>, request: &Request<'_>, options: &WhyNotOptions) -> Option<Remedies>

SEPARATION_PREFIX

Prefix of the name a dynamic rule has as an override (separation:&lt;rule>), in the reason of the decision and in the explanation.

Clash

Two members of a MutualExclusion that one subject holds in the same scope.

MethodSignature
describepub fn describe(&self, who: &str) -> String

SeparationOfDuties

Nobody accumulates two members of a MutualExclusion of the catalog in the same scope.

MethodSignature
newpub fn new() -> Self
with_subjectspub fn with_subjects<I: IntoIterator<Item = Subject>>(mut self, subjects: I) -> Self

SeparationRule

A dynamic rule of the catalog as an override that only denies.

MethodSignature
newpub fn new(rule: ActionConflict) -> Self

Approvals, elevation and recertification#

Changes that wait for a reviewer, time-boxed elevation, and periodic review of who holds what. Walk-throughs: Approvals, Elevation and Recertification.

ApprovalRule

Who may approve a kind of change: whoever holds permission on resource.

ApprovalPolicy

The kinds of change that wait for approval.

MethodSignature
newpub fn new() -> Self
from_rulespub fn from_rules(rules: impl IntoIterator<Item = ApprovalRule>) -> Self
requirepub fn require(mut self, kind: MutationKind, permission: impl Into<String>, resource: Resource) -> Self
require_allpub fn require_all(self, permission: impl Into<String>, resource: Resource) -> Self
rule_forpub fn rule_for(&self, mutation: &Mutation) -> Option<&ApprovalRule>
rulespub fn rules(&self) -> &[ApprovalRule]

PendingStatus

Where a request stands.

PendingRequest

A change waiting for another actor.

MethodSignature
newpub fn new(id: impl Into<String>, actor: Subject, mutation: Mutation, requested_at: u64) -> Self
expiring_atpub fn expiring_at(mut self, expires_at: Option<u64>) -> Self
with_statuspub fn with_status(mut self, status: PendingStatus) -> Self
with_impactpub fn with_impact(mut self, impact: Impact) -> Self
with_elevationpub fn with_elevation(mut self, elevation: ElevationInfo) -> Self
is_pendingpub fn is_pending(&self) -> bool
is_duepub fn is_due(&self, now: u64) -> bool
targetpub fn target(&self) -> String

PendingError

PendingStore

Where the requests are kept.

MemoryPendingStore

PendingStore in memory.

MethodSignature
newpub fn new() -> Self

ApprovalError

Review

What a change is judged against: the grants as they are now, the tuples, the instant and the metadata of the call (ip, request id, reason) that the audit keeps from the detailed level.

MethodSignature
newpub fn new(engine: &'a Engine, current: &'a [Grant], now: u64, meta: &'a Attributes) -> Self
with_tuplespub fn with_tuples(mut self, tuples: &'a dyn TupleStore) -> Self
with_nowpub fn with_now(mut self, now: u64) -> Self
with_currentpub fn with_current(mut self, current: &'a [Grant]) -> Self

Proposed

The outcome of Approvals::propose.

Approved

A request approved and applied: the grants to persist (unchanged for a role change; the subject to write comes from Mutation::subject_after of the request) and the request as it now stands.

ImpactReview

The impact of a pending request as proposed and as it would be now, from Approvals::review_impact.

Approvals

The approval flow over a Governance, an ApprovalPolicy and a PendingStore.

MethodSignature
newpub fn new(governance: &'a Governance, policy: &'a ApprovalPolicy, store: &'a dyn PendingStore) -> Self
with_distinct_rolespub fn with_distinct_roles(mut self) -> Self
with_impactpub fn with_impact(mut self, options: &'a ImpactOptions<'a>) -> Self
review_impactpub fn review_impact(&self, review: &Review<'_>, id: &str) -> Result<ImpactReview, ApprovalError>
fail_modepub fn fail_mode(mut self, mode: FailMode) -> Self
pendingpub fn pending(&self, now: u64) -> Result<Vec<PendingRequest>, PendingError>
proposepub fn propose( &self, review: &Review<'_>, actor: &Subject, mutation: &Mutation, id: impl Into<String>, expires_at: Option<u64>) -> Result<Proposed, ApprovalError>
approvepub fn approve(&self, review: &Review<'_>, approver: &Subject, id: &str) -> Result<Approved, ApprovalError>
rejectpub fn reject( &self, review: &Review<'_>, approver: &Subject, id: &str, reason: &str) -> Result<PendingRequest, ApprovalError>
expire_duepub fn expire_due(&self, now: u64, meta: &Attributes) -> Result<Vec<PendingRequest>, ApprovalError>

ElevationTarget

What an elevation gives: a role, or a permission on a target.

MethodSignature
rolepub fn role(role: impl Into<String>) -> Self
permissionpub fn permission(permission: impl Into<String>, target: TargetSelector) -> Self
scopedpub fn scoped(mut self, new_scope: Anchor) -> Self
keypub fn key(&self) -> ElevationKey

ElevationKey

A role or a permission, as the policy names it.

ElevationRule

How a role or permission may be elevated.

MethodSignature
newpub fn new( key: ElevationKey, max_duration_ms: u64, approver_permission: impl Into<String>, approver_resource: Resource) -> Self
requiring_justificationpub fn requiring_justification(mut self) -> Self
allowing_break_glasspub fn allowing_break_glass(mut self, max_duration_ms: u64) -> Self

BreakGlassRule

The limit of a break-glass elevation.

ElevationPolicy

The roles and permissions that can be elevated, and how.

MethodSignature
newpub fn new() -> Self
from_rulespub fn from_rules(rules: impl IntoIterator<Item = ElevationRule>) -> Self
withpub fn with(mut self, rule: ElevationRule) -> Self
rule_forpub fn rule_for(&self, target: &ElevationTarget) -> Option<&ElevationRule>
rulespub fn rules(&self) -> &[ElevationRule]

ElevationRequest

A request for an elevation.

MethodSignature
newpub fn new(id: impl Into<String>, actor: Subject, target: ElevationTarget, duration_ms: u64) -> Self
justifiedpub fn justified(mut self, justification: impl Into<String>) -> Self
break_glasspub fn break_glass(mut self) -> Self

ElevationInfo

What a PendingRequest says about the elevation it carries.

MethodSignature
newpub fn new(target: ElevationTarget, duration_ms: u64) -> Self

ReviewState

Where the review of a break-glass elevation stands.

Revocation

An elevation taken back before its time.

MethodSignature
newpub fn new(by: impl Into<String>, at: u64, reason: Option<String>) -> Self

Elevated

The outcome of Elevations::request.

Revoked

An elevation revoked and the grants to persist.

Elevations

The elevation flow over a Governance, an ElevationPolicy and a PendingStore.

MethodSignature
newpub fn new(governance: &'a Governance, policy: &'a ElevationPolicy, store: &'a dyn PendingStore) -> Self
with_impactpub fn with_impact(mut self, options: &'a ImpactOptions<'a>) -> Self
fail_modepub fn fail_mode(mut self, mode: FailMode) -> Self
activepub fn active(&self, now: u64) -> Result<Vec<PendingRequest>, PendingError>
pending_reviewspub fn pending_reviews(&self) -> Result<Vec<PendingRequest>, PendingError>
expire_duepub fn expire_due(&self, now: u64, meta: &Attributes) -> Result<Vec<PendingRequest>, ApprovalError>
requestpub fn request( &self, review: &Review<'_>, req: &ElevationRequest, expires_at: Option<u64>) -> Result<Elevated, ApprovalError>
approvepub fn approve(&self, review: &Review<'_>, approver: &Subject, id: &str) -> Result<Approved, ApprovalError>
rejectpub fn reject( &self, review: &Review<'_>, approver: &Subject, id: &str, reason: &str) -> Result<PendingRequest, ApprovalError>
revokepub fn revoke( &self, review: &Review<'_>, by: &Subject, id: &str, reason: Option<&str>) -> Result<Revoked, ApprovalError>
close_reviewpub fn close_review( &self, review: &Review<'_>, reviewer: &Subject, id: &str, note: &str) -> Result<PendingRequest, ApprovalError>

More on PendingRequest

MethodSignature
elevation_activepub fn elevation_active(&self, now: u64) -> bool

RecertError

Why a recertification step failed.

ReviewerRule

Who may review an item.

MethodSignature
permissionpub fn permission(permission: impl Into<String>, resource: Resource) -> Self
rolepub fn role(role: impl Into<String>) -> Self
subjectpub fn subject(id: impl Into<String>) -> Self

ReviewerRoute

Sends the items about one permission or role to a reviewer rule other than the campaign's default.

MethodSignature
for_permissionpub fn for_permission(permission: impl Into<String>, reviewer: ReviewerRule) -> Self
for_rolepub fn for_role(role: impl Into<String>, reviewer: ReviewerRule) -> Self

RecertScope

What a campaign reviews.

MethodSignature
newpub fn new() -> Self
anchoredpub fn anchored(mut self, anchor: Anchor) -> Self
permissionspub fn permissions<I, S>(mut self, permissions: I) -> Self where I: IntoIterator<Item = S>, S: Into<String>,
rolespub fn roles<I, S>(mut self, roles: I) -> Self where I: IntoIterator<Item = S>, S: Into<String>,
subject_kindspub fn subject_kinds<I, S>(mut self, kinds: I) -> Self where I: IntoIterator<Item = S>, S: Into<String>,

DefaultAction

What runs on an item nobody reviewed when the campaign closes.

CampaignSpec

What a campaign is made of, before it opens.

MethodSignature
newpub fn new( id: impl Into<String>, reviewer: ReviewerRule, reviewer_permission: impl Into<String>, reviewer_resource: Resource, due_at: u64, keep_period_ms: u64) -> Self
namedpub fn named(mut self, name: impl Into<String>) -> Self
scopedpub fn scoped(mut self, scope: RecertScope) -> Self
routedpub fn routed(mut self, route: ReviewerRoute) -> Self
defaulting_topub fn defaulting_to(mut self, action: DefaultAction) -> Self
escalating_topub fn escalating_to(mut self, reviewer: ReviewerRule) -> Self

RecertTarget

The access an item is about.

MethodSignature
labelpub fn label(&self) -> String

Delegation

A reviewer handing an item over.

ItemState

Where an item stands.

RecertItem

One access to certify.

MethodSignature
is_openpub fn is_open(&self) -> bool

CampaignStatus

Where a campaign stands.

Campaign

A recertification campaign and its items.

MethodSignature
is_openpub fn is_open(&self) -> bool
itempub fn item(&self, id: &str) -> Option<&RecertItem>
open_itemspub fn open_items(&self) -> impl Iterator<Item = &RecertItem>
certifiedpub fn certified(&self, now: u64) -> impl Iterator<Item = &RecertItem>
reportpub fn report(&self) -> CampaignReport

ReviewerTally

What each reviewer did.

CampaignReport

A campaign counted by outcome and by reviewer, from Campaign::report.

RecertDecision

What a reviewer decides about an item.

Decided

A decision taken and the grants to persist.

Closed

A campaign closed: the grants to persist, the subjects whose roles changed and the report.

RecertStore

Where the campaigns are kept.

MemoryRecertStore

RecertStore in memory.

MethodSignature
newpub fn new() -> Self

Recertifications

The recertification flow over a Governance and a RecertStore.

MethodSignature
newpub fn new(governance: &'a Governance, store: &'a dyn RecertStore) -> Self
with_impactpub fn with_impact(mut self, options: &'a ImpactOptions<'a>) -> Self
fail_modepub fn fail_mode(mut self, mode: FailMode) -> Self
open_campaignspub fn open_campaigns(&self) -> Result<Vec<Campaign>, RecertError>
reportpub fn report(&self, id: &str) -> Result<CampaignReport, RecertError>
openpub fn open( &self, review: &Review<'_>, opener: &Subject, spec: CampaignSpec, subjects: &[Subject]) -> Result<Campaign, RecertError>
decidepub fn decide( &self, review: &Review<'_>, reviewer: &Subject, id: &str, item: &str, decision: RecertDecision, reason: Option<&str>) -> Result<Decided, RecertError>
closepub fn close(&self, review: &Review<'_>, closer: &Subject, id: &str) -> Result<Closed, RecertError>

Audit#

Audit records carry AUDIT_FORMAT 1: a hash chain per sink, Merkle proofs over it, optional RFC 3161 timestamps, and a report. Walk-through: Audit.

AUDIT_FORMAT

Version of the audit record format: the canonical form and the hash of the chain fixed in docs/audit-format.md.

AuditLevel

How much of each change is recorded.

MethodSignature
typical_record_bytespub const fn typical_record_bytes(self) -> u64
typical_decision_bytespub const fn typical_decision_bytes(self) -> u64
estimate_decision_bytespub const fn estimate_decision_bytes(self, records: u64) -> u64
estimate_bytespub const fn estimate_bytes(self, records: u64) -> u64

AuditAction

AuditOutcome

DecisionSummary

Summary of a decision, kept from AuditLevel::Standard upward.

GrantSummary

Summary of a grant, kept from AuditLevel::Standard upward.

RoleChange

Recorded role assignment.

PendingRef

The pending request an approval-flow record is about, kept from AuditLevel::Standard upward.

RecertRef

The campaign and item a recertification record is about, kept from AuditLevel::Standard upward.

AuditRecord

One record of the trail.

AuditError

AuditSink

Destination of the records.

FailMode

What happens to a change when its audit record cannot be written.

AuditStatus

Where a record ended up.

DroppedRecord

A record the retry queue could not keep.

DropHook

Called, outside any lock, for each record dropped because the queue was full.

RetryPolicy

Limits of the retry queue that open mode feeds.

MethodSignature
with_capacitypub fn with_capacity(mut self, capacity: usize) -> Self
with_base_delay_mspub fn with_base_delay_ms(mut self, base_delay_ms: u64) -> Self
with_max_delay_mspub fn with_max_delay_ms(mut self, max_delay_ms: u64) -> Self
with_on_droppub fn with_on_drop(mut self, on_drop: DropHook) -> Self

AuditStats

Counters of the retry queue, for a metric or a health check.

PendingQueue

The retry queue of open mode.

MethodSignature
newpub fn new(policy: RetryPolicy) -> Self
statspub fn stats(&self) -> AuditStats
pendingpub fn pending(&self) -> Vec<AuditRecord>
flushpub fn flush(&self, sink: &dyn AuditSink, now: u64, force: bool) -> usize

Emitted

A record and where it ended up.

Redactor

Masks the sensitive parts of a record before it is hashed and written.

Observer

Called with every record the auditor accepted, written or queued, and where it ended up.

MemoryAuditLog

In-memory records, for tests and for callers who drain the trail themselves.

MethodSignature
newpub fn new() -> Self
recordspub fn records(&self) -> Vec<AuditRecord>
drainpub fn drain(&self) -> Vec<AuditRecord>

JsonLinesAudit

One JSON record per line on a Write (file, socket, stdout).

MethodSignature
newpub fn new(out: W) -> Self
into_innerpub fn into_inner(self) -> W

Clock

Auditor

Builds the records at the configured level and hands them to the sink.

MethodSignature
newpub fn new(level: AuditLevel, sink: Arc<dyn AuditSink>) -> Self
with_fail_modepub fn with_fail_mode(mut self, mode: FailMode) -> Self
with_permission_fail_modepub fn with_permission_fail_mode(mut self, permission: impl Into<String>, mode: FailMode) -> Self
with_retrypub fn with_retry(mut self, policy: RetryPolicy) -> Self
with_queuepub fn with_queue(mut self, queue: Arc<PendingQueue>) -> Self
with_redactorpub fn with_redactor(mut self, redactor: Redactor) -> Self
observepub fn observe(mut self, observer: impl Fn(&AuditRecord, AuditStatus) + Send + Sync + 'static) -> Self
queuepub fn queue(&self) -> &Arc<PendingQueue>
statspub fn stats(&self) -> AuditStats
flushpub fn flush(&self) -> usize
chain_headpub fn chain_head(&self) -> Option<String>
with_clockpub fn with_clock(mut self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self
resume_chainpub fn resume_chain(self, last_hash: impl Into<String>) -> Self
levelpub fn level(&self) -> AuditLevel
decidepub fn decide( &self, engine: &Engine, ctx: &Context<'_>, request: &Request<'_>, meta: &Attributes) -> (Decision, Result<AuditRecord, AuditError>)
decisionpub fn decision( &self, request: &Request<'_>, decision: &Decision, meta: &Attributes) -> Result<AuditRecord, AuditError>
explainedpub fn explained(&self, explanation: &Explanation, meta: &Attributes) -> Result<AuditRecord, AuditError>
grant_mutationpub fn grant_mutation( &self, actor: &Subject, mutation: &Mutation, before: &[Grant], result: &Result<Vec<Grant>, Vec<Violation>>, meta: &Attributes) -> Result<AuditRecord, AuditError>
grant_mutation_withpub fn grant_mutation_with( &self, actor: &Subject, mutation: &Mutation, before: &[Grant], result: &Result<Vec<Grant>, Vec<Violation>>, meta: &Attributes, call: Option<FailMode>) -> Result<Emitted, AuditError>
grant_mutation_impactpub fn grant_mutation_impact( &self, actor: &Subject, mutation: &Mutation, before: &[Grant], result: &Result<Vec<Grant>, Vec<Violation>>, meta: &Attributes, call: Option<FailMode>, impact: Option<&Impact>) -> Result<Emitted, AuditError>
tuple_changepub fn tuple_change( &self, actor: &Subject, added: bool, tuple: &Tuple, outcome: AuditOutcome, meta: &Attributes) -> Result<AuditRecord, AuditError>
exclusivepub fn exclusive( &self, actor: &Subject, action: AuditAction, resource: &ObjectRef, outcome: AuditOutcome, at: u64, meta: &Attributes) -> Result<AuditRecord, AuditError>
role_changepub fn role_change( &self, actor: &Subject, assigned: bool, change: &RoleChange, outcome: AuditOutcome, meta: &Attributes) -> Result<AuditRecord, AuditError>

ChainError

Hash

A SHA-256 digest.

MerkleError

Why a proof was refused.

MerkleTree

A tree kept in memory, for building proofs over a stretch of the trail.

MethodSignature
newpub fn new(leaves: Vec<Hash>) -> Self
from_recordspub fn from_records(records: &[AuditRecord]) -> Result<Self, AuditError>
sizepub fn size(&self) -> usize
rootpub fn root(&self) -> Hash
root_atpub fn root_at(&self, size: usize) -> Option<Hash>
inclusion_proofpub fn inclusion_proof(&self, index: usize) -> Option<Vec<Hash>>
consistency_proofpub fn consistency_proof(&self, first: usize) -> Option<Vec<Hash>>

TimestampError

Why a request could not be built or a response was refused.

MethodSignature
codepub fn code(&self) -> &'static str

HashAlgorithm

A hash algorithm for the stamped digest.

MethodSignature
namepub fn name(self) -> &'static str

TimestampRequest

A TimeStampReq (RFC 3161 §2.4.1) to send to a TSA.

MethodSignature
newpub fn new(algorithm: HashAlgorithm, digest: Vec<u8>) -> Self
for_chain_headpub fn for_chain_head(head: &str, nonce: Option<u64>) -> Result<Self>
to_derpub fn to_der(&self) -> Result<Vec<u8>>

TimestampInfo

What a verified time stamp states.

VerifyOptions

What to check besides the signature.

MethodSignature
newpub fn new(imprint: Vec<u8>, trusted_roots: Vec<Vec<u8>>) -> Self
for_chain_headpub fn for_chain_head(head: &str, trusted_roots: Vec<Vec<u8>>) -> Result<Self>

LineError

A line of a JSON Lines trail that is not an audit record.

Period

The span of time the records cover.

BreakKind

How a record fails the chain.

ChainBreak

One place where the chain does not hold.

ChainStatus

The state of the hash chain.

Anchors

Anchors known from outside the trail.

MethodSignature
headpub fn head(mut self, head: impl Into<String>) -> Self
startpub fn start(mut self, start: impl Into<String>) -> Self

AnchorCheck

Outcome of comparing the trail with an anchor.

TimestampCheck

Result of verifying one time stamp, filled by the caller (see timestamp).

MethodSignature
verifiedpub fn verified(label: impl Into<String>, gen_time: i64, policy: String, serial: String) -> Self
failedpub fn failed(label: impl Into<String>, error: impl Into<String>) -> Self

ConformanceReport

The report.

MethodSignature
buildpub fn build(records: &[AuditRecord], anchors: &Anchors) -> Self
from_json_linespub fn from_json_lines(text: &str, anchors: &Anchors) -> Self
with_timestampspub fn with_timestamps(mut self, timestamps: Vec<TimestampCheck>) -> Self
is_conformingpub fn is_conforming(&self) -> bool

Policy language and tooling#

Needs the dsl feature (dsl-fs adds the file store, import the Casbin and OpenFGA importers). The DSL schema is DSL_SCHEMA 5. Walk-throughs: Policy language, Diff and lint and Importers.

MAX_SOURCE_BYTES

The largest source accepted: input is external and unbounded.

DSL_SCHEMA

The version of the canonical JSON that Policy::from_json reads, frozen as stable from 1.0: it only grows, and a reader refuses a document newer than it.

Parsed

One source read and validated.

More on Policy

MethodSignature
validatepub fn validate(&self) -> Result<(), Diagnostics>

ConvertError

Why a source could not be converted.

FormatError

Why a source could not be formatted.

Built

The policy a Project builds and where each of its elements was declared.

Project

Several sources, each in its own syntax, gathered into one policy.

MethodSignature
newpub fn new() -> Self
lenpub fn len(&self) -> usize
is_emptypub fn is_empty(&self) -> bool
add_sourcepub fn add_source(&mut self, name: &str, text: &str) -> Result<Language, Diagnostics>
buildpub fn build(&self) -> Result<Built, Diagnostics>

MAX_SOURCES

The most sources a project takes.

MAX_PROJECT_BYTES

The most bytes all the sources of a project may hold together.

MAX_FIXTURE_BYTES

The largest fixture DiffFixture::parse reads.

DiffFixture

The data a diff asks its questions about, besides the two policies.

MethodSignature
parsepub fn parse(file: &str, text: &str) -> Result<Self, DiffError>

DiffError

Why a diff could not be made.

DiffOptions

What bounds the work of a diff.

MethodSignature
with_limitspub fn with_limits(mut self, limits: QueryLimits) -> Self

DiffSide

One version of a policy and, when it came from sources, where its elements are written.

MethodSignature
newpub fn new(policy: &'a Policy) -> Self
with_originspub fn with_origins(mut self, origins: &'a Origins) -> Self

ChangeKind

Which way a decision moved.

Responsible

What decided on one side.

DecisionChange

A question whose answer differs between the two versions.

Universe

The questions a diff asked.

PolicyDiff

The decisions that differ between two versions.

MethodSignature
is_emptypub fn is_empty(&self) -> bool
countpub fn count(&self, kind: ChangeKind) -> usize

Severity

How much a finding matters.

MethodSignature
namepub const fn name(self) -> &'static str

LintCode

The kinds of finding.

MethodSignature
codepub const fn code(self) -> &'static str
namepub const fn name(self) -> &'static str
severitypub const fn severity(self) -> Severity
parsepub fn parse(text: &str) -> Option<LintCode>

Finding

One thing the lint found.

MethodSignature
lint_codepub fn lint_code(&self) -> Option<LintCode>
positionpub fn position(&self) -> Option<String>

LintOptions

What to leave out.

MethodSignature
ignoringpub fn ignoring(mut self, code: impl Into<String>) -> Self

Report

What an import did: what was converted, what had no faithful translation and what was converted with a narrower reach.

ImportError

An import that could not be completed: the Report holds what was converted and what was not.

Exclusive ownership#

Needs the exclusive feature. One holder per resource, with priority, preemption and a deadline. Walk-through: Exclusive store.

DEFAULT_HOLD_PERMISSION

Permission that allows holding a resource exclusively, unless configured otherwise.

DEFAULT_PREEMPT_PERMISSION

Permission that allows taking a resource from a lower-priority holder, unless configured otherwise.

Lease

Active or expired ownership of a resource.

MethodSignature
newpub fn new(resource: ObjectRef, holder: ObjectRef, priority: i64, acquired_at: u64, expires_at: u64) -> Self
is_activepub fn is_active(&self, now: u64) -> bool
grantedpub fn granted(claim: &Claim, now: u64) -> Self
renewedpub fn renewed(&self, now: u64, ttl_ms: u64) -> Self

Terms

Priority and duration of a claim.

MethodSignature
newpub fn new(priority: i64, ttl_ms: u64) -> Self

Claim

Request to own resource on behalf of holder.

MethodSignature
newpub fn new(resource: ObjectRef, holder: ObjectRef, terms: Terms) -> Self

Preemption

Whether ExclusiveRegistry::acquire may take a resource from a lower-priority holder.

Acquisition

Outcome of an acquisition.

MethodSignature
decidepub fn decide(current: Option<Lease>, claim: &Claim, now: u64, preemption: Preemption) -> Self

OwnedChange

Outcome of a change only the holder can make: ExclusiveStore::renew_lease and ExclusiveStore::release_lease.

MethodSignature
decidepub fn decide(current: Option<Lease>, holder: &ObjectRef, now: u64) -> Self

StoreError

Failure to read or write the lease store.

ExclusiveError

ExclusiveStore

Persistence of the leases, one per resource.

MemoryExclusiveStore

Leases in memory.

MethodSignature
newpub fn new() -> Self

ExclusivePermissions

Names of the permissions the checked acquisition asks the engine for.

MethodSignature
newpub fn new(hold: impl Into<String>, preempt: impl Into<String>) -> Self

ExclusiveRegistry

Exclusive ownership of resources over a store.

MethodSignature
newpub fn new(store: S) -> Self
with_permissionspub fn with_permissions(mut self, permissions: ExclusivePermissions) -> Self
with_max_ttlpub fn with_max_ttl(mut self, max_ttl_ms: u64) -> Self
with_auditpub fn with_audit(mut self, auditor: Arc<Auditor>) -> Self
permissionspub fn permissions(&self) -> &ExclusivePermissions
storepub fn store(&self) -> &S
validatepub fn validate(&self, engine: &Engine) -> Result<(), ExclusiveError>
holderpub fn holder(&self, resource: &ObjectRef, now: u64) -> Result<Option<Lease>, ExclusiveError>
acquirepub fn acquire(&mut self, claim: &Claim, now: u64, preemption: Preemption) -> Result<Acquisition, ExclusiveError>
acquire_checkedpub fn acquire_checked( &mut self, engine: &Engine, ctx: &Context<'_>, subject: &Subject, resource: &Resource, terms: Terms, now: u64) -> Result<Acquisition, ExclusiveError>
releasepub fn release(&mut self, resource: &ObjectRef, holder: &ObjectRef, now: u64) -> Result<Lease, ExclusiveError>
renewpub fn renew( &mut self, resource: &ObjectRef, holder: &ObjectRef, now: u64, ttl_ms: u64) -> Result<Lease, ExclusiveError>
renew_checkedpub fn renew_checked( &mut self, engine: &Engine, ctx: &Context<'_>, subject: &Subject, resource: &Resource, now: u64, ttl_ms: u64) -> Result<Lease, ExclusiveError>
expirepub fn expire(&mut self, now: u64) -> Result<Vec<Lease>, ExclusiveError>

Real time: strig-sync#

strig-sync = "0.10". A permission change becomes a Change notice; the Hub delivers it to the sessions and caches of this instance and publishes it on a Transport for the others. A notice never carries grants: whoever receives it reloads from its own source.

  • Hub::builder

    pub fn builder() -> HubBuilder
    pub fn new() -> Self

    A hub with a transport, or a local-only hub with Hub::new. The builder takes capacity(usize), origin(impl Into<String>), transport(impl Transport) and shared_transport(Arc<dyn Transport>), then build() -> Hub. The channel capacity is 1024 and the origin is random until you set one.

  • pub async fn publish(&self, mut change: Change) -> Result<Change, TransportError>

    Stamps origin, sequence and time, delivers locally and publishes on the transport. Local delivery happens even when the transport fails; the error comes back to the caller.

  • Hub::spawn_relay

    pub fn spawn_relay(&self) -> RelayHandle

    Listens to the transport in the background and delivers what the other instances publish. It reconnects with backoff from 100 ms to 5 s and emits Resync on each reconnection. It stops when the RelayHandle is dropped.

  • Hub::on_change, Hub::subscribe

    pub fn on_change(&self, sink: Arc<dyn ChangeSink>)
    pub fn subscribe(&self) -> broadcast::Receiver<Change>

    A synchronous sink for every change, or a broadcast receiver. A closure Fn(&Change) is a ChangeSink, and so is CapabilityCache.

  • Hub::schedule_expiry

    pub fn schedule_expiry(&self, boundary_ms: u64, now_ms: u64, change: Change) -> bool

    Delivers change on this instance when the clock reaches boundary_ms, so a grant that starts or stops recomputes without a write. It never goes through the transport. Returns false outside a Tokio runtime.

Change#

  • Change

    pub struct Change { pub kind: ChangeKind, pub scope: Anchor, pub subject: Option<String>, pub id: Option<String>, pub origin: String, pub seq: u64, pub at: u64 }

    What changed and on which step of the path. origin, seq and at are filled in by the hub. Serialized as JSON, which is also the wire format of the transports.

  • ChangeKind

    pub enum ChangeKind { Grants, Tuples, Roles, Catalog, Custom, Resync }

    Custom is an application change that also invalidates permissions, such as a customer plan. Resync means the node lost changes and must reload everything.

ConstructorSignature
Change::newpub fn new(kind: ChangeKind, scope: Anchor) -> Self
Change::grants, Change::tuplespub fn grants(scope: Anchor) -> Self
Change::rolespub fn roles(subject: impl Into<String>, scope: Anchor) -> Self
Change::catalog, Change::resyncpub fn catalog() -> Self
Change::expirypub fn expiry(subject: impl Into<String>) -> Self
Change::expiry_for_everyonepub fn expiry_for_everyone() -> Self
for_subject, with_idpub fn for_subject(mut self, subject: impl Into<String>) -> Self

Transport#

  • Transport

    pub trait Transport: Send + Sync + 'static { fn name(&self) -> &str; async fn publish(&self, change: &Change) -> Result<(), TransportError>; async fn subscribe(&self) -> Result<ChangeStream, TransportError>; }

    The medium between instances. Delivery is at most once: the hub covers a gap with Resync. strig-redis and strig-postgres implement it; another broker plugs in the same way. MemoryTransport::new(capacity: usize) is for tests and shares one channel between clones.

  • TransportError

    pub enum TransportError { Connection(String), Decode(String), Closed }

    Match on the variant: the text is Portuguese.

Sessions#

  • Session::open

    pub fn open(hub: &Hub, subject: Subject, scopes: Vec<Resource>, provider: Option<Arc<dyn CapabilityProvider>>, options: SessionOptions) -> (SessionControl, SessionStream)

    A client's session, independent of the web framework. The stream yields the ServerMessages to write to SSE or WebSocket; the control passes on what the client sends.

  • SessionOptions

    pub struct SessionOptions { pub heartbeat: Option<Duration>, pub buffer: usize }

    The ping interval, 25 s by default, and the messages queued for a slow client, 64 by default.

  • SessionControl

    pub async fn send(&self, message: ClientMessage) -> bool
    pub async fn handle_text(&self, text: &str) -> Result<bool, serde_json::Error>

    send returns false once the session ended. handle_text takes a WebSocket text frame; invalid JSON is an error and the session goes on.

MessageDirectionFields
ServerMessage::Helloserver to clientorigin, subject
ServerMessage::Capabilitiesserver to clientscope, set: replaces the previous set
ServerMessage::Changeserver to clientchange
ServerMessage::Resyncserver to clientnone: discard what you have and wait for new capabilities
ServerMessage::Error, Pingserver to clientmessage; none
ClientMessage::Watch, Unwatchclient to serverscopes; WebSocket only
ClientMessage::Refreshclient to servernone: ask again for every watched scope

ServerMessage has event_name, to_json and to_sse; ClientMessage::from_json reads a frame. scope_to_string(&Resource) -> String and scope_from_str(&str) -> Resource convert the kind:id/kind:id form.

Capabilities and the cache#

  • CapabilityProvider

    pub trait CapabilityProvider: Send + Sync + 'static { async fn capabilities(&self, subject: &Subject, scope: &Resource) -> Result<CapabilitySet, BoxError>; }

    Computes what a session sends to its client. evaluate and now_ms have defaults; override evaluate when you know the candidate grants, so the expiry notice sees grants that start later.

  • GrantLoader

    pub trait GrantLoader: Send + Sync + 'static { async fn load(&self, subject: &Subject, scope: &Resource) -> Result<Vec<Grant>, BoxError>; }

    Fetches the candidate grants of a subject in a scope. Return the grants that start later too. A Vec<Grant> is a loader.

  • EngineProvider

    pub fn new(engine: Arc<Engine>, loader: L) -> Self
    pub fn with_clock(mut self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self
    pub fn with_cache(mut self, cache: Arc<CapabilityCache>) -> Self

    The default provider: loads through the loader, filters with Engine::capabilities, stores in the cache. Register the same cache on the hub with hub.on_change(cache.clone()).

  • CapabilityCache

    pub fn new(ttl: Duration, capacity: usize) -> Self
    pub fn get(&self, subject: &Subject, scope: &Resource) -> Option<CapabilitySet>
    pub fn insert(&self, subject: &Subject, scope: &Resource, set: CapabilitySet)

    A cache of CapabilitySet, invalidated by the hub. TtlCache<K, V> is the generic one underneath.

axum routes: strig-axum#

strig-axum = "0.10". Authentication stays with your application: your handler identifies the subject and calls the route.

  • Realtime::new

    pub fn new(hub: Hub) -> Self
    pub fn with_provider(mut self, provider: Arc<dyn CapabilityProvider>) -> Self
    pub fn with_options(mut self, options: SessionOptions) -> Self
    pub fn hub(&self) -> &Hub

    The hub, an optional provider and the session options, shared by the routes. With a provider, a session sends the capabilities of each scope and again on every change. Realtime is Clone, so it fits axum state.

  • pub fn sse(&self, subject: Subject, scopes: Vec<Resource>) -> Sse<impl Stream<Item = Result<Event, Infallible>> + use<>>

    A text/event-stream response. SSE is one-way, so the scopes are fixed when the connection opens.

  • Realtime::websocket

    pub fn websocket(&self, upgrade: WebSocketUpgrade, subject: Subject, scopes: Vec<Resource>) -> Response

    Performs the upgrade and binds the socket to a session. The client can then send watch, unwatch and refresh; invalid JSON gets an error message and the socket stays open.

Transports#

Both are a Transport for Hub::builder().transport(..).

  • pub fn new(url: &str, channel: impl Into<String>) -> Result<Self, TransportError>
    pub fn from_client(client: Client, channel: impl Into<String>) -> Self
    pub fn channel(&self) -> &str

    strig-redis = "0.10". Redis pub/sub. Publishing reconnects on its own; each subscribe opens a dedicated connection, and when it drops the hub reopens it and emits Resync.

  • pub fn new(url: &str, channel: impl Into<String>) -> Result<Self, TransportError>
    pub fn with_tls<T>(url: &str, channel: impl Into<String>, tls: T) -> Result<Self, TransportError>

    strig-postgres = "0.10". Postgres LISTEN/NOTIFY, without TLS or with any tokio-postgres connector.

  • strig_postgres::notify

    pub async fn notify<C: GenericClient + Sync>(client: &C, channel: &str, change: &Change) -> Result<(), TransportError>

    Sends a change through a client or a transaction. NOTIFY goes out on commit, so a notice sent in the transaction that writes the grant goes out only if the write does. It arrives without an origin, so every instance delivers it, the writer included. MAX_PAYLOAD is 7999 bytes.

Postgres queries#

The strig_postgres::query module stores grants and tuples and turns a listing into a WHERE. Values reach the database as bound parameters; only table and column names are spliced into SQL, after they are checked as plain identifiers.

ItemSignatureWhat it does
PgTables::newpub fn new(grants: impl Into<String>, tuples: impl Into<String>) -> Result<Self, PgQueryError>Names the two tables; the default is strig_grants and strig_tuples.
PgTables::schema_sqlpub fn schema_sql(&self) -> StringThe DDL of both tables and their indexes. Safe to run twice.
PgTables::put_grantpub async fn put_grant<C: GenericClient>(&self, client: &C, grant: &Grant) -> Result<(), PgQueryError>Stores a grant.
PgTables::grants_by_permissionpub async fn grants_by_permission<C: GenericClient>(&self, client: &C, permissions: &[&str], now: Option<u64>) -> Result<Vec<Grant>, PgQueryError>Loads the rows a listing reads. grants_by_target_kind and grants_by_subject are the siblings.
PgTable::newpub fn new(kind: impl Into<String>, id_column: impl Into<String>) -> Result<Self, PgQueryError>The table of the resources; add path_column and attr_column.
filter_wherepub fn filter_where(filter: &AccessFilter, layout: &PathLayout, table: &PgTable, first_param: usize) -> Result<PgFilter, PgQueryError>An AccessFilter as a parameterized WHERE, with the residue to check row by row.
window_predicatepub fn window_predicate(columns: &WindowColumns, param_index: usize, now: Option<u64>) -> Result<WindowPredicate, InstantOutOfRange>The validity-window filter. Do not feed EngineProvider with it.
candidate_predicatepub fn candidate_predicate(columns: &WindowColumns, param_index: usize, now: u64) -> Result<WindowPredicate, InstantOutOfRange>Every grant that has not expired, so a grant that starts later still triggers its recompute.

PgQueryError is #[non_exhaustive] and prints English: InvalidIdentifier, UnmappedAttribute, UnmappedKind, UnsupportedExpr, EmptyUsersetRelation, Residual, InstantOutOfRange, Database, Decode. A listing that reads an attribute or a path kind with no column fails loudly, because reading it as "no row" would open access under a deny.

Postgres stores#

strig-postgres = "0.10". Every store is built from a PgTables and a connection URL; each has a connect_with_tls twin that takes a TLS connector, and with_timeout bounds every statement.

ItemSignatureWhat it does
connectpub async fn connect(url: &str) -> Result<Client, tokio_postgres::Error>Opens a plain connection and spawns its driver task.
migratepub async fn migrate(client: &Client) -> Result<Vec<u32>, PgQueryError>Brings the default tables up to LATEST_VERSION and returns the versions it applied. Additive and idempotent.
migrate_withpub async fn migrate_with(client: &Client, tables: &PgTables) -> Result<Vec<u32>, PgQueryError>The same, for custom table names.
schema_versionpub async fn schema_version(client: &Client, tables: &PgTables) -> Result<Option<u32>, PgQueryError>The version in the ledger, or None before the first migration.
PgStore::loadpub async fn load<C: GenericClient>(client: &C, tables: PgTables) -> Result<Self, PgQueryError>Reads grants and tuples into memory.
PgStore::reloadpub async fn reload<C: GenericClient>(&self, client: &C) -> Result<(), PgQueryError>Reads both again; reload_grants and reload_tuples read one.
PgStore::is_stalepub fn is_stale(&self) -> boolTrue when the last reload failed; cleared by the next one that succeeds.
PgStore::grantspub fn grants(&self) -> PgGrantsA GrantSource and GrantIndex over the snapshot; tuples gives the TupleStore and TupleIndex.
PgStore::followpub fn follow<F, Fut, E>(&self, changes: broadcast::Receiver<Change>, connect: F, retry: Duration) -> JoinHandle<()>Reloads on every Change; a failed reload is retried every retry and the store reads as stale meanwhile.
PgTables::assign_rolepub async fn assign_role<C: GenericClient>(&self, client: &C, subject: &Subject, role: &RoleAssignment) -> Result<(), PgQueryError>Stores a role assignment; revoke_role, roles_of and subject are the siblings.
PgTables::commit_mutationpub async fn commit_mutation<C: GenericClient + Sync>(&self, client: &C, channel: &str, mutation: &Mutation) -> Result<Option<Change>, PgQueryError>Applies a governed Mutation and notifies on channel, in one transaction under lock_governance.
PgPendingStoreconnect(url: &str, tables: PgTables) -> Result<Self, PgQueryError>A PendingStore in a table; due(now) lists requests past their deadline.
PgRecertStoreconnect(url: &str, tables: PgTables) -> Result<Self, PgQueryError>A RecertStore in a table.
PgExclusiveStoreconnect(url: &str, tables: PgTables) -> Result<Self, PgQueryError>An ExclusiveStore in a table. Needs the exclusive feature.

Redis store#

strig-redis = "0.10" has one public type, RedisExclusiveStore, an ExclusiveStore for a resource held across processes.

ItemSignatureWhat it does
newpub fn new(url: &str, prefix: impl Into<String>) -> Result<Self, StoreError>Does not connect yet; fails if the URL does not parse or the prefix is empty. prefix namespaces every key.
from_clientpub fn from_client(client: Client, prefix: impl Into<String>) -> Result<Self, StoreError>Reuses a client you already have.
with_timeoutpub fn with_timeout(mut self, timeout: Duration) -> SelfBounds every command.
with_retentionpub fn with_retention(mut self, retention: Duration) -> SelfHow long a lease that ran out stays in Redis for the sweep to find. Default one hour.

Decision server: strig-server#

strig-server = "0.10", with the client feature on by default. The server answers over HTTP from a DecisionSource you provide and decides with its own clock. It does no authentication and no rate limiting: put it behind your gateway. Any answer that is not a 200 from a decision route means no access.

  • pub fn new(source: Arc<dyn DecisionSource>) -> Self
    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self
    pub fn with_config(mut self, config: ServerConfig) -> Self
    pub fn router(self) -> Router

    Builds the axum router. Routes: POST /v1/check, /v1/check/batch, /v1/list, /v1/who, /v1/access, and GET /health/live, /health/ready.

  • DecisionSource

    pub trait DecisionSource: Send + Sync + 'static { async fn snapshot(&self) -> Result<Arc<Snapshot>, SourceError>; }

    Loads the data of one answer. When it fails, the server answers 503 and denies. Snapshot::new(engine: Arc<Engine>, grants: Vec<Grant>) holds the engine and the grants; MemorySource::new(snapshot) keeps one in memory, and replace swaps it without a restart.

  • ServerConfig

    pub fn with_max_body_bytes(mut self, bytes: usize) -> Self
    pub fn with_max_batch(mut self, items: usize) -> Self
    pub fn with_max_resources(mut self, items: usize) -> Self
    pub fn with_default_timeout(mut self, timeout: Duration) -> Self
    pub fn with_max_timeout(mut self, timeout: Duration) -> Self
    pub fn with_query_limits(mut self, limits: QueryLimits) -> Self
    pub fn with_max_work(mut self, work: usize) -> Self
    pub fn with_max_concurrent_work(mut self, slots: usize) -> Self

    The limits. Defaults: body 1 MiB, batch 256 checks, 1000 resources, work 1 000 000 (checks times grants), deadline 2 s with a ceiling of 10 s. A request sets its deadline with the x-strig-timeout-ms header.

Statuserror.codeMeaning
400malformed_json, invalid_request, batch_too_large, too_many_resourcesThe request is wrong; retrying it unchanged fails again.
404, 405not_found, method_not_allowedNo such route, or the wrong method.
413, 415body_too_large, unsupported_media_typeThe body is over the limit, or is not application/json.
503source_unavailable, query_limit_exceeded, overloaded, relation_depth_exceeded, deadline_exceeded, clock_unavailable, internalThe server could not decide: deny, and retry later.

The body is {"error": {"code": "...", "message": "..."}}. code is stable; message is fixed per code and never carries table names or driver text.

The Rust client#

  • pub fn http(base_url: impl Into<String>, config: ClientConfig) -> Self
    pub fn new(transport: Arc<dyn Transport>, config: ClientConfig) -> Self

    A client over plain HTTP, or over any Transport. Every call has a timeout, 2 s by default, sent to the server as the deadline. A circuit breaker opens after 5 consecutive failures and refuses calls for 30 s before it lets one probe through; 4xx does not count.

  • Client::check

    pub async fn check(&self, request: &CheckRequest) -> ClientDecision
    pub async fn check_batch(&self, requests: &[CheckRequest]) -> Vec<ClientDecision>

    CheckRequest and the other request types are in strig_server::wire. A failed check is ClientDecision::Denied(Failure), never an allow. A batch is one call and keeps the order; if it fails, every check is denied with the same cause.

  • Client::list, who, access

    pub async fn list(&self, request: &ListRequest) -> Result<ListResponse, Failure>
    pub async fn who(&self, request: &WhoRequest) -> Result<WhoResponse, Failure>
    pub async fn access(&self, request: &AccessRequest) -> Result<AccessResponse, Failure>

    There is no deny to fall back on, so they return Err(Failure): show nothing.

  • ClientDecision, Failure

    pub enum ClientDecision { Remote(CheckResponse), Denied(Failure) }

    is_allowed, effect, decision and failure read it. Failure is #[non_exhaustive]: CircuitOpen, Timeout, Unreachable, Server, Rejected, UnexpectedStatus and InvalidResponse. A code the client does not know is ErrorCode::Unknown(String).

HTTP API#

strig-server speaks JSON over HTTP. A request and its answer:

Text
curl -s localhost:8080/v1/check \
  -H 'content-type: application/json' \
  -H 'x-strig-timeout-ms: 500' \
  -d '{"subject":{"kind":"user","id":"ana"},"permission":"document.view","resource":{"kind":"document","id":"d1"}}'
JSON
{"decision": {"effect": "allow"}, "evaluated_at": 1700000000000, "requested_at": 1700000000000}

All times are milliseconds since the Unix epoch, UTC. The server decides with its own clock: at in a body is echoed for audit and never used to decide. There is no authentication and no rate limiting; put the server behind your gateway.

Fail closed. Only 200 from a decision route is a success. A network error, a timeout, any other status and an unreadable 200 all mean no access. A deny is a normal 200 with effect: "deny".

Routes#

RouteBodyAnswer
POST /v1/checksubject, permission, resource, optional env, at, min_revisiondecision, evaluated_at, requested_at, and revision when the source tracks one.
POST /v1/check/batch{"checks": [...]}{"results": [...]} in request order. All or nothing: a failure is one error, never partial results.
POST /v1/listsubject, permission, kind, optional layout, resources, env, atkind, permission, exact, shape, residual, warnings, evaluated_at, and ids when resources was sent. Never read residual as an allow.
POST /v1/whopermission, optional resource, env, atentries (each with a typed subject and the via that grants it), except, evaluated_at.
POST /v1/accessresource, env, atWho holds which permission on the resource, with the path that decided each.
GET /health/livenone200 {"status":"live"} while the process runs.
GET /health/readynone200 {"status":"ready"} when the grant source answers; otherwise 503, so the instance leaves the pool.

shape.type in a list answer is nothing, kind (with except), ids, within (with anchors) or compound (with expr).

Headers#

HeaderEffect
x-strig-timeout-ms: <n>Deadline of this request, capped at the server's ceiling (default 10 s; default deadline 2 s). 0, a negative number or text is 400 invalid_request. A passed deadline is 503 deadline_exceeded.
x-strig-min-revision: <scope>@<value>Answer only from data at that revision or later (any route; check and check/batch also take min_revision). A source that is behind is polled until the deadline, then 503 revision_not_reached. Another scope, or no revision at all, is 503 revision_mismatch at once. A malformed token is 400 invalid_request.
x-strig-reason: trueOn the AuthZEN and Envoy routes with with_reasons(true): adds a fixed reason code to the answer.

Limits#

LimitDefaultPast it
Body1 MiB413 body_too_large
Batch256 checks400 batch_too_large
Candidate resources in a list1000400 too_many_resources
Work (checks × grants)1 000 000503 query_limit_exceeded
QueryLimits for list, who, access1000 and 100 000503 query_limit_exceeded
Work slotsone per CPU503 overloaded

Errors#

JSON
{"error": {"code": "source_unavailable", "message": "the grant source is unavailable; access is denied"}}

code is stable and safe to branch on. message is fixed per code and never carries table names, paths or driver text. 4xx means the request is wrong and retrying it unchanged fails again; 503 means the server could not decide: deny, and retry later.

Statuserror.codeMeaning
400malformed_jsonThe body is not JSON.
400invalid_requestValid JSON that does not fit the route, an unknown field, a layout that does not fit kind, a bad deadline header or a malformed revision token.
400batch_too_large, too_many_resourcesOver the batch or the candidate limit.
404, 405not_found, method_not_allowedNo such route, or the wrong method.
413, 415body_too_large, unsupported_media_typeBody over the limit, or not application/json.
503source_unavailableThe grants or the policy could not be loaded.
503query_limit_exceeded, overloaded, relation_depth_exceeded, deadline_exceededA limit, the work slots, a relation chain too deep to read a deny, or the deadline.
503revision_not_reached, revision_mismatchThe source is behind the required revision, or tracks another scope.
503clock_unavailable, internalNo usable instant, or anything else inside the server, including a caught panic.

AuthZEN#

DecisionServer::with_authzen(AuthzenConfig) also serves the OpenID AuthZEN Authorization API 1.0 next to /v1; without it these routes answer 404. Same body limit, deadline, work budget and absence of authentication.

Text
curl -s localhost:8080/access/v1/evaluation \
  -H 'content-type: application/json' \
  -d '{"subject":{"type":"user","id":"ana"},"action":{"name":"document.view"},"resource":{"type":"document","id":"d1"}}'
JSON
{"decision": true}
RouteNotes
POST /access/v1/evaluation{subject, action, resource, context?} answers {decision, context?}.
POST /access/v1/evaluationsTop-level subject, action, resource, context are defaults an item overrides. options.evaluations_semantic is execute_all (default), deny_on_first_deny or permit_on_first_permit; anything else is 400.
POST /access/v1/search/subjectSubjects of subject.type that hold action.name on resource.
POST /access/v1/search/actionThe permissions of the catalog that subject holds on resource.
POST /access/v1/search/resourceOnly with AuthzenConfig::with_resource_catalog; otherwise 404.
GET /.well-known/authzen-configurationOnly with AuthzenConfig::with_issuer (an https URL); otherwise 404.
AuthZENStrig
subject.type, subject.idSubject.kind, Subject.id. Kinds in authenticated_kinds (default user) also carry the authenticated principal.
subject.propertiesAttributes. roles (default name) holds the roles, as strings or {role, scope?, valid_from?, valid_until?}; principals holds principal names. Neither becomes an attribute.
resource.type, resource.idThe first step of the path, type:id.
resource.propertiesAttributes. path (default name) holds the broader steps, most specific first. With a PathResolver the server's answer is used instead; a resource it does not know is a deny with context.error.status 404.
action.nameThe permission. action.properties is not read.
contextenv. The server replaces now with its clock.

decision is true only for an allow; a permission outside the catalog is 200 {"decision": false}. With with_reasons(true) and the header x-strig-reason: true, context.reason is one of override, grant, no_applicable_grant, unknown_permission, missing_prerequisite; it never names a grant, role or permission. Errors use the /v1 error body with the statuses of the spec: 400 for a request that does not fit, 500 for everything the server could not decide.

Searches are sorted and take page: {token?, limit?} (limit defaults to and is capped by with_max_page_size, 1000); the answer carries page: {next_token, count, total}, and next_token is "" on the last page. A token is bound to its request: change the entity, the context or the limit and it is 400. Subject search sets context.incomplete to true when a party that is not a subject of a type (role, principal, userset, wildcard, anyone) was left out. signed_metadata, capabilities, tenant suffixes of the well-known URI, action.properties and page.properties are not read.

Envoy external authorization#

With the envoy feature, DecisionServer::envoy_service(EnvoyConfig) builds the envoy.service.auth.v3.Authorization gRPC service over the same source, clock, limits and work slots as the HTTP routes. Take it before router(), which consumes the server. Without the feature the crate has no tonic or prost in its build.

CheckRequestStrig
attributes.request.http.method and pathThe first route whose methods and pattern match decides. A path with dot segments, an empty middle segment, an encoded /, \ or NUL, invalid UTF-8 or more than 64 segments matches no route.
A header (with_subject_header) or filter metadata (with_subject_metadata)The subject id, of the kind with_subject_kind (default user), with the authenticated principal. A value that is empty, over 512 bytes or holds a comma is no subject.
A header (with_roles_header), comma-separatedThe roles, up to 64 of at most 512 bytes; past that there is no subject.
RouteRule::require(permission, ResourceTemplate::new(kind, id))The permission and the resource; {param} is filled from the path. A template naming a parameter the pattern lacks fails at configuration.
with_path_resolverThe broader steps of the resource, as for AuthZEN.

Patterns start with /; a segment is a literal, {name} (one segment, captured), * (one segment) or, last, ** (the rest). Methods are * or a list such as GET,HEAD. Rules are tried in the order they were added. The adapter trusts the subject and roles it reads: Envoy must set those headers itself and overwrite what the client sent.

Casestatus.codeHTTPx-strig-reason (with with_reasons(true))
The engine allows, or the route is publicOK (0)
The engine deniesPERMISSION_DENIED (7)403denied
No route matchessame403no_route
No usable subject on a route that needs onesame403no_subject
The resolver does not know the resourcesame403unknown_resource
Source down, deadline passed, no work slot, clock or work failedsame403unavailable
No HTTP attributes, or a template that cannot be filledsame403bad_request

A public route decides nothing and does not read the source, so it allows even while the source is down. A message over max_body_bytes or a call that outlives max_timeout is a gRPC error (RESOURCE_EXHAUSTED, CANCELLED): leave failure_mode_allow: false in the Envoy filter so Envoy denies on those too.

Command line: strig-cli#

cargo install strig-cli installs the strig binary. Every command exits 0 when it did what you asked, 1 when a case failed, a finding matched or a change has no faithful translation, and 2 when the arguments, the policy or a test file are wrong or there is nothing to run.

Text
$ strig test policies/
$ echo $?
1
CommandWhat it does
strig test <dir> [--junit <file>]Runs the *.strig-test.json files of <dir> against its *.strig policy. --junit also writes JUnit XML.
strig audit report <trail.jsonl> [--json] [--anchor-head <hash>] [--anchor-start <hash>] [--timestamp <resp.tsr>]... [--root <ca.pem>]...Conformance report over an audit trail. Exits 1 when it does not conform. See Audit.
strig import casbin <model.conf> <policy.csv> -o <dir> [--language <l>] [--action <a>]...Converts a Casbin model and policy into <dir>/policy.strig. Exits 1 when part of it has no faithful translation.
strig import openfga <model> <tuples> -o <dir> [--language <l>]The same for an OpenFGA model and tuples. --action is Casbin only.
strig diff <before> <after> [--fixture <file>] [--now <ms>] [--json] [--fail-on allow|any] [--max-subjects <n>] [--max-decisions <n>]The decisions that change between two versions of a policy (directories or *.strig files). Exits 1 when a change matches --fail-on (default any).
strig lint <dir> [--json] [--ignore <code>]... [--config <file>] [--fail-on error|warning|info|never]Findings about dead or suspicious policy. Exits 1 on a warning or worse.
strig helpPrints the usage text. --help and -h do the same.

Policies at compile time: strig-macros#

strig-macros = "0.10". A policy that does not validate does not build. Add strig with the dsl feature to your own Cargo.toml, and use the same version of both: strig-macros pins strig with =.

  • policy!("<policy text>")

    Compiles and validates a policy written as a text literal. The result is a strig::dsl::Policy. An error stops the build and points at the literal, with policy:line:column counted inside the text. Prefer a raw string for anything with several lines.

  • include_policy!

    include_policy!("<path>")

    The same, from a file relative to the CARGO_MANIFEST_DIR of the caller. The file must be inside the crate, and paths through target/ or a hidden component are refused, as are files over 4 MiB. An error reads path:line:column: message.

The expansion embeds the validated policy as JSON and reads that JSON back on each evaluation; the policy text itself is not parsed at runtime. In a hot path, keep it in a static with LazyLock.

JavaScript: the npm package#

npm install @the-hades-organization/strig, for Node, Bun and the browser. The native module (N-API) serves Node and Bun, WebAssembly serves the browser and is the fallback. The native module comes as one package per platform; see JavaScript. Set STRIG_BACKEND=native or wasm to force one. The Rust crate behind it, strig-node, is not published on its own.

call condition functions, your own overrides and your own invariants are synchronous callbacks passed to new Engine(spec, hooks); see JavaScript. The JSON spec covers the built-in resource_owner and permission_holder.

  • export function load(options: { backend: 'native' }): Promise<NativeStrig>
    export function load(options?: { backend?: 'auto' | 'native' | 'wasm'; wasm?: unknown }): Promise<Strig>

    Loads a backend and returns Engine, Context, Exclusive, auditEstimate, backend and the policy-language functions (compile, print, convert, format, isFormatted, loadProject). loadProjectDir exists only on the native module.

  • Engine

    constructor(spec: unknown, hooks?: EngineHooks)
    decide(context: Context, request: DecisionRequest, now?: number | bigint): Decision
    check(context: Context, request: DecisionRequest, now?: number | bigint): boolean
    explain(context: Context, request: DecisionRequest, now?: number | bigint): Explanation

    Takes the same EngineSpec JSON as Rust and, optionally, EngineHooks (callbacks, audit sink and policy). Engine<P extends string = string> takes the union of your permission ids to make check, decide, explain, list, whoCan, whoCanOn and checkFor strict; see Catalog types. decide returns the effect and a reason tagged by kind: override, grant, no_applicable_grant, unknown_permission or missing_prerequisite. The system clock is never used: pass now, or set it on the Context.

  • Engine, the rest

    capabilities(context: Context, subject: Subject, scope: Resource, now?: number | bigint): CapabilitySet
    validateGrant(grant: Grant): void
    list(context: Context, subject: Subject, permission: string, kind: string, options?: ListOptions, now?: number | bigint): ListResult
    whoCanOn(context: Context, permission: string, resource: Resource, now?: number | bigint): WhoCanOnResult
    apply(input: ApplyInput): ApplyResult

    Also whoCan, accessOf, checkFor, catalog, materialize and applyTemplate. apply checks the invariants of a grant or role change and returns the violations, an audit record and auditStatus. propose, resolve and expire are the approval flow (Approvals); flushAudit and auditStats drive the retry queue (Audit).

  • Context

    constructor(init?: { grants?: Grant[]; tuples?: unknown[]; env?: Record<string, unknown>; now?: number | bigint | null; limits?: QueryLimits })

    The grants of a decision. Change it with setGrants, addGrant, removeGrant, addTuple, setEnv, setNow and setLimits. The instant persists, so a long-lived Context needs setNow on every request.

Every error the binding throws has a stable error.code, the same on both backends: INVALID_ARGUMENT, INVALID_INPUT, INVALID_SPEC, INVALID_GRANT, UNKNOWN_SUBJECT, QUERY_LIMIT_EXCEEDED, RELATION_DEPTH_EXCEEDED, QUERY_ERROR, UNKNOWN_INVARIANT, REENTRANT_CALL, the EXCLUSIVE_* and DSL_* codes, and INTERNAL. A scalar argument that is not accepted, such as NaN or a negative instant, is INVALID_ARGUMENT; it is never coerced.

ImportWhat it gives you
@the-hades-organization/strigload, the types and scopeFromString(text: string): Resource.
.../clientPermissionClient: connects over SSE or WebSocket, keeps the capabilities of each scope and decides locally. Use it to shape the interface; the server still decides.
.../serverHub, openSession, sseResponse, pipeSse, engineProvider and the transports redisTransport, ioredisTransport, pgTransport. Notices use the strig-sync format, so Rust and JS instances can share a channel.
.../remoteRemoteClient, CircuitBreaker: the client of a decision server.
.../express, .../fastify, .../nestjsauthorize, authorizeRoutes, createCan; the Fastify plugin; Can, StrigGuard and StrigRouteGuard. Their framework is an optional peer dependency. See Web frameworks.
.../approvalsApprovals, MemoryPendingStore, PendingStoreError. See Approvals.
.../storeopenJsonStore, JsonFileStore, JsonStoreError, STORE_VERSION. See JavaScript.
.../testingexpressRoutes, nestRoutes, collectFastifyRoutes, auditRoutes, assertRoutesCovered. See Web frameworks.
.../typesgenerateTypes; the strig-types command writes the same output.
  • export function authorize<Req = any>(options: AuthorizerOptions<Req>): Handler<Req>

    Express middleware that calls next() only on an allow. A caller with no subject gets 401, a deny 403, a decision that could not be made 503 and an extractor error 500; change them with unauthenticatedStatus, denyStatus, failureStatus and errorStatus. Pass exactly one of local: { engine, context, now } and remote: RemoteClient.

  • RemoteClient

    constructor(options: RemoteOptions)
    check(request: CheckInput): Promise<RemoteResult>
    checkBatch(requests: CheckInput[]): Promise<RemoteResult[]>

    RemoteOptions is { url, timeoutMs?, fetch?, headers?, breaker? }. The timeout is 2000 ms by default; the breaker opens after 5 failures for 30 000 ms. allowed is true only for a 200 whose effect is allow; a failure carries failure.

Type declarations by subpath#

Copied from the .d.ts files the package ships: the root, then one block per subpath of exports. strig-types is the package's one binary and writes the output of generateTypes.

Package root: @the-hades-organization/strig#

TypeScript
function load(options: { backend: 'native' }): Promise<NativeStrig>
function load(options?: { backend?: 'auto' | 'native' | 'wasm'; wasm?: unknown }): Promise<Strig>
class Context {
  constructor(init?: { grants?: Grant[]; tuples?: unknown[]; env?: Record<string, unknown>; now?: number | bigint | null; limits?: QueryLimits });
  setGrants(grants: Grant[]): void;
  addGrant(grant: Grant): void;
  removeGrant(id: string): boolean;
  grants(): Grant[];
  readonly size: number;
  addTuple(tuple: unknown): boolean;
  removeTuple(tuple: unknown): boolean;
  setEnv(env: Record<string, unknown>): void;
  loadCapabilities(set: CapabilitySet): Subject;
  setNow(now: number | bigint | null): void;
  setLimits(limits: QueryLimits | null): void;
}
class Engine<P extends string = string> {
  constructor(spec: unknown, hooks?: EngineHooks);
  decide(context: Context, request: DecisionRequest<P>, now?: number | bigint): Decision;
  check(context: Context, request: DecisionRequest<P>, now?: number | bigint): boolean;
  explain(context: Context, request: DecisionRequest<P>, now?: number | bigint): Explanation;
  allowedFields(context: Context, request: DecisionRequest<P>, now?: number | bigint): FieldSet;
  whyNot(context: Context, request: DecisionRequest<P>, now?: number | bigint, options?: WhyNotOptions): Remedies | null;
  explainFields(context: Context, request: DecisionRequest<P>, now?: number | bigint): FieldExplanation;
  checkMany(context: Context, requests: readonly DecisionRequest<P>[], now?: number | bigint): boolean[];
  explainMany(context: Context, requests: readonly DecisionRequest<P>[], now?: number | bigint): Explanation[];
  capabilities(context: Context, subject: Subject, scope: Resource, now?: number | bigint): CapabilitySet;
  validateGrant(grant: Grant): void;
  catalog(): unknown;
  apply(input: ApplyInput): ApplyResult;
  materialize(input: MaterializeInput): Materialized;
  applyTemplate(input: ApplyTemplateInput): ApplyTemplateResult;
  impact(input: ApplyInput): ImpactResult;
  reviewImpact(input: ReviewImpactInput): ReviewImpactResult;
  propose(input: ProposeInput): ProposeResult;
  resolve(input: ResolveInput): ResolveResult;
  elevate(input: ElevateInput): ElevateResult;
  recertify(input: RecertifyInput): RecertifyResult;
  expire(input: ExpireInput): ExpireResult;
  flushAudit(): AuditStats;
  auditStats(): AuditStats;
  list(context: Context, subject: Subject, permission: PermissionArg<P>, kind: string, options?: ListOptions, now?: number | bigint): ListResult;
  whoCan(context: Context, permission: PermissionArg<P>, now?: number | bigint): SubjectRef[];
  whoCanOn(context: Context, permission: PermissionArg<P>, resource: Resource, now?: number | bigint): WhoCanOnResult;
  accessOf(context: Context, resource: Resource, now?: number | bigint): Array<{ subject: SubjectRef; permissions: string[] }>;
  checkFor(context: Context, subject: SubjectRef, permission: PermissionArg<P>, resource: Resource, subjects: Subject[], now?: number | bigint): CheckForResult;
}
class Exclusive {
  constructor(options?: ExclusiveOptions);
  validate(engine: Engine): void;
  acquire(engine: Engine, context: Context, subject: Subject, resource: Resource, terms: { priority: number; ttlMs: number }, now?: number | bigint,): Acquisition;
  holder(resource: ObjectRef, now?: number | bigint): Lease | null;
  release(resource: ObjectRef, holder: ObjectRef, now?: number | bigint): Lease;
  renew(engine: Engine, context: Context, subject: Subject, resource: Resource, ttlMs: number, now?: number | bigint,): Lease;
  expire(now?: number | bigint): Lease[];
}

Types: AuditLevel, AuditFailMode, AuditDelivery, AuditRedaction, Subject, SubjectMatcher, ObjectRef, ErrorCode, BindingError, ConditionOperand, Weekday, Condition, Grant, Reason, Verdict, Decision, Explanation, ConditionTrace, CapabilitySet, FieldSet, FieldVerdict, FieldExplanation, WhyNotCause, WhyNotChange, WhyNotCaveat, Remedy, Remedies, WhyNotOptions, PermissionArg, DecisionRequest, RoleAssignment, Bypass, InvariantSpec, ImpactSource, ImpactOptions, Access, AccessChange, Impact, SeparationClash, PotentialClash, ApplyInput, TemplateGrant, RoleTemplate, MaterializeInput, Materialized, ApplyTemplateInput, ApplyTemplateResult, Violation, AccessVia, SubjectRef, FilterExpr, FilterShape, FilterResidual, ListOptions, ListResult, WhoCanOnResult, CheckForResult, QueryLimits, Lease, Acquisition, ExclusiveOptions, Suggestion, ApplyResult, ImpactResult, ApprovalRule, PendingStatus, PendingRequest, ElevationTarget, ElevationRule, ElevationRequest, ReviewState, ElevationInfo, ElevateInput, ElevateResult, ReviewerRule, ReviewerRoute, RecertScope, RecertDefaultAction, CampaignSpec, RecertDecision, RecertItemState, RecertItem, Campaign, CampaignReport, RecertifyInput, RecertifyResult, ApprovalFlowInput, ProposeInput, ResolveInput, ReviewImpactInput, ReviewImpactResult, ExpireInput, ProposeResult, ResolveResult, ExpireResult, AuditStats, AuditPolicy, ChainAnchors, ChainVerification, MerkleVerification, MerkleInclusionInput, MerkleConsistencyInput, TimestampInput, TimestampVerification, HostCondition, HostOverrideRequest, HostOverrideOutcome, HostOverride, HostProposal, HostInvariantResult, EngineHooks, PolicyLanguage, DslErrorCode, DslPlace, DslDiagnostic, DslError, PolicyPermission, MutuallyExclusive, ConflictingActions, PolicyCatalog, PolicyStrategy, PolicyDocument, PolicyNote, PolicySource, PolicyTestFixture, PolicyTestFile, PolicyTestCase, PolicyTestOutcome, PolicyTestResult, PolicyTestReport, PolicyDiffResponsible, PolicyDecisionChange, PolicyDiffUniverse, PolicyDiff, PolicyDiffFixture, PolicyDiffOptions, PolicyLintFinding, PolicyLintOptions, PolicyLanguageApi, NativePolicyLanguageApi, Strig, NativeStrig.

/protocol#

TypeScript
function parseRevision(text: string): { scope: string; value: bigint; } | undefined
function revisionReached(required: string, have: string | undefined): Reached
function anchorToString(anchor: Anchor): string
function scopeToString(scope: Resource): string
function scopeFromString(text: string): Resource
function sameAnchor(a: Anchor, b: Anchor): boolean
function resourceContains(resource: Resource, anchor: Anchor): boolean
function changeAffects(change: Change, subjectId: string | null, scope: Resource): boolean
function resourceWithin(resource: Resource, scope: Resource): boolean
function encodeSse(message: ServerMessage): string
function readSse(body: ReadableStream<Uint8Array>, onMessage: (message: ServerMessage) => void): Promise<void>
const GLOBAL = "global"
const PROTOCOL_VERSION = 2

Types: Anchor, Resource, ChangeKind, Change, ServerMessage, ClientMessage, Reached.

/client#

TypeScript
class PermissionClient<P extends string = string> {
  readonly url: string | URL;
  readonly transport: 'sse' | 'websocket';
  scopes: Resource[];
  readonly strig: Pick<Strig, 'Context'>;
  readonly engine: Engine<string>;
  readonly headers: Record<string, string>;
  readonly fetch: typeof fetch;
  readonly WebSocket: typeof WebSocket;
  readonly minDelay: number;
  readonly maxDelay: number;
  private entries;
  private listeners;
  private required?;
  private closed;
  private abort?;
  private socket?;
  constructor(options: PermissionClientOptions);
}

Types: PermissionClientOptions.

/server#

TypeScript
function change(kind: ChangeKind, scope: Anchor, extra?: Partial<Change>): Change
function openSession({ hub, subject, scopes, provider, heartbeatMs, revision, minRevision, send, }: SessionOptions & { send: (message: ServerMessage) => void; }): Session
function sseResponse(options: SessionOptions): Response
function pipeSse(res: ServerResponse, options: SessionOptions): Session
function engineProvider({ engine, Context, loadGrants, }: { engine: Engine; Context: typeof ContextClass; loadGrants: (subject: Subject, scope: Resource) => Promise<Grant[]> | Grant[]; }): Provider
function memoryTransport(): Transport
function redisTransport({ publisher, subscriber, channel, }: { publisher: RedisPublisher; subscriber: RedisSubscriber; channel?: string; }): Transport
function ioredisTransport({ publisher, subscriber, channel, }: { publisher: RedisPublisher; subscriber: IoredisSubscriber; channel?: string; }): Transport
function pgTransport({ client, listener, channel, }: { client: Queryable; listener: PgListener; channel?: string; }): Transport
function notify(queryable: Queryable, channel: string, item: Change): Promise<void>
class Hub {
  readonly origin: string;
  private readonly transport;
  private seq;
  private readonly listeners;
  private stopRelay;
  constructor(options?: { origin?: string; transport?: Transport; });
}

Types: Transport, Provider, SessionOptions, Session, RedisPublisher, RedisSubscriber, IoredisSubscriber, Queryable, PgListener.

/remote#

TypeScript
function messageFor(code: string): string
function parseErrorCode(value: unknown): ErrorCode | { unknown: string; }
const ERROR_MESSAGES: Readonly<Record<string, string>>
class CircuitBreaker {
  #private;
  readonly failureThreshold: number;
  readonly waitMs: number;
}
class RemoteClient {
  #private;
  private readonly base;
  private readonly timeoutMs;
  private readonly fetch;
  private readonly headers;
  private readonly minRevision?;
  readonly breaker: CircuitBreaker;
  constructor(options: RemoteOptions);
  check(request: CheckInput): Promise<RemoteResult>;
  checkBatch(requests: CheckInput[], options?: { minRevision?: string; }): Promise<RemoteResult[]>;
}

Types: ErrorCode, FailureReason, Failure, CheckInput, RemoteResult, BreakerOptions, RemoteOptions.

/express#

TypeScript
function authorize<Req = any>(options: AuthorizerOptions<Req>): Handler<Req>
function createCan<Req = any>(options: AuthorizerOptions<Req>): (permission: string, resource?: Resource | ((req: Req) => Resource)) => Handler<Req>
function authorizeRoutes<Req = any>(options: RouteTableOptions<Req>): Handler<Req>

/fastify#

TypeScript
function authorize<Req = any>(options: AuthorizerOptions<Req>): PreHandler<Req>
function createCan<Req = any>(options: AuthorizerOptions<Req>): (permission: string, resource?: Resource | ((request: Req) => Resource)) => PreHandler<Req>
function authorizeRoutes<Req = any>(options: RouteTableOptions<Req>): PreHandler<Req>
function plugin(fastify: FastifyInstanceLike, options: AuthorizerOptions): Promise<void>

/nestjs#

TypeScript
function Can(permission: string, resolver?: (request: any) => Resource): MethodDecorator & ClassDecorator
const STRIG_CAN: string
class StrigGuard {
  #private;
  private readonly options;
  private readonly decide;
  constructor(options: AuthorizerOptions);
  canActivate(context: ExecutionContextLike): Promise<boolean>;
}
class StrigRouteGuard {
  #private;
  private readonly options;
  private readonly byTable;
  private readonly byCan;
  constructor(options: RouteTableOptions);
  canActivate(context: ExecutionContextLike): Promise<boolean>;
}

/approvals#

TypeScript
function checkRecertUpdate(stored: Campaign | undefined, next: Campaign): void
class PendingStoreError extends Error {
  readonly code: PendingStoreErrorCode;
  constructor(code: PendingStoreErrorCode, message: string);
}
class MemoryPendingStore implements PendingStore {
  private readonly requests;
  get(id: string): PendingRequest | undefined;
  put(request: PendingRequest): void;
  update(request: PendingRequest): void;
  annotate(request: PendingRequest): void;
  list(): PendingRequest[];
}
class Approvals {
  private readonly engine;
  readonly store: PendingStore;
  private readonly options;
  private head;
  constructor(engine: ApprovalEngine, store: PendingStore, options: ApprovalsOptions);
  propose(actor: Subject, mutation: ApplyInput['mutation'], current: Grant[], options?: ProposeOptions): Promise<ProposeResult>;
  pending(now?: number): Promise<PendingRequest[]>;
  approve(id: string, approver: Subject, current: Grant[], options?: DecideOptions): Promise<ResolveResult>;
  reject(id: string, approver: Subject, reason: string, current?: Grant[], options?: DecideOptions): Promise<ResolveResult>;
  reviewImpact(id: string, current: Grant[], options?: CallOptions): Promise<ReviewImpactResult>;
  expire(options?: CallOptions): Promise<ExpireResult>;
  private decide;
  private close;
  private common;
  private follow;
  private clock;
}
class Elevations {
  private readonly engine;
  readonly store: PendingStore;
  private readonly options;
  private head;
  constructor(engine: ElevationEngine, store: PendingStore, options: ElevationsOptions);
  request(request: ElevationRequest, current: Grant[], options?: ElevationPersistOptions & { expiresAt?: number; }): Promise<ElevateResult>;
  approve(id: string, approver: Subject, current: Grant[], options?: ElevationPersistOptions): Promise<ElevateResult>;
  reject(id: string, approver: Subject, reason: string, current: Grant[], options?: CallOptions): Promise<ElevateResult>;
  revoke(id: string, by: Subject, current: Grant[], options?: ElevationPersistOptions & { reason?: string; }): Promise<ElevateResult>;
  closeReview(id: string, reviewer: Subject, note: string, current: Grant[], options?: CallOptions): Promise<ElevateResult>;
  active(now?: number): Promise<PendingRequest[]>;
  pendingReviews(): Promise<PendingRequest[]>;
  private step;
  private load;
  private requireStore;
  private annotate;
  private clock;
}
class RecertStoreError extends Error {
  readonly code: RecertStoreErrorCode;
  constructor(code: RecertStoreErrorCode, message: string);
}
class MemoryRecertStore implements RecertStore {
  private readonly campaigns;
  get(id: string): Campaign | undefined;
  put(campaign: Campaign): void;
  update(campaign: Campaign): void;
  list(): Campaign[];
}
class Recertifications {
  private readonly engine;
  readonly store: RecertStore;
  private readonly options;
  private head;
  constructor(engine: RecertEngine, store: RecertStore, options?: RecertificationsOptions);
  open(spec: CampaignSpec, opener: Subject, subjects: Subject[], current: Grant[], options?: CallOptions): Promise<RecertifyResult>;
  decide(id: string, item: string, decision: RecertDecision, reviewer: Subject, current: Grant[], options?: RecertPersistOptions & { reason?: string; }): Promise<RecertifyResult>;
  close(id: string, closer: Subject, current: Grant[], options?: RecertPersistOptions): Promise<RecertifyResult>;
  report(id: string): Promise<CampaignReport>;
  openCampaigns(): Promise<Campaign[]>;
  private step;
  private load;
}

Types: PendingStoreErrorCode, PendingStore, ApprovalEngine, ApprovalsOptions, CallOptions, ProposeOptions, DecideOptions, ElevationEngine, ElevationsOptions, ElevationPersistOptions, RecertStoreErrorCode, RecertStore, RecertEngine, RecertificationsOptions, RecertPersistOptions.

/store#

TypeScript
function openJsonStore(options: JsonFileStoreOptions): Promise<JsonFileStore>
const STORE_VERSION = 1
class JsonStoreError extends Error {
  readonly code: StoreErrorCode;
  constructor(code: StoreErrorCode, message: string, options?: { cause?: unknown; });
}
class JsonFileStore {
  readonly path: string;
  private readonly lockPath;
  private readonly options;
  private data;
  private queue;
  private readonly listeners;
  private readonly errorListeners;
  private watcher;
  private debounce;
  constructor(options: JsonFileStoreOptions);
  load(): Promise<this>;
  reload(): Promise<StoreData>;
}

Types: StoreErrorCode, StoreData, JsonFileStoreOptions, ApplyMutation, Governance.

/testing#

TypeScript
function auditRoutes<Req = any>(routes: readonly RouteInfo[], table: readonly RouteRule<Req>[], options?: { caseSensitive?: boolean; }): RouteAudit<Req>
function assertRoutesCovered<Req = any>(routes: readonly RouteInfo[], table: readonly RouteRule<Req>[], options?: { caseSensitive?: boolean; }): void
function expressRoutes(app: unknown, prefix?: string): RouteInfo[]
function collectFastifyRoutes(fastify: FastifyRouteHooks): RouteInfo[]
function nestRoutes(app: { getHttpAdapter(): { getInstance(): unknown; }; }): RouteInfo[]
class RouteTableAuditError extends Error {
  readonly audit: RouteAudit;
  constructor(audit: RouteAudit);
}

Types: RouteInfo, RouteAudit.

/react#

TypeScript
function StrigProvider<P extends string = string>({ client, connect, children }: StrigProviderProps<P>): ReactNode
function useCan<P extends string = string>(permission: PermissionArg<P>, resource: Resource): boolean
function useStrigStatus(): StrigStatus
function useRequireRevision(): (revision: string) => void
function Can<P extends string = string>({ permission, resource, fallback, children }: CanProps<P>): ReactNode

Types: StrigProviderProps, CanProps.

/angular#

TypeScript
function provideStrig<P extends string>(client: PermissionClient<P>, options?: StrigOptions): EnvironmentProviders
function strigCanActivate<P extends string = string>(permission: PermissionArg<P>, resource: Resource | ((route: any, state: any) => Resource), options?: StrigGuardOptions): (route: any, state: any) => Promise<any>
const STRIG_CLIENT: InjectionToken<PermissionClient<any>>
const STRIG_OPTIONS: InjectionToken<StrigOptions>
class StrigService<P extends string = string> {
  private readonly bridge;
  private readonly server;
  private readonly tick;
  private readonly state;
  readonly status: Signal<StrigStatus>;
  constructor();
  can(permission: Reactive<PermissionArg<P> | null | undefined>, resource: Reactive<Resource | null | undefined>): Signal<boolean>;
  settled(timeoutMs?: number): Promise<boolean>;
  requireRevision(revision: string): void;
  check(permission: PermissionArg<P>, resource: Resource): boolean;
  static ɵfac: i0.ɵɵFactoryDeclaration<StrigService<any>, never>;
  static ɵprov: i0.ɵɵInjectableDeclaration<StrigService<any>>;
}
class StrigCanDirective<P extends string = string> {
  private readonly template;
  private readonly container;
  private readonly permission;
  private readonly resource;
  private readonly fallback;
  private view?;
  private shown?;
  set strigCan(value: PermissionArg<P> | null | undefined);
  set strigCanResource(value: Resource | null | undefined);
  set strigCanElse(value: TemplateRef<unknown> | null | undefined);
  constructor();
  static ɵfac: i0.ɵɵFactoryDeclaration<StrigCanDirective<any>, never>;
  static ɵdir: i0.ɵɵDirectiveDeclaration<StrigCanDirective<any>, "[strigCan]", never, { "strigCan": { "alias": "strigCan"; "required": true; }; "strigCanResource": { "alias": "strigCanResource"; "required": false; }; "strigCanElse": { "alias": "strigCanElse"; "required": false; }; }, {}, never, never, true, never>;
}

Types: StrigOptions, StrigGuardOptions.

/prisma#

TypeScript
function toWhere<P extends string>(filter: ListFilter<P>, mapping: PrismaMapping): OrmFilter<PrismaWhere, P>
const prisma: OrmAdapter<PrismaWhere, string>

Types: PrismaWhere, PrismaMapping.

/drizzle#

TypeScript
function toWhere<P extends string>(filter: ListFilter<P>, mapping: DrizzleMapping): OrmFilter<SQL, P>
const drizzle: OrmAdapter<SQL, AnyColumn>

Types: DrizzleMapping.

/kysely#

TypeScript
function toWhere<P extends string>(filter: ListFilter<P>, mapping: KyselyMapping): OrmFilter<KyselyWhere, P>
const kysely: OrmAdapter<KyselyWhere, string>

Types: KyselyMapping, KyselyWhere.

/types#

TypeScript
function generateTypes(catalog: CatalogInput): string

Types: CatalogInput.

Python: strig-auth#

Text
pip install strig-auth
Text
import strig
from strig import Context, Engine, StrigError, dsl

The package is strig-auth on PyPI and strig on import; it needs Python 3.9 or later. Values are plain JSON (dict, list, str, int, float, bool, None) with the same camelCase field names as the JavaScript API; method names are snake_case. Every failure raises StrigError with a stable code; DslError adds diagnostics. Walk-through: Python.

The public surface, as the package's type stubs declare it:

strig/_native.pyi, __init__.py, dsl.py, errors.py
# ===== _native.pyi =====
"""Type stubs of the native extension. Values are plain JSON (`dict`, `list`, `str`, `int`, `float`,
`bool`, `None`) with the same camelCase field names as the JavaScript API."""

from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence

Json = Any
JsonObject = Dict[str, Any]
Request = Mapping[str, Any]
Hook = Callable[[Any], Any]

class Context:
    def __init__(
        self,
        grants: Optional[Sequence[Mapping[str, Any]]] = None,
        *,
        tuples: Optional[Sequence[Mapping[str, Any]]] = None,
        env: Optional[Mapping[str, Any]] = None,
        now: Optional[int] = None,
        limits: Optional[Mapping[str, Any]] = None,
    ) -> None: ...
    def set_grants(self, grants: Sequence[Mapping[str, Any]]) -> None: ...
    def add_grant(self, grant: Mapping[str, Any]) -> None: ...
    def remove_grant(self, id: str) -> bool: ...
    def grants(self) -> List[JsonObject]: ...
    @property
    def size(self) -> int: ...
    def __len__(self) -> int: ...
    def add_tuple(self, tuple: Mapping[str, Any]) -> bool: ...
    def remove_tuple(self, tuple: Mapping[str, Any]) -> bool: ...
    def set_env(self, env: Mapping[str, Any]) -> None: ...
    def load_capabilities(self, capabilities: Mapping[str, Any]) -> JsonObject: ...
    def set_now(self, now: Optional[int] = None) -> None: ...
    def set_limits(self, limits: Optional[Mapping[str, Any]] = None) -> None: ...

class Engine:
    def __init__(
        self,
        spec: Mapping[str, Any],
        *,
        conditions: Optional[Mapping[str, Callable[[List[Any]], bool]]] = None,
        overrides: Optional[Iterable[Mapping[str, Any]]] = None,
        invariants: Optional[Mapping[str, Callable[[JsonObject], Any]]] = None,
        audit_sink: Optional[Callable[[JsonObject], None]] = None,
        audit_redact: Optional[Callable[[JsonObject], JsonObject]] = None,
        on_audit_drop: Optional[Callable[[JsonObject], None]] = None,
        audit_policy: Optional[Mapping[str, Any]] = None,
    ) -> None: ...
    def decide(self, context: Context, request: Request, now: Optional[int] = None) -> JsonObject: ...
    def check(self, context: Context, request: Request, now: Optional[int] = None) -> bool: ...
    def explain(self, context: Context, request: Request, now: Optional[int] = None) -> JsonObject: ...
    def why_not(
        self,
        context: Context,
        request: Request,
        now: Optional[int] = None,
        options: Optional[Mapping[str, Any]] = None,
    ) -> Optional[JsonObject]: ...
    def check_many(self, context: Context, requests: Sequence[Request], now: Optional[int] = None) -> List[bool]: ...
    def explain_many(
        self, context: Context, requests: Sequence[Request], now: Optional[int] = None
    ) -> List[JsonObject]: ...
    def capabilities(
        self, context: Context, subject: Mapping[str, Any], scope: Mapping[str, Any], now: Optional[int] = None
    ) -> JsonObject: ...
    def validate_grant(self, grant: Mapping[str, Any]) -> None: ...
    def catalog(self) -> JsonObject: ...
    def apply(self, input: Mapping[str, Any]) -> JsonObject: ...
    def impact(self, input: Mapping[str, Any]) -> JsonObject: ...
    def review_impact(self, input: Mapping[str, Any]) -> JsonObject: ...
    def propose(self, input: Mapping[str, Any]) -> JsonObject: ...
    def resolve(self, input: Mapping[str, Any]) -> JsonObject: ...
    def elevate(self, input: Mapping[str, Any]) -> JsonObject: ...
    def recertify(self, input: Mapping[str, Any]) -> JsonObject: ...
    def expire(self, input: Mapping[str, Any]) -> JsonObject: ...
    def flush_audit(self) -> JsonObject: ...
    def audit_stats(self) -> JsonObject: ...
    def materialize(self, input: Mapping[str, Any]) -> JsonObject: ...
    def apply_template(self, input: Mapping[str, Any]) -> JsonObject: ...
    def list(
        self,
        context: Context,
        subject: Mapping[str, Any],
        permission: str,
        kind: str,
        options: Optional[Mapping[str, Any]] = None,
        now: Optional[int] = None,
    ) -> JsonObject: ...
    def who_can(self, context: Context, permission: str, now: Optional[int] = None) -> List[JsonObject]: ...
    def who_can_on(
        self, context: Context, permission: str, resource: Mapping[str, Any], now: Optional[int] = None
    ) -> JsonObject: ...
    def access_of(
        self, context: Context, resource: Mapping[str, Any], now: Optional[int] = None
    ) -> List[JsonObject]: ...
    def check_for(
        self,
        context: Context,
        subject_ref: Mapping[str, Any],
        permission: str,
        resource: Mapping[str, Any],
        subjects: Sequence[Mapping[str, Any]],
        now: Optional[int] = None,
    ) -> JsonObject: ...

class Exclusive:
    def __init__(self, options: Optional[Mapping[str, Any]] = None) -> None: ...
    def validate(self, engine: Engine) -> None: ...
    def acquire(
        self,
        engine: Engine,
        context: Context,
        subject: Mapping[str, Any],
        resource: Mapping[str, Any],
        terms: Mapping[str, Any],
        now: Optional[int] = None,
    ) -> JsonObject: ...
    def holder(self, resource: Mapping[str, Any], now: Optional[int] = None) -> Optional[JsonObject]: ...
    def release(
        self, resource: Mapping[str, Any], holder: Mapping[str, Any], now: Optional[int] = None
    ) -> JsonObject: ...
    def renew(
        self,
        engine: Engine,
        context: Context,
        subject: Mapping[str, Any],
        resource: Mapping[str, Any],
        ttl_ms: int,
        now: Optional[int] = None,
    ) -> JsonObject: ...
    def expire(self, now: Optional[int] = None) -> List[JsonObject]: ...

def audit_estimate(level: str, records: int) -> float: ...
def verify_audit_chain(records: Sequence[Mapping[str, Any]], anchors: Optional[Mapping[str, Any]] = None) -> JsonObject: ...
def dsl_compile(text: str, options: Optional[Mapping[str, Any]] = None) -> JsonObject: ...
def dsl_print(policy: Mapping[str, Any], language: str) -> JsonObject: ...
def dsl_convert(text: str, language: str) -> JsonObject: ...
def dsl_format(text: str, options: Optional[Mapping[str, Any]] = None) -> JsonObject: ...
def dsl_is_formatted(text: str, options: Optional[Mapping[str, Any]] = None) -> JsonObject: ...
def dsl_load_project(sources: Sequence[Mapping[str, str]]) -> JsonObject: ...
def dsl_load_project_dir(dir: str) -> JsonObject: ...
def dsl_run_tests(policy: Mapping[str, Any], tests: Sequence[Any]) -> JsonObject: ...

# ===== __init__.py =====
from typing import Any, Dict, List
from . import dsl
from ._native import Context, Engine, Exclusive, audit_estimate, verify_audit_chain
from .errors import DslError, StrigError
def scope_from_string(text: str) -> Dict[str, Any]: ...
__all__ = ['Context', 'DslError', 'Engine', 'Exclusive', 'StrigError', 'audit_estimate', 'dsl', 'scope_from_string', 'verify_audit_chain']

# ===== dsl.py =====
from __future__ import annotations
from typing import Any, Dict, List, Optional
from . import _native
from .errors import DslError
__all__ = ['compile', 'print', 'convert', 'format', 'is_formatted', 'load_project', 'load_project_dir', 'run_tests']
def compile(text: str, file: Optional[str]=None) -> Dict[str, Any]: ...
def print(policy: Dict[str, Any], language: str) -> str: ...
def convert(text: str, language: str) -> str: ...
def format(text: str, file: Optional[str]=None) -> str: ...
def is_formatted(text: str, file: Optional[str]=None) -> bool: ...
def load_project(sources: List[Dict[str, str]]) -> Dict[str, Any]: ...
def load_project_dir(directory: str) -> Dict[str, Any]: ...
def run_tests(policy: Dict[str, Any], tests: List[Any]) -> Dict[str, Any]: ...

# ===== errors.py =====
from __future__ import annotations
from typing import Any, List
class StrigError(Exception):
    code: str
    message: str
    def __init__(self, code: str, message: str) -> None: ...
    ...
class DslError(StrigError):
    diagnostics: List[Any]
    def __init__(self, code: str, message: str, diagnostics: List[Any] | None=None) -> None: ...
    ...

Go#

Text
go get github.com/The-Hades-Organization/Strig/bindings/go@v0.10.0

Go 1.22 or later. The engine is the Wasm module, run on wazero; there is no cgo. Engine and Context hold module memory, so Close them. An Engine is single-threaded: Fork gives each worker its own. Every error is a *Error with a stable Code; errors.Is matches two of them by Code. Walk-through: Go.

Text
engine, err := strig.NewEngine(spec)
if err != nil { return err }
defer engine.Close()

ctx, _ := engine.NewContext(map[string]any{"grants": grants})
defer ctx.Close()

ok, err := engine.Check(ctx, map[string]any{
    "subject":    map[string]any{"kind": "user", "id": "ana"},
    "permission": "document.view",
    "resource":   map[string]any{"path": []any{map[string]any{"kind": "document", "id": "d1"}}},
})
if strig.CodeOf(err) == "INVALID_GRANT" { /* ... */ }
ItemSignature
NewEnginefunc NewEngine(spec any) (*Engine, error)
Engine.Forkfunc (e *Engine) Fork() (*Engine, error)
Engine.Closefunc (e *Engine) Close() error
Engine.NewContextfunc (e *Engine) NewContext(init any) (*Context, error)
Engine.Checkfunc (e *Engine) Check(c *Context, request any, opts ...Option) (bool, error)
Engine.Decidefunc (e *Engine) Decide(c *Context, request any, opts ...Option) (*Decision, error)
Engine.Explainfunc (e *Engine) Explain(c *Context, request any, opts ...Option) (map[string]any, error)
Engine.CheckManyfunc (e *Engine) CheckMany(c *Context, requests any, opts ...Option) ([]bool, error)
Engine.Listfunc (e *Engine) List(c *Context, subject any, permission, kind string, options any, opts ...Option) (map[string]any, error)
Engine.WhoCanfunc (e *Engine) WhoCan(c *Context, permission string, opts ...Option) ([]map[string]any, error)
Engine.Catalogfunc (e *Engine) Catalog() (map[string]any, error)
Engine.Apply, Impact, ReviewImpact, Propose, Resolve, Expirefunc (e *Engine) Apply(input any) (map[string]any, error), and the same shape for the others
Context.SetGrantsfunc (c *Context) SetGrants(grants any) error
Context.AddGrantfunc (c *Context) AddGrant(grant any) error
Context.RemoveGrantfunc (c *Context) RemoveGrant(id string) (bool, error)
Context.Grantsfunc (c *Context) Grants() ([]map[string]any, error)
Context.AddTuple, RemoveTuplefunc (c *Context) AddTuple(tuple any) (bool, error)
Context.SetEnvfunc (c *Context) SetEnv(env any) error
Context.SetNowfunc (c *Context) SetNow(t time.Time) error
Context.SetLimitsfunc (c *Context) SetLimits(limits any) error
Context.Closefunc (c *Context) Close() error
WithNowfunc WithNow(t time.Time) Option
Compilefunc Compile(text string, file ...string) (map[string]any, error)
Formatfunc Format(text string) (string, error)
CodeOffunc CodeOf(err error) string
Decisionstruct { Effect string; Reason json.RawMessage; Matched []string; Warnings []string }, with Allowed() bool
Errorstruct { Code string; Message string; Diagnostics []any }
ErrClosed, ErrBrokenINVALID_ARGUMENT after Close; INTERNAL when the module trapped and was discarded.

Java#

Text
<dependency>
  <groupId>io.github.the-hades-organization</groupId>
  <artifactId>strig</artifactId>
  <version>0.10.0</version>
</dependency>

Package io.github.thehadesorganization.strig. The engine is the same Wasm module, run on Chicory. Engine and Context are AutoCloseable; use try-with-resources. Failures throw StrigException with a stable code(); a policy error also carries diagnostics(). Walk-through: Java and the JVM.

Text
try (Engine engine = new Engine(spec);
     Context ctx = engine.newContext(Map.of("grants", grants))) {
    Decision d = engine.decide(ctx, request);
    if (!d.allowed()) { /* d.reason() */ }
}
ItemSignature
Enginepublic Engine(Object spec), public Engine fork(), public synchronized void close()
newContextpublic Context newContext(), public Context newContext(Object init)
checkpublic boolean check(Context context, Object request), and with a trailing Instant now
decidepublic Decision decide(Context context, Object request), and with a trailing Instant now
explainpublic Map<String, Object> explain(Context context, Object request), and with Instant now
checkManypublic List<Boolean> checkMany(Context context, Object requests), and with Instant now
listpublic Map<String, Object> list(Context context, Object subject, String permission, String kind, Object options)
whoCanpublic List<Map<String, Object>> whoCan(Context context, String permission)
catalogpublic Map<String, Object> catalog()
apply, impact, reviewImpact, propose, resolve, expirepublic Map<String, Object> apply(Object input), and the same shape for the others
ContextsetGrants(Object), addGrant(Object), boolean removeGrant(String id), List<Map<String, Object>> grants(), boolean addTuple(Object), boolean removeTuple(Object), setEnv(Object), setNow(Instant), setLimits(Object), close()
Strigstatic Map<String, Object> compile(String text), compile(String text, String file), static String format(String text)
Decisionrecord Decision(String effect, JsonNode reason, List<String> matched, List<String> warnings), with boolean allowed()
StrigExceptionString code(), List<Object> diagnostics()

Wasm ABI#

The Go and Java packages call one module, strig-<version>.wasm. A host in another language can do the same. The module imports nothing and exports a linear memory and three functions.

ExportSignatureWhat it does
memorylinear memoryThe host writes inputs into it and reads outputs from it.
strig_alloc(len: usize) -> *mut u8Gives the host len bytes to write an input into.
strig_free(ptr: *mut u8, len: usize)Releases memory from strig_alloc or from a strig_call result, once.
strig_call(op_ptr, op_len, in_ptr, in_len) -> u64Runs one operation. op is UTF-8 text and the input is a JSON object. The result packs (ptr << 32) | len of a JSON envelope; read it, then free it.

The envelope is one of:

JSON
{"ok": true, "value": {"effect": "allow"}}
{"ok": false, "code": "INVALID_GRANT", "message": "...", "diagnostics": []}

code is the same errorCode every binding raises. Input that is not UTF-8 is INVALID_INPUT.

The operations, by group:

GroupOperations
Policy languagecompile, format, print, convert, isFormatted, loadProject, runTests, diff, lint
Handlesengine.new, engine.free, context.new, context.free
Contextcontext.setGrants, context.addGrant, context.removeGrant, context.grants, context.addTuple, context.removeTuple, context.setEnv, context.setNow, context.setLimits
Decisionscheck, decide, explain, whyNot, checkMany, explainMany, list, whoCan, catalog
Changesapply, impact, reviewImpact, propose, resolve, elevate, recertify, expire

Engines and contexts live inside the module and are named by integer ids. The module is single-threaded: for concurrency, instantiate one module per worker. Callbacks (call conditions, overrides, invariants) are not part of the ABI; a request that needs one fails closed with the engine's own error. There is no clock: an operation that needs the instant takes now in its input, and the host fills it.

Protocol 2#

The client protocol of strig-sync, strig-server and the JavaScript /protocol module is version 2 (PROTOCOL_VERSION). A peer that sends no hello.version is read as version 1; version 2 only adds optional fields and messages, so the two interoperate. Messages are JSON objects tagged by type, sent as Server-Sent Events (event: <type>, data: <json>) or over a WebSocket.

DirectiontypeFieldsMeaning
Serverhelloorigin, subject?, versionFirst message; version is 1 when absent.
Servercapabilitiesscope, set, revision?The current grants of the subject for a watched scope; replaces the previous set. A client that requires a revision treats a set without it, or behind it, as no decision.
ServerchangechangeA change that affects a watched scope.
ServerresyncnoneThe client lost changes: discard what it has and wait for new capabilities.
ServererrormessageA failure.
ServerpingnoneKeep-alive.
Clientwatch, unwatchscopesStarts or stops watching scopes; watch answers with each scope's capabilities.
ClientrefreshnoneAsks again for the capabilities of every watched scope.
Clientrefresh_at_leastrevisionLike refresh, but every set must come from data at revision or later. A scope that cannot be brought that far gets an error whose message is revision_not_reached, revision_scope_mismatch or revision_untracked, never an older set.

A scope is text in a query string: steps from the most specific to the broadest, separated by /, each kind:id or just kind (document:d1/project:p1/org:o1).

Error codes#

Each list is closed: a code is added, never changed or reused. Removing one, or making an existing situation report a different one, is a breaking change. A deprecated code keeps being thrown until the next major version.

JavaScript, Python, Go, Java and Wasm raise the same ErrorCode. A Rust error variant added later maps to INTERNAL, or to the *_ERROR code of its family, until it gets a code of its own.

FamilyCodes
InputINVALID_ARGUMENT, INVALID_INPUT, INVALID_SPEC, INVALID_GRANT, UNKNOWN_SUBJECT, UNKNOWN_INVARIANT, REENTRANT_CALL
QueriesQUERY_LIMIT_EXCEEDED, RELATION_DEPTH_EXCEEDED, QUERY_ERROR
Exclusive ownershipEXCLUSIVE_ZERO_TTL, EXCLUSIVE_NOT_HELD, EXCLUSIVE_NOT_HOLDER, EXCLUSIVE_ANONYMOUS_SUBJECT, EXCLUSIVE_UNIDENTIFIED_RESOURCE, EXCLUSIVE_TTL_TOO_LONG, EXCLUSIVE_DENIED, EXCLUSIVE_UNKNOWN_PERMISSION, EXCLUSIVE_STORE, EXCLUSIVE_ERROR
Policy languageDSL_PARSE, DSL_VALIDATE, DSL_CONFLICT, DSL_UNREPRESENTABLE, DSL_UNSUPPORTED, DSL_LIMIT, DSL_DUPLICATE_SOURCE, DSL_IO
OtherINTERNAL

strig-server and the JavaScript /remote client answer with error.code in the body: malformed_json, invalid_request, batch_too_large, too_many_resources, not_found, method_not_allowed, body_too_large, unsupported_media_type, source_unavailable, query_limit_exceeded, overloaded, relation_depth_exceeded, deadline_exceeded, clock_unavailable, revision_not_reached, revision_mismatch, internal. A client treats a code it does not know as internal. Status and meaning of each.

Rust error enums (EngineError, SpecError, PendingError, ApprovalError, AuditError, ChainError, ExclusiveError, StoreError, QueryError and the others) are #[non_exhaustive]; their variants are the codes, and the mapping to the lists above is part of the contract.