# 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: 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) -> Self` | | `with_fail_mode` | `pub fn with_fail_mode(mut self, mode: FailMode) -> Self` | | `with_permission_fail_mode` | `pub fn with_permission_fail_mode(mut self, permission: impl Into, mode: FailMode) -> Self` | | `with_retry` | `pub fn with_retry(mut self, policy: RetryPolicy) -> Self` | | `with_queue` | `pub fn with_queue(mut self, queue: Arc) -> Self` | | `with_redactor` | `pub fn with_redactor(mut self, redactor: Redactor) -> Self` | | `observe` | `pub fn observe(mut self, observer: impl Fn(&AuditRecord, AuditStatus) + Send + Sync + 'static) -> Self` | | `queue` | `pub fn queue(&self) -> &Arc` | | `stats` | `pub fn stats(&self) -> AuditStats` | | `flush` | `pub fn flush(&self) -> usize` | | `chain_head` | `pub fn chain_head(&self) -> Option` | | `with_clock` | `pub fn with_clock(mut self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self` | | `resume_chain` | `pub fn resume_chain(self, last_hash: impl Into) -> Self` | | `level` | `pub fn level(&self) -> AuditLevel` | | `decide` | `pub fn decide( &self, engine: &Engine, ctx: &Context<'_>, request: &Request<'_>, meta: &Attributes) -> (Decision, Result)` | | `decision` | `pub fn decision( &self, request: &Request<'_>, decision: &Decision, meta: &Attributes) -> Result` | | `explained` | `pub fn explained(&self, explanation: &Explanation, meta: &Attributes) -> Result` | | `grant_mutation` | `pub fn grant_mutation( &self, actor: &Subject, mutation: &Mutation, before: &[Grant], result: &Result, Vec>, meta: &Attributes) -> Result` | | `grant_mutation_with` | `pub fn grant_mutation_with( &self, actor: &Subject, mutation: &Mutation, before: &[Grant], result: &Result, Vec>, meta: &Attributes, call: Option) -> Result` | | `grant_mutation_impact` | `pub fn grant_mutation_impact( &self, actor: &Subject, mutation: &Mutation, before: &[Grant], result: &Result, Vec>, meta: &Attributes, call: Option, impact: Option<&Impact>) -> Result` | | `tuple_change` | `pub fn tuple_change( &self, actor: &Subject, added: bool, tuple: &Tuple, outcome: AuditOutcome, meta: &Attributes) -> Result` | | `exclusive` | `pub fn exclusive( &self, actor: &Subject, action: AuditAction, resource: &ObjectRef, outcome: AuditOutcome, at: u64, meta: &Attributes) -> Result` | | `role_change` | `pub fn role_change( &self, actor: &Subject, assigned: bool, change: &RoleChange, outcome: AuditOutcome, meta: &Attributes) -> Result` | #### `ChainError` #### `Hash` A SHA-256 digest. #### `MerkleError` Why a proof was refused. #### `MerkleTree` A tree kept in memory, for building proofs over a stretch of the trail. | Method | Signature | | --- | --- | | `new` | `pub fn new(leaves: Vec) -> Self` | | `from_records` | `pub fn from_records(records: &[AuditRecord]) -> Result` | | `size` | `pub fn size(&self) -> usize` | | `root` | `pub fn root(&self) -> Hash` | | `root_at` | `pub fn root_at(&self, size: usize) -> Option` | | `inclusion_proof` | `pub fn inclusion_proof(&self, index: usize) -> Option>` | | `consistency_proof` | `pub fn consistency_proof(&self, first: usize) -> Option>` | #### `TimestampError` Why a request could not be built or a response was refused. | Method | Signature | | --- | --- | | `code` | `pub fn code(&self) -> &'static str` | #### `HashAlgorithm` A hash algorithm for the stamped digest. | Method | Signature | | --- | --- | | `name` | `pub fn name(self) -> &'static str` | #### `TimestampRequest` A `TimeStampReq` (RFC 3161 §2.4.1) to send to a TSA. | Method | Signature | | --- | --- | | `new` | `pub fn new(algorithm: HashAlgorithm, digest: Vec) -> Self` | | `for_chain_head` | `pub fn for_chain_head(head: &str, nonce: Option) -> Result` | | `to_der` | `pub fn to_der(&self) -> Result>` | #### `TimestampInfo` What a verified time stamp states. #### `VerifyOptions` What to check besides the signature. | Method | Signature | | --- | --- | | `new` | `pub fn new(imprint: Vec, trusted_roots: Vec>) -> Self` | | `for_chain_head` | `pub fn for_chain_head(head: &str, trusted_roots: Vec>) -> Result` | #### `LineError` A line of a JSON Lines trail that is not an audit record. #### `Period` The span of time the records cover. #### `BreakKind` How a record fails the chain. #### `ChainBreak` One place where the chain does not hold. #### `ChainStatus` The state of the hash chain. #### `Anchors` Anchors known from outside the trail. | Method | Signature | | --- | --- | | `head` | `pub fn head(mut self, head: impl Into) -> Self` | | `start` | `pub fn start(mut self, start: impl Into) -> Self` | #### `AnchorCheck` Outcome of comparing the trail with an anchor. #### `TimestampCheck` Result of verifying one time stamp, filled by the caller (see `timestamp`). | Method | Signature | | --- | --- | | `verified` | `pub fn verified(label: impl Into, gen_time: i64, policy: String, serial: String) -> Self` | | `failed` | `pub fn failed(label: impl Into, error: impl Into) -> Self` | #### `ConformanceReport` The report. | Method | Signature | | --- | --- | | `build` | `pub fn build(records: &[AuditRecord], anchors: &Anchors) -> Self` | | `from_json_lines` | `pub fn from_json_lines(text: &str, anchors: &Anchors) -> Self` | | `with_timestamps` | `pub fn with_timestamps(mut self, timestamps: Vec) -> Self` | | `is_conforming` | `pub fn is_conforming(&self) -> bool` | ## Policy language and tooling Needs the `dsl` feature (`dsl-fs` adds the file store, `import` the Casbin and OpenFGA importers). The DSL schema is `DSL_SCHEMA` 5. Walk-throughs: [Policy language](https://strig.vercel.app/docs/policy-language.md), [Diff and lint](https://strig.vercel.app/docs/tools/diff-lint.md) and [Importers](https://strig.vercel.app/docs/tools/importers.md). #### `MAX_SOURCE_BYTES` The largest source accepted: input is external and unbounded. #### `DSL_SCHEMA` The version of the canonical JSON that `Policy::from_json` reads, frozen as stable from 1.0: it only grows, and a reader refuses a document newer than it. #### `Parsed` One source read and validated. #### More on `Policy` | Method | Signature | | --- | --- | | `validate` | `pub fn validate(&self) -> Result<(), Diagnostics>` | #### `ConvertError` Why a source could not be converted. #### `FormatError` Why a source could not be formatted. #### `Built` The policy a `Project` builds and where each of its elements was declared. #### `Project` Several sources, each in its own syntax, gathered into one policy. | Method | Signature | | --- | --- | | `new` | `pub fn new() -> Self` | | `len` | `pub fn len(&self) -> usize` | | `is_empty` | `pub fn is_empty(&self) -> bool` | | `add_source` | `pub fn add_source(&mut self, name: &str, text: &str) -> Result` | | `build` | `pub fn build(&self) -> Result` | #### `MAX_SOURCES` The most sources a project takes. #### `MAX_PROJECT_BYTES` The most bytes all the sources of a project may hold together. #### `MAX_FIXTURE_BYTES` The largest fixture `DiffFixture::parse` reads. #### `DiffFixture` The data a diff asks its questions about, besides the two policies. | Method | Signature | | --- | --- | | `parse` | `pub fn parse(file: &str, text: &str) -> Result` | #### `DiffError` Why a diff could not be made. #### `DiffOptions` What bounds the work of a diff. | Method | Signature | | --- | --- | | `with_limits` | `pub fn with_limits(mut self, limits: QueryLimits) -> Self` | #### `DiffSide` One version of a policy and, when it came from sources, where its elements are written. | Method | Signature | | --- | --- | | `new` | `pub fn new(policy: &'a Policy) -> Self` | | `with_origins` | `pub fn with_origins(mut self, origins: &'a Origins) -> Self` | #### `ChangeKind` Which way a decision moved. #### `Responsible` What decided on one side. #### `DecisionChange` A question whose answer differs between the two versions. #### `Universe` The questions a diff asked. #### `PolicyDiff` The decisions that differ between two versions. | Method | Signature | | --- | --- | | `is_empty` | `pub fn is_empty(&self) -> bool` | | `count` | `pub fn count(&self, kind: ChangeKind) -> usize` | #### `Severity` How much a finding matters. | Method | Signature | | --- | --- | | `name` | `pub const fn name(self) -> &'static str` | #### `LintCode` The kinds of finding. | Method | Signature | | --- | --- | | `code` | `pub const fn code(self) -> &'static str` | | `name` | `pub const fn name(self) -> &'static str` | | `severity` | `pub const fn severity(self) -> Severity` | | `parse` | `pub fn parse(text: &str) -> Option` | #### `Finding` One thing the lint found. | Method | Signature | | --- | --- | | `lint_code` | `pub fn lint_code(&self) -> Option` | | `position` | `pub fn position(&self) -> Option` | #### `LintOptions` What to leave out. | Method | Signature | | --- | --- | | `ignoring` | `pub fn ignoring(mut self, code: impl Into) -> Self` | #### `Report` What an import did: what was converted, what had no faithful translation and what was converted with a narrower reach. #### `ImportError` An import that could not be completed: the `Report` holds what was converted and what was not. ## Exclusive ownership Needs the `exclusive` feature. One holder per resource, with priority, preemption and a deadline. Walk-through: [Exclusive store](https://strig.vercel.app/docs/storage/exclusive-store.md). #### `DEFAULT_HOLD_PERMISSION` Permission that allows holding a resource exclusively, unless configured otherwise. #### `DEFAULT_PREEMPT_PERMISSION` Permission that allows taking a resource from a lower-priority holder, unless configured otherwise. #### `Lease` Active or expired ownership of a resource. | Method | Signature | | --- | --- | | `new` | `pub fn new(resource: ObjectRef, holder: ObjectRef, priority: i64, acquired_at: u64, expires_at: u64) -> Self` | | `is_active` | `pub fn is_active(&self, now: u64) -> bool` | | `granted` | `pub fn granted(claim: &Claim, now: u64) -> Self` | | `renewed` | `pub fn renewed(&self, now: u64, ttl_ms: u64) -> Self` | #### `Terms` Priority and duration of a claim. | Method | Signature | | --- | --- | | `new` | `pub fn new(priority: i64, ttl_ms: u64) -> Self` | #### `Claim` Request to own `resource` on behalf of `holder`. | Method | Signature | | --- | --- | | `new` | `pub fn new(resource: ObjectRef, holder: ObjectRef, terms: Terms) -> Self` | #### `Preemption` Whether `ExclusiveRegistry::acquire` may take a resource from a lower-priority holder. #### `Acquisition` Outcome of an acquisition. | Method | Signature | | --- | --- | | `decide` | `pub fn decide(current: Option, claim: &Claim, now: u64, preemption: Preemption) -> Self` | #### `OwnedChange` Outcome of a change only the holder can make: `ExclusiveStore::renew_lease` and `ExclusiveStore::release_lease`. | Method | Signature | | --- | --- | | `decide` | `pub fn decide(current: Option, holder: &ObjectRef, now: u64) -> Self` | #### `StoreError` Failure to read or write the lease store. #### `ExclusiveError` #### `ExclusiveStore` Persistence of the leases, one per resource. #### `MemoryExclusiveStore` Leases in memory. | Method | Signature | | --- | --- | | `new` | `pub fn new() -> Self` | #### `ExclusivePermissions` Names of the permissions the checked acquisition asks the engine for. | Method | Signature | | --- | --- | | `new` | `pub fn new(hold: impl Into, preempt: impl Into) -> Self` | #### `ExclusiveRegistry` Exclusive ownership of resources over a store. | Method | Signature | | --- | --- | | `new` | `pub fn new(store: S) -> Self` | | `with_permissions` | `pub fn with_permissions(mut self, permissions: ExclusivePermissions) -> Self` | | `with_max_ttl` | `pub fn with_max_ttl(mut self, max_ttl_ms: u64) -> Self` | | `with_audit` | `pub fn with_audit(mut self, auditor: Arc) -> Self` | | `permissions` | `pub fn permissions(&self) -> &ExclusivePermissions` | | `store` | `pub fn store(&self) -> &S` | | `validate` | `pub fn validate(&self, engine: &Engine) -> Result<(), ExclusiveError>` | | `holder` | `pub fn holder(&self, resource: &ObjectRef, now: u64) -> Result, ExclusiveError>` | | `acquire` | `pub fn acquire(&mut self, claim: &Claim, now: u64, preemption: Preemption) -> Result` | | `acquire_checked` | `pub fn acquire_checked( &mut self, engine: &Engine, ctx: &Context<'_>, subject: &Subject, resource: &Resource, terms: Terms, now: u64) -> Result` | | `release` | `pub fn release(&mut self, resource: &ObjectRef, holder: &ObjectRef, now: u64) -> Result` | | `renew` | `pub fn renew( &mut self, resource: &ObjectRef, holder: &ObjectRef, now: u64, ttl_ms: u64) -> Result` | | `renew_checked` | `pub fn renew_checked( &mut self, engine: &Engine, ctx: &Context<'_>, subject: &Subject, resource: &Resource, now: u64, ttl_ms: u64) -> Result` | | `expire` | `pub fn expire(&mut self, now: u64) -> Result, ExclusiveError>` | ## Real time: strig-sync `strig-sync = "0.10"`. A permission change becomes a `Change` notice; the `Hub` delivers it to the sessions and caches of this instance and publishes it on a `Transport` for the others. A notice never carries grants: whoever receives it reloads from its own source. ### Hub::builder ``` pub fn builder() -> HubBuilder pub fn new() -> Self ``` A hub with a transport, or a local-only hub with `Hub::new`. The builder takes `capacity(usize)`, `origin(impl Into)`, `transport(impl Transport)` and `shared_transport(Arc)`, then `build() -> Hub`. The channel capacity is 1024 and the origin is random until you set one. ### Hub::publish ``` pub async fn publish(&self, mut change: Change) -> Result ``` Stamps origin, sequence and time, delivers locally and publishes on the transport. Local delivery happens even when the transport fails; the error comes back to the caller. ### Hub::spawn_relay ``` pub fn spawn_relay(&self) -> RelayHandle ``` Listens to the transport in the background and delivers what the other instances publish. It reconnects with backoff from 100 ms to 5 s and emits `Resync` on each reconnection. It stops when the `RelayHandle` is dropped. ### Hub::on_change, Hub::subscribe ``` pub fn on_change(&self, sink: Arc) pub fn subscribe(&self) -> broadcast::Receiver ``` A synchronous sink for every change, or a broadcast receiver. A closure `Fn(&Change)` is a `ChangeSink`, and so is `CapabilityCache`. ### Hub::schedule_expiry ``` pub fn schedule_expiry(&self, boundary_ms: u64, now_ms: u64, change: Change) -> bool ``` Delivers `change` on this instance when the clock reaches `boundary_ms`, so a grant that starts or stops recomputes without a write. It never goes through the transport. Returns `false` outside a Tokio runtime. ### Change #### Change ``` pub struct Change { pub kind: ChangeKind, pub scope: Anchor, pub subject: Option, pub id: Option, pub origin: String, pub seq: u64, pub at: u64 } ``` What changed and on which step of the path. `origin`, `seq` and `at` are filled in by the hub. Serialized as JSON, which is also the wire format of the transports. #### ChangeKind ``` pub enum ChangeKind { Grants, Tuples, Roles, Catalog, Custom, Resync } ``` `Custom` is an application change that also invalidates permissions, such as a customer plan. `Resync` means the node lost changes and must reload everything. | Constructor | Signature | | --- | --- | | `Change::new` | `pub fn new(kind: ChangeKind, scope: Anchor) -> Self` | | `Change::grants`, `Change::tuples` | `pub fn grants(scope: Anchor) -> Self` | | `Change::roles` | `pub fn roles(subject: impl Into, scope: Anchor) -> Self` | | `Change::catalog`, `Change::resync` | `pub fn catalog() -> Self` | | `Change::expiry` | `pub fn expiry(subject: impl Into) -> Self` | | `Change::expiry_for_everyone` | `pub fn expiry_for_everyone() -> Self` | | `for_subject`, `with_id` | `pub fn for_subject(mut self, subject: impl Into) -> Self` | ### Transport #### Transport ``` pub trait Transport: Send + Sync + 'static { fn name(&self) -> &str; async fn publish(&self, change: &Change) -> Result<(), TransportError>; async fn subscribe(&self) -> Result; } ``` The medium between instances. Delivery is at most once: the hub covers a gap with `Resync`. `strig-redis` and `strig-postgres` implement it; another broker plugs in the same way. `MemoryTransport::new(capacity: usize)` is for tests and shares one channel between clones. #### TransportError ``` pub enum TransportError { Connection(String), Decode(String), Closed } ``` Match on the variant: the text is Portuguese. ### Sessions #### Session::open ``` pub fn open(hub: &Hub, subject: Subject, scopes: Vec, provider: Option>, options: SessionOptions) -> (SessionControl, SessionStream) ``` A client's session, independent of the web framework. The stream yields the `ServerMessage`s to write to SSE or WebSocket; the control passes on what the client sends. #### SessionOptions ``` pub struct SessionOptions { pub heartbeat: Option, pub buffer: usize } ``` The `ping` interval, 25 s by default, and the messages queued for a slow client, 64 by default. #### SessionControl ``` pub async fn send(&self, message: ClientMessage) -> bool pub async fn handle_text(&self, text: &str) -> Result ``` `send` returns `false` once the session ended. `handle_text` takes a WebSocket text frame; invalid JSON is an error and the session goes on. | Message | Direction | Fields | | --- | --- | --- | | `ServerMessage::Hello` | server to client | `origin`, `subject` | | `ServerMessage::Capabilities` | server to client | `scope`, `set`: replaces the previous set | | `ServerMessage::Change` | server to client | `change` | | `ServerMessage::Resync` | server to client | none: discard what you have and wait for new `capabilities` | | `ServerMessage::Error`, `Ping` | server to client | `message`; none | | `ClientMessage::Watch`, `Unwatch` | client to server | `scopes`; WebSocket only | | `ClientMessage::Refresh` | client to server | none: ask again for every watched scope | `ServerMessage` has `event_name`, `to_json` and `to_sse`; `ClientMessage::from_json` reads a frame. `scope_to_string(&Resource) -> String` and `scope_from_str(&str) -> Resource` convert the `kind:id/kind:id` form. ### Capabilities and the cache #### CapabilityProvider ``` pub trait CapabilityProvider: Send + Sync + 'static { async fn capabilities(&self, subject: &Subject, scope: &Resource) -> Result; } ``` Computes what a session sends to its client. `evaluate` and `now_ms` have defaults; override `evaluate` when you know the candidate grants, so the expiry notice sees grants that start later. #### GrantLoader ``` pub trait GrantLoader: Send + Sync + 'static { async fn load(&self, subject: &Subject, scope: &Resource) -> Result, BoxError>; } ``` Fetches the candidate grants of a subject in a scope. Return the grants that start later too. A `Vec` is a loader. #### EngineProvider ``` pub fn new(engine: Arc, loader: L) -> Self pub fn with_clock(mut self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self pub fn with_cache(mut self, cache: Arc) -> Self ``` The default provider: loads through the loader, filters with `Engine::capabilities`, stores in the cache. Register the same cache on the hub with `hub.on_change(cache.clone())`. #### CapabilityCache ``` pub fn new(ttl: Duration, capacity: usize) -> Self pub fn get(&self, subject: &Subject, scope: &Resource) -> Option pub fn insert(&self, subject: &Subject, scope: &Resource, set: CapabilitySet) ``` A cache of `CapabilitySet`, invalidated by the hub. `TtlCache` is the generic one underneath. ## axum routes: strig-axum `strig-axum = "0.10"`. Authentication stays with your application: your handler identifies the subject and calls the route. ### Realtime::new ``` pub fn new(hub: Hub) -> Self pub fn with_provider(mut self, provider: Arc) -> Self pub fn with_options(mut self, options: SessionOptions) -> Self pub fn hub(&self) -> &Hub ``` The hub, an optional provider and the session options, shared by the routes. With a provider, a session sends the capabilities of each scope and again on every change. `Realtime` is `Clone`, so it fits axum state. ### Realtime::sse ``` pub fn sse(&self, subject: Subject, scopes: Vec) -> Sse> + use<>> ``` A `text/event-stream` response. SSE is one-way, so the scopes are fixed when the connection opens. ### Realtime::websocket ``` pub fn websocket(&self, upgrade: WebSocketUpgrade, subject: Subject, scopes: Vec) -> Response ``` Performs the upgrade and binds the socket to a session. The client can then send `watch`, `unwatch` and `refresh`; invalid JSON gets an `error` message and the socket stays open. ## Transports Both are a `Transport` for `Hub::builder().transport(..)`. ### RedisTransport::new ``` pub fn new(url: &str, channel: impl Into) -> Result pub fn from_client(client: Client, channel: impl Into) -> Self pub fn channel(&self) -> &str ``` `strig-redis = "0.10"`. Redis pub/sub. Publishing reconnects on its own; each `subscribe` opens a dedicated connection, and when it drops the hub reopens it and emits `Resync`. ### PgTransport::new ``` pub fn new(url: &str, channel: impl Into) -> Result pub fn with_tls(url: &str, channel: impl Into, tls: T) -> Result ``` `strig-postgres = "0.10"`. Postgres `LISTEN/NOTIFY`, without TLS or with any `tokio-postgres` connector. ### strig_postgres::notify ``` pub async fn notify(client: &C, channel: &str, change: &Change) -> Result<(), TransportError> ``` Sends a change through a client or a transaction. `NOTIFY` goes out on commit, so a notice sent in the transaction that writes the grant goes out only if the write does. It arrives without an origin, so every instance delivers it, the writer included. `MAX_PAYLOAD` is 7999 bytes. ### Postgres queries The `strig_postgres::query` module stores grants and tuples and turns a listing into a `WHERE`. Values reach the database as bound parameters; only table and column names are spliced into SQL, after they are checked as plain identifiers. | Item | Signature | What it does | | --- | --- | --- | | `PgTables::new` | `pub fn new(grants: impl Into, tuples: impl Into) -> Result` | Names the two tables; the default is `strig_grants` and `strig_tuples`. | | `PgTables::schema_sql` | `pub fn schema_sql(&self) -> String` | The DDL of both tables and their indexes. Safe to run twice. | | `PgTables::put_grant` | `pub async fn put_grant(&self, client: &C, grant: &Grant) -> Result<(), PgQueryError>` | Stores a grant. | | `PgTables::grants_by_permission` | `pub async fn grants_by_permission(&self, client: &C, permissions: &[&str], now: Option) -> Result, PgQueryError>` | Loads the rows a listing reads. `grants_by_target_kind` and `grants_by_subject` are the siblings. | | `PgTable::new` | `pub fn new(kind: impl Into, id_column: impl Into) -> Result` | The table of the resources; add `path_column` and `attr_column`. | | `filter_where` | `pub fn filter_where(filter: &AccessFilter, layout: &PathLayout, table: &PgTable, first_param: usize) -> Result` | An `AccessFilter` as a parameterized `WHERE`, with the residue to check row by row. | | `window_predicate` | `pub fn window_predicate(columns: &WindowColumns, param_index: usize, now: Option) -> Result` | The validity-window filter. Do not feed `EngineProvider` with it. | | `candidate_predicate` | `pub fn candidate_predicate(columns: &WindowColumns, param_index: usize, now: u64) -> Result` | Every grant that has not expired, so a grant that starts later still triggers its recompute. | `PgQueryError` is `#[non_exhaustive]` and prints English: `InvalidIdentifier`, `UnmappedAttribute`, `UnmappedKind`, `UnsupportedExpr`, `EmptyUsersetRelation`, `Residual`, `InstantOutOfRange`, `Database`, `Decode`. A listing that reads an attribute or a path kind with no column fails loudly, because reading it as "no row" would open access under a deny. ### Postgres stores `strig-postgres = "0.10"`. Every store is built from a `PgTables` and a connection URL; each has a `connect_with_tls` twin that takes a TLS connector, and `with_timeout` bounds every statement. | Item | Signature | What it does | | --- | --- | --- | | `connect` | `pub async fn connect(url: &str) -> Result` | Opens a plain connection and spawns its driver task. | | `migrate` | `pub async fn migrate(client: &Client) -> Result, PgQueryError>` | Brings the default tables up to `LATEST_VERSION` and returns the versions it applied. Additive and idempotent. | | `migrate_with` | `pub async fn migrate_with(client: &Client, tables: &PgTables) -> Result, PgQueryError>` | The same, for custom table names. | | `schema_version` | `pub async fn schema_version(client: &Client, tables: &PgTables) -> Result, PgQueryError>` | The version in the ledger, or `None` before the first migration. | | `PgStore::load` | `pub async fn load(client: &C, tables: PgTables) -> Result` | Reads grants and tuples into memory. | | `PgStore::reload` | `pub async fn reload(&self, client: &C) -> Result<(), PgQueryError>` | Reads both again; `reload_grants` and `reload_tuples` read one. | | `PgStore::is_stale` | `pub fn is_stale(&self) -> bool` | True when the last reload failed; cleared by the next one that succeeds. | | `PgStore::grants` | `pub fn grants(&self) -> PgGrants` | A `GrantSource` and `GrantIndex` over the snapshot; `tuples` gives the `TupleStore` and `TupleIndex`. | | `PgStore::follow` | `pub fn follow(&self, changes: broadcast::Receiver, connect: F, retry: Duration) -> JoinHandle<()>` | Reloads on every `Change`; a failed reload is retried every `retry` and the store reads as stale meanwhile. | | `PgTables::assign_role` | `pub async fn assign_role(&self, client: &C, subject: &Subject, role: &RoleAssignment) -> Result<(), PgQueryError>` | Stores a role assignment; `revoke_role`, `roles_of` and `subject` are the siblings. | | `PgTables::commit_mutation` | `pub async fn commit_mutation(&self, client: &C, channel: &str, mutation: &Mutation) -> Result, PgQueryError>` | Applies a governed `Mutation` and notifies on `channel`, in one transaction under `lock_governance`. | | `PgPendingStore` | `connect(url: &str, tables: PgTables) -> Result` | A `PendingStore` in a table; `due(now)` lists requests past their deadline. | | `PgRecertStore` | `connect(url: &str, tables: PgTables) -> Result` | A `RecertStore` in a table. | | `PgExclusiveStore` | `connect(url: &str, tables: PgTables) -> Result` | An `ExclusiveStore` in a table. Needs the `exclusive` feature. | ### Redis store `strig-redis = "0.10"` has one public type, `RedisExclusiveStore`, an `ExclusiveStore` for a resource held across processes. | Item | Signature | What it does | | --- | --- | --- | | `new` | `pub fn new(url: &str, prefix: impl Into) -> Result` | Does not connect yet; fails if the URL does not parse or the prefix is empty. `prefix` namespaces every key. | | `from_client` | `pub fn from_client(client: Client, prefix: impl Into) -> Result` | Reuses a client you already have. | | `with_timeout` | `pub fn with_timeout(mut self, timeout: Duration) -> Self` | Bounds every command. | | `with_retention` | `pub fn with_retention(mut self, retention: Duration) -> Self` | How long a lease that ran out stays in Redis for the sweep to find. Default one hour. | ## Decision server: strig-server `strig-server = "0.10"`, with the `client` feature on by default. The server answers over HTTP from a `DecisionSource` you provide and decides with its own clock. It does no authentication and no rate limiting: put it behind your gateway. Any answer that is not a `200` from a decision route means no access. ### DecisionServer::router ``` pub fn new(source: Arc) -> Self pub fn with_clock(mut self, clock: Arc) -> Self pub fn with_config(mut self, config: ServerConfig) -> Self pub fn router(self) -> Router ``` Builds the axum router. Routes: `POST /v1/check`, `/v1/check/batch`, `/v1/list`, `/v1/who`, `/v1/access`, and `GET /health/live`, `/health/ready`. ### DecisionSource ``` pub trait DecisionSource: Send + Sync + 'static { async fn snapshot(&self) -> Result, SourceError>; } ``` Loads the data of one answer. When it fails, the server answers 503 and denies. `Snapshot::new(engine: Arc, grants: Vec)` holds the engine and the grants; `MemorySource::new(snapshot)` keeps one in memory, and `replace` swaps it without a restart. ### ServerConfig ``` pub fn with_max_body_bytes(mut self, bytes: usize) -> Self pub fn with_max_batch(mut self, items: usize) -> Self pub fn with_max_resources(mut self, items: usize) -> Self pub fn with_default_timeout(mut self, timeout: Duration) -> Self pub fn with_max_timeout(mut self, timeout: Duration) -> Self pub fn with_query_limits(mut self, limits: QueryLimits) -> Self pub fn with_max_work(mut self, work: usize) -> Self pub fn with_max_concurrent_work(mut self, slots: usize) -> Self ``` The limits. Defaults: body 1 MiB, batch 256 checks, 1000 resources, work 1 000 000 (checks times grants), deadline 2 s with a ceiling of 10 s. A request sets its deadline with the `x-strig-timeout-ms` header. | Status | `error.code` | Meaning | | --- | --- | --- | | 400 | `malformed_json`, `invalid_request`, `batch_too_large`, `too_many_resources` | The request is wrong; retrying it unchanged fails again. | | 404, 405 | `not_found`, `method_not_allowed` | No such route, or the wrong method. | | 413, 415 | `body_too_large`, `unsupported_media_type` | The body is over the limit, or is not `application/json`. | | 503 | `source_unavailable`, `query_limit_exceeded`, `overloaded`, `relation_depth_exceeded`, `deadline_exceeded`, `clock_unavailable`, `internal` | The server could not decide: deny, and retry later. | The body is `{"error": {"code": "...", "message": "..."}}`. `code` is stable; `message` is fixed per code and never carries table names or driver text. ### The Rust client #### Client::http ``` pub fn http(base_url: impl Into, config: ClientConfig) -> Self pub fn new(transport: Arc, config: ClientConfig) -> Self ``` A client over plain HTTP, or over any `Transport`. Every call has a timeout, 2 s by default, sent to the server as the deadline. A circuit breaker opens after 5 consecutive failures and refuses calls for 30 s before it lets one probe through; `4xx` does not count. #### Client::check ``` pub async fn check(&self, request: &CheckRequest) -> ClientDecision pub async fn check_batch(&self, requests: &[CheckRequest]) -> Vec ``` `CheckRequest` and the other request types are in `strig_server::wire`. A failed check is `ClientDecision::Denied(Failure)`, never an allow. A batch is one call and keeps the order; if it fails, every check is denied with the same cause. #### Client::list, who, access ``` pub async fn list(&self, request: &ListRequest) -> Result pub async fn who(&self, request: &WhoRequest) -> Result pub async fn access(&self, request: &AccessRequest) -> Result ``` There is no deny to fall back on, so they return `Err(Failure)`: show nothing. #### ClientDecision, Failure ``` pub enum ClientDecision { Remote(CheckResponse), Denied(Failure) } ``` `is_allowed`, `effect`, `decision` and `failure` read it. `Failure` is `#[non_exhaustive]`: `CircuitOpen`, `Timeout`, `Unreachable`, `Server`, `Rejected`, `UnexpectedStatus` and `InvalidResponse`. A code the client does not know is `ErrorCode::Unknown(String)`. ## HTTP API `strig-server` speaks JSON over HTTP. A request and its answer: ```bash curl -s localhost:8080/v1/check \ -H 'content-type: application/json' \ -H 'x-strig-timeout-ms: 500' \ -d '{"subject":{"kind":"user","id":"ana"},"permission":"document.view","resource":{"kind":"document","id":"d1"}}' ``` ```json {"decision": {"effect": "allow"}, "evaluated_at": 1700000000000, "requested_at": 1700000000000} ``` All times are milliseconds since the Unix epoch, UTC. The server decides with its own clock: `at` in a body is echoed for audit and never used to decide. There is no authentication and no rate limiting; put the server behind your gateway. **Fail closed.** Only `200` from a decision route is a success. A network error, a timeout, any other status and an unreadable `200` all mean no access. A deny is a normal `200` with `effect: "deny"`. ### Routes | Route | Body | Answer | | --- | --- | --- | | `POST /v1/check` | `subject`, `permission`, `resource`, optional `env`, `at`, `min_revision` | `decision`, `evaluated_at`, `requested_at`, and `revision` when the source tracks one. | | `POST /v1/check/batch` | `{"checks": [...]}` | `{"results": [...]}` in request order. All or nothing: a failure is one error, never partial results. | | `POST /v1/list` | `subject`, `permission`, `kind`, optional `layout`, `resources`, `env`, `at` | `kind`, `permission`, `exact`, `shape`, `residual`, `warnings`, `evaluated_at`, and `ids` when `resources` was sent. Never read `residual` as an allow. | | `POST /v1/who` | `permission`, optional `resource`, `env`, `at` | `entries` (each with a typed `subject` and the `via` that grants it), `except`, `evaluated_at`. | | `POST /v1/access` | `resource`, `env`, `at` | Who holds which permission on the resource, with the path that decided each. | | `GET /health/live` | none | `200 {"status":"live"}` while the process runs. | | `GET /health/ready` | none | `200 {"status":"ready"}` when the grant source answers; otherwise `503`, so the instance leaves the pool. | `shape.type` in a list answer is `nothing`, `kind` (with `except`), `ids`, `within` (with `anchors`) or `compound` (with `expr`). ### Headers | Header | Effect | | --- | --- | | `x-strig-timeout-ms: ` | Deadline of this request, capped at the server's ceiling (default 10 s; default deadline 2 s). `0`, a negative number or text is `400 invalid_request`. A passed deadline is `503 deadline_exceeded`. | | `x-strig-min-revision: @` | Answer only from data at that revision or later (any route; `check` and `check/batch` also take `min_revision`). A source that is behind is polled until the deadline, then `503 revision_not_reached`. Another scope, or no revision at all, is `503 revision_mismatch` at once. A malformed token is `400 invalid_request`. | | `x-strig-reason: true` | On the AuthZEN and Envoy routes with `with_reasons(true)`: adds a fixed reason code to the answer. | ### Limits | Limit | Default | Past it | | --- | --- | --- | | Body | 1 MiB | `413 body_too_large` | | Batch | 256 checks | `400 batch_too_large` | | Candidate resources in a list | 1000 | `400 too_many_resources` | | Work (checks × grants) | 1 000 000 | `503 query_limit_exceeded` | | `QueryLimits` for `list`, `who`, `access` | 1000 and 100 000 | `503 query_limit_exceeded` | | Work slots | one per CPU | `503 overloaded` | ### Errors ```json {"error": {"code": "source_unavailable", "message": "the grant source is unavailable; access is denied"}} ``` `code` is stable and safe to branch on. `message` is fixed per code and never carries table names, paths or driver text. `4xx` means the request is wrong and retrying it unchanged fails again; `503` means the server could not decide: deny, and retry later. | Status | `error.code` | Meaning | | --- | --- | --- | | 400 | `malformed_json` | The body is not JSON. | | 400 | `invalid_request` | Valid JSON that does not fit the route, an unknown field, a `layout` that does not fit `kind`, a bad deadline header or a malformed revision token. | | 400 | `batch_too_large`, `too_many_resources` | Over the batch or the candidate limit. | | 404, 405 | `not_found`, `method_not_allowed` | No such route, or the wrong method. | | 413, 415 | `body_too_large`, `unsupported_media_type` | Body over the limit, or not `application/json`. | | 503 | `source_unavailable` | The grants or the policy could not be loaded. | | 503 | `query_limit_exceeded`, `overloaded`, `relation_depth_exceeded`, `deadline_exceeded` | A limit, the work slots, a relation chain too deep to read a deny, or the deadline. | | 503 | `revision_not_reached`, `revision_mismatch` | The source is behind the required revision, or tracks another scope. | | 503 | `clock_unavailable`, `internal` | No usable instant, or anything else inside the server, including a caught panic. | ### AuthZEN `DecisionServer::with_authzen(AuthzenConfig)` also serves the OpenID AuthZEN Authorization API 1.0 next to `/v1`; without it these routes answer `404`. Same body limit, deadline, work budget and absence of authentication. ```bash curl -s localhost:8080/access/v1/evaluation \ -H 'content-type: application/json' \ -d '{"subject":{"type":"user","id":"ana"},"action":{"name":"document.view"},"resource":{"type":"document","id":"d1"}}' ``` ```json {"decision": true} ``` | Route | Notes | | --- | --- | | `POST /access/v1/evaluation` | `{subject, action, resource, context?}` answers `{decision, context?}`. | | `POST /access/v1/evaluations` | Top-level `subject`, `action`, `resource`, `context` are defaults an item overrides. `options.evaluations_semantic` is `execute_all` (default), `deny_on_first_deny` or `permit_on_first_permit`; anything else is `400`. | | `POST /access/v1/search/subject` | Subjects of `subject.type` that hold `action.name` on `resource`. | | `POST /access/v1/search/action` | The permissions of the catalog that `subject` holds on `resource`. | | `POST /access/v1/search/resource` | Only with `AuthzenConfig::with_resource_catalog`; otherwise `404`. | | `GET /.well-known/authzen-configuration` | Only with `AuthzenConfig::with_issuer` (an `https` URL); otherwise `404`. | | AuthZEN | Strig | | --- | --- | | `subject.type`, `subject.id` | `Subject.kind`, `Subject.id`. Kinds in `authenticated_kinds` (default `user`) also carry the `authenticated` principal. | | `subject.properties` | Attributes. `roles` (default name) holds the roles, as strings or `{role, scope?, valid_from?, valid_until?}`; `principals` holds principal names. Neither becomes an attribute. | | `resource.type`, `resource.id` | The first step of the path, `type:id`. | | `resource.properties` | Attributes. `path` (default name) holds the broader steps, most specific first. With a `PathResolver` the server's answer is used instead; a resource it does not know is a deny with `context.error.status` `404`. | | `action.name` | The permission. `action.properties` is not read. | | `context` | `env`. The server replaces `now` with its clock. | `decision` is `true` only for an allow; a permission outside the catalog is `200 {"decision": false}`. With `with_reasons(true)` and the header `x-strig-reason: true`, `context.reason` is one of `override`, `grant`, `no_applicable_grant`, `unknown_permission`, `missing_prerequisite`; it never names a grant, role or permission. Errors use the `/v1` error body with the statuses of the spec: `400` for a request that does not fit, `500` for everything the server could not decide. Searches are sorted and take `page: {token?, limit?}` (`limit` defaults to and is capped by `with_max_page_size`, 1000); the answer carries `page: {next_token, count, total}`, and `next_token` is `""` on the last page. A token is bound to its request: change the entity, the context or the limit and it is `400`. Subject search sets `context.incomplete` to `true` when a party that is not a subject of a type (role, principal, userset, wildcard, `anyone`) was left out. `signed_metadata`, `capabilities`, tenant suffixes of the well-known URI, `action.properties` and `page.properties` are not read. ### Envoy external authorization With the `envoy` feature, `DecisionServer::envoy_service(EnvoyConfig)` builds the `envoy.service.auth.v3.Authorization` gRPC service over the same source, clock, limits and work slots as the HTTP routes. Take it before `router()`, which consumes the server. Without the feature the crate has no `tonic` or `prost` in its build. | `CheckRequest` | Strig | | --- | --- | | `attributes.request.http.method` and `path` | The first route whose methods and pattern match decides. A path with dot segments, an empty middle segment, an encoded `/`, `\` or NUL, invalid UTF-8 or more than 64 segments matches no route. | | A header (`with_subject_header`) or filter metadata (`with_subject_metadata`) | The subject id, of the kind `with_subject_kind` (default `user`), with the `authenticated` principal. A value that is empty, over 512 bytes or holds a comma is no subject. | | A header (`with_roles_header`), comma-separated | The roles, up to 64 of at most 512 bytes; past that there is no subject. | | `RouteRule::require(permission, ResourceTemplate::new(kind, id))` | The permission and the resource; `{param}` is filled from the path. A template naming a parameter the pattern lacks fails at configuration. | | `with_path_resolver` | The broader steps of the resource, as for AuthZEN. | Patterns start with `/`; a segment is a literal, `{name}` (one segment, captured), `*` (one segment) or, last, `**` (the rest). Methods are `*` or a list such as `GET,HEAD`. Rules are tried in the order they were added. The adapter trusts the subject and roles it reads: Envoy must set those headers itself and overwrite what the client sent. | Case | `status.code` | HTTP | `x-strig-reason` (with `with_reasons(true)`) | | --- | --- | --- | --- | | The engine allows, or the route is `public` | `OK` (0) | | | | The engine denies | `PERMISSION_DENIED` (7) | 403 | `denied` | | No route matches | same | 403 | `no_route` | | No usable subject on a route that needs one | same | 403 | `no_subject` | | The resolver does not know the resource | same | 403 | `unknown_resource` | | Source down, deadline passed, no work slot, clock or work failed | same | 403 | `unavailable` | | No HTTP attributes, or a template that cannot be filled | same | 403 | `bad_request` | A `public` route decides nothing and does not read the source, so it allows even while the source is down. A message over `max_body_bytes` or a call that outlives `max_timeout` is a gRPC error (`RESOURCE_EXHAUSTED`, `CANCELLED`): leave `failure_mode_allow: false` in the Envoy filter so Envoy denies on those too. ## Command line: strig-cli `cargo install strig-cli` installs the `strig` binary. Every command exits `0` when it did what you asked, `1` when a case failed, a finding matched or a change has no faithful translation, and `2` when the arguments, the policy or a test file are wrong or there is nothing to run. ```text $ strig test policies/ $ echo $? 1 ``` | Command | What it does | | --- | --- | | `strig test [--junit ]` | Runs the `*.strig-test.json` files of `` against its `*.strig` policy. `--junit` also writes JUnit XML. | | `strig audit report [--json] [--anchor-head ] [--anchor-start ] [--timestamp ]... [--root ]...` | Conformance report over an audit trail. Exits `1` when it does not conform. See [Audit](https://strig.vercel.app/docs/audit.md). | | `strig import casbin -o [--language ] [--action ]...` | Converts a Casbin model and policy into `/policy.strig`. Exits `1` when part of it has no faithful translation. | | `strig import openfga -o [--language ]` | The same for an OpenFGA model and tuples. `--action` is Casbin only. | | `strig diff [--fixture ] [--now ] [--json] [--fail-on allow\|any] [--max-subjects ] [--max-decisions ]` | The decisions that change between two versions of a policy (directories or `*.strig` files). Exits `1` when a change matches `--fail-on` (default `any`). | | `strig lint [--json] [--ignore ]... [--config ] [--fail-on error\|warning\|info\|never]` | Findings about dead or suspicious policy. Exits `1` on a warning or worse. | | `strig help` | Prints the usage text. `--help` and `-h` do the same. | ## Policies at compile time: strig-macros `strig-macros = "0.10"`. A policy that does not validate does not build. Add `strig` with the `dsl` feature to your own `Cargo.toml`, and use the same version of both: `strig-macros` pins `strig` with `=`. ### policy! ``` policy!("") ``` Compiles and validates a policy written as a text literal. The result is a `strig::dsl::Policy`. An error stops the build and points at the literal, with `policy:line:column` counted inside the text. Prefer a raw string for anything with several lines. ### include_policy! ``` include_policy!("") ``` The same, from a file relative to the `CARGO_MANIFEST_DIR` of the caller. The file must be inside the crate, and paths through `target/` or a hidden component are refused, as are files over 4 MiB. An error reads `path:line:column: message`. The expansion embeds the validated policy as JSON and reads that JSON back on each evaluation; the policy text itself is not parsed at runtime. In a hot path, keep it in a `static` with `LazyLock`. ## JavaScript: the npm package `npm install @the-hades-organization/strig`, for Node, Bun and the browser. The native module (N-API) serves Node and Bun, WebAssembly serves the browser and is the fallback. The native module comes as one package per platform; see [JavaScript](https://strig.vercel.app/docs/javascript.md#install-by-platform). Set `STRIG_BACKEND=native` or `wasm` to force one. The Rust crate behind it, `strig-node`, is not published on its own. `call` condition functions, your own overrides and your own invariants are synchronous callbacks passed to `new Engine(spec, hooks)`; see [JavaScript](https://strig.vercel.app/docs/javascript.md#rules-written-in-javascript). The JSON spec covers the built-in `resource_owner` and `permission_holder`. ### load ``` export function load(options: { backend: 'native' }): Promise export function load(options?: { backend?: 'auto' | 'native' | 'wasm'; wasm?: unknown }): Promise ``` Loads a backend and returns `Engine`, `Context`, `Exclusive`, `auditEstimate`, `backend` and the policy-language functions (`compile`, `print`, `convert`, `format`, `isFormatted`, `loadProject`). `loadProjectDir` exists only on the native module. ### Engine ``` constructor(spec: unknown, hooks?: EngineHooks) decide(context: Context, request: DecisionRequest, now?: number | bigint): Decision check(context: Context, request: DecisionRequest, now?: number | bigint): boolean explain(context: Context, request: DecisionRequest, now?: number | bigint): Explanation ``` Takes the same `EngineSpec` JSON as Rust and, optionally, `EngineHooks` (callbacks, audit sink and policy). `Engine

