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