Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ jobs:
cache: pip
- run: python -m pip install -r requirements-dev.txt
- run: python -m pytest --cov=policy_engine --cov-report=term-missing
- run: python -m build
if: matrix.os == 'windows-latest' && matrix.python == '3.11'
- run: python scripts/verify_distribution.py
if: matrix.os == 'windows-latest' && matrix.python == '3.11'

quality:
runs-on: ubuntu-latest
Expand All @@ -55,11 +59,5 @@ jobs:
- run: python -m pip_audit --local --progress-spinner off
- run: python -m build
- run: python -m twine check dist/*
- name: Smoke-test built wheel
shell: bash
run: |
python -m venv /tmp/samsarix-policy-wheel
/tmp/samsarix-policy-wheel/bin/python -m pip install --no-deps dist/*.whl
/tmp/samsarix-policy-wheel/bin/samsarix-policy --version
cd /tmp
/tmp/samsarix-policy-wheel/bin/python -c "from importlib.resources import files; import policy_engine; assert files('policy_engine').joinpath('schemas', 'policy.schema.json').is_file()"
- name: Verify distributions and installed journeys
run: python scripts/verify_distribution.py
9 changes: 2 additions & 7 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,8 @@ jobs:
PY
- run: python -m build
- run: python -m twine check dist/*
- name: Smoke-test wheel
run: |
python -m venv /tmp/samsarix-policy-release
/tmp/samsarix-policy-release/bin/python -m pip install --no-deps dist/*.whl
cd /tmp
/tmp/samsarix-policy-release/bin/samsarix-policy --version
/tmp/samsarix-policy-release/bin/python -I -c "from importlib.resources import files; import policy_engine; assert files('policy_engine').joinpath('schemas', 'decision.schema.json').is_file()"
- name: Verify distributions and installed journeys
run: python scripts/verify_distribution.py
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: samsarix-policy-engine-${{ github.run_id }}
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ until the owner publishes a release.
- Policy, request, decision, and policy-test JSON Schemas with validated examples.
- Schema-validated policy test suites, a stable test report API, and `samsarix-policy test` for CI.
- Correlation-safe batch evaluation for up to 1,000 requests through the API and CLI.
- Versioned policy artifacts with full SHA-256 manifest pins, application contracts, optional
passing-suite evidence, and `pack` / `verify-artifact` / pinned `check` commands.
- Public fail-closed `guarded_call` and opt-in minimized audit events; actual pinned-file consumer.
- Self-contained offline schemas and automated wheel/sdist inventories plus installed journeys.
- Direct Request construction now validates fields and bounded contexts before freezing; mixed-key
batch errors remain structured; unpaired surrogates and integers over 4,096 bits are rejected.
- A regression-tested agent-tool enforcement example covering explicit allow, explicit deny,
default deny, overlapping rules, environment boundaries, and approvals.
- Examples, tests, pinned CI, dependency maintenance, candidate-artifact automation, structured
Expand Down
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ include requirements-dev.txt
recursive-include docs *.md
recursive-include examples *.json *.md *.py
recursive-include tests *.py
recursive-include scripts *.py
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ Install the local package and run the included decision:
python -m pip install -e .
samsarix-policy validate examples/policy.json
samsarix-policy check --policy examples/policy.json --request examples/request.allowed.json --pretty
samsarix-policy test --policy examples/agent-tool-gateway/policy.json \
--suite examples/agent-tool-gateway/policy-tests.json --pretty
samsarix-policy test --policy examples/agent-tool-gateway/policy.json --suite examples/agent-tool-gateway/policy-tests.json --pretty
```

The allowed example exits `0` and prints a JSON decision. The denied example prints a denial and
Expand Down Expand Up @@ -99,12 +98,15 @@ characters; regex metacharacters have no special meaning. Conditions are ANDed a
paths under the request's `context` object. See [Policy format](docs/POLICY_FORMAT.md) for the full
contract and the bundled [policy](policy_engine/schemas/policy.schema.json),
[request](policy_engine/schemas/request.schema.json),
[decision](policy_engine/schemas/decision.schema.json), and
[decision](policy_engine/schemas/decision.schema.json),
[test-suite](policy_engine/schemas/test-suite.schema.json), and
[batch](policy_engine/schemas/batch.schema.json) schemas for editor and integration
support.

For multi-action gateways and jobs, see [bounded batch evaluation](docs/BATCH_EVALUATION.md).
For tested revisions, trusted deployment pins, and opt-in audited enforcement, see
[policy artifacts](docs/POLICY_ARTIFACTS.md). Run `python examples/pinned_gateway.py` for an actual
temporary-file read and a denied callback using the public API.

## Python API

Expand Down Expand Up @@ -142,6 +144,9 @@ samsarix-policy check --policy POLICY --request REQUEST|-
[--explain] [--pretty]
samsarix-policy test --policy POLICY --suite TEST_SUITE [--pretty]
samsarix-policy batch --policy POLICY --batch BATCH [--explain] [--pretty]
samsarix-policy pack --policy POLICY --revision REV --application APP --output NEW_FILE [--suite SUITE]
samsarix-policy verify-artifact --artifact FILE --sha256 TRUSTED_SHA256 --application APP
samsarix-policy check --artifact FILE --sha256 TRUSTED_SHA256 --application APP --request REQUEST
```

Use `--request -` to read a request from stdin. Policy files are limited to 1 MiB, request files
Expand All @@ -159,6 +164,7 @@ python -m mypy policy_engine
python -m pytest --cov=policy_engine --cov-report=term-missing
python -m build
python -m twine check dist/*
python scripts/verify_distribution.py
```

CI runs the same meaningful checks across supported Python versions. A wheel-install smoke test is
Expand All @@ -182,7 +188,8 @@ from this product; Git history retains it at commit `da2029a` for provenance.
decision before performing the action.
- Policies and requests are untrusted input and are validated with bounded resource use.
- Default-deny is the secure default, and explicit deny overrides allow.
- The engine stores nothing, transmits nothing, and logs no request or context values.
- Evaluation stores nothing and transmits nothing. The optional `guarded_call` audit sink is
caller-owned, synchronous, and off by default; audit delivery failure prevents execution.
- Policy digests identify content but are not signatures; authenticate policy distribution in the
embedding system when tamper resistance matters.
- Evaluation has no external API or operating cost beyond local CPU and memory.
Expand All @@ -195,8 +202,8 @@ See [SECURITY.md](SECURITY.md) for the trust boundary and responsible-reporting
service, policy editor, database, or complete RBAC/ABAC platform.
- Conditions do not execute code, call external data sources, traverse arrays by path, or support
regex. These constraints keep evaluation reviewable and bounded.
- Policies are loaded explicitly. Hot reload, signing, remote bundles, and decision-log sinks remain
embedding concerns.
- Policies and revisioned artifacts are loaded explicitly. Hot reload, signing, remote delivery,
and durable audit storage remain embedding concerns.
- Test suites verify supplied cases; they do not prove that callers enforce decisions or construct
truthful request attributes.
- `default: "allow"` exists for migration scenarios but should be chosen deliberately.
Expand Down
9 changes: 5 additions & 4 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,17 @@ Current hardening backlog:

- A regression-tested agent-tool example now enforces decisions before invoking callbacks. A
production consumer and representative-user evidence are still required for flagship adoption.
- No signed policy distribution, hot reload, policy version service, audit sink, identity model, or multi-process cache; these are acceptable exclusions but limit the wedge.
- No signed policy distribution, hot reload, remote version service, identity model, or multi-process
cache. These remain deliberate exclusions. Local pinned artifacts and opt-in audit hooks exist.
- Wildcard and condition semantics are deliberately small and may be insufficient for complex authorization.
- The 1,000-evaluation monthly BSL production grant is poorly aligned with normal policy-engine volume.
- CI and wheel/sdist behavior are verified. PyPI package-name ownership and trusted-publisher
configuration still require owner evidence before publication.
- The flagship already contains multiple policy implementations, leaving canonical ownership unresolved.

Bounded batch evaluation is implemented with strict correlation and resource limits. The next
competitive increments are versioned policy artifacts, an opt-in redacted audit adapter, and
consumer-specific enforcement adapters. The evidence and rationale are
Bounded batch evaluation, revisioned/pinned artifacts, minimized audit hooks, and a local file
enforcement consumer are implemented. Further framework adapters, signing, and hot reload should
follow representative-user demand, not block evaluation of the release candidate. The rationale is
recorded in `docs/COMPETITIVE_LANDSCAPE.md`.

## Samsarix adoption
Expand Down
6 changes: 5 additions & 1 deletion docs/BATCH_EVALUATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ Batch evaluation amortizes policy loading when a gateway, agent, or job must aut
samsarix-policy batch --policy examples/policy.json --batch examples/request.batch.json --pretty
```

Input contains 1–1,000 requests and is limited to 2 MiB. Every request needs a unique, non-null `request_id`; decisions retain input order. Malformed entries reject the whole batch with exit code `2`. A valid batch exits `0` even when individual decisions deny access; inspect each decision.
Input contains 1–1,000 requests; file loading through `load_batch` and the CLI is limited to 2 MiB.
In-memory construction enforces request count plus each request's field/context limits instead.
Every request needs a unique, non-null `request_id`; decisions retain input order. Malformed entries
reject the whole batch with exit code `2`. A valid batch exits `0` even when individual decisions
deny access; inspect each decision.

Library consumers call `parse_batch` or `load_batch`, then `evaluate_batch(engine, batch)`. Enable explanations only for diagnostics because output scales with request and rule counts. Enforce every decision immediately before its corresponding action.
19 changes: 10 additions & 9 deletions docs/COMPETITIVE_LANDSCAPE.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Competitive landscape and product wedge

Research refreshed August 8, 2026. This document records product decisions, not compatibility or
Research refreshed August 31, 2026 (OPA bundles and OpenFGA immutable-model guidance rechecked).
This document records product decisions, not compatibility or
feature-parity claims.

## Recurring capabilities
Expand All @@ -25,15 +26,15 @@ a daemon, policy language runtime, database, or telemetry.

## Prioritized increments

1. **Executable policy suites and enforcement example** — implemented in the current increment.
2. **Bounded batch evaluation** — evaluate heterogeneous requests with stable per-item results and
1. **Executable policy suites and enforcement example** — implemented.
2. **Bounded batch evaluation** — implemented; evaluate heterogeneous requests with stable per-item results and
clear whole-batch validation/failure semantics.
3. **Versioned policy artifacts** — a manifest containing policy digest, application compatibility,
and test evidence; signature verification only with a reviewed cryptographic dependency.
4. **Opt-in audit adapter** — caller-owned sink interface, explicit redaction, backpressure behavior,
and correlation IDs; never silent telemetry.
5. **Consumer adapters** — framework-specific enforcement examples only after the core contracts are
stable and each adapter has a side-effect-boundary integration test.
3. **Versioned policy artifacts** — implemented: full manifest digest, exact application contract,
revision, and optional passing-test evidence; trusted pins required for deployment loading.
4. **Opt-in audit adapter** — implemented: minimized events, synchronous caller-owned sink,
fail-closed delivery, and opt-in correlation IDs; no silent telemetry.
5. **Consumer adapters** — the pinned file gateway proves a real local side-effect boundary.
Framework-specific adapters remain demand-driven; no dependency-heavy web framework is required.

## Deliberate non-goals

Expand Down
116 changes: 116 additions & 0 deletions docs/POLICY_ARTIFACTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# Pinned artifacts and action enforcement

Use an artifact when a reviewed policy must move from CI to a particular application without
silently picking up a different revision. Everything runs locally; no signing key or service is
required. An artifact is **not a signature**. The expected hash must come from separately protected
deployment configuration, not from the downloaded artifact itself.

## Complete local journey

After installing this repository, run:

```bash
python examples/pinned_gateway.py
```

The demo tests the file policy, packages revision `files-r1`, pins it for `file-gateway-v1`, verifies
it, reads an actual temporary document through `guarded_call`, and rejects a secret-read callback.
Output includes the document text, `denied_operation_executed: false`, and two minimized audit
records. Temporary files are cleaned up. This is a local reference consumer, not production adoption.

To prepare an artifact for your own deployment (use a new output filename each time):

```bash
samsarix-policy pack --policy examples/policy.json --revision files-r1 --application file-gateway-v1 --suite examples/file-policy-tests.json --output policy.artifact.json
```

Record the `sha256` printed by this trusted build in protected deployment configuration. Then use
that 64-character value in place of `TRUSTED_SHA256`:

```text
samsarix-policy verify-artifact --artifact policy.artifact.json --sha256 TRUSTED_SHA256 --application file-gateway-v1
samsarix-policy check --artifact policy.artifact.json --sha256 TRUSTED_SHA256 --application file-gateway-v1 --request examples/request.allowed.json
```

`pack` never overwrites a file. Failed suites, invalid input, file errors, or pin mismatches exit `2`
without a decision on stdout. `verify-artifact` exits `0` on success; `check` retains allow `0` and
deny `3`. The packer's output file uses canonical ASCII JSON regardless of terminal encoding.
An interrupted write may leave an incomplete file: verification rejects it; retry at a new path.

## Contract and compatibility

- `schema_version: 1` describes the artifact envelope. The nested policy's schema version still
describes rule grammar; neither field is a deployment revision.
- `revision` is a caller-assigned identifier (for example a Git commit or release label).
- `application` is an exact-match consumer contract identifier (for example `invoice-service-v2`).
It is not an automatically inferred compatibility guarantee or version range.
- `policy` is the validated, normalized policy, including defaults and descriptions, excluding
its editor-only `$schema`. Rule/pattern/list ordering is preserved; conditions are path-sorted.
- `tests` is null if no suite was supplied. Otherwise the builder executes every case and records
suite name, case count, and full suite SHA-256. Requests and test case names are not embedded.
Suite name and policy content can still be sensitive: treat artifacts as configuration data.
- `sha256` is the full SHA-256 of the manifest **without** its `sha256` field. It binds the policy,
revision, application, canonicalization identifier, and test evidence together.
- `canonicalization: samsarix-json-v1` means Python JSON serialization with sorted object keys,
`ensure_ascii=True`, `allow_nan=False`, and separators `(',', ':')`, encoded as ASCII without a
newline. It is not RFC 8785/JCS. Numeric `1` and `1.0` can have different identities. Do not
reimplement this format in another language without matching golden vectors.
- Artifacts are bounded to 2 MiB, including metadata. Existing policy limits still apply.
`create_artifact` also enforces the serialized limit; `load_artifact` bounds its file read.

Parsing normalizes the nested policy before hashing; insignificant formatting, key order, and
equivalent omitted defaults do not change its identity. This is a content identity, not the hash of
the raw file. Existing decisions retain the backward-compatible 32-character `policy_digest`,
which does **not** include revision/application/evidence; do not substitute it for the artifact pin.

`parse_artifact` checks internal consistency only. `load_artifact(path, expected_sha256=...,
application=...)` additionally enforces trusted pins. An attacker can recompute an internal hash,
but cannot match a separately protected pin for different content. Suite metadata is a builder
claim, not independent attestation; verification does not rerun tests whose inputs are not shipped.
To roll back, explicitly restore a prior trusted pin and its reviewed artifact together. There is
no automatic newest-version selection, anti-rollback counter, hot reload, or signature verifier.

## Library enforcement and audit

```python
from policy_engine import PolicyEngine, guarded_call, load_artifact

artifact = load_artifact(path, expected_sha256=trusted_digest, application="file-gateway-v1")
engine = PolicyEngine(artifact.policy)
result = guarded_call(engine, request, operation, audit_sink=my_sink)
```

The sink receives an immutable `AuditEvent` **before** an allowed operation executes, and also on
denials. Its JSON contract has `schema_version: 1`, `event: policy_decision`, `allowed`, `reason`,
`policy_digest`, and `request_id` (null by default). Principal, action, resource, context, policy ID,
rule IDs, and mismatch paths are omitted. Set `include_request_id=True` only for safe correlation
IDs. A sink can serialize with `event.to_dict()`; there is no default log, file, network, or telemetry.

- Denial raises `ActionDenied` and never invokes the callback.
- Sink failure raises `AuditDeliveryError` and never invokes the callback. The original exception
is chained for diagnostics; callers must avoid exposing sink error details to untrusted users.
- No sink means no audit I/O. A supplied sink is synchronous backpressure: caller-owned timeout,
storage durability, retention, access control, and sink availability must be designed explicitly.
- The callback is called once on allow. Callback exceptions propagate without retries.
- A decision event is not an operation-success receipt or transaction. If exactly-once effects or
durable audit are needed, the embedding application owns that transactional protocol.

Only trusted application code may construct request attributes, select callbacks, and map logical
resources to actual files/tools. Do not pass attacker-controlled paths directly to file APIs. The
library cannot protect operations that bypass the guard or changes to a resource after evaluation.

## Offline editor/integration schemas

```python
from policy_engine.schemas import schema_document

document = schema_document("artifact.schema.json")
# Optional integration dependency, not needed for runtime policy evaluation:
# jsonschema.Draft202012Validator(document).validate(artifact.to_dict())
```

`schema_document` bundles all references as local JSON pointers from package resources. It does not
fetch schema URLs. The six raw schema files retain logical `$id` values; those identifiers do not
promise hosted endpoints. Use the bundled document for offline validation. JSON Schema cannot
verify checksums, correlate unique batch IDs, or enforce every aggregate runtime limit; Python
parsers/loaders remain authoritative.
Loading