` takes the union of your permission ids to make `check`, `decide`, `explain`, `list`, `whoCan`, `whoCanOn` and `checkFor` strict; see [Catalog types](https://strig.vercel.app/docs/javascript.md#catalog-types-for-the-frontend). `decide` returns the effect and a `reason` tagged by `kind`: `override`, `grant`, `no_applicable_grant`, `unknown_permission` or `missing_prerequisite`. The system clock is never used: pass `now`, or set it on the `Context`. ### Engine, the rest ``` capabilities(context: Context, subject: Subject, scope: Resource, now?: number | bigint): CapabilitySet validateGrant(grant: Grant): void list(context: Context, subject: Subject, permission: string, kind: string, options?: ListOptions, now?: number | bigint): ListResult whoCanOn(context: Context, permission: string, resource: Resource, now?: number | bigint): WhoCanOnResult apply(input: ApplyInput): ApplyResult ``` Also `whoCan`, `accessOf`, `checkFor`, `catalog`, `materialize` and `applyTemplate`. `apply` checks the invariants of a grant or role change and returns the violations, an audit record and `auditStatus`. `propose`, `resolve` and `expire` are the approval flow ([Approvals](https://strig.vercel.app/docs/approvals.md)); `flushAudit` and `auditStats` drive the retry queue ([Audit](https://strig.vercel.app/docs/audit.md)). ### Context ``` constructor(init?: { grants?: Grant[]; tuples?: unknown[]; env?: Record; now?: number | bigint | null; limits?: QueryLimits }) ``` The grants of a decision. Change it with `setGrants`, `addGrant`, `removeGrant`, `addTuple`, `setEnv`, `setNow` and `setLimits`. The instant persists, so a long-lived `Context` needs `setNow` on every request. Every error the binding throws has a stable `error.code`, the same on both backends: `INVALID_ARGUMENT`, `INVALID_INPUT`, `INVALID_SPEC`, `INVALID_GRANT`, `UNKNOWN_SUBJECT`, `QUERY_LIMIT_EXCEEDED`, `RELATION_DEPTH_EXCEEDED`, `QUERY_ERROR`, `UNKNOWN_INVARIANT`, `REENTRANT_CALL`, the `EXCLUSIVE_*` and `DSL_*` codes, and `INTERNAL`. A scalar argument that is not accepted, such as `NaN` or a negative instant, is `INVALID_ARGUMENT`; it is never coerced. | Import | What it gives you | | --- | --- | | `@the-hades-organization/strig` | `load`, the types and `scopeFromString(text: string): Resource`. | | `.../client` | `PermissionClient`: connects over SSE or WebSocket, keeps the capabilities of each scope and decides locally. Use it to shape the interface; the server still decides. | | `.../server` | `Hub`, `openSession`, `sseResponse`, `pipeSse`, `engineProvider` and the transports `redisTransport`, `ioredisTransport`, `pgTransport`. Notices use the `strig-sync` format, so Rust and JS instances can share a channel. | | `.../remote` | `RemoteClient`, `CircuitBreaker`: the client of a decision server. | | `.../express`, `.../fastify`, `.../nestjs` | `authorize`, `authorizeRoutes`, `createCan`; the Fastify `plugin`; `Can`, `StrigGuard` and `StrigRouteGuard`. Their framework is an optional peer dependency. See [Web frameworks](https://strig.vercel.app/docs/web-frameworks.md). | | `.../approvals` | `Approvals`, `MemoryPendingStore`, `PendingStoreError`. See [Approvals](https://strig.vercel.app/docs/approvals.md). | | `.../store` | `openJsonStore`, `JsonFileStore`, `JsonStoreError`, `STORE_VERSION`. See [JavaScript](https://strig.vercel.app/docs/javascript.md#grants-and-roles-in-a-json-file). | | `.../testing` | `expressRoutes`, `nestRoutes`, `collectFastifyRoutes`, `auditRoutes`, `assertRoutesCovered`. See [Web frameworks](https://strig.vercel.app/docs/web-frameworks.md#test-the-table). | | `.../types` | `generateTypes`; the `strig-types` command writes the same output. | ### authorize ``` export function authorize(options: AuthorizerOptions): Handler ``` Express middleware that calls `next()` only on an allow. A caller with no subject gets 401, a deny 403, a decision that could not be made 503 and an extractor error 500; change them with `unauthenticatedStatus`, `denyStatus`, `failureStatus` and `errorStatus`. Pass exactly one of `local: { engine, context, now }` and `remote: RemoteClient`. ### RemoteClient ``` constructor(options: RemoteOptions) check(request: CheckInput): Promise checkBatch(requests: CheckInput[]): Promise ``` `RemoteOptions` is `{ url, timeoutMs?, fetch?, headers?, breaker? }`. The timeout is 2000 ms by default; the breaker opens after 5 failures for 30 000 ms. `allowed` is true only for a `200` whose effect is `allow`; a failure carries `failure`. ### Type declarations by subpath Copied from the `.d.ts` files the package ships: the root, then one block per subpath of `exports`. `strig-types` is the package's one binary and writes the output of `generateTypes`. ### Package root: `@the-hades-organization/strig` ```ts title="TypeScript" function load(options: { backend: 'native' }): Promise function load(options?: { backend?: 'auto' | 'native' | 'wasm'; wasm?: unknown }): Promise class Context { constructor(init?: { grants?: Grant[]; tuples?: unknown[]; env?: Record; now?: number | bigint | null; limits?: QueryLimits }); setGrants(grants: Grant[]): void; addGrant(grant: Grant): void; removeGrant(id: string): boolean; grants(): Grant[]; readonly size: number; addTuple(tuple: unknown): boolean; removeTuple(tuple: unknown): boolean; setEnv(env: Record): void; loadCapabilities(set: CapabilitySet): Subject; setNow(now: number | bigint | null): void; setLimits(limits: QueryLimits | null): void; } class Engine

