diff --git a/.lint_baselines/falsey_clobber.json b/.lint_baselines/falsey_clobber.json index c507eaf..37f9821 100644 --- a/.lint_baselines/falsey_clobber.json +++ b/.lint_baselines/falsey_clobber.json @@ -22,24 +22,24 @@ "axonflow/adapters/tool_wrapper.py:190:20", "axonflow/adapters/tool_wrapper.py:208:20", "axonflow/adapters/tool_wrapper.py:220:20", - "axonflow/client.py:1124:20", - "axonflow/client.py:1225:20", - "axonflow/client.py:1405:16", - "axonflow/client.py:1482:16", - "axonflow/client.py:2027:37", - "axonflow/client.py:2068:18", - "axonflow/client.py:2126:37", - "axonflow/client.py:2677:24", - "axonflow/client.py:2698:33", - "axonflow/client.py:2699:31", - "axonflow/client.py:2711:25", - "axonflow/client.py:2772:28", - "axonflow/client.py:2813:69", + "axonflow/client.py:1149:20", + "axonflow/client.py:1250:20", + "axonflow/client.py:1430:16", + "axonflow/client.py:1507:16", + "axonflow/client.py:2052:37", + "axonflow/client.py:2093:18", + "axonflow/client.py:2151:37", + "axonflow/client.py:2702:24", + "axonflow/client.py:2723:33", + "axonflow/client.py:2724:31", + "axonflow/client.py:2736:25", + "axonflow/client.py:2797:28", + "axonflow/client.py:2838:69", "axonflow/client.py:316:14", "axonflow/client.py:321:24", "axonflow/client.py:322:20", - "axonflow/client.py:649:44", - "axonflow/client.py:7247:25", + "axonflow/client.py:665:44", + "axonflow/client.py:7300:25", "axonflow/execution.py:205:19", "axonflow/masfeat.py:345:23", "axonflow/masfeat.py:346:24", diff --git a/CHANGELOG.md b/CHANGELOG.md index 42e98dc..9b62ad1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,14 +17,14 @@ The first Python SDK release carrying these entries sends the PEP capability han - **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. +- **`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 route: a route that carries an id is reported once, by its template (for example `GET /api/v1/static-policies/{id}`), and any other by its path without the query string. A client derived through `as_user` shares that memory. - **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. +- **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`, the `policy` a tier refusal names, any findings and `retry_after`. The typed answers carry every member the platform sends: `TypedAuthoringEdition`'s `catalog_digest`, `registry_version` and `catalog_fixture`; a `TemplateOmissionReport` (`template_omissions` and `template_omissions_unavailable` on the publication and the activation), naming the organization template's controls a document omits, since activating it removes them; and `TypedPolicySystemControl.name` and `mandatory`, a plain `bool` that is `False` when the platform omits it. `active()` returns `None` only for the platform's `nothing_active`; any other 404, from a platform before v11.0.0 or an endpoint that is not an agent, raises `TypedPolicyRefusal` with status 404. The platform currently also answers `nothing_active` for a store read failure (getaxonflow/axonflow-enterprise#4255). `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/pep_handshake.py` declares an enforcement point's capabilities for the client and for one call, and `examples/typed_policies.py` authors policy as a typed document (it publishes and activates only when asked, prints the publication's template-omission report before it activates, and finds its default document from its own location, so it runs from any directory). Both exit non-zero when a step fails, including a publication or activation the example asked for and the platform refused; the README runs the handshake example first, 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 -- **`simulate_policies`, `get_policy_impact_report` and `detect_policy_conflicts`.** A v11.0.0 platform deprecates the policy simulation routes and removes them in v11.1. Each method's documentation says so, and the client reports each route once through `PlatformRouteDeprecationWarning` when the platform stamps it; the successor is `/api/v1/typed-policies`. `create_policy_override` and `delete_policy_override` document that a v11.0.0 platform refuses them with `409 LEGACY_POLICY_WRITE_FROZEN`, raised as `LegacyPolicyWriteFrozenError`. +- **`simulate_policies`, `get_policy_impact_report` and `detect_policy_conflicts`.** A v11.0.0 platform deprecates the policy simulation routes and removes them in v11.1. Each keeps answering until v11.1; on a v11.0.0 platform its result comes from the legacy engine, which no longer decides, so it does not predict what the platform enforces. Each method's documentation says so, and the client reports each route once through `PlatformRouteDeprecationWarning` when the platform stamps it; the successor is `/api/v1/typed-policies`. `create_policy_override` and `delete_policy_override` document that a v11.0.0 platform refuses them with `409 LEGACY_POLICY_WRITE_FROZEN`, raised as `LegacyPolicyWriteFrozenError`. ### Fixed diff --git a/README.md b/README.md index 193f675..ed7040c 100644 --- a/README.md +++ b/README.md @@ -343,11 +343,11 @@ Against a v11.0.0 platform this SDK reaches the new decision plane. Against an o - **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. +- **Route deprecation (v11.0.0).** The platform stamps its legacy policy routes, and the client reports each stamped route once through `PlatformRouteDeprecationWarning`; a route that carries an id is reported once, by its template (`GET /api/v1/static-policies/{id}`), not once per id. `simulate_policies`, `get_policy_impact_report` and `detect_policy_conflicts` are deprecated: each keeps answering until v11.1, and on a v11.0.0 platform its result comes from the legacy engine, which no longer decides, so it does not predict what the platform enforces. - **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)). +- **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()` does not read that as nothing active: it returns `None` only for the platform's `404 nothing_active` (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). +Runnable programs, in this order: [`examples/pep_handshake.py`](examples/pep_handshake.py), then [`examples/typed_policies.py`](examples/typed_policies.py). Run the handshake example first: 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. From v11.0.0 the deny's first reason is that code, followed by one naming each constraint it could not evaluate and the attribute it needed (getaxonflow/axonflow-enterprise#4247). The typed-policies example publishes and activates only when asked, and before it activates it prints which of the organization template's controls the document omits. ### PEP capability handshake @@ -373,7 +373,7 @@ 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. 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. +- **Which edition refuses what.** From v11.0.0, on every edition, the engine refuses with `unsupported_obligation` a mandatory obligation the caller's declaration cannot discharge, and a caller that presents no declaration can discharge none: `decide` under an organization's redact override refuses a caller that does not declare redaction (`field_redact` at version 1), so on Community too a caller that declares `field_mask` but not `field_redact` is refused there. What only Enterprise adds happens at the handler, for an enforcement point that presented a declaration: an allow carrying a mandatory obligation outside the declared set becomes a deny, a refusal names the capability the declaration lacks, and on the MCP check-input round-trip a redaction the declaration cannot discharge is refused rather than handed back masked. So declare every obligation your enforcement point carries out, and only those. A Community deployment drops a declared capability in a family its edition does not issue, counts it, and lets the request proceed. - **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. @@ -391,9 +391,11 @@ async with AxonFlow(endpoint="...", client_id="...", client_secret="...") as cli system = await client.typed_policies.system() # the platform's own controls, read-only ``` +- **Activation replaces the organization template.** Activating a document that omits the organization template's controls removes those controls for the organization. The template's controls carry the destructive-command blocks, DROP and TRUNCATE prevention and the blocking SQL-injection rows. `publish()` and `activate()` report which ones a document omits as `template_omissions`, and the example prints that report. The publish fixture the example uses is a minimal example, not a starting point for production: it omits all of them. - **Activation promotes.** A digest whose version does not advance past the active one is refused. Rolling back to an earlier document, and withdrawing the active one, are operations of the customer portal behind its session; the agent does not proxy them, so the SDK has no method for either. -- **The organization and the author are the ones your credentials resolve to.** The agent stamps both, and the platform overwrites any author named inside the document. -- **Refusals are typed.** Every refusal raises `TypedPolicyRefusal` with the HTTP `status`, the platform's `reason` (such as `publication_refused`, `activation_refused` or `tier_limit`), any `findings`, and `retry_after` when the refusal is retryable. On an edition with separation of duties, publishing refuses with the finding code `APPROVER_IS_AUTHOR`: the route names no approver, and such a deployment approves in the customer portal. +- **The organization and the author are the ones your credentials resolve to.** The agent stamps both, and the platform overwrites any author named inside the document. On Community the organization is the deployment's (`ORG_ID`). +- **Refusals are typed.** Every refusal raises `TypedPolicyRefusal` with the HTTP `status`, the platform's `reason` (such as `publication_refused`, `activation_refused` or `tier_limit`), any `findings`, the `policy` a tier refusal names, and `retry_after` when the refusal is retryable. On an edition with separation of duties, publishing refuses with the finding code `APPROVER_IS_AUTHOR`: the route names no approver, and such a deployment approves in the customer portal. +- **`active()` is `None` only for the platform's `nothing_active`.** Any other `404`, from a platform before v11.0.0 or an endpoint that is not an agent, raises `TypedPolicyRefusal` with status `404`. The platform currently also answers `nothing_active` when its document store cannot be read (getaxonflow/axonflow-enterprise#4255). - `validate()` answers identically on every edition; the edition's boundary is applied when you publish. ## Configuration diff --git a/axonflow/__init__.py b/axonflow/__init__.py index 9e9d605..7d355b6 100644 --- a/axonflow/__init__.py +++ b/axonflow/__init__.py @@ -190,6 +190,7 @@ AuthoringFinding, EditionConstructReport, SyncTypedPoliciesNamespace, + TemplateOmissionReport, TypedAuthoringDocumentRequest, TypedAuthoringEdition, TypedPoliciesNamespace, @@ -430,6 +431,7 @@ "ActiveTypedPolicy", "TypedPolicySystemControl", "TypedPolicySystemCorpus", + "TemplateOmissionReport", "REQUEST_REDACTION_PATH", "RESPONSE_REDACTION_PATH", "has_request_redaction", diff --git a/axonflow/client.py b/axonflow/client.py index 96c1847..4ee2f0f 100644 --- a/axonflow/client.py +++ b/axonflow/client.py @@ -349,8 +349,21 @@ def _legacy_policy_write_frozen(response: httpx.Response) -> LegacyPolicyWriteFr return LegacyPolicyWriteFrozenError(str(err.get("message", "legacy policy write frozen"))) +def _route_with_id(template: str, path_id: str) -> str: + """Fill the ``{id}`` in a route template with ``path_id``. + + The id is sent as given, not percent-encoded, as it was before the path was + built from a template (getaxonflow/axonflow-sdk-python#263). + """ + return template.replace("{id}", path_id, 1) + + def _warn_if_route_deprecated( - response: httpx.Response, method: str, path: str, reported: set[str] + response: httpx.Response, + method: str, + path: str, + reported: set[str], + route_template: str | None = None, ) -> None: """Warn when the platform stamps the route a call used as deprecated. @@ -361,14 +374,17 @@ def _warn_if_route_deprecated( the tag as well as after it. Each route is reported once per client. ``reported`` is the client's memory - of the routes it has reported, keyed by method and path without the query - string, as the TypeScript and Go SDKs key theirs. + of the routes it has reported, keyed by method and route: for a call whose + path carries an id, the route template it was built from + (``GET /api/v1/static-policies/{id}``), so a stamped route is reported once, + not once per id; otherwise the path without the query string. """ deprecation = response.headers.get("Deprecation") removed_in = response.headers.get("X-AxonFlow-Removed-In") if deprecation is None and removed_in is None: return - route = f"{method} {path.split('?', 1)[0]}" + key = route_template if route_template is not None else path.split("?", 1)[0] + route = f"{method} {key}" if route in reported: return reported.add(route) @@ -1075,17 +1091,26 @@ async def _request( *, json_data: dict[str, Any] | None = None, extra_headers: dict[str, str] | None = None, + path_id: str | None = None, ) -> dict[str, Any]: """Make HTTP request to Agent. + When ``path_id`` is given, ``path`` is a route template and its ``{id}`` + is filled with it, so the route-deprecation record keys on the template. + ``extra_headers`` are merged into THIS request only. They never reach the client's default header set, so a header supplied for one call cannot leak into the next one - which is the property that makes a per-call declaration safe to vary (see the governed methods' own ``extra_headers`` documentation). """ + route_template = None + if path_id is not None: + route_template, path = path, _route_with_id(path, path_id) response = await self._send_raw(method, path, json_data=json_data, headers=extra_headers) - _warn_if_route_deprecated(response, method, path, self._reported_deprecated_routes) + _warn_if_route_deprecated( + response, method, path, self._reported_deprecated_routes, route_template + ) try: response.raise_for_status() @@ -2923,8 +2948,11 @@ async def simulate_policies( v11.0.0 and removes it in v11.1. It stamps ``Deprecation``, ``X-AxonFlow-Removed-In: v11.1`` and a ``Link`` to ``/api/v1/typed-policies`` on every response, and this client reports the route once through - :class:`PlatformRouteDeprecationWarning`. Its successor is the typed simulate on - ``/api/v1/typed-policies``, which ships with the v11 series. + :class:`PlatformRouteDeprecationWarning`. It keeps answering until v11.1; on a + v11.0.0 platform its result comes from the legacy engine, which no longer + decides, so it does not predict what the platform enforces. Policy is + authored and tested through the typed policy methods (see + ``client.typed_policies.validate``). Runs the full policy evaluation pipeline without actually blocking or auditing the request. Useful for testing policy configurations @@ -2985,8 +3013,11 @@ async def get_policy_impact_report( v11.0.0 and removes it in v11.1. It stamps ``Deprecation``, ``X-AxonFlow-Removed-In: v11.1`` and a ``Link`` to ``/api/v1/typed-policies`` on every response, and this client reports the route once through - :class:`PlatformRouteDeprecationWarning`. Policy is authored and tested through - the typed policy methods (see ``client.typed_policies.validate``). + :class:`PlatformRouteDeprecationWarning`. It keeps answering until v11.1; on a + v11.0.0 platform its result comes from the legacy engine, which no longer + decides, so it does not predict what the platform enforces. Policy is + authored and tested through the typed policy methods (see + ``client.typed_policies.validate``). Generates an impact report showing how a specific policy would affect a set of sample inputs. Useful for understanding the @@ -3045,8 +3076,11 @@ async def detect_policy_conflicts( v11.0.0 and removes it in v11.1. It stamps ``Deprecation``, ``X-AxonFlow-Removed-In: v11.1`` and a ``Link`` to ``/api/v1/typed-policies`` on every response, and this client reports the route once through - :class:`PlatformRouteDeprecationWarning`. Policy is authored and tested through - the typed policy methods (see ``client.typed_policies.validate``). + :class:`PlatformRouteDeprecationWarning`. It keeps answering until v11.1; on a + v11.0.0 platform its result comes from the legacy engine, which no longer + decides, so it does not predict what the platform enforces. Policy is + authored and tested through the typed policy methods (see + ``client.typed_policies.validate``). Analyzes active policies for conflicts such as overlapping conditions with contradictory actions. Optionally scoped to @@ -3883,7 +3917,7 @@ async def get_static_policy(self, policy_id: str) -> StaticPolicy: if self._config.debug: self._logger.debug("Getting static policy", policy_id=policy_id) - response = await self._request("GET", f"/api/v1/static-policies/{policy_id}") + response = await self._request("GET", "/api/v1/static-policies/{id}", path_id=policy_id) return StaticPolicy.model_validate(response) async def create_static_policy( @@ -3937,7 +3971,8 @@ async def update_static_policy( response = await self._request( "PUT", - f"/api/v1/static-policies/{policy_id}", + "/api/v1/static-policies/{id}", + path_id=policy_id, json_data=request.model_dump(exclude_none=True, by_alias=True), ) return StaticPolicy.model_validate(response) @@ -3951,7 +3986,7 @@ async def delete_static_policy(self, policy_id: str) -> None: if self._config.debug: self._logger.debug("Deleting static policy", policy_id=policy_id) - await self._request("DELETE", f"/api/v1/static-policies/{policy_id}") + await self._request("DELETE", "/api/v1/static-policies/{id}", path_id=policy_id) async def toggle_static_policy( self, @@ -3972,7 +4007,8 @@ async def toggle_static_policy( response = await self._request( "PATCH", - f"/api/v1/static-policies/{policy_id}", + "/api/v1/static-policies/{id}", + path_id=policy_id, json_data={"enabled": enabled}, ) return StaticPolicy.model_validate(response) @@ -4061,7 +4097,8 @@ async def get_static_policy_versions( response = await self._request( "GET", - f"/api/v1/static-policies/{policy_id}/versions", + "/api/v1/static-policies/{id}/versions", + path_id=policy_id, ) versions = response.get("versions", []) return [PolicyVersion.model_validate(v) for v in versions] @@ -4106,7 +4143,8 @@ async def create_policy_override( response = await self._request( "POST", - f"/api/v1/static-policies/{policy_id}/override", + "/api/v1/static-policies/{id}/override", + path_id=policy_id, json_data=request.model_dump(mode="json", exclude_none=True, by_alias=True), ) return PolicyOverride.model_validate(response) @@ -4124,7 +4162,7 @@ async def delete_policy_override(self, policy_id: str) -> None: if self._config.debug: self._logger.debug("Deleting policy override", policy_id=policy_id) - await self._request("DELETE", f"/api/v1/static-policies/{policy_id}/override") + await self._request("DELETE", "/api/v1/static-policies/{id}/override", path_id=policy_id) async def list_policy_overrides(self) -> list[PolicyOverride]: """List all active policy overrides (Enterprise). @@ -4209,7 +4247,9 @@ async def get_dynamic_policy(self, policy_id: str) -> DynamicPolicy: if self._config.debug: self._logger.debug("Getting dynamic policy", policy_id=policy_id) - response = await self._orchestrator_request("GET", f"/api/v1/dynamic-policies/{policy_id}") + response = await self._orchestrator_request( + "GET", "/api/v1/dynamic-policies/{id}", path_id=policy_id + ) # Response may be wrapped in {"policy": {...}} policy_data = response.get("policy", response) if isinstance(response, dict) else response return DynamicPolicy.model_validate(policy_data) @@ -4257,7 +4297,8 @@ async def update_dynamic_policy( response = await self._orchestrator_request( "PUT", - f"/api/v1/dynamic-policies/{policy_id}", + "/api/v1/dynamic-policies/{id}", + path_id=policy_id, json_data=request.model_dump(exclude_none=True, by_alias=True), ) # Response may be wrapped in {"policy": {...}} @@ -4273,7 +4314,9 @@ async def delete_dynamic_policy(self, policy_id: str) -> None: if self._config.debug: self._logger.debug("Deleting dynamic policy", policy_id=policy_id) - await self._orchestrator_request("DELETE", f"/api/v1/dynamic-policies/{policy_id}") + await self._orchestrator_request( + "DELETE", "/api/v1/dynamic-policies/{id}", path_id=policy_id + ) async def toggle_dynamic_policy( self, @@ -4294,7 +4337,8 @@ async def toggle_dynamic_policy( response = await self._orchestrator_request( "PUT", - f"/api/v1/dynamic-policies/{policy_id}", + "/api/v1/dynamic-policies/{id}", + path_id=policy_id, json_data={"enabled": enabled}, ) # Response may be wrapped in {"policy": {...}} @@ -4878,9 +4922,13 @@ async def _orchestrator_request( scoped_resource: str | None = None, scoped_identifier: str | None = None, scoped_page_key: str | None = None, + path_id: str | None = None, ) -> dict[str, Any] | list[Any] | None: """Make HTTP request to Orchestrator. + ``path_id`` fills the ``{id}`` in ``path``, a route template, as on + :meth:`_request`. + ``scoped_resource``/``scoped_identifier`` opt a route into the read-scope diagnosis: a 404 on a role-scoped read is re-raised as :class:`~axonflow.read_identity.ReadScopeError` when the platform's @@ -4895,12 +4943,17 @@ async def _orchestrator_request( would end up holding on whichever branch the server happened to take. """ self._pre_request_hook() + route_template = None + if path_id is not None: + route_template, path = path, _route_with_id(path, path_id) base_url = self._config.endpoint url = f"{base_url}{path}" try: response = await self._http_client.request(method, url, json=json_data) - _warn_if_route_deprecated(response, method, path, self._reported_deprecated_routes) + _warn_if_route_deprecated( + response, method, path, self._reported_deprecated_routes, route_template + ) response.raise_for_status() if response.status_code == 204: # noqa: PLR2004 return None @@ -8770,8 +8823,11 @@ def simulate_policies( v11.0.0 and removes it in v11.1. It stamps ``Deprecation``, ``X-AxonFlow-Removed-In: v11.1`` and a ``Link`` to ``/api/v1/typed-policies`` on every response, and this client reports the route once through - :class:`PlatformRouteDeprecationWarning`. Its successor is the typed simulate on - ``/api/v1/typed-policies``, which ships with the v11 series. + :class:`PlatformRouteDeprecationWarning`. It keeps answering until v11.1; on a + v11.0.0 platform its result comes from the legacy engine, which no longer + decides, so it does not predict what the platform enforces. Policy is + authored and tested through the typed policy methods (see + ``client.typed_policies.validate``). """ return self._run_sync( self._async_client.simulate_policies( @@ -8794,8 +8850,11 @@ def get_policy_impact_report( v11.0.0 and removes it in v11.1. It stamps ``Deprecation``, ``X-AxonFlow-Removed-In: v11.1`` and a ``Link`` to ``/api/v1/typed-policies`` on every response, and this client reports the route once through - :class:`PlatformRouteDeprecationWarning`. Policy is authored and tested through - the typed policy methods (see ``client.typed_policies.validate``). + :class:`PlatformRouteDeprecationWarning`. It keeps answering until v11.1; on a + v11.0.0 platform its result comes from the legacy engine, which no longer + decides, so it does not predict what the platform enforces. Policy is + authored and tested through the typed policy methods (see + ``client.typed_policies.validate``). """ return self._run_sync(self._async_client.get_policy_impact_report(policy_id, inputs)) @@ -8809,8 +8868,11 @@ def detect_policy_conflicts( v11.0.0 and removes it in v11.1. It stamps ``Deprecation``, ``X-AxonFlow-Removed-In: v11.1`` and a ``Link`` to ``/api/v1/typed-policies`` on every response, and this client reports the route once through - :class:`PlatformRouteDeprecationWarning`. Policy is authored and tested through - the typed policy methods (see ``client.typed_policies.validate``). + :class:`PlatformRouteDeprecationWarning`. It keeps answering until v11.1; on a + v11.0.0 platform its result comes from the legacy engine, which no longer + decides, so it does not predict what the platform enforces. Policy is + authored and tested through the typed policy methods (see + ``client.typed_policies.validate``). """ return self._run_sync(self._async_client.detect_policy_conflicts(policy_id=policy_id)) diff --git a/axonflow/exceptions.py b/axonflow/exceptions.py index 923746b..891821a 100644 --- a/axonflow/exceptions.py +++ b/axonflow/exceptions.py @@ -298,10 +298,11 @@ class TypedPolicyRefusal(AxonFlowError): ``status`` is the HTTP status and ``reason`` the platform's reason, for example ``publication_refused`` (422), ``activation_refused`` (409), - ``tier_limit`` (402, with ``code`` naming the limit) or ``artifact_cap`` - (429). ``findings`` holds the declared findings a refused publication or - document carries, and ``retry_after`` the seconds from ``Retry-After`` when - the refusal is retryable. ``message`` is the platform's own explanation. + ``tier_limit`` (402, with ``code`` naming the limit and ``policy`` the + policy that crossed it) or ``artifact_cap`` (429). ``findings`` holds the + declared findings a refused publication or document carries, and + ``retry_after`` the seconds from ``Retry-After`` when the refusal is + retryable. ``message`` is the platform's own explanation. """ def __init__( @@ -311,13 +312,18 @@ def __init__( status: int, reason: str | None = None, code: str | None = None, + policy: str | None = None, findings: list[Any] | None = None, retry_after: int | None = None, ) -> None: - super().__init__(message, details={"status": status, "reason": reason, "code": code}) + super().__init__( + message, + details={"status": status, "reason": reason, "code": code, "policy": policy}, + ) self.status = status self.reason = reason self.code = code + self.policy = policy self.findings = findings or [] self.retry_after = retry_after diff --git a/axonflow/pep_handshake.py b/axonflow/pep_handshake.py index 8385297..b823e2d 100644 --- a/axonflow/pep_handshake.py +++ b/axonflow/pep_handshake.py @@ -8,12 +8,19 @@ {"profile_version": 1, "pep_id": "...", "audience": "...", "capabilities": [{"type": "field_redact", "version": 1}]} -On an Enterprise deployment, an allow verdict carrying a mandatory obligation -the declared set cannot discharge becomes a deny, so the enforcement point is -never handed an instruction it would drop. A Community deployment records the -declaration and does not deny on it. A capability in a family the deployment's -edition does not issue is dropped from the declaration, counted and logged; the -request proceeds. +From platform v11.0.0, on every edition, the engine refuses with +``unsupported_obligation`` a mandatory obligation the caller's declaration +cannot discharge, and a caller that presents no declaration can discharge none: +``decide`` under an organization's redact override refuses a caller that does +not declare redaction (``field_redact`` at version 1). What only Enterprise +adds happens at the handler, for an enforcement point that presented a +declaration: an allow carrying a mandatory obligation outside the declared set +becomes a deny, so the enforcement point is never handed an instruction it +would drop; a refusal names the capability the declaration lacks; and on the +MCP check-input round-trip, a redaction the declaration cannot discharge is +refused rather than handed back masked. A capability in a family the +deployment's edition does not issue is dropped from the declaration, counted +and logged; the request proceeds. WHERE IT IS SENT. Four request planes read the header: ``decide`` (``/api/v1/decide``), the AuthZEN evaluation route (``evaluate`` and diff --git a/axonflow/typed_policies.py b/axonflow/typed_policies.py index 7541db9..a7861b6 100644 --- a/axonflow/typed_policies.py +++ b/axonflow/typed_policies.py @@ -14,7 +14,8 @@ fixtures, signs, and pins the artifact by its digest. - ``activate(digest)``: promotes a published digest to active. - ``active()``: the document in force, as the exact bytes that were signed, or - ``None`` when nothing is active. + ``None`` when the platform answers that nothing is active (a ``404`` whose + reason is ``nothing_active``). - ``system()``: the platform's own controls, read-only. The organization and the author are the ones this client's credentials resolve @@ -25,6 +26,11 @@ are operations of the customer portal, behind its session; the agent does not proxy them, so this module has no method for either. +Activation also REPLACES the organization template: activating a document that +omits the template's controls removes those controls for the organization. +``publish()`` and ``activate()`` report which ones a document omits as +``template_omissions``. + On an edition with separation of duties, ``publish`` refuses every publication with the finding code ``APPROVER_IS_AUTHOR``: publishing through this route names no approver, and such a deployment approves in the customer portal. @@ -50,6 +56,7 @@ "AuthoringFinding", "EditionConstructReport", "SyncTypedPoliciesNamespace", + "TemplateOmissionReport", "TypedAuthoringDocumentRequest", "TypedAuthoringEdition", "TypedPoliciesNamespace", @@ -70,6 +77,7 @@ # collection the platform declares without omitempty reads null as empty. _NULL_AS_EMPTY_LIST = BeforeValidator(lambda v: [] if v is None else v) _NULL_AS_EMPTY_DICT = BeforeValidator(lambda v: {} if v is None else v) +_NULL_AS_FALSE = BeforeValidator(lambda v: False if v is None else v) class EditionConstructReport(BaseModel): @@ -111,6 +119,16 @@ class TypedAuthoringEdition(BaseModel): success: bool = False catalog: str | None = Field(default=None, description="The configured authoring vocabulary.") + catalog_digest: str | None = Field( + default=None, description="The digest that names the authoring vocabulary." + ) + registry_version: int | None = Field( + default=None, description="The version of the action registry in that vocabulary." + ) + catalog_fixture: bool | None = Field( + default=None, + description="True when the vocabulary is a test-world fixture, not a deployment's.", + ) root: str | None = Field( default=None, description="The one authority root this surface publishes under." ) @@ -130,20 +148,48 @@ class TypedPolicyValidation(BaseModel): findings: Annotated[list[AuthoringFinding], _NULL_AS_EMPTY_LIST] = Field(default_factory=list) +class TemplateOmissionReport(BaseModel): + """The organization template's controls a document omits. + + Activating a document that omits them removes them for the organization. + ``of`` is how many controls the template carries, and ``omitted`` names each + one the document leaves out. + """ + + omitted: Annotated[list[str], _NULL_AS_EMPTY_LIST] = Field(default_factory=list) + of: int | None = None + message: str | None = None + + class TypedPolicyPublication(BaseModel): - """A published artifact. Activation names ``digest``, never the version.""" + """A published artifact. Activation names ``digest``, never the version. + + ``template_omissions`` reports the organization template's controls the + document omits, and is ``None`` when it omits none; + ``template_omissions_unavailable`` says why that report could not be + produced, when it could not. + """ success: bool = False digest: str version: int | None = None findings: Annotated[list[AuthoringFinding], _NULL_AS_EMPTY_LIST] = Field(default_factory=list) + template_omissions: TemplateOmissionReport | None = None + template_omissions_unavailable: str | None = None class TypedPolicyActivation(BaseModel): - """The audited activation record.""" + """The audited activation record. + + ``template_omissions`` and ``template_omissions_unavailable`` are the report + for the activated document, as on :class:`TypedPolicyPublication`, beside + the record rather than inside it. + """ success: bool = False activation: dict[str, Any] = Field(default_factory=dict) + template_omissions: TemplateOmissionReport | None = None + template_omissions_unavailable: str | None = None class ActiveTypedPolicy(BaseModel): @@ -161,9 +207,12 @@ class TypedPolicySystemControl(BaseModel): """One shipped control, with what happens when it cannot be evaluated.""" id: str + name: str | None = None authority: str | None = None assurance: str | None = Field(default=None, description="enforcement, gating_risk or advisory") - mandatory: bool | None = None + mandatory: Annotated[bool, _NULL_AS_FALSE] = Field( + default=False, description="False when the platform omits it." + ) description: str | None = None obligations: list[dict[str, Any]] = Field(default_factory=list) @@ -184,6 +233,16 @@ class TypedPolicySystemCorpus(BaseModel): document: Annotated[dict[str, Any], _NULL_AS_EMPTY_DICT] = Field(default_factory=dict) +def _reason(response: httpx.Response) -> str | None: + """The platform's ``reason`` in a JSON answer, or ``None``.""" + try: + body = response.json() + except ValueError: + return None + reason = body.get("reason") if isinstance(body, dict) else None + return reason if isinstance(reason, str) else None + + def _raise_for_refusal(response: httpx.Response, route: str) -> None: """Raise the typed refusal for a non-2xx answer; return for a 2xx one.""" status = response.status_code @@ -206,6 +265,7 @@ def _raise_for_refusal(response: httpx.Response, route: str) -> None: status=status, reason=body.get("reason"), code=body.get("code"), + policy=body.get("policy"), findings=[ AuthoringFinding.model_validate(f) for f in (findings if isinstance(findings, list) else []) @@ -293,9 +353,17 @@ async def activate(self, digest: str, *, reason: str | None = None) -> TypedPoli return TypedPolicyActivation.model_validate(await self._json("POST", "/activate", payload)) async def active(self) -> ActiveTypedPolicy | None: - """The document in force, as the exact bytes that were signed, or ``None`` if nothing is.""" + """The document in force, as the exact bytes that were signed. + + ``None`` only when the platform answers that nothing is active: a ``404`` + whose reason is ``nothing_active``. Any other ``404``, from a platform + before v11.0.0 or an endpoint that is not an agent, raises + :class:`~axonflow.exceptions.TypedPolicyRefusal` with status 404. The + platform currently also answers ``nothing_active`` when its document + store cannot be read (getaxonflow/axonflow-enterprise#4255). + """ response = await self._send("GET", f"{TYPED_POLICIES_PATH}/active") - if response.status_code == 404: # noqa: PLR2004 + if response.status_code == 404 and _reason(response) == "nothing_active": # noqa: PLR2004 return None _raise_for_refusal(response, "/active") return ActiveTypedPolicy(source=response.content.decode("utf-8"), document=response.json()) @@ -339,7 +407,7 @@ def activate(self, digest: str, *, reason: str | None = None) -> TypedPolicyActi return self._run(self._namespace.activate(digest, reason=reason)) # type: ignore[no-any-return] def active(self) -> ActiveTypedPolicy | None: - """The document in force, or ``None`` if nothing is.""" + """The document in force, or ``None`` when the platform answers ``nothing_active``.""" return self._run(self._namespace.active()) # type: ignore[no-any-return] def system(self) -> TypedPolicySystemCorpus: diff --git a/examples/pep_handshake.py b/examples/pep_handshake.py index 43518ae..6d9833b 100644 --- a/examples/pep_handshake.py +++ b/examples/pep_handshake.py @@ -2,11 +2,12 @@ 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. +declaration from v10.4.0. From v11.0.0, on every edition, the engine refuses a +mandatory obligation the declaration cannot discharge: an organization's redact +override on ``decide`` refuses a caller that does not declare redaction. On an +Enterprise deployment, in addition, an allow carrying a mandatory obligation +outside the declared set becomes a deny, so the enforcement point is never +handed an instruction it would drop. 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 @@ -15,7 +16,9 @@ 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. +this example on a fresh stack. From v11.0.0 the deny's first reason is that +code, followed by one naming each constraint it could not evaluate and the +attribute it needed (getaxonflow/axonflow-enterprise#4247). Env vars: diff --git a/examples/typed_policies.py b/examples/typed_policies.py index ba988ca..d67d803 100644 --- a/examples/typed_policies.py +++ b/examples/typed_policies.py @@ -5,7 +5,19 @@ 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. +active policy. Before it activates, it prints the publication's report of the +organization template's controls the document omits: activating a document +that omits them removes them for the organization. A publication or activation +it was asked for and refused fails the run. + +Run ``examples/pep_handshake.py`` first. 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. From v11.0.0 the deny's first reason is that code, followed by one +naming each constraint it could not evaluate and the attribute it needed +(getaxonflow/axonflow-enterprise#4247). The default document is such a +document. Env vars: @@ -13,10 +25,11 @@ * ``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``) + (default: the repository's ``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:: +The default body is found from this file's own location, so it runs from any +directory:: python examples/typed_policies.py @@ -31,19 +44,48 @@ import sys from collections.abc import Awaitable, Callable from pathlib import Path +from typing import Any -from axonflow import AxonFlow, TypedPolicyRefusal +from axonflow import AxonFlow, TypedPolicyPublication, TypedPolicyRefusal from axonflow.exceptions import AxonFlowError +#: The document and fixtures used when ``AXONFLOW_TYPED_POLICY_BODY`` is unset: +#: the body the platform's own route test proves publishable. +DEFAULT_BODY = ( + Path(__file__).resolve().parent.parent / "tests" / "fixtures" / "typed_policy_publish_body.json" +) -async def main() -> int: - body_path = Path( - os.environ.get( - "AXONFLOW_TYPED_POLICY_BODY", "tests/fixtures/typed_policy_publish_body.json" + +def load_body() -> tuple[dict[str, Any], list[dict[str, Any]]]: + """The document and fixtures to author: ``AXONFLOW_TYPED_POLICY_BODY``'s, or the default.""" + path = Path(os.environ.get("AXONFLOW_TYPED_POLICY_BODY") or DEFAULT_BODY) + body = json.loads(path.read_text(encoding="utf-8")) + return body["document"], body["fixtures"] + + +def print_refusal(what: str, refusal: TypedPolicyRefusal) -> None: + """Print a refusal: the platform's reason and any findings that refused it.""" + print(f"{what}: HTTP {refusal.status} {refusal.reason}: {refusal}") + for f in refusal.findings: + print(f" {f.severity} {f.code} {f.policy_id or ''}") + + +def print_template_omissions(published: TypedPolicyPublication) -> None: + """Print which of the organization template's controls the document omits.""" + report = published.template_omissions + if report is not None: + omitted = ", ".join(report.omitted) + print( + f"template omissions: {len(report.omitted)} of {report.of} template controls: {omitted}" ) - ) - body = json.loads(body_path.read_text(encoding="utf-8")) - document, fixtures = body["document"], body["fixtures"] + elif published.template_omissions_unavailable is not None: + print(f"template omissions: unavailable: {published.template_omissions_unavailable}") + else: + print("template omissions: none") + + +async def main() -> int: + document, fixtures = load_body() failures = 0 @@ -82,17 +124,27 @@ async def validate() -> None: async def publish_and_activate() -> None: try: published = await client.typed_policies.publish(document, fixtures) - print(f"published {published.digest} (version {published.version})") + except TypedPolicyRefusal as refusal: + # A refusal carries the platform's reason and, for a refused + # document, the findings that refused it. Publishing was asked + # for, so a refusal fails the run. + print_refusal("refused", refusal) + raise + print(f"published {published.digest} (version {published.version})") + # Activating a document that omits the organization template's + # controls removes them for the organization, so the report comes first. + print_template_omissions(published) + try: 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 ''}") + # Activation promotes: a digest whose version does not advance + # past the active one is refused. Activating was asked for, so a + # refusal fails the run. + print_refusal("activation refused", refusal) + raise + print("activated") # The document in force comes back as the exact text that was signed. async def in_force() -> None: diff --git a/runtime-e2e/pep_handshake_planes/README.md b/runtime-e2e/pep_handshake_planes/README.md index 905f458..48058ba 100644 --- a/runtime-e2e/pep_handshake_planes/README.md +++ b/runtime-e2e/pep_handshake_planes/README.md @@ -20,7 +20,7 @@ Each call must move exactly the one series listed, by exactly one. `accepted` me ## What it does not prove -The consequence of a declaration differs by edition. On Enterprise, an allow verdict carrying a mandatory obligation the declared set cannot discharge becomes a deny. On Community, the declaration is recorded and does not deny. That rule is the platform's own, and the platform's suites prove it. This driver proves the declaration arrives and is admitted, which is the SDK's part. +What a declaration changes is the platform's rule, and the platform's suites prove it. From v11.0.0, on every edition, the engine refuses a mandatory obligation the declaration cannot discharge; on Enterprise, in addition, an allow carrying a mandatory obligation outside the declared set becomes a deny. This driver proves the declaration arrives and is admitted, which is the SDK's part. `proxy_llm_call` (`/api/request`) and the OpenAI-compatible route do not read the header, and the SDK does not send it there. The unit tests in `tests/test_pep_handshake.py` assert that absence on the wire. diff --git a/runtime-e2e/typed_policies/README.md b/runtime-e2e/typed_policies/README.md index 71d3671..55c5258 100644 --- a/runtime-e2e/typed_policies/README.md +++ b/runtime-e2e/typed_policies/README.md @@ -6,13 +6,13 @@ | Call | Expected answer | |---|---| -| `active()` before anything is activated | `None`, from the platform's `404 nothing_active` | -| `edition()` | the deployment's root and construct boundary | -| `system()` | the shipped system corpus: its digest and controls | +| `active()` before anything is activated | `None`, from the platform's `404` whose reason is `nothing_active` | +| `edition()` | the deployment's root and construct boundary; its vocabulary named by `catalog_digest` and a `registry_version`, and `catalog_fixture` false | +| `system()` | the shipped system corpus: its digest and controls, with at least one control named and one mandatory, and every `mandatory` a `bool` | | `validate(document, fixtures)` | success, with no rejecting finding | -| `publish(document, fixtures)` | a signed artifact's digest | -| `activate(digest)` | success: the digest is promoted to active | -| `active()` after the activation | the document just activated, as the exact signed source; its author is the caller the agent resolved, not the `someone-else` the document names | +| `publish(document, fixtures)` | a signed artifact's digest, and `template_omissions` naming every organization template control the document omits (`len(omitted) == of > 0`) | +| `activate(digest)` | success: the digest is promoted to active, with the same `template_omissions` as the publication | +| `active()` after the activation | the document just activated, as the exact signed source; its author is the caller the agent resolved, not the `someone-else` the document names (on Community: `Client` / `axonflow-api-credential` / the client id) | | `activate(digest)` again | `TypedPolicyRefusal` with status 409 and reason `activation_refused`: activation promotes, and the version does not advance | | `publish(document, [])` | `TypedPolicyRefusal` with status 422 and reason `publication_refused`, whose message names the missing fixtures | | `validate()` on the document with one action changed to `tool.not_registered` | `success` false, with the platform's rejecting finding `ACTION_NOT_REGISTERED` on `grant.refund` | @@ -24,6 +24,8 @@ The document is `tests/fixtures/typed_policy_publish_body.json`, the body the pl Rolling back to an earlier document and withdrawing the active one are customer portal operations that the agent does not proxy, so the SDK has no method for either and this driver does not exercise them. The separation-of-duties refusal (`APPROVER_IS_AUTHOR`) needs an edition with separation of duties; the unit tests in `tests/test_typed_policies.py` assert its shape, and the platform's suites own the rule. +Two members are covered by unit tests only. `TypedPolicyRefusal.policy`, the policy a tier refusal names, needs a deployment at its tier ceiling. `template_omissions_unavailable`, the reason the platform could not produce the omission report, needs a document store that cannot be read. This driver sets up neither. + ## Running it Boot a FRESH stack from the platform's main, one on which nothing is active for the organization, then: diff --git a/runtime-e2e/typed_policies/test.py b/runtime-e2e/typed_policies/test.py index a951ec9..f5792ab 100644 --- a/runtime-e2e/typed_policies/test.py +++ b/runtime-e2e/typed_policies/test.py @@ -3,14 +3,19 @@ Drives ``client.typed_policies`` against a real agent and orchestrator and asserts, on a fresh stack: -1. Nothing is active yet: ``active()`` answers ``None`` from the platform's 404. -2. ``edition()`` reports the deployment's boundary, and ``system()`` the shipped - controls with their digest. +1. Nothing is active yet: ``active()`` answers ``None`` from the platform's 404 + whose reason is ``nothing_active``, the reason it keys on. +2. ``edition()`` reports the deployment's boundary and names its vocabulary by + digest (not a test-world fixture), and ``system()`` the shipped controls with + their digest, names and mandatory flags. 3. The document the platform's own route test proves publishable validates - clean, publishes to a digest, and activates. + clean, publishes to a digest, and activates. The publication reports every + organization template control the document omits, and the activation + reports the same. 4. ``active()`` returns that document as the exact signed source, with the AUTHOR overwritten by the platform: the document deliberately names - ``someone-else``, and the platform signs the caller the agent resolved. + ``someone-else``, and on Community the platform signs the Client principal of + the presented credentials. 5. Activating the same digest again is refused as a typed 409 (``activation_refused``): activation promotes, and the version does not advance. @@ -79,12 +84,34 @@ async def run(client: AxonFlow) -> None: ) check(edition.success and edition.root == "organization", "edition() reports the root") check(edition.constructs is not None, "edition() reports the construct boundary") + print( + f" vocabulary: catalog_digest={edition.catalog_digest} " + f"registry_version={edition.registry_version} catalog_fixture={edition.catalog_fixture}" + ) + check(bool(edition.catalog_digest), "edition() names its vocabulary by digest") + check( + edition.registry_version is not None and edition.registry_version > 0, + "edition() names the version of its action registry", + ) + check( + edition.catalog_fixture is False, + "the deployment's vocabulary is not a test-world fixture, so a document can activate", + ) system = await typed.system() print( f" system: root={system.root} version={system.version} digest={system.digest} " f"controls={len(system.controls)} assurance_counts={system.assurance_counts}" ) check(bool(system.digest) and len(system.controls) > 0, "system() returns the shipped corpus") + named = sum(1 for c in system.controls if c.name) + mandatory = sum(1 for c in system.controls if c.mandatory) + print(f" system controls: {named} named, {mandatory} mandatory, of {len(system.controls)}") + check(named > 0, "system() reads each control's name") + check(mandatory > 0, "system() reads which controls are mandatory") + check( + all(isinstance(c.mandatory, bool) for c in system.controls), + "every control's mandatory flag is a bool", + ) print("== validate, publish, activate") validation = await typed.validate(document, fixtures) @@ -95,9 +122,27 @@ async def run(client: AxonFlow) -> None: published = await typed.publish(document, fixtures) print(f" publish: digest={published.digest} version={published.version}") check(bool(published.digest), "publish() returns the artifact digest") + report = published.template_omissions + if report is not None: + print( + f" template omissions: {len(report.omitted)} of {report.of}: {', '.join(report.omitted)}" + ) + else: + print( + f" template omissions: none (unavailable={published.template_omissions_unavailable!r})" + ) + # The document names none of the template's controls, so it omits every one. + check( + report is not None and (report.of or 0) > 0 and len(report.omitted) == report.of, + "the publication reports every organization template control the document omits", + ) activation = await typed.activate(published.digest, reason="sdk-python runtime proof") print(f" activate: success={activation.success} activation={activation.activation}") check(activation.success, "activate() promotes the digest") + check( + activation.template_omissions == published.template_omissions, + "the activation reports the same omissions as the publication", + ) print("== the document in force") active = await typed.active() @@ -111,8 +156,18 @@ async def run(client: AxonFlow) -> None: json.loads(active.source) == active.document, "active().source is the signed source the document parses from", ) + # The author is the caller the agent stamped, never the name the request + # carried. On Community that caller is the API client: a Client principal + # in the api-credential realm, named by the client id this proof presents. + stamped = bool(author.get("type")) and bool(author.get("local")) + if edition.constructs is not None and edition.constructs.edition == "community": + stamped = ( + author.get("type") == "Client" + and author.get("qualifier") == "axonflow-api-credential" + and author.get("local") == CLIENT_ID + ) check( - author.get("local") != "someone-else", + stamped and author.get("local") != "someone-else", "the platform signed the caller as author, not the name in the request", ) diff --git a/runtime-e2e/v11_examples/README.md b/runtime-e2e/v11_examples/README.md new file mode 100644 index 0000000..93c0451 --- /dev/null +++ b/runtime-e2e/v11_examples/README.md @@ -0,0 +1,43 @@ +# v11_examples + +Real-stack proof that the two v11 examples run as the README says. `run.sh` copies the package sources to a temporary directory, installs the SDK from there into a virtual environment (so nothing is built inside the tree), checks that the examples' interpreter imports it from that environment, and runs `examples/pep_handshake.py` and `examples/typed_policies.py` with that interpreter against a live Community agent, in the README's order: the handshake example first. Every run starts from the temporary directory, outside the tree, with no body file and no `PYTHONPATH`: `typed_policies.py` finds its default document from its own location. Telemetry is off. Nothing is mocked. + +## Precondition + +Before any run, `curl` asks `GET /api/v1/typed-policies/active` and requires `404` with reason `nothing_active`: no typed document is active. Otherwise the leg stops with exit 2, because it changes the organization's active policy and needs a fresh stack. The check is made outside the SDK, so an SDK regression is never reported as a stale stack. + +## What it proves + +| Run | Expected | +|---|---| +| 1. `pep_handshake.py` | exits 0; the first decide's verdict is `allow`; the declaration the platform would refuse fails in the client at `/pep_id`, before anything is sent | +| 2. `typed_policies.py` without publishing, the README's default | exits 0; `active()` reads the platform's `nothing_active` as nothing active | +| 3. `typed_policies.py` with `AXONFLOW_TYPED_POLICY_PUBLISH=1` | exits 0; prints the publication's template-omission report before it activates; the document is published and activated | +| 4. `typed_policies.py` asked to publish a document the save-time checks reject | exits 1, printing the platform's typed `422 document_refused`: an example that was asked to publish and could not must not report success | +| 5. `typed_policies.py` publishing the same document again | the publication is accepted, and the activation is refused as a typed `409 activation_refused`; exits 1, since an example asked to activate and refused must not report success either | +| 6. `pep_handshake.py` again, after the activation | printed as an observation, not asserted (below) | + +Run 4 publishes a copy of `tests/fixtures/typed_policy_publish_body.json` with one action the registry does not contain (the same edit `runtime-e2e/typed_policies` makes), written to the temporary directory. It is refused before anything is admitted, so it changes nothing on the stack. + +Run 5 is refused because activation promotes. An artifact's digest covers its publication time, so publishing the same document again produces a new artifact, but its document version is the active one's, and a version that does not advance is not promoted. + +## Why the sixth run is an observation + +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. From v11.0.0 the deny's first reason is that code, followed by one naming each constraint it could not evaluate and the attribute it needed (getaxonflow/axonflow-enterprise#4247). The example's default document is such a document, so the sixth run shows that deny. It is the platform's by-design answer, not the SDK's, so this leg prints it rather than pinning it. It is why the README runs the handshake example first. + +A stack built before getaxonflow/axonflow-enterprise#4247 shows only the bare `["unknown_constraint"]`. + +## What it does not prove + +- **That the handshake reaches the wire.** A fresh Community stack allows the first decide with or without a declaration, and the `/pep_id` refusal happens in the client. The wire proof is `runtime-e2e/pep_handshake_planes`. +- **That the organization carries no other state.** The precondition proves no typed document is active. A recorded detection override, or a legacy per-policy override on a platform that still accepts them, would still apply. And while getaxonflow/axonflow-enterprise#4255 is open, an unreadable document store also answers `nothing_active`. + +## Run + +Community on the application database role, on a fresh stack: + +``` +AXONFLOW_AGENT_URL=http://localhost:8080 ./runtime-e2e/v11_examples/run.sh +``` + +It leaves `AXONFLOW_CLIENT_ID` and `AXONFLOW_CLIENT_SECRET` unset, so the examples present the client id `community`, and on Community the organization is the deployment's (`ORG_ID`). `PYTHON` names the interpreter the virtual environment is built from (default `python3`; 3.10 or later), and installing the SDK needs its dependencies from the package index. It exits 0 when every assertion passes, 1 when one fails, and 2 when `timeout` (GNU coreutils) or a suitable Python is not installed, a virtual environment cannot be built, the agent is not reachable, or a typed document is already active. It changes the organization's active policy. diff --git a/runtime-e2e/v11_examples/run.sh b/runtime-e2e/v11_examples/run.sh new file mode 100755 index 0000000..77f6af6 --- /dev/null +++ b/runtime-e2e/v11_examples/run.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# Runtime proof: examples/pep_handshake.py and examples/typed_policies.py, +# against the SDK built from this tree, on a LIVE Community agent, in the order +# the README gives: the handshake example first. NO mocks. The package sources +# are copied to a temporary directory, so nothing is built inside the tree, and +# installed from there into a virtual environment; every example runs with that +# interpreter from the temporary directory, outside the tree, with no body file +# and no PYTHONPATH: typed_policies finds its default document from its own +# location. +# +# Precondition, checked with curl rather than the SDK: no typed document is +# active (GET /api/v1/typed-policies/active answers 404 nothing_active). +# Otherwise the leg stops with exit 2: it changes the organization's active +# policy, so it needs a fresh stack. +# +# 1. pep_handshake: exits 0, the first decide is allowed, and the declaration +# the platform would refuse fails in the client at /pep_id, before +# anything is sent. +# 2. typed_policies without publishing (the README's default): exits 0, and +# active() reads the platform's nothing_active as nothing active. +# 3. typed_policies with AXONFLOW_TYPED_POLICY_PUBLISH=1: exits 0, prints the +# publication's template-omission report BEFORE it activates, and the +# document is published and activated. +# 4. typed_policies asked to publish a document the save-time checks reject: +# exits 1, printing the platform's typed 422 document_refused. +# 5. typed_policies publishing the same document again: the publication is a +# new artifact of the same document version, so the activation is refused +# (a typed 409 activation_refused, since activation promotes), and the +# example exits 1. +# 6. pep_handshake again: printed as an OBSERVATION, not asserted. After run +# 3 activates a document with an organization-scope constraint, a decide +# that does not supply the attribute the constraint conditions on is +# denied fail-closed with reasons ["unknown_constraint"]. From v11.0.0 the +# deny's first reason is that code, followed by one naming each constraint +# it could not evaluate and the attribute it needed +# (getaxonflow/axonflow-enterprise#4247). +# +# Credentials are left unset, so the examples present the client id +# "community", and on Community the organization is the deployment's. +# +# AXONFLOW_AGENT_URL=http://localhost:8080 ./runtime-e2e/v11_examples/run.sh +# +# PYTHON names the interpreter the virtual environment is built from (default +# python3; the SDK needs 3.10 or later). +# +# Exit codes: 0 all proofs passed; 1 a proof failed; 2 timeout or a suitable +# Python is not installed, a virtual environment cannot be built, the agent is +# not reachable, or a typed document is already active. +set -uo pipefail +command -v timeout > /dev/null || { echo "FAIL: this leg needs timeout (GNU coreutils; on macOS: brew install coreutils)"; exit 2; } +PYTHON="${PYTHON:-python3}" +"$PYTHON" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' 2> /dev/null || { + echo "FAIL: $PYTHON is not Python 3.10 or later; set PYTHON" + exit 2 +} +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +ENDPOINT="${AXONFLOW_AGENT_URL:-http://localhost:8080}" +unset AXONFLOW_CLIENT_ID AXONFLOW_CLIENT_SECRET PYTHONPATH +export AXONFLOW_AGENT_URL="$ENDPOINT" AXONFLOW_TELEMETRY=off + +if ! timeout 60 bash -c "until curl -sf --max-time 5 ${ENDPOINT}/health > /dev/null; do sleep 2; done"; then + echo "FAIL: agent at ${ENDPOINT} did not become healthy within 60s" + exit 2 +fi + +OUT="$(mktemp -d "${TMPDIR:-/tmp}/v11-examples.XXXXXX")" +trap 'rm -rf "$OUT"' EXIT +# The SDK is built and installed first, outside the timeouts, so a cold install +# does not count against a run. It is built from a copy of the package sources, +# so no build directory is left in the tree and nothing an earlier build left +# there can ship in what this leg tests. +mkdir "$OUT/src" && cp -R "$ROOT/pyproject.toml" "$ROOT/README.md" "$ROOT/LICENSE" "$ROOT/axonflow" "$OUT/src/" || { + echo "FAIL: could not copy this tree's package sources" + exit 1 +} +"$PYTHON" -m venv "$OUT/venv" || { + echo "FAIL: $PYTHON could not build a virtual environment" + exit 2 +} +"$OUT/venv/bin/python" -m pip install --quiet --disable-pip-version-check "$OUT/src" || { + echo "FAIL: the SDK did not install from this tree's sources" + exit 1 +} +# Where the examples' interpreter imports the SDK from, asked the way the +# examples run: from $OUT, with $ROOT/examples first on sys.path (a script's own +# directory) and no PYTHONPATH. It must be the virtual environment, compared as +# real paths: on macOS the default TMPDIR is behind a symlink. +installed=$(cd "$OUT" && "$OUT/venv/bin/python" -c 'import os, sys; sys.path[0] = sys.argv[1]; import axonflow; print(os.path.realpath(os.path.dirname(axonflow.__file__)))' "$ROOT/examples") || { + echo "FAIL: the installed SDK does not import" + exit 1 +} +echo "installed: $installed" +case "$installed" in + "$(cd "$OUT" && pwd -P)/venv/"*) ;; + *) echo "FAIL: the examples would import the SDK from $installed, not the virtual environment"; exit 1 ;; +esac + +echo "=== precondition: no typed document is active" +code=$(curl -s --max-time 10 -o "$OUT/active.json" -w '%{http_code}' "${ENDPOINT}/api/v1/typed-policies/active") +reason=$("$PYTHON" -c 'import json,sys; print(json.load(open(sys.argv[1])).get("reason",""))' "$OUT/active.json" 2> /dev/null || true) +if [ "$code" != 404 ] || [ "$reason" != nothing_active ]; then + echo "FAIL: a typed document is already active, or the route did not answer nothing_active (HTTP $code, reason '$reason'): run this leg on a fresh stack" + exit 2 +fi +echo "ok: HTTP 404 nothing_active" + +FAILURES=0 +check() { + if [ "$1" = ok ]; then echo "PASS: $2"; else echo "FAIL: $2"; FAILURES=$((FAILURES + 1)); fi +} +# Runs one example with the installed SDK, from $OUT, outside the tree, with +# extra environment, prints its output, and returns its exit code. +run_example() { + local example=$1 log=$2 + shift 2 + (cd "$OUT" && env -u PYTHONPATH "$@" timeout 120 "$OUT/venv/bin/python" "$ROOT/examples/$example.py") > "$log" 2>&1 + local rc=$? + sed 's/^/ | /' "$log" + return "$rc" +} + +echo "=== 1. pep_handshake on a fresh stack" +rc=0; run_example pep_handshake "$OUT/1.log" || rc=$? +check "$([ "$rc" = 0 ] && echo ok)" "pep_handshake exits 0 (exit $rc)" +# The verdict of the first decide, the one under the client's declaration. +first=$(awk '/^=== decide with the client.s declaration ===/ {f = 1; next} + f && /^verdict=/ {sub(/ .*/, ""); print; exit} + f && /^===/ {exit}' "$OUT/1.log") +check "$([ "$first" = verdict=allow ] && echo ok)" "the first decide is allowed on a fresh stack ($first)" +check "$(grep -q '^refused at /pep_id: ' "$OUT/1.log" && echo ok)" \ + "the declaration the platform would refuse fails in the client, at /pep_id, before anything is sent" + +echo "=== 2. typed_policies without publishing, as the README runs it" +rc=0; run_example typed_policies "$OUT/2.log" || rc=$? +check "$([ "$rc" = 0 ] && echo ok)" "typed_policies exits 0 without publishing (exit $rc)" +check "$(grep -qx 'nothing is active' "$OUT/2.log" && echo ok)" \ + "active() reads the platform's nothing_active as nothing active" + +echo "=== 3. typed_policies with AXONFLOW_TYPED_POLICY_PUBLISH=1, as the README runs it" +rc=0; run_example typed_policies "$OUT/3.log" AXONFLOW_TYPED_POLICY_PUBLISH=1 || rc=$? +check "$([ "$rc" = 0 ] && echo ok)" "typed_policies exits 0 (exit $rc)" +omissions=$(grep -n -m1 '^template omissions: ' "$OUT/3.log" | cut -d: -f1) +activated=$(grep -n -m1 -x 'activated' "$OUT/3.log" | cut -d: -f1) +check "$([ -n "$omissions" ] && [ -n "$activated" ] && [ "$omissions" -lt "$activated" ] && echo ok)" \ + "it prints the publication's template-omission report before it activates" +check "$([ -n "$activated" ] && echo ok)" "the document is published and activated" + +echo "=== 4. typed_policies asked to publish a document the save-time checks reject" +# The vendored body with one action the registry does not contain: the same +# edit runtime-e2e/typed_policies makes to it. +"$PYTHON" - "$ROOT/tests/fixtures/typed_policy_publish_body.json" "$OUT/refused_body.json" << 'PY' || { echo "FAIL: could not write the refused body"; exit 1; } +import json, sys +body = json.load(open(sys.argv[1])) +body["document"]["metadata"]["document_id"] = "v11-examples-refused" +body["document"]["policy"]["policies"][0]["actions"]["actions"][0]["local"] = "tool.not_registered" +json.dump(body, open(sys.argv[2], "w")) +PY +rc=0; run_example typed_policies "$OUT/4.log" \ + AXONFLOW_TYPED_POLICY_PUBLISH=1 AXONFLOW_TYPED_POLICY_BODY="$OUT/refused_body.json" || rc=$? +check "$([ "$rc" = 1 ] && echo ok)" "typed_policies exits 1 when the publication it asked for is refused (exit $rc)" +check "$(grep -q '^refused: HTTP 422 document_refused: ' "$OUT/4.log" && echo ok)" \ + "it prints the platform's typed 422 document_refused" + +echo "=== 5. typed_policies publishing the same document again" +rc=0; run_example typed_policies "$OUT/5.log" AXONFLOW_TYPED_POLICY_PUBLISH=1 || rc=$? +check "$([ "$rc" = 1 ] && echo ok)" "typed_policies exits 1 when the activation it asked for is refused (exit $rc)" +check "$(grep -q '^published ' "$OUT/5.log" && echo ok)" \ + "the second publication is accepted: a new artifact of the same document version" +check "$(grep -q '^activation refused: HTTP 409 activation_refused: ' "$OUT/5.log" && echo ok)" \ + "it prints the platform's typed 409 activation_refused" + +echo "=== 6. OBSERVATION, not asserted: pep_handshake after the activation" +run_example pep_handshake "$OUT/6.log" || true +echo " observed: $(grep -m1 -oE '^verdict=.*' "$OUT/6.log" || echo 'no verdict printed')" + +if [ "$FAILURES" -gt 0 ]; then + echo + echo "FAIL: v11_examples ($FAILURES assertion(s))" + exit 1 +fi +echo +echo "PASS: v11_examples" diff --git a/tests/test_legacy_deprecations.py b/tests/test_legacy_deprecations.py index 7888296..b3c3add 100644 --- a/tests/test_legacy_deprecations.py +++ b/tests/test_legacy_deprecations.py @@ -2,11 +2,12 @@ A v11 platform stamps every response from its deprecated policy surface, and the client reports each stamped route ONCE per client through -``PlatformRouteDeprecationWarning``, as the TypeScript and Go SDKs do: keyed by -method and path without the query string, and shared with clients derived through -``as_user``. The stamp below is exactly what the platform's -``policypath.StampDeprecation`` writes at 857455033, with the header names as Go -canonicalises them (as a live capture showed): ``X-Axonflow-Removed-In`` and +``PlatformRouteDeprecationWarning``: keyed by method and route (for a path that +carries an id, the route template it was built from; otherwise the path without +the query string), and shared with clients derived through ``as_user``. The +stamp below is exactly what the platform's ``policypath.StampDeprecation`` +writes at 857455033, with the header names as Go canonicalises them (as a live +capture showed): ``X-Axonflow-Removed-In`` and the successor ``Link``, with ``Deprecation`` omitted until release prep sets the tag date. @@ -16,10 +17,13 @@ from __future__ import annotations +import re import warnings from collections.abc import Iterator -from contextlib import contextmanager +from contextlib import contextmanager, suppress +from pathlib import Path +import httpx import pytest from axonflow import ( @@ -28,7 +32,13 @@ LegacyPolicyWriteFrozenError, PlatformRouteDeprecationWarning, ) -from axonflow.policies import CreatePolicyOverrideRequest, ListStaticPoliciesOptions, OverrideAction +from axonflow.policies import ( + CreatePolicyOverrideRequest, + ListStaticPoliciesOptions, + OverrideAction, + UpdateDynamicPolicyRequest, + UpdateStaticPolicyRequest, +) BASE = "https://test.axonflow.com" STATIC = f"{BASE}/api/v1/static-policies" @@ -132,7 +142,7 @@ async def test_a_refused_stamped_request_is_still_reported_once( for _ in range(2): with pytest.raises(AxonFlowError): await client.get_static_policy("pol_missing") - assert [w.route for w in found] == ["GET /api/v1/static-policies/pol_missing"] + assert [w.route for w in found] == ["GET /api/v1/static-policies/{id}"] def test_the_sync_client_reports_once(self, sync_client, httpx_mock) -> None: stamped_list(httpx_mock, calls=2) @@ -142,6 +152,158 @@ def test_the_sync_client_reports_once(self, sync_client, httpx_mock) -> None: assert len(found) == 1 +# The route templates of the eleven methods that reach a deprecated route with an +# id, in the order TestOncePerTemplate calls them, with the method each sends. +ID_BEARING_CALLS = [ + ("GET", "/api/v1/static-policies/{id}"), + ("PUT", "/api/v1/static-policies/{id}"), + ("DELETE", "/api/v1/static-policies/{id}"), + ("PATCH", "/api/v1/static-policies/{id}"), + ("GET", "/api/v1/static-policies/{id}/versions"), + ("POST", "/api/v1/static-policies/{id}/override"), + ("DELETE", "/api/v1/static-policies/{id}/override"), + ("GET", "/api/v1/dynamic-policies/{id}"), + ("PUT", "/api/v1/dynamic-policies/{id}"), + ("DELETE", "/api/v1/dynamic-policies/{id}"), + ("PUT", "/api/v1/dynamic-policies/{id}"), +] + +# The platform's deprecated families (policypath.DeprecatedFamilies at 857455033). +FAMILIES = ( + "static-policies", + "system-policies", + "dynamic-policies", + "tenant-policies", + "policies", + "templates", + "policy-overrides", +) +_FAMILY = "(" + "|".join(FAMILIES) + ")" +# A path on a family built with a value after the family: an f-string +# interpolation, a concatenation, %-formatting or str.format. +BUILT = [ + re.compile(r"""[fF]["'][^"']*/api/v1/""" + _FAMILY + r"""/[^"']*\{"""), + re.compile(r"""["']/api/v1/""" + _FAMILY + r"""/[^"']*["']\s*\+"""), + re.compile(r"""["']/api/v1/""" + _FAMILY + r"""/[^"']*%[sd]"""), + re.compile(r"""["']/api/v1/""" + _FAMILY + r"""/[^"']*\{[^"']*["']\.format\("""), +] +TEMPLATE = re.compile(r"""(? None: + for policy_id in ("pol_1", "pol_2"): + httpx_mock.add_response( + method="GET", + url=f"{STATIC}/{policy_id}", + status_code=404, + json={"error": "not found"}, + headers=STAMP, + ) + httpx_mock.add_response( + method="DELETE", + url=f"{STATIC}/{policy_id}/override", + status_code=204, + headers=STAMP, + ) + with reports() as found: + for policy_id in ("pol_1", "pol_2"): + with pytest.raises(AxonFlowError): + await client.get_static_policy(policy_id) + await client.delete_policy_override(policy_id) + assert [w.route for w in found] == [ + "GET /api/v1/static-policies/{id}", + "DELETE /api/v1/static-policies/{id}/override", + ] + + @pytest.mark.asyncio + async def test_every_id_bearing_method_reports_its_template_once( + self, client: AxonFlow, httpx_mock + ) -> None: + # Each method is called with two ids. The server must receive each + # call's own request, with the id in its path, so a method that shares + # its template with another (toggle_dynamic_policy and + # update_dynamic_policy are both PUT /api/v1/dynamic-policies/{id}) is + # seen to send; and the ten templates are each reported once. + served: list[tuple[str, str]] = [] + + def answer(request: httpx.Request) -> httpx.Response: + served.append((request.method, request.url.path)) + return httpx.Response(404, json={"error": "not found"}, headers=STAMP) + + httpx_mock.add_callback(answer, is_reusable=True) + override = CreatePolicyOverrideRequest( + action_override=OverrideAction.WARN, override_reason="migration" + ) + with reports() as found: + for policy_id in ("x", "y"): + calls = ( + client.get_static_policy(policy_id), + client.update_static_policy(policy_id, UpdateStaticPolicyRequest()), + client.delete_static_policy(policy_id), + client.toggle_static_policy(policy_id, enabled=True), + client.get_static_policy_versions(policy_id), + client.create_policy_override(policy_id, override), + client.delete_policy_override(policy_id), + client.get_dynamic_policy(policy_id), + client.update_dynamic_policy(policy_id, UpdateDynamicPolicyRequest()), + client.delete_dynamic_policy(policy_id), + client.toggle_dynamic_policy(policy_id, enabled=True), + ) + for call in calls: + # The 404 is refused; what is asserted is what was sent and reported. + with suppress(AxonFlowError): + await call + assert served == [ + (method, template.replace("{id}", policy_id)) + for policy_id in ("x", "y") + for method, template in ID_BEARING_CALLS + ] + assert sorted(w.route for w in found) == sorted( + {f"{method} {template}" for method, template in ID_BEARING_CALLS} + ) + + def test_no_id_bearing_path_is_built_outside_its_template(self) -> None: + # A source census over the platform's seven deprecated families: no path + # on them is built with a value after the family, so every id-bearing + # call names its {id} template and passes the id as path_id, and the + # client builds the path from the template. A new call site therefore + # cannot report once per id. Its blind spot: a path assembled another way + # (a join, a list of parts) is not seen. + for family in FAMILIES: + for planted in ( + f'f"/api/v1/{family}/{{policy_id}}"', + f'"/api/v1/{family}/" + policy_id', + f'"/api/v1/{family}/%s" % policy_id', + f'"/api/v1/{family}/{{}}".format(policy_id)', + ): + assert any(r.search(planted) for r in BUILT), f"the census misses {planted}" + for unbuilt in ( + '"/api/v1/static-policies"', + '"/api/v1/static-policies/{id}", path_id=policy_id', + ): + assert not any(r.search(unbuilt) for r in BUILT), f"the census counts {unbuilt}" + package = Path(__file__).resolve().parents[1] / "axonflow" + built, templates = [], 0 + for source in sorted(package.rglob("*.py")): + for number, line in enumerate(source.read_text().splitlines(), 1): + if any(r.search(line) for r in BUILT): + built.append(f"{source.name}:{number}") + templates += len(TEMPLATE.findall(line)) + assert built == [], ( + f"a deprecated route's path built with an id outside its template: {built}" + ) + assert templates == len(ID_BEARING_CALLS), ( + f"found {templates} id-bearing templates, want {len(ID_BEARING_CALLS)}: " + "a new one updates ID_BEARING_CALLS" + ) + + class TestTheDocumentedDeprecations: @pytest.mark.parametrize( ("method", "route"), diff --git a/tests/test_typed_policies.py b/tests/test_typed_policies.py index 97d1f5a..cb06f5b 100644 --- a/tests/test_typed_policies.py +++ b/tests/test_typed_policies.py @@ -8,6 +8,7 @@ from __future__ import annotations +import importlib.util import json from pathlib import Path @@ -152,6 +153,147 @@ async def test_nothing_active_is_none(self, httpx_mock): ) assert await _client().typed_policies.active() is None + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("answer", "reason"), + [ + ({"content": b"404 page not found"}, None), + ( + {"json": {"success": False, "reason": "no_such_endpoint", "error": "no route"}}, + "no_such_endpoint", + ), + ], + ids=["plain-text", "another-reason"], + ) + async def test_a_404_that_is_not_nothing_active_is_a_typed_refusal( + self, httpx_mock, answer, reason + ): + # A platform before v11.0.0, or an endpoint that is not an agent, is not + # "nothing active". + httpx_mock.add_response(url=f"{ROUTE}/active", status_code=404, **answer) + with pytest.raises(TypedPolicyRefusal) as caught: + await _client().typed_policies.active() + assert (caught.value.status, caught.value.reason) == (404, reason) + + @pytest.mark.asyncio + async def test_the_edition_names_its_vocabulary(self, httpx_mock): + httpx_mock.add_response( + url=f"{ROUTE}/edition", + json={ + "success": True, + "catalog": "deployment", + "catalog_digest": "sha256:vocabulary", + "registry_version": 2, + "catalog_fixture": True, + }, + ) + edition = await _client().typed_policies.edition() + assert (edition.catalog_digest, edition.registry_version, edition.catalog_fixture) == ( + "sha256:vocabulary", + 2, + True, + ) + + @pytest.mark.asyncio + async def test_the_publication_carries_the_template_omission_report(self, httpx_mock): + httpx_mock.add_response( + url=f"{ROUTE}/publish", + json={ + "success": True, + "digest": DIGEST, + "version": 1, + "findings": [], + "template_omissions": { + "omitted": ["sys_a", "sys_b"], + "of": 22, + "message": "omits 2 of 22", + }, + }, + ) + published = await _client().typed_policies.publish(DOCUMENT, FIXTURES) + report = published.template_omissions + assert report is not None + assert (report.omitted, report.of, report.message) == ( + ["sys_a", "sys_b"], + 22, + "omits 2 of 22", + ) + assert published.template_omissions_unavailable is None + + @pytest.mark.asyncio + async def test_a_publication_whose_omission_report_is_unavailable_says_why(self, httpx_mock): + httpx_mock.add_response( + url=f"{ROUTE}/publish", + json={ + "success": True, + "digest": DIGEST, + "version": 1, + "template_omissions_unavailable": "the organization template could not be read", + }, + ) + published = await _client().typed_policies.publish(DOCUMENT, FIXTURES) + assert published.template_omissions is None + assert published.template_omissions_unavailable == ( + "the organization template could not be read" + ) + + @pytest.mark.asyncio + async def test_the_activation_carries_the_omission_report_beside_the_record(self, httpx_mock): + httpx_mock.add_response( + url=f"{ROUTE}/activate", + json={ + "success": True, + "activation": {"digest": DIGEST}, + "template_omissions": {"omitted": ["sys_a"], "of": 22, "message": "omits 1 of 22"}, + }, + ) + activation = await _client().typed_policies.activate(DIGEST) + report = activation.template_omissions + assert report is not None + assert (report.omitted, report.of, report.message) == (["sys_a"], 22, "omits 1 of 22") + assert activation.template_omissions_unavailable is None + assert "template_omissions" not in activation.activation + + @pytest.mark.asyncio + async def test_an_activation_whose_omission_report_is_unavailable_says_why(self, httpx_mock): + httpx_mock.add_response( + url=f"{ROUTE}/activate", + json={ + "success": True, + "activation": {"digest": DIGEST}, + "template_omissions_unavailable": "the organization template could not be read", + }, + ) + activation = await _client().typed_policies.activate(DIGEST) + assert activation.template_omissions is None + assert activation.template_omissions_unavailable == ( + "the organization template could not be read" + ) + + @pytest.mark.asyncio + async def test_a_system_control_names_itself_and_is_not_mandatory_when_unsaid(self, httpx_mock): + httpx_mock.add_response( + url=f"{ROUTE}/system", + json={ + "success": True, + "system": { + "controls": [ + {"id": "sys.a", "name": "Block DROP TABLE", "mandatory": True}, + {"id": "sys.b"}, + {"id": "sys.c", "mandatory": None}, + ] + }, + }, + ) + system = await _client().typed_policies.system() + # Compared by value against False, so a drift back to None fails here. + assert [(c.id, c.name, c.mandatory) for c in system.controls] == [ + ("sys.a", "Block DROP TABLE", True), + ("sys.b", None, False), + ("sys.c", None, False), + ] + assert all(isinstance(c.mandatory, bool) for c in system.controls) + @pytest.mark.asyncio async def test_system(self, httpx_mock): httpx_mock.add_response( @@ -212,7 +354,7 @@ def _refusal(status, reason, **extra): pytest.param( "publish", 402, - _refusal(402, "tier_limit", code="ERR_TIER_LIMIT_ORG_ROOT_POLICY"), + _refusal(402, "tier_limit", code="ERR_TIER_LIMIT_ORG_ROOT_POLICY", policy="grant.refund"), {}, id="publish-402-tier-limit", ), @@ -258,6 +400,9 @@ async def test_every_documented_refusal_is_typed( body["reason"], body.get("code"), ) + # A tier refusal names the policy that crossed the ceiling; an outage + # refusal (with Retry-After) names none. + assert refusal.policy == body.get("policy") assert refusal.message == body["error"] assert [f.code for f in refusal.findings] == [f["code"] for f in body.get("findings", [])] assert refusal.retry_after == (int(headers["Retry-After"]) if headers else None) @@ -335,6 +480,24 @@ async def test_a_success_whose_body_is_not_an_object_is_an_error(self, httpx_moc ([], {}, {}), id="system-corpus", ), + pytest.param( + "publish", + {"success": True, "digest": DIGEST, "template_omissions": None}, + lambda r: r.template_omissions, + None, + id="publish-template-omissions", + ), + pytest.param( + "publish", + { + "success": True, + "digest": DIGEST, + "template_omissions": {"omitted": None, "of": 22, "message": "m"}, + }, + lambda r: r.template_omissions.omitted, + [], + id="publish-template-omissions-omitted", + ), ] @@ -370,3 +533,18 @@ def test_a_derived_client_gets_its_own_namespace_bound_to_itself(self): derived = parent.as_user("user-token") assert derived.typed_policies is not parent_namespace assert derived.typed_policies._send.__self__ is derived + + +class TestTheExample: + def test_the_example_finds_its_default_body_from_its_own_location(self): + # examples/typed_policies.py runs from any directory: its default body is + # found from the file's own location, and it is the vendored fixture. + path = Path(__file__).resolve().parents[1] / "examples" / "typed_policies.py" + spec = importlib.util.spec_from_file_location("typed_policies_example", path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + fixture = Path(__file__).resolve().parent / "fixtures" / "typed_policy_publish_body.json" + assert fixture == module.DEFAULT_BODY + assert module.DEFAULT_BODY.is_file()