# Introduction
URL: https://strig.vercel.app/docs
Strig answers one question: may this subject do this to this resource?
You write a policy. You ask questions. Each answer is a verdict and the grant that produced it. The examples on this page run against Strig 0.10.
Three questions, all about Bruno and `document.edit`:
| Question | Verdict | Why |
| --- | --- | --- |
| A document in Apollo's `plans` folder | allow | `g-edit` gives editors the permission on the project. |
| A document in Apollo's `legal` folder | deny | `g-seal` sits on the folder, a step closer to the document than the project, so it decides. |
| A document in Zephyr | deny | Bruno has no role in Zephyr, so no grant applies. |
Bruno can still read the `legal` folder: `g-view` allows `document.view`, and an editor inherits the viewer role.
> **Note**
>
> With no grant that applies, the answer is deny. A condition Strig cannot evaluate never opens access.
## How it thinks
Five things make up every decision.
**Subject.** Who is asking: an id, roles (optionally limited to a place), and attributes. Bruno holds `editor` in `project:apollo`, so the role does not reach Zephyr.
**Resource.** What is being touched, written as a path from the most specific step to the broadest: `document:spec → folder:legal → project:apollo → org:acme`. The path is how a grant on a project reaches a document inside it.
**Permission.** A dotted key from the catalog, such as `document.edit`. The catalog is validated when the policy loads. A permission that is not in it is denied, and `depends_on` means `document.edit` only holds where `document.view` does.
**Grant.** An `allow` or a `deny` for a subject, a permission and a target, optionally limited by scope, a condition or a validity window.
**Decision.** The engine collects the grants that apply along the resource path, then picks one. The default strategy, `most_specific`, lets the grant on the closest step decide, and a `deny` beats an `allow` on the same step. That is why `g-seal` overrides `g-edit` above. The other strategies (`deny_overrides`, `permit_overrides`, `first_applicable`) are one line in the policy.
The decision names the grant that settled it, so "why was this denied?" has an answer without reading code.
### One policy, three models
The same grants carry all three access-control models.
- **RBAC.** Roles inherit roles, as `editor` inherits `viewer` above.
- **ABAC.** A grant can carry a condition over `subject.*`, `resource.*` and `env.*`, for example `when subject.dept == "legal"`.
- **ReBAC.** A grant can apply to whoever holds a relation, such as `editor` on a document, read from tuples you store.
## Ask it
**Rust**
```rust
use strig::{Context, Reason, Request, Resource};
let policy = strig::dsl::parse("documents.strig", SOURCE)?.policy;
let engine = policy.engine_spec().builder()?.build()?;
let bruno = policy.subjects.iter().find(|s| s.id.as_deref() == Some("bruno")).expect("in the policy");
let ctx = Context::new(&policy.grants);
let legal = Resource::new("document", "spec")
.within("folder", "legal")
.within("project", "apollo")
.within("org", "acme");
let decision = engine.decide(&ctx, &Request::new(bruno, "document.edit", &legal));
assert!(!decision.is_allowed());
assert!(matches!(&decision.reason, Reason::Grant { grant_id, .. } if grant_id == "g-seal"));
```
**Node**
```js
import { load, scopeFromString } from '@the-hades-organization/strig';
const strig = await load();
const policy = strig.compile(SOURCE, { file: 'documents.strig' });
const { catalog, roles, strategy } = policy;
const engine = new strig.Engine({ catalog, roles, strategy });
const ctx = new strig.Context({ grants: policy.grants });
const bruno = policy.subjects.find((s) => s.id === 'bruno');
const resource = scopeFromString('document:spec/folder:legal/project:apollo/org:acme');
engine.check(ctx, { subject: bruno, permission: 'document.edit', resource }); // false
engine.explain(ctx, { subject: bruno, permission: 'document.edit', resource }).decision.reason.grantId; // 'g-seal'
```
`SOURCE` is the policy above. The same policy compiles to the same canonical JSON whether you write it as Rules, Blocks or Actors; see the [policy language](https://strig.vercel.app/docs/policy-language.md).
## Where it runs
The core does no IO, needs no async runtime and compiles to WebAssembly. Everything else is a separate crate or package you add only when you need it.
| You want | Use |
| --- | --- |
| Decisions inside a Rust service | `strig` |
| Decisions in Node or Bun, native or WebAssembly | `@the-hades-organization/strig` |
| Decisions in the browser, from the same engine | the WebAssembly build of the same package |
| Decisions from Python, Go or Java | [`strig-auth`](https://strig.vercel.app/docs/integrations/python.md), [the Go module](https://strig.vercel.app/docs/integrations/go.md), [the JVM artifact](https://strig.vercel.app/docs/integrations/jvm.md) |
| Decisions for services that do not embed the engine | `strig-server`, an HTTP server with a Rust client that denies when it gets no answer ([guide](https://strig.vercel.app/docs/integrations/server.md)) |
| Grants kept in Postgres or Redis | [`strig-postgres` and `strig-redis`](https://strig.vercel.app/docs/storage/postgres.md) |
| Permission changes pushed to clients as they happen | `strig-sync`, with Redis or Postgres between instances, and `strig-axum` for SSE and WebSocket |
| A policy checked while your crate compiles | `strig-macros`: `policy!` and `include_policy!` |
| A policy tested, diffed and linted in CI | `strig test`, `strig diff`, `strig lint` ([tools](https://strig.vercel.app/docs/tools/testing.md)) |
| The trace of a decision, grant simulation and the audit trail | the [inspector](https://strig.vercel.app/docs/tools/inspector.md), in a window or from the terminal |
On top of the decision, Strig covers how permissions change:
- **Field permissions.** A permission can name the fields it covers, and a grant narrows to some of them ([modeling](https://strig.vercel.app/docs/modeling/field-permissions.md)).
- **Governed changes.** Governance applies a change only if every invariant passes (no escalation, no lockout, your own rules), and reports who gains and who loses access before it applies ([impact](https://strig.vercel.app/docs/governance/impact.md)).
- **Approvals.** A change can wait for an approver, be time-boxed as an [elevation](https://strig.vercel.app/docs/governance/elevation.md), or be reviewed in a [recertification](https://strig.vercel.app/docs/governance/recertification.md) campaign. [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md) keeps incompatible permissions apart.
- **Audit.** With the `audit` feature, each change, applied or refused, becomes a hash-chained record, and if the record cannot be written the change is refused. A third party can [verify the trail](https://strig.vercel.app/docs/audit.md) without trusting you.
- **Consistency.** A decision can require the revision of a change you just made ([consistency](https://strig.vercel.app/docs/storage/consistency.md)).
## When to use it, and when not
Use Strig when permissions depend on where a resource sits (an organization, a project, a folder), when a deny should be a first-class answer, or when you need to explain a decision or audit a change after the fact.
Skip it when the check is a single flag on a user and will stay one. A column is simpler.
Two limits to know before you start:
- **Stable from 1.0, not yet released.** The current release is 0.10, where a minor version can still break the API. From 1.0, a breaking change to the Rust engine, the JSON spec, the policy language, the audit format or the npm package takes a new major version, with a deprecation window first. The Python, Go and Java and Kotlin packages, the Wasm ABI and the command-line tools are experimental: no semver guarantee until the versioning policy says otherwise. [Upgrading](https://strig.vercel.app/docs/upgrading.md) lists exactly what that covers.
- **The client does not guard anything.** `PermissionClient` decides locally for the interface. The server still decides on every operation.
## Where to next
- [Getting started](https://strig.vercel.app/docs/getting-started.md): Install the crate or the package and ask the first question.
- [Concepts](https://strig.vercel.app/docs/concepts.md): Permissions, roles, grants and how a verdict is reached.
- [Policy language](https://strig.vercel.app/docs/policy-language.md): One policy in three syntaxes, with the grammar.
- [Reference](https://strig.vercel.app/docs/reference.md): Every public name by crate and package, the HTTP API and the error codes.
- [Playground](https://github.com/The-Hades-Organization/Strig/tree/main/playground): Edit a policy and watch the engine answer, in the browser. There is no hosted copy yet; build it from the repository.
---
# Getting started
URL: https://strig.vercel.app/docs/getting-started
## Install
**Rust**
```text title="Terminal"
cargo add strig --features dsl,dsl-fs
cargo add serde_json
```
**Node**
```text title="Terminal"
npm install @the-hades-organization/strig
```
**Python**
```text title="Terminal"
pip install strig-auth
```
**Go**
```text title="Terminal"
go get github.com/The-Hades-Organization/Strig/bindings/go@v0.10.0
```
**Java**
```xml title="pom.xml"
io.github.the-hades-organization
strig
0.10.0
```
| Language | Needs |
| --- | --- |
| Rust | 1.88 or later |
| Node, Bun, browser | Node 18.17, Bun 1.1 or a current browser; one package, native module or WebAssembly |
| Python | 3.9 or later; one wheel per platform |
| Go | 1.22 or later; no cgo |
| Java, Kotlin | 17 or later; no native code |
All five run the same engine and read the same policy file. The examples on this page run against Strig 0.10 in Rust and Node; [Python](https://strig.vercel.app/docs/integrations/python.md), [Go](https://strig.vercel.app/docs/integrations/go.md) and [Java](https://strig.vercel.app/docs/integrations/jvm.md) have their own pages.
## Write the smallest useful policy
Save this as `policy.strig`. One file holds the catalog, the roles, who has them and the grants.
```rules title="policy.strig"
language rules
kinds project, document
broad org
permission document.view on project, document
permission document.edit on project, document depends_on document.view
role viewer
role editor inherits viewer
user:ana has role editor in project:apollo
g-view: allow role viewer to document.view on project in org:acme
g-edit: allow role editor to document.edit on project in org:acme
```
Ana edits in Apollo. An editor is also a viewer, and `document.edit` needs `document.view` on the same resource. Both grants sit on `project` inside `org:acme`.
## Ask the first question
Can Ana edit the document `spec`, in Apollo, in Acme? The program compiles the file, builds the engine, finds Ana and asks. The Node tab does the same in JavaScript.
**Rust**
```rust title="src/main.rs"
use strig::dsl::fs::read_file;
use strig::{Context, Request, Resource};
fn main() -> Result<(), Box> {
let permission = std::env::args().nth(1).expect("permission");
let policy = read_file("policy.strig")?.policy;
let engine = policy.engine_spec().build()?;
let context = Context::new(&policy.grants);
let ana = policy.subjects.iter().find(|s| s.id.as_deref() == Some("ana")).expect("ana");
let document = Resource::new("document", "spec").within("project", "apollo").within("org", "acme");
let decision = engine.decide(&context, &Request::new(ana, &permission, &document));
println!("{}", serde_json::to_string_pretty(&decision)?);
Ok(())
}
```
```text title="Terminal"
cargo run -- document.edit
```
```json title="Output"
{
"effect": "allow",
"reason": {
"kind": "grant",
"grant_id": "g-edit",
"permission": "document.edit",
"rank": 1,
"strategy": "most_specific"
},
"matched": [
"g-edit"
]
}
```
**Node**
```ts title="ask.mjs"
import { readFileSync } from 'node:fs';
import { load } from '@the-hades-organization/strig';
const { compile, Engine, Context } = await load();
const policy = compile(readFileSync('policy.strig', 'utf8'), { file: 'policy.strig' });
const { catalog, roles, strategy } = policy;
const engine = new Engine({ catalog, roles, strategy });
const context = new Context({ grants: policy.grants });
const subject = policy.subjects.find((s) => s.id === 'ana');
const resource = {
path: [
{ kind: 'document', id: 'spec' },
{ kind: 'project', id: 'apollo' },
{ kind: 'org', id: 'acme' },
],
};
const decision = engine.decide(context, { subject, permission: process.argv[2], resource });
console.log(JSON.stringify(decision, null, 2));
```
```text title="Terminal"
node ask.mjs document.edit
```
```json title="Output"
{
"effect": "allow",
"matched": [
"g-edit"
],
"reason": {
"grantId": "g-edit",
"kind": "grant",
"permission": "document.edit",
"rank": 1,
"strategy": "most_specific"
}
}
```
**allow**
## Read the answer
| Field | What it says |
| --- | --- |
| `effect` | The verdict: `allow` or `deny`. |
| `reason.kind` | Why: `grant` here. Other values appear below. |
| `reason.grant_id` | The grant that decided. Node spells it `grantId`. |
| `reason.strategy` | The rule that picked it: `most_specific`, the default. |
| `matched` | Every grant that applied to the question, in source order. |
`document.view` was not asked, but `document.edit` depends on it, and Ana holds it through `g-view`: she is an editor, and an editor is a viewer.
## Deny something
Add one line to `policy.strig`. It freezes editing for everyone in Acme.
```rules title="policy.strig"
g-freeze: deny anyone to document.edit on project in org:acme
```
Run the same question again.
**Rust**
```json title="Output"
{
"effect": "deny",
"reason": {
"kind": "grant",
"grant_id": "g-freeze",
"permission": "document.edit",
"rank": 1,
"strategy": "most_specific"
},
"matched": [
"g-edit",
"g-freeze"
]
}
```
**Node**
```json title="Output"
{
"effect": "deny",
"matched": [
"g-edit",
"g-freeze"
],
"reason": {
"grantId": "g-freeze",
"kind": "grant",
"permission": "document.edit",
"rank": 1,
"strategy": "most_specific"
}
}
```
**deny**
Both grants applied, on the same step of the path. With `most_specific`, a `deny` wins there. Viewing is untouched: `cargo run -- document.view` still answers `allow`, by `g-view`.
## See it fail closed
Ask for a permission the catalog does not declare. Remove `g-freeze` first, so the question stands on its own.
```text title="Terminal"
cargo run -- document.delete
```
```json title="Output"
{
"effect": "deny",
"reason": {
"kind": "unknown_permission"
}
}
```
Now make `g-edit` depend on something the engine cannot see. Replace its line with this one, and ask for `document.edit` again. Ana has no `mfa` attribute.
```rules title="policy.strig"
g-edit: allow role editor to document.edit on project in org:acme when subject.mfa == true
```
```json title="Output"
{
"effect": "deny",
"reason": {
"kind": "no_applicable_grant"
},
"warnings": [
"grant g-edit: atributo ausente: subject.mfa"
]
}
```
A condition the engine cannot evaluate never opens access. The `allow` is dropped, nothing else applies, and the answer is `deny` with the cause in `warnings`.
> **Note**
>
> The text of a warning is in Portuguese. Branch on `reason.kind`, not on the warning text.
Rust and Node print the same for these two.
## Next steps
- [Concepts](https://strig.vercel.app/docs/concepts.md): Catalog, grants, scope and the strategies that combine them.
- [Policy language](https://strig.vercel.app/docs/policy-language.md): The same policy in Blocks, Rules and Actors.
- [A multi-tenant SaaS](https://strig.vercel.app/docs/guides/saas-multi-tenant.md): A complete policy, from the catalog to the checks in a service.
---
# For AI agents
URL: https://strig.vercel.app/docs/for-ai-agents
This page describes Strig in the terms a coding assistant needs to write correct code against it. Every docs page is also available as markdown, and the repository has an [AGENTS.md](https://github.com/The-Hades-Organization/Strig/blob/main/AGENTS.md) with the same guide plus the commands to build and test the repository.
## Machine-readable docs
- [`/llms.txt`](/llms.txt): the index of the pages, one section per group.
- [`/llms-full.txt`](/llms-full.txt): the text of every page in one file.
- `/docs/.md`: the markdown of one page, for example `/docs/concepts.md`. A request to `/docs/` with `Accept: text/markdown` gets the same text.
- [API reference on docs.rs](https://docs.rs/strig) for the Rust crate.
## What it is
Strig is an authorization library with one decision engine for RBAC, ABAC and ReBAC, for Rust, Node, Bun, the browser, Python, Go and the JVM. You declare a catalog of permissions, hand the engine grants, and ask whether a subject may do something to a resource. The answer comes with the reason, and the engine can say what would turn a denial into an allow. Changes to grants can go through governance rules, be audited with a hash chain and be pushed in real time to other instances and the browser.
Use it when the question is "who can do what to which resource", the rules mix roles, attributes and relations, and you want decisions you can explain and audit.
It does not authenticate anyone. It takes the subject you give it as already established, and it is not an identity provider, a session store or a login flow. The optional decision server does not authenticate its callers either, so put it behind your own authentication.
## Install
| Language | Command | Stability |
| --- | --- | --- |
| Rust | `cargo add strig` (`--features dsl` for the policy language) | stable core |
| Node, Bun, browser | `npm install @the-hades-organization/strig` | stable |
| Python | `pip install strig-auth` (`import strig`) | experimental |
| Go | `go get github.com/The-Hades-Organization/Strig/bindings/go@latest` | experimental |
| Java, Kotlin | `io.github.the-hades-organization:strig` | experimental |
[Getting started](https://strig.vercel.app/docs/getting-started.md) has the install snippets with versions, and [Upgrading](https://strig.vercel.app/docs/upgrading.md) says what changed between them.
## The model in one paragraph
A catalog lists dotted permission keys (`project.edit`) and the kinds of target each accepts. A resource is a path of steps from the most specific to the broadest (`project:p1/org:acme`). A subject has an id, roles (optionally scoped to a step), principals and attributes. A grant says who (a user, a role, a principal, a relation or anyone), which permission, on which target, allow or deny, with an optional scope and condition. The engine collects the grants that apply to the request and a strategy picks the deciding one. The default strategy lets the grant closest to the resource decide, and a deny wins on the same step. With no applicable grant the answer is deny. A condition or relation that cannot be evaluated never opens access. See [Concepts](https://strig.vercel.app/docs/concepts.md).
## A minimal example
One catalog, one role grant, and the questions: may she, why, what would allow it, who can. Each example is a file that the repository's CI runs.
**Rust**
```rust
use strig::*;
let catalog = Catalog::builder()
.target_kinds(["project"])
.broad_target("org")
.permission(PermissionDef::new("project.view").targets(["project"]))
.permission(PermissionDef::new("project.edit").targets(["project"]))
.build()?;
let engine = Engine::builder(catalog).build()?;
let grants = vec![Grant::allow("g1", SubjectMatcher::role("member"), "project.view", TargetSelector::kind("project"))];
let ana = Subject::user("ana").with_role("member");
let project = Resource::new("project", "p1").within("org", "acme");
let ctx = Context::new(&grants);
let view = engine.decide(&ctx, &Request::new(&ana, "project.view", &project)); // Effect::Allow
let edit = engine.decide(&ctx, &Request::new(&ana, "project.edit", &project)); // Effect::Deny
let remedies = engine.why_not(&ctx, &Request::new(&ana, "project.edit", &project), &WhyNotOptions::default());
let who = engine.who_can(&QueryContext::new(&grants), "project.view");
```
**Node**
```js
import { load, scopeFromString } from '@the-hades-organization/strig';
const { Engine, Context } = await load(); // native on Node and Bun, wasm in the browser
const engine = new Engine({
catalog: {
targetKinds: ['project'],
broadTargets: ['org'],
permissions: [
{ key: 'project.view', targets: ['project'] },
{ key: 'project.edit', targets: ['project'] },
],
},
});
const ctx = new Context({
grants: [{ id: 'g1', subject: { kind: 'role', id: 'member' }, permission: 'project.view', target: { kind: 'project' }, effect: 'allow' }],
});
const ana = { kind: 'user', id: 'ana', roles: [{ role: 'member' }] };
const ask = (permission) => ({ subject: ana, permission, resource: scopeFromString('project:p1/org:acme') });
engine.check(ctx, ask('project.view')); // true
engine.check(ctx, ask('project.edit')); // false
engine.whyNot(ctx, ask('project.edit')); // { remedies: [...] }; null when already allowed
engine.whoCan(ctx, 'project.view'); // [{ type: 'role', id: 'member' }]
```
**Python**
```python
import strig
engine = strig.Engine({"catalog": {
"targetKinds": ["project"], "broadTargets": ["org"],
"permissions": [{"key": "project.view", "targets": ["project"]},
{"key": "project.edit", "targets": ["project"]}]}})
ctx = strig.Context([{"id": "g1", "subject": {"kind": "role", "id": "member"},
"permission": "project.view", "target": {"kind": "project"}, "effect": "allow"}])
ana = {"kind": "user", "id": "ana", "roles": [{"role": "member"}]}
def ask(permission):
return {"subject": ana, "permission": permission, "resource": strig.scope_from_string("project:p1/org:acme")}
engine.check(ctx, ask("project.view")) # True
engine.check(ctx, ask("project.edit")) # False
engine.why_not(ctx, ask("project.edit")) # {"remedies": [...]}; None when already allowed
engine.who_can(ctx, "project.view") # [{"type": "role", "id": "member"}]
```
**Go**
```go
engine, _ := strig.NewEngine(spec) // spec: the same catalog JSON as in the Node tab
defer engine.Close()
ctx, _ := engine.NewContext(map[string]any{"grants": grants})
request := map[string]any{
"subject": map[string]any{"kind": "user", "id": "ana", "roles": []map[string]any{{"role": "member"}}},
"permission": "project.view",
"resource": map[string]any{"path": []map[string]any{{"kind": "project", "id": "p1"}, {"kind": "org", "id": "acme"}}},
}
allowed, err := engine.Check(ctx, request) // an error is never an allow
parties, _ := engine.WhoCan(ctx, "project.view")
```
**Java**
```java
try (Engine engine = new Engine(spec); Context ctx = engine.newContext(Map.of("grants", List.of(grant)))) {
boolean allowed = engine.check(ctx, request); // an exception is never an allow
List> parties = engine.whoCan(ctx, "project.view");
}
```
`explain` and `why_not` exist in Rust, JavaScript and Python. Go and Java have `Explain` and `explain`, and no `why_not` yet.
## Questions the engine answers
| Question | Rust | JavaScript | Python |
| --- | --- | --- | --- |
| May this subject do this to this resource? | `decide`, `check_for` | `check`, `decide` | `check`, `decide` |
| Why did it come out that way? | `explain` | `explain` | `explain` |
| What would turn a denial into an allow? | `why_not` | `whyNot` | `why_not` |
| Which resources of a kind can the subject reach? | `list` | `list` | `list` |
| Who holds this permission? | `who_can`, `who_can_on`, `access_of` | `whoCan`, `whoCanOn`, `accessOf` | `who_can`, `who_can_on`, `access_of` |
[Why not](https://strig.vercel.app/docs/governance/why-not.md) covers the remedies, and [Concepts](https://strig.vercel.app/docs/concepts.md) the rest of the model.
## Common mistakes
- Treating a denial as an error. Deny is the default answer; read the reason or `explain` to see which grant, override or missing grant decided.
- Treating the library as authentication. The subject you pass is trusted as given.
- Checking only in the interface. `PermissionClient` in the browser decides from capabilities the server sent, to shape the interface; the server still decides on every operation.
- Forgetting the time. A grant with a validity window fails closed when the engine has no instant: pass `now` (milliseconds, UTC) or set it on the context.
- Wrong names in the JSON spec. Spec, grants, subjects and results use camelCase fields in every language (`targetKinds`, `validFrom`, `grantId`).
- Expecting callbacks outside Rust, JavaScript and Python. Custom conditions, overrides and invariants written in Go or Java are not supported yet, and a spec that needs one fails closed.
- Matching on error messages. Every binding reports the same `errorCode` (`INVALID_INPUT`, `UNKNOWN_SUBJECT`, and so on); match on the code.
- Changing grants by hand when rules apply. Use `Governance` in Rust or `engine.apply` in the other languages: it applies the change only if every invariant passes and audits the outcome.
## Where to read more
- [Getting started](https://strig.vercel.app/docs/getting-started.md), [Concepts](https://strig.vercel.app/docs/concepts.md) and [JavaScript](https://strig.vercel.app/docs/javascript.md).
- [Reference](https://strig.vercel.app/docs/reference.md) for the Rust API, and [docs.rs](https://docs.rs/strig).
- [Security](https://strig.vercel.app/docs/security.md) for reporting a vulnerability.
---
# Concepts
URL: https://strig.vercel.app/docs/concepts
A Strig decision answers one question: may this subject do this permission to this resource? This page takes the question apart, so you can write your first policy. Every answer on it is real output from the engine. Pick a command, and the bench shows the case.
## The question
A request has three parts.
- **Subject.** Who asks: an id, roles (each one optionally limited to a place), principals and attributes. You build it from what you know about the caller. Strig does not look anyone up.
- **Permission.** A dotted key from the catalog, such as `document.view`.
- **Resource.** What is touched, written as a path of steps from the most specific to the broadest: `document:spec`, `project:apollo`, `org:acme`. A `global` step ends every path without being written.
The answer is a `Decision`: `effect` (`allow` or `deny`), `reason`, `matched` (every grant that applied) and `warnings`. When nothing applies, the answer is `deny`.
Ana has a grant for `document.view`. Bob has none.
The same program asks every question on this page. It reads the policy file, finds the subject and builds the resource path from its arguments.
## Permissions
A permission is a dotted key that the catalog declares. The line that declares it also says where a grant of it can sit: `permission document.view on project, document`. A permission the catalog does not declare is denied, with the reason `unknown_permission`.
`implied by` lets a broader permission carry a narrower one. `document.invoice.export` is implied by `document.export`, so a grant of `document.export` holds for it. Ana has that grant and asks for the narrower permission:
`reason.permission` names the permission the grant was written for, not the one asked. The implication does not run the other way:
## Targets and broad targets
A grant has a target: the step of the path it sits on. `on project` matches whichever project is on the path, and `on document:spec` matches that one document. The position of the matching step is the rank, counted from the resource itself.
```text title="Path and rank"
document:spec project:apollo org:acme global
rank 0 rank 1 rank 2 rank 3
```
`kinds` lists the kinds of step a grant can sit on. `broad org` adds a kind that any permission accepts, such as an organization or a tenant. `global` is always broad. A grant on any other kind is refused when the file loads.
`in org:acme` is the scope, not the target. It says the resource path must pass through `org:acme` for the grant to apply.
`g-view` sits on `org`, a broad target, so it reaches `document.view` even though that permission lists only `document`. Dan asks about a document in Acme, then in another organization:
## Roles
A role is a name that grants can address. `role editor inherits viewer` gives editors whatever viewers hold. A subject holds a role everywhere or only inside a scope: `user:ana has role editor in project:apollo` holds for resources whose path goes through `project:apollo`.
A grant names who it is for with one of five matchers: `anyone`, `role `, `user `, `principal ` and `relation `. A relation grant applies to whoever holds that relation on the step the target matched, read from stored tuples. This page does not follow relations further.
Ana is an editor in Apollo. The same question, asked about Apollo and about Zephyr:
In Apollo the answer is `allow` only because `editor` inherits `viewer`: `document.edit` needs `document.view`, and `g-view` is written for `viewer`. In Zephyr, Ana holds no role, so no grant applies.
The Actors syntax writes the same policy grouped by who acts. The three syntaxes, Blocks, Rules and Actors, describe one policy, and the [policy language](https://strig.vercel.app/docs/policy-language.md) shows them side by side.
## Conditions
A grant can end with `when`, followed by a condition over `subject.*`, `resource.*` and `env.*` attributes. The grant applies only when the condition holds. Conditions compare values, test membership, combine with `and`, `or` and `not`, and can test text, lists, addresses and the time of day. The [policy language](https://strig.vercel.app/docs/policy-language.md) lists them.
| User | `subject.dept` | Verdict | `reason.kind` |
| --- | --- | --- | --- |
| `ana` | `"legal"` | allow | `grant`, by `g-legal` |
| `bob` | `"sales"` | deny | `no_applicable_grant` |
| `eve` | none | deny | `no_applicable_grant`, with a warning |
Bob's condition is false, so `g-legal` does not apply. Eve has no `dept` at all, and the engine cannot tell:
A condition that cannot be evaluated never opens access. An `allow` that depends on it does not apply, a `deny` that depends on it still does, and the cause goes to `warnings`.
## Time zones
*Added in 0.7.0.*
Office hours are local. `time_between` and `weekday_in` read UTC unless you give them an IANA zone with `tz`. The same condition, in the three syntaxes and in JSON:
```text title="Rules"
g-hours: allow role editor to document.edit on document when time_between "09:00" "18:00" tz "America/Sao_Paulo"
g-monday: allow role editor to document.view on document when weekday_in ["mon"] tz "Europe/Lisbon"
```
```json title="JSON"
{ "op": "time_between", "from": "09:00", "until": "18:00", "tz": "America/Sao_Paulo" }
```
- **The instant decides the local time.** Daylight saving time follows the zone's rules. 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.
- **Midnight and the date are local.** A window that crosses midnight (`"22:00"` to `"06:00"`) and the weekday both follow the local date.
- **An unknown name is refused when the policy loads**, with position and hint. A condition built without validation fails when evaluated, and an `allow` that errors never applies.
- **The trace shows the local time it used**, for example `12:30 America/Sao_Paulo (UTC-03:00)`.
- **Without `tz` nothing changes.** A policy that uses `tz` exports its JSON with `"schema": 3`, so a reader of schema 2 refuses it. See [Upgrading](https://strig.vercel.app/docs/upgrading.md).
The zone database is the default feature `tz` of the `strig` crate. It adds about 0.9 MB to the `.wasm` (2.70 MB to 3.58 MB, 657 KB to 785 KB gzipped). Build with `default-features = false, features = ["audit"]` to leave it out; a `tz` in a policy is then refused at load.
## Prerequisites
`depends_on` makes one permission require others: holding it means holding each listed permission on the same resource. `implied by` widens what a grant reaches. `depends_on` narrows what a grant is worth.
`document.edit` depends on `document.view`. Bob has a grant for `document.edit` and none for `document.view`:
`g-edit-bob` applied, and it is not enough. Ana holds both:
The catalog refuses a prerequisite that cannot be granted wherever the permission that needs it can, and it refuses a cycle.
## Fields
A grant can cover some fields of the resource. The catalog declares the fields a permission can be narrowed to, and a grant lists the ones it covers:
```text title="Rules"
permission document.edit on document fields title, body, status
g-edit: allow role editor to document.edit on document
g-freeze: deny role editor to document.edit on document fields status
```
Ana is an editor. Asked about `document.edit` on `title`, the answer is `allow`; on `status`, `deny`, by `g-freeze`. Asked about the whole document, the answer is `deny`, because editing the whole resource needs every field. `g-edit` has no `fields`, so it covers all of them, exactly as before. A grant that names a field the permission does not declare is refused when the policy loads, with the declared fields as the hint.
[Field permissions](https://strig.vercel.app/docs/modeling/field-permissions.md) covers how fields combine with `implied_by`, `depends_on` and the strategies.
## Which grant decides
Several grants can apply to one question. The strategy picks the one that decides. The default, `most_specific`, lets the grant on the closest step decide, and a `deny` beats an `allow` on the same step. An `allow` for one document and a `deny` for the whole project:
`g-edit` is on `document:spec`, at rank 0, so it beats the freeze for that one document. For `document:notes` only `g-freeze` applies.
Add `strategy deny_overrides` after `broad org` and ask about `document:spec` again.
The same two grants matched, and the verdict flipped. The strategy is one line of the policy:
| Strategy | The deciding grant |
| --- | --- |
| `most_specific` | On the closest step that has any grant; a `deny` first on that step. The default. |
| `deny_overrides` | A `deny` at any step. |
| `permit_overrides` | An `allow` at any step. |
| `first_applicable` | The first applicable grant in source order. |
## Reading the answer
The engine reaches a verdict in four steps:
1. An unknown permission is denied.
2. Overrides run in order, and the first one that answers decides.
3. A grant is a candidate when all of these hold:
- its permission is the one asked, or one that implies it;
- the resource path passes through its scope;
- its target matches a step of the path;
- its subject matches and its condition is true.
4. The strategy picks the deciding grant. With no candidate, the answer is `deny`. Then `depends_on` is checked, and a missing prerequisite turns an `allow` into a `deny`.
`reason.kind` says which step decided:
| `reason.kind` | It means |
| --- | --- |
| `grant` | A grant decided: `grant_id` (`grantId` in Node), its `permission`, its `rank` and the `strategy` that picked it. |
| `no_applicable_grant` | Nothing applied. The answer is `deny`. |
| `unknown_permission` | The permission is not in the catalog. The answer is `deny`. |
| `missing_prerequisite` | The permission would be allowed, but one it `depends_on` is not. |
| `override` | An override answered before the grants, with its `name`. |
`matched` lists every grant that applied, in source order, not only the one that decided.
## Separation of duties
Some permissions must not meet in one person. The catalog declares which, and governance refuses the change that would put them together:
```text title="Rules"
mutually-exclusive payment_duties of roles members [maker, checker] anchor org
conflicting-actions four_eyes first [payment.create] then [payment.approve] history trail distinct_roles true
always separation-of-duties
```
- `payment_duties`: nobody holds `maker` and `checker` in the same org, whether directly, by inheritance, by a grant or by an elevation.
- `four_eyes`: whoever did `payment.create` on a resource cannot do `payment.approve` on it. The engine reads the history from the `trail` attribute of the resource, a list such as `["payment.create:ana"]`, in every decision. A history it cannot read denies.
- `always separation-of-duties`: an invariant, so governance refuses a grant that would create a clash.
A policy that declares them exports `"schema": 5`. See [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md).
## Reading your own writes
Every accepted change gets a revision for its data scope, a text like `tenant@42`. A decision can name the revision it must not be older than:
```js
await saveGrant(grant); // returns the revision, 'tenant@42'
client.requireRevision('tenant@42'); // until the grants reach it, every check denies
```
A reader behind the revision denies instead of answering from older grants. [Consistency](https://strig.vercel.app/docs/storage/consistency.md) covers the stores, the server header `x-strig-min-revision` and the `revision_not_reached` error.
## What Strig leaves to you
- **Who the subject is.** Strig reads the subject you pass and decides for it. In a browser, `PermissionClient` decides locally to shape the interface, and the server still decides on every operation.
- **Where grants live.** The engine holds configuration, and the grants arrive with each call. Governance returns the new grant set when a change passes its invariants, and you persist it. Removing expired grants from storage is a job of yours.
- **The clock.** You supply the instant of the decision. Without it, a grant with a validity window or a time condition never allows.
- **Anything it has no condition for.** There is no regular-expression condition. Custom condition functions and overrides are code, not policy text: you register them in Rust, JavaScript or Python, and an exception in one denies.
- **IO.** The core does no IO and needs no async runtime. Real time, transports and the HTTP server are separate crates.
Three more parts of the model act on the same grants.
| Part | What it does |
| --- | --- |
| Overrides | Decide before the grants: an owner, a suspended account, a maintenance window. |
| Governance | A change to the grants is applied only if every invariant passes: no escalation, no lockout, your own rules. [Impact](https://strig.vercel.app/docs/governance/impact.md) says who gains and who loses access first. |
| Approvals | A change can wait for an approver, or hold for a limited time as an [elevation](https://strig.vercel.app/docs/governance/elevation.md). |
| Audit | With the `audit` feature, each change, applied or refused, becomes a record. [Verify it](https://strig.vercel.app/docs/audit.md) without trusting the writer. |
## Next steps
- [Policy language](https://strig.vercel.app/docs/policy-language.md): The same policy in Blocks, Rules and Actors.
- [Reference](https://strig.vercel.app/docs/reference.md): Types, fields and every reason the engine can give.
---
# Policy language
URL: https://strig.vercel.app/docs/policy-language
A Strig policy is data: a catalog of permissions, roles, assignments, grants and rules. You can build it in Rust, load it from JSON, or write it as text. The text form is the policy language. The examples on these pages run against Strig 1.0.
The language has three syntaxes. They describe the same thing and differ only in layout:
- **Blocks** gives every declaration a block with `key = value` fields. It is explicit and regular.
- **Rules** writes each fact as one line, meant to be read aloud.
- **Actors** groups the policy under whoever acts: a role, a user, a principal.
The panel beside this text shows one complete policy in each syntax. All three parse to equal policies.
## One model underneath
Parsing a source produces a `Policy`, the value you would otherwise build in code. Two sources in different syntaxes that mean the same thing give the same policy and the same JSON. `Policy::equivalent` compares two policies, and `convert` rewrites a source from one syntax into another.
The text is checked while it is parsed, with the same checks as `Policy::validate`. Treat the text as the way people edit the policy and the JSON as the artifact that services load.
```rust
use strig::dsl::{Language, convert, parse};
let blocks = std::fs::read_to_string("documents.strig")?;
let rules = convert(&blocks, Language::Rules)?;
let a = parse("documents.strig", &blocks)?.policy;
let b = parse("documents.rules", &rules)?.policy;
assert!(a.equivalent(&b));
```
The language needs the `dsl` feature of the `strig` crate. Reading and writing files needs `dsl-fs` as well.
```text title="Cargo.toml"
strig = { version = "0.10", features = ["dsl", "dsl-fs"] }
```
## Choose a syntax
| If you | Use |
| --- | --- |
| generate the file, or keep a large policy | Blocks |
| write a short policy, or review changes line by line | Rules |
| ask "what can an editor do?" more often than "who can edit?" | Actors |
The choice is per file, so it is cheap to change. `convert` moves a policy to another syntax and keeps its comments beside the same elements.
- [Blocks](https://strig.vercel.app/docs/policy-language/blocks.md): Declarations, fields, and the grammar of each.
- [Rules](https://strig.vercel.app/docs/policy-language/rules.md): Statements, one per line.
- [Actors](https://strig.vercel.app/docs/policy-language/actors.md): Headings for who acts, and what is indented under them.
## The same construct in each syntax
| Construct | Blocks | Rules | Actors |
| --- | --- | --- | --- |
| Kinds of resource | `target_kinds = [doc]` | `kinds doc` | `kinds doc` |
| Broadest kind | `broad_targets = [org]` | `broad org` | `broad org` |
| Strategy | `strategy = deny_overrides` | `strategy deny_overrides` | `strategy deny_overrides` |
| Depth limit | `max_depth = 4` | `depth 4` | `depth 4` |
| Permission | `permission doc.read { }` | `permission doc.read on doc` | `doc.read on doc` |
| Role inheritance | `inherits = [viewer]` | `role editor inherits viewer` | `role editor inherits viewer` |
| Role assignment | `assign editor { }` | `user:ana has role editor` | `role editor` |
| Grant | `grant g-edit { }` | `g-edit: allow ...` | `allow ... as g-edit` |
| Invariant | `invariant no_lockout { }` | `always no-lockout` | `no-lockout` |
The cells show the shape of each construct and elide the rest, which the page of each syntax gives in full. In Actors, a line sits under a heading: kinds, broad kinds and permissions under `catalog`, strategy and depth under `engine`, a role assignment under `subject user:ana`, a grant under who it applies to, and an invariant under `governance`.
Four constructs came after the first release, and each exists in all three syntaxes:
| Construct | Blocks | Rules | Actors |
| --- | --- | --- | --- |
| Fields of a permission or a grant | `fields = [title, body]` | `... on document fields title, body` | `... on document fields title, body as g-edit` |
| Exclusive set | `mutually_exclusive payment_duties { of = roles members = [maker, checker] }` | `mutually-exclusive payment_duties of roles members [maker, checker]` | the same line, under `catalog` |
| Conflicting actions | `conflicting_actions four_eyes { first = [payment.create] then = [payment.approve] }` | `conflicting-actions four_eyes first [payment.create] then [payment.approve]` | the same line, under `catalog` |
| Separation invariant | `invariant separation_of_duties { }` | `always separation-of-duties` | `separation-of-duties`, under `governance` |
[Field permissions](https://strig.vercel.app/docs/modeling/field-permissions.md) and [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md) explain what they decide.
Names change with the syntax in two places. A flag written `non_delegable` in Blocks is `non-delegable` in Rules and Actors, and the same goes for `management_only` and `override_only`. An invariant such as `no_lockout` is `no-lockout` outside Blocks.
## What the three share
### The language line
The first line of a source that is not blank or a comment names its syntax:
```text
language blocks
language rules
language actors
```
A source without it stops at line 1. An unknown name lists the valid ones.
```text title="Error"
a.strig:1:1: a source starts by declaring its language
hint: write on the first line: language blocks
```
```text title="Error"
b.strig:1:10: unknown language `prose`
hint: expected one of: blocks, rules, actors
```
A file has one `language` line and keeps that syntax to its end. A second `language` line is an error, even when it names the same syntax.
```text title="Error"
c.strig:7:1: a source declares its language once, on its first line (also at c.strig:1:1)
hint: one file holds one syntax: split the other into its own file
```
### Comments, names and references
- A comment starts with `//` and runs to the end of the line. Comments are kept as notes beside the element they sit next to, and `convert` writes them back in the new syntax.
- Permissions (`doc.read`), roles and kinds are bare words. Strings use double quotes.
- A resource or subject reference is `kind:id`, such as `project:apollo` or `user:ana`.
- Where a field takes a resource, it can be a path of steps joined by `>`, such as `org:acme > doc`. Each step is `kind` or `kind:id`.
- Dates are UTC: `2026-01-01` or `2026-01-01T09:00:00Z`, with optional milliseconds.
- Declaration order does not matter. A role can inherit one that is declared further down.
### Subject matchers
A grant says who it applies to with one of these:
| Matcher | Applies to |
| --- | --- |
| `anyone` | every subject |
| `role ` | subjects that hold the role |
| `user ` | one user |
| `principal ` | one principal |
| `relation ` | subjects that hold the relation |
### Conditions
A grant can carry a condition, written after `when`. The three syntaxes write conditions the same way.
| Form | Meaning |
| --- | --- |
| `==`, `!=`, `<`, `<=`, `>`, `>=`, `in` | comparison |
| `and` or `&&`, `or` or `\|\|`, `not` or `!` | combination, with parentheses to group |
| `exists ` | the attribute is present |
| `all(...)`, `any(...)` | quantifiers |
| `@function(arguments)` | a function |
| `a starts_with b`, `a ends_with b` | the text `a` begins or ends with `b` |
| `a contains b` | `a` has `b` as a substring, or as an element of the list |
| `a any_in b`, `a all_in b` | some or every element of list `a` is in list `b` |
| `a ip_in b` | the address `a` is inside the CIDR `b`, or one CIDR of the list `b` |
| `time_between "09:00" "17:30"` | the UTC time of day is in the window |
| `time_between "09:00" "18:00" tz "America/Sao_Paulo"` | the time of day on the wall clock of that IANA zone is in the window |
| `weekday_in ["mon", "tue"]` | the UTC weekday is one of the days |
| `weekday_in ["mon"] tz "Europe/Lisbon"` | the weekday in that zone is one of the days |
Attributes start with `subject.`, `resource.` or `env.`, as in `subject.dept == "legal"`.
- A window with a start after its end crosses midnight, and equal bounds make an empty window.
- Days are `mon`, `tue`, `wed`, `thu`, `fri`, `sat`, `sun`, written as strings.
- An address without a prefix length stands for one host.
- There is no regular-expression condition.
- The validator refuses a CIDR, a time of day or a weekday it cannot read, with the position and a hint.
- A condition the engine cannot evaluate never opens access. With a wrong operand type or an unreadable operand, an `allow` does not apply and a `deny` does.
- The time conditions read the decision instant, in UTC unless `tz` names a zone. Without an instant they cannot be resolved, so a grant that uses them never allows.
- `tz` takes an IANA name in quotes after the other arguments, in all three syntaxes. An unknown name is a validation error with a position and a hint. See [Time zones](https://strig.vercel.app/docs/concepts.md#time-zones).
- A policy that uses `tz` exports its JSON with `"schema": 3`, so a reader on schema 2 refuses it instead of reading the window in UTC. A policy without `tz` exports what it did before. The [schema numbers](#the-schema-number) below list the others.
```text title="Error"
g.strig:6:60: `9:00` is not a time of day
hint: write hours and minutes with two digits each, 00:00 to 23:59, like "09:30"
```
### Relation rewrites
A relation is defined in terms of others with a rewrite:
| Form | Meaning |
| --- | --- |
| `this` | the tuples stored for the relation |
| `a \| b` | union |
| `a & b` | intersection |
| `a - b` | difference |
| `parent->relation` | a walk to the parent, then a relation |
| `union(...)`, `intersection(...)`, `exclusion(a, b)` | the function forms |
Do not mix `|`, `&` and `-` without parentheses.
## The schema number
The canonical JSON of a policy carries a `schema` only when the policy needs a newer reader than the first. A reader refuses a schema above the one it knows, so an older reader never reads a restricted grant as an open one.
| Schema | A policy gets it when it uses |
| --- | --- |
| none or 1 | nothing below |
| 2 | the text, set, network and time conditions |
| 3 | `tz` in a time condition |
| 4 | `fields` in a grant or a permission |
| 5 | `mutually_exclusive` or `conflicting_actions` |
The current DSL schema is 5. What changes at a major version is in [Upgrading](https://strig.vercel.app/docs/upgrading.md).
## Several files, and checks on the way
A policy can span several files and several syntaxes. Add each source to a `Project` and build it. `add_source` returns the syntax it detected, and `build` merges the sources into one policy.
```rust
use strig::dsl::Project;
let mut project = Project::new();
project.add_source("catalog.strig", "language rules\n\nkinds doc\npermission doc.read on doc\n")?;
project.add_source("people.strig", "language blocks\n\ntarget_kinds = [org]\nrole viewer {\n}\n")?;
let built = project.build()?;
let policy = built.policy;
```
The merge refuses a declaration that appears twice and shows both places:
```text title="Error"
two.strig:3:1: the kind `doc` is listed in target_kinds twice (also at one.strig:3:1)
hint: list each kind in one source only
```
`strig-inspect fmt ` rewrites `.strig` files in the canonical layout of their syntax, and `fmt --check` lists the files that would change and exits with 1. In Rust, `format` and `is_formatted` do the same on text, and in Node, `strig.format` and `strig.isFormatted`. Two other crates read the language: `strig-macros` checks a policy while your program compiles, with `policy!` and `include_policy!`, and the [playground](https://github.com/The-Hades-Organization/Strig/tree/main/playground) edits it in all three syntaxes. `strig test`, `strig diff` and `strig lint` check a policy in CI: see [Tools](https://strig.vercel.app/docs/tools/testing.md).
### Errors
Every error carries `file:line:column`, a message and, when there is a likely fix, a hint. When a name is close to a declared one, the hint says which. The parser keeps going after the first error and reports up to 100, then "and N more". An error that involves two places names the second one with "also at". Messages and hints are in English. Each syntax page shows the errors that typical mistakes produce.
### Limits
Parsing is bounded, so untrusted text cannot exhaust memory or the stack.
| Limit | Value |
| --- | --- |
| Size of one source | 4 MiB |
| Sources in a project | 10000 |
| Total size of a project | 64 MiB |
| Policy files in a directory | 1024 |
| Nesting of conditions and groups | 64 |
| Errors reported | 100 |
A source over the size limit is refused at its first position, before any parsing.
---
# Blocks
URL: https://strig.vercel.app/docs/policy-language/blocks
Blocks gives each declaration a block of its own. It is the most explicit of the three syntaxes and the most regular, so it suits files that a program generates and policies that grow large. What the three syntaxes share (the `language` line, references, conditions, rewrites) is on [the section page](https://strig.vercel.app/docs/policy-language.md).
## Shape of a source
A source is the `language blocks` line, then the settings, then the declarations.
- A setting is `name = value`, at the top level.
- A field inside a block is also `name = value`. A list is `[a, b]`, a string uses double quotes, and a flag is `true`.
- A block opens with `{` on its header line and closes with `}` at the start of a line. A block with no fields still has both: a role with nothing to say is the line `role viewer {` followed by a line `}`.
- `//` starts a comment.
## Settings
| Setting | Value |
| --- | --- |
| `target_kinds` | the kinds of resource the policy talks about, such as `[project, folder, document]` |
| `broad_targets` | the kinds that sit at the top of a path, such as `[org]` |
| `strategy` | `most_specific` (the default), `deny_overrides`, `permit_overrides` or `first_applicable` |
| `max_depth` | a number: the depth limit of a relation check |
## Declarations
| Declaration | Fields |
| --- | --- |
| `permission { }` | `label`, `description`, `targets` (required), `implied_by`, `depends_on`, `fields`, `non_delegable`, `management_only`, `override_only`, `meta { k = "v" }` |
| `role { }` | `inherits` |
| `subject { }` | `principals`, `attrs { }`, and `assign { }` with `scope`, `valid_from`, `valid_until` |
| `grant { }` | `effect` (`allow` or `deny`), `subject`, `permission`, `target`, `scope`, `when`, `fields`, `valid_from`, `valid_until` |
| `mutually_exclusive { }` | `of` (`roles` or `permissions`), `members` (two or more), `anchor` (a kind; absent means global) |
| `conflicting_actions { }` | `first`, `then`, `history` (default `history`), `distinct_roles` |
| `relation { }` | `rewrite` |
| `relations = []` | declares that the policy uses no relations |
| `tuples { }` | one `object#relation@subject` per line |
| `override resource_owner { }` | `attr`, `except` |
| `override permission_holder { }` | `permission`, `except` |
| `invariant { }` | the fields of the kind, below |
In a grant, `subject` takes a matcher (`anyone`, `role viewer`, `user ana`, `principal ana`, `relation viewer`), `target` names the kind or the resource the grant sits on, and `scope` limits where it applies, as in `scope = org:acme`.
The invariant kinds and their fields are:
| Kind | Fields |
| --- | --- |
| `catalog_conformance`, `no_self_management`, `prerequisites` | none, written as an empty block |
| `require_permission` | `permission`, `resource` |
| `no_lockout` | `permissions`, `members`, `resource`, `reserve_role`, `reserve_scope`, `reserve_subjects`, `reserve_from`, `reserve_until` |
| `non_delegable` | `manager` |
| `management_only` | `roles` |
| `no_escalation` | `bypass`, `on` |
| `forbid` | `subject`, `permissions` |
| `separation_of_duties` | `subjects` (optional: also judged when a grant is added) |
## A complete example
One policy for the documents of an organization. Viewers see a project, editors edit documents in it, and `legal` is a folder that nobody edits.
```blocks title="documents.strig"
// Documents of an organization: who may read and edit them, and when.
language blocks
target_kinds = [document, folder, project]
broad_targets = [org]
max_depth = 4
permission project.view {
label = "View project"
targets = [project]
}
// Reading a document follows from viewing its project.
permission document.view {
targets = [project, folder, document]
implied_by = [project.view]
}
permission document.edit {
targets = [project, folder, document]
depends_on = [document.view] // never alone
}
role editor {
inherits = [viewer]
}
role viewer {
}
subject user:ana {
principals = [ana]
attrs {
dept = "legal"
}
assign editor {
scope = project:apollo
}
}
// A temporary assignment.
subject user:carla {
assign viewer {
scope = project:apollo
valid_from = 2026-01-01
valid_until = 2026-12-31T23:59:59Z
}
}
grant g-view {
effect = allow
subject = role viewer
permission = project.view
target = project
scope = org:acme
}
grant g-edit {
effect = allow
subject = role editor
permission = document.edit
target = project
scope = org:acme
when = subject.dept == "legal"
}
grant g-seal {
effect = deny
subject = anyone
permission = document.edit
target = folder:legal
scope = project:apollo
}
invariant no_self_management {
}
invariant catalog_conformance {
}
```
Read it from the top:
- The catalog is the three `permission` blocks. `document.view` follows from `project.view` through `implied_by`, and `document.edit` is never held without `document.view`, through `depends_on`.
- `editor` inherits `viewer`, so an editor holds everything a viewer does.
- Ana is an editor in Apollo, with a `dept` attribute that `g-edit` reads in its `when`. Carla is a viewer in Apollo for 2026 only: `valid_from` and `valid_until` are UTC.
- `g-view` and `g-edit` allow on `project` inside `org:acme`. `g-seal` denies `document.edit` on the folder `legal` inside Apollo. The folder is a closer step to the document than the project, so under `most_specific` it decides.
- The two invariants, `no_self_management` and `catalog_conformance`, are rules that governance checks every later change to the grants against. A change is applied only if every invariant passes.
## Relations and tuples
A relation is defined by a rewrite, and tuples state the facts it reads. A grant reaches them through the `relation` matcher.
```blocks title="relations.strig"
language blocks
target_kinds = [doc, org]
max_depth = 4
permission doc.read {
targets = [doc]
}
role viewer {
}
grant g-read {
effect = allow
subject = relation viewer
permission = doc.read
target = doc
}
// Owners and viewers of a document.
relation doc#owner {
rewrite = this
}
relation doc#viewer {
rewrite = this | owner
}
relation org#member {
rewrite = this
}
tuples {
doc:d1#owner@user:bob
doc:d1#viewer@org:acme#member // the whole organization
}
```
`org:acme#member` is a subject of its own in the second tuple, so every member of the organization is a viewer of `doc:d1`. A policy that uses no relations can say so with `relations = []`.
## Governance
Flags and invariants let the catalog state its own rules. This source uses `non_delegable`, `management_only` and `override_only`, the two overrides and the invariants.
```blocks title="governance.strig"
language blocks
target_kinds = [doc, org]
permission doc.read {
targets = [doc]
}
permission doc.edit {
targets = [doc]
implied_by = [doc.read]
non_delegable = true
}
permission org.settings {
targets = [org]
management_only = true
}
permission doc.purge {
label = "Purge for good"
targets = [doc]
override_only = true
meta {
risk = "high"
}
}
role viewer {
}
subject user:bob {
assign viewer {
}
}
// The owner of a document may do anything to it.
override resource_owner {
attr = "owner"
except = [doc.purge]
}
override permission_holder {
permission = doc.read
}
invariant no_self_management {
}
invariant catalog_conformance {
}
invariant require_permission {
permission = doc.read
resource = org:acme > doc
}
invariant no_lockout {
permissions = [doc.read]
members = [user:bob]
resource = doc:d1
reserve_role = viewer
reserve_subjects = [user:bob]
}
invariant forbid {
subject = anyone
permissions = [doc.edit]
}
```
## Common mistakes
### Misspelled field
A field misspelled, here `target` for `targets`:
```text title="policy.strig"
language blocks
target_kinds = [doc]
permission doc.read {
target = [doc]
}
```
```text title="Error"
policy.strig:5:12: permission `doc.read` needs `targets`
hint: add a line: targets = ...
policy.strig:6:3: unknown field `target` in permission
hint: did you mean `targets`?
```
The parser reports the missing required field and the unknown one. The hint on the second names the field you meant.
### Extra closing brace
A closing brace left over:
```text title="policy.strig"
language blocks
target_kinds = [doc]
permission doc.read {
targets = [doc]
}
}
```
```text title="Error"
policy.strig:8:1: expected a declaration, found `}`
```
### Block never closed
A block that is never closed:
```text title="policy.strig"
language blocks
target_kinds = [doc]
permission doc.read {
targets = [doc]
```
```text title="Error"
policy.strig:5:12: the permission block is not closed
hint: add a closing `}` at the start of a line
```
### Unknown permission in a grant
A permission with a typo in a grant. The hint names the nearest declared one:
```text title="policy.strig"
language blocks
target_kinds = [doc]
permission doc.read {
targets = [doc]
}
role editor {
}
grant g1 {
effect = allow
subject = role editor
permission = doc.raed
target = doc
}
```
```text title="Error"
policy.strig:15:3: unknown permission `doc.raed`
hint: did you mean `doc.read`? or declare it as a permission block
```
### Value not allowed
A value outside the allowed ones:
```text title="policy.strig"
language blocks
target_kinds = [doc]
permission doc.read {
targets = [doc]
}
role editor {
}
grant g1 {
effect = permit
subject = role editor
permission = doc.read
target = doc
}
```
```text title="Error"
policy.strig:13:12: effect must be allow or deny, found `permit`
```
### Required field missing
A required field left out:
```text title="policy.strig"
language blocks
target_kinds = [doc]
permission doc.read {
targets = [doc]
}
role editor {
}
grant g1 {
effect = allow
subject = role editor
permission = doc.read
}
```
```text title="Error"
policy.strig:12:7: grant `g1` needs `target`
hint: add a line: target = ...
```
### Name declared twice
A name declared twice. The first declaration is the one the second error points back to:
```text title="policy.strig"
language blocks
target_kinds = [doc]
permission doc.read {
targets = [doc]
}
permission doc.read {
targets = [doc]
}
```
```text title="Error"
policy.strig:9:12: permission `doc.read` is declared twice (also at policy.strig:5:12)
hint: the first declaration is the related position
```
---
# Rules
URL: https://strig.vercel.app/docs/policy-language/rules
Rules writes one statement per line. It is the shortest of the three syntaxes and reads almost as a sentence, so it suits short policies and review of a change line by line. What the three syntaxes share (the `language` line, references, conditions, rewrites) is on [the section page](https://strig.vercel.app/docs/policy-language.md).
## Shape of a source
A source is the `language rules` line, then one statement per line.
- A statement starts with its keyword, or with a grant id followed by a colon.
- A line indented deeper than the one above continues it. A long permission can wrap, and a comment can sit under the line it explains.
- A list is the names separated by commas (`kinds a, b, c`), or in square brackets inside the invariant fields.
- `//` starts a comment.
## Statements
| Statement | Form |
| --- | --- |
| `kinds` | `kinds a, b, c` |
| `broad` | `broad org` |
| `strategy` | `strategy `, where the name is `most_specific`, `deny_overrides`, `permit_overrides` or `first_applicable` |
| `depth` | `depth ` |
| `permission` | `permission on [implied by ] [depends_on ] [fields ] [label "..."] [about "..."] [non-delegable] [management-only] [override-only] [meta k = "v"]` |
| `role` | `role [inherits ]` |
| `subject` | `subject team:ops` declares a subject |
| role assignment | `user:ana has role [in ] [from ] [until ]` |
| principal | `user:ana has principal ` |
| attribute | `user:ana has attr = ` |
| `relations` | `relations none` declares that the policy uses no relations |
| `relation` | `relation doc#viewer = this \| owner` |
| `tuple` | `tuple doc:d1#owner@user:bob` |
| grant | `: allow\|deny to on [in ] [fields ] [when ] [from ] [until ]` |
| `mutually-exclusive` | `mutually-exclusive of roles\|permissions members [a, b] [anchor ]` |
| `conflicting-actions` | `conflicting-actions first [a] then [b] [history ] [distinct_roles true]` |
| `override` | `override resource-owner [except ]` and `override permission-holder [except ]` |
| `always` | `always [fields]` |
The invariant words are the Blocks names with hyphens: `catalog-conformance`, `no-self-management`, `prerequisites`, `require-permission`, `no-lockout`, `non-delegable`, `management-only`, `no-escalation`, `forbid` and `separation-of-duties` (`subjects`). Fields follow the word as `name value` pairs, with lists in square brackets, for example `always require-permission permission doc.read resource org:acme > doc`.
In a grant, the matcher is `anyone`, `role viewer`, `user ana`, `principal ana` or `relation viewer`. `on` names the kind or the resource the grant sits on, and `in` limits where it applies. The word after `to` is a permission the catalog declares.
## A complete example
One policy for the documents of an organization. Viewers see a project, editors edit documents in it, and `legal` is a folder that nobody edits.
```rules title="documents.strig"
// Documents of an organization: who may read and edit them, and when.
language rules
kinds document, folder, project
broad org
depth 4
permission project.view on project label "View project"
// Reading a document follows from viewing its project.
permission document.view on project, folder, document implied by project.view
permission document.edit on project, folder, document depends_on document.view
// never alone
role editor inherits viewer
role viewer
user:ana has role editor in project:apollo
user:ana has principal ana
user:ana has attr dept = "legal"
// A temporary assignment.
user:carla has role viewer in project:apollo from 2026-01-01 until 2026-12-31T23:59:59Z
g-view: allow role viewer to project.view on project in org:acme
g-edit: allow role editor to document.edit on project in org:acme when subject.dept == "legal"
g-seal: deny anyone to document.edit on folder:legal in project:apollo
always no-self-management
always catalog-conformance
```
Read it from the top:
- `kinds` and `broad` set the kinds of resource and the one at the top of a path. `depth` sets the depth limit of a relation check.
- Each `permission` line is a catalog entry. `document.view` follows from `project.view` through `implied by`, and `document.edit` is never held without `document.view`, through `depends_on`. The comment indented under it belongs to that line.
- `role editor inherits viewer` makes an editor hold everything a viewer does. Declaration order does not matter, so `viewer` can come after the role that inherits it.
- The `user:` lines fill in the subjects. Ana is an editor in Apollo and has a `dept` attribute that `g-edit` reads in its `when`. Carla is a viewer in Apollo for 2026 only, with dates in UTC.
- The three grant lines each start with their id. `g-seal` denies `document.edit` on the folder `legal` inside Apollo, a closer step to the document than the project, so under `most_specific` it decides.
- The two `always` lines are invariants, rules that governance checks every later change to the grants against.
## Relations and tuples
A relation is defined by a rewrite, and tuples state the facts it reads. A grant reaches them through the `relation` matcher.
```rules title="relations.strig"
language rules
kinds doc, org
depth 4
permission doc.read on doc
role viewer
g-read: allow relation viewer to doc.read on doc
// Owners and viewers of a document.
relation doc#owner = this
relation doc#viewer = this | owner
relation org#member = this
tuple doc:d1#owner@user:bob
tuple doc:d1#viewer@org:acme#member // the whole organization
```
`org:acme#member` is a subject of its own in the second tuple, so every member of the organization is a viewer of `doc:d1`.
## Governance
Flags and invariants let the catalog state its own rules. The flags go at the end of the permission line, and the invariants are `always` lines.
```rules title="governance.strig"
language rules
kinds doc, org
permission doc.read on doc
permission doc.edit on doc implied by doc.read non-delegable
permission org.settings on org management-only
permission doc.purge on doc label "Purge for good" meta risk = "high" override-only
role viewer
user:bob has role viewer
// The owner of a document may do anything to it.
override resource-owner owner except doc.purge
override permission-holder doc.read
always no-self-management
always catalog-conformance
always require-permission permission doc.read resource org:acme > doc
always no-lockout permissions [doc.read] members [user:bob] resource doc:d1 reserve_role viewer reserve_subjects [user:bob]
always forbid subject anyone permissions [doc.edit]
```
## Common mistakes
### Missing language line
The `language` line left out:
```text title="policy.strig"
role viewer
```
```text title="Error"
policy.strig:1:1: a source starts by declaring its language
hint: write on the first line: language blocks
```
### Second language line
A second `language` line, even for the same syntax:
```text title="policy.strig"
language rules
kinds doc
permission doc.read on doc
role editor
g1: allow role editor to doc.read on doc
language rules
```
```text title="Error"
policy.strig:7:1: a source declares its language once, on its first line (also at policy.strig:1:1)
hint: one file holds one syntax: split the other into its own file
```
### Grant without a colon
A grant with no colon after its id. The parser reads the id as a statement:
```text title="policy.strig"
language rules
kinds doc
permission doc.read on doc
role editor
g1 allow role editor to doc.read on doc
```
```text title="Error"
policy.strig:6:1: unknown statement `g1`
hint: expected one of: kinds, broad, strategy, depth, permission, role, subject, tuple, relation, relations, override, always
```
### The old needs word
The old `needs` word. It is now `depends_on`, in the same place on the line:
```text title="policy.strig"
language rules
kinds doc
permission doc.read on doc
permission doc.edit on doc needs doc.read
```
```text title="Error"
policy.strig:5:28: `needs` is now `depends_on`
hint: write: depends_on
```
### Undeclared role
A role that is not declared. The hint names the nearest one and the way to declare it:
```text title="policy.strig"
language rules
kinds doc
permission doc.read on doc
role editor
user:ana has role edtor
```
```text title="Error"
policy.strig:6:19: role `edtor` is not declared
hint: did you mean `editor`? or declare it with: role edtor { }
```
### Kind not in kinds
A kind that is not in `kinds`:
```text title="policy.strig"
language rules
kinds doc
permission doc.read on dcc
```
```text title="Error"
policy.strig:4:24: `doc.read` targets `dcc`, which is not in target_kinds or broad_targets
hint: did you mean `doc`? or add it to target_kinds
```
### Time without two digits
A time of day without two digits in the hour:
```text title="policy.strig"
language rules
kinds doc
permission doc.read on doc
role editor
g1: allow role editor to doc.read on doc when time_between "9:00" "17:00"
```
```text title="Error"
policy.strig:6:60: `9:00` is not a time of day
hint: write hours and minutes with two digits each, 00:00 to 23:59, like "09:30"
```
### Grant id used twice
A grant id used twice:
```text title="policy.strig"
language rules
kinds doc
permission doc.read on doc
role editor
g1: allow role editor to doc.read on doc
g1: allow role editor to doc.read on doc
```
```text title="Error"
policy.strig:7:1: grant `g1` is declared twice (also at policy.strig:6:1)
hint: the first declaration is the related position
```
---
# Actors
URL: https://strig.vercel.app/docs/policy-language/actors
Actors groups the policy under whoever acts: a role, a user, a principal. A heading names the actor and the indented lines under it say what that actor may do, so the file answers "what can an editor do?" by reading one place. What the three syntaxes share (the `language` line, references, conditions, rewrites) is on [the section page](https://strig.vercel.app/docs/policy-language.md).
## Shape of a source
A source is the `language actors` line, then headings.
- A heading starts in the first column. The lines under it are indented.
- A grant lives under the actor it applies to, and ends with `as `, which names it.
- The catalog, the relations, the tuples, the engine settings and the invariants each have a heading of their own.
- `//` starts a comment.
## Headings
| Heading | Lines under it |
| --- | --- |
| `role [inherits ]` | `in ` and, under it or directly, `allow\|deny on [fields ] [when ] [from ] [until ] as ` |
| `user ` or `subject ` | `role [in ] [from ] [until ]`, `principal `, `attr = `, and the same `allow` and `deny` lines |
| `principal `, `relation `, `anyone` | the `allow` and `deny` lines |
| `catalog` | `kinds`, `broad`, then each permission as in Rules, without the `permission` word, and the `mutually-exclusive` and `conflicting-actions` lines as in Rules |
| `relations` | `doc#viewer = this \| owner`, one per line |
| `tuples` | `doc:d1#owner@user:bob`, one per line |
| `engine` | `strategy`, `depth` and `override ...` |
| `governance` | the invariant words, as in Rules without `always` |
A permission line under `catalog` is ` on ` with the same optional parts as in Rules: `implied by`, `depends_on`, `label`, `about`, `non-delegable`, `management-only`, `override-only` and `meta`. The invariant words are the Blocks names with hyphens, such as `no-self-management` and `no-lockout`.
The actor heading is the matcher of the grant. Lines under `role editor` apply to the role, lines under `anyone` to every subject, and a `user`, `principal` or `relation` heading to that user, principal or relation. `in ` limits where the lines under it apply, as `in org:acme` does below. A grant line names its target after `on` and ends with `as `.
## A complete example
One policy for the documents of an organization. Viewers see a project, editors edit documents in it, and `legal` is a folder that nobody edits.
```actors title="documents.strig"
// Documents of an organization: who may read and edit them, and when.
language actors
role editor inherits viewer
role viewer
in org:acme
allow project.view on project as g-view
role editor
in org:acme
allow document.edit on project when subject.dept == "legal" as g-edit
anyone
in project:apollo
deny document.edit on folder:legal as g-seal
subject user:ana
role editor in project:apollo
principal ana
attr dept = "legal"
// A temporary assignment.
subject user:carla
role viewer in project:apollo from 2026-01-01 until 2026-12-31T23:59:59Z
catalog
kinds document, folder, project
broad org
project.view on project label "View project"
// Reading a document follows from viewing its project.
document.view on project, folder, document implied by project.view
document.edit on project, folder, document depends_on document.view
// never alone
engine
depth 4
governance
no-self-management
catalog-conformance
```
Read it from the top:
- `role editor inherits viewer` makes an editor hold everything a viewer does. The heading and the later `role viewer` can come in any order.
- Under `role viewer`, the lines say what a viewer may do: in `org:acme`, allow `project.view` on `project`, as the grant `g-view`. Under `role editor`, `g-edit` allows `document.edit` and carries a `when` that reads Ana's `dept` attribute.
- Under `anyone`, `g-seal` denies `document.edit` on the folder `legal` inside Apollo. The folder is a closer step to the document than the project, so under `most_specific` it decides.
- Each `subject` heading holds a person's roles, attributes and principals. Ana is an editor in Apollo. Carla is a viewer in Apollo for 2026 only, with dates in UTC.
- `catalog` lists the kinds and the permissions. `document.edit` is never held without `document.view`, through `depends_on`, and the comment indented under it belongs to that line.
- `engine` sets the depth limit of a relation check, and `governance` lists the invariants, rules that governance checks every later change to the grants against.
## Relations and tuples
A relation is defined under `relations`, and tuples state the facts it reads. A grant reaches them through a `relation` heading.
```actors title="relations.strig"
language actors
relation viewer
allow doc.read on doc as g-read
role viewer
catalog
kinds doc, org
doc.read on doc
relations
// Owners and viewers of a document.
doc#owner = this
doc#viewer = this | owner
org#member = this
tuples
doc:d1#owner@user:bob
doc:d1#viewer@org:acme#member // the whole organization
engine
depth 4
```
`org:acme#member` is a subject of its own in the second tuple, so every member of the organization is a viewer of `doc:d1`.
## Governance
Flags and invariants let the catalog state its own rules. The flags go at the end of a permission line under `catalog`, the overrides under `engine` and the invariants under `governance`.
```actors title="governance.strig"
language actors
role viewer
subject user:bob
role viewer
catalog
kinds doc, org
doc.read on doc
doc.edit on doc implied by doc.read non-delegable
org.settings on org management-only
doc.purge on doc label "Purge for good" meta risk = "high" override-only
engine
// The owner of a document may do anything to it.
override resource-owner owner except doc.purge
override permission-holder doc.read
governance
no-self-management
catalog-conformance
require-permission permission doc.read resource org:acme > doc
no-lockout permissions [doc.read] members [user:bob] resource doc:d1 reserve_role viewer reserve_subjects [user:bob]
forbid subject anyone permissions [doc.edit]
```
## Common mistakes
### Grant line in the first column
A grant line that starts in the first column, so it reads as a heading:
```text title="policy.strig"
language actors
catalog
kinds doc
doc.read on doc
role editor
allow doc.read on doc as g1
```
```text title="Error"
policy.strig:8:1: unknown heading `allow`
hint: expected one of: catalog, relations, tuples, engine, governance, role, user, subject, principal, relation, anyone
```
### Grant without an id
A grant with no `as `:
```text title="policy.strig"
language actors
catalog
kinds doc
doc.read on doc
role editor
allow doc.read on doc
```
```text title="Error"
policy.strig:8:24: a rule needs an id: end the line with `as `
```
### Undeclared permission
A permission the catalog does not declare:
```text title="policy.strig"
language actors
catalog
kinds doc
doc.read on doc
role editor
allow doc.write on doc as g1
```
```text title="Error"
policy.strig:8:9: unknown permission `doc.write`
hint: declare it as a permission block
```
### Unknown heading
A heading that is not one of the valid ones. The hint lists them:
```text title="policy.strig"
language actors
catalog
kinds doc
doc.read on doc
team ops
role editor
```
```text title="Error"
policy.strig:7:1: unknown heading `team`
hint: expected one of: catalog, relations, tuples, engine, governance, role, user, subject, principal, relation, anyone
```
### No catalog
A source with no `catalog`, so no permission is declared:
```text title="policy.strig"
language actors
role editor
allow doc.read on doc as g1
```
```text title="Error"
policy.strig:4:9: unknown permission `doc.read`
hint: declare it as a permission block
```
### Undeclared role
A role that no heading declares:
```text title="policy.strig"
language actors
catalog
kinds doc
doc.read on doc
subject user:ana
role editor
```
```text title="Error"
policy.strig:8:3: role `editor` is not declared
hint: declare it with: role editor { }
```
---
# JavaScript
URL: https://strig.vercel.app/docs/javascript
The npm package `@the-hades-organization/strig` runs the same engine on Node, Bun and in the browser. This page covers what is specific to JavaScript. Policies, decisions and governance work as they do in the other pages, with `camelCase` names. Every signature is in the [reference](https://strig.vercel.app/docs/reference.md#javascript-the-npm-package).
```js title="JavaScript"
import { load } from '@the-hades-organization/strig';
const { Engine, Context } = await load(); // native on Node and Bun, wasm in the browser
const engine = new Engine(spec); // the same EngineSpec JSON as in Rust
const ctx = new Context({ grants });
engine.check(ctx, { subject, permission: 'document.view', resource });
engine.apply({ actor, current, mutation: { add: grant }, invariants, audit: { level: 'standard' } });
```
## Entry points
Each subpath is its own import, so a browser bundle takes only what it uses.
| Import | For | Page |
| --- | --- | --- |
| `@the-hades-organization/strig` | the engine, `Context`, `compile`, `diff`, `lint`, the audit and Merkle verifiers | this page |
| `.../client`, `.../react`, `.../angular` | a client that decides locally for the interface | [Frontend](https://strig.vercel.app/docs/integrations/frontend.md) |
| `.../server`, `.../remote` | a hub that pushes changes, and the client of a decision server | [Server](https://strig.vercel.app/docs/integrations/server.md) |
| `.../express`, `.../fastify`, `.../nestjs` | route guards | [Web frameworks](https://strig.vercel.app/docs/web-frameworks.md) |
| `.../prisma`, `.../drizzle`, `.../kysely` | a list of allowed rows as a `where` | [ORMs](https://strig.vercel.app/docs/integrations/orms.md) |
| `.../approvals` | approvals, elevation, recertification | [Approvals](https://strig.vercel.app/docs/approvals.md) |
| `.../store` | grants and roles in a JSON file | [below](#grants-and-roles-in-a-json-file) |
| `.../testing` | check that every route has a rule | [Web frameworks](https://strig.vercel.app/docs/web-frameworks.md#test-the-table) |
| `.../types` | permission ids as a TypeScript union | [below](#catalog-types-for-the-frontend) |
Every signature is in the [reference](https://strig.vercel.app/docs/reference.md#javascript-the-npm-package).
## What the engine answers beyond a verdict
```js
engine.allowedFields(ctx, { subject, permission: 'document.edit', resource });
// { kind: 'only', fields: ['title', 'body'] }
engine.whyNot(ctx, { subject, permission: 'document.edit', resource });
// the cause of the denial and what would change it, or null when it is allowed
engine.impact({ actor, current: grants, mutation: { add: grant }, invariants });
// who gains and who loses access if this change were applied; nothing is applied
```
- [Field permissions](https://strig.vercel.app/docs/modeling/field-permissions.md) for `allowedFields` and `explainFields`.
- [Why not](https://strig.vercel.app/docs/governance/why-not.md) for `whyNot`, [Impact](https://strig.vercel.app/docs/governance/impact.md) for `impact` and `reviewImpact`.
- `engine.elevate(input)` and the `Elevations` and `Recertifications` classes of `.../approvals` are in [Elevation](https://strig.vercel.app/docs/governance/elevation.md) and [Recertification](https://strig.vercel.app/docs/governance/recertification.md).
Two functions work on policies, not on decisions. `strig.diff(before, after)` lists the decisions that change between two versions of a policy, and `strig.lint(policy)` reports findings such as a set already violated. [Diff and lint](https://strig.vercel.app/docs/tools/diff-lint.md) has the options and the CI use.
After a write, hold the client back until it has seen the change:
```js
client.requireRevision('tenant@42'); // until the capabilities reach it, every decision denies
client.behind(); // true while it is behind
```
The audit verifiers `verifyMerkleInclusion`, `verifyMerkleConsistency` and `verifyTimestamp` run offline, on both backends: see [Audit](https://strig.vercel.app/docs/audit.md).
## Install by platform
*Changed in 0.7.0.*
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.
```text title="Terminal"
npm install @the-hades-organization/strig
```
The native module no longer ships inside the main package, which had about 24 MB unpacked. Each platform has its own package, installed by npm as an optional dependency. 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` |
Each is published as `@the-hades-organization/`. The loader resolves the platform package, then a local build, then falls back to wasm.
- **Linux with musl** (Alpine, for example) has no native module and runs on the wasm backend, which is bundled in the main package. The [benchmarks](https://strig.vercel.app/docs/benchmarks.md) show what that costs.
- **`--omit=optional` or `--no-optional`** leaves the platform package out, so `load()` falls back to wasm. With `STRIG_BACKEND=native` it throws an error that names the package to install.
- **If you vendored `node_modules` by platform**, or copied files out of the package, point them at the platform package.
### Verify what you installed
Every npm package is published with provenance, and each release carries a CycloneDX SBOM. `npm audit signatures` checks both of what is in your `node_modules`. [Security](https://strig.vercel.app/docs/security.md#verify-a-release) has the commands.
## Rules written in JavaScript
*Added in 0.7.0.*
The function of a `call` condition, your own override and your own invariant are synchronous callbacks passed to the `Engine` constructor. The engine calls them in the middle of a decision or of `apply`, and they show up like the built-in ones: the `explain` trace names the override, a refusal carries your violation, and the audit records it as it records the built-in invariants.
```js title="JavaScript"
const engine = new Engine(spec, {
// `call` conditions: { op: 'call', func: 'same_dept', args: [{ attr: 'subject.dept' }, { attr: 'resource.dept' }] }
conditions: { same_dept: ([a, b]) => a === b },
// Decides before the grants: 'allowed', 'denied' or 'abstained'. `except` skips permissions.
overrides: [{ name: 'frozen', except: ['project.view'], evaluate: ({ permission }) => (frozen ? 'denied' : undefined) }],
invariants: {
// A role in use is not deleted.
role_in_use({ mutation, before }) {
if (!('remove' in mutation)) return;
const grant = before.find((g) => g.id === mutation.remove.id);
if (grant?.subject.kind === 'role' && inUse(grant.subject.id)) return `role ${grant.subject.id} is in use`;
},
},
});
engine.apply({ actor, current, mutation, invariants: [{ kind: 'custom', name: 'role_in_use' }] });
```
An invariant runs only when `invariants` lists `{ kind: 'custom', name }`, and an unknown name is `UNKNOWN_INVARIANT`.
| Callback | Gets | Answers |
| --- | --- | --- |
| `conditions[func]` | The operands of the `call`, already resolved: `{ attr: 'subject.dept' }` arrives as the value of the attribute. | A boolean. |
| `overrides[i].evaluate` | `{ subject, permission, resource, env, now }`. | `'allowed'`, `'denied'`, `'abstained'`, or nothing to abstain. |
| `invariants[name]` | `{ actor, mutation, before, after, now }`; `mutation` has the shape `apply` takes. | Nothing, `null` or `true` to accept; a text, or `{ message, suggestion? }`, to refuse. |
A host override runs after the overrides of the spec, in list order, and `except` lists permissions it is never consulted for. A `suggestion` is a change: the governance checks it against every invariant before it surfaces in the violation.
- **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 a `Context` gets `REENTRANT_CALL`. Changing the very `Context` under decision is refused by the runtime with an error of its own. Read what you need before the call and keep it in the closure.
- **Listings treat an override as opaque.** `list` cannot know what a function of yours would decide, so the resources it might decide on stay as residue, never as allowed.
The audit sink, its policy and the redactor go in the same second argument. They are on [Audit](https://strig.vercel.app/docs/audit.md#the-sink-in-javascript).
## Catalog types for the frontend
*Added in 0.7.0.*
The frontend should not hold permission ids as loose strings. `strig-types` turns an exported catalog into one `.ts` file, so a typo is a compile error.
A permission can carry its display name and description per locale, `labels` and `descriptions`, next to `label` and `description`. They are optional, they are not declared in the policy language, only in the catalog export (JSON) or the builder, and in Rust `PermissionDef::localized_label("pt-BR", "Editar")` sets one.
```text title="Terminal"
npx strig-types catalog.json -o src/permissions.generated.ts
```
The file has the `PermissionId` union, a `PermissionLocale` union, a `PERMISSIONS` constant with the metadata, `PERMISSION_IDS`, and three helpers: `isPermissionId`, `permissionLabel` and `permissionDescription`. The helpers take a locale and fall back to the default text. The output is sorted, so it changes only when the catalog does. Without `-o` it goes to the standard output.
`generateTypes` from `@the-hades-organization/strig/types` does the same as a function.
```ts title="TypeScript"
import { PermissionClient } from '@the-hades-organization/strig/client';
import { permissionLabel, isPermissionId, type PermissionId } from './permissions.generated';
// With the parameter, check, decide, explain, list, whoCan, whoCanOn and checkFor accept only these ids.
// Without it they accept any string, as before.
const engine = new strig.Engine(spec);
const client = new PermissionClient(/* ... */);
client.can('users:read', resource); // only ids of the union compile
permissionLabel('users:read', 'pt-BR'); // the label in that locale, or the default one
function guard(id: string) {
if (isPermissionId(id)) client.can(id, resource); // narrow a plain string first
}
```
## Grants and roles in a JSON file
*Added in 0.7.0.*
For a system with neither Postgres nor Redis, `@the-hades-organization/strig/store` keeps the grants and the role assignments in one JSON file. It runs on Node and Bun, because it uses `node:fs`.
```ts title="TypeScript"
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' }); // plus 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
```
The file is `{ "version": 1, "grants": [...], "roles": { "": [, ...] } }`. The roles themselves, the hierarchy, stay in the engine spec. The file holds who has which. It can also hold a `pending` list: see [Approvals](https://strig.vercel.app/docs/approvals.md#where-the-requests-are-kept).
- **It fails closed.** A missing file, invalid JSON, a repeated grant id or a `version` other than 1 throws `JsonStoreError` (`STORE_NOT_FOUND`, `STORE_CORRUPT`, `STORE_VERSION`) on load. The store never starts empty on its own. `createIfMissing` is the explicit way to start one.
- **Writes are atomic.** The store writes a temp file in the same directory, calls `fsync`, renames it over the file and then syncs the directory. A crash leaves the old file or the new one, never half of one.
- **Writes are serialised.** Calls in one process queue up. Between processes, a `.lock` created with `O_EXCL` is held. A lock whose owner died on this host, or that is older than `lockStaleMs` (30 s), is taken over. Each change re-reads the file under the lock, so processes do not overwrite each other. After `lockTimeoutMs` (5 s) a write fails with `STORE_LOCK_TIMEOUT`.
- **Changes** are `addGrant`, `updateGrant`, `removeGrant`, `assignRole`, `revokeRole`, `setRoles`, or `apply(engine, input)`, which runs the governance over the grants the file holds right now and persists what it accepts. A refusal writes nothing.
- **Reload.** `reload()` picks up an outside edit, and `watch()` does it on its own. It watches the directory, because the rename replaces the file. A bad file on reload keeps the last good snapshot, throws from `reload()` and goes to `onError` from `watch()`. `onChange` fires after every reload and every write.
Not here: audit records, which go to your own sink ([Audit](https://strig.vercel.app/docs/audit.md)).
- [Web frameworks](https://strig.vercel.app/docs/web-frameworks.md): One route table for Express, Fastify and NestJS, deny by default.
---
# Web frameworks
URL: https://strig.vercel.app/docs/web-frameworks
The Express, Fastify and NestJS integrations take the same options and decide on each request. Their framework is an optional peer dependency: an integration you do not import costs nothing, and importing one whose peer is missing throws `MissingPeerError`.
## One permission per handler
```js title="JavaScript"
import { load, scopeFromString } from '@the-hades-organization/strig';
import { authorize } from '@the-hades-organization/strig/express';
const { Engine, Context } = await load();
const options = {
subject: (req) => (req.headers['x-user'] ? { kind: 'user', id: req.headers['x-user'] } : undefined),
resource: (req) => scopeFromString(`document:${req.params.id}/org:o1`),
local: { engine: new Engine(spec), context: new Context({ grants }), now: () => Date.now() },
};
app.get('/doc/:id', authorize({ ...options, permission: 'document.view' }), handler);
```
| Option | Meaning |
| --- | --- |
| `subject(req)` | The caller. Returning nothing answers `401`. |
| `permission` | The permission, as text or `(req) => text`. |
| `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 same `authorize`, plus a `plugin` that adds `fastify.strigCan`.
- **NestJS** (`/nestjs`): `@Can('document.view')` on a handler or controller, with `new StrigGuard(options)` as the guard. A guarded handler with no `@Can` answers 500, so a missing declaration closes and never opens.
## One route table, deny by default
*Added in 0.7.0.*
A permission on every handler puts the rules in as many places as there are routes, and a route someone forgets is open. A route table puts them in one list, and a request no rule covers is refused (`denyStatus`, 403). A route is public only when its rule says `public: true`.
```js title="JavaScript"
import { authorizeRoutes } from '@the-hades-organization/strig/express';
const routes = [
{ method: 'GET', path: '/health', public: true },
{ method: 'GET', path: '/doc/:id', permission: 'document.view', resource: (req, params) => docScope(params.id) },
{ method: ['PUT', 'DELETE'], path: '/doc/:id', permission: 'document.edit', resource: (req, params) => docScope(params.id) },
];
app.use(authorizeRoutes({ subject, local: { engine, context }, routes })); // before the routers
```
Each rule has a `method` (a name, a list, or `'*'` for any), a `path`, and exactly one of `permission` and `public: true`. A bad table throws at startup. `resource` takes the request and the matched `params`: at app level Express has not filled `req.params` yet, so read the id from `params`.
### How a request is matched
- **Paths** use the framework syntax: literal segments, `:name` for one segment, and a trailing `*` for one or more.
- **The first matching rule decides**, so write the specific ones first. `HEAD` falls under `GET` rules.
- **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, and a malformed escape matches nothing.
- **Case** follows the framework. Express ignores it, Fastify is case sensitive, Nest follows its platform. Set `caseSensitive` on the table if you changed the Fastify option, and pass `{ caseSensitive: false }` to `assertRoutesCovered` for an Express app.
> **Warning**
>
> The table also answers 403 for URLs with no route, and a CORS preflight needs a rule of its own or has to be answered before the table.
### Where to mount it
| Framework | Import | Mount |
| --- | --- | --- |
| Express | `authorizeRoutes` from `/express` | `app.use(authorizeRoutes(options))`, before the routers. |
| Fastify | `authorizeRoutes` from `/fastify` | `fastify.addHook('onRequest', authorizeRoutes(options))`. |
| NestJS | `StrigRouteGuard` from `/nestjs` | `{ provide: APP_GUARD, useValue: new StrigRouteGuard(options) }`. |
In NestJS the table decides first. If it allows, a `@Can` on the handler or controller adds a second check that must also pass, even on a `public` rule. So `@Can` narrows and never opens what the table denies. A handler with no `@Can` needs nothing else.
```ts title="NestJS"
import { APP_GUARD } from '@nestjs/core';
import { Can, StrigRouteGuard } from '@the-hades-organization/strig/nestjs';
@Module({
providers: [{ provide: APP_GUARD, useValue: new StrigRouteGuard({ subject, local: { engine, context }, routes }) }],
})
export class AppModule {}
@Controller('doc')
export class DocController {
@Delete(':id')
@Can('document.purge', (req) => docScope(req.params.id)) // on top of what the table allows
remove() {}
}
```
Only HTTP contexts are supported. A GraphQL, WebSocket or RPC context answers 500.
## Test the table
*Added in 0.7.0.*
A table that drifts from the app is the failure it exists to prevent. `@the-hades-organization/strig/testing` lists the routes of an app and checks the table against them, in your own test suite.
```js title="JavaScript"
import { expressRoutes, assertRoutesCovered } from '@the-hades-organization/strig/testing';
assertRoutesCovered(expressRoutes(app), routes);
// throws, listing the routes with no rule and the rules with no route
```
- **A route with no rule** would be refused in production.
- **A rule with no route** is a typo, a removed route, or a rule hidden behind an earlier one.
| Function | Reads |
| --- | --- |
| `expressRoutes(app)` | An Express 4 or 5 app or router, nested routers included. Mounted sub-apps are not read. |
| `nestRoutes(app)` | A Nest app on the Express adapter, after `app.init()`. |
| `collectFastifyRoutes(fastify)` | Call it 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. |
`assertRoutesCovered` throws a `RouteTableAuditError` that carries the same audit.
## A decision server instead of a local engine
To get decisions from a [decision server](https://strig.vercel.app/docs/reference.md#decision-server-strig-server), pass a `RemoteClient` from `/remote` as `remote`. It has a timeout and a circuit breaker, and it denies when there is no answer.
```js title="JavaScript"
import { RemoteClient } from '@the-hades-organization/strig/remote';
const remote = new RemoteClient({ url: 'http://127.0.0.1:8080', timeoutMs: 250 });
const { allowed } = await remote.check({ subject, permission: 'document.view', resource });
```
## Next
A route guard answers one question per request. To filter a list down to the rows a subject may see, turn `engine.list` into a `where` with the [ORM adapters](https://strig.vercel.app/docs/integrations/orms.md). To run the decision server itself, see [Server](https://strig.vercel.app/docs/integrations/server.md).
---
# Postgres
URL: https://strig.vercel.app/docs/storage/postgres
`strig-postgres` stores the data behind the traits the engine already reads: `GrantSource`, `GrantIndex`, `TupleStore`, `TupleIndex` and `PendingStore`. Your decision code stays the same; only the place the grants live changes.
## Connect and migrate
```rust title="Rust"
use strig_postgres::{PgPendingStore, PgStore, PgTables, connect, migrate_with};
let tables = PgTables::default().in_schema("authz")?.with_prefix("strig")?;
let client = connect(&url).await?;
migrate_with(&client, &tables).await?;
let store = PgStore::load(&client, tables.clone()).await?;
let grants = store.grants(); // GrantSource + GrantIndex
let tuples = store.tuples(); // TupleStore + TupleIndex
let _follower = store.follow(hub.subscribe(), move || connect(&url), Duration::from_secs(1));
```
`PgTables` picks the schema and the table prefix. Both are checked as plain identifiers, so a value from configuration cannot smuggle SQL.
`migrate_with` is safe to run on every boot. It records each version in `_migrations`, runs inside one transaction under an advisory lock, and only adds (`CREATE ... IF NOT EXISTS`): nothing drops or rewrites data.
## The engine reads a snapshot
The core does no IO and `GrantSource` is synchronous, so `PgStore::load` reads the tables once and the engine decides from memory. The snapshot reloads when the transport delivers a `Change` (grants, tuples or a resync).
- A store exists only loaded, so the engine never decides over an empty set that is missing a deny.
- If a reload fails, the previous snapshot stays and `is_stale()` turns `true`. Put it in your readiness probe.
- The snapshot holds every grant and tuple. Size it for that. For a very large tuple set, answer `TupleStore` from your own indexed query.
## Write a change and notify in one transaction
`put_grant`, `delete_grant`, `put_tuple`, `delete_tuple`, `assign_role` and `revoke_role` take a client or a transaction. To apply a governed change end to end:
```rust title="Rust"
let tx = client.transaction().await?;
lock_governance(&tx).await?; // one change is judged at a time
let current = all_grants(&tx).await?; // read inside the transaction
let actor = tables.subject(&tx, "user", "ana").await?; // the subject with its stored roles
let next = governance.apply(&engine, &actor, ¤t, &mutation, None)?;
commit_mutation(&tx, "strig:changes", &mutation).await?; // writes the rows and queues NOTIFY
tx.commit().await?; // the notice leaves only now
```
`lock_governance` comes first so two instances never judge a change against the same stale set. `commit_mutation` writes what the `Mutation` changes and sends its `NOTIFY` in the same transaction: the notice goes out if, and only if, the change commits. Other instances reload when it arrives.
For a write you made yourself, call `strig_postgres::notify(&tx, channel, &change)` inside that transaction. The transport side is in [Revisions and real time](https://strig.vercel.app/docs/storage/consistency.md).
## Roles and pending requests
`strig_roles` keeps assignments per subject: the role, an optional scope and an optional validity window. A subject read from it carries the `authenticated` principal when its kind is `user`.
`PgPendingStore` is the `PendingStore` of the [approval flow](https://strig.vercel.app/docs/approvals.md), over a table with the expiry in an indexed column (`due(now)` lists what `expire_due` closes). `update` is one `UPDATE ... WHERE state = 'pending'`, so a request decided meanwhile by another process is never decided twice.
The trait is synchronous, so the store owns a connection on its own thread and each call blocks for one round trip. Call it from `spawn_blocking` inside async code. A call that does not answer in 10 seconds is a `PendingError::Store`, and the request is refused.
Recertification campaigns use `PgRecertStore` (migration 5 adds `strig_recert`); see [Recertification](https://strig.vercel.app/docs/governance/recertification.md). Shared exclusive leases use `PgExclusiveStore` (migration 4); see [Exclusive resources](https://strig.vercel.app/docs/storage/exclusive-store.md).
## Run the tests against a real database
The integration tests run when `STRIG_PG_URL` is set and skip without it:
```text title="Terminal"
STRIG_PG_URL=postgres://strig:strig@localhost/strig cargo test -p strig-postgres
```
---
# Redis
URL: https://strig.vercel.app/docs/storage/redis
`strig-redis` does two jobs: it is a `Transport` that tells every instance a grant changed, and it is a store for [exclusive leases](https://strig.vercel.app/docs/storage/exclusive-store.md). It does not store grants; for that use [Postgres](https://strig.vercel.app/docs/storage/postgres.md) or your own `GrantSource`.
## Tell the other instances
```rust title="Rust"
let hub = Hub::builder()
.transport(RedisTransport::new("redis://127.0.0.1/", "strig:changes")?)
.build();
let _relay = hub.spawn_relay();
let cache = Arc::new(CapabilityCache::new(Duration::from_secs(30), 10_000));
hub.on_change(cache.clone());
```
When an instance calls `hub.publish(change)`, the notice goes to the `strig:changes` channel. The hub of every other instance receives it and clears the cache entries it covers. A `Change` says what kind of change happened and on which step, never the grants: receivers reload from their own source.
Publishing reconnects on its own. If the subscription drops and comes back, or a client falls behind, the hub emits `Resync` and everything is reloaded.
## Share a lease
```rust title="Rust"
let mut registry = ExclusiveRegistry::new(
RedisExclusiveStore::new("redis://127.0.0.1/", "strig:exclusive")?,
);
```
Every instance that shares the resource uses the same prefix. Acquire, renew, release and the sweep each run as one atomic `WATCH`/`MULTI`/`EXEC` step. The semantics are in [Exclusive resources](https://strig.vercel.app/docs/storage/exclusive-store.md).
## What to plan for
| Piece | Behavior |
| --- | --- |
| Lease key expiry | Redis expiry only reclaims memory, after the lease lifetime plus a retention (one hour by default). Whether a lease is active is decided with the `now` you pass, never the Redis clock. |
| Connection | The synchronous connection of the `redis` crate, with timeouts. A timeout or a lost connection is a `StoreError`, and the call fails closed. |
| Blocking | Each call blocks for one round trip. Use `spawn_blocking` inside an async task. |
For NATS, Kafka or any other broker, implement `Transport` (`publish` and `subscribe`).
---
# Exclusive resources
URL: https://strig.vercel.app/docs/storage/exclusive-store
With the `exclusive` feature, a resource has 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.
```rust title="Rust"
let mut registry = ExclusiveRegistry::default();
let now = 0; // milliseconds since the Unix epoch, passed by the caller
let first = registry.acquire_checked(&engine, &ctx, &ana, &document, Terms::new(1, 60_000), now)?;
assert_eq!(first, Acquisition::Granted);
let second = registry.acquire_checked(&engine, &ctx, &bob, &document, Terms::new(9, 60_000), now + 10)?;
assert!(matches!(second, Acquisition::Preempted { .. }));
```
Ana holds the document for 60 seconds. Bob asks with priority 9 and holds `exclusive.preempt`, so he takes it. Without that permission the answer would be a refusal, however high the priority.
## Across processes
`ExclusiveRegistry::default()` keeps leases in memory, so a resource is exclusive inside one process. To share it between instances, give the registry a store that decides in the database or in Redis.
**Postgres**
```rust title="Rust"
// Run `migrate_with` first: schema version 4 adds `_exclusive`.
let store = PgExclusiveStore::connect(&url, PgTables::default()).await?;
let mut registry = ExclusiveRegistry::new(store);
```
**Redis**
```rust title="Rust"
// Every instance that shares the resource uses the same prefix.
let mut registry = ExclusiveRegistry::new(
RedisExclusiveStore::new("redis://127.0.0.1/", "strig:exclusive")?,
);
```
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.
| Guarantee | How |
| --- | --- |
| Same answers as the in-memory store | `strig::exclusive_conformance::run` (feature `conformance`) is the battery every store passes. Run it against a store of your own. |
| Time | Whether a lease is active is decided with the `now` you pass, never the clock of the database. |
| Failure | A timeout or a lost connection is a `StoreError`, and the call fails closed. |
The trait is synchronous, so both stores block the caller for the round trip. Use `spawn_blocking` inside an async task. Both crates have the `exclusive` feature on by default. The JavaScript binding does not expose exclusive stores yet; `Exclusive` there is in-process.
---
# Revisions and real time
URL: https://strig.vercel.app/docs/storage/consistency
*Added in 0.10.0.*
A grant change has to reach every instance and every browser session. Strig does it in two parts: a `Hub` that publishes change notices, and a **revision** that lets a reader refuse to decide from state older than a write it just made.
## Real time
```text title="Flow"
grant change ──► Hub::publish ──► local sessions (SSE/WebSocket) and CapabilityCache
│
└─► Transport (Redis, Postgres, your own) ──► Hub on the other instances
```
```rust title="Rust"
let hub = Hub::builder()
.transport(RedisTransport::new("redis://127.0.0.1/", "strig:changes")?)
.build();
let _relay = hub.spawn_relay();
let cache = Arc::new(CapabilityCache::new(Duration::from_secs(30), 10_000));
hub.on_change(cache.clone());
let provider = EngineProvider::new(engine, my_grant_loader).with_cache(cache);
let realtime = strig_axum::Realtime::new(hub).with_provider(Arc::new(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. See [Redis](https://strig.vercel.app/docs/storage/redis.md). |
| 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 | | 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`, `refresh` and `refresh_at_least` (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`.
## Reading your own writes
Ana removes a deny and reloads the page. The instance that answers the reload may not have seen the change yet. A revision closes that gap.
Each accepted change gets a revision: an opaque text `scope@value` that only grows within a data scope (the scope names what a counter orders, for example a tenant). The store hands it out:
- `Governance::with_revisions(Arc)` for the memory and file stores (`MemoryRevisions`).
- `strig_postgres::next_revision(&tx, "my_sequence", "tenant")` inside the transaction that writes the change, so the revision commits with it.
```rust title="Rust"
let applied = governance.apply_revised(&engine, &actor, &grants, &mutation, None, &Attributes::new())?;
let revision = applied.revision.expect("a source was configured"); // "tenant@42"
// hand it to whoever reads next: a header, a cookie, the response of the write
let provider = EngineProvider::new(engine, loader)
.with_cache(cache)
.with_consistency(ConsistencyOptions::default().timeout(Duration::from_secs(1)));
// provider.evaluate_revised(&subject, &scope, Some(&revision)) reloads, or waits for the Change, up to the timeout
```
An instance that is behind reloads, or waits for the `Change`, until the timeout. If it still has not reached the revision, it **denies with its own reason** and never decides from older state:
| Reason | Meaning |
| --- | --- |
| `revision_not_reached` | The instance has not caught up within the timeout. |
| `revision_scope_mismatch` | The token belongs to another data scope. |
| `revision_untracked` | The source cannot tell its own revision. |
| `source_unavailable` | The source could not be read. |
### Over the wire
- **Client protocol (version 2, additive).** `hello` carries `version`, `capabilities` carries the `revision` of the data the set was computed from, `change` carries the write's `revision`, and the client may send `refresh_at_least` with a revision. A scope that cannot be brought that far gets an `error`, never an older set. Over SSE, which has no upstream channel, the client reconnects with `?min_revision=`.
- **Decision server.** `/v1` accepts the token in the `x-strig-min-revision` header on every route, and in the `min_revision` field of `check` and `check/batch`. A source behind it answers `503` with `revision_not_reached` (or `revision_mismatch` for another scope), and answers carry the `revision` they were made from. These refusals do not count against the client's circuit breaker. In Rust: `Client::check_at_least` and `check_batch_at_least`.
### In JavaScript
After a write, give the client the revision the write returned:
```ts title="TypeScript"
import { PermissionClient } from '@the-hades-organization/strig/client';
const client = new PermissionClient({ /* url, scopes, engine */ minRevision: 'tenant@42' });
// or after a write, on a client that is already running:
client.requireRevision('tenant@42'); // every decision denies until the capabilities reach it
client.behind(); // true while it has not
client.revision('org:acme'); // the revision of the last capabilities for that scope
```
React exposes the same state as `useStrigStatus().behind` and `useRequireRevision()`; Angular as `StrigService.status().behind` and `requireRevision()`. See [Frontend](https://strig.vercel.app/docs/integrations/frontend.md).
`RemoteClient` takes `minRevision` in its options, per `check`, or per `checkBatch(requests, { minRevision })`. It sends the header and denies an answer that does not prove the revision, so a server that ignores the header cannot talk the client past it.
---
# Field permissions
URL: https://strig.vercel.app/docs/modeling/field-permissions
*Added in 0.9.0.*
A grant can name the fields of the resource it covers: "`document.edit` only on `title` and `body`". A grant without fields covers the whole resource, exactly as before.
## The decision, field by field
An editor may change `title`, `body` and `status`, except that `status` is frozen:
```rust title="Rust"
let catalog = Catalog::builder()
.target_kinds(["document"])
.permission(PermissionDef::new("document.edit").targets(["document"]).fields(["title", "body", "status"]))
.build()?;
let engine = Engine::builder(catalog).build()?;
let grants = vec![
Grant::allow("edit", SubjectMatcher::role("editor"), "document.edit", TargetSelector::kind("document")),
Grant::deny("freeze", SubjectMatcher::role("editor"), "document.edit", TargetSelector::kind("document"))
.fields(["status"]),
];
let ana = Subject::user("ana").with_role("editor");
let doc = Resource::new("document", "d1");
let ctx = Context::new(&grants);
engine.allowed_fields(&ctx, &ana, "document.edit", &doc); // FieldSet::Only { title, body }
engine.check(&ctx, &Request::new(&ana, "document.edit", &doc).field("title")); // true
engine.check(&ctx, &Request::new(&ana, "document.edit", &doc).field("status")); // false
```
The same in the policy language, where `fields` is a field of `permission` and of `grant` in all three syntaxes:
```blocks title="Blocks"
permission document.edit {
targets = [document]
fields = [title, body, status]
}
grant editors-freeze-status {
effect = deny
subject = role editor
permission = document.edit
target = document
fields = [status]
}
```
In Rules and Actors it is `fields title, body`.
## In JavaScript: mask a response
`engine.allowedFields` answers which fields; `pickAllowed` keeps only those on an object before it leaves your API.
```ts title="TypeScript"
import { pickAllowed } from '@the-hades-organization/strig';
const fields = engine.allowedFields(ctx, { subject, permission: 'document.edit', resource });
// { kind: 'only', fields: ['title', 'body'] }
res.json(pickAllowed(document, fields)); // title and body leave; status does not
```
`kind` is `'all'`, `'all_except'`, `'only'` or `'none'`. Pass `field` in the request to ask about one field: `engine.check(ctx, { subject, permission, resource, field: 'status' })`. In the browser, `PermissionClient.allowedFields(permission, resource)` and `can(permission, resource, field)` decide locally.
## How the pieces combine
- **One field is one decision.** A question about a field uses the same strategy (`MostSpecific`, `DenyOverrides`, `PermitOverrides`, `FirstApplicable`) over the grants that cover that field. A `deny` with fields takes away only those fields; an `allow` with fields gives only those. 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 `deny` with fields blocks it as soon as the strategy would deny any of its fields. So `check` stays safe as a gate: a field-restricted `allow` never opens the resource. `allowed_fields` answers "which fields".
- **`implied_by` carries the fields.** A grant of `document.manage` restricted to `title` gives `document.edit` on `title` only.
- **`depends_on` is judged on the same field.** `document.edit` on `body` needs `document.view` on `body`, 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, and `allowed_fields` can answer `AllExcept` ("everything but `status`"), since it cannot list the rest.
- **It fails closed.** A condition that cannot be evaluated drops an `allow` and keeps a `deny`, field by field. An override that allows gives every field.
- **A policy without fields decides as it always did.**
## See why a field was refused
`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`). In JavaScript: `engine.explainFields(ctx, request)`.
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 and older readers
- `NoEscalation` refuses to hand out a field the actor does not hold, and a whole-resource grant to someone who holds only some fields. `CatalogConformance` validates the fields against the catalog. See [Governance](https://strig.vercel.app/docs/approvals.md).
- 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.
- 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. An older client fails closed.
---
# Decision server
URL: https://strig.vercel.app/docs/integrations/server
`strig-server` answers decisions over HTTP, for services that do not embed the engine.
```rust title="Rust"
let source = Arc::new(MemorySource::new(Snapshot::new(Arc::new(engine), grants)));
let router = DecisionServer::new(source).router();
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
axum::serve(listener, router).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 [`API.md`](https://github.com/The-Hades-Organization/Strig/blob/main/crates/strig-server/API.md).
## Call it from a service
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.
```rust title="Rust"
let config = ClientConfig::default()
.with_timeout(Duration::from_millis(250))
.with_breaker(BreakerConfig::default().with_failure_threshold(5).with_open_for(Duration::from_secs(10)));
let client = Client::http("http://127.0.0.1:8080", config);
let request = CheckRequest::new(Subject::user("alice"), "document.view", Resource::new("document", "d1"));
if client.check(&request).await.is_allowed() {
// serve the document
}
```
## AuthZEN
`with_authzen` also serves the [OpenID AuthZEN Authorization API 1.0](https://openid.net/specs/authorization-api-1_0.html) next to `/v1`, so gateways and platforms that speak the standard query Strig with no adapter.
```rust title="Rust"
let config = AuthzenConfig::default()
.with_issuer("https://pdp.example.com")?
.with_path_resolver(Arc::new(MyOrgTree));
let router = DecisionServer::new(source).with_authzen(config).router();
```
| Route | Purpose |
| --- | --- |
| `POST /access/v1/evaluation` | One decision |
| `POST /access/v1/evaluations` | Several, with the three `evaluations_semantic`s |
| `POST /access/v1/search/subject`, `/action`, `/resource` | Searches (resource needs a `ResourceCatalog`) |
| `GET /.well-known/authzen-configuration` | Discovery (needs an issuer) |
- `subject.properties` become attributes; the `roles` and `principals` properties carry 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`.
What is left out is listed in [`API.md`](https://github.com/The-Hades-Organization/Strig/blob/main/crates/strig-server/API.md#authzen-authorization-api).
## Envoy
With the `envoy` feature (off by default; no `tonic` or `prost` without it), `envoy_service` serves Envoy's External Authorization (`envoy.service.auth.v3.Authorization/Check`, gRPC) over the same source, so a mesh or a gateway built on Envoy asks Strig before it forwards a request.
```rust title="Rust"
let envoy = EnvoyConfig::default()
.with_subject_header("x-user")?
.with_route("GET", "/healthz", RouteRule::public())?
.with_route(
"GET,HEAD",
"/documents/{id}",
RouteRule::require("document.view", ResourceTemplate::new("document", "{id}")),
)?;
let service = DecisionServer::new(source).envoy_service(envoy);
service.serve(TcpListener::bind("127.0.0.1:9191").await?, shutdown).await?;
```
- 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; 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 [`API.md`](https://github.com/The-Hades-Organization/Strig/blob/main/crates/strig-server/API.md#envoy-external-authorization-grpc-feature-envoy) and the sample [`envoy.yaml`](https://github.com/The-Hades-Organization/Strig/blob/main/crates/strig-server/examples/envoy.yaml).
## Where to go next
- Clients that decide locally from the capabilities stream: [JavaScript](https://strig.vercel.app/docs/javascript.md).
- Trace every request: [Observability](https://strig.vercel.app/docs/operations/observability.md).
- Walk through a public API end to end: [Public API guide](https://strig.vercel.app/docs/guides/public-api.md).
---
# Prisma, Drizzle and Kysely
URL: https://strig.vercel.app/docs/integrations/orms
`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 }`.
## Prisma
```ts title="TypeScript"
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 });
```
Prisma needs no peer dependency: the `where` is a plain object.
## Drizzle and Kysely
Drizzle and Kysely are optional peers. Kysely is never imported: its builder arrives as the callback argument.
```ts title="TypeScript"
import { toWhere } from '@the-hades-organization/strig/drizzle';
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();
```
## What the filter guarantees
- **Fails closed.** A kind or attribute the filter reads and the mapping lacks, an expression node with no query form, or a filter for another kind than the mapping's all throw `OrmFilterError`. Nothing becomes "all rows"; what is certainly empty becomes an impossible condition.
| `code` | Cause |
| --- | --- |
| `UNMAPPED_KIND` | The filter reads a kind the mapping lacks |
| `UNMAPPED_ATTRIBUTE` | The filter reads an attribute the mapping lacks |
| `UNSUPPORTED_EXPR` | An expression node with no query form |
| `UNSUPPORTED_VALUE` | A value the query cannot carry |
| `KIND_MISMATCH` | A filter for another kind than the mapping's |
- **A deny reaches only what it names.** Every test is true or false, never `NULL`, so `NOT (project_id = 'p2')` keeps the rows with no project, as `engine.check` does. In Prisma the negation is pushed to the fields: `{ OR: [{ projectId: null }, { projectId: { not: 'p2' } }] }`. A relation that can be absent goes in `optionalRelations`; one left out only costs rows a deny would drop, and 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`. `where` is the upper bound (every row that may be allowed). `settled` is the lower bound (rows allowed whatever the residue says), present only with a residue. Check the rows of `where` outside `settled` with `engine.check`. Without a residue, `where` is exact.
- **One contract.** Each module also exports an object (`prisma`, `drizzle`, `kysely`) with `toWhere(filter, mapping)`, typed over the `PermissionId` from [`strig-types`](https://strig.vercel.app/docs/integrations/frontend.md#catalog-types).
## How it is tested
The unit tests check the object each adapter builds. 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, and compares 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.
## Where to go next
- Filter in Postgres without an ORM: [Postgres](https://strig.vercel.app/docs/storage/postgres.md).
- Use it in an app: [Internal dashboard guide](https://strig.vercel.app/docs/guides/internal-dashboard.md).
---
# React and Angular
URL: https://strig.vercel.app/docs/integrations/frontend
`/react` and `/angular` put the real-time `PermissionClient` (`/client`, see [JavaScript](https://strig.vercel.app/docs/javascript.md)) 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).
## React
```tsx title="React"
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({ url: '/strig/stream', scopes: [project], strig, engine });
permission="document.edit" resource={doc} fallback={ }>
;
const canEdit = useCan('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.
## Angular
```ts title="Angular"
// 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: Edit
canEdit = inject(StrigService).can('document.edit', this.doc); // Signal; arguments may be signals
// routes
{ path: 'doc/:id', canActivate: [strigCanActivate('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. It then decides locally. A timeout or a deny returns `false`, or whatever `onDeny` returns; `onDeny` runs in the injection context, so it can return a `UrlTree`.
## Peer dependencies
React and Angular are optional peers, 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 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.
## Catalog types
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 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: 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 changes only when the catalog does.
```sh title="Shell"
npx strig-types catalog.json -o src/permissions.generated.ts
```
```ts title="TypeScript"
import { generateTypes } from '@the-hades-organization/strig/types'; // same thing, as a function
import type { PermissionId } from './permissions.generated';
const engine = new strig.Engine(spec); // strict: check, explain, list, whoCan... take only the ids
const client = new PermissionClient(/* ... */);
client.can('users:read', resource); // only ids of the union compile; narrow a plain string with isPermissionId first
```
Without the type parameter, any string is accepted.
## Where to go next
- Field-level UI (`pickAllowed`): [Permission by field](https://strig.vercel.app/docs/modeling/field-permissions.md).
- Building the client by hand: [JavaScript](https://strig.vercel.app/docs/javascript.md).
- Filtering lists on the server: [Prisma, Drizzle and Kysely](https://strig.vercel.app/docs/integrations/orms.md).
---
# Python
URL: https://strig.vercel.app/docs/integrations/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`).
```sh title="Shell"
pip install strig-auth
```
## Check and decide
```python title="Python"
import strig
from strig import dsl
spec = dsl.load_project_dir("policies") # or a plain dict: the EngineSpec JSON
engine = strig.Engine(spec)
ctx = strig.Context(grants, tuples=[...], env={"dept": "eng"}, now=1_700_000_000_000)
ctx.add_grant(grant); ctx.remove_grant("g1"); ctx.set_now(None)
request = {"subject": {"kind": "user", "id": "ana"}, "permission": "project.edit",
"resource": strig.scope_from_string("project:p1/org:o1")}
engine.check(ctx, request) # bool
engine.decide(ctx, request) # {"effect": "allow", "matched": [...], "reason": {...}}
engine.explain(ctx, request) # the trace
engine.check_many(ctx, [request, other], now=1_700_000_000_000)
engine.list(ctx, subject, "project.view", "project")
engine.who_can(ctx, "project.view")
```
## Change grants under the invariants
```python title="Python"
result = engine.apply({"actor": actor, "current": grants, "mutation": {"add": grant},
"invariants": [{"kind": "custom", "name": "role_in_use"}],
"audit": {"level": "forensic", "failMode": "open"}})
```
## Rules to know
- **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`, a `set`, a non-text key, an int over 64 bits) is refused with `INVALID_ARGUMENT`; nothing is coerced.
- **Errors are exceptions with a `code`.** A failed call raises `strig.StrigError` with `.code` equal to the `errorCode` of the JavaScript binding (`INVALID_INPUT`, `INVALID_ARGUMENT`, `UNKNOWN_SUBJECT`, `REENTRANT_CALL`, ...). Match on the code, not on the message. The policy language raises `strig.DslError` (a `StrigError`) with `.diagnostics`.
- **Time is explicit.** Every method that decides takes an optional `now` (ms UTC) that wins over `ctx.set_now`. Without one, the engine fails closed on validity windows. The system clock is used only by `apply`/`propose` for the audit record and by `Exclusive` when `now` is omitted.
## Rules written in Python
```python title="Python"
engine = strig.Engine(
spec,
conditions={...},
overrides=[{"name": ..., "except": [...], "evaluate": fn}],
invariants={...},
audit_sink=fn, audit_redact=fn, on_audit_drop=fn, audit_policy={...},
)
```
These 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 answers `denied`, an invariant that raises refuses with its message.
- A coroutine is a wrong answer.
- A callback that calls the engine or changes a `Context` gets `REENTRANT_CALL`.
- The GIL stays held during a call, so a callback runs on the thread that is deciding.
## Helpers
`strig.Exclusive(...)`, `strig.verify_audit_chain(records, anchors)` and `strig.audit_estimate(level, records)` mirror the JavaScript ones. `strig.dsl` has `compile`, `print`, `convert`, `format`, `is_formatted`, `load_project` and `load_project_dir`. Governance flows are `engine.impact`, `engine.review_impact`, `engine.elevate` and `engine.recertify`.
To build it from the repository: `pip install maturin && cd crates/strig-python && maturin develop && pytest`.
## Where to go next
- The policy files you load: [Policy language](https://strig.vercel.app/docs/policy-language.md).
- Audit sinks and verification: [Audit](https://strig.vercel.app/docs/audit.md).
---
# Go
URL: https://strig.vercel.app/docs/integrations/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](https://wazero.io), pure Go with no cgo, and the module is embedded with `go:embed`. Go 1.22 or later.
```sh title="Shell"
go get github.com/The-Hades-Organization/Strig/bindings/go@v0.10.0
```
## Check and decide
```go title="Go"
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{"grants": grants, "env": map[string]any{"dept": "eng"}})
ctx.AddGrant(grant); ctx.RemoveGrant("g1")
request := map[string]any{"subject": subject, "permission": "project.edit", "resource": resource}
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{request, other})
policy, err := strig.Compile(text) // the policy language, no engine needed
```
## Rules to know
- **Same JSON, same codes.** Requests and results are the JSON of the JavaScript API with the same camelCase fields. A failure is a `*strig.Error` whose `Code` is the `errorCode` of the JavaScript binding (`INVALID_INPUT`, `UNKNOWN_SUBJECT`, `DSL_PARSE`, ...), with `Diagnostics` for the policy language. Use `strig.CodeOf(err)` or `errors.As`.
- **Fails closed.** `Check` returns `false` with the error, never `true`. If the module traps, the instance is discarded and every later call returns `strig.ErrBroken`. A closed engine or context, or a context of another engine, is an error.
- **Concurrency.** An `Engine` is safe for concurrent use, but one WebAssembly instance is single-threaded, so calls are serialized. For parallel throughput give each worker its own `engine.Fork()` (its own instance, same spec, no shared state). A `Context` belongs to the engine that made it.
- **Time is explicit.** `WithNow(t)` or `ctx.SetNow(t)` set the instant; without one the engine fails closed on validity windows. `Apply`, `Propose`, `Resolve` and `Expire` take the host clock when the input has no `now`.
## Not in this binding yet
Callbacks (the `call` condition, overrides, invariants written in Go), the audit sink and exclusive resources. A spec that needs a callback fails closed.
## Other hosts
The `.wasm` is also a release asset (`strig-.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 ./...`.
## Where to go next
- Run decisions as a service instead: [Decision server](https://strig.vercel.app/docs/integrations/server.md).
- The JVM sibling: [Java and Kotlin](https://strig.vercel.app/docs/integrations/jvm.md).
---
# Java and Kotlin
URL: https://strig.vercel.app/docs/integrations/jvm
`io.github.the-hades-organization:strig` is the JVM binding: the same WebAssembly module as the [Go binding](https://strig.vercel.app/docs/integrations/go.md), run on [Chicory](https://github.com/dylibso/chicory) (pure JVM, no native code), with the same JSON `EngineSpec`. Java 17 or later; Kotlin uses the same classes.
```xml title="pom.xml"
io.github.the-hades-organization
strig
${strig.version}
```
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`.
## Check and decide
```java title="Java"
import io.github.thehadesorganization.strig.*;
try (Engine engine = new Engine(spec); // spec: a Map, a record or a JsonNode
Context ctx = engine.newContext(Map.of("grants", grants))) {
ctx.addGrant(grant);
boolean allowed = engine.check(ctx, request); // an exception is never an allow
Decision decision = engine.decide(ctx, request, Instant.now());
Map explanation = engine.explain(ctx, request);
List many = engine.checkMany(ctx, List.of(request, other));
} catch (StrigException e) {
e.code(); // INVALID_INPUT, UNKNOWN_SUBJECT, DSL_PARSE, ...
}
Map policy = Strig.compile(text); // the policy language, no engine needed
```
```kotlin title="Kotlin"
Engine(spec).use { engine ->
engine.newContext(mapOf("grants" to grants)).use { ctx -> engine.check(ctx, request) }
}
```
## Rules to know
- **Same JSON, same codes.** `StrigException.code()` is the `errorCode` of the JavaScript binding; `diagnostics()` carries the policy-language positions.
- **Fails closed.** `check` throws instead of returning `true` when it cannot decide. A trapped instance is discarded and every later call throws `INTERNAL`.
- **Concurrency.** An `Engine` is safe for concurrent use with serialized calls; give each worker `engine.fork()` for parallel throughput. A `Context` belongs 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 `call` condition, overrides, invariants written in Java), the audit sink and exclusive resources.
## Where to go next
- Run decisions as a service instead: [Decision server](https://strig.vercel.app/docs/integrations/server.md).
- Check the codes you will match on: [Reference](https://strig.vercel.app/docs/reference.md).
---
# Impact before apply
URL: https://strig.vercel.app/docs/governance/impact
*Added in 0.10.0.*
`Governance::apply` says whether a change passes the invariants. It does not say what the change does to access. `impact` answers that without applying anything: it judges the change as `apply` does (a refused change returns its violations), then asks the same questions over the grants before and after.
## Ask what a change does
```ts title="TypeScript"
const preview = engine.impact({
actor: ana,
current: grants,
mutation: { add: grant },
impact: { source: { kind: 'sample', subjects: [bob], resources: [project] } },
});
if (preview.ok) {
console.log(preview.impact.gained); // AccessChange[]: who gains, which permission, on which resource
console.log(preview.impact.lost);
console.log(preview.impact.indeterminate);
console.log(preview.impact.partial);
}
```
`preview.ok` is `false` when the invariants refuse the change, with `violations`. An entry of `gained` has this shape:
```json title="AccessChange"
{ "subject": "user:bob", "permission": "project.edit", "resource": { "path": [{ "kind": "project", "id": "p1" }] }, "before": "denied", "after": "allowed" }
```
`subject` reads `user:bob`, `role:editor` or `anyone`; `before` and `after` are `allowed`, `denied` or `indeterminate`.
In Rust:
```rust title="Rust"
let options = ImpactOptions::new(ImpactSource::sample(
SampleSpec::new().subject(bob).resource(project),
)); // or ImpactSource::derived()
let impact = governance.impact(&engine, &ana, ¤t, &Mutation::Add(grant), &options)?;
for change in &impact.gained { /* change.subject, change.permission, change.resource */ }
```
## Where the questions come from
| Source | What it asks |
| --- | --- |
| **Sample** (`kind: 'sample'`) | Yours: subjects × resources × permissions (and fields). Leave resources or permissions empty and they are the ones the change reaches and touches. |
| **Derived** (`ImpactSource::derived()`) | The reverse queries (`who_can_on`, `list`, `access_of`), restricted to the permissions the change touches, plus the ones that imply them (`implied_by`) and the ones that depend on them (`depends_on`). |
A deny that cuts, an override and a field count as they do in `check`. `ImpactOptions` takes the tuples, the `env`, the `QueryLimits` and an instant.
## Read the answer carefully
- **`partial` is `true` when a limit cut the work**, and `notes` says which limit. Absence from the list is then not proof.
- **`indeterminate` holds what could not be settled**: a condition or an override that cannot be evaluated. It never counts as a gain. A change is a gain only when the answer was a certain deny and is now an allow.
- **`separation`** lists the separation-of-duties clashes the change would create, whether or not the invariant is on. See [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md).
## Apply and keep the impact
- `Governance::apply_with_impact` applies the change and returns the grants with the impact. With an auditor at `detailed` or `forensic`, the audit record carries `impact`: counts and up to 10 examples. See the [audit format](https://strig.vercel.app/docs/audit.md).
- `Approvals::with_impact(&options)` stores the impact in the pending request when it is proposed. When the approver decides, `approve` recomputes it over the grants of that moment, and `Approved::proposed_impact` keeps the first one.
- `review_impact` shows the approver both impacts and whether they differ, before they decide:
```ts title="TypeScript"
const review = await flow.reviewImpact('req-1', grants);
```
The JSON store keeps the request whole, so existing stores open unchanged. In Python it is `engine.impact` and `engine.review_impact`; in Go and the JVM, `Impact` and `ReviewImpact`.
---
# Temporary elevation and break-glass
URL: https://strig.vercel.app/docs/governance/elevation
*Added in 0.10.0.*
Ana needs `project.edit` on `p1` for an incident. She asks for two hours, Caio approves, and the grant disappears on its own.
```rust title="Rust"
let target = ElevationTarget::permission("project.edit", TargetSelector::exact("project", "p1")).scoped(org());
let policy = ElevationPolicy::new().with(
ElevationRule::new(target.key(), 4 * HOUR, "org.approve", org_resource)
.requiring_justification()
.allowing_break_glass(HOUR), // never longer than the rule's own maximum
);
let flow = Elevations::new(&governance, &policy, &store); // + .with_impact(&options)
// Ana asks; it waits for an approver.
let Elevated::Pending(request) = flow.request(&review, &ElevationRequest::new("e1", ana, target, 2 * HOUR).justified("incident 42"), None)? else { unreachable!() };
// Caio approves: the window is [approval, approval + 2h), never past the maximum.
let approved = flow.approve(&review, &caio, "e1")?; // persist approved.grants
flow.revoke(&review, &ana, "e1", Some("done"))?; // early, by the actor or by an approver
```
The policy lists, per role or permission, the longest window, who approves, whether a justification is required and whether break-glass is allowed. A role or permission the policy does not list is refused.
## The same flow in JavaScript
`Elevations` is in `@the-hades-organization/strig/approvals`. It keeps requests in a `PendingStore` that has `annotate` (`MemoryPendingStore` and `JsonFileStore.pendingStore` do).
```js title="JavaScript"
const flow = new Elevations(engine, store.pendingStore, {
elevation: [{ key: { permission: 'project.edit' }, maxDurationMs: 4 * HOUR, approverPermission: 'org.approve', approverResource: orgResource, requireJustification: true, breakGlass: { maxDurationMs: HOUR } }],
invariants,
audit: { level: 'forensic' },
});
await flow.request({ id: 'e1', actor: ana, target, durationMs: 2 * HOUR, justification: 'incident 42' }, grants);
await flow.approve('e1', caio, grants, { persist: (r) => saveGrants(r.grants) });
await flow.revoke('e1', ana, grants, { reason: 'done', persist: (r) => saveGrants(r.grants) });
await flow.closeReview('e2', caio, 'legitimate use', grants); // after a break-glass
```
`engine.elevate(input)` is also in Python and in the Wasm ABI (`elevate`).
## What approval does
- The elevation becomes an allow grant `elevation:`, or a role assignment with `valid_from` and `valid_until`. The engine drops it at the instant; nothing has to run.
- The author never approves their own request. The invariants run again over `current`, and the impact (`with_impact`) is stored in the request, as for any change. See [Impact before apply](https://strig.vercel.app/docs/governance/impact.md).
- A duration over the maximum, a missing justification and a target the policy does not list are refused when asked.
- A policy tightened after the request refuses an approval that would go past the new maximum.
## Break-glass
`ElevationRequest::break_glass()` works only where the rule has `allowing_break_glass`, with its own, shorter maximum and a justification.
- The actor approves it themselves: it is in force at once, marked `break_glass`, with a review `pending`.
- It needs an auditor at `forensic`. Its records are written with `FailMode::Closed` whatever the call, the permission or the auditor say: if the sink fails, the elevation is denied.
- Another actor who holds the approver permission closes the review with `close_review`, which writes an `elevation_review` record (also forensic and closed). `pending_reviews()` lists what is open. The actor cannot close their own.
## Revoke, renew, list
`revoke` takes the grant or the role back through the governance and keeps the `Revocation` in the request. Renewing is a new request. `Elevations::active(now)` lists what is in force.
## Where it is kept
The elevation is the `elevation` field of the `PendingRequest`, so the stores need no schema change. A decided request is annotated with the revocation or the review through `PendingStore::annotate`; implement it in your own store, because the default refuses. See [Approvals](https://strig.vercel.app/docs/approvals.md) for the stores.
In `strig-sync`, `hub.elevation_approved(&request, now)` publishes the `Change` and schedules the expiry notice at `valid_until`; `hub.elevation_revoked(&request)` publishes the revocation.
## Choices to know
- Revocation is judged by the invariants as the one who revokes, so an invariant such as `NoSelfManagement` can refuse a self-revocation.
- A request for a target the policy does not list is an attempt to escalate. It is refused with the violation `not_in_policy` and audited (`mutation_propose`, outcome `rejected`, `refusal: not_in_policy` in the metadata) at the auditor's level. A failing sink in `closed` mode turns it into an `audit` refusal.
- A refused `revoke` on a request that is not an elevation, not approved, already revoked or already over leaves no record.
- `annotate` runs after the grant was applied. If it fails, the grant is already gone and the request lacks the mark, so keep the grants the call returned.
---
# Separation of duties
URL: https://strig.vercel.app/docs/governance/separation-of-duties
*Added in 0.10.0.*
Whoever creates a payment does not approve it, and nobody is both `maker` and `checker` in the same org. Both rules live in the catalog.
```rust title="Rust"
let catalog = Catalog::builder()
.target_kinds(["org", "payment"])
.permission(PermissionDef::new("payment.create").targets(["payment"]))
.permission(PermissionDef::new("payment.approve").targets(["payment"]))
// static: nobody holds both roles inside the same org
.mutually_exclusive(MutualExclusion::new("payment_duties", ExclusiveKind::Roles, ["maker", "checker"]).per_anchor("org"))
// dynamic: whoever created a payment does not approve it
.conflicting_actions(ActionConflict::new("four_eyes", ["payment.create"], ["payment.approve"]))
.build()?;
let governance = Governance::new().with(SeparationOfDuties::new());
```
## Static: what nobody holds together
A `mutually_exclusive` set lists roles or permissions, with a name and a scope: global, or `per_anchor("org")` to clash only inside the same anchor.
The `SeparationOfDuties` invariant refuses a change that would create an accumulation that did not exist. It sees every way a member is reached: a direct role, an inherited one (`RoleGraph`), a grant or a temporary elevation. The `Violation` names the set and both sides.
- Removing and revoking never create a clash, so a set that is already violated can always be repaired. A `deny` is never read as taking a member away.
- `with_subjects` adds subjects whose holdings an added grant is also judged against.
- `Impact` lists the clashes a change would create in `separation`, whether or not the invariant is on. See [Impact before apply](https://strig.vercel.app/docs/governance/impact.md).
- `strig lint` reports the sets already violated (`L009`). See [Diff and lint](https://strig.vercel.app/docs/tools/diff-lint.md).
## Dynamic: what nobody does twice
A `conflicting_actions` rule says that whoever did a `first` action on a resource does not do a `then` action on it. The engine evaluates it on every decision, before the overrides, with no IO.
The history is an attribute of the resource (`history` by default, or the one the rule names) or of `env`: a list of `":"` entries.
```json title="resource attributes"
{ "history": ["payment.create:ana"] }
```
Ana asks for `payment.approve` on that resource and the denial reads `Reason::Override`, named `separation:four_eyes`.
- With `distinct_roles`, an entry also carries the roles the author acted with (`"payment.create:ana|maker"`), and a subject who holds one of them is refused too.
- An entry with no roles refuses, and so does a history that cannot be read: the rule fails closed.
- A listing or a reverse query never lets the rule open anything. For a permission in `then` the answer stays a residue.
## In an approval flow
`Approvals::with_distinct_roles()` also refuses an approver who shares a role with the author, on top of the rule that the author never approves their own request. See [Approvals](https://strig.vercel.app/docs/approvals.md).
## In the policy language
It is `mutually_exclusive` and `conflicting_actions` in the catalog and the `separation_of_duties` invariant. A policy that uses them exports `"schema": 5`. See the [policy language](https://strig.vercel.app/docs/policy-language.md).
## Other catalog rules
Some rules belong to one permission, so they sit 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 not a way to give someone a stronger role than your own.
```rust title="Rust"
let catalog = Catalog::builder()
.target_kind("project")
.permission(PermissionDef::new("project.view").targets(["project"]))
.permission(PermissionDef::new("project.edit").targets(["project"]).depends_on(["project.view"]))
.permission(PermissionDef::new("project.share").targets(["project"]).non_delegable())
.permission(PermissionDef::new("project.purge").targets(["project"]).override_only())
.build()?;
let engine = Engine::builder(catalog).build()?;
let governance = Governance::new()
.with(CatalogConformance)
.with(Prerequisites)
.with(NoEscalation::new());
// `lead` holds `project.edit` only, so handing out `project.view` is an escalation.
let current = vec![Grant::allow("l", SubjectMatcher::user("lead"), "project.edit", TargetSelector::kind("project"))];
let handout = Mutation::Add(Grant::allow("a", SubjectMatcher::user("ana"), "project.view", TargetSelector::kind("project")));
let refused = governance.apply(&engine, &Subject::user("lead"), ¤t, &handout, None).unwrap_err();
assert_eq!(refused[0].invariant, "no_escalation");
```
Two more tools:
- **Lockout reserve.** `NoLockout::with_reserve` names who should take over a critical permission. When a change would leave it with no holder, the `Violation` carries a `Suggestion` with the role assignment that fixes it. Nothing is applied; the suggestion is also written to the audit record.
- **Role templates.** `RoleTemplate::materialize` turns a template into ordinary grants. The template id and version go into the change metadata; the grants keep no link to the template.
---
# Access recertification
URL: https://strig.vercel.app/docs/governance/recertification
*Added in 0.10.0.*
A campaign (ISO 27001, SOX) has someone review, before a deadline, every grant and role assignment inside a scope, and expires what nobody renewed. Nothing here does IO: the caller supplies the instant and persists the grants.
```rust title="Rust"
let spec = CampaignSpec::new("2026-q4", ReviewerRule::permission("org.manage", org_resource), "org.manage", org_resource, due_at, 90 * DAY)
.scoped(RecertScope::new().anchored(org_anchor).permissions(["project.edit"]))
.routed(ReviewerRoute::for_role("admin", ReviewerRule::role("ciso")))
.defaulting_to(DefaultAction::Expire); // or Flag, or Escalate (with .escalating_to(rule))
let flow = Recertifications::new(&governance, &store); // + .with_impact(&options)
let campaign = flow.open(&review, &opener, spec, &people)?; // one item per allow grant and role assignment in scope
flow.decide(&review, &bia, "2026-q4", "grant:ana-edit", RecertDecision::Keep, None)?;
let revoked = flow.decide(&review, &bia, "2026-q4", "grant:caio-edit", RecertDecision::Revoke, Some("left the team"))?; // persist revoked.grants
flow.decide(&review, &bia, "2026-q4", "grant:dan-edit", RecertDecision::Delegate { to: carl }, Some("carl owns it"))?;
let closed = flow.close(&review, &bia, "2026-q4")?; // from the deadline on: the default action over what nobody reviewed
```
## The same campaign in JavaScript
`Recertifications` is in `@the-hades-organization/strig/approvals`. `engine.recertify(input)` is also in Python and in the Wasm ABI (`recertify`).
```js title="JavaScript"
const flow = new Recertifications(engine, store.recertStore, { invariants, audit: { level: 'forensic' } });
await flow.open({ id: '2026-q4', reviewer: { kind: 'permission', permission: 'org.manage', resource: orgResource }, reviewerPermission: 'org.manage', reviewerResource: orgResource, dueAt, keepPeriodMs: 90 * DAY, scope: { permissions: ['project.edit'] } }, opener, people, grants);
await flow.decide('2026-q4', 'grant:ana-edit', { action: 'keep' }, bia, grants);
await flow.decide('2026-q4', 'grant:caio-edit', { action: 'revoke' }, bia, grants, { reason: 'left the team', persist: (r) => saveGrants(r.grants) });
await flow.close('2026-q4', bia, grants, { persist: (r) => saveGrants(r.grants) }); // from the deadline on
```
## The campaign
A campaign fixes:
- the scope: an anchor, permissions, roles, subject kinds;
- the reviewer: whoever holds a permission on a resource, a role, or one declared subject, with `ReviewerRoute`s that send a permission or role to another rule;
- the deadline, the period a kept item stays certified, and the default action.
Opening is refused when the opener is anonymous, the deadline is not in the future, the period is zero, an escalation default has no reviewer, or nothing falls in the scope. With `with_impact`, each item carries what revoking it would take from others. See [Impact before apply](https://strig.vercel.app/docs/governance/impact.md).
## Decisions
| Decision | Effect |
| --- | --- |
| `Keep` | Certifies the access for the period. The grant is not changed: the certification is the item. |
| `Revoke` | Becomes a `Mutation` (`Remove` or `RevokeRole`) through the governance with the reviewer as actor, so the invariants and the audit apply. Persist the `grants` and `revoked_role` it returns. |
| `Delegate` | Hands the item to someone who holds the reviewer permission, with a reason. |
The reviewer needs the campaign's permission and never reviews their own access. [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md) applies to them: a reviewer who has a clash is refused. Nobody decides from the deadline on.
## Closing
From `due_at`, `close` runs the default action over the items nobody reviewed:
- `Expire` revokes them through the governance. An item the governance refuses to expire is `Flagged`, with the reason.
- `Flag` leaves them marked.
- `Escalate` hands them to another reviewer rule.
Flagged and escalated items stay in the report as `unresolved`. `Campaign::report()` counts the campaign by outcome and by reviewer.
## Audit
Opening, each decision and the closing are `recert_open`, `recert_decide` and `recert_close` records, with the campaign, item, decision and target in the `recert` field. See the [audit format](https://strig.vercel.app/docs/audit.md).
## Where it is kept
`RecertStore` is `MemoryRecertStore`, `PgRecertStore` (`strig-postgres`; migration 5 adds `strig_recert`) or `JsonFileStore.recertStore` in JavaScript. See [Postgres](https://strig.vercel.app/docs/storage/postgres.md).
A write carries the campaign's `revision`, and a stale write is refused, so two reviewers of the same campaign do not overwrite each other. A host with several processes also serialises per campaign before it applies the grants.
---
# Why not?
URL: https://strig.vercel.app/docs/governance/why-not
*Added in 0.10.0.*
`explain` says why a decision came out as it did. When that decision is a denial, `why_not` adds what would turn it into an `allow`: the smallest changes, smallest and most specific first. It returns nothing when the request is already allowed.
## Ask
```ts title="TypeScript"
const answer = engine.whyNot(ctx, {
subject: { kind: 'user', id: 'bruno' },
permission: 'org.settings',
resource: scopeFromString('org:acme'),
});
```
Bruno is a member of `org:acme`, and only admins reach the org settings. The answer, with the grant abridged:
```json title="Example result"
{
"cause": { "kind": "no_applicable_grant" },
"remedies": [
{ "kind": "assign_role", "role": "admin", "scope": { "kind": "org", "id": "acme" }, "rank": 0, "caveats": ["affects_others"] },
{ "kind": "add_grant", "grant": { "id": "…", "effect": "allow", "permission": "org.settings" }, "rank": 0 }
]
}
```
`cause` is what denied it. `remedies` are the changes that fix it. The shape is typed as `Remedies` in `index.d.ts`; the exact fields of each remedy differ by kind.
In Rust:
```rust title="Rust"
let answer = engine.why_not(&ctx, &request, &WhyNotOptions::default()).expect("denied");
println!("{:?}", answer.cause);
for remedy in &answer.remedies {
println!("{:?} {:?}", remedy.change, remedy.caveats);
}
```
In Python: `engine.why_not(ctx, request, now=None, options=None)`. The Wasm ABI has the `whyNot` operation, and `strig-inspect explain` prints the remedies after a denial.
## Causes
| Cause | Meaning |
| --- | --- |
| `no_applicable_grant` | Nothing allows it. |
| `deny` | A `deny` grant decided; it names the grant, the permission and the target. |
| `override` | An override ruled before the grants (a suspended account, for example). |
| `unknown_permission` | The permission is not in the catalog. |
| `override_only_permission` | The permission is `override_only`, so only an override can allow it. |
| `missing_prerequisite` | A `depends_on` permission is missing. The cause says which, with the cause of the prerequisite, and the remedies are for the prerequisite. |
## Remedies
| Change | Meaning |
| --- | --- |
| `satisfy_condition` | An otherwise applicable `allow` has a condition that failed (`failed`, with the values the engine saw) or could not be evaluated (`unresolved`, a missing attribute for example). No value is invented: it names what has to hold. |
| `add_grant` | An `allow` for the subject on the most specific step of the path, checked with `validate_grant`, so it respects the catalog's `targets` and `fields`. A field question asks for that field only. The grant `id` is a placeholder. |
| `narrow_deny` | Take the asked field out of the `fields` of the `deny` that decided. |
| `assign_role` | A role that has an applicable `allow`, scoped to the narrowest step of the path. |
| `remove_deny` | Remove the `deny` that decided. |
## What you can trust
**Every remedy is verified.** The engine applies it alone to a copy of the subject or of the grants and decides the request again. Only a change that comes out as `allow` is returned, so a suggestion that would not work (a role blocked by a deny, a grant a `DenyOverrides` strategy still beats) does not appear. Nothing is written.
- A denial by an **override** comes back with no remedy: no change of grants or roles undoes it. The same goes for `unknown_permission` and `override_only_permission`.
- Each remedy carries `caveats` for the governance the catalog knows (`management_only`, `non_delegable`, `override_only`) and `affects_others` when the change edits a grant that is not the subject's own. The invariants of a `Governance` are not consulted, so the change may still be refused when you apply it.
- Grants of other subjects are never listed: only the `deny` that decided is named, and only a role's `allow` is used to suggest that role.
- Changes are single. A denial that needs two changes at once (an allow that is also beaten by a deny) shows the deny's removal only if that alone is enough.
## Bound the work
`options = { maxDecisions, maxRemedies }` caps the verifications and the list (16 remedies by default). The engine has no clock, so the bound on work is a count, as in the reverse queries; the limits of the `Context` apply by default. When either cuts the answer, `partial` is `true`: there may be more.
To check a remedy against the invariants before you offer it, run it through [`impact`](https://strig.vercel.app/docs/governance/impact.md), which judges it as `apply` does.
---
# Approvals
URL: https://strig.vercel.app/docs/approvals
*Added in 0.7.0.*
A change the policy marks as needing approval does not apply on the spot. It waits as a **pending request**, and another actor approves or refuses it. The policy is per kind of change and names who approves.
The kinds are `add`, `remove`, `assign_role` and `revoke_role`. A kind with no rule applies at once, as it always did, so a governance nobody wraps in `Approvals` behaves as before.
## How a request lives
1. **Propose.** The author proposes a change. The invariants judge it, and if they accept and the policy asks for approval, it is kept as a request: id, author, change, instant and an optional expiry. If they refuse, nothing is kept.
2. **Approve or reject.** An approver decides. The author never decides their own request, and the approver must hold the permission the policy names, on the resource it names.
3. **Apply.** An approval runs the invariants again over the grants as they are now, as the author, before it applies. If they now refuse, the request stays pending.
4. **Expire.** A request with an expiry that has come can no longer be decided. `expire` closes the ones that are due.
A request ends in one of three states: `approved`, `rejected` (with a reason) or `expired`.
> **Note**
>
> Not covered: several approvers (a quorum) and the author withdrawing their own request.
## In JavaScript
The engine judges and audits each step. `Approvals` keeps the requests and chains the audit records.
```js title="JavaScript"
import { Approvals, MemoryPendingStore } from '@the-hades-organization/strig/approvals';
const flow = new Approvals(engine, new MemoryPendingStore(), {
approval: [{ kind: 'add', permission: 'org.approve', resource: orgResource }],
invariants,
});
// Ana proposes; the request is kept and expires in an hour.
const proposed = await flow.propose(ana, { add: grant }, grants, { id: 'req-1', expiresAt: Date.now() + 3_600_000 });
// Caio approves. `persist` runs before the request is marked approved.
const done = await flow.approve('req-1', caio, grants, { persist: (r) => saveGrants(r.grants) });
await flow.reject('req-2', caio, 'outside the change window', grants);
await flow.expire();
```
`approval` is a list of rules: `{ kind, permission, resource }` says that a change of that kind needs an approver who holds `permission` on `resource`. `propose` takes the author, the change in the shape `apply` takes, the grants as they are now, and `id`, `expiresAt`, `now`, `meta` and `tuples` as options. `pending()` lists the requests still waiting.
What a call answers:
| Call | Answer |
| --- | --- |
| `propose` | `{ ok: true, applied: true, grants }` when the kind needs no approval and the change went through. `{ ok: true, applied: false, request }` when it waits. `{ ok: false, code: 'REFUSED', violations }` when the invariants refused it. |
| `approve`, `reject` | `{ ok: true, request, grants? }` when decided. `REFUSED` when the approver is the author, lacks the permission, or the invariants now refuse; the request stays pending. `EXPIRED` when its time came; the request is closed. `NOT_PENDING` when it was already decided. |
| `expire` | `{ ok: true, expired }` with the requests it closed. |
`persist` is where you save what the approval produced, the grants and, for a role change, the subject. A throw there leaves the request pending, so a failed write never leaves a request marked approved over grants you did not store.
`propose`, `resolve` and `expire` also exist on `Engine` itself. They judge and audit but store nothing, so you keep the `request` yourself. `Approvals` is the version that does.
### Where the requests are kept
`MemoryPendingStore` keeps them in memory. For a store of your own, implement `PendingStore`: `get`, `put` (refuses a taken id), `update` (refuses a request that is no longer pending) and `list`. Errors are `PendingStoreError` with `PENDING_DUPLICATE`, `PENDING_UNKNOWN` or `PENDING_NOT_PENDING`.
`JsonFileStore` keeps the requests in the same file as the grants (see [JavaScript](https://strig.vercel.app/docs/javascript.md#grants-and-roles-in-a-json-file)). `store.approvePending` persists the grants before it marks the request approved.
```js title="JavaScript"
import { openJsonStore } from '@the-hades-organization/strig/store';
const store = await openJsonStore({ path: './strig.json', createIfMissing: true });
const flow = new Approvals(engine, store.pendingStore, { approval, invariants });
await flow.propose(ana, { add: grant }, store.grants(), { id: 'req-1' });
await store.approvePending(flow, 'req-1', caio);
```
A file without a `pending` list reads as before, and the store version stays 1. If several processes or versions share one store file, upgrade all of them before the first request is proposed.
## In Rust
```rust title="Rust"
let policy = ApprovalPolicy::new()
.require(MutationKind::Add, "org.approve", org_resource.clone())
.require(MutationKind::AssignRole, "org.approve", org_resource);
let store = MemoryPendingStore::new();
let flow = Approvals::new(&governance, &policy, &store);
let review = Review { engine: &engine, current: ¤t, tuples: None, now, meta: &request_meta };
// Ana proposes; the invariants judge it and, if they accept, it is kept (expires in an hour).
let Proposed::Pending(request) = flow.propose(&review, &ana, &Mutation::Add(grant), "req-1", Some(now + 3_600_000))? else {
unreachable!("the policy covers Add");
};
// Caio approves: he needs `org.approve`, he is not Ana, and the invariants run again over `current`.
let approved = flow.approve(&review, &caio, &request.id)?;
// 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. `expire_due(now, &meta)` closes the requests whose expiry came, and approving a due request closes it too.
The crate keeps no clock and no database: pass the instant, and serialise approvals of one request when several processes share a store. Requests live behind the `PendingStore` trait, with `MemoryPendingStore` in memory.
## What the approver sees
*Added in 0.10.0.*
With `impact` set, `propose` keeps the [impact](https://strig.vercel.app/docs/governance/impact.md) of the change in the request, and `reviewImpact` hands the approver both numbers before they decide:
```js title="JavaScript"
const flow = new Approvals(engine, store, { approval, invariants, impact: { limits: { maxParties: 1000 } } });
await flow.propose(ana, { add: grant }, grants, { id: 'req-1' });
const review = await flow.reviewImpact('req-1', grants);
// { proposed: { gained, lost, … }, current: { gained, lost, … }, changed: false }
```
`proposed` is what the change would do when Ana proposed it. `current` is what it would do over the grants today. `changed: true` means the grants moved in between, so the approver is judging something different from what was asked. Nothing is recorded by the call. `approve` recomputes the impact the same way and returns the one from the proposal as `proposedImpact`.
In Rust, `Approvals::with_impact` and `Approvals::review_impact` do the same, and `Approved::proposed_impact` carries the proposed one. Stores keep the request whole, so the Postgres store and the JSON store need no migration, and a request from before reads as without impact.
## Distinct roles
*Added in 0.10.0.*
By default only the person is compared: the author cannot approve their own request. `Approvals::with_distinct_roles` also refuses an approver who holds a role, directly or by inheritance, that the author holds on the resource the policy names.
```rust title="Rust"
let flow = Approvals::new(&governance, &policy, &store).with_distinct_roles();
// Ana and Caio are both `finance-editor`: Caio's approval is refused.
```
The refusal is an `ApprovalError::Refused` with the violation `distinct_approver_roles`, and the request stays pending. The same idea applies to actions in a policy: see [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md).
A change that grants a break-glass or time-limited role goes through [Temporary elevation](https://strig.vercel.app/docs/governance/elevation.md), which reuses this flow, and a periodic review of who still needs a grant is [Recertification](https://strig.vercel.app/docs/governance/recertification.md).
## What the audit records
Every step is audited, under the fail mode of the call. With an auditor on the governance, each step becomes a record of one of four actions, and the approval record is written before the change is applied.
| Action | `actor` | `outcome` |
| --- | --- | --- |
| `mutation_propose` | the author | `pending` when the request was kept, `rejected` when the invariants or the audit refused it |
| `mutation_approve` | the approver | `applied` when the change then went through, `rejected` when the approver was the author, lacked the permission, or the invariants now refuse it |
| `mutation_reject` | the approver | `applied` when the request was refused, `rejected` when the attempt was refused |
| `mutation_expire` | `strig-expiry` | `applied` |
`object` is the request id. A `pending` field names the request: its `author`, the `kind` of the change, its `target` (a grant id, or `role@subject`), the optional `expires_at` and, on a refusal by an approver, the `reason`.
An approval writes `mutation_approve` first and then the `grant_add`, `grant_remove` or `role_*` record of the change itself. That record has the author as `actor`, the approver in `meta.approved_by` and the request id in `meta.request_id`. A request whose approval record exists and whose change record does not was never applied.
The new values are additive: records and files written before read unchanged. See [Audit](https://strig.vercel.app/docs/audit.md) for the chain, and [Upgrading](https://strig.vercel.app/docs/upgrading.md#070) for what a Rust `match` on `AuditAction` and `AuditOutcome` needs.
---
# Testing a policy
URL: https://strig.vercel.app/docs/tools/testing
*Added in 0.10.0.*
Tests sit beside the policy, in `*.strig-test.json` files. `examples/policy-tests/` in the repository is a project that passes:
```sh title="Shell"
cargo install strig-cli --locked
strig test examples/policy-tests/
```
```text title="Output"
./workspace.strig-test.json
PASS an admin reaches the org settings
PASS a member does not
PASS a member reads a project
PASS a member writes during working hours in Sao Paulo
PASS and not at night
PASS without a clock the window never allows
PASS someone with no role gets nothing
PASS an admin may grant what they hold to someone else
PASS a member cannot grant what they lack
PASS nobody promotes themselves
10 passed, 0 failed, 0 errors
```
## A check case
A `check` case asks one decision. This one is the second case of that file:
```json title="workspace.strig-test.json"
{
"kind": "check",
"name": "a member does not",
"subject": "user:bruno",
"permission": "org.settings",
"resource": { "path": [{ "kind": "org", "id": "acme" }] },
"expect": "deny",
"reason": "no_applicable_grant"
}
```
`expect` is `allow` or `deny`. Optionally a case names the instant and the environment, the `reason`, and the deciding `grant` (the first case of the file pins `admin-settings`).
## A mutation case
A `mutation` case gives an actor and a change, and says whether the governance accepts or refuses it, optionally by which invariant. That is how "nobody promotes themselves" is tested against the `no_self_management` invariant.
## Exit codes
| Exit | Meaning |
| --- | --- |
| `0` | Every case passed |
| `1` | At least one case failed |
| `2` | Bad input |
An error in the test itself (a missing fixture, a subject that does not exist) is never a pass: it is counted under `errors` and exits `2`.
## In CI
`--junit` writes a report that any CI reads:
```sh title="Shell"
strig test policies/ --junit test-results/strig.xml
```
The GitHub Action installs the CLI and runs it:
```yaml title=".github/workflows/policy.yml"
- uses: The-Hades-Organization/Strig/.github/actions/strig-test@v0.10.0
with: { path: policies, version: 0.10.0 }
```
The action also takes `diff-base`, to run [`strig diff`](https://strig.vercel.app/docs/tools/diff-lint.md) against the base of the pull request.
## From code
The same runner is `strig::dsl::testing` in Rust, `strig.runTests(policy, tests)` in JavaScript and `strig.dsl.run_tests(policy, tests)` in Python.
## Where to go next
- Find policy that never acts: [Diff and lint](https://strig.vercel.app/docs/tools/diff-lint.md).
- See why a case came out as it did: [Inspector](https://strig.vercel.app/docs/tools/inspector.md).
---
# Diff and lint
URL: https://strig.vercel.app/docs/tools/diff-lint
## Diff two versions
Removing the `time_between` condition from a grant looks like a small edit. `strig diff` shows what it does:
```sh title="Shell"
strig diff before after --fail-on allow
```
```text title="Output"
WIDENED role:admin project.write on project:(any)
before: deny (no_applicable_grant)
after: allow (grant, grant `member-writes-in-hours` at after/workspace.strig:44:7)
WIDENED role:admin project.write on org:(any) in project:(any)
before: deny (no_applicable_grant)
after: allow (grant, grant `member-writes-in-hours` at after/workspace.strig:44:7)
... (four more lines, the same three for role:member)
6 changed (6 widened, 0 narrowed); 90 questions over 6 subjects, 3 permissions, 5 resources (derived from the policies)
```
The exit code is `1`, because `--fail-on allow` fails when any access widened. Without a clock, `before` denies: a validity window never allows without one.
Each line gives who, which permission, on what, whether access `widened` or `narrowed`, and the grant or override responsible on each side. The two arguments are directories or `.strig` files.
Without a fixture the questions are derived from the catalogs and the grants, and bounded by `QueryLimits`. A diff cut by a limit is marked `partial`, and finding no change then is not proof there is none. Pass a fixture to ask your own:
```js title="JavaScript"
const found = strig.diff(before, after, { fixture: { resources: ['org:1'] } });
```
In Rust it is `strig::dsl::analysis`. The `strig-test` action takes `diff-base` to diff against the base of the pull request. See [Testing a policy](https://strig.vercel.app/docs/tools/testing.md).
## Lint a policy
`strig lint` finds policy that never acts. Add a role nobody uses:
```sh title="Shell"
strig lint policies/
```
```text title="Output"
policies/workspace.strig:65:6: info L004 [unused-role] role `auditor` is declared and no grant, subject or related role uses it
hint: remove the role, or grant something to it
1 findings (0 errors, 0 warnings, 1 info)
```
It reports:
- a shadowed grant;
- an unreachable deny;
- a permission nobody holds;
- an unused role;
- a redundant `implied_by`;
- a condition that is always false or true;
- a field never granted;
- a separation-of-duties set that is already violated (`L009`, see [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md)).
Codes run `L001` to `L009`. `--json` adds severity, position and hint for each finding. To silence one rule from code:
```js title="JavaScript"
const findings = strig.lint(policy, { ignore: ['unused-role'] });
```
## Where to go next
- Run the cases you write against the policy: [Testing a policy](https://strig.vercel.app/docs/tools/testing.md).
- The syntax these tools read: [Policy language](https://strig.vercel.app/docs/policy-language.md).
---
# Importing Casbin and OpenFGA
URL: https://strig.vercel.app/docs/tools/importers
`strig import` reads the model and the policy of another library and writes a `.strig` file. Nothing runs Casbin or OpenFGA: the converter is a module of the library (feature `import`, on in `strig-cli`, no IO) that takes text and returns a policy and a report.
For a step-by-step migration, see [Migrating from Casbin / OpenFGA](https://strig.vercel.app/docs/guides/migrating-from-casbin-openfga.md).
## Try it on a Casbin ACL
```text title="model.conf"
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
```
```text title="policy.csv"
p, alice, data1, read
p, bob, data2, write
```
```sh title="Shell"
strig import casbin model.conf policy.csv -o ./policy
```
```text title="Output"
wrote policy/policy.strig
converted:
2 policy lines (`p`)
2 grants
1 matcher alternative(s)
2 permissions, one per action
```
```blocks title="policy/policy.strig"
language blocks
target_kinds = [object]
permission object.read {
targets = [object]
}
permission object.write {
targets = [object]
}
grant casbin_1 {
effect = allow
subject = user alice
permission = object.read
target = object:data1
}
grant casbin_2 {
effect = allow
subject = user bob
permission = object.write
target = object:data2
}
```
## Usage
```sh title="Shell"
strig import casbin model.conf policy.csv -o ./policy [--language blocks|rules|actors] [--action read]...
strig import openfga model.fga tuples.csv -o ./policy [--language blocks|rules|actors]
```
It writes `/policy.strig` and prints what was converted, what was converted with a narrower reach, and what was not.
| Exit | Meaning |
| --- | --- |
| `0` | Everything converted |
| `1` | Something has no faithful translation; nothing is written |
| `2` | Usage error |
The result is checked like any policy: run it with [`strig test`](https://strig.vercel.app/docs/tools/testing.md).
## Casbin
Read: ACL, RBAC (`g = _, _`, and domains with `g = _, _, _`), RBAC with `keyMatch` on the resource, and ABAC over attributes.
- A `p` line becomes grants. A `g` line becomes a role assignment or an edge of the role graph.
- The policy effect picks the strategy. `some(where (p.eft == allow))` is `most_specific`, and a `deny` line is dropped and reported. `!some(where (p.eft == deny))`, allow-and-deny and `priority(p.eft)` become `deny_overrides` or `first_applicable`.
- A model that does not constrain the action (ABAC) needs `--action `.
- `keyMatch` becomes a `starts_with` condition. `regexMatch` is read only over alternations of literals, expanded over the actions the policy names.
- A matcher with no faithful translation (`keyMatch2`, `globMatch`, arithmetic, `!=` between request and policy) is an error with the file, line and column and the reason. It is never an approximation that allows more.
## OpenFGA
The DSL and the JSON of the model are read, and the tuples as JSON, CSV, YAML or one per line.
- Types and relations become a `RelationSchema` (`This`, `Computed`, `TupleToUserset`, `Union`, `Intersection`, `Exclusion`).
- Tuples go to the `TupleStore`, and each relation gets a permission and a grant.
- Conditions (CEL) are not translated: a model or a tuple that uses one is an error that points at it.
## How it is tested
Each fixture under `crates/strig/tests/fixtures/import/` holds a model, a policy and a table of requests with the answers the source library gives (from its documentation). The tests decide the same requests with the imported policy, in the three syntaxes, and compare.
---
# Language server and VS Code
URL: https://strig.vercel.app/docs/tools/editor
`strig-lsp` is a language server for `.strig` files, and `editors/vscode` is the VS Code extension that uses it. Both read the project the way [`strig test`](https://strig.vercel.app/docs/tools/testing.md) does: every `*.strig` file in the directory of the open file is one policy, in any mix of the three syntaxes, and every `*.strig-test.json` beside it is a test file. Unsaved buffers count.
## Install
```sh title="Shell"
cargo install --git https://github.com/The-Hades-Organization/Strig strig-lsp --locked # the server
cargo install strig-cli --locked # `strig test`, for the command below
```
The extension finds `strig-lsp` and `strig` on `PATH`, or at the settings `strig.server.path` and `strig.cli.path`, and says how to install them when they are missing.
To build the extension from the repository:
```sh title="Shell"
cd editors/vscode && npm ci && npm test && npx vsce package
```
Publishing it to the Marketplace and Open VSX is not set up yet.
## What it gives you
- **Diagnostics while you type**, with the position and the hint of the validator. They include clashes between files (the other side is a related location) and the errors of a `*.strig-test.json`.
- **Format document**, the same layout as `strig::dsl::format`. A source that does not compile is left alone.
- **Completion** of permission ids, kinds, roles, subjects and condition operators from the project, narrowed by the line (`depends_on = [`, `inherits `, `when = ...`).
- **Hover** on a permission, with its targets, `implied_by`, `depends_on`, fields and labels per locale; and on a role or a kind.
- **Go to definition** of a permission, role, grant or subject, across files.
- **Code action** "Convert to rules/actors/blocks syntax" for the whole file.
The command "Strig: Run policy tests" runs `strig test .` in the folder of the open file.
## Other editors
Any editor that speaks LSP can run `strig-lsp` directly. It talks over stdio and takes no arguments.
## Where to go next
- Check a change before review: [Diff and lint](https://strig.vercel.app/docs/tools/diff-lint.md).
- The syntaxes the server reads: [Policy language](https://strig.vercel.app/docs/policy-language.md).
---
# Inspector
URL: https://strig.vercel.app/docs/tools/inspector
`strig-inspect` is built on `Engine::explain`, which Rust and JavaScript can also call directly. Ask why Ben cannot view the secret document in the example scenario:
```sh title="Shell"
strig-inspect explain --scenario crates/strig-inspect/examples/scenario.json \
--subject ben --permission document.view --resource secret
```
```text title="Output"
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 star marks the grant that decided. `+` is a candidate that applied, `-` a grant that did not and why.
## Install
The crate is not on crates.io and is outside the workspace `default-members`. Install it from a clone:
```sh title="Shell"
cargo install --path crates/strig-inspect # window and terminal commands
cargo install --path crates/strig-inspect --no-default-features # terminal commands only, no gpui
```
## Commands
```sh title="Shell"
strig-inspect --scenario scenario.json --audit trail.jsonl # window
strig-inspect --scenario scenario.json --subject ben --permission document.export --resource invoice-7 \
--disable pro-export --tab matrix # window opened on a selection and tab
strig-inspect matrix --scenario scenario.json --resource secret --disable no-secret --add grant.json
strig-inspect audit --audit trail.jsonl --scenario scenario.json
strig-inspect fmt [--check]
```
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:
```sh title="Shell"
cargo run -p strig-inspect --no-default-features --example trail -- \
crates/strig-inspect/examples/scenario.json > crates/strig-inspect/examples/audit.jsonl
```
## The 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 `forensic` records, shows the recorded trace and re-evaluates `detailed` and `forensic` decisions against the current policy, flagging the ones that would change. See [Audit](https://strig.vercel.app/docs/audit.md).
**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 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 and embeds its fonts 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](https://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, from a file, a paste or the built-in example.
In the Audit tab it verifies the `forensic` chain with `verifyAuditChain`. The page 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` in the repository.
## Where to go next
- The same question from code: `why_not` in [Why not](https://strig.vercel.app/docs/governance/why-not.md).
- Check a decision in a test: [Testing a policy](https://strig.vercel.app/docs/tools/testing.md).
---
# Observability
URL: https://strig.vercel.app/docs/operations/observability
Every crate has an optional `tracing` feature, off by default. It adds spans through [`tracing`](https://docs.rs/tracing) and metrics through the [`metrics`](https://docs.rs/metrics) facade. You pick the backend: Prometheus, OpenTelemetry or your own recorder.
```toml title="Cargo.toml"
strig = { version = "0.10", features = ["tracing"] }
strig-server = { version = "0.10", features = ["tracing"] }
```
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`.
## What it costs
With the feature off, nothing is compiled in. With it on and no subscriber or recorder installed, a decision costs about 110 ns more:
| `decide/simple` | Time |
| --- | --- |
| Before the feature existed | 517 ns |
| Feature off | 518 ns |
| Feature on, nothing installed | 630 ns |
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.
## Export over OpenTelemetry
`crates/strig-server/examples/otlp.rs` exports spans and metrics over OTLP/HTTP with `tracing-opentelemetry` and `metrics-exporter-opentelemetry`:
```text title="Terminal"
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
cargo run -p strig-server --features tracing --example otlp
```
Point the endpoint at your collector. Decision and query spans are `debug`; the rest are `info`, so set the filter to see them. Events (a dropped audit record, a lost `LISTEN` connection, a breaker changing phase) go out at `warn` or `info`.
## 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. 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 that name a constant.
A decision made by a custom invariant or override 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.
## Metrics
| 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. |
Two worth an alert: `strig_audit_pending` growing means the audit sink is failing and records are queuing, and `strig_client_breaker_state` at `2` means a client has stopped calling a decision server that keeps failing.
## Spans
| 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` |
---
# Fuzzing
URL: https://strig.vercel.app/docs/operations/fuzzing
`fuzz/` holds [`cargo-fuzz`](https://rust-fuzz.github.io/book/cargo-fuzz.html) (libFuzzer) targets, kept outside the default workspace. They feed random bytes to the parts of Strig that read input you do not control.
## What is covered
| Target | Covers | Property checked |
| --- | --- | --- |
| `dsl_parse` | The policy-language parser | Arbitrary text. |
| `dsl_format` | The policy formatter | Idempotent: formatting twice gives what formatting once gives. |
| `dsl_convert` | Conversion between Blocks, Rules and Actors | Round trip between the three syntaxes. |
| `spec_json` | `EngineSpec` JSON | Arbitrary JSON. |
| `condition_eval` | Condition evaluation | Arbitrary conditions and values. |
| `decide` | Decisions | Never an allow without a candidate grant. |
| `sync_protocol` | Real-time protocol messages | Arbitrary messages. |
| `server_wire` | Decision-server messages | Arbitrary messages. |
| `audit_chain` | Audit chain verification | Arbitrary records. |
## Run one
You need the nightly toolchain and `cargo-fuzz`:
```text title="Terminal"
rustup toolchain install nightly
cargo install cargo-fuzz
./fuzz/run.sh dsl_convert 120 # one target for 120 seconds, seeded from fuzz/seeds
```
The seeds in `fuzz/seeds` are versioned. The corpus libFuzzer grows (`fuzz/corpus`), `fuzz/artifacts` and `fuzz/target` are not.
## When it finds a crash
libFuzzer writes the input to `fuzz/artifacts//`. Reproduce it with:
```text title="Terminal"
cargo +nightly fuzz run fuzz/artifacts//
```
Fix it with a regression test in the ordinary suite, and mention the crash in the pull request.
## In CI
The `fuzz` workflow runs a short round on pull requests that touch the engine, sync, server or `fuzz/`, and a long one every night, keeping the crash as an artifact.
---
# A multi-tenant SaaS
URL: https://strig.vercel.app/docs/guides/saas-multi-tenant
A tenant is an `org`. Its members read and write its projects, its admins manage its members, and nobody reaches into another org. This guide builds that, from the policy to the pipeline.
## 1. Model: the org is the anchor
Every project lives under an org, so a resource path is `project:p1 → org:acme`. A role assigned with `scope = org:acme` holds only inside that org. That one line is the tenant boundary.
```blocks title="policies/saas.strig"
language blocks
target_kinds = [org, project]
permission project.read {
targets = [project]
}
permission project.write {
targets = [project]
depends_on = [project.read]
}
permission org.members.manage {
targets = [org]
}
role member {
}
role admin {
inherits = [member]
}
subject user:ana {
assign admin {
scope = org:acme
}
}
subject user:bruno {
assign member {
scope = org:acme
}
}
subject user:dora {
assign admin {
scope = org:globex
}
}
grant member-reads {
effect = allow
subject = role member
permission = project.read
target = project
}
grant member-writes {
effect = allow
subject = role member
permission = project.write
target = project
}
grant admin-manages-members {
effect = allow
subject = role admin
permission = org.members.manage
target = org
}
invariant no_self_management {
}
invariant no_escalation {
}
```
The `subject` blocks are seed data for this example. In production the assignments live in the store (step 4).
`no_escalation` keeps an admin from handing out more than they hold; `no_self_management` keeps anyone from changing their own access. See [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md) for the rest of the catalog rules.
## 2. Test the isolation before anything else
The cases that matter most for a tenant are the ones that must deny.
```json title="policies/saas.strig-test.json"
{
"name": "saas policy",
"cases": [
{
"kind": "check",
"name": "the same member gets nothing in globex",
"subject": "user:bruno",
"permission": "project.read",
"resource": { "path": [{ "kind": "project", "id": "g1" }, { "kind": "org", "id": "globex" }] },
"expect": "deny",
"reason": "no_applicable_grant"
},
{
"kind": "check",
"name": "an admin of globex does not manage acme",
"subject": "user:dora",
"permission": "org.members.manage",
"resource": { "path": [{ "kind": "org", "id": "acme" }] },
"expect": "deny",
"reason": "no_applicable_grant"
}
]
}
```
```sh title="Shell"
strig test policies/
```
```text title="Output"
./saas.strig-test.json
PASS a member of acme reads an acme project
PASS the same member gets nothing in globex
PASS an admin of globex does not manage acme
PASS an admin of acme manages acme
PASS an admin cannot promote themselves further
5 passed, 0 failed, 0 errors
```
The file above shows the two cases that must deny; the run also covers the two allows and a refused promotion. See [Testing a policy](https://strig.vercel.app/docs/tools/testing.md).
## 3. Where decisions run
Two decisions happen in a SaaS, and they run in different places.
- **One resource** (open project `p1`): `engine.check` in the API process, from the user's roles and the resource path.
- **A list** (all projects I can see): `engine.list` returns a filter, and your ORM runs it, so the database returns only the rows that may be allowed.
```ts title="TypeScript"
import { toWhere } from '@the-hades-organization/strig/prisma';
const result = engine.list(ctx, subject, 'project.read', 'project', { layout: ['project', 'org'] });
const { where, residual } = toWhere(result, { kind: 'project', id: 'id', paths: { org: 'orgId' } });
const projects = await prisma.project.findMany({ where });
```
Because the role is scoped to `org:acme`, the `where` carries `orgId = 'acme'` for Bruno. A `residual` means the database could not settle some condition: check those rows with `engine.check`. See [Prisma, Drizzle and Kysely](https://strig.vercel.app/docs/integrations/orms.md).
The UI follows the same decisions: [`` and `useCan`](https://strig.vercel.app/docs/integrations/frontend.md) deny until the capabilities arrive.
## 4. Store: Postgres, written with its notice
Keep grants, tuples and role assignments in Postgres so every API instance reads the same data. Apply a governed change and notify the other instances in one transaction, so the notice leaves if, and only if, the change commits.
```rust title="Rust"
let tx = client.transaction().await?;
lock_governance(&tx).await?;
let current = all_grants(&tx).await?;
let actor = tables.subject(&tx, "user", "ana").await?;
let next = governance.apply(&engine, &actor, ¤t, &mutation, None)?;
commit_mutation(&tx, "strig:changes", &mutation).await?;
tx.commit().await?;
```
Put `is_stale()` in the readiness probe. See [Postgres](https://strig.vercel.app/docs/storage/postgres.md) and, for reading your own writes right after a change, [Revisions and real time](https://strig.vercel.app/docs/storage/consistency.md).
## 5. Audit
Every call to `governance.apply` can write an audit record: who changed what, and with what outcome. For a SaaS that answers customer security questionnaires, use `forensic` and keep the chain. See [Audit](https://strig.vercel.app/docs/audit.md).
## 6. Deploy
- **Policy in CI.** `strig test policies/` and `strig lint policies/` on every pull request; the [GitHub Action](https://strig.vercel.app/docs/tools/testing.md#in-ci) runs both with a `diff-base` so a change that widens access shows up in the review.
- **Observability.** Turn on `tracing` to get a span per decision and per change. See [Observability](https://strig.vercel.app/docs/operations/observability.md).
- **Recertify.** Run a [campaign](https://strig.vercel.app/docs/governance/recertification.md) each quarter over the admin role.
- **Support access.** Give support staff a time-boxed [elevation](https://strig.vercel.app/docs/governance/elevation.md) instead of a standing role.
## What you built
| Concern | Where it lives |
| --- | --- |
| Tenant boundary | `scope = org:` on the role assignment |
| Who reads a list | `engine.list` and the ORM filter |
| Who changes access | `governance.apply` with `no_escalation` and `no_self_management` |
| Data | Postgres, committed with its notice |
| Proof | Audit records and the policy tests |
---
# An internal dashboard
URL: https://strig.vercel.app/docs/guides/internal-dashboard
An internal tool has few tenants and many rules about who sees what and who signs off. This guide builds reports that analysts view, leads export and approve, with a rule that the author of a report does not approve it.
## 1. Model: department as the anchor
```blocks title="policies/dashboard.strig"
language blocks
target_kinds = [dept, report]
permission report.view {
targets = [report]
}
permission report.export {
targets = [report]
depends_on = [report.view]
}
permission report.approve {
targets = [report]
depends_on = [report.view]
}
role analyst {
}
role finance_lead {
inherits = [analyst]
}
grant analyst-views {
effect = allow
subject = role analyst
permission = report.view
target = report
}
grant lead-exports {
effect = allow
subject = role finance_lead
permission = report.export
target = report
}
grant lead-approves {
effect = allow
subject = role finance_lead
permission = report.approve
target = report
}
invariant no_self_management {
}
invariant no_escalation {
}
```
`depends_on` means nobody holds `report.export` without `report.view` on the same report. Roles are assigned with `scope = dept:sales`, so an analyst of `sales` sees nothing in `hr`.
## 2. Test who may and who may not
```sh title="Shell"
strig test policies/
```
```text title="Output"
./dashboard.strig-test.json
PASS an analyst views a report in their department
PASS an analyst cannot export
PASS an analyst sees nothing in another department
PASS a lead approves
4 passed, 0 failed, 0 errors
```
Each name is a sentence a reviewer can read as a requirement. See [Testing a policy](https://strig.vercel.app/docs/tools/testing.md).
## 3. Four eyes: the author does not approve
Declare the rule in the catalog, so it holds in every decision and not only in the approve screen.
```rust title="Rust"
let catalog = Catalog::builder()
.target_kinds(["dept", "report"])
.permission(PermissionDef::new("report.create").targets(["report"]))
.permission(PermissionDef::new("report.approve").targets(["report"]))
.conflicting_actions(ActionConflict::new("four_eyes", ["report.create"], ["report.approve"]))
.build()?;
```
Record who acted in the report's `history` attribute (`"report.create:mara"`). When Mara asks for `report.approve` on it, the decision is a denial named `separation:four_eyes`, and a history the engine cannot read denies too. See [Separation of duties](https://strig.vercel.app/docs/governance/separation-of-duties.md).
## 4. Temporary access instead of standing access
An analyst needs one export for an audit. Do not grant `report.export` for good; let the lead approve a window.
```js title="JavaScript"
await flow.request({ id: 'e1', actor: lia, target, durationMs: 2 * HOUR, justification: 'Q3 audit' }, grants);
await flow.approve('e1', mara, grants, { persist: (r) => saveGrants(r.grants) });
```
The access ends at the instant the window closes, with no job to run. See [Temporary elevation](https://strig.vercel.app/docs/governance/elevation.md).
## 5. Show and hide in the UI
The buttons follow the same rules as the API. With React:
```tsx title="React"
permission="report.export" resource={report} fallback={null}>
```
`` denies until the first capabilities arrive, so a slow connection never flashes a button the user may not press. See [React and Angular](https://strig.vercel.app/docs/integrations/frontend.md).
## 6. Answer "why can't I?"
When Lia asks why she cannot export, support does not read the policy. `why_not` returns the shortest change that would allow it, and the inspector shows the full trace.
- [Why not](https://strig.vercel.app/docs/governance/why-not.md) for the answer from code.
- [Inspector](https://strig.vercel.app/docs/tools/inspector.md) for the trace, the matrix of permissions and the audit trail.
## 7. Run and prove
- **Where decisions run.** In the dashboard's own API process with `engine.check`; no separate server is needed for one app. If other services also need the answer, run the [decision server](https://strig.vercel.app/docs/integrations/server.md).
- **Store.** Postgres, if more than one instance runs; the JSON file store is enough for a single process. See [Postgres](https://strig.vercel.app/docs/storage/postgres.md).
- **Audit.** Write `detailed` records for exports and approvals, `forensic` for elevations. See [Audit](https://strig.vercel.app/docs/audit.md).
- **Review.** Run a quarterly [recertification](https://strig.vercel.app/docs/governance/recertification.md) over `finance_lead`.
---
# A public API
URL: https://strig.vercel.app/docs/guides/public-api
A public API has one question at the edge: may this key do this method on this path? This guide answers it at the gateway, so no service has to remember to ask.
## 1. Model: keys are subjects, roles are scoped to an account
An API key is a `user` subject whose id is the key id. Its role is assigned with the account as scope, so a key of `acme` reads only documents under `acme`.
```blocks title="policies/api.strig"
language blocks
target_kinds = [account, document]
permission document.view {
targets = [document]
}
permission document.edit {
targets = [document]
depends_on = [document.view]
}
role reader {
}
role editor {
inherits = [reader]
}
grant reader-views {
effect = allow
subject = role reader
permission = document.view
target = document
}
grant editor-edits {
effect = allow
subject = role editor
permission = document.edit
target = document
}
invariant no_escalation {
}
```
A key is created by assigning it a role through the governance, so `no_escalation` stops a key manager from minting a key stronger than their own.
## 2. Test the keys
The fixture gives two keys: `key_r1` is a `reader` of `account:acme`, and `key_none` has no role.
```json title="policies/api.fixture.json"
{
"subjects": [
{ "kind": "user", "id": "key_r1", "roles": [{ "role": "reader", "scope": { "kind": "account", "id": "acme" } }] },
{ "kind": "user", "id": "key_none" }
]
}
```
```sh title="Shell"
strig test policies/
```
```text title="Output"
./api.strig-test.json
PASS a reader key views a document
PASS a reader key cannot edit
PASS a key with no role gets nothing
3 passed, 0 failed, 0 errors
```
See [Testing a policy](https://strig.vercel.app/docs/tools/testing.md).
## 3. Where decisions run: at the gateway
Run the [decision server](https://strig.vercel.app/docs/integrations/server.md) with the `envoy` feature. Envoy asks it before it forwards each request, so the services behind it receive only requests that were allowed.
```rust title="Rust"
let envoy = EnvoyConfig::default()
.with_subject_header("x-api-key-id")?
.with_route("GET", "/healthz", RouteRule::public())?
.with_route(
"GET,HEAD",
"/documents/{id}",
RouteRule::require("document.view", ResourceTemplate::new("document", "{id}")),
)?
.with_route(
"PUT,PATCH",
"/documents/{id}",
RouteRule::require("document.edit", ResourceTemplate::new("document", "{id}")),
)?;
let service = DecisionServer::new(source).envoy_service(envoy);
service.serve(TcpListener::bind("127.0.0.1:9191").await?, shutdown).await?;
```
- The subject header must be set by an earlier filter that verified the key, never copied from the client.
- A path no rule covers is a `403`. So is a missing subject, a source that is down and a deadline that passed.
- A path with dot segments or encoded separators matches nothing, so `/documents/../admin` cannot borrow another rule.
Services that are not behind Envoy, or partners that speak the standard, can call `/v1/check` or the [AuthZEN](https://strig.vercel.app/docs/integrations/server.md#authzen) routes on the same server.
## 4. Store: one source for every replica
The server reads grants from a `DecisionSource`. For one replica, `MemorySource` is enough; for several, load a `PgStore` snapshot and let each replica follow changes. See [Postgres](https://strig.vercel.app/docs/storage/postgres.md). Put the server's `/health/ready` in the gateway's health check.
## 5. Audit
Log the decisions that matter to your customers: key creation and role changes, with `detailed` records and `redact` for fields such as `ip`. See [Audit](https://strig.vercel.app/docs/audit.md) and, to verify a chain later, the inspector's Audit tab ([Inspector](https://strig.vercel.app/docs/tools/inspector.md)).
## 6. Deploy and watch
- **Timeouts.** The client's default fails closed on a timeout; set it from your latency budget (the example in the server page uses 250 ms), and keep the circuit breaker on.
- **Tracing.** Turn on `tracing` for a span per decision. See [Observability](https://strig.vercel.app/docs/operations/observability.md).
- **Policy changes.** `strig diff` in the pull request shows who gains access before the change ships. See [Diff and lint](https://strig.vercel.app/docs/tools/diff-lint.md).
---
# Migrating from Casbin / OpenFGA
URL: https://strig.vercel.app/docs/guides/migrating-from-casbin-openfga
A migration is done when the new policy answers the same requests as the old one, and you can show it. `strig import` converts; `strig test` proves. This guide runs both on a Casbin RBAC-with-domains model.
## 1. Convert
```text title="model.conf"
[request_definition]
r = sub, dom, obj, act
[policy_definition]
p = sub, dom, obj, act
[role_definition]
g = _, _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.obj == p.obj && r.act == p.act
```
```text title="policy.csv"
p, admin, acme, data1, read
p, admin, acme, data1, write
g, alice, admin, acme
```
```sh title="Shell"
strig import casbin model.conf policy.csv -o ./policy
```
```text title="Output"
wrote policy/policy.strig
converted:
2 policy lines (`p`)
2 grants
1 role assignments (`g`, as subjects)
1 matcher alternative(s)
2 permissions, one per action
```
The domain became a scope, and `alice`'s `g` line became a role assignment in `domain:acme`:
```blocks title="policy/policy.strig"
language blocks
target_kinds = [domain, object]
permission object.read {
targets = [object]
}
permission object.write {
targets = [object]
}
role admin {
}
subject user:alice {
assign admin {
scope = domain:acme
}
}
grant casbin_1 {
effect = allow
subject = role admin
permission = object.read
target = object:data1
scope = domain:acme
}
grant casbin_2 {
effect = allow
subject = role admin
permission = object.write
target = object:data1
scope = domain:acme
}
```
## 2. Read what could not be converted
A matcher with no faithful translation stops the import and writes nothing. Here is a model that uses `keyMatch2`:
```text title="Output"
converted:
nothing
not converted:
bad.conf:8:23: `keyMatch2` has no faithful translation: conditions have no regular expressions, path parameters or globs
hint: only `keyMatch` (a `*` suffix) and `regexMatch` over alternations of literals are read
```
Exit is `1`. Strig never approximates a matcher into one that allows more. Rewrite the rule (a `keyMatch` with a `*` suffix, or one policy line per resource) and import again. See [Importing Casbin and OpenFGA](https://strig.vercel.app/docs/tools/importers.md) for what each source reads.
## 3. Turn your old decisions into tests
The old system's answers are the specification. Take a list of real requests with the answers Casbin gives, and write each as a case.
```json title="policy/policy.strig-test.json"
{
"name": "migrated from casbin",
"cases": [
{
"kind": "check",
"name": "alice reads data1 in acme",
"subject": "user:alice",
"permission": "object.read",
"resource": { "path": [{ "kind": "object", "id": "data1" }, { "kind": "domain", "id": "acme" }] },
"expect": "allow"
},
{
"kind": "check",
"name": "alice reads data1 in globex",
"subject": "user:alice",
"permission": "object.read",
"resource": { "path": [{ "kind": "object", "id": "data1" }, { "kind": "domain", "id": "globex" }] },
"expect": "deny"
}
]
}
```
```sh title="Shell"
strig test policy/
```
Cases the old library denies and the new one allows are the ones that matter. Run them from a recorded sample of production requests if you have one.
## 4. Lint, then review the diff
```sh title="Shell"
strig lint policy/
```
```text title="Output"
0 findings (0 errors, 0 warnings, 0 info)
```
Lint finds roles nobody uses and grants that never act, which imported policies often carry. See [Diff and lint](https://strig.vercel.app/docs/tools/diff-lint.md).
## 5. Switch over
1. Run both engines side by side and log every disagreement. The migrated engine is the one under test; the old one still decides.
2. When the log stays empty for a period you trust, let Strig decide. Keep the old engine logging for one more release.
3. Move the data. For OpenFGA, tuples go to the `TupleStore`: [Postgres](https://strig.vercel.app/docs/storage/postgres.md) keeps them across instances.
4. From now on change access through the governance, with [audit](https://strig.vercel.app/docs/audit.md) and [impact](https://strig.vercel.app/docs/governance/impact.md), rather than by editing a policy file.
## OpenFGA
```sh title="Shell"
strig import openfga model.fga tuples.csv -o ./policy
```
The DSL and the JSON of the model are read, with tuples as JSON, CSV, YAML or one per line. A model or tuple that uses a condition (CEL) is an error that points at it: express the condition in Strig's [policy language](https://strig.vercel.app/docs/policy-language.md) and drop it from the model before importing.
---
# Audit
URL: https://strig.vercel.app/docs/audit
With the `audit` feature, on by default, every change that goes through governance becomes an `AuditRecord`, applied or refused. A record says when, who, what, on which object and with which outcome. Role changes, ReBAC tuple changes and decisions can be recorded too.
Where the records go is yours to decide. Rust has two sinks, `MemoryAuditLog` and `JsonLinesAudit`, which writes to any `io::Write`; for a database, a queue or a SIEM, implement `AuditSink`. In JavaScript the sink is a function.
```rust title="Rust"
let auditor = Arc::new(Auditor::new(AuditLevel::Standard, Arc::new(JsonLinesAudit::new(file))));
```
## Levels
Each level keeps everything from the one above it. Sizes are compact JSON bytes per line, without compression or indexes, measured on a reference record: a grant with a scope and a two-clause condition, UUID ids, an actor with two roles and three metadata entries.
| Level | A change record keeps | Bytes | Per 1M records |
| --- | --- | ---: | ---: |
| `minimal` | When, who, action, object id, outcome | 175 | 175 MB |
| `standard` | A grant summary and the names of the invariants that refused | 388 | 388 MB |
| `detailed` | The whole grant, the full actor, the violation messages, the request metadata | 1,097 | 1.10 GB |
| `forensic` | The SHA-256 digest of the grant set before and after, and the hash chain | 1,415 | 1.42 GB |
Decisions are recorded by `Auditor::decide`, and at `forensic` they carry the full trace from `explain`. `AuditLevel::estimate_bytes(n)` projects your own volume.
## When the sink fails
*Added in 0.7.0.*
A log that cannot be written leaves a choice: refuse the change, or let it through and write the record late. Strig asks you to make it, per call, per permission or once for everything.
| Mode | What happens when the sink fails |
| --- | --- |
| `closed` (default) | The change is refused with the `audit` violation. No record, no change. |
| `open` | The change goes ahead. The record waits in an in-memory retry queue and is written when the sink recovers. |
The mode of a record is the first of these that is set: the mode of the call, the mode of its permission, the auditor's default, then `closed`. Role, tuple and exclusive-resource records carry no permission, so they follow the call and the default.
```rust title="Rust"
let auditor = Auditor::new(AuditLevel::Forensic, sink)
.with_fail_mode(FailMode::Closed)
.with_permission_fail_mode("report.view", FailMode::Open)
.with_retry(RetryPolicy { capacity: 500, ..RetryPolicy::default() })
.with_redactor(mask_attributes(["ip", "email"], "[redacted]"));
```
### The retry queue
- Records leave the queue in the order they entered, and nothing is written ahead of the record at the head. While it waits, every later record waits behind it, so the sink always sees the chain in order. A `closed` record made while others wait forces the queue to drain first and is refused if it cannot.
- The queue is bounded: `capacity` defaults to 1024. Retries back off from `base_delay_ms` (100), doubling up to `max_delay_ms` (30 000), and happen on the next record or on `flush`.
- A full queue drops the new record and keeps the older ones in place. A dropped record is not part of the chain: the next record continues the last one that was accepted, so the chain of what was written still verifies. The verifier cannot see the gap, so Strig reports it instead: `AuditStatus::Dropped`, the `dropped` counter of `AuditStats` and the drop callback, which receives the whole record so you can keep it elsewhere.
- The queue lives in memory. Records waiting when the process stops are lost: flush before shutdown, and treat `pending` as an alarm.
> **Warning**
>
> `open` trades completeness for availability. A record that waits can be lost with the process, and a dropped one is lost for good unless your callback keeps it. Use `open` for permissions where an outage of the log must not stop work, and keep `closed` for the rest.
### The sink in JavaScript
On Node, Bun and in wasm, the sink and its policy go in the second argument of `Engine`. The sink is synchronous, and a throw is a failure of the sink.
```js title="JavaScript"
const engine = new Engine(spec, {
auditSink: (record) => log.append(record),
auditPolicy: { failMode: 'closed', permissions: { 'report.view': 'open' }, capacity: 500 },
onAuditDrop: (record) => spill.write(record),
});
const out = engine.apply({
actor,
current,
mutation: { add: grant },
audit: { level: 'forensic', prevHash, failMode: 'open' },
});
out.auditStatus; // 'written' | 'pending' | 'dropped'
engine.flushAudit(); // retries the queue; answers { pending, writtenLate, dropped, failures, nextRetryAt }
engine.auditStats(); // the same counters, without a retry
```
`auditPolicy` also takes `baseDelayMs` and `maxDelayMs`. `apply` and `applyTemplate` take `failMode`, `redact` and `prevHash` in their `audit` option and return `auditStatus`; for a template it is the worst destination among the records. Without a sink, `apply` still returns the record and writes nothing: you store it wherever you keep your log.
## Redact what must not be kept
Attribute values such as an IP address or an email are often not for a log. A redactor masks them before the record is hashed and written.
```js title="JavaScript"
engine.apply({
actor,
current,
mutation,
audit: { level: 'detailed', redact: { keys: ['ip', 'email'], mask: '[redacted]' } },
});
```
It replaces the value of those attribute keys in `meta`, in the `attrs` of the actor and the resource, and in their copies inside a decision trace. The mask defaults to `[redacted]`. For anything else, pass a function: `hooks.auditRedact` in JavaScript, `Auditor::with_redactor` in Rust. It runs after `audit.redact`.
- **If a redactor fails, the change is refused, whatever the failure mode.** A record is never written unmasked.
- **The hash covers the masked record.** A log that only ever held the masked version still verifies. `before_digest` and `after_digest` are computed before redaction and carry no attribute.
- **Redaction does not read grants or `object`.** It does not look inside the condition of a grant or in the object string. Keep sensitive values out of ids.
## The chain
At the `forensic` level each record carries `prev_hash`, the `hash` of the record before it, and its own `hash`. Verification walks the records in the order they were written: each must have a `hash`, each from the second on must carry a `prev_hash` equal to the `hash` before it, and each `hash` must match the recomputation. An edited record is `Tampered`. A removed or reordered one makes the next `Broken`.
```js title="JavaScript"
import { load } from '@the-hades-organization/strig';
const { verifyAuditChain } = await load();
verifyAuditChain(records); // { ok: true, head } or { ok: false, code, index, message }
```
`code` is one of `TAMPERED`, `BROKEN`, `UNCHAINED`, `ANCHOR_MISMATCH` and `HEAD_MISMATCH`. Verify with the records as stored: they are re-serialized in the canonical order, so it does not matter that a JavaScript object does not keep the order of its keys. In Rust, `audit::verify_chain(&records)`, and `Auditor::resume_chain` continues a chain after a restart.
### Chain records in your own log
You do not have to hand Strig the destination. `apply` returns the record (`audit`; `audits` for a template), and you store it wherever you keep your log, in the order the changes were made.
- **Chain.** Pass `prevHash` (JS) or call `Auditor::resume_chain` (Rust) with the `hash` of the last record you stored, so the next record continues it.
- **One writer per chain.** Two records made from the same `prevHash` fork the chain. Serialize the calls.
- **Opaque hashes.** Store `hash` and `prev_hash` as they are and do not recompute them by any rule but the one below.
### Anchor the head
A chain proves that nothing was edited or removed from the middle. It cannot prove that the last records were not cut off, because there is nothing after them to disagree. Publish the **head**, the `hash` of the last record, somewhere the writer cannot rewrite: an external log, a signed timestamp, a ticket. Strig takes no network dependency for this; it gives you the value and checks against it.
```js title="JavaScript"
const { ok, head } = verifyAuditChain(records); // publish `head`, outside the log
// later, over the records written since the last anchor
verifyAuditChain(segment, { start: lastHead, head: newHead });
```
- `head` fails with `HEAD_MISMATCH` if the sequence ends anywhere else.
- `start` fails with `ANCHOR_MISMATCH` if the first record does not continue the hash you know. It lets you verify a segment instead of the whole log: the head you published last time is the `start` of the next check.
- In Rust: `Auditor::chain_head()` or `chain_head(&records)`, then `verify_chain_anchored(&records, start, head)`.
## The canonical format
The `forensic` trail is a contract, so a verifier in another language can check it. A record is one JSON object in compact JSON, encoded as UTF-8.
- **Key order is the order of the fields**, not alphabetical. Maps (`meta`, `attrs`) are the exception: their keys go in ascending byte order.
- **Absent fields are omitted**, never `null`. An empty list and an empty map do not appear either.
- **Strings escape only** `"`, `\` and the control characters below U+0020 (`\b`, `\t`, `\n`, `\f`, `\r`, and `\u00XX` in lowercase hex for the rest). Everything else is written as is in UTF-8, and `/` is not escaped.
- **Integers** are decimal, with no sign, exponent or fraction. `at` is milliseconds since the Unix epoch.
- **Enums** are `snake_case` strings.
The hash is:
```text title="Hash"
hash = lowercase_hex( SHA-256( canonical JSON of the record without the `hash` field ) )
```
The record is serialized with `prev_hash` already set and `hash` left out. Because `hash` is the last field, a verifier can take a line as received, cut the trailing `,"hash":"<64 hex>"` and hash what is left. That works on the JSON Lines Strig wrote (`JsonLinesAudit`) with nothing but SHA-256. The first record of a chain has no `prev_hash`.
The first fields, in order: `at`, `level`, `actor`, `action`, `object`, `outcome`; then the ones the level keeps, up to `explanation`, `before_digest`, `after_digest`, `prev_hash` and `hash`. The full table, with the nested types, is in [`docs/audit-format.md`](https://github.com/The-Hades-Organization/Strig/blob/main/docs/audit-format.md) in the repository, and a test there fails if the page and the code drift apart.
### Test vector
Reproduce this before you trust your verifier. A `forensic` tuple change, one line, with a `prev_hash` of 64 `a`:
```json title="Record, before hashing"
{"at":1700000000000,"level":"forensic","actor":"alice","action":"tuple_add","object":"doc:d1#viewer@user:bob","outcome":"applied","tuple":{"object":{"kind":"doc","id":"d1"},"relation":"viewer","subject":{"object":{"kind":"user","id":"bob"}}},"actor_detail":{"kind":"user","id":"alice","roles":[{"role":"admin"}],"principals":["authenticated"]},"meta":{"ip":"203.0.113.42","reason":"ticket \"SUP-1\" é"},"prev_hash":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
```
The SHA-256 of exactly those bytes, UTF-8 with no trailing newline:
```text title="Hash"
087dbffda54667a64ae971f80c70bf6544b205be90c9ca9cc592ef113f4a4cb5
```
The record as written is the same object with `,"hash":"087dbffd…4cb5"` before the closing `}`.
## Prove one record, or the time, to a third party
The chain proves the log is intact to whoever holds all of it. To hand an auditor one record without the rest, the records are also the leaves of a Merkle tree (RFC 6962, restated by RFC 9162). The chain and the record hash do not change.
```js title="JavaScript"
const { verifyMerkleInclusion, verifyMerkleConsistency } = await load();
verifyMerkleInclusion({ record, index: 41, size: 1000, proof, root });
// { ok: true } or { ok: false, code: 'ROOT_MISMATCH' }
verifyMerkleConsistency({ first: 600, second: 1000, firstRoot, secondRoot, proof });
// the tree of 1000 records extends the one of 600 you published before
```
The auditor needs the record, its position, the tree size, the proof (at most `ceil(log2 size)` hashes) and a root they already trust. Publish the root like the chain head. A consistency proof shows that a root you published earlier still holds: nothing before it was rewritten.
`code` is one of `INDEX_OUT_OF_RANGE`, `PROOF_LENGTH`, `ROOT_MISMATCH` and `SIZES`. In Rust, `strig::merkle::MerkleTree::from_records` builds the tree and the proofs, and `verify_inclusion` and `verify_consistency` check them. The leaf is `SHA-256(0x00 || line)` over the record exactly as written, `hash` included; a node is `SHA-256(0x01 || left || right)`. [`docs/audit-format.md`](https://github.com/The-Hades-Organization/Strig/blob/main/docs/audit-format.md) has the test vectors.
A Merkle root or a chain head says what the log held. A time-stamping authority says when, signed by someone other than the host. Ask it for a stamp over the head (RFC 3161), then verify the answer offline, against a root certificate you supply:
```js title="JavaScript"
const { verifyTimestamp } = await load();
verifyTimestamp({ response: base64Der, head, roots: caPem });
// { ok: true, genTime, serial, policy, algorithm, signerSubject, ... }
// { ok: false, code: 'UNTRUSTED_CHAIN', message }
```
The check fails closed: with no root every response is refused, and the status, the imprint, the signature, the certificate chain and the `id-kp-timeStamping` usage must all hold. Revocation (CRL, OCSP) is not consulted. In Rust the request is `strig::timestamp::TimestampRequest::for_chain_head(head, nonce)` and the check is `verify_response` (feature `timestamp`); the core does no network IO, so you POST the request yourself.
## Report on a trail
`strig audit report` reads a JSON Lines trail and answers what an auditor asks first:
```text title="Terminal"
strig audit report trail.jsonl --anchor-head 9f2c… --timestamp head.tsr --root ca.pem
```
It lists the period, records per action and outcome, applied changes per actor, refusals per invariant, every chain break with its position, the anchors compared with the trail, and each stamp verified against the head. `--json` prints the same as data. The exit status is `0` when the trail conforms, `1` when it does not, and `2` for a usage error; an empty trail does not conform. The flags are in the [reference](https://strig.vercel.app/docs/reference.md#command-line-strig-cli).
## The format is versioned
`AUDIT_FORMAT` is `1`. A record written today verifies with a verifier written against format 1, in any language. A change to key order, escaping, hash input or the meaning of a field takes a new format number and a major version, while an added optional field does not change the hash of a record that lacks it. [Upgrading](https://strig.vercel.app/docs/upgrading.md) lists what is frozen.
At `detailed` and `forensic`, the record of a change applied with its impact carries the optional field `impact`: `gained`, `lost`, `indeterminate`, `partial`, and up to 10 `examples`. See [Impact](https://strig.vercel.app/docs/governance/impact.md).
## Records of the approval flow
*Added in 0.7.0.*
A pending request and the features built on it write these actions, with the outcome `pending` for a proposal that was kept:
| Action | Written when |
| --- | --- |
| `mutation_propose`, `mutation_approve`, `mutation_reject`, `mutation_expire` | each step of a [pending request](https://strig.vercel.app/docs/approvals.md#what-the-audit-records) |
| `elevation_review` | another actor closes the review of a break-glass [elevation](https://strig.vercel.app/docs/governance/elevation.md) |
| `recert_open`, `recert_decide`, `recert_close` | a [recertification](https://strig.vercel.app/docs/governance/recertification.md) campaign opens, an item is decided (or defaulted at closing), the campaign closes |
A log consumer that validates `action` and `outcome` against a closed list needs these values before you turn the flows on.
- [Approvals](https://strig.vercel.app/docs/approvals.md): A change that waits for a second person before it applies.
---
# Reference
URL: https://strig.vercel.app/docs/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>) -> 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
```
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(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
```
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
```
Builds an engine from JSON, TOML or YAML configuration.
#### EngineSpec::builder
```
pub fn builder(&self) -> Result
```
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
```
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
```
Who holds the permission on this resource, overrides included.
#### Engine::who_can
```
pub fn who_can(&self, ctx: &QueryContext<'_>, permission: &str) -> Vec
```
Parties named by an allow grant anywhere. It evaluates nothing.
#### Engine::access_of
```
pub fn access_of(&self, ctx: &QueryContext<'_>, resource: &Resource) -> Result, 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, pub warnings: Vec }
```
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, pub path: Vec, pub roles: Vec, pub overrides: Vec, pub grants: Vec, pub strategy: String, pub prerequisites: Vec, 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, id: impl Into) -> Self
pub fn within(mut self, kind: impl Into, id: impl Into) -> 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) -> 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, 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` 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, subject: SubjectMatcher, permission: impl Into, 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`.
### 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 }
```
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; fn native(&self) -> Option { 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, 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) -> Self` |
| `starting_at` | `pub fn starting_at(scope: impl Into, value: u64) -> Self` |
#### `Revised`
A value together with the revision its write was given.
| Method | Signature |
| --- | --- |
| `new` | `pub fn new(value: T, revision: Option) -> 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` |
#### `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, message: impl Into) -> 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) -> Self` |
| `with_revisions` | `pub fn with_revisions(mut self, source: Arc) -> Self` |
| `apply_revised` | `pub fn apply_revised( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> Result>, Vec>` |
| `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>` |
| `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>` |
| `impact` | `pub fn impact( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, options: &ImpactOptions<'_>) -> Result>` |
| `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>` |
#### `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>, Option)` |
| `apply` | `pub fn apply( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>) -> Result, Vec>` |
| `impact` | `pub fn impact( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, options: &ImpactOptions<'_>) -> Result>` |
| `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>` |
| `apply_revised` | `pub fn apply_revised( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> Result>, Vec>` |
| `apply_with` | `pub fn apply_with( &self, engine: &Engine, actor: &Subject, current: &[Grant], mutation: &Mutation, tuples: Option<&dyn TupleStore>, meta: &Attributes) -> Result, Vec>` |
#### `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, 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(critical: I, members: Vec, resource: Resource) -> Self where I: IntoIterator- , S: Into
,` |
| `with_reserve` | `pub fn with_reserve(mut self, admin_role: RoleAssignment, subjects: I) -> Self where I: IntoIterator- ,` |
#### `Forbid`
`subject` never receives `allow` on `permissions` or on any permission that grants them.
| Method | Signature |
| --- | --- |
| `new` | `pub fn new
(subject: SubjectMatcher, permissions: I) -> Self where I: IntoIterator- , S: Into
,` |
#### `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) -> 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(roles: I) -> Self where I: IntoIterator- , S: Into
,` |
#### `Bypass`
Permission that exempts its holder from `NoEscalation` on `resource`.
| Method | Signature |
| --- | --- |
| `new` | `pub fn new(permission: impl Into, 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) -> Self` |
| `field` | `pub fn field(mut self, field: impl Into) -> 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` |
#### `SEPARATION_PREFIX`
Prefix of the name a dynamic rule has as an override (`separation:<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>(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- ) -> Self` |
| `require` | `pub fn require(mut self, kind: MutationKind, permission: impl Into
, resource: Resource) -> Self` |
| `require_all` | `pub fn require_all(self, permission: impl Into, 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, actor: Subject, mutation: Mutation, requested_at: u64) -> Self` |
| `expiring_at` | `pub fn expiring_at(mut self, expires_at: Option) -> 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` |
| `fail_mode` | `pub fn fail_mode(mut self, mode: FailMode) -> Self` |
| `pending` | `pub fn pending(&self, now: u64) -> Result, PendingError>` |
| `propose` | `pub fn propose( &self, review: &Review<'_>, actor: &Subject, mutation: &Mutation, id: impl Into, expires_at: Option) -> Result` |
| `approve` | `pub fn approve(&self, review: &Review<'_>, approver: &Subject, id: &str) -> Result` |
| `reject` | `pub fn reject( &self, review: &Review<'_>, approver: &Subject, id: &str, reason: &str) -> Result` |
| `expire_due` | `pub fn expire_due(&self, now: u64, meta: &Attributes) -> Result, ApprovalError>` |
#### `ElevationTarget`
What an elevation gives: a role, or a permission on a target.
| Method | Signature |
| --- | --- |
| `role` | `pub fn role(role: impl Into) -> Self` |
| `permission` | `pub fn permission(permission: impl Into, 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, 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- ) -> 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
, actor: Subject, target: ElevationTarget, duration_ms: u64) -> Self` |
| `justified` | `pub fn justified(mut self, justification: impl Into) -> 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, at: u64, reason: Option) -> 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, PendingError>` |
| `pending_reviews` | `pub fn pending_reviews(&self) -> Result, PendingError>` |
| `expire_due` | `pub fn expire_due(&self, now: u64, meta: &Attributes) -> Result, ApprovalError>` |
| `request` | `pub fn request( &self, review: &Review<'_>, req: &ElevationRequest, expires_at: Option) -> Result` |
| `approve` | `pub fn approve(&self, review: &Review<'_>, approver: &Subject, id: &str) -> Result` |
| `reject` | `pub fn reject( &self, review: &Review<'_>, approver: &Subject, id: &str, reason: &str) -> Result` |
| `revoke` | `pub fn revoke( &self, review: &Review<'_>, by: &Subject, id: &str, reason: Option<&str>) -> Result` |
| `close_review` | `pub fn close_review( &self, review: &Review<'_>, reviewer: &Subject, id: &str, note: &str) -> Result` |
#### 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, resource: Resource) -> Self` |
| `role` | `pub fn role(role: impl Into) -> Self` |
| `subject` | `pub fn subject(id: impl Into) -> 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, reviewer: ReviewerRule) -> Self` |
| `for_role` | `pub fn for_role(role: impl Into, 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(mut self, permissions: I) -> Self where I: IntoIterator- , S: Into
,` |
| `roles` | `pub fn roles(mut self, roles: I) -> Self where I: IntoIterator- , S: Into
,` |
| `subject_kinds` | `pub fn subject_kinds(mut self, kinds: I) -> Self where I: IntoIterator- , S: Into
,` |
#### `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, reviewer: ReviewerRule, reviewer_permission: impl Into, reviewer_resource: Resource, due_at: u64, keep_period_ms: u64) -> Self` |
| `named` | `pub fn named(mut self, name: impl Into) -> 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- ` |
| `certified` | `pub fn certified(&self, now: u64) -> impl Iterator
- ` |
| `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
, RecertError>` |
| `report` | `pub fn report(&self, id: &str) -> Result` |
| `open` | `pub fn open( &self, review: &Review<'_>, opener: &Subject, spec: CampaignSpec, subjects: &[Subject]) -> Result` |
| `decide` | `pub fn decide( &self, review: &Review<'_>, reviewer: &Subject, id: &str, item: &str, decision: RecertDecision, reason: Option<&str>) -> Result` |
| `close` | `pub fn close(&self, review: &Review<'_>, closer: &Subject, id: &str) -> Result` |
## 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` |
| `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` |
| `drain` | `pub fn drain(&self) -> Vec` |
#### `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