{ constructor(spec: unknown, hooks?: EngineHooks); decide(context: Context, request: DecisionRequest

, now?: number | bigint): Decision; check(context: Context, request: DecisionRequest

, now?: number | bigint): boolean; explain(context: Context, request: DecisionRequest

, now?: number | bigint): Explanation; allowedFields(context: Context, request: DecisionRequest

, now?: number | bigint): FieldSet; whyNot(context: Context, request: DecisionRequest

, now?: number | bigint, options?: WhyNotOptions): Remedies | null; explainFields(context: Context, request: DecisionRequest

, now?: number | bigint): FieldExplanation; checkMany(context: Context, requests: readonly DecisionRequest

[], now?: number | bigint): boolean[]; explainMany(context: Context, requests: readonly DecisionRequest

[], now?: number | bigint): Explanation[]; capabilities(context: Context, subject: Subject, scope: Resource, now?: number | bigint): CapabilitySet; validateGrant(grant: Grant): void; catalog(): unknown; apply(input: ApplyInput): ApplyResult; materialize(input: MaterializeInput): Materialized; applyTemplate(input: ApplyTemplateInput): ApplyTemplateResult; impact(input: ApplyInput): ImpactResult; reviewImpact(input: ReviewImpactInput): ReviewImpactResult; propose(input: ProposeInput): ProposeResult; resolve(input: ResolveInput): ResolveResult; elevate(input: ElevateInput): ElevateResult; recertify(input: RecertifyInput): RecertifyResult; expire(input: ExpireInput): ExpireResult; flushAudit(): AuditStats; auditStats(): AuditStats; list(context: Context, subject: Subject, permission: PermissionArg

, kind: string, options?: ListOptions, now?: number | bigint): ListResult; whoCan(context: Context, permission: PermissionArg

, now?: number | bigint): SubjectRef[]; whoCanOn(context: Context, permission: PermissionArg

, resource: Resource, now?: number | bigint): WhoCanOnResult; accessOf(context: Context, resource: Resource, now?: number | bigint): Array<{ subject: SubjectRef; permissions: string[] }>; checkFor(context: Context, subject: SubjectRef, permission: PermissionArg

, resource: Resource, subjects: Subject[], now?: number | bigint): CheckForResult; } class Exclusive { constructor(options?: ExclusiveOptions); validate(engine: Engine): void; acquire(engine: Engine, context: Context, subject: Subject, resource: Resource, terms: { priority: number; ttlMs: number }, now?: number | bigint,): Acquisition; holder(resource: ObjectRef, now?: number | bigint): Lease | null; release(resource: ObjectRef, holder: ObjectRef, now?: number | bigint): Lease; renew(engine: Engine, context: Context, subject: Subject, resource: Resource, ttlMs: number, now?: number | bigint,): Lease; expire(now?: number | bigint): Lease[]; } ``` Types: `AuditLevel`, `AuditFailMode`, `AuditDelivery`, `AuditRedaction`, `Subject`, `SubjectMatcher`, `ObjectRef`, `ErrorCode`, `BindingError`, `ConditionOperand`, `Weekday`, `Condition`, `Grant`, `Reason`, `Verdict`, `Decision`, `Explanation`, `ConditionTrace`, `CapabilitySet`, `FieldSet`, `FieldVerdict`, `FieldExplanation`, `WhyNotCause`, `WhyNotChange`, `WhyNotCaveat`, `Remedy`, `Remedies`, `WhyNotOptions`, `PermissionArg`, `DecisionRequest`, `RoleAssignment`, `Bypass`, `InvariantSpec`, `ImpactSource`, `ImpactOptions`, `Access`, `AccessChange`, `Impact`, `SeparationClash`, `PotentialClash`, `ApplyInput`, `TemplateGrant`, `RoleTemplate`, `MaterializeInput`, `Materialized`, `ApplyTemplateInput`, `ApplyTemplateResult`, `Violation`, `AccessVia`, `SubjectRef`, `FilterExpr`, `FilterShape`, `FilterResidual`, `ListOptions`, `ListResult`, `WhoCanOnResult`, `CheckForResult`, `QueryLimits`, `Lease`, `Acquisition`, `ExclusiveOptions`, `Suggestion`, `ApplyResult`, `ImpactResult`, `ApprovalRule`, `PendingStatus`, `PendingRequest`, `ElevationTarget`, `ElevationRule`, `ElevationRequest`, `ReviewState`, `ElevationInfo`, `ElevateInput`, `ElevateResult`, `ReviewerRule`, `ReviewerRoute`, `RecertScope`, `RecertDefaultAction`, `CampaignSpec`, `RecertDecision`, `RecertItemState`, `RecertItem`, `Campaign`, `CampaignReport`, `RecertifyInput`, `RecertifyResult`, `ApprovalFlowInput`, `ProposeInput`, `ResolveInput`, `ReviewImpactInput`, `ReviewImpactResult`, `ExpireInput`, `ProposeResult`, `ResolveResult`, `ExpireResult`, `AuditStats`, `AuditPolicy`, `ChainAnchors`, `ChainVerification`, `MerkleVerification`, `MerkleInclusionInput`, `MerkleConsistencyInput`, `TimestampInput`, `TimestampVerification`, `HostCondition`, `HostOverrideRequest`, `HostOverrideOutcome`, `HostOverride`, `HostProposal`, `HostInvariantResult`, `EngineHooks`, `PolicyLanguage`, `DslErrorCode`, `DslPlace`, `DslDiagnostic`, `DslError`, `PolicyPermission`, `MutuallyExclusive`, `ConflictingActions`, `PolicyCatalog`, `PolicyStrategy`, `PolicyDocument`, `PolicyNote`, `PolicySource`, `PolicyTestFixture`, `PolicyTestFile`, `PolicyTestCase`, `PolicyTestOutcome`, `PolicyTestResult`, `PolicyTestReport`, `PolicyDiffResponsible`, `PolicyDecisionChange`, `PolicyDiffUniverse`, `PolicyDiff`, `PolicyDiffFixture`, `PolicyDiffOptions`, `PolicyLintFinding`, `PolicyLintOptions`, `PolicyLanguageApi`, `NativePolicyLanguageApi`, `Strig`, `NativeStrig`. ### `/protocol` ```ts title="TypeScript" function parseRevision(text: string): { scope: string; value: bigint; } | undefined function revisionReached(required: string, have: string | undefined): Reached function anchorToString(anchor: Anchor): string function scopeToString(scope: Resource): string function scopeFromString(text: string): Resource function sameAnchor(a: Anchor, b: Anchor): boolean function resourceContains(resource: Resource, anchor: Anchor): boolean function changeAffects(change: Change, subjectId: string | null, scope: Resource): boolean function resourceWithin(resource: Resource, scope: Resource): boolean function encodeSse(message: ServerMessage): string function readSse(body: ReadableStream, onMessage: (message: ServerMessage) => void): Promise const GLOBAL = "global" const PROTOCOL_VERSION = 2 ``` Types: `Anchor`, `Resource`, `ChangeKind`, `Change`, `ServerMessage`, `ClientMessage`, `Reached`. ### `/client` ```ts title="TypeScript" class PermissionClient

