diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 4a2a3f5..47d4646 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -82,12 +82,24 @@ jobs: - name: Validate wcp_retry_idempotency.py syntax run: python -m py_compile examples/wcp_retry_idempotency.py + - name: Validate typed_policies.py syntax + run: python -m py_compile examples/typed_policies.py + + - name: Validate pep_handshake.py syntax + run: python -m py_compile examples/pep_handshake.py + - name: Import quickstart run: python -c "from examples.quickstart import main; print('quickstart.py imports successfully')" - name: Import gateway_mode run: python -c "from examples.gateway_mode import main, blocked_example; print('gateway_mode.py imports successfully')" + - name: Import typed_policies + run: python -c "from examples.typed_policies import main; print('typed_policies.py imports successfully')" + + - name: Import pep_handshake + run: python -c "from examples.pep_handshake import main; print('pep_handshake.py imports successfully')" + # Integration tests run against a live community stack spun up via docker-compose. # Runs on main merges, scheduled, and manual dispatch. Skipped on PRs to keep # latency reasonable — PR-level live coverage is added in QF-13. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d9939d..42e98dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,13 +11,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +The first Python SDK release carrying these entries sends the PEP capability handshake, which a platform reads from v10.4.0, and reaches `/api/v1/typed-policies`, which needs a v11.0.0 platform. Upgrade the SDK before the platform: from v11.0.0, `decide` refuses a client that does not declare redaction, including one that sends no handshake, wherever the organization has a redact override. Against an older platform this release works unchanged. + ### Added - **v11 decision provenance on every governed response.** From a v11.0.0 platform, `DecideResponse`, the gateway pre-check result (`PolicyApprovalResult`), `ClientResponse` (`/api/request`), `MCPCheckOutputResponse` and `ConnectorResponse` carry `engine`, `subject_type`, `policy_bundle` and `legacy_validators` (a list of `LegacyValidatorAction`), through a shared `DecisionProvenance` base. `DecideResponse` also carries `policy_identities` (each matched policy named, as `PolicyIdentity`), `policy_packs` and `document_version`, and the pre-check result carries `decision_id` and `verdict`. Every new field is `None` on an older platform. - **`LegacyPolicyWriteFrozenError`.** A v11.0.0 platform refuses writes to the static- and dynamic-policy routes with `409 LEGACY_POLICY_WRITE_FROZEN`. The SDK raises this typed error, a subclass of `AxonFlowError`, carrying the platform's message, which names the typed policy route. Every other 409 is handled as before. - **`PlatformRouteDeprecationWarning`.** When the platform stamps the route a call used as deprecated (`X-AxonFlow-Removed-In`, or the RFC 9745 `Deprecation` header), the SDK issues this `DeprecationWarning`, naming the successor route from `Link: rel="successor-version"` and the removal release. A v11.0.0 platform stamps the legacy static-policy, dynamic-policy and policy-simulation routes. Each route is reported once per client, keyed by method and path without the query string, and a client derived through `as_user` shares that memory, as the TypeScript and Go SDKs do. -- **The PEP capability handshake.** A v11 platform lets an enforcement point declare, on each call, the exact obligation types and versions it can discharge, in the `X-Axonflow-PEP-Handshake` header. `PEPHandshake` builds the declaration (`pep_id`, `audience` and the exact `PEPCapability` set, which may be empty), validates it by the platform's own rules, raising `PEPHandshakeError` with the JSON Pointer of the member at fault, and encodes it once. Pass it as `AxonFlow(pep_handshake=...)` to present it on every call to a plane that reads it: `decide`, `evaluate`, `evaluate_all`, `mcp_check_input`, `mcp_check_output`, `check_tool_input`, `check_tool_output`, `get_policy_approved_context`, `pre_check`, and the engine round-trip of `fulfill_request` and `decide_and_fulfill`. Pass it to one of those methods as `pep_handshake=` to declare it for that call only, in place of the client's. It is never sent to `proxy_llm_call` (`/api/request`), the OpenAI-compatible route or any other route, none of which reads it, and a client given no declaration sends none. On an Enterprise deployment, an allow carrying a mandatory obligation the declared set cannot discharge becomes a deny. A call that passes `pep_handshake=` and also sets the header in `extra_headers` is refused. +- **The PEP capability handshake.** A v11 platform lets an enforcement point declare, on each call, the exact obligation types and versions it can discharge, in the `X-Axonflow-PEP-Handshake` header. `PEPHandshake` builds the declaration (`pep_id`, `audience` and the exact `PEPCapability` set, which may be empty), validates it by the platform's own rules, raising `PEPHandshakeError` with the JSON Pointer of the member at fault, and encodes it once. Pass it as `AxonFlow(pep_handshake=...)` to present it on every call to a plane that reads it: `decide`, `evaluate`, `evaluate_all`, `mcp_check_input`, `mcp_check_output`, `check_tool_input`, `check_tool_output`, `get_policy_approved_context`, `pre_check`, and the engine round-trip of `fulfill_request` and `decide_and_fulfill`. Pass it to one of those methods as `pep_handshake=` to declare it for that call only, in place of the client's. It is never sent to `proxy_llm_call` (`/api/request`), the OpenAI-compatible route or any other route, none of which reads it, and a client given no declaration sends none. On an Enterprise deployment, an allow carrying a mandatory obligation the declared set cannot discharge becomes a deny. From v11.0.0, in every edition, `decide` under an organization's redact override refuses a client that does not declare redaction, including one that sends no handshake. A call that passes `pep_handshake=` and also sets the header in `extra_headers` is refused. - **Typed policy authoring (`client.typed_policies`).** The v11 successor to the legacy policy routes: `edition()`, `validate()`, `publish()`, `activate()`, `active()` and `system()` over the six routes the agent proxies under `/api/v1/typed-policies`, with typed results and `TypedPolicyRefusal` carrying the status, the platform's `reason`, any findings and `retry_after`. `activate()` promotes a published digest; rollback and withdraw are customer portal operations that the agent does not proxy, so the SDK has no method for them. The synchronous client has the same namespace. +- **Examples for the v11.0.0 platform.** `examples/typed_policies.py` authors policy as a typed document (it publishes and activates only when asked), and `examples/pep_handshake.py` declares an enforcement point's capabilities for the client and for one call. Both exit non-zero when a step fails, and CI compiles and imports them. The README gains a "v11.0.0 platform" section naming what each part needs from the platform, and its feature overview no longer shows `list_policies()`, which this SDK does not have, or a dynamic-policy write, which a v11.0.0 platform refuses. ### Deprecated diff --git a/README.md b/README.md index 461af3c..193f675 100644 --- a/README.md +++ b/README.md @@ -337,9 +337,21 @@ The tri-state applies to attribute **data**, not to the structural members (`sub The wire types are **generated** from the platform's canonical contract artifact (`scripts/gen_authzen_types.py`); CI fails if the committed module is not what the artifact produces. Runnable example: [`examples/authzen_evaluation.py`](examples/authzen_evaluation.py). Migration notes: [`docs/AUTHZEN_MIGRATION_DRAFT.md`](docs/AUTHZEN_MIGRATION_DRAFT.md). +### v11.0.0 platform + +Against a v11.0.0 platform this SDK reaches the new decision plane. Against an older platform the calls that existed before work as before, and each v11 field is `None`. What each part needs from the platform: + +- **Decision provenance (v11.0.0).** `DecideResponse`, the gateway pre-check result (`PolicyApprovalResult`), `ClientResponse` (`proxy_llm_call`), `MCPCheckOutputResponse` and `ConnectorResponse` carry `engine`, `subject_type`, `policy_bundle` and `legacy_validators`. A decision adds `policy_identities`, `policy_packs` and `document_version`, and the pre-check result `decision_id` and `verdict`. `legacy_validators` is filled only where a checksum validator acted, so it is `None` on `proxy_llm_call` by design. +- **Frozen legacy policy writes (v11.0.0).** A write to the static- or dynamic-policy routes is refused with `409 LEGACY_POLICY_WRITE_FROZEN`, raised as `LegacyPolicyWriteFrozenError`, whose message names the typed policy route. +- **Route deprecation (v11.0.0).** The platform stamps its legacy policy routes, and the client reports each stamped route once through `PlatformRouteDeprecationWarning`. `simulate_policies`, `get_policy_impact_report` and `detect_policy_conflicts` are documented as deprecated: the platform removes their routes in v11.1. +- **The PEP capability handshake (v10.4.0).** The platform reads the declaration from v10.4.0. From v11.0.0, an organization's redact override on `decide` refuses a caller that does not declare redaction (see [PEP capability handshake](#pep-capability-handshake)). +- **Typed policy authoring (v11.0.0).** An older platform does not serve these routes: `edition()`, `validate()`, `publish()` and `activate()` raise `TypedPolicyRefusal` with the platform's answer, and `active()` reads a 404 as `None` (see [Typed policy authoring](#typed-policy-authoring)). + +Runnable programs: [`examples/typed_policies.py`](examples/typed_policies.py) and [`examples/pep_handshake.py`](examples/pep_handshake.py). + ### PEP capability handshake -A v11 platform lets an enforcement point declare, on each call, the exact obligation types and schema versions it can discharge. Build the declaration once and give it to the client: +The platform, from v10.4.0, lets an enforcement point declare, on each call, the exact obligation types and schema versions it can discharge. Build the declaration once and give it to the client: ```python from axonflow import AxonFlow, PEPCapability, PEPHandshake @@ -360,8 +372,8 @@ The client sends it on every call to a plane that reads it: `decide`, `evaluate` One process can be two enforcement points: a request path and a response path that discharge different obligations. Pass `pep_handshake=` to one of those methods to declare it for that call only, in place of the client's. -- **There is no default.** A client given no declaration sends no header, and the platform behaves as it did before the handshake existed. `capabilities=[]` declares that the enforcement point discharges nothing. -- **What a declaration changes.** On an Enterprise deployment, an allow verdict carrying a mandatory obligation the declared set cannot discharge becomes a deny, so declare every obligation your enforcement point carries out, and only those. A Community deployment records the declaration without denying on it, and drops any capability in a family it does not issue. +- **There is no default.** A client given no declaration sends no header. From v11.0.0 that is not neutral: `decide` under an organization's redact override refuses a caller that does not declare redaction, in every edition. `capabilities=[]` declares that the enforcement point discharges nothing. +- **What a declaration changes.** On an Enterprise deployment, an allow verdict carrying a mandatory obligation the declared set cannot discharge becomes a deny, so declare every obligation your enforcement point carries out, and only those. A Community deployment does not turn such an allow into a deny, and drops any capability in a family it does not issue; the redact-override refusal above applies in every edition. - **Refused before it is sent.** `PEPHandshake` applies the platform's own rules at construction and raises `PEPHandshakeError` naming the member at fault (`.pointer` is `/pep_id`, `/audience` or `/capabilities`), instead of the first governed call coming back `400`. - **A header set by hand** in `extra_headers` is sent as given, in place of the client's declaration for that call. Passing it together with `pep_handshake=` is refused. @@ -564,16 +576,10 @@ result = await client.get_policy_approved_context( ) # result.approved = False, result.block_reason = "SQL injection detected" -# Static Policies - List and manage built-in policies -policies = await client.list_policies() -# Returns: [Policy(name="pii-detection", enabled=True), ...] - -# Dynamic Policies - Create runtime policies -await client.create_dynamic_policy( - name="block-competitor-queries", - conditions={"contains": ["competitor", "pricing"]}, - action="block", -) +# Typed Policy Authoring (v11.0.0) - validate, publish and activate a policy document +validation = await client.typed_policies.validate(document, fixtures) +published = await client.typed_policies.publish(document, fixtures) +await client.typed_policies.activate(published.digest) # MCP Connectors - Query external data sources resp = await client.query_connector( diff --git a/axonflow/pep_handshake.py b/axonflow/pep_handshake.py index a5e80bb..8385297 100644 --- a/axonflow/pep_handshake.py +++ b/axonflow/pep_handshake.py @@ -23,8 +23,10 @@ and ``pre_check``). ``proxy_llm_call`` (``/api/request``) and the OpenAI-compatible route do not read it, and the client never sends it there. -ABSENT IS NOT EMPTY. A client with no declaration sends no header, and the -platform behaves exactly as it did before the handshake existed. There is no +ABSENT IS NOT EMPTY. A client with no declaration sends no header. The +platform reads the declaration from v10.4.0; from v11.0.0, ``decide`` under an +organization's redact override refuses a caller that does not declare +redaction, so a client that sends none is refused there. There is no default declaration: only the caller knows what its enforcement point can discharge. ``capabilities=()`` is a declaration that it discharges nothing, which on Enterprise turns every allow that carries a mandatory obligation into diff --git a/examples/indonesia_compliance.py b/examples/indonesia_compliance.py index f5104db..c617964 100644 --- a/examples/indonesia_compliance.py +++ b/examples/indonesia_compliance.py @@ -91,6 +91,9 @@ async def main() -> None: try: from axonflow.policies import ListStaticPoliciesOptions + # A v11.0.0 platform deprecates this route and removes it in v11.1. The + # client reports it once through PlatformRouteDeprecationWarning, naming + # its successor, /api/v1/typed-policies. policies = await client.list_static_policies( ListStaticPoliciesOptions(category=PolicyCategory.PII_INDONESIA), ) diff --git a/examples/pep_handshake.py b/examples/pep_handshake.py new file mode 100644 index 0000000..43518ae --- /dev/null +++ b/examples/pep_handshake.py @@ -0,0 +1,130 @@ +"""Example: declaring an enforcement point's capabilities with the PEP handshake. + +An enforcement point (a PEP) declares, on each governed call, the exact +obligation types and schema versions it can discharge. The platform reads the +declaration from v10.4.0. On an Enterprise deployment an allow carrying a +mandatory obligation the declared set cannot discharge becomes a deny, so the +enforcement point is never handed an instruction it would drop; from v11.0.0, +an organization's redact override on ``decide`` refuses a caller that does not +declare redaction. + +This example builds a declaration once for the client, overrides it for one +call (one process can be two enforcement points), and shows that a declaration +the platform would refuse fails here, before anything is sent. + +After a document with an organization-scope constraint is activated, a decide +that does not supply the attribute the constraint conditions on is denied +fail-closed with reasons ["unknown_constraint"]; supply the attribute or run +this example on a fresh stack. + +Env vars: + +* ``AXONFLOW_AGENT_URL`` (default: http://localhost:8080) +* ``AXONFLOW_CLIENT_ID`` (default: community) +* ``AXONFLOW_CLIENT_SECRET`` (default: empty) + +Run:: + + python examples/pep_handshake.py + +Exits non-zero if a step fails, so it is usable as a smoke test. +""" + +from __future__ import annotations + +import asyncio +import os +import sys +from collections.abc import Awaitable, Callable + +from axonflow import ( + AxonFlow, + DecideRequest, + DecisionTarget, + PEPCapability, + PEPHandshake, + PEPHandshakeError, +) +from axonflow.exceptions import AxonFlowError + +AUDIENCE = "https://pep.example.com" + + +async def main() -> int: + # The request path redacts fields; it declares exactly that. + request_path = PEPHandshake( + pep_id="checkout-gateway", + audience=AUDIENCE, + capabilities=[PEPCapability("field_redact", 1)], + ) + request = DecideRequest( + stage="tool", + query="look up the weather", + target=DecisionTarget(type="tool", tool="search"), + ) + + failures = 0 + + async def step(name: str, fn: Callable[[], Awaitable[None]]) -> None: + nonlocal failures + print(f"\n=== {name} ===") + try: + await fn() + print("ok") + except AxonFlowError as e: + print(f"FAILED: {e}") + failures += 1 + + async with AxonFlow( + endpoint=os.environ.get("AXONFLOW_AGENT_URL", "http://localhost:8080"), + client_id=os.environ.get("AXONFLOW_CLIENT_ID", "community"), + client_secret=os.environ.get("AXONFLOW_CLIENT_SECRET", ""), + pep_handshake=request_path, + ) as client: + + async def with_the_clients() -> None: + decision = await client.decide(request) + reasons = decision.reasons or [] + print( + f"verdict={decision.verdict} obligations={len(decision.obligations)} " + f"reasons={reasons}" + ) + + # The response path masks fields instead. It declares its own set for + # this call, in place of the client's. + async def with_a_per_call_one() -> None: + response_path = PEPHandshake( + pep_id="checkout-gateway-response", + audience=AUDIENCE, + capabilities=[PEPCapability("field_mask", 1)], + ) + decision = await client.decide(request, pep_handshake=response_path) + reasons = decision.reasons or [] + print( + f"verdict={decision.verdict} obligations={len(decision.obligations)} " + f"reasons={reasons}" + ) + + await step("decide with the client's declaration", with_the_clients) + await step("decide with a per-call declaration", with_a_per_call_one) + + # A declaration the platform would refuse fails at construction, naming the + # member at fault, instead of the first governed call answering 400. + async def refused() -> None: + try: + PEPHandshake(pep_id="Checkout:Gateway", audience=AUDIENCE, capabilities=[]) + except PEPHandshakeError as refusal: + print(f"refused at {refusal.pointer}: {refusal}") + return + msg = "want a PEPHandshakeError, got none" + raise AxonFlowError(msg) + + await step("a declaration the platform would refuse", refused) + + if failures: + print(f"\n{failures} step(s) failed") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(asyncio.run(main())) diff --git a/examples/typed_policies.py b/examples/typed_policies.py new file mode 100644 index 0000000..ba988ca --- /dev/null +++ b/examples/typed_policies.py @@ -0,0 +1,118 @@ +"""Example: typed policy authoring against a running AxonFlow v11.0.0 platform. + +A v11.0.0 platform authors policy as a typed document: validated, published as +a signed artifact pinned by its digest, and promoted to active. This example +reads what the deployment may author, validates a document and prints every +finding, and shows the document in force. It publishes and activates only when +``AXONFLOW_TYPED_POLICY_PUBLISH=1``, because that changes the organization's +active policy. + +Env vars: + +* ``AXONFLOW_AGENT_URL`` (default: http://localhost:8080) +* ``AXONFLOW_CLIENT_ID`` (default: community) +* ``AXONFLOW_CLIENT_SECRET`` (default: empty) +* ``AXONFLOW_TYPED_POLICY_BODY`` a JSON file holding ``{"document": ..., "fixtures": [...]}`` + (default: ``tests/fixtures/typed_policy_publish_body.json``) +* ``AXONFLOW_TYPED_POLICY_PUBLISH`` set to ``1`` to also publish and activate the document + +Run it from the repository root, since the default body is a path in it:: + + python examples/typed_policies.py + +Exits non-zero if a step fails, so it is usable as a smoke test. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import sys +from collections.abc import Awaitable, Callable +from pathlib import Path + +from axonflow import AxonFlow, TypedPolicyRefusal +from axonflow.exceptions import AxonFlowError + + +async def main() -> int: + body_path = Path( + os.environ.get( + "AXONFLOW_TYPED_POLICY_BODY", "tests/fixtures/typed_policy_publish_body.json" + ) + ) + body = json.loads(body_path.read_text(encoding="utf-8")) + document, fixtures = body["document"], body["fixtures"] + + failures = 0 + + async def step(name: str, fn: Callable[[], Awaitable[None]]) -> None: + nonlocal failures + print(f"\n=== {name} ===") + try: + await fn() + print("ok") + except AxonFlowError as e: + print(f"FAILED: {e}") + failures += 1 + + async with AxonFlow( + endpoint=os.environ.get("AXONFLOW_AGENT_URL", "http://localhost:8080"), + client_id=os.environ.get("AXONFLOW_CLIENT_ID", "community"), + client_secret=os.environ.get("AXONFLOW_CLIENT_SECRET", ""), + ) as client: + # What this deployment may author: consult it before publishing, rather + # than learning the edition's boundary from a refusal. + async def edition() -> None: + e = await client.typed_policies.edition() + print(f"root={e.root} max_documents={e.max_documents} persistence={e.persistence}") + if e.constructs: + families = ", ".join(e.constructs.obligation_families) + print(f"edition={e.constructs.edition} obligation families={families}") + + # Validation reports every finding. A document with findings is still a + # successful call: read success and findings rather than expecting a raise. + async def validate() -> None: + validation = await client.typed_policies.validate(document, fixtures) + print(f"success={validation.success}") + for f in validation.findings: + print(f" {f.severity} {f.code} {f.policy_id or ''}: {f.detail or f.summary or ''}") + + async def publish_and_activate() -> None: + try: + published = await client.typed_policies.publish(document, fixtures) + print(f"published {published.digest} (version {published.version})") + await client.typed_policies.activate( + published.digest, reason="examples/typed_policies" + ) + print("activated") + except TypedPolicyRefusal as refusal: + # A refusal carries the platform's reason and, for a refused + # document, the findings that refused it. + print(f"refused: HTTP {refusal.status} {refusal.reason}: {refusal}") + for f in refusal.findings: + print(f" {f.severity} {f.code} {f.policy_id or ''}") + + # The document in force comes back as the exact text that was signed. + async def in_force() -> None: + active = await client.typed_policies.active() + if active is None: + print("nothing is active") + return + document_id = active.document.get("metadata", {}).get("document_id") + print(f"{len(active.source)} signed characters; document_id={document_id}") + + await step("what this deployment may author", edition) + await step("validate the document", validate) + if os.environ.get("AXONFLOW_TYPED_POLICY_PUBLISH") == "1": + await step("publish and activate", publish_and_activate) + await step("the document in force", in_force) + + if failures: + print(f"\n{failures} step(s) failed") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(asyncio.run(main()))