diff --git a/CHANGELOG.md b/CHANGELOG.md index f37c5af1..6c650266 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Provide explicit configuration, discovery, and full runtime assemblies. The default profile supports in-memory execution from installed Python, TypeScript, and Rust packages. - Add the pure TypeScript Prometheus text renderer and host-owned subscriber factories for configured event delivery. +- **Protocol 2.0.0 draft revision 2.** Add opt-in policy evaluation after input validation. The enabled pipeline combines approval requirements at one gate, binds approval to the selected module version and effective arguments, and enforces the gate before ordinary and streaming execution. Final-scope pending approvals require an explicitly compatible scoped handler. ### Changed diff --git a/conformance/README.md b/conformance/README.md index e146ee52..1ecb5d9b 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -69,6 +69,7 @@ declared extension. Adapter wire projections are verified in Surfaces. | `stream_completion.json` | SDK streaming completion | One invocation reports its canonical output, individual post-processing outcomes, and termination through the opt-in stream handle | | `approval_gate.json` | A05 | Approval gate Step 5: explicit compatibility policy, result-status outcomes, and scoped resumption | | `core_profile_governance.json` | §7.4, §7.9 | Core Profile defaults and explicit overrides through public preflight and execution, including an injected Executor | +| `post_validation_policy.json` | §7.4.1 | Opt-in policy evaluation, validated input approval binding, preflight, scoped resumption and zero stream starts on rejection | | `approval_request_fields.json` | D-03 | `ApprovalRequest` carries `caller_id` (null for a top-level call) and `action` (= `module_id`) — fields the Contract text already required and no SDK's `ApprovalRequest` carried | | `preflight_disclosure.json` | §12.8.5.1 | `Executor.validate()` withholds module-level introspection from a caller the ACL denied: no `module_preflight` / `module_preview` check, empty `predicted_changes`, and the hooks themselves not invoked. Module lookup is Step 3 and the ACL check is Step 4, so all three SDKs gated these hooks on "lookup succeeded" alone and ran module-authored code for a denied caller. Scoped to AUTHORIZATION: a failed `schema` check does **not** suppress introspection. Drivers MUST run the real `validate()` against a real Registry and ACL, and MUST observe hook invocation from inside the hook bodies — see `driver_contract` | | `middleware_on_error_recovery.json` | A11 | After-middleware error recovery: first-dict-wins, null passthrough, success non-override | diff --git a/conformance/fixtures/post_validation_policy.json b/conformance/fixtures/post_validation_policy.json new file mode 100644 index 00000000..ecd9cd57 --- /dev/null +++ b/conformance/fixtures/post_validation_policy.json @@ -0,0 +1,84 @@ +{ + "description": "Exercise the opted-in post-validation policy through the public Executor call, preflight, stream and scoped resumption paths.", + "driver_contract": { + "module_id": "demo.policy", + "module_version": "1.2.3", + "business_input": {"amount": 10, "secret": "private-fixture-value"}, + "input_schema": { + "type": "object", + "properties": { + "amount": {"type": "integer"}, + "secret": {"type": "string", "x-sensitive": true} + }, + "required": ["amount", "secret"], + "additionalProperties": false + }, + "notes": "Apply per-case input overrides. If configured, before middleware substitutes rewrite_amount. For resume, the handler first returns pending, then compares the full approval scope and atomically consumes the matching credential. Retry the original business inputs with _approval_token and any retry overrides. Counts include both traversals. For preflight, read the policy check or requires_approval in the public report. Count starts on module execute and on the stream producer. Spy requests must observe the real version, an argument snapshot without the credential, and /secret in sensitive_fields." + }, + "test_cases": [ + { + "id": "unary_uses_the_validated_middleware_result", + "entry": "call", + "rewrite_amount": 20, + "verdict": "allow", + "expected": {"module_starts": 1, "evaluated_amount": 20, "approval_requests": 0} + }, + { + "id": "both_requirements_use_one_final_approval", + "entry": "call", + "requires_approval": true, + "rewrite_amount": 20, + "verdict": "require_approval", + "expected": {"module_starts": 1, "evaluated_amount": 20, "approval_requests": 1, "approved_amount": 20} + }, + { + "id": "allow_preserves_the_early_approval_requirement", + "entry": "call", + "requires_approval": true, + "rewrite_amount": 20, + "verdict": "allow", + "expected": {"module_starts": 1, "evaluated_amount": 20, "approval_requests": 1, "approved_amount": 20} + }, + { + "id": "preflight_reports_approval_without_prompting", + "entry": "preflight", + "rewrite_amount": 20, + "verdict": "require_approval", + "expected": {"module_starts": 0, "evaluated_amount": 10, "approval_requests": 0, "requires_approval": true} + }, + { + "id": "denied_stream_does_not_start_its_producer", + "entry": "stream", + "verdict": "deny", + "expected": {"module_starts": 0, "evaluated_amount": 10, "approval_requests": 0, "error_code": "POLICY_DENIED"} + }, + { + "id": "provider_fault_fails_closed", + "entry": "call", + "verdict": "throw", + "expected": {"module_starts": 0, "evaluated_amount": 10, "approval_requests": 0, "error_code": "POLICY_EVALUATION_ERROR"} + }, + { + "id": "schema_rejection_prevents_policy_disclosure", + "entry": "call", + "inputs": {"amount": "invalid"}, + "verdict": "allow", + "expected": {"module_starts": 0, "evaluated_amount": null, "approval_requests": 0} + }, + { + "id": "resume_consumes_one_credential_for_final_inputs", + "entry": "resume", + "requires_approval": true, + "rewrite_amount": 20, + "verdict": "require_approval", + "expected": {"module_starts": 1, "evaluated_amount": 20, "approval_requests": 1, "approved_amount": 20, "resume_checks": 1} + }, + { + "id": "resume_rejects_changed_effective_inputs", + "entry": "resume", + "verdict": "require_approval", + "retry_inputs": {"amount": 20}, + "expected": {"module_starts": 0, "evaluated_amount": 20, "approval_requests": 1, "approved_amount": 10, "resume_checks": 1, "error_code": "APPROVAL_DENIED"} + } + ] +} diff --git a/docs/architecture.md b/docs/architecture.md index 0104e888..d7db4163 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -449,7 +449,7 @@ my-project/ ## 5. Extension Points -apcore provides a formal `ExtensionManager` API for managing pluggable extension points. The six built-in extension points are: `discoverer`, `middleware`, `acl`, `span_exporter`, `module_validator`, and `approval_handler`. +apcore provides `ExtensionManager` for pluggable extension points. The built-in points are `discoverer`, `middleware`, `acl`, `span_exporter`, `module_validator`, `approval_handler`, and `policy_evaluator`. ### 5.1 ExtensionManager API diff --git a/docs/features/approval-system.md b/docs/features/approval-system.md index fc9b273c..2e631f22 100644 --- a/docs/features/approval-system.md +++ b/docs/features/approval-system.md @@ -10,7 +10,7 @@ description: "Approval gate at Executor Step 5: fires on the governance union, p ## Overview -The Approval System decides whether a particular invocation needs sign-off before it runs, and asks an `ApprovalHandler` for that sign-off at **Step 5** of the execution pipeline — after ACL enforcement (Step 4) and before the Middleware Before Chain (Step 6). +The Approval System decides whether a particular invocation needs sign-off before it runs. By default, the Executor asks an `ApprovalHandler` for sign-off at **Step 5**, after ACL enforcement and before before middleware. The gate considers the module's own flags, the registry's declared annotations, the platform's execution policy, and the [ACL decision](./acl-system.md) for the invocation. [Execution Policy](#execution-policy) defines how these sources combine. @@ -48,6 +48,23 @@ An exception raised by the handler itself propagates unchanged; it is not conver To observe which parts of the gate are live on an executor, read [`governance_state()`](./core-executor.md#governance-state-api) — `builtin_approval_gate_wired`, `approval_handler_configured` and `policy_strict` are reported separately ([PROTOCOL_SPEC §6.6.5](../spec/protocol-spec.md#665-governance-state-query)). `Executor.validate()` reports the governance-effective `requires_approval` for a call, the same verdict the gate will enforce (§7.9.5). +### Policy on validated execution arguments + +A host can install a `PolicyEvaluator` on an Executor directly or through the +`policy_evaluator` extension point. The evaluator can allow the call, deny it, or +require approval. It receives the selected module version and detached inputs +after before middleware and validation. With this extension enabled, the +Executor combines the existing and evaluator approval requirements and asks the +handler once for the actual execution inputs. Before middleware in this assembly +performs trusted transformations without approval-dependent side effects. + +Preflight evaluates its own validated inputs and reports approval requirements. +The actual call evaluates again before dispatch. A denied policy blocks ordinary +execution and stream startup. A final-scope pending credential can be resumed +only through a handler that advertises final-scope support and checks the +principal, caller, target, selected version, and argument digest. See the +[post-validation policy contract](../spec/protocol-spec.md#741-post-validation-policy). + ### Startup Approval Report After registering modules and configuring the executor, call its startup report to list module IDs that declare `requires_approval` without an effective built-in approval gate. diff --git a/docs/features/execution-pipeline.md b/docs/features/execution-pipeline.md index 696b15d3..028cb7c7 100644 --- a/docs/features/execution-pipeline.md +++ b/docs/features/execution-pipeline.md @@ -131,6 +131,14 @@ A trace is process-local. `call_with_trace()` returns it; a `PipelineStepError` ### The standard pipeline +An Executor with a `PolicyEvaluator` runs `post_validation_policy` after input +validation and before execution or producer startup. This opt-in gate evaluates +the validated execution snapshot and enforces the combined approval requirement. +Install it with the built-in `standard` or `performance` strategy to retain the +validation and dispatch boundaries it depends on. +The [post-validation policy contract](../spec/protocol-spec.md#741-post-validation-policy) +describes the supported strategy boundary and preflight behavior. + | # | Step | Core | pure | removable | replaceable | What it does | |---|---|---|---|---|---|---| | 1 | `context_creation` | yes | yes | no | no | Create or inherit the execution context; set the global deadline. | diff --git a/docs/features/extension-system.md b/docs/features/extension-system.md index f358ba90..dedaa70f 100644 --- a/docs/features/extension-system.md +++ b/docs/features/extension-system.md @@ -1,5 +1,5 @@ --- -description: "ExtensionManager wiring named extension points (discoverer, middleware, acl, span_exporter, module_validator, approval_handler) into Registry and Executor, with cardinality/type checks." +description: "ExtensionManager wiring named extension points into Registry and Executor, with cardinality and type checks." --- # Extension System @@ -41,6 +41,7 @@ The Extension System provides a pluggable architecture for customizing and exten | `span_exporter` | Yes | SpanExporter protocol | Tracing span exporter | | `module_validator` | No | ModuleValidator protocol | Custom module validation | | `approval_handler` | No | ApprovalHandler protocol | Approval gate handler | +| `policy_evaluator` | No | PolicyEvaluator protocol | Optional policy over validated execution arguments | ### ExtensionPoint @@ -171,8 +172,9 @@ When `apply(registry, executor)` is called, the manager performs the following i 2. **Module Validator** → `registry.set_validator(ext)` — replaces the default module validator. 3. **ACL** → `executor.set_acl(ext)` — replaces the executor's ACL provider. 4. **Approval Handler** → `executor.set_approval_handler(ext)` — replaces the executor's approval handler. -5. **Middleware** → `executor.use(mw)` for each registered middleware — appends to the middleware chain. -6. **Span Exporters** → Locates the `TracingMiddleware` already in the executor's middleware chain and sets its exporter: +5. **Policy Evaluator** → `executor.set_policy_evaluator(ext)` — enables [policy on validated arguments](../spec/protocol-spec.md#741-post-validation-policy). +6. **Middleware** → `executor.use(mw)` for each registered middleware — appends to the middleware chain. +7. **Span Exporters** → Locates the `TracingMiddleware` already in the executor's middleware chain and sets its exporter: - If a single exporter is registered, it is set directly. - If multiple exporters are registered, they are wrapped in a composite exporter that delegates to all of them. A failure in one exporter is logged and does not affect the others. - If the chain has no `TracingMiddleware`, a warning is logged and the exporters are not applied — `apply` does not add one. @@ -272,21 +274,22 @@ Rust, where the manager owns its extensions, that path is ### Inputs - `registry` (Registry, required) — registry to wire extensions into (discoverer, module_validator) -- `executor` (Executor, required) — executor to wire extensions into (acl, approval_handler, middleware, span_exporter) +- `executor` (Executor, required) — executor to wire extensions into (acl, approval_handler, policy_evaluator, middleware, span_exporter) ### Errors - Errors raised by the Registry / Executor setters propagate (Rust: `Err(ModuleError)`, e.g. a rejected middleware). A registered span exporter with no `TracingMiddleware` in the chain is **not** an error: it is logged as a warning and skipped. ### Returns -- On success: void/None/() — all registered extensions wired in the documented order (discoverer → module_validator → acl → approval_handler → middleware chain → span exporters) +- On success: void/None/() — all registered extensions wired in the documented order (discoverer → module_validator → acl → approval_handler → policy_evaluator → middleware chain → span exporters) ### Side Effects (ordered) 1. `registry.set_discoverer(ext)` if discoverer registered 2. `registry.set_validator(ext)` if module_validator registered 3. `executor.set_acl(ext)` if acl registered 4. `executor.set_approval_handler(ext)` if approval_handler registered -5. `executor.use(mw)` for each middleware in registration order -6. Locate `TracingMiddleware` in the executor chain; set a single exporter directly or wrap several in a composite exporter; warn and skip if there is none +5. `executor.set_policy_evaluator(ext)` if policy_evaluator registered +6. `executor.use(mw)` for each middleware in registration order +7. Locate `TracingMiddleware` in the executor chain; set a single exporter directly or wrap several in a composite exporter; warn and skip if there is none ### Postconditions diff --git a/docs/index.md b/docs/index.md index f6e0bffd..2640994c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -24,10 +24,10 @@ A schema makes a capability contract machine-readable and validatable. It does n | Component | Package | Stable | In development | |---|---|---|---| -| Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `2.0.0` (draft) | -| Python SDK | `apcore` | `0.33.0` | `1.0.0a2` | -| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.2` | -| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.2` | +| Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `2.0.0` (draft revision 2) | +| Python SDK | `apcore` | `0.33.0` | `1.0.0a3` | +| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.3` | +| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.3` | The protocol `2.0.0` draft defines the contract for the SDK `1.0.0` release line. The three core SDKs share that release line. Surface adapters (`apcore-mcp`, `apcore-a2a`, `apcore-cli`, `apcore-toolkit`) are versioned independently and declare the core range they support in their package metadata. diff --git a/docs/spec/algorithms.md b/docs/spec/algorithms.md index 84285816..99005483 100644 --- a/docs/spec/algorithms.md +++ b/docs/spec/algorithms.md @@ -1239,7 +1239,7 @@ Steps: |------|------|------| | `manager` | `ExtensionManager` | The registered extensions, keyed by extension point name | | `registry` | `Registry` | Receives `discoverer` and `module_validator` | -| `executor` | `Executor` | Receives `acl`, `approval_handler`, `middleware` and `span_exporter` | +| `executor` | `Executor` | Receives `acl`, `approval_handler`, `policy_evaluator`, `middleware` and `span_exporter` | **Output:** @@ -1263,8 +1263,9 @@ Steps: 2. If manager holds a module_validator → registry.set_validator(it) 3. If manager holds an acl → executor.set_acl(it) 4. If manager holds an approval_handler → executor.set_approval_handler(it) - 5. For each middleware, in registration order → executor.use(it) - 6. If one or more span_exporters are registered → set them (composed into one + 5. If manager holds a policy_evaluator → executor.set_policy_evaluator(it) + 6. For each middleware, in registration order → executor.use(it) + 7. If one or more span_exporters are registered → set them (composed into one exporter when there are several) on the tracing middleware already in the executor's chain; when the chain has none, log a warning and install nothing ``` @@ -1278,7 +1279,7 @@ Steps: **Implementation Notes:** -- The six extension point names are `discoverer`, `middleware`, `acl`, `span_exporter`, `module_validator`, `approval_handler` (protocol-spec §11.3). A single-valued point holds one implementation and a later registration replaces it; `middleware` and `span_exporter` are multi-valued. +- A single-valued point holds one implementation and a later registration replaces it. `middleware` and `span_exporter` are multi-valued. The built-in points are listed in protocol-spec §11.3. - There is no priority ordering among implementations of one point, no `first_success` / `all` / `fallback` strategy, and no registration from `apcore.yaml` (D-143). --- diff --git a/docs/spec/conformance.md b/docs/spec/conformance.md index 09ed7c8e..0bf1f9c1 100644 --- a/docs/spec/conformance.md +++ b/docs/spec/conformance.md @@ -326,7 +326,7 @@ The following requirements are not met by the SDK implementations in this reposi ## 8. Conformance Test Fixtures -The repository ships **98 cross-language fixture files** under `conformance/fixtures/` covering **1229 test cases**. `conformance-integrity` checks these two numbers, §8.1's per-fixture counts and its Total row against the fixtures themselves. Each fixture is consumed by all three SDK test runners (§5.2). An SDK declaring a conformance level **MUST** pass every fixture whose tested feature is required at that level (§5.3). +The repository ships **99 cross-language fixture files** under `conformance/fixtures/` covering **1238 test cases**. `conformance-integrity` checks these two numbers, §8.1's per-fixture counts and its Total row against the fixtures themselves. Each fixture is consumed by all three SDK test runners (§5.2). An SDK declaring a conformance level **MUST** pass every fixture whose tested feature is required at that level (§5.3). ### 8.1 Fixture Inventory @@ -369,6 +369,7 @@ The repository ships **98 cross-language fixture files** under `conformance/fixt | [`error_codes`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/error_codes.json) | 19 | Error code collision detection (Algorithm A17, spec §8.4) | | [`error_details_shape`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/error_details_shape.json) | 5 | `SCHEMA_VALIDATION_ERROR` details items are `{path, keyword, message}` with a JSON Pointer path; `details` keys are snake_case (spec §8.1, D-149) | | [`core_profile_governance`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/core_profile_governance.json) | 8 | Core Profile governance defaults and explicit overrides through public preflight and execution, including an injected Executor (spec §7.4 and §7.9) | +| [`post_validation_policy`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/post_validation_policy.json) | 9 | Final argument policy, combined approval requirements, scoped resumption and stream producer gating (spec §7.4.1) | | [`ephemeral_modules`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/ephemeral_modules.json) | 7 | `ephemeral.*`: one audit event per register / unregister under the standard bootstrap, the bare ID `ephemeral`, `INVALID_MODULE_ID` rejections (spec §2.5.1, D-148) | | [`error_fingerprinting`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/error_fingerprinting.json) | 6 | Error fingerprint = SHA-256 of `code:module_id:normalized_message` for ErrorHistory dedup | | [`error_recovery_metadata`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/error_recovery_metadata.json) | 22 | `retryable` / `ai_guidance` / `user_fixable` / `suggestion` recovery metadata (spec §8) | @@ -430,7 +431,7 @@ The repository ships **98 cross-language fixture files** under `conformance/fixt | [`usage_contract`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/usage_contract.json) | 11 | `system.usage.*` value semantics no schema can assert (spec §6.7.1) | | [`usage_exporter`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/usage_exporter.json) | 3 | `UsageExporter` push interface (D-55) | | [`version_negotiation`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/version_negotiation.json) | 12 | Version negotiation (Algorithm A14) | -| **Total** | **1229** | **98 fixtures** | +| **Total** | **1238** | **99 fixtures** | ### 8.2 Loading Fixtures from a Test Runner diff --git a/docs/spec/protocol-spec.md b/docs/spec/protocol-spec.md index 48626fc8..12215263 100644 --- a/docs/spec/protocol-spec.md +++ b/docs/spec/protocol-spec.md @@ -8,6 +8,7 @@ description: "The canonical apcore protocol specification (RFC 2119): module, sc > Version: 2.0.0 > Status: Draft +> Draft Revision: 2 > Last Updated: 2026-11-27 --- @@ -5097,6 +5098,8 @@ These methods **MUST** be asynchronous (async/await) in implementations that sup Before returning `approved` from `check_approval_for_call`, a handler **MUST** verify the credential's expiry and match the current request to the original approved invocation. The scope **MUST** cover the trusted principal (when present), `caller_id`, canonical target ID, and the arguments. The handler **MUST** consume the approved credential atomically with successful verification. A handler using durable storage **MAY** authorize resumption after a process restart. +A handler that implements final-scope resumption **MUST** explicitly advertise `supports_final_scope` in the SDK's native form. It **MUST** distinguish the final scope from legacy records and verify the resolved module version and canonical argument digest as well as the trusted principal, caller and target. Absence of a final-scope marker on a stored record **MUST NOT** match a final-scope request. An SDK **MUST NOT** expose a pending final-scope credential or pass one to a handler that has not advertised this capability. Fresh synchronous approval remains available to such a handler. + ### 7.3 Data Types #### 7.3.1 ApprovalRequest @@ -5111,7 +5114,14 @@ ApprovalRequest: description: "Target module's canonical ID" arguments: type: object - description: "Snapshot of the business arguments at the approval gate, before the standard before-middleware and input-validation steps" + description: "Detached snapshot of the business arguments at the enforcing approval gate. Step 5 uses submitted arguments. The opted-in Step 7.5 uses the validated execution inputs." + module_version: + type: [string, "null"] + description: "Version on the registration selected by Step 3, when supplied by the final approval gate. Null indicates no registered version." + canonical_args_digest: + type: [string, "null"] + pattern: "^[0-9a-f]{64}$" + description: "SHA-256 digest of the final-scope argument encoding. A non-null value indicates final scope. This field is private to the trusted handler contract." context: type: object description: "Execution context (trace_id, identity, call_chain) — see §5.7 Context Parameter Specification" @@ -5251,10 +5261,26 @@ An implementation that read only the annotation would silently ignore every rule - The `_approval_token` mechanism (Phase B) allows clients to retry after external approval without re-triggering the approval flow. - The `_approval_token` key **MUST** be removed from business arguments before they reach subsequent steps. This applies to an invocation whose strategy omits the approval gate as well. The executor can carry the credential separately for the approval handler. A preflight has no approval decision to resume. -**Resume semantics.** When a caller retries an `APPROVAL_PENDING` call with `_approval_token` in the request arguments, the executor **MUST** re-enter the pipeline from Step 1. Implementations **MUST NOT** preserve intermediate `PipelineContext` state across suspension and resumption. The fresh traversal receives business arguments separately from the resume credential. Steps 1–4 run on both traversals, so the ACL audit entry (§6.3.1) and tracing occur once per traversal. Modules **MUST NOT** assume those steps are skipped on resume. In the standard strategy, Step 6 (`middleware_before`) and later steps run only after the gate allows the call to continue. Neither module middleware nor the module receives the credential as a business argument. External retry and replay layers can persist `approval_id` and the original inputs to drive this flow. See [Durability Boundary §2.2](./design-durability-boundary.md) for integration patterns. +**Resume semantics.** When a caller retries an `APPROVAL_PENDING` call with `_approval_token` in the request arguments, the executor **MUST** re-enter the pipeline from Step 1. Implementations **MUST NOT** preserve intermediate `PipelineContext` state across suspension and resumption. The fresh traversal receives business arguments separately from the resume credential. Steps 1–4 run on both traversals, so the ACL audit entry (§6.3.1) and tracing occur once per traversal. Modules **MUST NOT** assume those steps are skipped on resume. With the default approval timing, Step 6 (`middleware_before`) and later steps run only after the gate allows the call to continue. The condition for a host to opt in to final approval is defined in §7.4.1. Neither module middleware nor the module receives the credential as a business argument. External retry and replay layers can persist `approval_id` and the original inputs to drive this flow. See [Durability Boundary §2.2](./design-durability-boundary.md) for integration patterns. **Scope of approved arguments.** Fresh and resumed requests use the same gate-time snapshot. In the standard strategy, `middleware_before` can transform those inputs after approval, and input validation checks the transformed values. A deployment that lets a transformation change the resource or action being authorized can normalize the values before the gate or enforce a separate authorization check on the transformed values. +#### 7.4.1 Opt-in post-validation policy {#741-post-validation-policy} + +A host **MAY** install an instance-scoped `PolicyEvaluator` using the `policy_evaluator` extension point. The evaluator is code supplied by the host. Its asynchronous `evaluate(request)` returns a `PolicyVerdict` with `decision` set to `allow`, `deny`, or `require_approval`, and an optional static `rule_id`. `PolicyEvaluationRequest` carries the canonical target ID, its resolved registration version, `caller_id`, trusted identity, a detached snapshot of the validated execution arguments, and the sensitive instance field paths identified by the input schema as JSON Pointers. The evaluator does not receive the resume credential. Registration version refers to the selection in Step 3, including across async evaluation or reload. A host that changes a module's approval-relevant behavior without changing its version is responsible for invalidating its outstanding approvals. + +When an evaluator is installed, the strategy **MUST** preserve the built-in authorization and validation boundaries and run `post_validation_policy` (Step 7.5) after successful input validation and before the module call or stream producer starts. An incompatible strategy **MUST** fail configuration or invocation before execution. A skip, replacement, ignored error or recovery **MUST NOT** bypass the policy decision or dispatch values besides the covered snapshot. Policy evaluation **MUST NOT** receive inputs from a traversal that did not pass ACL and input validation. Step 4 retains its submitted-arguments ACL contract. + +Step 5 computes the early approval requirement without prompting, verifying, or consuming the credential. It **MAY** fail early when the built-in strict policy requires a handler and none is configured. Hosts enabling the evaluator **MUST** use before middleware solely for trusted transformations without approval-dependent side effects. Step 7.5 uses the union of the earlier requirement and the evaluator's approval requirement. `allow` **MUST NOT** clear an earlier requirement. The gate performs at most one request or one scoped verification on the final snapshot. Both required approval and submitted credentials require a handler. A submitted credential **MUST** be verified even if the current verdict is `allow`. Reject a mismatched, expired or consumed credential without a fresh approval request or execution. An evaluator's `deny` or failure is terminal before approval or dispatch. + +Approval uses the same pending, timeout, and explicit denial results as Step 5. The final scope binds the trusted principal `(identity.type, identity.id)` when present, `caller_id`, canonical target ID, resolved module version, and `canonical_args_digest`. The scope encoding is local to the producing SDK and is independent of the schema content hash. The handler **MUST** compare all scope fields as well as the final-scope marker. Scope digests **MUST NOT** be used to transfer approval between SDKs with different native numeric types. + +For the argument digest, the SDK **MUST** encode the effective argument object as UTF-8. Objects and arrays use compact JSON punctuation, strings use JSON escaping with Unicode scalar values preserved, and object names sort by unsigned UTF-16 code units. Encode null and booleans as JSON literals. Encode safe native integers as `i` followed by their signed decimal form and `;`. Encode finite binary64 floats as `f` followed by sixteen lowercase hex digits of their bits and `;`. Where the language has only binary64 numbers, safe integral values use integer encoding except negative zero. Safe integers are in the inclusive range `[-9007199254740991, 9007199254740991]`. Reject integers or integral floats outside the range, lone surrogates, non-finite or cyclic values, and host values for which the SDK cannot prove a lossless JSON-shaped projection. The SDK **MUST** fail closed for an unsupported value and **MUST NOT** change the business value merely to compute a digest. + +Preflight evaluates policy on the same validated input its dry traversal obtains after ACL, without running before middleware. It reports the combined approval requirement without prompting, consuming credentials, or emitting approval or policy-decision events. It **MUST NOT** invoke module-level preview or preflight callbacks following an authorization failure. Execution always reevaluates after normal transformations. A preflight result is not an approval or an execution permit. + +An evaluator has a finite timeout, defaulting to 1,000 milliseconds and bounded by the invocation deadline. Its timeout, malformed verdict, unsupported input representation, or exception is reported as `POLICY_EVALUATION_ERROR` with `retryable: true` and `user_fixable: false`. A denied verdict is `POLICY_DENIED` with `retryable: false`, `user_fixable: true`, and safe user guidance. External cancellation retains the invocation's cancellation outcome. Policy errors and `apcore.policy.decision` telemetry **MUST NOT** carry raw arguments, argument digests, credentials, or evaluator exceptions. A pending credential uses the caller-only approval delivery in §7.4. The policy event **MAY** include the decision, a safe static rule ID, and sensitive schema field paths. + ### 7.5 Error Types Implementations **MUST** define the following error types under `ModuleError`: @@ -5788,6 +5814,12 @@ error_codes: APPROVAL_PENDING: description: "Approval is pending, retry with _approval_token" http_status: 202 + POLICY_DENIED: + description: "The installed policy denied the validated invocation" + http_status: 403 + POLICY_EVALUATION_ERROR: + description: "The installed policy could not evaluate the invocation safely" + http_status: 503 ``` ### 8.3 Error Propagation @@ -5935,6 +5967,8 @@ Implementations **MUST NOT** default retry failed module invocations. Retry beha | `ACL_DENIED` | **No** | Permission insufficiency won't change with retry | | `APPROVAL_DENIED` | **No** | Explicit denial, retry won't change decision | | `APPROVAL_PENDING` | **No** | Async approval in progress, use polling instead | +| `POLICY_DENIED` | **No** | Policy denied the validated invocation | +| `POLICY_EVALUATION_ERROR` | **Yes** | Policy evaluation could not complete safely | | `MODULE_NOT_FOUND` | **No** | Module non-existence won't change with retry | | `MODULE_DISABLED` | **No** | Module explicitly disabled, needs re-enabling | | `MODULE_LOAD_ERROR` | **No** | Load errors typically need code fixes | @@ -8800,7 +8834,7 @@ Extensions are registered in code. No key in `apcore.yaml` registers an extensio implementations registered for one point are not chained (§11.7) (D-143). > **NOTE — `ExtensionManager` Extension Point Names:** -> The extension point names above (`schema_loader`, `id_converter`, `module_loader`, `executor`, `acl_checker`) are the conceptual taxonomy. `ExtensionManager` registers six built-in extension points under the following names: +> The extension point names above (`schema_loader`, `id_converter`, `module_loader`, `executor`, `acl_checker`) are the conceptual taxonomy. `ExtensionManager` registers the following built-in extension points: > > | Conceptual name | `ExtensionManager` name | Rationale | > |---------------------|--------------------------|-----------| @@ -8810,10 +8844,11 @@ implementations registered for one point are not chained (§11.7) (D-143). > | *(no equivalent)* | `middleware` | First-class middleware extension point for runtime pipeline customization | > | *(no equivalent)* | `span_exporter` | Observability export as a dedicated extension point | > | *(no equivalent)* | `approval_handler` | The approval gate's handler (§7) as an extension point | +> | *(no equivalent)* | `policy_evaluator` | Opt-in evaluation of validated execution arguments (§7.4.1) | > | `id_converter` | *(not an extension point)* | Not a common runtime customization need | > | `executor` | *(not an extension point)* | Local execution covers the supported use cases | > -> Implementations declaring Level 2 conformance use the `ExtensionManager` names (`discoverer`, `middleware`, `acl`, `span_exporter`, `module_validator`, `approval_handler`). +> Implementations declaring Level 2 conformance use the `ExtensionManager` names in the table. ### 11.4 Framework Built-in Middleware @@ -8897,14 +8932,14 @@ Extension Point: Executor execute(module: Module, method: String, inputs: Map, context: Context) → Map ``` -> **NOTE:** The interface contracts above use the conceptual names. See the mapping table in §11.3 for the `ExtensionManager` names (`discoverer`, `middleware`, `acl`, `span_exporter`, `module_validator`, `approval_handler`). +> **NOTE:** The interface contracts above use the conceptual names. See the mapping table in §11.3 for the `ExtensionManager` names. ### 11.7 Extension Loading Order Extensions are registered in code with `ExtensionManager.register(point_name, extension)` and wired with `apply(registry, executor)` (§11.3): -1. A single-valued point (`discoverer`, `acl`, `module_validator`, `approval_handler`) holds one +1. A single-valued point (`discoverer`, `acl`, `module_validator`, `approval_handler`, `policy_evaluator`) holds one implementation; registering another replaces it. 2. A multi-valued point (`middleware`, `span_exporter`) holds every registered implementation in registration order. @@ -9872,6 +9907,8 @@ set remains the closed set in D-80. The `validate()` preflight method (§12.2, SHOULD level) evaluates the strategy's pure steps. The standard execution checks are context creation, call-chain guard, module lookup, ACL, and input validation (Steps 1–4 and 7). The approval gate is impure and is skipped. `requires_approval` reports the governance-effective requirement without consulting the `ApprovalHandler` or requesting, resuming, or recording an approval decision. The invocation pipeline performs that decision on a formal call. Preflight can also run the optional module-level `preflight()` and `preview()` of §12.8.5.1 when ACL permits disclosure. +With an installed policy evaluator, a successful ACL and schema traversal also evaluates `post_validation_policy` (Step 7.5) and unions its approval requirement into the report. The optional module callbacks require that policy authorizes disclosure (§7.4.1). + #### 12.8.1 Design Principles 1. **Collect, don't throw.** All check failures are appended to a `checks` list. The caller_id sees every problem in one call. @@ -10306,7 +10343,8 @@ The specification and the SDK have independent version numbers. `CHANGELOG.md` r | Version | Date | Summary | Records | |---|---|---|---| -| 2.0.0 | Unreleased | Define an in-memory Core Profile and opt-in extensions (§1.8, §12). Deny calls requiring approval when the handler is absent, and require approval for destructive modules by default (§6.6.3.1, §7.4, §7.9). Require invocation-scoped approval resumption and use a non-secret correlation ID in telemetry (§7, §9.16.2). Specify managed drain, recovery, scoped forced removal, reload reports and lifecycle events (§6.7, §9.16.2, §12.7.9). Assign provider projections to Surfaces (§4.17 and Appendix D). Resolve path-typed configuration against one project root (§9.2.2). Clarify pipeline configuration, preflight and approval argument scope (§5.16.1, §7.3–7.4, §12.8), configured redaction (§6.1.8, §10.6.1) and trace IDs (§10.5). Align schema examples with Draft 2020-12 and the validation error format (§4.2, §4.14, §8.1). | D-153, [#113](https://github.com/aiperceivable/apcore/issues/113), [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | +| 2.0.0 (draft revision 2) | Unreleased | Add the opt-in post-validation policy evaluator, final-input approval binding, and preflight semantics (§7.2–§7.4.1, §11.3, §12.8). | [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | +| 2.0.0 (draft revision 1) | Unreleased | Define an in-memory Core Profile and opt-in extensions (§1.8, §12). Deny calls requiring approval when the handler is absent, and require approval for destructive modules by default (§6.6.3.1, §7.4, §7.9). Require invocation-scoped approval resumption and use a non-secret correlation ID in telemetry (§7, §9.16.2). Specify managed drain, recovery, scoped forced removal, reload reports and lifecycle events (§6.7, §9.16.2, §12.7.9). Assign provider projections to Surfaces (§4.17 and Appendix D). Resolve path-typed configuration against one project root (§9.2.2). Clarify pipeline configuration, preflight and approval argument scope (§5.16.1, §7.3–7.4, §12.8), configured redaction (§6.1.8, §10.6.1) and trace IDs (§10.5). Align schema examples with Draft 2020-12 and the validation error format (§4.2, §4.14, §8.1). | D-153, [#113](https://github.com/aiperceivable/apcore/issues/113), [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | | 1.66.0 | 2026-10-19 | A23 preserves optional enum, const, reference and applicator constraints inside an anyOf-null wrapper; required fields remain unchanged. | [#124](https://github.com/aiperceivable/apcore/issues/124) | | 1.65.0 | 2026-10-08 | Add public bare-name canonicalization with structured, non-throwing results in all SDKs; preserve A02, ASCII-only case conversion and existing underscores, and reject non-ASCII, invalid starts and overlong output (§2.2.1). | [Rust #40](https://github.com/aiperceivable/apcore-rust/issues/40) | | 1.64.0 | 2026-10-08 | Algorithm A02 is exhaustive and ASCII-scoped: it preserves existing underscores and non-ASCII characters through case conversion, then rejects a result outside the Canonical ID grammar; it never repairs arbitrary identifiers (§2.2). The repairing class-name conversion is named `snake_case_name` and is distinct from A02's `snake_case_identifier` (§2.1.1). | #122 | diff --git a/planning/overview.md b/planning/overview.md index afc4710d..17f4f563 100644 --- a/planning/overview.md +++ b/planning/overview.md @@ -12,6 +12,7 @@ Record lasting specifications, changes, and decisions in the spec, CHANGELOG, an |---|---|---| | [Module lifecycle](module-lifecycle/overview.md) | Owned shutdown, detailed removal, and managed reload in Python, TypeScript, and Rust | [Phases A and B complete](module-lifecycle/state.json) | | [APCore project review remediation](apcore-project-review-2026-11-26/overview.md) | Findings 1–8 and 26 across the runtime, wire contracts, observability, and conformance | [9 of 9 complete](apcore-project-review-2026-11-26/state.json) | +| [Post-validation policy](post-validation-policy/overview.md) | Argument-value policy and approval binding across Core SDKs and MCP | [Local implementation and verification complete](post-validation-policy/state.json) | The review remediation restored the fixture inventory before the eight runtime changes. Its verification record covers the combined SDK, fixture, and documentation checks. diff --git a/planning/post-validation-policy/overview.md b/planning/post-validation-policy/overview.md new file mode 100644 index 00000000..8b371d40 --- /dev/null +++ b/planning/post-validation-policy/overview.md @@ -0,0 +1,63 @@ +# Post-validation Policy + +## Overview + +Gap 1 is the first milestone after the alpha.2 Core profile and fail-closed approval changes. This proposal evaluates policy on the arguments that the selected module will receive and uses one bound approval for those arguments when an evaluator is installed. + +Core starts from `ea1c147` and Surfaces from `fc1a52c`. Both main-branch CI runs passed. The maintainer approved the opted-in gate and protocol draft revision 2. + +Targeted approval baselines passed on the merged Core tree. Python passed 129 cases, TypeScript passed 86, and Rust passed 112 with two existing ignored cases. A Python public-entry probe confirmed the design conflict. Step 5 saw the submitted value `10` and rejected a test credential scoped to the value `20` before middleware could normalize the input. + +## Scope + +- Core evaluator registration, Step 7.5 execution boundary, and invocation-scoped approval. +- Python, TypeScript, and Rust parity across execution, preflight, and streaming. +- MCP scoped approval and installed-package compatibility. Check other Surfaces consumers where the approved contract affects their builds or behavior. + +Gap 3 discovery, delegated identity, new budget and interaction primitives, media references, and SDK declaration ergonomics remain separate milestones. Release is paused. + +## Technology Stack + +Python with pytest, TypeScript with Vitest and pnpm, Rust with Cargo and Tokio, and the shared JSON fixture suite. Reuse the existing validators, execution strategies, scoped approval stores, and package CI. + +## Task Execution Order + +| Phase | Task | Scope | Status | +|---|---|---|---| +| 1 | [Shared contract](./tasks/shared-contract.md) | Maintainer decision, draft, and conformance expectations | Complete | +| 2 | [Python](./tasks/python.md) | Python SDK implementation and tests | Complete | +| 2 | [TypeScript](./tasks/typescript.md) | Portable and full SDK implementations and tests | Complete | +| 2 | [Rust](./tasks/rust.md) | Default and full SDK implementations and tests | Complete | +| 3 | [Surfaces](./tasks/surfaces.md) | Scoped approval storage and MCP transport verification | Complete | +| 4 | [Integration](./tasks/integration.md) | Candidate packages, cross-language tests, and compatibility review | Complete | + +## Progress + +Core implementation commit `83f627cb300a42b5c46550a04b48d18745147f21` and Surfaces commit `86a6f22bfa82a54a3f105ec434ab880687155b4f` passed the local verification recorded below. The Core artifact builds and repository-level integration are separate checks. + +## Verification results + +| Gate | Python | TypeScript | Rust | +|---|---:|---:|---:| +| Core full test suite | 6,674 passed | 5,883 passed | 3,245 passed | +| Toolkit with built Core | 1,289 passed | 1,079 passed | 714 passed | +| MCP with built Core | 1,278 passed | 996 passed | 1,153 passed | +| A2A with built Core | 522 passed | 492 passed | 242 passed | +| CLI with built Core | 1,098 passed | 950 passed | 1,052 passed | +| Toolkit with the stable minimum Core | 1,289 passed | 1,079 passed | 714 passed | + +All three SDKs run the nine shared post-validation policy cases. The conformance guards find 99 fixtures and 1,238 cases, with every fixture driven by each SDK. The packaged Python minimal and full profiles passed isolated installation checks. TypeScript passed its portable entry and browser import checks. Rust passed the minimum-toolchain profile and verified the packaged crate on that toolchain. + +MCP verified final-scope pending approval, polling, and one-shot resumption through real call and streaming entry points in each language. The direct and MCP Golden Path also passed with installed Core and MCP wheels. Core and MCP MkDocs strict builds passed. Artifact digests agree with the Surfaces locks and compatibility workflow pins. + +| Core distribution used for integration | SHA-256 | +|---|---| +| Python wheel | `02610c5a0d3a5519ba27914edd9b0e63da30c9b4985b31efaa43d5e8609092b9` | +| TypeScript npm tarball | `abce533e664afec207c4ff93d3af7475789e7144ac48db154af6efd08bbe3e07` | +| Rust crate | `7514b549b91d7beb83a0fefef9d4f365e4cb19b38f7a0664c4a814bcac4009bc` | + +## Reference Documents + +- [Implementation plan](./plan.md) +- Atlas `apcore_architecture_evolution_blueprint.md`, Gap 1 +- [Protocol specification](../../docs/spec/protocol-spec.md) diff --git a/planning/post-validation-policy/plan.md b/planning/post-validation-policy/plan.md new file mode 100644 index 00000000..28a0a550 --- /dev/null +++ b/planning/post-validation-policy/plan.md @@ -0,0 +1,103 @@ +# Post-validation Policy Implementation Plan + +The maintainer approved the opted-in approval timing and an increment of the protocol draft revision under 2.0.0. This plan records the implementation and test gates. + +## Goal + +Let an explicitly configured host policy evaluate the validated inputs that a module will execute and authorize any resulting approval against that invocation across Python, TypeScript, Rust, and the affected Surfaces adapters. + +## Architecture Design + +1. Resolve the module and snapshot its actual descriptor version from the registration or execution lease selected at Step 3. Keep the existing ACL decision at Step 4. An ACL denial ends the request before giving the policy evaluator access to arguments. +2. In the default assembly, Step 5 retains its existing timing and compatibility behavior. In an assembly with a `PolicyEvaluator`, Step 5 computes the existing approval requirement from module and declared annotations, execution policy, and ACL. A known approval requirement with strict policy and no handler still rejects before middleware. Before middleware performs trusted, side-effect-free input normalization for this assembly. Step 7 validates its output. The existing ACL evaluates submitted arguments, and the evaluator receives the validated view. +3. Step 7.5 runs the installed evaluator on a detached view of the effective inputs. It merges `require_approval` with the Step 5 requirement. A deny verdict or evaluation failure stops the invocation. The required approval is requested or resumed once for the final invocation, with the credential scoped to principal, `caller_id`, `module_id`, resolved module version, and canonical argument digest. The credential stays in the existing private pipeline slot until the enforcing gate consumes it. +4. The invocation binds the evaluation and approval to an owned snapshot. The built-in execute and stream producer entry points dispatch the covered snapshot. A configured strategy that cannot preserve validated ordering and execution coverage is rejected. Step skips, step error recovery, and module error middleware cannot convert a policy rejection into a successful result or execute an uncovered invocation. +5. Preflight uses the same evaluator on the inputs it validates after an allowed ACL decision. It reports the combined approval requirement without invoking approval handlers, consuming credentials, or starting the module or its producer. The real invocation reevaluates after before middleware has run. Preflight discloses neither module previews nor further policy inputs after the applicable authorization check fails. + +Use the existing `ExtensionManager` singleton provider pattern and the executor's existing approval and strategy wiring. `PolicyEvaluator` is a host-provided async interface. Use the existing native schema validators and `ScopedApprovalHandler` contract with MCP's transactional `consume_scoped` operation. The Core registry remains independent of the evaluator. The design adds no policy DSL or separate module dispatch path. + +## Design Decisions + +### High-Impact Decision Record: Approval timing and execution coverage + +**Necessity.** A retry restarts at Step 1. Two active gates can compute different argument scopes after normalization, but only one opaque resume credential is carried. If Step 5 consumes a final-scope credential first, a valid approval may be rejected or lost. The evaluator-enabled assembly authorizes once after validation and includes the early approval requirement. + +**Data characteristics.** The execution snapshot is request-local and derives from the actual registered module, effective inputs, and trusted context. Before middleware receives business inputs and serves as trusted normalization in the evaluator-enabled profile. Persisted approval records carry scope and expiry, with atomically consumable state owned by the handler. + +**Volatility.** Registration replacement and argument transformations can invalidate a previously authorized scope. Capture the selected module version at lookup. A version binds the version value, so deployments that replace implementation semantics under the same version must invalidate outstanding records or advance the version. Step 7.5 is additive; the existing step IDs and standard path remain stable without an evaluator. + +**Migration cost.** Hosts opt in by installing an evaluator. They must review their before middleware for side effects and assemble a strategy with the supported enforcement boundary. Existing unconfigured request handling and the legacy non-strict fallback retain their prior behavior. In the configured profile a required final approval has to be satisfiable by a handler, and an evaluator requirement cannot fall through to a non-strict default. + +**External contract impact.** `PolicyEvaluationRequest` exposes effective arguments and schema-derived sensitive paths to the trusted evaluator. `ApprovalRequest` gains resolved version and enough trusted scope metadata for a handler to distinguish final-scope records. Preserve the existing handler methods and wire metadata. Check Rust `ApprovalRequest` struct literals and public enum matches when choosing the additive shape. The error contracts distinguish `POLICY_DENIED`, sanitized `POLICY_EVALUATION_ERROR`, and caller cancellation. + +**Cheaper alternative.** A step that runs an evaluator after validation could coexist with two independent approval prompts, but it lacks safe resumption for the two-scope case. Moving all existing Step 5 approvals would change middleware ordering for unconfigured hosts. Use the single final gate only when a host supplies an evaluator. + +### High-Impact Decision Record: Approval scope and canonical arguments + +**Necessity.** A scope verifier needs stable argument equality and the actual module version. Reusing the schema content hash would apply inconsistent native number and string serialization across SDKs. + +**Data characteristics.** The digest covers only an interoperable projection of the effective arguments. Evaluate RFC 8785 viability against the minimum and full profiles before selecting the encoding. RFC 8785 may serialize distinct native values identically, such as signed zero or integer and float spellings. Require a lossless projection for distinctions visible to a module and reject ambiguous, non-finite, or unsupported values in the opted-in mode when their projection cannot be proven. Keep the execution values unchanged. Privileged evaluators and existing approval handlers receive only the inputs needed by their contracts. Telemetry excludes raw arguments, credentials, digest, and backend error text. + +**Volatility.** Version the scope representation independently of persisted legacy records. Fix its cross-language properties through fixture vectors for equivalent ordering, Unicode, numeric edge cases, and values that must reject. Keep the protocol on its proposed 2.0.0 line subject to the draft revision decision and repository version checklist. + +**Migration cost.** Keep legacy records eligible only for the existing scope. A missing version or scope marker cannot act as a wildcard for evaluator-enabled approvals. Document reissuance where stores cannot safely upgrade outstanding records. Reuse the current atomic consume behavior so stores need no second confirmation transition. + +**External contract impact.** MCP preserves its approval metadata and forwards the private credential through the existing Core invocation interface. Consumers gaining the new `ApprovalRequest` field must preserve construction compatibility where feasible. The new record scope stays inside the handler; external APIs do not receive digest fields. + +**Cheaper alternative.** Native JSON equality could compare arguments in one process. It would not provide the stable approval digest expected by scoped stores and cross-SDK conformance. Validate a small interoperable domain through the existing profile gates before adding any dependency. + +## Task Breakdown + +```mermaid +graph TD + shared[Shared contract and fixtures] --> python[Python SDK] + shared --> typescript[TypeScript SDK] + shared --> rust[Rust SDK] + python --> surfaces[Surfaces scoped approval] + typescript --> surfaces + rust --> surfaces + surfaces --> integration[Candidate and conformance matrix] +``` + +| Task | Depends on | Estimate | +|---|---|---| +| [Shared contract](./tasks/shared-contract.md) | Maintainer approval | 4 hours | +| [Python](./tasks/python.md) | Shared contract | 6 hours | +| [TypeScript](./tasks/typescript.md) | Shared contract | 6 hours | +| [Rust](./tasks/rust.md) | Shared contract | 8 hours | +| [Surfaces](./tasks/surfaces.md) | Python, TypeScript, Rust | 6 hours | +| [Integration](./tasks/integration.md) | Surfaces | 4 hours | + +## Risks and Considerations + +- **Normalization and queued approval.** A retry can produce different defaults, middleware outputs, or a new module version. Reevaluate on retry and reject a scope mismatch without dispatch or an automatic fallback approval. +- **Pipeline escape paths.** Test the real execute and producer boundaries, including mutable values held by middleware, configured and per-call strategies, step jumps, error recovery, and timed-out evaluators. +- **Error and deadline semantics.** Bound evaluator execution by its configured limit and the invocation deadline. Return a sanitized evaluation failure when it faults or exceeds its budget. Preserve the existing result for external cancellation and keep cancellation distinct from an evaluator timeout. +- **Audit and disclosure.** Record only approved rule identifiers, decision values, and sensitive field paths in the policy event payload. Include tested safe guidance for denials and fixed diagnostics for evaluator faults. Verify logs, events, and serialized errors with sentinel sensitive values. +- **Performance and packaging.** An unconfigured host should incur no evaluator invocation or canonicalization. Compare minimal and full package imports, artifact sizes, and hot-path costs with the alpha.2 baseline. Detect native data lost by coercion rather than hashing a different invocation. + +## Acceptance Criteria + +| Scenario | Normal call | Preflight | Stream before producer | +|---|---|---|---| +| ACL denies or schema rejects | Evaluator, approval, and execute are untouched | Evaluator, approval, and module preview are untouched | Evaluator, approval, and producer are untouched | +| Policy denies | `POLICY_DENIED` with safe guidance and no execution | Policy check reports denial without disclosure or side effects | `POLICY_DENIED` with zero producer starts | +| Evaluator fails or exceeds its limit | `POLICY_EVALUATION_ERROR` with sanitized details and no execution | Policy check reports the same fault class | No producer starts | +| Caller cancels | Existing cancellation outcome | Existing cancellation outcome | No producer starts | +| Early and policy rules both require approval | One prompt or one scoped consumption on final inputs | Reports required approval without consulting the handler | Same one-gate behavior before producer start | +| Middleware rewrites parameters and the original request requires approval | Approval covers rewritten, validated arguments, including when the evaluator returns `allow` | Evaluates the submitted validated input without the rewrite | Approval covers the same effective arguments as a call | +| Pending resumption | Re-enters from Step 1, consumes matching token once, rejects changed version, principal, caller, module, or effective arguments | Leaves any token untouched | Same resumption guard before producer start | +| No evaluator | Existing Step 5 order, fail-closed defaults, and explicit compatibility policy | Existing reporting | Existing execution, cancellation, and completion | + +- [ ] Maintainer decision recorded before normative edits. Update the specification draft revision, version-history row, and changelog together. Use a linked discussion issue before opening a spec PR. +- [ ] All three SDKs pass the shared fixtures through the public entry points. The matching scope accepts equivalent object key order and denies malformed values or replayed credentials. Disclosure probes confirm there is no provider access after failed authorization and no policy or credential leakage to diagnostics. +- [ ] MCP demonstrates pending approval and resumption against installed candidate packages, with exactly one successful execution and rejection for request changes. Existing Toolkit minimum compatibility and unaffected paths retain coverage from the normal package matrix. +- [ ] Local review and CI validate minimal and full profiles, adapter compatibility, docs builds, and package behavior. Tags and registry publication remain paused. + +## References + +- Atlas `apcore_architecture_evolution_blueprint.md`, Gap 1 and the later-alpha delivery stage +- [Protocol specification](../../docs/spec/protocol-spec.md#7-approval-system), approval and scoped resumption +- [Execution pipeline](../../docs/features/execution-pipeline.md), [approval system](../../docs/features/approval-system.md), and [extension system](../../docs/features/extension-system.md) +- [Conformance suite](../../conformance/README.md) and [alpha.2 delivery](../microkernel-delivery/alpha-2.md) +- [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785.html), candidate canonical encoding diff --git a/planning/post-validation-policy/state.json b/planning/post-validation-policy/state.json new file mode 100644 index 00000000..ee574ece --- /dev/null +++ b/planning/post-validation-policy/state.json @@ -0,0 +1,113 @@ +{ + "feature": "post-validation-policy", + "created": "2026-11-27T12:36:41Z", + "updated": "2026-11-27T13:24:04Z", + "status": "completed", + "execution_order": [ + "shared-contract", + "python", + "typescript", + "rust", + "surfaces", + "integration" + ], + "progress": { + "total_tasks": 6, + "completed": 6, + "in_progress": 0, + "pending": 0, + "skipped": 0, + "blocked": 0 + }, + "tasks": [ + { + "id": "shared-contract", + "file": "tasks/shared-contract.md", + "title": "Shared policy contract and conformance", + "status": "completed", + "started_at": "2026-11-27T12:53:49Z", + "completed_at": "2026-11-27T13:15:09Z", + "assignee": null, + "commits": [], + "estimated_hours": 4, + "dependencies": [] + }, + { + "id": "python", + "file": "tasks/python.md", + "title": "Python post-validation policy", + "status": "completed", + "started_at": "2026-11-27T13:15:09Z", + "completed_at": "2026-11-27T13:15:09Z", + "assignee": null, + "commits": [], + "estimated_hours": 6, + "dependencies": [ + "shared-contract" + ] + }, + { + "id": "typescript", + "file": "tasks/typescript.md", + "title": "TypeScript post-validation policy", + "status": "completed", + "started_at": "2026-11-27T13:15:09Z", + "completed_at": "2026-11-27T13:15:09Z", + "assignee": null, + "commits": [], + "estimated_hours": 6, + "dependencies": [ + "shared-contract" + ] + }, + { + "id": "rust", + "file": "tasks/rust.md", + "title": "Rust post-validation policy", + "status": "completed", + "started_at": "2026-11-27T13:15:09Z", + "completed_at": "2026-11-27T13:15:09Z", + "assignee": null, + "commits": [], + "estimated_hours": 8, + "dependencies": [ + "shared-contract" + ] + }, + { + "id": "surfaces", + "file": "tasks/surfaces.md", + "title": "Surfaces scoped approval", + "status": "completed", + "started_at": "2026-11-27T13:15:09Z", + "completed_at": "2026-11-27T13:24:04Z", + "assignee": null, + "commits": [], + "estimated_hours": 6, + "dependencies": [ + "python", + "typescript", + "rust" + ] + }, + { + "id": "integration", + "file": "tasks/integration.md", + "title": "Candidate integration and verification", + "status": "completed", + "started_at": "2026-11-27T13:15:09Z", + "completed_at": "2026-11-27T13:24:04Z", + "assignee": null, + "commits": [], + "estimated_hours": 4, + "dependencies": [ + "surfaces" + ] + } + ], + "metadata": { + "source_doc": "planning/post-validation-policy/plan.md", + "created_by": "code-forge", + "version": "1.0" + } +} diff --git a/planning/post-validation-policy/tasks/integration.md b/planning/post-validation-policy/tasks/integration.md new file mode 100644 index 00000000..d5f53f65 --- /dev/null +++ b/planning/post-validation-policy/tasks/integration.md @@ -0,0 +1,36 @@ +# Candidate Integration and Verification + +## Goal + +Verify the approved contract with cross-language fixtures and the actual Core and Surfaces package distributions. + +## Files Involved + +- Existing Core conformance fixtures and SDK distribution verification workflows. +- Existing Surfaces Core candidate compatibility matrix and MCP integration harnesses. +- Existing documentation and planning records referenced by the delivery. + +## Steps + +1. Run every affected SDK suite, the shared conformance inventory and drivers, and strict documentation checks. Re-run reviewed denial, credential and snapshot regressions independently in each SDK. +2. Build candidate wheels, npm archives and crates, then run compatibility CI against those artifacts. Record the exact Core and Surfaces SHAs and artifact identities. +3. Verify direct and MCP calls against the same policy and expected behavior. Exercise no-evaluator compatibility, evaluator-enabled denials, pending resumption, default and full profiles, and the supported Toolkit minimum where applicable. +4. Review terminal failure handling, profile dependencies, and no-evaluator performance against the alpha.2 baseline. Record unchecked or failed evidence and keep publication paused. + +## Acceptance Criteria + +- [ ] Three SDKs pass the same fixture expectations from their public entry points. +- [ ] Exact paired distributions pass the installed compatibility matrix and focused MCP resumption checks. +- [ ] Review findings, performance checks, and compatibility evidence are recorded before merge or release readiness is claimed. + +## Dependencies + +Depends on Surfaces. Required by the milestone completion review. + +## Estimated Time + +4 hours. + +## Design Decisions Reference + +See [plan.md](../plan.md#acceptance-criteria) for the acceptance matrix. diff --git a/planning/post-validation-policy/tasks/python.md b/planning/post-validation-policy/tasks/python.md new file mode 100644 index 00000000..ed5d9108 --- /dev/null +++ b/planning/post-validation-policy/tasks/python.md @@ -0,0 +1,35 @@ +# Python Post-validation Policy + +## Goal + +Implement the approved contract through Python's normal execution, preflight, and stream APIs. + +## Files Involved + +- `python/src/apcore/builtin_steps.py`, `executor.py`, `pipeline.py`, `registry/`, `extensions.py`, `approval.py`, `errors.py`, and existing public entry points. +- `python/tests/conformance/` and existing policy, governance, and stream tests under `python/tests/`. + +## Steps + +1. Read `python/CLAUDE.md`. Add the public conformance driver and run the new cases against the baseline for a red result. Exercise Pydantic-native validated arguments, module-owned defaults, and before middleware changing the submitted value. +2. Add evaluator wiring through `ExtensionManager`. Reuse the current approval gate's requirement calculation, handler path, and private credential slot. Capture the selected registration's version and dispatch only a snapshot bound to the final check. +3. Reuse the existing terminal error machinery. Route preflight through the evaluator after authorized validation. Verify that a denial cannot become a recovery result and that evaluator timeout and cancellation stay distinct. +4. Run `python -m pytest python/tests/conformance/` plus focused governance, strategy, and stream suites. Build and test both installation profiles and run the SDK's normal lint and type checks. + +## Acceptance Criteria + +- [ ] Native execution argument fidelity and approval scope are covered by the shared cases. +- [ ] Terminal failures, rejected token reuse, and no-provider preflight effects are observed at public APIs. +- [ ] The minimal installed profile and the legacy no-evaluator strategy pass their existing coverage. + +## Dependencies + +Depends on the shared contract. Required by Surfaces and integration. + +## Estimated Time + +6 hours. + +## Design Decisions Reference + +See [plan.md](../plan.md#design-decisions) for approval timing and the argument snapshot. diff --git a/planning/post-validation-policy/tasks/rust.md b/planning/post-validation-policy/tasks/rust.md new file mode 100644 index 00000000..641c63d4 --- /dev/null +++ b/planning/post-validation-policy/tasks/rust.md @@ -0,0 +1,35 @@ +# Rust Post-validation Policy + +## Goal + +Implement the approved contract under Rust's default and full feature profiles. + +## Files Involved + +- `rust/src/builtin_steps.rs`, `executor.rs`, `pipeline.rs`, `registry/registry.rs`, `extensions.rs`, `approval.rs`, `errors.rs`, and crate exports. +- `rust/tests/core_profile.rs`, `rust/tests/conformance_env.rs`, and the aggregate suite declared by `rust/tests/it.rs`. + +## Steps + +1. Read `rust/CLAUDE.md`. Add red public-entry fixture tests for the default profile and the execution suite. Include a descriptor version that differs from instance metadata or request hints. +2. Extend the execution lease with the selected descriptor version under the existing registry lock. Snapshot the evaluator with the other providers on an invocation. Reuse stock validation and terminal governance paths for normal, dry-run, and stream preparation. +3. Choose the approved compatibility shape for `ApprovalRequest`. Check public struct literals and exhaustive matches against the current API. Reuse the private credential and atomic resumption mechanisms. +4. Run `cargo test --locked --no-default-features --lib --test core_profile` and `cargo test --locked --all-features`. Run the repository's formatting and lint checks. Build the profile archive with the supported MSRV and exercise the installed package. + +## Acceptance Criteria + +- [ ] Shared tests prove the exact selected descriptor version, final input, and producer admission. +- [ ] Default and full profiles pass on supported toolchains with no unnecessary host dependencies. +- [ ] Existing public provider construction and strategy compatibility are verified or covered by an approved migration. + +## Dependencies + +Depends on the shared contract. Required by Surfaces and integration. + +## Estimated Time + +8 hours. + +## Design Decisions Reference + +See [plan.md](../plan.md#design-decisions) for the execution lease and provider contract. diff --git a/planning/post-validation-policy/tasks/shared-contract.md b/planning/post-validation-policy/tasks/shared-contract.md new file mode 100644 index 00000000..617b1ad6 --- /dev/null +++ b/planning/post-validation-policy/tasks/shared-contract.md @@ -0,0 +1,36 @@ +# Shared Policy Contract and Conformance + +## Goal + +Turn the approved policy placement and scope into a shared SDK contract and executable fixture expectations. + +## Files Involved + +- `docs/spec/protocol-spec.md`, `docs/index.md`, `CHANGELOG.md`, and the relevant decision register and feature references. +- `conformance/fixtures/post_validation_policy.json`, `conformance/README.md`, and `docs/spec/conformance.md`. +- Canonical schemas and error mappings where the approved contract introduces wire-visible fields or codes. + +## Steps + +1. Record maintainer approval of the opted-in behavior and protocol draft revision. Define the effective argument projection and digest from representative native and JSON values before committing the contract. Check the exact numeric and Unicode vectors across all three languages and preserve application-observable distinctions. +2. Specify the evaluator shape, policy verdict and error behavior, private credential lifecycle, sensitive-field projection, fail-closed ordering, module version origin, and strategy validity. Keep the existing raw ACL view distinct from validated policy inputs and preserve default assembly semantics. +3. Define public-API fixtures for phase B replay, unchanged scope, changed scope, middleware normalization, caller cancellation, evaluator error, denied ACL disclosure, and zero producer starts. Provide case IDs and expected fields for all three language drivers. +4. Align the approved draft header, history entry, and changelog. Run the repository's conformance inventory and strict documentation checks. Open a discussion issue before any specification PR. + +## Acceptance Criteria + +- [ ] The maintainer decision, default compatibility, final approval, and record migration boundaries are explicit. +- [ ] Shared fixture data and inventory agree and every expectation has an intended public driver. +- [ ] The chosen canonical domain is supported by the profiles and rejects observable ambiguity. + +## Dependencies + +Depends on maintainer approval. Required by Python, TypeScript, and Rust. + +## Estimated Time + +4 hours. + +## Design Decisions Reference + +See [plan.md](../plan.md#design-decisions) for approval timing, execution coverage, scope, and canonical arguments. diff --git a/planning/post-validation-policy/tasks/surfaces.md b/planning/post-validation-policy/tasks/surfaces.md new file mode 100644 index 00000000..e5cfe8e3 --- /dev/null +++ b/planning/post-validation-policy/tasks/surfaces.md @@ -0,0 +1,35 @@ +# Surfaces Scoped Approval + +## Goal + +Carry final-scope approval through MCP without changing transport metadata or duplicating Core policy. + +## Files Involved + +- Existing Python and TypeScript MCP `adapters/approval` and `approval_store` or `approval-store` files in `apcore-surfaces`. +- Existing Rust MCP approval adapter and `approval_store.rs`. +- MCP adapter tests and the existing compatibility build workflows that consume Core candidate packages. + +## Steps + +1. Add red store and transport tests for final-scope records in all three languages. Cover legacy unversioned records, expiry, concurrent consumption, changed module version, and a real MCP resumption attempt. +2. Reuse the stores' atomic `consume_scoped` paths and enforce matching scope on both issue and resume. Existing MCP `_meta` credential fields and business-argument filtering remain compatible. Avoid returning digest, credential, or raw policy input in diagnostics. +3. Build against all three candidate SDKs. Run component and transport tests, and check A2A, CLI, or other consumers where handler construction or forwarded results are affected. Keep unaffected consumers on their established compatibility gates. + +## Acceptance Criteria + +- [ ] Installed MCP and Core packages demonstrate pending approval and exactly one resumed execution with matching scope. +- [ ] Older incompatible records are rejected in the new scope without a wildcard or consume-then-fallback path. +- [ ] Supported MCP transport fields and adapter compatibility checks pass in all affected profiles. + +## Dependencies + +Depends on Python, TypeScript, and Rust. Required by integration. + +## Estimated Time + +6 hours. + +## Design Decisions Reference + +See [plan.md](../plan.md#design-decisions) for persisted approval records and public compatibility. diff --git a/planning/post-validation-policy/tasks/typescript.md b/planning/post-validation-policy/tasks/typescript.md new file mode 100644 index 00000000..162ca1ce --- /dev/null +++ b/planning/post-validation-policy/tasks/typescript.md @@ -0,0 +1,35 @@ +# TypeScript Post-validation Policy + +## Goal + +Implement the approved contract in the portable and Node TypeScript SDK assemblies. + +## Files Involved + +- `typescript/src/builtin-steps.ts`, `executor.ts`, `pipeline.ts`, `registry/`, `extensions.ts`, `approval.ts`, `errors.ts`, and existing public entry points. +- `typescript/tests/` public conformance, approval, execution, and streaming tests. + +## Steps + +1. Read `typescript/CLAUDE.md`. Add red public-entry tests for the contract and for recovery that would otherwise hide a terminal policy denial. +2. Integrate the evaluator through instance-owned `ExtensionManager` wiring. Capture the resolved registration version and the validated invocation snapshot. Ensure the actual execute and producer input is the covered snapshot. +3. Reuse existing gate and token storage. Protect the executor-level result from policy bypass through step jumps or error middleware. Verify a policy evaluator installed on one client does not affect other clients. +4. Run `pnpm exec vitest run` with the shared driver and focused suites, then the normal SDK checks. Package and verify direct calls and stream behavior from the portable and full entries. + +## Acceptance Criteria + +- [ ] Shared policy cases pass through `call`, preflight, and the native stream API. +- [ ] The portable profile remains free of Node-only imports from policy wiring and digest implementation. +- [ ] Conformance covers mutation attempts and denied recovery after the final authorization boundary. + +## Dependencies + +Depends on the shared contract. Required by Surfaces and integration. + +## Estimated Time + +6 hours. + +## Design Decisions Reference + +See [plan.md](../plan.md#design-decisions) for approval timing and the argument snapshot. diff --git a/python/apcore-conformance.yaml b/python/apcore-conformance.yaml index 3e27cea9..13a734e6 100644 --- a/python/apcore-conformance.yaml +++ b/python/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-python - version: 1.0.0a2 + version: 1.0.0a3 language: python spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/python/pyproject.toml b/python/pyproject.toml index 4907b234..d8943482 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "apcore" -version = "1.0.0a2" +version = "1.0.0a3" description = "Build once, invoke by code or AI — with schema, ACL, approval, and audit enforced at every call" readme = "README.md" requires-python = ">=3.11" diff --git a/python/src/apcore/__init__.py b/python/src/apcore/__init__.py index 051a0ac3..ff88d91e 100644 --- a/python/src/apcore/__init__.py +++ b/python/src/apcore/__init__.py @@ -145,6 +145,8 @@ ModuleNotFoundError, ModuleReloadConflictError, ModuleTimeoutError, + PolicyDeniedError, + PolicyEvaluationError, ReloadFailedError, SysModuleRegistrationError, SysModulesDisabledError, @@ -169,7 +171,14 @@ ) # Execution-time governance policy (apcore#76 RFC pilot) -from apcore.policy import ExecutionPolicy, PolicyDecision, PolicyRule +from apcore.policy import ( + ExecutionPolicy, + PolicyDecision, + PolicyEvaluationRequest, + PolicyEvaluator, + PolicyRule, + PolicyVerdict, +) # Middleware from apcore.middleware import ( @@ -596,6 +605,11 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st "Context", "ErrorCodes", "ExecutionPolicy", + "PolicyDeniedError", + "PolicyEvaluationError", + "PolicyEvaluationRequest", + "PolicyEvaluator", + "PolicyVerdict", "ExecutionStrategy", "Executor", "Identity", diff --git a/python/src/apcore/_post_validation_policy.py b/python/src/apcore/_post_validation_policy.py new file mode 100644 index 00000000..26a0103b --- /dev/null +++ b/python/src/apcore/_post_validation_policy.py @@ -0,0 +1,177 @@ +"""Keep policy evaluation and approval bound to the dispatch snapshot.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import math +import re +import struct +import time +from contextlib import suppress +from copy import copy, deepcopy +from typing import TYPE_CHECKING, Any + +from apcore.errors import PolicyEvaluationError +from apcore.context import _APPROVAL_TOKEN_KEY +from apcore.policy import PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict + +if TYPE_CHECKING: + from apcore.cancel import CancelToken + from apcore.context import Context + from apcore.pipeline import PipelineContext + +_SAFE_INT = (1 << 53) - 1 +_RULE_ID = re.compile(r"[A-Za-z0-9_.-]{1,64}\Z") +_EVALUATOR_TIMEOUT_SECONDS = 1.0 + + +def _scope_text(value: Any) -> str: + """Encode supported native values without conflating distinct numbers.""" + if value is None: + return "null" + if type(value) is bool: + return "true" if value else "false" + if type(value) is int and abs(value) <= _SAFE_INT: + return f"i{value};" + if type(value) is float and math.isfinite(value) and (not value.is_integer() or abs(value) <= _SAFE_INT): + return f"f{struct.pack('>d', value).hex()};" + if type(value) is str: + return json.dumps(value, ensure_ascii=False) + if type(value) is list: + return "[" + ",".join(_scope_text(item) for item in value) + "]" + if type(value) is dict and all(type(key) is str for key in value): + keys = sorted(value, key=lambda key: key.encode("utf-16-be")) + return "{" + ",".join(f"{_scope_text(key)}:{_scope_text(value[key])}" for key in keys) + "}" + raise ValueError("Unsupported value in policy scope") + + +def _argument_digest(arguments: dict[str, Any]) -> str: + try: + encoded = _scope_text(arguments).encode("utf-8") + except (ValueError, RecursionError, KeyError, RuntimeError): + raise PolicyEvaluationError() from None + return hashlib.sha256(encoded).hexdigest() + + +class _PolicyInvocation: + """Record the selected invocation before middleware or provider callbacks.""" + + def __init__(self, ctx: PipelineContext, version: str | None) -> None: + self.module_id = ctx.module_id + self.module = ctx.module + self.version = version + self.caller_id = ctx.context.caller_id + try: + self.identity = deepcopy(ctx.context.identity) + except Exception: + raise PolicyEvaluationError() from None + self.arguments: dict[str, Any] | None = None + self.digest: str | None = None + self.authorized = False + + def capture(self, ctx: PipelineContext) -> None: + arguments = ctx.validated_inputs + if arguments is None or _APPROVAL_TOKEN_KEY in arguments: + raise PolicyEvaluationError() + self.digest = _argument_digest(arguments) + self.arguments = deepcopy(arguments) + + def _check_binding(self, ctx: PipelineContext) -> None: + if ( + ctx.module_id != self.module_id + or ctx.module is not self.module + or ctx.context.caller_id != self.caller_id + or ctx.context.identity != self.identity + ): + raise PolicyEvaluationError() + + def checked_arguments(self, ctx: PipelineContext) -> dict[str, Any]: + self._check_binding(ctx) + capture = deepcopy(self.arguments) + if ( + ctx.validated_inputs is None + or capture is None + or self.digest is None + or _argument_digest(ctx.validated_inputs) != self.digest + or _argument_digest(capture) != self.digest + ): + raise PolicyEvaluationError() + return capture + + def preflight_snapshot(self, ctx: PipelineContext) -> tuple[dict[str, Any], Context[Any]]: + self._check_binding(ctx) + if self.arguments is None or self.digest is None or _argument_digest(self.arguments) != self.digest: + raise PolicyEvaluationError() + context = copy(ctx.context) + context.identity = deepcopy(self.identity) + context.call_chain = list(ctx.context.call_chain) + return self.arguments, context + + +async def _evaluate_policy( + evaluator: PolicyEvaluator, + request: PolicyEvaluationRequest, + token: CancelToken | None, + deadline: float | None, +) -> PolicyVerdict: + """Bound a trusted provider independently of its cancellation cooperation.""" + if token is not None: + token.check() + remaining = _EVALUATOR_TIMEOUT_SECONDS + if deadline is not None: + remaining = min(remaining, deadline - time.time()) + if remaining <= 0: + raise PolicyEvaluationError() + + loop = asyncio.get_running_loop() + expires_at = loop.time() + remaining + cancelled = loop.create_future() + + def report_cancellation() -> None: + if not cancelled.done(): + cancelled.set_result(None) + + def signal_cancellation() -> None: + with suppress(RuntimeError): + loop.call_soon_threadsafe(report_cancellation) + + unsubscribe = token._listen(signal_cancellation) if token is not None else None + task = asyncio.create_task(_read_verdict(evaluator, request)) + try: + await asyncio.wait((task, cancelled), timeout=remaining, return_when=asyncio.FIRST_COMPLETED) + if token is not None: + token.check() + # A non-yielding evaluator can finish before the loop services its timer. + if not task.done() or loop.time() >= expires_at: + raise PolicyEvaluationError() + return task.result() + finally: + if unsubscribe is not None: + unsubscribe() + cancelled.cancel() + if not task.done(): + task.cancel() + task.add_done_callback(_consume_result) + elif not task.cancelled(): + task.exception() + + +async def _read_verdict(evaluator: PolicyEvaluator, request: PolicyEvaluationRequest) -> PolicyVerdict: + try: + verdict = await evaluator.evaluate(request) + if isinstance(verdict, PolicyVerdict) and verdict.decision in ("allow", "deny", "require_approval"): + return verdict + except (Exception, asyncio.CancelledError): + pass + raise PolicyEvaluationError() + + +def _consume_result(task: asyncio.Future[PolicyVerdict]) -> None: + if not task.cancelled(): + task.exception() + + +def _safe_rule_id(rule_id: str | None) -> str | None: + return rule_id if isinstance(rule_id, str) and _RULE_ID.fullmatch(rule_id) else None diff --git a/python/src/apcore/approval.py b/python/src/apcore/approval.py index ab2ea10f..4bc778f8 100644 --- a/python/src/apcore/approval.py +++ b/python/src/apcore/approval.py @@ -37,8 +37,9 @@ class ApprovalRequest: Attributes: module_id: Canonical module ID being invoked. - arguments: Detached call arguments at the approval gate, before module - middleware rewrites or input validation. + arguments: Detached call arguments at the approval gate. When + ``canonical_args_digest`` is present, these are the validated + arguments covered by the final approval. context: Full execution context (trace_id, identity, call_chain). annotations: Module's annotation set (requires_approval is guaranteed true). description: Module's human-readable description. @@ -54,6 +55,8 @@ class ApprovalRequest: without cross-referencing ``module_id`` (spec decision D-03). Defaults to ``""`` for the same field-ordering reason as ``caller_id``; ``BuiltinApprovalGate`` always supplies it explicitly. + module_version: Selected module version for a final approval. + canonical_args_digest: SHA-256 binding for a final approval's arguments. """ module_id: str @@ -64,6 +67,8 @@ class ApprovalRequest: tags: list[str] = field(default_factory=list) caller_id: str | None = None action: str = "" + module_version: str | None = None + canonical_args_digest: str | None = field(default=None, repr=False) @dataclass(frozen=True) @@ -109,7 +114,11 @@ async def check_approval(self, approval_id: str) -> ApprovalResult: @runtime_checkable class ScopedApprovalHandler(ApprovalHandler, Protocol): - """An approval handler that supports resuming a specific invocation.""" + """An approval handler that supports resuming a specific invocation. + + Set ``supports_final_scope = True`` when issuance and resumption verify + the version and canonical argument digest as well as the existing scope. + """ async def check_approval_for_call(self, approval_id: str, request: ApprovalRequest) -> ApprovalResult: """Validate the current call's identity, target and arguments, then consume the approval.""" diff --git a/python/src/apcore/builtin_steps.py b/python/src/apcore/builtin_steps.py index 3f6ac088..357aad21 100644 --- a/python/src/apcore/builtin_steps.py +++ b/python/src/apcore/builtin_steps.py @@ -17,11 +17,12 @@ import logging import time from collections.abc import Awaitable, Callable -from copy import deepcopy -from typing import TYPE_CHECKING, Any, cast +from copy import copy, deepcopy +from typing import TYPE_CHECKING, Any, Literal, cast import pydantic +from apcore._post_validation_policy import _evaluate_policy, _PolicyInvocation, _safe_rule_id from apcore.approval import ApprovalRequest, ApprovalResult, ScopedApprovalHandler from apcore.cancel import CancelToken, ExecutionCancelledError from apcore.context import Context, GovernanceProjection @@ -37,6 +38,8 @@ ModuleExecuteError, ModuleNotFoundError, ModuleTimeoutError, + PolicyDeniedError, + PolicyEvaluationError, SchemaValidationError, StreamingInterfaceError, ) @@ -49,7 +52,13 @@ PipelineContext, StepResult, ) -from apcore.policy import ExecutionPolicy, PolicyDecision, strip_approval_token +from apcore.policy import ( + ExecutionPolicy, + PolicyDecision, + PolicyEvaluationRequest, + PolicyEvaluator, + strip_approval_token, +) from apcore.schema.annotations import governance_union from apcore.schema.hardening import warn_format_violations from apcore.schema.types import _validation_failure_message @@ -414,20 +423,30 @@ def _resolve_redaction(config: Any | None) -> RedactionConfig: def _redact_payload(data: dict[str, Any] | None, schema_model: Any, rules: RedactionConfig | None) -> dict[str, Any]: from apcore.utils.redaction import redact_sensitive - schema: Any = getattr(schema_model, "__apcore_source_schema__", None) - if not isinstance(schema, dict): - schema_json = getattr(schema_model, "model_json_schema", None) - schema = schema_json() if callable(schema_json) else {} rules = rules or _resolve_redaction(None) return redact_sensitive( data or {}, - schema, + _input_schema_json(schema_model), sensitive_keys=rules.sensitive_keys, regex_patterns=rules.compiled_regex_patterns, replacement=rules.replacement, ) +def _input_schema_json(schema_model: Any) -> dict[str, Any]: + if isinstance(schema_model, dict): + return schema_model + schema = getattr(schema_model, "__apcore_source_schema__", None) + if isinstance(schema, dict): + return schema + schema_json = getattr(schema_model, "model_json_schema", None) + if callable(schema_json): + schema = schema_json() + if isinstance(schema, dict): + return schema + return {} + + class BuiltinModuleLookup(BaseStep): """Resolve module from registry by ID with optional version hint. @@ -474,6 +493,7 @@ def _set_toggle_state(self, toggle_state: ToggleState) -> None: async def execute(self, ctx: PipelineContext) -> StepResult: version_hint = getattr(ctx, "version_hint", None) resolve = getattr(type(self._registry), "_resolve_registration", None) + version = None if resolve is not None: if ctx.execution_scope is not None: token = ( @@ -498,6 +518,8 @@ def release_lease() -> None: registration = resolve(self._registry, ctx.module_id, version_hint) module = registration.module if registration is not None else None declared_annotations = registration.metadata.get("annotations") if registration is not None else None + if ctx._policy_enabled and registration is not None: + version = registration.metadata.get("version") else: if version_hint is not None: module = self._registry.get(ctx.module_id, version_hint=version_hint) @@ -517,6 +539,8 @@ def release_lease() -> None: raise ModuleDisabledError(module_id=ctx.module_id) ctx.module = module + if ctx._policy_enabled: + ctx._policy_invocation = _PolicyInvocation(ctx, version) # PROTOCOL_SPEC §7.4 (D-96): resolve the registry's DECLARED annotations # here and hand them to the gate, which has no registry of its own — # the same shape as `acl_approval_required`, which Step 4 computes and @@ -577,6 +601,7 @@ def __init__(self, *, acl: Any | None = None, event_emitter: Any | None = None) replaceable=True, pure=True, requires=("context", "module"), + provides=("acl_decision",), ) self._acl = acl self._event_emitter = event_emitter @@ -751,10 +776,7 @@ def policy(self) -> ExecutionPolicy: """The ExecutionPolicy this gate applies (read by ``governance_state()``, §6.6.5.5).""" return self._policy - async def execute(self, ctx: PipelineContext) -> StepResult: - module = ctx.module - approval_token = ctx._take_approval_token() - + def _approval_requirements(self, ctx: PipelineContext) -> tuple[Any, PolicyDecision, bool]: # PROTOCOL_SPEC §6.1.6 / §7.4: Step 4's second result. The gate fires on # the UNION of the module annotation, this, and gate_destructive (§6.9 # rows 3-5) — an implementation that reads only the annotation silently @@ -771,7 +793,7 @@ async def execute(self, ctx: PipelineContext) -> StepResult: # so a metadata `false` would cancel a module that asks to be gated. # Both single-source readings are fail-OPEN. governance = governance_union( - getattr(module, "annotations", None), + getattr(ctx.module, "annotations", None), getattr(ctx, "declared_annotations", None), ) @@ -796,13 +818,24 @@ async def execute(self, ctx: PipelineContext) -> StepResult: # silently strip a requirement an ACL author attached to one # untrusted caller. Union is the only safe composition, so the OR # here is load-bearing and not a convenience. - needs_approval = decision.needs_approval or acl_requires_approval - effective_destructive = decision.destructive + return governance, decision, decision.needs_approval or acl_requires_approval + + @staticmethod + def _effective_annotations(governance: Any, decision: PolicyDecision, required: bool) -> ModuleAnnotations: + return dataclasses.replace( + _coerce_annotations(governance), + requires_approval=required, + destructive=decision.destructive, + ) + + async def execute(self, ctx: PipelineContext) -> StepResult: + approval_token = None if ctx._policy_enabled else ctx._take_approval_token() + governance, decision, required = self._approval_requirements(ctx) if decision.overridden: self._emit_policy_audit(decision, ctx.context) - if not needs_approval: - if effective_destructive: + if not required: + if decision.destructive: self._warn_once( f"destructive_ungated:{ctx.module_id}", "Module '%s' is annotated destructive=True but is not covered by the " @@ -811,19 +844,23 @@ async def execute(self, ctx: PipelineContext) -> StepResult: "gate_destructive=True). (apcore#76)", ctx.module_id, ) + + if required and self._handler is None and self._policy.strict: + result = ApprovalResult( + status="rejected", + reason="Approval required but no ApprovalHandler is configured; ExecutionPolicy(strict=True) fails closed", + ) + self._emit_audit(result, ctx.module_id, ctx.context) + raise ApprovalDeniedError(result=result, module_id=ctx.module_id) + + if ctx._policy_enabled: + ctx._policy_annotations = self._effective_annotations(governance, decision, required) + return StepResult(action="continue") + + if not required: return StepResult(action="continue") if self._handler is None: - if self._policy.strict: - result = ApprovalResult( - status="rejected", - reason=( - "Approval required but no ApprovalHandler is configured; " - "ExecutionPolicy(strict=True) fails closed" - ), - ) - self._emit_audit(result, ctx.module_id, ctx.context) - raise ApprovalDeniedError(result=result, module_id=ctx.module_id) self._warn_once( f"no_handler:{ctx.module_id}", "Module '%s' requires approval but no ApprovalHandler is configured; " @@ -833,25 +870,105 @@ async def execute(self, ctx: PipelineContext) -> StepResult: ) return StepResult(action="continue") - annotations = dataclasses.replace( - _coerce_annotations(governance), requires_approval=True, destructive=effective_destructive - ) - request = ApprovalRequest( - module_id=ctx.module_id, - arguments=deepcopy(ctx.inputs), - context=ctx.context, - annotations=annotations, - description=getattr(module, "description", None), - tags=list(getattr(module, "tags", None) or []), - caller_id=ctx.context.caller_id, - action=ctx.module_id, - ) + request = self._request(ctx, self._effective_annotations(governance, decision, required), ctx.inputs) if approval_token is None: result = await self._handler.request_approval(request) elif isinstance(self._handler, ScopedApprovalHandler): result = await self._handler.check_approval_for_call(approval_token, request) else: result = ApprovalResult(status="rejected", reason="The approval handler does not support scoped resumption") + return self._finish_approval(ctx, result, approval_token) + + @staticmethod + def _request( + ctx: PipelineContext, + annotations: ModuleAnnotations, + arguments: dict[str, Any], + invocation: _PolicyInvocation | None = None, + ) -> ApprovalRequest: + context = ctx.context + if invocation is not None: + context = copy(context) + context.call_chain = list(context.call_chain) + context.identity = deepcopy(invocation.identity) + return ApprovalRequest( + module_id=ctx.module_id, + arguments=deepcopy(arguments), + context=context, + annotations=annotations, + description=getattr(ctx.module, "description", None), + tags=list(getattr(ctx.module, "tags", None) or []), + caller_id=context.caller_id, + action=ctx.module_id, + module_version=invocation.version if invocation is not None else None, + canonical_args_digest=invocation.digest if invocation is not None else None, + ) + + async def _authorize_final( + self, ctx: PipelineContext, invocation: _PolicyInvocation, annotations: ModuleAnnotations + ) -> None: + approval_token = ctx._take_approval_token() + if not annotations.requires_approval and approval_token is None: + return + handler = self._handler + supports_final_scope = ( + isinstance(handler, ScopedApprovalHandler) and getattr(handler, "supports_final_scope", False) is True + ) + if handler is None or (approval_token is not None and not supports_final_scope): + result = ApprovalResult("rejected", reason="Final approval requires a compatible handler") + self._finish_approval(ctx, result, approval_token) + return + + request = self._request( + ctx, dataclasses.replace(annotations, requires_approval=True), invocation.checked_arguments(ctx), invocation + ) + try: + if approval_token is not None: + result = await handler.check_approval_for_call(approval_token, request) + else: + result = await handler.request_approval(request) + except ExecutionCancelledError: + raise + except Exception: + result = ApprovalResult("rejected") + if not isinstance(result, ApprovalResult): + result = ApprovalResult("rejected") + status = self._final_status(result) + if status == "pending" and not supports_final_scope: + result = ApprovalResult("rejected", reason="Final approval requires a compatible handler") + elif not self._safe_pending(result, status, invocation.digest): + # Approval providers can see sensitive arguments. Keep their + # arbitrary diagnostics out of the invocation trace and audit. + result = ApprovalResult( + status=status, + approval_id=result.approval_id if status == "pending" else None, + audit_id=result.audit_id + if isinstance(result.audit_id, str) and result.audit_id != invocation.digest + else None, + ) + self._finish_approval(ctx, result, approval_token) + + @staticmethod + def _final_status(result: ApprovalResult) -> Literal["approved", "rejected", "timeout", "pending"]: + if result.status in ("approved", "rejected", "timeout"): + return result.status + if result.status == "pending" and isinstance(result.approval_id, str) and result.approval_id: + return "pending" + return "rejected" + + @staticmethod + def _safe_pending(result: ApprovalResult, status: str, digest: str | None) -> bool: + # Transports can correlate the pending result by identity. Preserve it + # only when the handler has already stripped untrusted diagnostics. + return ( + status == "pending" + and result.reason is None + and result.approved_by is None + and result.metadata is None + and (result.audit_id is None or isinstance(result.audit_id, str) and result.audit_id != digest) + ) + + def _finish_approval(self, ctx: PipelineContext, result: ApprovalResult, approval_token: str | None) -> StepResult: self._emit_audit(result, ctx.module_id, ctx.context, approval_token) if result.status == "approved": @@ -1223,6 +1340,8 @@ async def execute(self, ctx: PipelineContext) -> StepResult: input_schema = getattr(module, "input_schema", None) if input_schema is None: ctx.validated_inputs = ctx.inputs + if ctx._policy_invocation is not None: + ctx._policy_invocation.capture(ctx) if ctx.context is not None and hasattr(ctx.context, "redacted_inputs"): ctx.context.redacted_inputs = _redact_payload(strip_approval_token(ctx.inputs), None, self._redaction) return StepResult(action="continue") @@ -1244,6 +1363,9 @@ async def execute(self, ctx: PipelineContext) -> StepResult: **{key: getattr(validated, key) for key in fields}, } + if ctx._policy_invocation is not None: + ctx._policy_invocation.capture(ctx) + # Redact sensitive fields after successful validation if ctx.context is not None and hasattr(ctx.context, "redacted_inputs"): ctx.context.redacted_inputs = _redact_payload( @@ -1253,6 +1375,85 @@ async def execute(self, ctx: PipelineContext) -> StepResult: return StepResult(action="continue") +class _BuiltinPostValidationPolicy(BaseStep): + _fail_closed_on_error = True + + def __init__(self, evaluator: PolicyEvaluator, approval: BuiltinApprovalGate) -> None: + super().__init__( + name="post_validation_policy", + description="Authorize the validated invocation", + removable=False, + replaceable=False, + pure=True, + requires=("acl_decision", "validated_inputs"), + ) + self._evaluator = evaluator + self._approval = approval + + async def execute(self, ctx: PipelineContext) -> StepResult: + from apcore.utils.redaction import sensitive_field_paths + + invocation = ctx._policy_invocation + if invocation is None: + raise PolicyEvaluationError() + arguments = invocation.checked_arguments(ctx) + schema = _input_schema_json(getattr(ctx.module, "input_schema", None)) + fields = sensitive_field_paths(arguments, schema) + request = PolicyEvaluationRequest( + module_id=invocation.module_id, + module_version=invocation.version, + caller_id=invocation.caller_id, + identity=deepcopy(invocation.identity), + arguments=deepcopy(arguments), + sensitive_fields=fields, + ) + ctx._policy_evaluation_active = True + try: + verdict = await _evaluate_policy( + self._evaluator, request, ctx.context.cancel_token, ctx.context.global_deadline + ) + finally: + ctx._policy_evaluation_active = False + if not ctx.dry_run: + self._emit_decision(ctx, verdict.decision, _safe_rule_id(verdict.rule_id), fields) + if verdict.decision == "deny": + raise PolicyDeniedError() + + if ctx.dry_run: + _, _, required = self._approval._approval_requirements(ctx) + ctx._policy_requires_approval = required or verdict.decision == "require_approval" + else: + annotations = ctx._policy_annotations + if annotations is None: + raise PolicyEvaluationError() + required = annotations.requires_approval or verdict.decision == "require_approval" + await self._approval._authorize_final( + ctx, invocation, dataclasses.replace(annotations, requires_approval=required) + ) + invocation.authorized = True + return StepResult(action="continue") + + def _emit_decision(self, ctx: PipelineContext, decision: str, rule_id: str | None, fields: tuple[str, ...]) -> None: + data = {"decision": decision, "rule_id": rule_id, "sensitive_fields": list(fields)} + span = _current_trace_span(ctx.context, include_parent=True) + if span is not None: + span.events.append({"name": "apcore.policy.decision", **data}) + if self._approval._event_emitter is not None: + from datetime import datetime, timezone + + from apcore.events.emitter import ApCoreEvent + + self._approval._event_emitter.emit( + ApCoreEvent( + event_type="apcore.policy.decision", + module_id=ctx.module_id, + timestamp=datetime.now(timezone.utc).isoformat(), + severity="warn" if decision == "deny" else "info", + data=data, + ) + ) + + # --------------------------------------------------------------------------- # Step 8: Execute # --------------------------------------------------------------------------- @@ -1307,7 +1508,13 @@ async def execute(self, ctx: PipelineContext) -> StepResult: if global_deadline is not None and time.time() > global_deadline: raise self._end_for_timeout(ctx, int(default_timeout)) - inputs = ctx.validated_inputs if ctx.validated_inputs is not None else ctx.inputs + if ctx._policy_enabled: + invocation = ctx._policy_invocation + if invocation is None or not invocation.authorized: + raise PolicyEvaluationError() + inputs = invocation.checked_arguments(ctx) + else: + inputs = ctx.validated_inputs if ctx.validated_inputs is not None else ctx.inputs if ctx.stream: from apcore.registry.registry import _validate_streaming_signature @@ -1579,6 +1786,34 @@ async def execute(self, ctx: PipelineContext) -> StepResult: # --------------------------------------------------------------------------- +def _bind_post_validation_policy(strategy: ExecutionStrategy, evaluator: PolicyEvaluator) -> ExecutionStrategy: + """Require the real governance and dispatch steps in execution order.""" + expected: list[tuple[str, type[BaseStep]]] = [ + ("context_creation", BuiltinContextCreation), + ("call_chain_guard", BuiltinCallChainGuard), + ("module_lookup", BuiltinModuleLookup), + ("acl_check", BuiltinACLCheck), + ("approval_gate", BuiltinApprovalGate), + ] + if "middleware_before" in strategy.step_names(): + expected.append(("middleware_before", BuiltinMiddlewareBefore)) + expected.extend((("input_validation", BuiltinInputValidation), ("execute", BuiltinExecute))) + before_dispatch = strategy.steps[: len(expected)] + if len(before_dispatch) != len(expected) or any( + type(step) is not expected_type or step.name != name or getattr(step, "match_modules", None) is not None + for step, (name, expected_type) in zip(before_dispatch, expected, strict=True) + ): + raise ConfigurationError("Post-validation policy requires the ordered built-in governance and execution steps") + if "post_validation_policy" in strategy.step_names(): + raise ConfigurationError("The post_validation_policy step is installed by the executor") + + approval = cast(BuiltinApprovalGate, before_dispatch[4]) + bound = copy(strategy) + bound.steps = list(strategy.steps) + bound.insert_before("execute", _BuiltinPostValidationPolicy(evaluator, approval)) + return bound + + def build_standard_strategy( *, registry: Any, diff --git a/python/src/apcore/errors.py b/python/src/apcore/errors.py index 91f2aff0..dca192ca 100644 --- a/python/src/apcore/errors.py +++ b/python/src/apcore/errors.py @@ -29,6 +29,8 @@ "ApprovalDeniedError", "ApprovalTimeoutError", "ApprovalPendingError", + "PolicyDeniedError", + "PolicyEvaluationError", "ModuleNotFoundError", "ModuleDisabledError", "ModuleTimeoutError", @@ -317,6 +319,31 @@ def target_id(self) -> str: return self.details["target_id"] +class PolicyDeniedError(ModuleError): + """The configured policy denied the validated invocation.""" + + def __init__(self) -> None: + super().__init__( + code="POLICY_DENIED", + message="Policy denied the validated invocation", + retryable=False, + user_fixable=True, + ai_guidance="Review the request against the host's policy before trying again.", + ) + + +class PolicyEvaluationError(ModuleError): + """The configured policy could not safely evaluate the invocation.""" + + def __init__(self) -> None: + super().__init__( + code="POLICY_EVALUATION_ERROR", + message="Policy evaluation failed", + retryable=True, + user_fixable=False, + ) + + class ApprovalError(ModuleError): """Base error for all approval-related errors. @@ -1452,6 +1479,8 @@ class ErrorCodes: APPROVAL_DENIED = "APPROVAL_DENIED" APPROVAL_TIMEOUT = "APPROVAL_TIMEOUT" APPROVAL_PENDING = "APPROVAL_PENDING" + POLICY_DENIED = "POLICY_DENIED" + POLICY_EVALUATION_ERROR = "POLICY_EVALUATION_ERROR" VERSION_INCOMPATIBLE = "VERSION_INCOMPATIBLE" ERROR_CODE_COLLISION = "ERROR_CODE_COLLISION" GENERAL_NOT_IMPLEMENTED = "GENERAL_NOT_IMPLEMENTED" diff --git a/python/src/apcore/executor.py b/python/src/apcore/executor.py index 767d0580..d9bfa773 100644 --- a/python/src/apcore/executor.py +++ b/python/src/apcore/executor.py @@ -19,7 +19,12 @@ from apcore._sync_bridge import _SyncBridge from apcore.acl import ACL from apcore.approval import ApprovalHandler -from apcore.builtin_steps import BuiltinContextCreation, BuiltinModuleLookup, _is_idempotent +from apcore.builtin_steps import ( + BuiltinContextCreation, + BuiltinModuleLookup, + _bind_post_validation_policy, + _is_idempotent, +) from apcore.cancel import CancelToken, ExecutionCancelledError from apcore.config import Config from apcore.context import Context @@ -35,6 +40,7 @@ ModuleError, ModuleNotFoundError, ModuleTimeoutError, + PolicyEvaluationError, SchemaValidationError, ) from apcore.utils.error_propagation import propagate_error @@ -54,7 +60,7 @@ PreviewResult, ) -from apcore.policy import ExecutionPolicy, strip_approval_token +from apcore.policy import ExecutionPolicy, PolicyEvaluator, strip_approval_token from apcore.pipeline import ( AbortReason, ExecutionStrategy, @@ -296,6 +302,7 @@ def __init__( config: Config | None = None, approval_handler: ApprovalHandler | None = None, policy: ExecutionPolicy | None = None, + policy_evaluator: PolicyEvaluator | None = None, event_emitter: Any = None, toggle_state: Any = None, sync_bridge_timeout_ms: int | None = None, @@ -314,6 +321,7 @@ def __init__( approval_handler: Optional approval handler for Step 5 gate. policy: Optional ExecutionPolicy with execution-time governance overrides for the Step 5 gate (apcore#76 RFC pilot). + policy_evaluator: Optional evaluator for the validated invocation. event_emitter: Optional EventEmitter. When provided, the executor emits apcore.stream.post_validation_failed events so post-stream failures (which cannot un-send already-yielded @@ -389,6 +397,7 @@ def __init__( # instance never received them, so a deny-all ACL let every call through # while governance_state() reported the gate as configured and wired. self._strategy = self._bind_providers(self._strategy) + self.set_policy_evaluator(policy_evaluator) self._pipeline_engine = PipelineEngine() @@ -425,6 +434,7 @@ def from_registry( config: Config | None = None, approval_handler: ApprovalHandler | None = None, policy: ExecutionPolicy | None = None, + policy_evaluator: PolicyEvaluator | None = None, sync_bridge_timeout_ms: int | None = None, ) -> Executor: """Convenience factory for creating an Executor from a Registry. @@ -437,6 +447,7 @@ def from_registry( config: Optional configuration. approval_handler: Optional approval handler. policy: Optional execution-time governance policy (apcore#76). + policy_evaluator: Optional evaluator for the validated invocation. sync_bridge_timeout_ms: Optional wait limit for the sync thread bridge. Returns: @@ -450,6 +461,7 @@ def from_registry( config=config, approval_handler=approval_handler, policy=policy, + policy_evaluator=policy_evaluator, sync_bridge_timeout_ms=sync_bridge_timeout_ms, ) @@ -592,6 +604,14 @@ def set_policy(self, policy: ExecutionPolicy | None) -> None: if isinstance(step, BuiltinApprovalGate): step.set_policy(policy) + def set_policy_evaluator(self, evaluator: PolicyEvaluator | None) -> None: + """Install the evaluator for future invocations, or remove it with None.""" + if evaluator is not None: + if not isinstance(evaluator, PolicyEvaluator) or not callable(evaluator.evaluate): + raise InvalidInputError("Policy evaluator must implement evaluate()") + _bind_post_validation_policy(self._strategy, evaluator) + self._policy_evaluator = evaluator + def use(self, middleware: Middleware) -> Executor: """Add class-based middleware with duplicate detection and return self for chaining.""" self._middleware_manager.use(middleware) @@ -745,6 +765,7 @@ async def validate_async( inputs = business_inputs if business_inputs is not None else {} checks: list[PreflightCheckResult] = [] + evaluator = self._policy_evaluator # Check 0: module_id format (before pipeline) try: @@ -780,11 +801,15 @@ async def validate_async( context=context, dry_run=True, version_hint=version_hint, + _policy_enabled=evaluator is not None, ) trace = None try: - _, trace = await self._pipeline_engine.run(self._strategy, pipe_ctx) + strategy = self._strategy + if evaluator is not None: + strategy = _bind_post_validation_policy(strategy, evaluator) + _, trace = await self._pipeline_engine.run(strategy, pipe_ctx) except PipelineAbortError as e: trace = e.pipeline_trace except PipelineStepError as e: @@ -840,8 +865,8 @@ async def validate_async( # now reading the union, would stop the call the preflight waved # through. That disagreement is the one thing this method exists to # prevent. - requires_approval = False - if pipe_ctx.module is not None: + requires_approval = bool(pipe_ctx._policy_requires_approval) + if evaluator is None and pipe_ctx.module is not None: annotations = governance_union( getattr(pipe_ctx.module, "annotations", None), pipe_ctx.declared_annotations, @@ -888,16 +913,31 @@ async def validate_async( acl_denied = (acl_enforced and not pipe_ctx._acl_allowed) or any( c.check == _ACL_CHECK and not c.passed for c in checks ) + can_disclose = not acl_denied and (evaluator is None or pipe_ctx._policy_requires_approval is not None) + module = pipe_ctx.module if can_disclose else None + disclosure_inputs, disclosure_context = inputs, pipe_ctx.context + if evaluator is not None and module is not None: + try: + invocation = pipe_ctx._policy_invocation + if invocation is None: + raise PolicyEvaluationError() + disclosure_inputs, disclosure_context = invocation.preflight_snapshot(pipe_ctx) + except PolicyEvaluationError as exc: + checks.append(PreflightCheckResult(check=_preflight_check_for(exc), passed=False, error=exc.to_dict())) + module = None + + def callback_inputs() -> tuple[dict[str, Any], Context[Any]]: + if evaluator is None: + return disclosure_inputs, disclosure_context + callback_context = copy(disclosure_context) + callback_context.identity = deepcopy(disclosure_context.identity) + callback_context.call_chain = list(disclosure_context.call_chain) + return deepcopy(disclosure_inputs), callback_context # Module-level preflight (optional) - if ( - not acl_denied - and pipe_ctx.module is not None - and hasattr(pipe_ctx.module, "preflight") - and callable(pipe_ctx.module.preflight) - ): + if module is not None and callable(getattr(module, "preflight", None)): try: - preflight_warnings = pipe_ctx.module.preflight(inputs, pipe_ctx.context) + preflight_warnings = module.preflight(*callback_inputs()) if isinstance(preflight_warnings, list) and preflight_warnings: checks.append( PreflightCheckResult( @@ -922,14 +962,9 @@ async def validate_async( # surface the failure as a warning on the module_preview check rather # than failing validation. This mirrors preflight() exception semantics. predicted_changes: list[Change] = [] - if ( - not acl_denied - and pipe_ctx.module is not None - and hasattr(pipe_ctx.module, "preview") - and callable(pipe_ctx.module.preview) - ): + if module is not None and callable(getattr(module, "preview", None)): try: - raw = pipe_ctx.module.preview(inputs, pipe_ctx.context) + raw = module.preview(*callback_inputs()) # Support both sync and async preview() implementations. if inspect.isawaitable(raw): raw = await raw @@ -1053,6 +1088,9 @@ async def _run_call( ) -> tuple[dict[str, Any], PipelineTrace]: self._validate_module_id(module_id) effective_strategy = self._effective_strategy(strategy) + evaluator = self._policy_evaluator + if evaluator is not None: + effective_strategy = _bind_post_validation_policy(effective_strategy, evaluator) if context is None: context = Context.create() context.bind_executor(self) @@ -1072,6 +1110,7 @@ async def _run_call( version_hint=version_hint, invocation_deadline=invocation_deadline, execution_scope=execution_scope, + _policy_enabled=evaluator is not None, ) try: output, trace = await self._pipeline_engine.run(effective_strategy, pipe_ctx) @@ -1148,9 +1187,9 @@ async def _recover_from_call_error( cancelled = self._unwrap_cancellation(exc) if cancelled is not None: raise cancelled - recoverable = True + recoverable = not pipe_ctx._policy_pending if isinstance(exc, PipelineStepError): - recoverable = exc.recoverable + recoverable = recoverable and exc.recoverable if isinstance(exc.cause, Exception): exc = exc.cause ctx_obj = pipe_ctx.context @@ -1230,7 +1269,12 @@ def _open_stream( def source(observation: _StreamObservation, scope: AsyncExitStack) -> AsyncGenerator[dict[str, Any], None]: return self._stream(module_id, inputs, context, version_hint, scope, observation) - def timeout_error(pipeline: PipelineContext | None) -> ModuleTimeoutError: + def timeout_error(pipeline: PipelineContext | None) -> ModuleError: + if pipeline is not None and pipeline._policy_evaluation_active: + token = pipeline.context.cancel_token + if token is not None and token.is_cancelled: + return ExecutionCancelledError() + return PolicyEvaluationError() return self._stream_timeout_error(module_id, pipeline) return StreamExecution( @@ -1247,6 +1291,10 @@ async def _stream( observation: _StreamObservation, ) -> AsyncGenerator[dict[str, Any], None]: self._validate_module_id(module_id) + evaluator = self._policy_evaluator + strategy = self._strategy + if evaluator is not None: + strategy = _bind_post_validation_policy(strategy, evaluator) # PROTOCOL_SPEC §"Contract: Executor binding to Context": bind self # to the Context before pipeline step 1. @@ -1265,16 +1313,17 @@ async def _stream( stream=True, execution_scope=execution_scope, _stream_observation=observation, + _policy_enabled=evaluator is not None, ) observation.context = pipe_ctx - observation.steps = self._strategy.step_names() + observation.steps = strategy.step_names() observation.monitor(context) self._check_stream_context(pipe_ctx) # Phase 1: Run pipeline up to execute step. # BuiltinExecute detects ctx.stream=True and checks for module.stream(). try: - await self._pipeline_engine.run(self._strategy, pipe_ctx) + await self._pipeline_engine.run(strategy, pipe_ctx) except PipelineAbortError as e: raise self._translate_abort(e) from e except PipelineStepError as e: @@ -1383,9 +1432,7 @@ async def _stream( self._check_stream_context(pipe_ctx) pipe_ctx.output = accumulated observation.start_post_processing() - post_steps = [ - s for s in self._strategy.steps if s.name in ("output_validation", "middleware_after", "return_result") - ] + post_steps = [s for s in strategy.steps if s.name in ("output_validation", "middleware_after", "return_result")] if post_steps: # The post-stream sub-strategy is a slice of an already-validated # parent strategy; its ``requires`` keys (e.g. ``module``, @@ -1394,7 +1441,7 @@ async def _stream( # dependency check that would otherwise reject the slice. post_strategy = ExecutionStrategy("post_stream", post_steps, validate_dependencies=False) if observation.captures_completion: - post_strategy.step_middlewares.extend(self._strategy.step_middlewares) + post_strategy.step_middlewares.extend(strategy.step_middlewares) try: await self._pipeline_engine.run(post_strategy, pipe_ctx) except Exception as post_exc: diff --git a/python/src/apcore/extensions.py b/python/src/apcore/extensions.py index f62881bb..df58f811 100644 --- a/python/src/apcore/extensions.py +++ b/python/src/apcore/extensions.py @@ -16,6 +16,7 @@ from apcore.errors import InvalidInputError from apcore.middleware import Middleware from apcore.observability.tracing import Span, SpanExporter, TracingMiddleware +from apcore.policy import PolicyEvaluator from apcore.registry.registry import Discoverer, ModuleValidator if TYPE_CHECKING: @@ -88,6 +89,12 @@ def _built_in_points() -> dict[str, ExtensionPoint]: description="Approval handler for Step 4.5 gate", multiple=False, ), + "policy_evaluator": ExtensionPoint( + name="policy_evaluator", + extension_type=PolicyEvaluator, + description="Policy evaluator for validated invocations", + multiple=False, + ), } @@ -95,7 +102,7 @@ class ExtensionManager: """Manages extension points and their registered implementations. Pre-registers built-in extension points: discoverer, middleware, - acl, span_exporter, module_validator, and approval_handler. + acl, span_exporter, module_validator, approval_handler, and policy_evaluator. """ def __init__(self) -> None: @@ -210,6 +217,7 @@ def apply(self, registry: Registry, executor: Executor) -> None: - module_validator -> registry.set_validator() - acl -> executor.set_acl() - approval_handler -> executor.set_approval_handler() + - policy_evaluator -> executor.set_policy_evaluator() - middleware -> executor.use() for each - span_exporter -> find TracingMiddleware, set exporter (composite if multiple) @@ -237,6 +245,10 @@ def apply(self, registry: Registry, executor: Executor) -> None: if approval is not None: executor.set_approval_handler(approval) + evaluator = self.get("policy_evaluator") + if evaluator is not None: + executor.set_policy_evaluator(evaluator) + # Middleware for mw in self.get_all("middleware"): executor.use(mw) diff --git a/python/src/apcore/pipeline.py b/python/src/apcore/pipeline.py index adef2620..5ce29438 100644 --- a/python/src/apcore/pipeline.py +++ b/python/src/apcore/pipeline.py @@ -14,11 +14,13 @@ from typing import TYPE_CHECKING, Any, Callable, Protocol, runtime_checkable from apcore.context import _APPROVAL_TOKEN_KEY -from apcore.errors import InvalidInputError, ModuleError, ModuleTimeoutError +from apcore.errors import InvalidInputError, ModuleError, ModuleTimeoutError, PolicyEvaluationError from apcore.middleware.manager import MiddlewareChainError from apcore.utils.pattern import match_pattern if TYPE_CHECKING: + from apcore._post_validation_policy import _PolicyInvocation + from apcore.module import ModuleAnnotations from apcore.streaming import _StreamObservation _logger = logging.getLogger(__name__) @@ -143,11 +145,20 @@ class PipelineContext: module_task: asyncio.Future[Any] | None = None _stream_observation: _StreamObservation | None = field(default=None, repr=False, compare=False) _acl_allowed: bool = field(default=False, repr=False, compare=False) + _policy_enabled: bool = field(default=False, repr=False, compare=False) def __post_init__(self) -> None: # Keep the resume credential outside the public dataclass state. self._approval_token: str | None = None self._running_pipeline = False + self._policy_invocation: _PolicyInvocation | None = None + self._policy_annotations: ModuleAnnotations | None = None + self._policy_requires_approval: bool | None = None + self._policy_evaluation_active = False + + @property + def _policy_pending(self) -> bool: + return self._policy_enabled and (self._policy_invocation is None or not self._policy_invocation.authorized) def _separate_approval_token(self) -> str | None: """Separate the invocation's resume credential from module inputs.""" @@ -897,7 +908,11 @@ async def _run_steps( # Middleware instances, not StepMiddlewares, so they must not # be substituted for ``step_mws``. error_mws: Sequence[StepMiddleware] = step_mws - fail_closed = getattr(step, "_fail_closed_on_error", False) + fail_closed = ( + getattr(step, "_fail_closed_on_error", False) + or ctx._policy_pending + or isinstance(exc, PolicyEvaluationError) + ) recovery: Any = None if error_mws: err_state = PipelineState( @@ -1024,6 +1039,9 @@ async def _run_steps( trace=trace, ) elif result.action == "skip_to": + if ctx._policy_enabled and i < name_to_idx.get("execute", 0): + trace.total_duration_ms = (time.monotonic() - start) * 1000 + raise PipelineStepError(step.name, PolicyEvaluationError(), trace=trace, recoverable=False) target = result.skip_to if target is None: raise StepNotFoundError("skip_to target is None") diff --git a/python/src/apcore/policy.py b/python/src/apcore/policy.py index 15ace94b..fb69884f 100644 --- a/python/src/apcore/policy.py +++ b/python/src/apcore/policy.py @@ -22,21 +22,58 @@ from __future__ import annotations -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Literal, Protocol, runtime_checkable from apcore.context import _APPROVAL_TOKEN_KEY from apcore.utils.pattern import calculate_specificity, match_pattern if TYPE_CHECKING: # pragma: no cover - import cycle guard, types only - from apcore.context import Context - -__all__ = ["PolicyRule", "PolicyDecision", "ExecutionPolicy", "strip_approval_token"] + from apcore.context import Context, Identity + +__all__ = [ + "PolicyRule", + "PolicyDecision", + "ExecutionPolicy", + "PolicyEvaluationRequest", + "PolicyEvaluator", + "PolicyVerdict", + "strip_approval_token", +] _POLICY_KEYS = {"rules", "gate_destructive", "strict"} _RULE_KEYS = {"pattern", "requires_approval", "destructive", "reason"} +@dataclass(frozen=True) +class PolicyEvaluationRequest: + """Detached, validated invocation inputs for a trusted policy evaluator.""" + + module_id: str + module_version: str | None + caller_id: str | None + identity: Identity | None = field(repr=False) + arguments: dict[str, Any] = field(repr=False) + sensitive_fields: tuple[str, ...] + + +@dataclass(frozen=True) +class PolicyVerdict: + """A decision and an optional static identifier for the matched rule.""" + + decision: Literal["allow", "deny", "require_approval"] + rule_id: str | None = None + + +@runtime_checkable +class PolicyEvaluator(Protocol): + """A host-provided post-validation policy evaluator.""" + + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + """Evaluate the selected module and its validated arguments.""" + ... + + @dataclass(frozen=True) class PolicyRule: """A single pattern-based governance override. diff --git a/python/src/apcore/utils/redaction.py b/python/src/apcore/utils/redaction.py index de90fd2f..86a77e5f 100644 --- a/python/src/apcore/utils/redaction.py +++ b/python/src/apcore/utils/redaction.py @@ -111,11 +111,20 @@ def redact_sensitive( _COMBINATORS: tuple[str, ...] = ("anyOf", "oneOf", "allOf") +def sensitive_field_paths(data: dict[str, Any], schema: dict[str, Any]) -> tuple[str, ...]: + """Return JSON Pointers for input values marked sensitive by their schema.""" + paths: set[str] = set() + redactor = _SchemaRedactor(schema, REDACTED_VALUE, paths=paths) + redactor._redact_value(copy.deepcopy(data), schema, redactor._resolver) + return tuple(sorted(paths, key=lambda path: path.encode("utf-16-be"))) + + class _SchemaRedactor: """Walk data and local schema references together, without schema expansion.""" - def __init__(self, schema: dict[str, Any], token: str) -> None: + def __init__(self, schema: dict[str, Any], token: str, *, paths: set[str] | None = None) -> None: self._token = token + self._paths = paths declared_dialect = schema.get("$schema") self._root_dialect: str = ( declared_dialect if isinstance(declared_dialect, str) else "https://json-schema.org/draft/2020-12/schema" @@ -173,18 +182,20 @@ def _views(self, schema: dict[str, Any], resolver: Any) -> list[tuple[dict[str, pending.append((branch, context.in_subresource(self._resource(branch)))) return views - def _redact_value(self, value: Any, schema: dict[str, Any], resolver: Any) -> Any: + def _redact_value(self, value: Any, schema: dict[str, Any], resolver: Any, path: str = "") -> Any: views = self._views(schema, resolver) - if value is not None and any(view.get("x-sensitive") is True for view, _ in views): + if (value is not None or self._paths is not None) and any(view.get("x-sensitive") is True for view, _ in views): + if self._paths is not None: + self._paths.add(path) return self._token if isinstance(value, dict): - self._redact_object(value, views) + self._redact_object(value, views, path) elif isinstance(value, list): for view, context in views: - self._redact_array(value, view, context) + self._redact_array(value, view, context, path) return value - def _redact_array(self, values: list[Any], schema: dict[str, Any], resolver: Any) -> None: + def _redact_array(self, values: list[Any], schema: dict[str, Any], resolver: Any, path: str) -> None: items = schema.get("items") dialect = self._dialects.get(id(schema), self._root_dialect) legacy = "/draft-07/" in dialect or "/2019-09/" in dialect @@ -194,14 +205,16 @@ def _redact_array(self, values: list[Any], schema: dict[str, Any], resolver: Any for index, positional in enumerate(prefix[: len(values)]): if isinstance(positional, dict): context = resolver.in_subresource(self._resource(positional)) - values[index] = self._redact_value(values[index], positional, context) + child_path = f"{path}/{index}" if self._paths is not None else "" + values[index] = self._redact_value(values[index], positional, context, child_path) tail = schema.get("additionalItems") if tuple_items is not None else items if isinstance(tail, dict): context = resolver.in_subresource(self._resource(tail)) for index in range(len(prefix), len(values)): - values[index] = self._redact_value(values[index], tail, context) + child_path = f"{path}/{index}" if self._paths is not None else "" + values[index] = self._redact_value(values[index], tail, context, child_path) - def _redact_object(self, data: dict[str, Any], views: list[tuple[dict[str, Any], Any]]) -> None: + def _redact_object(self, data: dict[str, Any], views: list[tuple[dict[str, Any], Any]], path: str = "") -> None: for schema, resolver in views: properties = schema.get("properties") if not isinstance(properties, dict): @@ -209,7 +222,10 @@ def _redact_object(self, data: dict[str, Any], views: list[tuple[dict[str, Any], for name, field_schema in properties.items(): if name in data and isinstance(field_schema, dict): child = resolver.in_subresource(self._resource(field_schema)) - data[name] = self._redact_value(data[name], field_schema, child) + child_path = ( + f"{path}/{name.replace('~', '~0').replace('/', '~1')}" if self._paths is not None else "" + ) + data[name] = self._redact_value(data[name], field_schema, child, child_path) def redact_fields(self, data: dict[str, Any], schema: dict[str, Any]) -> None: self._redact_object(data, self._views(schema, self._resolver)) diff --git a/python/tests/conformance/test_post_validation_policy.py b/python/tests/conformance/test_post_validation_policy.py new file mode 100644 index 00000000..cc220453 --- /dev/null +++ b/python/tests/conformance/test_post_validation_policy.py @@ -0,0 +1,146 @@ +"""Exercise the policy gate through public execution entry points.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from apcore import ApprovalRequest, ApprovalResult, Context, Executor, ModuleAnnotations, Registry +from apcore.errors import ApprovalPendingError, ModuleError +from apcore.middleware import Middleware +from apcore.policy import PolicyEvaluationRequest, PolicyVerdict +from conformance.canonical_fixtures import case_ids, load_fixture + +FIXTURE = "post_validation_policy.json" + + +def _scope(request: ApprovalRequest) -> tuple[object, ...]: + identity = request.context.identity + return ( + (identity.type, identity.id) if identity else None, + request.caller_id, + request.module_id, + request.module_version, + request.canonical_args_digest, + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("case", load_fixture(FIXTURE)["test_cases"], ids=case_ids(FIXTURE)) +async def test_post_validation_policy(case: dict[str, Any]) -> None: + contract = load_fixture(FIXTURE)["driver_contract"] + module_id, version = contract["module_id"], contract["module_version"] + starts: list[int] = [] + evaluated: list[int] = [] + approvals: list[int] = [] + resume_checks: list[str] = [] + token = "fixture-policy-approval" + pending_scope: tuple[object, ...] | None = None + pending_result = ApprovalResult("pending", approval_id=token) + + class Operation: + description = "Test the final invocation" + input_schema = contract["input_schema"] + output_schema = {"type": "object"} + annotations = ModuleAnnotations(requires_approval=case.get("requires_approval", False)) + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + assert "_approval_token" not in inputs + starts.append(inputs["amount"]) + return {"amount": inputs["amount"]} + + async def stream(self, inputs: dict[str, Any], context: Context) -> Any: + starts.append(inputs["amount"]) + yield {"amount": inputs["amount"]} + + class Evaluator: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + assert request.module_version == version + assert request.module_id == module_id + assert "_approval_token" not in request.arguments + assert "/secret" in request.sensitive_fields + evaluated.append(request.arguments["amount"]) + if case["verdict"] == "throw": + raise RuntimeError(contract["business_input"]["secret"]) + request.arguments["amount"] = -1 + return PolicyVerdict(case["verdict"]) + + class Handler: + supports_final_scope = True + + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: + nonlocal pending_scope + assert request.module_version == version + assert request.canonical_args_digest is not None + assert "_approval_token" not in request.arguments + approvals.append(request.arguments["amount"]) + if case["entry"] == "resume": + pending_scope = _scope(request) + return pending_result + return ApprovalResult("approved") + + async def check_approval(self, approval_id: str) -> ApprovalResult: + raise AssertionError("Unscoped approval status cannot authorize a call") + + async def check_approval_for_call(self, approval_id: str, request: ApprovalRequest) -> ApprovalResult: + nonlocal pending_scope + resume_checks.append(approval_id) + if approval_id == token and pending_scope == _scope(request): + pending_scope = None + return ApprovalResult("approved") + return ApprovalResult("rejected") + + class Rewrite(Middleware): + async def before(self, module_id: str, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + assert "_approval_token" not in inputs + return {**inputs, "amount": case["rewrite_amount"]} + + registry = Registry() + await registry.register_async(module_id, Operation(), version=version) + executor = Executor(registry, policy_evaluator=Evaluator(), approval_handler=Handler()) + if "rewrite_amount" in case: + executor.use(Rewrite()) + + supplied = {**contract["business_input"], **case.get("inputs", {})} + result = None + error = None + try: + if case["entry"] == "preflight": + result = await executor.validate_async(module_id, {**supplied, "_approval_token": token}) + elif case["entry"] == "stream": + async for _ in executor.stream(module_id, supplied): + pass + elif case["entry"] == "resume": + with pytest.raises(ApprovalPendingError) as pending: + await executor.call_async(module_id, supplied) + assert pending.value.result is pending_result + assert pending.value.approval_id == token + await executor.call_async(module_id, {**supplied, **case.get("retry_inputs", {}), "_approval_token": token}) + else: + await executor.call_async(module_id, supplied) + except ModuleError as exc: + error = exc + finally: + executor.close() + + expected = case["expected"] + assert len(starts) == expected["module_starts"] + assert (evaluated[-1] if evaluated else None) == expected["evaluated_amount"] + assert len(approvals) == expected["approval_requests"] + if starts: + assert starts == [expected["evaluated_amount"]] + if "approved_amount" in expected: + assert approvals == [expected["approved_amount"]] + if "requires_approval" in expected: + assert result is not None and result.valid + assert result.requires_approval is expected["requires_approval"] + if "resume_checks" in expected: + assert resume_checks == [token] * expected["resume_checks"] + if "error_code" in expected: + assert error is not None and error.code == expected["error_code"] + assert contract["business_input"]["secret"] not in str(error.to_dict()) + elif not evaluated: + assert error is not None + else: + assert error is None diff --git a/python/tests/test_extensions.py b/python/tests/test_extensions.py index 1794ac9b..6850a57e 100644 --- a/python/tests/test_extensions.py +++ b/python/tests/test_extensions.py @@ -50,15 +50,23 @@ def export(self, span: Any) -> None: class TestExtensionManagerInit: - def test_has_five_built_in_points(self) -> None: + def test_has_seven_built_in_points(self) -> None: mgr = ExtensionManager() points = mgr.list_points() - assert len(points) == 6 + assert len(points) == 7 def test_built_in_point_names(self) -> None: mgr = ExtensionManager() names = {p.name for p in mgr.list_points()} - assert names == {"discoverer", "middleware", "acl", "span_exporter", "module_validator", "approval_handler"} + assert names == { + "discoverer", + "middleware", + "acl", + "span_exporter", + "module_validator", + "approval_handler", + "policy_evaluator", + } def test_list_points_returns_extension_point_instances(self) -> None: mgr = ExtensionManager() diff --git a/python/tests/test_post_validation_policy.py b/python/tests/test_post_validation_policy.py new file mode 100644 index 00000000..6a0343dd --- /dev/null +++ b/python/tests/test_post_validation_policy.py @@ -0,0 +1,304 @@ +"""Cover Python-specific dispatch and cancellation invariants for final policy.""" + +from __future__ import annotations + +import asyncio +import time +from typing import Any + +import pytest + +import apcore._post_validation_policy as post_validation_policy +from apcore import ( + ACL, + ApprovalPendingError, + ApprovalRequest, + ApprovalResult, + CancelToken, + Context, + Executor, + ExtensionManager, + Identity, + ModuleAnnotations, + ModuleError, + PolicyEvaluationRequest, + PolicyVerdict, + Registry, +) +from apcore.middleware import Middleware +from apcore.pipeline import PipelineState, StepResult + + +class Operation: + description = "Observe an invocation" + input_schema = {"type": "object", "properties": {"amount": {"type": "number"}}} + output_schema = {"type": "object"} + + def __init__(self) -> None: + self.starts = 0 + self.previews = 0 + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + self.starts += 1 + return inputs + + async def stream(self, inputs: dict[str, Any], context: Context) -> Any: + self.starts += 1 + yield inputs + + def preview(self, inputs: dict[str, Any], context: Context) -> None: + self.previews += 1 + + +async def _registered() -> tuple[Registry, Operation]: + registry = Registry() + module = Operation() + await registry.register_async("demo.observe", module, version="1.0.0") + return registry, module + + +class Allow: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + return PolicyVerdict("allow") + + +@pytest.mark.asyncio +async def test_denied_acl_prevents_provider_and_preview_disclosure() -> None: + class DoNotRead: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + pytest.fail("ACL denial must not disclose validated inputs to the evaluator") + + registry, module = await _registered() + with Executor(registry, acl=ACL([]), policy_evaluator=DoNotRead()) as executor: + report = await executor.validate_async("demo.observe", {"amount": 1}) + assert any(error["code"] == "ACL_DENIED" for error in report.errors) + with pytest.raises(ModuleError) as denied: + await executor.call_async("demo.observe", {"amount": 1}) + assert denied.value.code == "ACL_DENIED" + assert module.starts == module.previews == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("changed", ["arguments", "identity"]) +async def test_module_preflight_and_preview_use_the_policy_snapshot(changed: str) -> None: + evaluating, resume = asyncio.Event(), asyncio.Event() + observed: list[tuple[int, str | None]] = [] + + class Inspect(Operation): + def preflight(self, inputs: dict[str, Any], context: Context) -> list[str]: + observed.append((inputs["order"]["amount"], context.caller_id)) + inputs["order"]["amount"] = 30 + context.caller_id = "demo.other" + return [] + + def preview(self, inputs: dict[str, Any], context: Context) -> None: + observed.append((inputs["order"]["amount"], context.caller_id)) + + class Check: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + evaluating.set() + await resume.wait() + return PolicyVerdict("allow" if request.arguments["order"]["amount"] == 1 else "deny") + + registry = Registry() + await registry.register_async("demo.observe", Inspect()) + arguments = {"order": {"amount": 1}} + identity = Identity(id="operator", type="user", attrs={"team": "review"}) + with Executor(registry, policy_evaluator=Check()) as executor: + pending = asyncio.create_task(executor.validate_async("demo.observe", arguments, Context.create(identity))) + await asyncio.wait_for(evaluating.wait(), 1) + if changed == "arguments": + arguments["order"]["amount"] = 20 + else: + identity.attrs["team"] = "another" + resume.set() + report = await pending + + if changed == "arguments": + assert report.valid + assert observed == [(1, None), (1, None)] + else: + assert not report.valid + assert any(error["code"] == "POLICY_EVALUATION_ERROR" for error in report.errors) + assert observed == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("action", ["skip", "mutate", "recover"]) +async def test_step_middleware_cannot_bypass_the_final_gate(action: str) -> None: + class Tamper: + def after_step(self, name: str, state: PipelineState, result: StepResult) -> None: + if action == "skip" and name == "middleware_before": + result.action, result.skip_to = "skip_to", "return_result" + if action == "mutate" and name == "post_validation_policy": + assert state.context.validated_inputs is not None + state.context.validated_inputs["amount"] = 0 + + def on_step_error(self, name: str, state: PipelineState, error: Exception) -> dict[str, int]: + return {"recovered": 1} + + class DenyIfRecovering: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + return PolicyVerdict("deny" if action == "recover" else "allow") + + class Recover(Middleware): + def on_error(self, *args: Any) -> dict[str, int]: + return {"Recovered": 1} + + registry, module = await _registered() + with Executor(registry, policy_evaluator=DenyIfRecovering(), middlewares=[Recover()]) as executor: + executor.current_strategy.add_step_middleware(Tamper()) + with pytest.raises(ModuleError) as rejected: + await executor.call_async("demo.observe", {"amount": 1}) + assert rejected.value.code == ("POLICY_DENIED" if action == "recover" else "POLICY_EVALUATION_ERROR") + assert module.starts == 0 + + +@pytest.mark.asyncio +async def test_extension_applies_only_to_its_executor_and_requires_safe_strategy() -> None: + class Deny: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + return PolicyVerdict("deny") + + registry, module = await _registered() + manager = ExtensionManager() + manager.register("policy_evaluator", Deny()) + with Executor(registry) as configured, Executor(registry) as other: + manager.apply(registry, configured) + with pytest.raises(ModuleError) as rejected: + await configured.call_async("demo.observe", {"amount": 1}) + assert rejected.value.code == "POLICY_DENIED" + with pytest.raises(ModuleError) as incompatible: + await configured.call_async_with_trace("demo.observe", {"amount": 1}, strategy="minimal") + assert incompatible.value.code == "PIPELINE_CONFIGURATION_ERROR" + assert module.starts == 0 + assert await other.call_async("demo.observe", {"amount": 1}) == {"amount": 1} + + +@pytest.mark.asyncio +async def test_unversioned_handler_cannot_authorize_final_resumption() -> None: + class Legacy: + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: + return ApprovalResult("pending", approval_id="legacy-approval") + + async def check_approval(self, approval_id: str) -> ApprovalResult: + pytest.fail("A status lookup cannot authorize an invocation") + + async def check_approval_for_call(self, approval_id: str, request: ApprovalRequest) -> ApprovalResult: + pytest.fail("A legacy scope cannot authorize a final credential") + + registry, module = await _registered() + module.annotations = ModuleAnnotations(requires_approval=True) + with Executor(registry, policy_evaluator=Allow(), approval_handler=Legacy()) as executor: + for args in ({"amount": 1}, {"amount": 1, "_approval_token": "legacy-approval"}): + with pytest.raises(ModuleError) as rejected: + await executor.call_async("demo.observe", args) + assert rejected.value.code == "APPROVAL_DENIED" + assert "legacy-approval" not in str(rejected.value.to_dict()) + assert module.starts == 0 + + +@pytest.mark.asyncio +async def test_final_scope_uses_lookup_version_and_preserves_native_numeric_kinds() -> None: + class Required: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + return PolicyVerdict("require_approval") + + class Pending: + supports_final_scope = True + + def __init__(self) -> None: + self.scope: tuple[str | None, str | None] | None = None + + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: + self.scope = request.module_version, request.canonical_args_digest + return ApprovalResult("pending", approval_id="final-approval") + + async def check_approval(self, approval_id: str) -> ApprovalResult: + pytest.fail("A status lookup cannot authorize an invocation") + + async def check_approval_for_call(self, approval_id: str, request: ApprovalRequest) -> ApprovalResult: + if approval_id == "final-approval" and self.scope == ( + request.module_version, + request.canonical_args_digest, + ): + self.scope = None + return ApprovalResult("approved") + return ApprovalResult("rejected") + + registry, first = await _registered() + second = Operation() + await registry.register_async("demo.observe", second, version="2.0.0") + handler = Pending() + with Executor(registry, policy_evaluator=Required(), approval_handler=handler) as executor: + with pytest.raises(ApprovalPendingError) as pending: + await executor.call_async("demo.observe", {"amount": -0.0}, version_hint="1.0.0") + assert pending.value.approval_id == "final-approval" + assert handler.scope is not None and handler.scope[0] == "1.0.0" + + resume = {"amount": -0.0, "_approval_token": pending.value.approval_id} + for args, version in ((resume, "2.0.0"), (dict(resume, amount=0.0), "1.0.0")): + with pytest.raises(ModuleError) as rejected: + await executor.call_async("demo.observe", args, version_hint=version) + assert rejected.value.code == "APPROVAL_DENIED" + await executor.call_async("demo.observe", resume, version_hint="1.0.0") + + assert first.starts == 1 and second.starts == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("entry", ["call", "stream"]) +@pytest.mark.parametrize("end", ["timeout", "cancellation"]) +async def test_evaluator_timeout_and_cancellation_remain_distinct(entry: str, end: str) -> None: + evaluating = asyncio.Event() + + class Wait: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + evaluating.set() + await asyncio.Future() + pytest.fail("The policy evaluator should be bounded") + + registry, module = await _registered() + token = CancelToken() + deadline = time.time() + 0.25 if end == "timeout" else None + context = Context.create(cancel_token=token, global_deadline=deadline) + with Executor(registry, policy_evaluator=Wait()) as executor: + if entry == "call": + pending = asyncio.create_task(executor.call_async("demo.observe", {"amount": 1}, context)) + else: + stream = executor.stream_with_completion("demo.observe", {"amount": 1}, context) + pending = asyncio.ensure_future(anext(stream.chunks)) + await asyncio.wait_for(evaluating.wait(), timeout=1) + if end == "cancellation": + token.cancel() + with pytest.raises(ModuleError) as rejected: + await asyncio.wait_for(pending, timeout=2) + expected = "EXECUTION_CANCELLED" if end == "cancellation" else "POLICY_EVALUATION_ERROR" + assert rejected.value.code == expected + if entry == "stream": + assert (await stream.completion()).error_code == expected + assert module.starts == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("entry", ["call", "stream"]) +async def test_late_non_yielding_policy_cannot_authorize_dispatch(entry: str, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(post_validation_policy, "_EVALUATOR_TIMEOUT_SECONDS", 0.02) + + class LateAllow: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + time.sleep(0.05) + return PolicyVerdict("allow") + + registry, module = await _registered() + with Executor(registry, policy_evaluator=LateAllow()) as executor: + with pytest.raises(ModuleError) as rejected: + if entry == "call": + await executor.call_async("demo.observe", {"amount": 1}) + else: + stream = executor.stream_with_completion("demo.observe", {"amount": 1}) + await anext(stream.chunks) + assert rejected.value.code == "POLICY_EVALUATION_ERROR" + if entry == "stream": + assert (await stream.completion()).error_code == "POLICY_EVALUATION_ERROR" + assert module.starts == 0 diff --git a/python/tests/test_public_api.py b/python/tests/test_public_api.py index 1cdd6c59..ff6134ea 100644 --- a/python/tests/test_public_api.py +++ b/python/tests/test_public_api.py @@ -458,6 +458,11 @@ class TestPublicAPIAll: "Context", "ErrorCodes", "ExecutionPolicy", + "PolicyDeniedError", + "PolicyEvaluationError", + "PolicyEvaluationRequest", + "PolicyEvaluator", + "PolicyVerdict", "ExecutionStrategy", "Executor", "Identity", diff --git a/python/uv.lock b/python/uv.lock index 79df6e80..295688e3 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -199,7 +199,7 @@ wheels = [ [[package]] name = "apcore" -version = "1.0.0a2" +version = "1.0.0a3" source = { editable = "." } dependencies = [ { name = "jsonschema" }, diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 554d1a0c..15ab0d16 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -42,7 +42,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.2" +version = "1.0.0-alpha.3" dependencies = [ "async-stream", "async-trait", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 557bbd1a..b3754569 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore" -version = "1.0.0-alpha.2" +version = "1.0.0-alpha.3" edition = "2021" # Minimum supported Rust version. Verified with `cargo +1.86 check --all-features`. # The binding language constraint is `std::task::Waker::noop()` (used by the diff --git a/rust/apcore-conformance.yaml b/rust/apcore-conformance.yaml index 16f569f2..6124a5e5 100644 --- a/rust/apcore-conformance.yaml +++ b/rust/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-rust - version: 1.0.0-alpha.2 + version: 1.0.0-alpha.3 language: rust spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/rust/src/approval.rs b/rust/src/approval.rs index 33dd8839..7a472355 100644 --- a/rust/src/approval.rs +++ b/rust/src/approval.rs @@ -31,6 +31,12 @@ use crate::module::ModuleAnnotations; pub struct ApprovalRequest { pub module_id: String, pub arguments: serde_json::Value, + /// Version of the registration selected for final-scope approval. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub module_version: Option, + /// Digest of the validated inputs. Present only for final-scope approval. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub canonical_args_digest: Option, /// The execution context (`trace_id`, identity, `call_chain`). /// Skipped during serialization as Context contains non-serializable runtime refs. #[serde(skip)] @@ -151,6 +157,12 @@ pub trait ApprovalHandler: Send + Sync + std::fmt::Debug { /// Check the current status of a pending approval by ID. async fn check_approval(&self, approval_id: &str) -> Result; + /// Whether this handler binds and atomically consumes final-scope credentials. + /// Immediate approval decisions do not require this capability. + fn supports_final_scope(&self) -> bool { + false + } + /// Validate the current call's identity, target and arguments, then consume the approval. async fn check_approval_for_call( &self, diff --git a/rust/src/builtin_steps.rs b/rust/src/builtin_steps.rs index 0c9287be..7092382a 100644 --- a/rust/src/builtin_steps.rs +++ b/rust/src/builtin_steps.rs @@ -10,7 +10,7 @@ use crate::errors::{ErrorCode, ModuleError}; use crate::events::emitter::ApCoreEvent; use crate::executor::{redact_sensitive_with, validate_against_schema}; use crate::pipeline::{BuiltinGate, ExecutionStrategy, PipelineContext, Step, StepResult}; -use crate::policy::{ExecutionPolicy, PolicyDecision}; +use crate::policy::{ExecutionPolicy, PolicyDecision, PolicyEffect, PolicyEvaluationRequest}; // Macro for step metadata — execute is implemented manually per step. macro_rules! step_meta { @@ -126,6 +126,14 @@ step_meta!( replaceable = true, pure = true ); +step_meta!( + BuiltinPostValidationPolicy, + "post_validation_policy", + "Evaluate policy and authorize final validated inputs", + removable = true, + replaceable = false, + pure = true +); step_meta!( BuiltinMiddlewareBefore, "middleware_before", @@ -395,6 +403,10 @@ impl Step for BuiltinACLCheck { &["context", "module"] } + fn provides(&self) -> &[&str] { + &["acl_checked"] + } + async fn execute(&self, ctx: &mut PipelineContext) -> Result { if let Some(acl) = ctx.acl.clone() { let caller_id = ctx.context.caller_id.clone(); @@ -606,6 +618,20 @@ impl BuiltinApprovalGate { tracing::warn!("{}", message); } + fn warn_destructive_ungated(ctx: &PipelineContext) { + Self::warn_once( + ctx, + &format!("destructive_ungated:{}", ctx.module_id), + &format!( + "Module '{}' is annotated destructive=true but is not covered by the \ + approval gate (requires_approval is false and no policy gates \ + destructive modules). Consider requires_approval=true or \ + ExecutionPolicy(gate_destructive=true). (apcore#76)", + ctx.module_id + ), + ); + } + /// Preserve the full decision for the caller, including the pending /// credential at its existing details key for older clients. fn approval_error(module_id: &str, result: &crate::approval::ApprovalResult) -> ModuleError { @@ -643,6 +669,66 @@ impl BuiltinApprovalGate { } error } + + async fn reject_unavailable_handler(ctx: &PipelineContext, reason: &str) -> ModuleError { + let decision = crate::approval::ApprovalResult::rejected(reason); + Self::emit_approval_decision(ctx, &decision, None); + Self::emit_approval_decision_event(ctx, &decision, None).await; + Self::approval_error(&ctx.module_id, &decision) + } + + async fn authorize( + ctx: &mut PipelineContext, + module: &dyn crate::module::Module, + handler: &dyn crate::approval::ApprovalHandler, + annotations: crate::module::ModuleAnnotations, + arguments: Value, + digest: Option, + ) -> Result<(), ModuleError> { + const UNSUPPORTED_FINAL: &str = + "The approval handler does not support final-scope resumption"; + let approval_token = ctx.take_approval_credential()?; + let final_scope = digest.is_some(); + if final_scope && approval_token.is_some() && !handler.supports_final_scope() { + return Err(Self::reject_unavailable_handler(ctx, UNSUPPORTED_FINAL).await); + } + let description = module.description(); + let request = crate::approval::ApprovalRequest { + module_id: ctx.module_id.clone(), + arguments, + module_version: if final_scope { + ctx.module_lease + .as_ref() + .and_then(|lease| lease.version.clone()) + } else { + None + }, + canonical_args_digest: digest, + context: Some(ctx.context.clone()), + annotations, + caller_id: ctx.context.caller_id.clone(), + action: ctx.module_id.clone(), + description: (!description.is_empty()).then(|| description.to_owned()), + tags: module.tags(), + }; + let approval_result = if let Some(credential) = approval_token.as_deref() { + handler + .check_approval_for_call(credential, &request) + .await? + } else { + handler.request_approval(&request).await? + }; + if final_scope && approval_result.status == "pending" && !handler.supports_final_scope() { + return Err(Self::reject_unavailable_handler(ctx, UNSUPPORTED_FINAL).await); + } + let audit_id = approval_result.observable_id(approval_token.as_deref()); + Self::emit_approval_decision(ctx, &approval_result, audit_id); + Self::emit_approval_decision_event(ctx, &approval_result, audit_id).await; + if approval_result.status != "approved" { + return Err(Self::approval_error(&ctx.module_id, &approval_result)); + } + Ok(()) + } } #[async_trait] @@ -659,7 +745,7 @@ impl Step for BuiltinApprovalGate { #[allow(clippy::too_many_lines)] // approval gate logic is inherently multi-step; splitting would obscure the protocol flow async fn execute(&self, ctx: &mut PipelineContext) -> Result { - let approval_token = ctx.take_approval_credential()?; + ctx.validate_approval_credential()?; let registry = ctx .registry @@ -753,43 +839,28 @@ impl Step for BuiltinApprovalGate { Self::emit_policy_override_event(ctx, &decision).await; } + let mut annotations = module_annotations.unwrap_or_default(); + annotations.requires_approval = needs_approval; + annotations.destructive = decision.destructive; + if needs_approval && ctx.approval_handler.is_none() && policy.strict { + return Err(Self::reject_unavailable_handler( + ctx, + "Approval required but no ApprovalHandler is configured; ExecutionPolicy(strict=true) fails closed", + ).await); + } + if ctx.policy_evaluator.is_some() { + ctx.policy_approval_annotations = Some(annotations); + return Ok(StepResult::continue_step()); + } if !needs_approval { - // Fail-loud governance (apcore#76): a module that is effectively - // destructive but that no approval gate covers is warned about once. if decision.destructive { - Self::warn_once( - ctx, - &format!("destructive_ungated:{}", ctx.module_id), - &format!( - "Module '{}' is annotated destructive=true but is not covered by the \ - approval gate (requires_approval is false and no policy gates \ - destructive modules). Consider requires_approval=true or \ - ExecutionPolicy(gate_destructive=true). (apcore#76)", - ctx.module_id - ), - ); + Self::warn_destructive_ungated(ctx); } return Ok(StepResult::continue_step()); } // A missing handler refuses an approval-required call by default. let Some(handler) = ctx.approval_handler.clone() else { - if policy.strict { - // strict=true fails CLOSED: build a rejected result, audit it, - // and deny. - let result = crate::approval::ApprovalResult { - status: "rejected".to_string(), - reason: Some( - "Approval required but no ApprovalHandler is configured; \ - ExecutionPolicy(strict=true) fails closed" - .to_string(), - ), - ..Default::default() - }; - Self::emit_approval_decision(ctx, &result, None); - Self::emit_approval_decision_event(ctx, &result, None).await; - return Err(Self::approval_error(&ctx.module_id, &result)); - } // An explicit non-strict policy warns once per module and // continues. It emits no decision event // — parity with the "no audit log when gate skipped" contract. @@ -807,35 +878,16 @@ impl Step for BuiltinApprovalGate { }; let module = module.ok_or_else(|| ModuleError::module_not_found(&ctx.module_id))?; - let mut annotations = module_annotations.unwrap_or_default(); - annotations.requires_approval = true; - annotations.destructive = decision.destructive; - let description = module.description(); - let request = crate::approval::ApprovalRequest { - module_id: ctx.module_id.clone(), - arguments: ctx.inputs.clone(), - context: Some(ctx.context.clone()), + let arguments = ctx.inputs.clone(); + Self::authorize( + ctx, + module.as_ref(), + handler.as_ref(), annotations, - caller_id: ctx.context.caller_id.clone(), - action: ctx.module_id.clone(), - description: (!description.is_empty()).then(|| description.to_owned()), - tags: module.tags(), - }; - let approval_result = if let Some(credential) = approval_token.as_deref() { - handler - .check_approval_for_call(credential, &request) - .await? - } else { - handler.request_approval(&request).await? - }; - let audit_id = approval_result.observable_id(approval_token.as_deref()); - Self::emit_approval_decision(ctx, &approval_result, audit_id); - Self::emit_approval_decision_event(ctx, &approval_result, audit_id).await; - - if approval_result.status != "approved" { - return Err(Self::approval_error(&ctx.module_id, &approval_result)); - } - + arguments, + None, + ) + .await?; Ok(StepResult::continue_step()) } } @@ -858,6 +910,11 @@ impl Step for BuiltinInputValidation { let input_schema = module.input_schema(); validate_against_schema(&ctx.inputs, &input_schema, "Input")?; + if ctx.policy_evaluator.is_some() { + ctx.policy_sensitive_fields = + crate::executor::schema_sensitive_fields(&ctx.inputs, &input_schema); + } + let mut captured = capture_redacted(&ctx.inputs, &input_schema, ctx); captured.remove("_approval_token"); ctx.context.redacted_inputs = Some(captured); @@ -866,6 +923,133 @@ impl Step for BuiltinInputValidation { } } +#[async_trait] +impl Step for BuiltinPostValidationPolicy { + impl_step_meta!(BuiltinPostValidationPolicy); + + fn requires(&self) -> &[&str] { + &["module", "acl_checked", "validated_inputs"] + } + + fn builtin_gate(&self) -> Option { + Some(BuiltinGate::PostValidationPolicy) + } + + async fn execute(&self, ctx: &mut PipelineContext) -> Result { + let evaluator = ctx + .policy_evaluator + .clone() + .ok_or_else(|| missing_pipeline_input("policy_evaluator"))?; + let arguments = ctx + .validated_inputs + .clone() + .ok_or_else(|| missing_pipeline_input("validated_inputs"))?; + if !arguments.is_object() || arguments.get(crate::policy::APPROVAL_TOKEN_KEY).is_some() { + return Err(crate::policy::evaluation_error()); + } + let digest = crate::policy::final_arguments_digest(&arguments)?; + let request = PolicyEvaluationRequest { + module_id: ctx.module_id.clone(), + module_version: ctx + .module_lease + .as_ref() + .and_then(|lease| lease.version.clone()), + caller_id: ctx.context.caller_id.clone(), + identity: ctx.context.identity.clone(), + sensitive_fields: std::mem::take(&mut ctx.policy_sensitive_fields), + arguments, + }; + let verdict = crate::policy::evaluate(evaluator.as_ref(), &request, &ctx.context).await?; + if !ctx.dry_run { + Self::emit_decision(ctx, &request, &verdict).await; + } + if verdict.decision == PolicyEffect::Deny { + return Err(ModuleError::new( + ErrorCode::PolicyDenied, + "The post-validation policy denied the invocation", + ) + .with_ai_guidance("Change the arguments to satisfy the configured policy.")); + } + if !ctx.dry_run { + Self::authorize(ctx, &request, digest, verdict.decision).await?; + ctx.policy_inputs = Some(request.arguments); + } + ctx.policy_effect = Some(verdict.decision); + Ok(StepResult::continue_step()) + } +} + +impl BuiltinPostValidationPolicy { + async fn authorize( + ctx: &mut PipelineContext, + request: &PolicyEvaluationRequest, + digest: String, + effect: PolicyEffect, + ) -> Result<(), ModuleError> { + if let Some(token) = &ctx.context.cancel_token { + token.check_for(&ctx.module_id)?; + } + let mut annotations = ctx + .policy_approval_annotations + .take() + .ok_or_else(|| missing_pipeline_input("policy_approval_annotations"))?; + if annotations.requires_approval + || effect == PolicyEffect::RequireApproval + || ctx.has_approval_credential() + { + let Some(handler) = ctx.approval_handler.clone() else { + return Err(BuiltinApprovalGate::reject_unavailable_handler( + ctx, + "Final-scope approval requires an ApprovalHandler", + ) + .await); + }; + let module = ctx + .module + .clone() + .ok_or_else(|| missing_pipeline_input("module"))?; + annotations.requires_approval = true; + BuiltinApprovalGate::authorize( + ctx, + module.as_ref(), + handler.as_ref(), + annotations, + request.arguments.clone(), + Some(digest), + ) + .await?; + } else if annotations.destructive { + BuiltinApprovalGate::warn_destructive_ungated(ctx); + } + Ok(()) + } + + async fn emit_decision( + ctx: &PipelineContext, + request: &PolicyEvaluationRequest, + verdict: &crate::policy::PolicyVerdict, + ) { + let Some(emitter) = ctx.event_emitter.as_ref() else { + return; + }; + let event = ApCoreEvent::with_module( + "apcore.policy.decision", + serde_json::json!({ + "rule_id": verdict.rule_id, + "decision": verdict.decision, + "sensitive_fields": request.sensitive_fields, + }), + ctx.module_id.clone(), + if verdict.decision == PolicyEffect::Deny { + "warn" + } else { + "info" + }, + ); + emitter.emit(&event).await; + } +} + #[async_trait] impl Step for BuiltinMiddlewareBefore { impl_step_meta!(BuiltinMiddlewareBefore); @@ -993,6 +1177,7 @@ impl Step for BuiltinExecute { } async fn execute(&self, ctx: &mut PipelineContext) -> Result { + ctx.bind_policy_inputs()?; let module = ctx .module .as_ref() diff --git a/rust/src/errors.rs b/rust/src/errors.rs index 6acb115d..901787ab 100644 --- a/rust/src/errors.rs +++ b/rust/src/errors.rs @@ -97,6 +97,8 @@ pub enum ErrorCode { ApprovalDenied, ApprovalTimeout, ApprovalPending, + PolicyDenied, + PolicyEvaluationError, VersionIncompatible, ErrorCodeCollision, DependencyNotFound, @@ -317,6 +319,8 @@ impl ErrorCode { ErrorCode::ApprovalDenied, ErrorCode::ApprovalTimeout, ErrorCode::ApprovalPending, + ErrorCode::PolicyDenied, + ErrorCode::PolicyEvaluationError, ErrorCode::VersionIncompatible, ErrorCode::ErrorCodeCollision, ErrorCode::DependencyNotFound, @@ -464,6 +468,7 @@ pub fn retryable_for_code(code: ErrorCode) -> Option { // execution, so it carries the annotation without reaching the retry // gate. ErrorCode::ApprovalTimeout + | ErrorCode::PolicyEvaluationError | ErrorCode::ModuleTimeout | ErrorCode::GeneralInternalError // A full task pool is a capacity condition, not a caller fault: the @@ -504,6 +509,7 @@ pub fn retryable_for_code(code: ErrorCode) -> Option { | ErrorCode::ACLRuleError | ErrorCode::ApprovalDenied | ErrorCode::ApprovalPending + | ErrorCode::PolicyDenied | ErrorCode::ModuleDisabled // Call-chain structure: retrying reproduces the same chain. | ErrorCode::CallDepthExceeded @@ -580,6 +586,7 @@ pub fn user_fixable_for_code(code: ErrorCode) -> Option { // Caller can fix by changing input/config: ErrorCode::SchemaValidationError | ErrorCode::GeneralInvalidInput + | ErrorCode::PolicyDenied | ErrorCode::ModuleNotFound | ErrorCode::VersionConstraintInvalid // A malformed `parent_id` override is supplied by the caller, so the @@ -593,6 +600,7 @@ pub fn user_fixable_for_code(code: ErrorCode) -> Option { // Governance / system / structural / transient — not caller-fixable by input: ErrorCode::ACLDenied | ErrorCode::ApprovalDenied + | ErrorCode::PolicyEvaluationError | ErrorCode::ApprovalTimeout | ErrorCode::ModuleTimeout | ErrorCode::ModuleDisabled diff --git a/rust/src/executor.rs b/rust/src/executor.rs index a1aab4cd..f5dc68e5 100644 --- a/rust/src/executor.rs +++ b/rust/src/executor.rs @@ -16,7 +16,7 @@ use crate::acl::ACL; use crate::approval::ApprovalHandler; use crate::builtin_steps::{ build_internal_strategy, build_minimal_strategy, build_performance_strategy, - build_standard_strategy, build_testing_strategy, + build_standard_strategy, build_testing_strategy, BuiltinPostValidationPolicy, }; use crate::cancel::CancelToken; use crate::config::Config; @@ -33,7 +33,7 @@ use crate::pipeline::{ BuiltinGate, ExecutionStrategy, PipelineContext, PipelineEngine, PipelineTrace, RunOptions, StepTrace, StrategyInfo, }; -use crate::policy::ExecutionPolicy; +use crate::policy::{ExecutionPolicy, PolicyEffect, PolicyEvaluator}; use crate::registry::registry::{module_id_pattern, ModuleExecutionLease, Registry}; use crate::runtime::background_runtime; use crate::stream_completion::{StreamChunks, StreamCompletionHandle, StreamRecorder}; @@ -589,6 +589,10 @@ pub fn redact_sensitive(data: &Value, schema: &Value) -> Value { redacted } +pub(crate) fn schema_sensitive_fields(data: &Value, schema: &Value) -> Vec { + schema_redaction::sensitive_fields(data, schema) +} + /// Redact for the executor's input/output capture point. /// /// PROTOCOL_SPEC §10.6.1 "Where the rules apply": the union of §10.6's @@ -837,6 +841,7 @@ pub struct Executor { /// Execution-time governance policy consulted by the Step-5 approval gate /// (apcore#76 RFC pilot). Flows to the gate via `PipelineContext`. pub policy: Option>, + policy_evaluator: Option>, /// Event emitter for governance events (apcore#77). When set, the ACL and /// approval-gate steps publish `apcore.acl.denied` / /// `apcore.approval.decision` / `apcore.policy.override` on the bus. @@ -944,6 +949,15 @@ fn strategy_from_config( } } +fn has_policy_compatible_layout(strategy: &ExecutionStrategy) -> bool { + fn step_types(strategy: &ExecutionStrategy) -> impl Iterator + '_ { + strategy.steps().iter().map(|step| step.as_ref().type_id()) + } + + step_types(strategy).eq(step_types(&build_standard_strategy())) + || step_types(strategy).eq(step_types(&build_performance_strategy())) +} + impl Executor { /// Create a new executor with the given (shared) registry and config. /// @@ -965,6 +979,7 @@ impl Executor { pipeline_load_error, approval_handler: None, policy: None, + policy_evaluator: None, event_emitter: None, governance_warned: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())), redaction: std::sync::OnceLock::new(), @@ -994,6 +1009,7 @@ impl Executor { pipeline_load_error: None, approval_handler: None, policy: None, + policy_evaluator: None, event_emitter: None, governance_warned: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())), redaction: std::sync::OnceLock::new(), @@ -1019,6 +1035,7 @@ impl Executor { pipeline_load_error: None, approval_handler: None, policy: None, + policy_evaluator: None, event_emitter: None, governance_warned: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())), redaction: std::sync::OnceLock::new(), @@ -1060,6 +1077,7 @@ impl Executor { pipeline_load_error, approval_handler: approval_handler.map(|h| Arc::from(h) as Arc), policy: None, + policy_evaluator: None, event_emitter: None, governance_warned: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())), redaction: std::sync::OnceLock::new(), @@ -1196,6 +1214,35 @@ impl Executor { self.policy = policy.map(Arc::new); } + /// Install or clear the Executor's post-validation evaluator. + /// + /// Installation requires the stock `standard` or `performance` layout. + /// Step middleware may observe those steps. Before middleware on the + /// opted-in path must perform side-effect-free normalization. + /// + /// # Errors + /// + /// Returns [`ErrorCode::PipelineConfigurationError`] for an incompatible strategy. + pub fn set_policy_evaluator( + &mut self, + evaluator: Option>, + ) -> Result<(), ModuleError> { + match (self.policy_evaluator.is_some(), evaluator.is_some()) { + (false, true) => { + if !has_policy_compatible_layout(&self.strategy) { + return Err(ModuleError::new(ErrorCode::PipelineConfigurationError, + "Post-validation policy requires the stock standard or performance strategy")); + } + self.strategy + .insert_after("input_validation", Box::new(BuiltinPostValidationPolicy))?; + } + (true, false) => self.strategy.remove("post_validation_policy")?, + _ => {} + } + self.policy_evaluator = evaluator; + Ok(()) + } + /// Set (or clear) the event emitter used to publish governance events /// (apcore#77): `apcore.acl.denied`, `apcore.approval.decision`, and /// `apcore.policy.override`. @@ -1328,6 +1375,12 @@ impl Executor { record_attempts: bool, ) -> Result<(Value, PipelineTrace), ModuleError> { self.ensure_startup_configuration()?; + if self.policy_evaluator.is_some() && !std::ptr::eq(strategy, self.strategy()) { + return Err(ModuleError::new( + ErrorCode::PipelineConfigurationError, + "Per-call strategy overrides cannot replace the active policy strategy", + )); + } Self::validate_module_id(module_id)?; let mut parent = context.cloned().unwrap_or_else(Context::anonymous); parent.bind_executor(self.instance_handle())?; @@ -1384,7 +1437,7 @@ impl Executor { ctx: &PipelineContext, error: &ModuleError, ) -> Option { - if ctx.terminal_gate_failure + if ctx.blocks_error_recovery() || error.code == ErrorCode::ExecutionCancelled || ctx.executed_middlewares.is_empty() { @@ -1570,7 +1623,9 @@ impl Executor { // Step-4 `acl_check` that just ran (it is `pure`, so a dry run executes // it). Reporting only the policy-effective value would tell a caller no // approval is needed for a call the Step-5 gate will stop. - let requires_approval = policy_effective_approval || pipe_ctx.acl_approval_required; + let requires_approval = policy_effective_approval + || pipe_ctx.acl_approval_required + || pipe_ctx.policy_effect == Some(PolicyEffect::RequireApproval); // Module-level introspection is gated on TWO conditions, not one. // @@ -1615,8 +1670,10 @@ impl Executor { .as_ref() .is_some_and(crate::acl::AccessDecision::is_allowed); let mut predicted_changes: Vec = Vec::new(); + let policy_permitted = pipe_ctx.policy_evaluator.is_none() + || pipe_ctx.policy_effect == Some(PolicyEffect::Allow); if let (true, Some(module)) = ( - !acl_denied && (!acl_required || acl_permitted), + !acl_denied && (!acl_required || acl_permitted) && policy_permitted, pipe_ctx.module.clone(), ) { let warnings = module.preflight(inputs, ctx); @@ -2535,6 +2592,7 @@ impl Executor { ctx.acl = self.acl.as_ref().map(Arc::clone); ctx.approval_handler = self.approval_handler.as_ref().map(Arc::clone); ctx.policy = self.policy.as_ref().map(Arc::clone); + ctx.policy_evaluator = self.policy_evaluator.as_ref().map(Arc::clone); ctx.event_emitter = self.event_emitter.as_ref().map(Arc::clone); ctx.governance_warned = Some(Arc::clone(&self.governance_warned)); ctx.middleware_manager = Some(Arc::clone(&self.middleware_manager)); diff --git a/rust/src/executor/schema_redaction.rs b/rust/src/executor/schema_redaction.rs index 0c73e7bc..1584f36e 100644 --- a/rust/src/executor/schema_redaction.rs +++ b/rust/src/executor/schema_redaction.rs @@ -1,6 +1,7 @@ //! Local-reference traversal for schema-driven redaction. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::fmt::Write; use serde_json::Value; @@ -101,89 +102,145 @@ fn decode_fragment(fragment: &str) -> Option { pub(super) fn redact(value: &mut Value, schema: &Value) { let preserve_object_root = value.is_object(); - redact_value( - value, - schema, - &LocalSchemas::new(schema), - preserve_object_root, - ); + SchemaTraversal { + local: LocalSchemas::new(schema), + paths: None, + } + .visit(value, schema, preserve_object_root); } -fn redact_value<'a>( - value: &mut Value, - schema: &'a Value, - local: &LocalSchemas<'a>, - preserve_object_root: bool, -) { - let mut pending = vec![schema]; - let mut visited = HashSet::new(); - while let Some(schema) = pending.pop() { - // Identity is stable within the immutable schema and scoped to one data value. - if !visited.insert(std::ptr::from_ref(schema)) { - continue; - } - if !preserve_object_root && schema.get("x-sensitive") == Some(&Value::Bool(true)) { - if !value.is_null() { - *value = Value::String(super::REDACTED_VALUE.to_string()); +pub(super) fn sensitive_fields(value: &Value, schema: &Value) -> Vec { + // The traversal only reads values in collecting mode. + let mut snapshot = value.clone(); + let mut traversal = SchemaTraversal { + local: LocalSchemas::new(schema), + paths: Some(SensitivePaths::default()), + }; + traversal.visit(&mut snapshot, schema, false); + traversal + .paths + .into_iter() + .flat_map(|paths| paths.fields) + .collect() +} + +#[derive(Default)] +struct SensitivePaths { + current: String, + fields: BTreeSet, +} + +#[derive(Clone, Copy)] +enum Segment<'a> { + Key(&'a str), + Index(usize), +} + +struct SchemaTraversal<'a> { + local: LocalSchemas<'a>, + paths: Option, +} + +impl<'a> SchemaTraversal<'a> { + fn visit(&mut self, value: &mut Value, schema: &'a Value, preserve_object_root: bool) { + let mut pending = vec![schema]; + let mut visited = HashSet::new(); + while let Some(schema) = pending.pop() { + // Identity is stable within the immutable schema and scoped to one data value. + if !visited.insert(std::ptr::from_ref(schema)) { + continue; } - return; - } - if let Some(reference) = schema.get("$ref").and_then(Value::as_str) { - if let Some(target) = local.resolve(schema, reference) { - pending.push(target); + if !preserve_object_root && schema.get("x-sensitive") == Some(&Value::Bool(true)) { + if let Some(paths) = &mut self.paths { + paths.fields.insert(paths.current.clone()); + } else if !value.is_null() { + *value = Value::String(super::REDACTED_VALUE.to_string()); + } + return; } - } - for keyword in ["allOf", "anyOf", "oneOf"] { - if let Some(branches) = schema.get(keyword).and_then(Value::as_array) { - pending.extend(branches); + if let Some(reference) = schema.get("$ref").and_then(Value::as_str) { + if let Some(target) = self.local.resolve(schema, reference) { + pending.push(target); + } + } + for keyword in ["allOf", "anyOf", "oneOf"] { + if let Some(branches) = schema.get(keyword).and_then(Value::as_array) { + pending.extend(branches); + } + } + match value { + Value::Object(object) => { + if let Some(properties) = schema.get("properties").and_then(Value::as_object) { + for (name, field_schema) in properties { + if let Some(field) = object.get_mut(name) { + self.visit_child(field, field_schema, Segment::Key(name)); + } + } + } + } + Value::Array(items) => self.visit_items(items, schema), + _ => {} } } - redact_shape(value, schema, local); } -} -fn redact_shape<'a>(value: &mut Value, schema: &'a Value, local: &LocalSchemas<'a>) { - match value { - Value::Object(object) => { - if let Some(properties) = schema.get("properties").and_then(Value::as_object) { - for (name, field_schema) in properties { - if let Some(field) = object.get_mut(name) { - redact_value(field, field_schema, local, false); + fn visit_child(&mut self, value: &mut Value, schema: &'a Value, segment: Segment<'_>) { + let previous_length = self.paths.as_mut().map(|paths| { + let length = paths.current.len(); + paths.current.push('/'); + match segment { + Segment::Key(name) => { + for character in name.chars() { + match character { + '~' => paths.current.push_str("~0"), + '/' => paths.current.push_str("~1"), + character => paths.current.push(character), + } } } + Segment::Index(index) => { + let _ = write!(paths.current, "{index}"); + } } + length + }); + self.visit(value, schema, false); + if let (Some(paths), Some(length)) = (&mut self.paths, previous_length) { + paths.current.truncate(length); } - Value::Array(items) => redact_items(items, schema, local), - _ => {} } -} -fn redact_items<'a>(items: &mut [Value], schema: &'a Value, local: &LocalSchemas<'a>) { - let modern_items = - local.drafts.get(&std::ptr::from_ref(schema)) == Some(&referencing::Draft::Draft202012); - let prefix = modern_items - .then(|| schema.get("prefixItems").and_then(Value::as_array)) - .flatten(); - if let Some(prefix) = prefix { - for (item, item_schema) in items.iter_mut().zip(prefix) { - redact_value(item, item_schema, local, false); - } - } - match schema.get("items") { - Some(Value::Array(tuple)) if !modern_items => { - for (item, item_schema) in items.iter_mut().zip(tuple) { - redact_value(item, item_schema, local, false); + fn visit_items(&mut self, items: &mut [Value], schema: &'a Value) { + let modern_items = self.local.drafts.get(&std::ptr::from_ref(schema)) + == Some(&referencing::Draft::Draft202012); + let prefix = modern_items + .then(|| schema.get("prefixItems").and_then(Value::as_array)) + .flatten(); + if let Some(prefix) = prefix { + for (index, (item, item_schema)) in items.iter_mut().zip(prefix).enumerate() { + self.visit_child(item, item_schema, Segment::Index(index)); } - if let Some(additional) = schema.get("additionalItems") { - for item in items.iter_mut().skip(tuple.len()) { - redact_value(item, additional, local, false); + } + match schema.get("items") { + Some(Value::Array(tuple)) if !modern_items => { + for (index, (item, item_schema)) in items.iter_mut().zip(tuple).enumerate() { + self.visit_child(item, item_schema, Segment::Index(index)); + } + if let Some(additional) = schema.get("additionalItems") { + for (index, item) in items.iter_mut().enumerate().skip(tuple.len()) { + self.visit_child(item, additional, Segment::Index(index)); + } } } - } - Some(Value::Array(_)) | None => {} - Some(item_schema) => { - for item in items.iter_mut().skip(prefix.map_or(0, Vec::len)) { - redact_value(item, item_schema, local, false); + Some(Value::Array(_)) | None => {} + Some(item_schema) => { + for (index, item) in items + .iter_mut() + .enumerate() + .skip(prefix.map_or(0, Vec::len)) + { + self.visit_child(item, item_schema, Segment::Index(index)); + } } } } diff --git a/rust/src/extensions.rs b/rust/src/extensions.rs index 21ff7cc7..85bb1c86 100644 --- a/rust/src/extensions.rs +++ b/rust/src/extensions.rs @@ -13,6 +13,7 @@ use crate::executor::Executor; use crate::middleware::base::Middleware; use crate::observability::span::SpanExporter; use crate::observability::tracing_middleware::TracingMiddleware; +use crate::policy::PolicyEvaluator; use crate::registry::registry::{Discoverer, ModuleValidator, Registry}; // --------------------------------------------------------------------------- @@ -55,8 +56,10 @@ pub enum ExtensionKind { SpanExporter(Arc), /// Custom module validation. ModuleValidator(Arc), - /// Approval handler for Step 4.5 gate. + /// Approval handler for the invocation approval gate. ApprovalHandler(Arc), + /// Post-validation evaluator for an executor. + PolicyEvaluator(Arc), } impl std::fmt::Debug for ExtensionKind { @@ -74,6 +77,7 @@ impl std::fmt::Debug for ExtensionKind { ExtensionKind::ApprovalHandler(h) => { write!(f, "ExtensionKind::ApprovalHandler({h:?})") } + ExtensionKind::PolicyEvaluator(_) => write!(f, "ExtensionKind::PolicyEvaluator(...)"), } } } @@ -95,6 +99,9 @@ impl ExtensionKind { ExtensionKind::SpanExporter(e) => std::ptr::from_ref(&**e).cast::<()>(), ExtensionKind::ModuleValidator(v) => std::ptr::from_ref(&**v).cast::<()>(), ExtensionKind::ApprovalHandler(h) => std::ptr::from_ref(&**h).cast::<()>(), + ExtensionKind::PolicyEvaluator(evaluator) => { + std::ptr::from_ref(&**evaluator).cast::<()>() + } } } @@ -107,6 +114,7 @@ impl ExtensionKind { ExtensionKind::SpanExporter(_) => "span_exporter", ExtensionKind::ModuleValidator(_) => "module_validator", ExtensionKind::ApprovalHandler(_) => "approval_handler", + ExtensionKind::PolicyEvaluator(_) => "policy_evaluator", } } } @@ -165,6 +173,14 @@ fn built_in_points() -> HashMap { multiple: false, }, ); + points.insert( + "policy_evaluator".to_string(), + ExtensionPoint { + name: "policy_evaluator".to_string(), + description: "Post-validation invocation policy".to_string(), + multiple: false, + }, + ); points } @@ -553,6 +569,12 @@ impl ExtensionManager { registry: &Registry, executor: &mut Executor, ) -> Result<(), ModuleError> { + if let Some(ExtensionKind::PolicyEvaluator(evaluator)) = + self.first_builtin("policy_evaluator") + { + executor.set_policy_evaluator(Some(Arc::clone(evaluator)))?; + } + // Discoverer if let Some(ExtensionKind::Discoverer(d)) = self.first_builtin("discoverer") { registry.set_discoverer_shared(Arc::clone(d)); @@ -650,6 +672,7 @@ impl ExtensionManager { "span_exporter" => "SpanExporter", "module_validator" => "ModuleValidator", "approval_handler" => "ApprovalHandler", + "policy_evaluator" => "PolicyEvaluator", _ => "Unknown", } } @@ -663,7 +686,7 @@ mod tests { fn test_new_has_built_in_points() { let mgr = ExtensionManager::new(); let points = mgr.list_points(); - assert_eq!(points.len(), 6); + assert_eq!(points.len(), 7); let names: Vec = points.iter().map(|p| p.name.clone()).collect(); assert!(names.contains(&"discoverer".to_string())); @@ -672,6 +695,7 @@ mod tests { assert!(names.contains(&"span_exporter".to_string())); assert!(names.contains(&"module_validator".to_string())); assert!(names.contains(&"approval_handler".to_string())); + assert!(names.contains(&"policy_evaluator".to_string())); } #[test] @@ -927,7 +951,7 @@ mod tests { #[test] fn test_default_impl() { let mgr = ExtensionManager::default(); - assert_eq!(mgr.list_points().len(), 6); + assert_eq!(mgr.list_points().len(), 7); } #[test] diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 8dae8533..f6f8e9f2 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -164,7 +164,10 @@ pub use pipeline_config::{ build_strategy_from_config, build_strategy_from_config_with_toggle, register_step_type, registered_step_types, unregister_step_type, }; -pub use policy::{ExecutionPolicy, PolicyDecision, PolicyRule}; +pub use policy::{ + ExecutionPolicy, PolicyDecision, PolicyEffect, PolicyEvaluationRequest, PolicyEvaluator, + PolicyRule, PolicyVerdict, +}; pub use registry::registry::{ is_ephemeral_module_id, module_id_pattern, registry_events, Registry, RegistryEvents, DEFAULT_MODULE_VERSION, EPHEMERAL_NAMESPACE_PREFIX, MAX_MODULE_ID_LENGTH, MODULE_ID_PATTERN, diff --git a/rust/src/pipeline.rs b/rust/src/pipeline.rs index c860a432..ec69b71a 100644 --- a/rust/src/pipeline.rs +++ b/rust/src/pipeline.rs @@ -58,7 +58,8 @@ pub type RunUntilPredicate = Box bool + Send + Sync>; /// `value`, the failure is treated as a successful continue, and /// `after_step` still fires for the recovered step. Returning `Ok(None)` /// lets the original error propagate, subject to `ignore_errors`. -/// Built-in ACL and approval gate failures propagate after all entered +/// Built-in governance gate failures and failures before an installed +/// post-validation policy admits the invocation propagate after all entered /// middleware observes the error in reverse order for cleanup. /// /// Invocation order (`features/middleware-system.md` "Pipeline Step Middleware" @@ -119,6 +120,8 @@ pub enum BuiltinGate { Acl, /// The built-in approval gate (`approval_gate`). Approval, + /// The opt-in post-validation policy and final-scope approval gate. + PostValidationPolicy, } /// A single unit of work in the execution pipeline. @@ -126,7 +129,7 @@ pub enum BuiltinGate { /// Step implementations receive their configuration via constructor — the trait /// only defines the `execute()` contract and metadata accessors. #[async_trait] -pub trait Step: Send + Sync { +pub trait Step: Send + Sync + std::any::Any { /// Unique identifier within a strategy (e.g. "`acl_check`"). fn name(&self) -> &str; @@ -308,6 +311,11 @@ pub struct PipelineContext { /// from the strategy — absence of the gate is not a requirement. pub acl_approval_required: bool, pub(crate) acl_decision: Option, + pub(crate) policy_evaluator: Option>, + pub(crate) policy_approval_annotations: Option, + pub(crate) policy_effect: Option, + pub(crate) policy_inputs: Option, + pub(crate) policy_sensitive_fields: Vec, /// Set by `input_validation` step. pub validated_inputs: Option, /// Set by `execute` step (non-streaming). @@ -396,6 +404,11 @@ impl PipelineContext { governance_projection: None, acl_approval_required: false, acl_decision: None, + policy_evaluator: None, + policy_approval_annotations: None, + policy_effect: None, + policy_inputs: None, + policy_sensitive_fields: Vec::new(), validated_inputs: None, output: None, stream: None, @@ -445,6 +458,32 @@ impl PipelineContext { self.approval_credential.take().is_some() } + pub(crate) fn has_approval_credential(&self) -> bool { + self.approval_credential.is_some() + } + + fn policy_admission_pending(&self) -> bool { + self.policy_evaluator.is_some() && self.policy_effect.is_none() + } + + pub(crate) fn blocks_error_recovery(&self) -> bool { + self.terminal_gate_failure || self.policy_admission_pending() + } + + pub(crate) fn bind_policy_inputs(&mut self) -> Result<(), ModuleError> { + if self.policy_evaluator.is_some() { + let Some(arguments) = self.policy_inputs.take() else { + self.terminal_gate_failure = true; + return Err(ModuleError::new( + ErrorCode::PipelineConfigurationError, + "Execution requires the final-scope policy check", + )); + }; + self.inputs = arguments; + } + Ok(()) + } + pub(crate) fn declared_module_annotations(&self) -> Option { if let Some(lease) = &self.module_lease { return lease.declared_annotations.clone(); @@ -688,8 +727,7 @@ impl Step for NeutralisedGate { false } fn pure(&self) -> bool { - // The built-in values: the ACL gate is pure, the approval gate is not. - self.gate == BuiltinGate::Acl + self.gate != BuiltinGate::Approval } fn timeout_ms(&self) -> u64 { self.inner.timeout_ms() @@ -1324,6 +1362,8 @@ impl PipelineEngine { let step_timeout_ms = step.timeout_ms(); if ctx.dry_run && ((ctx.module.is_none() && step.requires().contains(&"module")) + || (step.builtin_gate() == Some(BuiltinGate::PostValidationPolicy) + && !ctx.preflight_errors.is_empty()) || step .requires() .iter() @@ -1407,6 +1447,9 @@ impl PipelineEngine { } } if let Some(err) = before_err { + if step.builtin_gate() == Some(BuiltinGate::PostValidationPolicy) { + ctx.terminal_gate_failure = true; + } // Spec: "Step middleware errors raised from `before_step` // itself (not from the step body) MUST be wrapped in // `MiddlewareChainError`, identical to the module-level @@ -1500,8 +1543,8 @@ impl PipelineEngine { idx += 1; continue; } - let is_gate = step.builtin_gate().is_some(); - let recovery = if is_gate { + let terminal = step.builtin_gate().is_some() || ctx.blocks_error_recovery(); + let recovery = if terminal { ctx.terminal_gate_failure = true; observe_step_error_hooks( middlewares, @@ -1534,7 +1577,7 @@ impl PipelineEngine { Some("error_recovered".to_string()), ) } - Ok(None) if step_ignore_errors && !is_gate => { + Ok(None) if step_ignore_errors && !terminal => { tracing::warn!(step = step.name(), error = %err, "Step failed (ignored)"); ctx.trace.steps.push(StepTrace { name: step.name().to_string(), @@ -1585,6 +1628,9 @@ impl PipelineEngine { .await .err(); if let Some(err) = after_err { + if step.builtin_gate() == Some(BuiltinGate::PostValidationPolicy) { + ctx.terminal_gate_failure = true; + } ctx.trace.steps.push(StepTrace { name: step_name_for_hooks.clone(), duration_ms, @@ -1655,6 +1701,12 @@ impl PipelineEngine { return Ok((ctx.output.clone(), ctx.trace.clone())); } "skip_to" => { + if ctx.policy_admission_pending() { + return Err(ModuleError::new( + ErrorCode::PipelineConfigurationError, + "Pipeline jumps require completed post-validation policy admission", + )); + } let target = skip_target.as_deref().unwrap_or(""); // O(1) lookup via the strategy's name_to_idx map (§1.5). // The lookup must reject same-position and backward diff --git a/rust/src/policy.rs b/rust/src/policy.rs index 3de947c8..f638dd20 100644 --- a/rust/src/policy.rs +++ b/rust/src/policy.rs @@ -29,6 +29,11 @@ use crate::errors::{ErrorCode, ModuleError}; use crate::module::ModuleAnnotations; use crate::utils::{calculate_specificity, match_pattern}; +mod evaluator; + +pub(crate) use evaluator::{evaluate, evaluation_error, final_arguments_digest}; +pub use evaluator::{PolicyEffect, PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict}; + /// The framework-owned Phase B approval token key (PROTOCOL_SPEC §7.4). /// Stripped from `arguments` before policy resolution (§7.9.6 rule 5) and /// excluded from the §6.1.8 governance projection on the same grounds. diff --git a/rust/src/policy/evaluator.rs b/rust/src/policy/evaluator.rs new file mode 100644 index 00000000..260295be --- /dev/null +++ b/rust/src/policy/evaluator.rs @@ -0,0 +1,207 @@ +use std::fmt::Write; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use async_trait::async_trait; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::{Number, Value}; +use sha2::{Digest, Sha256}; + +use crate::context::{Context, Identity}; +use crate::errors::{ErrorCode, ModuleError}; + +/// The post-validation decision for an invocation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PolicyEffect { + Allow, + Deny, + RequireApproval, +} + +/// A decision and its optional policy-defined static rule identifier. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct PolicyVerdict { + pub decision: PolicyEffect, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rule_id: Option, +} + +/// Detached validated input supplied to an explicitly installed policy evaluator. +#[derive(Clone, Serialize, Deserialize, JsonSchema)] +pub struct PolicyEvaluationRequest { + pub module_id: String, + pub module_version: Option, + pub caller_id: Option, + #[schemars(with = "Option")] + pub identity: Option, + pub arguments: Value, + /// JSON pointers to fields marked sensitive by the module's input schema. + pub sensitive_fields: Vec, +} + +/// An instance-scoped policy evaluated before execution and by preflight. +/// Implementations must be safe to use for a dry run. +#[async_trait] +pub trait PolicyEvaluator: Send + Sync { + async fn evaluate( + &self, + request: &PolicyEvaluationRequest, + ) -> Result; +} + +impl std::fmt::Debug for dyn PolicyEvaluator { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("PolicyEvaluator(...)") + } +} + +pub(crate) fn evaluation_error() -> ModuleError { + ModuleError::new( + ErrorCode::PolicyEvaluationError, + "The post-validation policy evaluator did not return a decision", + ) +} + +pub(crate) async fn evaluate( + evaluator: &dyn PolicyEvaluator, + request: &PolicyEvaluationRequest, + context: &Context, +) -> Result { + let started = tokio::time::Instant::now(); + let timeout = context.global_deadline.map_or(1.0, |deadline| { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + (deadline - now.as_secs_f64()).clamp(0.0, 1.0) + }); + if let Some(token) = &context.cancel_token { + token.check_for(&request.module_id)?; + } + if !timeout.is_finite() || timeout <= 0.0 { + return Err(evaluation_error()); + } + let expiration = started + Duration::from_secs_f64(timeout); + let decision = tokio::time::timeout_at(expiration, evaluator.evaluate(request)); + let result = if let Some(token) = &context.cancel_token { + tokio::select! { + biased; + () = token.cancelled() => { + token.check_for(&request.module_id)?; + return Err(evaluation_error()); + } + result = decision => result, + } + } else { + decision.await + }; + if let Some(token) = &context.cancel_token { + token.check_for(&request.module_id)?; + } + // An evaluator that never yielded may finish after the timer expired. + if tokio::time::Instant::now() >= expiration { + return Err(evaluation_error()); + } + result + .ok() + .and_then(Result::ok) + .ok_or_else(evaluation_error) +} + +pub(crate) fn final_arguments_digest(arguments: &Value) -> Result { + let mut encoding = String::new(); + write_scope(arguments, &mut encoding).map_err(|()| { + ModuleError::new( + ErrorCode::PolicyEvaluationError, + "Arguments cannot be bound without losing numeric precision", + ) + })?; + Ok(format!("{:x}", Sha256::digest(encoding.as_bytes()))) +} + +fn write_scope(value: &Value, output: &mut String) -> Result<(), ()> { + match value { + Value::Object(object) => { + let mut fields: Vec<_> = object.iter().collect(); + fields.sort_unstable_by(|(left, _), (right, _)| { + left.encode_utf16().cmp(right.encode_utf16()) + }); + output.push('{'); + for (index, (key, value)) in fields.into_iter().enumerate() { + if index != 0 { + output.push(','); + } + output.push_str(&serde_json::to_string(key).map_err(|_| ())?); + output.push(':'); + write_scope(value, output)?; + } + output.push('}'); + } + Value::Array(items) => { + output.push('['); + for (index, value) in items.iter().enumerate() { + if index != 0 { + output.push(','); + } + write_scope(value, output)?; + } + output.push(']'); + } + Value::Number(number) => write_number(number, output)?, + _ => output.push_str(&serde_json::to_string(value).map_err(|_| ())?), + } + Ok(()) +} + +fn write_number(number: &Number, output: &mut String) -> Result<(), ()> { + const MAX_INTEGER: u64 = 9_007_199_254_740_991; + const MAX_FLOAT_INTEGER: f64 = 9_007_199_254_740_991.0; + if let Some(value) = number.as_i64() { + if value.unsigned_abs() > MAX_INTEGER { + return Err(()); + } + return write!(output, "i{value};").map_err(|_| ()); + } + // Nonnegative integers above i64::MAX are always outside the safe domain. + if number.is_u64() { + return Err(()); + } + let value = number.as_f64().ok_or(())?; + if !value.is_finite() || (value.fract() == 0.0 && value.abs() > MAX_FLOAT_INTEGER) { + return Err(()); + } + write!(output, "f{:016x};", value.to_bits()).map_err(|_| ()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn policy_arguments_encoding_preserves_native_values() { + let mut encoding = String::new(); + write_scope( + &json!({"\u{10000}": -0.0, "\u{e000}": [1, 1.0, "\u{6771}\u{4eac}"], "10": 3}), + &mut encoding, + ) + .unwrap(); + assert_eq!( + encoding, + "{\"10\":i3;,\"\u{10000}\":f8000000000000000;,\"\u{e000}\":[i1;,f3ff0000000000000;,\"\u{6771}\u{4eac}\"]}" + ); + assert_ne!( + final_arguments_digest(&json!(-0.0)).unwrap(), + final_arguments_digest(&json!(0.0)).unwrap() + ); + for unsupported in [ + json!(9_007_199_254_740_992_u64), + json!(-9_007_199_254_740_992.0), + ] { + assert_eq!( + final_arguments_digest(&unsupported).unwrap_err().code, + ErrorCode::PolicyEvaluationError + ); + } + } +} diff --git a/rust/src/registry/registry.rs b/rust/src/registry/registry.rs index 9e994aac..03c101d4 100644 --- a/rust/src/registry/registry.rs +++ b/rust/src/registry/registry.rs @@ -651,6 +651,7 @@ pub(crate) struct ModuleExecutionLease { references: Arc, execution: Option, pub declared_annotations: Option, + pub version: Option, pub enabled: bool, } @@ -2500,6 +2501,7 @@ impl Registry { references, execution, declared_annotations: descriptor.and_then(|entry| entry.annotations.clone()), + version: descriptor.map(|entry| entry.version.clone()), enabled: descriptor.is_none_or(|entry| entry.enabled), }); let deprecated = descriptor diff --git a/rust/tests/core_profile.rs b/rust/tests/core_profile.rs index 06670fd8..3ee32f2a 100644 --- a/rust/tests/core_profile.rs +++ b/rust/tests/core_profile.rs @@ -14,6 +14,7 @@ use serde_json::{json, Value}; #[path = "conformance_env.rs"] mod conformance_env; +mod post_validation_policy; #[derive(Default)] struct Report { diff --git a/rust/tests/post_validation_policy.rs b/rust/tests/post_validation_policy.rs new file mode 100644 index 00000000..72b758e8 --- /dev/null +++ b/rust/tests/post_validation_policy.rs @@ -0,0 +1,819 @@ +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use apcore::approval::{ApprovalHandler, ApprovalRequest, ApprovalResult}; +use apcore::errors::ErrorCode; +use apcore::middleware::Middleware; +use apcore::pipeline::{PipelineState, StepMiddleware}; +use apcore::registry::ModuleDescriptor; +use apcore::{ + ChunkStream, Config, Context, Executor, Module, ModuleAnnotations, ModuleError, PolicyEffect, + PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict, Registry, ACL, +}; +use async_trait::async_trait; +use futures_util::{stream, StreamExt}; +use serde_json::{json, Value}; + +use super::conformance_env; + +struct Probe { + schema: Value, + requirements: bool, + starts: Arc, +} + +#[async_trait] +impl Module for Probe { + fn description(&self) -> &'static str { + "Return validated policy inputs" + } + + fn input_schema(&self) -> Value { + self.schema.clone() + } + + fn output_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn annotations(&self) -> ModuleAnnotations { + ModuleAnnotations { + requires_approval: self.requirements, + ..ModuleAnnotations::default() + } + } + + async fn execute( + &self, + inputs: Value, + _context: &Context, + ) -> Result { + self.starts.fetch_add(1, Ordering::Relaxed); + Self::result(inputs) + } + + fn stream(&self, inputs: Value, _context: &Context) -> Option { + self.starts.fetch_add(1, Ordering::Relaxed); + Some(Box::pin(stream::iter([Self::result(inputs)]))) + } +} + +impl Probe { + fn result(inputs: Value) -> Result { + if inputs.get("fail_execution") == Some(&Value::Bool(true)) { + return Err(ModuleError::new( + ErrorCode::ModuleExecuteError, + "probe failed", + )); + } + Ok(inputs) + } +} + +struct Evaluator { + decision: String, + observed: Mutex>, +} + +#[async_trait] +impl PolicyEvaluator for Evaluator { + async fn evaluate( + &self, + request: &PolicyEvaluationRequest, + ) -> Result { + self.observed.lock().unwrap().push(request.clone()); + let decision = match self.decision.as_str() { + "allow" => PolicyEffect::Allow, + "deny" => PolicyEffect::Deny, + "require_approval" => PolicyEffect::RequireApproval, + "throw" => { + return Err(ModuleError::new( + ErrorCode::GeneralInternalError, + "backend leaked private-fixture-value", + )); + } + unexpected => panic!("unsupported fixture verdict: {unexpected}"), + }; + Ok(PolicyVerdict { + decision, + rule_id: Some("fixture-rule".to_string()), + }) + } +} + +#[derive(Debug)] +enum Rewrite { + Amount(Value), + Reject, +} + +#[async_trait] +impl Middleware for Rewrite { + fn name(&self) -> &'static str { + "fixture-rewrite" + } + + async fn before( + &self, + _module_id: &str, + mut inputs: Value, + _context: &Context, + ) -> Result, ModuleError> { + match self { + Self::Amount(amount) => { + inputs["amount"] = amount.clone(); + Ok(Some(inputs)) + } + Self::Reject => Err(ModuleError::new( + ErrorCode::GeneralInvalidInput, + "normalization failed", + )), + } + } + + async fn after( + &self, + _module_id: &str, + _inputs: Value, + _output: Value, + _context: &Context, + ) -> Result, ModuleError> { + Ok(None) + } + + async fn on_error( + &self, + _module_id: &str, + _inputs: Value, + _error: &ModuleError, + _context: &Context, + ) -> Result, ModuleError> { + // Policy denials and faults must remain terminal even with recovery. + Ok(Some(json!({"recovered": true}))) + } +} + +fn approval_scope(request: &ApprovalRequest) -> Value { + json!({ + "principal": request.context.as_ref().and_then(|ctx| ctx.identity.as_ref()), + "caller_id": request.caller_id, + "module_id": request.module_id, + "module_version": request.module_version, + "canonical_args_digest": request.canonical_args_digest, + }) +} + +const TEST_CREDENTIAL: &str = "fixture-resume-credential"; + +#[derive(Debug)] +struct Approver { + pending: bool, + supports_final_scope: bool, + requested: Mutex>, + scope: Mutex>, + checks: AtomicUsize, +} + +#[async_trait] +impl ApprovalHandler for Approver { + fn supports_final_scope(&self) -> bool { + self.supports_final_scope + } + + async fn request_approval( + &self, + request: &ApprovalRequest, + ) -> Result { + self.requested.lock().unwrap().push(request.clone()); + if self.pending { + *self.scope.lock().unwrap() = Some(approval_scope(request)); + let mut result = ApprovalResult::default(); + result.status = "pending".to_string(); + result.approval_id = Some(TEST_CREDENTIAL.to_string()); + return Ok(result); + } + Ok(ApprovalResult::approved("fixture-reviewer")) + } + + async fn check_approval(&self, _approval_id: &str) -> Result { + panic!("status query cannot authorize execution"); + } + + async fn check_approval_for_call( + &self, + approval_id: &str, + request: &ApprovalRequest, + ) -> Result { + self.checks.fetch_add(1, Ordering::Relaxed); + let mut stored = self.scope.lock().unwrap(); + if approval_id != TEST_CREDENTIAL || stored.as_ref() != Some(&approval_scope(request)) { + return Ok(ApprovalResult::rejected("scope mismatch")); + } + stored.take(); + Ok(ApprovalResult::approved("fixture-reviewer")) + } +} + +fn override_inputs(inputs: &mut Value, overrides: &Value) { + if let Some(overrides) = overrides.as_object() { + inputs.as_object_mut().unwrap().extend(overrides.clone()); + } +} + +async fn invoke_fixture( + executor: &Executor, + module_id: &str, + case: &Value, + mut inputs: Value, +) -> (Result, Option) { + let id = case["id"].as_str().unwrap(); + let entry = case["entry"].as_str().unwrap(); + let mut requires_approval = None; + let result = match entry { + "call" => executor.call(module_id, inputs, None, None).await, + "preflight" => { + let preflight = executor.validate(module_id, &inputs, None).await.unwrap(); + assert!(preflight + .checks + .iter() + .any(|check| check.check == "post_validation_policy" && check.passed)); + requires_approval = Some(preflight.requires_approval); + Ok(Value::Null) + } + "stream" => executor + .stream(module_id, inputs, None, None) + .next() + .await + .unwrap(), + "resume" => { + let pending = executor + .call(module_id, inputs.clone(), None, None) + .await + .unwrap_err(); + assert_eq!(pending.code, ErrorCode::ApprovalPending, "{id}: {pending}"); + override_inputs(&mut inputs, &case["retry_inputs"]); + assert_eq!(pending.details["approval_id"], TEST_CREDENTIAL, "{id}"); + inputs["_approval_token"] = pending.details["approval_id"].clone(); + executor.call(module_id, inputs, None, None).await + } + _ => panic!("unsupported fixture entry: {entry}"), + }; + (result, requires_approval) +} + +fn assert_evaluations(observed: &[PolicyEvaluationRequest], contract: &Value, id: &str) { + let module_id = contract["module_id"].as_str().unwrap(); + for request in observed { + assert_eq!(request.module_id, module_id, "{id}"); + assert_eq!( + json!(request.module_version), + contract["module_version"], + "{id}" + ); + assert_eq!(request.sensitive_fields, ["/secret"], "{id}"); + assert!(request.arguments.get("_approval_token").is_none(), "{id}"); + } +} + +#[tokio::test] +async fn post_validation_policy_matches_shared_fixture() { + let fixture: Value = serde_json::from_str( + &std::fs::read_to_string( + conformance_env::find_fixtures_root().join("post_validation_policy.json"), + ) + .unwrap(), + ) + .unwrap(); + let contract = &fixture["driver_contract"]; + let module_id = contract["module_id"].as_str().unwrap(); + for case in fixture["test_cases"].as_array().unwrap() { + let id = case["id"].as_str().unwrap(); + let entry = case["entry"].as_str().unwrap(); + let registry = Arc::new(Registry::new()); + let starts = Arc::new(AtomicUsize::new(0)); + let probe = Probe { + schema: contract["input_schema"].clone(), + requirements: case["requires_approval"].as_bool().unwrap_or(false), + starts: Arc::clone(&starts), + }; + let descriptor: ModuleDescriptor = serde_json::from_value(json!({ + "module_id": module_id, + "version": contract["module_version"], + "input_schema": probe.input_schema(), + "output_schema": probe.output_schema(), + })) + .unwrap(); + registry + .register(module_id, Box::new(probe), descriptor) + .unwrap(); + + let evaluator = spy_evaluator(case["verdict"].as_str().unwrap()); + let approver = Arc::new(Approver { + pending: entry == "resume", + supports_final_scope: true, + requested: Mutex::new(Vec::new()), + scope: Mutex::new(None), + checks: AtomicUsize::new(0), + }); + let mut executor = Executor::new(registry, Config::in_memory()); + executor + .set_policy_evaluator(Some(evaluator.clone())) + .unwrap(); + executor.set_approval_handler_shared(approver.clone()); + if let Some(amount) = case.get("rewrite_amount") { + executor + .use_middleware(Box::new(Rewrite::Amount(amount.clone()))) + .unwrap(); + } else if matches!(case["verdict"].as_str(), Some("deny" | "throw")) { + executor + .use_middleware(Box::new(Rewrite::Amount( + contract["business_input"]["amount"].clone(), + ))) + .unwrap(); + } + let mut inputs = contract["business_input"].clone(); + override_inputs(&mut inputs, &case["inputs"]); + let (result, requires_approval) = invoke_fixture(&executor, module_id, case, inputs).await; + let observed = evaluator.observed.lock().unwrap(); + assert_evaluations(&observed, contract, id); + let approval_requests = approver.requested.lock().unwrap(); + for request in approval_requests.iter() { + assert_eq!( + json!(request.module_version), + contract["module_version"], + "{id}" + ); + assert_eq!( + request.canonical_args_digest.as_ref().unwrap().len(), + 64, + "{id}" + ); + assert!(request.arguments.get("_approval_token").is_none(), "{id}"); + } + let error = result.as_ref().err(); + if let (Some(request), Ok(output)) = (observed.last(), &result) { + if entry != "preflight" { + assert_eq!(&request.arguments, output, "{id}"); + } + } + assert!( + !error.is_some_and(|error| error.to_string().contains("private-fixture-value")), + "{id}" + ); + let observed_results = json!({ + "module_starts": starts.load(Ordering::Relaxed), + "evaluated_amount": observed.last().map(|r| &r.arguments["amount"]), + "approval_requests": approval_requests.len(), + "approved_amount": approval_requests.last().map(|r| &r.arguments["amount"]), + "requires_approval": requires_approval, + "resume_checks": approver.checks.load(Ordering::Relaxed), + "error_code": error.map(ModuleError::wire_code), + }); + for (key, expected) in case["expected"].as_object().unwrap() { + assert_eq!(&observed_results[key], expected, "{id}: {key}"); + } + } +} + +fn probe_registry(version: &str) -> Arc { + let registry = Arc::new(Registry::new()); + register_version(®istry, version); + registry +} + +fn register_version(registry: &Registry, version: &str) { + let probe = Probe { + schema: json!({"type": "object"}), + requirements: false, + starts: Arc::new(AtomicUsize::new(0)), + }; + register_probe(registry, version, probe); +} + +fn register_probe(registry: &Registry, version: &str, probe: Probe) { + let descriptor = serde_json::from_value(json!({ + "module_id": "demo.policy", + "version": version, + "input_schema": probe.input_schema(), + "output_schema": probe.output_schema(), + })) + .unwrap(); + registry + .register("demo.policy", Box::new(probe), descriptor) + .unwrap(); +} + +fn spy_evaluator(verdict: &str) -> Arc { + Arc::new(Evaluator { + decision: verdict.to_string(), + observed: Mutex::new(Vec::new()), + }) +} + +fn pending_approver(supports_final_scope: bool) -> Arc { + Arc::new(Approver { + pending: true, + supports_final_scope, + requested: Mutex::new(Vec::new()), + scope: Mutex::new(None), + checks: AtomicUsize::new(0), + }) +} + +#[tokio::test] +async fn preflight_after_acl_denial_reaches_neither_policy_nor_preview() { + let mut executor = Executor::new(probe_registry("1.0.0"), Config::in_memory()); + let evaluator = spy_evaluator("allow"); + let mut extensions = apcore::ExtensionManager::new(); + extensions + .register( + "policy_evaluator", + apcore::ExtensionKind::PolicyEvaluator(evaluator.clone()), + ) + .unwrap(); + let registry = Arc::clone(&executor.registry); + extensions.apply(®istry, &mut executor).unwrap(); + executor.set_acl(ACL::new(vec![], "deny", None)); + let report = executor + .validate("demo.policy", &json!({}), None) + .await + .unwrap(); + assert!(!report.valid); + assert!(report + .checks + .iter() + .all(|check| !matches!(check.check.as_str(), "module_preflight" | "module_preview"))); + assert!(evaluator.observed.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn installed_policy_refuses_an_unguarded_strategy() { + let registry = probe_registry("1.0.0"); + let evaluator = spy_evaluator("allow"); + let mut incompatible = + Executor::with_strategy_name(Arc::clone(®istry), Config::in_memory(), "minimal") + .unwrap(); + assert_eq!( + incompatible + .set_policy_evaluator(Some(evaluator.clone())) + .unwrap_err() + .code, + ErrorCode::PipelineConfigurationError + ); + let mut executor = Executor::new(registry, Config::in_memory()); + executor + .set_policy_evaluator(Some(evaluator.clone())) + .unwrap(); + assert_eq!( + executor + .call_with_trace( + "demo.policy", + json!({}), + None, + None, + Some(&apcore::builtin_steps::build_minimal_strategy()) + ) + .await + .unwrap_err() + .code, + ErrorCode::PipelineConfigurationError + ); + assert!(evaluator.observed.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn final_resume_checks_the_current_version_even_after_allow() { + let registry = probe_registry("1.0.0"); + let mut executor = Executor::new(Arc::clone(®istry), Config::in_memory()); + let handler = pending_approver(true); + executor.set_approval_handler_shared(handler.clone()); + executor + .set_policy_evaluator(Some(spy_evaluator("require_approval"))) + .unwrap(); + let pending = executor + .call("demo.policy", json!({}), None, None) + .await + .unwrap_err(); + assert_eq!(pending.code, ErrorCode::ApprovalPending); + assert_eq!(pending.details["approval_id"], TEST_CREDENTIAL); + registry.unregister("demo.policy").unwrap(); + register_version(®istry, "2.0.0"); + executor + .set_policy_evaluator(Some(spy_evaluator("allow"))) + .unwrap(); + + let result = executor + .call( + "demo.policy", + json!({"_approval_token": TEST_CREDENTIAL}), + None, + Some("1.0.0"), + ) + .await; + assert_eq!(result.unwrap_err().code, ErrorCode::ApprovalDenied); + assert_eq!(handler.checks.load(Ordering::Relaxed), 1); + assert_eq!(handler.requested.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn unsupported_handler_cannot_expose_a_final_scope_credential() { + let mut executor = Executor::new(probe_registry("1.0.0"), Config::in_memory()); + executor + .set_policy_evaluator(Some(spy_evaluator("require_approval"))) + .unwrap(); + let handler = pending_approver(false); + executor.set_approval_handler_shared(handler.clone()); + let result = executor + .call("demo.policy", json!({}), None, None) + .await + .unwrap_err(); + assert_eq!(result.code, ErrorCode::ApprovalDenied); + assert!(!result.details.contains_key("approval_id")); + assert!(!result.to_dict().to_string().contains(TEST_CREDENTIAL)); + let result = executor + .call( + "demo.policy", + json!({"_approval_token": TEST_CREDENTIAL}), + None, + None, + ) + .await + .unwrap_err(); + assert_eq!(result.code, ErrorCode::ApprovalDenied); + assert_eq!(handler.checks.load(Ordering::Relaxed), 0); +} + +struct PendingPolicy(Arc); + +#[async_trait] +impl PolicyEvaluator for PendingPolicy { + async fn evaluate( + &self, + _request: &PolicyEvaluationRequest, + ) -> Result { + self.0.notify_one(); + std::future::pending().await + } +} + +#[tokio::test] +async fn policy_timeout_is_distinct_from_caller_cancellation() { + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + let mut executor = Executor::new(probe_registry("1.0.0"), Config::in_memory()); + let entered = Arc::new(tokio::sync::Notify::new()); + executor + .set_policy_evaluator(Some(Arc::new(PendingPolicy(Arc::clone(&entered))))) + .unwrap(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs_f64(); + let mut context = Context::anonymous(); + context.global_deadline = Some(now + 0.12); + let timeout = tokio::time::timeout( + Duration::from_millis(600), + executor.call("demo.policy", json!({}), Some(&context), None), + ) + .await + .expect("evaluator must honor the earlier invocation deadline") + .unwrap_err(); + assert_eq!(timeout.code, ErrorCode::PolicyEvaluationError); + assert_eq!(timeout.to_dict()["retryable"], true); + assert_eq!(timeout.to_dict()["user_fixable"], false); + + let cancel = apcore::CancelToken::new(); + let entered = Arc::new(tokio::sync::Notify::new()); + executor + .set_policy_evaluator(Some(Arc::new(PendingPolicy(Arc::clone(&entered))))) + .unwrap(); + context.global_deadline = None; + context.cancel_token = Some(cancel.clone()); + let (result, ()) = tokio::join!( + executor.call("demo.policy", json!({}), Some(&context), None), + async { + entered.notified().await; + cancel.cancel(); + }, + ); + assert_eq!(result.unwrap_err().code, ErrorCode::ExecutionCancelled); +} + +struct LateApproval { + expiration: std::time::SystemTime, + evaluations: AtomicUsize, +} + +#[async_trait] +impl PolicyEvaluator for LateApproval { + async fn evaluate( + &self, + _request: &PolicyEvaluationRequest, + ) -> Result { + self.evaluations.fetch_add(1, Ordering::Relaxed); + let remaining = self + .expiration + .duration_since(std::time::SystemTime::now()) + .unwrap_or_default(); + // Deliberately do not yield before returning the verdict. + std::thread::sleep(remaining + std::time::Duration::from_millis(20)); + Ok(PolicyVerdict { + decision: PolicyEffect::RequireApproval, + rule_id: None, + }) + } +} + +fn counted_policy_probe() -> (Registry, Arc) { + let registry = Registry::new(); + let starts = Arc::new(AtomicUsize::new(0)); + register_probe( + ®istry, + "1.0.0", + Probe { + schema: json!({"type":"object", "properties":{"amount":{"type":"integer"}},"required":["amount"]}), + requirements: false, + starts: Arc::clone(&starts), + }, + ); + (registry, starts) +} + +#[tokio::test] +async fn a_late_nonyielding_verdict_cannot_advance_admission() { + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + let (registry, starts) = counted_policy_probe(); + let mut executor = Executor::new(registry, Config::in_memory()); + let approver = pending_approver(true); + executor.set_approval_handler_shared(approver.clone()); + for entry in ["call", "stream", "preflight"] { + let expiration = SystemTime::now() + Duration::from_millis(200); + let evaluator = Arc::new(LateApproval { + expiration, + evaluations: AtomicUsize::new(0), + }); + executor + .set_policy_evaluator(Some(evaluator.clone())) + .unwrap(); + let mut context = Context::anonymous(); + context.global_deadline = + Some(expiration.duration_since(UNIX_EPOCH).unwrap().as_secs_f64()); + + let input = json!({"amount": 10}); + let error_code = match entry { + "call" => executor + .call("demo.policy", input, Some(&context), None) + .await + .unwrap_err() + .code + .wire_str(), + "stream" => executor + .stream("demo.policy", input, Some(&context), None) + .next() + .await + .unwrap() + .unwrap_err() + .code + .wire_str(), + _ => { + let report = executor + .validate("demo.policy", &input, Some(&context)) + .await + .unwrap(); + assert!(!report.valid && !report.requires_approval); + report + .checks + .iter() + .find(|check| check.check == "post_validation_policy") + .and_then(|check| check.error.as_ref()) + .unwrap()["code"] + .as_str() + .unwrap() + .to_owned() + } + }; + assert_eq!(evaluator.evaluations.load(Ordering::Relaxed), 1, "{entry}"); + assert_eq!(error_code, "POLICY_EVALUATION_ERROR", "{entry}"); + } + assert!(approver.requested.lock().unwrap().is_empty()); + assert_eq!(starts.load(Ordering::Relaxed), 0); +} + +#[tokio::test] +async fn module_recovery_is_gated_by_successful_final_admission() { + let (registry, starts) = counted_policy_probe(); + let mut executor = Executor::new(registry, Config::in_memory()); + let evaluator = spy_evaluator("allow"); + executor + .set_policy_evaluator(Some(evaluator.clone())) + .unwrap(); + executor + .use_middleware(Box::new(Rewrite::Amount(json!("invalid")))) + .unwrap(); + + let input = json!({"amount": 10}); + let error = executor + .call("demo.policy", input.clone(), None, None) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::SchemaValidationError); + let error = executor + .stream("demo.policy", input.clone(), None, None) + .next() + .await + .unwrap() + .unwrap_err(); + assert_eq!(error.code, ErrorCode::SchemaValidationError); + assert!(evaluator.observed.lock().unwrap().is_empty()); + assert_eq!(starts.load(Ordering::Relaxed), 0); + + // Legacy calls retain recovery from the same pre-dispatch failure. + executor.set_policy_evaluator(None).unwrap(); + assert_eq!( + executor + .call("demo.policy", input, None, None) + .await + .unwrap(), + json!({"recovered":true}) + ); + + // Once the policy admits an invocation, execution errors remain recoverable. + executor.remove("fixture-rewrite"); + executor + .use_middleware(Box::new(Rewrite::Amount(json!(10)))) + .unwrap(); + executor.set_policy_evaluator(Some(evaluator)).unwrap(); + let input = json!({"amount": 10, "fail_execution": true}); + assert_eq!( + executor + .call("demo.policy", input.clone(), None, None) + .await + .unwrap(), + json!({"recovered":true}) + ); + assert_eq!( + executor + .stream("demo.policy", input, None, None) + .next() + .await + .unwrap() + .unwrap(), + json!({"recovered":true}) + ); + assert_eq!(starts.load(Ordering::Relaxed), 2); +} + +struct StepRecovery(AtomicUsize); + +#[async_trait] +impl StepMiddleware for StepRecovery { + async fn on_step_error( + &self, + _step_name: &str, + _state: &PipelineState<'_>, + _error: &ModuleError, + ) -> Result, ModuleError> { + self.0.fetch_add(1, Ordering::Relaxed); + Ok(Some(json!({"recovered": true}))) + } +} + +#[tokio::test] +async fn step_recovery_cannot_advance_a_failed_normalization_to_policy() { + let (registry, starts) = counted_policy_probe(); + let observer = Arc::new(StepRecovery(AtomicUsize::new(0))); + let mut strategy = apcore::builtin_steps::build_standard_strategy(); + strategy.add_step_middleware(observer.clone()); + let mut executor = Executor::with_strategy(registry, Config::in_memory(), strategy); + let evaluator = spy_evaluator("allow"); + executor + .set_policy_evaluator(Some(evaluator.clone())) + .unwrap(); + executor.use_middleware(Box::new(Rewrite::Reject)).unwrap(); + + let input = json!({"amount": 10}); + let error = executor + .call("demo.policy", input.clone(), None, None) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::GeneralInvalidInput); + let error = executor + .stream("demo.policy", input.clone(), None, None) + .next() + .await + .unwrap() + .unwrap_err(); + assert_eq!(error.code, ErrorCode::GeneralInvalidInput); + assert!(evaluator.observed.lock().unwrap().is_empty()); + assert_eq!(starts.load(Ordering::Relaxed), 0); + assert_eq!(observer.0.load(Ordering::Relaxed), 2); + + // Dry-run preflight still reads the submitted input without normalizing it. + let report = executor + .validate("demo.policy", &input, None) + .await + .unwrap(); + assert!(report.valid); + assert_eq!(evaluator.observed.lock().unwrap().len(), 1); +} diff --git a/rust/tests/test_extensions.rs b/rust/tests/test_extensions.rs index a58dda01..3589def1 100644 --- a/rust/tests/test_extensions.rs +++ b/rust/tests/test_extensions.rs @@ -22,7 +22,7 @@ fn make_acl() -> ExtensionKind { #[test] fn test_new_has_six_built_in_points() { let mgr = ExtensionManager::new(); - assert_eq!(mgr.list_points().len(), 6); + assert_eq!(mgr.list_points().len(), 7); } #[test] @@ -47,7 +47,7 @@ fn test_list_points_contains_all_expected_names() { #[test] fn test_default_equals_new() { let mgr = ExtensionManager::default(); - assert_eq!(mgr.list_points().len(), 6); + assert_eq!(mgr.list_points().len(), 7); } // --------------------------------------------------------------------------- diff --git a/typescript/apcore-conformance.yaml b/typescript/apcore-conformance.yaml index 0a90f047..7fc0d021 100644 --- a/typescript/apcore-conformance.yaml +++ b/typescript/apcore-conformance.yaml @@ -2,7 +2,7 @@ # It does not certify every fixture required by Level 1 or Level 2. implementation: name: apcore-typescript - version: "1.0.0-alpha.2" + version: "1.0.0-alpha.3" language: typescript spec_version: "1.65.0" maintainer: AI Perceivable diff --git a/typescript/package.json b/typescript/package.json index 00f9a1b7..e3a6cbb6 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-js", - "version": "1.0.0-alpha.2", + "version": "1.0.0-alpha.3", "description": "Build once, invoke by code or AI — with schema, ACL, approval, and audit enforced at every call", "type": "module", "main": "./dist/index.js", diff --git a/typescript/src/approval.ts b/typescript/src/approval.ts index 9f0213a2..7e31b311 100644 --- a/typescript/src/approval.ts +++ b/typescript/src/approval.ts @@ -69,6 +69,10 @@ export interface ApprovalRequest { readonly annotations: ModuleAnnotations; readonly description: string | null; readonly tags: readonly string[]; + /** The resolved registration version of a final-scope request. */ + readonly moduleVersion?: string | null; + /** Present on approvals bound to the final validated invocation. */ + readonly canonicalArgsDigest?: string; } /** @@ -90,6 +94,8 @@ export function createApprovalRequest(options: { tags?: string[]; callerId?: string | null; action?: string; + moduleVersion?: string | null; + canonicalArgsDigest?: string; }): ApprovalRequest { return Object.freeze({ moduleId: options.moduleId, @@ -100,6 +106,8 @@ export function createApprovalRequest(options: { annotations: options.annotations, description: options.description ?? null, tags: Object.freeze([...(options.tags ?? [])]), + ...(options.moduleVersion !== undefined ? { moduleVersion: options.moduleVersion } : {}), + ...(options.canonicalArgsDigest !== undefined ? { canonicalArgsDigest: options.canonicalArgsDigest } : {}), }); } @@ -144,6 +152,8 @@ export function createApprovalResult(options: { * Both methods are asynchronous. */ export interface ApprovalHandler { + /** Opt in to issuing and consuming approvals bound to the final invocation. */ + readonly supportsFinalScope?: boolean; requestApproval(request: ApprovalRequest): Promise; checkApproval(approvalId: string): Promise; /** Validate the current call's identity, target and arguments, then consume the approval. */ diff --git a/typescript/src/browser/index.ts b/typescript/src/browser/index.ts index f61fa042..3020b8d3 100644 --- a/typescript/src/browser/index.ts +++ b/typescript/src/browser/index.ts @@ -98,6 +98,8 @@ export { ApprovalDeniedError, ApprovalTimeoutError, ApprovalPendingError, + PolicyDeniedError, + PolicyEvaluationError, ModuleNotFoundError, ModuleDisabledError, ModuleTimeoutError, diff --git a/typescript/src/builtin-steps.ts b/typescript/src/builtin-steps.ts index dc58c000..e2f6bcf1 100644 --- a/typescript/src/builtin-steps.ts +++ b/typescript/src/builtin-steps.ts @@ -12,7 +12,7 @@ import type { ACL, AccessDecision } from './acl.js'; import { buildGovernanceProjection } from './acl-handlers.js'; import { governanceUnion } from './schema/annotations.js'; import { RedactionConfig } from './observability/context-logger.js'; -import type { ApprovalHandler, ApprovalResult } from './approval.js'; +import type { ApprovalHandler, ApprovalRequest, ApprovalResult } from './approval.js'; import { createApprovalRequest, createApprovalResult, takeApprovalToken } from './approval.js'; import type { Config } from './config.js'; import { getDefault } from './config-defaults.js'; @@ -28,19 +28,25 @@ import { ModuleExecuteError, ModuleNotFoundError, ModuleTimeoutError, + PolicyDeniedError, + PolicyEvaluationError, SchemaValidationError, } from './errors.js'; import { DEFAULT_TOGGLE_STATE, type ToggleState } from './sys-modules/toggle.js'; -import { redactSensitive } from './executor.js'; +import { redactSensitive, sensitivePolicyFields } from './executor.js'; import { auditSpan } from './execution-lifetime.js'; import { type EventEmitter, createEvent } from './events/emitter.js'; import { applyDecisionToAnnotations, DEFAULT_EXECUTION_POLICY } from './policy.js'; import type { ExecutionPolicy, PolicyDecision } from './policy.js'; +import { + assertPolicyBinding, copyPolicyInputs, evaluatePolicy, policyApprovalContext, policyArgumentsDigest, policyInvocationOf, + type PolicyEvaluator, +} from './policy-evaluation.js'; import { MiddlewareChainError, type MiddlewareManager } from './middleware/manager.js'; import type { Module, ModuleAnnotations } from './module.js'; import { DEFAULT_ANNOTATIONS, isModuleIdempotent } from './module.js'; import type { GovernanceGateMarker, PipelineContext, Step, StepResult } from './pipeline.js'; -import { ExecutionStrategy, GOVERNANCE_GATE } from './pipeline.js'; +import { ConfigurationError, ExecutionStrategy, GOVERNANCE_GATE } from './pipeline.js'; import { isStreamingModule } from './streaming.js'; import type { Registry } from './registry/registry.js'; import { jsonSchemaToTypeBox } from './schema/loader-pure.js'; @@ -102,6 +108,8 @@ export class BuiltinContextCreation implements Step { async execute(ctx: PipelineContext): Promise { // Always wrap in a child context for this module call. // If no parent context was provided, create a fresh root first. + const invocation = policyInvocationOf(ctx); + if (invocation) assertPolicyBinding(ctx, invocation); let derived: Context; if (ctx.context == null) { // Issue #66: no executor arg; auto-binding happens on the next @@ -141,6 +149,13 @@ export class BuiltinContextCreation implements Step { } ctx.context = derived; + if (invocation) { + invocation.context = derived; + invocation.callerId = derived.callerId; + invocation.identity = derived.identity; + invocation.principalId = derived.identity?.id; + invocation.principalType = derived.identity?.type; + } ctx.onContextReady?.(derived); return { action: 'continue' }; } @@ -227,9 +242,11 @@ export class BuiltinModuleLookup implements Step { } async execute(ctx: PipelineContext): Promise { + const invocation = policyInvocationOf(ctx); + if (invocation) assertPolicyBinding(ctx, invocation); if (this._registry.isClosed) throw new ModuleNotFoundError(ctx.moduleId); const mod = this._registry.get(ctx.moduleId, ctx.versionHint); - if (mod === null || (!ctx.dryRun && this._registry.isDraining(ctx.moduleId))) { + if (mod === null || (!(invocation?.preflight ?? ctx.dryRun) && this._registry.isDraining(ctx.moduleId))) { throw new ModuleNotFoundError(ctx.moduleId); } @@ -250,6 +267,14 @@ export class BuiltinModuleLookup implements Step { // reached `getDefinition()` and the manifest while the module executed // UNGATED. ctx.declaredAnnotations = this._registry.getDeclaredAnnotations(ctx.moduleId); + if (invocation) { + const version = this._registry.getModuleMetadata(moduleId)['version']; + invocation.selected = { + module: mod, + version: typeof version === 'string' ? version : null, + governance: governanceUnion((mod as Record)['annotations'], ctx.declaredAnnotations), + }; + } // PROTOCOL_SPEC §6.1.8: the governance projection is computed HERE, during // module lookup, so it is available to the ACL check at Step 4. The @@ -293,6 +318,7 @@ export class BuiltinACLCheck implements Step { // "computed at Step 3, available at Step 4" is enforced by the strategy's // dependency check rather than left to step ordering holding by habit. readonly requires = ['context', 'module', 'governanceProjection'] as const; + readonly provides = ['policy_acl_checked'] as const; readonly pure = true; /** A governance gate: `configure` cannot weaken it (PROTOCOL_SPEC 5.16.1, D-130). */ readonly [GOVERNANCE_GATE]: GovernanceGateMarker = { pureIsDefault: true }; @@ -331,7 +357,10 @@ export class BuiltinACLCheck implements Step { } async execute(ctx: PipelineContext): Promise { + const invocation = policyInvocationOf(ctx); + if (invocation) assertPolicyBinding(ctx, invocation); if (this._acl === null) { + if (invocation) invocation.aclApprovalRequired = false; return { action: 'continue' }; } const callerId = ctx.context.callerId; @@ -351,6 +380,7 @@ export class BuiltinACLCheck implements Step { this._emitDenied(callerId, ctx.moduleId, ctx.context, ctx.dryRun === true); throw new ACLDeniedError(callerId, ctx.moduleId); } + if (invocation) invocation.aclApprovalRequired = decision.approvalRequired; return { action: 'continue' }; } @@ -495,7 +525,9 @@ export class BuiltinApprovalGate implements Step { async execute(ctx: PipelineContext): Promise { const mod = ctx.module as Record | null; - const approvalToken = takeApprovalToken(ctx); + const invocation = policyInvocationOf(ctx); + const approvalToken = invocation ? null : takeApprovalToken(ctx); + if (invocation) assertPolicyBinding(ctx, invocation); // §6.9 row 4 — the ACL is a CALLER-scoped authorization layer and an // `ExecutionPolicy` is a MODULE-scoped platform override, so a policy may @@ -504,7 +536,7 @@ export class BuiltinApprovalGate implements Step { // escalation: a policy rule written for `orders.*` would silently strip a // requirement an ACL author attached to one untrusted caller. Union is the // only safe composition, so this term is OR-ed with the policy's resolution. - const aclApprovalRequired = ctx.aclApprovalRequired === true; + const aclApprovalRequired = (invocation ? invocation.aclApprovalRequired : ctx.aclApprovalRequired) === true; // PROTOCOL_SPEC §7.4 (D-96): governance is the UNION of the live module // instance and the registry's declared annotations. Reading the instance @@ -514,7 +546,8 @@ export class BuiltinApprovalGate implements Step { // worse: it carries YAML > code precedence, so a metadata `false` would // cancel a module that asks to be gated. Both single-source readings are // fail-OPEN. - const governance = governanceUnion(mod?.['annotations'], ctx.declaredAnnotations); + const governance = invocation?.selected ? invocation.selected.governance + : governanceUnion(mod?.['annotations'], ctx.declaredAnnotations); // §7.9.6: policy resolution receives arguments before schema validation. // The executor isolates the credential before the pipeline starts. @@ -526,7 +559,17 @@ export class BuiltinApprovalGate implements Step { this._emitPolicyAudit(decision, ctx.context); } - if (!decision.needsApproval && !aclApprovalRequired) { + const needsApproval = decision.needsApproval || aclApprovalRequired; + if (invocation && !(needsApproval && this._handler === null && this._policy.strict)) { + invocation.earlyApproval = { + needed: needsApproval, + annotations: applyDecisionToAnnotations(governance ?? DEFAULT_ANNOTATIONS, decision), + handler: this._handler, + }; + return { action: 'continue' }; + } + + if (!needsApproval) { if (decision.destructive) { this._warnOnce( `destructive_ungated:${ctx.moduleId}`, @@ -559,40 +602,109 @@ export class BuiltinApprovalGate implements Step { return { action: 'continue' }; } - let annotations = applyDecisionToAnnotations(governance ?? DEFAULT_ANNOTATIONS, decision); - if (!annotations.requiresApproval) annotations = Object.freeze({ ...annotations, requiresApproval: true }); + const annotations = applyDecisionToAnnotations(governance ?? DEFAULT_ANNOTATIONS, decision); + const request = this._request(ctx, annotations, structuredClone(ctx.inputs)); + await this._authorize(this._handler, approvalToken, request); + return { action: 'continue' }; + } + + /** Authorize the detached and validated scope, using the handler selected in Step 5. */ + async authorizeFinal(ctx: PipelineContext, needsApproval: boolean): Promise { + const invocation = policyInvocationOf(ctx); + const early = invocation?.earlyApproval; + const snapshot = invocation?.validated; + if (!invocation || !early || !snapshot) throw new PolicyEvaluationError(ctx.moduleId); + const token = takeApprovalToken(ctx); + if (!needsApproval && token === null) return; + if (early.handler === null) { + throw new ApprovalDeniedError(createApprovalResult({ + status: 'rejected', reason: 'Final approval requires an ApprovalHandler', + }), ctx.moduleId); + } + const digest = await policyArgumentsDigest(ctx.moduleId, snapshot); + assertPolicyBinding(ctx, invocation); + ctx.context.cancelToken?.check(); + const request = this._request(ctx, early.annotations, structuredClone(snapshot.arguments), { + moduleVersion: invocation.selected?.version ?? null, + canonicalArgsDigest: digest, + }); + await this._authorize(early.handler, token, request, ctx.context); + assertPolicyBinding(ctx, invocation); + } - const request = createApprovalRequest({ + private _request( + ctx: PipelineContext, + annotations: ModuleAnnotations, + args: Record, + scope?: { moduleVersion: string | null; canonicalArgsDigest: string }, + ): ApprovalRequest { + const mod = ctx.module as Record | null; + return createApprovalRequest({ moduleId: ctx.moduleId, callerId: ctx.context.callerId, action: ctx.moduleId, - arguments: structuredClone(ctx.inputs), - context: ctx.context, - annotations, + arguments: args, + context: scope === undefined ? ctx.context : policyApprovalContext(ctx.context), + annotations: annotations.requiresApproval ? annotations : Object.freeze({ ...annotations, requiresApproval: true }), description: (mod?.['description'] as string) ?? null, tags: (mod?.['tags'] as string[]) ?? [], + ...scope, }); - const result = approvalToken === null - ? await this._handler.requestApproval(request) - : await this._handler.checkApprovalForCall?.(approvalToken, request) - ?? createApprovalResult({ status: 'rejected', reason: 'The approval handler does not support scoped resumption' }); + } - this._emitAudit(result, ctx.moduleId, ctx.context, approvalToken); + private async _authorize( + handler: ApprovalHandler, token: string | null, request: ApprovalRequest, auditContext = request.context, + ): Promise { + const final = request.canonicalArgsDigest !== undefined; + let result: ApprovalResult; + try { + const supportsFinalScope = final && handler.supportsFinalScope === true; + result = await this._requestApproval(handler, token, request, !final || supportsFinalScope); + if (final) result = this._safeFinalResult(result, supportsFinalScope); + } catch (error) { + if (!final) throw error; + result = createApprovalResult({ status: 'rejected' }); + } + if (final) auditContext.cancelToken?.check(); + this._emitAudit(result, request.moduleId, auditContext, token); if (result.status === 'approved') { - return { action: 'continue' }; + return; } if (result.status === 'timeout') { - throw new ApprovalTimeoutError(result, ctx.moduleId); + throw new ApprovalTimeoutError(result, request.moduleId); } if (result.status === 'pending') { - throw new ApprovalPendingError(result, ctx.moduleId); + throw new ApprovalPendingError(result, request.moduleId); } // rejected or unknown - throw new ApprovalDeniedError(result, ctx.moduleId); + throw new ApprovalDeniedError(result, request.moduleId); + } + + private async _requestApproval( + handler: ApprovalHandler, token: string | null, request: ApprovalRequest, resumeAllowed: boolean, + ): Promise { + if (token === null) return await handler.requestApproval(request); + if (resumeAllowed) { + const result = await handler.checkApprovalForCall?.(token, request); + if (result) return result; + } + return createApprovalResult({ status: 'rejected', reason: 'The approval handler does not support scoped resumption' }); + } + + private _safeFinalResult(result: ApprovalResult, supportsFinalScope: boolean): ApprovalResult { + const status = result?.status; + const id = result?.approvalId; + const auditId = result?.auditId; + const pending = status === 'pending' && supportsFinalScope && typeof id === 'string' && id.length > 0; + return createApprovalResult({ + status: pending ? 'pending' : status === 'approved' || status === 'timeout' ? status : 'rejected', + approvalId: pending ? id : null, + auditId: typeof auditId === 'string' && auditId !== id ? auditId : null, + }); } /** Warn once per dedup key (module/kind pair). */ @@ -694,25 +806,69 @@ export class BuiltinInputValidation implements Step { readonly provides = ['validated_inputs'] as const; async execute(ctx: PipelineContext): Promise { + const invocation = policyInvocationOf(ctx); + if (invocation) assertPolicyBinding(ctx, invocation); + let snapshot = invocation ? copyPolicyInputs(ctx.moduleId, ctx.inputs) : null; const mod = ctx.module as Record; const inputSchema = resolveSchema(mod, 'inputSchema'); - if (inputSchema == null) { - // Refresh the capture after middleware_before, as the schema branch - // does, with the configured rules (PROTOCOL_SPEC 10.6.1). - ctx.context.redactedInputs = redactSensitive(ctx.inputs, {}, this._redaction); - ctx.validatedInputs = ctx.inputs; - return { action: 'continue' }; + if (inputSchema !== null) { + validateSchema(inputSchema, snapshot?.arguments ?? ctx.inputs, 'Input'); + // Native TypeBox validators can change the inputs and retain aliases. + // Capture both the values and their encoding from the detached result. + if (snapshot) snapshot = copyPolicyInputs(ctx.moduleId, snapshot.arguments); } - // Throws SchemaValidationError directly for error type preservation - validateSchema(inputSchema, ctx.inputs, 'Input'); + const effectiveSchema = inputSchema ?? {}; + const effectiveInputs = snapshot?.arguments ?? ctx.inputs; + ctx.context.redactedInputs = redactSensitive(effectiveInputs, effectiveSchema, this._redaction); + ctx.validatedInputs = snapshot ? structuredClone(effectiveInputs) : effectiveInputs; + if (invocation && snapshot) { + snapshot.sensitiveFields = sensitivePolicyFields(effectiveInputs, effectiveSchema); + invocation.validated = snapshot; + } + return { action: 'continue' }; + } +} - ctx.context.redactedInputs = redactSensitive( - ctx.inputs, - inputSchema as unknown as Record, - this._redaction, - ); - ctx.validatedInputs = ctx.inputs; +/** Evaluate and approve the inputs owned by the invocation before dispatch. */ +class BuiltinPostValidationPolicy implements Step { + readonly name = 'post_validation_policy'; + readonly description = 'Evaluate policy and approve the validated invocation'; + readonly removable = false; + readonly replaceable = false; + readonly pure = true; + readonly requires = ['validated_inputs', 'policy_acl_checked'] as const; + readonly [GOVERNANCE_GATE]: GovernanceGateMarker = { pureIsDefault: true }; + + constructor( + private readonly evaluator: PolicyEvaluator, + private readonly approvalGate: BuiltinApprovalGate, + private readonly emitter: EventEmitter | null, + ) {} + + async execute(ctx: PipelineContext): Promise { + const invocation = policyInvocationOf(ctx); + if (!invocation?.validated || invocation.aclApprovalRequired === undefined || + (!invocation.preflight && !invocation.earlyApproval)) { + throw new PolicyEvaluationError(ctx.moduleId); + } + assertPolicyBinding(ctx, invocation); + const verdict = await evaluatePolicy(this.evaluator, ctx, invocation, invocation.validated); + assertPolicyBinding(ctx, invocation); + if (!invocation.preflight && this.emitter) { + this.emitter.emit(createEvent('apcore.policy.decision', ctx.moduleId, verdict.decision === 'deny' ? 'warn' : 'info', { + decision: verdict.decision, + ...(verdict.ruleId === undefined ? {} : { rule_id: verdict.ruleId }), + sensitive_fields: [...invocation.validated.sensitiveFields], + })); + } + if (verdict.decision === 'deny') throw new PolicyDeniedError(ctx.moduleId); + + invocation.requiresApproval = invocation.earlyApproval?.needed === true || verdict.decision === 'require_approval'; + if (!invocation.preflight) { + await this.approvalGate.authorizeFinal(ctx, invocation.requiresApproval); + } + invocation.approvedForDispatch = true; return { action: 'continue' }; } } @@ -780,7 +936,16 @@ export class BuiltinExecute implements Step { constructor(private readonly _config: Config | null) {} async execute(ctx: PipelineContext): Promise { + const invocation = policyInvocationOf(ctx); + let inputs = ctx.inputs; + if (invocation) { + assertPolicyBinding(ctx, invocation); + if (!invocation.approvedForDispatch || !invocation.validated) throw new PolicyEvaluationError(ctx.moduleId); + ctx.inputs = structuredClone(invocation.validated.arguments); + inputs = invocation.validated.arguments; + } const mod = ctx.module as Record; + const context = ctx.context; // Cancel check before execution — throw directly for error type preservation if (ctx.context.cancelToken !== null) { @@ -789,10 +954,20 @@ export class BuiltinExecute implements Step { // The stream executor pauses the pipeline once the producer is available. // Its next configured step runs after the chunks have been accumulated. - if (ctx.stream) { + if (invocation?.stream ?? ctx.stream) { const candidate = ctx.module as Module; if (isStreamingModule(candidate)) { - ctx.outputStream = this._streamWithLease(ctx, () => candidate.stream(ctx.inputs, ctx.context)); + if (invocation) { + const protectedProducer = this._streamWithLease(ctx, () => { + assertPolicyBinding(ctx, invocation); + invocation.dispatched = true; + return candidate.stream(inputs, context); + }); + invocation.producer = protectedProducer; + ctx.outputStream = protectedProducer; + } else { + ctx.outputStream = this._streamWithLease(ctx, () => candidate.stream(ctx.inputs, ctx.context)); + } return { action: 'continue' }; } // fallback: execute normally and wrap as single-chunk @@ -834,13 +1009,14 @@ export class BuiltinExecute implements Step { const release = moduleExecutionLeases.get(ctx)?.(); let executionPromise: Promise>; try { + if (invocation) invocation.dispatched = true; executionPromise = Promise.resolve( ( executeFn as ( inputs: Record, context: Context, ) => Promise> | Record - ).call(mod, ctx.inputs, ctx.context), + ).call(mod, inputs, ctx.context), ); } catch (error) { release?.(); @@ -1140,6 +1316,35 @@ export function buildPerformanceStrategy(deps: StandardStrategyDeps): ExecutionS ]); } +/** Attach the final gate only to a strategy with enforceable built-in boundaries. */ +export function withPostValidationPolicy( + strategy: ExecutionStrategy, + evaluator: PolicyEvaluator, + emitter: EventEmitter | null, +): ExecutionStrategy { + const withMiddleware = strategy.steps.length === 11; + const expected = [ + BuiltinContextCreation, BuiltinCallChainGuard, BuiltinModuleLookup, BuiltinACLCheck, BuiltinApprovalGate, + ...(withMiddleware ? [BuiltinMiddlewareBefore] : []), BuiltinInputValidation, + BuiltinExecute, BuiltinOutputValidation, ...(withMiddleware ? [BuiltinMiddlewareAfter] : []), BuiltinReturnResult, + ]; + const pureSteps: ReadonlySet = new Set([ + BuiltinContextCreation, BuiltinCallChainGuard, BuiltinModuleLookup, BuiltinACLCheck, BuiltinInputValidation, + BuiltinOutputValidation, BuiltinReturnResult, + ]); + if (strategy.steps.length !== expected.length || strategy.steps.some((step, index) => { + const expectedType = expected[index]; + return Object.getPrototypeOf(step) !== expectedType.prototype || step.execute !== expectedType.prototype.execute || + step.matchModules != null || step.ignoreErrors === true || Boolean(step.pure) !== pureSteps.has(expectedType); + })) { + throw new ConfigurationError('A policy evaluator requires the built-in standard or performance pipeline boundaries.'); + } + const approvedStrategy = strategy.mapSteps(step => step); + const approvalGate = approvedStrategy.steps[4] as BuiltinApprovalGate; + approvedStrategy.insertAfter('input_validation', new BuiltinPostValidationPolicy(evaluator, approvalGate, emitter)); + return approvedStrategy; +} + /** * Build a minimal strategy: context → lookup → execute → return only. * No safety checks, no ACL, no approval, no validation, no middleware. diff --git a/typescript/src/core.ts b/typescript/src/core.ts index e6cac8a2..d9ff4c69 100644 --- a/typescript/src/core.ts +++ b/typescript/src/core.ts @@ -3,6 +3,7 @@ export { SchemaExporter } from './schema/exporter.js'; export { redactSensitive } from './executor.js'; export { ExecutionPolicy, PolicyRule } from './policy.js'; export type { PolicyCallSite, PolicyDecision, PolicyRuleOverrides } from './policy.js'; +export type { PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict } from './policy-evaluation.js'; export { STREAMING_MARKER, isStreamingModule } from './streaming.js'; export type { StreamingModule } from './streaming.js'; export type { RegistryOptions } from './registry/registry.js'; diff --git a/typescript/src/errors.ts b/typescript/src/errors.ts index 407cb156..abf45a3c 100644 --- a/typescript/src/errors.ts +++ b/typescript/src/errors.ts @@ -1037,6 +1037,26 @@ export class ApprovalPendingError extends ApprovalError { } } +export class PolicyDeniedError extends ModuleError { + static override readonly DEFAULT_RETRYABLE = false; + + constructor(moduleId: string) { + super(ErrorCodes.POLICY_DENIED, 'The invocation was denied by policy.', { moduleId }, + undefined, undefined, undefined, 'Adjust the inputs to meet the applicable policy.', true); + this.name = 'PolicyDeniedError'; + } +} + +export class PolicyEvaluationError extends ModuleError { + static override readonly DEFAULT_RETRYABLE = true; + + constructor(moduleId: string) { + super(ErrorCodes.POLICY_EVALUATION_ERROR, 'The invocation policy could not be evaluated.', { moduleId }, + undefined, undefined, undefined, undefined, false); + this.name = 'PolicyEvaluationError'; + } +} + export class ConfigNamespaceDuplicateError extends ModuleError { static override readonly DEFAULT_RETRYABLE: boolean | null = false; @@ -1588,6 +1608,8 @@ export const ErrorCodes = Object.freeze({ APPROVAL_DENIED: 'APPROVAL_DENIED', APPROVAL_TIMEOUT: 'APPROVAL_TIMEOUT', APPROVAL_PENDING: 'APPROVAL_PENDING', + POLICY_DENIED: 'POLICY_DENIED', + POLICY_EVALUATION_ERROR: 'POLICY_EVALUATION_ERROR', VERSION_INCOMPATIBLE: 'VERSION_INCOMPATIBLE', ERROR_CODE_COLLISION: 'ERROR_CODE_COLLISION', GENERAL_NOT_IMPLEMENTED: 'GENERAL_NOT_IMPLEMENTED', diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index 0e40d74e..a776ec3c 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -13,6 +13,9 @@ import { } from './utils/redaction-references.js'; import { type ApprovalHandler, discardApprovalToken, prepareApprovalInputs, stripApprovalToken } from './approval.js'; import { DEFAULT_EXECUTION_POLICY, type ExecutionPolicy } from './policy.js'; +import { + assertPolicyBinding, beginPolicyInvocation, endPolicyInvocation, policyIngressInputs, policyInvocationOf, type PolicyEvaluator, +} from './policy-evaluation.js'; import { BuiltinACLCheck, BuiltinApprovalGate, @@ -22,6 +25,7 @@ import { buildPerformanceStrategy, buildStandardStrategy, buildTestingStrategy, + withPostValidationPolicy, } from './builtin-steps.js'; import type { StandardStrategyDeps } from './builtin-steps.js'; import { awaitExecution, CancelToken, ExecutionCancelledError } from './cancel.js'; @@ -42,6 +46,7 @@ import { InvalidInputError, ModuleError, ModuleTimeoutError, + PolicyEvaluationError, } from './errors.js'; import { AfterMiddleware, @@ -255,28 +260,50 @@ function isPlainObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } +type SensitivePath = { fields: Set; pointer: string }; + +function childSensitivePath(path: SensitivePath | undefined, key: string): SensitivePath | undefined { + if (path === undefined) return undefined; + return { fields: path.fields, pointer: `${path.pointer}/${key.replace(/~/g, '~0').replace(/\//g, '~1')}` }; +} + +/** @internal Find the schema's sensitive instance paths without modifying execution inputs. */ +export function sensitivePolicyFields(data: Record, inputSchema: Record): string[] { + const schema = sourceSchemaFor(inputSchema); + const refs = createRedactionReferenceContext(schema); + const fields = new Set(); + redactBySchema(data, schema, refs, { fields, pointer: '' }); + return [...fields].sort(); +} + /** Redact `value` as described by `schema`; returns the value to store. */ function redactBySchema( value: unknown, schema: Record, context: RedactionReferenceContext, + sensitivePath?: SensitivePath, ): unknown { - if (value === null || value === undefined) return value; + if ((value === null || value === undefined) && sensitivePath === undefined) return value; const variants = schemaVariants(schema, context); - if (variants.some((v) => v['x-sensitive'] === true)) return REDACTED_VALUE; + if (variants.some((v) => v['x-sensitive'] === true)) { + sensitivePath?.fields.add(sensitivePath.pointer); + return REDACTED_VALUE; + } if (Array.isArray(value)) { - for (const variant of variants) redactArrayBySchema(value, variant, context); + for (const variant of variants) redactArrayBySchema(value, variant, context, sensitivePath); return value; } if (isPlainObject(value)) { - redactFields(value, schema, context); + redactFields(value, schema, context, sensitivePath); } return value; } -function redactArrayBySchema(value: unknown[], schema: Record, context: RedactionReferenceContext): void { +function redactArrayBySchema( + value: unknown[], schema: Record, context: RedactionReferenceContext, path?: SensitivePath, +): void { const dialect = context.dialects.get(schema) ?? context.rootSchema['$schema']; const legacyTuple = typeof dialect === 'string' && (dialect.includes('/draft-07/') || dialect.includes('/2019-09/')); const tuple = legacyTuple && Array.isArray(schema['items']) ? schema['items'] : undefined; @@ -284,7 +311,10 @@ function redactArrayBySchema(value: unknown[], schema: Record, for (let index = 0; index < value.length; index++) { const itemSchema = prefix ? prefix[index] ?? schema['items'] : tuple ? tuple[index] ?? schema['additionalItems'] : schema['items']; - if (isPlainObject(itemSchema)) value[index] = redactBySchema(value[index], itemSchema, context); + if (isPlainObject(itemSchema)) { + const redacted = redactBySchema(value[index], itemSchema, context, childSensitivePath(path, String(index))); + if (path === undefined) value[index] = redacted; + } } } @@ -292,13 +322,15 @@ function redactFields( data: Record, schemaDict: Record, context: RedactionReferenceContext, + path?: SensitivePath, ): void { for (const variant of schemaVariants(schemaDict, context)) { const properties = variant['properties']; if (!isPlainObject(properties)) continue; for (const [fieldName, fieldSchema] of Object.entries(properties)) { - if (!(fieldName in data) || !isPlainObject(fieldSchema)) continue; - data[fieldName] = redactBySchema(data[fieldName], fieldSchema, context); + if (!(path === undefined ? fieldName in data : Object.hasOwn(data, fieldName)) || !isPlainObject(fieldSchema)) continue; + const redacted = redactBySchema(data[fieldName], fieldSchema, context, childSensitivePath(path, fieldName)); + if (path === undefined) data[fieldName] = redacted; } } } @@ -507,6 +539,7 @@ export class Executor { private _config: Config | null; private _approvalHandler: ApprovalHandler | null; private _policy: ExecutionPolicy | null; + private _policyEvaluator: PolicyEvaluator | null = null; private readonly _toggleState: ToggleState; private _eventEmitter: EventEmitter | null; private _eventEmitterConfigured: boolean; @@ -524,6 +557,7 @@ export class Executor { config?: Config | null; approvalHandler?: ApprovalHandler | null; policy?: ExecutionPolicy | null; + policyEvaluator?: PolicyEvaluator | null; toggleState?: ToggleState | null; eventEmitter?: EventEmitter | null; }) { @@ -606,6 +640,7 @@ export class Executor { // deny-all ACL given here let every call through while governanceState() // reported the gate as configured and wired. this._strategy = this._bindProviders(this._strategy); + this.setPolicyEvaluator(options.policyEvaluator ?? null); this._pipelineEngine = new PipelineEngine(); } @@ -688,7 +723,7 @@ export class Executor { const result: StrategyInfo[] = []; // Current strategy first. - const current = this._strategy.info(); + const current = this.describePipeline(); result.push(current); seen.add(current.name); @@ -719,7 +754,7 @@ export class Executor { /** Describe the pipeline of the executor's current strategy. */ describePipeline(): StrategyInfo { - return this._strategy.info(); + return this._strategyForInvocation().info(); } /** Get the current execution strategy. */ @@ -936,6 +971,20 @@ export class Executor { } } + /** Install an evaluator for final validated inputs on this executor. */ + setPolicyEvaluator(evaluator: PolicyEvaluator | null): void { + if (evaluator !== null) { + if (typeof evaluator.evaluate !== 'function') throw new TypeError('A policy evaluator must provide an evaluate method'); + withPostValidationPolicy(this._strategy, evaluator, this._eventEmitter); + } + this._policyEvaluator = evaluator; + } + + private _strategyForInvocation(strategy = this._strategy): ExecutionStrategy { + if (strategy !== this._strategy) strategy = this._bindProviders(strategy); + return this._policyEvaluator === null ? strategy : withPostValidationPolicy(strategy, this._policyEvaluator, this._eventEmitter); + } + use(middleware: Middleware): Executor { this._middlewareManager.add(middleware); return this; @@ -1010,7 +1059,8 @@ export class Executor { ): Promise<[Record, PipelineTrace]> { this._validateModuleId(moduleId); // Per-call strategies use the providers owned by this executor (D-129). - if (strategy !== this._strategy) strategy = this._bindProviders(strategy); + const protectedCall = this._policyEvaluator !== null; + strategy = this._strategyForInvocation(strategy); // Issue #66: auto-bind executor to context on every entry. withExecutor // is idempotent for the same instance and raises ContextBindingError on @@ -1039,8 +1089,13 @@ export class Executor { try { while (true) { try { + if (protectedCall) { + beginPolicyInvocation(pipeCtx); + pipeCtx.inputs = policyIngressInputs(pipeCtx.inputs, moduleId); + } prepareApprovalInputs(pipeCtx); const [output, trace] = await this._pipelineEngine.run(strategy, pipeCtx); + if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw new PolicyEvaluationError(moduleId); return [(output ?? {}) as Record, trace]; } catch (exc) { if (exc instanceof ExecutionCancelledError) throw exc; @@ -1059,6 +1114,7 @@ export class Executor { unwrapped instanceof MiddlewareChainError ? unwrapped.original : (unwrapped as Error); if (underlying instanceof ExecutionCancelledError) throw underlying; const wrapped = propagateError(underlying, moduleId, ctxObj); + if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; const executedMw = pipeCtx.executedMiddlewares; if (executedMw && executedMw.length > 0) { const recovery = await this._middlewareManager.executeOnError( @@ -1081,6 +1137,7 @@ export class Executor { } } finally { discardApprovalToken(pipeCtx); + if (protectedCall) endPolicyInvocation(pipeCtx); this._finishCallContext(pipeCtx.context, ctx); } } @@ -1180,8 +1237,9 @@ export class Executor { ): StreamExecution { const parent = context ?? Context.create(); const token = new CancelToken(parent.cancelToken); - const tracker = new StreamCompletionTracker(this._strategy.steps.map((step) => step.name)); - const chunks = this._stream(moduleId, inputs, parent._withCancellationScope(token), versionHint, tracker); + const strategy = this._strategyForInvocation(); + const tracker = new StreamCompletionTracker(strategy.steps.map((step) => step.name)); + const chunks = this._stream(moduleId, inputs, parent._withCancellationScope(token), versionHint, tracker, strategy); return createStreamExecution(chunks, token, moduleId, tracker, parent.globalDeadline); } @@ -1191,8 +1249,10 @@ export class Executor { context?: Context | null, versionHint?: string | null, tracker?: StreamCompletionTracker, + strategy = this._strategyForInvocation(), ): AsyncGenerator> { this._validateModuleId(moduleId); + const protectedCall = strategy !== this._strategy && strategy.findStepIndex('post_validation_policy') !== undefined; // Issue #66: auto-bind executor (see call() for rationale). let ctx = context ?? Context.create(); @@ -1207,7 +1267,7 @@ export class Executor { validatedOutput: null, stream: true, outputStream: null, - strategy: this._strategy, + strategy, trace: null, versionHint: versionHint ?? null, ...(tracker && { onContextReady: (context: Context) => tracker.armDeadline?.(context.globalDeadline) }), @@ -1229,14 +1289,20 @@ export class Executor { } }; const pipeline = this._pipelineEngine.runWithPause( - this._strategy, pipeCtx, () => pipeCtx.outputStream != null, observeStep, + strategy, pipeCtx, () => (protectedCall ? policyInvocationOf(pipeCtx)?.producer : pipeCtx.outputStream) != null, observeStep, ); try { // Run through producer creation, or finish the unary fallback. try { + if (protectedCall) { + beginPolicyInvocation(pipeCtx); + pipeCtx.inputs = policyIngressInputs(pipeCtx.inputs, moduleId); + } prepareApprovalInputs(pipeCtx); await pipeline.next(); + const invocation = policyInvocationOf(pipeCtx); + if (protectedCall && !invocation?.dispatched && !invocation?.producer) throw new PolicyEvaluationError(moduleId); } catch (exc) { if (exc instanceof ExecutionCancelledError) throw exc; const ctxObj = pipeCtx.context; @@ -1250,6 +1316,7 @@ export class Executor { unwrapped instanceof MiddlewareChainError ? unwrapped.original : (unwrapped as Error); if (underlying instanceof ExecutionCancelledError) throw underlying; const wrapped = propagateError(underlying, moduleId, ctxObj); + if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; if (pipeCtx.executedMiddlewares && pipeCtx.executedMiddlewares.length > 0) { const recovery = await this._middlewareManager.executeOnError( moduleId, @@ -1275,7 +1342,9 @@ export class Executor { // If no outputStream, pipeline already executed normally — yield single result if (tracker) pipeCtx.context.cancelToken?.check(); - if (pipeCtx.outputStream == null) { + const outputStream = protectedCall ? policyInvocationOf(pipeCtx)?.producer + : pipeCtx.outputStream as AsyncGenerator> | null; + if (outputStream == null) { const output = pipeCtx.output ?? {}; if (tracker && tracker.output === null) tracker.output = copyChunkValue(output) as Record; yield output; @@ -1283,7 +1352,6 @@ export class Executor { } // Phase 2: Iterate stream, accumulate chunks - const outputStream = pipeCtx.outputStream as AsyncGenerator>; const accumulated: Record = {}; // PROTOCOL_SPEC §5: resolved ONCE per stream, not per chunk. A // configuration mutated mid-stream — `system.control.update_config` can do @@ -1325,6 +1393,7 @@ export class Executor { if (exc instanceof ExecutionCancelledError) throw exc; const ctxObj = pipeCtx.context; const wrapped = propagateError(exc as Error, moduleId, ctxObj); + if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; if (exc instanceof ModuleTimeoutError && ctxObj.signal.aborted) throw wrapped; if (pipeCtx.executedMiddlewares && pipeCtx.executedMiddlewares.length > 0) { const recovery = await this._middlewareManager.executeOnError( @@ -1414,6 +1483,7 @@ export class Executor { } } finally { discardApprovalToken(pipeCtx); + if (protectedCall) endPolicyInvocation(pipeCtx); this._finishCallContext(pipeCtx.context, ctx); } } @@ -1430,7 +1500,6 @@ export class Executor { inputs?: Record | null, context?: Context | null, ): Promise { - const effectiveInputs = stripApprovalToken(inputs ?? {}); const checks: PreflightCheckResult[] = []; // Check 0: module_id format (before pipeline) @@ -1446,6 +1515,18 @@ export class Executor { return createPreflightResult(checks); } + const protectedCall = this._policyEvaluator !== null; + let strategy: ExecutionStrategy; + let effectiveInputs: Record; + try { + strategy = this._strategyForInvocation(); + effectiveInputs = stripApprovalToken(protectedCall ? policyIngressInputs(inputs ?? {}, moduleId) : inputs ?? {}); + } catch (error) { + if (!(error instanceof ModuleError)) throw error; + checks.push({ check: 'post_validation_policy', passed: false, error: error.toJSON() }); + return createPreflightResult(checks); + } + // Run pipeline in dry_run mode — pure=false steps are skipped. // Issue #66: auto-bind executor on every entry (see call() for rationale). // A-D-014: validate() MUST be non-throwing. A Context already bound to a @@ -1476,15 +1557,16 @@ export class Executor { validatedOutput: null, stream: false, outputStream: null, - strategy: this._strategy, + strategy, trace: null, dryRun: true, }; + if (protectedCall) beginPolicyInvocation(pipeCtx); try { let trace: PipelineTrace | null = null; try { - const [, t] = await this._pipelineEngine.run(this._strategy, pipeCtx); + const [, t] = await this._pipelineEngine.run(strategy, pipeCtx); trace = t; } catch (e) { // Step raised a domain error (ModuleNotFoundError, ACLDeniedError, etc.) @@ -1540,7 +1622,7 @@ export class Executor { // reading the union, would stop the call the preflight waved through. // That disagreement is the one thing this method exists to prevent. const governance = governanceUnion(mod['annotations'], pipeCtx.declaredAnnotations); - const gate = this._strategy.steps.find((step) => step instanceof BuiltinApprovalGate); + const gate = strategy.steps.find((step) => step instanceof BuiltinApprovalGate); const policy = gate?.policy ?? this._policy ?? DEFAULT_EXECUTION_POLICY; // §7.9.6: preflight resolves the same policy against the same call site. requiresApproval = policy.resolve(moduleId, governance, { @@ -1555,7 +1637,7 @@ export class Executor { // in the dry-run pipeline above (it is `pure`), so its verdict is already // on `pipeCtx` — and §6.9 row 4 forbids a policy from clearing it, which is // why this is OR-ed on top rather than folded into the branch above. - if (pipeCtx.aclApprovalRequired === true) { + if (pipeCtx.aclApprovalRequired === true || policyInvocationOf(pipeCtx)?.requiresApproval === true) { requiresApproval = true; } @@ -1571,38 +1653,56 @@ export class Executor { // on lookup alone runs module code for a caller the ACL just denied and // hands back what it said. // - // Scoped to authorization deliberately: a failed `schema` check does NOT - // suppress introspection, because a caller the ACL permits is entitled to - // the module's account of what would happen even when its inputs are - // malformed. - const aclEnforced = this._strategy.steps.some((step) => step instanceof BuiltinACLCheck && step.acl !== null); + // Without an evaluator, the ACL can permit introspection even for + // malformed inputs. The opted-in path requires policy approval of a + // successfully validated snapshot before any module callback runs. + const aclEnforced = strategy.steps.some((step) => step instanceof BuiltinACLCheck && step.acl !== null); const aclDenied = (aclEnforced && pipeCtx.aclAllowed !== true) || checks.some((c) => c.check === Executor.ACL_CHECK && !c.passed); + const invocation = policyInvocationOf(pipeCtx); + let discloseModule = !aclDenied && (!protectedCall || invocation?.approvedForDispatch === true); + const module = (invocation ? invocation.selected?.module : pipeCtx.module) as Module | null | undefined; + const callbackContext = invocation?.context ?? pipeCtx.context; + const callbackInputs = (): Record => invocation?.validated + ? structuredClone(invocation.validated.arguments) : effectiveInputs; + // Each callback can await or mutate its context. Recheck the binding + // before invocation and before using any result from that invocation. + const canDisclose = (): boolean => { + if (!discloseModule || !invocation) return discloseModule; + try { + assertPolicyBinding(pipeCtx, invocation); + return true; + } catch (error) { + if (!(error instanceof PolicyEvaluationError)) throw error; + checks.push({ check: 'post_validation_policy', passed: false, error: error.toJSON() }); + discloseModule = false; + return false; + } + }; // Module-level preflight (optional) - if (!aclDenied && pipeCtx.module != null) { - const mod = pipeCtx.module as Record; - const modWithPreflight = mod as { preflight?: Module['preflight'] }; - if (typeof modWithPreflight.preflight === 'function') { + if (canDisclose() && module != null) { + const preflight = module.preflight; + if (typeof preflight === 'function' && canDisclose()) { try { - const preflightWarnings = await modWithPreflight.preflight(effectiveInputs, pipeCtx.context); - if (Array.isArray(preflightWarnings) && preflightWarnings.length > 0) { + const preflightWarnings = await preflight.call(module, callbackInputs(), callbackContext); + if (canDisclose()) { checks.push({ check: Executor.MODULE_PREFLIGHT_CHECK, passed: true, - warnings: preflightWarnings, + ...(Array.isArray(preflightWarnings) && preflightWarnings.length > 0 && { warnings: preflightWarnings }), }); - } else { - checks.push({ check: Executor.MODULE_PREFLIGHT_CHECK, passed: true }); } } catch (exc: unknown) { - const excName = exc instanceof Error ? exc.constructor.name : 'Error'; - const excMsg = exc instanceof Error ? exc.message : String(exc); - checks.push({ - check: Executor.MODULE_PREFLIGHT_CHECK, - passed: true, - warnings: [`preflight() raised ${excName}: ${excMsg}`], - }); + if (canDisclose()) { + const excName = exc instanceof Error ? exc.constructor.name : 'Error'; + const excMsg = exc instanceof Error ? exc.message : String(exc); + checks.push({ + check: Executor.MODULE_PREFLIGHT_CHECK, + passed: true, + warnings: [`preflight() raised ${excName}: ${excMsg}`], + }); + } } } } @@ -1613,35 +1713,37 @@ export class Executor { // throws or async rejections) are treated as advisory warnings and do NOT // fail validation, mirroring `preflight()` semantics (RFC Open Question 1). let predictedChanges: Change[] = []; - if (!aclDenied && pipeCtx.module != null) { - const mod = pipeCtx.module as Record; - const modWithPreview = mod as { preview?: Module['preview'] }; - if (typeof modWithPreview.preview === 'function') { + if (canDisclose() && module != null) { + const preview = module.preview; + if (typeof preview === 'function' && canDisclose()) { try { - const raw = modWithPreview.preview(effectiveInputs, pipeCtx.context); + const raw = preview.call(module, callbackInputs(), callbackContext); // Support both sync and async preview() implementations. const result: PreviewResult | null = raw != null && typeof (raw as Promise).then === 'function' ? await (raw as Promise) : (raw as PreviewResult | null); - if (result != null) { + if (canDisclose() && result != null) { predictedChanges = Array.isArray(result.changes) ? result.changes : []; checks.push({ check: Executor.MODULE_PREVIEW_CHECK, passed: true }); } } catch (exc: unknown) { - const excName = exc instanceof Error ? exc.constructor.name : 'Error'; - const excMsg = exc instanceof Error ? exc.message : String(exc); - checks.push({ - check: Executor.MODULE_PREVIEW_CHECK, - passed: true, - warnings: [`preview() raised ${excName}: ${excMsg}`], - }); + if (canDisclose()) { + const excName = exc instanceof Error ? exc.constructor.name : 'Error'; + const excMsg = exc instanceof Error ? exc.message : String(exc); + checks.push({ + check: Executor.MODULE_PREVIEW_CHECK, + passed: true, + warnings: [`preview() raised ${excName}: ${excMsg}`], + }); + } } } } return createPreflightResult(checks, requiresApproval, predictedChanges); } finally { + if (protectedCall) endPolicyInvocation(pipeCtx); if (pipeCtx.context.cancelToken !== validateCtx.cancelToken) pipeCtx.context.cancelToken?.dispose(); } diff --git a/typescript/src/extensions.ts b/typescript/src/extensions.ts index d66fb830..96e785ce 100644 --- a/typescript/src/extensions.ts +++ b/typescript/src/extensions.ts @@ -14,6 +14,7 @@ import { Middleware } from './middleware/index.js'; import { TracingMiddleware } from './observability/tracing.js'; import type { Span, SpanExporter } from './observability/tracing.js'; import type { Discoverer, ModuleValidator, Registry } from './registry/registry.js'; +import type { PolicyEvaluator } from './policy-evaluation.js'; /** * Delegates span export to multiple underlying exporters. @@ -132,14 +133,22 @@ function builtInPoints(): Map { typeCheck: isApprovalHandler, typeName: 'ApprovalHandler', }], + ['policy_evaluator', { + name: 'policy_evaluator', + description: 'Asynchronous policy evaluation on validated invocation arguments', + multiple: false, + typeCheck: value => typeof value === 'object' && value !== null && + typeof (value as Partial).evaluate === 'function', + typeName: 'PolicyEvaluator', + }], ]); } /** * Manages extension points and their registered implementations. * - * Pre-registers six built-in extension points: discoverer, middleware, - * acl, span_exporter, module_validator, and approval_handler. + * Pre-registers the built-in discovery, middleware, ACL, tracing, module + * validation, approval, and policy evaluation points. */ export class ExtensionManager { private _points: Map; @@ -274,6 +283,9 @@ export class ExtensionManager { executor.setApprovalHandler(approvalHandler); } + const evaluator = this.get('policy_evaluator') as PolicyEvaluator | null; + if (evaluator !== null) executor.setPolicyEvaluator(evaluator); + // Middleware for (const mw of this.getAll('middleware')) { executor.use(mw as Middleware); diff --git a/typescript/src/node-api.ts b/typescript/src/node-api.ts index a7c16152..ce6954c0 100644 --- a/typescript/src/node-api.ts +++ b/typescript/src/node-api.ts @@ -78,6 +78,7 @@ export type { ApprovalRequest, ApprovalResult, ApprovalHandler } from './approva // Execution-time governance policy (apcore#76 RFC pilot) export { ExecutionPolicy, PolicyRule } from './policy.js'; export type { PolicyCallSite, PolicyDecision, PolicyRuleOverrides } from './policy.js'; +export type { PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict } from './policy-evaluation.js'; // Errors export { @@ -90,6 +91,8 @@ export { ApprovalDeniedError, ApprovalTimeoutError, ApprovalPendingError, + PolicyDeniedError, + PolicyEvaluationError, ModuleNotFoundError, ModuleDisabledError, ModuleTimeoutError, diff --git a/typescript/src/pipeline.ts b/typescript/src/pipeline.ts index fbb933e3..35fd1abe 100644 --- a/typescript/src/pipeline.ts +++ b/typescript/src/pipeline.ts @@ -8,6 +8,7 @@ import { ModuleError, ModuleTimeoutError } from './errors.js'; import type { ErrorOptions } from './errors.js'; import { MiddlewareChainError } from './middleware/manager.js'; import { matchPattern } from './utils/pattern.js'; +import { policyInvocationOf } from './policy-evaluation.js'; // --------------------------------------------------------------------------- // Step interface @@ -1059,6 +1060,8 @@ export class PipelineEngine { ): AsyncGenerator { const pipelineStart = performance.now(); const steps = strategy.steps; + const policyInvocation = policyInvocationOf(ctx); + const isDryRun = () => policyInvocation?.preflight ?? ctx.dryRun === true; const trace: PipelineTrace = { moduleId: ctx.moduleId, strategyName: strategy.name, @@ -1073,7 +1076,7 @@ export class PipelineEngine { let paused = false; const completedStep = (stepName: string): boolean => { stepOutputs[stepName] = ctx.output != null ? { ...ctx.output } : null; - if (!ctx.runUntil?.({ stepName, outputs: stepOutputs, context: ctx })) return false; + if (policyInvocation || !ctx.runUntil?.({ stepName, outputs: stepOutputs, context: ctx })) return false; trace.totalDurationMs = performance.now() - pipelineStart; trace.success = true; return true; @@ -1094,7 +1097,7 @@ export class PipelineEngine { if (stepMatchModules !== null) { const matched = stepMatchModules.some((pattern) => matchPattern(pattern, ctx.moduleId)); if (!matched) { - if (ctx.dryRun) { + if (isDryRun()) { for (const key of step.provides ?? []) failedProvides.add(key); } trace.steps.push({ @@ -1111,7 +1114,7 @@ export class PipelineEngine { } // 2 dry_run filter: skip steps with side effects - if (ctx.dryRun && !stepPure) { + if (isDryRun() && !stepPure) { // Capabilities are declarations, not necessarily context attributes. for (const key of step.provides ?? []) failedProvides.add(key); trace.steps.push({ @@ -1125,7 +1128,7 @@ export class PipelineEngine { idx += 1; continue; } - if (ctx.dryRun && (step.requires ?? []).some((key) => failedProvides.has(key))) { + if (isDryRun() && (step.requires ?? []).some((key) => failedProvides.has(key))) { trace.steps.push({ name: step.name, durationMs: 0, result: { action: 'continue' }, skipped: true, decisionPoint: false, skipReason: 'missing_dependency' }); for (const key of step.provides ?? []) failedProvides.add(key); @@ -1151,7 +1154,7 @@ export class PipelineEngine { // middlewares only, in reverse order. const executedStepMws: StepMiddleware[] = []; let chainError: MiddlewareChainError | null = null; - for (const mw of ctx.dryRun ? [] : this._stepMiddlewares) { + for (const mw of isDryRun() ? [] : this._stepMiddlewares) { executedStepMws.push(mw); if (!mw.beforeStep) continue; try { @@ -1233,7 +1236,7 @@ export class PipelineEngine { } catch (exc) { const durationMs = performance.now() - stepStart; const cause = exc instanceof Error ? exc : new Error(String(exc)); - if (ctx.dryRun) { + if (isDryRun()) { // D-134: report every evaluable pure check without converting a // failed check into successful recovery output. trace.steps.push({ name: step.name, durationMs, @@ -1247,7 +1250,8 @@ export class PipelineEngine { // 3 b onStepError hooks: reverse registration order (onion model), // first non-null recovery wins and short-circuits the rest (§2.2). - const isGovernanceGate = governanceGateOf(step) !== null; + const isGovernanceGate = governanceGateOf(step) !== null || + (policyInvocation !== undefined && !policyInvocation.dispatched); const observedCancellation = observeStep !== undefined && cause instanceof ModuleError && cause.code === 'EXECUTION_CANCELLED'; let recovery: unknown; @@ -1343,7 +1347,7 @@ export class PipelineEngine { skipped: false, decisionPoint: result.confidence != null, }); - if (ctx.dryRun) { + if (isDryRun()) { if (result.action === 'abort') { for (const key of step.provides ?? []) failedProvides.add(key); } else { @@ -1368,6 +1372,7 @@ export class PipelineEngine { trace, ); } else if (result.action === 'skip_to') { + if (policyInvocation) throw new ConfigurationError('A policy-enabled pipeline cannot skip steps.'); const target = result.skipTo ?? ''; // The strategy may be edited by the host while an invocation is paused. const targetIdx = steps === strategy.steps diff --git a/typescript/src/policy-evaluation.ts b/typescript/src/policy-evaluation.ts new file mode 100644 index 00000000..79423c54 --- /dev/null +++ b/typescript/src/policy-evaluation.ts @@ -0,0 +1,265 @@ +import { awaitExecution, CancelToken, ExecutionCancelledError } from './cancel.js'; +import { Context, createIdentity, type Identity } from './context.js'; +import { PolicyEvaluationError } from './errors.js'; +import type { ApprovalHandler } from './approval.js'; +import type { ModuleAnnotations } from './module.js'; +import type { PipelineContext } from './pipeline.js'; +import { sha256Hex } from './utils/sha256.js'; + +export interface PolicyEvaluationRequest { + readonly moduleId: string; + readonly moduleVersion: string | null; + readonly callerId: string | null; + readonly identity: Identity | null; + readonly arguments: Readonly>; + readonly sensitiveFields: readonly string[]; + readonly signal: AbortSignal; +} + +export interface PolicyVerdict { + readonly decision: 'allow' | 'deny' | 'require_approval'; + readonly ruleId?: string; +} + +/** A host-supplied policy on the validated inputs of an invocation. */ +export interface PolicyEvaluator { + evaluate(request: PolicyEvaluationRequest): Promise; +} + +type ValidationSnapshot = { + readonly arguments: Record; + readonly canonical: readonly string[]; + sensitiveFields: readonly string[]; +}; + +interface PolicyInvocation { + readonly id: string; + readonly preflight: boolean; + readonly stream: boolean; + readonly parent: Context; + context?: Context; + callerId?: string | null; + identity?: Identity | null; + principalId?: string; + principalType?: string; + selected?: { module: unknown; version: string | null; governance: ModuleAnnotations | null }; + aclApprovalRequired?: boolean; + earlyApproval?: { needed: boolean; annotations: ModuleAnnotations; handler: ApprovalHandler | null }; + validated?: ValidationSnapshot; + evaluating?: boolean; + approvedForDispatch?: boolean; + requiresApproval?: boolean; + dispatched?: boolean; + producer?: AsyncGenerator>; +} + +// Policy state is private to this traversal. Step hooks can inspect the +// public PipelineContext but cannot supply their own authorization proof. +const invocations = new WeakMap(); + +/** @internal */ +export function beginPolicyInvocation(ctx: PipelineContext): void { + invocations.set(ctx, { + id: ctx.moduleId, preflight: ctx.dryRun === true, stream: ctx.stream === true, parent: ctx.context, + }); +} + +/** @internal */ +export function policyInvocationOf(ctx: PipelineContext): PolicyInvocation | undefined { + return invocations.get(ctx); +} + +/** @internal Release the validated snapshot when its traversal ends. */ +export function endPolicyInvocation(ctx: PipelineContext): void { + invocations.delete(ctx); +} + +/** @internal */ +export function assertPolicyBinding(ctx: PipelineContext, invocation: PolicyInvocation): void { + const { context, selected } = invocation; + if (ctx.moduleId !== invocation.id || ctx.context !== (context ?? invocation.parent) || + (context && (context.callerId !== invocation.callerId || context.identity !== invocation.identity || + context.identity?.id !== invocation.principalId || context.identity?.type !== invocation.principalType)) || + (selected && ctx.module !== selected.module)) { + throw new PolicyEvaluationError(invocation.id); + } +} + +function ownData(descriptors: { [key: string]: PropertyDescriptor }, key: string): unknown { + const descriptor = Object.hasOwn(descriptors, key) ? descriptors[key] : undefined; + if (!descriptor?.enumerable || !Object.hasOwn(descriptor, 'value')) { + throw new Error('Policy inputs must use enumerable data properties.'); + } + return descriptor.value; +} + +function quote(value: string): string { + // In Unicode mode a surrogate pair is a single scalar, so this matches + // only surrogate code points that have no matching code unit. + if (/[\uD800-\uDFFF]/u.test(value)) throw new Error('Policy inputs must contain Unicode scalar values.'); + return JSON.stringify(value); +} + +function encodeNumber(value: number): string { + if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) { + throw new Error('Policy inputs must contain finite, lossless numbers.'); + } + if (Number.isInteger(value) && !Object.is(value, -0)) return `i${value};`; + const view = new DataView(new ArrayBuffer(8)); + view.setFloat64(0, value); + return `f${view.getBigUint64(0).toString(16).padStart(16, '0')};`; +} + +function copyArgument(value: unknown, parts: string[], active: Set): unknown { + if (typeof value === 'string') parts.push(quote(value)); + else if (typeof value === 'number') parts.push(encodeNumber(value)); + else if (value === null || typeof value === 'boolean') parts.push(String(value)); + else if (typeof value === 'object' && !active.has(value)) { + active.add(value); + try { + if (Array.isArray(value) && Object.getPrototypeOf(value) === Array.prototype) { + return copyArray(value, parts, active); + } + if (Object.getPrototypeOf(value) === Object.prototype) return copyObject(value, parts, active); + throw new Error('Policy inputs must use plain objects and arrays.'); + } finally { + active.delete(value); + } + } else throw new Error('Policy inputs must contain acyclic JSON values.'); + return value; +} + +function copyArray(value: unknown[], parts: string[], active: Set): unknown[] { + const descriptors = Object.getOwnPropertyDescriptors(value); + if (Reflect.ownKeys(descriptors).length !== value.length + 1) { + throw new Error('Policy input arrays must be dense and have no additional properties.'); + } + parts.push('['); + const copy: unknown[] = []; + for (let index = 0; index < value.length; index++) { + if (index > 0) parts.push(','); + copy.push(copyArgument(ownData(descriptors, String(index)), parts, active)); + } + parts.push(']'); + return copy; +} + +function copyObject(value: object, parts: string[], active: Set): Record { + const descriptors = Object.getOwnPropertyDescriptors(value); + const keys = Object.keys(descriptors); + if (Reflect.ownKeys(descriptors).length !== keys.length) { + throw new Error('Policy input objects must have string keys.'); + } + // Canonicalize ordering by unsigned UTF-16 as required by the wire contract. + const copies = new Map(); + parts.push('{'); + for (const key of keys.slice().sort()) { + if (copies.size > 0) parts.push(','); + parts.push(quote(key), ':'); + copies.set(key, copyArgument(ownData(descriptors, key), parts, active)); + } + parts.push('}'); + // Preserve the accepted business object's property order for execution. + return Object.fromEntries(keys.map((key) => [key, copies.get(key)])); +} + +/** @internal Detach the inputs and capture their canonical encoding. */ +export function copyPolicyInputs(moduleId: string, inputs: Record): ValidationSnapshot { + try { + const parts: string[] = []; + const args = copyArgument(inputs, parts, new Set()); + if (args === null || typeof args !== 'object' || Array.isArray(args) || Object.hasOwn(args, '_approval_token')) { + throw new Error('Policy requires an object of business arguments.'); + } + return { arguments: args as Record, canonical: parts, sensitiveFields: [] }; + } catch { + throw new PolicyEvaluationError(moduleId); + } +} + +/** @internal Reject unsafe top-level properties before the existing ACL and token extraction read them. */ +export function policyIngressInputs(inputs: Record, moduleId: string): Record { + try { + if (Object.getPrototypeOf(inputs) !== Object.prototype) throw new Error('Expected a plain input object.'); + const descriptors = Object.getOwnPropertyDescriptors(inputs); + const entries = Object.keys(descriptors).map((key) => [key, ownData(descriptors, key)]); + if (Reflect.ownKeys(descriptors).length !== entries.length) throw new Error('Expected string keys.'); + return Object.fromEntries(entries); + } catch { + throw new PolicyEvaluationError(moduleId); + } +} + +/** @internal */ +export async function policyArgumentsDigest(moduleId: string, snapshot: ValidationSnapshot): Promise { + try { + return await sha256Hex(snapshot.canonical.join('')); + } catch { + throw new PolicyEvaluationError(moduleId); + } +} + +function detachIdentity(identity: Identity | null): Identity | null { + return identity === null ? null : createIdentity(identity.id, identity.type, [...identity.roles], structuredClone(identity.attrs)); +} + +/** @internal Isolate the scope handed to an asynchronous approval handler. */ +export function policyApprovalContext(context: Context): Context { + const snapshot = new Context( + context.traceId, context.callerId, [...context.callChain], context.executor, + detachIdentity(context.identity), context.redactedInputs, context.data, context.cancelToken, + context.services, context.globalDeadline, context.redactedOutput, + ); + Object.defineProperties(snapshot, { identity: { writable: false }, callerId: { writable: false } }); + return snapshot; +} + +/** @internal Bound evaluator work and sanitize provider errors. */ +export async function evaluatePolicy( + evaluator: PolicyEvaluator, + ctx: PipelineContext, + invocation: PolicyInvocation, + snapshot: ValidationSnapshot, +): Promise { + const { context, moduleId } = ctx; + const parent = context.cancelToken; + const token = new CancelToken(parent); + const deadline = context.globalDeadline; + const timeout = Math.min(1_000, deadline === null ? 1_000 : deadline * 1_000 - Date.now()); + const started = performance.now(); + invocation.evaluating = true; + try { + token.check(); + if (timeout <= 0) throw new PolicyEvaluationError(moduleId); + const request: PolicyEvaluationRequest = Object.freeze({ + moduleId, + moduleVersion: invocation.selected?.version ?? null, + callerId: context.callerId, + identity: detachIdentity(context.identity), + arguments: structuredClone(snapshot.arguments), + sensitiveFields: Object.freeze([...snapshot.sensitiveFields]), + signal: token.signal, + }); + const evaluation = Promise.resolve().then(() => evaluator.evaluate(request)); + const verdict = await awaitExecution(evaluation, token, moduleId, timeout, true); + if (performance.now() - started >= timeout) { + token.cancel(); + throw new PolicyEvaluationError(moduleId); + } + const decision = verdict?.decision; + if (decision !== 'allow' && decision !== 'deny' && decision !== 'require_approval') { + throw new PolicyEvaluationError(moduleId); + } + const ruleId = verdict?.ruleId; + return { + decision, + ...(typeof ruleId === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(ruleId) ? { ruleId } : {}), + }; + } catch { + if (parent?.isCancelled || parent?.signal.aborted) throw new ExecutionCancelledError(); + throw new PolicyEvaluationError(moduleId); + } finally { + invocation.evaluating = false; + token.dispose(); + } +} diff --git a/typescript/src/schema/loader-pure.ts b/typescript/src/schema/loader-pure.ts index 35dff8e9..6955aced 100644 --- a/typescript/src/schema/loader-pure.ts +++ b/typescript/src/schema/loader-pure.ts @@ -14,6 +14,7 @@ import { Value } from '@sinclair/typebox/value'; import { applicatorFailure, containsNeedsEvaluator, hasApplicatorKeyword } from './applicators.js'; import { SchemaCircularRefError, SchemaNotFoundError } from '../errors.js'; import { compareCodePoints } from '../utils/compare-code-points.js'; +import { sha256Hex } from '../utils/sha256.js'; import { createRedactionReferenceContext, resolveLocalSchemaReference, @@ -49,27 +50,7 @@ export function sortedKeysStringify(obj: unknown): string { * (Node-only sync variant) and the Python/Rust SDKs (sync finding A-D-033). */ export async function contentHashAsync(schema: unknown): Promise { - const canonical = sortedKeysStringify(schema); - type WebCryptoSubtle = { - digest(algo: string, data: ArrayBuffer | ArrayBufferView): Promise; - }; - const subtle: WebCryptoSubtle | undefined = - typeof globalThis !== 'undefined' - ? (globalThis as { crypto?: { subtle?: WebCryptoSubtle } }).crypto?.subtle - : undefined; - if (!subtle) { - throw new Error( - 'contentHashAsync(): no WebCrypto SubtleCrypto available in this runtime.', - ); - } - const data = new TextEncoder().encode(canonical); - const digest = await subtle.digest('SHA-256', data); - const bytes = new Uint8Array(digest); - let hex = ''; - for (const b of bytes) { - hex += b.toString(16).padStart(2, '0'); - } - return hex; + return sha256Hex(sortedKeysStringify(schema)); } // --------------------------------------------------------------------------- diff --git a/typescript/src/stream-completion.ts b/typescript/src/stream-completion.ts index c873de25..bddbcdc0 100644 --- a/typescript/src/stream-completion.ts +++ b/typescript/src/stream-completion.ts @@ -1,8 +1,9 @@ import { awaitExecution, type CancelToken, ExecutionCancelledError } from './cancel.js'; -import { ModuleError, ModuleTimeoutError } from './errors.js'; +import { ModuleError, ModuleTimeoutError, PolicyEvaluationError } from './errors.js'; import { trackExecution } from './execution-lifetime.js'; import { isModuleIdempotent } from './module.js'; import type { PipelineContext, StepTrace } from './pipeline.js'; +import { policyInvocationOf } from './policy-evaluation.js'; export type StreamCompletionReason = 'completed' | 'failed' | 'cancelled' | 'timed_out' | 'consumer_closed'; @@ -125,7 +126,10 @@ export function createStreamExecution( function expireDeadline(): void { const budget = Math.max(0, Math.ceil(deadlineMs! - startedAt!)); - interruption = new ModuleTimeoutError(moduleId, budget, { retryable: isModuleIdempotent(tracker.context?.module) }); + const context = tracker.context; + interruption = context !== null && policyInvocationOf(context)?.evaluating + ? new PolicyEvaluationError(moduleId) + : new ModuleTimeoutError(moduleId, budget, { retryable: isModuleIdempotent(context?.module) }); // Publish the deadline's own error before the interruption reaches the // producer as cancellation. Its physical shutdown may still be pending. settle('timed_out', interruption.code); diff --git a/typescript/src/utils/sha256.ts b/typescript/src/utils/sha256.ts new file mode 100644 index 00000000..bd22969e --- /dev/null +++ b/typescript/src/utils/sha256.ts @@ -0,0 +1,7 @@ +/** Compute a SHA-256 digest using the portable Web Crypto implementation. */ +export async function sha256Hex(value: string): Promise { + const subtle = globalThis.crypto?.subtle; + if (!subtle) throw new Error('Web Crypto SubtleCrypto is unavailable.'); + const bytes = new Uint8Array(await subtle.digest('SHA-256', new TextEncoder().encode(value))); + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); +} diff --git a/typescript/tests/test-extensions.test.ts b/typescript/tests/test-extensions.test.ts index afb8891a..34ddd7f3 100644 --- a/typescript/tests/test-extensions.test.ts +++ b/typescript/tests/test-extensions.test.ts @@ -40,16 +40,16 @@ class StubExporter implements SpanExporter { // --------------------------------------------------------------------------- describe('ExtensionManager init', () => { - it('has six built-in extension points', () => { + it('has seven built-in extension points', () => { const mgr = new ExtensionManager(); const points = mgr.listPoints(); - expect(points).toHaveLength(6); + expect(points).toHaveLength(7); }); it('built-in point names match expected set', () => { const mgr = new ExtensionManager(); const names = new Set(mgr.listPoints().map((p: ExtensionPoint) => p.name)); - expect(names).toEqual(new Set(['discoverer', 'middleware', 'acl', 'span_exporter', 'module_validator', 'approval_handler'])); + expect(names).toEqual(new Set(['discoverer', 'middleware', 'acl', 'span_exporter', 'module_validator', 'approval_handler', 'policy_evaluator'])); }); it('listPoints returns ExtensionPoint objects', () => { diff --git a/typescript/tests/test-post-validation-policy.test.ts b/typescript/tests/test-post-validation-policy.test.ts new file mode 100644 index 00000000..9953a5f8 --- /dev/null +++ b/typescript/tests/test-post-validation-policy.test.ts @@ -0,0 +1,414 @@ +import { readFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { join } from 'node:path'; +import { Kind, Type, TypeRegistry } from '@sinclair/typebox'; +import { describe, expect, it, vi } from 'vitest'; +import { + ACL, + CancelToken, + Context, + createAnnotations, + createApprovalResult, + Executor, + ModuleError, + Registry, + STREAMING_MARKER, + type ApprovalHandler, + type ApprovalRequest, + type PolicyEvaluationRequest, +} from '../src/index.js'; +import { ExtensionManager } from '../src/full.js'; +import { Middleware } from '../src/middleware/index.js'; +import { findFixturesRoot } from './spec-repo.js'; + +interface Case { + id: string; + entry: 'call' | 'stream' | 'preflight' | 'resume'; + verdict: 'allow' | 'deny' | 'require_approval' | 'throw'; + requires_approval?: boolean; + rewrite_amount?: number; + inputs?: Record; + retry_inputs?: Record; + expected: { + module_starts: number; + evaluated_amount: number | null; + approval_requests: number; + approved_amount?: number; + requires_approval?: boolean; + resume_checks?: number; + error_code?: string; + }; +} + +const fixture = JSON.parse(readFileSync(join(findFixturesRoot(), 'post_validation_policy.json'), 'utf8')) as { + driver_contract: { + module_id: string; + module_version: string; + input_schema: Record; + business_input: Record; + }; + test_cases: Case[]; +}; + +const { module_id: moduleId, module_version: version, input_schema: inputSchema, business_input: input } = fixture.driver_contract; + +async function makeRegistry(requiresApproval = false) { + const registry = new Registry(); + const execute = vi.fn(async (args: Record) => args); + const stream = vi.fn(async function* (args: Record) { yield args; }); + const preview = vi.fn(() => null); + await registry.register(moduleId, { + [STREAMING_MARKER]: true, + description: 'Return validated arguments', + inputSchema, + outputSchema: inputSchema, + annotations: createAnnotations({ streaming: true, requiresApproval }), + execute, + stream, + preview, + }, version); + return { registry, execute, stream, preview }; +} + +function sameApprovalScope(left: ApprovalRequest, right: ApprovalRequest): boolean { + return left.moduleId === right.moduleId && left.moduleVersion === right.moduleVersion && + left.callerId === right.callerId && left.context.identity?.id === right.context.identity?.id && + left.context.identity?.type === right.context.identity?.type && + left.canonicalArgsDigest === right.canonicalArgsDigest; +} + +describe('post_validation_policy.json', () => { + it.each(fixture.test_cases)('$id', async (testCase) => { + const { registry, execute, stream } = await makeRegistry(testCase.requires_approval); + const evaluated: PolicyEvaluationRequest[] = []; + const approved: ApprovalRequest[] = []; + let credentials = 0; + const approvalHandler: ApprovalHandler = { + supportsFinalScope: true, + async requestApproval(request) { + approved.push(request); + return testCase.entry === 'resume' + ? createApprovalResult({ status: 'pending', approvalId: 'scoped-resume' }) + : createApprovalResult({ status: 'approved' }); + }, + async checkApproval() { throw new Error('Status-only checks cannot authorize'); }, + async checkApprovalForCall(credential, request) { + const matches = credentials++ === 0 && credential === 'scoped-resume' && + sameApprovalScope(approved[0], request); + return createApprovalResult({ status: matches ? 'approved' : 'rejected' }); + }, + }; + const executor = new Executor({ registry, approvalHandler, policyEvaluator: { + async evaluate(request) { + evaluated.push(request); + if (testCase.verdict === 'throw') throw new Error('backend-canary'); + return { decision: testCase.verdict }; + }, + } }); + if (testCase.rewrite_amount !== undefined) { + executor.useBefore((_id, args) => ({ ...args, amount: testCase.rewrite_amount })); + } + + let observedError: unknown; + let requiresApproval = false; + const args = { ...input, ...testCase.inputs }; + try { + if (testCase.entry === 'preflight') { + requiresApproval = (await executor.validate(moduleId, args)).requiresApproval; + } else if (testCase.entry === 'stream') { + for await (const _chunk of executor.stream(moduleId, args)) { /* drain */ } + } else if (testCase.entry === 'resume') { + await expect(executor.call(moduleId, args)).rejects.toMatchObject({ code: 'APPROVAL_PENDING' }); + await executor.call(moduleId, { ...args, ...testCase.retry_inputs, _approval_token: 'scoped-resume' }); + } else { + await executor.call(moduleId, args); + } + } catch (error) { + observedError = error; + } + + const expected = testCase.expected; + expect(execute.mock.calls.length + stream.mock.calls.length).toBe(expected.module_starts); + expect(evaluated.at(-1)?.arguments.amount ?? null).toBe(expected.evaluated_amount); + expect(approved).toHaveLength(expected.approval_requests); + if ('approved_amount' in expected) expect(approved.at(-1)?.arguments.amount).toBe(expected.approved_amount); + if ('requires_approval' in expected) expect(requiresApproval).toBe(expected.requires_approval); + if ('resume_checks' in expected) expect(credentials).toBe(expected.resume_checks); + if ('error_code' in expected) { + expect(observedError).toMatchObject({ code: expected.error_code }); + expect(JSON.stringify(observedError)).not.toContain('backend-canary'); + } else if (expected.evaluated_amount === null) { + expect(observedError).toBeInstanceOf(ModuleError); + } else { + expect(observedError).toBeUndefined(); + } + for (const request of evaluated) { + expect(request.moduleVersion).toBe(version); + expect(request.arguments).not.toHaveProperty('_approval_token'); + expect(request.sensitiveFields).toContain('/secret'); + } + for (const request of approved) { + expect(request.moduleVersion).toBe(version); + expect(request.canonicalArgsDigest).toMatch(/^[0-9a-f]{64}$/); + expect(request.arguments).not.toHaveProperty('_approval_token'); + } + }); +}); + +describe('post-validation policy executor integration', () => { + it('does not expose an ACL-rejected preflight to the evaluator or preview', async () => { + const { registry, preview } = await makeRegistry(); + const evaluate = vi.fn(async () => ({ decision: 'allow' as const })); + const executor = new Executor({ registry, acl: new ACL([], 'deny'), policyEvaluator: { evaluate } }); + const report = await executor.validate(moduleId, input); + expect(report.valid).toBe(false); + expect(evaluate).not.toHaveBeenCalled(); + expect(preview).not.toHaveBeenCalled(); + }); + + it('discloses independently detached validated inputs to preflight and preview', async () => { + const registry = new Registry(); + const businessArgs = { nested: { amount: 10 } }; + const schema = Type.Object({ nested: Type.Object({ amount: Type.Number() }) }); + const preflight = vi.fn((args: typeof businessArgs) => { + expect(args.nested.amount).toBe(10); + args.nested.amount = 30; + return []; + }); + const preview = vi.fn((args: typeof businessArgs) => { + expect(args.nested.amount).toBe(10); + return null; + }); + await registry.register(moduleId, { + description: 'Preview validated inputs', inputSchema: schema, outputSchema: schema, + execute: (args: typeof businessArgs) => args, preflight, preview, + }); + const executor = new Executor({ registry, policyEvaluator: { + async evaluate(request) { + expect(request.arguments).toEqual({ nested: { amount: 10 } }); + await Promise.resolve(); + businessArgs.nested.amount = 20; + return { decision: 'allow' }; + }, + } }); + const report = await executor.validate(moduleId, businessArgs); + expect(report.valid).toBe(true); + expect(report.checks.flatMap(check => check.warnings ?? [])).toEqual([]); + expect(preflight).toHaveBeenCalledOnce(); + expect(preview).toHaveBeenCalledOnce(); + expect(businessArgs.nested.amount).toBe(20); + }); + + it('stops preflight disclosure when the module changes the policy-bound caller', async () => { + const registry = new Registry(); + const preflight = vi.fn((_args: unknown, context: Context) => { + Reflect.set(context, 'callerId', 'replacement.caller'); + return ['unexpected result']; + }); + const preview = vi.fn(() => null); + await registry.register(moduleId, { + description: 'Probe preflight binding', inputSchema, outputSchema: inputSchema, + execute: (args: Record) => args, preflight, preview, + }); + const executor = new Executor({ registry, policyEvaluator: { + async evaluate() { return { decision: 'allow' }; }, + } }); + const report = await executor.validate(moduleId, input); + expect(preflight).toHaveBeenCalledOnce(); + expect(preview).not.toHaveBeenCalled(); + expect(report.valid).toBe(false); + expect(report.checks).toContainEqual(expect.objectContaining({ + check: 'post_validation_policy', passed: false, error: expect.objectContaining({ code: 'POLICY_EVALUATION_ERROR' }), + })); + expect(report.checks.flatMap(check => check.warnings ?? [])).toEqual([]); + }); + + it('prevents error middleware from recovering a rejected policy', async () => { + const { registry, execute, stream } = await makeRegistry(); + const onError = vi.fn(() => input); + class Recovery extends Middleware { override onError = onError; } + const executor = new Executor({ registry, middlewares: [new Recovery()], policyEvaluator: { + async evaluate() { return { decision: 'deny' }; }, + } }); + executor.addStepMiddleware({ onStepError: () => input }); + await expect(executor.call(moduleId, input)).rejects.toMatchObject({ code: 'POLICY_DENIED' }); + await expect(executor.stream(moduleId, input).next()).rejects.toMatchObject({ code: 'POLICY_DENIED' }); + expect(onError).not.toHaveBeenCalled(); + expect(execute).not.toHaveBeenCalled(); + expect(stream).not.toHaveBeenCalled(); + }); + + it('does not substitute unvalidated inputs or an injected producer from step middleware', async () => { + const { registry, stream } = await makeRegistry(); + const executor = new Executor({ registry, policyEvaluator: { + async evaluate(request) { + Reflect.set(request.arguments, 'amount', 50); + return { decision: 'allow' }; + }, + } }); + const injected = vi.fn(async function* () { yield { amount: 999 }; }); + executor.addStepMiddleware({ + beforeStep(name, state) { + if (name === 'input_validation') state.context.outputStream = injected(); + if (name === 'execute') state.context.inputs = { ...input, amount: 999 }; + }, + }); + const iterator = executor.stream(moduleId, input); + expect((await iterator.next()).value).toEqual(input); + expect((await iterator.next()).done).toBe(true); + expect(stream.mock.lastCall?.[0]).toEqual(input); + }); + + it('rejects a strategy missing the approval and validation boundaries', async () => { + const { registry, execute } = await makeRegistry(); + const evaluator = { async evaluate() { return { decision: 'allow' as const }; } }; + expect(() => new Executor({ registry, strategy: 'minimal', policyEvaluator: evaluator })) + .toThrow(expect.objectContaining({ code: 'PIPELINE_CONFIGURATION_ERROR' })); + expect(execute).not.toHaveBeenCalled(); + }); + + it('does not turn caller cancellation into an evaluator fault', async () => { + const { registry, execute } = await makeRegistry(); + const token = new CancelToken(); + const executor = new Executor({ registry, policyEvaluator: { + async evaluate() { + token.cancel(); + return { decision: 'allow' }; + }, + } }); + await expect(executor.call(moduleId, input, Context.create(null, null, token))) + .rejects.toMatchObject({ code: 'EXECUTION_CANCELLED' }); + expect(execute).not.toHaveBeenCalled(); + }); + + it('registers a code-only evaluator on just one executor', async () => { + const { registry } = await makeRegistry(); + const enabled = new Executor({ registry }); + const normal = new Executor({ registry }); + const manager = new ExtensionManager(); + manager.register('policy_evaluator', { async evaluate() { return { decision: 'deny' }; } }); + manager.apply(registry, enabled); + await expect(enabled.call(moduleId, input)).rejects.toMatchObject({ code: 'POLICY_DENIED' }); + await expect(normal.call(moduleId, input)).resolves.toEqual(input); + }); + + it('requires final-scope support for pending approval and does not fall back on resume', async () => { + const { registry, execute } = await makeRegistry(); + const pending = vi.fn(async () => createApprovalResult({ status: 'pending', approvalId: 'legacy-token' })); + const resume = vi.fn(async () => createApprovalResult({ status: 'approved' })); + const executor = new Executor({ + registry, + approvalHandler: { requestApproval: pending, checkApproval: resume, checkApprovalForCall: resume }, + policyEvaluator: { async evaluate() { return { decision: 'require_approval' }; } }, + }); + await expect(executor.call(moduleId, input)).rejects.toMatchObject({ code: 'APPROVAL_DENIED' }); + executor.setPolicyEvaluator({ async evaluate() { return { decision: 'allow' }; } }); + await expect(executor.call(moduleId, { ...input, _approval_token: 'legacy-token' })) + .rejects.toMatchObject({ code: 'APPROVAL_DENIED' }); + expect(pending).toHaveBeenCalledOnce(); + expect(resume).not.toHaveBeenCalled(); + expect(execute).not.toHaveBeenCalled(); + }); + + it('hashes the approved JSON-shaped values with UTF-16 ordering and signed-zero preservation', async () => { + const registry = new Registry(); + const echo = (args: Record) => args; + await registry.register(moduleId, { + description: 'Return the supplied JSON values', inputSchema: { type: 'object' }, outputSchema: { type: 'object' }, execute: echo, + }); + const approval = vi.fn(async (_request: ApprovalRequest) => createApprovalResult({ status: 'approved' })); + const executor = new Executor({ + registry, + approvalHandler: { requestApproval: approval, checkApproval: async () => createApprovalResult({ status: 'rejected' }) }, + policyEvaluator: { async evaluate() { return { decision: 'require_approval' }; } }, + }); + const result = await executor.call(moduleId, { '2': 7, '10': -0, '\u{10400}': 0.25, '\uE000': true }); + const expected = createHash('sha256') + .update('{"10":f8000000000000000;,"2":i7;,"\u{10400}":f3fd0000000000000;,"\uE000":true}') + .digest('hex'); + expect(approval.mock.lastCall?.[0].canonicalArgsDigest).toBe(expected); + expect(Object.is(result['10'], -0)).toBe(true); + }); + + it.each([false, true])('binds exactly the TypeBox-validated input when a validator retains a reference (%s)', + async (mutateAfterValidation) => { + const kind = 'Test:NormalizePolicyInput'; + let checked: { message: string } | null = null; + TypeRegistry.Set(kind, (_schema, value) => { + if (value === null || typeof value !== 'object' || !('message' in value) || typeof value.message !== 'string') return false; + checked = value as { message: string }; + checked.message = checked.message.trim(); + return true; + }); + try { + const registry = new Registry(); + const echo = (args: Record) => args; + const schema = Type.Unsafe({ [Kind]: kind, type: 'object' }); + await registry.register(moduleId, { + description: 'Return the validated inputs', inputSchema: schema, + outputSchema: Type.Object({ message: Type.String() }), execute: echo, + }); + const approval = vi.fn(async (_request: ApprovalRequest) => createApprovalResult({ + status: 'pending', approvalId: 'validator-scope', + })); + const resume = vi.fn(async (token: string, request: ApprovalRequest) => { + const original = approval.mock.lastCall?.[0]; + const matches = token === 'validator-scope' && original !== undefined && sameApprovalScope(original, request); + return createApprovalResult({ status: matches ? 'approved' : 'rejected' }); + }); + const executor = new Executor({ + registry, + approvalHandler: { + supportsFinalScope: true, requestApproval: approval, checkApprovalForCall: resume, + checkApproval: async () => createApprovalResult({ status: 'rejected' }), + }, + policyEvaluator: { + async evaluate(request) { + expect(request.arguments).toEqual({ message: 'hello' }); + await Promise.resolve(); + if (checked && mutateAfterValidation) checked.message = 'changed after validation'; + return { decision: 'require_approval' }; + }, + }, + }); + await expect(executor.call(moduleId, { message: ' hello ' })) + .rejects.toMatchObject({ code: 'APPROVAL_PENDING' }); + const expected = createHash('sha256').update('{"message":"hello"}').digest('hex'); + expect(approval.mock.lastCall?.[0].canonicalArgsDigest).toBe(expected); + expect(approval.mock.lastCall?.[0].arguments).toEqual({ message: 'hello' }); + const result = await executor.call(moduleId, { message: 'hello ', _approval_token: 'validator-scope' }); + expect(resume.mock.lastCall?.[1].canonicalArgsDigest).toBe(expected); + expect(resume.mock.lastCall?.[1].arguments).toEqual({ message: 'hello' }); + expect(result).toEqual({ message: 'hello' }); + } finally { + TypeRegistry.Delete(kind); + } + }); + + it.each(['call', 'streamWithCompletion'] as const)('bounds evaluator work in %s by the invocation deadline', async (entry) => { + vi.useFakeTimers(); + try { + const { registry, execute } = await makeRegistry(); + let signal: AbortSignal | undefined; + const executor = new Executor({ registry, policyEvaluator: { + async evaluate(request) { + signal = request.signal; + await new Promise(resolve => signal?.addEventListener('abort', () => resolve(), { once: true })); + return { decision: 'allow' }; + }, + } }); + const context = Context.create(null, null, null, {}, null, (Date.now() + 25) / 1000); + const stream = entry === 'streamWithCompletion' ? executor.streamWithCompletion(moduleId, input, context) : null; + const result = expect(stream ? stream.chunks.next() : executor.call(moduleId, input, context)).rejects.toMatchObject({ + code: 'POLICY_EVALUATION_ERROR', retryable: true, userFixable: false, + }); + await vi.advanceTimersByTimeAsync(25); + await result; + if (stream) await expect(stream.completion).resolves.toMatchObject({ reason: 'failed', errorCode: 'POLICY_EVALUATION_ERROR' }); + expect(signal?.aborted).toBe(true); + expect(execute).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); +});