# Reference

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.

| Surface | Install | Section |
| --- | --- | --- |
| `strig` | `strig = "0.10"` (default feature `audit`; `dsl` and `dsl-fs` add the policy language) | [Engine](#engine) |
| `strig-sync`, `strig-redis`, `strig-postgres` | `strig-sync = "0.10"` | [Real-time](#real-time-strig-sync) |
| `strig-axum`, `strig-server`, `strig-macros` | `strig-server = "0.10"` | [Server](#decision-server-strig-server) |
| `strig-cli` | `cargo install strig-cli` | [Command line](#command-line) |
| npm package | `npm install @the-hades-organization/strig` | [npm](#javascript-the-npm-package) |
| `strig-auth` (Python), Go, Java | `pip install strig-auth` | [Python](#python-strig-auth) |

[Upgrading](https://strig.vercel.app/docs/upgrading.md) 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.

### Engine::builder

```
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 method | Signature | What it does |
| --- | --- | --- |
| `roles` | `pub fn roles(mut self, roles: RoleGraph) -> Self` | Sets role inheritance. |
| `relations` | `pub fn relations(mut self, schema: RelationSchema) -> Self` | Turns on ReBAC with this schema. |
| `conditions` | `pub fn conditions(mut self, registry: ConditionRegistry) -> Self` | Registers custom condition functions. |
| `strategy` | `pub fn strategy(mut self, strategy: impl Strategy + 'static) -> Self` | Picks how applicable grants combine. |
| `override_with` | `pub fn override_with(self, rule: impl Override + 'static) -> Self` | Adds an override that decides before the grants. |
| `override_except` | `pub fn override_except<I, S>(mut self, rule: impl Override + 'static, except: I) -> Self` | Adds an override that does not reach the listed permissions. |
| `max_relation_depth` | `pub fn max_relation_depth(mut self, depth: usize) -> Self` | Caps 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

#### Engine::decide

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

Allows or denies the request and says why.

#### Engine::check

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

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

#### Engine::explain

```
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.

#### Engine::check_for

```
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.

#### Engine::list

```
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.

#### Engine::who_can_on

```
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.

### Decision

```
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`.

### Reason

```
pub enum Reason
```

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

| Variant | It 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. |
| `NoApplicableGrant` | No grant applied: default deny. |
| `UnknownPermission` | The 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. |

> **Note**
>
> `Reason` is not `#[non_exhaustive]`, so a `match` on it must name all five variants, `MissingPrerequisite` included.

### 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

### Request::new

```
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.

> **Note**
>
> `Context` has the public field `now`, and `Grant` has `valid_from` and `valid_until`. A struct literal of either must name every field; the constructors set them for you.

## Grants

### Grant::allow

```
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

### 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 type | In a policy | The deciding grant |
| --- | --- | --- |
| `MostSpecific` | `most_specific` | The most specific step with any grant decides; on it, deny wins. The default. |
| `DenyOverrides` | `deny_overrides` | Any deny wins. |
| `PermitOverrides` | `permit_overrides` | Any allow wins. |
| `FirstApplicable` | `first_applicable` | The 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.

| Type | Variants | From |
| --- | --- | --- |
| `EngineError` | `UnknownPermission(String)` | `EngineBuilder::build` |
| `GrantError` | `EmptyId`, `UnknownPermission(String)`, `UnknownTargetKind(String)`, `TargetNotAllowed { permission, target }`, `OverrideOnly(String)`, `RelationsDisabled`, `UnknownFunction(String)`, `InvalidWindow(ValidityError)`, `InvalidField(String)`, `UnknownField { permission, field }` | `Engine::validate_grant` |
| `SpecError` | `Catalog(CatalogErrors)`, `Roles(RbacError)`, `Engine(EngineError)` | `EngineSpec::build` |
| `QueryError` | `UnknownSubject(SubjectRef)`, `LimitExceeded { what, limit }`, `RelationDepthExceeded { grant_id }` | `check_for`, `who_can_on`, `access_of` |
| `dsl::Diagnostics` | A list of `Diagnostic { location, message, hint, related }` | `dsl::parse` |

> **Warning**
>
> `EngineError`, `GrantError`, `SpecError` and the catalog errors print their text in Portuguese, while `QueryError` and `dsl::Diagnostics` print English. Match on the variant, not on the text: the variants are the contract, the messages are not.

| Variant | Message |
| --- | --- |
| `EngineError::UnknownPermission` | `exceção de override cita permissão fora do catálogo: {0}` |
| `GrantError::EmptyId` | `grant sem id` |
| `GrantError::UnknownPermission` | `permissão desconhecida: {0}` |
| `GrantError::UnknownTargetKind` | `tipo de alvo não registrado: {0}` |
| `GrantError::TargetNotAllowed` | `a permissão {permission} não aceita alvo {target}` |
| `GrantError::OverrideOnly` | `a permissão {0} vale só por override e não pode ser citada em grant` |
| `GrantError::RelationsDisabled` | `grant por relação exige RelationSchema no motor` |
| `GrantError::UnknownFunction` | `condição chama função não registrada: {0}` |
| `GrantError::InvalidWindow` | `janela de validade inválida: {0}` |
| `GrantError::InvalidField` | `campo inválido '{0}': use segmentos [A-Za-z_][A-Za-z0-9_]* separados por ponto` |
| `GrantError::UnknownField` | `a 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](#error-codes). The [deprecation policy](https://strig.vercel.app/docs/upgrading.md#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](https://strig.vercel.app/docs/modeling/field-permissions.md) and [Consistency](https://strig.vercel.app/docs/storage/consistency.md).

#### `FieldSet`

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

| Method | Signature |
| --- | --- |
| `contains` | `pub fn contains(&self, field: &str) -> bool` |
| `is_none` | `pub fn is_none(&self) -> bool` |
| `is_all` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(scope: impl Into<String>, value: u64) -> Self` |
| `scope` | `pub fn scope(&self) -> &str` |
| `value` | `pub fn value(&self) -> u64` |
| `reached_by` | `pub fn reached_by(required: &Revision, have: Option<&Revision>) -> Reached` |
| `reaches` | `pub fn reaches(&self, required: &Revision) -> Reached` |
| `advanced` | `pub fn advanced(&self, by: u64) -> Self` |

#### `Reached`

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

| Method | Signature |
| --- | --- |
| `is_reached` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(scope: impl Into<String>) -> Self` |
| `starting_at` | `pub fn starting_at(scope: impl Into<String>, value: u64) -> Self` |

#### `Revised`

A value together with the revision its write was given.

| Method | Signature |
| --- | --- |
| `new` | `pub 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](https://strig.vercel.app/docs/governance/impact.md), [Why not](https://strig.vercel.app/docs/governance/why-not.md) and [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md).

#### `Mutation`

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

| Method | Signature |
| --- | --- |
| `role_change` | `pub fn role_change(&self) -> Option<(&Subject, &RoleAssignment, bool)>` |
| `kind` | `pub fn kind(&self) -> MutationKind` |
| `subject_after` | `pub fn subject_after(&self) -> Option<Subject>` |

#### `MutationKind`

The kind of a `Mutation`, without its payload.

| Method | Signature |
| --- | --- |
| `as_str` | `pub fn as_str(self) -> &'static str` |

#### `Proposal`

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

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(actor: &'a Subject, mutation: &'a Mutation, before: &'a [Grant], after: &'a [Grant]) -> Self` |
| `with_tuples` | `pub fn with_tuples(mut self, tuples: &'a dyn TupleStore) -> Self` |
| `with_now` | `pub fn with_now(mut self, now: u64) -> Self` |
| `grant` | `pub fn grant(&self) -> Option<&'a Grant>` |
| `subject_after` | `pub fn subject_after<'s>(&self, subject: &'s Subject) -> Cow<'s, Subject>` |
| `before_context` | `pub fn before_context(&self) -> Context<'_>` |
| `after_context` | `pub fn after_context(&self) -> Context<'_>` |

#### `Suggestion`

Compensating change proposed with a `Violation`.

| Method | Signature |
| --- | --- |
| `into_mutation` | `pub fn into_mutation(self, subject: Subject) -> Mutation` |
| `subject_id` | `pub fn subject_id(&self) -> &str` |

#### `Violation`

| Method | Signature |
| --- | --- |
| `new` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |
| `with` | `pub fn with(mut self, invariant: impl Invariant + 'static) -> Self` |
| `audited` | `pub fn audited(mut self, auditor: Arc<Auditor>) -> Self` |
| `with_revisions` | `pub fn with_revisions(mut self, source: Arc<dyn RevisionSource>) -> Self` |
| `apply_revised` | `pub fn apply_revised( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> Result<Revised<Vec<Grant>>, Vec<Violation>>` |
| `len` | `pub fn len(&self) -> usize` |
| `is_empty` | `pub fn is_empty(&self) -> bool` |
| `apply` | `pub fn apply( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>) -> Result<Vec<Grant>, Vec<Violation>>` |
| `at` | `pub fn at(&self, now: u64) -> GovernanceAt<'_>` |
| `apply_with` | `pub fn apply_with( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> Result<Vec<Grant>, Vec<Violation>>` |
| `impact` | `pub fn impact( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, options: &ImpactOptions<'_>) -> Result<Impact, Vec<Violation>>` |
| `apply_with_impact` | `pub 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`.

| Method | Signature |
| --- | --- |
| `fail_mode` | `pub fn fail_mode(mut self, mode: FailMode) -> Self` |
| `apply_reporting` | `pub 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>)` |
| `apply` | `pub fn apply( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>) -> Result<Vec<Grant>, Vec<Violation>>` |
| `impact` | `pub fn impact( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, options: &ImpactOptions<'_>) -> Result<Impact, Vec<Violation>>` |
| `apply_with_impact` | `pub 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_revised` | `pub 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_with` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub 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`.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new<I, S>(critical: I, members: Vec<Subject>, resource: Resource) -> Self where I: IntoIterator<Item = S>, S: Into<String>,` |
| `with_reserve` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub 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`.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(permission: impl Into<String>, resource: Resource) -> Self` |

#### `NoEscalation`

The actor only hands out what they hold.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |
| `bypass` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |
| `subject` | `pub fn subject(mut self, subject: Subject) -> Self` |
| `resource` | `pub fn resource(mut self, resource: Resource) -> Self` |
| `permission` | `pub fn permission(mut self, permission: impl Into<String>) -> Self` |
| `field` | `pub fn field(mut self, field: impl Into<String>) -> Self` |

#### `ImpactSource`

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

| Method | Signature |
| --- | --- |
| `derived` | `pub fn derived() -> Self` |
| `sample` | `pub fn sample(spec: SampleSpec) -> Self` |

#### `ImpactOptions`

What the impact of a change is computed over.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(source: ImpactSource) -> Self` |
| `with_tuples` | `pub fn with_tuples(mut self, tuples: &'a dyn TupleIndex) -> Self` |
| `with_env` | `pub fn with_env(mut self, env: &'a Attributes) -> Self` |
| `with_limits` | `pub fn with_limits(mut self, limits: QueryLimits) -> Self` |
| `at` | `pub 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.

| Method | Signature |
| --- | --- |
| `is_empty` | `pub fn is_empty(&self) -> bool` |
| `summary` | `pub 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.

| Method | Signature |
| --- | --- |
| `with_limits` | `pub fn with_limits(mut self, limits: QueryLimits) -> Self` |
| `with_max_remedies` | `pub 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`

| Method | Signature |
| --- | --- |
| `why_not` | `pub 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.

| Method | Signature |
| --- | --- |
| `describe` | `pub fn describe(&self, who: &str) -> String` |

#### `SeparationOfDuties`

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

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |
| `with_subjects` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub 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](https://strig.vercel.app/docs/approvals.md), [Elevation](https://strig.vercel.app/docs/governance/elevation.md) and [Recertification](https://strig.vercel.app/docs/governance/recertification.md).

#### `ApprovalRule`

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

#### `ApprovalPolicy`

The kinds of change that wait for approval.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |
| `from_rules` | `pub fn from_rules(rules: impl IntoIterator<Item = ApprovalRule>) -> Self` |
| `require` | `pub fn require(mut self, kind: MutationKind, permission: impl Into<String>, resource: Resource) -> Self` |
| `require_all` | `pub fn require_all(self, permission: impl Into<String>, resource: Resource) -> Self` |
| `rule_for` | `pub fn rule_for(&self, mutation: &Mutation) -> Option<&ApprovalRule>` |
| `rules` | `pub fn rules(&self) -> &[ApprovalRule]` |

#### `PendingStatus`

Where a request stands.

#### `PendingRequest`

A change waiting for another actor.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(id: impl Into<String>, actor: Subject, mutation: Mutation, requested_at: u64) -> Self` |
| `expiring_at` | `pub fn expiring_at(mut self, expires_at: Option<u64>) -> Self` |
| `with_status` | `pub fn with_status(mut self, status: PendingStatus) -> Self` |
| `with_impact` | `pub fn with_impact(mut self, impact: Impact) -> Self` |
| `with_elevation` | `pub fn with_elevation(mut self, elevation: ElevationInfo) -> Self` |
| `is_pending` | `pub fn is_pending(&self) -> bool` |
| `is_due` | `pub fn is_due(&self, now: u64) -> bool` |
| `target` | `pub fn target(&self) -> String` |

#### `PendingError`

#### `PendingStore`

Where the requests are kept.

#### `MemoryPendingStore`

`PendingStore` in memory.

| Method | Signature |
| --- | --- |
| `new` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(engine: &'a Engine, current: &'a [Grant], now: u64, meta: &'a Attributes) -> Self` |
| `with_tuples` | `pub fn with_tuples(mut self, tuples: &'a dyn TupleStore) -> Self` |
| `with_now` | `pub fn with_now(mut self, now: u64) -> Self` |
| `with_current` | `pub 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`.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(governance: &'a Governance, policy: &'a ApprovalPolicy, store: &'a dyn PendingStore) -> Self` |
| `with_distinct_roles` | `pub fn with_distinct_roles(mut self) -> Self` |
| `with_impact` | `pub fn with_impact(mut self, options: &'a ImpactOptions<'a>) -> Self` |
| `review_impact` | `pub fn review_impact(&self, review: &Review<'_>, id: &str) -> Result<ImpactReview, ApprovalError>` |
| `fail_mode` | `pub fn fail_mode(mut self, mode: FailMode) -> Self` |
| `pending` | `pub fn pending(&self, now: u64) -> Result<Vec<PendingRequest>, PendingError>` |
| `propose` | `pub fn propose( &self, review: &Review<'_>, actor: &Subject, mutation: &Mutation, id: impl Into<String>, expires_at: Option<u64>) -> Result<Proposed, ApprovalError>` |
| `approve` | `pub fn approve(&self, review: &Review<'_>, approver: &Subject, id: &str) -> Result<Approved, ApprovalError>` |
| `reject` | `pub fn reject( &self, review: &Review<'_>, approver: &Subject, id: &str, reason: &str) -> Result<PendingRequest, ApprovalError>` |
| `expire_due` | `pub 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.

| Method | Signature |
| --- | --- |
| `role` | `pub fn role(role: impl Into<String>) -> Self` |
| `permission` | `pub fn permission(permission: impl Into<String>, target: TargetSelector) -> Self` |
| `scoped` | `pub fn scoped(mut self, new_scope: Anchor) -> Self` |
| `key` | `pub fn key(&self) -> ElevationKey` |

#### `ElevationKey`

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

#### `ElevationRule`

How a role or permission may be elevated.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new( key: ElevationKey, max_duration_ms: u64, approver_permission: impl Into<String>, approver_resource: Resource) -> Self` |
| `requiring_justification` | `pub fn requiring_justification(mut self) -> Self` |
| `allowing_break_glass` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |
| `from_rules` | `pub fn from_rules(rules: impl IntoIterator<Item = ElevationRule>) -> Self` |
| `with` | `pub fn with(mut self, rule: ElevationRule) -> Self` |
| `rule_for` | `pub fn rule_for(&self, target: &ElevationTarget) -> Option<&ElevationRule>` |
| `rules` | `pub fn rules(&self) -> &[ElevationRule]` |

#### `ElevationRequest`

A request for an elevation.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(id: impl Into<String>, actor: Subject, target: ElevationTarget, duration_ms: u64) -> Self` |
| `justified` | `pub fn justified(mut self, justification: impl Into<String>) -> Self` |
| `break_glass` | `pub fn break_glass(mut self) -> Self` |

#### `ElevationInfo`

What a `PendingRequest` says about the elevation it carries.

| Method | Signature |
| --- | --- |
| `new` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub 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`.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(governance: &'a Governance, policy: &'a ElevationPolicy, store: &'a dyn PendingStore) -> Self` |
| `with_impact` | `pub fn with_impact(mut self, options: &'a ImpactOptions<'a>) -> Self` |
| `fail_mode` | `pub fn fail_mode(mut self, mode: FailMode) -> Self` |
| `active` | `pub fn active(&self, now: u64) -> Result<Vec<PendingRequest>, PendingError>` |
| `pending_reviews` | `pub fn pending_reviews(&self) -> Result<Vec<PendingRequest>, PendingError>` |
| `expire_due` | `pub fn expire_due(&self, now: u64, meta: &Attributes) -> Result<Vec<PendingRequest>, ApprovalError>` |
| `request` | `pub fn request( &self, review: &Review<'_>, req: &ElevationRequest, expires_at: Option<u64>) -> Result<Elevated, ApprovalError>` |
| `approve` | `pub fn approve(&self, review: &Review<'_>, approver: &Subject, id: &str) -> Result<Approved, ApprovalError>` |
| `reject` | `pub fn reject( &self, review: &Review<'_>, approver: &Subject, id: &str, reason: &str) -> Result<PendingRequest, ApprovalError>` |
| `revoke` | `pub fn revoke( &self, review: &Review<'_>, by: &Subject, id: &str, reason: Option<&str>) -> Result<Revoked, ApprovalError>` |
| `close_review` | `pub fn close_review( &self, review: &Review<'_>, reviewer: &Subject, id: &str, note: &str) -> Result<PendingRequest, ApprovalError>` |

#### More on `PendingRequest`

| Method | Signature |
| --- | --- |
| `elevation_active` | `pub fn elevation_active(&self, now: u64) -> bool` |

#### `RecertError`

Why a recertification step failed.

#### `ReviewerRule`

Who may review an item.

| Method | Signature |
| --- | --- |
| `permission` | `pub fn permission(permission: impl Into<String>, resource: Resource) -> Self` |
| `role` | `pub fn role(role: impl Into<String>) -> Self` |
| `subject` | `pub 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.

| Method | Signature |
| --- | --- |
| `for_permission` | `pub fn for_permission(permission: impl Into<String>, reviewer: ReviewerRule) -> Self` |
| `for_role` | `pub fn for_role(role: impl Into<String>, reviewer: ReviewerRule) -> Self` |

#### `RecertScope`

What a campaign reviews.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |
| `anchored` | `pub fn anchored(mut self, anchor: Anchor) -> Self` |
| `permissions` | `pub fn permissions<I, S>(mut self, permissions: I) -> Self where I: IntoIterator<Item = S>, S: Into<String>,` |
| `roles` | `pub fn roles<I, S>(mut self, roles: I) -> Self where I: IntoIterator<Item = S>, S: Into<String>,` |
| `subject_kinds` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new( id: impl Into<String>, reviewer: ReviewerRule, reviewer_permission: impl Into<String>, reviewer_resource: Resource, due_at: u64, keep_period_ms: u64) -> Self` |
| `named` | `pub fn named(mut self, name: impl Into<String>) -> Self` |
| `scoped` | `pub fn scoped(mut self, scope: RecertScope) -> Self` |
| `routed` | `pub fn routed(mut self, route: ReviewerRoute) -> Self` |
| `defaulting_to` | `pub fn defaulting_to(mut self, action: DefaultAction) -> Self` |
| `escalating_to` | `pub fn escalating_to(mut self, reviewer: ReviewerRule) -> Self` |

#### `RecertTarget`

The access an item is about.

| Method | Signature |
| --- | --- |
| `label` | `pub fn label(&self) -> String` |

#### `Delegation`

A reviewer handing an item over.

#### `ItemState`

Where an item stands.

#### `RecertItem`

One access to certify.

| Method | Signature |
| --- | --- |
| `is_open` | `pub fn is_open(&self) -> bool` |

#### `CampaignStatus`

Where a campaign stands.

#### `Campaign`

A recertification campaign and its items.

| Method | Signature |
| --- | --- |
| `is_open` | `pub fn is_open(&self) -> bool` |
| `item` | `pub fn item(&self, id: &str) -> Option<&RecertItem>` |
| `open_items` | `pub fn open_items(&self) -> impl Iterator<Item = &RecertItem>` |
| `certified` | `pub fn certified(&self, now: u64) -> impl Iterator<Item = &RecertItem>` |
| `report` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |

#### `Recertifications`

The recertification flow over a `Governance` and a `RecertStore`.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(governance: &'a Governance, store: &'a dyn RecertStore) -> Self` |
| `with_impact` | `pub fn with_impact(mut self, options: &'a ImpactOptions<'a>) -> Self` |
| `fail_mode` | `pub fn fail_mode(mut self, mode: FailMode) -> Self` |
| `open_campaigns` | `pub fn open_campaigns(&self) -> Result<Vec<Campaign>, RecertError>` |
| `report` | `pub fn report(&self, id: &str) -> Result<CampaignReport, RecertError>` |
| `open` | `pub fn open( &self, review: &Review<'_>, opener: &Subject, spec: CampaignSpec, subjects: &[Subject]) -> Result<Campaign, RecertError>` |
| `decide` | `pub fn decide( &self, review: &Review<'_>, reviewer: &Subject, id: &str, item: &str, decision: RecertDecision, reason: Option<&str>) -> Result<Decided, RecertError>` |
| `close` | `pub 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](https://strig.vercel.app/docs/audit.md).

#### `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.

| Method | Signature |
| --- | --- |
| `typical_record_bytes` | `pub const fn typical_record_bytes(self) -> u64` |
| `typical_decision_bytes` | `pub const fn typical_decision_bytes(self) -> u64` |
| `estimate_decision_bytes` | `pub const fn estimate_decision_bytes(self, records: u64) -> u64` |
| `estimate_bytes` | `pub 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.

| Method | Signature |
| --- | --- |
| `with_capacity` | `pub fn with_capacity(mut self, capacity: usize) -> Self` |
| `with_base_delay_ms` | `pub fn with_base_delay_ms(mut self, base_delay_ms: u64) -> Self` |
| `with_max_delay_ms` | `pub fn with_max_delay_ms(mut self, max_delay_ms: u64) -> Self` |
| `with_on_drop` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(policy: RetryPolicy) -> Self` |
| `stats` | `pub fn stats(&self) -> AuditStats` |
| `pending` | `pub fn pending(&self) -> Vec<AuditRecord>` |
| `flush` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |
| `records` | `pub fn records(&self) -> Vec<AuditRecord>` |
| `drain` | `pub fn drain(&self) -> Vec<AuditRecord>` |

#### `JsonLinesAudit`

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

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(out: W) -> Self` |
| `into_inner` | `pub fn into_inner(self) -> W` |

#### `Clock`

#### `Auditor`

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

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(level: AuditLevel, sink: Arc<dyn AuditSink>) -> Self` |
| `with_fail_mode` | `pub fn with_fail_mode(mut self, mode: FailMode) -> Self` |
| `with_permission_fail_mode` | `pub fn with_permission_fail_mode(mut self, permission: impl Into<String>, mode: FailMode) -> Self` |
| `with_retry` | `pub fn with_retry(mut self, policy: RetryPolicy) -> Self` |
| `with_queue` | `pub fn with_queue(mut self, queue: Arc<PendingQueue>) -> Self` |
| `with_redactor` | `pub fn with_redactor(mut self, redactor: Redactor) -> Self` |
| `observe` | `pub fn observe(mut self, observer: impl Fn(&AuditRecord, AuditStatus) + Send + Sync + 'static) -> Self` |
| `queue` | `pub fn queue(&self) -> &Arc<PendingQueue>` |
| `stats` | `pub fn stats(&self) -> AuditStats` |
| `flush` | `pub fn flush(&self) -> usize` |
| `chain_head` | `pub fn chain_head(&self) -> Option<String>` |
| `with_clock` | `pub fn with_clock(mut self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self` |
| `resume_chain` | `pub fn resume_chain(self, last_hash: impl Into<String>) -> Self` |
| `level` | `pub fn level(&self) -> AuditLevel` |
| `decide` | `pub fn decide( &self, engine: &Engine, ctx: &Context<'_>, request: &Request<'_>, meta: &Attributes) -> (Decision, Result<AuditRecord, AuditError>)` |
| `decision` | `pub fn decision( &self, request: &Request<'_>, decision: &Decision, meta: &Attributes) -> Result<AuditRecord, AuditError>` |
| `explained` | `pub fn explained(&self, explanation: &Explanation, meta: &Attributes) -> Result<AuditRecord, AuditError>` |
| `grant_mutation` | `pub fn grant_mutation( &self, actor: &Subject, mutation: &Mutation, before: &[Grant], result: &Result<Vec<Grant>, Vec<Violation>>, meta: &Attributes) -> Result<AuditRecord, AuditError>` |
| `grant_mutation_with` | `pub 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_impact` | `pub 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_change` | `pub fn tuple_change( &self, actor: &Subject, added: bool, tuple: &Tuple, outcome: AuditOutcome, meta: &Attributes) -> Result<AuditRecord, AuditError>` |
| `exclusive` | `pub fn exclusive( &self, actor: &Subject, action: AuditAction, resource: &ObjectRef, outcome: AuditOutcome, at: u64, meta: &Attributes) -> Result<AuditRecord, AuditError>` |
| `role_change` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(leaves: Vec<Hash>) -> Self` |
| `from_records` | `pub fn from_records(records: &[AuditRecord]) -> Result<Self, AuditError>` |
| `size` | `pub fn size(&self) -> usize` |
| `root` | `pub fn root(&self) -> Hash` |
| `root_at` | `pub fn root_at(&self, size: usize) -> Option<Hash>` |
| `inclusion_proof` | `pub fn inclusion_proof(&self, index: usize) -> Option<Vec<Hash>>` |
| `consistency_proof` | `pub fn consistency_proof(&self, first: usize) -> Option<Vec<Hash>>` |

#### `TimestampError`

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

| Method | Signature |
| --- | --- |
| `code` | `pub fn code(&self) -> &'static str` |

#### `HashAlgorithm`

A hash algorithm for the stamped digest.

| Method | Signature |
| --- | --- |
| `name` | `pub fn name(self) -> &'static str` |

#### `TimestampRequest`

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

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(algorithm: HashAlgorithm, digest: Vec<u8>) -> Self` |
| `for_chain_head` | `pub fn for_chain_head(head: &str, nonce: Option<u64>) -> Result<Self>` |
| `to_der` | `pub fn to_der(&self) -> Result<Vec<u8>>` |

#### `TimestampInfo`

What a verified time stamp states.

#### `VerifyOptions`

What to check besides the signature.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(imprint: Vec<u8>, trusted_roots: Vec<Vec<u8>>) -> Self` |
| `for_chain_head` | `pub 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.

| Method | Signature |
| --- | --- |
| `head` | `pub fn head(mut self, head: impl Into<String>) -> Self` |
| `start` | `pub 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`).

| Method | Signature |
| --- | --- |
| `verified` | `pub fn verified(label: impl Into<String>, gen_time: i64, policy: String, serial: String) -> Self` |
| `failed` | `pub fn failed(label: impl Into<String>, error: impl Into<String>) -> Self` |

#### `ConformanceReport`

The report.

| Method | Signature |
| --- | --- |
| `build` | `pub fn build(records: &[AuditRecord], anchors: &Anchors) -> Self` |
| `from_json_lines` | `pub fn from_json_lines(text: &str, anchors: &Anchors) -> Self` |
| `with_timestamps` | `pub fn with_timestamps(mut self, timestamps: Vec<TimestampCheck>) -> Self` |
| `is_conforming` | `pub 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](https://strig.vercel.app/docs/policy-language.md), [Diff and lint](https://strig.vercel.app/docs/tools/diff-lint.md) and [Importers](https://strig.vercel.app/docs/tools/importers.md).

#### `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`

| Method | Signature |
| --- | --- |
| `validate` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |
| `len` | `pub fn len(&self) -> usize` |
| `is_empty` | `pub fn is_empty(&self) -> bool` |
| `add_source` | `pub fn add_source(&mut self, name: &str, text: &str) -> Result<Language, Diagnostics>` |
| `build` | `pub 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.

| Method | Signature |
| --- | --- |
| `parse` | `pub 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.

| Method | Signature |
| --- | --- |
| `with_limits` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(policy: &'a Policy) -> Self` |
| `with_origins` | `pub 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.

| Method | Signature |
| --- | --- |
| `is_empty` | `pub fn is_empty(&self) -> bool` |
| `count` | `pub fn count(&self, kind: ChangeKind) -> usize` |

#### `Severity`

How much a finding matters.

| Method | Signature |
| --- | --- |
| `name` | `pub const fn name(self) -> &'static str` |

#### `LintCode`

The kinds of finding.

| Method | Signature |
| --- | --- |
| `code` | `pub const fn code(self) -> &'static str` |
| `name` | `pub const fn name(self) -> &'static str` |
| `severity` | `pub const fn severity(self) -> Severity` |
| `parse` | `pub fn parse(text: &str) -> Option<LintCode>` |

#### `Finding`

One thing the lint found.

| Method | Signature |
| --- | --- |
| `lint_code` | `pub fn lint_code(&self) -> Option<LintCode>` |
| `position` | `pub fn position(&self) -> Option<String>` |

#### `LintOptions`

What to leave out.

| Method | Signature |
| --- | --- |
| `ignoring` | `pub 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](https://strig.vercel.app/docs/storage/exclusive-store.md).

#### `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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(resource: ObjectRef, holder: ObjectRef, priority: i64, acquired_at: u64, expires_at: u64) -> Self` |
| `is_active` | `pub fn is_active(&self, now: u64) -> bool` |
| `granted` | `pub fn granted(claim: &Claim, now: u64) -> Self` |
| `renewed` | `pub fn renewed(&self, now: u64, ttl_ms: u64) -> Self` |

#### `Terms`

Priority and duration of a claim.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(priority: i64, ttl_ms: u64) -> Self` |

#### `Claim`

Request to own `resource` on behalf of `holder`.

| Method | Signature |
| --- | --- |
| `new` | `pub 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.

| Method | Signature |
| --- | --- |
| `decide` | `pub 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`.

| Method | Signature |
| --- | --- |
| `decide` | `pub 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.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new() -> Self` |

#### `ExclusivePermissions`

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

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(hold: impl Into<String>, preempt: impl Into<String>) -> Self` |

#### `ExclusiveRegistry`

Exclusive ownership of resources over a store.

| Method | Signature |
| --- | --- |
| `new` | `pub fn new(store: S) -> Self` |
| `with_permissions` | `pub fn with_permissions(mut self, permissions: ExclusivePermissions) -> Self` |
| `with_max_ttl` | `pub fn with_max_ttl(mut self, max_ttl_ms: u64) -> Self` |
| `with_audit` | `pub fn with_audit(mut self, auditor: Arc<Auditor>) -> Self` |
| `permissions` | `pub fn permissions(&self) -> &ExclusivePermissions` |
| `store` | `pub fn store(&self) -> &S` |
| `validate` | `pub fn validate(&self, engine: &Engine) -> Result<(), ExclusiveError>` |
| `holder` | `pub fn holder(&self, resource: &ObjectRef, now: u64) -> Result<Option<Lease>, ExclusiveError>` |
| `acquire` | `pub fn acquire(&mut self, claim: &Claim, now: u64, preemption: Preemption) -> Result<Acquisition, ExclusiveError>` |
| `acquire_checked` | `pub fn acquire_checked( &mut self, engine: &Engine, ctx: &Context<'_>, subject: &Subject, resource: &Resource, terms: Terms, now: u64) -> Result<Acquisition, ExclusiveError>` |
| `release` | `pub fn release(&mut self, resource: &ObjectRef, holder: &ObjectRef, now: u64) -> Result<Lease, ExclusiveError>` |
| `renew` | `pub fn renew( &mut self, resource: &ObjectRef, holder: &ObjectRef, now: u64, ttl_ms: u64) -> Result<Lease, ExclusiveError>` |
| `renew_checked` | `pub fn renew_checked( &mut self, engine: &Engine, ctx: &Context<'_>, subject: &Subject, resource: &Resource, now: u64, ttl_ms: u64) -> Result<Lease, ExclusiveError>` |
| `expire` | `pub 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.

### Hub::publish

```
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.

| Constructor | Signature |
| --- | --- |
| `Change::new` | `pub fn new(kind: ChangeKind, scope: Anchor) -> Self` |
| `Change::grants`, `Change::tuples` | `pub fn grants(scope: Anchor) -> Self` |
| `Change::roles` | `pub fn roles(subject: impl Into<String>, scope: Anchor) -> Self` |
| `Change::catalog`, `Change::resync` | `pub fn catalog() -> Self` |
| `Change::expiry` | `pub fn expiry(subject: impl Into<String>) -> Self` |
| `Change::expiry_for_everyone` | `pub fn expiry_for_everyone() -> Self` |
| `for_subject`, `with_id` | `pub 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 `ServerMessage`s 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.

| Message | Direction | Fields |
| --- | --- | --- |
| `ServerMessage::Hello` | server to client | `origin`, `subject` |
| `ServerMessage::Capabilities` | server to client | `scope`, `set`: replaces the previous set |
| `ServerMessage::Change` | server to client | `change` |
| `ServerMessage::Resync` | server to client | none: discard what you have and wait for new `capabilities` |
| `ServerMessage::Error`, `Ping` | server to client | `message`; none |
| `ClientMessage::Watch`, `Unwatch` | client to server | `scopes`; WebSocket only |
| `ClientMessage::Refresh` | client to server | none: 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.

### Realtime::sse

```
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(..)`.

### RedisTransport::new

```
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`.

### PgTransport::new

```
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.

| Item | Signature | What it does |
| --- | --- | --- |
| `PgTables::new` | `pub 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_sql` | `pub fn schema_sql(&self) -> String` | The DDL of both tables and their indexes. Safe to run twice. |
| `PgTables::put_grant` | `pub async fn put_grant<C: GenericClient>(&self, client: &C, grant: &Grant) -> Result<(), PgQueryError>` | Stores a grant. |
| `PgTables::grants_by_permission` | `pub 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::new` | `pub 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_where` | `pub 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_predicate` | `pub 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_predicate` | `pub 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.

| Item | Signature | What it does |
| --- | --- | --- |
| `connect` | `pub async fn connect(url: &str) -> Result<Client, tokio_postgres::Error>` | Opens a plain connection and spawns its driver task. |
| `migrate` | `pub 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_with` | `pub async fn migrate_with(client: &Client, tables: &PgTables) -> Result<Vec<u32>, PgQueryError>` | The same, for custom table names. |
| `schema_version` | `pub async fn schema_version(client: &Client, tables: &PgTables) -> Result<Option<u32>, PgQueryError>` | The version in the ledger, or `None` before the first migration. |
| `PgStore::load` | `pub async fn load<C: GenericClient>(client: &C, tables: PgTables) -> Result<Self, PgQueryError>` | Reads grants and tuples into memory. |
| `PgStore::reload` | `pub async fn reload<C: GenericClient>(&self, client: &C) -> Result<(), PgQueryError>` | Reads both again; `reload_grants` and `reload_tuples` read one. |
| `PgStore::is_stale` | `pub fn is_stale(&self) -> bool` | True when the last reload failed; cleared by the next one that succeeds. |
| `PgStore::grants` | `pub fn grants(&self) -> PgGrants` | A `GrantSource` and `GrantIndex` over the snapshot; `tuples` gives the `TupleStore` and `TupleIndex`. |
| `PgStore::follow` | `pub 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_role` | `pub 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_mutation` | `pub 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`. |
| `PgPendingStore` | `connect(url: &str, tables: PgTables) -> Result<Self, PgQueryError>` | A `PendingStore` in a table; `due(now)` lists requests past their deadline. |
| `PgRecertStore` | `connect(url: &str, tables: PgTables) -> Result<Self, PgQueryError>` | A `RecertStore` in a table. |
| `PgExclusiveStore` | `connect(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.

| Item | Signature | What it does |
| --- | --- | --- |
| `new` | `pub 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_client` | `pub fn from_client(client: Client, prefix: impl Into<String>) -> Result<Self, StoreError>` | Reuses a client you already have. |
| `with_timeout` | `pub fn with_timeout(mut self, timeout: Duration) -> Self` | Bounds every command. |
| `with_retention` | `pub fn with_retention(mut self, retention: Duration) -> Self` | How 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.

### DecisionServer::router

```
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.

| Status | `error.code` | Meaning |
| --- | --- | --- |
| 400 | `malformed_json`, `invalid_request`, `batch_too_large`, `too_many_resources` | The request is wrong; retrying it unchanged fails again. |
| 404, 405 | `not_found`, `method_not_allowed` | No such route, or the wrong method. |
| 413, 415 | `body_too_large`, `unsupported_media_type` | The body is over the limit, or is not `application/json`. |
| 503 | `source_unavailable`, `query_limit_exceeded`, `overloaded`, `relation_depth_exceeded`, `deadline_exceeded`, `clock_unavailable`, `internal` | The 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

#### Client::http

```
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:

```bash
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

| Route | Body | Answer |
| --- | --- | --- |
| `POST /v1/check` | `subject`, `permission`, `resource`, optional `env`, `at`, `min_revision` | `decision`, `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/list` | `subject`, `permission`, `kind`, optional `layout`, `resources`, `env`, `at` | `kind`, `permission`, `exact`, `shape`, `residual`, `warnings`, `evaluated_at`, and `ids` when `resources` was sent. Never read `residual` as an allow. |
| `POST /v1/who` | `permission`, optional `resource`, `env`, `at` | `entries` (each with a typed `subject` and the `via` that grants it), `except`, `evaluated_at`. |
| `POST /v1/access` | `resource`, `env`, `at` | Who holds which permission on the resource, with the path that decided each. |
| `GET /health/live` | none | `200 {"status":"live"}` while the process runs. |
| `GET /health/ready` | none | `200 {"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

| Header | Effect |
| --- | --- |
| `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: true` | On the AuthZEN and Envoy routes with `with_reasons(true)`: adds a fixed reason code to the answer. |

### Limits

| Limit | Default | Past it |
| --- | --- | --- |
| Body | 1 MiB | `413 body_too_large` |
| Batch | 256 checks | `400 batch_too_large` |
| Candidate resources in a list | 1000 | `400 too_many_resources` |
| Work (checks × grants) | 1 000 000 | `503 query_limit_exceeded` |
| `QueryLimits` for `list`, `who`, `access` | 1000 and 100 000 | `503 query_limit_exceeded` |
| Work slots | one per CPU | `503 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.

| Status | `error.code` | Meaning |
| --- | --- | --- |
| 400 | `malformed_json` | The body is not JSON. |
| 400 | `invalid_request` | Valid 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. |
| 400 | `batch_too_large`, `too_many_resources` | Over the batch or the candidate limit. |
| 404, 405 | `not_found`, `method_not_allowed` | No such route, or the wrong method. |
| 413, 415 | `body_too_large`, `unsupported_media_type` | Body over the limit, or not `application/json`. |
| 503 | `source_unavailable` | The grants or the policy could not be loaded. |
| 503 | `query_limit_exceeded`, `overloaded`, `relation_depth_exceeded`, `deadline_exceeded` | A limit, the work slots, a relation chain too deep to read a deny, or the deadline. |
| 503 | `revision_not_reached`, `revision_mismatch` | The source is behind the required revision, or tracks another scope. |
| 503 | `clock_unavailable`, `internal` | No 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.

```bash
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}
```

| Route | Notes |
| --- | --- |
| `POST /access/v1/evaluation` | `{subject, action, resource, context?}` answers `{decision, context?}`. |
| `POST /access/v1/evaluations` | Top-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/subject` | Subjects of `subject.type` that hold `action.name` on `resource`. |
| `POST /access/v1/search/action` | The permissions of the catalog that `subject` holds on `resource`. |
| `POST /access/v1/search/resource` | Only with `AuthzenConfig::with_resource_catalog`; otherwise `404`. |
| `GET /.well-known/authzen-configuration` | Only with `AuthzenConfig::with_issuer` (an `https` URL); otherwise `404`. |

| AuthZEN | Strig |
| --- | --- |
| `subject.type`, `subject.id` | `Subject.kind`, `Subject.id`. Kinds in `authenticated_kinds` (default `user`) also carry the `authenticated` principal. |
| `subject.properties` | Attributes. `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.id` | The first step of the path, `type:id`. |
| `resource.properties` | Attributes. `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.name` | The permission. `action.properties` is not read. |
| `context` | `env`. 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.

| `CheckRequest` | Strig |
| --- | --- |
| `attributes.request.http.method` and `path` | The 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-separated | The 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_resolver` | The 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.

| Case | `status.code` | HTTP | `x-strig-reason` (with `with_reasons(true)`) |
| --- | --- | --- | --- |
| The engine allows, or the route is `public` | `OK` (0) | | |
| The engine denies | `PERMISSION_DENIED` (7) | 403 | `denied` |
| No route matches | same | 403 | `no_route` |
| No usable subject on a route that needs one | same | 403 | `no_subject` |
| The resolver does not know the resource | same | 403 | `unknown_resource` |
| Source down, deadline passed, no work slot, clock or work failed | same | 403 | `unavailable` |
| No HTTP attributes, or a template that cannot be filled | same | 403 | `bad_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
```

| Command | What 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](https://strig.vercel.app/docs/audit.md). |
| `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 help` | Prints 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!("<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](https://strig.vercel.app/docs/javascript.md#install-by-platform). 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](https://strig.vercel.app/docs/javascript.md#rules-written-in-javascript). The JSON spec covers the built-in `resource_owner` and `permission_holder`.

### load

```
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](https://strig.vercel.app/docs/javascript.md#catalog-types-for-the-frontend). `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](https://strig.vercel.app/docs/approvals.md)); `flushAudit` and `auditStats` drive the retry queue ([Audit](https://strig.vercel.app/docs/audit.md)).

### 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.

| Import | What it gives you |
| --- | --- |
| `@the-hades-organization/strig` | `load`, the types and `scopeFromString(text: string): Resource`. |
| `.../client` | `PermissionClient`: connects over SSE or WebSocket, keeps the capabilities of each scope and decides locally. Use it to shape the interface; the server still decides. |
| `.../server` | `Hub`, `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. |
| `.../remote` | `RemoteClient`, `CircuitBreaker`: the client of a decision server. |
| `.../express`, `.../fastify`, `.../nestjs` | `authorize`, `authorizeRoutes`, `createCan`; the Fastify `plugin`; `Can`, `StrigGuard` and `StrigRouteGuard`. Their framework is an optional peer dependency. See [Web frameworks](https://strig.vercel.app/docs/web-frameworks.md). |
| `.../approvals` | `Approvals`, `MemoryPendingStore`, `PendingStoreError`. See [Approvals](https://strig.vercel.app/docs/approvals.md). |
| `.../store` | `openJsonStore`, `JsonFileStore`, `JsonStoreError`, `STORE_VERSION`. See [JavaScript](https://strig.vercel.app/docs/javascript.md#grants-and-roles-in-a-json-file). |
| `.../testing` | `expressRoutes`, `nestRoutes`, `collectFastifyRoutes`, `auditRoutes`, `assertRoutesCovered`. See [Web frameworks](https://strig.vercel.app/docs/web-frameworks.md#test-the-table). |
| `.../types` | `generateTypes`; the `strig-types` command writes the same output. |

### authorize

```
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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

```ts title="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`

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

Types: `PrismaWhere`, `PrismaMapping`.

### `/drizzle`

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

Types: `DrizzleMapping`.

### `/kysely`

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

Types: `KyselyMapping`, `KyselyWhere`.

### `/types`

```ts title="TypeScript"
function generateTypes(catalog: CatalogInput): string
```

Types: `CatalogInput`.

## Python: strig-auth

```bash
pip install strig-auth
```

```python
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](https://strig.vercel.app/docs/integrations/python.md).

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

```python title="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

```bash
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](https://strig.vercel.app/docs/integrations/go.md).

```go
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" { /* ... */ }
```

| Item | Signature |
| --- | --- |
| `NewEngine` | `func NewEngine(spec any) (*Engine, error)` |
| `Engine.Fork` | `func (e *Engine) Fork() (*Engine, error)` |
| `Engine.Close` | `func (e *Engine) Close() error` |
| `Engine.NewContext` | `func (e *Engine) NewContext(init any) (*Context, error)` |
| `Engine.Check` | `func (e *Engine) Check(c *Context, request any, opts ...Option) (bool, error)` |
| `Engine.Decide` | `func (e *Engine) Decide(c *Context, request any, opts ...Option) (*Decision, error)` |
| `Engine.Explain` | `func (e *Engine) Explain(c *Context, request any, opts ...Option) (map[string]any, error)` |
| `Engine.CheckMany` | `func (e *Engine) CheckMany(c *Context, requests any, opts ...Option) ([]bool, error)` |
| `Engine.List` | `func (e *Engine) List(c *Context, subject any, permission, kind string, options any, opts ...Option) (map[string]any, error)` |
| `Engine.WhoCan` | `func (e *Engine) WhoCan(c *Context, permission string, opts ...Option) ([]map[string]any, error)` |
| `Engine.Catalog` | `func (e *Engine) Catalog() (map[string]any, error)` |
| `Engine.Apply`, `Impact`, `ReviewImpact`, `Propose`, `Resolve`, `Expire` | `func (e *Engine) Apply(input any) (map[string]any, error)`, and the same shape for the others |
| `Context.SetGrants` | `func (c *Context) SetGrants(grants any) error` |
| `Context.AddGrant` | `func (c *Context) AddGrant(grant any) error` |
| `Context.RemoveGrant` | `func (c *Context) RemoveGrant(id string) (bool, error)` |
| `Context.Grants` | `func (c *Context) Grants() ([]map[string]any, error)` |
| `Context.AddTuple`, `RemoveTuple` | `func (c *Context) AddTuple(tuple any) (bool, error)` |
| `Context.SetEnv` | `func (c *Context) SetEnv(env any) error` |
| `Context.SetNow` | `func (c *Context) SetNow(t time.Time) error` |
| `Context.SetLimits` | `func (c *Context) SetLimits(limits any) error` |
| `Context.Close` | `func (c *Context) Close() error` |
| `WithNow` | `func WithNow(t time.Time) Option` |
| `Compile` | `func Compile(text string, file ...string) (map[string]any, error)` |
| `Format` | `func Format(text string) (string, error)` |
| `CodeOf` | `func CodeOf(err error) string` |
| `Decision` | `struct { Effect string; Reason json.RawMessage; Matched []string; Warnings []string }`, with `Allowed() bool` |
| `Error` | `struct { Code string; Message string; Diagnostics []any }` |
| `ErrClosed`, `ErrBroken` | `INVALID_ARGUMENT` after `Close`; `INTERNAL` when the module trapped and was discarded. |

## Java

```xml
<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](https://strig.vercel.app/docs/integrations/jvm.md).

```java
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() */ }
}
```

| Item | Signature |
| --- | --- |
| `Engine` | `public Engine(Object spec)`, `public Engine fork()`, `public synchronized void close()` |
| `newContext` | `public Context newContext()`, `public Context newContext(Object init)` |
| `check` | `public boolean check(Context context, Object request)`, and with a trailing `Instant now` |
| `decide` | `public Decision decide(Context context, Object request)`, and with a trailing `Instant now` |
| `explain` | `public Map<String, Object> explain(Context context, Object request)`, and with `Instant now` |
| `checkMany` | `public List<Boolean> checkMany(Context context, Object requests)`, and with `Instant now` |
| `list` | `public Map<String, Object> list(Context context, Object subject, String permission, String kind, Object options)` |
| `whoCan` | `public List<Map<String, Object>> whoCan(Context context, String permission)` |
| `catalog` | `public Map<String, Object> catalog()` |
| `apply`, `impact`, `reviewImpact`, `propose`, `resolve`, `expire` | `public Map<String, Object> apply(Object input)`, and the same shape for the others |
| `Context` | `setGrants(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()` |
| `Strig` | `static Map<String, Object> compile(String text)`, `compile(String text, String file)`, `static String format(String text)` |
| `Decision` | `record Decision(String effect, JsonNode reason, List<String> matched, List<String> warnings)`, with `boolean allowed()` |
| `StrigException` | `String 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.

| Export | Signature | What it does |
| --- | --- | --- |
| `memory` | linear memory | The host writes inputs into it and reads outputs from it. |
| `strig_alloc` | `(len: usize) -> *mut u8` | Gives 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) -> u64` | Runs 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:

| Group | Operations |
| --- | --- |
| Policy language | `compile`, `format`, `print`, `convert`, `isFormatted`, `loadProject`, `runTests`, `diff`, `lint` |
| Handles | `engine.new`, `engine.free`, `context.new`, `context.free` |
| Context | `context.setGrants`, `context.addGrant`, `context.removeGrant`, `context.grants`, `context.addTuple`, `context.removeTuple`, `context.setEnv`, `context.setNow`, `context.setLimits` |
| Decisions | `check`, `decide`, `explain`, `whyNot`, `checkMany`, `explainMany`, `list`, `whoCan`, `catalog` |
| Changes | `apply`, `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.

| Direction | `type` | Fields | Meaning |
| --- | --- | --- | --- |
| Server | `hello` | `origin`, `subject?`, `version` | First message; `version` is 1 when absent. |
| Server | `capabilities` | `scope`, `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. |
| Server | `change` | `change` | A change that affects a watched scope. |
| Server | `resync` | none | The client lost changes: discard what it has and wait for new `capabilities`. |
| Server | `error` | `message` | A failure. |
| Server | `ping` | none | Keep-alive. |
| Client | `watch`, `unwatch` | `scopes` | Starts or stops watching scopes; `watch` answers with each scope's capabilities. |
| Client | `refresh` | none | Asks again for the capabilities of every watched scope. |
| Client | `refresh_at_least` | `revision` | Like `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.

| Family | Codes |
| --- | --- |
| Input | `INVALID_ARGUMENT`, `INVALID_INPUT`, `INVALID_SPEC`, `INVALID_GRANT`, `UNKNOWN_SUBJECT`, `UNKNOWN_INVARIANT`, `REENTRANT_CALL` |
| Queries | `QUERY_LIMIT_EXCEEDED`, `RELATION_DEPTH_EXCEEDED`, `QUERY_ERROR` |
| Exclusive ownership | `EXCLUSIVE_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 language | `DSL_PARSE`, `DSL_VALIDATE`, `DSL_CONFLICT`, `DSL_UNREPRESENTABLE`, `DSL_UNSUPPORTED`, `DSL_LIMIT`, `DSL_DUPLICATE_SOURCE`, `DSL_IO` |
| Other | `INTERNAL` |

**`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](#error-codes-server).

**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.
