From 4c687ce0d0b7890a2852ee6898d81fb66d2bcf1b Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 08:58:30 +0800 Subject: [PATCH 1/6] docs(planning): prepare the identity delegation milestone Signed-off-by: tercel --- planning/identity-delegation/overview.md | 22 +++++++++ planning/identity-delegation/plan.md | 27 +++++++++++ planning/identity-delegation/state.json | 45 +++++++++++++++++++ .../identity-delegation/tasks/core-sdks.md | 8 ++++ .../tasks/shared-contract.md | 9 ++++ .../identity-delegation/tasks/surfaces.md | 7 +++ .../identity-delegation/tasks/verification.md | 5 +++ 7 files changed, 123 insertions(+) create mode 100644 planning/identity-delegation/overview.md create mode 100644 planning/identity-delegation/plan.md create mode 100644 planning/identity-delegation/state.json create mode 100644 planning/identity-delegation/tasks/core-sdks.md create mode 100644 planning/identity-delegation/tasks/shared-contract.md create mode 100644 planning/identity-delegation/tasks/surfaces.md create mode 100644 planning/identity-delegation/tasks/verification.md diff --git a/planning/identity-delegation/overview.md b/planning/identity-delegation/overview.md new file mode 100644 index 00000000..48f12982 --- /dev/null +++ b/planning/identity-delegation/overview.md @@ -0,0 +1,22 @@ +# Identity Delegation + +Gap 2 follows the merged capability discovery milestone. The Core base is `173db455`, and the Surfaces base is `d2bac9be`. The local candidate branches are `core-alpha5` and `surfaces-alpha5`. + +The proposed contract covers trusted delegation in Core, scoped authorization and audit, and opt-in mapping of verified JWT claims in MCP and A2A. Implementation of the new protocol behavior follows maintainer approval of the proposed semantics. The proposal advances the draft revision on the current protocol version line. + +## Baseline verification + +| Existing behavior | Python | TypeScript | Rust | +| --- | ---: | ---: | ---: | +| Core identity and context | 272 passed | 108 passed | 44 passed | +| MCP Python authentication | 72 passed | | | +| A2A Python authentication | 35 passed | | | + +The Python and TypeScript Core runs include ACL tests. The Rust aggregate run selects existing identity cases. + +## Implementation order + +1. Approve the [proposed contract](./plan.md) and define the [shared conformance cases](./tasks/shared-contract.md). +2. Implement the [Core SDK changes](./tasks/core-sdks.md) independently in Python, TypeScript, and Rust. +3. Apply the same authority contract to the [MCP and A2A adapters](./tasks/surfaces.md). +4. Run the [dual-repository verification](./tasks/verification.md) against fixed source and package candidates. diff --git a/planning/identity-delegation/plan.md b/planning/identity-delegation/plan.md new file mode 100644 index 00000000..ee5ed1c1 --- /dev/null +++ b/planning/identity-delegation/plan.md @@ -0,0 +1,27 @@ +# Identity Delegation Implementation Plan + +## Local authority + +Keep the existing Identity constructors and the six-argument Context creation contract. Add immutable optional `scopes` and an optional `on_behalf_of` link. Preserve absent fields in the legacy wire shape. A missing scope collection means that scope enforcement is not enabled for that ordinary identity. An explicit empty collection means there is no scoped authority. Treat scope strings as case-sensitive literals. + +A trusted host can issue a scoped root. A local delegation accepts a trusted actor and an explicit requested scope set. The requested set must be a subset of the parent ceiling at every hop. A parent with no explicit ceiling cannot seed delegated scope. Check the direct constructor, the delegation helper and trusted restoration against the same depth and subset invariants. Count edges from a direct identity at depth zero and allow up to eight. Reject object cycles and excessive nesting. Repeated actors within a bounded chain do not reset its authority. Deserialization validates structure and attenuation. It does not authenticate the supplied identity. + +## Authorization, binding, and audit + +For scope-enabled identities, require the first matching ACL grant to include a nonempty top-level `scopes` conjunct. The actor must possess every listed scope. A scope check that can be bypassed through a compound branch does not establish that grant. An allow without a scope grant, including a permissive default, denies scoped execution. A scoped request reaching a pipeline without a recognized enforcing gate fails closed. A scope-free legacy Identity continues to use the ordinary ACL contract. Keep actor types and roles on the actual actor. Add explicit root-subject type and role predicates and a delegation-depth predicate. The root subject of a direct call is its actor. Discovery evaluates these predicates using the same prospective caller and trusted scope as execution. + +Use a shared detached authority projection per SDK for discovery cursors, policy requests and approval scope. Include the effective actor, root subject and scope ceiling where applicable. Include trusted local lineage where it contributes to authority. Keep prior actors from an RFC 8693 history out of authority decisions. An approval issued for one authority must never resume or be consumed under another. Existing direct approvals keep their direct-call scope. A legacy credential does not satisfy a delegated request. + +Expose actor ID, root subject ID and active delegation depth in the applicable audit records. Reuse D-93 redaction for attributes at every depth. Audit snapshots must not expose raw signed tokens or unredacted attributes from an ancestor. + +## JWT projection and transport ownership + +Make the scope and delegation mapping opt-in in all six authenticators. Require a verified signature, expected issuer and audience, and applicable time claims before mapping a configured scope or delegation. A present malformed delegation or invalid configured scope fails authentication. Keep the current claim format when mapping is disabled. Parse `scope` and configured provider `scp` according to their declared formats. If both configured representations are present, require the normalized sets to agree. + +Map the verified top-level subject and the outermost actor to one active Core delegation edge. The token scopes are the current ceiling. Derive actor roles only from explicitly mapped claims about the current actor. Bound validation of nested actor claims with the same structural limit. Preserve their identifiers for bounded audit history where configured. The active authorization depth remains one regardless of that history. Verify this distinction against [RFC 8693 §4.1](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.1) and the token scope representation in [RFC 8693 §4.2](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.2). + +Bind transport and stored task ownership to the issuer-qualified actor and effective subject where supported. Keep that ownership key separate from the authority projection. Apply current scope to each protected operation. Include current authority in permission caches and recheck governed result retrieval and resumption so narrower claims do not inherit stale permissions. Equivalent token refresh may retain the same owner. + +## Candidate boundary + +Complete the Core contract first, then the six adapter mappings, then installed-artifact validation. The SDK wrappers reuse the current Context, ACL, policy, and approval entry points. This candidate covers resource-server consumption of credential claims and local trusted delegation. Opening a PR, merging a candidate, and releasing packages are separate steps. diff --git a/planning/identity-delegation/state.json b/planning/identity-delegation/state.json new file mode 100644 index 00000000..4ce902cd --- /dev/null +++ b/planning/identity-delegation/state.json @@ -0,0 +1,45 @@ +{ + "feature": "identity-delegation", + "created": "2026-11-28", + "updated": "2026-11-28", + "status": "in_progress", + "execution_order": ["shared-contract", "core-sdks", "surfaces", "verification"], + "progress": { + "total_tasks": 4, + "completed": 0, + "in_progress": 0, + "pending": 3, + "skipped": 0, + "blocked": 1 + }, + "tasks": [ + { + "id": "shared-contract", + "file": "tasks/shared-contract.md", + "title": "Shared delegation contract and conformance", + "status": "blocked", + "blocker": "Maintainer approval of the proposed protocol draft revision" + }, + { + "id": "core-sdks", + "file": "tasks/core-sdks.md", + "title": "Python, TypeScript, and Rust delegated identity", + "status": "pending", + "dependencies": ["shared-contract"] + }, + { + "id": "surfaces", + "file": "tasks/surfaces.md", + "title": "MCP and A2A verified claim mapping", + "status": "pending", + "dependencies": ["core-sdks"] + }, + { + "id": "verification", + "file": "tasks/verification.md", + "title": "Dual-repository verification", + "status": "pending", + "dependencies": ["core-sdks", "surfaces"] + } + ] +} diff --git a/planning/identity-delegation/tasks/core-sdks.md b/planning/identity-delegation/tasks/core-sdks.md new file mode 100644 index 00000000..39b95a6f --- /dev/null +++ b/planning/identity-delegation/tasks/core-sdks.md @@ -0,0 +1,8 @@ +# Core SDKs + +Python owns `python/`, TypeScript owns `typescript/`, and Rust owns `rust/`. Each SDK uses the existing identity and context APIs, ACL condition registry, discovery projection, policy snapshot and approval verification hooks. + +1. Pin existing construction and wire shapes. Add the checked delegated data model and scope narrowing with explicit parent authority. +2. Align ACL predicates, discovery and actual execution. Reuse the existing matcher, audit producer and fail-closed execution path. +3. Carry a stable authority projection into cursor binding, request snapshots and permission to resume approvals. Preserve the direct path and fail safely on a malformed delegated representation. +4. Run the shared fixtures plus SDK-specific regressions through public APIs. Cover legacy compatibility, concurrent use of detached identities and audit redaction. diff --git a/planning/identity-delegation/tasks/shared-contract.md b/planning/identity-delegation/tasks/shared-contract.md new file mode 100644 index 00000000..407d290a --- /dev/null +++ b/planning/identity-delegation/tasks/shared-contract.md @@ -0,0 +1,9 @@ +# Shared Contract and Conformance + +After maintainer approval, update the protocol draft revision, history, changelog, applicable wire schemas, and decision record. Preserve existing anchors and old optional-field wire shape. Pin these behaviors in shared fixtures before changing SDK implementation. + +- A direct identity has depth zero. A chain of eight edges succeeds. A ninth edge, an object cycle, an upward scope transition and a missing delegated scope fail. Repeated principals cannot recover authority. +- Absent and empty scope collections round-trip distinctly. Legacy direct identity input remains valid. A malformed present delegation fails restoration without becoming an ordinary identity. +- Decision tests cover actor roles, root-subject roles/types, depth, partial matching of required scopes and a legacy allow without a scope predicate. Discovery and invocation apply the same trusted scope. +- Test approval and cursor isolation when the actor stays constant and the subject or effective scope changes. Verify that an unauthorized resume leaves the stored approval available to its original authority. +- Exercise signed JWT claims with valid and invalid issuer and audience, expired tokens, malformed opt-in claims and conflicting scope sources. Nested actors never contribute authorization. Verify redaction at every identity depth. diff --git a/planning/identity-delegation/tasks/surfaces.md b/planning/identity-delegation/tasks/surfaces.md new file mode 100644 index 00000000..2706cb66 --- /dev/null +++ b/planning/identity-delegation/tasks/surfaces.md @@ -0,0 +1,7 @@ +# MCP and A2A + +Start from the approved Core identity APIs. Extend the existing JWT authenticators in Python, TypeScript, and Rust. Keep verification and claim projection together per adapter and reuse the existing route-to-Context paths. + +- Exercise actual authentication middleware and real protocol calls. Check invalid signatures, absent or mismatched required verification claims, scope conflicts and audit-only historical actors. The resource server accepts the token's current scope ceiling and does not infer grants from previous actors. +- Check ownership and permission separately for stream sessions, MCP and A2A tasks, event subscriptions, approval polling/resumption and A2A visibility caches. Cover the same actor acting for distinct subjects, a refreshed credential with narrower authority, and an anonymous request targeting a delegated task. Exercise Python and Rust MCP session ownership, TypeScript MCP SSE reuse, and all A2A task and push-store owner buckets. Warm the Rust A2A capability cache before reducing the caller's scope. +- Verify that incoming protocol request fields cannot supply authority. Ensure malformed opt-in claims do not continue as an anonymous request. Preserve the direct mapping path when delegation is disabled. diff --git a/planning/identity-delegation/tasks/verification.md b/planning/identity-delegation/tasks/verification.md new file mode 100644 index 00000000..4e302853 --- /dev/null +++ b/planning/identity-delegation/tasks/verification.md @@ -0,0 +1,5 @@ +# Dual-repository Verification + +Verify all three SDKs against the shared cases, the Core Profile, and full checks. Confirm that syntax validation, authority proof, denial behavior, cursor isolation, approval identity and recursive audit redaction have passing runtime assertions. Build the wheel, npm tarball and Rust crate from one Core candidate and record checksums. + +Install the Core candidates into Toolkit, MCP, A2A and CLI in all three SDK ecosystems. Run real protocol client tests for both MCP and A2A with verified credentials and a before-and-after scope reduction on the same actor. Verify the existing minimum Toolkit compatibility and the direct and MCP Golden Path. Record both repository revisions and the installed package identities. From 6a4aa25b93526f09ca698aa9ffb982f94e613158 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 17:23:13 +0800 Subject: [PATCH 2/6] feat(core): enforce trusted delegated identity scopes Signed-off-by: tercel --- CHANGELOG.md | 1 + conformance/README.md | 1 + conformance/decision_coverage.json | 16 + conformance/fixtures/identity_delegation.json | 545 ++++++++++++++++++ docs/features/acl-system.md | 6 +- docs/features/identity-system.md | 59 +- docs/guides/acl-configuration.md | 23 + docs/index.md | 8 +- docs/spec/conformance.md | 5 +- docs/spec/decision-register.md | 1 + docs/spec/protocol-spec.md | 49 +- planning/identity-delegation/plan.md | 4 +- planning/identity-delegation/state.json | 15 +- python/apcore-conformance.yaml | 2 +- python/pyproject.toml | 2 +- python/src/apcore/_post_validation_policy.py | 8 +- python/src/apcore/acl.py | 57 +- python/src/apcore/acl_handlers.py | 51 +- python/src/apcore/approval.py | 4 + python/src/apcore/builtin_steps.py | 47 +- python/src/apcore/capabilities.py | 11 +- python/src/apcore/context.py | 224 +++++-- python/src/apcore/executor.py | 17 +- python/src/apcore/pipeline.py | 49 +- python/src/apcore/policy.py | 1 + python/src/apcore/sys_modules/identity.py | 25 +- .../conformance/test_identity_delegation.py | 38 ++ python/tests/test_identity_delegation.py | 174 ++++++ python/uv.lock | 2 +- rust/Cargo.lock | 2 +- rust/Cargo.toml | 2 +- rust/apcore-conformance.yaml | 2 +- rust/src/acl.rs | 105 +++- rust/src/acl_handlers.rs | 164 +++++- rust/src/approval.rs | 14 + rust/src/builtin_steps.rs | 78 ++- rust/src/capability.rs | 44 +- rust/src/context.rs | 268 ++++++++- rust/src/executor.rs | 51 +- rust/src/pipeline.rs | 89 ++- rust/src/pipeline_config.rs | 30 +- rust/src/policy/evaluator.rs | 8 + rust/src/sys_modules/mod.rs | 116 +++- rust/tests/capability_discovery.rs | 50 ++ rust/tests/identity_system_spec.rs | 161 ++++++ rust/tests/post_validation_policy.rs | 255 +++++++- schemas/acl-config.schema.json | 39 ++ typescript/apcore-conformance.yaml | 2 +- typescript/package.json | 2 +- typescript/src/acl.ts | 80 ++- typescript/src/approval.ts | 6 + typescript/src/browser/index.ts | 4 +- typescript/src/builtin-steps.ts | 33 +- typescript/src/capability-discovery.ts | 5 +- typescript/src/context.ts | 67 +-- typescript/src/executor.ts | 39 +- typescript/src/identity.ts | 211 +++++++ typescript/src/node-api.ts | 4 +- typescript/src/policy-evaluation.ts | 11 +- typescript/src/scoped-invocation.ts | 60 ++ typescript/src/sys-modules/audit.ts | 74 ++- .../conformance-identity-delegation.test.ts | 43 ++ .../tests/test-identity-delegation.test.ts | 214 +++++++ 63 files changed, 3413 insertions(+), 365 deletions(-) create mode 100644 conformance/fixtures/identity_delegation.json create mode 100644 python/tests/conformance/test_identity_delegation.py create mode 100644 python/tests/test_identity_delegation.py create mode 100644 typescript/src/identity.ts create mode 100644 typescript/src/scoped-invocation.ts create mode 100644 typescript/tests/conformance-identity-delegation.test.ts create mode 100644 typescript/tests/test-identity-delegation.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 16fca12a..b481008a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. - **Protocol 2.0.0 draft revision 3.** Add caller-scoped capability summaries and full-schema lookup using silent ACL visibility. Add the read-only `system.manifest.search` module with opaque cursors bound to the original requester. +- **Protocol 2.0.0 draft revision 4.** Add trusted identity delegation, scope-aware ACL grants, root-subject conditions, and authority binding for discovery cursors, policy input, and pending approval resumption. ### Changed diff --git a/conformance/README.md b/conformance/README.md index 98d89d6c..2afcd7c3 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -75,6 +75,7 @@ declared extension. Adapter wire projections are verified in Surfaces. | `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 | | `identity_system.json` | — | Identity construction, field access, and context propagation (AC-014, AC-015) | +| `identity_delegation.json` | — | Trusted context restoration, scope attenuation, active delegation depth, and ordered ACL authorization (D-155) | | `context_trace_parent.json` | §10.5 | Context.create trace_parent strict validation: 32-hex only, W3C-invalid rejection, no auto-normalization | | `context_create.json` | Issue #66 | Context.create unified-signature contract: 6-param input list, executor/caller_id NOT inputs, Executor binding (local + deserialize + hot-reload), idempotent same-executor rebind, cross-executor conflict, child() propagation of executor + cancel_token, distributed cancel_token/global_deadline semantics, TraceParent embeds tracestate | | `dependency_version_constraints.json` | §5.3, §5.15.2 | Dependency `version` constraint enforcement: exact, `>=`, `<=`, `^`, `~`, ranges, optional skip | diff --git a/conformance/decision_coverage.json b/conformance/decision_coverage.json index c9e4e74a..17445d29 100644 --- a/conformance/decision_coverage.json +++ b/conformance/decision_coverage.json @@ -1076,6 +1076,22 @@ "capability_discovery.json#prospective_nested_context_depth" ], "discriminates": "Rejects disclosure through an unresolved deny or missing role, preserves a valid conditional approval hint without execution, and checks the prospective target caller frame." + }, + "D-155": { + "title": "trusted delegation attenuates explicit scope for ordered ACL decisions", + "kind": "behavioural", + "cases": [ + "identity_delegation.json#delegated_scope_and_subject_grant", + "identity_delegation.json#subject_role_does_not_grant_actor_role", + "identity_delegation.json#first_matching_unscoped_allow_denies", + "identity_delegation.json#compound_scope_does_not_grant", + "identity_delegation.json#default_allow_denies", + "identity_delegation.json#malformed_depth_denial_blocks_later_allow", + "identity_delegation.json#restoration_rejects_scope_widening", + "identity_delegation.json#repeated_actor_keeps_bounded_authority", + "identity_delegation.json#restoration_rejects_ninth_link" + ], + "discriminates": "Requires an explicit scoped ACL grant, separates actor and subject roles, denies earlier unscoped grants and permissive defaults, and rejects widening and excessive depth during restoration without treating a repeated actor as a new root." } } } diff --git a/conformance/fixtures/identity_delegation.json b/conformance/fixtures/identity_delegation.json new file mode 100644 index 00000000..323751f3 --- /dev/null +++ b/conformance/fixtures/identity_delegation.json @@ -0,0 +1,545 @@ +{ + "description": "Trusted delegation attenuates explicit scope and binds ACL access to the current actor and root subject.", + "driver_contract": "Restore input.identity inside a native Context, then check the root subject and active depth. Where rules are supplied, evaluate an external caller targeting delegation.target using those rules and the supplied or default deny effect.", + "test_cases": [ + { + "id": "legacy_identity_preserves_acl", + "input": { + "identity": {"id": "agent-1", "type": "agent", "roles": ["runner"], "attrs": {}}, + "rules": [{"callers": ["@external"], "targets": ["delegation.target"], "effect": "allow"}] + }, + "expected": {"valid": true, "depth": 0, "subject_id": "agent-1", "effect": "allow"} + }, + { + "id": "delegated_scope_and_subject_grant", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + }, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": { + "scopes": ["read"], + "identity_types": ["agent"], + "roles": ["runner"], + "subject_types": ["user"], + "subject_roles": ["approver"], + "max_delegation_depth": 1 + } + } + ] + }, + "expected": {"valid": true, "depth": 1, "subject_id": "user-1", "effect": "allow"} + }, + { + "id": "insufficient_effective_scope", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + }, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": {"scopes": ["read", "deploy"]} + } + ] + }, + "expected": {"valid": true, "depth": 1, "subject_id": "user-1", "effect": "deny"} + }, + { + "id": "subject_role_does_not_grant_actor_role", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + }, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": {"scopes": ["read"], "roles": ["approver"]} + } + ] + }, + "expected": {"valid": true, "depth": 1, "subject_id": "user-1", "effect": "deny"} + }, + { + "id": "direct_identity_is_its_own_subject", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"] + }, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": { + "scopes": ["read"], + "subject_types": ["agent"], + "subject_roles": ["runner"], + "max_delegation_depth": 0 + } + } + ] + }, + "expected": {"valid": true, "depth": 0, "subject_id": "agent-1", "effect": "allow"} + }, + { + "id": "first_matching_unscoped_allow_denies", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + }, + "rules": [ + {"callers": ["@external"], "targets": ["delegation.target"], "effect": "allow"}, + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": {"scopes": ["read"]} + } + ] + }, + "expected": {"valid": true, "depth": 1, "subject_id": "user-1", "effect": "deny"} + }, + { + "id": "compound_scope_does_not_grant", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + }, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": {"$or": [{"scopes": ["read"]}, {"roles": ["runner"]}]} + } + ] + }, + "expected": {"valid": true, "depth": 1, "subject_id": "user-1", "effect": "deny"} + }, + { + "id": "default_allow_denies", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + }, + "rules": [], + "default_effect": "allow" + }, + "expected": {"valid": true, "depth": 1, "subject_id": "user-1", "effect": "deny"} + }, + { + "id": "explicit_empty_scopes_deny", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": [], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + }, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": {"scopes": ["read"]} + } + ] + }, + "expected": {"valid": true, "depth": 1, "subject_id": "user-1", "effect": "deny"} + }, + { + "id": "excessive_acl_delegation_depth", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + }, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": {"scopes": ["read"], "max_delegation_depth": 0} + } + ] + }, + "expected": {"valid": true, "depth": 1, "subject_id": "user-1", "effect": "deny"} + }, + { + "id": "integral_numeric_depth_threshold", + "input": { + "identity": {"id": "user-1", "type": "user", "roles": [], "attrs": {}, "scopes": ["read"]}, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": {"scopes": ["read"], "max_delegation_depth": 0.0} + } + ] + }, + "expected": {"valid": true, "depth": 0, "subject_id": "user-1", "effect": "allow"} + }, + { + "id": "malformed_depth_denial_blocks_later_allow", + "input": { + "identity": {"id": "user-1", "type": "user", "roles": [], "attrs": {}, "scopes": ["read"]}, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "deny", + "conditions": {"max_delegation_depth": 9} + }, + {"callers": ["@external"], "targets": ["delegation.target"], "effect": "allow", "conditions": {"scopes": ["read"]}} + ] + }, + "expected": {"valid": true, "depth": 0, "subject_id": "user-1", "effect": "deny"} + }, + { + "id": "restoration_rejects_scope_widening", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["write"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + } + }, + "expected": {"valid": false} + }, + { + "id": "restoration_rejects_missing_parent_ceiling", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": {"id": "user-1", "type": "agent", "roles": ["runner"], "attrs": {}} + } + }, + "expected": {"valid": false} + }, + { + "id": "restoration_rejects_malformed_scopes", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read write"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["deploy", "read"] + } + } + }, + "expected": {"valid": false} + }, + { + "id": "repeated_actor_keeps_bounded_authority", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"] + } + } + } + } + } + } + } + } + }, + "rules": [ + { + "callers": ["@external"], + "targets": ["delegation.target"], + "effect": "allow", + "conditions": {"scopes": ["read"], "max_delegation_depth": 8} + } + ] + }, + "expected": {"valid": true, "depth": 8, "subject_id": "user-1", "effect": "allow"} + }, + { + "id": "restoration_rejects_ninth_link", + "input": { + "identity": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "agent-1", + "type": "agent", + "roles": ["runner"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"], + "on_behalf_of": { + "id": "user-1", + "type": "user", + "roles": ["approver"], + "attrs": {}, + "issuer": "https://id.example", + "scopes": ["read"] + } + } + } + } + } + } + } + } + } + } + }, + "expected": {"valid": false} + } + ] +} diff --git a/docs/features/acl-system.md b/docs/features/acl-system.md index 1827e42f..17de709f 100644 --- a/docs/features/acl-system.md +++ b/docs/features/acl-system.md @@ -73,10 +73,14 @@ Pattern matching is handled at two levels: When a rule has a `conditions` dict, all specified conditions must be satisfied (AND logic): - `identity_types`: Context identity's type must be in the provided list. - `roles`: At least one of the context identity's roles must overlap with the condition's role list (set intersection). +- `scopes`: The current actor must hold every listed effective scope. Use a nonempty list at the top level of a scoped allow rule. +- `subject_types`: The root subject's type must be in the provided list. +- `subject_roles`: At least one of the root subject's roles must overlap with the list. +- `max_delegation_depth`: The active delegation chain must have at most this many links. A direct identity has depth zero. - `max_call_depth`: The length of `context.call_chain` must not exceed the threshold. - `arguments`: A structure-only test of the call's argument keys — `has_key` (any listed key present), `has_all_keys` (every listed key present), `has_none_of` (no listed key present); several predicates are AND-ed. It never reads argument values. It reads the call's governance projection (§6.1.8); when no projection is available the condition is unevaluable, never "no arguments" ([PROTOCOL_SPEC §6.1.7](../spec/protocol-spec.md)). -These four are the built-ins, plus the compound operators `$or` and `$not`. The set is open: `register_condition()` adds a condition key at runtime, and a rule may reference any key a handler has been registered for. `arguments` itself has no registration point. +The built-ins also include the compound operators `$or` and `$not`. The set is open: `register_condition()` adds a condition key at runtime, and a rule may reference any key a handler has been registered for. `arguments` itself has no registration point. A scope-enabled identity requires the first matching allow rule to enforce the stock `scopes` predicate at the top level. See [Trusted Identity Delegation](../spec/protocol-spec.md#trusted-identity-delegation). If no context is provided but conditions are present, the rule does not match — **provided the rule passes the precheck below**. A malformed rule is unevaluable first, context or no context. See the warning in [PROTOCOL_SPEC §6.5](../spec/protocol-spec.md#65-edge-case-handling) — a *well-formed* conditional `deny` rule is not a backstop for context-less callers. diff --git a/docs/features/identity-system.md b/docs/features/identity-system.md index ac91acf9..d3ab64ee 100644 --- a/docs/features/identity-system.md +++ b/docs/features/identity-system.md @@ -5,7 +5,7 @@ description: "Immutable Identity (id, type, roles, attrs) for the caller, attach # Identity System -> **Type:** Implementation guide. **Normative spec:** [PROTOCOL_SPEC](../spec/protocol-spec.md) §5.7 Context Parameter Specification (`identity` sub-schema). +> **Type:** Implementation guide. **Normative spec:** [Context Parameter Specification](../spec/protocol-spec.md#57-context-parameter-specification) and [Trusted Identity Delegation](../spec/protocol-spec.md#trusted-identity-delegation). ## Overview @@ -42,8 +42,8 @@ The Identity System gives the caller a structured representation that flows thro `roles` passed as a list is converted to a tuple, and `attrs` is copied, so mutating the caller's objects afterwards does not change the identity. === "TypeScript" ```typescript - // Shape of the frozen Identity class. The package root exports it as a - // type; construct instances with createIdentity(). + // Public fields of the frozen Identity class. Use createIdentity() to + // construct an instance. interface Identity { readonly id: string; readonly type: string; // Default: "user" @@ -96,7 +96,7 @@ The `type` field is a free-form string; the values above are the conventions lis ### Equality and Hashability -`Identity` is a value type. Equality is **structural** — two identities are equal when `id`, `type`, `roles` and `attrs` are equal. Hashability differs per language (D-26): +An `Identity` includes its ID, type, roles, attributes, and any explicit authority fields. Native equality and hashability differ per language (D-26): - **Rust**: derives `PartialEq`/`Eq` and implements `Hash` (attributes are hashed in key order), so it can be used as a `HashMap` key. - **Python**: a frozen dataclass whose `attrs` field is a `dict`, so `hash(identity)` raises `TypeError`; cross-language code SHOULD NOT rely on hashing identities. @@ -201,6 +201,55 @@ rules: See [ACL System](./acl-system.md) for the full condition syntax. +### Trusted Delegation + +A trusted host can assign an explicit scope ceiling to an authenticated identity and delegate a subset to another trusted actor. The resulting identity uses the delegate's ID, type, and roles. Its root subject remains the identity that supplied the original authority. Every link requires an explicit scope set, and a chain can contain up to eight links. An omitted scope collection keeps a direct identity under the ordinary ACL contract. An empty collection grants zero scopes. + +=== "Python" + ```python + from apcore import Context, Identity + + subject = Identity("user-123", scopes=("reports:read", "reports:write")) + actor = Identity("reports-worker", type="service") + delegated = subject.delegate(actor, ("reports:read",)) + context = Context.create(identity=delegated) + assert context.identity is not None + assert context.identity.root_subject.id == "user-123" + ``` +=== "TypeScript" + ```typescript + import { Context, createIdentity } from "apcore-js"; + + const subject = createIdentity("user-123", "user", [], {}, { + scopes: ["reports:read", "reports:write"], + }); + const actor = createIdentity("reports-worker", "service"); + const delegated = subject.delegate(actor, ["reports:read"]); + const context = Context.create(delegated); + if (context.identity?.rootSubject.id !== "user-123") { + throw new Error("Unexpected root subject"); + } + ``` +=== "Rust" + ```rust + use apcore::{Context, Identity}; + use apcore::errors::ModuleError; + use serde_json::Value; + use std::collections::HashMap; + + fn main() -> Result<(), ModuleError> { + let subject = Identity::new("user-123".into(), "user".into(), vec![], HashMap::new()) + .with_authority(Some(vec!["reports:read".into(), "reports:write".into()]), None)?; + let actor = Identity::new("reports-worker".into(), "service".into(), vec![], HashMap::new()); + let delegated = subject.delegate(actor, vec!["reports:read".into()])?; + let context = Context::create(Some(delegated), None, None, None, Value::Null, None); + assert_eq!(context.identity.as_ref().map(|i| i.root_subject().id()), Some("user-123")); + Ok(()) + } + ``` + +Authorize scoped identities with a nonempty top-level `scopes` condition on the matching ACL allow rule. The actor must hold every listed scope. `identity_types` and `roles` inspect the actor. `subject_types` and `subject_roles` inspect the root subject, and `max_delegation_depth` limits active links. Capability discovery applies the same scope rules as execution. + ### ContextFactory A `ContextFactory` turns a runtime-specific request (a Django `HttpRequest`, an Express `Request`, an Axum extractor) into a `Context`, extracting the identity on the way. @@ -301,7 +350,7 @@ The identity is included when a Context is serialized for cross-process transfer } ``` -Deserialization rebuilds the `Identity` from this object. See [Context Object §Serialization](./context-object.md#serialization). +Serialization adds `scopes`, `on_behalf_of`, and `issuer` when present. A parent identity uses the same wire fields as the actor. Deserialization verifies bounded depth and scope attenuation. Accept identity data as authority only after authenticating it at the host boundary. See [Context Object §Serialization](./context-object.md#serialization). ## Dependencies diff --git a/docs/guides/acl-configuration.md b/docs/guides/acl-configuration.md index de4e2ad4..5aae1dab 100644 --- a/docs/guides/acl-configuration.md +++ b/docs/guides/acl-configuration.md @@ -235,11 +235,34 @@ All keys in a `conditions` object must hold for the rule to match. |-----|-------------| | `roles` | The caller's `Identity` has at least one of the listed roles | | `identity_types` | The caller's identity type is one of the listed values | +| `scopes` | The current actor has every listed effective scope | +| `subject_types` | The root subject's identity type is one of the listed values | +| `subject_roles` | The root subject has at least one of the listed roles | +| `max_delegation_depth` | The number of active delegation links is at most this integer from 0 through 8 | | `max_call_depth` | The call chain is no deeper than this value | | `arguments` | The call's argument **keys** satisfy `has_key`, `has_all_keys` or `has_none_of` | | `$or` | Any of the listed condition objects holds | | `$not` | The wrapped condition object does not hold | +For an identity with explicit scopes, a grant requires the first matching allow rule to include a nonempty top-level `scopes` list. The rule can also constrain the current actor and the root subject independently. + +```yaml +version: "1.0" +default_effect: deny +audit: + enabled: true + include_denied: true +rules: + - callers: ["@external"] + targets: ["reports.read"] + effect: allow + conditions: + scopes: ["reports:read"] + identity_types: ["service"] + subject_roles: ["report_viewer"] + max_delegation_depth: 1 +``` + ```yaml # acl/global_acl.yaml version: "1.0" diff --git a/docs/index.md b/docs/index.md index 89a62129..ffbb26b2 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 revision 3) | -| Python SDK | `apcore` | `0.33.0` | `1.0.0a4` | -| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.4` | -| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.4` | +| Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `2.0.0` (draft revision 4) | +| Python SDK | `apcore` | `0.33.0` | `1.0.0a5` | +| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.5` | +| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.5` | 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/conformance.md b/docs/spec/conformance.md index 63891bff..9a1149ae 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 **100 cross-language fixture files** under `conformance/fixtures/` covering **1252 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 **101 cross-language fixture files** under `conformance/fixtures/` covering **1269 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 @@ -383,6 +383,7 @@ The repository ships **100 cross-language fixture files** under `conformance/fix | [`json_input_native_types`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/json_input_native_types.json) | 4 | A natively typed contract accepts the JSON strings its schema accepts — date-time, UUID, enum — and still rejects what the schema rejects (type-mapping §17.3, D-136) | | [`gate_step_configure`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/gate_step_configure.json) | 8 | `configure` cannot weaken `acl_check` / `approval_gate`: `ignore_errors: true`, `match_modules` and `pure: true` are rejected at load (spec §5.16.1, D-130) | | [`governance_state`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/governance_state.json) | 13 | `Executor.governance_state()` — configured vs. actually wired (spec §6.6.5) | +| [`identity_delegation`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/identity_delegation.json) | 17 | Trusted scope attenuation and delegated ACL authorization (spec §6.11) | | [`identity_system`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/identity_system.json) | 8 | Identity construction and propagation (spec §5.7) | | [`multi_root_discovery`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/multi_root_discovery.json) | 6 | `extensions.roots` multi-root discovery with namespace isolation (§9.1.1, D-70) | | [`middleware_hardening`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/middleware_hardening.json) | 11 | Context namespacing, CircuitBreaker | @@ -432,7 +433,7 @@ The repository ships **100 cross-language fixture files** under `conformance/fix | [`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** | **1252** | **100 fixtures** | +| **Total** | **1269** | **101 fixtures** | ### 8.2 Loading Fixtures from a Test Runner diff --git a/docs/spec/decision-register.md b/docs/spec/decision-register.md index fdc1f6a0..02f74a25 100644 --- a/docs/spec/decision-register.md +++ b/docs/spec/decision-register.md @@ -166,6 +166,7 @@ them. | D-132 | The specification follows three agreeing, correct implementations | In force | v1.62.0 | [divergence log](./2026-09-divergence-decisions.md#d-132-the-specification-follows-three-agreeing-correct-implementations) | | D-153 | Managed lifecycle binds admission, cancellation, and recovery to a generation | Draft | — | [Managed Module Lifecycle](./protocol-spec.md#1279-managed-module-lifecycle) | | D-154 | Capability discovery proves visibility before projecting metadata and rechecks access on every request | Draft | — | [ACL-aware capability discovery](./protocol-spec.md#acl-aware-capability-discovery) | +| D-155 | Trusted identities attenuate explicit scopes, and scoped ACL grants and approval credentials bind to the current authority | Draft | — | [Trusted identity delegation](./protocol-spec.md#trusted-identity-delegation) | | E-01 | `start_reaper` starts synchronously; only `stop()` is awaited | In force | — | [2026-09 audit log](./2026-09-decision-log.md#e-01-asynctaskmanagerstart_reaper-does-the-call-itself-need-to-be-awaited) | | E-02 | `APCore.discover` is sync in Python, async in TypeScript and Rust | In force | — | [2026-09 audit log](./2026-09-decision-log.md#e-02-apcorediscover-synchronous-in-all-languages-contradicted-two-of-three-implementations) | | E-03 | `ACL(rules=[…])` validates every rule it is handed | In force | v1.33.0 | [2026-09 audit log](./2026-09-decision-log.md#e-03-aclrules-did-not-re-validate-a-rule-mutated-before-its-first-construction) | diff --git a/docs/spec/protocol-spec.md b/docs/spec/protocol-spec.md index d6575bca..6fced5dd 100644 --- a/docs/spec/protocol-spec.md +++ b/docs/spec/protocol-spec.md @@ -8,8 +8,8 @@ description: "The canonical apcore protocol specification (RFC 2119): module, sc > Version: 2.0.0 > Status: Draft -> Draft Revision: 3 -> Last Updated: 2026-11-27 +> Draft Revision: 4 +> Last Updated: 2026-11-28 --- @@ -2490,6 +2490,17 @@ context_schema: attrs: type: object description: "Extension attributes (tenant_id, email, etc. business fields)" + scopes: + type: array + items: + type: string + description: "Optional effective scope set; an empty set grants no scoped authority (§6.11)" + on_behalf_of: + type: object + description: "Optional parent identity with the same shape, pointing toward the root subject (§6.11)" + issuer: + type: string + description: "Optional trusted issuer qualifier for the actor's identity namespace (§6.11)" # ====== Everything else ====== @@ -3871,8 +3882,12 @@ audit: | Field | Type | Description | |-------|------|-------------| -| `identity_types` | `list[string]` | Identity type must be in list | -| `roles` | `list[string]` | At least one role must overlap | +| `identity_types` | `list[string]` | The current actor type must be in the list | +| `roles` | `list[string]` | At least one current actor role must overlap | +| `scopes` | Nonempty `list[string]` | The current actor must have every listed effective scope (§6.11) | +| `subject_types` | Nonempty `list[string]` | The root subject type must be in the list (§6.11) | +| `subject_roles` | Nonempty `list[string]` | At least one root subject role must overlap (§6.11) | +| `max_delegation_depth` | `integer` (0–8) | The number of active delegation links must not exceed the threshold (§6.11) | | `max_call_depth` | `integer` | Call chain length must not exceed threshold | | `arguments` | `object` | Predicates over the call's argument **keys** (§6.1.7) | | `$or` | `list[object]` | Compound: passes if **any** sub-condition object passes (each sub-object's keys are AND-ed internally). Sub-objects **MAY** contain further compound operators. | @@ -4509,6 +4524,9 @@ Every `check()` **MUST** emit exactly one audit entry through the configured aud | `matched_rule_index` | `integer \| null` | Index of the matched rule in definition order | | `identity_type` | `string \| null` | Identity type from the context, when present | | `roles` | `list[string]` | Identity roles from the context; empty when absent | +| `actor_id` | `string` | Current actor ID for a scope-enabled identity (§6.11) | +| `subject_id` | `string` | Root subject ID for a scope-enabled identity (§6.11) | +| `delegation_depth` | `integer` | Active delegation depth for a scope-enabled identity (§6.11) | | `call_depth` | `integer \| null` | Length of `context.call_chain`, when present | | `trace_id` | `string \| null` | Trace ID from the context, when present | | `handler_error` | `string \| null` | Non-null **if and only if** a condition was unevaluable (§6.1.1). **MUST** name each unevaluable condition's **path** (§6.1.4) and the reason, ordered and separated as §6.1.1 rule 2 requires. | @@ -5069,6 +5087,26 @@ The Executor and APCore **MUST** expose idiomatic equivalents of `list_callable( A caller-aware adapter **MUST** use the same trusted context as its invocation path when applying discovery to its published modules. Standard MCP `tools/list` **MUST** retain the complete `inputSchema` of each eligible tool. Lightweight summaries and definition lookup **MUST** use the separate discovery API. MCP exposes `system.manifest.search` as a read-only query tool when the module is available to the requester. When the adapter publishes module documentation resources, listing and direct access **MUST** apply the same visibility. Transport control tools and ACL-gated management manifests retain their own authorization contracts. +### 6.11 Trusted Identity Delegation {#trusted-identity-delegation} + +An `Identity` **MAY** carry immutable `scopes`, `on_behalf_of`, and `issuer` fields. `scopes` is a set of nonempty, case-sensitive strings with no characters in the Unicode `White_Space` property. SDKs **MUST** normalize duplicate members. An absent scope set leaves an ordinary identity under the existing ACL contract. A present empty set explicitly grants zero scopes. The optional `issuer` qualifies the identity namespace and, when supplied, **MUST** be a nonempty string. Identity attributes remain separate from these fields. + +The Identity in the Context is the current actor. Each `on_behalf_of` link points toward the root subject that delegated authority. For a direct identity, the actor is also the root subject and delegation depth is zero. Trusted hosts **MAY** create a scoped root and derive a delegated identity from a trusted direct actor and an explicit requested scope set. Each requested scope **MUST** be present in the immediate parent's effective set and in the recipient's own ceiling if the supplied actor already carries one. Every linked identity **MUST** have an explicit scope set, including the parent of the first delegation. SDKs **MUST** reject cycles, malformed authority fields, widening, and chains deeper than eight active links. Repeated actor identifiers in a bounded, attenuating chain confer no additional authority. + +Context and identity restoration **MUST** validate the same structure and attenuation as local construction. The wire names are `scopes`, `on_behalf_of`, and `issuer`, with `on_behalf_of` containing a nested identity object. SDKs **MUST** omit absent fields and preserve the legacy wire shape for identities that omit all three. Callers **MUST NOT** treat successful deserialization as authentication or accept an untrusted caller's payload as the authority of an existing Context. + +For a scope-enabled identity, the first matching ACL allow rule **MUST** contain a nonempty, top-level `scopes` condition enforced by the stock predicate. Each listed scope **MUST** be present on the current actor. An otherwise matching allow without this grant **MUST** produce a deny, even if a later rule could grant access. Scope tests reachable only through compound conditions and an `allow` default **MUST NOT** grant access. Deny rules retain the ordinary condition and ordering semantics in §6.1 and §6.3. Conditions for `subject_types` and `subject_roles` evaluate against the root subject. `max_delegation_depth` evaluates against the active link count. An identity-dependent condition without a trusted identity **MUST NOT** match. + +The effective ACL configuration and pipeline **MUST** enforce scoped authority for execution, streaming, preflight, and discovery. When the Executor cannot establish that the scope gate applies, each of those paths **MUST** fail closed. Discovery uses the prospective caller frame in §6.10 and applies the same ordered semantics without emitting ACL audit entries. + +SDKs **MUST** bind delegation-sensitive cursors and approval resumption to a stable projection of the current actor, root subject, effective scopes and trusted active lineage. This projection includes security-relevant role memberships, identity types and issuer qualifiers, and excludes arbitrary attributes and token history. Final-input policy **MUST** receive a detached view of the trusted authority. A deployment **MAY** use a separate stable ownership projection for transport records, keyed on issuer-qualified actor and root subject. Reauthentication can carry the same owner, but current scopes **MUST** govern protected operations and scoped authority **MUST** participate in permission cache keys. + +A handler that can resume a pending approval for a scope-enabled identity **MUST** advertise support for authority scope and **MUST** verify the authority projection alongside the applicable invocation scope. The SDK **MUST NOT** issue a pending credential or attempt resumption for a scope-enabled identity when the handler lacks this capability. A handler **MUST NOT** grant access to or consume a record for a different authority. Final-scope pending approvals also require the capability specified in §7.2. Legacy approvals retain their existing invocation binding. + +ACL audit entries for scope-enabled identities **MUST** include `actor_id`, `subject_id`, and active `delegation_depth`. When an audit event carries a redacted identity snapshot, D-93 redaction **MUST** apply to attributes at every hop. The snapshot **MUST NOT** contain raw credentials. + +Adapters that opt into RFC 8693 JWT scope and actor projection **MUST** verify the signature, expected `iss` and `aud`, and required `exp` before accepting the projection. They **MUST** validate `nbf` and `iat` when supplied. The standard `scope` claim uses the scope-token string syntax in RFC 6749 §3.3. A deployment **MAY** map an additional provider claim whose value is a scope string or array of scope tokens. When both configured claims are present, their normalized sets **MUST** agree. At least one configured scope representation **MUST** be present. The top-level `sub` and outermost `act` claim yield at most one active Core link. Outer actor roles require an explicit trusted mapping. Nested `act` claims are history limited to a structurally validated depth of eight. Those claims **MUST NOT** contribute to Core roles, scope, active depth, approval, or ownership. A supplied credential that fails verification or the configured claim mapping **MUST** be rejected when projection is enabled. See [RFC 8693 §4.1](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.1) for the actor claim and [§4.2](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.2) for scope strings. + --- ## 7. Approval System @@ -5301,7 +5339,7 @@ When an evaluator is installed, the strategy **MUST** preserve the built-in auth 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. +Approval uses the same pending, timeout, and explicit denial results as Step 5. The final scope binds `caller_id`, canonical target ID, resolved module version, `canonical_args_digest`, and the trusted principal when present. It binds `(identity.type, identity.id)` for a legacy principal and additionally binds the authority projection in §6.11 for a scope-enabled principal. 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. @@ -10372,6 +10410,7 @@ The specification and the SDK have independent version numbers. `CHANGELOG.md` r | Version | Date | Summary | Records | |---|---|---|---| +| 2.0.0 (draft revision 4) | Unreleased | Define trusted identity delegation, ACL scope enforcement, and authority binding for discovery and approvals (§6.11, §7.4.1). | D-155, [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | | 2.0.0 (draft revision 3) | Unreleased | Add silent ACL visibility, caller-scoped summaries and schema lookup, and `system.manifest.search` (§6.10, §11.3). | D-154, [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) | diff --git a/planning/identity-delegation/plan.md b/planning/identity-delegation/plan.md index ee5ed1c1..d455b916 100644 --- a/planning/identity-delegation/plan.md +++ b/planning/identity-delegation/plan.md @@ -18,10 +18,12 @@ Expose actor ID, root subject ID and active delegation depth in the applicable a Make the scope and delegation mapping opt-in in all six authenticators. Require a verified signature, expected issuer and audience, and applicable time claims before mapping a configured scope or delegation. A present malformed delegation or invalid configured scope fails authentication. Keep the current claim format when mapping is disabled. Parse `scope` and configured provider `scp` according to their declared formats. If both configured representations are present, require the normalized sets to agree. -Map the verified top-level subject and the outermost actor to one active Core delegation edge. The token scopes are the current ceiling. Derive actor roles only from explicitly mapped claims about the current actor. Bound validation of nested actor claims with the same structural limit. Preserve their identifiers for bounded audit history where configured. The active authorization depth remains one regardless of that history. Verify this distinction against [RFC 8693 §4.1](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.1) and the token scope representation in [RFC 8693 §4.2](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.2). +Map the verified top-level subject and the outermost actor to one active Core delegation edge. The token scopes are the current ceiling. Derive actor roles only from explicitly mapped claims about the current actor. Validate nested actor claims against the same structural limit and discard the history after validation. The active authorization depth remains one regardless of that history. See [RFC 8693 §4.1](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.1) for the actor distinction and [RFC 8693 §4.2](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.2) for the scope representation. Bind transport and stored task ownership to the issuer-qualified actor and effective subject where supported. Keep that ownership key separate from the authority projection. Apply current scope to each protected operation. Include current authority in permission caches and recheck governed result retrieval and resumption so narrower claims do not inherit stale permissions. Equivalent token refresh may retain the same owner. +Bind live MCP session reuse to equivalent authority so a narrowed credential cannot cancel an earlier invocation or answer its approval. An actor with changed scopes or roles opens a new session and can still access its stored tasks when the current Core decision permits it. + ## Candidate boundary Complete the Core contract first, then the six adapter mappings, then installed-artifact validation. The SDK wrappers reuse the current Context, ACL, policy, and approval entry points. This candidate covers resource-server consumption of credential claims and local trusted delegation. Opening a PR, merging a candidate, and releasing packages are separate steps. diff --git a/planning/identity-delegation/state.json b/planning/identity-delegation/state.json index 4ce902cd..b399efb7 100644 --- a/planning/identity-delegation/state.json +++ b/planning/identity-delegation/state.json @@ -6,32 +6,31 @@ "execution_order": ["shared-contract", "core-sdks", "surfaces", "verification"], "progress": { "total_tasks": 4, - "completed": 0, - "in_progress": 0, - "pending": 3, + "completed": 2, + "in_progress": 1, + "pending": 1, "skipped": 0, - "blocked": 1 + "blocked": 0 }, "tasks": [ { "id": "shared-contract", "file": "tasks/shared-contract.md", "title": "Shared delegation contract and conformance", - "status": "blocked", - "blocker": "Maintainer approval of the proposed protocol draft revision" + "status": "completed" }, { "id": "core-sdks", "file": "tasks/core-sdks.md", "title": "Python, TypeScript, and Rust delegated identity", - "status": "pending", + "status": "completed", "dependencies": ["shared-contract"] }, { "id": "surfaces", "file": "tasks/surfaces.md", "title": "MCP and A2A verified claim mapping", - "status": "pending", + "status": "in_progress", "dependencies": ["core-sdks"] }, { diff --git a/python/apcore-conformance.yaml b/python/apcore-conformance.yaml index d8fbb247..c6cf5bd3 100644 --- a/python/apcore-conformance.yaml +++ b/python/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-python - version: 1.0.0a4 + version: 1.0.0a5 language: python spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/python/pyproject.toml b/python/pyproject.toml index c62faef0..8f0d57dd 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "apcore" -version = "1.0.0a4" +version = "1.0.0a5" 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/_post_validation_policy.py b/python/src/apcore/_post_validation_policy.py index 26a0103b..76252b56 100644 --- a/python/src/apcore/_post_validation_policy.py +++ b/python/src/apcore/_post_validation_policy.py @@ -64,7 +64,9 @@ def __init__(self, ctx: PipelineContext, version: str | None) -> None: self.version = version self.caller_id = ctx.context.caller_id try: - self.identity = deepcopy(ctx.context.identity) + identity = ctx.context.identity + self.authority_key = identity.authority_key() if identity is not None else None + self.identity = deepcopy(identity) except Exception: raise PolicyEvaluationError() from None self.arguments: dict[str, Any] | None = None @@ -79,11 +81,13 @@ def capture(self, ctx: PipelineContext) -> None: self.arguments = deepcopy(arguments) def _check_binding(self, ctx: PipelineContext) -> None: + identity = ctx.context.identity 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 + or identity != self.identity + or (self.authority_key is not None and (identity is None or identity.authority_key() != self.authority_key)) ): raise PolicyEvaluationError() diff --git a/python/src/apcore/acl.py b/python/src/apcore/acl.py index 76a1c3a5..520887b7 100644 --- a/python/src/apcore/acl.py +++ b/python/src/apcore/acl.py @@ -23,17 +23,22 @@ _ArgumentsHandler, _IdentityTypesHandler, _MaxCallDepthHandler, + _MaxDelegationDepthHandler, _NotHandler, _NotHandlerAsync, _OrHandler, _OrHandlerAsync, _projection_var, _RolesHandler, + _ScopesHandler, + _SubjectRolesHandler, + _SubjectTypesHandler, join_condition_path, validate_arguments_condition, + validate_identity_condition, ) from apcore.config import Config -from apcore.context import Context +from apcore.context import Context, _identity_audit_fields from apcore.errors import ACLRuleError from apcore.utils.pattern import match_pattern @@ -272,8 +277,7 @@ def _pattern_array_fault(patterns: Any) -> str | None: if patterns[0] == "$not" and operands != 1: if operands == 0: return ( - "'$not' at index 0 MUST be followed by exactly one pattern, and none was given. " - f"{_EMPTY_ARITY_REMEDY}" + f"'$not' at index 0 MUST be followed by exactly one pattern, and none was given. {_EMPTY_ARITY_REMEDY}" ) return ( f"'$not' at index 0 MUST be followed by exactly one pattern, got {operands}. Through spec " @@ -334,7 +338,7 @@ def _validate_approval(approval: Any, effect: Any, *, where: str) -> None: """ if approval not in _APPROVAL_VALUES: raise ACLRuleError( - f"{where} has invalid approval {approval!r}, must be " f"{APPROVAL_REQUIRED!r} or {APPROVAL_NOT_REQUIRED!r}" + f"{where} has invalid approval {approval!r}, must be {APPROVAL_REQUIRED!r} or {APPROVAL_NOT_REQUIRED!r}" ) if approval == APPROVAL_REQUIRED and effect == "deny": raise ACLRuleError( @@ -485,6 +489,9 @@ class AuditEntry: # ``decision`` is a string downstream consumers parse, and a third value # would break every existing parser. approval_required: bool = False + actor_id: str | None = None + subject_id: str | None = None + delegation_depth: int | None = None @dataclass(frozen=True) @@ -530,10 +537,15 @@ class VisibilityDecision: approval_conditional: bool = False +_BUILTIN_SCOPES = _ScopesHandler() _VISIBILITY_HANDLERS = { "identity_types": _IdentityTypesHandler(), "roles": _RolesHandler(), "max_call_depth": _MaxCallDepthHandler(), + "scopes": _BUILTIN_SCOPES, + "subject_types": _SubjectTypesHandler(), + "subject_roles": _SubjectRolesHandler(), + "max_delegation_depth": _MaxDelegationDepthHandler(), } _MATCH = ConditionOutcome.SATISFIED _NO_MATCH = ConditionOutcome.UNSATISFIED @@ -715,7 +727,11 @@ def _emit_default(self, entry: AuditEntry) -> None: config = self._config or {} level = _AUDIT_LEVELS.get(str(config.get("log_level", "info")), logging.INFO) try: - _audit_logger_default.log(level, AUDIT_EVENT_NAME, extra={"apcore_audit": asdict(entry)}) + fields = asdict(entry) + if entry.actor_id is None: + for key in ("actor_id", "subject_id", "delegation_depth"): + del fields[key] + _audit_logger_default.log(level, AUDIT_EVENT_NAME, extra={"apcore_audit": fields}) except Exception as exc: # noqa: BLE001 — a logging handler can fail too self._report_failure(exc) @@ -1286,6 +1302,10 @@ def _precheck_conditions(cls, conditions: Any, *, async_path: bool, path_prefix: for suffix, reason in validate_arguments_condition(value): faults.append(_Fault(path=f"{path}{suffix}", key=key, reason=reason)) else: + fault = validate_identity_condition(key, value) + if fault is not None: + faults.append(_Fault(path=path, key=key, reason=fault)) + continue sync_resolvable = key in cls._condition_handlers async_resolvable = sync_resolvable or key in cls._async_condition_handlers resolvable = async_resolvable if async_path else sync_resolvable @@ -1720,6 +1740,7 @@ def check_access( pending_approval=pending_approval, audit_sink=audit_sink, context=context, + async_path=False, ) finally: _projection_var.reset(projection_token) @@ -1823,6 +1844,7 @@ async def async_check_access( pending_approval=pending_approval, audit_sink=audit_sink, context=context, + async_path=True, ) finally: _projection_var.reset(projection_token) @@ -1840,6 +1862,8 @@ def evaluate_visibility( if rule.effect != "allow" and outcomes != {_NO_MATCH}: return VisibilityDecision(False) if _MATCH in outcomes: + if not self._scope_grant(rule, context, async_path=True): + return VisibilityDecision(False) possible_approvals.update( pending or rule.approval == APPROVAL_REQUIRED for pending in pending_approvals ) @@ -1848,7 +1872,7 @@ def evaluate_visibility( if _FAULT in outcomes and self._raises_pending_approval(rule): pending_approvals = (pending_approvals | {True}) if _NO_MATCH in outcomes else {True} else: - if default_effect != "allow": + if default_effect != "allow" or not self._scope_grant(None, context, async_path=True): return VisibilityDecision(False) possible_approvals.update(pending_approvals) @@ -1915,6 +1939,16 @@ def _snapshot(self, caller_id: str | None) -> tuple[str, list[ACLRule], str, "_A with self._lock: return effective_caller, list(self._rules), self._default_effect, self._audit_sink + @classmethod + def _scope_grant(cls, rule: ACLRule | None, context: Context | None, *, async_path: bool) -> bool: + if context is None or context.identity is None or context.identity.scopes is None: + return True + if rule is None or not isinstance(rule.conditions, dict): + return False + stock_handler = cls._condition_handlers.get("scopes") + handler = cls._async_condition_handlers.get("scopes", stock_handler) if async_path else stock_handler + return handler is _BUILTIN_SCOPES and _BUILTIN_SCOPES.evaluate(rule.conditions.get("scopes"), context) + def _finalize_check( self, *, @@ -1928,6 +1962,7 @@ def _finalize_check( pending_approval: bool, audit_sink: "_AuditSink", context: Context | None, + async_path: bool, ) -> AccessDecision: """Log the decision, emit an audit entry, and return the structured result. @@ -1982,6 +2017,8 @@ def _finalize_check( # clears it — "denied *and* put it to a human" is the same meaningless # state §6.1.6 rejects on a rule — while ``matched_rule_index`` keeps # naming the rule that actually decided, not the unevaluable one. + if access == "allow" and not self._scope_grant(matched_rule, context, async_path=async_path): + access = "deny" approval_required = access == "allow" and (approval_required or pending_approval) self._logger.debug( @@ -2062,13 +2099,14 @@ def _build_audit_entry( roles: tuple[str, ...] = () call_depth: int | None = None trace_id: str | None = None + identity = context.identity if context is not None else None if context is not None: trace_id = context.trace_id call_depth = len(context.call_chain) - if context.identity is not None: - identity_type = context.identity.type - roles = tuple(context.identity.roles) + if identity is not None: + identity_type = identity.type + roles = tuple(identity.roles) return AuditEntry( timestamp=datetime.now(timezone.utc).isoformat(), @@ -2084,6 +2122,7 @@ def _build_audit_entry( trace_id=trace_id, handler_error=_handler_error_message(), approval_required=approval_required, + **(_identity_audit_fields(context) if context is not None else {}), ) def _match_pattern(self, pattern: str, value: str, context: Context | None = None) -> bool: diff --git a/python/src/apcore/acl_handlers.py b/python/src/apcore/acl_handlers.py index e281df5f..5e081b83 100644 --- a/python/src/apcore/acl_handlers.py +++ b/python/src/apcore/acl_handlers.py @@ -18,7 +18,7 @@ from enum import Enum from typing import Any, Awaitable, Callable, ClassVar, Mapping, Protocol, Union, runtime_checkable -from apcore.context import Context +from apcore.context import Context, _MAX_DELEGATION_DEPTH, _valid_scope_literal __all__ = [ "ConditionOutcome", @@ -176,6 +176,55 @@ def evaluate(self, value: Any, context: Context) -> bool: return bool(set(context.identity.roles) & set(value)) +class _ScopesHandler: + """Require every literal scope in an explicit, nonempty list.""" + + def evaluate(self, value: Any, context: Context) -> bool: + identity = context.identity + return ( + identity is not None + and identity.scopes is not None + and _is_nonempty_string_list(value) + and set(value).issubset(identity.scopes) + ) + + +def _is_nonempty_string_list(value: Any) -> bool: + return isinstance(value, list) and bool(value) and all(isinstance(item, str) and item for item in value) + + +class _SubjectTypesHandler: + def evaluate(self, value: Any, context: Context) -> bool: + return context.identity is not None and context.identity.root_subject.type in value + + +class _SubjectRolesHandler: + def evaluate(self, value: Any, context: Context) -> bool: + return context.identity is not None and any(role in value for role in context.identity.root_subject.roles) + + +class _MaxDelegationDepthHandler: + def evaluate(self, value: Any, context: Context) -> bool: + threshold = _delegation_depth_threshold(value) + return context.identity is not None and threshold is not None and context.identity.delegation_depth <= threshold + + +def _delegation_depth_threshold(value: Any) -> int | None: + if isinstance(value, float) and value.is_integer(): + value = int(value) + return value if type(value) is int and 0 <= value <= _MAX_DELEGATION_DEPTH else None + + +def validate_identity_condition(key: str, value: Any) -> str | None: + if key in ("scopes", "subject_roles", "subject_types") and not _is_nonempty_string_list(value): + return "value must be a nonempty list of nonempty strings" + if key == "scopes" and not all(_valid_scope_literal(scope) for scope in value): + return "scope strings must not contain whitespace" + if key == "max_delegation_depth" and _delegation_depth_threshold(value) is None: + return "value must be an integer from 0 through 8" + return None + + class _MaxCallDepthHandler: """Check call chain length does not exceed threshold.""" diff --git a/python/src/apcore/approval.py b/python/src/apcore/approval.py index 4bc778f8..6f812deb 100644 --- a/python/src/apcore/approval.py +++ b/python/src/apcore/approval.py @@ -57,6 +57,7 @@ class ApprovalRequest: ``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. + authority_key: Native binding for the current scoped identity. """ module_id: str @@ -69,6 +70,7 @@ class ApprovalRequest: action: str = "" module_version: str | None = None canonical_args_digest: str | None = field(default=None, repr=False) + authority_key: str | None = field(default=None, repr=False) @dataclass(frozen=True) @@ -118,6 +120,8 @@ class ScopedApprovalHandler(ApprovalHandler, Protocol): Set ``supports_final_scope = True`` when issuance and resumption verify the version and canonical argument digest as well as the existing scope. + Set ``supports_authority_scope = True`` when issuance and resumption + also bind the authority key before consuming the approval. """ async def check_approval_for_call(self, approval_id: str, request: ApprovalRequest) -> ApprovalResult: diff --git a/python/src/apcore/builtin_steps.py b/python/src/apcore/builtin_steps.py index 357aad21..48a786cd 100644 --- a/python/src/apcore/builtin_steps.py +++ b/python/src/apcore/builtin_steps.py @@ -23,9 +23,10 @@ import pydantic from apcore._post_validation_policy import _evaluate_policy, _PolicyInvocation, _safe_rule_id +from apcore.acl import ACL from apcore.approval import ApprovalRequest, ApprovalResult, ScopedApprovalHandler from apcore.cancel import CancelToken, ExecutionCancelledError -from apcore.context import Context, GovernanceProjection +from apcore.context import Context, GovernanceProjection, _identity_audit_fields from apcore.context_keys import _current_trace_span from apcore.decorator import FunctionModule from apcore.errors import ( @@ -620,6 +621,11 @@ def acl(self) -> Any | None: return self._acl async def execute(self, ctx: PipelineContext) -> StepResult: + identity = getattr(ctx.context, "identity", None) + if getattr(identity, "scopes", None) is not None and type(self._acl) is not ACL: + caller_id = ctx.context.caller_id + self._emit_denied(caller_id, ctx.module_id, ctx.context, ctx.dry_run) + raise ACLDeniedError(caller_id=caller_id, target_id=ctx.module_id) if self._acl is None: return StepResult(action="continue") @@ -710,6 +716,7 @@ def _emit_denied(self, caller_id: str, module_id: str, ctx: Context, dry_run: bo "caller_id": caller_id, "reason": "ACL denied", "trace_id": getattr(ctx, "trace_id", None), + **_identity_audit_fields(ctx), }, ) ) @@ -720,6 +727,12 @@ def _emit_denied(self, caller_id: str, module_id: str, ctx: Context, dry_run: bo # --------------------------------------------------------------------------- +def _supports_authority_scope(handler: Any, authority_key: str | None) -> bool: + return authority_key is None or ( + isinstance(handler, ScopedApprovalHandler) and getattr(handler, "supports_authority_scope", False) is True + ) + + class BuiltinApprovalGate(_GovernanceGateFields): """Approval handler flow for modules requiring approval. @@ -857,6 +870,11 @@ async def execute(self, ctx: PipelineContext) -> StepResult: ctx._policy_annotations = self._effective_annotations(governance, decision, required) return StepResult(action="continue") + identity = getattr(ctx.context, "identity", None) + if approval_token is not None and not required and getattr(identity, "scopes", None) is not None: + result = ApprovalResult(status="rejected", reason="No approval applies to the current scoped invocation") + return self._finish_approval(ctx, result, approval_token) + if not required: return StepResult(action="continue") @@ -871,12 +889,15 @@ async def execute(self, ctx: PipelineContext) -> StepResult: return StepResult(action="continue") request = self._request(ctx, self._effective_annotations(governance, decision, required), ctx.inputs) + supports_scope = _supports_authority_scope(self._handler, request.authority_key) if approval_token is None: result = await self._handler.request_approval(request) - elif isinstance(self._handler, ScopedApprovalHandler): + elif supports_scope and 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") + if result.status == "pending" and not supports_scope: + result = ApprovalResult(status="rejected", reason="The approval handler does not bind scoped authority") return self._finish_approval(ctx, result, approval_token) @staticmethod @@ -887,10 +908,12 @@ def _request( invocation: _PolicyInvocation | None = None, ) -> ApprovalRequest: context = ctx.context - if invocation is not None: + identity = context.identity if invocation is None else invocation.identity + authority_key = identity.authority_key() if invocation is None and identity is not None else None + if invocation is not None or authority_key is not None: context = copy(context) context.call_chain = list(context.call_chain) - context.identity = deepcopy(invocation.identity) + context.identity = deepcopy(identity) return ApprovalRequest( module_id=ctx.module_id, arguments=deepcopy(arguments), @@ -902,6 +925,7 @@ def _request( 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, + authority_key=invocation.authority_key if invocation is not None else authority_key, ) async def _authorize_final( @@ -912,7 +936,9 @@ async def _authorize_final( return handler = self._handler supports_final_scope = ( - isinstance(handler, ScopedApprovalHandler) and getattr(handler, "supports_final_scope", False) is True + isinstance(handler, ScopedApprovalHandler) + and getattr(handler, "supports_final_scope", False) is True + and _supports_authority_scope(handler, invocation.authority_key) ) 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") @@ -1042,6 +1068,7 @@ def _emit_policy_audit(self, decision: PolicyDecision, ctx: Context) -> None: "needs_approval": decision.needs_approval, "reason": (rule.reason if rule else None) or "", "trace_id": getattr(ctx, "trace_id", None), + **_identity_audit_fields(ctx), }, ) ) @@ -1074,6 +1101,7 @@ def _emit_audit( "approved_by": result.approved_by or "", "reason": result.reason or "", "approval_id": audit_id or "", + **_identity_audit_fields(ctx), } ) if self._event_emitter is not None: @@ -1094,6 +1122,7 @@ def _emit_audit( "reason": result.reason, "approval_id": audit_id, "trace_id": getattr(ctx, "trace_id", None), + **_identity_audit_fields(ctx), }, ) ) @@ -1406,6 +1435,7 @@ async def execute(self, ctx: PipelineContext) -> StepResult: identity=deepcopy(invocation.identity), arguments=deepcopy(arguments), sensitive_fields=fields, + authority_key=invocation.authority_key, ) ctx._policy_evaluation_active = True try: @@ -1434,7 +1464,12 @@ async def execute(self, ctx: PipelineContext) -> StepResult: 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)} + data = { + "decision": decision, + "rule_id": rule_id, + "sensitive_fields": list(fields), + **_identity_audit_fields(ctx.context), + } span = _current_trace_span(ctx.context, include_parent=True) if span is not None: span.events.append({"name": "apcore.policy.decision", **data}) diff --git a/python/src/apcore/capabilities.py b/python/src/apcore/capabilities.py index 5b897b70..5f748207 100644 --- a/python/src/apcore/capabilities.py +++ b/python/src/apcore/capabilities.py @@ -137,14 +137,7 @@ def digest(self) -> str: scope = { "caller_id": self.caller_id, "call_chain": list(self.call_chain), - "identity": None - if identity is None - else { - "id": identity.id, - "type": identity.type, - "roles": list(identity.roles), - "attrs": identity.attrs, - }, + "identity": identity._authority_projection() if identity is not None else None, } try: return _argument_digest(scope) @@ -354,6 +347,8 @@ def _still_current(executor: Executor, module_id: str, version_hint: str | None, def _visibility_decision(acl: ACL | None, module_id: str, context: Context) -> VisibilityDecision: + if context.identity is not None and context.identity.scopes is not None and type(acl) is not ACL: + return VisibilityDecision(False) if acl is None: return VisibilityDecision(True) evaluator = getattr(acl, "evaluate_visibility", None) diff --git a/python/src/apcore/context.py b/python/src/apcore/context.py index 168e5fe5..f529de30 100644 --- a/python/src/apcore/context.py +++ b/python/src/apcore/context.py @@ -4,12 +4,15 @@ import logging import uuid -from dataclasses import dataclass, field +from collections.abc import Sequence +from copy import deepcopy +from dataclasses import dataclass, field, replace from types import MappingProxyType from typing import TYPE_CHECKING, Any, Generic, Mapping, Protocol, TypeVar, runtime_checkable from apcore.cancel import CancelToken from apcore.context_keys import TRACING_SAMPLED, _current_trace_span, _middleware_data +from apcore.errors import InvalidInputError from apcore.trace_context import _valid_inbound_parent_id if TYPE_CHECKING: @@ -21,6 +24,34 @@ __all__ = ["Context", "Identity", "ContextFactory", "GovernanceProjection"] T = TypeVar("T") +_MAX_DELEGATION_DEPTH = 8 + + +def _valid_scope_literal(scope: Any) -> bool: + return ( + isinstance(scope, str) + and bool(scope) + and not any(char.isspace() and char not in "\x1c\x1d\x1e\x1f" for char in scope) + ) + + +def _normalize_scopes(scopes: Sequence[str]) -> tuple[str, ...]: + if isinstance(scopes, (str, bytes)) or not isinstance(scopes, (list, tuple)): + raise InvalidInputError("Identity.scopes must be an array of scope strings") + if not all(_valid_scope_literal(scope) for scope in scopes): + raise InvalidInputError("Identity.scopes must contain nonempty strings without whitespace") + return tuple(sorted(set(scopes))) + + +def _identity_audit_fields(context: Context) -> dict[str, Any]: + identity = getattr(context, "identity", None) + if not isinstance(identity, Identity) or identity.scopes is None: + return {} + return { + "actor_id": identity.id, + "subject_id": identity.root_subject.id, + "delegation_depth": identity.delegation_depth, + } @dataclass(frozen=True) @@ -31,8 +62,22 @@ class Identity: type: str = "user" roles: tuple[str, ...] = field(default_factory=tuple) attrs: dict[str, Any] = field(default_factory=dict) + scopes: Sequence[str] | None = field(default=None, kw_only=True) + on_behalf_of: Identity | None = field(default=None, kw_only=True) + issuer: str | None = field(default=None, kw_only=True) def __post_init__(self) -> None: + scoped = self.scopes is not None or self.on_behalf_of is not None + if scoped and ( + not isinstance(self.id, str) + or not self.id + or not isinstance(self.type, str) + or not self.type + or not isinstance(self.roles, (list, tuple)) + or any(not isinstance(role, str) or not role for role in self.roles) + ): + raise InvalidInputError("Scoped identities require a nonempty ID and type and valid roles") + # Ensure attrs is a dict if None was passed, and protect against mutation # of the original dict passed to the constructor. if not isinstance(self.attrs, dict): @@ -52,6 +97,133 @@ def __post_init__(self) -> None: elif not isinstance(self.roles, tuple): object.__setattr__(self, "roles", tuple(self.roles)) + if self.scopes is not None: + object.__setattr__(self, "scopes", _normalize_scopes(self.scopes)) + if self.issuer is not None and (not isinstance(self.issuer, str) or not self.issuer): + raise InvalidInputError("Identity.issuer must be a nonempty string") + self._lineage() + + def _lineage(self) -> tuple[Identity, ...]: + chain: list[Identity] = [self] + seen = {id(self)} + current = self + while current.on_behalf_of is not None: + parent = current.on_behalf_of + if not isinstance(parent, Identity) or id(parent) in seen or len(chain) > _MAX_DELEGATION_DEPTH: + raise InvalidInputError("Identity delegation must be acyclic and at most eight edges deep") + if current.scopes is None or parent.scopes is None or not set(current.scopes).issubset(parent.scopes): + raise InvalidInputError("Identity delegation requires explicit scopes within the parent ceiling") + chain.append(parent) + seen.add(id(parent)) + current = parent + return tuple(chain) + + @property + def root_subject(self) -> Identity: + """Return the root subject of the active authority chain.""" + return self._lineage()[-1] + + @property + def delegation_depth(self) -> int: + """Return the number of active delegation edges.""" + return len(self._lineage()) - 1 + + def delegate(self, actor: Identity, scopes: Sequence[str]) -> Identity: + """Create a new actor identity with attenuated local authority.""" + if not isinstance(actor, Identity) or actor.on_behalf_of is not None: + raise InvalidInputError("Identity delegation requires a direct actor") + requested = _normalize_scopes(scopes) + if actor.scopes is not None and not set(requested).issubset(actor.scopes): + raise InvalidInputError("Requested scopes exceed the actor's own scope ceiling") + return replace(actor, scopes=requested, on_behalf_of=self) + + def authority_key(self) -> str | None: + """Return the native authority binding for a scope-enabled identity.""" + if self.scopes is None: + return None + from apcore._post_validation_policy import _argument_digest + + return _argument_digest(self._authority_projection()) + + def owner_key(self) -> str | None: + """Return the actor and root-subject binding independently of scopes.""" + if self.scopes is None: + return None + from apcore._post_validation_policy import _argument_digest + + subject = self.root_subject + return _argument_digest( + { + "actor": [self.issuer, self.type, self.id], + "subject": [subject.issuer, subject.type, subject.id], + } + ) + + def _authority_projection(self) -> dict[str, Any]: + if self.scopes is None: + return self._to_wire(detach_attrs=True) + subject: dict[str, Any] | None = None + for identity in reversed(self._lineage()): + node: dict[str, Any] = { + "id": identity.id, + "type": identity.type, + "roles": sorted(set(identity.roles)), + "scopes": list(identity.scopes) if identity.scopes is not None else None, + } + if identity.issuer is not None: + node["issuer"] = identity.issuer + if subject is not None: + node["on_behalf_of"] = subject + subject = node + assert subject is not None + return subject + + def _to_wire(self, *, detach_attrs: bool = False) -> dict[str, Any]: + self._lineage() + return self._encode_wire(detach_attrs) + + def _encode_wire(self, detach_attrs: bool) -> dict[str, Any]: + result = { + "id": self.id, + "type": self.type, + "roles": list(self.roles), + "attrs": deepcopy(self.attrs) if detach_attrs else dict(self.attrs), + } + if self.scopes is not None: + result["scopes"] = list(self.scopes) + if self.on_behalf_of is not None: + result["on_behalf_of"] = self.on_behalf_of._encode_wire(detach_attrs) + if self.issuer is not None: + result["issuer"] = self.issuer + return result + + @classmethod + def _from_wire(cls, value: Any, depth: int = 0) -> Identity: + prefix = "Context.deserialize" + if not isinstance(value, dict): + raise InvalidInputError(f"{prefix}: 'identity' must be an object, got {type(value).__name__}") + if depth > _MAX_DELEGATION_DEPTH: + raise InvalidInputError("Identity delegation must be acyclic and at most eight edges deep") + if not isinstance(value.get("id"), str) or not value["id"]: + raise InvalidInputError(f"{prefix}: 'identity.id' is required and must be a non-empty string") + roles = value.get("roles", ()) if "scopes" in value or "on_behalf_of" in value else value.get("roles") or () + if not isinstance(roles, (list, tuple)): + raise InvalidInputError(f"{prefix}: 'identity.roles' must be a list of strings") + attrs = value.get("attrs") or {} + if not isinstance(attrs, dict): + raise InvalidInputError(f"{prefix}: 'identity.attrs' must be an object") + if "issuer" in value and value["issuer"] is None: + raise InvalidInputError("Identity.issuer must be a nonempty string") + return cls( + value["id"], + value.get("type", "user"), + tuple(roles), + attrs, + scopes=_normalize_scopes(value["scopes"]) if "scopes" in value else None, + on_behalf_of=cls._from_wire(value["on_behalf_of"], depth + 1) if "on_behalf_of" in value else None, + issuer=value.get("issuer"), + ) + def get_attr(self, key: str, default: Any = None) -> Any: """Get an attribute value by key. @@ -289,15 +461,7 @@ def serialize(self) -> dict[str, Any]: "caller_id": self.caller_id, "call_chain": list(self.call_chain), } - if self.identity is not None: - result["identity"] = { - "id": self.identity.id, - "type": self.identity.type, - "roles": list(self.identity.roles), - "attrs": dict(self.identity.attrs), - } - else: - result["identity"] = None + result["identity"] = self.identity._to_wire() if self.identity is not None else None if self.redacted_inputs is not None: result["redacted_inputs"] = dict(self.redacted_inputs) if self.redacted_output is not None: @@ -321,50 +485,12 @@ def deserialize(cls, data: dict[str, Any]) -> Context: version, ) - identity = None - if data.get("identity") is not None: - # CTX-1. This used to index `id_data["id"]` unguarded, so a - # malformed wire identity left a bare `KeyError: 'id'` or - # `TypeError: string indices must be integers` escaping a method - # documented to "best-effort proceed" — neither is an apcore error, - # neither carries a registry code, and neither is what a caller - # catching ModuleError around a deserialize is prepared for. - # apcore-typescript coerces every field and apcore-rust drops the - # identity; both report rather than crash on a builtin. - from apcore.errors import InvalidInputError - - id_data = data["identity"] - if not isinstance(id_data, dict): - raise InvalidInputError( - message=f"Context.deserialize: 'identity' must be an object, got {type(id_data).__name__}", - ) - if not isinstance(id_data.get("id"), str) or not id_data["id"]: - raise InvalidInputError( - message="Context.deserialize: 'identity.id' is required and must be a non-empty string", - ) - roles = id_data.get("roles") or () - if isinstance(roles, (str, bytes)) or not isinstance(roles, (list, tuple)): - raise InvalidInputError( - message="Context.deserialize: 'identity.roles' must be a list of strings", - ) - attrs = id_data.get("attrs") or {} - if not isinstance(attrs, dict): - raise InvalidInputError( - message="Context.deserialize: 'identity.attrs' must be an object", - ) - identity = Identity( - id=id_data["id"], - type=id_data.get("type", "user"), - roles=tuple(roles), - attrs=attrs, - ) - return cls( trace_id=data.get("trace_id", ""), caller_id=data.get("caller_id"), call_chain=list(data.get("call_chain", [])), executor=None, - identity=identity, + identity=Identity._from_wire(data["identity"]) if data.get("identity") is not None else None, redacted_inputs=data.get("redacted_inputs"), redacted_output=data.get("redacted_output"), data=dict(data.get("data", {})), diff --git a/python/src/apcore/executor.py b/python/src/apcore/executor.py index 9b76b2da..921856b2 100644 --- a/python/src/apcore/executor.py +++ b/python/src/apcore/executor.py @@ -875,6 +875,10 @@ async def validate_async( # Convert pipeline trace to PreflightResult checks if trace is not None: checks.extend(_trace_to_checks(trace, pipe_ctx.preflight_errors)) + scoped = getattr(getattr(context, "identity", None), "scopes", None) is not None + if scoped and not pipe_ctx._acl_allowed and not any(c.check == _ACL_CHECK and not c.passed for c in checks): + error = ACLDeniedError(context.caller_id, module_id) + checks.append(PreflightCheckResult(check=_ACL_CHECK, passed=False, error=error.to_dict())) # Detect requires_approval (preflight reports, does not enforce). # @@ -1218,6 +1222,11 @@ async def _recover_from_call_error( # typed cause is what middleware on_error handlers and the final # caller observe — not the chain-machinery wrapper. original = exc.original if isinstance(exc, MiddlewareChainError) else exc + if ( + isinstance(original, ACLDeniedError) + and getattr(getattr(ctx_obj, "identity", None), "scopes", None) is not None + ): + recoverable = False wrapped = propagate_error(original, module_id, ctx_obj) if ctx_obj else original executed_mw = pipe_ctx.executed_middlewares if recoverable and executed_mw: @@ -1808,18 +1817,14 @@ def ungated_approval_modules(self) -> list[str]: enforcing_gates = [ step for step in self._strategy.steps - if isinstance(step, BuiltinApprovalGate) - and (step.handler is not None or step.policy.strict) + if isinstance(step, BuiltinApprovalGate) and (step.handler is not None or step.policy.strict) ] ungated: list[str] = [] for module_id in self._registry.list(visibility=["public", "hidden"]): annotations = self._module_governance_annotations(module_id) if annotations is None or not annotations.requires_approval: continue - if not any( - gate.policy.resolve(module_id, annotations).needs_approval - for gate in enforcing_gates - ): + if not any(gate.policy.resolve(module_id, annotations).needs_approval for gate in enforcing_gates): ungated.append(module_id) return ungated diff --git a/python/src/apcore/pipeline.py b/python/src/apcore/pipeline.py index 5ce29438..75de8a0b 100644 --- a/python/src/apcore/pipeline.py +++ b/python/src/apcore/pipeline.py @@ -13,8 +13,8 @@ from collections.abc import Sequence from typing import TYPE_CHECKING, Any, Callable, Protocol, runtime_checkable -from apcore.context import _APPROVAL_TOKEN_KEY -from apcore.errors import InvalidInputError, ModuleError, ModuleTimeoutError, PolicyEvaluationError +from apcore.context import Identity, _APPROVAL_TOKEN_KEY +from apcore.errors import ACLDeniedError, InvalidInputError, ModuleError, ModuleTimeoutError, PolicyEvaluationError from apcore.middleware.manager import MiddlewareChainError from apcore.utils.pattern import match_pattern @@ -677,6 +677,29 @@ async def _invoke_step_cleanup_hooks( class PipelineEngine: """Executes a pipeline strategy step by step.""" + @staticmethod + def _scoped_gate_index(strategy: ExecutionStrategy, ctx: PipelineContext) -> int: + from apcore.acl import ACL + from apcore.builtin_steps import BuiltinACLCheck, BuiltinContextCreation, BuiltinModuleLookup + + context_ready = False + lookup_ready = False + for index, step in enumerate(strategy.steps): + patterns = getattr(step, "match_modules", None) + if patterns is not None and not _any_match(patterns, ctx.module_id): + continue + if step.name == "execute": + break + if type(step) is BuiltinContextCreation: + context_ready = True + elif type(step) is BuiltinModuleLookup: + lookup_ready = context_ready + elif isinstance(step, BuiltinACLCheck): + if type(step) is BuiltinACLCheck and type(step.acl) is ACL and lookup_ready and step.pure: + return index + break + raise ACLDeniedError(ctx.context.caller_id, ctx.module_id) + async def run( self, strategy: ExecutionStrategy, @@ -720,11 +743,19 @@ async def _run_steps( unavailable: set[str] = set() effective_run_until = run_until or ctx.run_until observation = ctx._stream_observation + identity = getattr(ctx.context, "identity", None) + gate_index = None + if isinstance(identity, Identity) and identity.scopes is not None and not ctx._acl_allowed: + gate_index = self._scoped_gate_index(strategy, ctx) + scoped_target = ctx.module_id + scoped_module = None i = 0 # Index-based loop (not for-each) to support skip_to. while i < len(steps): step = steps[i] + if gate_index is not None and i > gate_index and not ctx._acl_allowed and not ctx.dry_run: + raise ACLDeniedError(ctx.context.caller_id, scoped_target) if observation is not None and observation.defer_step(step.name, ctx): i += 1 continue @@ -841,6 +872,15 @@ async def _run_steps( observation.before_step(step.name, ctx) recovered = False try: + if gate_index is not None and i >= gate_index: + if ( + ctx.context.identity is not identity + or ctx.module_id != scoped_target + or (i > gate_index and ctx.module is not scoped_module) + ): + raise ACLDeniedError(ctx.context.caller_id, scoped_target) + if i == gate_index: + scoped_module = ctx.module if timeout_ms > 0: result = await asyncio.wait_for( step.execute(ctx), @@ -912,6 +952,7 @@ async def _run_steps( getattr(step, "_fail_closed_on_error", False) or ctx._policy_pending or isinstance(exc, PolicyEvaluationError) + or (gate_index is not None and isinstance(exc, ACLDeniedError)) ) recovery: Any = None if error_mws: @@ -1076,12 +1117,16 @@ async def _run_steps( context=ctx, ) if effective_run_until(state): + if gate_index is not None and not ctx._acl_allowed: + raise ACLDeniedError(ctx.context.caller_id, scoped_target) trace.success = True trace.total_duration_ms = (time.monotonic() - start) * 1000 return ctx.output, trace i += 1 + if gate_index is not None and not ctx._acl_allowed and not ctx.dry_run: + raise ACLDeniedError(ctx.context.caller_id, scoped_target) trace.success = not any(item.result.action == "abort" for item in trace.steps if not item.skipped) trace.total_duration_ms = (time.monotonic() - start) * 1000 # Use ctx.output — it's the most up-to-date (middleware_after may modify it) diff --git a/python/src/apcore/policy.py b/python/src/apcore/policy.py index fb69884f..312d8780 100644 --- a/python/src/apcore/policy.py +++ b/python/src/apcore/policy.py @@ -55,6 +55,7 @@ class PolicyEvaluationRequest: identity: Identity | None = field(repr=False) arguments: dict[str, Any] = field(repr=False) sensitive_fields: tuple[str, ...] + authority_key: str | None = field(default=None, repr=False) @dataclass(frozen=True) diff --git a/python/src/apcore/sys_modules/identity.py b/python/src/apcore/sys_modules/identity.py index 106c7c06..d04d2890 100644 --- a/python/src/apcore/sys_modules/identity.py +++ b/python/src/apcore/sys_modules/identity.py @@ -9,6 +9,8 @@ from typing import Any +from apcore.context import Identity, _identity_audit_fields + #: Identity ``attrs`` whose names match one of these case-insensitive #: substrings are replaced with the literal string ``""`` in #: audit-event payloads (Issue #45.2). This list is intentionally a @@ -50,6 +52,18 @@ def _redact_identity_attr(name: str, value: Any) -> Any: return value +def _redact_nested(value: Any, ancestors: frozenset[int]) -> Any: + if not isinstance(value, (dict, list, tuple)): + return value + if id(value) in ancestors: + return _IDENTITY_REDACTED_TOKEN + ancestors = ancestors | {id(value)} + if isinstance(value, dict): + return {key: _redact_nested(_redact_identity_attr(str(key), child), ancestors) for key, child in value.items()} + children = [_redact_nested(child, ancestors) for child in value] + return tuple(children) if isinstance(value, tuple) else children + + def _extract_identity_dict(context: Any) -> dict[str, Any] | None: """Return a redacted-safe dict view of ``context.identity`` or ``None``. @@ -67,6 +81,10 @@ def _extract_identity_dict(context: Any) -> dict[str, Any] | None: identity = getattr(context, "identity", None) if identity is None: return None + return _identity_snapshot(identity) + + +def _identity_snapshot(identity: Any) -> dict[str, Any]: snapshot: dict[str, Any] = { "id": getattr(identity, "id", None), "type": getattr(identity, "type", None), @@ -74,19 +92,22 @@ def _extract_identity_dict(context: Any) -> dict[str, Any] | None: roles = list(getattr(identity, "roles", ()) or ()) if roles: snapshot["roles"] = roles + parent = identity.on_behalf_of if isinstance(identity, Identity) else None + if isinstance(parent, Identity): + snapshot["on_behalf_of"] = _identity_snapshot(parent) attrs = getattr(identity, "attrs", None) or {} if isinstance(attrs, dict): for key, value in attrs.items(): # Don't shadow the canonical id/type/roles keys. if key in snapshot: continue - snapshot[key] = _redact_identity_attr(key, value) + snapshot[key] = _redact_nested(_redact_identity_attr(str(key), value), frozenset()) return snapshot def _audit_payload_extras(context: Any) -> dict[str, Any]: """Build the ``caller_id`` (+ optional ``identity``) fragment for audit events.""" - extras: dict[str, Any] = {"caller_id": _extract_caller_id(context)} + extras: dict[str, Any] = {"caller_id": _extract_caller_id(context), **_identity_audit_fields(context)} identity_dict = _extract_identity_dict(context) if identity_dict is not None: extras["identity"] = identity_dict diff --git a/python/tests/conformance/test_identity_delegation.py b/python/tests/conformance/test_identity_delegation.py new file mode 100644 index 00000000..b975a02d --- /dev/null +++ b/python/tests/conformance/test_identity_delegation.py @@ -0,0 +1,38 @@ +"""Drive the canonical identity delegation fixture through public entry points.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from apcore.acl import ACL, ACLRule +from apcore.context import Context +from apcore.errors import InvalidInputError + +from .canonical_fixtures import load_fixture + +CASES = load_fixture("identity_delegation.json")["test_cases"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("case", CASES, ids=[case["id"] for case in CASES]) +async def test_identity_delegation(case: dict[str, Any]) -> None: + inputs, expected = case["input"], case["expected"] + if not expected["valid"]: + with pytest.raises(InvalidInputError): + Context.deserialize({"identity": inputs["identity"]}) + return + + context = Context.deserialize({"identity": inputs["identity"]}) + assert context.identity is not None + assert context.identity.delegation_depth == expected["depth"] + assert context.identity.root_subject.id == expected["subject_id"] + if "effect" in expected: + acl = ACL( + [ACLRule(**rule) for rule in inputs["rules"]], + default_effect=inputs.get("default_effect", "deny"), + ) + assert acl.check_access(None, "delegation.target", context).access == expected["effect"] + assert (await acl.async_check_access(None, "delegation.target", context)).access == expected["effect"] + assert acl.evaluate_visibility(None, "delegation.target", context).visible is (expected["effect"] == "allow") diff --git a/python/tests/test_identity_delegation.py b/python/tests/test_identity_delegation.py new file mode 100644 index 00000000..1b1a2fe1 --- /dev/null +++ b/python/tests/test_identity_delegation.py @@ -0,0 +1,174 @@ +"""Observable contracts for scoped and delegated callers.""" + +from __future__ import annotations + +import pytest + +from apcore.acl import ACL, ACLRule +from apcore.approval import ApprovalRequest, ApprovalResult +from apcore.context import Context, Identity +from apcore.errors import ACLDeniedError, ApprovalDeniedError, ApprovalPendingError, InvalidInputError +from apcore.executor import Executor +from apcore.policy import PolicyEvaluationRequest, PolicyVerdict +from apcore.registry import Registry +from apcore.sys_modules.identity import _audit_payload_extras + + +class _Module: + description = "Delegation test" + input_schema = {"type": "object"} + output_schema = {"type": "object"} + + async def execute(self, inputs, context): + return {"actor": context.identity.id} + + +def _executor(*rules: ACLRule) -> Executor: + registry = Registry() + registry.register("test.run", _Module()) + return Executor(registry, acl=ACL(list(rules), default_effect="allow") if rules else None) + + +def _allow(conditions: dict | None = None) -> ACLRule: + return ACLRule(["*"], ["test.run"], "allow", conditions=conditions) + + +def test_identity_delegation_round_trips_and_preserves_legacy_wire() -> None: + legacy = Identity("root", "user", ("owner",), {"note": "ordinary"}) + assert "scopes" not in Context.create(legacy).serialize()["identity"] + assert legacy.authority_key() is None + assert legacy.owner_key() is None + scopes = ["write", "read", "read"] + root = Identity("root", "user", ("owner",), {}, scopes=scopes, issuer="https://issuer.example") + scopes.clear() + actor = Identity("agent", "ai", ("worker",)) + delegated = root.delegate(actor, []) + assert root.scopes == ("read", "write") + assert delegated.scopes == () + assert delegated.root_subject == root + assert delegated.delegation_depth == 1 + assert Context.deserialize(Context.create(delegated).serialize()).identity == delegated + assert delegated.owner_key() == root.delegate(actor, ["read"]).owner_key() + assert delegated.authority_key() != root.delegate(actor, ["read"]).authority_key() + + +def test_identity_delegation_rejects_malformed_authority() -> None: + root = Identity("same", scopes=["read"]) + delegated = root + for _ in range(8): + delegated = delegated.delegate(Identity("same"), ["read"]) + assert delegated.delegation_depth == 8 + for bad in ( + lambda: delegated.delegate(Identity("same"), []), + lambda: root.delegate(Identity("same"), ["write"]), + lambda: root.delegate(Identity("same", scopes=[]), ["read"]), + lambda: Identity("same").delegate(Identity("same"), []), + lambda: Identity("same", on_behalf_of=root), + lambda: Identity("", scopes=["read"]), + lambda: Identity("same", "", scopes=["read"]), + lambda: Identity("same", roles=("",), scopes=["read"]), + ): + with pytest.raises(InvalidInputError): + bad() + encoded = Context.create(root).serialize() + encoded["identity"]["on_behalf_of"] = encoded["identity"] + with pytest.raises(InvalidInputError): + Context.deserialize(encoded) + + +@pytest.mark.asyncio +async def test_scoped_executor_and_discovery_require_first_stock_scope_grant() -> None: + root = Identity("root", "user", ("owner",), scopes=["Read", "write"]) + caller = root.delegate(Identity("agent", "ai", ("worker",)), ["Read"]) + grant = _allow( + { + "scopes": ["Read"], + "roles": ["worker"], + "subject_roles": ["owner"], + "subject_types": ["user"], + "max_delegation_depth": 1, + } + ) + with _executor(grant) as executor: + assert await executor.call_async("test.run", {}, Context.create(caller)) == {"actor": "agent"} + assert executor.get_callable_descriptor("test.run", Context.create(caller)) is not None + for rules in ( + (), + (_allow(), grant), + (_allow({"scopes": ["Read", "write"]}),), + (_allow({"$or": [{"scopes": ["Read"]}]}),), + ): + with _executor(*rules) as executor: + with pytest.raises(ACLDeniedError): + await executor.call_async("test.run", {}, Context.create(caller)) + assert not (await executor.validate_async("test.run", {}, Context.create(caller))).valid + assert executor.get_callable_descriptor("test.run", Context.create(caller)) is None + with pytest.raises(ACLDeniedError): + async for _ in executor.stream("test.run", {}, Context.create(caller)): + pytest.fail("Scoped principal streamed without a scope grant") + + +def test_audit_recursively_redacts_identity_attributes() -> None: + root = Identity("root", attrs={"profile": {"Authorization": "signed", "name": "root"}}, scopes=["read"]) + caller = root.delegate(Identity("agent", attrs={"outer": [{"session_token": "signed"}]}), ["read"]) + audit = _audit_payload_extras(Context.create(caller)) + assert (audit["actor_id"], audit["subject_id"], audit["delegation_depth"]) == ("agent", "root", 1) + nested = audit["identity"] + assert nested["outer"] == [{"session_token": ""}] + assert nested["on_behalf_of"]["profile"] == {"Authorization": "", "name": "root"} + + +@pytest.mark.asyncio +async def test_scoped_approvals_bind_detached_authority_before_consuming() -> None: + class Handler: + supports_final_scope = True + supports_authority_scope = True + binding: str | None = None + + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: + self.binding = request.authority_key + assert request.context.identity is not None + assert request.context.identity.attrs["key"] == "private" + return ApprovalResult("pending", approval_id="pending-credential") + + async def check_approval(self, approval_id: str) -> ApprovalResult: + pytest.fail("Approval must bind the current request") + + async def check_approval_for_call(self, approval_id: str, request: ApprovalRequest) -> ApprovalResult: + if approval_id != "pending-credential" or self.binding is None or request.authority_key != self.binding: + return ApprovalResult("rejected") + self.binding = None + return ApprovalResult("approved") + + class Evaluate: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + assert request.identity is not None + assert request.identity.root_subject.attrs.get("secret") in ("private", None) + assert request.authority_key == request.identity.authority_key() + request.identity.attrs["detached"] = True + return PolicyVerdict("require_approval") + + registry = Registry() + registry.register("test.run", _Module()) + handler = Handler() + actor = Identity("actor", attrs={"key": "private"}) + root = Identity("root", attrs={"secret": "private"}, scopes=["read", "write"]) + original = root.delegate(actor, ["read", "write"]) + with Executor( + registry, + acl=ACL([_allow({"scopes": ["read"]})]), + approval_handler=handler, + policy_evaluator=Evaluate(), + ) as executor: + with pytest.raises(ApprovalPendingError): + await executor.call_async("test.run", {}, Context.create(original)) + for changed in (root.delegate(actor, ["read"]), Identity("other", scopes=["read"]).delegate(actor, ["read"])): + with pytest.raises(ApprovalDeniedError): + await executor.call_async( + "test.run", {"_approval_token": "pending-credential"}, Context.create(changed) + ) + assert handler.binding == original.authority_key() + assert await executor.call_async( + "test.run", {"_approval_token": "pending-credential"}, Context.create(original) + ) == {"actor": "actor"} + assert handler.binding is None diff --git a/python/uv.lock b/python/uv.lock index 3cfdb6cf..a2dbcb2c 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -199,7 +199,7 @@ wheels = [ [[package]] name = "apcore" -version = "1.0.0a4" +version = "1.0.0a5" source = { editable = "." } dependencies = [ { name = "jsonschema" }, diff --git a/rust/Cargo.lock b/rust/Cargo.lock index db7e30ff..4e08a693 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -42,7 +42,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.4" +version = "1.0.0-alpha.5" dependencies = [ "async-stream", "async-trait", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index a75722e0..accfa234 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore" -version = "1.0.0-alpha.4" +version = "1.0.0-alpha.5" 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 42abe97d..716e12f5 100644 --- a/rust/apcore-conformance.yaml +++ b/rust/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-rust - version: 1.0.0-alpha.4 + version: 1.0.0-alpha.5 language: rust spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/rust/src/acl.rs b/rust/src/acl.rs index 52311074..f4b872ed 100644 --- a/rust/src/acl.rs +++ b/rust/src/acl.rs @@ -10,8 +10,8 @@ use std::sync::{Arc, Once}; use crate::acl_handlers::{ evaluate_conditions_async_outcome as handlers_evaluate_conditions_async_outcome, - precheck_conditions, register_builtin_handlers, ConditionOutcome, PrecheckPath, RuleFault, - CONDITION_HANDLERS, + has_stock_scope_grant, precheck_conditions, register_builtin_handlers, ConditionOutcome, + PrecheckPath, RuleFault, CONDITION_HANDLERS, }; use crate::context::Context; use crate::errors::{ErrorCode, ModuleError}; @@ -636,6 +636,12 @@ pub struct AuditEntry { pub matched_rule_index: Option, #[serde(skip_serializing_if = "Option::is_none")] pub identity_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub actor_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subject_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub delegation_depth: Option, #[serde(default)] pub roles: Vec, #[serde(skip_serializing_if = "Option::is_none")] @@ -809,6 +815,9 @@ impl AuditSink { matched_rule = ?entry.matched_rule, matched_rule_index = ?entry.matched_rule_index, identity_type = ?entry.identity_type, + actor_id = ?entry.actor_id, + subject_id = ?entry.subject_id, + delegation_depth = ?entry.delegation_depth, roles = ?entry.roles, call_depth = ?entry.call_depth, trace_id = ?entry.trace_id, @@ -1790,6 +1799,9 @@ impl ACL { _ if rule.effect != "allow" => return None, _ => {} } + if !Self::scope_permits(rule.conditions.as_ref(), ctx, PrecheckPath::Async) { + return None; + } possible_with_approval |= requires_approval || pending_approval; possible_without_approval |= !(requires_approval || pending_approval); if decision == DiscoveryRule::Match { @@ -1799,12 +1811,13 @@ impl ACL { )); } } - (self.default_effect == "allow").then(|| { - AccessHint::from_approval_outcomes( - possible_with_approval || pending_approval, - possible_without_approval || !pending_approval, - ) - }) + (self.default_effect == "allow" && Self::scope_permits(None, ctx, PrecheckPath::Async)) + .then(|| { + AccessHint::from_approval_outcomes( + possible_with_approval || pending_approval, + possible_without_approval || !pending_approval, + ) + }) } fn discovery_rule( @@ -1870,24 +1883,24 @@ impl ACL { match self.matches_rule(idx, rule, caller, target_id, ctx) { RuleMatch::Match => { return self.finalize_rule_match( - idx, - rule, + (idx, rule), caller, target_id, ctx, pending_approval, + PrecheckPath::Sync, ) } RuleMatch::Unevaluable => { match Self::resolve_unevaluable_rule(idx, rule, &paths_before) { UnevaluableResolution::TakesEffect => { return self.finalize_rule_match( - idx, - rule, + (idx, rule), caller, target_id, ctx, pending_approval, + PrecheckPath::Sync, ) } UnevaluableResolution::StepsAside { @@ -2338,6 +2351,7 @@ impl ACL { // requirement (§6.1.1 rule 5): it is reached only when the rule list is // EMPTY, and a requirement can only be raised by a rule. There is // nothing to carry, so no parameter to carry it. + let default_effect = Self::scope_default(default_effect, ctx); let entry = self.build_audit_entry( caller, target_id, @@ -2361,13 +2375,14 @@ impl ACL { /// construction. fn finalize_rule_match( &self, - idx: usize, - rule: &ACLRule, + matched: (usize, &ACLRule), caller: &str, target_id: &str, ctx: Option<&Context>, pending_approval: bool, + path: PrecheckPath, ) -> AccessDecision { + let (idx, rule) = matched; // §6.9 row 1: the matched rule determines `access`; the approval // requirement is that rule's own UNION any pending one (§6.1.1 rule 5), // which may therefore originate in a rule that did not match. @@ -2378,12 +2393,18 @@ impl ACL { // not going to run, so there is nothing to put to a human. // `matched_rule_index` still names the rule that actually decided // rather than the unevaluable one. - let approval_required = - rule.effect == "allow" && (rule.approval_required() || pending_approval); + let effect = if rule.effect == "allow" + && !Self::scope_permits(rule.conditions.as_ref(), ctx, path) + { + "deny" + } else { + &rule.effect + }; + let approval_required = effect == "allow" && (rule.approval_required() || pending_approval); let entry = self.build_audit_entry( caller, target_id, - &rule.effect, + effect, "rule_match", rule.description.as_deref(), Some(idx), @@ -2391,12 +2412,7 @@ impl ACL { ctx, ); self.emit_audit(&entry); - AccessDecision::new( - rule.effect.clone(), - approval_required, - Some(idx), - "rule_match", - ) + AccessDecision::new(effect, approval_required, Some(idx), "rule_match") } /// Audit + return for the no-rule-matched path. Shared by `check` and @@ -2420,6 +2436,7 @@ impl ACL { // carry it. The result is `approval_required: true` with // `matched_rule_index: None`, which is a legal combination since // v1.29.0. A `deny` default clears it, per `finalize_rule_match`. + let default_effect = Self::scope_default(default_effect, ctx); let approval_required = default_effect == "allow" && pending_approval; let entry = self.build_audit_entry( caller, @@ -2435,6 +2452,28 @@ impl ACL { AccessDecision::new(default_effect, approval_required, None, "default_effect") } + fn scope_permits( + conditions: Option<&serde_json::Value>, + ctx: Option<&Context>, + path: PrecheckPath, + ) -> bool { + ctx.is_none_or(|ctx| { + ctx.identity + .as_ref() + .and_then(crate::Identity::scopes) + .is_none() + || has_stock_scope_grant(conditions, ctx, path) + }) + } + + fn scope_default<'a>(effect: &'a str, ctx: Option<&Context>) -> &'a str { + if Self::scope_permits(None, ctx, PrecheckPath::Sync) { + effect + } else { + "deny" + } + } + /// Build an audit entry from the check parameters and context. #[allow(clippy::too_many_arguments)] #[allow(clippy::unused_self)] // method must be on `&self` for trait-object dispatch consistency @@ -2449,6 +2488,8 @@ impl ACL { approval_required: bool, ctx: Option<&Context>, ) -> AuditEntry { + let identity = ctx.and_then(|ctx| ctx.identity.as_ref()); + let scoped = identity.filter(|identity| identity.scopes().is_some()); AuditEntry { approval_required, timestamp: Utc::now().to_rfc3339(), @@ -2458,11 +2499,11 @@ impl ACL { reason: reason.to_string(), matched_rule: matched_rule_desc.map(std::string::ToString::to_string), matched_rule_index, - identity_type: ctx - .and_then(|c| c.identity.as_ref().map(|id| id.identity_type().to_string())), - roles: ctx - .and_then(|c| c.identity.as_ref().map(|id| id.roles().to_vec())) - .unwrap_or_default(), + identity_type: identity.map(|id| id.identity_type().to_string()), + actor_id: scoped.map(|id| id.id().to_string()), + subject_id: scoped.map(|id| id.root_subject().id().to_string()), + delegation_depth: scoped.map(crate::Identity::delegation_depth), + roles: identity.map(|id| id.roles().to_vec()).unwrap_or_default(), call_depth: ctx.map(|c| c.call_chain.len()), trace_id: ctx.map(|c| c.trace_id.clone()), // Read the per-call handler-error slot populated by @@ -2555,24 +2596,24 @@ impl ACL { { RuleMatch::Match => { return self.finalize_rule_match( - idx, - rule, + (idx, rule), caller, target_id, ctx, pending_approval, + PrecheckPath::Async, ) } RuleMatch::Unevaluable => { match Self::resolve_unevaluable_rule(idx, rule, &paths_before) { UnevaluableResolution::TakesEffect => { return self.finalize_rule_match( - idx, - rule, + (idx, rule), caller, target_id, ctx, pending_approval, + PrecheckPath::Async, ) } UnevaluableResolution::StepsAside { diff --git a/rust/src/acl_handlers.rs b/rust/src/acl_handlers.rs index f1d298c3..0e4c5741 100644 --- a/rust/src/acl_handlers.rs +++ b/rust/src/acl_handlers.rs @@ -729,6 +729,126 @@ impl ACLConditionHandler for RolesHandler { } } +struct ScopesHandler; + +#[async_trait] +impl ACLConditionHandler for ScopesHandler { + async fn evaluate(&self, value: &Value, ctx: &Context) -> bool { + scopes_match(value, ctx) + } +} + +fn scopes_match(value: &Value, ctx: &Context) -> bool { + let Some(scopes) = ctx.identity.as_ref().and_then(crate::Identity::scopes) else { + return false; + }; + value.as_array().is_some_and(|required| { + !required.is_empty() + && required.iter().all(|value| { + value.as_str().is_some_and(|scope| { + crate::context::valid_scope_literal(scope) + && scopes.iter().any(|held| held == scope) + }) + }) + }) +} + +pub(crate) fn has_stock_scope_grant( + conditions: Option<&Value>, + ctx: &Context, + path: PrecheckPath, +) -> bool { + let Some(required) = conditions.and_then(|conditions| conditions.get("scopes")) else { + return false; + }; + let stock = match path { + PrecheckPath::Sync => CONDITION_HANDLERS + .read() + .get("scopes") + .is_some_and(|handler| Arc::ptr_eq(handler, &DISCOVERY_SCOPES)), + PrecheckPath::Async => stock_discovery_handler("scopes").is_some(), + }; + stock && scopes_match(required, ctx) +} + +struct SubjectTypesHandler; + +#[async_trait] +impl ACLConditionHandler for SubjectTypesHandler { + async fn evaluate(&self, value: &Value, ctx: &Context) -> bool { + ctx.identity + .as_ref() + .zip(value.as_array()) + .is_some_and(|(identity, types)| { + let subject = identity.root_subject(); + types + .iter() + .filter_map(Value::as_str) + .any(|kind| kind == subject.identity_type()) + }) + } +} + +struct SubjectRolesHandler; + +#[async_trait] +impl ACLConditionHandler for SubjectRolesHandler { + async fn evaluate(&self, value: &Value, ctx: &Context) -> bool { + ctx.identity + .as_ref() + .zip(value.as_array()) + .is_some_and(|(identity, roles)| { + let subject = identity.root_subject(); + roles + .iter() + .filter_map(Value::as_str) + .any(|role| subject.roles().iter().any(|held| held == role)) + }) + } +} + +struct MaxDelegationDepthHandler; + +#[async_trait] +impl ACLConditionHandler for MaxDelegationDepthHandler { + async fn evaluate(&self, value: &Value, ctx: &Context) -> bool { + ctx.identity + .as_ref() + .zip(delegation_threshold(value)) + .is_some_and(|(identity, max)| identity.delegation_depth() as u64 <= max) + } +} + +fn delegation_threshold(value: &Value) -> Option { + integral_threshold(value) + .filter(|threshold| *threshold <= crate::context::MAX_DELEGATION_DEPTH as u64) +} + +fn identity_condition_fault(key: &str, value: &Value) -> Option<&'static str> { + match key { + "scopes" | "subject_roles" | "subject_types" => { + let Some(items) = value.as_array().filter(|items| { + !items.is_empty() + && items + .iter() + .all(|item| item.as_str().is_some_and(|item| !item.is_empty())) + }) else { + return Some("value must be a nonempty list of nonempty strings"); + }; + (key == "scopes" + && !items + .iter() + .filter_map(Value::as_str) + .all(crate::context::valid_scope_literal)) + .then_some("scope strings must not contain whitespace") + } + "max_delegation_depth" if delegation_threshold(value).is_none() => { + Some("value must be an integer from zero to eight") + } + _ => None, + } +} + /// Extract a non-negative integer threshold from a JSON number, accepting /// integral floats (`5.0` → `5`) but rejecting non-integral floats (`5.5`). /// @@ -1224,20 +1344,14 @@ fn collect_condition_faults( )); } } - // §6.1.7's `arguments` is the one leaf whose operand the precheck - // CAN judge. Its predicate vocabulary is closed by the spec and - // there is no registration point for it, so the shape of a - // well-formed operand is knowable without running anything — - // which is what makes it structural rather than a handler's own - // business. Being in the precheck also means `validate_rules()` - // reports a broken predicate, and that a structurally broken - // `deny` rule is unevaluable even for a context-less call, which - // is §6.1.4's whole point. + // These closed operand contracts can be validated without + // running a handler, even when there is no caller context. "arguments" => collect_argument_faults(value, &key_path, out), - // Every other leaf handler is the authority on its own value, and - // asking it would mean running it — which the precheck must not - // do. Those value faults surface at execution instead. - _ => {} + _ => { + if let Some(reason) = identity_condition_fault(key, value) { + out.push(structural_fault(key_path, Some(key), reason)); + } + } } } } @@ -1301,6 +1415,14 @@ static DISCOVERY_IDENTITY_TYPES: LazyLock> = LazyLock::new(|| Arc::new(IdentityTypesHandler)); static DISCOVERY_ROLES: LazyLock> = LazyLock::new(|| Arc::new(RolesHandler)); +static DISCOVERY_SCOPES: LazyLock> = + LazyLock::new(|| Arc::new(ScopesHandler)); +static DISCOVERY_SUBJECT_TYPES: LazyLock> = + LazyLock::new(|| Arc::new(SubjectTypesHandler)); +static DISCOVERY_SUBJECT_ROLES: LazyLock> = + LazyLock::new(|| Arc::new(SubjectRolesHandler)); +static DISCOVERY_MAX_DELEGATION_DEPTH: LazyLock> = + LazyLock::new(|| Arc::new(MaxDelegationDepthHandler)); static DISCOVERY_MAX_CALL_DEPTH: LazyLock> = LazyLock::new(|| Arc::new(MaxCallDepthHandler)); static DISCOVERY_OR: LazyLock> = @@ -1312,6 +1434,10 @@ fn stock_discovery_handler(key: &str) -> Option<&'static Arc &*DISCOVERY_IDENTITY_TYPES, "roles" => &*DISCOVERY_ROLES, + "scopes" => &*DISCOVERY_SCOPES, + "subject_types" => &*DISCOVERY_SUBJECT_TYPES, + "subject_roles" => &*DISCOVERY_SUBJECT_ROLES, + "max_delegation_depth" => &*DISCOVERY_MAX_DELEGATION_DEPTH, "max_call_depth" => &*DISCOVERY_MAX_CALL_DEPTH, "$or" => &*DISCOVERY_OR, "$not" => &*DISCOVERY_NOT, @@ -1369,6 +1495,12 @@ fn discovery_condition(key: &str, value: &Value, ctx: &Context) -> Condit pub fn register_builtin_handlers() { seed_condition("identity_types", || Arc::clone(&DISCOVERY_IDENTITY_TYPES)); seed_condition("roles", || Arc::clone(&DISCOVERY_ROLES)); + seed_condition("scopes", || Arc::clone(&DISCOVERY_SCOPES)); + seed_condition("subject_types", || Arc::clone(&DISCOVERY_SUBJECT_TYPES)); + seed_condition("subject_roles", || Arc::clone(&DISCOVERY_SUBJECT_ROLES)); + seed_condition("max_delegation_depth", || { + Arc::clone(&DISCOVERY_MAX_DELEGATION_DEPTH) + }); seed_condition("max_call_depth", || Arc::clone(&DISCOVERY_MAX_CALL_DEPTH)); // §6.1.7: `arguments` is part of the language §6.1 already defines, not a // mechanism beside it, so it is seeded here with the other built-ins and @@ -1645,9 +1777,9 @@ mod tests { ); assert_eq!( body.matches("seed_condition(").count() + body.matches("seed_async_condition(").count(), - 8, - "expected all eight built-in registrations to be seeded — four \ - sync-only handlers plus the two mode-matched compound pairs:\n{body}" + 12, + "expected all twelve built-in registrations to be seeded — eight \ + sync handlers plus the two mode-matched compound pairs:\n{body}" ); } diff --git a/rust/src/approval.rs b/rust/src/approval.rs index 7a472355..5c467e88 100644 --- a/rust/src/approval.rs +++ b/rust/src/approval.rs @@ -63,6 +63,14 @@ pub struct ApprovalRequest { pub tags: Vec, } +impl ApprovalRequest { + /// Authority to bind when issuing or consuming a durable approval. + #[must_use] + pub fn authority_key(&self) -> Option { + self.context.as_ref()?.identity.as_ref()?.authority_key() + } +} + /// Outcome of an approval request. /// /// Marked `#[non_exhaustive]` (issue #24) so a future spec revision can add a @@ -163,6 +171,12 @@ pub trait ApprovalHandler: Send + Sync + std::fmt::Debug { false } + /// Whether durable approvals are atomically bound to the current authority. + /// An immediate decision does not require this capability. + fn supports_authority_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 e927450a..18689c99 100644 --- a/rust/src/builtin_steps.rs +++ b/rust/src/builtin_steps.rs @@ -451,14 +451,18 @@ impl Step for BuiltinACLCheck { // (allows are high-volume and already covered by tracing spans). if !ctx.dry_run { if let Some(emitter) = ctx.event_emitter.clone() { + let mut data = serde_json::json!({ + "module_id": ctx.module_id, + "caller_id": caller_id, + "reason": "ACL denied", + "trace_id": ctx.context.trace_id, + }); + if let Some(identity) = &ctx.context.identity { + identity.enrich_principal_audit(&mut data); + } let event = ApCoreEvent::with_module( "apcore.acl.denied", - serde_json::json!({ - "module_id": ctx.module_id, - "caller_id": caller_id, - "reason": "ACL denied", - "trace_id": ctx.context.trace_id, - }), + data, ctx.module_id.clone(), "warn", ); @@ -470,7 +474,9 @@ impl Step for BuiltinACLCheck { &ctx.module_id, )); } + ctx.record_scope_grant(); } + ctx.require_scope_grant()?; Ok(StepResult::continue_step()) } } @@ -530,16 +536,20 @@ impl BuiltinApprovalGate { } else { "warn" }; + let mut data = serde_json::json!({ + "module_id": ctx.module_id, + "status": result.status, + "approved_by": result.approved_by, + "reason": result.reason, + "approval_id": audit_id, + "trace_id": ctx.context.trace_id, + }); + if let Some(identity) = &ctx.context.identity { + identity.enrich_principal_audit(&mut data); + } let event = ApCoreEvent::with_module( "apcore.approval.decision", - serde_json::json!({ - "module_id": ctx.module_id, - "status": result.status, - "approved_by": result.approved_by, - "reason": result.reason, - "approval_id": audit_id, - "trace_id": ctx.context.trace_id, - }), + data, ctx.module_id.clone(), severity, ); @@ -691,6 +701,8 @@ impl BuiltinApprovalGate { ) -> Result<(), ModuleError> { const UNSUPPORTED_FINAL: &str = "The approval handler does not support final-scope resumption"; + const UNSUPPORTED_AUTHORITY: &str = + "The approval handler does not bind durable approvals to current authority"; let approval_token = ctx.take_approval_credential()?; let final_scope = digest.is_some(); if final_scope && approval_token.is_some() && !handler.supports_final_scope() { @@ -715,6 +727,10 @@ impl BuiltinApprovalGate { description: (!description.is_empty()).then(|| description.to_owned()), tags: module.tags(), }; + let authority_scope = request.authority_key().is_some(); + if authority_scope && approval_token.is_some() && !handler.supports_authority_scope() { + return Err(Self::reject_unavailable_handler(ctx, UNSUPPORTED_AUTHORITY).await); + } let approval_result = if let Some(credential) = approval_token.as_deref() { handler .check_approval_for_call(credential, &request) @@ -725,6 +741,12 @@ impl BuiltinApprovalGate { if final_scope && approval_result.status == "pending" && !handler.supports_final_scope() { return Err(Self::reject_unavailable_handler(ctx, UNSUPPORTED_FINAL).await); } + if authority_scope + && approval_result.status == "pending" + && !handler.supports_authority_scope() + { + return Err(Self::reject_unavailable_handler(ctx, UNSUPPORTED_AUTHORITY).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; @@ -749,6 +771,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 { + ctx.require_scope_grant()?; ctx.validate_approval_credential()?; let registry = ctx @@ -857,6 +880,7 @@ impl Step for BuiltinApprovalGate { return Ok(StepResult::continue_step()); } if !needs_approval { + ctx.reject_unconsumed_scoped_approval()?; if decision.destructive { Self::warn_destructive_ungated(ctx); } @@ -940,6 +964,7 @@ impl Step for BuiltinPostValidationPolicy { } async fn execute(&self, ctx: &mut PipelineContext) -> Result { + ctx.require_scope_grant()?; let evaluator = ctx .policy_evaluator .clone() @@ -997,10 +1022,11 @@ impl BuiltinPostValidationPolicy { .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 required = annotations.requires_approval || effect == PolicyEffect::RequireApproval; + if !required { + ctx.reject_unconsumed_scoped_approval()?; + } + if required || ctx.has_approval_credential() { let Some(handler) = ctx.approval_handler.clone() else { return Err(BuiltinApprovalGate::reject_unavailable_handler( ctx, @@ -1036,13 +1062,17 @@ impl BuiltinPostValidationPolicy { let Some(emitter) = ctx.event_emitter.as_ref() else { return; }; + let mut data = serde_json::json!({ + "rule_id": verdict.rule_id, + "decision": verdict.decision, + "sensitive_fields": request.sensitive_fields, + }); + if let Some(identity) = &request.identity { + identity.enrich_principal_audit(&mut data); + } let event = ApCoreEvent::with_module( "apcore.policy.decision", - serde_json::json!({ - "rule_id": verdict.rule_id, - "decision": verdict.decision, - "sensitive_fields": request.sensitive_fields, - }), + data, ctx.module_id.clone(), if verdict.decision == PolicyEffect::Deny { "warn" @@ -1181,6 +1211,8 @@ impl Step for BuiltinExecute { } async fn execute(&self, ctx: &mut PipelineContext) -> Result { + ctx.require_scope_grant()?; + ctx.reject_unconsumed_scoped_approval()?; ctx.bind_policy_inputs()?; let module = ctx .module diff --git a/rust/src/capability.rs b/rust/src/capability.rs index 6ff4e5ee..45d77111 100644 --- a/rust/src/capability.rs +++ b/rust/src/capability.rs @@ -150,7 +150,13 @@ pub trait CapabilitySearchProvider: Send + Sync { struct CursorScope { caller_id: Option, call_chain: Vec, - identity: Option, + principal: Option, +} + +#[derive(Clone, PartialEq, Eq)] +enum CursorPrincipal { + Legacy(Identity), + Scoped(String), } impl From<&Context> for CursorScope { @@ -158,7 +164,12 @@ impl From<&Context> for CursorScope { Self { caller_id: context.caller_id.clone(), call_chain: context.call_chain.clone(), - identity: context.identity.clone(), + principal: context.identity.as_ref().map(|identity| { + identity.authority_key().map_or_else( + || CursorPrincipal::Legacy(identity.clone()), + CursorPrincipal::Scoped, + ) + }), } } } @@ -437,14 +448,25 @@ impl Executor { if permits_lookup != Some(true) { return None; } - let steps = strategy.steps(); - let acl_index = steps - .iter() - .position(|step| step.builtin_gate() == Some(BuiltinGate::Acl))?; - if !steps[..acl_index].iter().any(|step| { - crate::pipeline_config::builtin_context_creation_applies(step.as_ref(), module_id) - }) { - return None; + let scoped = parent + .identity + .as_ref() + .and_then(Identity::scopes) + .is_some(); + if scoped { + if !crate::pipeline_config::builtin_scope_gate_applies(strategy, module_id) { + return None; + } + } else { + let steps = strategy.steps(); + let acl_index = steps + .iter() + .position(|step| step.builtin_gate() == Some(BuiltinGate::Acl))?; + if !steps[..acl_index].iter().any(|step| { + crate::pipeline_config::builtin_context_creation_applies(step.as_ref(), module_id) + }) { + return None; + } } if let Some(acl) = &self.acl { let prospective = parent.child(module_id); @@ -454,7 +476,7 @@ impl Executor { Some(&prospective), ); } - Some(AccessHint::Allowed) + (!scoped).then_some(AccessHint::Allowed) } fn has_discovery_gate(&self, gate: BuiltinGate) -> bool { diff --git a/rust/src/context.rs b/rust/src/context.rs index 85746603..0db20c35 100644 --- a/rust/src/context.rs +++ b/rust/src/context.rs @@ -3,14 +3,19 @@ use async_trait::async_trait; use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; use std::collections::HashMap; use parking_lot::RwLock; use std::sync::Arc; use crate::cancel::CancelToken; +use crate::errors::ModuleError; use crate::trace_context::TraceParent; +/// Maximum number of active delegation edges an identity may carry. +pub const MAX_DELEGATION_DEPTH: usize = 8; + const TRACE_ID_ZEROS: &str = "00000000000000000000000000000000"; const TRACE_ID_FFFF: &str = "ffffffffffffffffffffffffffffffff"; @@ -53,23 +58,62 @@ struct IdentityRaw { roles: Vec, #[serde(default)] attrs: HashMap, + #[serde(default, deserialize_with = "present_identity_field")] + scopes: Option>, + #[serde(default, deserialize_with = "present_identity_field")] + on_behalf_of: Option>, + #[serde(default, deserialize_with = "present_identity_field")] + issuer: Option, } -impl From for Identity { - fn from(raw: IdentityRaw) -> Self { - Identity { - id: raw.id, - identity_type: raw.identity_type, - roles: raw.roles, - attrs: raw.attrs, +fn present_identity_field<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: Deserialize<'de>, +{ + T::deserialize(deserializer).map(Some) +} + +impl IdentityRaw { + fn into_identity(self, depth: usize) -> Result { + if depth > MAX_DELEGATION_DEPTH { + return Err(ModuleError::invalid_input( + "Delegation depth exceeds the maximum", + )); + } + let parent = self + .on_behalf_of + .map(|parent| parent.into_identity(depth + 1).map(Box::new)) + .transpose()?; + let mut identity = Identity { + id: self.id, + identity_type: self.identity_type, + roles: self.roles, + attrs: self.attrs, + scopes: self.scopes, + issuer: self.issuer, + on_behalf_of: parent, + }; + identity.normalize_authority()?; + if let Some(parent) = identity.on_behalf_of() { + parent.check_ceiling(identity.scopes())?; } + Ok(identity) + } +} + +impl TryFrom for Identity { + type Error = ModuleError; + + fn try_from(raw: IdentityRaw) -> Result { + raw.into_identity(0) } } /// Frozen/immutable identity representing the caller. /// Fields are private to enforce immutability after construction. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(from = "IdentityRaw")] +#[serde(try_from = "IdentityRaw")] #[allow(clippy::struct_field_names)] // `identity_type` intentionally prefixed for clarity with renamed JSON field pub struct Identity { id: String, @@ -77,6 +121,12 @@ pub struct Identity { identity_type: String, roles: Vec, attrs: HashMap, + #[serde(skip_serializing_if = "Option::is_none")] + scopes: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + on_behalf_of: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + issuer: Option, } impl Identity { @@ -93,9 +143,174 @@ impl Identity { identity_type, roles, attrs, + scopes: None, + on_behalf_of: None, + issuer: None, + } + } + + /// Attach authority to a direct identity established by a trusted host. + /// + /// An absent scope set preserves the scope-free path. An empty set carries + /// no scoped authority. A delegated identity cannot be reissued this way. + pub fn with_authority( + mut self, + scopes: Option>, + issuer: Option, + ) -> Result { + if self.on_behalf_of.is_some() { + return Err(ModuleError::invalid_input( + "Only a direct identity can receive initial authority", + )); + } + self.scopes = scopes; + self.issuer = issuer; + self.normalize_authority()?; + Ok(self) + } + + /// Narrow this identity's authority to a trusted direct actor. + pub fn delegate(&self, mut actor: Self, scopes: Vec) -> Result { + if actor.on_behalf_of.is_some() || self.delegation_depth() >= MAX_DELEGATION_DEPTH { + return Err(ModuleError::invalid_input( + "Invalid actor or delegation depth", + )); + } + self.check_ceiling(Some(&scopes))?; + if actor.scopes.is_some() { + actor.check_ceiling(Some(&scopes))?; + } + actor.scopes = Some(scopes); + actor.normalize_authority()?; + actor.on_behalf_of = Some(Box::new(self.clone())); + Ok(actor) + } + + fn normalize_authority(&mut self) -> Result<(), ModuleError> { + if (self.scopes.is_some() || self.issuer.is_some() || self.on_behalf_of.is_some()) + && (self.id.is_empty() || self.identity_type.is_empty()) + { + return Err(ModuleError::invalid_input( + "Scoped principals require a nonempty id and type", + )); + } + if self.issuer.as_ref().is_some_and(String::is_empty) { + return Err(ModuleError::invalid_input("Issuer must be nonempty")); + } + if let Some(scopes) = &mut self.scopes { + if scopes.iter().any(|scope| !valid_scope_literal(scope)) { + return Err(ModuleError::invalid_input( + "Scope literals must be nonempty and contain no whitespace", + )); + } + scopes.sort_unstable(); + scopes.dedup(); + } + Ok(()) + } + + fn check_ceiling(&self, requested: Option<&[String]>) -> Result<(), ModuleError> { + match self.scopes().zip(requested) { + Some((ceiling, requested)) + if requested + .iter() + .all(|scope| ceiling.binary_search(scope).is_ok()) => + { + Ok(()) + } + _ => Err(ModuleError::invalid_input( + "Delegated scopes exceed the explicit ceiling", + )), } } + /// Effective scope ceiling, if scope enforcement is enabled. + #[must_use] + pub fn scopes(&self) -> Option<&[String]> { + self.scopes.as_deref() + } + + /// Immediate parent authority, if this identity is acting on behalf of one. + #[must_use] + pub fn on_behalf_of(&self) -> Option<&Self> { + self.on_behalf_of.as_deref() + } + + /// Issuer supplied by the trusted identity source. + #[must_use] + pub fn issuer(&self) -> Option<&str> { + self.issuer.as_deref() + } + + fn lineage(&self) -> impl Iterator { + std::iter::successors(Some(self), |identity| identity.on_behalf_of()) + } + + /// Original subject whose authority is being exercised. + #[must_use] + pub fn root_subject(&self) -> &Self { + self.lineage().last().unwrap_or(self) + } + + /// Number of active delegation edges. + #[must_use] + pub fn delegation_depth(&self) -> usize { + self.lineage().count() - 1 + } + + /// Opaque key binding discovery and approval to current authority. + #[must_use] + pub fn authority_key(&self) -> Option { + self.scopes()?; + let lineage: Vec<_> = self + .lineage() + .map(|identity| { + let mut roles: Vec<&str> = identity.roles().iter().map(String::as_str).collect(); + roles.sort_unstable(); + roles.dedup(); + serde_json::json!([ + identity.issuer(), + identity.id(), + identity.identity_type(), + roles, + identity.scopes(), + ]) + }) + .collect(); + Some(Self::projection_key( + "authority", + &serde_json::Value::Array(lineage), + )) + } + + /// Opaque principal ownership key that survives scope refresh. + #[must_use] + pub fn owner_key(&self) -> Option { + self.scopes()?; + let subject = self.root_subject(); + let principals = serde_json::json!([ + [self.issuer(), self.id(), self.identity_type()], + [subject.issuer(), subject.id(), subject.identity_type()], + ]); + Some(Self::projection_key("owner", &principals)) + } + + pub(crate) fn enrich_principal_audit(&self, event: &mut serde_json::Value) { + if self.scopes().is_some() { + event["actor_id"] = serde_json::json!(self.id()); + event["subject_id"] = serde_json::json!(self.root_subject().id()); + event["delegation_depth"] = serde_json::json!(self.delegation_depth()); + } + } + + fn projection_key(domain: &str, projection: &serde_json::Value) -> String { + let mut hash = Sha256::new(); + hash.update(domain.as_bytes()); + hash.update([0]); + hash.update(projection.to_string()); + format!("{:x}", hash.finalize()) + } + /// The unique identifier of the caller. #[must_use] pub fn id(&self) -> &str { @@ -130,6 +345,10 @@ impl Identity { } } +pub(crate) fn valid_scope_literal(scope: &str) -> bool { + !scope.is_empty() && !scope.chars().any(char::is_whitespace) +} + // Manual Hash impl: serde_json::Value doesn't implement Hash, so we sort // attrs by key and hash each value's canonical JSON string representation. // This is consistent with the derived PartialEq/Eq (order-independent HashMap @@ -140,6 +359,9 @@ impl std::hash::Hash for Identity { self.id.hash(state); self.identity_type.hash(state); self.roles.hash(state); + self.scopes.hash(state); + self.issuer.hash(state); + self.on_behalf_of.hash(state); let mut pairs: Vec<_> = self.attrs.iter().collect(); pairs.sort_by_key(|(k, _)| k.as_str()); for (k, v) in pairs { @@ -329,12 +551,7 @@ impl Context { }); if let Some(ref identity) = self.identity { - result["identity"] = serde_json::json!({ - "id": identity.id(), - "type": identity.identity_type(), - "roles": identity.roles(), - "attrs": identity.attrs(), - }); + result["identity"] = serde_json::json!(identity); } else { result["identity"] = serde_json::Value::Null; } @@ -386,13 +603,12 @@ impl Context { /// `global_deadline`) are set to `None`/default after deserialization. /// If `_context_version` is greater than 1, a warning is logged /// but deserialization proceeds (forward compatibility). - #[allow(clippy::needless_pass_by_value)] // public API: callers pass owned Value; changing to &Value would be breaking - pub fn deserialize(value: serde_json::Value) -> Result + pub fn deserialize(mut value: serde_json::Value) -> Result where T: Default, { let obj = value - .as_object() + .as_object_mut() .ok_or_else(|| serde::de::Error::custom("expected JSON object"))?; let version = obj @@ -408,13 +624,19 @@ impl Context { ); } - let identity: Option = obj.get("identity").and_then(|v| { - if v.is_null() { - None - } else { - serde_json::from_value(v.clone()).ok() + let identity = match obj.remove("identity") { + Some(value) + if value.as_object().is_some_and(|identity| { + ["scopes", "issuer", "on_behalf_of"] + .iter() + .any(|key| identity.contains_key(*key)) + }) => + { + Some(serde_json::from_value(value)?) } - }); + Some(value) => serde_json::from_value(value).ok(), + None => None, + }; let data_map: HashMap = obj .get("data") diff --git a/rust/src/executor.rs b/rust/src/executor.rs index d4ed153c..90058ffe 100644 --- a/rust/src/executor.rs +++ b/rust/src/executor.rs @@ -1200,6 +1200,40 @@ impl Executor { Ok(()) } + fn ensure_scope_gate( + &self, + strategy: &ExecutionStrategy, + module_id: &str, + context: &Context, + ) -> Result<(), ModuleError> { + if context + .identity + .as_ref() + .and_then(crate::Identity::scopes) + .is_some() + && (self.acl.is_none() + || !crate::pipeline_config::builtin_scope_gate_applies(strategy, module_id)) + { + return Err(ModuleError::acl_denied( + context.caller_id.as_deref(), + module_id, + )); + } + Ok(()) + } + + fn denied_scope_preflight(error: &ModuleError) -> PreflightResult { + PreflightResult { + checks: vec![PreflightCheckResult { + check: crate::module::ACL_CHECK_NAME.to_owned(), + passed: false, + error: Some(error.to_dict()), + warnings: vec![], + }], + ..PreflightResult::default() + } + } + /// Set the approval handler. pub fn set_approval_handler(&mut self, handler: Box) { self.set_approval_handler_shared(Arc::from(handler)); @@ -1388,6 +1422,7 @@ impl Executor { } Self::validate_module_id(module_id)?; let mut parent = context.cloned().unwrap_or_else(Context::anonymous); + self.ensure_scope_gate(strategy, module_id, &parent)?; parent.bind_executor(self.instance_handle())?; let started = std::time::Instant::now(); let mut previous_steps = Vec::new(); @@ -1402,6 +1437,8 @@ impl Executor { let (output, mut trace) = match PipelineEngine::run(strategy, &mut attempt).await { Ok((output, trace)) => { Self::reject_aborted_trace(&trace)?; + attempt.require_scope_grant()?; + attempt.reject_unconsumed_scoped_approval()?; (output.unwrap_or(Value::Null), trace) } Err(error) => { @@ -1506,6 +1543,9 @@ impl Executor { let context = ctx .cloned() .unwrap_or_else(Context::::anonymous); + if let Err(error) = self.ensure_scope_gate(&self.strategy, module_id, &context) { + return Ok(Self::denied_scope_preflight(&error)); + } let mut pipe_ctx = PipelineContext::new(module_id, inputs.clone(), context, self.strategy.name()); let business_inputs = pipe_ctx @@ -1533,6 +1573,9 @@ impl Executor { let mut checks: Vec = Vec::new(); let trace_result = PipelineEngine::run(&self.strategy, &mut pipe_ctx).await; + if let Err(error) = pipe_ctx.require_scope_grant() { + return Ok(Self::denied_scope_preflight(&error)); + } match trace_result { Ok((_output, trace)) => { checks.extend(trace_to_checks(&trace.steps, &pipe_ctx.preflight_errors)); @@ -2011,7 +2054,11 @@ impl Executor { let result = Self::run_stream_segment(&self.strategy, &mut setup.pipe_ctx, options, recorder).await; let raw_error = match result { - Ok((_, trace)) => return Self::reject_aborted_trace(&trace), + Ok((_, trace)) => { + Self::reject_aborted_trace(&trace)?; + setup.pipe_ctx.require_scope_grant()?; + return setup.pipe_ctx.reject_unconsumed_scoped_approval(); + } Err(error) => error, }; // A failed after-step hook can leave an opened producer in the context. @@ -2260,6 +2307,7 @@ impl Executor { self.ensure_startup_configuration()?; // D-103: no synthetic principal for a call that supplied none. let context = ctx.unwrap_or_else(Context::::anonymous); + self.ensure_scope_gate(&self.strategy, module_id, &context)?; let mut pipe_ctx = PipelineContext::new(module_id, inputs, context, self.strategy.name()); pipe_ctx.validate_approval_credential()?; @@ -2304,6 +2352,7 @@ impl Executor { // can observe the trace). Streaming requires a resolved module, so // an aborted pre-execute phase is an error for us. Self::reject_aborted_trace(&trace)?; + pipe_ctx.require_scope_grant()?; let module = pipe_ctx.module.clone().ok_or_else(|| { ModuleError::new( diff --git a/rust/src/pipeline.rs b/rust/src/pipeline.rs index 84cec066..f4ddbb00 100644 --- a/rust/src/pipeline.rs +++ b/rust/src/pipeline.rs @@ -317,6 +317,7 @@ pub struct PipelineContext { /// from the strategy — absence of the gate is not a requirement. pub acl_approval_required: bool, pub(crate) acl_decision: Option, + initial_scope: Option, pub(crate) policy_evaluator: Option>, pub(crate) policy_approval_annotations: Option, pub(crate) policy_effect: Option, @@ -386,6 +387,43 @@ pub struct PipelineContext { pub trace: PipelineTrace, } +struct ScopeInvocation { + authority: String, + module_id: String, + caller_id: String, + call_chain: Vec, + /// Set only by the stock ACL gate after a scope-constrained grant. + granted: bool, +} + +impl ScopeInvocation { + fn from_parent(context: &Context, module_id: &str) -> Option { + let authority = context.identity.as_ref()?.authority_key()?; + let prospective = context.child(module_id); + Some(Self { + authority, + module_id: module_id.to_owned(), + caller_id: prospective + .caller_id + .unwrap_or_else(|| crate::acl::EXTERNAL_CALLER.into()), + call_chain: prospective.call_chain, + granted: false, + }) + } + + fn matches(&self, ctx: &PipelineContext, authority: &str) -> bool { + self.authority == authority + && self.module_id == ctx.module_id + && self.caller_id + == ctx + .context + .caller_id + .as_deref() + .unwrap_or(crate::acl::EXTERNAL_CALLER) + && self.call_chain == ctx.context.call_chain + } +} + impl PipelineContext { /// Create a new `PipelineContext` for a module invocation. pub fn new( @@ -399,6 +437,7 @@ impl PipelineContext { let approval_credential = inputs .as_object_mut() .and_then(|object| object.remove(crate::policy::APPROVAL_TOKEN_KEY)); + let initial_scope = ScopeInvocation::from_parent(&context, &module_id); Self { trace: PipelineTrace::new(module_id.clone(), strategy_name.clone()), module_id, @@ -410,6 +449,7 @@ impl PipelineContext { governance_projection: None, acl_approval_required: false, acl_decision: None, + initial_scope, policy_evaluator: None, policy_approval_annotations: None, policy_effect: None, @@ -468,12 +508,59 @@ impl PipelineContext { self.approval_credential.is_some() } + pub(crate) fn reject_unconsumed_scoped_approval(&self) -> Result<(), ModuleError> { + if self.initial_scope.is_some() && self.has_approval_credential() { + return Err(ModuleError::new( + ErrorCode::ApprovalDenied, + "The supplied approval credential was not authorized for this scoped invocation", + )); + } + Ok(()) + } + 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() + self.terminal_gate_failure + || self.policy_admission_pending() + || self.require_scope_grant().is_err() + || self.reject_unconsumed_scoped_approval().is_err() + } + + pub(crate) fn record_scope_grant(&mut self) { + let granted = self.initial_scope.as_ref().is_some_and(|initial| { + self.context + .identity + .as_ref() + .and_then(crate::Identity::authority_key) + .is_some_and(|current| initial.matches(self, ¤t)) + }); + if let Some(initial) = &mut self.initial_scope { + initial.granted = granted; + } + } + + pub(crate) fn require_scope_grant(&self) -> Result<(), ModuleError> { + let current = self + .context + .identity + .as_ref() + .and_then(crate::Identity::authority_key); + let admitted = match (&self.initial_scope, ¤t) { + (None, None) => true, + (Some(initial), Some(current)) => initial.granted && initial.matches(self, current), + _ => false, + }; + if admitted { + Ok(()) + } else { + Err(ModuleError::acl_denied( + self.context.caller_id.as_deref(), + &self.module_id, + )) + } } pub(crate) fn bind_policy_inputs(&mut self) -> Result<(), ModuleError> { diff --git a/rust/src/pipeline_config.rs b/rust/src/pipeline_config.rs index 255b9094..c11e38f0 100644 --- a/rust/src/pipeline_config.rs +++ b/rust/src/pipeline_config.rs @@ -7,7 +7,7 @@ use std::sync::OnceLock; use serde_json::Value; -use crate::builtin_steps::{build_standard_strategy, BuiltinContextCreation}; +use crate::builtin_steps::{build_standard_strategy, BuiltinACLCheck, BuiltinContextCreation}; use crate::errors::{ErrorCode, ModuleError}; use crate::pipeline::{ExecutionStrategy, Step}; @@ -90,18 +90,38 @@ struct ConfiguredStep { pub(crate) fn builtin_context_creation_applies(step: &dyn Step, module_id: &str) -> bool { // The outermost overlay supplies the engine's matcher. Inspect wrapped // steps only for their implementation identity. + builtin_step_applies::(step, module_id) +} + +pub(crate) fn builtin_scope_gate_applies(strategy: &ExecutionStrategy, module_id: &str) -> bool { + let steps = strategy.steps(); + let Some(index) = steps.iter().position(|step| { + step.pure() + && !step.ignore_errors() + && builtin_step_applies::(step.as_ref(), module_id) + }) else { + return false; + }; + steps[..index].iter().any(|step| { + step.pure() + && !step.ignore_errors() + && builtin_context_creation_applies(step.as_ref(), module_id) + }) +} + +fn builtin_step_applies(step: &dyn Step, module_id: &str) -> bool { step.match_modules().is_none_or(|patterns| { patterns .iter() .any(|pattern| crate::utils::helpers::match_pattern(pattern, module_id)) - }) && is_builtin_context_creation(step) + }) && is_builtin_step::(step) } -fn is_builtin_context_creation(step: &dyn Step) -> bool { +fn is_builtin_step(step: &dyn Step) -> bool { let implementation = step as &dyn std::any::Any; implementation.downcast_ref::().map_or_else( - || implementation.is::(), - |configured| is_builtin_context_creation(configured.inner.as_ref()), + || implementation.is::(), + |configured| is_builtin_step::(configured.inner.as_ref()), ) } diff --git a/rust/src/policy/evaluator.rs b/rust/src/policy/evaluator.rs index 260295be..c46df5b6 100644 --- a/rust/src/policy/evaluator.rs +++ b/rust/src/policy/evaluator.rs @@ -40,6 +40,14 @@ pub struct PolicyEvaluationRequest { pub sensitive_fields: Vec, } +impl PolicyEvaluationRequest { + /// Opaque key for the detached current authority, when scope is enabled. + #[must_use] + pub fn authority_key(&self) -> Option { + self.identity.as_ref()?.authority_key() + } +} + /// An instance-scoped policy evaluated before execution and by preflight. /// Implementations must be safe to use for a dry run. #[async_trait] diff --git a/rust/src/sys_modules/mod.rs b/rust/src/sys_modules/mod.rs index 574fd89a..1aa0af1b 100644 --- a/rust/src/sys_modules/mod.rs +++ b/rust/src/sys_modules/mod.rs @@ -318,7 +318,48 @@ fn redact_identity_attr(name: &str, value: &serde_json::Value) -> serde_json::Va { return serde_json::Value::String(IDENTITY_REDACTED_TOKEN.to_string()); } - value.clone() + redact_identity_value(value) +} + +#[cfg(feature = "sys-modules")] +fn redact_identity_value(value: &serde_json::Value) -> serde_json::Value { + match value { + serde_json::Value::Object(fields) => serde_json::Value::Object( + fields + .iter() + .map(|(key, value)| (key.clone(), redact_identity_attr(key, value))) + .collect(), + ), + serde_json::Value::Array(values) => { + serde_json::Value::Array(values.iter().map(redact_identity_value).collect()) + } + _ => value.clone(), + } +} + +#[cfg(feature = "sys-modules")] +fn audit_identity(identity: &crate::Identity) -> serde_json::Value { + let mut snapshot = serde_json::json!({"id": identity.id(), "type": identity.identity_type()}); + if !identity.roles().is_empty() { + snapshot["roles"] = serde_json::json!(identity.roles()); + } + if let Some(fields) = snapshot.as_object_mut() { + for (key, value) in identity.attrs() { + if !matches!(key.as_str(), "id" | "type" | "roles") { + fields.insert(key.clone(), redact_identity_attr(key, value)); + } + } + } + if let Some(scopes) = identity.scopes() { + snapshot["scopes"] = serde_json::json!(scopes); + } + if let Some(issuer) = identity.issuer() { + snapshot["issuer"] = serde_json::json!(issuer); + } + if let Some(parent) = identity.on_behalf_of() { + snapshot["on_behalf_of"] = audit_identity(parent); + } + snapshot } /// Augment an audit-event payload with caller identity extracted from the @@ -354,29 +395,68 @@ pub(crate) fn augment_with_context_identity( serde_json::json!(identity.identity_type()), ); - // Canonical nested snapshot. - let mut snapshot = serde_json::Map::new(); - snapshot.insert("id".to_string(), serde_json::json!(identity.id())); - snapshot.insert( - "type".to_string(), - serde_json::json!(identity.identity_type()), - ); - let roles = identity.roles(); - if !roles.is_empty() { - snapshot.insert("roles".to_string(), serde_json::json!(roles)); - } - for (key, value) in identity.attrs() { - if matches!(key.as_str(), "id" | "type" | "roles") { - continue; - } - snapshot.insert(key.clone(), redact_identity_attr(key, value)); + if identity.scopes().is_some() { + obj.insert( + "subject_id".into(), + serde_json::json!(identity.root_subject().id()), + ); + obj.insert( + "delegation_depth".into(), + serde_json::json!(identity.delegation_depth()), + ); } - obj.insert("identity".to_string(), serde_json::Value::Object(snapshot)); + obj.insert("identity".to_string(), audit_identity(identity)); } } data } +#[cfg(all(test, feature = "sys-modules"))] +mod identity_audit_tests { + use super::augment_with_context_identity; + use crate::context::{Context, Identity}; + use serde_json::{json, Value}; + + #[test] + fn scoped_audit_redacts_nested_attributes_at_every_hop() { + let root = Identity::new( + "root".into(), + "user".into(), + vec![], + [( + "provider".into(), + json!({"session_id": "root-session", "region": "west"}), + )] + .into_iter() + .collect(), + ) + .with_authority(Some(vec!["read".into()]), None) + .unwrap(); + let actor = Identity::new( + "actor".into(), + "agent".into(), + vec![], + [("network".into(), json!([{"auth_header": "actor-secret"}]))] + .into_iter() + .collect(), + ); + let context = Context::::new(root.delegate(actor, vec!["read".into()]).unwrap()); + let event = augment_with_context_identity(json!({}), &context); + assert_eq!(event["actor_id"], "actor"); + assert_eq!(event["subject_id"], "root"); + assert_eq!(event["delegation_depth"], 1); + assert_eq!(event["identity"]["network"][0]["auth_header"], ""); + assert_eq!( + event["identity"]["on_behalf_of"]["provider"]["session_id"], + "" + ); + assert_eq!( + event["identity"]["on_behalf_of"]["provider"]["region"], + "west" + ); + } +} + // --------------------------------------------------------------------------- // SysModuleError — strict registration failure (Issue #45 §1.5) // --------------------------------------------------------------------------- diff --git a/rust/tests/capability_discovery.rs b/rust/tests/capability_discovery.rs index 0e49ad81..9f327975 100644 --- a/rust/tests/capability_discovery.rs +++ b/rust/tests/capability_discovery.rs @@ -228,6 +228,56 @@ fn test_capability_cursor_is_bound_and_rechecks_current_registrations() { assert!(executor.list_callable(Some(&owner), second).is_err()); } +#[test] +fn test_scoped_capability_cursor_rejects_new_subject_or_effective_scope() { + let mut executor = Executor::new(Registry::new(), Config::default()); + executor.set_acl(ACL::new( + serde_json::from_value(json!([{ + "callers": ["@external"], "targets": ["demo.*"], + "effect": "allow", "conditions": {"scopes": ["read"]} + }])) + .unwrap(), + "deny", + None, + )); + for id in ["demo.a", "demo.b"] { + register(&executor, &json!({"module_id": id})); + } + let delegated = |subject, scopes| { + let root = reader(subject, vec!["eligible".into()]) + .identity + .unwrap() + .with_authority(Some(vec!["read".into(), "write".into()]), None) + .unwrap(); + let actor = reader("shared-actor", vec![]).identity.unwrap(); + Context::new(root.delegate(actor, scopes).unwrap()) + }; + let owner = delegated("subject", vec!["read".into(), "write".into()]); + let query = CapabilityQuery { + limit: 1, + ..Default::default() + }; + let first = executor.list_callable(Some(&owner), query.clone()).unwrap(); + assert_eq!(first.items[0].module_id, "demo.a"); + assert!(first.next_cursor.is_some()); + let next = CapabilityQuery { + cursor: first.next_cursor, + ..query + }; + for other in [ + delegated("different-subject", vec!["read".into(), "write".into()]), + delegated("subject", vec!["read".into()]), + ] { + assert!(executor.list_callable(Some(&other), next.clone()).is_err()); + } + let equivalent = delegated( + "subject", + vec!["write".into(), "read".into(), "read".into()], + ); + let last = executor.list_callable(Some(&equivalent), next).unwrap(); + assert_eq!(last.items[0].module_id, "demo.b"); +} + #[test] fn test_capability_descriptors_check_current_version_and_same_version_replacement() { let executor = Executor::new(Registry::new(), Config::default()); diff --git a/rust/tests/identity_system_spec.rs b/rust/tests/identity_system_spec.rs index f994f74a..f7f9529b 100644 --- a/rust/tests/identity_system_spec.rs +++ b/rust/tests/identity_system_spec.rs @@ -30,9 +30,170 @@ use std::sync::Arc; use async_trait::async_trait; use serde_json::{json, Value}; +use super::conformance_env; use apcore::context::{Context, ContextFactory, Identity}; use apcore::errors::ModuleError; +#[test] +fn scoped_delegation_round_trips_and_cannot_widen_authority() { + let subject = Identity::new("subject".into(), "user".into(), vec![], HashMap::new()) + .with_authority( + Some(vec!["read".into(), "write".into()]), + Some("issuer".into()), + ) + .unwrap(); + let actor = Identity::new("actor".into(), "service".into(), vec![], HashMap::new()); + let delegated = subject + .delegate(actor.clone(), vec!["read".into()]) + .unwrap(); + assert_eq!(delegated.id(), "actor"); + assert_eq!(delegated.root_subject().id(), "subject"); + assert_eq!(delegated.delegation_depth(), 1); + assert_eq!(delegated.scopes().unwrap(), &["read".to_string()]); + assert!(delegated.delegate(actor, vec!["write".into()]).is_err()); + + let context = Context::::new(delegated.clone()); + let mut wire = context.serialize(); + let restored = Context::::deserialize(wire.clone()).unwrap(); + assert_eq!(restored.identity, Some(delegated)); + wire["identity"]["scopes"] = json!(["admin"]); + assert!(Context::::deserialize(wire).is_err()); +} + +#[tokio::test] +async fn scoped_delegation_conformance() { + let path = conformance_env::find_fixtures_root().join("identity_delegation.json"); + let fixture: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + for case in fixture["test_cases"].as_array().unwrap() { + let id = case["id"].as_str().unwrap(); + let input = &case["input"]; + let expected = &case["expected"]; + let context = Context::::deserialize(json!({"identity": input["identity"]})); + assert_eq!(context.is_ok(), expected["valid"] == true, "{id}"); + let Ok(context) = context else { + continue; + }; + let identity = context.identity.as_ref().unwrap(); + assert_eq!( + json!(identity.delegation_depth()), + expected["depth"], + "{id}" + ); + assert_eq!( + json!(identity.root_subject().id()), + expected["subject_id"], + "{id}" + ); + if let Some(effect) = expected["effect"].as_str() { + let audit = Arc::new(std::sync::Mutex::new(vec![])); + let captured = Arc::clone(&audit); + let acl = apcore::ACL::new( + serde_json::from_value(input["rules"].clone()).unwrap(), + input["default_effect"].as_str().unwrap_or("deny"), + Some(Arc::new(move |entry| { + captured.lock().unwrap().push(entry.clone()) + })), + ); + let target_id = "delegation.target"; + assert_eq!( + acl.check_access(None, target_id, Some(&context), None) + .access, + effect, + "{id}" + ); + assert_eq!( + acl.async_check_access(None, target_id, Some(&context), None) + .await + .access, + effect, + "{id}" + ); + assert_eq!( + acl.evaluate_visibility(None, target_id, Some(&context)) + .is_some(), + effect == "allow", + "{id}" + ); + let entries = audit.lock().unwrap(); + assert_eq!(entries.len(), 2, "discovery must remain silent: {id}"); + for entry in entries.iter() { + assert_eq!(entry.decision, effect, "{id}"); + if identity.scopes().is_some() { + assert_eq!(entry.actor_id.as_deref(), Some(identity.id()), "{id}"); + assert_eq!( + entry.subject_id.as_deref(), + Some(identity.root_subject().id()), + "{id}" + ); + assert_eq!( + entry.delegation_depth, + Some(identity.delegation_depth()), + "{id}" + ); + } else { + assert!(entry.delegation_depth.is_none(), "{id}"); + } + } + } + } +} + +#[test] +fn scoped_owner_is_stable_across_scope_refresh_but_authority_changes() { + let subject = Identity::new("subject".into(), "user".into(), vec![], HashMap::new()) + .with_authority( + Some(vec!["read".into(), "write".into()]), + Some("issuer".into()), + ) + .unwrap(); + let actor = Identity::new("actor".into(), "service".into(), vec![], HashMap::new()); + let older = subject + .delegate(actor.clone(), vec!["write".into(), "read".into()]) + .unwrap(); + let refreshed = subject + .delegate(actor.clone(), vec!["read".into(), "read".into()]) + .unwrap(); + assert_eq!(older.owner_key(), refreshed.owner_key()); + assert_ne!(older.authority_key(), refreshed.authority_key()); + assert_eq!(None, actor.authority_key()); + assert!(subject.delegate(actor, vec![" read".into()]).is_err()); +} + +#[tokio::test] +async fn scoped_identity_conditions_validate_operands_before_matching() { + let target = "delegation.target"; + let identity = Identity::new("user".into(), "user".into(), vec![], HashMap::new()) + .with_authority(Some(vec!["read".into()]), None) + .unwrap(); + let context = Context::::new(identity); + for malformed in [ + json!({"scopes": []}), + json!({"subject_types": ["user", 0]}), + json!({"max_delegation_depth": {"lte": 0}}), + json!({"max_delegation_depth": 9}), + ] { + let acl = apcore::ACL::new( + serde_json::from_value(json!([ + {"callers": ["@external"], "targets": [target], "effect": "deny", "conditions": malformed}, + {"callers": ["@external"], "targets": [target], "effect": "allow", "conditions": {"scopes": ["read"]}}, + ])) + .unwrap(), + "deny", + None, + ); + assert!(!acl + .check_access(None, target, Some(&context), None) + .is_allowed()); + assert!(!acl + .async_check_access(None, target, Some(&context), None) + .await + .is_allowed()); + assert!(acl + .evaluate_visibility(None, target, Some(&context)) + .is_none()); + } +} + // --------------------------------------------------------------------------- // Helpers // diff --git a/rust/tests/post_validation_policy.rs b/rust/tests/post_validation_policy.rs index 72b758e8..c4c3a657 100644 --- a/rust/tests/post_validation_policy.rs +++ b/rust/tests/post_validation_policy.rs @@ -4,11 +4,11 @@ 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::pipeline::{PipelineContext, PipelineState, Step, StepMiddleware, StepResult}; use apcore::registry::ModuleDescriptor; use apcore::{ - ChunkStream, Config, Context, Executor, Module, ModuleAnnotations, ModuleError, PolicyEffect, - PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict, Registry, ACL, + ChunkStream, Config, Context, Executor, Identity, Module, ModuleAnnotations, ModuleError, + PolicyEffect, PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict, Registry, ACL, }; use async_trait::async_trait; use futures_util::{stream, StreamExt}; @@ -155,6 +155,7 @@ impl Middleware for Rewrite { fn approval_scope(request: &ApprovalRequest) -> Value { json!({ + "authority": request.authority_key(), "principal": request.context.as_ref().and_then(|ctx| ctx.identity.as_ref()), "caller_id": request.caller_id, "module_id": request.module_id, @@ -169,6 +170,7 @@ const TEST_CREDENTIAL: &str = "fixture-resume-credential"; struct Approver { pending: bool, supports_final_scope: bool, + supports_authority_scope: bool, requested: Mutex>, scope: Mutex>, checks: AtomicUsize, @@ -180,6 +182,10 @@ impl ApprovalHandler for Approver { self.supports_final_scope } + fn supports_authority_scope(&self) -> bool { + self.supports_authority_scope + } + async fn request_approval( &self, request: &ApprovalRequest, @@ -309,6 +315,7 @@ async fn post_validation_policy_matches_shared_fixture() { let evaluator = spy_evaluator(case["verdict"].as_str().unwrap()); let approver = Arc::new(Approver { + supports_authority_scope: false, pending: entry == "resume", supports_final_scope: true, requested: Mutex::new(Vec::new()), @@ -414,12 +421,254 @@ fn pending_approver(supports_final_scope: bool) -> Arc { Arc::new(Approver { pending: true, supports_final_scope, + supports_authority_scope: false, requested: Mutex::new(Vec::new()), scope: Mutex::new(None), checks: AtomicUsize::new(0), }) } +fn delegated_context(subject: &str, scopes: &[&str]) -> Context { + let principal = |id: &str| { + Identity::new( + id.into(), + "user".into(), + vec![], + std::collections::HashMap::new(), + ) + }; + let root = principal(subject) + .with_authority( + Some(vec!["read".into(), "write".into()]), + Some("idp".into()), + ) + .unwrap(); + Context::new( + root.delegate( + principal("agent"), + scopes.iter().map(ToString::to_string).collect(), + ) + .unwrap(), + ) +} + +fn read_scoped_acl() -> ACL { + ACL::new( + serde_json::from_value(json!([{ + "effect": "allow", "callers": ["@external"], "targets": ["demo.policy"], + "conditions": {"scopes": ["read"]} + }])) + .unwrap(), + "deny", + None, + ) +} + +struct AlternateFlow; + +#[async_trait] +impl Step for AlternateFlow { + fn name(&self) -> &'static str { + "alternate_flow" + } + + fn description(&self) -> &'static str { + "Route to execution after lookup" + } + + fn removable(&self) -> bool { + true + } + + fn replaceable(&self) -> bool { + true + } + + fn pure(&self) -> bool { + true + } + + async fn execute(&self, _: &mut PipelineContext) -> Result { + Ok(StepResult::skip_to("execute")) + } +} + +#[tokio::test] +async fn scoped_invocation_requires_observed_acl_admission_on_the_active_path() { + let mut strategy = apcore::builtin_steps::build_standard_strategy(); + strategy + .insert_before("acl_check", Box::new(AlternateFlow)) + .unwrap(); + let mut executor = + Executor::with_strategy(probe_registry("1.0.0"), Config::in_memory(), strategy); + executor.set_acl(read_scoped_acl()); + let target = "demo.policy"; + let context = delegated_context("subject", &["read"]); + let call = executor.call(target, json!({}), Some(&context), None).await; + assert_eq!(call.unwrap_err().code, ErrorCode::ACLDenied); + let stream = executor + .stream(target, json!({}), Some(&context), None) + .next() + .await + .unwrap(); + assert_eq!(stream.unwrap_err().code, ErrorCode::ACLDenied); + assert!( + !executor + .validate(target, &json!({}), Some(&context)) + .await + .unwrap() + .valid + ); +} + +#[tokio::test] +async fn scoped_calls_streams_preflights_and_discovery_require_the_enforcing_gate() { + let registry = probe_registry("1.0.0"); + let target = "demo.policy"; + let context = delegated_context("subject", &["read"]); + let absent = Executor::new(Arc::clone(®istry), Config::in_memory()); + let mut removed = + Executor::with_strategy_name(Arc::clone(®istry), Config::in_memory(), "minimal") + .unwrap(); + removed.set_acl(read_scoped_acl()); + for executor in [&absent, &removed] { + assert_eq!( + executor + .call(target, json!({}), Some(&context), None) + .await + .unwrap_err() + .code, + ErrorCode::ACLDenied + ); + assert_eq!( + executor + .stream(target, json!({}), Some(&context), None) + .next() + .await + .unwrap() + .unwrap_err() + .code, + ErrorCode::ACLDenied + ); + let report = executor + .validate(target, &json!({}), Some(&context)) + .await + .unwrap(); + assert!(!report.valid); + assert_eq!(report.checks.len(), 1); + assert_eq!( + report.checks[0].error.as_ref().unwrap()["code"], + "ACL_DENIED" + ); + assert!(executor + .get_callable_descriptor(target, None, Some(&context)) + .is_none()); + } + let mut guarded = Executor::new(registry, Config::in_memory()); + guarded.set_acl(read_scoped_acl()); + assert!(guarded + .call(target, json!({}), Some(&context), None) + .await + .is_ok()); + assert!(guarded + .stream(target, json!({}), Some(&context), None) + .next() + .await + .unwrap() + .is_ok()); + assert!( + guarded + .validate(target, &json!({}), Some(&context)) + .await + .unwrap() + .valid + ); + assert!(guarded + .get_callable_descriptor(target, None, Some(&context)) + .is_some()); + assert_eq!( + guarded + .call( + target, + json!({"_approval_token": TEST_CREDENTIAL}), + Some(&context), + None + ) + .await + .unwrap_err() + .code, + ErrorCode::ApprovalDenied + ); +} + +#[tokio::test] +async fn scoped_approval_cannot_resume_under_a_different_subject_or_ceiling() { + let mut executor = Executor::new(probe_registry("1.0.0"), Config::in_memory()); + executor.set_acl(read_scoped_acl()); + let policy = spy_evaluator("require_approval"); + executor.set_policy_evaluator(Some(policy.clone())).unwrap(); + let target = "demo.policy"; + let original = delegated_context("subject", &["read", "write"]); + let unsupported = pending_approver(true); + executor.set_approval_handler_shared(unsupported.clone()); + assert_eq!( + executor + .call(target, json!({}), Some(&original), None) + .await + .unwrap_err() + .code, + ErrorCode::ApprovalDenied + ); + let credential = json!({"_approval_token": TEST_CREDENTIAL}); + assert_eq!( + executor + .call(target, credential.clone(), Some(&original), None) + .await + .unwrap_err() + .code, + ErrorCode::ApprovalDenied + ); + assert_eq!(unsupported.checks.load(Ordering::Relaxed), 0); + + let mut handler = pending_approver(true); + Arc::get_mut(&mut handler).unwrap().supports_authority_scope = true; + executor.set_approval_handler_shared(handler.clone()); + let pending = executor + .call(target, json!({}), Some(&original), None) + .await + .unwrap_err(); + assert_eq!(pending.code, ErrorCode::ApprovalPending); + assert_eq!(pending.details["approval_id"], TEST_CREDENTIAL); + let original_key = original.identity.as_ref().unwrap().authority_key(); + assert_eq!( + handler.requested.lock().unwrap()[0].authority_key(), + original_key + ); + assert_eq!( + policy.observed.lock().unwrap()[0].authority_key(), + original_key + ); + for different in [ + delegated_context("other-subject", &["read", "write"]), + delegated_context("subject", &["read"]), + ] { + assert_eq!( + executor + .call(target, credential.clone(), Some(&different), None) + .await + .unwrap_err() + .code, + ErrorCode::ApprovalDenied + ); + assert!(handler.scope.lock().unwrap().is_some()); + } + assert!(executor + .call(target, credential, Some(&original), None) + .await + .is_ok()); + assert!(handler.scope.lock().unwrap().is_none()); +} + #[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()); diff --git a/schemas/acl-config.schema.json b/schemas/acl-config.schema.json index 69e71c71..eba98353 100644 --- a/schemas/acl-config.schema.json +++ b/schemas/acl-config.schema.json @@ -159,6 +159,45 @@ ] ] }, + "scopes": { + "type": "array", + "description": "Require every listed effective scope. A scoped allow rule must include this condition at the top level.", + "minItems": 1, + "items": { + "type": "string", + "description": "A case-sensitive scope literal with no whitespace.", + "minLength": 1, + "not": { + "pattern": "[\\u0009-\\u000D\\u0020\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]" + } + } + }, + "subject_types": { + "type": "array", + "description": "Require the root subject type to be one of the listed types.", + "minItems": 1, + "items": { + "type": "string", + "description": "A root subject identity type.", + "minLength": 1 + } + }, + "subject_roles": { + "type": "array", + "description": "Require at least one of the listed roles on the root subject.", + "minItems": 1, + "items": { + "type": "string", + "description": "A root subject role.", + "minLength": 1 + } + }, + "max_delegation_depth": { + "type": "integer", + "description": "Limit the number of active delegation links. Zero permits direct identities only.", + "minimum": 0, + "maximum": 8 + }, "max_call_depth": { "type": "integer", "description": "Only match when call chain depth does not exceed this value.", diff --git a/typescript/apcore-conformance.yaml b/typescript/apcore-conformance.yaml index 1a67c9a3..e24d23e9 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.4" + version: "1.0.0-alpha.5" language: typescript spec_version: "1.65.0" maintainer: AI Perceivable diff --git a/typescript/package.json b/typescript/package.json index 652b93e7..609da262 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-js", - "version": "1.0.0-alpha.4", + "version": "1.0.0-alpha.5", "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/acl.ts b/typescript/src/acl.ts index 48202453..e81f3bb2 100644 --- a/typescript/src/acl.ts +++ b/typescript/src/acl.ts @@ -24,6 +24,9 @@ import { describeArgumentsFaults, isOutcomeHandler, } from './acl-handlers.js'; +import { + delegationDepthOf, hasScopeCeiling, isScopeLiteral, isTrustedIdentity, MAX_DELEGATION_DEPTH, rootSubjectOf, +} from './identity.js'; /** * Minimal structural view of a `Config` used by `ACL.discover()`. @@ -113,10 +116,48 @@ const HIDDEN_VISIBILITY: VisibilityDecision = Object.freeze({ visible: false, approvalRequired: false, approvalConditional: false, }); -const visibilityHandlers = new Map([ +function isDelegationDepth(value: unknown): value is number { + return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= MAX_DELEGATION_DEPTH; +} + +function identityConditionFault(key: string, value: unknown): string | null { + if (key === 'max_delegation_depth' && !isDelegationDepth(value)) return 'must be an integer from 0 through 8'; + if (key === 'scopes' && (!Array.isArray(value) || value.length === 0 || ![...value].every(isScopeLiteral))) { + return 'must be a nonempty list of scope literals'; + } + if ((key === 'subject_types' || key === 'subject_roles') && + (!Array.isArray(value) || value.length === 0 || ![...value].every(item => typeof item === 'string' && item.length > 0))) { + return 'must be a nonempty list of nonempty strings'; + } + return null; +} + +const scopesHandler = { + evaluate(value: unknown, context: Context): boolean { + const scopes = isTrustedIdentity(context.identity) ? context.identity.scopes : undefined; + return scopes !== undefined && Array.isArray(value) && value.length > 0 && + [...value].every(scope => isScopeLiteral(scope) && scopes.includes(scope)); + }, +}; + +const visibilityHandlers = new Map([ ['identity_types', new IdentityTypesHandler()], ['roles', new RolesHandler()], ['max_call_depth', new MaxCallDepthHandler()], + ['scopes', scopesHandler], + ['subject_types', { + evaluate: (value, context) => isTrustedIdentity(context.identity) && Array.isArray(value) && + value.includes(rootSubjectOf(context.identity).type), + }], + ['subject_roles', { + evaluate: (value, context) => isTrustedIdentity(context.identity) && Array.isArray(value) && + rootSubjectOf(context.identity).roles.some(role => value.includes(role)), + }], + ['max_delegation_depth', { + evaluate: (value, context) => isTrustedIdentity(context.identity) && + isDelegationDepth(value) && + delegationDepthOf(context.identity) <= value, + }], ]); type VisibilityCondition = boolean | 'unknown'; @@ -147,6 +188,9 @@ export interface AuditEntry { readonly matchedRule: string | null; // Rule description readonly matchedRuleIndex: number | null; readonly identityType: string | null; + readonly actorId?: string; + readonly subjectId?: string; + readonly delegationDepth?: number; readonly roles: readonly string[]; readonly callDepth: number | null; readonly traceId: string | null; @@ -660,6 +704,12 @@ function precheckConditions( continue; } + const fault = identityConditionFault(key, value); + if (fault !== null) { + out.push({ path, key, message: `ACL condition '${path}' ${fault}`, syncResolvable: false, asyncResolvable: false }); + continue; + } + // §6.1.1 case 1 / §6.1.3 — resolvable on the evaluation path in use. const { syncResolvable, asyncResolvable } = conditionResolvability(key); const resolvable = mode === 'sync' ? syncResolvable : asyncResolvable; @@ -1022,6 +1072,9 @@ export function auditEntryToWire(entry: AuditEntry): Record { matched_rule: entry.matchedRule, matched_rule_index: entry.matchedRuleIndex, identity_type: entry.identityType, + ...(entry.actorId === undefined ? {} : { + actor_id: entry.actorId, subject_id: entry.subjectId, delegation_depth: entry.delegationDepth, + }), roles: entry.roles, call_depth: entry.callDepth, trace_id: entry.traceId, @@ -1725,10 +1778,11 @@ export class ACL { pendingApproval ||= ACL._raisesPendingApproval(rule); continue; } + if (!ACL._grantsScope(rule, context, 'async')) return HIDDEN_VISIBILITY; possibleApprovals.add(pendingApproval || rule.approval === 'required'); if (outcome === true) return ACL._visibleApproval(possibleApprovals); } - if (this._defaultEffect !== 'allow') return HIDDEN_VISIBILITY; + if (this._defaultEffect !== 'allow' || hasScopeCeiling(context?.identity)) return HIDDEN_VISIBILITY; possibleApprovals.add(pendingApproval); return ACL._visibleApproval(possibleApprovals); } @@ -1741,6 +1795,14 @@ export class ACL { }; } + private static _grantsScope(rule: ACLRule, context: Context | null, mode: EvaluationPath): boolean { + if (context === null || !hasScopeCeiling(context.identity)) return true; + const handler = (mode === 'async' ? ACL.asyncConditionHandlers.get('scopes') : undefined) + ?? ACL.conditionHandlers.get('scopes'); + return handler === scopesHandler && rule.conditions != null && + Object.hasOwn(rule.conditions, 'scopes') && scopesHandler.evaluate(rule.conditions.scopes, context) === true; + } + private _visibilityRule( rule: ACLRule, callerId: string, targetId: string, context: Context | null, ): VisibilityCondition | 'unevaluable' { @@ -1828,7 +1890,7 @@ export class ACL { continue; } return this._decideByRule( - effectiveCaller, targetId, rule, idx, ctx, auditSink, frame, pendingApproval, + effectiveCaller, targetId, rule, idx, ctx, auditSink, frame, pendingApproval, 'sync', ); } @@ -1886,7 +1948,7 @@ export class ACL { continue; } return this._decideByRule( - effectiveCaller, targetId, rule, idx, ctx, auditSink, frame, pendingApproval, + effectiveCaller, targetId, rule, idx, ctx, auditSink, frame, pendingApproval, 'async', ); } @@ -1914,6 +1976,7 @@ export class ACL { auditSink: AuditSink, frame: EvaluationFrame, pendingApproval: boolean, + mode: EvaluationPath, ): AccessDecision { // §6.1.5 (v1.30.0): this ternary is TOTAL over the closed value set, not a // fallback — as of #111 an `effect` outside {allow, deny} cannot reach here @@ -1922,7 +1985,7 @@ export class ACL { // It stays a ternary rather than becoming a throw because §6.1.1 makes // `check()` a call that MUST NOT raise; closing the doors is the mechanism, // and a rule object mutated in place after validation is the only residue. - const access = rule.effect === 'allow' ? 'allow' : 'deny'; + const access = rule.effect === 'allow' && ACL._grantsScope(rule, ctx, mode) ? 'allow' : 'deny'; // §6.1.6: the two results are orthogonal, and `approval: required` on a // `deny` rule is rejected at every entry point — the `access` guard is // belt-and-braces against a rule object mutated in place after load. @@ -1969,7 +2032,7 @@ export class ACL { // Total over the closed set for the same reason as in `_decideByRule`: // §6.1.5 closes `default_effect` on the same terms, and the constructor — // which `ACL.load()` also reaches — has always rejected anything else. - const access = defaultEffect === 'allow' ? 'allow' : 'deny'; + const access = defaultEffect === 'allow' && !hasScopeCeiling(ctx?.identity) ? 'allow' : 'deny'; const reason = ruleCount === 0 ? 'no_rules' : 'default_effect'; // A `deny` default clears the pending requirement exactly as a matched // `deny` rule does (§6.1.1 rule 5, third bullet). @@ -2091,6 +2154,11 @@ export class ACL { matchedRule: matchedRule?.description ?? null, matchedRuleIndex, identityType, + ...(context?.identity == null || !isTrustedIdentity(context.identity) || !hasScopeCeiling(context.identity) ? {} : { + actorId: context.identity.id, + subjectId: rootSubjectOf(context.identity).id, + delegationDepth: delegationDepthOf(context.identity), + }), roles, callDepth, traceId, diff --git a/typescript/src/approval.ts b/typescript/src/approval.ts index 7e31b311..4b24526d 100644 --- a/typescript/src/approval.ts +++ b/typescript/src/approval.ts @@ -73,6 +73,8 @@ export interface ApprovalRequest { readonly moduleVersion?: string | null; /** Present on approvals bound to the final validated invocation. */ readonly canonicalArgsDigest?: string; + /** Present when approval is bound to scoped or issuer-qualified authority. */ + readonly authorityKey?: string; } /** @@ -96,6 +98,7 @@ export function createApprovalRequest(options: { action?: string; moduleVersion?: string | null; canonicalArgsDigest?: string; + authorityKey?: string; }): ApprovalRequest { return Object.freeze({ moduleId: options.moduleId, @@ -108,6 +111,7 @@ export function createApprovalRequest(options: { tags: Object.freeze([...(options.tags ?? [])]), ...(options.moduleVersion !== undefined ? { moduleVersion: options.moduleVersion } : {}), ...(options.canonicalArgsDigest !== undefined ? { canonicalArgsDigest: options.canonicalArgsDigest } : {}), + ...(options.authorityKey !== undefined ? { authorityKey: options.authorityKey } : {}), }); } @@ -154,6 +158,8 @@ export function createApprovalResult(options: { export interface ApprovalHandler { /** Opt in to issuing and consuming approvals bound to the final invocation. */ readonly supportsFinalScope?: boolean; + /** Opt in to issuing and consuming approvals bound to a current authority key. */ + readonly supportsAuthorityScope?: 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 6d23d5f6..8cdf61ad 100644 --- a/typescript/src/browser/index.ts +++ b/typescript/src/browser/index.ts @@ -27,7 +27,7 @@ export type { Discoverer, ModuleValidator } from '../registry/registry.js'; // ---- Context / identity / cancel ----------------------------------------- export { CancelToken, ExecutionCancelledError } from '../cancel.js'; -export { Context, createIdentity } from '../context.js'; +export { Context, Identity, createIdentity } from '../context.js'; export { ContextKey } from '../context-key.js'; export { TRACING_SPANS, @@ -37,7 +37,7 @@ export { REDACTED_OUTPUT, RETRY_COUNT_BASE, } from '../context-keys.js'; -export type { Identity, ContextFactory } from '../context.js'; +export type { IdentityOptions, ContextFactory } from '../context.js'; export { TraceContext } from '../trace-context.js'; export type { TraceParent } from '../trace-context.js'; diff --git a/typescript/src/builtin-steps.ts b/typescript/src/builtin-steps.ts index 3641d93d..d5b251cc 100644 --- a/typescript/src/builtin-steps.ts +++ b/typescript/src/builtin-steps.ts @@ -18,6 +18,8 @@ import type { Config } from './config.js'; import { getDefault } from './config-defaults.js'; import { CancelToken, awaitExecution } from './cancel.js'; import { Context } from './context.js'; +import { authorityKeyOf, hasScopeCeiling } from './identity.js'; +import { assertScopedInvocation, isStockScopeAcl, recordScopedGrant } from './scoped-invocation.js'; import { ACLDeniedError, ApprovalDeniedError, @@ -155,6 +157,7 @@ export class BuiltinContextCreation implements Step { invocation.identity = derived.identity; invocation.principalId = derived.identity?.id; invocation.principalType = derived.identity?.type; + invocation.authorityKey = authorityKeyOf(derived.identity); } ctx.onContextReady?.(derived); return { action: 'continue' }; @@ -364,12 +367,17 @@ export class BuiltinACLCheck implements Step { async execute(ctx: PipelineContext): Promise { const invocation = policyInvocationOf(ctx); if (invocation) assertPolicyBinding(ctx, invocation); + assertScopedInvocation(ctx, false); + if (hasScopeCeiling(ctx.context.identity) && !isStockScopeAcl(this._acl)) { + throw new ACLDeniedError(ctx.context.callerId, ctx.moduleId); + } if (this._acl === null) { if (invocation) invocation.aclApprovalRequired = false; return { action: 'continue' }; } const callerId = ctx.context.callerId; const decision = await this._decide(ctx, callerId); + recordScopedGrant(ctx, decision); // §6.9 rows 3–4 / §7.4: the ACL's approval requirement is carried to the // approval gate at Step 5, which fires on the union of it, the module's // annotation and `gateDestructive`. An implementation that reads only the @@ -575,6 +583,9 @@ export class BuiltinApprovalGate implements Step { } if (!needsApproval) { + if (approvalToken !== null && authorityKeyOf(ctx.context.identity) !== null) { + throw new ApprovalDeniedError(createApprovalResult({ status: 'rejected' }), ctx.moduleId); + } if (decision.destructive) { this._warnOnce( `destructive_ungated:${ctx.moduleId}`, @@ -644,16 +655,18 @@ export class BuiltinApprovalGate implements Step { scope?: { moduleVersion: string | null; canonicalArgsDigest: string }, ): ApprovalRequest { const mod = ctx.module as Record | null; + const authorityKey = authorityKeyOf(ctx.context.identity); return createApprovalRequest({ moduleId: ctx.moduleId, callerId: ctx.context.callerId, action: ctx.moduleId, arguments: args, - context: scope === undefined ? ctx.context : policyApprovalContext(ctx.context), + context: scope === undefined && authorityKey === null ? 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, + ...(authorityKey === null ? {} : { authorityKey }), }); } @@ -661,16 +674,18 @@ export class BuiltinApprovalGate implements Step { handler: ApprovalHandler, token: string | null, request: ApprovalRequest, auditContext = request.context, ): Promise { const final = request.canonicalArgsDigest !== undefined; + const authorityScoped = request.authorityKey !== 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); + const supportsScope = (!final || handler.supportsFinalScope === true) && + (!authorityScoped || handler.supportsAuthorityScope === true); + result = await this._requestApproval(handler, token, request, supportsScope); + if (final || authorityScoped) result = this._safeFinalResult(result, supportsScope); } catch (error) { - if (!final) throw error; + if (!final && !authorityScoped) throw error; result = createApprovalResult({ status: 'rejected' }); } - if (final) auditContext.cancelToken?.check(); + if (final || authorityScoped) auditContext.cancelToken?.check(); this._emitAudit(result, request.moduleId, auditContext, token); if (result.status === 'approved') { @@ -941,6 +956,7 @@ export class BuiltinExecute implements Step { constructor(private readonly _config: Config | null) {} async execute(ctx: PipelineContext): Promise { + assertScopedInvocation(ctx, true); const invocation = policyInvocationOf(ctx); let inputs = ctx.inputs; if (invocation) { @@ -971,7 +987,10 @@ export class BuiltinExecute implements Step { invocation.producer = protectedProducer; ctx.outputStream = protectedProducer; } else { - ctx.outputStream = this._streamWithLease(ctx, () => candidate.stream(ctx.inputs, ctx.context)); + ctx.outputStream = this._streamWithLease(ctx, () => { + assertScopedInvocation(ctx, true); + return candidate.stream(ctx.inputs, ctx.context); + }); } return { action: 'continue' }; } diff --git a/typescript/src/capability-discovery.ts b/typescript/src/capability-discovery.ts index 8c08bd9f..d073bcb6 100644 --- a/typescript/src/capability-discovery.ts +++ b/typescript/src/capability-discovery.ts @@ -1,5 +1,6 @@ import type { Context } from './context.js'; import { InvalidInputError } from './errors.js'; +import { cursorPrincipal } from './identity.js'; import { copyPolicyInputs } from './policy-evaluation.js'; import { uuidV4 } from './utils/uuid.js'; @@ -103,9 +104,7 @@ function buildCursorBinding(context: Context | null, filters: SearchFilters): st const identity = context?.identity; try { return copyPolicyInputs('capability discovery', { - principal: identity === null || identity === undefined ? null : { - id: identity.id, type: identity.type, roles: [...new Set(identity.roles)].sort(), attrs: identity.attrs, - }, + principal: cursorPrincipal(identity), callerId: context?.callerId ?? null, callChain: [...(context?.callChain ?? [])], filters: { ...filters, readonly: filters.readonly ?? null }, diff --git a/typescript/src/context.ts b/typescript/src/context.ts index 89bc353f..363eecfb 100644 --- a/typescript/src/context.ts +++ b/typescript/src/context.ts @@ -9,46 +9,10 @@ import { copyObservationState, inheritObservationParent, setRemoteSpanParent } f import { ContextLogger } from './observability/context-logger.js'; import type { TraceParent } from './trace-context.js'; -export class Identity { - readonly id: string; - readonly type: string; - readonly roles: readonly string[]; - readonly attrs: Readonly>; +import { hasScopeCeiling, identityFromWire, identityToWire, type Identity } from './identity.js'; - constructor( - id: string, - type: string = 'user', - roles: string[] = [], - attrs: Record = {}, - ) { - this.id = id; - this.type = type; - this.roles = Object.freeze([...roles]); - this.attrs = Object.freeze({ ...attrs }); - Object.freeze(this); - } - - /** - * Get an attribute value by key. - * - * Aligned with apcore D-03. May trigger a fetch if the identity - * is lazy-loaded (future extension). - */ - getAttr(key: string, defaultValue?: T): T | undefined { - // Presence check so a stored `null` is returned as null rather than - // coalesced to the default (Python/Rust parity: `attrs.get(key, default)`). - return key in this.attrs ? (this.attrs[key] as T) : defaultValue; - } -} - -export function createIdentity( - id: string, - type: string = 'user', - roles: string[] = [], - attrs: Record = {}, -): Identity { - return new Identity(id, type, roles, attrs); -} +export { Identity, createIdentity } from './identity.js'; +export type { IdentityOptions } from './identity.js'; export class Context { readonly traceId: string; @@ -93,6 +57,9 @@ export class Context { this.callChain = Object.freeze([...callChain]); this.executor = executor; this.identity = identity; + if (hasScopeCeiling(identity)) { + Object.defineProperty(this, 'identity', { writable: false, configurable: false }); + } this.redactedInputs = redactedInputs; this.redactedOutput = redactedOutput; this.data = data; @@ -325,18 +292,7 @@ export class Context { data.identity != null && typeof data.identity === 'object' && !Array.isArray(data.identity) ? (data.identity as Record) : null; - const identity = identityData - ? createIdentity( - typeof identityData.id === 'string' ? identityData.id : String(identityData.id ?? ''), - typeof identityData.type === 'string' ? identityData.type : 'user', - Array.isArray(identityData.roles) - ? identityData.roles.filter((r): r is string => typeof r === 'string') - : [], - identityData.attrs != null && typeof identityData.attrs === 'object' && !Array.isArray(identityData.attrs) - ? (identityData.attrs as Record) - : {}, - ) - : null; + const identity = identityData === null ? null : identityFromWire(identityData); return new Context( typeof data.trace_id === 'string' ? data.trace_id : '', @@ -382,14 +338,7 @@ export class Context { trace_id: this.traceId, caller_id: this.callerId, call_chain: [...this.callChain], - identity: this.identity - ? { - id: this.identity.id, - type: this.identity.type, - roles: [...this.identity.roles], - attrs: { ...this.identity.attrs }, - } - : null, + identity: this.identity === null ? null : identityToWire(this.identity), data: filteredData, }; if (this.redactedInputs !== undefined && this.redactedInputs !== null) { diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index fc91c965..9df9f691 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -31,6 +31,7 @@ import { BuiltinACLCheck, BuiltinApprovalGate, BuiltinContextCreation, + BuiltinExecute, BuiltinModuleLookup, buildInternalStrategy, buildMinimalStrategy, @@ -49,6 +50,8 @@ import { buildStrategyFromConfigSync, ConfigurationError } from './pipeline-conf // Node-only code into the browser dependency graph. import { type EventEmitter, createEvent } from './events/emitter.js'; import { Context } from './context.js'; +import { hasScopeCeiling } from './identity.js'; +import { assertScopeGate, assertScopedInvocation, beginScopedInvocation, isStockScopeAcl } from './scoped-invocation.js'; import { governanceUnion } from './schema/annotations.js'; import { sourceSchemaFor } from './schema/loader-pure.js'; import { RedactionConfig } from './observability/context-logger.js'; @@ -894,9 +897,11 @@ export class Executor { !lookup.usesRegistry(this._registry) || lookup.toggleState.isDisabled(moduleId)) return null; const generation = this._registry.publicGeneration(moduleId); if (generation === null) return null; - const gates = steps.filter(step => step.name === 'acl_check' || step instanceof BuiltinACLCheck); + const gates = steps.filter(step => (step.name === 'acl_check' || step instanceof BuiltinACLCheck) && + stepMatchesModule(step, moduleId)); if (gates.length === 0 || steps.indexOf(gates[0]) <= lookupIndex) return null; const target = parent.child(moduleId); + if (hasScopeCeiling(target.identity) && !this._hasScopeGate(this._strategy, moduleId)) return null; let approvalRequired = false; let approvalConditional = false; for (const gate of gates) { @@ -1165,6 +1170,27 @@ export class Executor { return this._policyEvaluator === null ? strategy : withPostValidationPolicy(strategy, this._policyEvaluator, this._eventEmitter); } + private _hasScopeGate(strategy: ExecutionStrategy, moduleId: string): boolean { + const steps = strategy.steps.filter(step => stepMatchesModule(step, moduleId)); + const create = steps.findIndex(step => step.name === 'context_creation'); + const lookup = steps.findIndex(step => step.name === 'module_lookup'); + const dispatch = steps.findIndex(step => step.name === 'execute'); + const check = steps.findIndex(step => step.name === 'acl_check'); + const gate = steps[check]; + const execute = steps[dispatch]; + return create >= 0 && create < lookup && lookup < check && check < dispatch && + Object.getPrototypeOf(steps[create]) === BuiltinContextCreation.prototype && + steps[create].execute === BuiltinContextCreation.prototype.execute && + Object.getPrototypeOf(steps[lookup]) === BuiltinModuleLookup.prototype && + steps[lookup].execute === BuiltinModuleLookup.prototype.execute && + gate.ignoreErrors !== true && gate instanceof BuiltinACLCheck && + Object.getPrototypeOf(gate) === BuiltinACLCheck.prototype && + gate.execute === BuiltinACLCheck.prototype.execute && gate.pure && + isStockScopeAcl(gate.acl) && execute instanceof BuiltinExecute && + Object.getPrototypeOf(execute) === BuiltinExecute.prototype && + execute.execute === BuiltinExecute.prototype.execute; + } + use(middleware: Middleware): Executor { this._middlewareManager.add(middleware); return this; @@ -1248,6 +1274,7 @@ export class Executor { // is enforced regardless of how the caller built the Context. let ctx = context ?? Context.create(); ctx = bindExecutorToCtx(ctx, this); + if (hasScopeCeiling(ctx.identity)) assertScopeGate(ctx, moduleId, this._hasScopeGate(strategy, moduleId)); const pipeCtx: PipelineContext = { moduleId, inputs: inputs ?? {}, @@ -1269,12 +1296,14 @@ export class Executor { try { while (true) { try { + beginScopedInvocation(pipeCtx); if (protectedCall) { beginPolicyInvocation(pipeCtx); pipeCtx.inputs = policyIngressInputs(pipeCtx.inputs, moduleId); } prepareApprovalInputs(pipeCtx); const [output, trace] = await this._pipelineEngine.run(strategy, pipeCtx); + assertScopedInvocation(pipeCtx, true); if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw new PolicyEvaluationError(moduleId); return [(output ?? {}) as Record, trace]; } catch (exc) { @@ -1437,6 +1466,7 @@ export class Executor { // Issue #66: auto-bind executor (see call() for rationale). let ctx = context ?? Context.create(); ctx = bindExecutorToCtx(ctx, this); + if (hasScopeCeiling(ctx.identity)) assertScopeGate(ctx, moduleId, this._hasScopeGate(strategy, moduleId)); const pipeCtx: PipelineContext = { moduleId, inputs: inputs ?? {}, @@ -1475,12 +1505,14 @@ export class Executor { try { // Run through producer creation, or finish the unary fallback. try { + beginScopedInvocation(pipeCtx); if (protectedCall) { beginPolicyInvocation(pipeCtx); pipeCtx.inputs = policyIngressInputs(pipeCtx.inputs, moduleId); } prepareApprovalInputs(pipeCtx); await pipeline.next(); + assertScopedInvocation(pipeCtx, true); const invocation = policyInvocationOf(pipeCtx); if (protectedCall && !invocation?.dispatched && !invocation?.producer) throw new PolicyEvaluationError(moduleId); } catch (exc) { @@ -1742,11 +1774,16 @@ export class Executor { dryRun: true, }; if (protectedCall) beginPolicyInvocation(pipeCtx); + beginScopedInvocation(pipeCtx); try { let trace: PipelineTrace | null = null; try { + if (hasScopeCeiling(validateCtx.identity)) { + assertScopeGate(validateCtx, moduleId, this._hasScopeGate(strategy, moduleId)); + } const [, t] = await this._pipelineEngine.run(strategy, pipeCtx); + if (!t.steps.some(step => step.error !== undefined)) assertScopedInvocation(pipeCtx, true); trace = t; } catch (e) { // Step raised a domain error (ModuleNotFoundError, ACLDeniedError, etc.) diff --git a/typescript/src/identity.ts b/typescript/src/identity.ts new file mode 100644 index 00000000..0e8612c7 --- /dev/null +++ b/typescript/src/identity.ts @@ -0,0 +1,211 @@ +/** Trusted caller identity and its active local delegation chain. */ + +import { compareCodePoints } from './utils/compare-code-points.js'; + +export const MAX_DELEGATION_DEPTH = 8; +const trustedIdentities = new WeakSet(); + +export interface IdentityOptions { + readonly scopes?: readonly string[]; + readonly onBehalfOf?: Identity; + readonly issuer?: string; +} + +export class Identity { + readonly id: string; + readonly type: string; + readonly roles: readonly string[]; + readonly attrs: Readonly>; + readonly scopes?: readonly string[]; + readonly onBehalfOf?: Identity; + readonly issuer?: string; + + constructor( + id: string, type: string = 'user', roles: readonly string[] = [], + attrs: Record = {}, options: IdentityOptions = {}, + ) { + const { scopes, onBehalfOf, issuer } = options; + if (scopes !== undefined && (!Array.isArray(scopes) || ![...scopes].every(isScopeLiteral))) { + throw new TypeError('Identity scopes must be a list of nonempty strings without whitespace'); + } + if (issuer !== undefined && !isNonemptyString(issuer)) { + throw new TypeError('Identity issuer must be a nonempty string'); + } + if ((scopes !== undefined || issuer !== undefined || onBehalfOf !== undefined) && + (!isNonemptyString(id) || !isNonemptyString(type) || + !Array.isArray(roles) || ![...roles].every(role => typeof role === 'string') || !isRecord(attrs))) { + throw new TypeError('Invalid scoped identity'); + } + if (onBehalfOf !== undefined) { + if (!isTrustedIdentity(onBehalfOf) || delegationDepthOf(onBehalfOf) >= MAX_DELEGATION_DEPTH) { + throw new TypeError('Invalid identity delegation chain'); + } + const ceiling = onBehalfOf.scopes; + if (scopes === undefined || ceiling === undefined || !scopes.every(scope => ceiling.includes(scope))) { + throw new TypeError('Delegated scopes must be a subset of the parent scopes'); + } + } + this.id = id; + this.type = type; + this.roles = Object.freeze([...roles]); + this.attrs = Object.freeze({ ...attrs }); + if (scopes !== undefined) this.scopes = Object.freeze(sortedSet(scopes)); + if (onBehalfOf !== undefined) this.onBehalfOf = onBehalfOf; + if (issuer !== undefined) this.issuer = issuer; + trustedIdentities.add(this); + Object.freeze(this); + } + + /** Read an attribute, preserving a stored null. */ + getAttr(key: string, defaultValue?: T): T | undefined { + return key in this.attrs ? (this.attrs[key] as T) : defaultValue; + } + + get rootSubject(): Identity { + return rootSubjectOf(this); + } + + get delegationDepth(): number { + return delegationDepthOf(this); + } + + /** Issue explicitly attenuated authority to the supplied actor. */ + delegate(actor: Identity, scopes: readonly string[]): Identity { + if (!isTrustedIdentity(actor) || actor.onBehalfOf !== undefined) { + throw new TypeError('A trusted direct actor is required'); + } + const ceiling = actor.scopes; + if (ceiling !== undefined && (!Array.isArray(scopes) || !scopes.every(scope => ceiling.includes(scope)))) { + throw new TypeError('Delegated scopes must be a subset of the actor scopes'); + } + return new Identity(actor.id, actor.type, actor.roles, actor.attrs, { scopes, onBehalfOf: this, issuer: actor.issuer }); + } + + /** The current authorization scope, including trusted local lineage. */ + authorityKey(): string | null { + return authorityKeyOf(this); + } + + /** The transport owner remains stable when the same actor refreshes its scopes. */ + ownerKey(): string | null { + return this.scopes === undefined ? null : JSON.stringify([principal(this), principal(rootSubjectOf(this))]); + } +} + +function isNonemptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} + +/** @internal Check a case-sensitive scope literal at all authority entry points. */ +export function isScopeLiteral(value: unknown): value is string { + return isNonemptyString(value) && !/\p{White_Space}/u.test(value); +} + +/** @internal Reject identities that were not constructed by the native SDK. */ +export function isTrustedIdentity(identity: Identity | null | undefined): identity is Identity { + return identity != null && trustedIdentities.has(identity); +} + +/** @internal Follow the validated active links without getter overrides. */ +export function rootSubjectOf(identity: Identity): Identity { + let subject = identity; + while (subject.onBehalfOf !== undefined) subject = subject.onBehalfOf; + return subject; +} + +/** @internal Count the validated active links without getter overrides. */ +export function delegationDepthOf(identity: Identity): number { + let depth = 0; + for (let ancestor = identity.onBehalfOf; ancestor !== undefined; ancestor = ancestor.onBehalfOf) depth++; + return depth; +} + +function sortedSet(values: readonly string[]): string[] { + return [...new Set(values)].sort(compareCodePoints); +} + +function principal(identity: Identity): [string | null, string, string] { + return [identity.issuer ?? null, identity.type, identity.id]; +} + +function authorityChain(identity: Identity): unknown[] { + const chain: unknown[] = []; + for (let actor: Identity | undefined = identity; actor !== undefined; actor = actor.onBehalfOf) { + chain.push([principal(actor), sortedSet(actor.roles), actor.scopes ?? null]); + } + return chain; +} + +/** @internal Resolve the native authority key without dispatching to a caller override. */ +export function authorityKeyOf(identity: Identity | null | undefined): string | null { + return identity?.scopes === undefined ? null : JSON.stringify(authorityChain(requireTrustedIdentity(identity))); +} + +function requireTrustedIdentity(identity: Identity): Identity { + if (!isTrustedIdentity(identity)) throw new TypeError('A trusted identity is required'); + return identity; +} + +export function createIdentity( + id: string, type: string = 'user', roles: readonly string[] = [], + attrs: Record = {}, options?: IdentityOptions, +): Identity { + return new Identity(id, type, roles, attrs, options); +} + +/** @internal Whether the caller opted into the scoped grant requirement. */ +export function hasScopeCeiling(identity: Identity | null | undefined): boolean { + return identity?.scopes !== undefined; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** @internal Encode only present optional identity fields. */ +export function identityToWire(identity: Identity): Record { + return { + id: identity.id, type: identity.type, roles: [...identity.roles], attrs: { ...identity.attrs }, + ...(identity.scopes === undefined ? {} : { scopes: [...identity.scopes] }), + ...(identity.issuer === undefined ? {} : { issuer: identity.issuer }), + ...(identity.onBehalfOf === undefined ? {} : { on_behalf_of: identityToWire(identity.onBehalfOf) }), + }; +} + +/** @internal Restore a detached trusted identity after structurally validating its chain. */ +export function identityFromWire(data: Record, depth: number = 0): Identity { + const { id, type, roles, attrs, scopes, issuer, on_behalf_of: parent } = data; + const strict = depth > 0 || ['scopes', 'issuer', 'on_behalf_of'].some(key => Object.hasOwn(data, key)); + if (depth > MAX_DELEGATION_DEPTH || + (strict && (!isNonemptyString(id) || !isNonemptyString(type) || + (roles !== undefined && (!Array.isArray(roles) || ![...roles].every(role => typeof role === 'string'))) || + (attrs !== undefined && !isRecord(attrs)))) || + (Object.hasOwn(data, 'scopes') && !Array.isArray(scopes)) || + (Object.hasOwn(data, 'issuer') && !isNonemptyString(issuer)) || + (Object.hasOwn(data, 'on_behalf_of') && !isRecord(parent))) { + throw new TypeError('Invalid wire identity'); + } + return new Identity( + typeof id === 'string' ? id : String(id ?? ''), + typeof type === 'string' ? type : 'user', + Array.isArray(roles) ? roles.filter((r): r is string => typeof r === 'string') : [], + isRecord(attrs) ? attrs : {}, + { + scopes: Array.isArray(scopes) ? scopes : undefined, + issuer: typeof issuer === 'string' ? issuer : undefined, + onBehalfOf: isRecord(parent) ? identityFromWire(parent, depth + 1) : undefined, + }, + ); +} + +/** @internal Keep the legacy cursor shape and bind scoped authority without its attributes. */ +export function cursorPrincipal(identity: Identity | null | undefined): unknown { + if (identity == null) return null; + const authorityKey = authorityKeyOf(identity); + return authorityKey === null ? { ...identityToWire(identity), roles: sortedSet(identity.roles) } : { authorityKey }; +} + +/** @internal Detach a snapshot of an identity, including its trusted active lineage. */ +export function detachIdentity(identity: Identity | null): Identity | null { + return identity === null ? null : identityFromWire(structuredClone(identityToWire(identity))); +} diff --git a/typescript/src/node-api.ts b/typescript/src/node-api.ts index 1658c303..e1ceff88 100644 --- a/typescript/src/node-api.ts +++ b/typescript/src/node-api.ts @@ -5,7 +5,7 @@ export type { DrainAbortedContext, DrainAbortReason, DrainContext, LifecycleErro // Core export { CancelToken, ExecutionCancelledError } from './cancel.js'; -export { Context, createIdentity } from './context.js'; +export { Context, Identity, createIdentity } from './context.js'; export { ContextKey } from './context-key.js'; export { TRACING_SPANS, @@ -15,7 +15,7 @@ export { REDACTED_OUTPUT, RETRY_COUNT_BASE, } from './context-keys.js'; -export type { Identity, ContextFactory } from './context.js'; +export type { IdentityOptions, ContextFactory } from './context.js'; export { Registry, REGISTRY_EVENTS, diff --git a/typescript/src/policy-evaluation.ts b/typescript/src/policy-evaluation.ts index 79423c54..99838ec1 100644 --- a/typescript/src/policy-evaluation.ts +++ b/typescript/src/policy-evaluation.ts @@ -1,6 +1,7 @@ import { awaitExecution, CancelToken, ExecutionCancelledError } from './cancel.js'; -import { Context, createIdentity, type Identity } from './context.js'; +import { Context, type Identity } from './context.js'; import { PolicyEvaluationError } from './errors.js'; +import { authorityKeyOf, detachIdentity } from './identity.js'; import type { ApprovalHandler } from './approval.js'; import type { ModuleAnnotations } from './module.js'; import type { PipelineContext } from './pipeline.js'; @@ -42,6 +43,7 @@ interface PolicyInvocation { identity?: Identity | null; principalId?: string; principalType?: string; + authorityKey?: string | null; selected?: { module: unknown; version: string | null; governance: ModuleAnnotations | null }; aclApprovalRequired?: boolean; earlyApproval?: { needed: boolean; annotations: ModuleAnnotations; handler: ApprovalHandler | null }; @@ -79,7 +81,8 @@ export function assertPolicyBinding(ctx: PipelineContext, invocation: PolicyInvo 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)) || + context.identity?.id !== invocation.principalId || context.identity?.type !== invocation.principalType || + authorityKeyOf(context.identity) !== invocation.authorityKey)) || (selected && ctx.module !== selected.module)) { throw new PolicyEvaluationError(invocation.id); } @@ -199,10 +202,6 @@ export async function policyArgumentsDigest(moduleId: string, snapshot: Validati } } -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( diff --git a/typescript/src/scoped-invocation.ts b/typescript/src/scoped-invocation.ts new file mode 100644 index 00000000..10aa790b --- /dev/null +++ b/typescript/src/scoped-invocation.ts @@ -0,0 +1,60 @@ +import { ACL, type AccessDecision } from './acl.js'; +import type { Context, Identity } from './context.js'; +import { ACLDeniedError } from './errors.js'; +import { hasScopeCeiling } from './identity.js'; +import type { PipelineContext } from './pipeline.js'; + +type ScopedBinding = { + readonly identity: Identity; + readonly moduleId: string; + readonly callerId: string | null; + readonly callChain: readonly string[]; + allowed: boolean; +}; + +const bindings = new WeakMap(); + +/** @internal Require the actual stock ACL semantics for a scoped call. */ +export function isStockScopeAcl(acl: ACL | null): acl is ACL { + return acl !== null && Object.getPrototypeOf(acl) === ACL.prototype && + acl.asyncCheckAccess === ACL.prototype.asyncCheckAccess && + acl.evaluateVisibility === ACL.prototype.evaluateVisibility; +} + +/** @internal Bind the authority before any arbitrary middleware hook runs. */ +export function beginScopedInvocation(ctx: PipelineContext): void { + const identity = ctx.context.identity; + if (identity !== null && hasScopeCeiling(identity)) { + const callChain = ctx.context.callChain; + bindings.set(ctx, { + identity, moduleId: ctx.moduleId, callerId: callChain.at(-1) ?? null, + callChain: [...callChain, ctx.moduleId], allowed: false, + }); + } +} + +function remainsBound(ctx: PipelineContext, binding: ScopedBinding): boolean { + return ctx.context.identity === binding.identity && ctx.moduleId === binding.moduleId && + ctx.context.callerId === binding.callerId && ctx.context.callChain.length === binding.callChain.length && + ctx.context.callChain.every((id, index) => id === binding.callChain[index]); +} + +/** @internal Check the bound authority at the ACL gate and before dispatch. */ +export function assertScopedInvocation(ctx: PipelineContext, requireGrant: boolean): void { + const binding = bindings.get(ctx); + if (binding && (!remainsBound(ctx, binding) || (requireGrant && !binding.allowed))) { + throw new ACLDeniedError(binding.callerId, binding.moduleId); + } +} + +/** @internal Call only from the stock gate after consulting the stock ACL. */ +export function recordScopedGrant(ctx: PipelineContext, decision: AccessDecision): void { + assertScopedInvocation(ctx, false); + const binding = bindings.get(ctx); + if (binding) binding.allowed = decision.access === 'allow'; +} + +/** @internal Fail closed before traversing a strategy without a scope gate. */ +export function assertScopeGate(ctx: Context, moduleId: string, hasGate: boolean): void { + if (hasScopeCeiling(ctx.identity) && !hasGate) throw new ACLDeniedError(ctx.callerId, moduleId); +} diff --git a/typescript/src/sys-modules/audit.ts b/typescript/src/sys-modules/audit.ts index f78bfe52..de3ebce3 100644 --- a/typescript/src/sys-modules/audit.ts +++ b/typescript/src/sys-modules/audit.ts @@ -1,4 +1,4 @@ -import type { Context } from '../context.js'; +import type { Context, Identity } from '../context.js'; export type AuditAction = 'update_config' | 'reload_module' | 'toggle_feature'; @@ -8,6 +8,8 @@ export interface AuditEntry { targetModuleId: string; actorId: string; actorType: string; + subjectId?: string; + delegationDepth?: number; traceId: string; change: { before: unknown; after: unknown }; /** @@ -65,12 +67,17 @@ export function buildAuditEntry( change: { before: unknown; after: unknown }, correlationId = '', ): AuditEntry { + const identity = context?.identity; return { timestamp: new Date().toISOString(), action, targetModuleId, actorId: context?.identity?.id ?? 'unknown', actorType: context?.identity?.type ?? 'unknown', + ...(identity == null ? {} : { + subjectId: identity.rootSubject?.id ?? identity.id, + delegationDepth: identity.delegationDepth ?? 0, + }), traceId: context?.traceId ?? 'unknown', change, correlationId, @@ -131,34 +138,47 @@ export function extractAuditIdentity( if (!ident) { return { caller_id: callerId, identity: null }; } - const snapshot: Record = { + return { caller_id: callerId, identity: auditIdentitySnapshot(ident) }; +} + +const identityAuditFields = new Set([ + 'id', 'type', 'roles', 'display_name', 'actor_id', 'subject_id', 'delegation_depth', 'on_behalf_of', 'issuer', 'scopes', +]); + +function auditIdentitySnapshot(ident: Identity): Record { + const attrs = Object.fromEntries( + Object.entries(ident.attrs).filter(([key]) => !identityAuditFields.has(key)), + ); + const displayName = ident.attrs['display_name']; + return { + ...redactAuditFields(attrs, new Set()), id: ident.id, type: ident.type, + actor_id: ident.id, + subject_id: ident.rootSubject?.id ?? ident.id, + delegation_depth: ident.delegationDepth ?? 0, + ...(ident.roles.length === 0 ? {} : { roles: [...ident.roles] }), + ...(typeof displayName === 'string' && displayName.length > 0 ? { display_name: displayName } : {}), + ...(ident.onBehalfOf === undefined ? {} : { on_behalf_of: auditIdentitySnapshot(ident.onBehalfOf) }), }; - // D-118: an EMPTY roles list is omitted, not emitted as `roles: []`. The spec - // names only `id`, `type` and optionally `display_name` for this snapshot, - // and apcore-python and apcore-rust both omit the key; this SDK emitted it - // unconditionally. `roles: []` and an absent `roles` are different claims to a - // subscriber reading the audit trail — the first says the principal was - // checked and carries no roles, the second says roles were not part of this - // record at all. Emitting the first for every identity makes the distinction - // unavailable. - if (ident.roles.length > 0) { - snapshot['roles'] = [...ident.roles]; - } - // Surface display_name from attrs if present (spec #45.2 calls it out as - // an optional first-class field on the audit identity snapshot). - const displayName = (ident.attrs as Record)['display_name']; - if (typeof displayName === 'string' && displayName.length > 0) { - snapshot['display_name'] = displayName; - } - // Pass through any other attrs, redacting those whose key matches a - // sensitive substring (case-insensitive). - for (const [k, v] of Object.entries(ident.attrs)) { - if (k === 'display_name') continue; - const lk = k.toLowerCase(); - const sensitive = SENSITIVE_IDENTITY_ATTR_SUBSTRINGS.some((s) => lk.includes(s)); - snapshot[k] = sensitive ? '' : v; +} + +function redactAuditFields(data: Record, ancestors: Set): Record { + return Object.fromEntries(Object.entries(data).map(([key, value]) => { + const sensitive = SENSITIVE_IDENTITY_ATTR_SUBSTRINGS.some(part => key.toLowerCase().includes(part)); + return [key, sensitive ? '' : redactAuditValue(value, ancestors)]; + })); +} + +function redactAuditValue(value: unknown, ancestors: Set): unknown { + if (typeof value === 'function') return ''; + if (typeof value !== 'object' || value === null) return value; + if (ancestors.has(value)) return ''; + ancestors.add(value); + try { + if (Array.isArray(value)) return value.map(item => redactAuditValue(item, ancestors)); + return redactAuditFields(value as Record, ancestors); + } finally { + ancestors.delete(value); } - return { caller_id: callerId, identity: snapshot }; } diff --git a/typescript/tests/conformance-identity-delegation.test.ts b/typescript/tests/conformance-identity-delegation.test.ts new file mode 100644 index 00000000..f19a010a --- /dev/null +++ b/typescript/tests/conformance-identity-delegation.test.ts @@ -0,0 +1,43 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { ACL, Context, type ACLRule } from '../src/index.js'; +import { findFixturesRoot } from './spec-repo.js'; + +interface DelegationCase { + readonly id: string; + readonly input: { + readonly identity: Record; + readonly rules?: Omit[]; + readonly default_effect?: 'allow' | 'deny'; + }; + readonly expected: { + readonly valid: boolean; + readonly depth?: number; + readonly subject_id?: string; + readonly effect?: 'allow' | 'deny'; + }; +} + +const fixture = JSON.parse(readFileSync(join(findFixturesRoot(), 'identity_delegation.json'), 'utf8')) as { + readonly test_cases: readonly DelegationCase[]; +}; + +describe('identity_delegation.json', () => { + it.each(fixture.test_cases)('$id', async ({ input, expected }) => { + const restore = (): Context => Context.fromJSON({ identity: input.identity }); + if (!expected.valid) { + expect(restore).toThrow(TypeError); + return; + } + const context = restore(); + expect(context.identity?.delegationDepth).toBe(expected.depth); + expect(context.identity?.rootSubject.id).toBe(expected.subject_id); + if (input.rules !== undefined) { + const acl = new ACL(input.rules.map(rule => ({ description: '', ...rule })), input.default_effect); + expect(acl.checkAccess(null, 'delegation.target', context).access).toBe(expected.effect); + expect((await acl.asyncCheckAccess(null, 'delegation.target', context)).access).toBe(expected.effect); + expect(acl.evaluateVisibility(null, 'delegation.target', context).visible).toBe(expected.effect === 'allow'); + } + }); +}); diff --git a/typescript/tests/test-identity-delegation.test.ts b/typescript/tests/test-identity-delegation.test.ts new file mode 100644 index 00000000..c55970f8 --- /dev/null +++ b/typescript/tests/test-identity-delegation.test.ts @@ -0,0 +1,214 @@ +import { describe, expect, it, vi } from 'vitest'; +import { ACL, auditEntryToWire, type ACLRule } from '../src/acl.js'; +import { + Context, createAnnotations, createApprovalResult, createIdentity, Executor, Registry, + STREAMING_MARKER, type ApprovalHandler, type ApprovalRequest, type PolicyEvaluationRequest, +} from '../src/index.js'; +import { extractAuditIdentity } from '../src/sys-modules/audit.js'; + +const moduleId = 'delegation.target'; +const permit: ACLRule = { + callers: ['@external'], targets: ['delegation.*'], effect: 'allow', description: 'Grant scope', + conditions: { scopes: ['read'] }, +}; + +function actorContext(subject = 'alice', scopes: readonly string[] = ['read']): Context { + const root = createIdentity(subject, 'user', ['reviewer'], { tenant: { name: 'example' } }, { scopes: ['read', 'write'] }); + return Context.create(root.delegate(createIdentity('worker', 'agent', ['automation']), scopes)); +} + +async function setup() { + const registry = new Registry(); + const execute = vi.fn(() => ({ done: true })); + const stream = vi.fn(async function* () { yield { done: true }; }); + const preview = vi.fn(() => null); + for (const id of [moduleId, 'delegation.other']) { + await registry.register(id, { + inputSchema: { type: 'object' }, + outputSchema: { type: 'object' }, + description: 'Task', + annotations: createAnnotations({ streaming: true, discoverable: true }), + [STREAMING_MARKER]: true, + execute, stream, preview, + }); + } + return { registry, execute, stream, preview }; +} + +async function collect(chunks: AsyncGenerator>): Promise[]> { + const results: Record[] = []; + for await (const chunk of chunks) results.push(chunk); + return results; +} + +describe('scoped identity delegation', () => { + it('keeps legacy, empty, and delegated authority distinct across context restoration', () => { + const legacy = createIdentity('alice'); + const root = createIdentity('alice', 'user', ['reviewer'], {}, { scopes: ['write', 'read'], issuer: 'issuer' }); + const actor = createIdentity('worker', 'agent', ['automation'], {}, { issuer: 'issuer' }); + const leaf = root.delegate(actor, ['read']); + const empty = root.delegate(actor, []); + + expect(legacy.authorityKey()).toBeNull(); + expect(actor.authorityKey()).toBeNull(); + expect(actor.ownerKey()).toBeNull(); + expect(leaf.rootSubject).toBe(root); + expect(leaf.delegationDepth).toBe(1); + expect(empty.ownerKey()).toBe(leaf.ownerKey()); + expect(empty.authorityKey()).not.toBe(leaf.authorityKey()); + expect(Object.isFrozen(leaf.scopes)).toBe(true); + expect(Context.fromJSON(Context.create(leaf).toJSON()).identity?.authorityKey()).toBe(leaf.authorityKey()); + expect(Context.create(legacy).toJSON().identity).not.toHaveProperty('scopes'); + expect(() => root.delegate(actor, ['admin'])).toThrow(); + expect(() => root.delegate(leaf, ['read'])).toThrow(); + const restricted = createIdentity('worker', 'agent', [], {}, { scopes: [] }); + expect(() => root.delegate(restricted, ['read'])).toThrow(); + expect(() => root.delegate(actor, ['not\u00a0a.scope'])).toThrow(); + expect(() => legacy.delegate(actor, [])).toThrow(); + + const wire = Context.create(leaf).toJSON(); + expect(() => Context.fromJSON({ ...wire, identity: { ...(wire.identity as object), scopes: ['admin'] } })).toThrow(); + let nested = leaf; + for (let depth = 2; depth <= 8; depth++) nested = nested.delegate(actor, ['read']); + expect(nested.delegationDepth).toBe(8); + expect(() => nested.delegate(actor, ['read'])).toThrow(); + const cycle: Record = { id: 'cycle', type: 'agent', scopes: ['read'] }; + cycle.on_behalf_of = cycle; + expect(() => Context.fromJSON({ identity: cycle })).toThrow(); + }); + + it('requires the first matching ACL grant to prove all scopes and uses the root subject separately', async () => { + const root = createIdentity('alice', 'user', ['reviewer'], {}, { scopes: ['read', 'write'] }); + const leaf = root.delegate(createIdentity('worker', 'agent', ['automation']), ['read']); + const context = Context.create(leaf); + const allow = { callers: ['@external'], targets: ['*'], effect: 'allow', description: 'grant' }; + const conditions = { + scopes: ['read'], identity_types: ['agent'], roles: ['automation'], + subject_types: ['user'], subject_roles: ['reviewer'], max_delegation_depth: 1, + }; + const rejecting = [ + new ACL([], 'allow'), + new ACL([allow, { ...allow, conditions }]), + new ACL([{ ...allow, conditions: { $or: [{ scopes: ['read'] }] } }]), + new ACL([{ ...allow, conditions: { ...conditions, scopes: ['read', 'write'] } }], 'allow'), + ]; + for (const acl of rejecting) { + expect(acl.check(null, 'fixture.target', context)).toBe(false); + expect(await acl.asyncCheck(null, 'fixture.target', context)).toBe(false); + expect(acl.evaluateVisibility(null, 'fixture.target', context).visible).toBe(false); + } + const acl = new ACL([{ ...allow, conditions }]); + expect(acl.check(null, 'fixture.target', context)).toBe(true); + expect(await acl.asyncCheck(null, 'fixture.target', context)).toBe(true); + expect(acl.evaluateVisibility(null, 'fixture.target', context).visible).toBe(true); + }); + + it('enforces a stock scope gate for call, stream, preflight, and capability discovery', async () => { + const { registry, execute, preview, stream } = await setup(); + const context = actorContext(); + class CustomAcl extends ACL { + override asyncCheckAccess = vi.fn(async () => ({ + access: 'allow' as const, approvalRequired: false, matchedRuleIndex: null, reason: 'custom', + })); + } + for (const options of [{}, { strategy: 'minimal' }, { acl: new CustomAcl([permit]) }]) { + const executor = new Executor({ registry, ...options }); + await expect(executor.call(moduleId, {}, context)).rejects.toMatchObject({ code: 'ACL_DENIED' }); + await expect(collect(executor.stream(moduleId, {}, context))).rejects.toMatchObject({ code: 'ACL_DENIED' }); + expect(await executor.validate(moduleId, {}, context)).toMatchObject({ valid: false }); + expect(executor.listCallable(context).items).toEqual([]); + } + expect(execute).not.toHaveBeenCalled(); + expect(stream).not.toHaveBeenCalled(); + expect(preview).not.toHaveBeenCalled(); + + const executor = new Executor({ registry, acl: new ACL([permit]) }); + expect(await executor.call(moduleId, {}, context)).toEqual({ done: true }); + expect(await collect(executor.stream(moduleId, {}, context))).toEqual([{ done: true }]); + expect(await executor.validate(moduleId, {}, context)).toMatchObject({ valid: true }); + const first = executor.listCallable(context, { limit: 1 }); + expect(first.nextCursor).not.toBeNull(); + const options = { limit: 1, cursor: first.nextCursor }; + expect(executor.listCallable(actorContext(), options).items).toHaveLength(1); + expect(() => executor.listCallable(actorContext('alice', ['read', 'write']), options)).toThrow('Invalid or expired'); + expect(() => executor.listCallable(actorContext('bob'), options)).toThrow('Invalid or expired'); + }); + + it('passes detached delegation into policy and binds pending approval to current authority', async () => { + const { registry, execute } = await setup(); + const context = actorContext(); + const evaluate = vi.fn(async (_request: PolicyEvaluationRequest) => ({ decision: 'require_approval' as const })); + let pending: ApprovalRequest | undefined; + const resume = vi.fn(async (_token: string, request: ApprovalRequest) => { + if (pending === undefined || pending.authorityKey !== request.authorityKey || + pending.canonicalArgsDigest !== request.canonicalArgsDigest) { + return createApprovalResult({ status: 'rejected' }); + } + pending = undefined; + return createApprovalResult({ status: 'approved' }); + }); + const handler: ApprovalHandler = { + supportsAuthorityScope: true, + supportsFinalScope: true, + requestApproval: async (request) => { + pending = request; + return createApprovalResult({ status: 'pending', approvalId: 'credential' }); + }, + checkApproval: vi.fn(), + checkApprovalForCall: resume, + }; + const executor = new Executor({ + registry, acl: new ACL([permit]), approvalHandler: handler, policyEvaluator: { evaluate }, + }); + await expect(executor.call(moduleId, {}, context)).rejects.toMatchObject({ code: 'APPROVAL_PENDING' }); + expect(pending?.authorityKey).toBe(context.identity?.authorityKey()); + const detached = evaluate.mock.calls[0][0].identity; + expect(detached?.rootSubject.id).toBe(context.identity?.rootSubject.id); + expect(detached?.scopes).toEqual(context.identity?.scopes); + expect(detached?.rootSubject.attrs.tenant).not.toBe(context.identity?.rootSubject.attrs.tenant); + const credentials = { _approval_token: 'credential' }; + await expect(executor.call(moduleId, credentials, actorContext('alice', ['read', 'write']))).rejects + .toMatchObject({ code: 'APPROVAL_DENIED' }); + expect(pending).toBeDefined(); + expect(execute).not.toHaveBeenCalled(); + expect(await executor.call(moduleId, credentials, context)).toEqual({ done: true }); + expect(resume).toHaveBeenCalledTimes(2); + expect(pending).toBeUndefined(); + }); + + it('rejects pending scoped approval and skips resumption when a handler lacks authority binding', async () => { + const { registry, execute } = await setup(); + const context = actorContext(); + const resume = vi.fn(async () => createApprovalResult({ status: 'approved' })); + const executor = new Executor({ + registry, + acl: new ACL([{ ...permit, approval: 'required' }]), + approvalHandler: { + requestApproval: async () => createApprovalResult({ status: 'pending', approvalId: 'unbound' }), + checkApproval: vi.fn(), + checkApprovalForCall: resume, + }, + }); + await expect(executor.call(moduleId, {}, context)).rejects.toMatchObject({ code: 'APPROVAL_DENIED' }); + await expect(executor.call(moduleId, { _approval_token: 'unbound' }, context)).rejects + .toMatchObject({ code: 'APPROVAL_DENIED' }); + expect(resume).not.toHaveBeenCalled(); + expect(execute).not.toHaveBeenCalled(); + }); + + it('attributes ACL decisions and redacts nested contextual audit credentials', async () => { + const root = createIdentity('alice', 'user', [], { profile: { access_token: 'raw-root', region: 'eu' } }, { scopes: ['read'] }); + const actor = createIdentity('worker', 'agent', [], { api_key: 'raw-actor', subject_id: 'forged' }); + const context = Context.create(root.delegate(actor, ['read'])); + const audit = vi.fn(); + const acl = new ACL([permit], 'deny', audit); + expect(await acl.asyncCheck(null, moduleId, context)).toBe(true); + expect(auditEntryToWire(audit.mock.calls[0][0])).toMatchObject({ + actor_id: 'worker', subject_id: 'alice', delegation_depth: 1, + }); + expect(extractAuditIdentity(context).identity).toMatchObject({ + actor_id: 'worker', subject_id: 'alice', delegation_depth: 1, api_key: '', + on_behalf_of: { id: 'alice', profile: { access_token: '', region: 'eu' } }, + }); + }); +}); From 4331d2c80194f2bdd485d5c0847514cbf6ea7e35 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 17:37:47 +0800 Subject: [PATCH 3/6] docs(planning): record delegated identity candidate verification Signed-off-by: tercel --- docs/spec/protocol-spec.md | 2 +- planning/identity-delegation/overview.md | 27 ++++++++++++++++++++++++ planning/identity-delegation/state.json | 12 +++++------ 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/docs/spec/protocol-spec.md b/docs/spec/protocol-spec.md index 6fced5dd..166a621e 100644 --- a/docs/spec/protocol-spec.md +++ b/docs/spec/protocol-spec.md @@ -5105,7 +5105,7 @@ A handler that can resume a pending approval for a scope-enabled identity **MUST ACL audit entries for scope-enabled identities **MUST** include `actor_id`, `subject_id`, and active `delegation_depth`. When an audit event carries a redacted identity snapshot, D-93 redaction **MUST** apply to attributes at every hop. The snapshot **MUST NOT** contain raw credentials. -Adapters that opt into RFC 8693 JWT scope and actor projection **MUST** verify the signature, expected `iss` and `aud`, and required `exp` before accepting the projection. They **MUST** validate `nbf` and `iat` when supplied. The standard `scope` claim uses the scope-token string syntax in RFC 6749 §3.3. A deployment **MAY** map an additional provider claim whose value is a scope string or array of scope tokens. When both configured claims are present, their normalized sets **MUST** agree. At least one configured scope representation **MUST** be present. The top-level `sub` and outermost `act` claim yield at most one active Core link. Outer actor roles require an explicit trusted mapping. Nested `act` claims are history limited to a structurally validated depth of eight. Those claims **MUST NOT** contribute to Core roles, scope, active depth, approval, or ownership. A supplied credential that fails verification or the configured claim mapping **MUST** be rejected when projection is enabled. See [RFC 8693 §4.1](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.1) for the actor claim and [§4.2](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.2) for scope strings. +Adapters that opt into RFC 8693 JWT scope and actor projection **MUST** verify the signature, expected `iss` and `aud`, and required `exp` before accepting the projection. They **MUST** validate `nbf` and `iat` when supplied. The standard `scope` claim uses the scope-token string syntax in RFC 6749 §3.3. A deployment **MAY** map an additional provider claim whose value is a scope string or array of scope tokens. When both configured claims are present, their normalized sets **MUST** agree. At least one configured scope representation **MUST** be present. The top-level `sub` and outermost `act` claim yield at most one active Core link. Outer actor roles require an explicit trusted mapping. Nested `act` claims are history limited to a structurally validated depth of eight. Those claims **MUST NOT** contribute to Core roles, scope, active depth, approval, or ownership. A supplied credential on a governed route that fails verification or the configured claim mapping **MUST** be rejected when projection is enabled. Explicitly exempt endpoints **MUST NOT** establish scoped authority from rejected credentials. See [RFC 8693 §4.1](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.1) for the actor claim and [§4.2](https://www.rfc-editor.org/rfc/rfc8693.html#section-4.2) for scope strings. --- diff --git a/planning/identity-delegation/overview.md b/planning/identity-delegation/overview.md index 48f12982..805cf128 100644 --- a/planning/identity-delegation/overview.md +++ b/planning/identity-delegation/overview.md @@ -20,3 +20,30 @@ The Python and TypeScript Core runs include ACL tests. The Rust aggregate run se 2. Implement the [Core SDK changes](./tasks/core-sdks.md) independently in Python, TypeScript, and Rust. 3. Apply the same authority contract to the [MCP and A2A adapters](./tasks/surfaces.md). 4. Run the [dual-repository verification](./tasks/verification.md) against fixed source and package candidates. + +## Local candidate verification + +The Core distribution source is `6a4aa25b93526f09ca698aa9ffb982f94e613158` on `core-alpha5`. The verified Surfaces source is `417116190fe2815c0204ffacd70744cc55f43f3c` on `surfaces-alpha5`. The Core distribution files used for the Surfaces runs have the following SHA-256 digests. + +| Distribution | SHA-256 | +| --- | --- | +| Python wheel | `4e14ff5854f3024ebbc63d4fd7d7e73f6e6a5255291f3b3f0bd9372c5112c7d5` | +| npm archive, produced with the CI pnpm version | `a3c57f10ead7cae35c6d6b22ee2013cc87e7e1281fa820234827e6c2e83679cc` | +| Rust crate, produced with Rust 1.86 | `9471bdd15aa13ec971ba940414f486b5e40b62426d73827b63918bd6b88d5cb9` | + +The table counts passing tests, including Rust doctests. + +| Verification | Python | TypeScript | Rust | +| --- | ---: | ---: | ---: | +| Core full suite | 6,732 | 5,945 | 3,265 | +| Toolkit with the candidate Core | 1,289 | 1,079 | 714 | +| MCP with the candidate Core | 1,303 | 1,002 | 1,164 | +| A2A with the candidate Core | 539 | 495 | 247 | +| CLI with the candidate Core | 1,098 | 950 | 1,052 | +| Toolkit with its minimum stable Core | 1,289 | 1,079 | 714 | + +All three SDKs exercise the 17 shared delegation cases. The fixture drivers and expected-key guards cover 101 JSON fixtures and 1,269 cases. Python Ruff and Pyright, TypeScript type checks with 90.46% Core branch coverage, and strict Rust Clippy passed. The installed minimal Python wheel ran Quick Start, the installed npm archive ran the browser entry on Node 20, and Rust passed the 23-test Core Profile gate on Rust 1.86. Core and the four Surface documentation sites passed their configured strict builds. + +Signed MCP requests exercise current actor and root subject isolation, authority-bound session reuse, durable task disclosure, and atomic approval consumption. The Python SSE smoke test rejected another subject and narrower scopes, then accepted equivalent refreshed credentials. A2A task and push operations enforce current scope, including against Rust task records after restarting the server. The Python Golden Path passed through direct calls and an MCP client with both wheels installed. + +The A2A authentication guide records the owner-key migration for existing IDs beginning with `apcore:`. The candidate is at the local verification stage. diff --git a/planning/identity-delegation/state.json b/planning/identity-delegation/state.json index b399efb7..f18bcecd 100644 --- a/planning/identity-delegation/state.json +++ b/planning/identity-delegation/state.json @@ -2,13 +2,13 @@ "feature": "identity-delegation", "created": "2026-11-28", "updated": "2026-11-28", - "status": "in_progress", + "status": "completed", "execution_order": ["shared-contract", "core-sdks", "surfaces", "verification"], "progress": { "total_tasks": 4, - "completed": 2, - "in_progress": 1, - "pending": 1, + "completed": 4, + "in_progress": 0, + "pending": 0, "skipped": 0, "blocked": 0 }, @@ -30,14 +30,14 @@ "id": "surfaces", "file": "tasks/surfaces.md", "title": "MCP and A2A verified claim mapping", - "status": "in_progress", + "status": "completed", "dependencies": ["core-sdks"] }, { "id": "verification", "file": "tasks/verification.md", "title": "Dual-repository verification", - "status": "pending", + "status": "completed", "dependencies": ["core-sdks", "surfaces"] } ] From 109eb5d2fd612d67c800fabde5f27130d007d643 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 17:48:56 +0800 Subject: [PATCH 4/6] fix(core): close scoped execution and task admission review gaps Signed-off-by: tercel --- planning/identity-delegation/overview.md | 6 +- python/src/apcore/async_task.py | 8 ++ python/src/apcore/capabilities.py | 11 +- python/src/apcore/pipeline.py | 111 +++++++++++------- python/tests/test_async_task_store.py | 16 +++ python/tests/test_identity_delegation.py | 55 +++++++++ rust/src/builtin_steps.rs | 2 + rust/src/pipeline.rs | 30 +++-- rust/src/pipeline_config.rs | 44 ++++--- rust/tests/capability_discovery.rs | 35 ++++++ rust/tests/post_validation_policy.rs | 57 +++++++++ typescript/src/async-task.ts | 9 +- typescript/src/builtin-steps.ts | 4 +- typescript/src/executor.ts | 5 +- typescript/src/pipeline.ts | 3 +- typescript/src/scoped-invocation.ts | 13 ++ typescript/tests/async-task.test.ts | 15 +++ .../tests/test-identity-delegation.test.ts | 26 +++- 18 files changed, 377 insertions(+), 73 deletions(-) diff --git a/planning/identity-delegation/overview.md b/planning/identity-delegation/overview.md index 805cf128..4613c013 100644 --- a/planning/identity-delegation/overview.md +++ b/planning/identity-delegation/overview.md @@ -21,7 +21,7 @@ The Python and TypeScript Core runs include ACL tests. The Rust aggregate run se 3. Apply the same authority contract to the [MCP and A2A adapters](./tasks/surfaces.md). 4. Run the [dual-repository verification](./tasks/verification.md) against fixed source and package candidates. -## Local candidate verification +## Initial local candidate verification The Core distribution source is `6a4aa25b93526f09ca698aa9ffb982f94e613158` on `core-alpha5`. The verified Surfaces source is `417116190fe2815c0204ffacd70744cc55f43f3c` on `surfaces-alpha5`. The Core distribution files used for the Surfaces runs have the following SHA-256 digests. @@ -47,3 +47,7 @@ All three SDKs exercise the 17 shared delegation cases. The fixture drivers and Signed MCP requests exercise current actor and root subject isolation, authority-bound session reuse, durable task disclosure, and atomic approval consumption. The Python SSE smoke test rejected another subject and narrower scopes, then accepted equivalent refreshed credentials. A2A task and push operations enforce current scope, including against Rust task records after restarting the server. The Python Golden Path passed through direct calls and an MCP client with both wheels installed. The A2A authentication guide records the owner-key migration for existing IDs beginning with `apcore:`. The candidate is at the local verification stage. + +## Pull request review + +The review follow-up aligns scoped discovery and dispatch on the active stock pipeline, binds the resolved registration throughout a scoped invocation, and lets the MCP task bridge register the owner before the first asynchronous task-store write. The Surfaces workflows pin the updated Core source and distribution for verification. diff --git a/python/src/apcore/async_task.py b/python/src/apcore/async_task.py index fe4c8f52..0045173d 100644 --- a/python/src/apcore/async_task.py +++ b/python/src/apcore/async_task.py @@ -425,6 +425,8 @@ class AsyncTaskManager: Accepts a pluggable :class:`TaskStore` for custom persistence. """ + supports_task_allocation_callback = True + def __init__( self, executor: ExecutorProtocol, @@ -496,6 +498,8 @@ async def submit( inputs: dict[str, Any], context: Context | None = None, retry_policy: "RetryPolicy | RetryConfig | None" = None, + *, + on_task_allocated: Callable[[str], None] | None = None, ) -> str: """Submit a module for background execution. @@ -509,6 +513,8 @@ async def submit( retry_policy: Optional retry configuration — either the canonical :class:`RetryConfig` or the legacy :class:`RetryPolicy`. None means no retries. + on_task_allocated: Synchronous bookkeeping callback called with the + task ID immediately before the first store write. The write may fail. Returns: The generated task_id (UUID4 string). @@ -531,6 +537,8 @@ async def submit( submitted_at=time.time(), max_retries=retry_policy.max_retries if retry_policy is not None else 0, ) + if on_task_allocated is not None: + on_task_allocated(task_id) await self._save(info) async_task = asyncio.create_task(self._run(task_id, module_id, inputs, context, retry_policy)) diff --git a/python/src/apcore/capabilities.py b/python/src/apcore/capabilities.py index 5f748207..8d440b2a 100644 --- a/python/src/apcore/capabilities.py +++ b/python/src/apcore/capabilities.py @@ -16,7 +16,7 @@ from apcore.builtin_steps import BuiltinACLCheck, BuiltinApprovalGate, BuiltinContextCreation, BuiltinModuleLookup from apcore.context import Context, Identity from apcore.errors import InvalidInputError, PolicyEvaluationError -from apcore.pipeline import _any_match +from apcore.pipeline import _any_match, _scoped_gate_index from apcore.policy import ExecutionPolicy from apcore.schema.annotations import governance_union @@ -304,10 +304,17 @@ def descriptor( def _visible( executor: Executor, module_id: str, context: Context, version_hint: str | None ) -> tuple[_Registration, VisibilityDecision] | None: + strategy = executor.current_strategy + if ( + context.identity is not None + and context.identity.scopes is not None + and _scoped_gate_index(strategy, module_id) is None + ): + return None context_ready = False lookup = None gate = None - for step in executor.current_strategy.steps: + for step in strategy.steps: patterns = getattr(step, "match_modules", None) if patterns is not None and not _any_match(patterns, module_id): continue diff --git a/python/src/apcore/pipeline.py b/python/src/apcore/pipeline.py index 75de8a0b..8b75258d 100644 --- a/python/src/apcore/pipeline.py +++ b/python/src/apcore/pipeline.py @@ -674,32 +674,62 @@ async def _invoke_step_cleanup_hooks( continue +@dataclass(frozen=True) +class _ScopedFrame: + identity: Identity + module_id: str + caller_id: str | None + call_chain: tuple[str, ...] + gate_index: int + + @classmethod + def capture(cls, ctx: PipelineContext, identity: Identity, gate_index: int) -> _ScopedFrame: + chain = tuple(ctx.context.call_chain) + return cls(identity, ctx.module_id, chain[-1] if chain else None, (*chain, ctx.module_id), gate_index) + + def require_match(self, ctx: PipelineContext) -> None: + context = ctx.context + if ( + context.identity is not self.identity + or ctx.module_id != self.module_id + or context.caller_id != self.caller_id + or tuple(context.call_chain) != self.call_chain + ): + raise ACLDeniedError(self.caller_id, self.module_id) + + def require_grant(self, ctx: PipelineContext, module: Any) -> None: + self.require_match(ctx) + if not ctx._acl_allowed or ctx.module is not module: + raise ACLDeniedError(self.caller_id, self.module_id) + + +def _scoped_gate_index(strategy: ExecutionStrategy, module_id: str) -> int | None: + """Find the stock scope gate before dispatch for execution and discovery.""" + from apcore.acl import ACL + from apcore.builtin_steps import BuiltinACLCheck, BuiltinContextCreation, BuiltinModuleLookup + + context_ready = False + lookup_ready = False + for index, step in enumerate(strategy.steps): + patterns = getattr(step, "match_modules", None) + if patterns is not None and not _any_match(patterns, module_id): + continue + if step.name == "execute": + break + if type(step) is BuiltinContextCreation: + context_ready = True + elif type(step) is BuiltinModuleLookup: + lookup_ready = context_ready + elif isinstance(step, BuiltinACLCheck): + if type(step) is BuiltinACLCheck and type(step.acl) is ACL and lookup_ready and step.pure: + return index + break + return None + + class PipelineEngine: """Executes a pipeline strategy step by step.""" - @staticmethod - def _scoped_gate_index(strategy: ExecutionStrategy, ctx: PipelineContext) -> int: - from apcore.acl import ACL - from apcore.builtin_steps import BuiltinACLCheck, BuiltinContextCreation, BuiltinModuleLookup - - context_ready = False - lookup_ready = False - for index, step in enumerate(strategy.steps): - patterns = getattr(step, "match_modules", None) - if patterns is not None and not _any_match(patterns, ctx.module_id): - continue - if step.name == "execute": - break - if type(step) is BuiltinContextCreation: - context_ready = True - elif type(step) is BuiltinModuleLookup: - lookup_ready = context_ready - elif isinstance(step, BuiltinACLCheck): - if type(step) is BuiltinACLCheck and type(step.acl) is ACL and lookup_ready and step.pure: - return index - break - raise ACLDeniedError(ctx.context.caller_id, ctx.module_id) - async def run( self, strategy: ExecutionStrategy, @@ -744,18 +774,20 @@ async def _run_steps( effective_run_until = run_until or ctx.run_until observation = ctx._stream_observation identity = getattr(ctx.context, "identity", None) - gate_index = None + scoped_frame = None if isinstance(identity, Identity) and identity.scopes is not None and not ctx._acl_allowed: - gate_index = self._scoped_gate_index(strategy, ctx) - scoped_target = ctx.module_id + gate_index = _scoped_gate_index(strategy, ctx.module_id) + if gate_index is None: + raise ACLDeniedError(ctx.context.caller_id, ctx.module_id) + scoped_frame = _ScopedFrame.capture(ctx, identity, gate_index) scoped_module = None i = 0 # Index-based loop (not for-each) to support skip_to. while i < len(steps): step = steps[i] - if gate_index is not None and i > gate_index and not ctx._acl_allowed and not ctx.dry_run: - raise ACLDeniedError(ctx.context.caller_id, scoped_target) + if scoped_frame is not None and i > scoped_frame.gate_index and not ctx._acl_allowed and not ctx.dry_run: + raise ACLDeniedError(scoped_frame.caller_id, scoped_frame.module_id) if observation is not None and observation.defer_step(step.name, ctx): i += 1 continue @@ -872,15 +904,12 @@ async def _run_steps( observation.before_step(step.name, ctx) recovered = False try: - if gate_index is not None and i >= gate_index: - if ( - ctx.context.identity is not identity - or ctx.module_id != scoped_target - or (i > gate_index and ctx.module is not scoped_module) - ): - raise ACLDeniedError(ctx.context.caller_id, scoped_target) - if i == gate_index: + if scoped_frame is not None and i >= scoped_frame.gate_index: + if i == scoped_frame.gate_index: + scoped_frame.require_match(ctx) scoped_module = ctx.module + else: + scoped_frame.require_grant(ctx, scoped_module) if timeout_ms > 0: result = await asyncio.wait_for( step.execute(ctx), @@ -952,7 +981,7 @@ async def _run_steps( getattr(step, "_fail_closed_on_error", False) or ctx._policy_pending or isinstance(exc, PolicyEvaluationError) - or (gate_index is not None and isinstance(exc, ACLDeniedError)) + or (scoped_frame is not None and isinstance(exc, ACLDeniedError)) ) recovery: Any = None if error_mws: @@ -1117,16 +1146,16 @@ async def _run_steps( context=ctx, ) if effective_run_until(state): - if gate_index is not None and not ctx._acl_allowed: - raise ACLDeniedError(ctx.context.caller_id, scoped_target) + if scoped_frame is not None: + scoped_frame.require_grant(ctx, scoped_module) trace.success = True trace.total_duration_ms = (time.monotonic() - start) * 1000 return ctx.output, trace i += 1 - if gate_index is not None and not ctx._acl_allowed and not ctx.dry_run: - raise ACLDeniedError(ctx.context.caller_id, scoped_target) + if scoped_frame is not None and not ctx.dry_run: + scoped_frame.require_grant(ctx, scoped_module) trace.success = not any(item.result.action == "abort" for item in trace.steps if not item.skipped) trace.total_duration_ms = (time.monotonic() - start) * 1000 # Use ctx.output — it's the most up-to-date (middleware_after may modify it) diff --git a/python/tests/test_async_task_store.py b/python/tests/test_async_task_store.py index 424ac3e9..7c322c06 100644 --- a/python/tests/test_async_task_store.py +++ b/python/tests/test_async_task_store.py @@ -63,6 +63,22 @@ def test_protocol_methods_declared_async(self) -> None: assert inspect.iscoroutinefunction(method), f"TaskStore Protocol method {name!r} must be async (D-17)" +@pytest.mark.asyncio +async def test_submit_allocates_task_id_before_initial_write() -> None: + allocated: list[str] = [] + + class RejectingStore(InMemoryTaskStore): + async def save(self, info: TaskInfo) -> None: + assert allocated == [info.task_id] + raise RuntimeError("initial store write failed") + + manager = AsyncTaskManager(executor=_StubExecutor(), store=RejectingStore()) + with pytest.raises(RuntimeError, match="initial store write failed"): + await manager.submit("module", {}, on_task_allocated=allocated.append) + assert len(allocated) == 1 + assert await manager.list_tasks_async() == [] + + # --------------------------------------------------------------------------- # A-D-AT-03 / D-11 — ReaperHandle.stop is async and drains the task # --------------------------------------------------------------------------- diff --git a/python/tests/test_identity_delegation.py b/python/tests/test_identity_delegation.py index 1b1a2fe1..ce853922 100644 --- a/python/tests/test_identity_delegation.py +++ b/python/tests/test_identity_delegation.py @@ -2,13 +2,18 @@ from __future__ import annotations +from collections.abc import AsyncIterator +from typing import Any + import pytest from apcore.acl import ACL, ACLRule from apcore.approval import ApprovalRequest, ApprovalResult +from apcore.builtin_steps import build_standard_strategy from apcore.context import Context, Identity from apcore.errors import ACLDeniedError, ApprovalDeniedError, ApprovalPendingError, InvalidInputError from apcore.executor import Executor +from apcore.pipeline import ExecutionStrategy, PipelineContext, _ScopedFrame from apcore.policy import PolicyEvaluationRequest, PolicyVerdict from apcore.registry import Registry from apcore.sys_modules.identity import _audit_payload_extras @@ -108,6 +113,56 @@ async def test_scoped_executor_and_discovery_require_first_stock_scope_grant() - pytest.fail("Scoped principal streamed without a scope grant") +def test_scoped_discovery_requires_an_acl_gate_before_dispatch() -> None: + registry = Registry() + registry.register("test.run", _Module()) + acl = ACL([_allow({"scopes": ["read"]}), _allow()]) + steps = build_standard_strategy(registry=registry).steps + acl_index = next(index for index, step in enumerate(steps) if step.name == "acl_check") + acl_gate = steps.pop(acl_index) + dispatch_index = next(index for index, step in enumerate(steps) if step.name == "execute") + steps.insert(dispatch_index + 1, acl_gate) + strategy = ExecutionStrategy("late-acl", steps) + + with Executor(registry, acl=acl, strategy=strategy) as executor: + scoped = Context.create(Identity("actor", scopes=["read"])) + assert executor.get_callable_descriptor("test.run", scoped) is None + assert not executor.list_callable(scoped).items + assert executor.get_callable_descriptor("test.run", Context.create(Identity("ordinary"))) is not None + + +@pytest.mark.parametrize("field", ["caller_id", "call_chain"]) +def test_scoped_guard_requires_the_original_child_frame(field: str) -> None: + identity = Identity("actor", scopes=["read"]) + parent = Context.create(identity).child("test.parent") + pipeline = PipelineContext("test.run", {}, parent) + frame = _ScopedFrame.capture(pipeline, identity, gate_index=0) + pipeline.context = parent.child("test.run") + frame.require_match(pipeline) + + other_child = Context.create(identity).child("test.other").child("test.run") + setattr(pipeline.context, field, getattr(other_child, field)) + with pytest.raises(ACLDeniedError): + frame.require_match(pipeline) + + +@pytest.mark.asyncio +async def test_scoped_nested_call_and_stream_keep_the_child_frame() -> None: + class StreamingModule(_Module): + async def stream(self, inputs: dict[str, Any], context: Context) -> AsyncIterator[dict[str, Any]]: + yield {"caller": context.caller_id, "chain": context.call_chain} + + registry = Registry() + registry.register("test.run", StreamingModule()) + grant = ACLRule(["test.parent"], ["test.run"], "allow", conditions={"scopes": ["read"]}) + caller = Context.create(Identity("actor", scopes=["read"])).child("test.parent") + + with Executor(registry, acl=ACL([grant])) as executor: + assert await executor.call_async("test.run", {}, caller) == {"actor": "actor"} + chunks = [chunk async for chunk in executor.stream("test.run", {}, caller)] + assert chunks == [{"caller": "test.parent", "chain": ["test.parent", "test.run"]}] + + def test_audit_recursively_redacts_identity_attributes() -> None: root = Identity("root", attrs={"profile": {"Authorization": "signed", "name": "root"}}, scopes=["read"]) caller = root.delegate(Identity("agent", attrs={"outer": [{"session_token": "signed"}]}), ["read"]) diff --git a/rust/src/builtin_steps.rs b/rust/src/builtin_steps.rs index 18689c99..82bcb932 100644 --- a/rust/src/builtin_steps.rs +++ b/rust/src/builtin_steps.rs @@ -365,6 +365,7 @@ impl Step for BuiltinModuleLookup { return Err(ModuleError::module_disabled(&ctx.module_id)); } ctx.module = Some(module.clone()); + ctx.record_scope_lookup(&module); ctx.module_lease = Some(lease); // PROTOCOL_SPEC §6.1.8 rule 1: compute the governance projection of the @@ -412,6 +413,7 @@ impl Step for BuiltinACLCheck { } async fn execute(&self, ctx: &mut PipelineContext) -> Result { + ctx.require_scope_binding(false)?; if let Some(acl) = ctx.acl.clone() { let caller_id = ctx.context.caller_id.clone(); // The structured accessor (PROTOCOL_SPEC §6.8.1), never the boolean: diff --git a/rust/src/pipeline.rs b/rust/src/pipeline.rs index f4ddbb00..e0be8f10 100644 --- a/rust/src/pipeline.rs +++ b/rust/src/pipeline.rs @@ -392,6 +392,7 @@ struct ScopeInvocation { module_id: String, caller_id: String, call_chain: Vec, + resolved_module: Option>, /// Set only by the stock ACL gate after a scope-constrained grant. granted: bool, } @@ -407,6 +408,7 @@ impl ScopeInvocation { .caller_id .unwrap_or_else(|| crate::acl::EXTERNAL_CALLER.into()), call_chain: prospective.call_chain, + resolved_module: None, granted: false, }) } @@ -421,6 +423,11 @@ impl ScopeInvocation { .as_deref() .unwrap_or(crate::acl::EXTERNAL_CALLER) && self.call_chain == ctx.context.call_chain + && self + .resolved_module + .as_ref() + .zip(ctx.module.as_ref()) + .is_some_and(|(expected, actual)| Arc::ptr_eq(expected, actual)) } } @@ -529,20 +536,23 @@ impl PipelineContext { || self.reject_unconsumed_scoped_approval().is_err() } + pub(crate) fn record_scope_lookup(&mut self, module: &Arc) { + if let Some(initial) = &mut self.initial_scope { + initial.resolved_module = Some(Arc::clone(module)); + } + } + pub(crate) fn record_scope_grant(&mut self) { - let granted = self.initial_scope.as_ref().is_some_and(|initial| { - self.context - .identity - .as_ref() - .and_then(crate::Identity::authority_key) - .is_some_and(|current| initial.matches(self, ¤t)) - }); if let Some(initial) = &mut self.initial_scope { - initial.granted = granted; + initial.granted = true; } } pub(crate) fn require_scope_grant(&self) -> Result<(), ModuleError> { + self.require_scope_binding(true) + } + + pub(crate) fn require_scope_binding(&self, grant_required: bool) -> Result<(), ModuleError> { let current = self .context .identity @@ -550,7 +560,9 @@ impl PipelineContext { .and_then(crate::Identity::authority_key); let admitted = match (&self.initial_scope, ¤t) { (None, None) => true, - (Some(initial), Some(current)) => initial.granted && initial.matches(self, current), + (Some(initial), Some(current)) => { + (!grant_required || initial.granted) && initial.matches(self, current) + } _ => false, }; if admitted { diff --git a/rust/src/pipeline_config.rs b/rust/src/pipeline_config.rs index c11e38f0..71b40ffa 100644 --- a/rust/src/pipeline_config.rs +++ b/rust/src/pipeline_config.rs @@ -7,7 +7,10 @@ use std::sync::OnceLock; use serde_json::Value; -use crate::builtin_steps::{build_standard_strategy, BuiltinACLCheck, BuiltinContextCreation}; +use crate::builtin_steps::{ + build_standard_strategy, BuiltinACLCheck, BuiltinContextCreation, BuiltinExecute, + BuiltinModuleLookup, +}; use crate::errors::{ErrorCode, ModuleError}; use crate::pipeline::{ExecutionStrategy, Step}; @@ -94,27 +97,38 @@ pub(crate) fn builtin_context_creation_applies(step: &dyn Step, module_id: &str) } pub(crate) fn builtin_scope_gate_applies(strategy: &ExecutionStrategy, module_id: &str) -> bool { - let steps = strategy.steps(); - let Some(index) = steps.iter().position(|step| { - step.pure() - && !step.ignore_errors() - && builtin_step_applies::(step.as_ref(), module_id) - }) else { - return false; - }; - steps[..index].iter().any(|step| { - step.pure() - && !step.ignore_errors() - && builtin_context_creation_applies(step.as_ref(), module_id) - }) + let mut context_ready = false; + let mut module_ready = false; + let mut gate_ready = false; + for step in strategy.steps().iter().map(Box::as_ref) { + if !step_applies(step, module_id) { + continue; + } + if step.name() == "execute" || is_builtin_step::(step) { + return gate_ready && is_builtin_step::(step) && !step.ignore_errors(); + } + let enforcing = step.pure() && !step.ignore_errors(); + if is_builtin_step::(step) { + context_ready = enforcing; + } else if is_builtin_step::(step) { + module_ready = context_ready && enforcing; + } else if is_builtin_step::(step) { + gate_ready = module_ready && enforcing; + } + } + false } fn builtin_step_applies(step: &dyn Step, module_id: &str) -> bool { + step_applies(step, module_id) && is_builtin_step::(step) +} + +fn step_applies(step: &dyn Step, module_id: &str) -> bool { step.match_modules().is_none_or(|patterns| { patterns .iter() .any(|pattern| crate::utils::helpers::match_pattern(pattern, module_id)) - }) && is_builtin_step::(step) + }) } fn is_builtin_step(step: &dyn Step) -> bool { diff --git a/rust/tests/capability_discovery.rs b/rust/tests/capability_discovery.rs index 9f327975..e5a65d09 100644 --- a/rust/tests/capability_discovery.rs +++ b/rust/tests/capability_discovery.rs @@ -371,6 +371,41 @@ fn test_capability_discovery_fails_closed_without_the_stock_gate() { .is_none()); } +#[test] +fn test_scoped_discovery_requires_acl_before_dispatch() { + use apcore::builtin_steps::{ + BuiltinACLCheck, BuiltinContextCreation, BuiltinExecute, BuiltinModuleLookup, + }; + let strategy = apcore::ExecutionStrategy::new( + "late-acl", + vec![ + Box::new(BuiltinContextCreation), + Box::new(BuiltinModuleLookup::default()), + Box::new(BuiltinExecute), + Box::new(BuiltinACLCheck), + ], + ) + .unwrap(); + let mut executor = Executor::with_strategy(Registry::new(), Config::default(), strategy); + executor.set_acl(ACL::new( + serde_json::from_value(json!([{ + "callers": ["@external"], "targets": ["demo.private"], + "effect": "allow", "conditions": {"scopes": ["read"]} + }])) + .unwrap(), + "deny", + None, + )); + register(&executor, &json!({"module_id": "demo.private"})); + let identity = Identity::new("reader".into(), "user".into(), vec![], HashMap::new()) + .with_authority(Some(vec!["read".into()]), None) + .unwrap(); + let requester = Context::new(identity); + assert!(executor + .get_callable_descriptor("demo.private", None, Some(&requester)) + .is_none()); +} + #[tokio::test] async fn test_capability_visibility_requires_context_creation_for_the_target() { let strategy = apcore::pipeline_config::build_strategy_from_config(&json!({ diff --git a/rust/tests/post_validation_policy.rs b/rust/tests/post_validation_policy.rs index c4c3a657..504b5a46 100644 --- a/rust/tests/post_validation_policy.rs +++ b/rust/tests/post_validation_policy.rs @@ -466,6 +466,63 @@ fn read_scoped_acl() -> ACL { struct AlternateFlow; +struct SubstituteRegistration(Arc); + +#[async_trait] +impl Step for SubstituteRegistration { + fn name(&self) -> &'static str { + "substitute_registration" + } + + fn description(&self) -> &'static str { + "Substitute the selected module" + } + + fn removable(&self) -> bool { + true + } + + fn replaceable(&self) -> bool { + true + } + + fn pure(&self) -> bool { + true + } + + async fn execute(&self, ctx: &mut PipelineContext) -> Result { + ctx.module = Some(Arc::clone(&self.0)); + Ok(StepResult::continue_step()) + } +} + +#[tokio::test] +async fn scoped_invocation_remains_bound_to_stock_module_lookup() { + let target = "demo.policy"; + let replacement = probe_registry("2.0.0").get(target).unwrap().unwrap(); + let context = delegated_context("subject", &["read"]); + for before in ["acl_check", "execute"] { + let mut strategy = apcore::builtin_steps::build_standard_strategy(); + strategy + .insert_before( + before, + Box::new(SubstituteRegistration(Arc::clone(&replacement))), + ) + .unwrap(); + let mut executor = + Executor::with_strategy(probe_registry("1.0.0"), Config::in_memory(), strategy); + executor.set_acl(read_scoped_acl()); + let call = executor.call(target, json!({}), Some(&context), None).await; + assert_eq!(call.unwrap_err().code, ErrorCode::ACLDenied); + let stream = executor + .stream(target, json!({}), Some(&context), None) + .next() + .await + .unwrap(); + assert_eq!(stream.unwrap_err().code, ErrorCode::ACLDenied); + } +} + #[async_trait] impl Step for AlternateFlow { fn name(&self) -> &'static str { diff --git a/typescript/src/async-task.ts b/typescript/src/async-task.ts index 4293c9ab..28d39d14 100644 --- a/typescript/src/async-task.ts +++ b/typescript/src/async-task.ts @@ -164,6 +164,7 @@ interface AsyncTaskManagerOptions { * Uses a simple counter-based concurrency limiter instead of a semaphore. */ export class AsyncTaskManager { + readonly supportsTaskAllocationCallback = true; private readonly _executor: Executor; private readonly _store: TaskStore; private readonly _maxConcurrent: number; @@ -203,7 +204,12 @@ export class AsyncTaskManager { async submit( moduleId: string, inputs: Record, - opts?: { context?: Context | null; retry?: RetryConfig }, + opts?: { + context?: Context | null; + retry?: RetryConfig; + /** Synchronous bookkeeping before the first store write, which may fail. */ + onTaskAllocated?: (taskId: string) => void; + }, ): Promise { const taskId = uuidv4(); const retry = opts?.retry ?? null; @@ -237,6 +243,7 @@ export class AsyncTaskManager { if (active >= this._maxTasks) { throw new TaskLimitExceededError(this._maxTasks); } + opts?.onTaskAllocated?.(taskId); await this._store.save(info); }); diff --git a/typescript/src/builtin-steps.ts b/typescript/src/builtin-steps.ts index d5b251cc..011bd8d6 100644 --- a/typescript/src/builtin-steps.ts +++ b/typescript/src/builtin-steps.ts @@ -19,7 +19,7 @@ import { getDefault } from './config-defaults.js'; import { CancelToken, awaitExecution } from './cancel.js'; import { Context } from './context.js'; import { authorityKeyOf, hasScopeCeiling } from './identity.js'; -import { assertScopedInvocation, isStockScopeAcl, recordScopedGrant } from './scoped-invocation.js'; +import { assertScopedInvocation, isStockScopeAcl, recordScopedGrant, recordScopedLookup } from './scoped-invocation.js'; import { ACLDeniedError, ApprovalDeniedError, @@ -265,6 +265,7 @@ export class BuiltinModuleLookup implements Step { } ctx.module = mod; + recordScopedLookup(ctx); const moduleId = ctx.moduleId; moduleExecutionLeases.set(ctx, this._registry.bindExecution(moduleId, mod, ctx.context.cancelToken)); // PROTOCOL_SPEC §7.4 (D-96): resolve the registry's DECLARED annotations @@ -980,6 +981,7 @@ export class BuiltinExecute implements Step { if (isStreamingModule(candidate)) { if (invocation) { const protectedProducer = this._streamWithLease(ctx, () => { + assertScopedInvocation(ctx, true); assertPolicyBinding(ctx, invocation); invocation.dispatched = true; return candidate.stream(inputs, context); diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index 9df9f691..1a30f7a8 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -51,7 +51,7 @@ import { buildStrategyFromConfigSync, ConfigurationError } from './pipeline-conf import { type EventEmitter, createEvent } from './events/emitter.js'; import { Context } from './context.js'; import { hasScopeCeiling } from './identity.js'; -import { assertScopeGate, assertScopedInvocation, beginScopedInvocation, isStockScopeAcl } from './scoped-invocation.js'; +import { assertScopeGate, assertScopedInvocation, beginScopedInvocation, isScopedAdmissionError, isStockScopeAcl } from './scoped-invocation.js'; import { governanceUnion } from './schema/annotations.js'; import { sourceSchemaFor } from './schema/loader-pure.js'; import { RedactionConfig } from './observability/context-logger.js'; @@ -1323,6 +1323,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 (isScopedAdmissionError(pipeCtx, underlying)) throw wrapped; if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; const executedMw = pipeCtx.executedMiddlewares; if (executedMw && executedMw.length > 0) { @@ -1528,6 +1529,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 (isScopedAdmissionError(pipeCtx, underlying)) throw wrapped; if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; if (pipeCtx.executedMiddlewares && pipeCtx.executedMiddlewares.length > 0) { const recovery = await this._middlewareManager.executeOnError( @@ -1605,6 +1607,7 @@ export class Executor { if (exc instanceof ExecutionCancelledError) throw exc; const ctxObj = pipeCtx.context; const wrapped = propagateError(exc as Error, moduleId, ctxObj); + if (isScopedAdmissionError(pipeCtx, exc)) throw wrapped; if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; if (exc instanceof ModuleTimeoutError && ctxObj.signal.aborted) throw wrapped; if (pipeCtx.executedMiddlewares && pipeCtx.executedMiddlewares.length > 0) { diff --git a/typescript/src/pipeline.ts b/typescript/src/pipeline.ts index d312b336..83f60d8e 100644 --- a/typescript/src/pipeline.ts +++ b/typescript/src/pipeline.ts @@ -9,6 +9,7 @@ import type { ErrorOptions } from './errors.js'; import { MiddlewareChainError } from './middleware/manager.js'; import { matchPattern } from './utils/pattern.js'; import { policyInvocationOf } from './policy-evaluation.js'; +import { isScopedAdmissionError } from './scoped-invocation.js'; // --------------------------------------------------------------------------- // Step interface @@ -1251,7 +1252,7 @@ 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 || isScopedAdmissionError(ctx, cause) || (policyInvocation !== undefined && !policyInvocation.dispatched); const observedCancellation = observeStep !== undefined && cause instanceof ModuleError && cause.code === 'EXECUTION_CANCELLED'; diff --git a/typescript/src/scoped-invocation.ts b/typescript/src/scoped-invocation.ts index 10aa790b..518bf6f9 100644 --- a/typescript/src/scoped-invocation.ts +++ b/typescript/src/scoped-invocation.ts @@ -9,6 +9,7 @@ type ScopedBinding = { readonly moduleId: string; readonly callerId: string | null; readonly callChain: readonly string[]; + resolvedModule?: unknown; allowed: boolean; }; @@ -33,8 +34,15 @@ export function beginScopedInvocation(ctx: PipelineContext): void { } } +/** @internal Record the registered module selected by the stock lookup step. */ +export function recordScopedLookup(ctx: PipelineContext): void { + const binding = bindings.get(ctx); + if (binding) binding.resolvedModule = ctx.module; +} + function remainsBound(ctx: PipelineContext, binding: ScopedBinding): boolean { return ctx.context.identity === binding.identity && ctx.moduleId === binding.moduleId && + binding.resolvedModule !== undefined && binding.resolvedModule === ctx.module && ctx.context.callerId === binding.callerId && ctx.context.callChain.length === binding.callChain.length && ctx.context.callChain.every((id, index) => id === binding.callChain[index]); } @@ -54,6 +62,11 @@ export function recordScopedGrant(ctx: PipelineContext, decision: AccessDecision if (binding) binding.allowed = decision.access === 'allow'; } +/** @internal A denial on a scoped invocation cannot become recovery output. */ +export function isScopedAdmissionError(ctx: PipelineContext, error: unknown): boolean { + return bindings.has(ctx) && error instanceof ACLDeniedError; +} + /** @internal Fail closed before traversing a strategy without a scope gate. */ export function assertScopeGate(ctx: Context, moduleId: string, hasGate: boolean): void { if (hasScopeCeiling(ctx.identity) && !hasGate) throw new ACLDeniedError(ctx.callerId, moduleId); diff --git a/typescript/tests/async-task.test.ts b/typescript/tests/async-task.test.ts index 5146d456..55440244 100644 --- a/typescript/tests/async-task.test.ts +++ b/typescript/tests/async-task.test.ts @@ -68,6 +68,21 @@ describe('TaskStatus', () => { describe('AsyncTaskManager', () => { describe('submit and status transitions', () => { + it('allocates the task ID before the initial store write', async () => { + const allocated: string[] = []; + class RejectingStore extends InMemoryTaskStore { + override async save(task: TaskInfo): Promise { + expect(allocated).toEqual([task.taskId]); + throw new Error('initial store write failed'); + } + } + const manager = new AsyncTaskManager({ executor: new Executor({ registry: createRegistry() }), store: new RejectingStore() }); + await expect(manager.submit('test.simple', {}, { onTaskAllocated: id => { allocated.push(id); } })) + .rejects.toThrow('initial store write failed'); + expect(allocated).toHaveLength(1); + expect(await manager.listTasks()).toEqual([]); + }); + it('reconciles a completed result after the runner exhausts its store writes', async () => { let notifyFailed!: () => void; const writesFailed = new Promise((resolve) => { notifyFailed = resolve; }); diff --git a/typescript/tests/test-identity-delegation.test.ts b/typescript/tests/test-identity-delegation.test.ts index c55970f8..003bd498 100644 --- a/typescript/tests/test-identity-delegation.test.ts +++ b/typescript/tests/test-identity-delegation.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest'; import { ACL, auditEntryToWire, type ACLRule } from '../src/acl.js'; import { - Context, createAnnotations, createApprovalResult, createIdentity, Executor, Registry, + Context, createAnnotations, createApprovalResult, createIdentity, Executor, Middleware, Registry, STREAMING_MARKER, type ApprovalHandler, type ApprovalRequest, type PolicyEvaluationRequest, } from '../src/index.js'; import { extractAuditIdentity } from '../src/sys-modules/audit.js'; @@ -176,6 +176,30 @@ describe('scoped identity delegation', () => { expect(pending).toBeUndefined(); }); + it.each(['acl_check', 'execute'])('keeps scoped dispatch bound to stock lookup before %s', async (step) => { + const { registry } = await setup(); + const replacement = registry.get('delegation.other'); + const executor = new Executor({ registry, acl: new ACL([permit]) }); + const recover = vi.fn(async () => ({ recovered: true })); + class RecoveringMiddleware extends Middleware { + override onError = recover; + } + executor.use(new RecoveringMiddleware()); + executor.currentStrategy.insertBefore(step, { + name: 'substitute_registration', + description: 'Substitute the selected module', + removable: true, + replaceable: true, + execute: async ctx => { + ctx.module = replacement; + return { action: 'continue' }; + }, + }); + await expect(executor.call(moduleId, {}, actorContext())).rejects.toMatchObject({ code: 'ACL_DENIED' }); + await expect(collect(executor.stream(moduleId, {}, actorContext()))).rejects.toMatchObject({ code: 'ACL_DENIED' }); + expect(recover).not.toHaveBeenCalled(); + }); + it('rejects pending scoped approval and skips resumption when a handler lacks authority binding', async () => { const { registry, execute } = await setup(); const context = actorContext(); From 509e273d4b2ae941d90b942604bcb24a23e27277 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 17:54:26 +0800 Subject: [PATCH 5/6] fix(python): pin scoped resolution at stock module lookup Signed-off-by: tercel --- python/src/apcore/capabilities.py | 4 +- python/src/apcore/pipeline.py | 76 ++++++++++++++++-------- python/tests/test_identity_delegation.py | 66 +++++++++++++++++++- 3 files changed, 118 insertions(+), 28 deletions(-) diff --git a/python/src/apcore/capabilities.py b/python/src/apcore/capabilities.py index 8d440b2a..40aa1932 100644 --- a/python/src/apcore/capabilities.py +++ b/python/src/apcore/capabilities.py @@ -16,7 +16,7 @@ from apcore.builtin_steps import BuiltinACLCheck, BuiltinApprovalGate, BuiltinContextCreation, BuiltinModuleLookup from apcore.context import Context, Identity from apcore.errors import InvalidInputError, PolicyEvaluationError -from apcore.pipeline import _any_match, _scoped_gate_index +from apcore.pipeline import _any_match, _scoped_steps from apcore.policy import ExecutionPolicy from apcore.schema.annotations import governance_union @@ -308,7 +308,7 @@ def _visible( if ( context.identity is not None and context.identity.scopes is not None - and _scoped_gate_index(strategy, module_id) is None + and _scoped_steps(strategy.steps, module_id) is None ): return None context_ready = False diff --git a/python/src/apcore/pipeline.py b/python/src/apcore/pipeline.py index 8b75258d..59c10d04 100644 --- a/python/src/apcore/pipeline.py +++ b/python/src/apcore/pipeline.py @@ -674,18 +674,25 @@ async def _invoke_step_cleanup_hooks( continue +@dataclass(frozen=True) +class _ScopedSteps: + lookup: int + gate: int + dispatch: int + + @dataclass(frozen=True) class _ScopedFrame: identity: Identity module_id: str caller_id: str | None call_chain: tuple[str, ...] - gate_index: int + steps: _ScopedSteps @classmethod - def capture(cls, ctx: PipelineContext, identity: Identity, gate_index: int) -> _ScopedFrame: + def capture(cls, ctx: PipelineContext, identity: Identity, steps: _ScopedSteps) -> _ScopedFrame: chain = tuple(ctx.context.call_chain) - return cls(identity, ctx.module_id, chain[-1] if chain else None, (*chain, ctx.module_id), gate_index) + return cls(identity, ctx.module_id, chain[-1] if chain else None, (*chain, ctx.module_id), steps) def require_match(self, ctx: PipelineContext) -> None: context = ctx.context @@ -697,33 +704,42 @@ def require_match(self, ctx: PipelineContext) -> None: ): raise ACLDeniedError(self.caller_id, self.module_id) - def require_grant(self, ctx: PipelineContext, module: Any) -> None: + def require_module(self, ctx: PipelineContext, module: Any) -> None: self.require_match(ctx) - if not ctx._acl_allowed or ctx.module is not module: + if module is None or ctx.module is not module: + raise ACLDeniedError(self.caller_id, self.module_id) + + def require_grant(self, ctx: PipelineContext, module: Any) -> None: + self.require_module(ctx, module) + if not ctx._acl_allowed: raise ACLDeniedError(self.caller_id, self.module_id) -def _scoped_gate_index(strategy: ExecutionStrategy, module_id: str) -> int | None: - """Find the stock scope gate before dispatch for execution and discovery.""" +def _scoped_steps(steps: Sequence[Step], module_id: str) -> _ScopedSteps | None: + """Find the ordered stock scope steps for execution and discovery.""" from apcore.acl import ACL - from apcore.builtin_steps import BuiltinACLCheck, BuiltinContextCreation, BuiltinModuleLookup + from apcore.builtin_steps import BuiltinACLCheck, BuiltinContextCreation, BuiltinExecute, BuiltinModuleLookup context_ready = False - lookup_ready = False - for index, step in enumerate(strategy.steps): + lookup_index = gate_index = None + for index, step in enumerate(steps): patterns = getattr(step, "match_modules", None) if patterns is not None and not _any_match(patterns, module_id): continue - if step.name == "execute": + if step.name == "execute" or isinstance(step, BuiltinExecute): + if type(step) is BuiltinExecute and lookup_index is not None and gate_index is not None: + return _ScopedSteps(lookup_index, gate_index, index) break + if gate_index is not None: + continue if type(step) is BuiltinContextCreation: context_ready = True elif type(step) is BuiltinModuleLookup: - lookup_ready = context_ready + lookup_index = index if context_ready else None elif isinstance(step, BuiltinACLCheck): - if type(step) is BuiltinACLCheck and type(step.acl) is ACL and lookup_ready and step.pure: - return index - break + if type(step) is not BuiltinACLCheck or type(step.acl) is not ACL or lookup_index is None or not step.pure: + break + gate_index = index return None @@ -766,7 +782,7 @@ async def _run_steps( # and apcore-rust ``pipeline_ctx.trace``. ctx.trace = trace start = time.monotonic() - steps = strategy.steps + steps: Sequence[Step] = strategy.steps step_mws = [] if ctx.dry_run else strategy.step_middlewares name_to_idx = strategy._name_to_idx # O(1) step lookup step_outputs: dict[str, Any] = {} @@ -776,17 +792,19 @@ async def _run_steps( identity = getattr(ctx.context, "identity", None) scoped_frame = None if isinstance(identity, Identity) and identity.scopes is not None and not ctx._acl_allowed: - gate_index = _scoped_gate_index(strategy, ctx.module_id) - if gate_index is None: + steps = tuple(steps) + scoped_steps = _scoped_steps(steps, ctx.module_id) + if scoped_steps is None: raise ACLDeniedError(ctx.context.caller_id, ctx.module_id) - scoped_frame = _ScopedFrame.capture(ctx, identity, gate_index) + scoped_frame = _ScopedFrame.capture(ctx, identity, scoped_steps) scoped_module = None + scoped_dispatched = False i = 0 # Index-based loop (not for-each) to support skip_to. while i < len(steps): step = steps[i] - if scoped_frame is not None and i > scoped_frame.gate_index and not ctx._acl_allowed and not ctx.dry_run: + if scoped_frame is not None and i > scoped_frame.steps.gate and not ctx._acl_allowed and not ctx.dry_run: raise ACLDeniedError(scoped_frame.caller_id, scoped_frame.module_id) if observation is not None and observation.defer_step(step.name, ctx): i += 1 @@ -904,11 +922,12 @@ async def _run_steps( observation.before_step(step.name, ctx) recovered = False try: - if scoped_frame is not None and i >= scoped_frame.gate_index: - if i == scoped_frame.gate_index: + if scoped_frame is not None: + if i == scoped_frame.steps.lookup: scoped_frame.require_match(ctx) - scoped_module = ctx.module - else: + elif i == scoped_frame.steps.gate: + scoped_frame.require_module(ctx, scoped_module) + elif i > scoped_frame.steps.gate: scoped_frame.require_grant(ctx, scoped_module) if timeout_ms > 0: result = await asyncio.wait_for( @@ -917,6 +936,11 @@ async def _run_steps( ) else: result = await step.execute(ctx) + if scoped_frame is not None: + if i == scoped_frame.steps.lookup: + scoped_module = ctx.module + elif i == scoped_frame.steps.dispatch: + scoped_dispatched = True except Exception as exc: duration = (time.monotonic() - step_start) * 1000 @@ -1148,6 +1172,8 @@ async def _run_steps( if effective_run_until(state): if scoped_frame is not None: scoped_frame.require_grant(ctx, scoped_module) + if not ctx.dry_run and not scoped_dispatched: + raise ACLDeniedError(scoped_frame.caller_id, scoped_frame.module_id) trace.success = True trace.total_duration_ms = (time.monotonic() - start) * 1000 return ctx.output, trace @@ -1156,6 +1182,8 @@ async def _run_steps( if scoped_frame is not None and not ctx.dry_run: scoped_frame.require_grant(ctx, scoped_module) + if not scoped_dispatched: + raise ACLDeniedError(scoped_frame.caller_id, scoped_frame.module_id) trace.success = not any(item.result.action == "abort" for item in trace.steps if not item.skipped) trace.total_duration_ms = (time.monotonic() - start) * 1000 # Use ctx.output — it's the most up-to-date (middleware_after may modify it) diff --git a/python/tests/test_identity_delegation.py b/python/tests/test_identity_delegation.py index ce853922..9014ded2 100644 --- a/python/tests/test_identity_delegation.py +++ b/python/tests/test_identity_delegation.py @@ -13,7 +13,15 @@ from apcore.context import Context, Identity from apcore.errors import ACLDeniedError, ApprovalDeniedError, ApprovalPendingError, InvalidInputError from apcore.executor import Executor -from apcore.pipeline import ExecutionStrategy, PipelineContext, _ScopedFrame +from apcore.pipeline import ( + BaseStep, + ExecutionStrategy, + PipelineContext, + PipelineState, + StepResult, + _ScopedFrame, + _ScopedSteps, +) from apcore.policy import PolicyEvaluationRequest, PolicyVerdict from apcore.registry import Registry from apcore.sys_modules.identity import _audit_payload_extras @@ -131,12 +139,66 @@ def test_scoped_discovery_requires_an_acl_gate_before_dispatch() -> None: assert executor.get_callable_descriptor("test.run", Context.create(Identity("ordinary"))) is not None +@pytest.mark.asyncio +@pytest.mark.parametrize("replace_dispatch", [False, True]) +async def test_scoped_strategy_requires_stock_dispatch(replace_dispatch: bool) -> None: + class HostDispatch(BaseStep): + async def execute(self, ctx: PipelineContext) -> StepResult: + return StepResult("continue") + + registry = Registry() + registry.register("test.run", _Module()) + steps = build_standard_strategy(registry=registry).steps + dispatch = next(index for index, step in enumerate(steps) if step.name == "execute") + steps = steps[:dispatch] + if replace_dispatch: + steps.append(HostDispatch("execute")) + strategy = ExecutionStrategy("host-dispatch", steps) + + with Executor(registry, acl=ACL([_allow({"scopes": ["read"]})]), strategy=strategy) as executor: + scoped = Context.create(Identity("actor", scopes=["read"])) + with pytest.raises(ACLDeniedError): + await executor.call_async("test.run", {}, scoped) + assert not (await executor.validate_async("test.run", {}, scoped)).valid + assert executor.get_callable_descriptor("test.run", scoped) is None + + +@pytest.mark.asyncio +async def test_scoped_strategy_requires_dispatch_before_returning_output() -> None: + class FinishEarly(BaseStep): + async def execute(self, ctx: PipelineContext) -> StepResult: + return StepResult("skip_to", skip_to="return_result") + + with _executor(_allow({"scopes": ["read"]})) as executor: + executor.current_strategy.insert_before("execute", FinishEarly("finish_early")) + context = Context.create(Identity("actor", scopes=["read"])) + with pytest.raises(ACLDeniedError): + await executor.call_async("test.run", {}, context) + + +@pytest.mark.asyncio +async def test_scoped_lookup_binds_module_before_step_observers() -> None: + class ClearLookupOutput: + def after_step(self, step_name: str, state: PipelineState, result: StepResult) -> None: + if step_name == "module_lookup": + state.context.module = None + + with _executor(_allow({"scopes": ["read"]})) as executor: + executor.current_strategy.add_step_middleware(ClearLookupOutput()) + context = Context.create(Identity("actor", scopes=["read"])) + with pytest.raises(ACLDeniedError): + await executor.call_async("test.run", {}, context) + with pytest.raises(ACLDeniedError): + async for _ in executor.stream("test.run", {}, context): + pytest.fail("A scoped stream must retain its selected module") + + @pytest.mark.parametrize("field", ["caller_id", "call_chain"]) def test_scoped_guard_requires_the_original_child_frame(field: str) -> None: identity = Identity("actor", scopes=["read"]) parent = Context.create(identity).child("test.parent") pipeline = PipelineContext("test.run", {}, parent) - frame = _ScopedFrame.capture(pipeline, identity, gate_index=0) + frame = _ScopedFrame.capture(pipeline, identity, _ScopedSteps(0, 1, 2)) pipeline.context = parent.child("test.run") frame.require_match(pipeline) From e4e2329de4ce8fa45669572ef9bd81c48da0d746 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 17:56:44 +0800 Subject: [PATCH 6/6] fix(core): preserve scoped recovery and identify private task stores Signed-off-by: tercel --- python/src/apcore/async_task.py | 6 ++++++ python/src/apcore/pipeline.py | 9 ++++----- python/tests/test_identity_delegation.py | 18 ++++++++++++++++++ typescript/src/async-task.ts | 3 +++ 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/python/src/apcore/async_task.py b/python/src/apcore/async_task.py index 0045173d..2c8abb35 100644 --- a/python/src/apcore/async_task.py +++ b/python/src/apcore/async_task.py @@ -436,6 +436,7 @@ def __init__( ) -> None: self._executor = executor self._max_tasks = max_tasks + self._owns_private_task_store = store is None self._store: TaskStore = store if store is not None else InMemoryTaskStore() self._semaphore = asyncio.Semaphore(max_concurrent) # Admission guard (mirrors Rust's admission_lock): serializes the @@ -448,6 +449,11 @@ def __init__( self._reaper_interval: float = 3600.0 self._reaper_max_age: float = 3600.0 + @property + def owns_private_task_store(self) -> bool: + """Whether the task store was created exclusively for this manager.""" + return self._owns_private_task_store + async def _save(self, info: TaskInfo) -> None: """Persist ``info`` via the configured store. diff --git a/python/src/apcore/pipeline.py b/python/src/apcore/pipeline.py index 59c10d04..12999e96 100644 --- a/python/src/apcore/pipeline.py +++ b/python/src/apcore/pipeline.py @@ -929,6 +929,8 @@ async def _run_steps( scoped_frame.require_module(ctx, scoped_module) elif i > scoped_frame.steps.gate: scoped_frame.require_grant(ctx, scoped_module) + if i == scoped_frame.steps.dispatch: + scoped_dispatched = True if timeout_ms > 0: result = await asyncio.wait_for( step.execute(ctx), @@ -936,11 +938,8 @@ async def _run_steps( ) else: result = await step.execute(ctx) - if scoped_frame is not None: - if i == scoped_frame.steps.lookup: - scoped_module = ctx.module - elif i == scoped_frame.steps.dispatch: - scoped_dispatched = True + if scoped_frame is not None and i == scoped_frame.steps.lookup: + scoped_module = ctx.module except Exception as exc: duration = (time.monotonic() - step_start) * 1000 diff --git a/python/tests/test_identity_delegation.py b/python/tests/test_identity_delegation.py index 9014ded2..ddb240b9 100644 --- a/python/tests/test_identity_delegation.py +++ b/python/tests/test_identity_delegation.py @@ -176,6 +176,24 @@ async def execute(self, ctx: PipelineContext) -> StepResult: await executor.call_async("test.run", {}, context) +@pytest.mark.asyncio +async def test_scoped_dispatch_preserves_business_error_recovery() -> None: + class FailingModule(_Module): + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + raise ValueError("Business error") + + class Recover: + def on_step_error(self, step_name: str, state: PipelineState, error: Exception) -> dict[str, Any] | None: + return {"recovered": True} if step_name == "execute" else None + + registry = Registry() + registry.register("test.run", FailingModule()) + with Executor(registry, acl=ACL([_allow({"scopes": ["read"]})])) as executor: + executor.current_strategy.add_step_middleware(Recover()) + context = Context.create(Identity("actor", scopes=["read"])) + assert await executor.call_async("test.run", {}, context) == {"recovered": True} + + @pytest.mark.asyncio async def test_scoped_lookup_binds_module_before_step_observers() -> None: class ClearLookupOutput: diff --git a/typescript/src/async-task.ts b/typescript/src/async-task.ts index 28d39d14..caaea9b6 100644 --- a/typescript/src/async-task.ts +++ b/typescript/src/async-task.ts @@ -165,6 +165,8 @@ interface AsyncTaskManagerOptions { */ export class AsyncTaskManager { readonly supportsTaskAllocationCallback = true; + /** Whether the task store was created exclusively for this manager. */ + readonly ownsPrivateTaskStore: boolean; private readonly _executor: Executor; private readonly _store: TaskStore; private readonly _maxConcurrent: number; @@ -187,6 +189,7 @@ export class AsyncTaskManager { constructor(opts: AsyncTaskManagerOptions) { this._executor = opts.executor; + this.ownsPrivateTaskStore = opts.store == null; this._store = opts.store ?? new InMemoryTaskStore(); this._maxConcurrent = opts.maxConcurrent ?? 10; this._maxTasks = opts.maxTasks ?? 1000;