Strig
English · Português (Brasil)
Strig is an authorization library for Rust. You declare a permission catalog, hand the engine your grants, and ask whether a subject may do something to a resource. RBAC, ABAC and ReBAC are evaluated over the same grants. Changes to grants go through governance rules, are audited, and can be pushed in real time to other instances and to the browser.
The core does no IO, needs no async runtime and compiles to WebAssembly. Real time, transports and the JavaScript bindings are separate, optional crates.
Documentation · Playground · API on docs.rs · Changelog
[!NOTE] Strig is pre-1.0: the API can change between minor versions. Versions up to 0.5.0 were published as Themis. The versioning and deprecation policy says what counts as public API and what breaks it, migration.md shows what to change when you upgrade, and benchmarks has the numbers.
Install
Features of the strig crate:
| Feature | Default | Adds |
|---|---|---|
audit |
yes | Audit trail for grant changes and decisions, with a hash chain |
exclusive |
no | One holder per resource, with priority and preemption |
conformance |
no | Turns on exclusive and adds strig::exclusive_conformance, the battery an ExclusiveStore adapter runs in its tests (not stable API) |
dsl |
no | The policy language: parse, validate, convert, format. No IO, works in wasm |
dsl-fs |
no | dsl plus reading and writing .strig files and directories |
Quick start
use *;
Deny Grant { grant_id: "g2", permission: "document.invoice.export", rank: 1, strategy: "most_specific" }
Allow Grant { grant_id: "g1", permission: "document.export", rank: 3, strategy: "most_specific" }
Dave may export documents anywhere in acme (g1), but not invoices: g2 sits on doc_type:invoice, one step from the document (rank: 1), while g1 sits on org:acme, three steps away (rank: 3). The rank counts steps from the resource itself (rank 0), and the default strategy lets the lowest rank decide.
The same engine runs in Node, Bun and the browser; see JavaScript.
The same engine can be configured from JSON, TOML or YAML through EngineSpec, or from a .strig file in the policy language. EngineSpec::builder() returns the EngineBuilder, so you can add in code what does not serialize, such as condition functions.
More to run:
Crates
All crates except strig-inspect, strig-node, strig-python and strig-wasi are on crates.io at the same version.
| Crate | Use it for | Main dependencies |
|---|---|---|
strig |
Catalog, decision engine, governance, auditing, JSON spec, policy language | serde, thiserror; sha2 with audit |
strig-sync |
Change hub, Transport trait, SSE/WebSocket sessions independent of any web framework, capability cache |
tokio |
strig-redis |
Transport over Redis pub/sub |
redis |
strig-postgres |
Transport over Postgres LISTEN/NOTIFY, sent inside your transaction; grants, tuples, roles and pending requests stored in Postgres |
tokio-postgres |
strig-axum |
axum SSE and WebSocket routes over strig-sync sessions |
axum |
strig-server |
HTTP decision server, and a Rust client that denies when it gets no answer | axum, hyper-util (client) |
strig-macros |
policy! and include_policy!: the policy is validated at compile time |
strig |
strig-node |
The npm package: native module (N-API) for Node and Bun, WebAssembly for the browser | napi or wasm-bindgen |
strig-python |
The PyPI package strig-auth (import strig): native extension (PyO3, abi3) over the same core as strig-node |
pyo3 |
strig-wasi |
The C-ABI WebAssembly module the Go and JVM bindings run: JSON in, JSON out, no wasm-bindgen |
strig-node |
strig-cli |
The strig command: strig test runs the tests of a policy, for people and for CI (JUnit) |
strig |
strig-inspect |
Inspector: decision traces, grant simulation, access matrix, audit trail. Desktop window and terminal commands | gpui-pre, gpui-component |
[]
= "0.6"
= "0.6"
Concepts
| Concept | Type | What it holds |
|---|---|---|
| Catalog | Catalog, PermissionDef |
Dotted permission keys (document.invoice.export), the targets each accepts, implied_by, free-form meta. Exports and imports JSON. |
| Resource | Resource, Anchor |
A path of steps (anchors) from the most specific to the broadest (document:7 → doc_type:invoice → project:42 → org:9), with an implicit global at the end, plus attributes. |
| Subject | Subject |
Id, roles (optionally scoped), principals (authenticated, anonymous or your own), attributes. |
| Grant | Grant |
Who (User, Role, Principal, Relation, Any), which permission, on which target (a kind or an exact step), allow or deny, with an optional scope (an anchor the resource path must pass through) and condition. |
| Engine | Engine |
Decides. Returns a Decision with the effect, the reason, the matched grants and warnings. |
| Governance | Governance, Invariant |
Applies a grant change only if every invariant passes, and audits the outcome. |
The catalog is validated when it is built. It refuses a malformed key, a duplicate, an unregistered target, a missing parent, a cycle, and anything your own CatalogRule rejects.
How a decision is made
- Unknown permission. Deny with
Reason::UnknownPermission. - Overrides. They run in order, and the first one that answers decides.
override_excepttakes permissions, and the ones they imply, out of an override's reach. - Collection. A grant is a candidate when all of these hold:
- its permission is the requested one, or one that implies it;
- its scope is on the resource path;
- its target matches a step of the path;
- its subject matches;
- its condition is true.
- Strategy. The strategy picks the deciding grant. With no candidate, deny.
A condition or relation that cannot be evaluated (missing attribute, engine without a TupleStore) never opens access: the allow is dropped, the deny still applies, and the reason goes into Decision::warnings.
| Strategy | Rule |
|---|---|
MostSpecific (default) |
The most specific step with any grant decides; on that step, deny wins. |
DenyOverrides |
Any deny wins. |
PermitOverrides |
Any allow wins. |
FirstApplicable |
The first grant in source order decides. |
The three models
RBAC
RoleGraph::builder().inherit("maintainer", "member") gives maintainer the grants of member. Subject::with_role_in(role, anchor) limits a role to the resources under that step.
ABAC
Grant::when(condition) attaches a serializable Condition. Operands read subject.*, resource.* and env.*.
| Operators | On |
|---|---|
eq, ne, lt, le, gt, ge, is_in, exists |
Any value |
starts_with, ends_with, contains |
Text (contains also tests list membership) |
any_in, all_in |
Lists |
ip_in |
An address in a CIDR or a list of CIDRs |
time_between, weekday_in |
The decision instant, in UTC or in the IANA zone tz |
all, any, not |
Other conditions |
call |
Your own function, registered with ConditionRegistry::register |
The time conditions read the instant given by Context::at; without it they cannot be resolved, so the allow does not apply. There is no regular-expression condition. Engine::validate_grant checks that every call names a registered function.
Time zones
Office hours are local, so time_between and weekday_in take an optional IANA zone: Condition::time_between("09:00", "18:00").in_tz("America/Sao_Paulo") in Rust, {"op": "time_between", "from": "09:00", "until": "18:00", "tz": "America/Sao_Paulo"} in JSON or JavaScript, and time_between "09:00" "18:00" tz "America/Sao_Paulo" or weekday_in ["mon", "tue"] tz "Europe/Lisbon" in the policy language. Without tz the clock is UTC, as before.
- Daylight saving time. The instant decides the local time. A window inside the hour that a spring-forward jump skips never holds that day; the hour that a fall-back repeats holds on both passes. A window that crosses midnight (
"22:00"to"06:00") and the weekday follow the local date. - Unknown names. The validator refuses a zone it does not know when the policy loads, with position and hint. A condition built without validation fails when evaluated, and an
allowwith an error never applies. - Trace.
explainshows the local time it used, for example12:30 America/Sao_Paulo (UTC-03:00). - Cost. The zone database is the default feature
tzof thestrigcrate (chrono-tz) and adds about 0.9 MB (0.13 MB gzipped) to the.wasm. Without the feature atzis refused at load.
ReBAC
Store object#relation@subject tuples in a TupleStore and describe each type in a RelationSchema with This, Computed, TupleToUserset, Union, Intersection and Exclusion. user:* stands for every user.
A grant with SubjectMatcher::relation("editor") applies to whoever holds editor on the step its target matched. The search stops at max_relation_depth (32 by default) and cuts cycles.
Governance
Governance runs a grant change through a list of invariants and returns the new grant set only if all of them pass. Persist the result on Ok; on Err you get the violations.
From here on, snippets reuse the engine, grants and subjects of earlier examples; names such as actor, current (the grants you hold today) and request_meta stand for your own values. The None argument is an optional TupleStore for ReBAC, and apply_with is apply plus request metadata for the audit trail.
let governance = new
.with
.with
.with
.with
.with
.audited;
let next = governance.apply_with?;
// persist `next`
Assigning or revoking a role goes through the same invariants and is audited as role_assign or role_revoke. The grant set comes back unchanged; the subject to persist comes from Mutation::subject_after.
let change = AssignRole ;
governance.apply_with?;
let bob = change.subject_after.expect; // persist bob's roles
Forbid applies to a role assignment only when the assignment targets a user, and it ignores scope. Write your own rule by implementing Invariant. The invariant list can also come from JSON (InvariantSpec).
Approving a change before it applies
A change the policy marks as needing approval does not apply on the spot: it waits as a pending request that another actor approves or refuses. The policy is per kind of change and names who approves.
let policy = new
.require
.require;
let store = new;
let flow = new;
let review = Review ;
// Ana proposes; the invariants judge it and, if they accept, it is kept (expires in an hour).
let Pending = flow.propose? else ;
// Caio approves: he needs `org.approve`, he is not Ana, and the invariants run again over `current`.
let approved = flow.approve?;
// persist `approved.grants`
An approver who is the author, lacks the permission, or meets invariants that now refuse gets ApprovalError::Refused and the request stays pending; reject(&review, &caio, id, "reason") closes it with a reason, and expire_due(now, &meta) closes the ones whose expiry came (approving a due request closes it too). With an auditor on the governance, every step is a record (mutation_propose, mutation_approve, mutation_reject, mutation_expire; see docs/audit-format.md), and the approval record is written before the change is applied. The crate keeps no clock and no database: pass the instant, and serialise approvals of one request when several processes share a store. Not covered: several approvers (quorum) and the author withdrawing their own request.
In JavaScript the engine judges and audits each step and Approvals keeps the requests:
import from '@the-hades-organization/strig/approvals';
const flow = ;
const proposed = await flow.;
const done = await flow.; // `persist` runs before the request is marked approved
await flow.;
await flow.;
JsonFileStore keeps the requests in the same file (new Approvals(engine, store.pendingStore, options), and store.approvePending(flow, id, approver) persists the grants before marking the request approved). Without a rule for its kind, propose applies the change at once (applied: true).
Rules declared in the catalog
Some rules belong to a permission, so they are declared on its PermissionDef:
| Flag | Effect |
|---|---|
depends_on |
Holding the permission requires holding each listed one on the same resource (checked by Prerequisites). |
non_delegable |
Only a manager hands it out, not whoever merely holds it. |
management_only |
Grantable only to management roles. |
override_only |
Valid only through an override; a plain grant of it does not count. |
NoEscalation keeps an actor from handing out what they do not hold: an allow grant or a role assignment is refused unless the actor holds every permission it confers, and every permission those imply, wherever it would apply. Holding org.roles.edit is therefore not a way to give someone a stronger role than your own.
let catalog = builder
.target_kind
.permission
.permission
.permission
.permission
.build?;
let engine = builder.build?;
let governance = new
.with
.with
.with;
// `lead` holds `project.edit` only, so handing out `project.view` is an escalation.
let current = vec!;
let handout = Add;
let refused = governance.apply.unwrap_err;
assert_eq!;
Two more tools:
- Lockout reserve.
NoLockout::with_reservenames who should take over a critical permission. When a change would leave that permission with no holder, theViolationcarries aSuggestionwith the role assignment that fixes it. Nothing is applied; the suggestion is also written to the audit record. - Role templates.
RoleTemplate::materializeturns a template into ordinary grants. The template id and version go into the change metadata; the grants keep no link to the template.
Auditing
With the audit feature, every change that goes through governance becomes an AuditRecord, applied or refused. Record ReBAC tuples and role assignments with Auditor::tuple_change and Auditor::role_change. If the sink fails to write, governance refuses the change with the audit violation: no record, no change (unless you choose FailMode::Open, below).
let auditor = new;
Built-in sinks are MemoryAuditLog and JsonLinesAudit, which writes to any io::Write. To send records to a database, a queue or a SIEM, implement AuditSink.
What each level keeps
Each level keeps everything from the one above it. Sizes are compact JSON bytes per line of JSON Lines, without compression or indexes, measured on a reference record (audit::reference_record): a grant with a scope and a two-clause condition, UUID ids, an actor with two roles and three request metadata entries.
| Level | Change records keep | Bytes | Per 1M records |
|---|---|---|---|
minimal |
When, who, action, object id, outcome | 175 | 175 MB |
standard |
+ grant summary (permission, subject, target, effect, scope, has a condition) and the names of the invariants that refused | 388 | 388 MB |
detailed |
+ the whole grant with its condition, the full actor, the violation messages, the request metadata | 1,097 | 1.10 GB |
forensic |
+ SHA-256 digest of the grant set before and after, and the hash chain | 1,415 | 1.42 GB |
Decisions can be audited too: Auditor::decide(&engine, &ctx, &request, &meta) decides and records. The reference decision (audit::reference_decision_record) has three grants in the source, one with a condition, a resource with three steps, UUID ids and three metadata entries.
| Level | Decision records keep | Bytes | Per 1M records |
|---|---|---|---|
minimal |
When, subject, permission@resource, allowed or denied |
285 | 285 MB |
standard |
+ the reason (override, deciding grant and step, or no grant) and the matched grants | 669 | 669 MB |
detailed |
+ the full subject and resource, the warnings, the request metadata. Enough to re-evaluate the decision later | 1,239 | 1.24 GB |
forensic |
+ the full trace from Engine::explain, and the hash chain |
3,582 | 3.58 GB |
To project your own volume, call AuditLevel::estimate_bytes(n) for changes and AuditLevel::estimate_decision_bytes(n) for decisions; the forensic decision size grows with the number of grants the source returns. In a database, add the row overhead (about 28 bytes per row in Postgres) and your indexes.
The numbers are checked: the estimates_match_reference_records and decision_estimates_match_reference_records tests fail if a measured size drifts more than 10% from the table, and cargo run -p strig --example audit_storage measures again.
Hash chain
At the forensic level each record carries the hash of the previous one. audit::verify_chain detects an edited or removed record, and Auditor::resume_chain continues the chain after a restart.
The exact bytes of a record and the hash computation, with a test vector another language can reproduce, are in docs/audit-format.md. The same page explains how to take only the records and chain them in your own log, and how to anchor the head of the chain outside (Auditor::chain_head, then verify_chain_anchored(&records, start, head)), which is what catches records cut off the end.
When the sink fails
By default a sink that fails refuses the change (FailMode::Closed). With FailMode::Open the change goes ahead and the record waits in an in-memory retry queue, in order, with a capacity and a backoff you set (RetryPolicy); AuditStatus::Pending says it is waiting and Auditor::stats() counts what is waiting or was dropped. The mode is chosen per call (governance.at(now).fail_mode(..), Auditor::grant_mutation_with), per permission (with_permission_fail_mode) or as the auditor's default (with_fail_mode), in that order of precedence.
let auditor = new
.with_fail_mode
.with_permission_fail_mode
.with_retry
.with_redactor;
with_redactor masks attributes before the record is hashed and written, so the hash covers the masked version.
In JS the sink is a synchronous function; a throw is a failure of the sink:
const engine = ;
const out = engine.;
out.; // 'written' | 'pending' | 'dropped'
engine.; // retries the queue, answers { pending, writtenLate, dropped, failures, nextRetryAt }
; // { ok: true, head } or { ok: false, code }
Validity windows
Grant::valid_between(from, until) limits a grant in time; valid_from and valid_until set one end.
- Times are milliseconds since the Unix epoch. The window includes
fromand excludesuntil. - The caller supplies the instant:
Context::at(now)for decisions,Governance::at(now)for changes. - Without an instant, a grant with a window does not apply, so a missing clock denies.
let grant = allow
.valid_between;
let grants = vec!;
let ana = user;
let project = new;
let request = new;
assert!;
assert!;
assert!;
CapabilityCache expires its entries at the next window boundary. Removing expired grants from storage is left to a job of yours.
Field permissions
A grant can name the fields of the resource it covers, as CASL does: "document.edit only on title and body". A grant without fields covers the whole resource, exactly as before.
let catalog = builder
.target_kinds
.permission
.build?;
let engine = builder.build?;
let grants = vec!;
let ana = user.with_role;
let doc = new;
let ctx = new;
engine.allowed_fields; // FieldSet::Only { title, body }
engine.check; // true
engine.check; // false
How the pieces combine:
- One field is one decision. A question about a field (
Request::field) is decided by the same strategy (MostSpecific,DenyOverrides,PermitOverrides,FirstApplicable) over the grants that cover that field. Adenywith fields takes away only those fields; anallowwith fields gives only those. There is no new rule to learn: each field is judged as if the grants that do not name it did not exist. - The whole resource needs every field. A question without a field is allowed only by a grant without fields, and a
denywith fields blocks it as soon as the strategy would deny any of its fields. Socheckstays safe to use as a gate: a field-restrictedallownever opens the resource, and it isallowed_fieldsthat answers "which fields". implied_bycarries the fields. A grant ofdocument.managerestricted totitlegivesdocument.editontitleonly.depends_onis judged on the same field.document.editonbodyneedsdocument.viewonbody(or on the whole resource).- The catalog can declare the fields of a permission. Then a grant that names another field is refused by
validate_grant(and by the policy validator, with the line and a hint), and a request for an undeclared field is denied. Without a declaration the engine trusts the names the grants use, andallowed_fieldscan answerAllExcept("everything butstatus"), since it cannot list the rest. - It fails closed. A condition that cannot be evaluated drops an
allowand keeps adeny, field by field. An override that allows gives every field. - A policy without fields decides as it always did. The tests pin this.
Engine::explain_fields returns, for each field, the grants that gave it and the ones that took it away; Engine::explain of a request with a field marks the grants that do not cover it (FieldNotCovered). Listings (list) and who_can answer for the whole resource: a field-restricted allow is left out and a field-restricted deny counts as a plain one.
Governance follows: NoEscalation refuses to hand out a field the actor does not hold (and a whole-resource grant to someone who holds only some fields), and CatalogConformance validates the fields against the catalog.
In the policy language, fields is a field of permission and of grant in the three syntaxes (fields = [title, body] in Blocks, fields title, body in Rules and Actors). A policy that uses fields exports "schema": 4, so a reader of an older schema refuses it instead of reading a field-restricted grant as a whole-resource one. See docs/dsl.md.
In JavaScript, engine.allowedFields(ctx, request) returns { kind: 'all' | 'all_except' | 'only' | 'none', fields? }, request.field asks about one field, and pickAllowed(object, fields) masks a response:
const fields = engine.allowedFields(ctx, { subject, permission: 'document.edit', resource });
res.json(pickAllowed(document, fields)); // only title and body leave
PermissionClient.allowedFields(permission, resource) and can(permission, resource, field) decide locally. Capabilities that carry field-restricted grants are sent in two forms (grants for older readers, which never see a restricted allow and read a restricted deny as whole, and withFields with the real ones), so an older client fails closed.
Reverse queries and filtered listing
Ask who can do something, or what a subject can reach, instead of checking one request. QueryContext carries the grants (and .at(now)), QueryLimits bounds the work, and PgTables turns the answers into SQL.
let qctx = new.at;
let filter = engine.list;
let who = engine.who_can;
assert_eq!;
| Call | Returns |
|---|---|
engine.list(&qctx, &subject, permission, kind) |
An AccessFilter over the resources of that kind the subject can reach, ready to become a WHERE clause. |
engine.who_can(&qctx, permission) |
Everyone named by an allow grant of the permission, anywhere. Denies, overrides and conditions are not evaluated. |
engine.who_can_on(..) |
The same on one resource, with denies, overrides and conditions evaluated. |
engine.access_of(..) |
Everyone with access to a resource, and their permissions. |
engine.check_for(..) |
A check by subject reference: a SubjectResolver loads the subject, and the answer names the path that decided. |
Exclusive resources
With the exclusive feature, a resource can have one holder at a time. Terms::new(priority, ttl_ms) sets how strong the claim is and how long it lasts. A higher priority takes the resource over only when the claimant also holds exclusive.preempt. Permissions and time are checked by the same engine as any other decision.
let mut registry = default;
let now = 0; // milliseconds since the Unix epoch, passed by the caller
let first = registry.acquire_checked?;
assert_eq!;
let second = registry.acquire_checked?;
assert!;
Across processes
ExclusiveRegistry::default() keeps the leases in memory, so a resource is exclusive inside one process. To share it between instances, give the registry a store that decides atomically in the database:
// Postgres: run `migrate_with` first (schema version 4 adds `<prefix>_exclusive`).
let store = connect.await?;
let mut registry = new;
// Redis: every instance that shares the resource uses the same prefix.
let mut registry = new;
Acquire, renew, release and the sweep (expire) are one atomic step in each store: a row lock in a transaction for Postgres, WATCH/MULTI/EXEC for Redis. Two instances racing for the same resource have exactly one winner. Both give the same answers as the in-memory store (strig::exclusive_conformance::run (feature conformance) is the battery every store passes), and whether a lease is active is always decided with the now you pass, never the clock of the database. In Redis the native expiry only reclaims memory, after the lease's lifetime plus a retention (one hour by default). The trait is synchronous: both stores block the caller for the round trip (use spawn_blocking inside an async task) and fail closed with a StoreError on a timeout or a lost connection. Postgres keeps its connection on a thread of its own, like PgPendingStore; Redis uses the synchronous connection of the redis crate with timeouts. Both crates have the exclusive feature, on by default. The JavaScript binding does not expose them yet.
Real time
grant change ──► Hub::publish ──► local sessions (SSE/WebSocket) and CapabilityCache
│
└─► Transport (Redis, Postgres, your own) ──► Hub on the other instances
let hub = builder
.transport
.build;
let _relay = hub.spawn_relay;
let cache = new;
hub.on_change;
let provider = new.with_cache;
let realtime = new.with_provider;
// in the routes: realtime.sse(subject, scopes) or realtime.websocket(upgrade, subject, scopes)
A change notice (Change) says what kind of change happened and on which step, without the grants. Receivers reload from their own source, so any transport can carry it.
A session watches scopes, that is, anchors such as org:acme. With a CapabilityProvider, it sends its client the capabilities (the permissions the subject holds) of each affected scope, and changes that arrive together are recomputed once. When the transport drops and comes back, or a client falls behind, the hub emits Resync and everything is reloaded.
| Transport | Crate | Notes |
|---|---|---|
| Redis | strig-redis |
Pub/sub; publishing reconnects on its own. |
| Postgres | strig-postgres |
LISTEN/NOTIFY. Call strig_postgres::notify(&tx, channel, &change) inside the transaction that writes the grant, and the notice goes out only on commit. TLS through PgTransport::with_tls. |
| Your own | NATS, Kafka or any broker: implement Transport (publish and subscribe). |
The client protocol is JSON and identical over SSE and WebSocket. The server sends hello, capabilities, change, resync, error and ping; the client sends watch, unwatch and refresh (WebSocket only). For a web framework other than axum, forward the stream from Session::open and write each message with ServerMessage::to_sse or to_json.
Postgres storage
strig-postgres also keeps the data in Postgres: grants, ReBAC tuples, role assignments and pending requests, behind the same traits the engine already reads (GrantSource, GrantIndex, TupleStore, TupleIndex, PendingStore).
use ;
let tables = default.in_schema?.with_prefix?; // schema and names are yours
let client = connect.await?;
migrate_with.await?; // idempotent, versioned, safe on every boot
let store = load.await?;
let grants = store.grants; // GrantSource + GrantIndex, served from memory
let tuples = store.tuples; // TupleStore + TupleIndex
let _follower = store.follow;
- Why a snapshot. The core does no IO and
GrantSourceis synchronous, soPgStore::loadreads the tables and the engine is served from memory. The snapshot reloads when the transport delivers aChange(grants, tuples or resync; a lagging receiver reloads everything). A store only exists loaded, so the engine never decides over an empty set that is missing a deny. If a reload fails the previous snapshot stays andis_stale()turns true: put it in your readiness probe. The snapshot holds every grant and tuple, so size it for that; for very large tuple sets keep answeringTupleStorefrom your own indexed query. - Writing.
put_grant,delete_grant,put_tuple,delete_tuple,assign_roleandrevoke_roletake a client or a transaction.commit_mutation(&tx, channel, &mutation)writes what aMutationchanges and sends itsNOTIFYin the same transaction, so the notice goes out if, and only if, the change commits. Calllock_governance(&tx)first and readall_grants(&tx)inside the transaction, so two instances never judge a change against the same stale set. - Governance end to end. Read the grants and the actor (
tables.subject(&tx, "user", id)builds theSubjectwith its stored roles), runGovernance::apply, thencommit_mutationand commit. Other instances reload on the notice. - Roles.
strig_roleskeeps the assignments per subject (role, optional scope, optional window). A subject read from it carries theauthenticatedprincipal when its kind isuser. - Pending requests.
PgPendingStoreis aPendingStoreover a table, with the expiry in an indexed column (due(now)lists whatexpire_duecloses). The trait is synchronous, so the store owns a connection on its own thread and each call blocks for one round trip: call it fromspawn_blockinginside async code. A call that does not answer in time (10 s by default) is aPendingError::Store, which refuses, andupdateis oneUPDATE ... WHERE state = 'pending', so a request decided meanwhile by another process is never decided twice. - Migrations.
migrate/migrate_withembed the SQL, record each version in<prefix>_migrationsand run in one transaction under an advisory lock. They are additive (CREATE ... IF NOT EXISTS); nothing drops or rewrites data. Schema and table names are validated as plain identifiers.
The tests run against a real Postgres when STRIG_PG_URL is set (see Development) and skip without it.
Decision server and remote client
strig-server answers decisions over HTTP, for services that do not embed the engine.
let source = new;
let router = new.router;
let listener = bind.await?;
serve.await?;
The router serves POST /v1/check, /v1/check/batch, /v1/list, /v1/who and /v1/access, plus GET /health/live and /health/ready. Grants come from a DecisionSource; MemorySource holds a Snapshot you can replace. Decisions use the server's clock. The full contract is in crates/strig-server/API.md.
The client fails closed. Only a 200 counts as an answer: a timeout, a refused connection, a 503 or an unreadable body becomes ClientDecision::Denied with the reason, and a circuit breaker stops calling a server that keeps failing.
let config = default
.with_timeout
.with_breaker;
let client = http;
let request = new;
if client.check.await.is_allowed
AuthZEN
DecisionServer::new(source).with_authzen(AuthzenConfig::default()) also serves the OpenID AuthZEN Authorization API 1.0 (Final, January 2026) next to /v1, so gateways and platforms that speak the standard query Strig with no adapter: POST /access/v1/evaluation, /access/v1/evaluations (with the three evaluations_semantics), /access/v1/search/subject, /access/v1/search/action, /access/v1/search/resource (with a ResourceCatalog) and GET /.well-known/authzen-configuration (with an issuer). subject.properties become attributes, with roles and principals properties for roles and principals; the broader steps of the resource path come from a path property or from a PathResolver the server owns; context is env. It fails closed like /v1: a malformed request is a 400, a permission that is not in the catalog is {"decision": false}, and a server that cannot decide answers 500. The mapping and what is left out are in crates/strig-server/API.md.
let config = default
.with_issuer?
.with_path_resolver;
let router = new.with_authzen.router;
Envoy
With the envoy feature (off by default, no tonic or prost without it), DecisionServer::envoy_service(EnvoyConfig) serves Envoy's External Authorization (envoy.service.auth.v3.Authorization/Check, gRPC) over the same source as the HTTP routes, so a service mesh or a gateway built on Envoy asks Strig before it forwards a request. A declarative EnvoyConfig maps the request: the subject comes from a header or from the filter metadata (for example the claims jwt_authn validated), each method and path pattern asks one permission, and the resource is a template over the path parameters. OK on an allow; PERMISSION_DENIED with HTTP 403 on a deny, a path no rule covers, a missing subject, a source that is down or a deadline that passed, with an optional fixed x-strig-reason. A path with dot segments or encoded separators matches nothing. See crates/strig-server/API.md and examples/envoy.yaml.
let envoy = default
.with_subject_header?
.with_route?
.with_route?;
let service = new.envoy_service;
service.serve.await?;
Observability
Every crate has an optional tracing feature, off by default. It adds spans through tracing and metrics through the metrics facade, so you pick the backend: Prometheus, OpenTelemetry or your own recorder. The features chain (strig-sync/tracing turns on strig/tracing, strig-postgres/tracing and strig-redis/tracing turn on strig-sync/tracing, strig-server/tracing turns on strig/tracing).
= { = "0.8", = ["tracing"] }
= { = "0.8", = ["tracing"] }
With the feature off nothing is compiled in: the instrumented entry points are the plain calls. With it on and no subscriber or recorder installed, a decision costs about 110 ns more (decide/simple: 518 ns off, 630 ns on, against 517 ns before the feature existed; the bigger operations are within noise). The core still does no IO and still compiles to WebAssembly with and without the feature; there the decision latency histogram is not recorded, because std::time::Instant is not available on wasm32-unknown-unknown. The JavaScript binding is not instrumented yet.
No personal data. A metric label is one of: operation, permission (only a permission the catalog knows; anything else is unknown), effect, reason kind, invariant name, step, outcome, status, change kind, transport name, route, error code, breaker phase. Never a subject id, a resource id, an attribute or a request body, and spans carry the same fields. Tests in each crate run a scenario with recognizable ids and fail if one shows up in a label or a span. An invariant you write labels the metric with the name you gave it, so keep it a constant.
A decision a custom invariant or override makes while governance judges a change belongs to that change: only the outermost operation on a thread feeds the metrics, so strig_decisions_total counts what your application asked for. Spans nest either way.
| Metric | Type | Labels |
|---|---|---|
strig_decisions_total |
counter | operation (decide, explain), effect, reason, permission |
strig_decision_duration_seconds |
histogram | operation |
strig_query_duration_seconds |
histogram | operation (list, who_can, who_can_on) |
strig_mutations_total |
counter | outcome (applied, refused) |
strig_mutation_violations_total |
counter | invariant |
strig_approvals_total |
counter | step (propose, approve, reject, expire), outcome |
strig_audit_writes_total |
counter | status (written, pending, dropped, refused) |
strig_audit_pending |
gauge | none (depth of the retry queue) |
strig_audit_write_failures_total |
counter | none |
strig_audit_dropped_total |
counter | none |
strig_sync_changes_total |
counter | kind, direction (published, received) |
strig_sync_publish_errors_total |
counter | transport |
strig_sync_sessions_open / strig_sync_sessions_opened_total |
gauge / counter | none |
strig_sync_resyncs_total |
counter | reason (reconnect, lagged, notice) |
strig_sync_transport_reconnects_total |
counter | transport |
strig_sync_transport_failures_total |
counter | transport, stage (subscribe, stream) |
strig_server_requests_total |
counter | route, status |
strig_server_request_duration_seconds |
histogram | route |
strig_server_errors_total |
counter | code |
strig_client_calls_total |
counter | route, outcome |
strig_client_call_duration_seconds |
histogram | route |
strig_client_breaker_transitions_total |
counter | to (closed, half_open, open) |
strig_client_breaker_state |
gauge | none (0 closed, 1 half open, 2 open) |
| Span | Where | Fields |
|---|---|---|
strig.decision |
decide, check, explain |
operation, permission, effect, reason |
strig.query |
list, who_can, who_can_on |
operation, permission, kind |
strig.governance.apply |
Governance::apply and GovernanceAt |
outcome |
strig.approval |
propose, approve, reject, expire_due |
step, outcome |
strig.audit.write |
each audit record sent to the sink | mode |
strig.sync.publish, strig.sync.relay, strig.sync.session |
hub publish, transport relay, one client session | transport on publish |
strig.postgres.publish, strig.postgres.subscribe, strig.postgres.store.load, strig.postgres.store.reload, strig.postgres.store.commit_mutation, strig.redis.publish, strig.redis.subscribe |
the transports | none |
strig.server.request, strig.client.call |
the decision server and its client | route, status or outcome |
Events (a dropped audit record, a lost LISTEN connection, a breaker changing phase) go out at warn or info. Decision and query spans are debug, the rest info.
crates/strig-server/examples/otlp.rs exports both over OTLP/HTTP with tracing-opentelemetry and metrics-exporter-opentelemetry:
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
JavaScript: Node, Bun and the browser
import from '@the-hades-organization/strig';
const = await ; // native on Node/Bun, wasm in the browser
const engine = ; // the same EngineSpec JSON as in Rust
const ctx = ;
engine.;
engine.;
On Node and Bun, load() tries the native module and falls back to wasm. Set STRIG_BACKEND=native or STRIG_BACKEND=wasm to force one.
The native module ships as one small package per platform, installed by npm as an optional dependency of @the-hades-organization/strig (a typical install is about 2 MB to download and 8 MB on disk):
| Platform | Package |
|---|---|
| Linux x64 and arm64 (glibc) | strig-linux-x64-gnu, strig-linux-arm64-gnu |
| macOS Intel and Apple silicon | strig-darwin-x64, strig-darwin-arm64 |
| Windows x64 | strig-win32-x64-msvc |
Any other platform (Alpine/musl, for example) runs on the wasm backend, which is bundled in the main package. If you install with --omit=optional (or --no-optional), load() falls back to wasm too, and STRIG_BACKEND=native throws an error naming the package to install.
The JSON spec covers the built-in overrides, resource_owner and permission_holder. Custom condition functions (call), custom overrides and custom invariants are not part of the spec: in JS they are synchronous callbacks passed to the Engine constructor (see "Rules written in JavaScript").
In the browser
PermissionClient (/client) connects over SSE or WebSocket, keeps the capabilities of each scope and decides locally with the same engine. Use it to shape the interface; the server still decides on every operation.
import from '@the-hades-organization/strig/client';
const client = .;
client.;
client.;
Cost of a call and batches
A Context keeps its grants, tuples, env and instant on the Rust side, so a decision never sends them again; change them with addGrant (the same id replaces), removeGrant, addTuple, removeTuple, setNow and setEnv. What still crosses the boundary on each call is the request, and the binding sends it as one JSON.stringify string (the decision comes back the same way) when it is plain JSON; a request with undefined, NaN, functions, bigints or class instances takes the original path and its errors. check answers a boolean without building the Decision.
To decide many requests against one Context and one instant, cross the boundary once:
const allowed = engine.; // boolean[], in order
const traces = engine.; // Explanation[], in order
A request that cannot be read throws and decides none; it never becomes a silent false. Numbers per case are in docs/benchmarks.md.
Rules written in JavaScript
The call condition function, your own override and your own Invariant exist in JS too, as synchronous callbacks passed to the Engine constructor. The engine calls them in the middle of a decision or of apply; they show up like the native ones: the explain trace names the override, a refusal carries your violation, and the audit records it as it records the built-in invariants.
const engine = ;
engine.;
- A condition function gets the resolved operands and returns a boolean. An invariant gets
{ actor, mutation, before, after, now }(themutationhas the shapeapplytakes) and returns nothing to accept, or a text, or{ message, suggestion? }to refuse. Thesuggestionis a change; the governance re-checks it against every invariant before it surfaces. - A throw denies, never crashes. A condition that throws (or does not return a boolean) is a condition error: an allow grant does not apply, a deny grant still does, and the trace carries the message. An override that throws answers
denied. An invariant that throws refuses with the message of the error. - Callbacks are synchronous. A promise is not awaited; it is a wrong answer and denies like a throw.
- No re-entry. A callback that calls the engine, or changes another
Context, getsREENTRANT_CALL; changing theContextunder decision is refused by the runtime. Read what you need before the call and keep it in the closure. - A custom override is opaque to listings (
list), like any override that does not describe its reach: the resources it might decide on stay as residue, never as allowed.
Real time on a JS backend
/server has Hub, openSession, sseResponse (Fetch API: Bun.serve, Hono, Deno), pipeSse (Node's http) and three transports: redisTransport (node-redis and Bun's RedisClient), ioredisTransport and pgTransport (the pg package). Notices use the strig-sync format, so Rust and JS instances can share a channel.
Grants and roles in a JSON file
For a system with neither Postgres nor Redis, /store keeps the grants and the role assignments in one JSON file (Node and Bun):
import { openJsonStore } from '@the-hades-organization/strig/store';
const store = await openJsonStore({ path: './strig.json', createIfMissing: true });
const provider = engineProvider({ engine, Context, loadGrants: store.loadGrants }); // the grant source
const subject = store.subject({ kind: 'user', id: 'ana' }); // + the roles in the file
const result = await store.apply(engine, { actor, mutation: { assign_role: { subject, role: { role: 'admin' } } }, invariants });
// accepted: the new grants and roles are written; refused: nothing is written
- File:
{ "version": 1, "grants": [...], "roles": { "<subject id>": [<assignment>, ...] } }. Roles themselves (the hierarchy) stay in the engine spec; the file holds who has which. - Fails closed. A missing file, invalid JSON, a repeated grant id or a
versionother than 1 throwsJsonStoreError(STORE_NOT_FOUND,STORE_CORRUPT,STORE_VERSION) on load. The store never starts empty on its own;createIfMissingis the explicit way to start one. - Writes are atomic and serialised. Temp file in the same directory,
fsync,rename, thenfsyncof the directory. Calls in one process queue up; between processes a<file>.lock(created withO_EXCL) is held, and a lock whose owner died on this host, or that is older thanlockStaleMs(30 s), is taken over. Each change re-reads the file under the lock, so processes do not overwrite each other.STORE_LOCK_TIMEOUTafterlockTimeoutMs(5 s). - Changes:
addGrant,updateGrant,removeGrant,assignRole,revokeRole,setRoles, orapply(engine, input), which runs the governance over the grants the file holds right now and persists what it accepts. - Reload:
reload()after an outside edit, orwatch()to reload on its own (it watches the directory, since the rename replaces the file). A bad file on reload keeps the last good snapshot, throws fromreload()and goes toonErrorfromwatch().onChangefires after every reload and write. - Not here: audit records and a Rust-only store.
Express, Fastify and NestJS
The three integrations take the same options and decide on each route:
import from '@the-hades-organization/strig';
import from '@the-hades-organization/strig/express';
const = await ;
const options = ;
app.;
| Option | Meaning |
|---|---|
subject(req) |
The subject; returning nothing answers 401. |
resource(req) |
The resource. |
local: { engine, context, now } or remote: RemoteClient |
Where the decision comes from. Pass exactly one. |
The request never passes unless the decision allows it:
| Outcome | Status | Change it with |
|---|---|---|
| No subject | 401 |
unauthenticatedStatus |
| Denied | 403 |
denyStatus |
| The decision could not be made | 503 |
failureStatus |
Your subject or resource function threw |
500, with no detail |
errorStatus, onError |
- Fastify (
/fastify): the sameauthorize, plus apluginthat addsfastify.strigCan. - NestJS (
/nestjs):@Can('document.view')on a handler or controller, withnew StrigGuard(options)as the guard.
One route table, deny by default
To keep every rule in one place, give the integration a table instead of a permission per handler. A request no rule covers is refused (denyStatus, 403); a route is public only when its rule says public: true.
import from '@the-hades-organization/strig/express';
const routes = ;
app.; // before the routers
Paths use the framework syntax: literal segments, :name for one segment, a trailing * for one or more. The first matching rule decides, so write the specific ones first; HEAD falls under GET rules, and * as the method means any. The table matches the way the framework routes, so no request can slip past a protected rule into a broader public one: every segment is percent-decoded before the comparison (/%61dmin/1 is /admin/1; %2F stays inside its segment; a malformed escape matches nothing), and literals ignore case with caseSensitive: false. The default is the framework's own: Express ignores case, Fastify is case sensitive (set caseSensitive on the table if you changed the Fastify option), Nest follows its platform. Pass { caseSensitive: false } to assertRoutesCovered for an Express app. Each rule has permission or public: true (a bad table throws at startup). resource receives the request and the matched params: at app level Express has not filled req.params yet.
- Express (
/express) and Fastify (/fastify):authorizeRoutes(options)is a global middleware oronRequesthook (fastify.addHook('onRequest', ...)). It also answers 403 for URLs with no route, and a CORS preflight needs a rule or has to be answered before it. - NestJS (
/nestjs):{ provide: APP_GUARD, useValue: new StrigRouteGuard(options) }. The table decides first. If it allows, a@Canon the handler adds a second check that must also pass:@Cannarrows, it never opens what the table denies (and it applies on apublicrule too). A handler without@Canneeds nothing else.
Put the table under test so it cannot drift from the app (/testing):
import from '@the-hades-organization/strig/testing';
; // throws listing routes with no rule and rules with no route
expressRoutes(app) reads an Express 4 or 5 app or router (nested routers included, not mounted sub-apps); nestRoutes(app) does it for a Nest app on the Express adapter after app.init(); on Fastify call collectFastifyRoutes(fastify) before registering routes and pass the array it returns once the app is ready. auditRoutes(routes, table) returns { uncovered, unusedRules, ok } if you prefer to assert yourself.
Express, Fastify and NestJS are optional peer dependencies. An integration you do not import costs nothing, and importing one whose peer is missing throws MissingPeerError.
To get decisions from a decision server instead, pass a RemoteClient (/remote) as remote. It has a timeout and a breaker, and denies when there is no answer:
import from '@the-hades-organization/strig/remote';
const remote = ;
const = await remote.;
Catalog types for the frontend
A permission can carry its display name and description per locale (labels / descriptions, next to label / description; in Rust PermissionDef::localized_label("pt-BR", "Editar")). They are optional and are not declared in the policy language, only in the catalog export (JSON) or the builder. strig-types turns an exported catalog into one .ts file with the PermissionId union, a PERMISSIONS constant with the metadata and the helpers isPermissionId, permissionLabel and permissionDescription (locale with fallback to the default text). The output is sorted, so it only changes when the catalog does.
import { generateTypes } from '@the-hades-organization/strig/types'; // same thing, as a function
import { PermissionClient } from '@the-hades-organization/strig/client';
import type { PermissionId } from './permissions.generated';
const engine = new strig.Engine<PermissionId>(spec); // strict: check, explain, list, whoCan... take only the ids; without the parameter, any string
const client = new PermissionClient<PermissionId>(/* ... */);
client.can('users:read', resource); // only ids of the union compile; narrow a plain string with isPermissionId first
React and Angular
/react and /angular put the real-time PermissionClient (/client) behind the usual UI primitives. The decision is local, on the capabilities the stream delivers, and the answer is deny whenever there is none: before the first capabilities, after a disconnect, during a resync, on the server (SSR) and for a scope the grants do not cover. React 18 and 19, Angular 17+ (standalone, signals). Both take the PermissionId generated by strig-types as the type parameter.
import { PermissionClient } from '@the-hades-organization/strig/client';
import { StrigProvider, useCan, Can, useStrigStatus } from '@the-hades-organization/strig/react';
import type { PermissionId } from './permissions.generated';
const client = new PermissionClient<PermissionId>({ url: '/strig/stream', scopes: [project], strig, engine });
<StrigProvider client={client}>
<Can<PermissionId> permission="document.edit" resource={doc} fallback={<ReadOnly />}>
<Editor />
</Can>
</StrigProvider>;
const canEdit = useCan<PermissionId>('document.edit', doc); // re-renders when capabilities arrive
const { connected, resyncing, error } = useStrigStatus();
StrigProvider opens the stream on mount and closes it on unmount (connect={false} leaves that to you), and never connects on the server. Without a provider every hook denies.
// app.config.ts
import { provideStrig } from '@the-hades-organization/strig/angular';
providers: [provideStrig(client)]; // { connect: false } to open the stream yourself
// component
import { StrigCanDirective, StrigService, strigCanActivate } from '@the-hades-organization/strig/angular';
// template: <button *strigCan="'document.edit'; resource: doc; else readOnly">Edit</button>
canEdit = inject(StrigService<PermissionId>).can('document.edit', this.doc); // Signal<boolean>; arguments may be signals
// routes
{ path: 'doc/:id', canActivate: [strigCanActivate<PermissionId>('document.view', (route) => resourceOf(route))] }
The route guard waits for the first capabilities (waitMs, default 5000 ms) so a deep link is not refused while the stream opens, then decides locally; a timeout or a deny returns false, or whatever onDeny returns (run in the injection context, so it can return a UrlTree).
React and Angular are optional peer dependencies and are imported statically, so your bundler resolves its own copy (a copy loaded behind its back could be a second React and break the hooks). A missing peer therefore fails at module resolution with the loader's own error naming the package, not with MissingPeerError as the Express, Fastify and NestJS integrations do. The package ships Angular as partial Ivy output for the Angular linker. Vue and Svelte can follow the same way: the bridge in client-bridge.ts is framework-neutral and each binding is about a hundred lines.
Filtering a listing in Prisma, Drizzle and Kysely
engine.list(...) says what a subject can reach in a kind; /prisma, /drizzle and /kysely turn that answer into the where of your ORM, with the same meaning as PgTables has in Rust. Each takes the list result and a mapping of where the resource keeps what the filter reads, and returns { permission, where, settled?, residual }. Drizzle and Kysely are optional peers (Kysely is never imported: its builder arrives as the callback argument); Prisma needs none, since the where is a plain object.
import { toWhere } from '@the-hades-organization/strig/prisma';
const result = engine.list(ctx, subject, 'document.view', 'document', { layout: ['document', 'project', 'org'] });
const { where, settled, residual } = toWhere(result, {
kind: 'document',
id: 'id',
paths: { project: 'projectId', org: 'project.orgId' }, // a dotted path crosses a to-one relation
attrs: { owner: 'ownerId' },
optionalRelations: ['project'], // Prisma only: relations that may be absent
});
const documents = await prisma.document.findMany({ where });
import { toWhere } from '@the-hades-organization/strig/drizzle'; // paths: { project: documents.projectId, ... }
const { where } = toWhere(result, { kind: 'document', id: documents.id, paths: { project: documents.projectId, org: documents.orgId } });
const rows = await db.select().from(documents).where(where);
import { toWhere as toKyselyWhere } from '@the-hades-organization/strig/kysely'; // columns as strings
const { where: kyselyWhere } = toKyselyWhere(result, { kind: 'document', id: 'id', paths: { project: 'project_id', org: 'org_id' } });
const rows2 = await db.selectFrom('document').selectAll().where(kyselyWhere).execute();
- Fails closed. A kind or attribute the filter reads and the mapping lacks, an expression node with no query form, a filter for another kind than the mapping's: all throw
OrmFilterError(code:UNMAPPED_KIND,UNMAPPED_ATTRIBUTE,UNSUPPORTED_EXPR,UNSUPPORTED_VALUE,KIND_MISMATCH). Nothing becomes "all rows"; what is certainly empty becomes an impossible condition. - A deny reaches only what it names. Every test is true or false, never
NULL, soNOT (project_id = 'p2')keeps the rows with no project, asengine.checkdoes. In Prisma the negation is pushed to the fields ({ OR: [{ projectId: null }, { projectId: { not: 'p2' } }] }), and a relation that can be absent is listed inoptionalRelations; one left out only costs rows a deny would drop, never opens access. - A residue is not permission. A condition over the resource, an override or a strategy the database cannot settle stays in
residual.whereis the upper bound (every row that may be allowed) andsettledthe lower bound (rows allowed whatever the residue says), present only with a residue: check the rows ofwhereoutsidesettledwithengine.check. Without a residuewhereis exact. - One contract. Each module also exports an object (
prisma,drizzle,kysely) withtoWhere(filter, mapping), typed over thePermissionIdfromstrig-types.
The unit tests check the object each adapter builds, and an oracle runs every scenario (allow by kind, by anchor, by exact id, denies that cut, a condition that stays a residue) against SQLite (Drizzle and Kysely) and an evaluator of the Prisma shape, comparing the rows with the ids engine.list resolves. TypeORM, Sequelize and MikroORM have no adapter yet; the mapping and the compiler (bounds, Emitter) are what a new one would reuse.
Python
strig-auth is the Python binding over the same engine and the same JSON EngineSpec as the Rust and JavaScript APIs: a native extension (PyO3), one abi3 wheel per platform for Python 3.9 and later, with type stubs (py.typed).
= # or a plain dict: the EngineSpec JSON
=
=
; ;
=
# bool
# {"effect": "allow", "matched": [...], "reason": {...}}
# the trace
=
- Same JSON, same names. Arguments and results are the dicts and lists the JavaScript API takes and returns, with the same camelCase fields (
validFrom,grantId,auditStatus); methods and keyword arguments are snake_case (check_many,who_can_on,audit_sink). Anything that is not JSON (nan, aset, a non-text key, an int over 64 bits) is refused withINVALID_ARGUMENT; nothing is coerced. - Errors are exceptions with a
code. A failed call raisesstrig.StrigErrorwith.codeequal to theerrorCodeof the JavaScript binding (INVALID_INPUT,INVALID_ARGUMENT,UNKNOWN_SUBJECT,REENTRANT_CALL, ...); match on the code, not on the message. The policy language raisesstrig.DslError(aStrigError) with.diagnostics. - Rules written in Python.
Engine(spec, conditions={...}, overrides=[{"name": ..., "except": [...], "evaluate": fn}], invariants={...}, audit_sink=fn, audit_redact=fn, on_audit_drop=fn, audit_policy={...})take synchronous callables with the same contract as the JavaScript hooks: an exception denies (a condition that raises does not grant, an override that raises answersdenied, an invariant that raises refuses with its message), a coroutine is a wrong answer, and a callback that calls the engine or changes aContextgetsREENTRANT_CALL. The GIL stays held during a call, so a callback runs on the thread that is deciding. - Time is explicit. Every method that decides takes an optional
now(ms UTC) that wins overctx.set_now; without one the engine fails closed on validity windows. The system clock is used only byapply/proposefor the audit record and byExclusivewhennowis omitted. strig.Exclusive(...),strig.verify_audit_chain(records, anchors)andstrig.audit_estimate(level, records)mirror the JavaScript ones.strig.dslhascompile,print,convert,format,is_formatted,load_projectandload_project_dir.
To build it from the repository: pip install maturin && cd crates/strig-python && maturin develop && pytest.
Go
github.com/The-Hades-Organization/Strig/bindings/go is the Go binding over the same engine and the same JSON EngineSpec as the other APIs. It runs the engine compiled to WebAssembly (crates/strig-wasi, a plain C ABI with JSON in and out) on wazero, pure Go with no cgo, and the module is embedded with go:embed. Go 1.22 or later.
import strig "github.com/The-Hades-Organization/Strig/bindings/go"
engine, err := strig.NewEngine(spec) // spec: a map, a struct or a json.RawMessage
defer engine.Close()
ctx, _ := engine.NewContext(map[string]any)
ctx.AddGrant(grant); ctx.RemoveGrant("g1")
request := map[string]any
allowed, err := engine.Check(ctx, request) // (bool, error): an error is never an allow
decision, err := engine.Decide(ctx, request) // *Decision{Effect, Reason, Matched, Warnings}
explanation, err := engine.Explain(ctx, request, strig.WithNow(time.Now()))
many, err := engine.CheckMany(ctx, []any)
policy, err := strig.Compile(text) // the policy language, no engine needed
- Same JSON, same codes. Requests and results are the JSON of the JavaScript API with the same camelCase fields. A failure is a
*strig.ErrorwhoseCodeis theerrorCodeof the JavaScript binding (INVALID_INPUT,UNKNOWN_SUBJECT,DSL_PARSE, ...), withDiagnosticsfor the policy language; usestrig.CodeOf(err)orerrors.As. - Fails closed.
Checkreturnsfalsewith the error, nevertrue. If the module traps, the instance is discarded and every later call returnsstrig.ErrBroken. A closed engine or context, or a context of another engine, is an error. - Concurrency. An
Engineis safe for concurrent use, but one WebAssembly instance is single-threaded, so calls are serialized. For parallel throughput give each worker its ownengine.Fork()(its own instance, same spec, no shared state). AContextbelongs to the engine that made it. - Time is explicit.
WithNow(t)orctx.SetNow(t)set the instant; without one the engine fails closed on validity windows.Apply,Propose,ResolveandExpiretake the host clock when the input has nonow. - Not in this binding yet: callbacks (the
callcondition, overrides, invariants written in Go), the audit sink and exclusive resources. A spec that needs a callback fails closed.
The .wasm is also a release asset (strig-<version>.wasm) for any other host that speaks WebAssembly. To rebuild the embedded module: sh bindings/scripts/build-wasi.sh, then cd bindings/go && go test ./....
Java and Kotlin
io.github.the-hades-organization:strig is the JVM binding: the same WebAssembly module, run on Chicory (pure JVM, no native code), with the same JSON EngineSpec. Java 17 or later; Kotlin uses the same classes.
io.github.the-hades-organization
strig
${strig.version}
;
try
Map policy ; // the policy language, no engine needed
Engine(spec).use { engine ->
engine.newContext(mapOf("grants" to grants)).use { ctx -> engine.check(ctx, request) }
}
- Same JSON, same codes.
StrigException.code()is theerrorCodeof the JavaScript binding;diagnostics()carries the policy-language positions. - Fails closed.
checkthrows instead of returningtruewhen it cannot decide; a trapped instance is discarded and every later call throwsINTERNAL. - Concurrency. An
Engineis safe for concurrent use with serialized calls; give each workerengine.fork()for parallel throughput. AContextbelongs to its engine. Close both. - Time is explicit. Every deciding method has an overload taking an
Instant; without one the engine fails closed on validity windows. - Not in this binding yet: callbacks (the
callcondition, overrides, invariants written in Java), the audit sink and exclusive resources.
Publishing to Maven Central is not enabled yet (it needs the project's account and signing key). Until then, build the jar from the repository: sh bindings/scripts/build-wasi.sh jvm && cd bindings/jvm && mvn verify.
Policy language
With the dsl feature, a policy can be written as text instead of JSON. The same policy has three syntaxes, Blocks, Rules and Actors, and convert moves between them. Every error carries a position and a hint. The validated JSON stays the source of truth.
Try it in the playground, which runs the real engine compiled to WebAssembly. The guide has the three syntaxes side by side and the grammar.
use ;
const SOURCE: &str = "language blocks
target_kinds = [org]
permission org.read {
targets = [org]
}
";
let parsed = parse?;
let json = parsed.policy.to_json?;
let as_rules = convert?;
as_rules holds:
language rules
kinds org
permission org.read on org
Conditions in when read the same in the three syntaxes, for example a starts_with b, env.ip ip_in "10.0.0.0/8", time_between "09:00" "17:30" and weekday_in ["mon", "tue"]. The validator refuses a CIDR, a time of day, a weekday or a time zone it cannot read. When a name is one typo away from a declared permission, role or parent, the hint adds did you mean `x`?.
- Formatting.
strig::dsl::formatandis_formattedrewrite a source in the canonical layout of its syntax and keep the comments.strig-inspect fmt [--check] <file|dir>does the same for.strigfiles;--checklists the files that would change and exits with 1. - Files. With
dsl-fs,strig::dsl::fs::read_dirreads every*.strigfile of a directory into aProject, andwrite_filewrites a policy back.
In Node
The binding exposes the same language, native and WebAssembly, behind load(). A compiled policy is the canonical JSON, the same for the three syntaxes, with the comments in notes.
import from '@the-hades-organization/strig';
const strig = await ;
const source = `language blocks
target_kinds = [org]
permission org.read {
targets = [org]
}
`;
const policy = strig.; // canonical JSON
const rules = strig.; // 'blocks' | 'rules' | 'actors'
const actors = strig.; // text to text
const merged = strig.;
const fromDisk = strig.?.; // native module only
format(source)returns the source in the canonical layout of its syntax;isFormatted(source)says whether it already is.loadProjectDir(dir)exists only on the native module, since WebAssembly has no file access. It reads the*.strigfiles of the directory and refuses a policy file that is a symbolic link. Pass only adirfrom a trusted source.
Every failure is an Error whose code is the same on both targets:
code |
Cause |
|---|---|
DSL_PARSE |
The text does not parse. |
DSL_VALIDATE |
The policy parses but is invalid. |
DSL_CONFLICT |
Two sources declare the same thing; both positions are reported. |
DSL_UNREPRESENTABLE |
The target syntax cannot express the policy. |
DSL_UNSUPPORTED |
The syntax is not available in this build. |
DSL_LIMIT |
A size or count limit was exceeded. |
DSL_DUPLICATE_SOURCE |
The same path appears twice in loadProject. |
DSL_IO |
A file or a link in loadProjectDir. The message carries the path, so do not forward it to a remote client. |
error.diagnostics lists up to 100 { file, line, column, message, hint, related? } entries; when more were found, the last entry says "and N more". file, line and column are null for a policy that did not come from text. related ({ file, line, column }) appears on a DSL_CONFLICT.
try catch
Testing a policy
Tests sit beside the policy: *.strig-test.json files of check cases (subject, permission, resource, optional instant
and environment, expected allow or deny, optionally the reason and the deciding grant) and mutation cases (an actor
and a change, accepted or refused, optionally by which invariant). strig test runs them, and an error in the test itself
is never a pass:
- uses: The-Hades-Organization/Strig/.github/actions/strig-test@v0.9.0
with:
The same runner is strig::dsl::testing in Rust and strig.runTests(policy, tests) in JavaScript and strig.dsl.run_tests(policy, tests) in Python. The format, the
report and the exit codes are in the guide; examples/policy-tests/ has a project that
passes.
Macros
policy! and include_policy!, from the strig-macros crate, validate the policy at compile time: a policy that does not validate does not build. They live in their own crate rather than behind a strig feature; the guide explains why.
use ;
let inline: Policy = policy!;
let from_file: Policy = include_policy!;
Inspector (strig-inspect)
strig-inspect shows why a decision came out the way it did. It is built on Engine::explain, which Rust and JS can also call directly. From the example scenario:
DENIED — ben asks document.view on document:secret → project:roadmap → org:acme → global
reason: grant no-secret (document.view, step 0) chosen by strategy most_specific
permissions that grant: document.view, project.view
effective roles: member
override resource_owner: abstained
grants (5):
+ members-view allow project.view → role member on org [step 2]
candidate
- editors-edit allow project.edit → relation editor on project
permission not related
★ no-secret deny document.view → any subject on document:secret [step 0]
candidate
- pro-export allow document.export → role member on org
permission not related
- no-invoice-export deny document.invoice.export → role member on doc_type:invoice
permission not related
The crate is not on crates.io and is outside the workspace default-members. Install it from a clone:
|
A scenario is a JSON file with the policy (spec, an EngineSpec), the data (grants, tuples, env) and the named subjects and resources to examine. The example in crates/strig-inspect/examples/ comes with a forensic trail of six decisions, audit.jsonl, generated by:
The window has three tabs:
- Evaluation: pick a subject, permission and resource and see the decision, the reason, the resource path with the deciding step, the effective roles, each override, and why each grant did or did not apply, with its condition tree and the resolved values.
- Matrix: every catalog permission for every subject on one resource. Click a cell to open its trace.
- Audit: reads a JSON Lines trail, checks the hash chain of the
forensicrecords, shows the recorded trace and re-evaluatesdetailedandforensicdecisions against the current policy, flagging the ones that would change.
Simulation works across the tabs: turn grants off or on, or add some with --add, and see whether the set would allow the access. When a decision changes, the original decision is shown next to it, and changed matrix cells are marked.
Files reload when they change on disk. The window follows the system light or dark appearance, uses the playground's palette, and embeds its fonts (Noto Sans and JetBrains Mono, OFL) and icons, so it looks the same on any machine. The interface is in English.
In the browser
The playground also hosts the inspector: strig-playground.vercel.app/inspector.html. It has the same three tabs and the same simulation, over the engine compiled to WebAssembly, so there is nothing to install. It reads the same scenario JSON as strig-inspect, from a file, a paste or the built-in example (crates/strig-inspect/examples/scenario.json).
- Evaluation: the decision, the reason, the path, the effective roles, each override and why each grant did or did not apply, over
explain. - Matrix: every catalog permission for every subject on one resource. Click a cell to open its evaluation.
- Audit: load a JSON Lines trail, verify the
forensicchain withverifyAuditChainand re-evaluatedetailedandforensicdecisions against the current policy, flagging the ones that would change. - Simulation: turn grants off or add some from a form; a changed decision shows the original beside it, and changed matrix cells are marked.
The page uses the playground's identity, follows the light or dark scheme and works from 360 px wide. The scenario and the trail are read in the page and never leave the browser. To run it locally, see playground/README.md.
Extension points
| Trait | Implement it to |
|---|---|
GrantSource |
Read grants from a database, a cache, or several sources ((A, B) tuples chain). |
TupleStore |
Keep ReBAC tuples outside memory. |
Override |
Decide before the grants: owner, superadmin, suspended account, maintenance window. FnOverride takes a closure. |
Strategy |
Combine grants with another rule. |
Invariant |
Add a rule for grant changes. |
CatalogRule |
Validate the catalog your way (RequireMeta, FnRule). |
AuditSink |
Send the audit trail somewhere else. |
Transport |
Carry change notices between instances. |
CapabilityProvider, GrantLoader |
Control how a session computes the capabilities it sends. |
ChangeSink |
React synchronously to each change (cache, metric). |
Development
# transports against real servers (skipped without the variables)
STRIG_REDIS_URL=redis://127.0.0.1:6379/ STRIG_PG_URL=postgres://postgres:pw@127.0.0.1/postgres \
The npm package lives in crates/strig-node/js. crates/strig-node/scripts/build.sh builds the native module (js/native/strig.<platform>-<arch>.node, the local-build fallback of the loader) and the WebAssembly (js/wasm/); the release splits the native modules into per-platform packages with scripts/package-platforms.mjs; the wasm part needs the wasm32-unknown-unknown target and wasm-bindgen-cli 0.2.130.
Set STRIG_RUST_SERVER to the URL of the strig-axum server example to also test the JS client against the Rust server.
To run the playground locally, see playground/README.md.
Building the strig-inspect window on Linux needs the Wayland and X11 development libraries, for example libxkbcommon-dev, libwayland-dev, libxcb1-dev and libvulkan-dev.
Benchmarks: cargo bench -p strig --bench engine, and node bench/bench.mjs in crates/strig-node/js (or bun); see docs/benchmarks.md.
Fuzzing: ./fuzz/run.sh <target> [seconds] (nightly and cargo install cargo-fuzz) runs the targets in fuzz/ for the policy language, EngineSpec, conditions, decisions, the sync and server messages and the audit chain; see CONTRIBUTING.md.
Source comments are in Brazilian Portuguese. Issues and pull requests are welcome in English or Portuguese; see CONTRIBUTING.md.
License
MIT. The fonts embedded in strig-inspect are under the SIL Open Font License 1.1 (see crates/strig-inspect/assets/fonts).