From ca0f5ea00929e4e4207208db2da814a068d7100f Mon Sep 17 00:00:00 2001 From: Deathcharge Date: Mon, 31 Aug 2026 13:06:55 -0400 Subject: [PATCH 1/2] Complete pinned policy deployment and audited enforcement --- .github/workflows/ci.yml | 14 +- .github/workflows/release.yml | 9 +- CHANGELOG.md | 6 + MANIFEST.in | 1 + README.md | 16 +- ROADMAP.md | 9 +- docs/BATCH_EVALUATION.md | 6 +- docs/COMPETITIVE_LANDSCAPE.md | 19 +- docs/POLICY_ARTIFACTS.md | 116 ++++++++++++ docs/PRODUCTIZATION.md | 59 ++++++- docs/RELEASING.md | 11 +- examples/file-policy-tests.json | 9 + examples/pinned_gateway.py | 76 ++++++++ policy_engine/__init__.py | 19 ++ policy_engine/artifacts.py | 194 +++++++++++++++++++++ policy_engine/batching.py | 4 +- policy_engine/cli.py | 97 ++++++++++- policy_engine/enforcement.py | 77 ++++++++ policy_engine/engine.py | 7 +- policy_engine/errors.py | 4 + policy_engine/models.py | 17 +- policy_engine/schemas/__init__.py | 58 +++++- policy_engine/schemas/artifact.schema.json | 34 ++++ policy_engine/validation.py | 39 +++-- pyproject.toml | 1 + scripts/smoke_installed.py | 158 +++++++++++++++++ scripts/verify_distribution.py | 70 ++++++++ tests/test_artifacts.py | 170 ++++++++++++++++++ tests/test_cli.py | 57 ++++++ tests/test_enforcement.py | 93 ++++++++++ tests/test_example_consumer.py | 11 ++ 31 files changed, 1399 insertions(+), 62 deletions(-) create mode 100644 docs/POLICY_ARTIFACTS.md create mode 100644 examples/file-policy-tests.json create mode 100644 examples/pinned_gateway.py create mode 100644 policy_engine/artifacts.py create mode 100644 policy_engine/enforcement.py create mode 100644 policy_engine/schemas/artifact.schema.json create mode 100644 scripts/smoke_installed.py create mode 100644 scripts/verify_distribution.py create mode 100644 tests/test_artifacts.py create mode 100644 tests/test_enforcement.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 28b5d6e..c080ec1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 36ebfde..a4eec0f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 }} diff --git a/CHANGELOG.md b/CHANGELOG.md index ed01231..bf3ad96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/MANIFEST.in b/MANIFEST.in index 43e1baf..c87ecc3 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -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 diff --git a/README.md b/README.md index ea0917b..6179155 100644 --- a/README.md +++ b/README.md @@ -99,12 +99,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 @@ -142,6 +145,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 @@ -159,6 +165,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 @@ -182,7 +189,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. @@ -195,8 +203,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. diff --git a/ROADMAP.md b/ROADMAP.md index cb35155..6971925 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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 diff --git a/docs/BATCH_EVALUATION.md b/docs/BATCH_EVALUATION.md index d0aa3e0..12d9c5c 100644 --- a/docs/BATCH_EVALUATION.md +++ b/docs/BATCH_EVALUATION.md @@ -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. diff --git a/docs/COMPETITIVE_LANDSCAPE.md b/docs/COMPETITIVE_LANDSCAPE.md index 159eebd..ec3052b 100644 --- a/docs/COMPETITIVE_LANDSCAPE.md +++ b/docs/COMPETITIVE_LANDSCAPE.md @@ -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 @@ -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 diff --git a/docs/POLICY_ARTIFACTS.md b/docs/POLICY_ARTIFACTS.md new file mode 100644 index 0000000..595a1ab --- /dev/null +++ b/docs/POLICY_ARTIFACTS.md @@ -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. diff --git a/docs/PRODUCTIZATION.md b/docs/PRODUCTIZATION.md index e22ad37..352b259 100644 --- a/docs/PRODUCTIZATION.md +++ b/docs/PRODUCTIZATION.md @@ -1,6 +1,7 @@ # Productization record -Last updated: 2026-07-28 +Last updated: 2026-08-31. Historical results below are dated; the wrap-up section describes the +current candidate. ## Repository assessment @@ -132,7 +133,7 @@ planned checks as passed. - [x] `validate` and `check` CLI commands. - [x] Runnable allow and deny examples. - [x] Public API documentation and policy-format reference. -- [x] Draft 2020-12 policy, request, decision, test-suite, and batch schemas with example validation. +- [x] Six Draft 2020-12 schemas, including artifacts, with self-contained offline bundling. - [x] Test suite and CI workflow. - [x] Build and package configuration. - [x] Pinned CI actions, dependency updates, candidate-artifact workflow, and release runbook. @@ -224,3 +225,57 @@ Run locally on Windows with Python 3.11.9 on 2026-07-28: The engineering disposition is **release candidate**, not public-release approval. Public publication remains blocked on the named owner/legal license decisions and PyPI setup, and production use remains gated on independent security review and representative user validation. + +## 2026-08-31 wrap-up: current candidate + +Baseline: clean `main` at `8ddaa1f` after upstream dependency-maintenance merges, 115 passing tests. +Completed the remaining local promotion/enforcement workflow: + +- Deterministic unsigned artifacts pin revision, exact application contract, normalized policy, + and optional passing-suite evidence under a full SHA-256 manifest digest. Deployment loading + requires a separately trusted digest and application identifier. +- `pack`, `verify-artifact`, and pinned `check` commands, with exclusive-create output and stable + allow/deny/invalid exit behavior. No release tag or public publication is implicit. +- Public `guarded_call` enforces before invoking callbacks and supports a synchronous optional + minimized audit sink. Denial and audit failure prevent execution; no automatic retries or logs. +- Actual temporary-file consumer (`examples/pinned_gateway.py`) and three-case file policy suite. +- Direct Request values validate fields/context before freezing. Mixed-key batch errors remain + structured; diagnostic accumulation stops at its budget. Unpaired Unicode surrogates and + >4,096-bit integers are rejected; policy hashing streams JSON chunks. +- Self-contained offline schemas resolve only packaged resources. Raw schema IDs are identifiers, + not promises of a deployed `schemas.samsarix.com` service. +- The distribution verifier checks both archive inventories and exercises every command from an + isolated wheel install. Linux and Windows CI use that same verifier. +- Development pip is constrained to `>=26.2,<27` after the audit reported `PYSEC-2026-3721` against + pip 26.1.2. Upgraded locally to 26.2.1 and re-audited: no known vulnerabilities (unpublished local + package skipped). Runtime dependencies remain empty. + +Local verification: formatting, lint and strict mypy passed; 150 tests passed with 93.15% +branch-aware coverage. Wheel and sdist build/Twine checks and isolated installed journeys passed. +Final distribution checks use `python scripts/verify_distribution.py --dist +dist/candidate-20260831-final`; exact final artifact hashes and CI results belong in the PR record. + +### Remaining owner-controlled release gates + +1. Confirm license parameters with the owner/counsel. The standard BUSL body and 1,000-evaluation + grant were not changed in this increment. No commercial agreement has been fabricated. +2. Confirm the PyPI project belongs to Samsarix LLC; configure a trusted publisher tied to + `Deathcharge/policy-engine`, the release workflow, and protected `pypi` environment; approve + publication explicitly. Public-install evidence cannot exist before publication. +3. Supply production-consumer/representative-user and independent-review evidence before claiming + production adoption. The local reference consumer is not a production customer. + +Repository migration is optional: keeping `Deathcharge/policy-engine` preserves working history and +links. A later owner-directed transfer can update URLs without changing Python imports or package +identity. No other repository, website, account, infrastructure, or Git history was changed. + +### Ordered post-candidate work + +1. Representative integration trials: attribute construction, enforcement coverage, expected load, + licensing fit, and support expectations. +2. Measured benchmark corpus and workload-specific batch/explanation limits if needed. +3. Framework adapters driven by those trials; signing/hot reload only with explicit requirements. + No general-purpose hosted control plane is planned for this library. + +Disposition: **engineering release candidate with named external gates**, not a published or +independently production-validated offering. Optional roadmap items are not core-path placeholders. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index bded7a4..f6e6ea3 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -31,12 +31,13 @@ python -m pytest --cov=policy_engine --cov-report=term-missing python -m pip_audit --local --progress-spinner off python -m build python -m twine check dist/* +python scripts/verify_distribution.py ``` Inspect the wheel and source archive separately. The wheel must contain only the importable -`policy_engine` package, all five JSON schemas, the typing marker, and its distribution metadata +`policy_engine` package, all six JSON schemas, the typing marker, and its distribution metadata and license file. The source archive additionally contains the maintainer documentation, examples, -tests, and development requirements declared by `MANIFEST.in`. Neither artifact may contain +tests, verification scripts, and development requirements declared by `MANIFEST.in`. Neither artifact may contain credentials, virtual environments, caches, build logs, or the historical `helix_core` extraction. ## 3. Exercise the artifact @@ -57,13 +58,15 @@ wheel-smoke/bin/samsarix-policy test \ --policy "$REPOSITORY_ROOT"/examples/agent-tool-gateway/policy.json \ --suite "$REPOSITORY_ROOT"/examples/agent-tool-gateway/policy-tests.json \ --pretty -wheel-smoke/bin/python -I -c "from importlib.resources import files; root = files('policy_engine').joinpath('schemas'); assert all(root.joinpath(name).is_file() for name in ('policy.schema.json', 'request.schema.json', 'decision.schema.json', 'test-suite.schema.json', 'batch.schema.json'))" +wheel-smoke/bin/python -I -c "from policy_engine.schemas import SCHEMA_NAMES, schema_document; assert len(SCHEMA_NAMES) == 6; assert all(schema_document(name) for name in SCHEMA_NAMES)" ``` Use `wheel-smoke\Scripts\` instead of `wheel-smoke/bin/` on Windows. Also verify the denied fixture exits `3` and invalid input exits `2`. The policy-suite command must exit `0` with `passed: true`, `total: 7`, and `failed_count: 0`; the final command verifies that the installed wheel exposes all -five schemas used by editors and integrations. +six schemas used by editors and integrations. `scripts/verify_distribution.py` automates isolated +wheel installation, both archive inventories, and allow/deny/invalid, suite, batch, artifact-pinning, +and guarded-audit journeys. Use `--dist PATH` for a directory containing exactly one wheel and sdist. ## 4. Tag and stage diff --git a/examples/file-policy-tests.json b/examples/file-policy-tests.json new file mode 100644 index 0000000..a5defb7 --- /dev/null +++ b/examples/file-policy-tests.json @@ -0,0 +1,9 @@ +{ + "schema_version": 1, + "name": "file-gateway-v1", + "cases": [ + {"name": "public read", "request": {"principal": "agent:demo", "action": "file.read", "resource": "workspace/public/guide.txt"}, "expect": {"allowed": true, "reason": "explicit_allow"}}, + {"name": "secret overlap denied", "request": {"principal": "agent:demo", "action": "file.read", "resource": "workspace/public/.env"}, "expect": {"allowed": false, "reason": "explicit_deny"}}, + {"name": "unapproved write denied", "request": {"principal": "agent:demo", "action": "file.write", "resource": "workspace/scratch/task.txt"}, "expect": {"allowed": false, "reason": "default_deny"}} + ] +} diff --git a/examples/pinned_gateway.py b/examples/pinned_gateway.py new file mode 100644 index 0000000..42b369f --- /dev/null +++ b/examples/pinned_gateway.py @@ -0,0 +1,76 @@ +"""Run an actual temporary workspace read through a pinned artifact and audited guard.""" + +from __future__ import annotations + +import json +import tempfile +from contextlib import suppress +from pathlib import Path + +from policy_engine import ( + ActionDenied, + PolicyEngine, + create_artifact, + guarded_call, + load_artifact, + load_policy, +) + + +def main() -> None: + policy = load_policy(Path(__file__).with_name("policy.json")) + suite = json.loads( + Path(__file__).with_name("file-policy-tests.json").read_text(encoding="utf-8") + ) + artifact = create_artifact( + policy, revision="files-r1", application="file-gateway-v1", suite=suite + ) + # This demo is its own trusted builder. Deployments must transport this pin separately. + trusted_pin = artifact.sha256 + with tempfile.TemporaryDirectory(prefix="samsarix-gateway-") as directory: + workspace = Path(directory) + artifact_path = workspace / "policy.artifact.json" + artifact_path.write_bytes(artifact.to_bytes()) + document = workspace / "guide.txt" + document.write_text("A real document read, authorized by Samsarix.", encoding="utf-8") + loaded = load_artifact( + artifact_path, expected_sha256=trusted_pin, application="file-gateway-v1" + ) + engine = PolicyEngine(loaded.policy) + events = [] + # Map a trusted logical resource to a known file; do not use request strings as paths. + allowed = { + "principal": "agent:demo", + "action": "file.read", + "resource": "workspace/public/guide.txt", + } + result = guarded_call( + engine, allowed, lambda: document.read_text(encoding="utf-8"), audit_sink=events.append + ) + denied = {**allowed, "resource": "secrets/.env"} + called = False + + def forbidden_operation(): + nonlocal called + called = True + raise AssertionError("secret operation should not execute") + + with suppress(ActionDenied): + guarded_call(engine, denied, forbidden_operation, audit_sink=events.append) + assert not called + print( + json.dumps( + { + "revision": loaded.revision, + "artifact_sha256": loaded.sha256, + "result": result, + "denied_operation_executed": called, + "audit": [event.to_dict() for event in events], + }, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/policy_engine/__init__.py b/policy_engine/__init__.py index 3ac96db..bd94fcd 100644 --- a/policy_engine/__init__.py +++ b/policy_engine/__init__.py @@ -1,8 +1,17 @@ """Samsarix Policy Engine public API.""" +from .artifacts import ( + ArtifactTestEvidence, + PolicyArtifact, + create_artifact, + load_artifact, + parse_artifact, +) from .batching import BatchDecision, BatchRequest, evaluate_batch, load_batch, parse_batch +from .enforcement import ActionDenied, AuditDeliveryError, AuditEvent, guarded_call from .engine import PolicyEngine, decide, wildcard_match from .errors import ( + ArtifactValidationError, BatchValidationError, DocumentLoadError, PolicyEngineError, @@ -28,6 +37,11 @@ __version__ = "0.1.0" __all__ = [ + "ActionDenied", + "ArtifactTestEvidence", + "ArtifactValidationError", + "AuditDeliveryError", + "AuditEvent", "BatchDecision", "BatchRequest", "BatchValidationError", @@ -35,6 +49,7 @@ "DocumentLoadError", "Effect", "Policy", + "PolicyArtifact", "PolicyEngine", "PolicyEngineError", "PolicyTestCase", @@ -49,13 +64,17 @@ "TestSuiteValidationError", "ValidationError", "__version__", + "create_artifact", "decide", "evaluate_batch", + "guarded_call", + "load_artifact", "load_batch", "load_policy", "load_request", "load_request_bytes", "load_test_suite", + "parse_artifact", "parse_batch", "parse_policy", "parse_request", diff --git a/policy_engine/artifacts.py b/policy_engine/artifacts.py new file mode 100644 index 0000000..3f79b5a --- /dev/null +++ b/policy_engine/artifacts.py @@ -0,0 +1,194 @@ +"""Deterministic policy artifacts for pinned, offline deployment (not signatures).""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import re +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from .engine import PolicyEngine, _policy_document +from .errors import ArtifactValidationError +from .loader import _load_json_file +from .models import Policy +from .testing import MAX_TEST_CASES, MAX_TEST_SUITE_BYTES, parse_test_suite, run_test_suite + +MAX_ARTIFACT_BYTES = 2_097_152 +CANONICALIZATION = "samsarix-json-v1" +_IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") +_SHA256 = re.compile(r"[a-f0-9]{64}") +_FIELDS = {"schema_version", "canonicalization", "revision", "application", "policy", "tests"} + + +def _check_identifier(value: object, label: str) -> None: + if not isinstance(value, str) or not _IDENTIFIER.fullmatch(value): + raise ArtifactValidationError([f"{label} must be a 1-128 character identifier"]) + + +def _check_digest(value: object) -> None: + if not isinstance(value, str) or not _SHA256.fullmatch(value): + raise ArtifactValidationError(["sha256 must be 64 lowercase hexadecimal characters"]) + + +def _encode(value: Any, *, limit: int = MAX_ARTIFACT_BYTES) -> bytes: + """Enforce a serialized byte budget and reject non-JSON values.""" + result = bytearray() + encoder = json.JSONEncoder( + ensure_ascii=True, sort_keys=True, separators=(",", ":"), allow_nan=False + ) + try: + for chunk in encoder.iterencode(value): + result.extend(chunk.encode("ascii")) + if len(result) > limit: + raise ArtifactValidationError([f"canonical JSON exceeds {limit} bytes"]) + except (TypeError, ValueError, RecursionError) as exc: + raise ArtifactValidationError(["value cannot be represented as canonical JSON"]) from exc + return bytes(result) + + +@dataclass(frozen=True, slots=True) +class ArtifactTestEvidence: + """Builder-reported passing suite identity; not independent test attestation.""" + + suite_name: str + suite_sha256: str + case_count: int + + def __post_init__(self) -> None: + if ( + not isinstance(self.suite_name, str) + or not self.suite_name + or len(self.suite_name) > 128 + or any(ord(c) < 32 for c in self.suite_name) + ): + raise ArtifactValidationError(["tests.suite_name must be a non-empty bounded string"]) + _check_digest(self.suite_sha256) + if type(self.case_count) is not int or not 1 <= self.case_count <= MAX_TEST_CASES: + raise ArtifactValidationError(["tests.case_count must be an integer from 1 to 1000"]) + + def to_dict(self) -> dict[str, Any]: + """Return evidence without request contexts or test names.""" + return { + "suite_name": self.suite_name, + "suite_sha256": self.suite_sha256, + "case_count": self.case_count, + } + + +@dataclass(frozen=True, slots=True) +class PolicyArtifact: + """A validated immutable policy, application contract, revision, and optional evidence.""" + + policy: Policy + revision: str + application: str + tests: ArtifactTestEvidence | None = None + + def __post_init__(self) -> None: + _check_identifier(self.revision, "revision") + _check_identifier(self.application, "application") + if not isinstance(self.policy, (Policy, Mapping)): + raise ArtifactValidationError(["policy must be a Policy or mapping"]) + if self.tests is not None and not isinstance(self.tests, ArtifactTestEvidence): + raise ArtifactValidationError(["tests must be ArtifactTestEvidence or None"]) + object.__setattr__(self, "policy", PolicyEngine(self.policy).policy) + self.to_bytes() # Every constructible artifact must fit the loader's size limit. + + def _payload(self) -> dict[str, Any]: + return { + "schema_version": 1, + "canonicalization": CANONICALIZATION, + "revision": self.revision, + "application": self.application, + "policy": _policy_document(self.policy), + "tests": self.tests.to_dict() if self.tests else None, + } + + @property + def sha256(self) -> str: + """Full digest of all manifest fields, excluding the digest field itself.""" + return hashlib.sha256(_encode(self._payload())).hexdigest() + + def to_dict(self) -> dict[str, Any]: + """Return an independently owned JSON-serializable artifact.""" + return {**self._payload(), "sha256": self.sha256} + + def to_bytes(self) -> bytes: + """Return canonical ASCII JSON bytes; no newline or platform-specific encoding.""" + return _encode(self.to_dict()) + + +def create_artifact( + policy: Policy | Mapping[str, Any], + *, + revision: str, + application: str, + suite: Mapping[str, Any] | None = None, +) -> PolicyArtifact: + """Build an artifact; when a suite is supplied, require every expectation to pass.""" + engine = PolicyEngine(policy) + evidence = None + if suite is not None: + if not isinstance(suite, Mapping): + raise ArtifactValidationError(["suite must be a mapping"]) + # Snapshot exactly the supplied JSON; formatting/key order are immaterial to this hash. + suite_bytes = _encode(dict(suite), limit=MAX_TEST_SUITE_BYTES) + parsed = parse_test_suite(json.loads(suite_bytes)) + report = run_test_suite(engine, parsed) + if not report.passed: + raise ArtifactValidationError([f"policy suite has {report.failed_count} failed cases"]) + evidence = ArtifactTestEvidence( + parsed.name, hashlib.sha256(suite_bytes).hexdigest(), report.total + ) + return PolicyArtifact(engine.policy, revision, application, evidence) + + +def parse_artifact(data: object) -> PolicyArtifact: + """Check internal integrity only. Use load_artifact with trusted pins for deployment.""" + if not isinstance(data, Mapping) or set(data) != _FIELDS | {"sha256"}: + raise ArtifactValidationError( + ["artifact must contain exactly the documented manifest fields"] + ) + if type(data["schema_version"]) is not int or data["schema_version"] != 1: + raise ArtifactValidationError(["artifact.schema_version must be integer 1"]) + if data["canonicalization"] != CANONICALIZATION: + raise ArtifactValidationError(["unsupported artifact canonicalization"]) + _check_digest(data["sha256"]) + raw_tests = data["tests"] + tests = None + if raw_tests is not None: + if not isinstance(raw_tests, Mapping) or set(raw_tests) != { + "suite_name", + "suite_sha256", + "case_count", + }: + raise ArtifactValidationError( + ["tests must contain exactly suite_name, suite_sha256, case_count"] + ) + tests = ArtifactTestEvidence( + raw_tests["suite_name"], raw_tests["suite_sha256"], raw_tests["case_count"] + ) + if not isinstance(data["policy"], Mapping): + raise ArtifactValidationError(["artifact.policy must be an object"]) + artifact = PolicyArtifact( + PolicyEngine(data["policy"]).policy, data["revision"], data["application"], tests + ) + if not hmac.compare_digest(artifact.sha256, data["sha256"]): + raise ArtifactValidationError(["artifact integrity check failed"]) + return artifact + + +def load_artifact(path: str | Path, *, expected_sha256: str, application: str) -> PolicyArtifact: + """Load for deployment using digest and application pins from trusted configuration.""" + _check_digest(expected_sha256) + _check_identifier(application, "application") + artifact = parse_artifact(_load_json_file(path, max_bytes=MAX_ARTIFACT_BYTES)) + if not hmac.compare_digest(artifact.sha256, expected_sha256): + raise ArtifactValidationError(["artifact does not match trusted sha256 pin"]) + if artifact.application != application: + raise ArtifactValidationError(["artifact application does not match deployment contract"]) + return artifact diff --git a/policy_engine/batching.py b/policy_engine/batching.py index d0b9bd9..0d7d098 100644 --- a/policy_engine/batching.py +++ b/policy_engine/batching.py @@ -88,7 +88,7 @@ def parse_batch(data: object) -> BatchRequest: if not isinstance(data, Mapping): raise BatchValidationError(["batch must be an object"]) issues: list[str] = [] - unknown = sorted(set(data) - {"schema_version", "requests"}) + unknown = sorted(str(key) for key in set(data) - {"schema_version", "requests"}) issues.extend(f"batch contains unknown field {field!r}" for field in unknown[:MAX_BATCH_ISSUES]) schema_version = data.get("schema_version") if schema_version != 1 or isinstance(schema_version, bool): @@ -104,6 +104,8 @@ def parse_batch(data: object) -> BatchRequest: requests: list[Request] = [] seen_ids: set[str] = set() for index, raw_request in enumerate(raw_requests[:MAX_BATCH_REQUESTS]): + if len(issues) >= MAX_BATCH_ISSUES: + break label = f"batch.requests[{index}]" if not isinstance(raw_request, Mapping): issues.append(f"{label} must be an object") diff --git a/policy_engine/cli.py b/policy_engine/cli.py index f016c3c..023357d 100644 --- a/policy_engine/cli.py +++ b/policy_engine/cli.py @@ -6,14 +6,22 @@ import json import sys from collections.abc import Sequence +from pathlib import Path from typing import Any, Never from . import __version__ +from .artifacts import create_artifact, load_artifact from .batching import evaluate_batch, load_batch from .engine import PolicyEngine from .errors import DocumentLoadError, ValidationError -from .loader import MAX_REQUEST_BYTES, load_policy, load_request, load_request_bytes -from .testing import load_test_suite, run_test_suite +from .loader import ( + MAX_REQUEST_BYTES, + _load_json_file, + load_policy, + load_request, + load_request_bytes, +) +from .testing import MAX_TEST_SUITE_BYTES, load_test_suite, run_test_suite EXIT_ALLOWED = 0 EXIT_TEST_FAILED = 1 @@ -46,7 +54,13 @@ def _parser() -> argparse.ArgumentParser: validate.add_argument("--pretty", action="store_true", help="indent JSON output") check = subparsers.add_parser("check", help="evaluate one action request") - check.add_argument("--policy", "-p", required=True, help="path to a JSON policy") + source = check.add_mutually_exclusive_group(required=True) + source.add_argument("--policy", "-p", help="path to a JSON policy") + source.add_argument("--artifact", help="path to a pinned policy artifact") + check.add_argument("--sha256", help="trusted full artifact digest (required with --artifact)") + check.add_argument( + "--application", help="expected application contract (required with --artifact)" + ) check.add_argument( "--request", "-r", required=True, help="path to a JSON request, or - to read stdin" ) @@ -62,6 +76,22 @@ def _parser() -> argparse.ArgumentParser: batch.add_argument("--batch", "-b", required=True, help="path to a JSON batch document") batch.add_argument("--explain", action="store_true", help="include per-rule match details") batch.add_argument("--pretty", action="store_true", help="indent JSON output") + + pack = subparsers.add_parser("pack", help="create a deterministic, unsigned policy artifact") + pack.add_argument("--policy", "-p", required=True) + pack.add_argument("--revision", required=True) + pack.add_argument("--application", required=True) + pack.add_argument("--suite", help="require this JSON suite to pass before packaging") + pack.add_argument("--output", required=True, help="new artifact file (never overwrites)") + pack.add_argument("--pretty", action="store_true") + + verify = subparsers.add_parser( + "verify-artifact", help="verify trusted artifact and application pins" + ) + verify.add_argument("--artifact", required=True) + verify.add_argument("--sha256", required=True) + verify.add_argument("--application", required=True) + verify.add_argument("--pretty", action="store_true") return parser @@ -101,9 +131,60 @@ def _error(exc: Exception, *, pretty: bool) -> int: def main(argv: Sequence[str] | None = None) -> int: """Run the CLI and return a process exit code.""" - args = _parser().parse_args(argv) + parser = _parser() + args = parser.parse_args(argv) + if args.command == "check": + if args.artifact and (not args.sha256 or not args.application): + parser.error( + "--artifact requires --sha256 and --application from trusted configuration" + ) + if args.policy and (args.sha256 or args.application): + parser.error("--sha256 and --application require --artifact") pretty = bool(args.pretty) try: + if args.command == "pack": + suite = ( + _load_json_file(args.suite, max_bytes=MAX_TEST_SUITE_BYTES) if args.suite else None + ) + artifact = create_artifact( + load_policy(args.policy), + revision=args.revision, + application=args.application, + suite=suite, + ) + payload = artifact.to_bytes() + try: + with Path(args.output).open("xb") as handle: + handle.write(payload) + except OSError as exc: + raise DocumentLoadError(f"could not create artifact: {exc}") from exc + _write_json( + sys.stdout, + { + "sha256": artifact.sha256, + "revision": artifact.revision, + "application": artifact.application, + }, + pretty=pretty, + ) + return EXIT_ALLOWED + + if args.command == "verify-artifact": + artifact = load_artifact( + args.artifact, expected_sha256=args.sha256, application=args.application + ) + _write_json( + sys.stdout, + { + "valid": True, + "sha256": artifact.sha256, + "revision": artifact.revision, + "application": artifact.application, + }, + pretty=pretty, + ) + return EXIT_ALLOWED + if args.command == "validate": policy = load_policy(args.policy) engine = PolicyEngine(policy) @@ -121,7 +202,13 @@ def main(argv: Sequence[str] | None = None) -> int: ) return EXIT_ALLOWED - policy = load_policy(args.policy) + policy = ( + load_artifact( + args.artifact, expected_sha256=args.sha256, application=args.application + ).policy + if args.command == "check" and args.artifact + else load_policy(args.policy) + ) engine = PolicyEngine(policy) if args.command == "test": report = run_test_suite(engine, load_test_suite(args.suite)) diff --git a/policy_engine/enforcement.py b/policy_engine/enforcement.py new file mode 100644 index 0000000..e2968bf --- /dev/null +++ b/policy_engine/enforcement.py @@ -0,0 +1,77 @@ +"""Synchronous action-boundary enforcement and opt-in, data-minimized decision audit.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from typing import Any, TypeVar + +from .engine import PolicyEngine +from .errors import PolicyEngineError +from .models import Decision, Request + +T = TypeVar("T") + + +class ActionDenied(PolicyEngineError, PermissionError): + """The operation was not invoked because its policy decision denied access.""" + + def __init__(self, decision: Decision): + self.decision = decision + super().__init__(decision.reason) + + +class AuditDeliveryError(PolicyEngineError): + """The caller's audit sink failed; no operation was invoked.""" + + +@dataclass(frozen=True, slots=True) +class AuditEvent: + """Decision-only record: no principal, action, resource, context, or rule names.""" + + allowed: bool + reason: str + policy_digest: str + request_id: str | None = None + + def to_dict(self) -> dict[str, Any]: + """Return the versioned event contract; not an operation-success receipt.""" + return { + "schema_version": 1, + "event": "policy_decision", + "allowed": self.allowed, + "reason": self.reason, + "policy_digest": self.policy_digest, + "request_id": self.request_id, + } + + +def guarded_call( + engine: PolicyEngine, + request: Request | Mapping[str, Any], + operation: Callable[[], T], + *, + audit_sink: Callable[[AuditEvent], None] | None = None, + include_request_id: bool = False, +) -> T: + """Authorize, optionally audit, then invoke once; deny or audit failure prevents invocation. + + The synchronous sink provides backpressure. Its timeout, persistence, and retention are owned + by the caller. Operation exceptions propagate without retries. Request IDs are omitted unless + explicitly opted in, since they can contain identifying information. + """ + decision = engine.evaluate(request) + if audit_sink is not None: + event = AuditEvent( + decision.allowed, + decision.reason, + decision.policy_digest, + decision.request_id if include_request_id else None, + ) + try: + audit_sink(event) + except Exception as exc: + raise AuditDeliveryError("audit sink failed; operation not invoked") from exc + if not decision.allowed: + raise ActionDenied(decision) + return operation() diff --git a/policy_engine/engine.py b/policy_engine/engine.py index fa7a46c..5841cdc 100644 --- a/policy_engine/engine.py +++ b/policy_engine/engine.py @@ -162,8 +162,11 @@ def _policy_document(policy: Policy) -> dict[str, Any]: def _digest(value: Any) -> str: - encoded = json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode() - return hashlib.sha256(encoded).hexdigest()[:32] + digest = hashlib.sha256() + encoder = json.JSONEncoder(ensure_ascii=False, separators=(",", ":"), sort_keys=True) + for chunk in encoder.iterencode(value): + digest.update(chunk.encode("utf-8")) + return digest.hexdigest()[:32] class PolicyEngine: diff --git a/policy_engine/errors.py b/policy_engine/errors.py index cb96ee3..7af2ba5 100644 --- a/policy_engine/errors.py +++ b/policy_engine/errors.py @@ -33,3 +33,7 @@ class TestSuiteValidationError(ValidationError): class BatchValidationError(ValidationError): """Raised when a batch request document is invalid.""" + + +class ArtifactValidationError(ValidationError): + """Raised when artifact structure, integrity, or deployment pins do not match.""" diff --git a/policy_engine/models.py b/policy_engine/models.py index 826ae4c..0b15f23 100644 --- a/policy_engine/models.py +++ b/policy_engine/models.py @@ -96,7 +96,22 @@ class Request: request_id: str | None = None def __post_init__(self) -> None: - object.__setattr__(self, "context", _freeze_json(dict(self.context))) + from .validation import _request_fields + + principal, action, resource, context, request_id = _request_fields( + { + "principal": self.principal, + "action": self.action, + "resource": self.resource, + "context": self.context, + "request_id": self.request_id, + } + ) + object.__setattr__(self, "principal", principal) + object.__setattr__(self, "action", action) + object.__setattr__(self, "resource", resource) + object.__setattr__(self, "request_id", request_id) + object.__setattr__(self, "context", _freeze_json(context)) @dataclass(frozen=True, slots=True) diff --git a/policy_engine/schemas/__init__.py b/policy_engine/schemas/__init__.py index 7fb3203..6aa0856 100644 --- a/policy_engine/schemas/__init__.py +++ b/policy_engine/schemas/__init__.py @@ -1 +1,57 @@ -"""Bundled JSON schemas for editor and integration tooling.""" +"""Packaged JSON Schema access without network resolution or optional dependencies.""" + +from __future__ import annotations + +import json +from importlib.resources import files +from typing import Any + +SCHEMA_NAMES = ( + "policy.schema.json", + "request.schema.json", + "decision.schema.json", + "test-suite.schema.json", + "batch.schema.json", + "artifact.schema.json", +) + + +def schema_document(name: str) -> dict[str, Any]: + """Return a self-contained Draft 2020-12 document with all references bundled. + + Pass the result to your preferred validator. No URL is fetched. Unknown schema names or + external references fail rather than falling back to network retrieval. + """ + if name not in SCHEMA_NAMES: + raise ValueError("unknown packaged schema name") + documents = { + key: json.loads(files(__package__).joinpath(key).read_text(encoding="utf-8")) + for key in SCHEMA_NAMES + } + + def rewrite(value: Any, current: str) -> Any: + prefix = "#" if current == name else f"#/$defs/{current}" + if isinstance(value, list): + return [rewrite(item, current) for item in value] + if not isinstance(value, dict): + return value + result = {} + for key, item in value.items(): + if key == "$id": + continue + if key == "$ref": + if item.startswith("#"): + result[key] = prefix + item[1:] + else: + target = item.rsplit("/", 1)[-1] + if target not in documents or item not in (target, documents[target]["$id"]): + raise ValueError("unrecognized external schema reference") + result[key] = "#" if target == name else f"#/$defs/{target}" + else: + result[key] = rewrite(item, current) + return result + + root: dict[str, Any] = rewrite(documents[name], name) + definitions = root.setdefault("$defs", {}) + definitions.update({key: rewrite(doc, key) for key, doc in documents.items() if key != name}) + return root diff --git a/policy_engine/schemas/artifact.schema.json b/policy_engine/schemas/artifact.schema.json new file mode 100644 index 0000000..ef570fa --- /dev/null +++ b/policy_engine/schemas/artifact.schema.json @@ -0,0 +1,34 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://schemas.samsarix.com/policy-engine/v1/artifact.schema.json", + "title": "Samsarix unsigned policy artifact", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "canonicalization", "revision", "application", "policy", "tests", "sha256"], + "properties": { + "schema_version": {"const": 1}, + "canonicalization": {"const": "samsarix-json-v1"}, + "revision": {"$ref": "#/$defs/identifier"}, + "application": {"$ref": "#/$defs/identifier"}, + "sha256": {"$ref": "#/$defs/digest"}, + "policy": {"$ref": "policy.schema.json"}, + "tests": { + "oneOf": [ + {"type": "null"}, + { + "type": "object", "additionalProperties": false, + "required": ["suite_name", "suite_sha256", "case_count"], + "properties": { + "suite_name": {"type": "string", "minLength": 1, "maxLength": 128}, + "suite_sha256": {"$ref": "#/$defs/digest"}, + "case_count": {"type": "integer", "minimum": 1, "maximum": 1000} + } + } + ] + } + }, + "$defs": { + "identifier": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"}, + "digest": {"type": "string", "pattern": "^[a-f0-9]{64}$"} + } +} diff --git a/policy_engine/validation.py b/policy_engine/validation.py index cdefd46..2539d48 100644 --- a/policy_engine/validation.py +++ b/policy_engine/validation.py @@ -8,7 +8,7 @@ from typing import Any, cast from .errors import PolicyValidationError, RequestValidationError -from .models import Condition, ConditionValue, Effect, JsonValue, Operator, Policy, Request, Rule +from .models import Condition, ConditionValue, Effect, Operator, Policy, Request, Rule MAX_RULES = 512 MAX_PATTERN_ITEMS = 64 @@ -20,6 +20,7 @@ MAX_STRING_LENGTH = 16_384 MAX_IDENTIFIER_LENGTH = 128 MAX_PATTERN_LENGTH = 512 +MAX_INTEGER_BITS = 4096 _IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$") _CONTEXT_PATH = re.compile(r"^[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*){0,15}$") @@ -74,24 +75,34 @@ def visit(item: Any, depth: int, path: str) -> None: if item is None or isinstance(item, bool): return if isinstance(item, (int, float)): + if isinstance(item, int) and item.bit_length() > MAX_INTEGER_BITS: + issues.append(f"{path} exceeds {MAX_INTEGER_BITS} integer bits") if isinstance(item, float) and not math.isfinite(item): issues.append(f"{path} must be a finite number") return if isinstance(item, str): + if any(0xD800 <= ord(character) <= 0xDFFF for character in item): + issues.append(f"{path} contains an unpaired Unicode surrogate") if len(item) > MAX_STRING_LENGTH: issues.append(f"{path} exceeds {MAX_STRING_LENGTH} characters") return - if isinstance(item, list): + if isinstance(item, (list, tuple)): for index, child in enumerate(item): + if nodes_exceeded: + break visit(child, depth + 1, f"{path}[{index}]") return - if isinstance(item, dict): + if isinstance(item, Mapping): for key, child in item.items(): + if nodes_exceeded: + break if not isinstance(key, str): issues.append(f"{path} contains a non-string object key") continue if len(key) > MAX_IDENTIFIER_LENGTH: issues.append(f"{path} contains an overlong object key") + if any(0xD800 <= ord(character) <= 0xDFFF for character in key): + issues.append(f"{path} contains a Unicode surrogate in an object key") visit(child, depth + 1, f"{path}.{key}") return issues.append(f"{path} contains unsupported value type {type(item).__name__}") @@ -302,8 +313,8 @@ def parse_policy(data: Mapping[str, Any]) -> Policy: ) -def parse_request(data: Mapping[str, Any]) -> Request: - """Validate a mapping and return an immutable request.""" +def _request_fields(data: Mapping[str, Any]) -> tuple[str, str, str, Any, str | None]: + """Validate both parsed requests and directly constructed public values.""" document = dict(data) issues = _Issues() issues.extend(_validate_json_value(document, label="request")) @@ -316,7 +327,7 @@ def parse_request(data: Mapping[str, Any]) -> Request: issues.append(f"request.{field} exceeds {MAX_PATTERN_LENGTH} characters") context = document.get("context", {}) - if not isinstance(context, dict): + if not isinstance(context, Mapping): issues.append("request.context must be an object") context = {} @@ -332,10 +343,12 @@ def parse_request(data: Mapping[str, Any]) -> Request: if issues: raise RequestValidationError(issues.finalized()) - return Request( - principal=principal, - action=action, - resource=resource, - context=cast(dict[str, JsonValue], context), - request_id=request_id, - ) + return principal, action, resource, context, request_id + + +def parse_request(data: Mapping[str, Any]) -> Request: + """Validate a mapping and return an immutable request.""" + if not isinstance(data, Mapping): + raise RequestValidationError(["request must be an object"]) + principal, action, resource, context, request_id = _request_fields(data) + return Request(principal, action, resource, context, request_id) diff --git a/pyproject.toml b/pyproject.toml index 26cfdd5..fd5677c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,7 @@ dev = [ "jsonschema>=4.23,<5", "mypy>=1.15,<3", "pip-audit>=2.7,<3", + "pip>=26.2,<27", "pytest>=8,<10", "pytest-cov>=6,<8", "ruff>=0.11,<1", diff --git a/scripts/smoke_installed.py b/scripts/smoke_installed.py new file mode 100644 index 0000000..0edf8cf --- /dev/null +++ b/scripts/smoke_installed.py @@ -0,0 +1,158 @@ +"""Dependency-free wheel journey, run in isolated mode by verify_distribution.""" + +from __future__ import annotations + +import json +import subprocess +import sys +from importlib.resources import files +from pathlib import Path + +import policy_engine +from policy_engine import ( + ActionDenied, + PolicyEngine, + create_artifact, + evaluate_batch, + guarded_call, + load_artifact, + load_batch, + load_policy, + load_test_suite, + run_test_suite, +) +from policy_engine.schemas import SCHEMA_NAMES, schema_document + + +def main() -> None: + root = Path(sys.argv[1]).resolve() + assert not Path(policy_engine.__file__).resolve().is_relative_to(root / "policy_engine") + for name in SCHEMA_NAMES: + assert files("policy_engine.schemas").joinpath(name).is_file() + assert schema_document(name)["type"] == "object" + examples = root / "examples" + gateway = examples / "agent-tool-gateway" + engine = PolicyEngine(load_policy(examples / "policy.json")) + assert run_test_suite( + PolicyEngine(load_policy(gateway / "policy.json")), + load_test_suite(gateway / "policy-tests.json"), + ).passed + batch = load_batch(examples / "request.batch.json") + assert [d.allowed for d in evaluate_batch(engine, batch).decisions] == [True, False] + events = [] + assert ( + guarded_call(engine, batch.requests[0], lambda: "executed", audit_sink=events.append) + == "executed" + ) + try: + guarded_call( + engine, batch.requests[1], lambda: sys.exit("denial executed"), audit_sink=events.append + ) + except ActionDenied: + pass + else: + raise AssertionError("denial did not raise") + assert [event.allowed for event in events] == [True, False] + artifact = create_artifact(engine.policy, revision="smoke-r1", application="smoke-v1") + artifact_path = Path.cwd() / "artifact.json" + artifact_path.write_bytes(artifact.to_bytes()) + assert ( + load_artifact(artifact_path, expected_sha256=artifact.sha256, application="smoke-v1") + == artifact + ) + + def cli(arguments: list[str], code: int = 0) -> dict: + result = subprocess.run( + [sys.executable, "-I", "-m", "policy_engine", *arguments], + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == code, (arguments, result.stdout, result.stderr) + return json.loads(result.stdout if code in (0, 1, 3) else result.stderr) + + cli(["validate", str(examples / "policy.json")]) + cli( + ["check", "-p", str(examples / "policy.json"), "-r", str(examples / "request.allowed.json")] + ) + cli( + ["check", "-p", str(examples / "policy.json"), "-r", str(examples / "request.denied.json")], + 3, + ) + cli(["check"], 2) + assert ( + cli( + [ + "batch", + "-p", + str(examples / "policy.json"), + "-b", + str(examples / "request.batch.json"), + ] + )["count"] + == 2 + ) + assert ( + cli(["test", "-p", str(gateway / "policy.json"), "-s", str(gateway / "policy-tests.json")])[ + "total" + ] + == 7 + ) + packed = Path.cwd() / "tested-artifact.json" + summary = cli( + [ + "pack", + "-p", + str(gateway / "policy.json"), + "--revision", + "r1", + "--application", + "gateway-v1", + "--suite", + str(gateway / "policy-tests.json"), + "--output", + str(packed), + ] + ) + assert json.loads(packed.read_bytes())["tests"]["case_count"] == 7 + cli( + [ + "verify-artifact", + "--artifact", + str(packed), + "--sha256", + summary["sha256"], + "--application", + "gateway-v1", + ] + ) + cli( + [ + "verify-artifact", + "--artifact", + str(packed), + "--sha256", + "0" * 64, + "--application", + "gateway-v1", + ], + 2, + ) + assert cli( + [ + "check", + "--artifact", + str(artifact_path), + "--sha256", + artifact.sha256, + "--application", + "smoke-v1", + "-r", + str(examples / "request.allowed.json"), + ] + )["allowed"] + print("Installed check/test/batch/pack/verify-artifact and guarded audit journeys passed.") + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_distribution.py b/scripts/verify_distribution.py new file mode 100644 index 0000000..e19f9a1 --- /dev/null +++ b/scripts/verify_distribution.py @@ -0,0 +1,70 @@ +"""Inspect both distributions, then exercise the wheel from an isolated temporary environment.""" + +from __future__ import annotations + +import argparse +import subprocess +import sys +import tarfile +import tempfile +import venv +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SCHEMAS = {"policy", "request", "decision", "test-suite", "batch", "artifact"} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--dist", type=Path, default=ROOT / "dist") + args = parser.parse_args() + wheels = list(args.dist.glob("*.whl")) + sources = list(args.dist.glob("*.tar.gz")) + assert len(wheels) == len(sources) == 1, ( + "use a directory containing exactly one wheel and sdist" + ) + wheel = wheels[0].resolve() + with zipfile.ZipFile(wheel) as archive: + names = set(archive.namelist()) + assert all( + name.startswith("policy_engine/") or name.split("/")[0].endswith(".dist-info") + for name in names + ) + assert {f"policy_engine/schemas/{name}.schema.json" for name in SCHEMAS} <= names + assert "policy_engine/py.typed" in names + assert any(name.endswith("/licenses/LICENSE") for name in names) + with tarfile.open(sources[0], "r:gz") as archive: + names = {name.partition("/")[2] for name in archive.getnames()} + for directory in ("docs", "examples", "tests", "scripts"): + assert any(name.startswith(directory + "/") for name in names), directory + assert "requirements-dev.txt" in names + assert not any( + part in {".venv", ".git", "__pycache__", "helix_core"} + for name in names + for part in name.split("/") + ) + + with tempfile.TemporaryDirectory(prefix="samsarix-policy-wheel-") as directory: + workspace = Path(directory) + venv.EnvBuilder(with_pip=True).create(workspace / "venv") + executable = ( + workspace / "venv" / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") + ) + subprocess.run( + [str(executable), "-I", "-m", "pip", "install", "--no-deps", "--no-index", str(wheel)], + check=True, + cwd=workspace, + timeout=180, + ) + subprocess.run( + [str(executable), "-I", str(ROOT / "scripts" / "smoke_installed.py"), str(ROOT)], + check=True, + cwd=workspace, + timeout=180, + ) + print("Wheel inventory, sdist inventory, and isolated installed journeys passed.") + + +if __name__ == "__main__": + main() diff --git a/tests/test_artifacts.py b/tests/test_artifacts.py new file mode 100644 index 0000000..327d1f5 --- /dev/null +++ b/tests/test_artifacts.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +import copy +import hashlib +import json + +import pytest +from jsonschema import Draft202012Validator + +from policy_engine import ( + ArtifactTestEvidence, + ArtifactValidationError, + DocumentLoadError, + PolicyArtifact, + PolicyEngine, + create_artifact, + load_artifact, + parse_artifact, +) +from policy_engine.artifacts import MAX_ARTIFACT_BYTES, _encode +from policy_engine.schemas import SCHEMA_NAMES, schema_document + +POLICY = { + "schema_version": 1, + "id": "files", + "rules": [{"id": "read", "effect": "allow", "actions": ["read"], "resources": ["public:*"]}], +} +REQUEST = {"principal": "agent", "action": "read", "resource": "public:guide"} +SUITE = { + "schema_version": 1, + "name": "contract-v1", + "cases": [{"name": "public", "request": REQUEST, "expect": {"allowed": True}}], +} + + +def make_artifact(): + return create_artifact(POLICY, revision="r1", application="gateway-v1", suite=SUITE) + + +def test_canonical_golden_digest_across_supported_python_versions(): + artifact = create_artifact( + {"schema_version": 1, "id": "golden", "rules": []}, revision="r1", application="golden-v1" + ) + assert artifact.sha256 == "b2ff7aa55ace273e621e56edeb2dc476d1c4eb2a6602f2ada67a7aa34b889837" + + +def test_invalid_direct_artifact_arguments_are_structured(): + with pytest.raises(ArtifactValidationError, match="policy must"): + PolicyArtifact(None, "r1", "app") + with pytest.raises(ArtifactValidationError, match="tests must"): + PolicyArtifact(PolicyEngine(POLICY).policy, "r1", "app", {}) + with pytest.raises(ArtifactValidationError, match="suite must"): + create_artifact(POLICY, revision="r1", application="app", suite=[]) + + +def test_artifact_determinism_integrity_and_detachment(tmp_path): + source = copy.deepcopy(POLICY) + first = create_artifact(source, revision="r1", application="gateway-v1", suite=SUITE) + source["rules"].clear() + second = make_artifact() + assert first.to_bytes() == second.to_bytes() + document = first.to_dict() + digest = document.pop("sha256") + assert ( + digest + == hashlib.sha256( + json.dumps( + document, ensure_ascii=True, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode() + ).hexdigest() + ) + path = tmp_path / "policy.artifact.json" + path.write_bytes(first.to_bytes()) + loaded = load_artifact(path, expected_sha256=digest, application="gateway-v1") + assert loaded.tests.case_count == 1 + assert PolicyEngine(loaded.policy).evaluate(REQUEST).allowed + assert parse_artifact(json.loads(first.to_bytes())) == first + document["policy"]["rules"].clear() + assert len(first.policy.rules) == 1 + + +@pytest.mark.parametrize( + "key,value", + [ + ("revision", "r2"), + ("application", "other"), + ("schema_version", True), + ("canonicalization", "jcs"), + ("policy", []), + ("tests", {}), + ("sha256", "INVALID"), + ], +) +def test_artifact_rejects_tampered_fields(key, value): + document = make_artifact().to_dict() + document[key] = value + with pytest.raises(ArtifactValidationError): + parse_artifact(document) + + +@pytest.mark.parametrize("document", [None, [], {}, {"unexpected": 1}]) +def test_artifact_rejects_non_documents(document): + with pytest.raises(ArtifactValidationError): + parse_artifact(document) + + +def test_self_consistent_replacement_still_fails_trusted_pin(tmp_path): + original = make_artifact() + replacement = create_artifact(POLICY, revision="r2", application="gateway-v1") + path = tmp_path / "artifact.json" + path.write_bytes(replacement.to_bytes()) + with pytest.raises(ArtifactValidationError, match="trusted sha256"): + load_artifact(path, expected_sha256=original.sha256, application="gateway-v1") + with pytest.raises(ArtifactValidationError, match="application"): + load_artifact(path, expected_sha256=replacement.sha256, application="other") + with pytest.raises(ArtifactValidationError, match="64 lowercase"): + load_artifact(path, expected_sha256="bad", application="gateway-v1") + + +def test_failed_suite_cannot_produce_artifact(): + suite = copy.deepcopy(SUITE) + suite["cases"][0]["expect"]["allowed"] = False + with pytest.raises(ArtifactValidationError, match="failed cases"): + create_artifact(POLICY, revision="r1", application="gateway-v1", suite=suite) + + +@pytest.mark.parametrize( + "name,digest,count", + [("", "0" * 64, 1), ("test", "x", 1), ("test", "0" * 64, True), ("test", "0" * 64, 0)], +) +def test_evidence_validates_public_constructor(name, digest, count): + with pytest.raises(ArtifactValidationError): + ArtifactTestEvidence(name, digest, count) + + +def test_artifact_limits_and_serialization_errors(tmp_path): + path = tmp_path / "oversized.json" + path.write_bytes(b" " * (MAX_ARTIFACT_BYTES + 1)) + with pytest.raises(DocumentLoadError, match="exceeds"): + load_artifact(path, expected_sha256="0" * 64, application="gateway-v1") + for value, limit in [("long", 2), (float("nan"), 10), (object(), 10)]: + with pytest.raises(ArtifactValidationError): + _encode(value, limit=limit) + with pytest.raises(ArtifactValidationError, match="identifier"): + create_artifact(POLICY, revision="../r1", application="gateway-v1") + + +def test_schema_bundles_are_offline_and_validate_artifacts(): + for name in SCHEMA_NAMES: + schema = schema_document(name) + Draft202012Validator.check_schema(schema) + + def check_refs(value): + if isinstance(value, dict): + if "$ref" in value: + assert value["$ref"].startswith("#") + for child in value.values(): + check_refs(child) + elif isinstance(value, list): + for child in value: + check_refs(child) + + check_refs(schema) + validator = Draft202012Validator(schema_document("artifact.schema.json")) + validator.validate(make_artifact().to_dict()) + bad = make_artifact().to_dict() + bad["policy"]["rules"][0]["effect"] = "invalid" + assert not validator.is_valid(bad) + with pytest.raises(ValueError, match="unknown"): + schema_document("../../anything") diff --git a/tests/test_cli.py b/tests/test_cli.py index 9053a3e..6608ef3 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -131,3 +131,60 @@ def test_policy_test_command_reports_passes_and_assertion_failures(tmp_path, cap report = json.loads(capsys.readouterr().out) assert report["passed"] is False assert report["failed_count"] == 1 + + +def test_artifact_cli_journey_and_no_overwrite(tmp_path, capsys): + policy, allowed, denied = write_documents(tmp_path) + artifact = tmp_path / "artifact.json" + pack_args = [ + "pack", + "-p", + str(policy), + "--revision", + "r1", + "--application", + "cli-v1", + "--output", + str(artifact), + ] + assert main(pack_args) == EXIT_ALLOWED + digest = json.loads(capsys.readouterr().out)["sha256"] + original = artifact.read_bytes() + pins = ["--artifact", str(artifact), "--sha256", digest, "--application", "cli-v1"] + assert main(["verify-artifact", *pins, "--pretty"]) == EXIT_ALLOWED + assert json.loads(capsys.readouterr().out)["valid"] + assert main(["check", *pins, "-r", str(allowed)]) == EXIT_ALLOWED + assert json.loads(capsys.readouterr().out)["allowed"] + assert main(["check", *pins, "-r", str(denied)]) == EXIT_DENIED + assert not json.loads(capsys.readouterr().out)["allowed"] + assert main(pack_args) == EXIT_INVALID + assert capsys.readouterr().out == "" + assert artifact.read_bytes() == original + pins[3] = "0" * 64 + assert main(["verify-artifact", *pins]) == EXIT_INVALID + assert capsys.readouterr().out == "" + + +@pytest.mark.parametrize("source", [["--artifact", "p"], ["--policy", "p", "--sha256", "0" * 64]]) +def test_artifact_check_requires_complete_pins(source, capsys): + with pytest.raises(SystemExit) as error: + main(["check", *source, "-r", "r"]) + assert error.value.code == EXIT_INVALID + assert capsys.readouterr().out == "" + + +def test_cli_batch_decisions_and_validation_atomicity(tmp_path, capsys): + policy, allowed, _ = write_documents(tmp_path) + request = json.loads(allowed.read_text()) + request["request_id"] = "one" + batch = tmp_path / "batch.json" + batch.write_text(json.dumps({"schema_version": 1, "requests": [request]})) + args = ["batch", "-p", str(policy), "-b", str(batch), "--explain"] + assert main(args) == EXIT_ALLOWED + output = json.loads(capsys.readouterr().out) + assert output["decisions"][0]["evaluations"] + batch.write_text(json.dumps({"schema_version": 1, "requests": [request, {}]})) + assert main(args) == EXIT_INVALID + captured = capsys.readouterr() + assert captured.out == "" + assert "batch.requests[1]" in captured.err diff --git a/tests/test_enforcement.py b/tests/test_enforcement.py new file mode 100644 index 0000000..f968b55 --- /dev/null +++ b/tests/test_enforcement.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +import pytest + +from policy_engine import ActionDenied, AuditDeliveryError, PolicyEngine, Request, guarded_call +from policy_engine.errors import RequestValidationError + + +def test_guarded_call_enforces_and_audits_in_order(): + engine = PolicyEngine( + {"schema_version": 1, "id": "secret-policy", "default": "allow", "rules": []} + ) + request = Request( + "private-user", "private-action", "private-resource", {"secret": "token"}, "user-1" + ) + events = [] + + def sink(event): + events.append(event.to_dict()) + + def operation(): + assert len(events) == 1 + return 42 + + assert guarded_call(engine, request, operation, audit_sink=sink) == 42 + assert events[0]["request_id"] is None + assert all( + secret not in str(events) for secret in ("private", "token", "secret-policy", "user-1") + ) + assert guarded_call(engine, request, lambda: 3, audit_sink=sink, include_request_id=True) == 3 + assert events[-1]["request_id"] == "user-1" + assert guarded_call(engine, request, lambda: 4) == 4 + + +@pytest.mark.parametrize("allow", [True, False]) +def test_audit_failure_prevents_any_operation(allow): + engine = PolicyEngine( + {"schema_version": 1, "id": "p", "default": "allow" if allow else "deny", "rules": []} + ) + calls = [] + + def broken_sink(event): + raise OSError("disk full") + + with pytest.raises(AuditDeliveryError): + guarded_call( + engine, + {"principal": "u", "action": "a", "resource": "r"}, + lambda: calls.append(1), + audit_sink=broken_sink, + ) + assert calls == [] + + +def test_denial_and_operation_failure_do_not_retry(): + engine = PolicyEngine({"schema_version": 1, "id": "p", "rules": []}) + calls = [] + events = [] + request = {"principal": "u", "action": "a", "resource": "r"} + with pytest.raises(ActionDenied) as error: + guarded_call(engine, request, lambda: calls.append(1), audit_sink=events.append) + assert error.value.decision.reason == "default_deny" + assert not events[0].allowed + assert calls == [] + allow = PolicyEngine({"schema_version": 1, "id": "p", "default": "allow", "rules": []}) + + def broken_operation(): + calls.append(1) + raise RuntimeError("operation failed") + + with pytest.raises(RuntimeError, match="operation failed"): + guarded_call(allow, request, broken_operation) + assert calls == [1] + + +def test_direct_request_constructor_cannot_skip_validation(): + for fields in [ + dict(principal="", action="a", resource="r", context={}), + dict(principal="u", action="a", resource="r", context={"x": float("nan")}), + dict(principal="u", action="a", resource="r", context={}, request_id=[]), + ]: + with pytest.raises(RequestValidationError): + Request(**fields) + cyclic = {} + cyclic["self"] = cyclic + with pytest.raises(RequestValidationError): + Request("u", "a", "r", cyclic) + + +@pytest.mark.parametrize("context", [{"x": "\ud800"}, {"\udfff": 1}, {"x": 1 << 4096}]) +def test_unserializable_request_values_fail_with_structured_error(context): + with pytest.raises(RequestValidationError): + Request("u", "a", "r", context) diff --git a/tests/test_example_consumer.py b/tests/test_example_consumer.py index 7c01b62..190a237 100644 --- a/tests/test_example_consumer.py +++ b/tests/test_example_consumer.py @@ -45,3 +45,14 @@ def operation() -> str: assert allowed["executed"] is True assert allowed["result"] == "executed" assert called is True + + +def test_pinned_gateway_real_read_and_denied_callback(capsys): + import json + + example = runpy.run_path(str(ROOT / "examples" / "pinned_gateway.py")) + example["main"]() + report = json.loads(capsys.readouterr().out) + assert report["result"].startswith("A real document read") + assert not report["denied_operation_executed"] + assert [event["allowed"] for event in report["audit"]] == [True, False] From 28ce9db0ee740c5dc4f4f473aa59c3b33cd845cb Mon Sep 17 00:00:00 2001 From: Deathcharge Date: Mon, 31 Aug 2026 13:15:14 -0400 Subject: [PATCH 2/2] Clarify cross-platform release setup commands --- README.md | 3 +-- docs/RELEASING.md | 6 ++++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6179155..298bca5 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/RELEASING.md b/docs/RELEASING.md index f6e6ea3..beb3317 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -23,6 +23,12 @@ Run the complete gate from a clean checkout: ```bash python -m venv .venv +``` + +Activate it with `source .venv/bin/activate` on macOS/Linux or +`.venv\Scripts\Activate.ps1` in Windows PowerShell. Then run these commands using that environment: + +```bash python -m pip install -r requirements-dev.txt python -m ruff format --check . python -m ruff check .