{ readonly url: string | URL; readonly transport: 'sse' | 'websocket'; scopes: Resource[]; readonly strig: Pick; readonly engine: Engine; readonly headers: Record; readonly fetch: typeof fetch; readonly WebSocket: typeof WebSocket; readonly minDelay: number; readonly maxDelay: number; private entries; private listeners; private required?; private closed; private abort?; private socket?; constructor(options: PermissionClientOptions); } ``` Types: `PermissionClientOptions`. ### `/server` ```ts title="TypeScript" function change(kind: ChangeKind, scope: Anchor, extra?: Partial): Change function openSession({ hub, subject, scopes, provider, heartbeatMs, revision, minRevision, send, }: SessionOptions & { send: (message: ServerMessage) => void; }): Session function sseResponse(options: SessionOptions): Response function pipeSse(res: ServerResponse, options: SessionOptions): Session function engineProvider({ engine, Context, loadGrants, }: { engine: Engine; Context: typeof ContextClass; loadGrants: (subject: Subject, scope: Resource) => Promise | Grant[]; }): Provider function memoryTransport(): Transport function redisTransport({ publisher, subscriber, channel, }: { publisher: RedisPublisher; subscriber: RedisSubscriber; channel?: string; }): Transport function ioredisTransport({ publisher, subscriber, channel, }: { publisher: RedisPublisher; subscriber: IoredisSubscriber; channel?: string; }): Transport function pgTransport({ client, listener, channel, }: { client: Queryable; listener: PgListener; channel?: string; }): Transport function notify(queryable: Queryable, channel: string, item: Change): Promise class Hub { readonly origin: string; private readonly transport; private seq; private readonly listeners; private stopRelay; constructor(options?: { origin?: string; transport?: Transport; }); } ``` Types: `Transport`, `Provider`, `SessionOptions`, `Session`, `RedisPublisher`, `RedisSubscriber`, `IoredisSubscriber`, `Queryable`, `PgListener`. ### `/remote` ```ts title="TypeScript" function messageFor(code: string): string function parseErrorCode(value: unknown): ErrorCode | { unknown: string; } const ERROR_MESSAGES: Readonly> class CircuitBreaker { #private; readonly failureThreshold: number; readonly waitMs: number; } class RemoteClient { #private; private readonly base; private readonly timeoutMs; private readonly fetch; private readonly headers; private readonly minRevision?; readonly breaker: CircuitBreaker; constructor(options: RemoteOptions); check(request: CheckInput): Promise; checkBatch(requests: CheckInput[], options?: { minRevision?: string; }): Promise; } ``` Types: `ErrorCode`, `FailureReason`, `Failure`, `CheckInput`, `RemoteResult`, `BreakerOptions`, `RemoteOptions`. ### `/express` ```ts title="TypeScript" function authorize(options: AuthorizerOptions): Handler function createCan(options: AuthorizerOptions): (permission: string, resource?: Resource | ((req: Req) => Resource)) => Handler function authorizeRoutes(options: RouteTableOptions): Handler ``` ### `/fastify` ```ts title="TypeScript" function authorize(options: AuthorizerOptions): PreHandler function createCan(options: AuthorizerOptions): (permission: string, resource?: Resource | ((request: Req) => Resource)) => PreHandler function authorizeRoutes(options: RouteTableOptions): PreHandler function plugin(fastify: FastifyInstanceLike, options: AuthorizerOptions): Promise ``` ### `/nestjs` ```ts title="TypeScript" function Can(permission: string, resolver?: (request: any) => Resource): MethodDecorator & ClassDecorator const STRIG_CAN: string class StrigGuard { #private; private readonly options; private readonly decide; constructor(options: AuthorizerOptions); canActivate(context: ExecutionContextLike): Promise; } class StrigRouteGuard { #private; private readonly options; private readonly byTable; private readonly byCan; constructor(options: RouteTableOptions); canActivate(context: ExecutionContextLike): Promise; } ``` ### `/approvals` ```ts title="TypeScript" function checkRecertUpdate(stored: Campaign | undefined, next: Campaign): void class PendingStoreError extends Error { readonly code: PendingStoreErrorCode; constructor(code: PendingStoreErrorCode, message: string); } class MemoryPendingStore implements PendingStore { private readonly requests; get(id: string): PendingRequest | undefined; put(request: PendingRequest): void; update(request: PendingRequest): void; annotate(request: PendingRequest): void; list(): PendingRequest[]; } class Approvals { private readonly engine; readonly store: PendingStore; private readonly options; private head; constructor(engine: ApprovalEngine, store: PendingStore, options: ApprovalsOptions); propose(actor: Subject, mutation: ApplyInput['mutation'], current: Grant[], options?: ProposeOptions): Promise; pending(now?: number): Promise; approve(id: string, approver: Subject, current: Grant[], options?: DecideOptions): Promise; reject(id: string, approver: Subject, reason: string, current?: Grant[], options?: DecideOptions): Promise; reviewImpact(id: string, current: Grant[], options?: CallOptions): Promise; expire(options?: CallOptions): Promise; private decide; private close; private common; private follow; private clock; } class Elevations { private readonly engine; readonly store: PendingStore; private readonly options; private head; constructor(engine: ElevationEngine, store: PendingStore, options: ElevationsOptions); request(request: ElevationRequest, current: Grant[], options?: ElevationPersistOptions & { expiresAt?: number; }): Promise; approve(id: string, approver: Subject, current: Grant[], options?: ElevationPersistOptions): Promise; reject(id: string, approver: Subject, reason: string, current: Grant[], options?: CallOptions): Promise; revoke(id: string, by: Subject, current: Grant[], options?: ElevationPersistOptions & { reason?: string; }): Promise; closeReview(id: string, reviewer: Subject, note: string, current: Grant[], options?: CallOptions): Promise; active(now?: number): Promise; pendingReviews(): Promise; private step; private load; private requireStore; private annotate; private clock; } class RecertStoreError extends Error { readonly code: RecertStoreErrorCode; constructor(code: RecertStoreErrorCode, message: string); } class MemoryRecertStore implements RecertStore { private readonly campaigns; get(id: string): Campaign | undefined; put(campaign: Campaign): void; update(campaign: Campaign): void; list(): Campaign[]; } class Recertifications { private readonly engine; readonly store: RecertStore; private readonly options; private head; constructor(engine: RecertEngine, store: RecertStore, options?: RecertificationsOptions); open(spec: CampaignSpec, opener: Subject, subjects: Subject[], current: Grant[], options?: CallOptions): Promise; decide(id: string, item: string, decision: RecertDecision, reviewer: Subject, current: Grant[], options?: RecertPersistOptions & { reason?: string; }): Promise; close(id: string, closer: Subject, current: Grant[], options?: RecertPersistOptions): Promise; report(id: string): Promise; openCampaigns(): Promise; private step; private load; } ``` Types: `PendingStoreErrorCode`, `PendingStore`, `ApprovalEngine`, `ApprovalsOptions`, `CallOptions`, `ProposeOptions`, `DecideOptions`, `ElevationEngine`, `ElevationsOptions`, `ElevationPersistOptions`, `RecertStoreErrorCode`, `RecertStore`, `RecertEngine`, `RecertificationsOptions`, `RecertPersistOptions`. ### `/store` ```ts title="TypeScript" function openJsonStore(options: JsonFileStoreOptions): Promise const STORE_VERSION = 1 class JsonStoreError extends Error { readonly code: StoreErrorCode; constructor(code: StoreErrorCode, message: string, options?: { cause?: unknown; }); } class JsonFileStore { readonly path: string; private readonly lockPath; private readonly options; private data; private queue; private readonly listeners; private readonly errorListeners; private watcher; private debounce; constructor(options: JsonFileStoreOptions); load(): Promise; reload(): Promise; } ``` Types: `StoreErrorCode`, `StoreData`, `JsonFileStoreOptions`, `ApplyMutation`, `Governance`. ### `/testing` ```ts title="TypeScript" function auditRoutes(routes: readonly RouteInfo[], table: readonly RouteRule[], options?: { caseSensitive?: boolean; }): RouteAudit function assertRoutesCovered(routes: readonly RouteInfo[], table: readonly RouteRule[], options?: { caseSensitive?: boolean; }): void function expressRoutes(app: unknown, prefix?: string): RouteInfo[] function collectFastifyRoutes(fastify: FastifyRouteHooks): RouteInfo[] function nestRoutes(app: { getHttpAdapter(): { getInstance(): unknown; }; }): RouteInfo[] class RouteTableAuditError extends Error { readonly audit: RouteAudit; constructor(audit: RouteAudit); } ``` Types: `RouteInfo`, `RouteAudit`. ### `/react` ```ts title="TypeScript" function StrigProvider

({ client, connect, children }: StrigProviderProps

): ReactNode function useCan

(permission: PermissionArg

, resource: Resource): boolean function useStrigStatus(): StrigStatus function useRequireRevision(): (revision: string) => void function Can

({ permission, resource, fallback, children }: CanProps

): ReactNode ``` Types: `StrigProviderProps`, `CanProps`. ### `/angular` ```ts title="TypeScript" function provideStrig

(client: PermissionClient

, options?: StrigOptions): EnvironmentProviders function strigCanActivate

(permission: PermissionArg

, resource: Resource | ((route: any, state: any) => Resource), options?: StrigGuardOptions): (route: any, state: any) => Promise const STRIG_CLIENT: InjectionToken> const STRIG_OPTIONS: InjectionToken class StrigService

{ private readonly bridge; private readonly server; private readonly tick; private readonly state; readonly status: Signal; constructor(); can(permission: Reactive | null | undefined>, resource: Reactive): Signal; settled(timeoutMs?: number): Promise; requireRevision(revision: string): void; check(permission: PermissionArg

, resource: Resource): boolean; static ɵfac: i0.ɵɵFactoryDeclaration, never>; static ɵprov: i0.ɵɵInjectableDeclaration>; } class StrigCanDirective

{ private readonly template; private readonly container; private readonly permission; private readonly resource; private readonly fallback; private view?; private shown?; set strigCan(value: PermissionArg

| null | undefined); set strigCanResource(value: Resource | null | undefined); set strigCanElse(value: TemplateRef | null | undefined); constructor(); static ɵfac: i0.ɵɵFactoryDeclaration, never>; static ɵdir: i0.ɵɵDirectiveDeclaration, "[strigCan]", never, { "strigCan": { "alias": "strigCan"; "required": true; }; "strigCanResource": { "alias": "strigCanResource"; "required": false; }; "strigCanElse": { "alias": "strigCanElse"; "required": false; }; }, {}, never, never, true, never>; } ``` Types: `StrigOptions`, `StrigGuardOptions`. ### `/prisma` ```ts title="TypeScript" function toWhere

(filter: ListFilter

, mapping: PrismaMapping): OrmFilter const prisma: OrmAdapter ``` Types: `PrismaWhere`, `PrismaMapping`. ### `/drizzle` ```ts title="TypeScript" function toWhere

(filter: ListFilter

, mapping: DrizzleMapping): OrmFilter const drizzle: OrmAdapter ``` Types: `DrizzleMapping`. ### `/kysely` ```ts title="TypeScript" function toWhere

(filter: ListFilter

, mapping: KyselyMapping): OrmFilter const kysely: OrmAdapter ``` Types: `KyselyMapping`, `KyselyWhere`. ### `/types` ```ts title="TypeScript" function generateTypes(catalog: CatalogInput): string ``` Types: `CatalogInput`. ## Python: strig-auth ```bash pip install strig-auth ``` ```python import strig from strig import Context, Engine, StrigError, dsl ``` The package is `strig-auth` on PyPI and `strig` on import; it needs Python 3.9 or later. Values are plain JSON (`dict`, `list`, `str`, `int`, `float`, `bool`, `None`) with the same camelCase field names as the JavaScript API; method names are snake_case. Every failure raises `StrigError` with a stable `code`; `DslError` adds `diagnostics`. Walk-through: [Python](https://strig.vercel.app/docs/integrations/python.md). The public surface, as the package's type stubs declare it: ```python title="strig/_native.pyi, __init__.py, dsl.py, errors.py" # ===== _native.pyi ===== """Type stubs of the native extension. Values are plain JSON (`dict`, `list`, `str`, `int`, `float`, `bool`, `None`) with the same camelCase field names as the JavaScript API.""" from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence Json = Any JsonObject = Dict[str, Any] Request = Mapping[str, Any] Hook = Callable[[Any], Any] class Context: def __init__( self, grants: Optional[Sequence[Mapping[str, Any]]] = None, *, tuples: Optional[Sequence[Mapping[str, Any]]] = None, env: Optional[Mapping[str, Any]] = None, now: Optional[int] = None, limits: Optional[Mapping[str, Any]] = None, ) -> None: ... def set_grants(self, grants: Sequence[Mapping[str, Any]]) -> None: ... def add_grant(self, grant: Mapping[str, Any]) -> None: ... def remove_grant(self, id: str) -> bool: ... def grants(self) -> List[JsonObject]: ... @property def size(self) -> int: ... def __len__(self) -> int: ... def add_tuple(self, tuple: Mapping[str, Any]) -> bool: ... def remove_tuple(self, tuple: Mapping[str, Any]) -> bool: ... def set_env(self, env: Mapping[str, Any]) -> None: ... def load_capabilities(self, capabilities: Mapping[str, Any]) -> JsonObject: ... def set_now(self, now: Optional[int] = None) -> None: ... def set_limits(self, limits: Optional[Mapping[str, Any]] = None) -> None: ... class Engine: def __init__( self, spec: Mapping[str, Any], *, conditions: Optional[Mapping[str, Callable[[List[Any]], bool]]] = None, overrides: Optional[Iterable[Mapping[str, Any]]] = None, invariants: Optional[Mapping[str, Callable[[JsonObject], Any]]] = None, audit_sink: Optional[Callable[[JsonObject], None]] = None, audit_redact: Optional[Callable[[JsonObject], JsonObject]] = None, on_audit_drop: Optional[Callable[[JsonObject], None]] = None, audit_policy: Optional[Mapping[str, Any]] = None, ) -> None: ... def decide(self, context: Context, request: Request, now: Optional[int] = None) -> JsonObject: ... def check(self, context: Context, request: Request, now: Optional[int] = None) -> bool: ... def explain(self, context: Context, request: Request, now: Optional[int] = None) -> JsonObject: ... def why_not( self, context: Context, request: Request, now: Optional[int] = None, options: Optional[Mapping[str, Any]] = None, ) -> Optional[JsonObject]: ... def check_many(self, context: Context, requests: Sequence[Request], now: Optional[int] = None) -> List[bool]: ... def explain_many( self, context: Context, requests: Sequence[Request], now: Optional[int] = None ) -> List[JsonObject]: ... def capabilities( self, context: Context, subject: Mapping[str, Any], scope: Mapping[str, Any], now: Optional[int] = None ) -> JsonObject: ... def validate_grant(self, grant: Mapping[str, Any]) -> None: ... def catalog(self) -> JsonObject: ... def apply(self, input: Mapping[str, Any]) -> JsonObject: ... def impact(self, input: Mapping[str, Any]) -> JsonObject: ... def review_impact(self, input: Mapping[str, Any]) -> JsonObject: ... def propose(self, input: Mapping[str, Any]) -> JsonObject: ... def resolve(self, input: Mapping[str, Any]) -> JsonObject: ... def elevate(self, input: Mapping[str, Any]) -> JsonObject: ... def recertify(self, input: Mapping[str, Any]) -> JsonObject: ... def expire(self, input: Mapping[str, Any]) -> JsonObject: ... def flush_audit(self) -> JsonObject: ... def audit_stats(self) -> JsonObject: ... def materialize(self, input: Mapping[str, Any]) -> JsonObject: ... def apply_template(self, input: Mapping[str, Any]) -> JsonObject: ... def list( self, context: Context, subject: Mapping[str, Any], permission: str, kind: str, options: Optional[Mapping[str, Any]] = None, now: Optional[int] = None, ) -> JsonObject: ... def who_can(self, context: Context, permission: str, now: Optional[int] = None) -> List[JsonObject]: ... def who_can_on( self, context: Context, permission: str, resource: Mapping[str, Any], now: Optional[int] = None ) -> JsonObject: ... def access_of( self, context: Context, resource: Mapping[str, Any], now: Optional[int] = None ) -> List[JsonObject]: ... def check_for( self, context: Context, subject_ref: Mapping[str, Any], permission: str, resource: Mapping[str, Any], subjects: Sequence[Mapping[str, Any]], now: Optional[int] = None, ) -> JsonObject: ... class Exclusive: def __init__(self, options: Optional[Mapping[str, Any]] = None) -> None: ... def validate(self, engine: Engine) -> None: ... def acquire( self, engine: Engine, context: Context, subject: Mapping[str, Any], resource: Mapping[str, Any], terms: Mapping[str, Any], now: Optional[int] = None, ) -> JsonObject: ... def holder(self, resource: Mapping[str, Any], now: Optional[int] = None) -> Optional[JsonObject]: ... def release( self, resource: Mapping[str, Any], holder: Mapping[str, Any], now: Optional[int] = None ) -> JsonObject: ... def renew( self, engine: Engine, context: Context, subject: Mapping[str, Any], resource: Mapping[str, Any], ttl_ms: int, now: Optional[int] = None, ) -> JsonObject: ... def expire(self, now: Optional[int] = None) -> List[JsonObject]: ... def audit_estimate(level: str, records: int) -> float: ... def verify_audit_chain(records: Sequence[Mapping[str, Any]], anchors: Optional[Mapping[str, Any]] = None) -> JsonObject: ... def dsl_compile(text: str, options: Optional[Mapping[str, Any]] = None) -> JsonObject: ... def dsl_print(policy: Mapping[str, Any], language: str) -> JsonObject: ... def dsl_convert(text: str, language: str) -> JsonObject: ... def dsl_format(text: str, options: Optional[Mapping[str, Any]] = None) -> JsonObject: ... def dsl_is_formatted(text: str, options: Optional[Mapping[str, Any]] = None) -> JsonObject: ... def dsl_load_project(sources: Sequence[Mapping[str, str]]) -> JsonObject: ... def dsl_load_project_dir(dir: str) -> JsonObject: ... def dsl_run_tests(policy: Mapping[str, Any], tests: Sequence[Any]) -> JsonObject: ... # ===== __init__.py ===== from typing import Any, Dict, List from . import dsl from ._native import Context, Engine, Exclusive, audit_estimate, verify_audit_chain from .errors import DslError, StrigError def scope_from_string(text: str) -> Dict[str, Any]: ... __all__ = ['Context', 'DslError', 'Engine', 'Exclusive', 'StrigError', 'audit_estimate', 'dsl', 'scope_from_string', 'verify_audit_chain'] # ===== dsl.py ===== from __future__ import annotations from typing import Any, Dict, List, Optional from . import _native from .errors import DslError __all__ = ['compile', 'print', 'convert', 'format', 'is_formatted', 'load_project', 'load_project_dir', 'run_tests'] def compile(text: str, file: Optional[str]=None) -> Dict[str, Any]: ... def print(policy: Dict[str, Any], language: str) -> str: ... def convert(text: str, language: str) -> str: ... def format(text: str, file: Optional[str]=None) -> str: ... def is_formatted(text: str, file: Optional[str]=None) -> bool: ... def load_project(sources: List[Dict[str, str]]) -> Dict[str, Any]: ... def load_project_dir(directory: str) -> Dict[str, Any]: ... def run_tests(policy: Dict[str, Any], tests: List[Any]) -> Dict[str, Any]: ... # ===== errors.py ===== from __future__ import annotations from typing import Any, List class StrigError(Exception): code: str message: str def __init__(self, code: str, message: str) -> None: ... ... class DslError(StrigError): diagnostics: List[Any] def __init__(self, code: str, message: str, diagnostics: List[Any] | None=None) -> None: ... ... ``` ## Go ```bash go get github.com/The-Hades-Organization/Strig/bindings/go@v0.10.0 ``` Go 1.22 or later. The engine is the Wasm module, run on wazero; there is no cgo. `Engine` and `Context` hold module memory, so `Close` them. An `Engine` is single-threaded: `Fork` gives each worker its own. Every error is a `*Error` with a stable `Code`; `errors.Is` matches two of them by `Code`. Walk-through: [Go](https://strig.vercel.app/docs/integrations/go.md). ```go engine, err := strig.NewEngine(spec) if err != nil { return err } defer engine.Close() ctx, _ := engine.NewContext(map[string]any{"grants": grants}) defer ctx.Close() ok, err := engine.Check(ctx, map[string]any{ "subject": map[string]any{"kind": "user", "id": "ana"}, "permission": "document.view", "resource": map[string]any{"path": []any{map[string]any{"kind": "document", "id": "d1"}}}, }) if strig.CodeOf(err) == "INVALID_GRANT" { /* ... */ } ``` | Item | Signature | | --- | --- | | `NewEngine` | `func NewEngine(spec any) (*Engine, error)` | | `Engine.Fork` | `func (e *Engine) Fork() (*Engine, error)` | | `Engine.Close` | `func (e *Engine) Close() error` | | `Engine.NewContext` | `func (e *Engine) NewContext(init any) (*Context, error)` | | `Engine.Check` | `func (e *Engine) Check(c *Context, request any, opts ...Option) (bool, error)` | | `Engine.Decide` | `func (e *Engine) Decide(c *Context, request any, opts ...Option) (*Decision, error)` | | `Engine.Explain` | `func (e *Engine) Explain(c *Context, request any, opts ...Option) (map[string]any, error)` | | `Engine.CheckMany` | `func (e *Engine) CheckMany(c *Context, requests any, opts ...Option) ([]bool, error)` | | `Engine.List` | `func (e *Engine) List(c *Context, subject any, permission, kind string, options any, opts ...Option) (map[string]any, error)` | | `Engine.WhoCan` | `func (e *Engine) WhoCan(c *Context, permission string, opts ...Option) ([]map[string]any, error)` | | `Engine.Catalog` | `func (e *Engine) Catalog() (map[string]any, error)` | | `Engine.Apply`, `Impact`, `ReviewImpact`, `Propose`, `Resolve`, `Expire` | `func (e *Engine) Apply(input any) (map[string]any, error)`, and the same shape for the others | | `Context.SetGrants` | `func (c *Context) SetGrants(grants any) error` | | `Context.AddGrant` | `func (c *Context) AddGrant(grant any) error` | | `Context.RemoveGrant` | `func (c *Context) RemoveGrant(id string) (bool, error)` | | `Context.Grants` | `func (c *Context) Grants() ([]map[string]any, error)` | | `Context.AddTuple`, `RemoveTuple` | `func (c *Context) AddTuple(tuple any) (bool, error)` | | `Context.SetEnv` | `func (c *Context) SetEnv(env any) error` | | `Context.SetNow` | `func (c *Context) SetNow(t time.Time) error` | | `Context.SetLimits` | `func (c *Context) SetLimits(limits any) error` | | `Context.Close` | `func (c *Context) Close() error` | | `WithNow` | `func WithNow(t time.Time) Option` | | `Compile` | `func Compile(text string, file ...string) (map[string]any, error)` | | `Format` | `func Format(text string) (string, error)` | | `CodeOf` | `func CodeOf(err error) string` | | `Decision` | `struct { Effect string; Reason json.RawMessage; Matched []string; Warnings []string }`, with `Allowed() bool` | | `Error` | `struct { Code string; Message string; Diagnostics []any }` | | `ErrClosed`, `ErrBroken` | `INVALID_ARGUMENT` after `Close`; `INTERNAL` when the module trapped and was discarded. | ## Java ```xml io.github.the-hades-organization strig 0.10.0 ``` Package `io.github.thehadesorganization.strig`. The engine is the same Wasm module, run on Chicory. `Engine` and `Context` are `AutoCloseable`; use try-with-resources. Failures throw `StrigException` with a stable `code()`; a policy error also carries `diagnostics()`. Walk-through: [Java and the JVM](https://strig.vercel.app/docs/integrations/jvm.md). ```java try (Engine engine = new Engine(spec); Context ctx = engine.newContext(Map.of("grants", grants))) { Decision d = engine.decide(ctx, request); if (!d.allowed()) { /* d.reason() */ } } ``` | Item | Signature | | --- | --- | | `Engine` | `public Engine(Object spec)`, `public Engine fork()`, `public synchronized void close()` | | `newContext` | `public Context newContext()`, `public Context newContext(Object init)` | | `check` | `public boolean check(Context context, Object request)`, and with a trailing `Instant now` | | `decide` | `public Decision decide(Context context, Object request)`, and with a trailing `Instant now` | | `explain` | `public Map explain(Context context, Object request)`, and with `Instant now` | | `checkMany` | `public List checkMany(Context context, Object requests)`, and with `Instant now` | | `list` | `public Map list(Context context, Object subject, String permission, String kind, Object options)` | | `whoCan` | `public List> whoCan(Context context, String permission)` | | `catalog` | `public Map catalog()` | | `apply`, `impact`, `reviewImpact`, `propose`, `resolve`, `expire` | `public Map apply(Object input)`, and the same shape for the others | | `Context` | `setGrants(Object)`, `addGrant(Object)`, `boolean removeGrant(String id)`, `List> grants()`, `boolean addTuple(Object)`, `boolean removeTuple(Object)`, `setEnv(Object)`, `setNow(Instant)`, `setLimits(Object)`, `close()` | | `Strig` | `static Map compile(String text)`, `compile(String text, String file)`, `static String format(String text)` | | `Decision` | `record Decision(String effect, JsonNode reason, List matched, List warnings)`, with `boolean allowed()` | | `StrigException` | `String code()`, `List diagnostics()` | ## Wasm ABI The Go and Java packages call one module, `strig-.wasm`. A host in another language can do the same. The module imports nothing and exports a linear memory and three functions. | Export | Signature | What it does | | --- | --- | --- | | `memory` | linear memory | The host writes inputs into it and reads outputs from it. | | `strig_alloc` | `(len: usize) -> *mut u8` | Gives the host `len` bytes to write an input into. | | `strig_free` | `(ptr: *mut u8, len: usize)` | Releases memory from `strig_alloc` or from a `strig_call` result, once. | | `strig_call` | `(op_ptr, op_len, in_ptr, in_len) -> u64` | Runs one operation. `op` is UTF-8 text and the input is a JSON object. The result packs `(ptr << 32) \| len` of a JSON envelope; read it, then free it. | The envelope is one of: ```json {"ok": true, "value": {"effect": "allow"}} {"ok": false, "code": "INVALID_GRANT", "message": "...", "diagnostics": []} ``` `code` is the same `errorCode` every binding raises. Input that is not UTF-8 is `INVALID_INPUT`. The operations, by group: | Group | Operations | | --- | --- | | Policy language | `compile`, `format`, `print`, `convert`, `isFormatted`, `loadProject`, `runTests`, `diff`, `lint` | | Handles | `engine.new`, `engine.free`, `context.new`, `context.free` | | Context | `context.setGrants`, `context.addGrant`, `context.removeGrant`, `context.grants`, `context.addTuple`, `context.removeTuple`, `context.setEnv`, `context.setNow`, `context.setLimits` | | Decisions | `check`, `decide`, `explain`, `whyNot`, `checkMany`, `explainMany`, `list`, `whoCan`, `catalog` | | Changes | `apply`, `impact`, `reviewImpact`, `propose`, `resolve`, `elevate`, `recertify`, `expire` | Engines and contexts live inside the module and are named by integer ids. The module is single-threaded: for concurrency, instantiate one module per worker. Callbacks (`call` conditions, overrides, invariants) are not part of the ABI; a request that needs one fails closed with the engine's own error. There is no clock: an operation that needs the instant takes `now` in its input, and the host fills it. ## Protocol 2 The client protocol of `strig-sync`, `strig-server` and the JavaScript `/protocol` module is version 2 (`PROTOCOL_VERSION`). A peer that sends no `hello.version` is read as version 1; version 2 only adds optional fields and messages, so the two interoperate. Messages are JSON objects tagged by `type`, sent as Server-Sent Events (`event: `, `data: `) or over a WebSocket. | Direction | `type` | Fields | Meaning | | --- | --- | --- | --- | | Server | `hello` | `origin`, `subject?`, `version` | First message; `version` is 1 when absent. | | Server | `capabilities` | `scope`, `set`, `revision?` | The current grants of the subject for a watched scope; replaces the previous set. A client that requires a revision treats a set without it, or behind it, as no decision. | | Server | `change` | `change` | A change that affects a watched scope. | | Server | `resync` | none | The client lost changes: discard what it has and wait for new `capabilities`. | | Server | `error` | `message` | A failure. | | Server | `ping` | none | Keep-alive. | | Client | `watch`, `unwatch` | `scopes` | Starts or stops watching scopes; `watch` answers with each scope's capabilities. | | Client | `refresh` | none | Asks again for the capabilities of every watched scope. | | Client | `refresh_at_least` | `revision` | Like `refresh`, but every set must come from data at `revision` or later. A scope that cannot be brought that far gets an `error` whose `message` is `revision_not_reached`, `revision_scope_mismatch` or `revision_untracked`, never an older set. | A scope is text in a query string: steps from the most specific to the broadest, separated by `/`, each `kind:id` or just `kind` (`document:d1/project:p1/org:o1`). ## Error codes Each list is closed: a code is added, never changed or reused. Removing one, or making an existing situation report a different one, is a breaking change. A deprecated code keeps being thrown until the next major version. **JavaScript, Python, Go, Java and Wasm** raise the same `ErrorCode`. A Rust error variant added later maps to `INTERNAL`, or to the `*_ERROR` code of its family, until it gets a code of its own. | Family | Codes | | --- | --- | | Input | `INVALID_ARGUMENT`, `INVALID_INPUT`, `INVALID_SPEC`, `INVALID_GRANT`, `UNKNOWN_SUBJECT`, `UNKNOWN_INVARIANT`, `REENTRANT_CALL` | | Queries | `QUERY_LIMIT_EXCEEDED`, `RELATION_DEPTH_EXCEEDED`, `QUERY_ERROR` | | Exclusive ownership | `EXCLUSIVE_ZERO_TTL`, `EXCLUSIVE_NOT_HELD`, `EXCLUSIVE_NOT_HOLDER`, `EXCLUSIVE_ANONYMOUS_SUBJECT`, `EXCLUSIVE_UNIDENTIFIED_RESOURCE`, `EXCLUSIVE_TTL_TOO_LONG`, `EXCLUSIVE_DENIED`, `EXCLUSIVE_UNKNOWN_PERMISSION`, `EXCLUSIVE_STORE`, `EXCLUSIVE_ERROR` | | Policy language | `DSL_PARSE`, `DSL_VALIDATE`, `DSL_CONFLICT`, `DSL_UNREPRESENTABLE`, `DSL_UNSUPPORTED`, `DSL_LIMIT`, `DSL_DUPLICATE_SOURCE`, `DSL_IO` | | Other | `INTERNAL` | **`strig-server` and the JavaScript `/remote` client** answer with `error.code` in the body: `malformed_json`, `invalid_request`, `batch_too_large`, `too_many_resources`, `not_found`, `method_not_allowed`, `body_too_large`, `unsupported_media_type`, `source_unavailable`, `query_limit_exceeded`, `overloaded`, `relation_depth_exceeded`, `deadline_exceeded`, `clock_unavailable`, `revision_not_reached`, `revision_mismatch`, `internal`. A client treats a code it does not know as `internal`. [Status and meaning of each](#error-codes-server). **Rust** error enums (`EngineError`, `SpecError`, `PendingError`, `ApprovalError`, `AuditError`, `ChainError`, `ExclusiveError`, `StoreError`, `QueryError` and the others) are `#[non_exhaustive]`; their variants are the codes, and the mapping to the lists above is part of the contract. --- # Upgrading URL: https://strig.vercel.app/docs/upgrading From `1.0.0-rc.1` the public API is frozen. A change that breaks it needs a new major version, a line under **Breaking** in the [changelog](https://github.com/The-Hades-Organization/Strig/blob/main/CHANGELOG.md) and a section on this page. Minor versions add features and deprecations. Patches only fix. All crates, the npm package, the Python package, the Go module tag and the Java artifact share one version number, and a release bumps them together. Moving from 0.10? Only Rust code that names a few types changes: [0.10 → 1.0](#100). The JavaScript, Python, Go and Java packages, the policy language, stored data and the audit hash need no edit. ## What 1.0 freezes Three numbers and one list do not change inside a major version. Readers keep reading every schema and format they read at 1.0. | Value | At 1.0 | Where it lives | | --- | --- | --- | | Policy JSON schema | `DSL_SCHEMA` = 5 | `strig::dsl::DSL_SCHEMA` | | Audit record and chain hash | `AUDIT_FORMAT` = 1 | `strig::audit::AUDIT_FORMAT` | | Client and sync protocol | version 2 (`hello.version`, 1 when absent) | [Reference](https://strig.vercel.app/docs/reference.md#protocol) | | `errorCode` lists | closed; codes are added, never changed or reused | [Reference](https://strig.vercel.app/docs/reference.md#error-codes) | Four checks in CI keep the promise, so it does not rest on review alone. | Check | What it locks | Fails when | | --- | --- | --- | | `cargo semver-checks` | The public Rust API of `strig`, `strig-sync`, `strig-redis`, `strig-postgres`, `strig-axum`, `strig-server` and `strig-macros`, against the last version on crates.io | An item is removed, renamed or changed without a major version | | API snapshots | `crates/strig-node/js/api/strig.d.ts.snap` (every published `.d.ts`) and `crates/strig-python/api/strig.pyi.snap` | The JavaScript or Python surface changes and the snapshot was not updated | | Frozen fixtures | The policy JSON for every syntax, an audit record and its chain hash, one file per sync message, the `strig-server` wire | The output changes by one byte | | `errorCode` lists | The closed lists in the [Reference](https://strig.vercel.app/docs/reference.md#error-codes) | A code is removed or changed | ## What is public API | Surface | What is covered | | --- | --- | | Rust crates | Everything reachable from the public items of `strig`, `strig-sync`, `strig-redis`, `strig-postgres`, `strig-axum`, `strig-macros` and `strig-server`, with the documented feature flags. | | `strig-cli` | Subcommands, flags and exit codes. | | npm package | The exports of `@the-hades-organization/strig` and its subpaths, their TypeScript types, and the `strig-types` command. | | Python package | The exports of `strig` (`pip install strig-auth`), their method names and keyword arguments, and the type stubs. | | Go module | The exports of `github.com/The-Hades-Organization/Strig/bindings/go`. | | Java and Kotlin package | The public classes of `io.github.the-hades-organization:strig`. | | Wasm ABI | The exports of `strig-.wasm` (`memory`, `strig_alloc`, `strig_free`, `strig_call`), the operation names and JSON inputs of `strig_call`, and the envelope it answers with. | | Policy language | The grammar and meaning of the three syntaxes, and the canonical JSON the parser produces. | | JSON spec | The shape of `EngineSpec`, `Grant`, `Condition`, `Catalog`, the exported catalog and the files read by the JSON store, with their `schema` numbers. | | Audit format | The canonical form of a record and the hash of the chain, with its test vector. | | `errorCode`s | The `code` of every error the bindings raise, and the stable names the Rust errors map to. | | Wire protocol | The messages of `strig-sync`, `strig-server` and the JS `/protocol` module. | Not public, and free to change in any release: items marked `#[doc(hidden)]`, anything under an `internal` or `__private` name, the layout of the built `dist/` and `wasm/` folders (use the exports map), the wording of error messages and hints (match on `code`, never on the text), the text of `explain` traces, the playground, the `strig-inspect` window and benchmark numbers. Three crates are not library API. `strig-node` and `strig-inspect` are not published: the npm package is the surface of the first, and the second is covered only by its command line. `strig-lsp` ships inside the editor extension and speaks the Language Server Protocol. ## What counts as a breaking change | Where | Breaking | Not breaking | | --- | --- | --- | | Rust | Removing or renaming a public item. Changing a signature or a trait. Adding a required method to a trait you implement (`AuditSink`, `Invariant`, `ExclusiveStore`, `TupleStore`). Adding a variant or field to a type that is not `#[non_exhaustive]`. Changing a default feature. Raising the MSRV in a patch. | Adding a variant or field to a `#[non_exhaustive]` type. Adding a method with a default body. | | npm, Python, Go, Java | Removing or renaming an export, option, field, method or exception. Changing the `code` of an error. Narrowing an accepted type or widening a returned one. Dropping a supported runtime version. Moving a subpath. | Adding an export, a method or an optional argument. | | Wasm ABI | Changing the signature of an export, removing or renaming an operation, changing the envelope. | New operations and new optional input fields. | | Policy language and JSON | A source that parsed before parses to a different policy. Removing a keyword, `op`, field or syntax. Making the validator reject what it accepted. | Adding a keyword. A policy that uses it exports a higher `schema`, so an older reader refuses it instead of reading it wrongly. | | Audit format | Any change to the canonical form or the hash. It invalidates stored chains and anchors, so it needs a major version and a migration for existing chains. | A new optional record field that is left out of the canonical form when unset. | | `errorCode`s | Removing a code, or making a situation report a different one. | Adding a code. | | Decisions | A change that allows where it denied. It needs a test with the deny cases that must still deny, and is announced under **Changed** or **Breaking**. | A fix that denies where it allowed wrongly. It is announced under **Fixed**, as security fixes are. | ### Types that can grow Public enums that may gain variants, and public structs the library returns, are `#[non_exhaustive]`. A `match` on them needs a catch-all arm, and a result struct is read, never built with a literal: ```rust title="Rust" match builder.build() { Ok(engine) => use_it(engine), Err(EngineError::UnknownPermission(p)) => reject(p), Err(_) => reject_unknown(), // fails closed } ``` Structs you build to configure or feed the library (`Review`, `Resource`, `Anchor`, `Lease`, `SessionOptions`, `RetryPolicy`, `Proposal`, `EvalContext` and similar) are `#[non_exhaustive]` too. Pass the required fields to `new(...)` and the optional ones through `with_*`: ```rust title="Rust" let policy = RetryPolicy::default().with_capacity(500); ``` Five types stay exhaustive on purpose: `Effect`, `PendingStatus`, `TupleSubject`, `Mutation` and `SubjectMatcher`. Every store matches them, so a new variant must fail at compile time instead of dropping a write silently. Adding a variant to one of them is a major change. ## Versions before and after 1.0 - **Before 1.0** (`0.y.z`): a minor version may break the API. A patch never does. Every break is in the changelog, and on this page when it needs more than a line. - **From 1.0** (`x.y.z`): only a major version breaks the public API. A minor adds features and deprecations. A patch only fixes. Security fixes ship in a patch of every supported line. - **A pre-release** (`1.0.0-rc.1`) can change until the final version. ## Supported toolchains | Toolchain | Supported | Dropping a version | | --- | --- | --- | | Rust (MSRV) | 1.88 | A minor version only, never a patch. The MSRV stays at least six months old and the changelog announces it. | | Node and Bun | Node 18.17 or newer, Bun 1.1 or newer | A major version, unless the runtime has been end-of-life for more than six months. | | Python | 3.9 or newer. One `abi3` wheel per platform covers every later version: `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `win32-x64`. The source distribution builds anywhere with a Rust toolchain. | As Node. | | Go | 1.22 or newer | As Node. | | Java | 17 or newer, and Kotlin on any version that targets it | As Node. | | Browsers | Current evergreen browsers, through the `browser` export and the WebAssembly backend | A major version. | The npm package has a native module for `linux-x64` and `linux-arm64` (glibc), `darwin-x64`, `darwin-arm64` and `win32-x64`. Linux with musl uses the WebAssembly backend. Go and Java run the engine on a WebAssembly runtime written in the host language, so any OS and architecture that runs Go or the JVM works. Adding a platform is not breaking. Removing one is. ## Deprecation policy 1. **Warn in a minor.** The release notes list the feature under **Deprecated**, with the replacement and the version where it goes. 2. **Remove only in the next major.** A deprecated item stays through the rest of the major line. 3. **Keep it working.** A deprecated item keeps its behaviour. The only change allowed is the warning. 4. **Security is the exception.** When keeping something works against safety, it can be removed or made to fail closed in a minor or a patch. The advisory and the changelog say so. How the warning reaches you: | Where | How you see it | | --- | --- | | Rust | `#[deprecated(since = "1.2.0", note = "use new_name; removed in 2.0")]`. The compiler warns at every use. CI builds with `-D warnings`, so a project that denies warnings fails at the first build after the upgrade. | | JavaScript and TypeScript | A `@deprecated` JSDoc tag in the `.d.ts`, with the replacement, which editors strike through. At runtime, a one-time `process.emitWarning(message, 'DeprecationWarning', 'STRIG_DEPnnn')` on Node and Bun (`console.warn` in the browser). Run Node with `--throw-deprecation` in your tests to fail on a use. The changelog repeats each `STRIG_DEPnnn` code. | | Policy language and JSON | A deprecated keyword or field still parses. The validator reports a warning with the position and the replacement in the hint. | | Error codes | A deprecated code keeps being thrown until the major version. The changelog names the code that replaces it. | Changes made before this policy, such as the `needs` to `depends_on` rename in 0.5.0, were breaking at once. From now on a rename goes through the steps above. Nothing is deprecated at 1.0. ## 1.0.0 The public API is frozen from `1.0.0-rc.1`. This was the last window for breaking changes, and it breaks only Rust code that names the types below. ### Rust: growing enums and result structs are `#[non_exhaustive]` About 40 public enums that can gain a variant and about 60 structs the library returns can now grow without a major version. The enums include the error types (`EngineError`, `GrantError`, `SpecError`, `PendingError`, `AuditError`, `QueryError`), `Condition`, `Operand`, `Reason`, `Rewrite`, `Value` and `MutationKind`. The structs include `Decision`, `Explanation`, `WhoCan`, `CheckAnswer`, `AuditStats`, `Violation` and `Materialized`. **Before.** ```rust title="Rust" match builder.build() { Ok(engine) => use_it(engine), Err(EngineError::UnknownPermission(p)) => reject(p), } ``` **After.** Add a catch-all arm that fails closed, and `..` when you destructure a result struct. ```rust title="Rust" match builder.build() { Ok(engine) => use_it(engine), Err(EngineError::UnknownPermission(p)) => reject(p), Err(_) => reject_unknown(), } let Decision { effect, .. } = decision; ``` **Step.** Search your code for `match` on these enums and for destructured result structs. A result struct is no longer built with a literal outside its crate: take one from the API that produces it. ### Rust: input structs are built with a constructor The 20 structs you build to configure or feed the library can no longer be built with a literal, nor with `..Default::default()`, outside their crate. Required fields go in `new(...)`, optional ones in `with_*`, and configuration structs keep `Default`. Reading a field is unchanged, and so is assigning one on a value you own. A pattern that destructures one needs `..`. **Before.** ```rust title="Rust" let policy = RetryPolicy { capacity: 500, ..RetryPolicy::default() }; let review = Review { now: t, ..review }; ``` **After.** ```rust title="Rust" let policy = RetryPolicy::default().with_capacity(500); let review = review.with_now(t); // Review is now Copy ``` **Step.** Replace each literal with the constructor in the table. A store implemented outside this repository builds what it returns the same way (`Lease::new`, `Review::new`). | Struct | Before | After | | --- | --- | --- | | `Review` | `Review { engine, current, tuples: None, now, meta }` | `Review::new(engine, current, now, meta)`, `.with_tuples(store)` | | `Proposal` | `Proposal { actor, mutation, before, after, tuples: None, now: None }` | `Proposal::new(actor, mutation, before, after)`, `.with_tuples(store)`, `.with_now(now)` | | `EvalContext` | `EvalContext { subject, resource, env }` | `EvalContext::new(subject, resource, env)` | | `CapabilitySet` | `CapabilitySet { subject, grants }` | `CapabilitySet::new(subject, grants)` | | `Lease` | `Lease { resource, holder, priority, acquired_at, expires_at }` | `Lease::new(resource, holder, priority, acquired_at, expires_at)` | | `ExclusivePermissions` | `ExclusivePermissions { hold, preempt }` | `ExclusivePermissions::new(hold, preempt)` | | `Resource` | `Resource { path, attrs: Default::default() }` | `Resource::from_path(path)`, or `Resource::new(kind, id).within(..)` | | `Anchor` | `Anchor { kind, id }` | `Anchor::new(kind, id)` or `Anchor::kind_only(kind)` | | `RoleAssignment` | `RoleAssignment { role, scope, valid_from, valid_until }` | `RoleAssignment::new(role)` or `::in_scope(role, scope)`, `.valid_from(t)`, `.valid_until(t)` | | `OverrideSpec` | `OverrideSpec { rule, except }` | `OverrideSpec::new(rule).with_except(except)` | | `RetryPolicy` | `RetryPolicy { capacity: 500, ..RetryPolicy::default() }` | `RetryPolicy::default().with_capacity(500)`; also `with_base_delay_ms`, `with_max_delay_ms`, `with_on_drop` | | `Note` | `Note { text, anchor, origin }` | `Note::new(text, anchor, origin)` | | `NoteAnchor` | `NoteAnchor { element, placement }` | `NoteAnchor::new(element, placement)` | | `NoteOrigin` | `NoteOrigin { file, language, line, column, field }` | `NoteOrigin::new(file, language, line, column)`, `.with_field(field)` | | `import::openfga::Options` | `Options { model_file, ..Options::default() }` | `Options::default().with_model_file(..)`, `.with_tuples_file(..)` | | `import::casbin::Options` | `Options { actions, ..Options::default() }` | `Options::default().with_actions(..)`, `.with_model_file(..)`, `.with_policy_file(..)` | | `SessionOptions` (`strig-sync`) | `SessionOptions { heartbeat: None, ..Default::default() }` | `SessionOptions::default().with_heartbeat(None)`, `.with_buffer(n)` | | `WindowColumns` (`strig-postgres`) | `WindowColumns { effect, ..Default::default() }` | `WindowColumns::default().with_effect(..)`; also `with_valid_from`, `with_valid_until`, `with_allow_effect` | | `ListRequest` (`strig-server`) | `ListRequest { subject, permission, kind, layout, resources, env, at }` | `ListRequest::new(subject, permission, kind)`, `.with_layout(..)`, `.with_resources(..)`, `.with_env(..)`, `.with_at(..)` | | `RawResponse` (`strig-server`) | `RawResponse { status, body }` | `RawResponse::new(status, body)` | ### New, no action - `strig::audit::AUDIT_FORMAT` (1) and `strig::dsl::DSL_SCHEMA` (5) are public constants. - `dsl.run_tests` is in the `__all__` of the Python package. ## 0.10.0 Four changes break, all of them only for Rust code that names these types. The JavaScript package, the Python, Go and Java bindings, the JSON protocol, stored requests and records, and the audit hash need no edit. ### Rust: `AuditAction` is `#[non_exhaustive]` and has `ElevationReview` **Before.** ```rust title="Rust" match record.action { AuditAction::Apply => .., AuditAction::Check => .. /* every variant */ } ``` **After.** ```rust title="Rust" match record.action { AuditAction::Apply => .., AuditAction::Check => .., _ => .. } ``` **Step.** Add a `_ =>` arm to every `match` on `AuditAction`. `ElevationReview` is written only by `Elevations::close_review`, and in the JSON it is `elevation_review`: add it to a closed list of `action` values in a log consumer. `PendingStore` has a new method, `annotate`, with a default that refuses, so existing implementations still compile. ### Rust: `PendingRequest`, `Approved` and `AuditRecord` gain `impact` **Before.** ```rust title="Rust" let req = PendingRequest { id, actor, mutation, requested_at, status, expires_at, .. }; let AuditRecord { id, action, .. } = record; ``` **After.** ```rust title="Rust" let req = PendingRequest::new(id, actor, mutation, requested_at).expiring_at(Some(at)).with_impact(impact); let AuditRecord { id, action, .. } = record; ``` **Step.** Build a `PendingRequest` with `PendingRequest::new(..)` and its builders (`expiring_at`, `with_status`, `with_impact`, `with_elevation`). `Approved` (field `proposed_impact`) and `AuditRecord` come from `Approvals` and the auditor, so only code that built them by hand changes. Add `..` to every pattern that destructures any of the three. Stored requests and records without `impact` still load. ### Rust: `CatalogExport` gains `mutually_exclusive` and `conflicting_actions` **Before.** ```rust title="Rust" let export = CatalogExport { permissions, roles }; let CatalogExport { permissions, roles } = export; ``` **After.** ```rust title="Rust" let export = CatalogExport { permissions, roles, ..CatalogExport::default() }; let CatalogExport { permissions, roles, .. } = export; ``` **Step.** Build it with `CatalogExport { .., ..CatalogExport::default() }` or through `Catalog::export`, and put `..` in every pattern that destructures it. `Impact` gains `separation`. JSON and the bindings are unaffected: both fields are optional on read and omitted when empty. ### Rust: revisions in `strig-sync` and `strig-server` types `Change` (`strig-sync`), `Snapshot`, `CheckRequest`, `CheckResponse`, `BatchRequest` and `BatchResponse` (`strig-server`) gain a `revision` (`min_revision` on the two requests). `ServerMessage` and `ClientMessage` gain variants and fields (`ClientMessage::RefreshAtLeast`, `ServerMessage::Hello.version`, `ServerMessage::Capabilities.revision`). All of them are now `#[non_exhaustive]`. **Before.** ```rust title="Rust" let change = Change { scope, kind, .. }; let req = CheckRequest { subject, permission, resource, env, at }; match message { ServerMessage::Hello { .. } => .., ServerMessage::Change(c) => .. /* every variant */ } ``` **After.** ```rust title="Rust" let change = Change::new(kind, scope).with_revision(rev); let req = CheckRequest::new(subject, permission, resource).with_env(env).at(at).with_min_revision(rev); match message { ServerMessage::Hello { .. } => .., ServerMessage::Change(c) => .., _ => .. } ``` **Step.** Build values with the constructors and builders (`Change::new` and `with_revision`, `Snapshot::new` with `with_revision` and `with_tuples`, `CheckRequest::new` with `with_env`, `at` and `with_min_revision`, `BatchRequest::new`, `ServerMessage::hello` and `ServerMessage::capabilities` with `with_revision`). Add `..` to every pattern that destructures these structs and the two `ServerMessage` variants, and a `_` arm to every `match` on the two enums. Responses are built by the server, so only code that built them by hand changes. The JSON protocol stays additive: every new field is optional and omitted when empty, and a peer that sends none keeps working. ### Policies with separation of duties export `"schema": 5` `DSL_SCHEMA` is now 5. A policy that uses `mutually_exclusive`, `conflicting_actions` or the `separation_of_duties` invariant exports its canonical JSON with `"schema": 5`. A reader of an older schema refuses it instead of ignoring a rule that denies. A policy without them exports the schema it did before. **Step.** Upgrade every reader of the exported JSON (the JS package, `strig-cli`, other services) before you ship a policy that uses them. ### New, no action Everything else in 0.10 is additive: the language server and VS Code extension, audit proofs (Merkle, RFC 3161), `why_not`, change impact, `strig diff` and `strig lint`, the Casbin and OpenFGA importers, temporary elevation and break-glass, separation of duties, recertification campaigns and revisions for reading your own writes. ## 0.9.0 One change breaks, and only for Rust code. The JavaScript package, the JSON spec and stored data need no edit. ### Rust: `Grant`, `PermissionDef`, `Request`, `CatalogError`, `GrantError` and `Verdict` are `#[non_exhaustive]` Field permissions add `Grant::fields`, `PermissionDef::fields`, `Request::field` and new variants of `CatalogError`, `GrantError` and `Verdict`. **Before.** ```rust title="Rust" let g = Grant { id, effect, subject, permission, target, condition, .. }; match verdict { Verdict::Candidate => .., Verdict::OutOfScope => .. /* every variant */ } ``` **After.** ```rust title="Rust" let g = Grant::allow(id, subject, permission, target).when(condition); let r = Request::new(subject, permission, resource).field("email"); match verdict { Verdict::Candidate => .., Verdict::OutOfScope => .., _ => .. } ``` **Step.** Build values with the constructors and builders (`Grant::allow`, `Grant::deny`, `Grant::new` and its chained methods, `PermissionDef::new` and its builders, `Request::new` with `.field(..)`), and add a `_` arm to every `match` on `CatalogError`, `GrantError` and `Verdict`. Nothing changes for a policy that does not use fields. ### Policies with fields export `"schema": 4` `DSL_SCHEMA` is now 4. A policy that uses `fields` exports its canonical JSON with `"schema": 4`. A reader of an older schema refuses it instead of reading a field-restricted grant as covering the whole resource. A policy without fields exports the schema it did before. **Step.** Upgrade every reader of the exported JSON before you ship a policy with fields. ### New, no action ORM adapters (`/prisma`, `/drizzle`, `/kysely`), Envoy External Authorization in `strig-server` (`envoy` feature, off by default), policy tests and `strig-cli`, the Python package `strig-auth`, the Go and Java bindings over `strig-wasi`, and `allowedFields`, `explainFields` and `pickAllowed` in the JS binding. ## 0.8.0 Nothing breaks. Every change is additive and the defaults behave as in 0.7. Upgrading the crates and the npm package needs no edit to your code, your policies or your stored data. ### New, no action: opt-in features - **`tracing`** (a feature of `strig`, `strig-sync`, `strig-postgres`, `strig-redis` and `strig-server`, off by default): spans through `tracing` and metrics through the `metrics` facade. With the feature off nothing is compiled in. - **`conformance`** (a feature of `strig`, off by default, not stable API): `strig::exclusive_conformance::run`, the battery to run against your own `ExclusiveStore`. - **React and Angular** (`@the-hades-organization/strig/react` and `/angular`): `react` (18 or 19) and `@angular/core` (17+) are optional peers. Install them only if you import those subpaths. ### New, no action: Postgres and Redis storage `PgStore`, `PgExclusiveStore` and `RedisExclusiveStore` are additions. `strig-postgres` migration 4 adds the `_exclusive` table. `migrate` is idempotent and additive, so run it as you already do. The `ExclusiveStore` trait gained `acquire_lease`, `renew_lease`, `release_lease` and `remove_expired` with default bodies, so a store you implemented keeps compiling. `PgQueryError` is `#[non_exhaustive]`; an exhaustive `match` on it already needs a `_` arm. ### New, no action: AuthZEN in `strig-server` `DecisionServer::with_authzen(AuthzenConfig)` adds `/access/v1/*` and `/.well-known/authzen-configuration` next to `/v1`. Without that call the server has no such route and `/v1` is unchanged. ### New, no action: `checkMany` and `explainMany` `engine.checkMany(ctx, requests)` and `engine.explainMany(ctx, requests)` decide a batch in one call. `check`, `decide` and `explain` return the same results and throw the same errors as before. They run faster for plain-JSON requests. ## 0.7.0 Most of 0.7.0 is additive. The Rust items below break code that matches or builds the changed types exhaustively; the npm and policy items change behaviour you may depend on. ### Rust: `ChainError` has two new variants **Before.** `match error { Tampered { .. } => .., Broken { .. } => .., Unchained { .. } => .. }` was exhaustive. **After.** `verify_chain_anchored` can also return `ChainError::AnchorMismatch` (the chain does not start at the known anchor) and `ChainError::HeadMismatch` (it does not end at the published head). `verify_chain` itself returns the same three variants as before. **Step.** Add the two arms, or a `_ =>` arm that refuses the chain. `AuditError` and `AuditRecord` are unchanged, and so are stored records and hashes. ### Rust: `Condition::TimeBetween` and `Condition::WeekdayIn` have a `tz` field **Before.** ```rust title="Rust" let c = Condition::TimeBetween { from: "09:00".into(), until: "18:00".into() }; if let Condition::WeekdayIn { days } = &cond { .. } ``` **After.** Both variants carry `tz: Option`: ```rust title="Rust" let c = Condition::TimeBetween { from: "09:00".into(), until: "18:00".into(), tz: None }; if let Condition::WeekdayIn { days, .. } = &cond { .. } ``` **Step.** Add `tz: None` where you build the variants and `..` where you match them. The constructors `Condition::time_between` and `Condition::weekday_in` are unchanged, so prefer them, and `.in_tz("America/Sao_Paulo")` sets a zone. The JSON is unchanged: a condition without `tz` serializes exactly as before. ### Rust: new variants in `AuditAction` and `AuditOutcome` **Before.** `AuditAction` ended at `ExclusiveExpire` and `AuditOutcome` at `Denied`, and an exhaustive `match` on them compiled. **After.** The approval flow adds `AuditAction::MutationPropose`, `MutationApprove`, `MutationReject` and `MutationExpire`, and `AuditOutcome::Pending`. ```rust title="Rust" match record.action { // ... the arms you had AuditAction::MutationPropose => "change proposed", AuditAction::MutationApprove => "change approved", AuditAction::MutationReject => "change refused by an approver", AuditAction::MutationExpire => "pending change expired", } ``` **Step.** Add the four action arms and the `Pending` outcome arm, or a `_ =>` arm. Nothing changes for code that never calls the approval flow: only `Approvals` writes these values. In the JSON they are `mutation_propose`, `mutation_approve`, `mutation_reject`, `mutation_expire` and `pending`. If a log consumer, such as a SIEM mapping or a schema, accepts a closed list of `action` and `outcome` values, add them before you turn the flow on. ### Rust: `AuditRecord` has a `pending` field **Before.** `AuditRecord { at, level, actor, .., decision, full_grant, .. }` listed every field. **After.** There is one more field, `pending: Option`: the request of an approval-flow record, from the `standard` level up. **Step.** Add `pending: None` where you build the struct with a literal, and `..` where you destructure it. Records you already stored deserialize and hash as before. The field is left out of the canonical form when unset, so the hash chain and the test vector do not change. ### Policies that use `tz` export `"schema": 3` **Before.** `DSL_SCHEMA` was 2. **After.** `DSL_SCHEMA` is 3. A policy with no `tz` still exports the JSON it did before. One that uses `tz` exports its canonical JSON with `"schema": 3`. `Policy::from_json` accepts documents with or without `schema` and refuses one above 3. **Step.** Only if you read policy JSON with another reader, such as a service or a tool on an older version: upgrade it before you start writing `tz`. A reader of schema 2 refuses the document on purpose rather than reading the window in UTC. An unknown zone name is now a validation error when the policy loads, so fix the name. ### The `tz` default feature adds the time zone database **Before.** `strig` had `audit` as its only default feature. **After.** `default = ["audit", "tz"]`. The `tz` feature brings `chrono-tz`: about 0.9 MB more in the `.wasm` (2.70 MB to 3.58 MB, 657 KB to 785 KB gzipped). **Step.** If the size matters and you never use `tz`, set `default-features = false, features = ["audit"]`. A `tz` in a policy is then refused at load. ### npm: one package per platform **Before.** `@the-hades-organization/strig` bundled the five native modules, about 24 MB unpacked. **After.** Each platform has its own package, `@the-hades-organization/strig-`, installed as an optional dependency. A typical install is about 8 MB. The loader resolves the platform package, then a local build, then the wasm backend. Linux with musl is served by wasm, and `STRIG_BACKEND=native` throws a clear error when there is no native module. **Step.** Nothing for most installs. Do not install with `--omit=optional` or `--no-optional` if you want the native backend, or set `STRIG_BACKEND=wasm` on purpose. A Docker image on Alpine runs on wasm: see the numbers in [Benchmarks](https://strig.vercel.app/docs/benchmarks.md). If you vendored `node_modules` by platform or copied files out of the package, point them at the platform package. ### `strig-inspect --tab` and terminal text are in English **Before.** `strig-inspect --tab avaliacao|matriz|auditoria`, with terminal output such as `NEGADO`. **After.** `strig-inspect --tab evaluation|matrix|audit`, and the output is in English (`DENIED`). The example scenario in `examples/scenario.json` uses `ben`, `cara`, `visitor` and `invoice-7`. There is no locale selection yet. **Step.** Change `--tab` in scripts and shortcuts, and any script that matches the old text. ### New, no action `Mutation::kind()` and `MutationKind` (`add`, `remove`, `assign_role`, `revoke_role`), `strig::pending` (`Approvals`, `ApprovalPolicy`, `PendingStore`, `MemoryPendingStore`) and the JS `/approvals` subpath are additions. A `Governance` that nobody wraps in `Approvals` behaves as before, and a kind with no approval rule applies at once. The JSON store gains an optional `pending` list: a file without it 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. The other new pieces, the audit fail mode, the sink in JS, the route table, the `/store` and `/testing` subpaths, `strig-types` and the JS callbacks, are additive too. ## 0.6.0: Themis becomes Strig | Before | After | | --- | --- | | `themis-auth` (library `themis`) | `strig` (library `strig`) | | `themis-sync`, `-redis`, `-postgres`, `-axum`, `-macros`, `-server`, `-inspect` | `strig-sync`, `-redis`, `-postgres`, `-axum`, `-macros`, `-server`, `-inspect` | | npm `themis-auth` | npm `@the-hades-organization/strig` (since 0.6.1) | | `use themis::...` | `use strig::...` | | `*.themis` policy files | `*.strig` | | `THEMIS_*` environment variables | `STRIG_*` | **Step.** Rename the dependencies in `Cargo.toml` and `package.json`, the `use` paths, the policy file extension and the environment variables. Behaviour is the same. ## 0.5.0: `needs` becomes `depends_on` The Rules and Actors syntaxes write `depends_on ` on a `permission` line where they wrote `needs `. `needs` is now an error with the hint `write: depends_on `. Replace it in existing policy files, in the same position on the line. The JSON is unchanged. Blocks was already `depends_on`. --- # Security URL: https://strig.vercel.app/docs/security Strig decides who can access what, so a bug that grants access it should not is a security issue. ## Report a vulnerability Report it privately through GitHub Security Advisories: **Security → Report a vulnerability** on the [Strig repository](https://github.com/The-Hades-Organization/Strig/security/advisories/new). Do not open a public issue, a pull request or a discussion about it. Include the spec, the grants and the request that reproduce the problem, the decision you got and the one you expected, and the version: the crate or the npm package, and the backend, native or wasm. What to expect: | Step | When | | --- | --- | | Acknowledgement | Within 7 days. | | Assessment: accepted, declined with a reason, or more information needed | Within 14 days of the acknowledgement. | | Fix and advisory | We agree a fix and a release date with you and aim to release within 90 days of the report, sooner for an access bypass. We publish a GitHub Security Advisory, with a CVE when it applies, crediting you unless you prefer not to be named. Keep the report private until then. | ## Supported versions From 1.0, a security fix ships as a patch of the latest minor and of the last minor of the previous major, for 12 months after the new major. Before 1.0 only the latest `0.y` received fixes. A fix can come with a breaking change when keeping the old behaviour would be unsafe, and the release notes say so ([Upgrading](https://strig.vercel.app/docs/upgrading.md#deprecation-policy)). ## What is in scope - **A wrong authorization decision.** An allow where the model says deny: a deny grant, an override, a missing prerequisite, an expired validity window, a condition that does not hold, a failed callback. Also a deny explained wrongly in a way that misleads an operator. - **A bypass of governance.** A grant or role change that passes the invariants (`NoEscalation`, `NoLockout`, `Forbid`, `NonDelegable`, `ManagementOnly`, `SeparationOfDuties`, custom invariants) when it should be refused, or a refused change that reaches the stored grants. The same for an approval, an [elevation](https://strig.vercel.app/docs/governance/elevation.md) or a recertification that goes through when the flow should have refused it: an author approving their own request, an elevation past its maximum, a break-glass without its record. - **A break in the audit chain.** A record that can be altered, dropped or reordered without `verify_chain`, `verify_chain_anchored` or a [Merkle proof](https://strig.vercel.app/docs/audit.md) noticing, or a timestamp token that verifies for a head it does not cover. A hash that does not match [the format](https://strig.vercel.app/docs/audit.md#the-canonical-format). A redaction that leaks a masked attribute into the record. A change that goes through without a record under `FailMode::Closed`. - **Leaks across tenants or subjects** in listing and reverse queries (`list`, `who_can_on`, `access_of`), in the SQL produced by `strig-postgres`, in the real-time transports (`strig-sync`, `strig-redis`, `strig-axum`, `strig-server`) and in the JS integrations: the route table, `StrigRouteGuard` and `authorizeRoutes`, including a route the deny-by-default table lets through. - **Memory-safety or denial-of-service bugs** reachable from untrusted input: a policy file or JSON spec, a request, a frame on the wire, a store file. ## What is not in scope - Policies that are too permissive because of how the grants were written, and a catalog designed with a gap. - The behaviour of your own callbacks, sinks and stores (`call` conditions, JS overrides, an `AuditSink`), except when the engine mishandles what they return or throw. - Findings that need a malicious host process or access to the machine the engine runs on. - Vulnerabilities in a dependency with no way to reach them through Strig. Report these upstream. - The [inspector](https://strig.vercel.app/docs/tools/inspector.md) window and the playground, which are tools with no authority of their own. ## Verify a release Every GitHub release carries the native modules (`strig--.node`), the wasm archive, a `SHA256SUMS` file that lists all of them, and CycloneDX SBOMs: `strig--npm.cdx.json` for the npm package and the `*.cdx.json` files of the crates. Every npm package is published with provenance by the release workflow. ```text title="Terminal" # 1. Provenance: registry signatures and build attestations of what is in your node_modules. npm audit signatures # 2. A native module or archive from the release against the checksums. curl -LO https://github.com/The-Hades-Organization/Strig/releases/download/vX.Y.Z/SHA256SUMS sha256sum --check --ignore-missing SHA256SUMS # 3. The SBOMs: download the *.cdx.json files of the release and give them to your scanner, # for example `grype sbom:strig-X.Y.Z-npm.cdx.json`. ``` `npm audit signatures` fails for a package that has no valid signature or provenance. On the npm page of each package, "Provenance" links to the workflow run that built it. A package that has no provenance, or whose run is not in `The-Hades-Organization/Strig`, is not ours: do not install it, and tell us. --- # Benchmarks URL: https://strig.vercel.app/docs/benchmarks These numbers are a reference for the order of magnitude and for catching regressions, not a promise. Run them on your hardware before you size anything. ## Machine and versions | | | | --- | --- | | CPU | AMD Ryzen 7 7435HS (8 cores, 16 threads), laptop, frequency scaling on | | Memory | 15 GiB | | OS | Linux 7.3.3 (CachyOS) | | Rust | 1.99.0, `--release` bench profile | | criterion | 0.5.1 | | Node | 22.23.4 | | Bun | 1.4.4 | | Strig | 0.6.1 plus the unreleased changes of the day, `tz` feature on as by default | A laptop under normal desktop load: expect 10% to 20% of noise between runs on the slower cases. Two runs of the Rust suite gave 12.8 and 14.7 µs for the same case. Treat smaller differences as noise. ## What is measured All cases share one catalog (`document.view` and `document.edit` on `document` and `project`, broad target `org`). | Case | What it does | | --- | --- | | `decide/simple` | One `decide` against one role grant on the org. | | `decide/conditions_and_relations` | One `decide` of `document.edit` against about 1,000 grants: one guarded by an `eq` and a `time_between` condition, one through the `editor` relation (50 tuples), 1,000 unrelated grants the engine has to skip and, in Rust only, 10 deny locks. | | `list/plan` | `list` of what the subject can edit among `document`s: the plan of the filter, with the same grants and 50 tuples. | | `list/resolve_10k_rows` | `list` plus resolving the filter over 10,000 resources in memory (in JS, one call with `resources`). | | `apply/governance` | One `Add` of a grant through `Governance` with `CatalogConformance` and `NoSelfManagement`, no audit. | | `apply/governance_with_audit` | The same, audited at the `standard` level. In Rust to a `JsonLinesAudit` over `io::sink()`. In JS the record is built and returned, with no sink. | | `apply/governance_with_audit_sink` | JS only: the same, with an `auditSink` that does nothing, to price the call into JavaScript. | The JS numbers include what crosses the boundary: the request and the result are serialized as JSON, and a `decide` takes the `Context` that already holds the grants. That cost, not the decision, is most of the difference between a Rust call and a JS call on the small cases. ## Rust Median of the criterion estimate. | Case | Time | | --- | ---: | | `decide/simple` | 479 ns | | `decide/conditions_and_relations` | 14.7 µs | | `list/plan` | 41.1 µs | | `list/resolve_10k_rows` | 4.02 ms (about 400 ns per row) | | `apply/governance` | 410 ns | | `apply/governance_with_audit` | 1.01 µs | The cost of a decision grows with the grants that name the same permission and kind, not with the size of the catalog: the 1,000 unrelated grants are most of what separates the two decide cases. The audit adds about 0.6 µs per change at `standard`. The `forensic` level also hashes with SHA-256, so it costs more. Listing filters 10,000 rows in memory in the time of about 8,000 single `decide` calls of the simple case. `strig-postgres` turns the same plan into SQL instead of resolving rows in memory. ## JavaScript Median of seven samples of 500 ms each, after 300 ms of warm-up. This table was taken before the boundary change described [below](#javascript-the-boundary-before-and-after); `decide` and `apply` are faster now, and the second table has the new numbers for the small cases. | Case | Node, native | Node, wasm | Bun, native | Bun, wasm | | --- | ---: | ---: | ---: | ---: | | `decide/simple` | 16.1 µs | 19.6 µs | 12.6 µs | 22.0 µs | | `decide/conditions_and_relations` | 30.9 µs | 42.4 µs | 31.6 µs | 41.0 µs | | `list/plan` | 248 µs | 300 µs | 232 µs | 303 µs | | `list/resolve_10k_rows` | 87.1 ms | 92.7 ms | 77.2 ms | 103 ms | | `apply/governance` | 28.9 µs | 34.1 µs | 24.0 µs | 39.1 µs | | `apply/governance_with_audit` | 40.3 µs | 48.4 µs | 36.4 µs | 53.0 µs | | `apply/governance_with_audit_sink` | 45.3 µs | 57.3 µs | 38.4 µs | 82.0 µs | Reading them: - Before the change, the native module cost 16 µs for a simple decision, most of it the boundary, against 0.5 µs in Rust. - The wasm backend is about 1.2 to 1.4 times slower than native on Node. Bun's wasm shows the widest spread, so treat its figures as rough. This is also what a Linux musl or Alpine install runs on ([JavaScript](https://strig.vercel.app/docs/javascript.md#install-by-platform)). - `list/resolve_10k_rows` includes sending 10,000 resources into the engine. It is the cost of an exact in-memory filter from JS. - An `auditSink` adds one JavaScript call per record, about 5 µs on Node native. ## JavaScript: the boundary, before and after A `check` on Node native spent its time like this, when `decide/simple` took 16.1 µs against 0.48 µs in Rust: | Step | Cost | | --- | ---: | | An empty N-API call | 0.25 µs | | Reading the request object, property by property, about 0.7 µs per leaf | about 12 µs | | The engine | 0.5 µs | | `JSON.stringify` of the same request | 0.77 µs | | Parsing that string in Rust | 0.73 µs | The `Context` already held the grants on the Rust side, so the grants were never the cost; the request and the response were. The wasm glue showed the same shape (`check` 15.6 µs). The binding now crosses with one string (`JSON.stringify` in, `JSON.parse` out for `decide` and `explain`), and `checkMany` spreads the call over a batch. With 100 requests per batch (median): | Case | Node, native | Node, wasm | Bun, native | Bun, wasm | | --- | ---: | ---: | ---: | ---: | | `decide/simple` | 6.5 µs | 9.3 µs | 5.1 µs | 8.6 µs | | `check/simple` | 3.5 µs | 4.5 µs | 2.6 µs | 3.3 µs | | `checkMany/simple`, per decision | 2.5 µs | 3.7 µs | 2.5 µs | 3.2 µs | A single `decide` stays above 2 µs on Node native. A `check` costs at least 0.77 µs to stringify, 0.73 µs to parse, 0.49 µs in the engine and 0.25 µs for the call, about 2.3 µs, and a `decide` adds the building, serialising and parsing of the `Decision`, about 1.6 µs. Going lower needs a request that is not text, such as handles to a subject and a resource prepared once, which is a different API. For one request, `check` is the cheapest answer. For many, `checkMany`. ## Reproduce Rust, from the repository root: ```text title="Terminal" export CARGO_TARGET_DIR=/path/with/space # optional: the release build and criterion need a few GB cargo bench -p strig --bench engine ``` criterion prints the estimate per case and keeps its reports under `target/criterion`. `cargo bench -p strig --bench listing` prints listing against a per-row `check` for growing tables, and the cost of each kind of condition. JavaScript, from `crates/strig-node/js`: ```text title="Terminal" sh ../scripts/build.sh all # the native module and the wasm npm ci npm run build:ts node bench/bench.mjs # both backends; --backend native|wasm picks one bun bench/bench.mjs ``` The `Benchmarks` workflow in GitHub Actions, run by hand, does the same on a GitHub runner. It is not part of CI, and runner numbers are noisier than a dedicated machine, so compare only runs from the same kind of machine.