From 0425cf51748d893ac8a4ca86f02db27b5e1acadf Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sat, 21 Nov 2026 22:48:50 -0500 Subject: [PATCH 01/15] context_runtime: a tenant refuses to start without an authorization plane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since agent-harness stopped reading "no authorizer" as "allow everything", a registry without a plane denies every call it is given. Context Runtime had eleven tenants and a console building registries, and nothing in the package said where their decisions come from — so the upgrade would have landed as a fleet that answers nothing, with the tempting local fix being a lambda that returns True, which is an unnamed allow-all by another name. tools/authz.py makes the source of authorization one decision with three answers: pass authorizer=... (a permissions plane bound to a principal), inherit the process-wide plane installed with set_default_authorizer(), or declare local execution out loud — local_trust=True with a written reason, or CR_LOCAL_AUTHORITY for a whole process. None of the three, and building a tenant raises with all three named. Local execution is never implied by the absence of a plane, because the absence of one is exactly what a misconfigured server looks like too. The console resolves differently, and deliberately so: it is built at module import inside apps whose gate installs a plane per request, so refusing to import an app is a worse failure than the console answering every tool call with missing_explicit_grant. It builds, logs the gap once, and validate() turns that gap into a start-up failure for an app that wants one. Test suites that run tools declare local execution once per test (tests/conftest.py::local_run) — the same declaration a laptop deployment makes once at start-up. Where a test asserts a denial, it now also asserts which gate denied it: with no plane the call stops before the approval policy, and such a test would pass while proving nothing about the gate named in its title. (cherry picked from commit 983d5e45a7b289ee012760e2ad4ad8a0b9ed884b) --- .../integrations/agentic_billing.py | 17 ++- context_runtime/integrations/agentic_books.py | 16 ++- .../integrations/agentic_compliance.py | 16 ++- .../integrations/agentic_support.py | 16 ++- context_runtime/integrations/control_tower.py | 17 ++- context_runtime/integrations/edge_sentinel.py | 42 ++++-- context_runtime/integrations/growth_engine.py | 17 ++- context_runtime/integrations/market_radar.py | 19 ++- context_runtime/integrations/modules.py | 59 ++++++++- .../integrations/outreach_engine.py | 17 ++- .../integrations/social_autopilot.py | 16 ++- context_runtime/tools/__init__.py | 2 + context_runtime/tools/authz.py | 120 +++++++++++++++++ context_runtime/tools/base.py | 21 ++- tests/conftest.py | 43 +++++- tests/test_integration_modules.py | 25 +++- tests/test_integration_security.py | 57 +++++++- tests/test_mcp.py | 11 +- tests/test_outreach.py | 6 +- tests/test_persistence.py | 2 +- tests/test_tool_authorizer.py | 124 ++++++++++++++++-- tests/test_tools.py | 29 ++-- 22 files changed, 612 insertions(+), 80 deletions(-) create mode 100644 context_runtime/tools/authz.py diff --git a/context_runtime/integrations/agentic_billing.py b/context_runtime/integrations/agentic_billing.py index 9781a8f..eff845d 100644 --- a/context_runtime/integrations/agentic_billing.py +++ b/context_runtime/integrations/agentic_billing.py @@ -13,6 +13,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace from .bandit import EpsilonGreedyBandit @@ -104,16 +105,28 @@ class AgenticBillingTenant: def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[BillingSignalBundle, ...] = DEFAULT_BILLING, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, - fetch_tool_factory: Callable[[dict], ToolResult] | None = None): + fetch_tool_factory: Callable[[dict], ToolResult] | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms self.bandit = _billing_bandit(epsilon=epsilon, arms=arms, bandit=bandit) - self.registry = ToolRegistry() + # Who answers for a call in this registry is the deployment's choice, not this tenant's + # default: an explicit ``authorizer``, else a plane installed with set_default_authorizer, + # else explicitly declared local authority — otherwise construction fails here instead of + # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below + # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. + # ``fetch_signals`` reads usage, invoices, dunning state and payment history for a named + # account: a sensitive read of customer financial data, so ``read`` — and the plane, not + # this file, narrows it per tenant and per row. + self.registry = ToolRegistry(authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, + context="agentic_billing")) fetch_fn = fetch_tool_factory or _simulate_fetch self.registry.register(function_tool( name="fetch_signals", description="Fetch the selected billing signal bundle (simulated).", fn=fetch_fn, + action="read", )) self._pending: dict[str, tuple] = {} diff --git a/context_runtime/integrations/agentic_books.py b/context_runtime/integrations/agentic_books.py index 138525d..89a8dd0 100644 --- a/context_runtime/integrations/agentic_books.py +++ b/context_runtime/integrations/agentic_books.py @@ -14,6 +14,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace from .bandit import EpsilonGreedyBandit @@ -105,16 +106,27 @@ class AgenticBooksTenant: def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[BooksReportBundle, ...] = DEFAULT_BOOKS, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, - pull_tool_factory: Callable[[dict], ToolResult] | None = None): + pull_tool_factory: Callable[[dict], ToolResult] | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms self.bandit = _books_bandit(epsilon=epsilon, arms=arms, bandit=bandit) - self.registry = ToolRegistry() + # Who answers for a call in this registry is the deployment's choice, not this tenant's + # default: an explicit ``authorizer``, else a plane installed with set_default_authorizer, + # else explicitly declared local authority — otherwise construction fails here instead of + # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below + # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. + # ``pull_reports`` reads receivables, payables, tax and trial balance for the tenant: + # books data, and nothing is written — ``read``. + self.registry = ToolRegistry(authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, + context="agentic_books")) pull_fn = pull_tool_factory or _simulate_pull self.registry.register(function_tool( name="pull_reports", description="Pull the selected ledger/report bundle (simulated).", fn=pull_fn, + action="read", )) self._pending: dict[str, tuple] = {} diff --git a/context_runtime/integrations/agentic_compliance.py b/context_runtime/integrations/agentic_compliance.py index 0eb9850..432b799 100644 --- a/context_runtime/integrations/agentic_compliance.py +++ b/context_runtime/integrations/agentic_compliance.py @@ -14,6 +14,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace from .bandit import EpsilonGreedyBandit @@ -105,16 +106,27 @@ class AgenticComplianceTenant: def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[ComplianceEvidenceBundle, ...] = DEFAULT_COMPLIANCE, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, - pull_tool_factory: Callable[[dict], ToolResult] | None = None): + pull_tool_factory: Callable[[dict], ToolResult] | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms self.bandit = _compliance_bandit(epsilon=epsilon, arms=arms, bandit=bandit) - self.registry = ToolRegistry() + # Who answers for a call in this registry is the deployment's choice, not this tenant's + # default: an explicit ``authorizer``, else a plane installed with set_default_authorizer, + # else explicitly declared local authority — otherwise construction fails here instead of + # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below + # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. + # ``pull_evidence`` reads access, crypto, audit and patch evidence: security findings, + # which are sensitive to read and only later consequential to remediate — ``read``. + self.registry = ToolRegistry(authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, + context="agentic_compliance")) pull_fn = pull_tool_factory or _simulate_pull self.registry.register(function_tool( name="pull_evidence", description="Pull the selected rule-family evidence bundle (simulated).", fn=pull_fn, + action="read", )) self._pending: dict[str, tuple] = {} diff --git a/context_runtime/integrations/agentic_support.py b/context_runtime/integrations/agentic_support.py index 816d40f..02b8147 100644 --- a/context_runtime/integrations/agentic_support.py +++ b/context_runtime/integrations/agentic_support.py @@ -14,6 +14,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace from .bandit import EpsilonGreedyBandit @@ -106,16 +107,27 @@ class AgenticSupportTenant: def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[SupportContextBundle, ...] = DEFAULT_SUPPORT, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, - retrieve_tool_factory: Callable[[dict], ToolResult] | None = None): + retrieve_tool_factory: Callable[[dict], ToolResult] | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms self.bandit = _support_bandit(epsilon=epsilon, arms=arms, bandit=bandit) - self.registry = ToolRegistry() + # Who answers for a call in this registry is the deployment's choice, not this tenant's + # default: an explicit ``authorizer``, else a plane installed with set_default_authorizer, + # else explicitly declared local authority — otherwise construction fails here instead of + # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below + # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. + # ``retrieve_context`` reads ticket history, account detail and escalation state for a + # ticket: customer personal data — ``read``, scoped per tenant by the plane. + self.registry = ToolRegistry(authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, + context="agentic_support")) retrieve_fn = retrieve_tool_factory or _simulate_retrieve self.registry.register(function_tool( name="retrieve_context", description="Retrieve the selected support context bundle (simulated).", fn=retrieve_fn, + action="read", )) self._pending: dict[str, tuple] = {} diff --git a/context_runtime/integrations/control_tower.py b/context_runtime/integrations/control_tower.py index 1745248..966633a 100644 --- a/context_runtime/integrations/control_tower.py +++ b/context_runtime/integrations/control_tower.py @@ -15,6 +15,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace from .bandit import EpsilonGreedyBandit @@ -98,16 +99,28 @@ class ControlTowerTenant: def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[ControlTowerArm, ...] = DEFAULT_TOWER, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, - refresh_tool_factory: Callable[[dict], ToolResult] | None = None): + refresh_tool_factory: Callable[[dict], ToolResult] | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms self.bandit = bandit or _tower_bandit(epsilon=epsilon, arms=arms) - self.registry = ToolRegistry() + # Who answers for a call in this registry is the deployment's choice, not this tenant's + # default: an explicit ``authorizer``, else a plane installed with set_default_authorizer, + # else explicitly declared local authority — otherwise construction fails here instead of + # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below + # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. + # ``refresh_metabase`` re-runs Metabase queries and returns their rows — the same call + # agentic-os classifies as ``bi.refresh``/read: a query against the platform's own + # warehouse, which writes no business state. Persisting a card or dashboard would not be. + self.registry = ToolRegistry(authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, + context="control_tower")) refresh_fn = refresh_tool_factory or _refresh_queries self.registry.register(function_tool( name="refresh_metabase", description="Refresh the Metabase query set (simulated).", fn=refresh_fn, + action="read", )) self._pending: dict[str, tuple[Plan, ControlTowerArm, str, str]] = {} diff --git a/context_runtime/integrations/edge_sentinel.py b/context_runtime/integrations/edge_sentinel.py index 7aa1aa8..098e0da 100644 --- a/context_runtime/integrations/edge_sentinel.py +++ b/context_runtime/integrations/edge_sentinel.py @@ -21,7 +21,8 @@ from dataclasses import dataclass from ..runtime.runtime import ContextRuntime -from ..tools.base import ApprovalPolicy, ToolRegistry, ToolResult, ToolSpec +from ..tools.authz import resolve_authorizer +from ..tools.base import ACTIONS, ApprovalPolicy, ToolRegistry, ToolResult, ToolSpec from ..types import Goal, Hit, Plan, Trace from .bandit import EpsilonGreedyBandit @@ -61,7 +62,11 @@ def __init__(self, lapi_url: str | None = None, bouncer_key: str | None = None): def spec(self) -> ToolSpec: return ToolSpec(name="crowdsec_decisions", description="Live CrowdSec ban/captcha decisions (IP, scenario, duration).", - parameters={"type": "object", "properties": {"query": {"type": "string"}}}) + parameters={"type": "object", "properties": {"query": {"type": "string"}}}, + # It asks the platform's own CrowdSec LAPI for decisions and writes nothing — the + # platform's table draws the same line for `bi.refresh`. Sensitive, so scoped + # narrowly by the plane; sensitivity is not a reason to call it a write. + action="read") def run(self, args: dict) -> ToolResult: rows = self._live() if (self.lapi_url and self.bouncer_key) else self._sim(args.get("query", "")) @@ -108,7 +113,10 @@ class ThreatIntelTool: def spec(self) -> ToolSpec: return ToolSpec(name="threat_intel", description="Reputation/CVE lookup for an IP or hash or CVE id.", - parameters={"type": "object", "properties": {"query": {"type": "string"}}}) + parameters={"type": "object", "properties": {"query": {"type": "string"}}}, + # A lookup in a local reputation table — read. Swapping in a live third-party feed + # is a different tool and has to be classified by whoever wires it. + action="read") def run(self, args: dict) -> ToolResult: ind = (args.get("query") or "").strip() @@ -125,7 +133,9 @@ class EdrTimelineTool: def spec(self) -> ToolSpec: return ToolSpec(name="edr_timeline", description="Recent endpoint process/behavior events for triage.", - parameters={"type": "object", "properties": {"query": {"type": "string"}}}) + parameters={"type": "object", "properties": {"query": {"type": "string"}}}, + # Reads endpoint events for triage and writes nothing — read. + action="read") def run(self, args: dict) -> ToolResult: events = [ @@ -151,7 +161,12 @@ def spec(self) -> ToolSpec: description="Ban an IP at the edge (CrowdSec decision).", parameters={"type": "object", "properties": { "ip": {"type": "string"}, "duration": {"type": "string"}}}, - side_effecting=True, approval_required=True) + side_effecting=True, approval_required=True, + # The platform's own inventory classifies the same capability (`ban_ip`, + # apps/edge-sentinel/operator.py:79) as `write`: it changes live edge policy for a + # third party. The dry-run default is a runtime guard, not a licence to call it a + # read; the grant and the approval are separate checks. + action="write") def run(self, args: dict) -> ToolResult: ip, dur = args.get("ip", "?"), args.get("duration", "4h") @@ -218,15 +233,24 @@ class SOCTriageTenant: whether the verdict was confirmed.""" def __init__(self, runtime: ContextRuntime | None = None, registry: ToolRegistry | None = None, - bandit: EpsilonGreedyBandit | None = None, approver=None): + bandit: EpsilonGreedyBandit | None = None, approver=None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.bandit = bandit or _soc_bandit() - self.registry = registry or self._default_registry(approver) + # A registry handed in by the caller is already the caller's decision about who answers for a + # call; a registry built here names its own answerer (see tools/authz.py). + self.registry = registry or self._default_registry(approver, authorizer=authorizer, + local_trust=local_trust, + local_trust_reason=local_trust_reason) self._pending: dict[str, tuple[Plan, SourceBundle, str]] = {} @staticmethod - def _default_registry(approver) -> ToolRegistry: - reg = ToolRegistry(ApprovalPolicy(mode="deny_side_effects", approver=approver)) + def _default_registry(approver, *, authorizer=None, local_trust: bool = False, + local_trust_reason: str = "") -> ToolRegistry: + reg = ToolRegistry(ApprovalPolicy(mode="deny_side_effects", approver=approver), + authorizer=resolve_authorizer(authorizer, local_trust=local_trust, + local_trust_reason=local_trust_reason, + context="edge-sentinel soc tenant")) for t in (CrowdSecDecisionsTool(), ThreatIntelTool(), EdrTimelineTool(), BlockIpTool()): reg.register(t) return reg diff --git a/context_runtime/integrations/growth_engine.py b/context_runtime/integrations/growth_engine.py index 6af037e..94ecd58 100644 --- a/context_runtime/integrations/growth_engine.py +++ b/context_runtime/integrations/growth_engine.py @@ -8,6 +8,7 @@ from .bandit import EpsilonGreedyBandit from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Plan, Trace @@ -127,17 +128,29 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[AttributionArm, ...] = DEFAULT_GROWTH, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, bucket_fn: Callable[[str], str] = growth_engine_bucket, - report_tool_factory: Callable[[dict], ToolResult] | None = None): + report_tool_factory: Callable[[dict], ToolResult] | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms self.bandit = bandit or _growth_bandit(epsilon=epsilon, arms=arms) self.bucket_fn = bucket_fn - self.registry = ToolRegistry() + # Who answers for a call in this registry is the deployment's choice, not this tenant's + # default: an explicit ``authorizer``, else a plane installed with set_default_authorizer, + # else explicitly declared local authority — otherwise construction fails here instead of + # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below + # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. + # ``draft_attribution_report`` composes an attribution answer from analytics it reads; + # the text goes back to the caller and nothing is published — ``read``. Publishing the + # report is a separate route and is classified ``write`` where it is registered. + self.registry = ToolRegistry(authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, + context="growth_engine")) report_fn = report_tool_factory or _draft_attribution_report self.registry.register(function_tool( name="draft_attribution_report", description="Draft an attribution breakdown for the chosen arm (simulated).", fn=report_fn, + action="read", )) self._pending: dict[str, tuple[Plan, AttributionArm, str, str]] = {} diff --git a/context_runtime/integrations/market_radar.py b/context_runtime/integrations/market_radar.py index 38543e6..7b71cc1 100644 --- a/context_runtime/integrations/market_radar.py +++ b/context_runtime/integrations/market_radar.py @@ -11,6 +11,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace from .bandit import EpsilonGreedyBandit @@ -133,16 +134,30 @@ class MarketRadarTenant: def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[RadarArm, ...] = DEFAULT_RADAR, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, - scrape_tool_factory: Callable[[dict], ToolResult] | None = None): + scrape_tool_factory: Callable[[dict], ToolResult] | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms self.bandit = bandit or _radar_bandit(epsilon=epsilon, arms=arms) - self.registry = ToolRegistry() + # Who answers for a call in this registry is the deployment's choice, not this tenant's + # default: an explicit ``authorizer``, else a plane installed with set_default_authorizer, + # else explicitly declared local authority — otherwise construction fails here instead of + # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below + # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. + # ``perform_sweep`` is not a read: it initiates outbound fetches against the watch set + # (pricing page, changelog, careers, blog), downloads their content, and the result is + # persisted as tenant state. Third-party fetching with stored consequences is ``write`` + # under the platform's own inventory (compare crm.research, sbom, add_watch). The shipped + # default is the offline simulation; a real fetcher must be registered by whoever wires it. + self.registry = ToolRegistry(authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, + context="market_radar")) scrape_fn = scrape_tool_factory or _scrape_watch self.registry.register(function_tool( name="perform_sweep", description="Perform the selected market radar sweep (simulated).", fn=scrape_fn, + action="write", )) self._pending: dict[str, tuple[Plan, RadarArm, str, ToolResult]] = {} diff --git a/context_runtime/integrations/modules.py b/context_runtime/integrations/modules.py index 339432f..a21aaaf 100644 --- a/context_runtime/integrations/modules.py +++ b/context_runtime/integrations/modules.py @@ -21,7 +21,8 @@ from itertools import combinations from ..runtime.runtime import ContextRuntime -from ..tools.base import ApprovalPolicy, ToolRegistry, ToolResult, ToolSpec, function_tool +from ..tools.authz import RegistryConfigurationError, resolve_authorizer +from ..tools.base import ACTIONS, ApprovalPolicy, ToolRegistry, ToolResult, ToolSpec, function_tool from ..types import Goal, Hit, Plan, Trace from .bandit import EpsilonGreedyBandit @@ -161,15 +162,47 @@ def run(args: dict) -> ToolResult: hit = Hit(chunk_id=f"{module}:{source}", filename=f"{module}/{source}", source=source, text=f"[{module}/{source}] record relevant to: {q}", score=1.0) return ToolResult(ok=True, hits=[hit], text=f"{module}/{source}") - return function_tool(f"{module}_{source}", run, description=f"{module} source: {source}") + # The source tool reads records out of the module's own bundle and writes nothing — `read`. A + # source name is not evidence (the inventory calls `sbom`, a scan, a write and `search_articles`, + # a lookup, a read): this class describes the implementation above. An integrator that swaps a + # source for a live third-party fetch or scan registers a different tool and classifies it. + return function_tool(f"{module}_{source}", run, description=f"{module} source: {source}", + action="read") + + +# What each declared fleet action accomplishes, read off the platform's own classification table +# (agentic-os docs/TOOL_CLASSIFICATION_INVENTORY.md) wherever the same capability exists there: +# `refund` moves money (billing.charge = write); `dunning`, `post`, `send_campaign` and +# `send_sequence` are outbound communications (send_email, post_to_channel, crm.draft_outreach = +# write); `escalate`, `remediate` (compliance.remediate), `close` (a period close) and `rollback` +# (infra.rollback_release) change state — `write`; `fulfill_dsar` is the capability the platform +# lists as `privacy.delete` = `delete`. Declared per action, never derived from the word "action". +_ACTION_CLASSES: dict[str, str] = { + "refund": "write", + "dunning": "write", + "escalate": "write", + "remediate": "write", + "close": "write", + "post": "write", + "send_campaign": "write", + "send_sequence": "write", + "block_ip": "write", + "rollback": "write", + "fulfill_dsar": "delete", +} def _action_tool(module: str, action: str): def run(args: dict) -> ToolResult: return ToolResult(ok=True, data={"action": action, "applied": False}, text=f"[dry-run] {module}.{action}({args})") + action_class = _ACTION_CLASSES.get(action) + if action_class is None: + raise RegistryConfigurationError( + f"the fleet action {module}.{action} has no recorded risk class — add it to _ACTION_CLASSES " + f"in modules.py with the evidence for what it actually does, instead of defaulting it") return function_tool(f"{module}_{action}", run, description=f"{module} action: {action}", - side_effecting=True, approval_required=True) + side_effecting=True, approval_required=True, action=action_class) class ModuleTenant: @@ -177,12 +210,20 @@ class ModuleTenant: def __init__(self, spec: ModuleSpec, runtime: ContextRuntime | None = None, bandit: EpsilonGreedyBandit | None = None, approver=None, epsilon: float = 0.12, - persist_path: str | None = None): + persist_path: str | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.spec = spec self.runtime = runtime or ContextRuntime.default([]) self.arms = _bundles(spec.sources) self.bandit = bandit or EpsilonGreedyBandit(self.arms, epsilon=epsilon, persist_path=persist_path) - self.registry = ToolRegistry(ApprovalPolicy(mode="deny_side_effects", approver=approver)) + # The approval policy decides whether a confirmed caller may run a side-effecting tool; who is + # allowed to ask at all is a separate answer, named here (explicit ``authorizer``, else a plane + # installed with set_default_authorizer, else declared local authority — see tools/authz.py). + self.registry = ToolRegistry(ApprovalPolicy(mode="deny_side_effects", approver=approver), + authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, + local_trust_reason=local_trust_reason, + context=f"module fleet tenant {spec.name!r}")) for s in spec.sources: self.registry.register(_source_tool(spec.name, s)) for a in spec.actions: @@ -227,7 +268,11 @@ def _key(q: str) -> str: return hashlib.sha256(q.encode()).hexdigest()[:16] -def build_fleet(runtime: ContextRuntime | None = None, approver=None) -> dict[str, ModuleTenant]: +def build_fleet(runtime: ContextRuntime | None = None, approver=None, *, + authorizer=None, local_trust: bool = False, + local_trust_reason: str = "") -> dict[str, ModuleTenant]: """Instantiate the whole catalog as Context Runtime tenants — the migrated fleet.""" rt = runtime or ContextRuntime.default([]) - return {name: ModuleTenant(spec, runtime=rt, approver=approver) for name, spec in CATALOG.items()} + return {name: ModuleTenant(spec, runtime=rt, approver=approver, authorizer=authorizer, + local_trust=local_trust, local_trust_reason=local_trust_reason) + for name, spec in CATALOG.items()} diff --git a/context_runtime/integrations/outreach_engine.py b/context_runtime/integrations/outreach_engine.py index ffa9c10..c710f9e 100644 --- a/context_runtime/integrations/outreach_engine.py +++ b/context_runtime/integrations/outreach_engine.py @@ -19,6 +19,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Plan, Trace from .bandit import EpsilonGreedyBandit @@ -122,18 +123,30 @@ def __init__(self, runtime: ContextRuntime | None = None, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, bucket_fn: Callable[[str], str] = outreach_bucket, teardown_tool_factory: Callable[[dict], ToolResult] | None = None, - approver: Callable[[str], bool] | None = None): + approver: Callable[[str], bool] | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms self.bandit = bandit or _outreach_bandit(epsilon=epsilon, arms=arms) self.bucket_fn = bucket_fn # human-in-the-loop: send_sequence is approval-gated (default-deny), like the other modules. self.approver = approver or (lambda action: False) - self.registry = ToolRegistry() + # Who answers for a call in this registry is the deployment's choice, not this tenant's + # default: an explicit ``authorizer``, else a plane installed with set_default_authorizer, + # else explicitly declared local authority — otherwise construction fails here instead of + # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below + # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. + # ``draft_teardown`` writes nothing and contacts nobody: it returns the drafted opener. + # ``send_sequence`` below is the external communication and stays approval-gated with a + # default-deny approver, so drafting is ``read`` while sending needs both gates. + self.registry = ToolRegistry(authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, + context="outreach_engine")) self.registry.register(function_tool( name="draft_teardown", description="Draft the personalized opener (EXPLAIN teardown for artifact plays).", fn=teardown_tool_factory or _draft_teardown, + action="read", )) self._pending: dict[str, tuple[Plan, OutreachPlay, str, str]] = {} diff --git a/context_runtime/integrations/social_autopilot.py b/context_runtime/integrations/social_autopilot.py index 6eb9799..1d1ffaf 100644 --- a/context_runtime/integrations/social_autopilot.py +++ b/context_runtime/integrations/social_autopilot.py @@ -19,6 +19,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace from .bandit import EpsilonGreedyBandit @@ -130,16 +131,27 @@ class SocialAutopilotTenant: def __init__(self, runtime: ContextRuntime | None = None, strategies: tuple[SocialStrategy, ...] = DEFAULT_STRATEGIES, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, - caption_tool_factory: Callable[[dict], ToolResult] | None = None): + caption_tool_factory: Callable[[dict], ToolResult] | None = None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.strategies = strategies self.bandit = bandit or _social_bandit(epsilon=epsilon, strategies=strategies) - self.registry = ToolRegistry() + # Who answers for a call in this registry is the deployment's choice, not this tenant's + # default: an explicit ``authorizer``, else a plane installed with set_default_authorizer, + # else explicitly declared local authority — otherwise construction fails here instead of + # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below + # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. + # ``draft_caption`` returns drafted copy to the caller; the schedule/publish call that + # would make it an external communication is a separate consequential path — ``read``. + self.registry = ToolRegistry(authorizer=resolve_authorizer( + authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, + context="social_autopilot")) caption_fn = caption_tool_factory or _draft_caption self.registry.register(function_tool( name="draft_caption", description="Draft a caption for the chosen social strategy (simulated).", fn=caption_fn, + action="read", )) self._pending: dict[str, tuple[Plan, SocialStrategy, str, str]] = {} diff --git a/context_runtime/tools/__init__.py b/context_runtime/tools/__init__.py index 68678a4..c71d5e0 100644 --- a/context_runtime/tools/__init__.py +++ b/context_runtime/tools/__init__.py @@ -15,9 +15,11 @@ ToolResult, ToolSpec, ) +from .authz import LOCAL_AUTHORITY_ENV, local_authority, local_authority_from_env, resolve_authorizer from .retriever import ToolRetriever __all__ = [ "ToolSpec", "ToolResult", "ToolPlugin", "ToolRegistry", "ApprovalPolicy", "ToolError", "ToolRetriever", + "resolve_authorizer", "local_authority", "local_authority_from_env", "LOCAL_AUTHORITY_ENV", ] diff --git a/context_runtime/tools/authz.py b/context_runtime/tools/authz.py new file mode 100644 index 0000000..db0fde2 --- /dev/null +++ b/context_runtime/tools/authz.py @@ -0,0 +1,120 @@ +"""Who authorizes a Context Runtime tool call — and how a local run says so out loud. + +Context Runtime owns the seam (``ToolRegistry.authorizer``, defined upstream in ``agent_harness.tools``) and the +vocabulary a registration declares its risk in (``ToolSpec.action``). It deliberately does NOT own a policy engine: +the engine is whoever installs an authorizer. Three engines plug into the same seam today — +``agentic_os.permissions.make_authorizer(store, tool_actions=...)`` in a governed deployment, an operator's own +callable in a customer-controlled install, and :func:`~context_runtime.tools.base.local_trusted_authorizer` for a +single-operator run — and this module is the only place that chooses between them, so the twelve integration +tenants cannot each invent their own answer. + +**Three doors, in precedence order** (``resolve_authorizer``): + +1. *Per-registry*: the caller passed ``authorizer=...``. The integrator's explicit choice always wins. +2. *Process-wide*: an authorizer is installed with ``set_default_authorizer(...)`` — what + ``agentic_os.app_gate.install_gate`` does at start-up. Returning ``None`` here means "inherit it", read at + call time, so a plane installed after the tenant was built still governs it. +3. *Local authority*: the operator declared this process runs locally, on their own machine or their own + single-tenant box. That is the harness's local-trust authorizer: an attributed, greppable wildcard grant, + not a silent hole. The first use warns once per process and every decision is audited as + ``plane="local_trusted"``. + +**Missing configuration is not local trust.** With no authorizer, no installed plane and no declared local +authority, ``resolve_authorizer`` raises :class:`~context_runtime.tools.base.RegistryConfigurationError` at +construction, naming all three doors. Letting it pass would build a registry that answers every call with +``denied: missing_explicit_grant`` — correct, but discovered by a user instead of in a start-up log. + +Local authority is the FLOOR, never the ceiling: it is consulted only when neither of the first two doors is +open. A copied example with ``local_trust=True`` inside a service that installed a permissions plane therefore +cannot loosen that plane; the plane wins. +""" +from __future__ import annotations + +import os +from typing import Optional + +from .base import Authorizer, RegistryConfigurationError, default_authorizer_installed, local_trusted_authorizer + +#: Set this to a sentence — not to ``1`` — to declare that the process runs with the operator's own authority +#: ("single-operator laptop demo", "offline benchmark, simulated tools"). The reason is required because a +#: value that says nothing is how an allow-all switch gets copied into a production compose file. +LOCAL_AUTHORITY_ENV = "CR_LOCAL_AUTHORITY" + +#: Values people reach for when switching something on. They carry no reason, so they are refused. +_BARE_TRUTHY = {"1", "true", "t", "yes", "y", "on", "enable", "enabled"} + + +def _refuse(reason: str, *, context: str, source: str) -> str: + """A local-authority reason, checked. Raises rather than accepting an empty or bare-truthy declaration.""" + text = (reason or "").strip() + where = f" ({context})" if context else "" + if not text: + raise RegistryConfigurationError( + f"local authority was requested{where} without a reason. {source} takes a sentence describing " + f"why this process may act with the operator's own authority — the reason is what makes an " + f"allow-all choice reviewable in a manifest or a pull request.") + if text.lower() in _BARE_TRUTHY: + raise RegistryConfigurationError( + f"{source}={text!r} is not a reason{where}. Give it a sentence, e.g. " + f'{source}="single-operator local demo, no tenant in scope".') + return text + + +def local_authority(reason: str, *, context: str = "", source: str = "local_trust_reason") -> Authorizer: + """The explicit local-authority authorizer. ``reason`` is mandatory; see :func:`resolve_authorizer`.""" + _refuse(reason, context=context, source=source) + return local_trusted_authorizer() + + +def local_authority_from_env(*, context: str = "") -> tuple[bool, str]: + """``(declared, reason)`` from :data:`LOCAL_AUTHORITY_ENV`. Unset is ``(False, "")`` — never a trust grant.""" + raw = (os.environ.get(LOCAL_AUTHORITY_ENV) or "").strip() + if not raw: + return False, "" + return True, _refuse(raw, context=context, source=LOCAL_AUTHORITY_ENV) + + +def resolve_authorizer(authorizer: Optional[Authorizer] = None, *, local_trust: bool = False, + local_trust_reason: str = "", context: str = "", + on_missing: str = "raise") -> Optional[Authorizer]: + """The authorizer one Context Runtime registry should be built with, or ``None`` to inherit the default. + + ``authorizer`` — the integrator's per-registry choice — wins outright, unexamined: it is code, and code may + pass anything callable. Otherwise an installed process-wide plane is inherited (``None``). Otherwise local + authority is used, but only when it was declared — ``local_trust=True`` with a written + ``local_trust_reason``, or ``CR_LOCAL_AUTHORITY=""``. Otherwise this raises: a tenant that reaches + this point with no answer is a misconfiguration, and the least dangerous place to say so is construction. + + ``on_missing`` decides what "no answer" means. ``"raise"`` (the default, and right for a tenant that owns + its registry) makes it a start-up failure. ``"deny_later"`` returns ``None`` and lets the registry answer + every call with its own ``missing_authorizer`` denial — what a shared, request-facing surface such as + ``AgentConsole`` wants, because there the missing plane is a per-request fact the operator can still fix, + and the denial is already asserted in downstream tests. Neither mode grants local trust implicitly. + """ + if authorizer is not None: + if not callable(authorizer): + raise RegistryConfigurationError( + f"authorizer{f' for {context}' if context else ''} is {type(authorizer).__name__}, not a " + f"callable (principal, spec, args) -> decision") + return authorizer + if default_authorizer_installed(): + return None # inherit the plane; re-read at every call + env_declared, env_reason = local_authority_from_env(context=context) + if local_trust: + reason, source = ((local_trust_reason, "local_trust_reason") if local_trust_reason + else (env_reason, LOCAL_AUTHORITY_ENV)) + return local_authority(reason, context=context, source=source) + if env_declared: + return local_authority(env_reason, context=context, source=LOCAL_AUTHORITY_ENV) + if on_missing == "deny_later": + return None + if on_missing != "raise": + raise RegistryConfigurationError( + f"on_missing={on_missing!r} is not one of 'raise' / 'deny_later' ({context or 'caller'})") + raise RegistryConfigurationError( + f"no authorizer is configured{f' for {context}' if context else ''}, and Context Runtime will not " + f"guess. Do one of: pass authorizer=... (a permissions plane, e.g. " + f"agentic_os.permissions.make_authorizer(store, tool_actions=registry.classification())); install one " + f"process-wide with context_runtime.tools.set_default_authorizer(...) before building the tenant; or " + f"declare local execution explicitly with local_trust=True and a written local_trust_reason, or " + f'{LOCAL_AUTHORITY_ENV}="why this process is trusted".') \ No newline at end of file diff --git a/context_runtime/tools/base.py b/context_runtime/tools/base.py index 04f7632..f66d7a9 100644 --- a/context_runtime/tools/base.py +++ b/context_runtime/tools/base.py @@ -3,24 +3,41 @@ These definitions live in ``agent_harness.tools`` (github.com/redevops-io/agent-harness) and are re-exported here unchanged so existing imports keep working. They used to be a copy; the copy had no tests tying it to the original and could drift. ``agent-harness`` is standard-library only, so depending on it adds no transitive dependencies. + +Two of these names are load-bearing outside this repository. ``set_default_authorizer`` is the install point an +enterprise permissions plane uses once at start-up (``agentic_os.app_gate.install_gate`` reaches the engine through +this module), and the risk-class vocabulary (``ACTIONS``, ``ToolSpec.action``) is what a registration declares its +risk in. Where Context Runtime decides *who* authorizes one of its registries, as opposed to which engine answers, +is :mod:`context_runtime.tools.authz`. """ from __future__ import annotations from agent_harness.tools import ( # noqa: F401 (re-exports) + ACTIONS, ApprovalPolicy, Approver, + Authorization, Authorizer, + Decision, + PolicyReason, + RegistryConfigurationError, + ToolClassificationError, ToolError, ToolPlugin, ToolRegistry, ToolResult, ToolSpec, + ValidationReport, current_principal, + default_authorizer_installed, function_tool, + local_trusted_authorizer, set_default_authorizer, ) __all__ = [ - "ApprovalPolicy", "Approver", "Authorizer", "ToolError", "ToolPlugin", "ToolRegistry", "ToolResult", - "ToolSpec", "current_principal", "function_tool", "set_default_authorizer", + "ACTIONS", "ApprovalPolicy", "Approver", "Authorization", "Authorizer", "Decision", "PolicyReason", + "RegistryConfigurationError", "ToolClassificationError", "ToolError", "ToolPlugin", "ToolRegistry", + "ToolResult", "ToolSpec", "ValidationReport", "current_principal", "default_authorizer_installed", + "function_tool", "local_trusted_authorizer", "set_default_authorizer", ] diff --git a/tests/conftest.py b/tests/conftest.py index 04e01bc..aa1fe62 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,6 +6,20 @@ caller already chose one. * Per-test state: an autouse fixture points the home variables at the test's own ``tmp_path`` so no test reads another test's files or writes into the working directory. +* Per-test authorization plane: an autouse fixture starts every test with no process-wide authorizer + installed, and leaves none behind. + +The third is the one that decides what the authorization tests actually prove. Since agent-harness C1 a +registry with no authorizer denies every tool call, so a test that expects a tool to *run* has to say who +authorizes it — the same decision a deployment makes at start-up. ``local_run`` makes that declaration once +per test (the harness's attributed local-trust authorizer, installed process-wide, exactly as +``agentic_os.app_gate.install_gate`` installs a real plane) rather than smuggling an unnamed allow-all +lambda into each registry. Tests that assert the fail-closed behaviour deliberately do *not* ask for it. + +And the autouse cleanup is not decoration: a process-wide authorizer leaked by one test silently converts +every later fail-closed assertion into a passing one, which is the exact direction this migration is +worried about. It is declared after ``_per_test_home`` so a test can never reach the plane assertion +without the state directory that other fixtures expect to exist. """ from __future__ import annotations @@ -22,6 +36,11 @@ _SESSION_HOME = tempfile.TemporaryDirectory(prefix="cr-test-home-") os.environ["CONTEXT_RUNTIME_HOME"] = _SESSION_HOME.name +# Imported after the home variables are set: this package must not be imported before the isolation above +# exists, for the same reason the import-time note above exists. +from context_runtime.tools.base import (default_authorizer_installed, local_trusted_authorizer, # noqa: E402 + set_default_authorizer) + _REPO_ROOT = Path(__file__).resolve().parent.parent _STRAY = (".context-runtime", ".agentic-os") @@ -35,6 +54,16 @@ def _per_test_home(tmp_path, monkeypatch): yield home +@pytest.fixture(autouse=True) +def _clean_authorizer_plane(): + """Start each test with no process-wide plane, and leave none behind.""" + assert not default_authorizer_installed(), ( + "a process-wide authorizer is already installed — an earlier test did not clean up, and every " + "fail-closed assertion from here on would be testing the wrong thing") + yield + set_default_authorizer(None) + + @pytest.fixture(scope="session", autouse=True) def _no_stray_state_in_cwd(): """Fail the run if a test left a state directory in the working directory or the repository root.""" @@ -45,6 +74,18 @@ def _no_stray_state_in_cwd(): assert not created, f"tests wrote state into the working tree: {created}" +@pytest.fixture +def local_run(): + """Run this test's registries under a declared local authority (an attributed wildcard grant). + + Returns the ``plane`` name the decisions are audited under, so a test can assert who authorized the call + instead of only that it ran. + """ + plane = "pytest_local" + set_default_authorizer(local_trusted_authorizer(plane=plane)) + return plane + + def pytest_terminal_summary(terminalreporter): """Print every skip reason once with its count, so a run states plainly what it did NOT verify. Reasons that contain ``UNVERIFIED`` mark behaviour that is untested on this platform.""" @@ -62,4 +103,4 @@ def pytest_terminal_summary(terminalreporter): for reason, n in sorted(counts.items(), key=lambda kv: (not kv[0].startswith("UNVERIFIED"), -kv[1], kv[0])): tr.write_line(f"{n:4d} {reason[:200]}") unverified = sum(n for r, n in counts.items() if "UNVERIFIED" in r) - tr.write_line(f"{unverified} skipped item(s) are marked UNVERIFIED on this platform; {len(skipped) - unverified} other skip(s).") + tr.write_line(f"{unverified} skipped item(s) are marked UNVERIFIED on this platform; {len(skipped) - unverified} other skip(s).") \ No newline at end of file diff --git a/tests/test_integration_modules.py b/tests/test_integration_modules.py index 005cde4..9eea2c9 100644 --- a/tests/test_integration_modules.py +++ b/tests/test_integration_modules.py @@ -1,4 +1,11 @@ -"""The business-module fleet: catalog instantiates, tenants handle/learn/gate generically.""" +"""The business-module fleet: catalog instantiates, tenants handle/learn/gate generically. + +``local_run`` appears on the tests that build a tenant, because a tenant now refuses to be built without an +authorizer — its own, the process-wide plane, or a declared local authority. This suite is the third case: a +module tenant running on an operator's own machine with no policy plane to consult. Declaring it once per test +is what a deployment declares once at start-up; the alternative is an unnamed allow-all per registry, which is +the thing this migration exists to remove. +""" from __future__ import annotations from context_runtime.integrations.modules import ( @@ -6,7 +13,7 @@ ) -def test_whole_catalog_instantiates(): +def test_whole_catalog_instantiates(local_run): fleet = build_fleet() assert len(fleet) == len(CATALOG) >= 16 for name, tenant in fleet.items(): @@ -14,27 +21,31 @@ def test_whole_catalog_instantiates(): assert tenant.arms # has source bundles to choose from -def test_handle_pulls_source_evidence(): +def test_handle_pulls_source_evidence(local_run): t = ModuleTenant(CATALOG["support"]) r = t.handle("customer cannot log in after the latest release") assert r.hits and r.context assert all(h.source in CATALOG["support"].sources for h in r.hits) -def test_action_questions_recommend_gated_action(): +def test_action_questions_recommend_gated_action(local_run): t = ModuleTenant(CATALOG["billing"]) r = t.handle("issue a refund for the duplicate charge") assert r.kind == "action" and r.recommended_action == "billing.refund" -def test_side_effecting_action_denied_without_approver(): +def test_side_effecting_action_denied_without_approver(local_run): + """The denial here is the *approval* gate's. With no authorizer at all the call would stop one gate + earlier for a different reason, and the test would pass while testing the wrong gate.""" t = ModuleTenant(CATALOG["billing"], approver=lambda a: False) res = t.act("refund", amount=10) assert not res.ok and "denied" in res.error assert t.registry.audit[-1]["allowed"] is False + assert any(a.get("allowed") for a in t.registry.audit) # authorization allowed it (local trust) + assert "policy_reason" not in t.registry.audit[-1] # the last record is the approval gate's own -def test_action_allowed_with_approver_but_dry_run(): +def test_action_allowed_with_approver_but_dry_run(local_run): t = ModuleTenant(CATALOG["billing"], approver=lambda a: True) res = t.act("refund", amount=10) assert res.ok and "dry-run" in res.text @@ -51,7 +62,7 @@ def test_reward_prefers_cheaper_bundle(): assert reward(False, SourceBundle(("a",)), 4) == 0.0 -def test_tenant_learns_cheapest_sufficient_bundle(): +def test_tenant_learns_cheapest_sufficient_bundle(local_run): t = ModuleTenant(CATALOG["control_tower"], epsilon=0.1) latent = "warehouse" # the decisive source for this domain question q = "why did revenue fall last quarter?" diff --git a/tests/test_integration_security.py b/tests/test_integration_security.py index 4b44bd7..80491b6 100644 --- a/tests/test_integration_security.py +++ b/tests/test_integration_security.py @@ -1,4 +1,9 @@ -"""edge-sentinel SOC tenant: tools assemble evidence, bandit learns cheap sufficient bundles, blocks are gated.""" +"""edge-sentinel SOC tenant: tools assemble evidence, bandit learns cheap sufficient bundles, blocks are gated. + +``local_run`` on the tests that expect a tool to run: a registry with no authorizer denies every call, so an +evidence pull or an approved block needs a stated authority — and the test below pins that a tenant built +without one fails at construction rather than serving denials. +""" from __future__ import annotations import inspect @@ -8,6 +13,7 @@ from context_runtime.integrations.edge_sentinel import ( DEFAULT_BUNDLES, SOCTriageTenant, _soc_bandit, reward_triage, soc_bucket, ) +from context_runtime.tools.authz import RegistryConfigurationError def test_soc_bucketing(): @@ -16,7 +22,7 @@ def test_soc_bucketing(): assert soc_bucket("suspicious powershell process persistence") == "behavioral" -def test_triage_pulls_tool_evidence(): +def test_triage_pulls_tool_evidence(local_run): soc = SOCTriageTenant() r = soc.triage("Is 45.155.205.99 a known malicious scanner?") assert r.hits # tools returned evidence @@ -31,20 +37,61 @@ def test_reward_prefers_cheapest_correct_bundle(): assert reward_triage(False, cheap) == 0.0 -def test_block_ip_denied_without_approver(): +def test_soc_registry_classifies_its_tools(local_run): + """The risk class is declared where each tool is registered, and it is the shared vocabulary. + + ``block_ip`` reaches a firewall: it is ``write`` whatever the command looks like. The evidence tools read, + so a deployment can grant a triage-only principal ``read`` and hold the block back. + + ``local_run`` is here because the tenant refuses to be constructed without an authorizer; nothing in this + test depends on what the authorizer decides. + """ + soc = SOCTriageTenant() + classification = soc.registry.classification() + assert classification["block_ip"] == "write" + assert set(classification) == {"block_ip", "crowdsec_decisions", "edr_timeline", "threat_intel"} + assert (classification["threat_intel"] == classification["crowdsec_decisions"] + == classification["edr_timeline"] == "read") + assert set(classification.values()) <= {"read", "write", "delete"} + assert soc.registry.required_capability("block_ip") == { + "resource_kind": "tool", "resource_name": "block_ip", "requested_action": "write"} + assert soc.registry.validate(strict=True).ok + + +def test_soc_tenant_without_an_authorizer_refuses_to_start(monkeypatch): + """No plane, no local declaration ⇒ construction fails. Local trust is never implied by the absence of one.""" + monkeypatch.delenv("CR_LOCAL_AUTHORITY", raising=False) + with pytest.raises(RegistryConfigurationError) as exc: + SOCTriageTenant() + message = str(exc.value) + for door in ("authorizer=", "set_default_authorizer", "CR_LOCAL_AUTHORITY"): + assert door in message # the error names all three ways to answer it + + +def test_soc_tenant_declares_local_execution_out_loud(monkeypatch): + """``local_trust=True`` is only a decision when it comes with a written reason — a bare switch is refused.""" + monkeypatch.delenv("CR_LOCAL_AUTHORITY", raising=False) + with pytest.raises(RegistryConfigurationError): + SOCTriageTenant(local_trust=True) + soc = SOCTriageTenant(local_trust=True, local_trust_reason="single-operator laptop, simulated telemetry") + assert soc.act("185.220.101.4").ok is False # still approval-gated: local trust is not bypass + assert any(a["plane"] == "local_trusted" for a in soc.registry.audit) + + +def test_block_ip_denied_without_approver(local_run): soc = SOCTriageTenant(approver=lambda a: False) res = soc.act("185.220.101.4") assert not res.ok and "denied" in res.error assert soc.registry.audit[-1]["allowed"] is False -def test_block_ip_allowed_with_approver_but_dry_run(): +def test_block_ip_allowed_with_approver_but_dry_run(local_run): soc = SOCTriageTenant(approver=lambda a: True) res = soc.act("185.220.101.4") assert res.ok and "dry-run" in res.text # safe even when approved (CROWDSEC_LIVE unset) -def test_tenant_learns_cheap_sufficient_bundle(): +def test_tenant_learns_cheap_sufficient_bundle(local_run): soc = SOCTriageTenant(bandit=_soc_bandit(0.1)) latent = "threat_intel" q = "Is 45.155.205.99 a known malicious scanner?" # network_anomaly bucket, ti is decisive diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 48e23fa..239fac7 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -110,7 +110,7 @@ def test_mcp_mount_registers_tools_via_real_stdio(): client.close() -def test_mcp_echo_runs_under_bypass_and_returns_text(): +def test_mcp_echo_runs_under_bypass_and_returns_text(local_run): reg, names, client = _run_with_client_and_registry(policy=ApprovalPolicy(mode="bypass")) try: assert "echo" in reg.list() @@ -123,13 +123,16 @@ def test_mcp_echo_runs_under_bypass_and_returns_text(): client.close() -def test_mcp_tools_are_gated_by_approval_policy(): - # default policy (deny_side_effects) blocks side-effecting MCP tool (default_side=True) +def test_mcp_tools_are_gated_by_approval_policy(local_run): + # default policy (deny_side_effects) blocks side-effecting MCP tool (default_side=True). local_run is what + # makes this the approval gate's denial: with no authorizer installed, the call would already have been + # stopped at authorization and this test would prove nothing about the approval policy. reg, names, client = _run_with_client_and_registry() try: res = reg.run("echo", {"text": "hi"}) assert res.ok is False assert "denied" in (res.error or "") + assert "explicit_grant" not in (res.error or "") # stopped by the approval gate, not by authz finally: client.close() @@ -149,7 +152,7 @@ def test_mcp_tools_are_gated_by_approval_policy(): client2.close() -def test_mcp_iserror_maps_to_toolresult_failure(): +def test_mcp_iserror_maps_to_toolresult_failure(local_run): reg, names, client = _run_with_client_and_registry(policy=ApprovalPolicy(mode="bypass")) try: res = reg.run("echo", {"text": "ERR"}) diff --git a/tests/test_outreach.py b/tests/test_outreach.py index 64e2773..2780702 100644 --- a/tests/test_outreach.py +++ b/tests/test_outreach.py @@ -14,7 +14,7 @@ def test_bucketing_by_strongest_signal(): assert outreach_bucket("random company") == "cold" -def test_choose_drafts_opener_and_send_is_approval_gated(): +def test_choose_drafts_opener_and_send_is_approval_gated(local_run): t = OutreachEngineTenant() play = t.choose("their RAG has reranking pain", bucket="tech_pain") assert isinstance(play, OutreachPlay) @@ -28,7 +28,7 @@ def test_choose_drafts_opener_and_send_is_approval_gated(): assert t2.send_sequence("their RAG has reranking pain")["status"] == "sent" -def test_artifact_play_produces_a_teardown_opener(): +def test_artifact_play_produces_a_teardown_opener(local_run): t = OutreachEngineTenant() # force an artifact play and check the opener is the EXPLAIN teardown (the wedge) t.bandit = type(t.bandit)((OutreachPlay("tech_pain", "email", "artifact"),)) @@ -37,7 +37,7 @@ def test_artifact_play_produces_a_teardown_opener(): assert "EXPLAIN" in opener and "/planner" in opener -def test_learns_to_invest_effort_on_high_signal_accounts(): +def test_learns_to_invest_effort_on_high_signal_accounts(local_run): t = OutreachEngineTenant(epsilon=0.1) # teach: artifact converts on tech_pain (value high); template on tech_pain under-converts. def value(play): diff --git a/tests/test_persistence.py b/tests/test_persistence.py index f461695..8db93b7 100644 --- a/tests/test_persistence.py +++ b/tests/test_persistence.py @@ -25,7 +25,7 @@ def test_bandit_state_survives_reload(tmp_path): assert b2.value("ctx", "a")[0] == 20 -def test_module_tenant_persists(tmp_path): +def test_module_tenant_persists(local_run, tmp_path): p = str(tmp_path / "billing.json") t1 = ModuleTenant(CATALOG["billing"], persist_path=p) latent = CATALOG["billing"].sources[0] diff --git a/tests/test_tool_authorizer.py b/tests/test_tool_authorizer.py index d4c2e0c..6d1f471 100644 --- a/tests/test_tool_authorizer.py +++ b/tests/test_tool_authorizer.py @@ -1,38 +1,136 @@ -"""The tool-access authorization seam — an optional authorizer gates every tool call by principal, -before the side-effect approval gate. The enterprise permissions plane plugs in here (open-core).""" +"""The tool-access authorization seam, pinned the way agent-harness C1/C2 define it. + +The contract this file exists to defend is the two directions the old seam got wrong: + +* **no authorizer** used to mean "pass everything through"; it now means "nothing granted this", and the + registration says so at start-up rather than in front of a user; +* **an authorizer returning ``None``** used to mean "allow"; a decision is now required, and the absence of + one is a denial (the old ``Optional[str]`` shapes still work, but arrive tagged ``legacy=True`` so a + reviewer can find the call sites still on the pre-``authz/v1`` contract). + +Each test also reads the risk class the call is asked about, because the resource/action a tenant is checked +against is exactly what the per-tenant classification in ``integrations/`` decides. +""" from __future__ import annotations -from context_runtime.tools.base import ToolRegistry, ToolResult, function_tool, set_default_authorizer +import pytest + +from context_runtime.tools.base import ( + Authorization, PolicyReason, RegistryConfigurationError, ToolClassificationError, ToolRegistry, ToolResult, + function_tool, set_default_authorizer, +) -def _reg(authorizer=None) -> ToolRegistry: +def _reg(authorizer=None, *, action="read") -> ToolRegistry: r = ToolRegistry(authorizer=authorizer) - r.register(function_tool("read_vulns", lambda a: ToolResult(ok=True, text="rows"))) + r.register(function_tool("read_vulns", lambda a: ToolResult(ok=True, text="rows"), action=action)) return r -def test_no_authorizer_is_unchanged_behavior(): - assert _reg().run("read_vulns", {}).ok +# -- no authorizer installed ──────────────────────────────────────────────────────────────────────────── +def test_missing_authorizer_denies_rather_than_passing_through(): + reg = _reg() + res = reg.run("read_vulns", {}) + assert not res.ok # was: ok, the pass-through C1 removed + assert "missing_explicit_grant" in (res.error or "") + denial = reg.audit[-1] + assert denial["allowed"] is False and denial["policy_reason"] == PolicyReason.MISSING_EXPLICIT_GRANT + + +def test_missing_authorizer_is_a_start_up_problem_not_a_runtime_surprise(): + reg = _reg() + report = reg.validate() # a boot check can read this... + assert not report.ok and report.authorizer == "none" + assert any("authorizer" in p for p in report.problems) + with pytest.raises(RegistryConfigurationError): # ...or a constructor can just fail + reg.validate(strict=True) + + +def test_local_trusted_authorizer_runs_and_says_who_authorized_it(local_run): + reg = _reg() # inherits the declared local authority + assert reg.run("read_vulns", {}).ok + allow = reg.audit[-1] # an unattributed allow stays visible + assert allow["allowed"] is True and allow["plane"] == local_run + assert allow["policy_reason"] == PolicyReason.WILDCARD_GRANT + assert reg.unattributed_allows() # a wildcard is reported as one + + +# -- the decision an authorizer gives ─────────────────────────────────────────────────────────────────── def test_authorizer_denies_by_principal(): - # deny 'read_vulns' unless the principal carries the 'security' role def authz(principal, spec, args): roles = (principal or {}).get("roles", set()) - return None if spec.name != "read_vulns" or "security" in roles else "not permitted" + if spec.name == "read_vulns" and "security" not in roles: + return "not permitted" # the legacy shape still denies + return Authorization.allow(grant_ids=("role:security",), plane="permissions") reg = _reg(authz) assert reg.run("read_vulns", {}, principal={"roles": {"security"}}).ok + # An ordinary named grant is not audit noise, so it is not in the trail — but it is attributable: + decision = reg.authorize(reg.get("read_vulns").spec(), {}, principal={"roles": {"security"}}) + assert decision.grant_ids == ("role:security",) and decision.plane == "permissions" denied = reg.run("read_vulns", {}, principal={"roles": {"guest"}}) assert not denied.ok and "not permitted" in denied.error - assert reg.audit[-1]["allowed"] is False # the denial is audited + assert reg.audit[-1]["allowed"] is False # and every denial is audited + + +def test_an_authorizer_that_returns_nothing_denies(): + """The bug this change is about: an authorizer with a missing branch used to allow everything.""" + reg = _reg(lambda principal, spec, args: None) + res = reg.run("read_vulns", {}) + assert not res.ok and "no decision" in (res.error or "") + assert reg.audit[-1]["legacy"] is True # the old shape stays visible, never silent -def test_default_authorizer_governs_all_registries_then_clears(): +def test_a_raising_authorizer_is_a_denial_not_a_crash(): + def down(principal, spec, args): + raise ConnectionError("policy plane unreachable") + + res = _reg(down).run("read_vulns", {}) + assert not res.ok and "policy plane unreachable" in (res.error or "") + + +def test_default_authorizer_governs_all_registries_then_denies_again(): reg = _reg() set_default_authorizer(lambda p, spec, args: "blocked fleet-wide") try: - assert not reg.run("read_vulns", {}).ok # a registry with no authorizer inherits the default + assert not reg.run("read_vulns", {}).ok # a registry with no authorizer inherits the plane finally: set_default_authorizer(None) - assert reg.run("read_vulns", {}).ok + # Clearing the plane is not a return to pass-through: with nothing installed, nothing is granted. + assert not reg.run("read_vulns", {}).ok + + +def test_a_registrys_own_authorizer_wins_over_the_installed_plane(local_run): + """The per-registry door stays the first one: a tenant that names its authority is not overridden by a + process-wide local-trust default.""" + reg = _reg(lambda p, spec, args: "denied by this tenant's own plane") + assert not reg.run("read_vulns", {}).ok + assert "this tenant's own plane" in (reg.run("read_vulns", {}).error or "") + + +# -- the risk class a call is asked about ─────────────────────────────────────────────────────────────── + +def test_the_capability_triple_comes_from_the_registry_that_owns_the_tool(): + assert _reg().required_capability("read_vulns") == { + "resource_kind": "tool", "resource_name": "read_vulns", "requested_action": "read"} + + +def test_an_unclassified_tool_asks_for_nothing_and_therefore_matches_no_grant(): + reg = _reg(action="") + assert reg.required_capability("read_vulns")["requested_action"] == "" + assert reg.unclassified() == ["read_vulns"] + assert any("no risk class" in w for w in reg.validate().warnings) # reported, not swallowed + + +def test_a_read_class_on_a_side_effecting_tool_never_reaches_the_call_path(): + with pytest.raises(ToolClassificationError): + ToolRegistry().register(function_tool("nuke", lambda a: ToolResult(ok=True), + side_effecting=True, action="read")) + + +def test_re_registering_a_tool_cannot_lower_its_risk_class(): + reg = _reg(action="write") + with pytest.raises(ToolClassificationError): + reg.register(function_tool("read_vulns", lambda a: ToolResult(ok=True), action="read")) \ No newline at end of file diff --git a/tests/test_tools.py b/tests/test_tools.py index 61726c7..f727cbb 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -1,4 +1,10 @@ -"""The ToolPlugin seam: specs, the approval gate, the audit log, ToolRetriever.""" +"""The ToolPlugin seam: specs, the approval gate, the audit log, ToolRetriever. + +Two things every test here states out loud, because both are now part of the contract: a tool declares its +risk class with ``action=``, and a registry that is expected to *run* a tool runs under ``local_run`` — with no +authorizer installed the registry denies the call (agent-harness C1), which is the opposite of what it did +before that change. +""" from __future__ import annotations from context_runtime.plugins import base @@ -12,31 +18,34 @@ def _read_tool(): return function_tool("echo_docs", lambda a: ToolResult(ok=True, hits=[ Hit(chunk_id="x", filename="f", text=f"doc for {a.get('query')}", score=1.0)]), - description="returns docs") + description="returns docs", action="read") def _side_effect_tool(): return function_tool("nuke", lambda a: ToolResult(ok=True, text="boom"), - side_effecting=True, approval_required=True) + side_effecting=True, approval_required=True, action="write") -def test_read_tool_runs_and_satisfies_protocol(): +def test_read_tool_runs_and_satisfies_protocol(local_run): reg = ToolRegistry() t = reg.register(_read_tool()) assert isinstance(t, base.ToolPlugin) res = reg.run("echo_docs", {"query": "k8s"}) assert res.ok and res.hits and "k8s" in res.hits[0].text + assert reg.classification() == {"echo_docs": "read"} # the risk class travels with the registration -def test_side_effecting_tool_denied_by_default(): +def test_side_effecting_tool_denied_by_default(local_run): + # local_run so the *approval* gate is what denies: without an authorizer the call never reaches it. reg = ToolRegistry() reg.register(_side_effect_tool()) res = reg.run("nuke", {}) assert not res.ok and "denied" in res.error assert reg.audit[-1]["allowed"] is False # the gate is audited + assert "approval" in reg.audit[-1]["reason"] # ...and it says which gate denied it -def test_side_effecting_tool_allowed_with_approver(): +def test_side_effecting_tool_allowed_with_approver(local_run): reg = ToolRegistry(ApprovalPolicy(mode="deny_side_effects", approver=lambda a: True)) reg.register(_side_effect_tool()) res = reg.run("nuke", {}) @@ -44,7 +53,7 @@ def test_side_effecting_tool_allowed_with_approver(): assert reg.audit[-1]["allowed"] is True -def test_allowlist_mode(): +def test_allowlist_mode(local_run): reg = ToolRegistry(ApprovalPolicy(mode="allowlist", allow=["nuke"])) reg.register(_side_effect_tool()) assert reg.run("nuke", {}).ok @@ -57,7 +66,7 @@ def test_openai_specs(): assert specs[0]["type"] == "function" and specs[0]["function"]["name"] == "echo_docs" -def test_tool_retriever_exposes_tool_as_retrieval_source(): +def test_tool_retriever_exposes_tool_as_retrieval_source(local_run): reg = ToolRegistry() reg.register(_read_tool()) retr = ToolRetriever(reg, source_tool={"api": "echo_docs"}, default_tool="echo_docs") @@ -72,11 +81,11 @@ def test_unknown_tool_is_a_failed_result_not_a_crash(): assert not res.ok and "unknown tool" in res.error -def test_tool_that_raises_becomes_failed_result(): +def test_tool_that_raises_becomes_failed_result(local_run): def boom(args): raise ValueError("kaboom") reg = ToolRegistry() - reg.register(function_tool("boomer", boom, description="raises")) + reg.register(function_tool("boomer", boom, description="raises", action="write")) res = reg.run("boomer", {}) assert res.ok is False and "kaboom" in (res.error or "") # a crash is a failed result, not a runtime crash From e3577771cb03001cc11e3fa8b8674e4625d58e7a Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sat, 21 Nov 2026 22:49:11 -0500 Subject: [PATCH 02/15] mcp/console: every mounted tool carries a class the caller declared MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An MCP server is code pulled from somewhere else, and its readOnlyHint is that code's own announcement about itself. mount_mcp now takes the risk class from the operator — actions={"ffmpeg.convert_video": "read"} — and grades anything left out of the map as write. The hint still moves the approval gate, because "this one does not need confirming" is a claim an operator may choose to believe; it no longer moves the authorization class, which is the decision about whether the call happens at all. Before this, an MCP tool had no class whatsoever, so a deployment could not say "reads yes, mutations no" to a server mounted into a user-facing chat. Three details where the seam could have been quietly wrong. A class outside the vocabulary — the "readonly" typo — is refused at mount time instead of becoming a class no policy on earth can match. A map keyed both by the server's own name and by the mount's prefixed name resolves to the stricter of the two, so spelling cannot decide how much damage is authorised. And a tool classed "read" cannot also declare itself side-effecting: the spec is made consistent with the class, rather than the class quietly raised to match a mount-wide default. The console's @tool decorator takes the same class where the person writing the function can state it, and the console gains validate() — the start-up check that refuses to serve with unclassified tools or no plane — plus explicit local_trust/local_trust_reason like every other tenant. Its denial message now says whether it stopped for want of a grant or for want of a confirmation, because the fix to "I ran the demo and it refused" is different for each, and the two used to read the same. (cherry picked from commit ff1319ec764e5fe735b32f6aded065c518b6a933) --- context_runtime/integrations/agent_console.py | 91 ++++++++-- context_runtime/tools/mcp.py | 58 ++++++- tests/test_mcp_actions.py | 161 ++++++++++++++++++ 3 files changed, 294 insertions(+), 16 deletions(-) create mode 100644 tests/test_mcp_actions.py diff --git a/context_runtime/integrations/agent_console.py b/context_runtime/integrations/agent_console.py index c1cbd8a..8071bf1 100644 --- a/context_runtime/integrations/agent_console.py +++ b/context_runtime/integrations/agent_console.py @@ -27,6 +27,7 @@ import json import math +import logging import re from collections import Counter from dataclasses import dataclass @@ -34,9 +35,13 @@ from ..adapters.model_openai import OpenAICompatibleModel from ..adapters.model_stub import StubModel -from ..tools.base import ApprovalPolicy, ToolRegistry, ToolResult, ToolSpec +from ..tools.authz import RegistryConfigurationError, resolve_authorizer +from ..tools.base import (ACTIONS, ApprovalPolicy, ToolRegistry, ToolResult, ToolSpec, + ValidationReport, default_authorizer_installed) from ..types import ModelRequest +_log = logging.getLogger(__name__) + _WORD = re.compile(r"[a-z0-9]+") @@ -122,14 +127,26 @@ def tool( *, parameters: dict | None = None, side_effecting: bool = False, + action: str = "write", ) -> _Tool: - """Declare an app capability. ``fn`` takes an args dict and returns a dict/str/ToolResult.""" + """Declare an app capability. ``fn`` takes an args dict and returns a dict/str/ToolResult. + + ``action`` is the risk class the console asks for when this tool runs — declared by whoever wrote + ``fn``, because the console cannot see what it does. It defaults to ``write``, the strictest class + every capability must clear; a capability that erases data says so with ``action="delete"``, and a + genuinely read-only one with ``action="read"``. ``side_effecting`` remains the *approval* axis — + the two are separate checks and neither substitutes for the other. + """ + if action not in ACTIONS: + raise RegistryConfigurationError( + f"tool {name!r} declares action={action!r}, which is not one of the vocabulary {ACTIONS}") return _Tool( ToolSpec( name=name, description=description, parameters=parameters or {"type": "object", "properties": {}}, side_effecting=side_effecting, + action=action, ), fn, ) @@ -176,6 +193,8 @@ def __init__( model: Any = None, allow_side_effects: list[str] | None = None, authorizer=None, + local_trust: bool = False, + local_trust_reason: str = "", commands=None, policy=None, app: str = "", @@ -186,10 +205,29 @@ def __init__( self.index = PrimerIndex(self.primer) self.suggestions = list(suggestions) self.model = model if model is not None else (OpenAICompatibleModel.from_env() or StubModel()) - # authorizer (optional, enterprise): gates every tool by the request principal — falls back to - # the process-wide default (set_default_authorizer), so one install() call governs all consoles. - self.registry = ToolRegistry(ApprovalPolicy(mode="allowlist", allow=list(allow_side_effects or [])), - authorizer=authorizer) + # The console is a request-facing surface: an enterprise deployment hands it the request's principal + # as ``authorizer``, otherwise it inherits the process-wide plane installed with + # set_default_authorizer, so one install() governs every console (tools/authz.py). + # + # ``on_missing="deny_later"`` is the one place this module resolves differently from a tenant. A + # tenant owns its registry, so a missing plane is a build-time bug and construction refuses. A console + # is usually built at module import inside an app whose gate installs the plane a moment later or per + # request, and refusing to import an app is a worse failure than the console answering every tool call + # with ``missing_explicit_grant`` — which is what it does, because the registry itself fails closed. + # The console says so once, in the log, and ``validate()`` turns it into a start-up failure for an app + # that wants one. + self._authorizer = resolve_authorizer(authorizer, local_trust=local_trust, + local_trust_reason=local_trust_reason, + context=f"agent console for tenant {tenant!r}", + on_missing="deny_later") + if self._authorizer is None and not default_authorizer_installed(): + _log.warning("agent console %r has no authorization plane: every tool call will be denied with " + "missing_explicit_grant. Pass authorizer=..., install one with " + "context_runtime.tools.set_default_authorizer(...) before building the console, or " + "declare local execution with local_trust=True and a written reason.", tenant) + self.registry = ToolRegistry( + ApprovalPolicy(mode="allowlist", allow=list(allow_side_effects or [])), + authorizer=self._authorizer) # Policy Runtime: /commands are dispatched here (dual-path); `policy` enforces input/output/tool # phases and emits PolicyDecisions. Both optional and fall back to the process default → one # install governs the fleet. app = the policy scope slug (e.g. "market-radar"). @@ -201,23 +239,47 @@ def __init__( self.registry.register(t) self._tools[t.spec().name] = t - def mount_mcp(self, client, *, prefix: str | None = None, allow: list[str] | None = None) -> list[str]: + def mount_mcp(self, client, *, prefix: str | None = None, allow: list[str] | None = None, + actions: dict[str, str] | None = None, + default_action: str = "write") -> list[str]: """Mount an external MCP tool server's tools into this console. Registers each tool in the agent-harness registry AND the classify/dispatch catalog, so - the assistant can pick and run them like any native tool. Read-only MCP tools - (``readOnlyHint``) run ungated; side-effecting ones stay gated unless named in ``allow``. - Returns the mounted tool names. + the assistant can pick and run them like any native tool. + + Risk classes come from ``actions`` — ``{"ffmpeg.convert_video": "read", ...}`` — decided by + whoever mounts the server, after reading what that server does. Every tool outside that map + gets ``default_action``, which is ``write``: a server's own ``readOnlyHint`` still moves the + *approval* gate (an announced read-only tool need not be confirmed) but never the + authorization class, because the thing asking to be run is not allowed to grade its own risk. + + ``allow`` is the approval allowlist and is unchanged. Returns the mounted tool names. """ from ..tools.mcp import mount_mcp as _mount_mcp - names = _mount_mcp(self.registry, client, prefix=prefix) + names = _mount_mcp(self.registry, client, prefix=prefix, actions=actions, + default_action=default_action) for n in names: self._tools[n] = self.registry.get(n) # classify() sees it, respond() dispatches it if allow: self.registry.policy.allow.update(allow) return names + def validate(self, *, strict: bool = True) -> ValidationReport: + """Start-up check: every tool must carry a class the plane can ask about, and there must be a plane. + + An app calls this at boot (``console = AgentConsole(...); console.validate()``) and refuses to serve + when it answers anything. With no plane the console still builds — an app's gate installs one a moment + later, and refusing to import an app is a worse failure than the console denying — but a console that + *serves* without one answers every tool call with ``missing_explicit_grant``, which is a support ticket + rather than a diagnostic. This turns that into a start-up failure. The report's ``problems`` are the + reasons not to serve, its ``warnings`` the reachability facts a reviewer should see (a gated tool the + approval policy can never approve); ``strict=True``, the default, raises + :class:`~context_runtime.tools.base.RegistryConfigurationError` on a problem instead of returning it, + which is what a constructor wants. + """ + return self.registry.validate(strict=strict) + # ---- helpers ------------------------------------------------------------- @property @@ -315,7 +377,12 @@ def _answer_tool(self, name: str, args: dict, principal=None) -> dict: evidence = [{"tool": name, "args": args, "gate": gate.get("reason") or gate.get("decision", ""), "ok": result.ok}] summary = result.text or (json.dumps(result.data)[:800] if result.data is not None else "") if not result.ok: - body = summary or "That action needs confirmation before it can run." + # A denial carries its own reason and must show it: "this needs confirmation" is what a held + # side effect says, and it is the wrong thing to tell someone whose action was denied. + if result.denied: + body = summary or result.error or "That action is not authorized." + else: + body = summary or "That action needs confirmation before it can run." return {"intent": "action", "tool": name, "text": body, "evidence": evidence, "data": result.data, "approved": False} if self._live and summary: system = ( diff --git a/context_runtime/tools/mcp.py b/context_runtime/tools/mcp.py index 9d4f012..6fc77fc 100644 --- a/context_runtime/tools/mcp.py +++ b/context_runtime/tools/mcp.py @@ -16,7 +16,13 @@ import httpx -from .base import ToolPlugin, ToolRegistry, ToolResult, ToolSpec +from .authz import RegistryConfigurationError +from .base import ACTIONS, ToolRegistry, ToolResult, ToolSpec + +# How destructive each class is, used to reconcile a classification map keyed by both a tool's own name +# and the prefixed name it is registered under: the stricter of the two is used. ``ACTIONS`` is already +# ordered by risk (read < write < delete), so its index is the rank. +_STRENGTH: dict[str, int] = {action: rank for rank, action in enumerate(ACTIONS)} _log = logging.getLogger(__name__) @@ -234,13 +240,25 @@ class MCPToolPlugin: _client: MCPClient _name: str _default_side: bool = True + _action: str = "write" + + def __init__(self, tool_desc: dict[str, Any], client: MCPClient, *, name: str | None = None, + default_side_effecting: bool = True, action: str = "write") -> None: + """``action`` is the risk class this tool is asked about — set by whoever mounts the server. - def __init__(self, tool_desc: dict[str, Any], client: MCPClient, *, name: str | None = None, default_side_effecting: bool = True) -> None: + The server's ``readOnlyHint`` is an announcement from the code being run; it moves the + approval gate and nothing else. An MCP tool with no declared class is therefore ``write``. + """ + if action not in ACTIONS: + raise RegistryConfigurationError( + f"MCP tool {(name or tool_desc.get('name'))!r} declares action={action!r}, which is not " + f"one of the vocabulary {ACTIONS}") # support dataclass init + override for manual object.__setattr__(self, "_desc", tool_desc) object.__setattr__(self, "_client", client) object.__setattr__(self, "_name", name or tool_desc.get("name", "unnamed")) object.__setattr__(self, "_default_side", default_side_effecting) + object.__setattr__(self, "_action", action) def spec(self) -> ToolSpec: mcp_name = self._desc.get("name") or self._name @@ -248,12 +266,20 @@ def spec(self) -> ToolSpec: schema = self._desc.get("inputSchema") or self._desc.get("input_schema") or {"type": "object", "properties": {}} ann = self._desc.get("annotations") or {} read_only = bool(ann.get("readOnlyHint")) if "readOnlyHint" in ann else False - side = (not read_only) if "readOnlyHint" in ann else bool(self._default_side) + # ``read`` and ``side_effecting`` cannot both be true: the engine refuses a spec that asks to be + # authorized as the weakest class while declaring that it mutates something. When the operator + # classified this tool ``read``, that classification is the authoritative statement about it — + # truer than a mount-wide ``default_side_effecting`` that was never about this tool in particular. + if self._action == "read": + side = False + else: + side = (not read_only) if "readOnlyHint" in ann else bool(self._default_side) return ToolSpec( name=self._name, description=desc, parameters=schema, side_effecting=side, + action=self._action, ) def run(self, args: dict) -> ToolResult: @@ -288,12 +314,29 @@ def mount_mcp( *, prefix: str | None = None, default_side_effecting: bool = True, + actions: dict[str, str] | None = None, + default_action: str = "write", ) -> list[str]: """Initialize client if needed, list tools, register each wrapped MCPToolPlugin. Registered name = f'{prefix}.{name}' if prefix else name. + + ``actions`` gives a tool its risk class — keyed by the registered name, or by the server's own + name when a prefix is used — and is decided by whoever mounts the server, after reading what + that server does. A tool absent from the map gets ``default_action``, which is ``write``: an + announced ``readOnlyHint`` may relax the *approval* gate, never the authorization class, because + the thing asking to be run is not allowed to grade its own risk. ``actions`` values and + ``default_action`` must come from the shared vocabulary ``ACTIONS``. Returns the list of registered tool names. """ + if default_action not in ACTIONS: + raise RegistryConfigurationError( + f"mount_mcp default_action={default_action!r} is not one of the vocabulary {ACTIONS}") + declared = dict(actions or {}) + misgraded = {key: value for key, value in declared.items() if value not in ACTIONS} + if misgraded: + raise RegistryConfigurationError( + f"mount_mcp actions {sorted(misgraded)} use classes outside the vocabulary {ACTIONS}") try: if not client._initialized: client.initialize() @@ -309,7 +352,14 @@ def mount_mcp( continue raw = tdesc["name"] reg_name = f"{prefix}.{raw}" if prefix else raw - plugin = MCPToolPlugin(tdesc, client, name=reg_name, default_side_effecting=default_side_effecting) + # A map may be keyed by the server's own name or by the prefixed name this mount registers it + # under; when it is keyed by both and they disagree, the stricter class wins. Which name wins is + # otherwise a detail of how the caller spelled the key, and a classification that quietly becomes + # ``read`` because of a spelling is the failure this layer exists to prevent. + candidates = [declared[key] for key in (raw, reg_name) if key in declared] + action = max(candidates, key=_STRENGTH.get, default=default_action) + plugin = MCPToolPlugin(tdesc, client, name=reg_name, default_side_effecting=default_side_effecting, + action=action) registry.register(plugin) registered.append(reg_name) return registered diff --git a/tests/test_mcp_actions.py b/tests/test_mcp_actions.py new file mode 100644 index 0000000..4104eb8 --- /dev/null +++ b/tests/test_mcp_actions.py @@ -0,0 +1,161 @@ +"""MCP tools are mounted with a class the operator declared, never one the server claimed. + +An MCP server is code pulled from somewhere else, and ``readOnlyHint`` is its own announcement about itself. +The registry's rule is that the caller declares what it is about to run: the hint may relax the *approval* +gate — an announced read-only tool need not be confirmed — and it may never relax the authorization class, +which is what decides whether the call happens at all. + +The doubles here return a typed :class:`~context_runtime.tools.base.Authorization`, and that is deliberate: +under ``authz/v1`` an authorizer that returns ``None`` is a *denial*, so the instinctive ``lambda *a: None`` +is not an allow-all double, it is a double that denies everything while looking like one that allows it. +""" +from __future__ import annotations + +import pytest + +from context_runtime.integrations.agent_console import AgentConsole +from context_runtime.tools.authz import RegistryConfigurationError +from context_runtime.tools.base import ApprovalPolicy, Authorization, PolicyReason, ToolRegistry +from context_runtime.tools.mcp import mount_mcp + + +class FakeMCPClient: + """The surface mount_mcp touches: an initialized client that can list and call tools.""" + + def __init__(self, tools): + self._initialized = True + self._tools = tools + self.calls = [] + + def initialize(self): # pragma: no cover - mount_mcp only calls it when uninitialized + self._initialized = True + + def list_tools(self): + return list(self._tools) + + def call_tool(self, name, arguments=None): + self.calls.append((name, arguments)) + return {"content": [{"type": "text", "text": f"{name} ran"}], "isError": False} + + +def _tool(name, **annotations): + desc = {"name": name, "description": f"the {name} tool", + "inputSchema": {"type": "object", "properties": {}}} + if annotations: + desc["annotations"] = annotations + return desc + + +def _grant(principal, spec, args): + """An authorizer that says yes and names the grant standing behind the yes.""" + return Authorization.allow(reason=PolicyReason.EXPLICIT_GRANT, grant_ids=("grant-test",), + plane="test-plane") + + +def _spy(): + """An attributing allow that also records what it was asked about.""" + seen = [] + + def spy(principal, spec, args): + seen.append((spec.name, spec.action, spec.side_effecting)) + return _grant(principal, spec, args) + return spy, seen + + +def _runnable(*names, authorizer): + """A registry whose approval gate has been told these tools may run — so a refusal in these tests can + only have come from the authorization layer, which is the layer under test. The approval list is named + per tool rather than bypassed: bypass would hide a tool that never reached the gate at all.""" + return ToolRegistry(policy=ApprovalPolicy("allowlist", allow=list(names)), authorizer=authorizer) + + +def test_mounted_mcp_tool_defaults_to_write(): + """No class declared means the strictest class every capability must clear — not ``read`` because the + server said it was one, and not a free pass from having no class at all.""" + spy, seen = _spy() + reg = _runnable("convert_video", authorizer=spy) + mount_mcp(reg, FakeMCPClient([_tool("convert_video")])) + assert reg.run("convert_video", {}).ok + assert seen == [("convert_video", "write", True)] + + +def test_read_only_hint_relaxes_approval_but_never_the_class(): + """The hint is an announcement from the code being run: it may stop the call needing confirmation, + and it stops there.""" + spy, seen = _spy() + reg = ToolRegistry(authorizer=spy) + mount_mcp(reg, FakeMCPClient([_tool("search", readOnlyHint=True)])) + assert reg.run("search", {}).ok + assert seen == [("search", "write", False)] # not confirmed, still authorized as a write + + +def test_declared_action_is_the_one_asked_about(): + reg = ToolRegistry(authorizer=_grant) + mount_mcp(reg, FakeMCPClient([_tool("convert_video"), _tool("list_jobs")]), + actions={"convert_video": "read", "list_jobs": "write"}) + assert [reg.get(n).spec().action for n in ("convert_video", "list_jobs")] == ["read", "write"] + # a tool the operator classed read cannot also claim to mutate: the spec is made consistent with the + # class, rather than the class being quietly raised to match a flag + assert reg.get("convert_video").spec().side_effecting is False + + +def test_default_action_is_honoured_for_tools_left_out_of_the_map(): + """Mounting with ``default_action="delete"`` is how an operator says "I have not read this server, + assume the worst"; the grant the plane needs then has to be the one that matches — so the question put + to the plane has to carry ``delete``, not the tool's own opinion of itself.""" + spy, seen = _spy() + reg = _runnable("wipe", authorizer=spy) + mount_mcp(reg, FakeMCPClient([_tool("wipe")]), default_action="delete") + assert reg.run("wipe", {}).ok + assert seen == [("wipe", "delete", True)] + assert reg.get("wipe").spec().action == "delete" + + +def test_both_keyings_are_honoured_and_the_stricter_one_wins(): + """A map may be keyed by the server's own name or by the name the mount registers it under. Spelling + cannot be allowed to decide how much damage is authorised, so disagreement resolves to the stricter.""" + reg = ToolRegistry(authorizer=_grant) + mount_mcp(reg, FakeMCPClient([_tool("convert_video")]), prefix="ffmpeg", + actions={"convert_video": "read", "ffmpeg.convert_video": "write"}) + assert reg.get("ffmpeg.convert_video").spec().action == "write" + + reg2 = ToolRegistry(authorizer=_grant) + mount_mcp(reg2, FakeMCPClient([_tool("convert_video")]), prefix="ffmpeg", + actions={"convert_video": "read"}) + assert reg2.get("ffmpeg.convert_video").spec().action == "read" + + +def test_a_class_outside_the_vocabulary_is_refused_at_mount_time(): + """A typo here ("readonly", "modify") would otherwise become a class nothing in a policy can match.""" + client = FakeMCPClient([_tool("convert_video")]) + with pytest.raises(RegistryConfigurationError, match="outside the vocabulary"): + mount_mcp(ToolRegistry(authorizer=_grant), client, actions={"convert_video": "readonly"}) + with pytest.raises(RegistryConfigurationError, match="default_action"): + mount_mcp(ToolRegistry(authorizer=_grant), client, default_action="dangerous") + + +def test_an_unmounted_server_cannot_be_asked_for(): + """Nothing is registered until the server is mounted, so a tool the process has never seen cannot run — + the mount is the only door through which third-party code becomes callable.""" + spy, seen = _spy() + reg = ToolRegistry(authorizer=spy) + assert reg.list() == [] + assert reg.run("runtime_registered", {}).ok is False + assert seen == [] # the authorizer was not even consulted about a tool that is not there + + +def test_console_mount_appends_to_the_approval_allowlist(local_run): + """How an app's chat entry point mounts a server: declared classes, plus the tools chat may run without + a confirmation step. The two axes stay separate, and the console inherits the installed plane.""" + console = AgentConsole("Billing", "Billing is about invoices.", tools=[]) + console.mount_mcp(FakeMCPClient([_tool("convert_video", readOnlyHint=True)]), + actions={"convert_video": "read"}, allow=["convert_video"]) + assert console.registry.policy.allow == {"convert_video"} + + result = console.registry.run("convert_video", {}) + assert result.ok, result.error + allowed = [a for a in console.registry.audit if a.get("allowed")] + assert allowed and allowed[-1]["plane"] == local_run # who said yes, not just that it ran + # Local trust is a wildcard grant, so it shows up in unattributed_allows() on purpose: whoever reads + # that list is meant to see that no named grant stood behind these calls. + assert [a["tool"] for a in console.registry.unattributed_allows()] == ["convert_video"] \ No newline at end of file From f0ff7f4ae3b0e7840b4444a551d405754652b20c Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sat, 21 Nov 2026 22:52:19 -0500 Subject: [PATCH 03/15] pin agent-harness to the commit with the risk class on the registration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The integrations pass action= to ToolSpec and read registry.classification()/validate(); tools/authz.py hands a registry a plane built from Authorization/PolicyReason. None of that exists at dc84ebf, so anyone installing this branch — the README path, a fresh venv, a deploy — got a harness the package cannot run against, while the local suite stayed green because this venv has agent-harness installed editable from a working tree two commits ahead of the pin. There is no test workflow in this repo (docs-check and secret-scan only), so nothing downstream would have said so either; the pin is the whole install contract. Verified against the pin rather than the checkout: a fresh venv with agent-harness fetched from the pinned commit on GitHub, this package installed --no-deps, plus pyyaml/pytest/httpx, runs the tools, authorizer, MCP, console and tenant suites green — 66 passed, 1 skipped. The floor and why it is there are now written above the pin, so a future bump knows what it must not fall below. (cherry picked from commit 83cd3bc37faf37c35378dd01531d345769db0ff2) --- pyproject.toml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 5e0168f..7850eb3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,9 +7,12 @@ requires-python = ">=3.12" license = { text = "AGPL-3.0-or-later WITH Commons-Clause" } # v0.1 core runs fully offline with the stub plugins. agent-harness (tool contract, approval gate) is # standard-library only, so it adds no transitive dependencies. Pinned to a commit; bump deliberately. +# The floor is the commit that puts the risk class on the registration: the integrations pass action= to +# ToolSpec and call registry.classification()/validate(), and tools/authz.py hands the registry a plane built +# from Authorization/PolicyReason — all of which arrive with the authz line (C1 fail-closed, C2 risk class). dependencies = [ "pyyaml>=6.0", - "agent-harness @ git+https://github.com/redevops-io/agent-harness.git@6b8ba3a596a5e2caf0fdf009f2af013517591662", + "agent-harness @ git+https://github.com/redevops-io/agent-harness.git@7e422f541fc480e4c0cbb8d25789cdae359a9d46", ] [project.optional-dependencies] From 0f2696b79ba168add5af4837c6e76359f3e45f66 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 08:44:14 -0500 Subject: [PATCH 04/15] integrations: every risk-class comment cites a row that exists MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The classes themselves were right; three of the citations behind them were not. That matters more here than in ordinary prose: a comment naming a capability the platform's classification table does not contain is worse than no comment, because the next reader checks the class against a row they cannot find and concludes the table is decorative. * edge_sentinel.block_ip cited apps/edge-sentinel/operator.py:79 and a capability `ban_ip` living there. The blocking capability is `sentinel.block_ip`, registered at operator.py:57, listed write in agentic_os/tool_actions.py — which separately registers the console tool `ban_ip` as write — and in docs/TOOL_CLASSIFICATION_INVENTORY.md. The class stands, the pointer did not. * modules._ACTION_CLASSES justified post / send_campaign / send_sequence with `send_email`, `post_to_channel` and `billing.charge`, none of which the table has. The rows that do exist are social.publish, outreach.send_all, billing.refund and billing.dunning, all write. `close` has no counterpart at all (the platform registers only close_status, a read of whether a period is closed), so it is now classified from what closing a period does — it posts entries — instead of leaning on a borrowed citation. * social_autopilot.draft_caption is read while the platform's social.draft is write, because agentic-os's draft calls an external generator and the shipped function here is a local simulation. The divergence, and the condition that ends it (a caller passing caption_tool_factory that reaches a service), are stated instead of left for the next person to rediscover. Checked class-by-class against agentic_os/tool_actions.py: refund, dunning, escalate (support.escalate), remediate (compliance.remediate), rollback (infra.rollback_release), block_ip (ban_ip / sentinel.block_ip) and fulfill_dsar (privacy.delete = delete) match the platform; control-tower's bi.refresh and market-radar's crm.research / sbom / add_watch comparisons hold. The read-only tenants — fetch_signals, draft_teardown, draft_attribution_report, draft_caption — return text and write nothing, which is what read means there. (cherry picked from commit 2f0248718676ad3097f3f4318f530ea9a39f8a15) --- context_runtime/integrations/edge_sentinel.py | 9 +++++---- context_runtime/integrations/modules.py | 15 +++++++++------ context_runtime/integrations/social_autopilot.py | 8 ++++++-- 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/context_runtime/integrations/edge_sentinel.py b/context_runtime/integrations/edge_sentinel.py index 098e0da..077db10 100644 --- a/context_runtime/integrations/edge_sentinel.py +++ b/context_runtime/integrations/edge_sentinel.py @@ -162,10 +162,11 @@ def spec(self) -> ToolSpec: parameters={"type": "object", "properties": { "ip": {"type": "string"}, "duration": {"type": "string"}}}, side_effecting=True, approval_required=True, - # The platform's own inventory classifies the same capability (`ban_ip`, - # apps/edge-sentinel/operator.py:79) as `write`: it changes live edge policy for a - # third party. The dry-run default is a runtime guard, not a licence to call it a - # read; the grant and the approval are separate checks. + # The platform classifies the same capability — `sentinel.block_ip`, registered at + # agentic-os apps/edge-sentinel/operator.py:57 and listed write in both + # agentic_os/tool_actions.py and docs/TOOL_CLASSIFICATION_INVENTORY.md — because it + # changes live edge policy affecting third parties. The dry-run default is a runtime + # guard, not a licence to call it a read; grant and approval stay separate checks. action="write") def run(self, args: dict) -> ToolResult: diff --git a/context_runtime/integrations/modules.py b/context_runtime/integrations/modules.py index a21aaaf..cdbb60f 100644 --- a/context_runtime/integrations/modules.py +++ b/context_runtime/integrations/modules.py @@ -171,12 +171,15 @@ def run(args: dict) -> ToolResult: # What each declared fleet action accomplishes, read off the platform's own classification table -# (agentic-os docs/TOOL_CLASSIFICATION_INVENTORY.md) wherever the same capability exists there: -# `refund` moves money (billing.charge = write); `dunning`, `post`, `send_campaign` and -# `send_sequence` are outbound communications (send_email, post_to_channel, crm.draft_outreach = -# write); `escalate`, `remediate` (compliance.remediate), `close` (a period close) and `rollback` -# (infra.rollback_release) change state — `write`; `fulfill_dsar` is the capability the platform -# lists as `privacy.delete` = `delete`. Declared per action, never derived from the word "action". +# (agentic_os/tool_actions.py, evidence rows in docs/TOOL_CLASSIFICATION_INVENTORY.md) wherever the +# same capability exists there — and only where it does: `refund` and `dunning` are the platform's +# own `refund` / `billing.refund` / `billing.dunning` = write; `post` is `social.publish` = write; +# `send_campaign` and `send_sequence` are `outreach.send_all` = write; `escalate` is +# `support.escalate` = write; `remediate` is `compliance.remediate` = write; `rollback` is +# `infra.rollback_release` = write; `fulfill_dsar` is `privacy.delete` = delete. `close` has no +# counterpart there (the platform registers only `close_status`, a read of whether a period is +# closed), so it is classified from what closing a period does — it posts entries — as write. +# Declared per action, never derived from the word "action". _ACTION_CLASSES: dict[str, str] = { "refund": "write", "dunning": "write", diff --git a/context_runtime/integrations/social_autopilot.py b/context_runtime/integrations/social_autopilot.py index 1d1ffaf..3de6bba 100644 --- a/context_runtime/integrations/social_autopilot.py +++ b/context_runtime/integrations/social_autopilot.py @@ -141,8 +141,12 @@ def __init__(self, runtime: ContextRuntime | None = None, # else explicitly declared local authority — otherwise construction fails here instead of # denying every call later (see ``context_runtime/tools/authz.py``). Risk classes below # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. - # ``draft_caption`` returns drafted copy to the caller; the schedule/publish call that - # would make it an external communication is a separate consequential path — ``read``. + # ``draft_caption`` returns drafted copy to the caller and the shipped implementation is a + # local simulation, so it reads. Two named divergences from the platform table, both deliberate: + # agentic-os classes ``social.draft`` write because its draft calls an external generator, and + # the publish/schedule call is a separate consequential path (``social.publish`` write). Whoever + # passes ``caption_tool_factory`` that reaches a generation service re-registers this tool as + # write — the class describes the function that is actually installed. self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="social_autopilot")) From b07b02707ca8d64f8ad322a86dcb37098698b0e5 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 08:46:42 -0500 Subject: [PATCH 05/15] tests: the compaction loop test runs its tools under a declared local authority MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This one was being carried as "pre-existing" and it was not. It builds ToolRegistry(ApprovalPolicy("bypass")) with no authorizer, so under authz/v1 every call in the loop is denied; the test then asserts that the model recovered a tool output it had dropped, which cannot happen to a tool that never ran. It fails at the base commit for the same reason — base plus the C1/C2 harness is precisely the mismatch this branch exists to close — which is why "it also fails at base" was never evidence that it was unrelated to this change. Both loop tests now take local_run. The context-error test asserted only that the archive was non-empty, and a denial message would have filled an archive just as well, so it now checks that a stored entry really is the tool's five thousand x's. The assertion that passes for the wrong reason is the one a migration leaves behind. (cherry picked from commit 5bf05d3f3cf86187d890ab8afe97392f7a094252) --- tests/test_transcript_compaction.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/test_transcript_compaction.py b/tests/test_transcript_compaction.py index 2f62a61..95b3d36 100644 --- a/tests/test_transcript_compaction.py +++ b/tests/test_transcript_compaction.py @@ -2,6 +2,7 @@ from __future__ import annotations import json +from pathlib import Path import pytest @@ -119,7 +120,12 @@ def complete(self, messages, tools=None): return {"message": r, "finish_reason": "stop", "usage": {"prompt_tokens": self.prompt_tokens, "completion_tokens": 5}} -def test_inside_the_real_agent_loop_the_model_can_recover_compacted_output(): +def test_inside_the_real_agent_loop_the_model_can_recover_compacted_output(local_run): + # ``local_run`` is load-bearing, not boilerplate: this loop asserts that the model recovered a tool + # result it had dropped, which requires the tool to have RUN. Under authz/v1 a bare registry has no + # plane and denies every call, so without a declared local authority the compaction assertions below + # would be comparing stubs against denials. ``ApprovalPolicy("bypass")`` is the other gate (approval) + # and never authorized anything. reg = ToolRegistry(ApprovalPolicy("bypass")) reg.register(function_tool("dump", lambda a: ToolResult(text=f"BIG{a['n']} " + "filler " * 700 + f" SECRET{a['n']}"), parameters={"type": "object", "properties": {"n": {"type": "integer"}}, "required": ["n"]})) @@ -137,7 +143,7 @@ def test_inside_the_real_agent_loop_the_model_can_recover_compacted_output(): assert any("SECRET1" in m["content"] and not STUB.match(m["content"]) for m in last_msgs if m["role"] == "tool") # and recovered -def test_server_context_error_is_handled_by_the_manager_in_the_loop(): +def test_server_context_error_is_handled_by_the_manager_in_the_loop(local_run): reg = ToolRegistry(ApprovalPolicy("bypass")) reg.register(function_tool("dump", lambda a: ToolResult(text="x" * 5000), parameters={"type": "object", "properties": {}})) mgr = ContextRuntimeManager() @@ -146,6 +152,9 @@ def test_server_context_error_is_handled_by_the_manager_in_the_loop(): client = Scripted(replies, prompt_tokens=10) res = run_loop(client, reg, "s", "t", max_context_tokens=10**9, context_manager=mgr) assert res.stop == "done" and mgr.archive.entries + # ...and what reached the archive is the tool's output, not a denial message wearing its place: the + # assertion above passes either way, which is exactly how a migrated test quietly stops testing anything. + assert any(Path(e.path).read_text(encoding="utf-8").startswith("xxxx") for e in mgr.archive.entries.values()) def test_oversized_tool_output_is_archived_whole_at_admission_so_the_middle_is_recoverable(): From bac6f726e01a3c924a85625918e1eb7610048c90 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 10:05:59 -0500 Subject: [PATCH 06/15] integrations, control_plane: carry the migration onto the code main added MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaying C3 onto current main surfaced two things this branch had never seen, because its old base predated both. Neither is a merge artifact to paper over: each is a registry or a tool the fail-closed plane now has to answer for. **The 13th registry.** `revenue_intelligence.py` builds one per tenant, plus tools in `hubspot_crm.py` and `salesforce_crm.py`. It now resolves its authorizer the way the other twelve do, and every tool in that path declares its class: provider enrichment `read` (the platform's comparable row is `outreach.enrich` = read; the money these calls cost is metered separately in `external_spend`/`PROVIDER_COST`, and spending money is not the same axis as changing state — `ProviderTool.live` is a flag the class never acts on), `outreach_prepare` `read` (a draft returned to the caller; the platform splits the pair the same way, `outreach.draft_pitch` read vs `outreach.send_all` write), `outreach_send` `write`, `crm_enrich` `read` (a query against a platform service, network or not), `crm_update` `write` (a PATCH on a record in the customer's system of record). The GTM fleet action `outreach_send` joins `_ACTION_CLASSES`, whose raise-on-missing-class is the point of the table. **The fleet could not boot.** `Fleet.up()` builds a tenant per module at control-plane import, so with tenants that now refuse to start, the control-plane container stopped answering `/health` — the container test caught it. The fleet follows `AgentConsole`'s rule (`on_missing="deny_later"`), because the embedding application installs its gate a moment after this import and a process that boots and denies is diagnosable where one that refuses to start is not. It is not a grant: every tool call stays denied with `missing_authorizer`, and `/status` looks identical either way — so the fleet says so once, in a warning naming both ways out (`set_default_authorizer(...)`, or `CR_LOCAL_AUTHORITY="why this process is trusted"`). No image bakes the switch in; that choice stays with whoever deploys, which is why `CR_LOCAL_AUTHORITY` demands a sentence. **And one action nobody had read.** The failure was `the fleet action sidekick.coder has no recorded risk class`: `spec_for()` builds specs from a module the registry discovered at run time, so those action names come from data, not from this file — a curated table cannot contain them, and refusing to boot over one of them gives an operator no way to run a custom module. So the two cases split. A `CATALOG` action with no class is still a start-up error, because this repository wrote that name. A discovered action registers **unclassified** — matched by no grant, therefore denied — with one warning naming it. Guessing `read` for an action nobody read is the exact failure this migration exists to remove; leaving it unknown and denied is what the platform's own rule prescribes. --- CHANGELOG.md | 6 +++ context_runtime/control_plane/fleet.py | 38 +++++++++++++++- context_runtime/integrations/hubspot_crm.py | 11 ++++- context_runtime/integrations/modules.py | 30 ++++++++++--- .../integrations/revenue_intelligence.py | 44 ++++++++++++++++--- .../integrations/salesforce_crm.py | 9 +++- 6 files changed, 120 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a668eb..eaebb3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- **Breaking change (tool authorization): a Context Runtime tenant no longer starts without an authorization plane.** Every integration tenant and the module fleet resolves an authorizer at construction (`context_runtime/tools/authz.py`): an explicit `authorizer=`, else a plane installed process-wide with `context_runtime.tools.set_default_authorizer(...)` (what `agentic_os.app_gate.install_gate` does), else an explicitly declared local authority — `local_trust=True` with a written `local_trust_reason`, or `CR_LOCAL_AUTHORITY=""`. None of the three raises `RegistryConfigurationError` at construction instead of denying every call later; `CR_LOCAL_AUTHORITY=1` is refused, because a value that carries no reason is how an allow-all switch reaches a production manifest. This follows agent-harness #33 (a registry with no authorizer denies everything) and #34 (a tool with no declared risk class is permitted by no grant). +- **Behaviour change (risk classes are declared, never inferred).** `mount_mcp(..., actions={...}, default_action="write")` and `AgentConsole.tool(..., action=...)` take the class from the integrator; `readOnlyHint`/`title` pass through as annotations and relax the **approval** gate only. An MCP server is not allowed to grade its own risk. `AgentConsole.validate()` is the start-up check that refuses to serve a console with no plane. +- **Behaviour change (the module fleet):** standing a module up with no plane no longer kills the process — `Fleet.up()` follows `AgentConsole`'s rule (`on_missing="deny_later"`), because the embedding application installs its gate a moment after import and a container that never answers `/health` is worse than one that denies. It warns once, and every tool call stays denied (`missing_authorizer`) until a plane exists. **`/status` looks identical either way** — that is what the warning is for. +- **Behaviour change (fleet actions of discovered modules):** a `CATALOG` action without a recorded class is still a start-up error, because this file wrote those names. An action inferred from a module the registry discovered at run time (e.g. `sidekick.coder`) is now registered **unclassified** — matched by no grant, so denied — with one warning naming it. Before this it was impossible to run a custom module at all, and guessing `read` for an unread action is the failure this migration removes. +- **Pin:** `agent-harness` `6b8ba3a` → `7e422f541f` (fail-closed authorizer decisions + `ToolSpec.action`). `Dockerfile`, `deploy/geo-demo/Dockerfile.aks` and `deploy/proxmox-demo/Dockerfile.contextruntime` move with it; `tests/test_container.py` / `tests/test_geo_image.py` fail if they drift apart. + - **Fix (Windows):** `JsonlExporter` appends each trace through `locked_append` (inter-process and in-process lock, one write, explicit newline, no per-trace `fsync`). A bare `open(path, "a")` loses lines when writers overlap on Windows, where the C runtime appends as seek-then-write. `locked_append` gains `durable=False`. The exporter waits at most 1 s for the lock; if it cannot get it the trace is dropped and one warning is logged per exporter. A test fails on any new lock-free append writer in the repository's Python code. **Visible differences:** a `.jsonl.lock` sidecar file (0600) is created next to the trace file; in a read-only directory, or one holding a sidecar owned by another user, `export` now raises `PermissionError` where the bare append worked (the runtime and `MultiExporter` swallow exporter errors, so the trace is lost; one warning is logged); on Windows each line now ends in LF, where text-mode append wrote CRLF, so a trace file written by an older version and then appended to can mix the two (`splitlines()` and `json.loads` accept both). Native Windows and macOS portability of the core library. Details and the verification status of each item: [docs/native-portability.md](docs/native-portability.md). diff --git a/context_runtime/control_plane/fleet.py b/context_runtime/control_plane/fleet.py index 4557562..e3b621d 100644 --- a/context_runtime/control_plane/fleet.py +++ b/context_runtime/control_plane/fleet.py @@ -11,6 +11,7 @@ from __future__ import annotations import threading +import warnings from dataclasses import dataclass from pathlib import Path @@ -19,6 +20,8 @@ from ..integrations.modules import CATALOG, ModuleSpec, ModuleTenant from ..platform_services import ensure_private_dir, state_dir from ..runtime.runtime import ContextRuntime +from ..tools.authz import local_authority_from_env +from ..tools.base import default_authorizer_installed from .context import Approval, Context from .registry import Module, Registry @@ -32,6 +35,33 @@ } +#: the "no plane" fact is a start-up fact: it is said once per process, not once per module up/down. +_PLANE_WARNING_SHOWN = False + + +def _warn_if_no_plane() -> None: + """Say once, at the moment it is cheap to act on, that this fleet stands up with no authorization plane. + + The fleet is a long-lived, request-facing surface, so it follows the same rule as ``AgentConsole`` rather + than the tenants' own: standing a module up with no plane yet installed is a start-up the operator can + still fix — an embedding application installs its gate a moment after this import — whereas refusing to + import is a container that never answers ``/health``. It is not a grant: with no plane every tool call + comes back ``missing_authorizer``. Silence is the failure mode this migration exists to remove, because a + fleet that denies every tool call looks exactly like a healthy one on ``/status``. + """ + global _PLANE_WARNING_SHOWN + if _PLANE_WARNING_SHOWN or default_authorizer_installed() or local_authority_from_env()[0]: + return + _PLANE_WARNING_SHOWN = True + warnings.warn( + "the module fleet is standing up with no authorization plane: every tool call its tenants make is " + "denied (missing_authorizer) until the embedding application installs one with " + "context_runtime.tools.set_default_authorizer(...), or the process declares local authority with " + 'CR_LOCAL_AUTHORITY="why this process is trusted". The fleet still serves /health and /status on ' + "purpose: a process that boots and denies is diagnosable, one that refuses to start is not.", + stacklevel=3) + + def spec_for(m: Module) -> ModuleSpec: """A CATALOG tenant spec if we have one; otherwise a generic spec from the registry.""" key = _ALIAS.get(m.name) @@ -39,10 +69,14 @@ def spec_for(m: Module) -> ModuleSpec: return CATALOG[key] if m.name in CATALOG: return CATALOG[m.name] + # Not a CATALOG row: the action names come from a module the registry discovered at run time, so + # this file cannot vouch for what they do. They are registered unclassified (denied) rather than + # assumed safe — see integrations/modules.py::_action_tool. return ModuleSpec( name=m.name.replace("-", "_"), core="", pain=m.pain, sources=("primary", "secondary", "context"), metric="task_success", actions=tuple(a.replace("-", "_") for a in m.approval_required) or tuple(m.agents[:1]), + curated_actions=False, ) @@ -76,13 +110,15 @@ def _names(self) -> list[str]: # --- lifecycle --- def up(self, *names: str) -> list[ModuleStatus]: out = [] + _warn_if_no_plane() for n in (names or self._names()): m = self.registry.get(n) # the fleet gates approvals (via Context); the tenant's own tools default-deny. # each tenant's learned policy persists to the /data volume → survives restarts. self.tenants[n] = ModuleTenant( spec_for(m), runtime=self.runtime, approver=lambda a: False, - persist_path=str(self.home / "bandits" / f"{n}.json")) + persist_path=str(self.home / "bandits" / f"{n}.json"), + authorizer_on_missing="deny_later") self._up.add(n) out.append(ModuleStatus(n, True, m.agents, "context-runtime tenant")) return out diff --git a/context_runtime/integrations/hubspot_crm.py b/context_runtime/integrations/hubspot_crm.py index 0f2b74f..02a07c1 100644 --- a/context_runtime/integrations/hubspot_crm.py +++ b/context_runtime/integrations/hubspot_crm.py @@ -107,7 +107,12 @@ def __init__(self, fixtures: dict | None = None, client: HubSpotCRM | None = Non def spec(self) -> ToolSpec: return ToolSpec(name="crm_enrich", description="Resolve an account against HubSpot CRM (read-only).", parameters={"type": "object", "properties": { - "account_id": {"type": "string"}, "need": {"type": "string"}}}) + "account_id": {"type": "string"}, "need": {"type": "string"}}}, + # A search plus a read of one company — a query against a platform service, which is + # the doctrine's test for ``read`` (the platform's own ``outreach.enrich`` row agrees). + # It is genuinely a network call when a token is present; being remote is not the same + # as changing anything. + action="read") def run(self, args: dict) -> ToolResult: fx = self._fx.get(args.get("account_id", "")) @@ -138,7 +143,9 @@ def spec(self) -> ToolSpec: return ToolSpec(name="crm_update", description="Update a HubSpot company property.", parameters={"type": "object", "properties": { "company_id": {"type": "string"}, "properties": {"type": "object"}}}, - side_effecting=True, approval_required=True) + side_effecting=True, approval_required=True, + # PATCHes a record in the customer's CRM: state change in a system of record. + action="write") def run(self, args: dict) -> ToolResult: try: diff --git a/context_runtime/integrations/modules.py b/context_runtime/integrations/modules.py index cdbb60f..2430075 100644 --- a/context_runtime/integrations/modules.py +++ b/context_runtime/integrations/modules.py @@ -17,6 +17,7 @@ from __future__ import annotations import hashlib +import warnings from dataclasses import dataclass, field from itertools import combinations @@ -37,6 +38,8 @@ class ModuleSpec: sources: tuple[str, ...] # available context sources (become source tools) metric: str # the reward signal (its own success measure) actions: tuple[str, ...] = () # side-effecting, approval-gated actions + # True for a row of CATALOG below: this repository wrote those action names, so each one owes an + curated_actions: bool = True # Every agentic-os-stack module (migrated) + net-new tenants from Use-cases.odt (new). @@ -179,6 +182,9 @@ def run(args: dict) -> ToolResult: # `infra.rollback_release` = write; `fulfill_dsar` is `privacy.delete` = delete. `close` has no # counterpart there (the platform registers only `close_status`, a read of whether a period is # closed), so it is classified from what closing a period does — it posts entries — as write. +# `outreach_send` is the GTM module's own action; the platform's comparable row is again +# `outreach.send_all` = write, and the tool behind it (`SendOutreachTool` in revenue_intelligence.py) +# is registered side-effecting and approval-gated, so the two axes agree here rather than disagreeing. # Declared per action, never derived from the word "action". _ACTION_CLASSES: dict[str, str] = { "refund": "write", @@ -191,21 +197,31 @@ def run(args: dict) -> ToolResult: "send_sequence": "write", "block_ip": "write", "rollback": "write", + "outreach_send": "write", "fulfill_dsar": "delete", } -def _action_tool(module: str, action: str): +def _action_tool(module: str, action: str, *, curated: bool = True): def run(args: dict) -> ToolResult: return ToolResult(ok=True, data={"action": action, "applied": False}, text=f"[dry-run] {module}.{action}({args})") action_class = _ACTION_CLASSES.get(action) - if action_class is None: + if action_class is None and curated: raise RegistryConfigurationError( f"the fleet action {module}.{action} has no recorded risk class — add it to _ACTION_CLASSES " f"in modules.py with the evidence for what it actually does, instead of defaulting it") + if action_class is None: + # A module the registry discovered at run time, not a row this file wrote. Nobody has read what + # this action does, and "nobody read it" is not a licence to guess read: an unclassified tool is + # matched by no grant, so it is denied at the call — the same outcome the platform prescribes for + # an unknown effect, without taking the whole fleet down with one unreviewed module. + warnings.warn( + f"the fleet action {module}.{action} has no recorded risk class: it is registered " + f"unclassified, so no grant matches it and every call is denied until someone reads the " + f"implementation and records what it does in _ACTION_CLASSES (modules.py).", stacklevel=3) return function_tool(f"{module}_{action}", run, description=f"{module} action: {action}", - side_effecting=True, approval_required=True, action=action_class) + side_effecting=True, approval_required=True, action=action_class or "") class ModuleTenant: @@ -214,7 +230,8 @@ class ModuleTenant: def __init__(self, spec: ModuleSpec, runtime: ContextRuntime | None = None, bandit: EpsilonGreedyBandit | None = None, approver=None, epsilon: float = 0.12, persist_path: str | None = None, - authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): + authorizer=None, local_trust: bool = False, local_trust_reason: str = "", + authorizer_on_missing: str = "raise"): self.spec = spec self.runtime = runtime or ContextRuntime.default([]) self.arms = _bundles(spec.sources) @@ -226,11 +243,12 @@ def __init__(self, spec: ModuleSpec, runtime: ContextRuntime | None = None, authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, - context=f"module fleet tenant {spec.name!r}")) + context=f"module fleet tenant {spec.name!r}", + on_missing=authorizer_on_missing)) for s in spec.sources: self.registry.register(_source_tool(spec.name, s)) for a in spec.actions: - self.registry.register(_action_tool(spec.name, a)) + self.registry.register(_action_tool(spec.name, a, curated=spec.curated_actions)) self._pending: dict[str, tuple[Plan, SourceBundle, str]] = {} def handle(self, question: str) -> ModuleResult: diff --git a/context_runtime/integrations/revenue_intelligence.py b/context_runtime/integrations/revenue_intelligence.py index 0f4533f..4235cf4 100644 --- a/context_runtime/integrations/revenue_intelligence.py +++ b/context_runtime/integrations/revenue_intelligence.py @@ -22,6 +22,7 @@ from dataclasses import dataclass, field from ..runtime.runtime import ContextRuntime +from ..tools.authz import resolve_authorizer from ..tools.base import ApprovalPolicy, ToolRegistry, ToolResult, ToolSpec from ..types import Goal, Hit, Plan, Trace from .bandit import EpsilonGreedyBandit @@ -107,7 +108,14 @@ def spec(self) -> ToolSpec: return ToolSpec(name=f"{self.name}_enrich", description=f"Enrich an account via {self.name}.", parameters={"type": "object", "properties": { - "account_id": {"type": "string"}, "need": {"type": "string"}}}) + "account_id": {"type": "string"}, "need": {"type": "string"}}}, + # A lookup that returns data and mutates nothing — the platform's comparable row is + # ``outreach.enrich`` = read (agentic_os/tool_actions.py). The spend this capability + # causes is measured separately (``external_spend``/PROVIDER_COST) and spending money + # is not the same axis as changing state: ``self.live`` is a flag this class never + # acts on. Whoever wires a real provider call into the registration re-classifies it + # with the call, exactly as the crm slot below is filled by a different class. + action="read") def run(self, args: dict) -> ToolResult: fx = self._fx.get(args.get("account_id", "")) @@ -130,7 +138,11 @@ class PrepareOutreachTool: def spec(self) -> ToolSpec: return ToolSpec(name="outreach_prepare", description="Draft (not send) an outreach sequence.", - parameters={"type": "object", "properties": {"account_id": {"type": "string"}}}) + parameters={"type": "object", "properties": {"account_id": {"type": "string"}}}, + # Returns a draft to the caller; nothing is stored and no message is sent. The + # platform splits this pair the same way: ``outreach.draft_pitch``/``draft_followup`` + # read, ``outreach.send_all`` writes. + action="read") def run(self, args: dict) -> ToolResult: return ToolResult(ok=True, hits=[], data={"drafted": True, "account_id": args.get("account_id")}, @@ -143,7 +155,12 @@ class SendOutreachTool: def spec(self) -> ToolSpec: return ToolSpec(name="outreach_send", description="Send an outreach message.", parameters={"type": "object", "properties": {"account_id": {"type": "string"}}}, - side_effecting=True, approval_required=True) + side_effecting=True, approval_required=True, + # Mail leaves the building: ``outreach.send_all`` = write on the platform. The + # NO_OUTREACH switch and the approval gate are separate checks from this grant — + # the reason all three are here is that any one of them passing says nothing about + # the other two. + action="write") def run(self, args: dict) -> ToolResult: return ToolResult(ok=True, data={"sent": True, "account_id": args.get("account_id")}, @@ -232,7 +249,14 @@ class RevenueIntelligenceTenant: def __init__(self, fixtures: dict[str, Fixture], *, runtime: ContextRuntime | None = None, registry: ToolRegistry | None = None, bandit: EpsilonGreedyBandit | None = None, - approver=None, no_outreach: bool = True, segmented: bool = False, crm_tool=None): + approver=None, no_outreach: bool = True, segmented: bool = False, crm_tool=None, + authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): + # Who answers for a call in this registry is the deployment's choice, not this tenant's default: + # an explicit ``authorizer``, else a plane installed with set_default_authorizer, else explicitly + # declared local authority — otherwise construction fails here instead of denying every call later + # (see ``context_runtime/tools/authz.py``). Risk classes are read off what each tool does, never off + # its name or its ``side_effecting`` flag. A caller passing ``registry=`` brings its own wiring and + # is responsible for that registry's authorizer; this path only builds the default one. self.fixtures = fixtures self.runtime = runtime or ContextRuntime.default([]) self.bandit = bandit or _gtm_bandit() @@ -242,7 +266,9 @@ def __init__(self, fixtures: dict[str, Fixture], *, runtime: ContextRuntime | No self.segmented = segmented # ``crm_tool`` (e.g. HubSpotCRMTool) makes the ``crm`` provider a LIVE backend; None keeps the offline # fixture. Auto-enabled when a HubSpot Service Key is in the environment. - self.registry = registry or self._default_registry(fixtures, approver, crm_tool) + self.registry = registry or self._default_registry( + fixtures, approver, crm_tool, authorizer=authorizer, local_trust=local_trust, + local_trust_reason=local_trust_reason) self.external_spend = 0.0 self.events: list[dict] = [] # per-enrichment trace, for the population governor (arm G) self._pending: dict[str, tuple[Plan, ProviderBundle, str]] = {} @@ -251,8 +277,12 @@ def _ctx(self, fx: Fixture, bucket: str) -> str: return f"{bucket}|{fx.segment}" if self.segmented else bucket @staticmethod - def _default_registry(fixtures, approver, crm_tool=None) -> ToolRegistry: - reg = ToolRegistry(ApprovalPolicy(mode="deny_side_effects", approver=approver)) + def _default_registry(fixtures, approver, crm_tool=None, *, authorizer=None, + local_trust: bool = False, local_trust_reason: str = "") -> ToolRegistry: + reg = ToolRegistry(ApprovalPolicy(mode="deny_side_effects", approver=approver), + authorizer=resolve_authorizer(authorizer, local_trust=local_trust, + local_trust_reason=local_trust_reason, + context="revenue_intelligence")) # Live CRM is explicit opt-in (CR_CRM_LIVE=1 + a backend's credentials), so credentials sitting in # the environment never silently make the reproducible offline benchmark hit the network. Pick the # backend with CR_CRM_BACKEND=hubspot|salesforce, else auto-detect from which creds are present. diff --git a/context_runtime/integrations/salesforce_crm.py b/context_runtime/integrations/salesforce_crm.py index 3cc8c13..acd357b 100644 --- a/context_runtime/integrations/salesforce_crm.py +++ b/context_runtime/integrations/salesforce_crm.py @@ -137,7 +137,10 @@ def __init__(self, fixtures: dict | None = None, client: SalesforceCRM | None = def spec(self) -> ToolSpec: return ToolSpec(name="crm_enrich", description="Resolve an account against Salesforce (read-only).", parameters={"type": "object", "properties": { - "account_id": {"type": "string"}, "need": {"type": "string"}}}) + "account_id": {"type": "string"}, "need": {"type": "string"}}}, + # A SOQL query and a fetch of one Account — a read against a platform service, the same + # reading as ``outreach.enrich`` on the platform. Remote is not the same as mutating. + action="read") def run(self, args: dict) -> ToolResult: fx = self._fx.get(args.get("account_id", "")) @@ -167,7 +170,9 @@ def spec(self) -> ToolSpec: return ToolSpec(name="crm_update", description="Update a Salesforce Account field.", parameters={"type": "object", "properties": { "account_id": {"type": "string"}, "fields": {"type": "object"}}}, - side_effecting=True, approval_required=True) + side_effecting=True, approval_required=True, + # Writes a field on a record in the customer's CRM. + action="write") def run(self, args: dict) -> ToolResult: try: From c58c412616e13408be0fa42fa75b288972405997 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 10:06:20 -0500 Subject: [PATCH 07/15] build: the image pins move with the dependency pin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pin bump moved `pyproject.toml` only. Three images install agent-harness themselves — from the commit's source archive, with the archive's sha256 pinned, because the image has no git in it — and two tests compare them: `tests/test_container.py::test_dockerfile_pins_the_same_agent_harness_commit_as_pyproject` and `tests/test_geo_image.py::test_agent_harness_pin_equals_the_repository_dockerfile_and_pyproject`. Both were red on the replayed branch until now. `Dockerfile`, `deploy/geo-demo/Dockerfile.aks` and `deploy/proxmox-demo/Dockerfile.contextruntime` move to `7e422f541fc480e4c0cbb8d25789cdae359a9d46`. The digest `231eef6b8877127bf61834e271707cab6c28411e6a7b6236210a44a6704612a8` is the sha256 of `https://github.com/redevops-io/agent-harness/archive/.tar.gz`; the method is reproducible, which is the only way to know a digest was computed rather than guessed: re-hashing the commit this replaces (`6b8ba3a`) returns exactly the `d67eadb33c16…` those files carried before. `test_image_builds_starts_and_fails_closed` passes against the rebuilt image, which is the check that matters here — it is the one that runs the control plane for real, so it is where the fleet's start-up behaviour met an actual container rather than a test fixture. --- Dockerfile | 4 ++-- deploy/geo-demo/Dockerfile.aks | 4 ++-- deploy/proxmox-demo/Dockerfile.contextruntime | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index 23f29b1..26071d4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,8 +14,8 @@ RUN pip install --no-cache-dir "fastapi>=0.110" "uvicorn>=0.29" "httpx>=0.27" "p # application does not import without it. Pinned to the same commit as pyproject.toml, from the commit's # source archive (no git in this image) and verified against the archive's sha256. # tests/test_container.py checks that this commit equals the one in pyproject.toml. -ARG AGENT_HARNESS_COMMIT=6b8ba3a596a5e2caf0fdf009f2af013517591662 -ARG AGENT_HARNESS_SHA256=d67eadb33c161df00b70bad4f20c80f43d2f477031dce3259ee5d465c8844a47 +ARG AGENT_HARNESS_COMMIT=7e422f541fc480e4c0cbb8d25789cdae359a9d46 +ARG AGENT_HARNESS_SHA256=231eef6b8877127bf61834e271707cab6c28411e6a7b6236210a44a6704612a8 RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}" ENV PYTHONPATH=/app diff --git a/deploy/geo-demo/Dockerfile.aks b/deploy/geo-demo/Dockerfile.aks index f64507b..e9be383 100644 --- a/deploy/geo-demo/Dockerfile.aks +++ b/deploy/geo-demo/Dockerfile.aks @@ -27,8 +27,8 @@ RUN pip install --no-cache-dir -r /tmp/requirements.txt # context_runtime imports agent-harness (its tool contract) at import time, so the application does not start without it. # Pinned to the same commit as the repository's own Dockerfile and pyproject.toml, from the commit's source archive (no git in # this image) and verified against the archive's sha256. tests/test_geo_image.py keeps these two lines equal to the root Dockerfile. -ARG AGENT_HARNESS_COMMIT=6b8ba3a596a5e2caf0fdf009f2af013517591662 -ARG AGENT_HARNESS_SHA256=d67eadb33c161df00b70bad4f20c80f43d2f477031dce3259ee5d465c8844a47 +ARG AGENT_HARNESS_COMMIT=7e422f541fc480e4c0cbb8d25789cdae359a9d46 +ARG AGENT_HARNESS_SHA256=231eef6b8877127bf61834e271707cab6c28411e6a7b6236210a44a6704612a8 RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}" FROM ${PYTHON_IMAGE} diff --git a/deploy/proxmox-demo/Dockerfile.contextruntime b/deploy/proxmox-demo/Dockerfile.contextruntime index 5e40961..8c2ebd5 100644 --- a/deploy/proxmox-demo/Dockerfile.contextruntime +++ b/deploy/proxmox-demo/Dockerfile.contextruntime @@ -8,8 +8,8 @@ RUN pip install --no-cache-dir \ # agent-harness is a base dependency of context_runtime (the application does not import without it); same # commit and archive hash as the top-level Dockerfile and pyproject.toml. -ARG AGENT_HARNESS_COMMIT=6b8ba3a596a5e2caf0fdf009f2af013517591662 -ARG AGENT_HARNESS_SHA256=d67eadb33c161df00b70bad4f20c80f43d2f477031dce3259ee5d465c8844a47 +ARG AGENT_HARNESS_COMMIT=7e422f541fc480e4c0cbb8d25789cdae359a9d46 +ARG AGENT_HARNESS_SHA256=231eef6b8877127bf61834e271707cab6c28411e6a7b6236210a44a6704612a8 RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}" COPY context_runtime /app/context_runtime From c4051cfc38020e7deeca3f2dfe5dfae505c2e163 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 10:06:20 -0500 Subject: [PATCH 08/15] tests: the tenants and MCP mounts main added declare their plane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nine tests main added run tools through a tenant or a mounted MCP server, and under authz/v1 a registry with no plane denies everything. They take `local_run` — the declared local authority, attributed as `pytest_local` in the decision trail — rather than an unnamed allow-all lambda per registry. `test_revenue_intelligence.py` (four) and `test_hubspot_crm.py` (one) construct `RevenueIntelligenceTenant`, which now refuses to build without an answer to "who authorizes this"; `test_runtime_scan.py` (four) drives `scan.scan_start` through the mounted deploy-scan MCP server and was failing with `missing_explicit_grant` on the very first call, so its four MCP tests never reached the scope and approval assertions they exist to check. None of these is a relaxed assertion: every assertion that was there still runs. What changed is that the run now has an authorizer to deny it, which is the difference between a failing test and a test that was never asking anything. --- tests/test_hubspot_crm.py | 2 +- tests/test_revenue_intelligence.py | 8 ++++---- tests/test_runtime_scan.py | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/test_hubspot_crm.py b/tests/test_hubspot_crm.py index 0e2af64..3c68847 100644 --- a/tests/test_hubspot_crm.py +++ b/tests/test_hubspot_crm.py @@ -77,7 +77,7 @@ def fake_urlopen(req, timeout=20.0): assert seen["url"].startswith("https://api.hubapi.com/crm/v3/objects/companies/search") -def test_tenant_falls_back_to_fixture_without_key(monkeypatch): +def test_tenant_falls_back_to_fixture_without_key(monkeypatch, local_run): monkeypatch.delenv("HUBSPOT_SERVICE_KEY", raising=False) monkeypatch.delenv("HUBSPOT_API_KEY", raising=False) fx = {"a1": Fixture("a1", "Acme", "acme.io", "company_identity", "pdl", "Acme Inc")} diff --git a/tests/test_revenue_intelligence.py b/tests/test_revenue_intelligence.py index 05e3975..0b56f14 100644 --- a/tests/test_revenue_intelligence.py +++ b/tests/test_revenue_intelligence.py @@ -79,7 +79,7 @@ def test_decisive_present_beats_the_wrong_trap(): assert outcome_for(ProviderBundle(("apollo", "pdl")), fx) == "correct" -def test_runs_offline_and_denies_outreach(): +def test_runs_offline_and_denies_outreach(local_run): t = RevenueIntelligenceTenant(_fixtures(), approver=lambda spec: False, no_outreach=True) r = t.enrich("c2") assert r.outcome in ("correct", "wrong", "missing") @@ -89,7 +89,7 @@ def test_runs_offline_and_denies_outreach(): assert t.registry.audit[-1]["allowed"] is False -def test_learns_decisive_provider_per_need(): +def test_learns_decisive_provider_per_need(local_run): t = RevenueIntelligenceTenant(_fixtures(), bandit=_gtm_bandit(0.1), approver=lambda spec: False) ids = list(_fixtures()) for i in range(200): @@ -102,7 +102,7 @@ def test_learns_decisive_provider_per_need(): assert decisive in bundle.providers, f"{need}: learned {key} lacks decisive {decisive}" -def test_adaptive_beats_fixed_pipeline(): +def test_adaptive_beats_fixed_pipeline(local_run): fx = _fixtures() t = RevenueIntelligenceTenant(fx, bandit=_gtm_bandit(0.1), approver=lambda spec: False) ids = list(fx) @@ -125,7 +125,7 @@ def test_adaptive_beats_fixed_pipeline(): assert adaptive_cost / n <= fixed.cost -def test_learned_arm_f_cheaper_than_e_at_equal_quality(): +def test_learned_arm_f_cheaper_than_e_at_equal_quality(local_run): """Phase 3: conditioning on segment (arm F) resolves every need at strictly lower cost than the need-only policy (arm E), because E must buy a segment-covering bundle where F buys the cheap single.""" fx = _segmented_fixtures() diff --git a/tests/test_runtime_scan.py b/tests/test_runtime_scan.py index 0bbad15..99e39da 100644 --- a/tests/test_runtime_scan.py +++ b/tests/test_runtime_scan.py @@ -98,7 +98,7 @@ def _drive(reg, target, profile): return reg.run("scan.scan_results", {"job_id": job}) -def test_mcp_async_lifecycle(): +def test_mcp_async_lifecycle(local_run): reg, client, names = _mounted(approver=lambda a: True) # allow active for the lifecycle test try: assert {"scan.scan_start", "scan.scan_status", "scan.scan_results"} <= set(names) @@ -111,7 +111,7 @@ def test_mcp_async_lifecycle(): client.close() -def test_mcp_approval_gate_blocks_active(): +def test_mcp_approval_gate_blocks_active(local_run): reg, client, _ = _mounted(approver=passive_only_approver) try: # passive auto-approved @@ -124,7 +124,7 @@ def test_mcp_approval_gate_blocks_active(): client.close() -def test_mcp_off_scope_refused(): +def test_mcp_off_scope_refused(local_run): reg, client, _ = _mounted(approver=lambda a: True) # even with blanket approval… try: r = reg.run("scan.scan_start", {"target": "https://example.com/", "profile": "recon"}) @@ -134,7 +134,7 @@ def test_mcp_off_scope_refused(): client.close() -def test_mcp_unknown_profile(): +def test_mcp_unknown_profile(local_run): reg, client, _ = _mounted(approver=lambda a: True) try: r = reg.run("scan.scan_start", {"target": "vibexgen.io", "profile": "nope"}) From 263743037aabf887f861c5b329660678e85d2e2a Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 14:07:49 -0500 Subject: [PATCH 09/15] agent_console: a denied call answers with its reason instead of a 500 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `AgentConsole._answer_tool` asked the failed `ToolResult` for a `denied` flag that `agent_harness.tools` has never carried, so every authorization denial on a console tool raised AttributeError inside `respond` and the app answered 500 — the one path where a refused user most needs a reason. The flag is honoured when a result carries one; otherwise the registry's own audit trail decides, because that is where the two gates sign their names: an authorization outcome carries the plane's attribution (policy_reason/plane), while an approval hold writes only the four keys it has always written. A held side effect still answers "needs confirmation". Co-Authored-By: Cline --- context_runtime/integrations/agent_console.py | 26 ++++++- tests/test_console_denial_path.py | 78 +++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 tests/test_console_denial_path.py diff --git a/context_runtime/integrations/agent_console.py b/context_runtime/integrations/agent_console.py index 8071bf1..f39ee0a 100644 --- a/context_runtime/integrations/agent_console.py +++ b/context_runtime/integrations/agent_console.py @@ -361,6 +361,30 @@ def _effective_policy(self): from ..policy import current_policy return self._policy or current_policy() + def _denied_by_authorization(self, name: str, result) -> bool: + """Whether a failed result is the AUTHORIZATION gate refusing, not the APPROVAL gate holding the call. + + The two answers read differently to a user — "you are not allowed to do that" versus "this needs a + confirmation first" — and conflating them tells someone with no grant that pressing confirm would help. + + :mod:`agent_harness.tools` has never carried a ``denied`` flag on ``ToolResult``, so asking for one + raised ``AttributeError`` and a denied console call answered 500 instead of its reason. The flag is used + when a result has one; otherwise the registry's own audit trail is read: an authorization outcome is the + entry that carries the plane's attribution (``policy_reason``/``plane``), while an approval hold writes + only the four keys it has always written. No entry at all is not a denial — an unregistered tool, a tool + that crashed, and a policy block each failed somewhere else, and say so. + """ + explicit = getattr(result, "denied", None) + if explicit is not None: + return bool(explicit) + if not (result.error or "").startswith("denied:"): + return False + for entry in reversed(self.registry.audit): + if entry.get("tool") != name: + continue + return entry.get("allowed") is False and "policy_reason" in entry + return False + def _answer_tool(self, name: str, args: dict, principal=None) -> dict: # tool-phase policy: an approval rule pauses an irreversible action; a deny rule blocks it. policy = self._effective_policy() @@ -379,7 +403,7 @@ def _answer_tool(self, name: str, args: dict, principal=None) -> dict: if not result.ok: # A denial carries its own reason and must show it: "this needs confirmation" is what a held # side effect says, and it is the wrong thing to tell someone whose action was denied. - if result.denied: + if self._denied_by_authorization(name, result): body = summary or result.error or "That action is not authorized." else: body = summary or "That action needs confirmation before it can run." diff --git a/tests/test_console_denial_path.py b/tests/test_console_denial_path.py new file mode 100644 index 0000000..7bf9f22 --- /dev/null +++ b/tests/test_console_denial_path.py @@ -0,0 +1,78 @@ +"""A refused console call answers with its reason. Not with a 500. + +``AgentConsole`` reads the failed result the registry hands back and has to tell two kinds of "no" apart: the +AUTHORIZATION gate refusing (no grant — pressing confirm changes nothing) and the APPROVAL gate holding a +side effect for confirmation. It asked the result for a ``denied`` flag that :mod:`agent_harness.tools` has +never set, so every authorization denial on a console tool raised ``AttributeError`` inside ``respond`` and the +app answered 500 — the one path where a refused user most needs a reason. The flag is honoured when a result +carries one; otherwise the registry's audit trail decides, because that is where the two gates sign their names. +""" +from __future__ import annotations + +from types import SimpleNamespace + +from agent_harness.tools import ApprovalPolicy, Authorization + +from context_runtime.integrations.agent_console import AgentConsole +from context_runtime.tools.base import ToolResult, function_tool, local_trusted_authorizer + + +def _who(user="alice", app="growth-engine"): + return SimpleNamespace(user=user, app=app, roles=frozenset()) + + +def _deny_writes(principal, spec, args): + """An authorizer in the engine's own words. It says YES out loud: returning nothing is silence, and + silence is a denial (``missing_explicit_grant``), not permission — so the read needs a real decision.""" + if spec.name == "traffic_summary": + return Authorization.allow(grant_ids=("local:read",), plane="permissions") + return "no 'write' grant for this principal" + + +def _console(authorizer, **kw): + return AgentConsole( + "Growth Engine", "traffic and campaigns", app="growth-engine", + tools=[function_tool("traffic_summary", lambda a: ToolResult(ok=True, text="12k visits"), + description="traffic summary", action="read"), + function_tool("reallocate_budget", lambda a: ToolResult(ok=True, text="moved"), + description="move budget", side_effecting=True, action="write")], + authorizer=authorizer, **kw) # no model: the routing falls back to the keyword path + + +def test_a_denied_action_reports_its_reason_instead_of_raising(): + answer = _console(_deny_writes).respond("reallocate the budget to linkedin", principal=_who()) + assert answer["intent"] == "action" and answer["approved"] is False + assert "no 'write' grant" in answer["text"] + assert "needs confirmation" not in answer["text"] # refused, not held: confirming changes nothing + + +def test_an_allowed_read_reaches_the_tool(): + """The positive control: the same console, the same authorizer, a tool it does grant.""" + answer = _console(_deny_writes).respond("give me the traffic summary", principal=_who()) + assert answer["intent"] == "action" and answer["tool"] == "traffic_summary" + assert answer["approved"] is True and "12k visits" in answer["text"] # authorized: the tool ran + + +def test_a_held_side_effect_still_says_confirmation_not_refusal(): + """The other gate, the other sentence: authorized, but the approval policy has not been satisfied.""" + console = _console(local_trusted_authorizer()) + console.registry.policy = ApprovalPolicy("deny_side_effects", approver=lambda call: False) + answer = console.respond("reallocate the budget to linkedin", principal=_who()) + assert answer["approved"] is False # held, not run + assert "[no_grant]" not in answer["text"] and "grant" not in answer["text"].lower() + + +def test_a_result_that_carries_the_flag_is_believed(): + """When the engine does provide the flag, the audit trail is not consulted — the result speaks for itself.""" + console = _console(_deny_writes) + assert console._denied_by_authorization("traffic_summary", + SimpleNamespace(error="denied: whatever", denied=False)) is False + assert console._denied_by_authorization("traffic_summary", + SimpleNamespace(error="denied: whatever", denied=True)) is True + + +def test_a_tool_that_crashed_is_not_reported_as_a_refusal(): + """No authorization entry behind the failure means it never reached the gate: not a denial.""" + console = _console(_deny_writes) + assert console._denied_by_authorization("traffic_summary", SimpleNamespace(error="RuntimeError: boom")) is False + assert console._denied_by_authorization("nope", SimpleNamespace(error="denied: not registered")) is False \ No newline at end of file From 905d5bfe8824c7c24bb182e535ef69b56126a1f9 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 14:07:49 -0500 Subject: [PATCH 10/15] integrations: a replaced tool implementation declares its own risk class MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nine tenants ship a local simulation of one tool and register it at the class that simulation earned — `read`, because building a string touches nothing (market_radar's sweep is `write`: it fetches and stores). All nine also accept a `*_tool_factory` that replaces that simulation with code this repository has never read, and not one of them moved the class when it happened: pass a function that posts to a vendor and the tool stayed a `read`, so a principal holding only a read grant could run it. The social_autopilot note even promised the integrator would re-register it as write; nothing enforced the promise. `tools/actions.resolve_action` settles it the way `resolve_authorizer` and `mount_mcp(actions=)` already settle their seams. Nothing injected, the reviewed class stands. Something injected, the integrator declares the class of their own function through the tenant's new `*_action` keyword, and construction refuses instead of inheriting. A class outside ACTIONS refuses on either side: a typo is not a risk class, a wrong class runs on someone else's permission, and an unclassified one is matched by no grant and denied at every call. Co-Authored-By: Cline --- .../integrations/agentic_billing.py | 7 +- context_runtime/integrations/agentic_books.py | 7 +- .../integrations/agentic_compliance.py | 7 +- .../integrations/agentic_support.py | 7 +- context_runtime/integrations/control_tower.py | 7 +- context_runtime/integrations/growth_engine.py | 8 +- context_runtime/integrations/market_radar.py | 7 +- .../integrations/outreach_engine.py | 10 +- .../integrations/social_autopilot.py | 11 +- context_runtime/tools/__init__.py | 2 + context_runtime/tools/actions.py | 60 +++++++++ tests/test_injected_tool_classification.py | 119 ++++++++++++++++++ 12 files changed, 239 insertions(+), 13 deletions(-) create mode 100644 context_runtime/tools/actions.py create mode 100644 tests/test_injected_tool_classification.py diff --git a/context_runtime/integrations/agentic_billing.py b/context_runtime/integrations/agentic_billing.py index eff845d..e2c2588 100644 --- a/context_runtime/integrations/agentic_billing.py +++ b/context_runtime/integrations/agentic_billing.py @@ -13,6 +13,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.actions import resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -106,6 +107,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[BillingSignalBundle, ...] = DEFAULT_BILLING, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, fetch_tool_factory: Callable[[dict], ToolResult] | None = None, + fetch_action: str | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms @@ -118,6 +120,8 @@ def __init__(self, runtime: ContextRuntime | None = None, # ``fetch_signals`` reads usage, invoices, dunning state and payment history for a named # account: a sensitive read of customer financial data, so ``read`` — and the plane, not # this file, narrows it per tenant and per row. + # ``fetch_tool_factory`` replaces that function, and the class does not come with the slot it + # fills: a live billing call that raises an invoice or triggers dunning is not a read. self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="agentic_billing")) @@ -126,7 +130,8 @@ def __init__(self, runtime: ContextRuntime | None = None, name="fetch_signals", description="Fetch the selected billing signal bundle (simulated).", fn=fetch_fn, - action="read", + action=resolve_action(shipped="read", injected=fetch_tool_factory, declared=fetch_action, + param="fetch_action", tool="fetch_signals", context="agentic_billing"), )) self._pending: dict[str, tuple] = {} diff --git a/context_runtime/integrations/agentic_books.py b/context_runtime/integrations/agentic_books.py index 89a8dd0..4838c1f 100644 --- a/context_runtime/integrations/agentic_books.py +++ b/context_runtime/integrations/agentic_books.py @@ -14,6 +14,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.actions import resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -107,6 +108,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[BooksReportBundle, ...] = DEFAULT_BOOKS, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, pull_tool_factory: Callable[[dict], ToolResult] | None = None, + pull_action: str | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms @@ -118,6 +120,8 @@ def __init__(self, runtime: ContextRuntime | None = None, # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. # ``pull_reports`` reads receivables, payables, tax and trial balance for the tenant: # books data, and nothing is written — ``read``. + # ``pull_tool_factory`` replaces that function, and the class does not come with the slot it fills: + # a live ERP pull that posts journal entries or writes a report is not the same call as this one. self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="agentic_books")) @@ -126,7 +130,8 @@ def __init__(self, runtime: ContextRuntime | None = None, name="pull_reports", description="Pull the selected ledger/report bundle (simulated).", fn=pull_fn, - action="read", + action=resolve_action(shipped="read", injected=pull_tool_factory, declared=pull_action, + param="pull_action", tool="pull_reports", context="agentic_books"), )) self._pending: dict[str, tuple] = {} diff --git a/context_runtime/integrations/agentic_compliance.py b/context_runtime/integrations/agentic_compliance.py index 432b799..7cad245 100644 --- a/context_runtime/integrations/agentic_compliance.py +++ b/context_runtime/integrations/agentic_compliance.py @@ -14,6 +14,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.actions import resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -107,6 +108,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[ComplianceEvidenceBundle, ...] = DEFAULT_COMPLIANCE, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, pull_tool_factory: Callable[[dict], ToolResult] | None = None, + pull_action: str | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms @@ -118,6 +120,8 @@ def __init__(self, runtime: ContextRuntime | None = None, # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. # ``pull_evidence`` reads access, crypto, audit and patch evidence: security findings, # which are sensitive to read and only later consequential to remediate — ``read``. + # ``pull_tool_factory`` replaces that function, and the class does not come with the slot it fills: + # pulling evidence out of a live scanner or SIEM is not the same call as building this string. self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="agentic_compliance")) @@ -126,7 +130,8 @@ def __init__(self, runtime: ContextRuntime | None = None, name="pull_evidence", description="Pull the selected rule-family evidence bundle (simulated).", fn=pull_fn, - action="read", + action=resolve_action(shipped="read", injected=pull_tool_factory, declared=pull_action, + param="pull_action", tool="pull_evidence", context="agentic_compliance"), )) self._pending: dict[str, tuple] = {} diff --git a/context_runtime/integrations/agentic_support.py b/context_runtime/integrations/agentic_support.py index 02b8147..16e740e 100644 --- a/context_runtime/integrations/agentic_support.py +++ b/context_runtime/integrations/agentic_support.py @@ -14,6 +14,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.actions import resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -108,6 +109,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[SupportContextBundle, ...] = DEFAULT_SUPPORT, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, retrieve_tool_factory: Callable[[dict], ToolResult] | None = None, + retrieve_action: str | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms @@ -119,6 +121,8 @@ def __init__(self, runtime: ContextRuntime | None = None, # are read off what the tool actually does, never off its name or its ``side_effecting`` flag. # ``retrieve_context`` reads ticket history, account detail and escalation state for a # ticket: customer personal data — ``read``, scoped per tenant by the plane. + # ``retrieve_tool_factory`` replaces that function, and the class does not come with the slot it + # fills: a live desk that replies to the customer or reassigns the ticket is not a read. self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="agentic_support")) @@ -127,7 +131,8 @@ def __init__(self, runtime: ContextRuntime | None = None, name="retrieve_context", description="Retrieve the selected support context bundle (simulated).", fn=retrieve_fn, - action="read", + action=resolve_action(shipped="read", injected=retrieve_tool_factory, declared=retrieve_action, + param="retrieve_action", tool="retrieve_context", context="agentic_support"), )) self._pending: dict[str, tuple] = {} diff --git a/context_runtime/integrations/control_tower.py b/context_runtime/integrations/control_tower.py index 966633a..8410ec7 100644 --- a/context_runtime/integrations/control_tower.py +++ b/context_runtime/integrations/control_tower.py @@ -15,6 +15,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.actions import resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -100,6 +101,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[ControlTowerArm, ...] = DEFAULT_TOWER, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, refresh_tool_factory: Callable[[dict], ToolResult] | None = None, + refresh_action: str | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms @@ -112,6 +114,8 @@ def __init__(self, runtime: ContextRuntime | None = None, # ``refresh_metabase`` re-runs Metabase queries and returns their rows — the same call # agentic-os classifies as ``bi.refresh``/read: a query against the platform's own # warehouse, which writes no business state. Persisting a card or dashboard would not be. + # ``refresh_tool_factory`` replaces that function, and the class does not come with the slot it + # fills: whoever swaps in a live call declares it with ``refresh_action`` (``resolve_action``). self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="control_tower")) @@ -120,7 +124,8 @@ def __init__(self, runtime: ContextRuntime | None = None, name="refresh_metabase", description="Refresh the Metabase query set (simulated).", fn=refresh_fn, - action="read", + action=resolve_action(shipped="read", injected=refresh_tool_factory, declared=refresh_action, + param="refresh_action", tool="refresh_metabase", context="control_tower"), )) self._pending: dict[str, tuple[Plan, ControlTowerArm, str, str]] = {} diff --git a/context_runtime/integrations/growth_engine.py b/context_runtime/integrations/growth_engine.py index 94ecd58..52508d9 100644 --- a/context_runtime/integrations/growth_engine.py +++ b/context_runtime/integrations/growth_engine.py @@ -8,6 +8,7 @@ from .bandit import EpsilonGreedyBandit from ..runtime.runtime import ContextRuntime +from ..tools.actions import resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Plan, Trace @@ -129,6 +130,7 @@ def __init__(self, runtime: ContextRuntime | None = None, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, bucket_fn: Callable[[str], str] = growth_engine_bucket, report_tool_factory: Callable[[dict], ToolResult] | None = None, + report_action: str | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms @@ -142,6 +144,8 @@ def __init__(self, runtime: ContextRuntime | None = None, # ``draft_attribution_report`` composes an attribution answer from analytics it reads; # the text goes back to the caller and nothing is published — ``read``. Publishing the # report is a separate route and is classified ``write`` where it is registered. + # ``report_tool_factory`` replaces that function, and the class does not come with the slot it + # fills: a live report that lands in a warehouse or a dashboard is not the same call as this one. self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="growth_engine")) @@ -150,7 +154,9 @@ def __init__(self, runtime: ContextRuntime | None = None, name="draft_attribution_report", description="Draft an attribution breakdown for the chosen arm (simulated).", fn=report_fn, - action="read", + action=resolve_action(shipped="read", injected=report_tool_factory, declared=report_action, + param="report_action", tool="draft_attribution_report", + context="growth_engine"), )) self._pending: dict[str, tuple[Plan, AttributionArm, str, str]] = {} diff --git a/context_runtime/integrations/market_radar.py b/context_runtime/integrations/market_radar.py index 7b71cc1..9c28fd9 100644 --- a/context_runtime/integrations/market_radar.py +++ b/context_runtime/integrations/market_radar.py @@ -11,6 +11,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.actions import resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -135,6 +136,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[RadarArm, ...] = DEFAULT_RADAR, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, scrape_tool_factory: Callable[[dict], ToolResult] | None = None, + scrape_action: str | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms @@ -149,6 +151,8 @@ def __init__(self, runtime: ContextRuntime | None = None, # persisted as tenant state. Third-party fetching with stored consequences is ``write`` # under the platform's own inventory (compare crm.research, sbom, add_watch). The shipped # default is the offline simulation; a real fetcher must be registered by whoever wires it. + # That is enforced, not asked for: a function in ``scrape_tool_factory`` has to say its own class + # with ``scrape_action``, or construction refuses — the class is not inherited from the slot. self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="market_radar")) @@ -157,7 +161,8 @@ def __init__(self, runtime: ContextRuntime | None = None, name="perform_sweep", description="Perform the selected market radar sweep (simulated).", fn=scrape_fn, - action="write", + action=resolve_action(shipped="write", injected=scrape_tool_factory, declared=scrape_action, + param="scrape_action", tool="perform_sweep", context="market_radar"), )) self._pending: dict[str, tuple[Plan, RadarArm, str, ToolResult]] = {} diff --git a/context_runtime/integrations/outreach_engine.py b/context_runtime/integrations/outreach_engine.py index c710f9e..3f23b72 100644 --- a/context_runtime/integrations/outreach_engine.py +++ b/context_runtime/integrations/outreach_engine.py @@ -19,6 +19,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.actions import resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Plan, Trace @@ -123,6 +124,7 @@ def __init__(self, runtime: ContextRuntime | None = None, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, bucket_fn: Callable[[str], str] = outreach_bucket, teardown_tool_factory: Callable[[dict], ToolResult] | None = None, + teardown_action: str | None = None, approver: Callable[[str], bool] | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) @@ -139,14 +141,18 @@ def __init__(self, runtime: ContextRuntime | None = None, # ``draft_teardown`` writes nothing and contacts nobody: it returns the drafted opener. # ``send_sequence`` below is the external communication and stays approval-gated with a # default-deny approver, so drafting is ``read`` while sending needs both gates. + # ``teardown_tool_factory`` replaces that function, and the class does not come with the slot it + # fills: a live opener that sends, posts or creates something in a campaign is not a read. self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="outreach_engine")) + teardown_fn = teardown_tool_factory or _draft_teardown self.registry.register(function_tool( name="draft_teardown", description="Draft the personalized opener (EXPLAIN teardown for artifact plays).", - fn=teardown_tool_factory or _draft_teardown, - action="read", + fn=teardown_fn, + action=resolve_action(shipped="read", injected=teardown_tool_factory, declared=teardown_action, + param="teardown_action", tool="draft_teardown", context="outreach_engine"), )) self._pending: dict[str, tuple[Plan, OutreachPlay, str, str]] = {} diff --git a/context_runtime/integrations/social_autopilot.py b/context_runtime/integrations/social_autopilot.py index 3de6bba..38c3ac9 100644 --- a/context_runtime/integrations/social_autopilot.py +++ b/context_runtime/integrations/social_autopilot.py @@ -19,6 +19,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime +from ..tools.actions import resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -132,6 +133,7 @@ def __init__(self, runtime: ContextRuntime | None = None, strategies: tuple[SocialStrategy, ...] = DEFAULT_STRATEGIES, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, caption_tool_factory: Callable[[dict], ToolResult] | None = None, + caption_action: str | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.strategies = strategies @@ -144,9 +146,9 @@ def __init__(self, runtime: ContextRuntime | None = None, # ``draft_caption`` returns drafted copy to the caller and the shipped implementation is a # local simulation, so it reads. Two named divergences from the platform table, both deliberate: # agentic-os classes ``social.draft`` write because its draft calls an external generator, and - # the publish/schedule call is a separate consequential path (``social.publish`` write). Whoever - # passes ``caption_tool_factory`` that reaches a generation service re-registers this tool as - # write — the class describes the function that is actually installed. + # the publish/schedule call is a separate consequential path (``social.publish`` write). Passing + # ``caption_tool_factory`` replaces the simulation, so that function declares its own class with + # ``caption_action`` — construction refuses rather than hand a live generator a read grant. self.registry = ToolRegistry(authorizer=resolve_authorizer( authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context="social_autopilot")) @@ -155,7 +157,8 @@ def __init__(self, runtime: ContextRuntime | None = None, name="draft_caption", description="Draft a caption for the chosen social strategy (simulated).", fn=caption_fn, - action="read", + action=resolve_action(shipped="read", injected=caption_tool_factory, declared=caption_action, + param="caption_action", tool="draft_caption", context="social_autopilot"), )) self._pending: dict[str, tuple[Plan, SocialStrategy, str, str]] = {} diff --git a/context_runtime/tools/__init__.py b/context_runtime/tools/__init__.py index c71d5e0..f5bdee1 100644 --- a/context_runtime/tools/__init__.py +++ b/context_runtime/tools/__init__.py @@ -16,10 +16,12 @@ ToolSpec, ) from .authz import LOCAL_AUTHORITY_ENV, local_authority, local_authority_from_env, resolve_authorizer +from .actions import resolve_action from .retriever import ToolRetriever __all__ = [ "ToolSpec", "ToolResult", "ToolPlugin", "ToolRegistry", "ApprovalPolicy", "ToolError", "ToolRetriever", "resolve_authorizer", "local_authority", "local_authority_from_env", "LOCAL_AUTHORITY_ENV", + "resolve_action", ] diff --git a/context_runtime/tools/actions.py b/context_runtime/tools/actions.py new file mode 100644 index 0000000..3bf861d --- /dev/null +++ b/context_runtime/tools/actions.py @@ -0,0 +1,60 @@ +"""What risk class a Context Runtime tool is registered with — and who is allowed to set it. + +:mod:`context_runtime.tools.authz` answers who authorizes a call. This answers the other question a +registration has to settle: which capability the call will be checked for. Both are answered in one +place so that the integration tenants cannot each invent an answer, and both refuse to guess. + +The rule is the one the whole classification design rests on: **the class describes the effect of the +code that runs.** It is set by whoever read that code, and it is never inherited from the name the tool +is filed under, from a remote server's ``readOnlyHint``, or from a previous occupant of the slot. The +seam this module guards is the last of those three: every integration tenant ships a local simulation of +one tool — it builds a string and returns it, so it is a ``read`` — and lets an integrator replace it +with ``*_tool_factory``. A replacement that posts to a vendor, stores a row or launches a scan is not a +read, and inheriting the class of the function it replaced would hand that call to anyone holding a read +grant. + +So: nothing injected, the reviewed class of the shipped implementation stands. Something injected, the +integrator declares the class of their own function, and construction refuses without it — the same +posture as :func:`~context_runtime.tools.authz.resolve_authorizer` and as ``mount_mcp(actions=...)``, +where an unmapped MCP tool falls to ``write`` rather than to the server's own claim. +""" +from __future__ import annotations + +from typing import Optional + +from .base import ACTIONS, RegistryConfigurationError + + +def resolve_action(*, shipped: str, injected: Optional[object] = None, declared: Optional[str] = None, + param: str = "", tool: str = "", context: str = "") -> str: + """The risk class of the function that is actually installed, which is not always the shipped one's. + + ``shipped`` is the class this file reviewed for the implementation it ships; ``injected`` is the + caller's replacement function, or ``None`` when they took the shipped one; ``declared`` is the class + the caller says their own function deserves, via the tenant's ``*_action`` keyword. + + Nothing injected returns ``shipped`` untouched. Something injected returns ``declared`` — and raises + :class:`~context_runtime.tools.base.RegistryConfigurationError` when it is missing, because "the + simulation was a read" is not evidence about a function this repository has never seen. A value + outside :data:`~context_runtime.tools.base.ACTIONS` raises the same way, on either side: a typo is not + a risk class, and a wrong class is worse than no class, because an unclassified tool is matched by no + grant and so is denied at every call, while a wrongly-classified one runs on someone else's permission. + """ + where = f"{tool} ({context})" if tool and context else (tool or context or "this tool") + param = param or f"{tool.rsplit('.', 1)[-1] if tool else 'tool'}_action" + if shipped not in ACTIONS: + raise RegistryConfigurationError( + f"{where}: the shipped risk class {shipped!r} is not one of the vocabulary {ACTIONS} — a bug " + f"in this integration, not a value a caller can supply.") + if injected is None: + return shipped + if declared is None: + raise RegistryConfigurationError( + f"{where}: a function was injected in place of the implementation shipped here, and a risk " + f"class is not inherited from the tool it replaces. Pass {param}=... — one of {ACTIONS} — for " + f"what the injected function actually does. If it fetches, posts, stores or launches anything, " + f"that is not {shipped!r}.") + if declared not in ACTIONS: + raise RegistryConfigurationError( + f"{where}: {param}={declared!r} is not one of the vocabulary {ACTIONS}.") + return declared \ No newline at end of file diff --git a/tests/test_injected_tool_classification.py b/tests/test_injected_tool_classification.py new file mode 100644 index 0000000..252311a --- /dev/null +++ b/tests/test_injected_tool_classification.py @@ -0,0 +1,119 @@ +"""A replaced implementation carries its own risk class, or the tenant refuses to start. + +Every integration tenant here ships a local simulation of one tool — it builds a string and hands it back, +so the class it was reviewed at is ``read`` (``market_radar`` is the exception: a sweep fetches and stores, +so it is ``write``). Each tenant also exposes a ``*_tool_factory`` hook that replaces that simulation with +code this repository has never seen. Until now the class did not move with the code: pass a factory that +posts to a vendor and the tool stayed registered as ``read``, which means a principal holding only a read +grant could run it. That is the downgrade this file exists to keep closed. + +The rule being pinned is the one ``resolve_action`` implements: the class describes the effect of the +function that actually runs. Nothing injected, the reviewed class stands. Something injected, whoever read +their own function says what it is — and construction refuses instead of inheriting. +""" +from __future__ import annotations + +import importlib + +import pytest + +from agent_harness.tools import Authorization + +from context_runtime.tools.base import RegistryConfigurationError, ToolResult + +#: module, tenant class, factory hook, the class-declaring keyword, registered tool, reviewed class. +TENANTS = [ + ("control_tower", "ControlTowerTenant", "refresh_tool_factory", "refresh_action", "refresh_metabase", "read"), + ("agentic_compliance", "AgenticComplianceTenant", "pull_tool_factory", "pull_action", "pull_evidence", "read"), + ("agentic_books", "AgenticBooksTenant", "pull_tool_factory", "pull_action", "pull_reports", "read"), + ("agentic_support", "AgenticSupportTenant", "retrieve_tool_factory", "retrieve_action", "retrieve_context", + "read"), + ("agentic_billing", "AgenticBillingTenant", "fetch_tool_factory", "fetch_action", "fetch_signals", "read"), + ("growth_engine", "GrowthEngineTenant", "report_tool_factory", "report_action", "draft_attribution_report", + "read"), + ("market_radar", "MarketRadarTenant", "scrape_tool_factory", "scrape_action", "perform_sweep", "write"), + ("outreach_engine", "OutreachEngineTenant", "teardown_tool_factory", "teardown_action", "draft_teardown", + "read"), + ("social_autopilot", "SocialAutopilotTenant", "caption_tool_factory", "caption_action", "draft_caption", + "read"), +] +_IDS = [f"{mod}.{tool}" for mod, _, _, _, tool, _ in TENANTS] + +_REASON = "offline audit of the injected-factory seam" + + +def _tenant(module: str, cls: str, **kwargs): + return getattr(importlib.import_module(f"context_runtime.integrations.{module}"), cls)( + local_trust=True, local_trust_reason=_REASON, **kwargs) + + +def _vendor_call(args: dict) -> ToolResult: + """Stand-in for the thing an integrator actually swaps in: it leaves the process.""" + return ToolResult(ok=True, text="posted to a vendor") + + +def _read_only_plane(principal, spec, args): + """A permissions plane that granted ``read`` and nothing else — the principal this test cares about.""" + if spec.action != "read": + return f"no '{spec.action}' grant for this principal" + return Authorization.allow(grant_ids=("role:reader",), plane="permissions") + + +@pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) +def test_the_shipped_implementation_keeps_the_class_it_was_reviewed_at(module, cls, factory, action_kw, tool, + shipped): + tenant = _tenant(module, cls) + assert tenant.registry.get(tool).spec().action == shipped + + +@pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) +def test_a_replacement_without_a_class_of_its_own_refuses_to_start(module, cls, factory, action_kw, tool, + shipped): + """No silent inheritance: the integrator that swapped the function is the one who has to grade it.""" + with pytest.raises(RegistryConfigurationError) as exc: + _tenant(module, cls, **{factory: _vendor_call}) + message = str(exc.value) + assert action_kw in message # it names the parameter that answers the question + assert tool in message # and the tool the answer is about + + +@pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) +def test_a_replacement_declares_its_own_class(module, cls, factory, action_kw, tool, shipped): + tenant = _tenant(module, cls, **{factory: _vendor_call, action_kw: "write"}) + spec = tenant.registry.get(tool).spec() + assert spec.action == "write" + + +@pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) +def test_a_class_outside_the_vocabulary_refuses_to_start(module, cls, factory, action_kw, tool, shipped): + """A typo is not a risk class — and neither is a word invented for one tool.""" + with pytest.raises(RegistryConfigurationError): + _tenant(module, cls, **{factory: _vendor_call, action_kw: "generate"}) + + +def test_a_replaced_caption_no_longer_runs_on_a_read_grant(): + """The end of the story: the class is what a grant is matched against, so this is the denial that matters. + + ``draft_caption`` simulated is a read and runs for a read-only principal. The same tool with a real + generator behind it, declared as such, does not — while an integrator who genuinely replaced it with + another pure function can still declare ``read`` and keep working. + """ + shipped = _tenant("social_autopilot", "SocialAutopilotTenant") + assert shipped.registry.run("draft_caption", {"goal": "g", "channel": "linkedin"}).ok + # ^ that tenant ran on the declared local authority; the two below name the plane, the way a + # deployment does, because the grant is the thing under test. + + live = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_vendor_call, + caption_action="write", authorizer=_read_only_plane) + denied = live.registry.run("draft_caption", {"goal": "g", "channel": "linkedin"}) + assert not denied.ok and "no 'write' grant" in (denied.error or "") + assert live.registry.audit[-1]["allowed"] is False + + # and the shipped read-only simulation still runs for that same read-only principal + assert _tenant("social_autopilot", "SocialAutopilotTenant", + authorizer=_read_only_plane).registry.run( + "draft_caption", {"goal": "g", "channel": "linkedin"}).ok + + pure = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_vendor_call, + caption_action="read", authorizer=_read_only_plane) + assert pure.registry.run("draft_caption", {"goal": "g", "channel": "linkedin"}).ok \ No newline at end of file From 0b95a5720c04fe4c8b84200fe91ef7c6170b1a40 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 14:31:00 -0500 Subject: [PATCH 11/15] actions: an injected tool starts at write and has to contract its way down MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A declaration is not an authorization guarantee. The first cut of this seam let the integrator name any class, which moved the problem instead of closing it: the code asking to run was still grading its own risk, just out loud. So the seam now has a floor and a contract. Anything injected into a tenant's `*_tool_factory` seat is registered at `write` — a function this repository did not write is assumed to leave the process. The only way below the floor is `pure_read("")`, a typed claim whose reason is checked for saying something, and then checked against the function's own source using the sink vocabulary the platform's FR-04 sweep runs over its own read-classified tools. A visible `post`, `subprocess.run`, `open(..., "w")` or `os.remove` beats the claim; so does a `rmtree` hiding behind a `write`, which is the same under-declaration one rung lower. Ambiguous verbs (`remove`, `rename`, `move`) count only when the object they are called on names a filesystem, because a rule that flags `rows.remove(x)` is a rule that trains people to declare without reading. The blind spot is named in the module rather than hidden: the sweep reads the callable handed over, not what it delegates to, which is why the floor exists at all. Co-Authored-By: Cline --- .../integrations/agentic_billing.py | 4 +- context_runtime/integrations/agentic_books.py | 4 +- .../integrations/agentic_compliance.py | 4 +- .../integrations/agentic_support.py | 4 +- context_runtime/integrations/control_tower.py | 4 +- context_runtime/integrations/growth_engine.py | 4 +- context_runtime/integrations/market_radar.py | 4 +- .../integrations/outreach_engine.py | 4 +- .../integrations/social_autopilot.py | 4 +- context_runtime/tools/__init__.py | 3 +- context_runtime/tools/actions.py | 236 +++++++++++++++--- tests/test_injected_tool_classification.py | 221 ++++++++++++---- 12 files changed, 396 insertions(+), 100 deletions(-) diff --git a/context_runtime/integrations/agentic_billing.py b/context_runtime/integrations/agentic_billing.py index e2c2588..09712be 100644 --- a/context_runtime/integrations/agentic_billing.py +++ b/context_runtime/integrations/agentic_billing.py @@ -13,7 +13,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime -from ..tools.actions import resolve_action +from ..tools.actions import PureRead, resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -107,7 +107,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[BillingSignalBundle, ...] = DEFAULT_BILLING, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, fetch_tool_factory: Callable[[dict], ToolResult] | None = None, - fetch_action: str | None = None, + fetch_action: str | PureRead | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms diff --git a/context_runtime/integrations/agentic_books.py b/context_runtime/integrations/agentic_books.py index 4838c1f..274324b 100644 --- a/context_runtime/integrations/agentic_books.py +++ b/context_runtime/integrations/agentic_books.py @@ -14,7 +14,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime -from ..tools.actions import resolve_action +from ..tools.actions import PureRead, resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -108,7 +108,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[BooksReportBundle, ...] = DEFAULT_BOOKS, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, pull_tool_factory: Callable[[dict], ToolResult] | None = None, - pull_action: str | None = None, + pull_action: str | PureRead | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms diff --git a/context_runtime/integrations/agentic_compliance.py b/context_runtime/integrations/agentic_compliance.py index 7cad245..a7a49b9 100644 --- a/context_runtime/integrations/agentic_compliance.py +++ b/context_runtime/integrations/agentic_compliance.py @@ -14,7 +14,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime -from ..tools.actions import resolve_action +from ..tools.actions import PureRead, resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -108,7 +108,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[ComplianceEvidenceBundle, ...] = DEFAULT_COMPLIANCE, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, pull_tool_factory: Callable[[dict], ToolResult] | None = None, - pull_action: str | None = None, + pull_action: str | PureRead | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms diff --git a/context_runtime/integrations/agentic_support.py b/context_runtime/integrations/agentic_support.py index 16e740e..5670288 100644 --- a/context_runtime/integrations/agentic_support.py +++ b/context_runtime/integrations/agentic_support.py @@ -14,7 +14,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime -from ..tools.actions import resolve_action +from ..tools.actions import PureRead, resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -109,7 +109,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[SupportContextBundle, ...] = DEFAULT_SUPPORT, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, retrieve_tool_factory: Callable[[dict], ToolResult] | None = None, - retrieve_action: str | None = None, + retrieve_action: str | PureRead | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms diff --git a/context_runtime/integrations/control_tower.py b/context_runtime/integrations/control_tower.py index 8410ec7..e51c501 100644 --- a/context_runtime/integrations/control_tower.py +++ b/context_runtime/integrations/control_tower.py @@ -15,7 +15,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime -from ..tools.actions import resolve_action +from ..tools.actions import PureRead, resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -101,7 +101,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[ControlTowerArm, ...] = DEFAULT_TOWER, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, refresh_tool_factory: Callable[[dict], ToolResult] | None = None, - refresh_action: str | None = None, + refresh_action: str | PureRead | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms diff --git a/context_runtime/integrations/growth_engine.py b/context_runtime/integrations/growth_engine.py index 52508d9..7ae2e29 100644 --- a/context_runtime/integrations/growth_engine.py +++ b/context_runtime/integrations/growth_engine.py @@ -8,7 +8,7 @@ from .bandit import EpsilonGreedyBandit from ..runtime.runtime import ContextRuntime -from ..tools.actions import resolve_action +from ..tools.actions import PureRead, resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Plan, Trace @@ -130,7 +130,7 @@ def __init__(self, runtime: ContextRuntime | None = None, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, bucket_fn: Callable[[str], str] = growth_engine_bucket, report_tool_factory: Callable[[dict], ToolResult] | None = None, - report_action: str | None = None, + report_action: str | PureRead | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms diff --git a/context_runtime/integrations/market_radar.py b/context_runtime/integrations/market_radar.py index 9c28fd9..cf513af 100644 --- a/context_runtime/integrations/market_radar.py +++ b/context_runtime/integrations/market_radar.py @@ -11,7 +11,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime -from ..tools.actions import resolve_action +from ..tools.actions import PureRead, resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -136,7 +136,7 @@ def __init__(self, runtime: ContextRuntime | None = None, arms: tuple[RadarArm, ...] = DEFAULT_RADAR, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, scrape_tool_factory: Callable[[dict], ToolResult] | None = None, - scrape_action: str | None = None, + scrape_action: str | PureRead | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.arms = arms diff --git a/context_runtime/integrations/outreach_engine.py b/context_runtime/integrations/outreach_engine.py index 3f23b72..83fde13 100644 --- a/context_runtime/integrations/outreach_engine.py +++ b/context_runtime/integrations/outreach_engine.py @@ -19,7 +19,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime -from ..tools.actions import resolve_action +from ..tools.actions import PureRead, resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Plan, Trace @@ -124,7 +124,7 @@ def __init__(self, runtime: ContextRuntime | None = None, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, bucket_fn: Callable[[str], str] = outreach_bucket, teardown_tool_factory: Callable[[dict], ToolResult] | None = None, - teardown_action: str | None = None, + teardown_action: str | PureRead | None = None, approver: Callable[[str], bool] | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) diff --git a/context_runtime/integrations/social_autopilot.py b/context_runtime/integrations/social_autopilot.py index 38c3ac9..a0079ea 100644 --- a/context_runtime/integrations/social_autopilot.py +++ b/context_runtime/integrations/social_autopilot.py @@ -19,7 +19,7 @@ from typing import Callable from ..runtime.runtime import ContextRuntime -from ..tools.actions import resolve_action +from ..tools.actions import PureRead, resolve_action from ..tools.authz import resolve_authorizer from ..tools.base import ToolRegistry, ToolResult, function_tool from ..types import Goal, Trace @@ -133,7 +133,7 @@ def __init__(self, runtime: ContextRuntime | None = None, strategies: tuple[SocialStrategy, ...] = DEFAULT_STRATEGIES, bandit: EpsilonGreedyBandit | None = None, epsilon: float = 0.15, caption_tool_factory: Callable[[dict], ToolResult] | None = None, - caption_action: str | None = None, + caption_action: str | PureRead | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = ""): self.runtime = runtime or ContextRuntime.default([]) self.strategies = strategies diff --git a/context_runtime/tools/__init__.py b/context_runtime/tools/__init__.py index f5bdee1..6c46b7c 100644 --- a/context_runtime/tools/__init__.py +++ b/context_runtime/tools/__init__.py @@ -16,7 +16,7 @@ ToolSpec, ) from .authz import LOCAL_AUTHORITY_ENV, local_authority, local_authority_from_env, resolve_authorizer -from .actions import resolve_action +from .actions import PureRead, pure_read, resolve_action from .retriever import ToolRetriever __all__ = [ @@ -24,4 +24,5 @@ "ToolError", "ToolRetriever", "resolve_authorizer", "local_authority", "local_authority_from_env", "LOCAL_AUTHORITY_ENV", "resolve_action", + "PureRead", "pure_read", ] diff --git a/context_runtime/tools/actions.py b/context_runtime/tools/actions.py index 3bf861d..6dd2b16 100644 --- a/context_runtime/tools/actions.py +++ b/context_runtime/tools/actions.py @@ -1,60 +1,220 @@ -"""What risk class a Context Runtime tool is registered with — and who is allowed to set it. +"""What risk class a Context Runtime tool is registered with, and what it takes to claim one. :mod:`context_runtime.tools.authz` answers who authorizes a call. This answers the other question a -registration has to settle: which capability the call will be checked for. Both are answered in one -place so that the integration tenants cannot each invent an answer, and both refuse to guess. - -The rule is the one the whole classification design rests on: **the class describes the effect of the -code that runs.** It is set by whoever read that code, and it is never inherited from the name the tool -is filed under, from a remote server's ``readOnlyHint``, or from a previous occupant of the slot. The -seam this module guards is the last of those three: every integration tenant ships a local simulation of -one tool — it builds a string and returns it, so it is a ``read`` — and lets an integrator replace it -with ``*_tool_factory``. A replacement that posts to a vendor, stores a row or launches a scan is not a -read, and inheriting the class of the function it replaced would hand that call to anyone holding a read -grant. - -So: nothing injected, the reviewed class of the shipped implementation stands. Something injected, the -integrator declares the class of their own function, and construction refuses without it — the same -posture as :func:`~context_runtime.tools.authz.resolve_authorizer` and as ``mount_mcp(actions=...)``, -where an unmapped MCP tool falls to ``write`` rather than to the server's own claim. +registration has to settle: which capability the call will be checked for. Both live in one place so the +integration tenants cannot each invent an answer, and both refuse to guess. + +**The rule.** The class describes the effect of the code that runs. It is set by whoever read that code, and +it is never inherited from the name the tool is filed under, from a remote server's ``readOnlyHint``, or from +a previous occupant of the slot. The seam this module guards is the last of those three: every integration +tenant ships a local simulation of one tool — it builds a string and returns it, so it is a ``read`` — and +lets an integrator replace it with ``*_tool_factory``. A replacement that posts to a vendor, stores a row or +launches a scan is not a read, and inheriting the class of the function it replaced would hand that call to +anyone holding a read grant. + +**Why a declaration is not enough on its own.** "Trust me, mine really is a read" is the same failure wearing +a different hat: the code asking to run grades its own risk again, which is the thing this design refuses. +So an injected implementation starts at :data:`INJECTED_FLOOR` — anything swapped in from outside this +repository is assumed to leave the process until shown otherwise — and the only way below the floor is a +*capability contract*: a named constructor whose argument must be a sentence about why the function is inert, +which is what makes the claim reviewable in a manifest or a pull request rather than a bare flag. That claim +is then checked against the function's own source: :func:`write_sinks` looks for the sink vocabulary the +platform's own read-classification sweep (agentic-os FR-04) uses, and a function reaching one cannot be +registered below the class that sink implies, whatever its author declared. + +**What this does not pretend to be.** The sweep reads the callable that was handed over — nested definitions +included — not whatever that callable goes on to call. A factory that delegates to a client library is +invisible to it, which is exactly why the floor is ``write`` and not ``read``: the check exists to catch the +honest mistake and to make a false claim expensive, not to stand in for a review. """ from __future__ import annotations -from typing import Optional +import ast +import inspect +import textwrap +from dataclasses import dataclass +from typing import Callable, Optional from .base import ACTIONS, RegistryConfigurationError +#: The least class an injected implementation may be registered at without a capability contract. A function +#: this repository did not write gets the benefit of the doubt in the safe direction: assumed consequential. +INJECTED_FLOOR = "write" + +#: The sink vocabulary of the platform's sweep over tools classified ``read`` (agentic-os FR-04), copied +#: literally so Context Runtime stays installable without the platform. Attribute form: a subprocess, a file +#: written, an HTTP verb that is not a fetch. +SINK_ATTRS = frozenset({ + "system", "popen", "Popen", "check_output", "check_call", "call", "run", "spawn", "write_text", + "write_bytes", "writelines", "unlink", "rmtree", "copyfile", "makedirs", "mkdir", "touch", + "post", "put", "delete", "patch", "urlopen", "send", "submit", +}) + +#: Verbs that mean different things on different objects: ``os.remove`` deletes a file, ``rows.remove(x)`` +#: is a list and ``df.rename`` is a dataframe. They count as sinks only when what they are called on names a +#: filesystem — the alternative is a rule that flags ordinary code until people stop reading the classes. +FS_QUALIFIED_ATTRS = frozenset({"remove", "rename", "move", "rmdir", "truncate", "removedirs"}) + +#: The receivers that make a :data:`FS_QUALIFIED_ATTRS` verb a sink. +FS_RECEIVERS = frozenset({"os", "os_path", "shutil", "pathlib", "Path", "path", "fs", "filesystem"}) + +#: Bare-name form of the same vocabulary, again as FR-04 spells it. +SINK_NAMES = frozenset({"open", "_run", "run", "run_cmd", "Popen", "system"}) + +#: Context Runtime's addition, because a registry here is as likely to reach a database as a shell: the +#: transactional verbs that end with something having changed. +SINK_TX_ATTRS = frozenset({"commit", "save", "insert", "upsert", "store"}) + +#: The subset that forces the ``delete`` class rather than merely the floor: filesystem destruction with no +#: innocent reading. ``remove`` and ``delete`` stay in the sink set — enough to refuse a ``read`` claim — but +#: they are not here, because ``items.remove(x)`` and ``session.delete(row)`` are ordinary code that would +#: otherwise be pushed into asking for a delete grant it does not need. Over-declaring is allowed; forcing it +#: on innocent code is what makes people stop reading the classes. +DESTRUCTIVE_ATTRS = frozenset({"unlink", "rmtree", "rmdir"}) + +#: Everything reachable as an attribute, ambiguous verbs included — they are qualified by receiver below. +_ALL_ATTR_SINKS = SINK_ATTRS | SINK_TX_ATTRS | DESTRUCTIVE_ATTRS | FS_QUALIFIED_ATTRS + +#: Values that occupy the place of a reason and carry none. +_BARE_TRUTHY = frozenset({"1", "true", "t", "yes", "y", "on", "enable", "enabled", "pure", "read", + "pure read", "pure_read", "safe", "n/a", "none", "no reason", "todo"}) + + +@dataclass(frozen=True) +class PureRead: + """A caller's contract that an injected implementation is inert — the only claim below the floor. + + Built by :func:`pure_read`; the field is the sentence that makes the claim reviewable. It is a type + rather than a boolean so that lowering a tool's class cannot happen by accident, by a default, or by a + value copied out of an example. + """ + + reason: str + -def resolve_action(*, shipped: str, injected: Optional[object] = None, declared: Optional[str] = None, +def pure_read(reason: str) -> PureRead: + """``read``, claimed deliberately: ``reason`` has to say why the injected implementation touches nothing.""" + text = (reason or "").strip() + if not text: + raise RegistryConfigurationError( + "pure_read() needs a sentence explaining why the injected implementation is a read — what it " + "calls, and why that leaves nothing behind. The reason is what a reviewer reads.") + if text.lower() in _BARE_TRUTHY: + raise RegistryConfigurationError( + f"pure_read({text!r}) is not a reason. Name what the function calls and why that is inert, e.g. " + f'pure_read("formats its arguments into a string; no I/O — reviewed 2026-11-22").') + return PureRead(reason=text) + + +def _source_of(fn: object) -> Optional[str]: + """``fn``'s own source, or ``None`` when it cannot be read (built-in, compiled at run time).""" + try: + return textwrap.dedent(inspect.getsource(fn)) + except (OSError, TypeError, SyntaxError, IndentationError): + return None + + +def _receiver_name(node: ast.AST) -> str: + """The leftmost name of a dotted call target: ``os.path.remove`` -> ``os``, ``rows.remove`` -> ``rows``.""" + while isinstance(node, ast.Attribute): + node = node.value + return node.id if isinstance(node, ast.Name) else "" + + +def write_sinks(fn: Callable[[dict], object]) -> tuple[str, ...]: + """The sinks visible in ``fn``'s own source, nested definitions included; ``()`` if none or unreadable.""" + source = _source_of(fn) + if source is None: + return () + try: + tree = ast.parse(source) + except SyntaxError: # getsource returned something unparseable + return () + found: set[str] = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + if isinstance(func, ast.Attribute): + attr = func.attr + if attr in SINK_ATTRS or attr in SINK_TX_ATTRS or attr in DESTRUCTIVE_ATTRS: + found.add(attr) + elif attr in FS_QUALIFIED_ATTRS and _receiver_name(func.value) in FS_RECEIVERS: + found.add(f"{_receiver_name(func.value)}.{attr}") + elif isinstance(func, ast.Name) and func.id in (SINK_NAMES | SINK_ATTRS | SINK_TX_ATTRS): + found.add(func.id) + return tuple(sorted(found)) + + +def resolve_action(*, shipped: str, injected: Optional[object] = None, declared: Optional[object] = None, param: str = "", tool: str = "", context: str = "") -> str: """The risk class of the function that is actually installed, which is not always the shipped one's. - ``shipped`` is the class this file reviewed for the implementation it ships; ``injected`` is the - caller's replacement function, or ``None`` when they took the shipped one; ``declared`` is the class - the caller says their own function deserves, via the tenant's ``*_action`` keyword. + ``shipped`` is the class reviewed here for the implementation this file ships; ``injected`` is the + caller's replacement, or ``None`` when they took the shipped one; ``declared`` is what the caller asked + for through the tenant's ``*_action`` keyword — a class at or above :data:`INJECTED_FLOOR`, or + :func:`pure_read` to claim less. - Nothing injected returns ``shipped`` untouched. Something injected returns ``declared`` — and raises - :class:`~context_runtime.tools.base.RegistryConfigurationError` when it is missing, because "the - simulation was a read" is not evidence about a function this repository has never seen. A value - outside :data:`~context_runtime.tools.base.ACTIONS` raises the same way, on either side: a typo is not - a risk class, and a wrong class is worse than no class, because an unclassified tool is matched by no - grant and so is denied at every call, while a wrongly-classified one runs on someone else's permission. + Nothing injected returns ``shipped`` untouched, so a shipped pure implementation keeps the ``read`` it was + audited at. Something injected is where the discipline lives: + + * **no declaration** → refused. A class is not inherited from the tool that occupied the slot. + * **``"read"`` as a plain word** → refused. Below the floor is a claim that has to be made deliberately, + in the type built for it. + * **``pure_read(...)``** → refused unless the reason is a sentence, the source can be read, and + :func:`write_sinks` finds nothing in it. Evidence beats a declaration: nobody registers a below-the-floor + class over a visible ``post``, and nobody gets one for a function whose source cannot be read. + * **a destructive sink under ``delete``** → refused, for the same reason. + * **over-declaring** is always allowed: asking for more authority than a call needs can only ever deny it. """ where = f"{tool} ({context})" if tool and context else (tool or context or "this tool") param = param or f"{tool.rsplit('.', 1)[-1] if tool else 'tool'}_action" if shipped not in ACTIONS: raise RegistryConfigurationError( - f"{where}: the shipped risk class {shipped!r} is not one of the vocabulary {ACTIONS} — a bug " - f"in this integration, not a value a caller can supply.") + f"{where}: the shipped risk class {shipped!r} is not one of the vocabulary {ACTIONS} — a bug in " + f"this integration, not a value a caller can supply.") if injected is None: return shipped - if declared is None: + + claim = declared + if isinstance(claim, PureRead): + claimed = "read" + elif isinstance(claim, str): + if claim == "read": + raise RegistryConfigurationError( + f"{where}: {param}='read' is below the floor for a function injected into this slot. " + f"Something replaced the implementation this file audited, so it is registered as " + f"'{INJECTED_FLOOR}' unless its author contracts that it is inert: {param}=" + f'pure_read("what it calls, and why that leaves nothing behind").') + claimed = claim + elif claim is None: raise RegistryConfigurationError( - f"{where}: a function was injected in place of the implementation shipped here, and a risk " - f"class is not inherited from the tool it replaces. Pass {param}=... — one of {ACTIONS} — for " - f"what the injected function actually does. If it fetches, posts, stores or launches anything, " - f"that is not {shipped!r}.") - if declared not in ACTIONS: + f"{where}: a function was injected in place of the implementation shipped here, and a risk class " + f"is not inherited from the tool it replaces. Pass {param}=... — '{INJECTED_FLOOR}' or 'delete', " + f"or {param}=pure_read(...) for an implementation you have read and can argue is inert.") + else: + raise RegistryConfigurationError( + f"{where}: {param}={claim!r} is neither a risk class in {ACTIONS} nor a pure_read(...) contract.") + + if claimed not in ACTIONS: + raise RegistryConfigurationError( + f"{where}: {param}={claimed!r} is not one of the vocabulary {ACTIONS}.") + + sinks = write_sinks(injected) + if claimed == "read": + if _source_of(injected) is None: + raise RegistryConfigurationError( + f"{where}: {param}=pure_read(...) cannot be honoured for a function whose source is not " + f"readable (a built-in or something compiled at run time): there is nothing to check the " + f"claim against. Register it as '{INJECTED_FLOOR}'.") + if sinks: + raise RegistryConfigurationError( + f"{where}: {param}=pure_read(...) claims this injected function is inert, and its own source " + f"disagrees — it reaches {list(sinks)}. A call that leaves the process or changes state is " + f"not a read: register it as '{INJECTED_FLOOR}' (or 'delete'), whatever it is named.") + destructive = tuple(sorted(s for s in sinks if s in DESTRUCTIVE_ATTRS)) + if destructive and ACTIONS.index(claimed) < ACTIONS.index("delete"): raise RegistryConfigurationError( - f"{where}: {param}={declared!r} is not one of the vocabulary {ACTIONS}.") - return declared \ No newline at end of file + f"{where}: {param}={claimed!r} understates what this injected function does — it reaches " + f"{list(destructive)}, which is the 'delete' class. Over-declare rather than under-declare.") + return claimed \ No newline at end of file diff --git a/tests/test_injected_tool_classification.py b/tests/test_injected_tool_classification.py index 252311a..3003666 100644 --- a/tests/test_injected_tool_classification.py +++ b/tests/test_injected_tool_classification.py @@ -1,15 +1,20 @@ -"""A replaced implementation carries its own risk class, or the tenant refuses to start. - -Every integration tenant here ships a local simulation of one tool — it builds a string and hands it back, -so the class it was reviewed at is ``read`` (``market_radar`` is the exception: a sweep fetches and stores, -so it is ``write``). Each tenant also exposes a ``*_tool_factory`` hook that replaces that simulation with -code this repository has never seen. Until now the class did not move with the code: pass a factory that -posts to a vendor and the tool stayed registered as ``read``, which means a principal holding only a read -grant could run it. That is the downgrade this file exists to keep closed. - -The rule being pinned is the one ``resolve_action`` implements: the class describes the effect of the -function that actually runs. Nothing injected, the reviewed class stands. Something injected, whoever read -their own function says what it is — and construction refuses instead of inheriting. +"""An injected implementation earns its class: a floor by default, a contract to get under it. + +Every integration tenant ships a local simulation of one tool — it builds a string and hands it back, so the +class it was reviewed at is ``read`` (``market_radar`` is the exception: a sweep fetches and stores, so it is +``write``). Each tenant also exposes a ``*_tool_factory`` hook that replaces that simulation with code this +repository has never seen. Two failures were possible there, and they are the same failure — the code asking +to run grading its own risk: + +* **inherited** — pass a factory and the tool stayed registered at the shipped simulation's class, so a + function that posts to a vendor ran on a principal holding only a read grant; +* **self-declared** — let the caller simply say ``read`` and nothing has been gained, only moved. + +So an injected function sits at a floor of ``write``, and the only way below it is :func:`pure_read`, whose +argument has to be a sentence about why the function is inert — checked against the function's own source, +using the sink vocabulary the platform's FR-04 sweep uses. A visible ``post`` beats any declaration, and so +does a visible ``rmtree`` one class lower. The shipped simulations keep the ``read`` they were audited at: +this file exists to prove that ``draft_caption`` really is one. """ from __future__ import annotations @@ -19,6 +24,7 @@ from agent_harness.tools import Authorization +from context_runtime.tools import pure_read from context_runtime.tools.base import RegistryConfigurationError, ToolResult #: module, tenant class, factory hook, the class-declaring keyword, registered tool, reviewed class. @@ -40,6 +46,7 @@ _IDS = [f"{mod}.{tool}" for mod, _, _, _, tool, _ in TENANTS] _REASON = "offline audit of the injected-factory seam" +_INERT_REASON = "formats its arguments into a string; no I/O — reviewed 2026-11-22" def _tenant(module: str, cls: str, **kwargs): @@ -47,73 +54,201 @@ def _tenant(module: str, cls: str, **kwargs): local_trust=True, local_trust_reason=_REASON, **kwargs) -def _vendor_call(args: dict) -> ToolResult: - """Stand-in for the thing an integrator actually swaps in: it leaves the process.""" - return ToolResult(ok=True, text="posted to a vendor") +# ─────────── three injected implementations, one per kind of claim ─────────── + + +def _inert(args: dict) -> ToolResult: + """Builds a string out of its arguments. Nothing here leaves the process.""" + return ToolResult(ok=True, text=f"[{args.get('channel', 'channel')}] drafted locally") + + +class _VendorClient: + def post(self, path: str, payload: dict) -> dict: + return {"id": "remote-draft"} + + +def _vendor_post(args: dict) -> ToolResult: + """What an integrator actually swaps in: the arguments go off to a remote service.""" + return ToolResult(ok=True, text=str(_VendorClient().post("/captions", args))) + + +class _Disk: + def rmtree(self, path: str) -> None: + return None + + +def _wipes(args: dict) -> ToolResult: + """A tool named for tidiness. Nothing in the name says delete; the call does.""" + _Disk().rmtree(args.get("path", "/tmp/nothing")) + return ToolResult(ok=True, text="removed") def _read_only_plane(principal, spec, args): - """A permissions plane that granted ``read`` and nothing else — the principal this test cares about.""" + """A permissions plane that granted ``read`` and nothing else — the principal this file is about.""" if spec.action != "read": return f"no '{spec.action}' grant for this principal" return Authorization.allow(grant_ids=("role:reader",), plane="permissions") +# ───────────────────────── the shipped implementations ───────────────────────── + + @pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) def test_the_shipped_implementation_keeps_the_class_it_was_reviewed_at(module, cls, factory, action_kw, tool, shipped): - tenant = _tenant(module, cls) - assert tenant.registry.get(tool).spec().action == shipped + """The pure built-ins are not made to defend themselves: ``draft_caption`` is a read, and stays one.""" + assert _tenant(module, cls).registry.get(tool).spec().action == shipped + + +def test_the_shipped_caption_is_actually_inert_not_just_labelled_inert(): + """A class is only worth having if the function behind it does what the class says.""" + social = importlib.import_module("context_runtime.integrations.social_autopilot") + result = social._draft_caption({"goal": "g", "channel": "linkedin", "tone": "bold", "format": "post"}) + assert result.ok and result.data["channel"] == "linkedin" + + +# ─────────────────────────── the floor: no guessing ─────────────────────────── @pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) def test_a_replacement_without_a_class_of_its_own_refuses_to_start(module, cls, factory, action_kw, tool, shipped): - """No silent inheritance: the integrator that swapped the function is the one who has to grade it.""" with pytest.raises(RegistryConfigurationError) as exc: - _tenant(module, cls, **{factory: _vendor_call}) + _tenant(module, cls, **{factory: _vendor_post}) message = str(exc.value) - assert action_kw in message # it names the parameter that answers the question - assert tool in message # and the tool the answer is about + assert action_kw in message and tool in message # names the keyword and the tool it is about + assert "pure_read" in message # and how to claim below the floor @pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) -def test_a_replacement_declares_its_own_class(module, cls, factory, action_kw, tool, shipped): - tenant = _tenant(module, cls, **{factory: _vendor_call, action_kw: "write"}) - spec = tenant.registry.get(tool).spec() - assert spec.action == "write" +def test_a_replacement_declared_at_or_above_the_floor_is_registered_as_declared(module, cls, factory, action_kw, + tool, shipped): + tenant = _tenant(module, cls, **{factory: _vendor_post, action_kw: "write"}) + assert tenant.registry.get(tool).spec().action == "write" @pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) def test_a_class_outside_the_vocabulary_refuses_to_start(module, cls, factory, action_kw, tool, shipped): """A typo is not a risk class — and neither is a word invented for one tool.""" with pytest.raises(RegistryConfigurationError): - _tenant(module, cls, **{factory: _vendor_call, action_kw: "generate"}) + _tenant(module, cls, **{factory: _vendor_post, action_kw: "generate"}) -def test_a_replaced_caption_no_longer_runs_on_a_read_grant(): - """The end of the story: the class is what a grant is matched against, so this is the denial that matters. +# ───────────── intentional misclassification: the part that matters ───────────── + + +@pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) +def test_an_injected_function_cannot_claim_read_by_saying_read(module, cls, factory, action_kw, tool, shipped): + """The word is the downgrade. Below the floor has to be a deliberate claim, in its own type.""" + with pytest.raises(RegistryConfigurationError) as exc: + _tenant(module, cls, **{factory: _inert, action_kw: "read"}) + assert "below the floor" in str(exc.value) and "pure_read" in str(exc.value) + + +@pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) +def test_a_function_reaching_a_sink_cannot_be_registered_as_a_read(module, cls, factory, action_kw, tool, + shipped): + """A contract the source contradicts is refused, and the refusal names the sink.""" + with pytest.raises(RegistryConfigurationError) as exc: + _tenant(module, cls, **{factory: _vendor_post, action_kw: pure_read(_INERT_REASON)}) + message = str(exc.value) + assert "post" in message and "not a read" in message + - ``draft_caption`` simulated is a read and runs for a read-only principal. The same tool with a real - generator behind it, declared as such, does not — while an integrator who genuinely replaced it with - another pure function can still declare ``read`` and keep working. +def test_a_deleting_function_cannot_hide_one_class_below_delete(): + """The same under-declaration one rung lower: a ``rmtree`` registered as ``write`` still loses data.""" + with pytest.raises(RegistryConfigurationError) as exc: + _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_wipes, + caption_action="write") + assert "rmtree" in str(exc.value) and "delete" in str(exc.value) + + strict = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_wipes, + caption_action="delete") + assert strict.registry.get("draft_caption").spec().action == "delete" + + +def test_a_function_with_no_readable_source_cannot_claim_read(): + """No source, no evidence, no waiver: an unreadable callable is assumed consequential.""" + with pytest.raises(RegistryConfigurationError) as exc: + _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=len, + caption_action=pure_read("a built-in that reads nothing at all")) + assert "source" in str(exc.value) + + +def test_a_verb_counts_as_a_sink_when_the_object_it_is_called_on_says_so(): + """``os.remove`` deletes a file; ``rows.remove(x)`` is a list. One of these is not a write. + + The ambiguous verbs — remove, rename, move — are sinks when the receiver names a filesystem and ordinary + code otherwise. A rule that flags every ``.remove(`` is a rule that trains integrators to declare + ``write`` without reading anything, which is the thing being defended against. """ - shipped = _tenant("social_autopilot", "SocialAutopilotTenant") + import importlib + + actions = importlib.import_module("context_runtime.tools.actions") + + def removes_a_file(args): + import os + os.remove(args.get("path", "/tmp/none")) + return ToolResult(ok=True, text="gone") + + def removes_a_row(args): + rows = list(args.get("rows", [])) + if rows: + rows.remove(rows[0]) + return ToolResult(ok=True, text=str(rows)) + + assert any("os.remove" in sink for sink in actions.write_sinks(removes_a_file)) + assert actions.write_sinks(removes_a_row) == () + + with pytest.raises(RegistryConfigurationError): + _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=removes_a_file, + caption_action=pure_read(_INERT_REASON)) + inert = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=removes_a_row, + caption_action=pure_read("pops the first row off a local list; no I/O — reviewed 2026-11-22")) + assert inert.registry.get("draft_caption").spec().action == "read" + + +def test_the_capability_contract_refuses_a_reason_that_says_nothing(): + """The reason is the reviewable part. A flag wearing a sentence's clothes is what it replaced.""" + for empty in ("", " ", "true", "yes", "1", "pure", "safe", "n/a"): + with pytest.raises(RegistryConfigurationError): + pure_read(empty) + assert pure_read(_INERT_REASON).reason == _INERT_REASON + + +def test_a_declared_pure_read_contract_survives_construction(): + """The object that crosses the seam is the contract itself, not a string someone can typo.""" + from context_runtime.tools import PureRead + + assert PureRead is not None and pure_read(_INERT_REASON).reason == _INERT_REASON + + +# ─────────── and the decision the class is actually matched against ─────────── + + +def test_an_inert_injected_function_contracted_down_to_read_runs_for_a_read_only_principal(): + tenant = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_inert, + caption_action=pure_read(_INERT_REASON), authorizer=_read_only_plane) + assert tenant.registry.get("draft_caption").spec().action == "read" + assert tenant.registry.run("draft_caption", {"goal": "g", "channel": "linkedin"}).ok + + +def test_a_replaced_caption_no_longer_runs_on_a_read_grant(): + """The end of the story: the class is what a grant is matched against, so this is the denial that matters.""" + shipped = _tenant("social_autopilot", "SocialAutopilotTenant", authorizer=_read_only_plane) assert shipped.registry.run("draft_caption", {"goal": "g", "channel": "linkedin"}).ok - # ^ that tenant ran on the declared local authority; the two below name the plane, the way a - # deployment does, because the grant is the thing under test. - live = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_vendor_call, + live = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_vendor_post, caption_action="write", authorizer=_read_only_plane) denied = live.registry.run("draft_caption", {"goal": "g", "channel": "linkedin"}) assert not denied.ok and "no 'write' grant" in (denied.error or "") assert live.registry.audit[-1]["allowed"] is False - # and the shipped read-only simulation still runs for that same read-only principal - assert _tenant("social_autopilot", "SocialAutopilotTenant", - authorizer=_read_only_plane).registry.run( - "draft_caption", {"goal": "g", "channel": "linkedin"}).ok - pure = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_vendor_call, - caption_action="read", authorizer=_read_only_plane) - assert pure.registry.run("draft_caption", {"goal": "g", "channel": "linkedin"}).ok \ No newline at end of file +def test_an_unclassified_replacement_matches_no_grant_and_is_denied_everywhere(): + """What a registration that goes around the seam still cannot do: an empty class matches no grant.""" + from context_runtime.tools.base import ToolRegistry, function_tool + + registry = ToolRegistry(authorizer=_read_only_plane) + registry.register(function_tool("unclassified_thing", lambda a: ToolResult(ok=True, text="ran"), action="")) + assert not registry.run("unclassified_thing", {}).ok \ No newline at end of file From 9cee74741bcb21a47ac2c6512427c81a662eff61 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 14:38:01 -0500 Subject: [PATCH 12/15] build: the harness pin moves to the commit that carries the twin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The four places that name a harness commit (pyproject and the three Dockerfiles) move together from `7e422f5` to `10e5c2a`. The extra commit is not this repository's own code path — Context Runtime never calls `engine_authorizer_of` — it is what the engine does with what this repository hands it: a tenant that names no authorizer inherits the process default, and at the previous pin a registry reads a platform plane's "allowed" as silence and denies the call it was just granted. Pinning past the last symbol this repository imports is deliberate, and the comment next to the dependency now says so. The archive hashes are the sha256 of each commit's GitHub source archive. The method was checked against the pin it replaces: downloading `7e422f5` reproduces `231eef6b…`, the value these lines carried, and `10e5c2a` hashes identically across two fetches. Co-Authored-By: Cline --- Dockerfile | 4 ++-- deploy/geo-demo/Dockerfile.aks | 4 ++-- deploy/proxmox-demo/Dockerfile.contextruntime | 4 ++-- pyproject.toml | 6 +++++- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/Dockerfile b/Dockerfile index 26071d4..5567af0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,8 +14,8 @@ RUN pip install --no-cache-dir "fastapi>=0.110" "uvicorn>=0.29" "httpx>=0.27" "p # application does not import without it. Pinned to the same commit as pyproject.toml, from the commit's # source archive (no git in this image) and verified against the archive's sha256. # tests/test_container.py checks that this commit equals the one in pyproject.toml. -ARG AGENT_HARNESS_COMMIT=7e422f541fc480e4c0cbb8d25789cdae359a9d46 -ARG AGENT_HARNESS_SHA256=231eef6b8877127bf61834e271707cab6c28411e6a7b6236210a44a6704612a8 +ARG AGENT_HARNESS_COMMIT=10e5c2ae7419e096630fb031ef8204fede125ec9 +ARG AGENT_HARNESS_SHA256=1d3dc387512a068556fb7bd3e49bf63fbf8e6dc263368b02c00ac4bcb7b7f200 RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}" ENV PYTHONPATH=/app diff --git a/deploy/geo-demo/Dockerfile.aks b/deploy/geo-demo/Dockerfile.aks index e9be383..9d750cc 100644 --- a/deploy/geo-demo/Dockerfile.aks +++ b/deploy/geo-demo/Dockerfile.aks @@ -27,8 +27,8 @@ RUN pip install --no-cache-dir -r /tmp/requirements.txt # context_runtime imports agent-harness (its tool contract) at import time, so the application does not start without it. # Pinned to the same commit as the repository's own Dockerfile and pyproject.toml, from the commit's source archive (no git in # this image) and verified against the archive's sha256. tests/test_geo_image.py keeps these two lines equal to the root Dockerfile. -ARG AGENT_HARNESS_COMMIT=7e422f541fc480e4c0cbb8d25789cdae359a9d46 -ARG AGENT_HARNESS_SHA256=231eef6b8877127bf61834e271707cab6c28411e6a7b6236210a44a6704612a8 +ARG AGENT_HARNESS_COMMIT=10e5c2ae7419e096630fb031ef8204fede125ec9 +ARG AGENT_HARNESS_SHA256=1d3dc387512a068556fb7bd3e49bf63fbf8e6dc263368b02c00ac4bcb7b7f200 RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}" FROM ${PYTHON_IMAGE} diff --git a/deploy/proxmox-demo/Dockerfile.contextruntime b/deploy/proxmox-demo/Dockerfile.contextruntime index 8c2ebd5..2271466 100644 --- a/deploy/proxmox-demo/Dockerfile.contextruntime +++ b/deploy/proxmox-demo/Dockerfile.contextruntime @@ -8,8 +8,8 @@ RUN pip install --no-cache-dir \ # agent-harness is a base dependency of context_runtime (the application does not import without it); same # commit and archive hash as the top-level Dockerfile and pyproject.toml. -ARG AGENT_HARNESS_COMMIT=7e422f541fc480e4c0cbb8d25789cdae359a9d46 -ARG AGENT_HARNESS_SHA256=231eef6b8877127bf61834e271707cab6c28411e6a7b6236210a44a6704612a8 +ARG AGENT_HARNESS_COMMIT=10e5c2ae7419e096630fb031ef8204fede125ec9 +ARG AGENT_HARNESS_SHA256=1d3dc387512a068556fb7bd3e49bf63fbf8e6dc263368b02c00ac4bcb7b7f200 RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}" COPY context_runtime /app/context_runtime diff --git a/pyproject.toml b/pyproject.toml index 7850eb3..edf2bbb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,9 +10,13 @@ license = { text = "AGPL-3.0-or-later WITH Commons-Clause" } # The floor is the commit that puts the risk class on the registration: the integrations pass action= to # ToolSpec and call registry.classification()/validate(), and tools/authz.py hands the registry a plane built # from Authorization/PolicyReason — all of which arrive with the authz line (C1 fail-closed, C2 risk class). +# It then has to reach the commit that adds engine_authorizer_of: a tenant that names no authorizer inherits +# the process default, and below that commit the registry reads a platform plane's "allowed" as silence and +# denies the call it was just granted. The pin is one commit past the last thing this repository calls, +# because what it depends on now is what the engine does with what it was handed. dependencies = [ "pyyaml>=6.0", - "agent-harness @ git+https://github.com/redevops-io/agent-harness.git@7e422f541fc480e4c0cbb8d25789cdae359a9d46", + "agent-harness @ git+https://github.com/redevops-io/agent-harness.git@10e5c2ae7419e096630fb031ef8204fede125ec9", ] [project.optional-dependencies] From 20848722b335ae1045c69b0e20df8a8b9f03e669 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 18:47:32 -0500 Subject: [PATCH 13/15] refuse by default: delegation needs an authorizer, and so does a privileged service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two owner decisions, one rule underneath them: the code that wants to run does not get to decide the thing that lets it run. This changes both places where it was deciding. **Delegation had a floor, and a floor is a self-grant.** An injected implementation sat at `write` unless its author contracted lower. That looked conservative and behaved like an authorization: the caller picked the class in passing, in the same statement that swapped foreign code into a slot, and nobody who could be named stood behind it. `INJECTED_FLOOR` is gone. `delegated(action=…, authority=…, via=…, review=…)` is the only way a delegated callable is registered now — the class, who authorized it, what it hands its arguments to, and the review that connects the two. A bare class string, in either direction, is refused; so is a label where a sentence belongs (`authority="SEC-41"` names a ticket, not a decision, and tickets close). `read` cannot be bought with prose at all: a weak class is earned from the source, never asserted about it. **The blind spot the floor was covering, closed.** The sink sweep reads the callable's own body, so a wrapper that hands its arguments to a client object it did not build showed nothing — no `post`, no `write_text` — and a `pure_read` claim about it used to be checked and pass. `opaque_callees` now refuses a claim it cannot follow: every callee root must be a parameter, a local, a builtin, or an entry of `INERT_ROOTS`. Evidence still beats declaration in both directions: an authorized delegation is refused if the wrapper's own source reaches a `rmtree` while asking for `write`. **A privileged service with no plane no longer boots.** `fleet.py` used to warn and stand up anyway, with the argument that "a process that boots and denies is diagnosable, one that refuses to start is not". That argument is overruled: a fleet that denies every call looks exactly like a healthy one on `/status`, and silence was the failure this migration exists to remove. `require_plane()` runs before anything executes; the escape is not a warning but a mode — `CR_EXECUTION_MODE=diagnostic` with a written reason — in which privileged execution is structurally absent: the fleet builds no tenants, `up`/`dispatch`/`agent-run` answer 503, an agent console registers no tools and refuses `mount_mcp`, and `/health` says which instance it is. `on_missing="deny_later"` is refused for a registry that can execute; a component that is built before its plane exists (a console an app imports before its gate installs) says so with `on_missing="defer_to_plane"`, and the application that owns it remains obliged to gate readiness. **Compatibility, stated rather than softened.** Deployments that launch the control plane without a plane installed now exit with the three ways out in the message; the demo compose stacks need either a plane or `CR_EXECUTION_MODE=diagnostic` + `CR_DIAGNOSTIC_REASON`. `/health` gained two keys (`mode`, `privileged_execution`) and the two tests that pinned the body to `{"status": "ok"}` now pin the key set, because "the public route discloses nothing" could not survive coexisting with "a deny-only instance must not look healthy". `mount_mcp` lost its `default_action="write"` and mounts nothing for a tool nobody classed; call sites now name the class or say so once with an explicit default. Co-Authored-By: Cline --- context_runtime/control_plane/app.py | 41 ++- context_runtime/control_plane/fleet.py | 64 ++-- context_runtime/integrations/agent_console.py | 69 ++-- context_runtime/integrations/modules.py | 15 +- context_runtime/integrations/runtime_scan.py | 5 +- context_runtime/tools/__init__.py | 28 +- context_runtime/tools/actions.py | 280 ++++++++++++---- context_runtime/tools/authz.py | 130 +++++++- context_runtime/tools/mcp.py | 29 +- tests/conftest.py | 32 ++ tests/test_authorization_negative_controls.py | 298 ++++++++++++++++++ tests/test_container.py | 165 ++++++++-- tests/test_control_plane.py | 10 +- tests/test_control_plane_access.py | 10 +- tests/test_demo_proxy.py | 10 +- tests/test_injected_tool_classification.py | 124 +++++++- tests/test_mcp.py | 7 +- tests/test_mcp_actions.py | 18 +- tests/test_platform_services.py | 5 +- tests/test_web_search_mcp.py | 4 +- 20 files changed, 1154 insertions(+), 190 deletions(-) create mode 100644 tests/test_authorization_negative_controls.py diff --git a/context_runtime/control_plane/app.py b/context_runtime/control_plane/app.py index 5985e52..f94b3cd 100644 --- a/context_runtime/control_plane/app.py +++ b/context_runtime/control_plane/app.py @@ -199,8 +199,13 @@ def _build() -> Fleet: CORSMiddleware, allow_origins=[o.strip() for o in _cors if o.strip()], allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["*"], ) +# Building the fleet is the authorization gate: a privileged fleet that cannot name a plane to ask raises here, +# so the container exits instead of serving a dashboard over a fleet whose every call is denied. A fleet +# declared diagnostic (CR_EXECUTION_MODE=diagnostic, with a written reason) comes up and is built without an +# execution path — no tenants, so /up, /dispatch and /agent/run have nothing to fall back to. fleet = _build() -fleet.up() # (b) stand up every module as a Context Runtime tenant → deployed +if fleet.privileged: + fleet.up() # (b) stand up every module as a Context Runtime tenant → deployed # Hermes 0.17 inbound chatops gateway — daemon thread, started only if a channel # is configured (closed by default; honors AGENTIC_OS_GATEWAY_ALLOW / _OPEN). _gateway = channels.Gateway(fleet) @@ -490,8 +495,32 @@ def dashboard() -> str: @app.get("/health") def health() -> dict: - """Liveness only. The one unauthenticated route; it discloses nothing about the deployment.""" - return {"status": "ok"} + """Liveness, plus the one fact that stops a deny-only instance being read as a working one. + + It used to answer ``{"status": "ok"}`` and nothing else, on the grounds that a public route should + disclose nothing about the deployment. That held until the fleet could stand up with no authorization plane + and keep answering this endpoint while every tool call came back denied — the dashboard's green tick was + then indistinguishable from the outage it was supposed to detect. Two booleans are disclosed, both derived + from this process's own start-up decision: no paths, no tenants, no configuration, no module names. + """ + return {"status": "ok", "mode": "diagnostic" if not fleet.privileged else "execute", + "privileged_execution": fleet.privileged} + + +def require_execution() -> None: + """Refuse, before the handler runs, on the routes that would make a diagnostic instance execute. + + The handlers would fail anyway — there are no tenants — but a 500 from inside ``fleet.up()`` reads like a + crash, and this state is not a crash: it is a deployment that said what it is. 503 says so, and says what + to change. + """ + if not fleet.privileged: + raise HTTPException(503, "this control plane is running in the diagnostic mode (no authorization plane " + "was installed, so privileged execution is not available in it). To run " + "actions, start the execution instance: install a plane with " + "context_runtime.tools.set_default_authorizer(...) before the control plane " + "imports, or declare local authority with CR_LOCAL_AUTHORITY=\"why this " + "process may act as the operator\".") @app.get("/modules", response_model=list[ModuleList]) @@ -505,7 +534,7 @@ def status() -> list[dict]: return [asdict(s) for s in fleet.status()] -@app.post("/up", dependencies=[Depends(require_api_key)]) +@app.post("/up", dependencies=[Depends(require_api_key), Depends(require_execution)]) def up(names: list[str] | None = None) -> list[dict]: return [asdict(s) for s in fleet.up(*(names or []))] @@ -539,7 +568,7 @@ class DispatchRequest(BaseModel): background: bool = False -@app.post("/dispatch", dependencies=[Depends(require_api_key)]) +@app.post("/dispatch", dependencies=[Depends(require_api_key), Depends(require_execution)]) def dispatch(req: DispatchRequest) -> dict: """Run one agent action through the fleet (router-picked model). @@ -988,7 +1017,7 @@ class RunRequest(BaseModel): question: str -@app.post("/agent/run", dependencies=[Depends(require_api_key)]) +@app.post("/agent/run", dependencies=[Depends(require_api_key), Depends(require_execution)]) def agent_run(req: RunRequest) -> dict: """Plan a module's answer through its Context Runtime tenant (no side effects).""" try: diff --git a/context_runtime/control_plane/fleet.py b/context_runtime/control_plane/fleet.py index e3b621d..ecce945 100644 --- a/context_runtime/control_plane/fleet.py +++ b/context_runtime/control_plane/fleet.py @@ -20,8 +20,12 @@ from ..integrations.modules import CATALOG, ModuleSpec, ModuleTenant from ..platform_services import ensure_private_dir, state_dir from ..runtime.runtime import ContextRuntime -from ..tools.authz import local_authority_from_env -from ..tools.base import default_authorizer_installed +from ..tools.authz import ( + DIAGNOSTIC, + PrivilegedExecutionUnavailable, + execution_mode, + require_plane, +) from .context import Approval, Context from .registry import Module, Registry @@ -35,31 +39,20 @@ } -#: the "no plane" fact is a start-up fact: it is said once per process, not once per module up/down. -_PLANE_WARNING_SHOWN = False +#: Recorded once per process so /health can say what this fleet was allowed to become. It is a start-up fact, +#: which is exactly why it is no longer a warning: see ``require_plane``. +_MODE: tuple[str, str] | None = None -def _warn_if_no_plane() -> None: - """Say once, at the moment it is cheap to act on, that this fleet stands up with no authorization plane. +def mode() -> tuple[str, str]: + """``("execute", "")`` or ``("diagnostic", reason)`` for this fleet — decided once, at construction. - The fleet is a long-lived, request-facing surface, so it follows the same rule as ``AgentConsole`` rather - than the tenants' own: standing a module up with no plane yet installed is a start-up the operator can - still fix — an embedding application installs its gate a moment after this import — whereas refusing to - import is a container that never answers ``/health``. It is not a grant: with no plane every tool call - comes back ``missing_authorizer``. Silence is the failure mode this migration exists to remove, because a - fleet that denies every tool call looks exactly like a healthy one on ``/status``. + The control plane is a privileged execution service: it stands up tenants whose tools block IPs, file + tickets and bill customers. It therefore refuses to come up at all with nothing to ask, and the only + instance of it that may boot without a plane is one where execution has been taken out of the build — + no tenants, no dispatch, nothing for a missing grant to be about. """ - global _PLANE_WARNING_SHOWN - if _PLANE_WARNING_SHOWN or default_authorizer_installed() or local_authority_from_env()[0]: - return - _PLANE_WARNING_SHOWN = True - warnings.warn( - "the module fleet is standing up with no authorization plane: every tool call its tenants make is " - "denied (missing_authorizer) until the embedding application installs one with " - "context_runtime.tools.set_default_authorizer(...), or the process declares local authority with " - 'CR_LOCAL_AUTHORITY="why this process is trusted". The fleet still serves /health and /status on ' - "purpose: a process that boots and denies is diagnosable, one that refuses to start is not.", - stacklevel=3) + return _MODE if _MODE is not None else execution_mode(context="module fleet") def spec_for(m: Module) -> ModuleSpec: @@ -90,8 +83,16 @@ class ModuleStatus: class Fleet: def __init__(self, registry: Registry, router=None, context: Context | None = None, - workdir=None, runtime: ContextRuntime | None = None, home: str | None = None): + workdir=None, runtime: ContextRuntime | None = None, home: str | None = None, + privileged: bool | None = None): + global _MODE self.registry = registry + # Decided once, here, before anything can run: a privileged fleet refuses construction without a plane + # (``require_plane``), a diagnostic one comes up and is handed nothing to execute with. + _MODE = execution_mode(context="module fleet") + self.privileged = (_MODE[0] != DIAGNOSTIC) if privileged is None else privileged + if self.privileged: + require_plane(context="module fleet") self.router = router # kept for app compatibility; unused self.home = Path(home) if home else state_dir() # persistence root (the /data volume in a container) self.context = context or Context(ensure_private_dir(self.home)) @@ -109,16 +110,20 @@ def _names(self) -> list[str]: # --- lifecycle --- def up(self, *names: str) -> list[ModuleStatus]: + if not self.privileged: + raise PrivilegedExecutionUnavailable( + "this fleet is diagnostic: it does not stand modules up. It exists to show a fleet that has no " + "execution path — no tenants, no tool registry, nothing a missing grant could be about — and " + "standing one up would be the moment it silently became an execution service again. Run the " + "execution instance for that.") out = [] - _warn_if_no_plane() for n in (names or self._names()): m = self.registry.get(n) # the fleet gates approvals (via Context); the tenant's own tools default-deny. # each tenant's learned policy persists to the /data volume → survives restarts. self.tenants[n] = ModuleTenant( spec_for(m), runtime=self.runtime, approver=lambda a: False, - persist_path=str(self.home / "bandits" / f"{n}.json"), - authorizer_on_missing="deny_later") + persist_path=str(self.home / "bandits" / f"{n}.json")) self._up.add(n) out.append(ModuleStatus(n, True, m.agents, "context-runtime tenant")) return out @@ -139,6 +144,11 @@ def status(self) -> list[ModuleStatus]: # --- dispatch (now a Context Runtime plan, not a raw model call) --- def dispatch(self, module_name: str, agent: str, action: str, prompt: str, capability: str = "reason", background: bool = False) -> Approval | dict: + if not self.privileged: + raise PrivilegedExecutionUnavailable( + f"dispatch({module_name}/{action}) is refused: this fleet is diagnostic, so it has no tenants " + f"and no tool path behind them. A diagnostic instance answers questions about a fleet; it does " + f"not act as one.") m = self.registry.get(module_name) if agent not in m.agents: raise ValueError(f"module {module_name} has no agent {agent!r} (agents: {m.agents})") diff --git a/context_runtime/integrations/agent_console.py b/context_runtime/integrations/agent_console.py index f39ee0a..126deb9 100644 --- a/context_runtime/integrations/agent_console.py +++ b/context_runtime/integrations/agent_console.py @@ -31,11 +31,17 @@ import re from collections import Counter from dataclasses import dataclass -from typing import Any, Callable +from typing import Any, Callable, Optional from ..adapters.model_openai import OpenAICompatibleModel from ..adapters.model_stub import StubModel -from ..tools.authz import RegistryConfigurationError, resolve_authorizer +from ..tools.authz import ( + DIAGNOSTIC, + PrivilegedExecutionUnavailable, + RegistryConfigurationError, + execution_mode, + resolve_authorizer, +) from ..tools.base import (ACTIONS, ApprovalPolicy, ToolRegistry, ToolResult, ToolSpec, ValidationReport, default_authorizer_installed) from ..types import ModelRequest @@ -198,6 +204,7 @@ def __init__( commands=None, policy=None, app: str = "", + privileged: Optional[bool] = None, ): self.tenant = tenant self.subtitle = subtitle or f"Ask about {tenant} — how things work, or get something done." @@ -209,17 +216,18 @@ def __init__( # as ``authorizer``, otherwise it inherits the process-wide plane installed with # set_default_authorizer, so one install() governs every console (tools/authz.py). # - # ``on_missing="deny_later"`` is the one place this module resolves differently from a tenant. A - # tenant owns its registry, so a missing plane is a build-time bug and construction refuses. A console - # is usually built at module import inside an app whose gate installs the plane a moment later or per - # request, and refusing to import an app is a worse failure than the console answering every tool call - # with ``missing_explicit_grant`` — which is what it does, because the registry itself fails closed. - # The console says so once, in the log, and ``validate()`` turns it into a start-up failure for an app - # that wants one. + # ``on_missing="defer_to_plane"`` is the one place this module resolves differently from a tenant, and + # the distinction is the whole point of it: a console is a COMPONENT, not a service. An app builds one + # at module import and its gate installs the plane moments later, so refusing to build here refuses to + # import an app that was about to be configured correctly. What is NOT negotiable is what happens + # next — the application that owns this console must gate on ``validate()`` before it serves + # (``agentic_os.app_gate.validate_console``: no plane means no start when authorization was asked for, + # and a readiness failure in the health record when it was not). Building without a plane is allowed; + # SERVING without one is the failure mode, and it belongs to the service, not to this constructor. self._authorizer = resolve_authorizer(authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context=f"agent console for tenant {tenant!r}", - on_missing="deny_later") + on_missing="defer_to_plane") if self._authorizer is None and not default_authorizer_installed(): _log.warning("agent console %r has no authorization plane: every tool call will be denied with " "missing_explicit_grant. Pass authorizer=..., install one with " @@ -235,26 +243,45 @@ def __init__( self._policy = policy self.app = app self._tools: dict[str, _Tool] = {} - for t in tools: - self.registry.register(t) - self._tools[t.spec().name] = t + # A diagnostic instance does not get tools, which is what makes its read-only promise structural + # rather than a denial the operator has to trust: nothing is registered, so nothing can be offered to + # the model, dispatched, or re-approved into running. The alternative — register everything and let + # the plane say no on every call — is the state this repository just stopped calling healthy. + # ``privileged=False`` is the same declaration made in code rather than in the environment, for the + # surfaces an application builds as read-only regardless of how the process is configured. + mode_privileged = execution_mode(context=f"agent console for tenant {tenant!r}")[0] != DIAGNOSTIC + self.privileged = mode_privileged if privileged is None else privileged + if not self.privileged: + _log.warning("agent console %r is running in the diagnostic mode: %d tool(s) the app passed are " + "not registered, so this instance can plan and answer but cannot act.", tenant, + len(list(tools))) + else: + for t in tools: + self.registry.register(t) + self._tools[t.spec().name] = t def mount_mcp(self, client, *, prefix: str | None = None, allow: list[str] | None = None, actions: dict[str, str] | None = None, - default_action: str = "write") -> list[str]: + default_action: Optional[str] = None) -> list[str]: """Mount an external MCP tool server's tools into this console. Registers each tool in the agent-harness registry AND the classify/dispatch catalog, so the assistant can pick and run them like any native tool. Risk classes come from ``actions`` — ``{"ffmpeg.convert_video": "read", ...}`` — decided by - whoever mounts the server, after reading what that server does. Every tool outside that map - gets ``default_action``, which is ``write``: a server's own ``readOnlyHint`` still moves the - *approval* gate (an announced read-only tool need not be confirmed) but never the - authorization class, because the thing asking to be run is not allowed to grade its own risk. + whoever mounts the server, after reading what that server does. A tool outside that map gets + ``default_action``, and with no ``default_action`` it is not mounted at all: an MCP server is + code this console did not write, so a class it would fall back to is a grant nobody chose. + A server's own ``readOnlyHint`` still moves the *approval* gate (an announced read-only tool + need not be confirmed) but never the authorization class, because the thing asking to be run is + not allowed to grade its own risk. ``allow`` is the approval allowlist and is unchanged. Returns the mounted tool names. """ + if not self.privileged: + raise PrivilegedExecutionUnavailable( + "mount_mcp() is refused on a diagnostic console: mounting a tool server is how a read-only " + "instance acquires an execution path, which is the one thing its mode promise rules out.") from ..tools.mcp import mount_mcp as _mount_mcp names = _mount_mcp(self.registry, client, prefix=prefix, actions=actions, @@ -386,6 +413,12 @@ def _denied_by_authorization(self, name: str, result) -> bool: return False def _answer_tool(self, name: str, args: dict, principal=None) -> dict: + # Nothing is registered in a diagnostic console, so this is unreachable by accident of construction — + # and an answer this important is not left to an accident. Explicit refusal, not a lookup miss. + if not self.privileged: + raise PrivilegedExecutionUnavailable( + f"{name} was refused: this agent console is a diagnostic instance, so privileged execution is " + f"not available in it — no tool is registered. Run the execution instance instead.") # tool-phase policy: an approval rule pauses an irreversible action; a deny rule blocks it. policy = self._effective_policy() if policy is not None: diff --git a/context_runtime/integrations/modules.py b/context_runtime/integrations/modules.py index 2430075..61bc78e 100644 --- a/context_runtime/integrations/modules.py +++ b/context_runtime/integrations/modules.py @@ -22,7 +22,7 @@ from itertools import combinations from ..runtime.runtime import ContextRuntime -from ..tools.authz import RegistryConfigurationError, resolve_authorizer +from ..tools.authz import PrivilegedExecutionUnavailable, RegistryConfigurationError, resolve_authorizer from ..tools.base import ACTIONS, ApprovalPolicy, ToolRegistry, ToolResult, ToolSpec, function_tool from ..types import Goal, Hit, Plan, Trace from .bandit import EpsilonGreedyBandit @@ -231,8 +231,12 @@ def __init__(self, spec: ModuleSpec, runtime: ContextRuntime | None = None, bandit: EpsilonGreedyBandit | None = None, approver=None, epsilon: float = 0.12, persist_path: str | None = None, authorizer=None, local_trust: bool = False, local_trust_reason: str = "", - authorizer_on_missing: str = "raise"): + authorizer_on_missing: str = "raise", privileged: bool = True): self.spec = spec + # ``privileged=False`` is a promise about this object, not a request: it says the caller is a + # read-only surface, so ``act`` is refused here as well as at the registry. A surface that could + # execute and asked to be built without a plane is refused at construction instead. + self.privileged = privileged self.runtime = runtime or ContextRuntime.default([]) self.arms = _bundles(spec.sources) self.bandit = bandit or EpsilonGreedyBandit(self.arms, epsilon=epsilon, persist_path=persist_path) @@ -244,7 +248,7 @@ def __init__(self, spec: ModuleSpec, runtime: ContextRuntime | None = None, authorizer, local_trust=local_trust, local_trust_reason=local_trust_reason, context=f"module fleet tenant {spec.name!r}", - on_missing=authorizer_on_missing)) + on_missing=authorizer_on_missing, privileged=privileged)) for s in spec.sources: self.registry.register(_source_tool(spec.name, s)) for a in spec.actions: @@ -267,6 +271,11 @@ def handle(self, question: str) -> ModuleResult: return ModuleResult(self.spec.name, kind, bundle, tuple(hits), context, action, plan) def act(self, action: str, **args) -> ToolResult: + if not self.privileged: + raise PrivilegedExecutionUnavailable( + f"{self.spec.name}.{action} was refused: this tenant was built as a read-only surface " + f"(privileged=False), so it has no execution path to authorize a call through. A service that " + f"means to act builds a privileged tenant and installs a plane to ask.") return self.registry.run(f"{self.spec.name}_{action}", args) def record_outcome(self, question: str, success: bool) -> float: diff --git a/context_runtime/integrations/runtime_scan.py b/context_runtime/integrations/runtime_scan.py index e626718..95ad437 100644 --- a/context_runtime/integrations/runtime_scan.py +++ b/context_runtime/integrations/runtime_scan.py @@ -178,5 +178,8 @@ def mount_deploy_scan(registry: ToolRegistry, *, python: str | None = None, env: server_env.update(env or {}) client = MCPClient.stdio([python or sys.executable, "-m", "context_runtime.tools.mcp_servers.deploy_scan"], env=server_env) - names = mount_mcp(registry, client, prefix="scan", default_side_effecting=True) + # The scan server ships in this repository (tools/mcp_servers/deploy_scan.py), and every tool on it + # launches a scan — so the class is stated here rather than inherited from a default that no longer + # exists: mount_mcp now mounts nothing at all for a tool nobody gave a class. + names = mount_mcp(registry, client, prefix="scan", default_side_effecting=True, default_action="write") return client, names diff --git a/context_runtime/tools/__init__.py b/context_runtime/tools/__init__.py index 6c46b7c..c0dffe4 100644 --- a/context_runtime/tools/__init__.py +++ b/context_runtime/tools/__init__.py @@ -15,14 +15,38 @@ ToolResult, ToolSpec, ) -from .authz import LOCAL_AUTHORITY_ENV, local_authority, local_authority_from_env, resolve_authorizer -from .actions import PureRead, pure_read, resolve_action +from .authz import ( + DIAGNOSTIC, + DIAGNOSTIC_REASON_ENV, + EXECUTE, + EXECUTION_MODE_ENV, + LOCAL_AUTHORITY_ENV, + PrivilegedExecutionUnavailable, + execution_mode, + local_authority, + local_authority_from_env, + require_plane, + resolve_authorizer, +) +from .actions import ( + INERT_ROOTS, + MIN_DELEGATED_CLASS, + Delegated, + PureRead, + delegated, + opaque_callees, + pure_read, + resolve_action, +) from .retriever import ToolRetriever __all__ = [ "ToolSpec", "ToolResult", "ToolPlugin", "ToolRegistry", "ApprovalPolicy", "ToolError", "ToolRetriever", "resolve_authorizer", "local_authority", "local_authority_from_env", "LOCAL_AUTHORITY_ENV", + "require_plane", "execution_mode", "PrivilegedExecutionUnavailable", + "EXECUTION_MODE_ENV", "DIAGNOSTIC_REASON_ENV", "EXECUTE", "DIAGNOSTIC", "resolve_action", "PureRead", "pure_read", + "delegated", "Delegated", "opaque_callees", "INERT_ROOTS", "MIN_DELEGATED_CLASS", ] diff --git a/context_runtime/tools/actions.py b/context_runtime/tools/actions.py index 6dd2b16..5848a46 100644 --- a/context_runtime/tools/actions.py +++ b/context_runtime/tools/actions.py @@ -12,34 +12,53 @@ launches a scan is not a read, and inheriting the class of the function it replaced would hand that call to anyone holding a read grant. -**Why a declaration is not enough on its own.** "Trust me, mine really is a read" is the same failure wearing -a different hat: the code asking to run grades its own risk again, which is the thing this design refuses. -So an injected implementation starts at :data:`INJECTED_FLOOR` — anything swapped in from outside this -repository is assumed to leave the process until shown otherwise — and the only way below the floor is a -*capability contract*: a named constructor whose argument must be a sentence about why the function is inert, -which is what makes the claim reviewable in a manifest or a pull request rather than a bare flag. That claim -is then checked against the function's own source: :func:`write_sinks` looks for the sink vocabulary the -platform's own read-classification sweep (agentic-os FR-04) uses, and a function reaching one cannot be -registered below the class that sink implies, whatever its author declared. +**Delegation is refused by default; it is never classified by default.** Handing a tenant a callable from +outside this repository hands it a capability the platform has not read, so the answer to "what class is +that?" is *nobody knows, so it does not run* — not a class anyone assumes. There is deliberately no floor +here: a constant like ``write`` looks like a conservative default and behaves like a grant, because the code +swapping itself in picks it, in passing, while writing an adapter. Every class a delegated callable is +registered with has to name where it came from, and :func:`delegated` is the only way to say so: the class, +the authority that authorized this delegation, what the callable hands its arguments to, and the review that +connects the two. The refusal messages carry that sentence rather than a class. + +**The one claim that is verified instead of authorized.** :func:`pure_read` asks for *less* authority than a +delegation would, so it is not bought with provenance — it is proved, against the callable's own source: +:func:`write_sinks` searches the sink vocabulary the platform's read-classification sweep (agentic-os FR-04) +uses, and :func:`opaque_callees` refuses a claim the source cannot be read far enough to check. That is also +why :func:`delegated` will not carry a ``read``: three sentences from the code asking to run are not evidence +that the code is inert, and text this repository cannot check must never buy a weaker grant than the one the +reviewed implementation held. **What this does not pretend to be.** The sweep reads the callable that was handed over — nested definitions -included — not whatever that callable goes on to call. A factory that delegates to a client library is -invisible to it, which is exactly why the floor is ``write`` and not ``read``: the check exists to catch the -honest mistake and to make a false claim expensive, not to stand in for a review. +included. What it cannot see it refuses, and what it can see it only ever uses to *raise* a class or refuse a +claim: over-declaring stays legal, because registering a read as a ``write`` costs a call and registering a +write as a read costs a policy boundary. """ from __future__ import annotations import ast import inspect +import builtins import textwrap from dataclasses import dataclass from typing import Callable, Optional from .base import ACTIONS, RegistryConfigurationError -#: The least class an injected implementation may be registered at without a capability contract. A function -#: this repository did not write gets the benefit of the doubt in the safe direction: assumed consequential. -INJECTED_FLOOR = "write" +#: The least class a delegated implementation may be *authorized* at. This is not a default and not a floor: +#: nothing is registered at this class because a callable was handed over, and a bare string naming it is +#: refused (see :func:`resolve_action`). It is the bottom of the range :func:`delegated` accepts, so the only +#: thing it decides is that an authorized delegation asks for at least ``write``. +MIN_DELEGATED_CLASS = "write" + +#: Roots a ``pure_read`` claim may be checked against. The list is an allow-list on purpose: an effect this +#: module cannot read is an effect it refuses to grade, so a name missing from here costs the caller a +#: :func:`delegated` contract and a wrong entry in here costs a policy boundary. Parameters, locals and names +#: defined inside the callable never need to appear — they are visible in the source being checked. +INERT_ROOTS = frozenset({ + "json", "re", "math", "string", "textwrap", "datetime", "collections", "itertools", "typing", + "dataclasses", "hashlib", "base64", "urllib_parse", "ToolResult", "PureRead", +}) #: The sink vocabulary of the platform's sweep over tools classified ``read`` (agentic-os FR-04), copied #: literally so Context Runtime stays installable without the platform. Attribute form: a subprocess, a file @@ -79,6 +98,14 @@ _BARE_TRUTHY = frozenset({"1", "true", "t", "yes", "y", "on", "enable", "enabled", "pure", "read", "pure read", "pure_read", "safe", "n/a", "none", "no reason", "todo"}) +#: How many characters a sentence about a delegation has to clear to be treated as one. Below this, what +#: someone typed is a label ("SEC-41", "checked", "vendor") and a later reader has nothing to check. +_MIN_SENTENCE = 24 + +#: Names that need no provenance because calling them cannot reach outside the process. Derived, not typed +#: out, so the list cannot drift from the interpreter's own answer. +_BUILTINS = frozenset(dir(builtins)) + @dataclass(frozen=True) class PureRead: @@ -106,6 +133,70 @@ def pure_read(reason: str) -> PureRead: return PureRead(reason=text) +@dataclass(frozen=True) +class Delegated: + """An authorized delegation: code from outside this repository will run, and someone named who said so. + + Four fields because four questions go unanswered when a class is guessed — what capability is being + asked for (:attr:`action`), who authorized a callable this repository did not write to be runnable at all + (:attr:`authority`), what the callable actually hands its arguments to (:attr:`via`), and which review + connects the two (:attr:`review`). A record that answers them is greppable in a manifest and reviewable in + a pull request; a bare class string answers none of them, which is why it is refused. + """ + + action: str + authority: str + via: str + review: str + + +def _sentence(value: object, field: str, *, param: str, example: str) -> str: + """``value`` as a checked sentence. Empty, bare-truthy and one-word answers are refusals, not typos.""" + text = (value or "").strip() if isinstance(value, str) else "" + if not text or text.lower() in _BARE_TRUTHY: + raise RegistryConfigurationError( + f"{param}: {field}={value!r} does not say anything. {field} is the part a reviewer reads — " + f"e.g. {example}.") + if len(text) < _MIN_SENTENCE or " " not in text.strip(): + raise RegistryConfigurationError( + f"{param}: {field}={text!r} is a label, not a sentence. Give {field} enough words to be checked " + f"later — e.g. {example}.") + return text + + +def delegated(*, action: str, authority: str, via: str, review: str) -> Delegated: + """Authorize a delegated implementation at ``action`` — the only way one gets registered at all. + + ``authority`` names who authorized a callable from outside this repository to run at that class (a grant, + a policy-plane rule, a signed-off ticket — not the caller's own intent). ``via`` names what the callable + hands its arguments to, in the terms a reader can go and check. ``review`` is the sentence that says + somebody read the code and when. All three are required, in sentences, because the delegation the platform + is afraid of is the one that was wired up by someone who meant well and wrote down nothing. + + ``read`` is not accepted here on purpose: a class this weak has to be proved against the source with + :func:`pure_read`, never asserted in prose by the code asking to run. + """ + if action not in ACTIONS: + raise RegistryConfigurationError( + f"delegated(action={action!r}) is not one of the vocabulary {ACTIONS}.") + if ACTIONS.index(action) < ACTIONS.index(MIN_DELEGATED_CLASS): + raise RegistryConfigurationError( + f"delegated(action={action!r}) is refused: a delegation cannot be authorized into the '{action}' " + f"class, because prose from the code asking to run is not evidence that it is inert. " + f"{action.capitalize()} is the only class below '{MIN_DELEGATED_CLASS}' and it is proved against " + f"the callable's source with pure_read(...) — which refuses the claim the moment it cannot see " + f"enough of the code to check it.") + return Delegated( + action=action, + authority=_sentence(authority, "authority", param="delegated()", + example='authority="grant agentic-os:fleet/edge-sentinel block_ip (ticket SEC-41)"'), + via=_sentence(via, "via", param="delegated()", + example='via="sentinel_client.Client.block_ip, an HTTPS PUT to the Sentinel API"'), + review=_sentence(review, "review", param="delegated()", + example='review="read the client on 2026-11-22; it writes to one vendor API and nothing else"'), + ) + + def _source_of(fn: object) -> Optional[str]: """``fn``'s own source, or ``None`` when it cannot be read (built-in, compiled at run time).""" try: @@ -146,26 +237,76 @@ def write_sinks(fn: Callable[[dict], object]) -> tuple[str, ...]: return tuple(sorted(found)) +def opaque_callees(fn: Callable[[dict], object]) -> tuple[str, ...]: + """What ``fn`` calls that this module cannot see inside — the delegation a sink sweep is blind to. + + A call is visible when its root is a parameter or a local of ``fn``, a name bound inside its own body, a + builtin, or an entry of :data:`INERT_ROOTS`. Anything else — a client built at module scope, an object + closed over by a factory, a method on an injected session — is where the effect of the call goes, and this + file has no way to know what it is. An unreadable callable is reported as one opaque callee rather than as + zero, because "could not look" and "found nothing" have to stay different answers. + + Used to refuse a ``pure_read`` claim, never to grant one: an opaque callee is exactly what + :func:`delegated` exists to authorize. + """ + source = _source_of(fn) + if source is None: + return ("",) + try: + tree = ast.parse(source) + except SyntaxError: + return ("",) + code = getattr(fn, "__code__", None) or getattr(getattr(fn, "__func__", None), "__code__", None) + bound = set(getattr(code, "co_varnames", ())) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + bound.add(node.id) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + bound.add(node.name) + args = getattr(node, "args", None) + if args is not None: + bound.update(a.arg for a in (list(getattr(args, "posonlyargs", [])) + list(args.args) + + list(args.kwonlyargs))) + elif isinstance(node, (ast.Import, ast.ImportFrom)): + bound.update((a.asname or a.name.split(".")[0]) for a in node.names) + elif isinstance(node, ast.arg): + bound.add(node.arg) + invisible = _BUILTINS | INERT_ROOTS | bound + found: set[str] = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + root = (_receiver_name(node.func) if isinstance(node.func, ast.Attribute) + else node.func.id if isinstance(node.func, ast.Name) else "") + if root and root not in invisible: + found.add(root) + return tuple(sorted(found)) + + def resolve_action(*, shipped: str, injected: Optional[object] = None, declared: Optional[object] = None, param: str = "", tool: str = "", context: str = "") -> str: """The risk class of the function that is actually installed, which is not always the shipped one's. ``shipped`` is the class reviewed here for the implementation this file ships; ``injected`` is the - caller's replacement, or ``None`` when they took the shipped one; ``declared`` is what the caller asked - for through the tenant's ``*_action`` keyword — a class at or above :data:`INJECTED_FLOOR`, or - :func:`pure_read` to claim less. + caller's replacement, or ``None`` when they took the shipped one; ``declared`` is what the caller passed + through the tenant's ``*_action`` keyword — :func:`delegated` to authorize the delegation, or + :func:`pure_read` to prove the callable inert instead. Nothing injected returns ``shipped`` untouched, so a shipped pure implementation keeps the ``read`` it was - audited at. Something injected is where the discipline lives: - - * **no declaration** → refused. A class is not inherited from the tool that occupied the slot. - * **``"read"`` as a plain word** → refused. Below the floor is a claim that has to be made deliberately, - in the type built for it. - * **``pure_read(...)``** → refused unless the reason is a sentence, the source can be read, and - :func:`write_sinks` finds nothing in it. Evidence beats a declaration: nobody registers a below-the-floor - class over a visible ``post``, and nobody gets one for a function whose source cannot be read. - * **a destructive sink under ``delete``** → refused, for the same reason. - * **over-declaring** is always allowed: asking for more authority than a call needs can only ever deny it. + audited at. Something injected is a delegation, and delegation is refused by default: + + * **nothing passed** → refused. A class is not inherited from the tool that occupied the slot, and it is + not defaulted either — the default is the thing that gets copied into the next deployment. + * **a class as a plain word** (``"write"``, ``"delete"``, ``"read"``) → refused. A word is not an + authorization; naming a class is the answer, and the question was who gave it. + * **``delegated(...)``** → accepted for ``write``/``delete`` when the authority, the callee and the review + are all sentences, and never for less than the class the wrapper's own source implies. + * **``pure_read(...)``** → accepted only when the source can be read, :func:`write_sinks` finds nothing in + it, and :func:`opaque_callees` finds nothing it hands its arguments to. A claim this repository can + check is worth more than a claim it cannot. + + Over-declaring stays legal throughout: a call registered above its true class is denied, and a call + registered below it is a policy boundary that has already been crossed. """ where = f"{tool} ({context})" if tool and context else (tool or context or "this tool") param = param or f"{tool.rsplit('.', 1)[-1] if tool else 'tool'}_action" @@ -177,44 +318,65 @@ class over a visible ``post``, and nobody gets one for a function whose source c return shipped claim = declared - if isinstance(claim, PureRead): - claimed = "read" - elif isinstance(claim, str): - if claim == "read": - raise RegistryConfigurationError( - f"{where}: {param}='read' is below the floor for a function injected into this slot. " - f"Something replaced the implementation this file audited, so it is registered as " - f"'{INJECTED_FLOOR}' unless its author contracts that it is inert: {param}=" - f'pure_read("what it calls, and why that leaves nothing behind").') - claimed = claim - elif claim is None: - raise RegistryConfigurationError( - f"{where}: a function was injected in place of the implementation shipped here, and a risk class " - f"is not inherited from the tool it replaces. Pass {param}=... — '{INJECTED_FLOOR}' or 'delete', " - f"or {param}=pure_read(...) for an implementation you have read and can argue is inert.") - else: + # From here the code that would run was written outside this repository. Nothing is assumed about it — + # least of all its risk class, which is the one thing a caller must not get to supply silently. + if claim is None: raise RegistryConfigurationError( - f"{where}: {param}={claim!r} is neither a risk class in {ACTIONS} nor a pure_read(...) contract.") - - if claimed not in ACTIONS: - raise RegistryConfigurationError( - f"{where}: {param}={claimed!r} is not one of the vocabulary {ACTIONS}.") - - sinks = write_sinks(injected) - if claimed == "read": + f"{where}: a function was injected in place of the implementation shipped here, and nothing says " + f"who authorized it. A risk class is not inherited from the tool it replaces, and there is no " + f"default one either — the class a caller picks in passing while writing an adapter is a grant " + f"that nobody reviewed. Pass {param}=delegated(action=..., authority=..., via=..., review=...), " + f"or {param}=pure_read(...) for an implementation whose own source proves it inert.") + if isinstance(claim, PureRead): if _source_of(injected) is None: raise RegistryConfigurationError( f"{where}: {param}=pure_read(...) cannot be honoured for a function whose source is not " f"readable (a built-in or something compiled at run time): there is nothing to check the " - f"claim against. Register it as '{INJECTED_FLOOR}'.") + f"claim against. Authorize it with {param}=delegated(...) instead.") + sinks = write_sinks(injected) if sinks: raise RegistryConfigurationError( f"{where}: {param}=pure_read(...) claims this injected function is inert, and its own source " f"disagrees — it reaches {list(sinks)}. A call that leaves the process or changes state is " - f"not a read: register it as '{INJECTED_FLOOR}' (or 'delete'), whatever it is named.") - destructive = tuple(sorted(s for s in sinks if s in DESTRUCTIVE_ATTRS)) - if destructive and ACTIONS.index(claimed) < ACTIONS.index("delete"): + f"not a read, whatever it is named: authorize it with " + f"{param}=delegated(action='{MIN_DELEGATED_CLASS}', ...).") + hidden = opaque_callees(injected) + if hidden: + raise RegistryConfigurationError( + f"{where}: {param}=pure_read(...) cannot be honoured, because the claim cannot be checked: " + f"the function hands its arguments to {list(hidden)}, which is not defined in the code this " + f"check can read. That is delegation, and delegation is refused by default — either what it " + f"calls is provably inert (add it to INERT_ROOTS with the review that says so) or the " + f"delegation needs {param}=delegated(action=..., authority=..., via=..., review=...).") + return "read" + if isinstance(claim, Delegated): + if claim.action not in ACTIONS: + raise RegistryConfigurationError( + f"{where}: {param} carries a delegation for action={claim.action!r}, which is not one of the " + f"vocabulary {ACTIONS}.") + if ACTIONS.index(claim.action) < ACTIONS.index(MIN_DELEGATED_CLASS): + raise RegistryConfigurationError( + f"{where}: {param} delegates at {claim.action!r}. A delegation is never authorized below " + f"'{MIN_DELEGATED_CLASS}': prose buys a strong class, and only source evidence buys a weak " + f"one — use {param}=pure_read(...) if this call really is a read.") + # Built by hand instead of by delegated(): the sentences are the authorization, so they are checked + # here too rather than trusted because the object is the right shape. + _sentence(claim.authority, "authority", param=param, example='authority="grant SEC-41 ..."') + _sentence(claim.via, "via", param=param, example='via="sentinel_client.Client.block_ip"') + _sentence(claim.review, "review", param=param, example='review="read the client on 2026-11-22 ..."') + destructive = tuple(sorted(s for s in write_sinks(injected) if s in DESTRUCTIVE_ATTRS)) + if destructive and ACTIONS.index(claim.action) < ACTIONS.index("delete"): + raise RegistryConfigurationError( + f"{where}: {param} delegates at {claim.action!r}, but the wrapper's own source reaches " + f"{list(destructive)}, which is the 'delete' class. A delegation may over-ask and never " + f"under-state: raise it to 'delete' or stop reaching for the filesystem.") + return claim.action + if isinstance(claim, str): raise RegistryConfigurationError( - f"{where}: {param}={claimed!r} understates what this injected function does — it reaches " - f"{list(destructive)}, which is the 'delete' class. Over-declare rather than under-declare.") - return claimed \ No newline at end of file + f"{where}: {param}={claim!r} names a risk class and no authority. Delegated code is refused by " + f"default, so the class has to come from someone who can be named — a conservative-sounding word " + f"typed next to the factory is the same unnamed grant as a permissive one. Use " + f"{param}=delegated(action={claim!r}, authority=..., via=..., review=...) — or " + f"{param}=pure_read(...) for a call that is a read and can show it.") + raise RegistryConfigurationError( + f"{where}: {param}={claim!r} is neither a delegated(...) authorization nor a pure_read(...) claim.") \ No newline at end of file diff --git a/context_runtime/tools/authz.py b/context_runtime/tools/authz.py index db0fde2..2120164 100644 --- a/context_runtime/tools/authz.py +++ b/context_runtime/tools/authz.py @@ -24,6 +24,11 @@ construction, naming all three doors. Letting it pass would build a registry that answers every call with ``denied: missing_explicit_grant`` — correct, but discovered by a user instead of in a start-up log. +A service that serves requests does not get to discover it there either: it calls :func:`require_plane` before +it stands anything up, and a process that cannot answer its own tool calls does not start. The exception is +the mode in which there is nothing to answer — :data:`EXECUTION_MODE_ENV` — and not a warning beside the +denials, which is what used to be here and read as healthy. + Local authority is the FLOOR, never the ceiling: it is consulted only when neither of the first two doors is open. A copied example with ``local_trust=True`` inside a service that installed a permissions plane therefore cannot loosen that plane; the plane wins. @@ -42,17 +47,50 @@ #: Values people reach for when switching something on. They carry no reason, so they are refused. _BARE_TRUTHY = {"1", "true", "t", "yes", "y", "on", "enable", "enabled"} +#: What a process reads to declare that it is NOT a privileged execution service. Absent means ``execute``: +#: a service that runs tools has to be told, in words, that it is allowed to come up without a plane. +EXECUTION_MODE_ENV = "CR_EXECUTION_MODE" + +#: And why it is a diagnostic instance. A sentence for the same reason :data:`LOCAL_AUTHORITY_ENV` takes one: +#: a bare switch is what turns an escape hatch into a default, and this one is the difference between a +#: read-only console and a production service that quietly stopped being able to act. +DIAGNOSTIC_REASON_ENV = "CR_DIAGNOSTIC_REASON" + +EXECUTE = "execute" +DIAGNOSTIC = "diagnostic" + +#: The words that mean each mode. Spelled out because a deployment that types something else must be told, +#: not quietly routed into the permissive branch — which is the mistake that makes a mode switch useless. +_MODE_WORDS = { + EXECUTE: {EXECUTE, "privileged", "full", "production"}, + DIAGNOSTIC: {DIAGNOSTIC, "diagnostics", "read-only", "read_only", "readonly"}, +} + + +class PrivilegedExecutionUnavailable(RuntimeError): + """Something asked a diagnostic instance to execute. Refused by construction, not by policy. + A separate exception type from :class:`RegistryConfigurationError` because the two answers mean different + things to a caller: a configuration error says the deployment is wrong and should not have started, this + says the deployment is fine and this operation does not exist in it. + """ + + +def _refuse(reason: str, *, context: str, source: str, + what: str = "local authority") -> str: + """A reason that has to mean something. Raises rather than accepting an empty or bare-truthy declaration. -def _refuse(reason: str, *, context: str, source: str) -> str: - """A local-authority reason, checked. Raises rather than accepting an empty or bare-truthy declaration.""" + Shared by the two places in this module that take a sentence rather than a switch — local authority and + the diagnostic mode — because both fail the same way: a value that says nothing is how an escape hatch + gets copied into a production compose file. + """ text = (reason or "").strip() where = f" ({context})" if context else "" if not text: raise RegistryConfigurationError( - f"local authority was requested{where} without a reason. {source} takes a sentence describing " - f"why this process may act with the operator's own authority — the reason is what makes an " - f"allow-all choice reviewable in a manifest or a pull request.") + f"{what} was requested{where} without a reason. {source} takes a sentence describing why this " + f"process is allowed to be the exception — the reason is what makes the choice reviewable in a " + f"manifest or a pull request.") if text.lower() in _BARE_TRUTHY: raise RegistryConfigurationError( f"{source}={text!r} is not a reason{where}. Give it a sentence, e.g. " @@ -74,9 +112,61 @@ def local_authority_from_env(*, context: str = "") -> tuple[bool, str]: return True, _refuse(raw, context=context, source=LOCAL_AUTHORITY_ENV) +def execution_mode(*, context: str = "") -> tuple[str, str]: + """``("execute", "")`` or ``("diagnostic", reason)`` — whether this process may run tools at all. + + The default is the privileged answer, on purpose: a service that can act is the ordinary case, and the + read-only instance is the exception that has to be declared. A diagnostic instance must give a reason, and + an unrecognised value raises instead of falling through, because a typo in a mode variable that lands on + the permissive branch is indistinguishable from a deployment that meant to be privileged. + """ + raw = (os.environ.get(EXECUTION_MODE_ENV) or "").strip().lower() + if not raw or raw in _MODE_WORDS[EXECUTE]: + return EXECUTE, "" + if raw in _MODE_WORDS[DIAGNOSTIC]: + return DIAGNOSTIC, _refuse(os.environ.get(DIAGNOSTIC_REASON_ENV) or "", + context=context, source=DIAGNOSTIC_REASON_ENV, + what="a diagnostic (read-only) instance") + raise RegistryConfigurationError( + f"{EXECUTION_MODE_ENV}={raw!r} is not a mode. Use {EXECUTE!r} (the default: this process runs tools, " + f"so it refuses to start without an authorization plane) or {DIAGNOSTIC!r} together with a written " + f'{DIAGNOSTIC_REASON_ENV}="why this instance exists and cannot execute".') + + +def require_plane(*, context: str = "") -> str: + """The one call a privileged service makes at start-up. Returns the mode; raises when it may not serve. + + A service that runs tools and has nothing to ask is not healthy-but-degraded: it is a service that will + answer every action with ``missing_explicit_grant`` while its dashboard stays green. That state is a + start-up fact, so it is decided at start-up — where the operator is still reading the log — and the only + way past it without a plane is the mode in which execution does not exist, not a warning. + + Call this before standing anything up. It is deliberately not called by ``resolve_authorizer`` on behalf + of every caller: a library does not know whether the process embedding it serves requests. + """ + mode, reason = execution_mode(context=context) + if mode == DIAGNOSTIC: + return DIAGNOSTIC + if default_authorizer_installed(): + return EXECUTE + declared, _ = local_authority_from_env(context=context) + if declared: + return EXECUTE + where = f" ({context})" if context else "" + raise RegistryConfigurationError( + f"a privileged execution service is refusing to start{where}: no authorization plane is installed and " + f"no local authority is declared, so every tool call it would serve is denied " + f"(missing_explicit_grant) while its health check reads green. Do one of three things: install the " + f"plane before this service starts (context_runtime.tools.set_default_authorizer(...)); declare local " + f'authority with {LOCAL_AUTHORITY_ENV}="why this process may act as the operator"; or run it as the ' + f"read-only instance it actually is with " + f'{EXECUTION_MODE_ENV}={DIAGNOSTIC} {DIAGNOSTIC_REASON_ENV}="what this instance is for". A warning ' + f"here was tried and rejected — a fleet that denies everything looks exactly like a healthy one.") + + def resolve_authorizer(authorizer: Optional[Authorizer] = None, *, local_trust: bool = False, local_trust_reason: str = "", context: str = "", - on_missing: str = "raise") -> Optional[Authorizer]: + on_missing: str = "raise", privileged: bool = True) -> Optional[Authorizer]: """The authorizer one Context Runtime registry should be built with, or ``None`` to inherit the default. ``authorizer`` — the integrator's per-registry choice — wins outright, unexamined: it is code, and code may @@ -85,11 +175,16 @@ def resolve_authorizer(authorizer: Optional[Authorizer] = None, *, local_trust: ``local_trust_reason``, or ``CR_LOCAL_AUTHORITY=""``. Otherwise this raises: a tenant that reaches this point with no answer is a misconfiguration, and the least dangerous place to say so is construction. - ``on_missing`` decides what "no answer" means. ``"raise"`` (the default, and right for a tenant that owns - its registry) makes it a start-up failure. ``"deny_later"`` returns ``None`` and lets the registry answer - every call with its own ``missing_authorizer`` denial — what a shared, request-facing surface such as - ``AgentConsole`` wants, because there the missing plane is a per-request fact the operator can still fix, - and the denial is already asserted in downstream tests. Neither mode grants local trust implicitly. + ``on_missing`` decides what "no answer" means, and ``privileged`` decides who is allowed to ask for the + second answer. ``"raise"`` (the default) makes it a start-up failure. ``"deny_later"`` returns ``None`` and + lets the registry answer every call with its own ``missing_authorizer`` denial, and it is refused unless + the caller also says ``privileged=False``: only a surface that cannot reach a tool may be built on the + promise that the call path will say no, because "boots and denies" and "healthy" look identical from the + outside — which is the failure this seam was migrated to remove. ``"defer_to_plane"`` also returns + ``None``, and means something different: *this is a component, not a service* — the application embedding + it installs a plane moments later and is the thing that must refuse to serve if one never arrives + (``agentic_os.app_gate.validate_console``). A component may be built before its plane exists; a service + may not serve without one. Neither mode grants local trust implicitly. """ if authorizer is not None: if not callable(authorizer): @@ -106,11 +201,22 @@ def resolve_authorizer(authorizer: Optional[Authorizer] = None, *, local_trust: return local_authority(reason, context=context, source=source) if env_declared: return local_authority(env_reason, context=context, source=LOCAL_AUTHORITY_ENV) + if on_missing == "defer_to_plane": + return None # the embedding service owns readiness; see require_plane if on_missing == "deny_later": + if privileged: + raise RegistryConfigurationError( + f"on_missing='deny_later' is refused{f' for {context}' if context else ''} for a registry that " + f"can execute. It buys a process that starts, serves, and denies every tool call forever — " + f"indistinguishable from a working one on a dashboard, and the exact state the fail-closed " + f"migration was done to surface. Either build it with on_missing='raise' so the missing plane " + f"stops the start-up, or say what this surface really is: privileged=False, meaning it has no " + f"execution path for the denial to be about.") return None if on_missing != "raise": raise RegistryConfigurationError( - f"on_missing={on_missing!r} is not one of 'raise' / 'deny_later' ({context or 'caller'})") + f"on_missing={on_missing!r} is not one of 'raise' / 'deny_later' / 'defer_to_plane' " + f"({context or 'caller'})") raise RegistryConfigurationError( f"no authorizer is configured{f' for {context}' if context else ''}, and Context Runtime will not " f"guess. Do one of: pass authorizer=... (a permissions plane, e.g. " diff --git a/context_runtime/tools/mcp.py b/context_runtime/tools/mcp.py index 6fc77fc..e7ad0bf 100644 --- a/context_runtime/tools/mcp.py +++ b/context_runtime/tools/mcp.py @@ -11,8 +11,9 @@ import logging import os import subprocess +import warnings from dataclasses import dataclass -from typing import Any +from typing import Any, Optional import httpx @@ -315,7 +316,7 @@ def mount_mcp( prefix: str | None = None, default_side_effecting: bool = True, actions: dict[str, str] | None = None, - default_action: str = "write", + default_action: Optional[str] = None, ) -> list[str]: """Initialize client if needed, list tools, register each wrapped MCPToolPlugin. @@ -323,13 +324,16 @@ def mount_mcp( ``actions`` gives a tool its risk class — keyed by the registered name, or by the server's own name when a prefix is used — and is decided by whoever mounts the server, after reading what - that server does. A tool absent from the map gets ``default_action``, which is ``write``: an - announced ``readOnlyHint`` may relax the *approval* gate, never the authorization class, because + that server does. A tool absent from the map gets ``default_action`` — and if no ``default_action`` + was given, it gets nothing: it is not mounted, and the refusal is reported. There used to be a + ``write`` sitting in the signature as the default, which is a risk class a caller could receive + without ever choosing one; the class for an unread server is now something the mount has to say. + An announced ``readOnlyHint`` may relax the *approval* gate, never the authorization class, because the thing asking to be run is not allowed to grade its own risk. ``actions`` values and ``default_action`` must come from the shared vocabulary ``ACTIONS``. - Returns the list of registered tool names. + Returns the list of registered tool names — tools refused for want of a class are absent from it. """ - if default_action not in ACTIONS: + if default_action is not None and default_action not in ACTIONS: raise RegistryConfigurationError( f"mount_mcp default_action={default_action!r} is not one of the vocabulary {ACTIONS}") declared = dict(actions or {}) @@ -347,6 +351,7 @@ def mount_mcp( tools = client.list_tools() except Exception: return registered + unclassified: list[str] = [] for tdesc in tools: if not isinstance(tdesc, dict) or not tdesc.get("name"): continue @@ -358,8 +363,20 @@ def mount_mcp( # ``read`` because of a spelling is the failure this layer exists to prevent. candidates = [declared[key] for key in (raw, reg_name) if key in declared] action = max(candidates, key=_STRENGTH.get, default=default_action) + if action is None: + # Refused by default: nobody has read this tool enough to name what it can do, and a tool + # nobody classified matches no grant. Not registering it says the same thing louder, and + # before a request rather than during one. + unclassified.append(reg_name) + continue plugin = MCPToolPlugin(tdesc, client, name=reg_name, default_side_effecting=default_side_effecting, action=action) registry.register(plugin) registered.append(reg_name) + if unclassified: + warnings.warn( + f"mount_mcp refused to mount {len(unclassified)} tool(s) with no risk class: {sorted(unclassified)}. " + f"Pass actions={{...}} for each one, or default_action='write' to say in one place that this whole " + f"server is assumed consequential. An MCP server is code this repository did not write and cannot " + f"read, so the class is no longer something it hands out by default.", stacklevel=2) return registered diff --git a/tests/conftest.py b/tests/conftest.py index aa1fe62..f695cb8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -41,10 +41,42 @@ from context_runtime.tools.base import (default_authorizer_installed, local_trusted_authorizer, # noqa: E402 set_default_authorizer) +# ── the posture the control plane is imported in ───────────────────────────────────────────── +# ``context_runtime.control_plane.app`` stands its fleet up at import, and a fleet that runs tools refuses +# to be built with nothing to ask (``tools.authz.require_plane``) — importing it with no plane is now an +# error, not a warning. So the suite makes the choice a governed deployment makes, before the import that +# reads it: install a plane, then import the service. It is the harness's attributed local-trust authorizer +# under a name that says where it came from, and the session fixture below takes it back out again before +# any test runs, so nothing downstream inherits it. +# +# The three variables are popped rather than set: the suite must not be able to change posture because of +# something in the developer's shell. A test that wants the diagnostic mode says so for its own process +# (see tests/test_authorization_negative_controls.py), and a test that wants local authority asks for +# ``local_run``, which is audited and per-test. +for _posture_var in ("CR_EXECUTION_MODE", "CR_DIAGNOSTIC_REASON", "CR_LOCAL_AUTHORITY"): + os.environ.pop(_posture_var, None) +set_default_authorizer(local_trusted_authorizer(plane="pytest_import_time")) + _REPO_ROOT = Path(__file__).resolve().parent.parent _STRAY = (".context-runtime", ".agentic-os") +@pytest.fixture(scope="session", autouse=True) +def _import_time_plane_removed_before_any_test(): + """The plane exists to get the service imported. It must not survive into a single assertion. + + Session-scoped and declared here so it runs after collection — by the time the first test body starts, + every module-level ``app`` import has happened, and this takes the grant away. The per-test + ``_clean_authorizer_plane`` fixture would fail the run if it were still installed; this fixture is the + reason it does not, and it says so out loud rather than leaving a process-wide allow-all in place for + 1,900 tests that assert the opposite. + """ + if default_authorizer_installed(): + set_default_authorizer(None) + assert not default_authorizer_installed(), "a process-wide plane survived into the test session" + yield + + @pytest.fixture(autouse=True) def _per_test_home(tmp_path, monkeypatch): """A fresh state directory for every test (override inside a test with monkeypatch if needed).""" diff --git a/tests/test_authorization_negative_controls.py b/tests/test_authorization_negative_controls.py new file mode 100644 index 0000000..45c29ae --- /dev/null +++ b/tests/test_authorization_negative_controls.py @@ -0,0 +1,298 @@ +"""The five refusals, asserted as refusals. + +Every test in this file asks for something the design is supposed to say no to, and fails if anything runs. +They are grouped by the shape of the attack rather than by the module that implements the check, because the +point of the seam is that no single layer is the gate: a wrapper that lies about what it calls still meets +the plane, a caller who skips the wrapper meets the registry, and a service whose plane disappears meets its +own start-up rule. + +Two decisions from the owner of the stack set the posture these tests hold: + +* **delegation is refused by default** — permitted only when it is explicitly authorized, non-escalating and + carries provenance a reviewer can check. There is no implicit floor: no class is assigned to foreign code + because nobody felt like choosing one. +* **a privileged service with no authorization plane does not run** — readiness and start-up fail. A separate + diagnostic instance may boot precisely because privileged execution is not available inside it. +""" +from __future__ import annotations + +import pytest + +from agent_harness.tools import Authorization, Decision, ToolRegistry, function_tool + +from context_runtime.integrations.agent_console import AgentConsole +from context_runtime.integrations.modules import CATALOG, ModuleTenant +from context_runtime.tools import ( + Delegated, + PrivilegedExecutionUnavailable, + delegated, + execution_mode, + pure_read, + require_plane, + resolve_action, + resolve_authorizer, +) +from context_runtime.tools.authz import EXECUTION_MODE_ENV +from context_runtime.tools.base import (RegistryConfigurationError, ToolClassificationError, ToolResult, + set_default_authorizer) + +_AUTH = dict(authority="grant agentic-os:fleet/sec-41 block_ip (ticket SEC-41)", + via="sentinel_client.Client.block_ip, an HTTPS PUT to the Sentinel API", + review="read the client on 2026-11-22: it writes to one vendor API and holds nothing locally") +_INERT_CLAIM = "formats its arguments into a string; no I/O — reviewed 2026-11-22" + + +class _Vendor: + """A client object built outside the injected callable — the effect is over there, not in the source.""" + + def dispatch(self, payload: dict) -> dict: + return {"ok": True} + + +def _wrapper(args: dict) -> ToolResult: + """A plugin wrapper with nothing to see: no sink in its own body, everything delegated away.""" + return ToolResult(ok=True, text=str(_Vendor().dispatch(args))) + + +def _reader(principal, spec, args): + """A plane that granted ``read`` and nothing else.""" + if spec.action != "read": + return f"no '{spec.action}' grant for this principal" + return Authorization.allow(grant_ids=("role:reader",), plane="permissions") + + +# ── 1. a plugin wrapper attempting privilege escalation ────────────────────────────────────── + + +def test_a_wrapper_cannot_register_itself_as_a_read(): + """The escalation, in every form it arrives in. + + A wrapper's own body is clean by construction — the work happens in whatever it calls — so the two + things that could grant it a ``read`` are a claim about the source and a word in a keyword argument. + Neither is accepted: the claim is refused because it cannot be checked, and the word is refused because + a class with no authority behind it is a self-grant with better manners. + """ + with pytest.raises(RegistryConfigurationError, match="_Vendor"): + resolve_action(shipped="read", injected=_wrapper, declared=pure_read(_INERT_CLAIM), + tool="draft_caption") + for bare in ("read", "write", "delete"): + with pytest.raises(RegistryConfigurationError, match="no authority"): + resolve_action(shipped="read", injected=_wrapper, declared=bare, tool="draft_caption") + + +def test_an_authorized_wrapper_still_cannot_run_on_a_readers_authority(): + """Registering at ``write`` is not what stops the call — the class is only what the call is checked + against. This is the assertion that classification and authorization are two layers, and that passing + cleanly through the first does not buy a way past the second. + """ + tenant = ModuleTenant(CATALOG["edge_sentinel"], authorizer=_reader) + denied = tenant.registry.run("edge_sentinel_block_ip", {"ip": "1.2.3.4"}) + assert denied.ok is False and "no 'write' grant" in (denied.error or "") + last = tenant.registry.audit[-1] + assert last["allowed"] is False + + +def test_reregistering_a_tool_at_a_lower_class_is_refused(): + """Hot reload, plugin overwrite, second builder on the same registry: none may lower a class.""" + registry = ToolRegistry(authorizer=_reader) + registry.register(function_tool("wipe", lambda a: ToolResult(ok=True), action="delete")) + with pytest.raises(ToolClassificationError, match="downgrading the previous classification"): + registry.register(function_tool("wipe", lambda a: ToolResult(ok=True), action="read")) + with pytest.raises(ToolClassificationError, match="re-registered without a risk class"): + registry.register(function_tool("wipe", lambda a: ToolResult(ok=True))) + + +def test_a_spec_that_admits_side_effects_cannot_claim_read(): + registry = ToolRegistry(authorizer=_reader) + with pytest.raises(ToolClassificationError, match="classified 'read'"): + registry.register(function_tool("mutates", lambda a: ToolResult(ok=True), side_effecting=True, + action="read")) + + +# ── 2. delegation without provenance ───────────────────────────────────────────────────────── + + +def test_delegation_without_provenance_never_reaches_the_registry(): + """Nothing is registered on a guess: every unattributed form is refused before a tool exists.""" + with pytest.raises(RegistryConfigurationError, match="who authorized it"): + resolve_action(shipped="read", injected=_wrapper, tool="draft_caption") + for thin in ({**_AUTH, "authority": ""}, {**_AUTH, "via": "client"}, {**_AUTH, "review": "checked"}): + with pytest.raises(RegistryConfigurationError): + delegated(action="write", **thin) + with pytest.raises(RegistryConfigurationError, match="prose"): + delegated(action="read", **_AUTH) + + +def test_a_hand_built_authorization_record_is_checked_like_a_built_one(): + """Constructing the dataclass is not a way around the builder — the sentences are the authorization.""" + with pytest.raises(RegistryConfigurationError, match="authority"): + resolve_action(shipped="read", injected=_wrapper, + declared=Delegated(action="write", authority="", via="", review=""), + tool="draft_caption") + + +def test_an_authorization_below_the_strongest_class_is_refused_wherever_it_is_made(): + """``delegated()`` refuses a ``read`` delegation, and the resolver refuses one that arrived anyway.""" + with pytest.raises(RegistryConfigurationError, match="prose"): + delegated(action="read", **_AUTH) + with pytest.raises(RegistryConfigurationError, match="never authorized below"): + resolve_action(shipped="write", injected=_wrapper, + declared=Delegated(action="read", **_AUTH), tool="draft_caption") + + +# ── 3. a missing or incompatible authorization plane ───────────────────────────────────────── + + +def test_a_privileged_service_refuses_to_start_without_a_plane(): + """Three layers, one answer. + + ``require_plane`` is what a service calls; ``ModuleTenant`` is what a fleet builds; the harness + ``validate(strict=True)`` is what a console runs. None of them is allowed to hand back something that + serves and denies, because that state looks healthy. + """ + with pytest.raises(RegistryConfigurationError, match="refusing to start"): + require_plane(context="the fleet") + with pytest.raises(RegistryConfigurationError, match="no authorizer is configured"): + ModuleTenant(CATALOG["edge_sentinel"]) + with pytest.raises(RegistryConfigurationError, match="deny_later. is refused"): + resolve_authorizer(on_missing="deny_later", context="a registry that can run tools") + with pytest.raises(RegistryConfigurationError, match="not one of"): + resolve_authorizer(on_missing="later_please", context="a caller who guessed the keyword") + + +def test_an_incompatible_plane_is_a_denial_not_a_pass_through(): + """The old contract, met by the new engine: silence, an exception, and nonsense all deny. + + ``None`` used to mean *allowed* on this seam — which is how a plane that answers in its own vocabulary + ended up authorizing everything it never answered about. It is in the vocabulary of denials now. + """ + def silent(principal, spec, args): + return None # the pre-authz/v1 shape for "allowed" + + def exploding(principal, spec, args): + raise ConnectionError("the policy plane is unreachable") + + def nonsense(principal, spec, args): + return {"decision": "maybe"} + + for plane, reason in ((silent, "missing_explicit_grant"), (exploding, "no_resource_plane"), + (nonsense, "malformed_request")): + registry = ToolRegistry(authorizer=plane) + registry.register(function_tool("any_tool", lambda a: ToolResult(ok=True, text="ran"), action="read")) + result = registry.run("any_tool", {}) + assert result.ok is False, reason + assert registry.audit[-1]["allowed"] is False + assert registry.audit[-1]["policy_reason"] == reason + + +def test_a_plane_that_allows_by_returning_true_is_audited_as_legacy(): + """Still honoured — the coercion exists so old callers fail visibly, not silently.""" + registry = ToolRegistry(authorizer=lambda p, s, a: True) + registry.register(function_tool("any_tool", lambda a: ToolResult(ok=True, text="ran"), action="read")) + assert registry.run("any_tool", {}).ok + assert registry.audit[-1]["legacy"] is True + assert [a["tool"] for a in registry.unattributed_allows()] == ["any_tool"] + + +# ── 4. calling the engine directly, past the wrappers ──────────────────────────────────────── + + +def test_the_wrapper_is_not_the_gate_direct_execution_meets_the_same_plane(): + """Skipping the console, the fleet and the tenant still does not skip the registry. + + The wrappers add policy that the registry does not know about; they do not add the gate. A caller with + the registry object in hand gets the same answer as a caller who came in through the UI, which is what + makes "we route everything through the console" a statement about tidiness rather than security. + """ + tenant = ModuleTenant(CATALOG["edge_sentinel"], authorizer=_reader) + direct = tenant.registry.run("edge_sentinel_block_ip", {"ip": "1.2.3.4"}) + through_act = tenant.act("block_ip", ip="1.2.3.4") + assert direct.ok is False and through_act.ok is False + assert direct.error == through_act.error # same reason, same depth of door + assert [a["allowed"] for a in tenant.registry.audit] == [False, False] + + +def test_a_diagnostic_surface_cannot_be_asked_to_execute(): + """An authorizer that would say yes to everything is installed, and the call is refused anyway. + + In a diagnostic instance execution is not a policy question with a negative answer — the path is not + built. Nothing a later grant, a wrapper or a caller can do reaches a tool from here. + """ + set_default_authorizer(lambda p, s, a: True) + try: + tenant = ModuleTenant(CATALOG["edge_sentinel"], privileged=False) + with pytest.raises(PrivilegedExecutionUnavailable): + tenant.act("block_ip", ip="1.2.3.4") + + console = AgentConsole("Ops", "A console that reads.", tools=[ + function_tool("read_something", lambda a: ToolResult(ok=True, text="ok"), action="read")], + privileged=False) + assert console.registry.list() == [] # the tools were never registered + with pytest.raises(PrivilegedExecutionUnavailable): + console._answer_tool("read_something", {}) + with pytest.raises(PrivilegedExecutionUnavailable): + console.mount_mcp(object()) + finally: + set_default_authorizer(None) + + +# ── 5. execution after the service has already started ─────────────────────────────────────── + + +def test_removing_the_plane_after_start_up_leaves_nothing_authorized(): + """A grant that walked out of the room does not stay in the room. + + The registry reads the plane at call time, so the lifetime of an authorization is the lifetime of the + decision, not of the object it was asked through. The reverse half — a plane installed after the tenant + was built governs it — is what lets an application import a console before its gate exists. + """ + tenant = ModuleTenant(CATALOG["edge_sentinel"], privileged=False, authorizer_on_missing="deny_later") + registry = tenant.registry + registry.register(function_tool("later_tool", lambda a: ToolResult(ok=True, text="ran"), action="write")) + + def deny_everything(principal, spec, args): + return Authorization(Decision.DENY, reason="revoked", detail="the grant was withdrawn") + + set_default_authorizer(deny_everything) + try: + assert registry.run("later_tool", {}).ok is False + assert registry.audit[-1]["policy_reason"] == "revoked" + finally: + set_default_authorizer(None) + + denied = registry.run("later_tool", {}) # nothing cached from when a plane was there + assert denied.ok is False and "no authorizer is installed" in (denied.error or "") + + +def test_a_tool_registered_before_the_plane_arrives_is_governed_by_it_afterwards(): + """The ordering an embedding application depends on: build first, gate second, govern from then on.""" + registry = ToolRegistry() # authorizer read at call time + registry.register(function_tool("later_tool", lambda a: ToolResult(ok=True, text="ran"), action="write")) + assert registry.run("later_tool", {}).ok is False # not yet: nothing has answered for it + + set_default_authorizer(_reader) + try: + assert registry.run("later_tool", {}).ok is False # a plane now says no: write asked, read held + # The plane answered in the pre-authz/v1 shape (a string means deny), which the engine honours and + # marks. What matters here is that the plane was consulted at all, after the registry was built. + assert registry.audit[-1]["policy_reason"] == "missing_explicit_grant" + assert registry.audit[-1]["legacy"] is True + finally: + set_default_authorizer(None) + + +def test_the_posture_of_a_process_is_not_decided_by_an_unset_or_typoed_variable(monkeypatch): + """The mode is read where it is used, and an unset variable lands on the strict side. + + No mode means "this process runs tools", which is the assumption that has to be paid for at start-up; + a typo must not fall through to the permissive branch, because the permissive branch is the one that + ships. + """ + monkeypatch.delenv(EXECUTION_MODE_ENV, raising=False) + assert execution_mode() == ("execute", "") + monkeypatch.setenv(EXECUTION_MODE_ENV, "diagnostc") + with pytest.raises(RegistryConfigurationError, match="is not a mode"): + execution_mode() + monkeypatch.setenv(EXECUTION_MODE_ENV, "read-only") + with pytest.raises(RegistryConfigurationError, match="CR_DIAGNOSTIC_REASON"): + execution_mode() \ No newline at end of file diff --git a/tests/test_container.py b/tests/test_container.py index 45471eb..ca72704 100644 --- a/tests/test_container.py +++ b/tests/test_container.py @@ -1,7 +1,15 @@ -"""The control-plane image builds, starts, and fails closed. +"""The control-plane image builds, and what it does without a plane is the point of the file. + +Builds the repository Dockerfile and starts it on loopback only: + +* with nothing configured it **refuses to start** — a control plane whose every tool call would come back + ``missing_explicit_grant`` is not a running service, and a container that exits says so in the one place + an operator looks; +* declared diagnostic, it boots, says which mode it is on ``/health``, and refuses the routes that would + make it execute; +* declared locally authoritative, it boots and behaves like the service it is: ``/health`` answers, a + protected route is 503 with no key configured, 401 with a wrong key and 200 with the key. -Builds the repository Dockerfile, starts it on loopback only and checks: GET /health answers, a -protected route answers 503 with no key configured, 401 with a wrong key and 200 with the key. Skipped when docker (or its daemon) is not available. Synthetic keys only. """ from __future__ import annotations @@ -20,6 +28,9 @@ ROOT = Path(__file__).resolve().parent.parent KEY = "container-test-synthetic-key-0001" +#: What a container on the operator's own machine says when it has no permissions plane to install. A +#: sentence, not ``1`` — the same discipline the tool-registry seam applies to a local-trust switch. +LOCAL_AUTHORITY = "container test: an operator's own laptop, synthetic tenants, no real vendor reachable" def _docker_ready() -> bool: @@ -56,50 +67,155 @@ def _get(url: str, key: str | None = None) -> tuple[int, str]: return e.code, e.read().decode() -def _run(image: str, env: dict[str, str], started: list[str]) -> str: - """Start the image on loopback, register the container for cleanup, wait for /health, return the base URL.""" +def _post(url: str, key: str | None = None, body=None) -> tuple[int, str]: + data = json.dumps(body if body is not None else []).encode() + headers = {"content-type": "application/json", **({"X-API-Key": key} if key else {})} + req = urllib.request.Request(url, data=data, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=10) as r: # noqa: S310 (loopback) + return r.status, r.read().decode() + except urllib.error.HTTPError as e: + return e.code, e.read().decode() + + +@pytest.fixture(scope="module") +def control_plane_image(): + """One build for the three containers this file starts — the image is the subject, not the build.""" + if not _docker_ready(): + pytest.skip("a Linux docker engine is not available (no docker, or a Windows-containers daemon)") + image = f"context-runtime-control-plane-test:{uuid.uuid4().hex[:12]}" + build = subprocess.run(["docker", "build", "-q", "-t", image, str(ROOT)], + capture_output=True, text=True, encoding="utf-8", timeout=1800) + assert build.returncode == 0, build.stderr[-1500:] + yield image + subprocess.run(["docker", "rmi", "-f", image], capture_output=True) + + +def _start(image: str, env: dict[str, str], started: list[str]) -> str: + """``docker run -d`` with the given environment; registers the container for cleanup.""" args = ["docker", "run", "-d", "-p", "127.0.0.1::8080"] for k, v in env.items(): args += ["-e", f"{k}={v}"] - cid = subprocess.run([*args, image], capture_output=True, text=True, encoding="utf-8", check=True).stdout.strip() + cid = subprocess.run([*args, image], capture_output=True, text=True, encoding="utf-8", + check=True).stdout.strip() started.append(cid) - port_line = subprocess.run(["docker", "port", cid, "8080/tcp"], capture_output=True, text=True, encoding="utf-8", check=True).stdout - port = port_line.strip().splitlines()[0].rsplit(":", 1)[1] - base = f"http://127.0.0.1:{port}" + return cid + + +def _base(cid: str) -> str: + line = subprocess.run(["docker", "port", cid, "8080/tcp"], capture_output=True, text=True, + encoding="utf-8", check=True).stdout + return f"http://127.0.0.1:{line.strip().splitlines()[0].rsplit(':', 1)[1]}" + + +def _logs(cid: str) -> str: + out = subprocess.run(["docker", "logs", "--tail", "60", cid], capture_output=True, text=True, + encoding="utf-8") + return (out.stdout or "") + (out.stderr or "") + + +def _state(cid: str) -> tuple[bool, int]: + """``(running, exit_code)``.""" + line = subprocess.run(["docker", "inspect", "-f", "{{.State.Running}} {{.State.ExitCode}}", cid], + capture_output=True, text=True, encoding="utf-8", check=True).stdout.split() + return line[0] == "true", int(line[1]) + + +def test_the_image_refuses_to_start_with_nothing_to_ask(control_plane_image): + """The default posture of a privileged service with no plane is to not be running. + + This is the behaviour the container test used to assert the opposite of: the image came up, answered + ``/health`` with ``{"status": "ok"}``, and denied every tool call its fleet would ever make. A green + health check over a fleet that cannot act is the failure this whole seam exists to remove, so the + container now exits, and says which of the three doors to open. + """ + started: list[str] = [] + try: + cid = _start(control_plane_image, {}, started) + for _ in range(240): + running, code = _state(cid) + if not running: + assert code != 0, f"the container exited 0 having refused to serve: {_logs(cid)[-600:]}" + logs = _logs(cid) + assert "refusing to start" in logs, logs[-800:] + assert "CR_LOCAL_AUTHORITY" in logs and "CR_EXECUTION_MODE" in logs # names the exits + return + time.sleep(0.5) + raise AssertionError(f"container was still running after 120s: {_logs(cid)[-800:]}") + finally: + for cid in started: + subprocess.run(["docker", "rm", "-f", cid], capture_output=True) + + +def test_the_image_boots_diagnostic_and_has_nothing_to_execute(control_plane_image): + """The other door: a read-only instance may boot without a plane, and then has no execution path. + + It says so on the public health route — the one place a dashboard looks — and the routes that would + make it act answer 503 instead of quietly standing tenants up with no way to authorize them. + """ + started: list[str] = [] + try: + cid = _start(control_plane_image, {"CONTEXT_RUNTIME_API_KEY": KEY, + "CR_EXECUTION_MODE": "diagnostic", + "CR_DIAGNOSTIC_REASON": "container test: a read-only console with " + "no vendor credentials behind it"}, started) + base = _wait_ready(cid) + health = json.loads(_get(base + "/health")[1]) + assert health["status"] == "ok" and health["privileged_execution"] is False + assert health["mode"] == "diagnostic" + assert _post(base + "/up", KEY, ["agentic-billing"])[0] == 503 + assert _post(base + "/agent/run", KEY, {"module": "control-tower", "question": "q"})[0] == 503 + assert _post(base + "/dispatch", KEY, {"module": "agentic-billing", "agent": "checkout", + "action": "refund", "prompt": "x"})[0] == 503 + # the read side of the surface is untouched: the fleet is still describable + assert _get(base + "/status", KEY)[0] == 200 + finally: + for cid in started: + subprocess.run(["docker", "rm", "-f", cid], capture_output=True) + + +def _run(image: str, env: dict[str, str], started: list[str]) -> str: + """Start the image on loopback, register the container for cleanup, wait for /health, return the base URL.""" + cid = _start(image, env, started) + return _wait_ready(cid) + + +def _wait_ready(cid: str) -> str: + """Wait for the container to answer /health; a container that exits is a failure with its logs attached.""" + base = _base(cid) for _ in range(120): try: if _get(base + "/health")[0] == 200: return base except OSError: pass - if subprocess.run(["docker", "inspect", "-f", "{{.State.Running}}", cid], - capture_output=True, text=True, - encoding="utf-8").stdout.strip() != "true": - logs = subprocess.run(["docker", "logs", "--tail", "20", cid], capture_output=True, text=True, - encoding="utf-8") - raise AssertionError("container exited: " + (logs.stdout + logs.stderr)[-800:]) + if not _state(cid)[0]: + raise AssertionError("container exited: " + _logs(cid)[-800:]) time.sleep(0.5) raise AssertionError("container did not answer /health") @pytest.mark.skipif(not _docker_ready(), reason="a Linux docker engine is not available (no docker, or a Windows-containers daemon)") -def test_image_builds_starts_and_fails_closed(): - image = f"context-runtime-control-plane-test:{uuid.uuid4().hex[:12]}" +def test_image_starts_locally_authoritative_and_fails_closed(control_plane_image): + """The execution posture, declared: the service comes up and the access rules hold. + + It carries ``CR_LOCAL_AUTHORITY`` because that is what makes a bare container legal to start at all — + the sentence a laptop demo tells the gate, audited as a wildcard grant rather than assumed. Without it + the container refuses to start, which the test above asserts on its own. + """ cids: list[str] = [] + authority = {"CR_LOCAL_AUTHORITY": LOCAL_AUTHORITY} try: - build = subprocess.run(["docker", "build", "-q", "-t", image, str(ROOT)], - capture_output=True, text=True, encoding="utf-8", timeout=900) - assert build.returncode == 0, build.stderr[-1500:] - # no key configured: the health route answers, everything else is 503 - base = _run(image, {}, cids) - assert json.loads(_get(base + "/health")[1]) == {"status": "ok"} + base = _run(control_plane_image, dict(authority), cids) + assert json.loads(_get(base + "/health")[1]) == {"status": "ok", "mode": "execute", + "privileged_execution": True} for path in ("/approvals", "/status", "/api/fleet", "/notify/status", "/agent/policy/control-tower", "/v1/models"): assert _get(base + path)[0] == 503, path assert _get(base + "/approvals", "any-key")[0] == 503 # key configured: 401 without or with a wrong key, 200 with the key - base = _run(image, {"CONTEXT_RUNTIME_API_KEY": KEY}, cids) + base = _run(control_plane_image, {"CONTEXT_RUNTIME_API_KEY": KEY, **authority}, cids) assert _get(base + "/health")[0] == 200 assert _get(base + "/approvals")[0] == 401 assert _get(base + "/approvals", "wrong-key")[0] == 401 @@ -109,4 +225,3 @@ def test_image_builds_starts_and_fails_closed(): finally: for c in cids: subprocess.run(["docker", "rm", "-f", c], capture_output=True) - subprocess.run(["docker", "rmi", "-f", image], capture_output=True) diff --git a/tests/test_control_plane.py b/tests/test_control_plane.py index 9320a56..7191071 100644 --- a/tests/test_control_plane.py +++ b/tests/test_control_plane.py @@ -20,7 +20,11 @@ def _configured_server(monkeypatch): def test_health_reports_registry(): - assert anonymous.get("/health").json() == {"status": "ok"} # liveness only, no operational detail + # Liveness, and exactly two fields beyond it: whether this process can execute at all. A fleet that + # denies every call used to answer this route identically to one that works, which is how a broken + # authorization plane survived a green dashboard. Nothing else about the deployment belongs here. + assert anonymous.get("/health").json() == {"status": "ok", "mode": "execute", + "privileged_execution": True} assert len(client.get("/modules").json()) >= 14 @@ -51,7 +55,9 @@ def test_money_action_is_approval_gated(): assert d.json()["kind"] == "approval" -def test_down_up_cycle_changes_deployed_state(): +def test_down_up_cycle_changes_deployed_state(local_run): + """Taking a module down and up again. ``local_run`` because /up builds the tenant, and a tenant that + can execute refuses to be built with nothing to ask — the same refusal that stops a container.""" client.post("/down", json=["agentic-billing"]) after = {m["name"]: m["deployed"] for m in client.get("/status").json()} assert after["agentic-billing"] is False diff --git a/tests/test_control_plane_access.py b/tests/test_control_plane_access.py index dc89c11..fd8d570 100644 --- a/tests/test_control_plane_access.py +++ b/tests/test_control_plane_access.py @@ -111,7 +111,15 @@ def test_no_websocket_routes(): def test_health_is_public_and_minimal(no_key): r = no_key.get("/health") - assert r.status_code == 200 and r.json() == {"status": "ok"} + body = r.json() + assert r.status_code == 200 + # "Minimal" used to mean one key. It now means three, and the two that were added are the ones that + # stop an unauthorized caller from learning nothing while an operator learns everything: an instance + # with no authorization plane must not be able to answer this route like a working one. Anything beyond + # these three keys is operational detail and stays off the unauthenticated route. + assert set(body) == {"status", "mode", "privileged_execution"}, body + assert body["status"] == "ok" and body["mode"] in ("execute", "diagnostic") + assert isinstance(body["privileged_execution"], bool) @pytest.mark.parametrize("method,path", sorted(k for k, v in EXPECTED.items() if v != PUBLIC and k[0] != "*")) diff --git a/tests/test_demo_proxy.py b/tests/test_demo_proxy.py index 6685775..3d50dfa 100644 --- a/tests/test_demo_proxy.py +++ b/tests/test_demo_proxy.py @@ -100,7 +100,15 @@ def __init__(self, tmp: Path): app_env = {**base, "CONTEXT_RUNTIME_HOME": str(home / "cr"), "CONTEXT_RUNTIME_API_KEY": ADMIN_KEY, "CR_TENANT_KEYS": f"{READ_KEY}=*", "CONTEXT_RUNTIME_CORPUS_ROOT": str(self.root), - "CR_TENANTS": f"demo-finance={self.root / 'a'} | demo-medical={self.root / 'b'}"} + "CR_TENANTS": f"demo-finance={self.root / 'a'} | demo-medical={self.root / 'b'}", + # This backend is launched as a bare uvicorn process, and a control plane that runs tools + # now refuses to start with nothing to ask. Every other part of this test is about the + # proxy in front of it, so the app declares what a demo box on the operator's own machine + # declares — local authority, in a sentence, audited as a wildcard grant. The alternative + # is CR_EXECUTION_MODE=diagnostic, which would take the fleet's execution path away and + # leave the routes under test with nothing behind them. + "CR_LOCAL_AUTHORITY": "test stack: a control plane on the operator's own laptop, no " + "tenant in scope"} self.procs.append(subprocess.Popen( [sys.executable, "-m", "uvicorn", "context_runtime.control_plane.app:app", "--host", "127.0.0.1", "--port", str(self.app_port), "--log-level", "warning"], diff --git a/tests/test_injected_tool_classification.py b/tests/test_injected_tool_classification.py index 3003666..1c9bc62 100644 --- a/tests/test_injected_tool_classification.py +++ b/tests/test_injected_tool_classification.py @@ -1,4 +1,4 @@ -"""An injected implementation earns its class: a floor by default, a contract to get under it. +"""An injected implementation is refused by default, and what it takes to be allowed in anyway. Every integration tenant ships a local simulation of one tool — it builds a string and hands it back, so the class it was reviewed at is ``read`` (``market_radar`` is the exception: a sweep fetches and stores, so it is @@ -10,11 +10,21 @@ class it was reviewed at is ``read`` (``market_radar`` is the exception: a sweep function that posts to a vendor ran on a principal holding only a read grant; * **self-declared** — let the caller simply say ``read`` and nothing has been gained, only moved. -So an injected function sits at a floor of ``write``, and the only way below it is :func:`pure_read`, whose -argument has to be a sentence about why the function is inert — checked against the function's own source, -using the sink vocabulary the platform's FR-04 sweep uses. A visible ``post`` beats any declaration, and so -does a visible ``rmtree`` one class lower. The shipped simulations keep the ``read`` they were audited at: -this file exists to prove that ``draft_caption`` really is one. +The answer used to be a floor: an injected function sat at ``write`` unless its author contracted lower. That +was a third way of grading your own risk — a class the caller got by saying nothing, in the same statement +that swapped the code in — and it has been removed. Delegation is now refused unless it is authorized: + +* **``delegated(action=…, authority=…, via=…, review=…)``** — the class, who authorized a callable from + outside this repository to hold it, what the callable hands its arguments to, and the review that connects + them. Refused below ``write``, refused with a label in place of any of the three sentences, refused when + the wrapper's own source reaches further than the class it asks for. +* **``pure_read(reason)``** — not authorized but *proved*: the claim is checked against the callable's source + with the sink vocabulary the platform's FR-04 sweep uses, and against the callees that source hands its + arguments to. A visible ``post`` beats a declaration, so does a visible ``rmtree`` one class lower, and so + does a client object this repository cannot see inside. + +The shipped simulations keep the ``read`` they were audited at: this file exists to prove that +``draft_caption`` really is one. """ from __future__ import annotations @@ -25,8 +35,14 @@ class it was reviewed at is ``read`` (``market_radar`` is the exception: a sweep from agent_harness.tools import Authorization from context_runtime.tools import pure_read +from context_runtime.tools import delegated from context_runtime.tools.base import RegistryConfigurationError, ToolResult +#: An authorization with everything in it, for the tests whose subject is not the paperwork. +_AUTH = dict(authority="grant agentic-os:fleet/sec-41 block_ip (ticket SEC-41)", + via="sentinel_client.Client.block_ip, an HTTPS PUT to the Sentinel API", + review="read the client on 2026-11-22: it writes to one vendor API and holds nothing locally") + #: module, tenant class, factory hook, the class-declaring keyword, registered tool, reviewed class. TENANTS = [ ("control_tower", "ControlTowerTenant", "refresh_tool_factory", "refresh_action", "refresh_metabase", "read"), @@ -65,6 +81,18 @@ def _inert(args: dict) -> ToolResult: class _VendorClient: def post(self, path: str, payload: dict) -> dict: return {"id": "remote-draft"} +class _HiddenClient: + """A client whose method is not in the sink vocabulary — the effect is real, the verb is not a verb.""" + + def dispatch(self, payload: dict) -> dict: + return {"id": "remote-draft"} + + +def _delegating_wrapper(args: dict) -> ToolResult: + """A wrapper with nothing to see: no sink named here at all, and everything happening over there.""" + return ToolResult(ok=True, text=str(_HiddenClient().dispatch(args))) + + def _vendor_post(args: dict) -> ToolResult: @@ -107,7 +135,7 @@ def test_the_shipped_caption_is_actually_inert_not_just_labelled_inert(): assert result.ok and result.data["channel"] == "linkedin" -# ─────────────────────────── the floor: no guessing ─────────────────────────── +# ─────────────────── delegation is refused before it is classified ─────────────────── @pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) @@ -121,10 +149,17 @@ def test_a_replacement_without_a_class_of_its_own_refuses_to_start(module, cls, @pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) -def test_a_replacement_declared_at_or_above_the_floor_is_registered_as_declared(module, cls, factory, action_kw, - tool, shipped): - tenant = _tenant(module, cls, **{factory: _vendor_post, action_kw: "write"}) - assert tenant.registry.get(tool).spec().action == "write" +def test_a_bare_class_for_a_replacement_is_refused_however_conservative_it_is(module, cls, factory, action_kw, + tool, shipped): + """The removed floor, asserted as removed. ``write`` was the safe-sounding answer and it was still the + caller's own: a class a caller gets by saying nothing, in the same statement that swapped the code in, is + a grant nobody reviewed. Both ends of the vocabulary are refused, and the refusal teaches the form.""" + for bare in ("read", "write", "delete"): + with pytest.raises(RegistryConfigurationError) as exc: + _tenant(module, cls, **{factory: _vendor_post, action_kw: bare}) + message = str(exc.value) + assert "no authority" in message and "delegated(" in message + assert action_kw in message # names the keyword the caller has to fix @pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) @@ -139,10 +174,20 @@ def test_a_class_outside_the_vocabulary_refuses_to_start(module, cls, factory, a @pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) def test_an_injected_function_cannot_claim_read_by_saying_read(module, cls, factory, action_kw, tool, shipped): - """The word is the downgrade. Below the floor has to be a deliberate claim, in its own type.""" + """The word is the downgrade, and so is the word two classes up. A class string names no authority.""" with pytest.raises(RegistryConfigurationError) as exc: _tenant(module, cls, **{factory: _inert, action_kw: "read"}) - assert "below the floor" in str(exc.value) and "pure_read" in str(exc.value) + message = str(exc.value) + assert "no authority" in message and "pure_read" in message and "delegated(" in message + + +@pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) +def test_an_authorized_delegation_is_registered_at_the_class_it_was_authorized_for(module, cls, factory, + action_kw, tool, shipped): + """What replaced the floor: the same ``write``, now with someone's name on it, and it registers.""" + tenant = _tenant(module, cls, **{factory: _vendor_post, + action_kw: delegated(action="write", **_AUTH)}) + assert tenant.registry.get(tool).spec().action == "write" @pytest.mark.parametrize("module,cls,factory,action_kw,tool,shipped", TENANTS, ids=_IDS) @@ -159,14 +204,61 @@ def test_a_deleting_function_cannot_hide_one_class_below_delete(): """The same under-declaration one rung lower: a ``rmtree`` registered as ``write`` still loses data.""" with pytest.raises(RegistryConfigurationError) as exc: _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_wipes, - caption_action="write") + caption_action=delegated(action="write", **_AUTH)) assert "rmtree" in str(exc.value) and "delete" in str(exc.value) strict = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_wipes, - caption_action="delete") + caption_action=delegated(action="delete", **_AUTH)) assert strict.registry.get("draft_caption").spec().action == "delete" +def test_a_delegation_cannot_be_authorized_into_the_read_class(): + """Prose buys a strong class; only source evidence buys a weak one. The asymmetry is the whole design: a + ``delegated(read)`` is a smaller grant than ``delegated(write)``, which is exactly why the code asking to + run would reach for it, and exactly why three sentences from it cannot be what earns it.""" + with pytest.raises(RegistryConfigurationError) as exc: + delegated(action="read", **_AUTH) + assert "prose" in str(exc.value) and "pure_read" in str(exc.value) + + +@pytest.mark.parametrize("missing,label", [ + ("authority", "SEC-41"), ("authority", ""), + ("via", "client"), ("via", ""), + ("review", "checked"), ("review", ""), +]) +def test_an_authorization_with_a_label_where_a_sentence_belongs_is_refused(missing, label): + """Each of the three sentences is load-bearing, so each is checked separately. + + ``authority="SEC-41"`` is the one that will be argued about: a ticket reference looks like provenance and + is, until the ticket is closed and nobody can tell whether it authorized ``write`` or merely mentioned the + tool. What a reviewer needs in the manifest is the sentence, which is why a label is refused here rather + than allowed and grepped for later. The empty string is the same case with the paperwork left off. + """ + thin = dict(_AUTH) + thin[missing] = label + with pytest.raises(RegistryConfigurationError) as exc: + delegated(action="write", **thin) + assert missing in str(exc.value) + + +def test_a_wrapper_that_hides_where_it_delegates_cannot_be_registered_as_a_read(): + """The blind spot the floor used to cover, and the reason a floor was not enough. + + The sink sweep reads the callable's own source. A wrapper that hands its arguments to a client object it + did not build has no visible sink — nothing named ``post`` or ``write_text`` appears anywhere in it — so a + ``pure_read`` claim about it used to be checked and pass. It is now refused for what it is: a claim this + repository cannot check. Authorizing the same callable takes an authority, a callee and a review. + """ + hidden = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_delegating_wrapper, + caption_action=delegated(action="write", **_AUTH)) + assert hidden.registry.get("draft_caption").spec().action == "write" + with pytest.raises(RegistryConfigurationError) as exc: + _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_delegating_wrapper, + caption_action=pure_read(_INERT_REASON)) + message = str(exc.value) + assert "_HiddenClient" in message and "delegated(" in message + + def test_a_function_with_no_readable_source_cannot_claim_read(): """No source, no evidence, no waiver: an unreadable callable is assumed consequential.""" with pytest.raises(RegistryConfigurationError) as exc: @@ -239,7 +331,7 @@ def test_a_replaced_caption_no_longer_runs_on_a_read_grant(): assert shipped.registry.run("draft_caption", {"goal": "g", "channel": "linkedin"}).ok live = _tenant("social_autopilot", "SocialAutopilotTenant", caption_tool_factory=_vendor_post, - caption_action="write", authorizer=_read_only_plane) + caption_action=delegated(action="write", **_AUTH), authorizer=_read_only_plane) denied = live.registry.run("draft_caption", {"goal": "g", "channel": "linkedin"}) assert not denied.ok and "no 'write' grant" in (denied.error or "") assert live.registry.audit[-1]["allowed"] is False diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 239fac7..ba6726d 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -94,7 +94,10 @@ def _run_with_client_and_registry(policy: ApprovalPolicy | None = None): f.write(FAKE_SERVER) client = MCPClient.stdio([sys.executable, fake_path]) try: - names = mount_mcp(reg, client) + # No class is declared for this fake server's tools, so the mount says in one place that the + # whole server is assumed consequential. mount_mcp has no default class of its own to fall + # back to: with neither an actions map nor a default, it mounts nothing at all. + names = mount_mcp(reg, client, default_action="write") return reg, names, client except Exception: client.close() @@ -144,7 +147,7 @@ def test_mcp_tools_are_gated_by_approval_policy(local_run): f.write(FAKE_SERVER) client2 = MCPClient.stdio([sys.executable, fake_path]) try: - mount_mcp(reg2, client2) + mount_mcp(reg2, client2, default_action="write") res2 = reg2.run("echo", {"text": "allow"}) assert res2.ok is True assert "allow" in res2.text diff --git a/tests/test_mcp_actions.py b/tests/test_mcp_actions.py index 4104eb8..bc792a2 100644 --- a/tests/test_mcp_actions.py +++ b/tests/test_mcp_actions.py @@ -69,14 +69,18 @@ def _runnable(*names, authorizer): return ToolRegistry(policy=ApprovalPolicy("allowlist", allow=list(names)), authorizer=authorizer) -def test_mounted_mcp_tool_defaults_to_write(): - """No class declared means the strictest class every capability must clear — not ``read`` because the - server said it was one, and not a free pass from having no class at all.""" +def test_a_tool_nobody_classed_is_not_mounted_at_all(): + """Refused by default, and refused structurally: the tool is not in the registry, so there is no call + for a plane to deny and no grant that could accidentally match it. The signature used to carry + ``default_action="write"``, which handed out a risk class to a mount that had not read the server — + a floor in the same shape as the one the injected-factory seam just lost.""" spy, seen = _spy() reg = _runnable("convert_video", authorizer=spy) - mount_mcp(reg, FakeMCPClient([_tool("convert_video")])) - assert reg.run("convert_video", {}).ok - assert seen == [("convert_video", "write", True)] + with pytest.warns(UserWarning, match="no risk class"): + names = mount_mcp(reg, FakeMCPClient([_tool("convert_video")])) + assert names == [] and reg.list() == [] + assert reg.run("convert_video", {}).ok is False + assert seen == [] # nothing was registered, so nothing was ever asked about def test_read_only_hint_relaxes_approval_but_never_the_class(): @@ -84,7 +88,7 @@ def test_read_only_hint_relaxes_approval_but_never_the_class(): and it stops there.""" spy, seen = _spy() reg = ToolRegistry(authorizer=spy) - mount_mcp(reg, FakeMCPClient([_tool("search", readOnlyHint=True)])) + mount_mcp(reg, FakeMCPClient([_tool("search", readOnlyHint=True)]), default_action="write") assert reg.run("search", {}).ok assert seen == [("search", "write", False)] # not confirmed, still authorized as a write diff --git a/tests/test_platform_services.py b/tests/test_platform_services.py index 95752a1..dcfa048 100644 --- a/tests/test_platform_services.py +++ b/tests/test_platform_services.py @@ -461,7 +461,10 @@ def test_control_plane_state_defaults_to_no_working_directory_path(tmp_path, mon monkeypatch.setenv("USERPROFILE", str(tmp_path / "h")) monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "h" / "AppData" / "Local")) monkeypatch.chdir(tmp_path) - fleet = Fleet(Registry.load()) + # A privileged fleet now refuses to be built with no plane to ask, so the state-path check asks for the + # one fleet that has nothing to authorize: diagnostic, no tenants, no execution path. The subject of the + # test is where the fleet keeps its files, and that answer does not depend on the posture. + fleet = Fleet(Registry.load(), privileged=False) assert fleet.home.is_absolute() and str(tmp_path / "h") in str(fleet.home) assert not (tmp_path / ".context-runtime").exists() diff --git a/tests/test_web_search_mcp.py b/tests/test_web_search_mcp.py index a2e9fd7..c89493d 100644 --- a/tests/test_web_search_mcp.py +++ b/tests/test_web_search_mcp.py @@ -24,7 +24,9 @@ def test_web_search_mounts_as_readonly_tool(): console = AgentConsole("X", "A watch monitors a URL.", tools=[tool("noop", "noop", lambda a: {"text": "ok"})]) client = _client() try: - names = console.mount_mcp(client) + # This server ships in this repository and only fetches, so the mount can name the class instead of + # relying on one: read, stated here, reviewed with the source it describes. + names = console.mount_mcp(client, actions={"web_search": "read"}) assert "web_search" in names assert "web_search" in console._tools # visible to classify + dispatch spec = console.registry.get("web_search").spec() From f81b7be69e3c696efecc1277643a2cc41b3eefa6 Mon Sep 17 00:00:00 2001 From: Alex Mats Date: Sun, 22 Nov 2026 20:50:36 -0500 Subject: [PATCH 14/15] fix(authz): stop MCP readOnlyHint from suppressing the approval gate Finding M1 of the independent authorization-stack security review: MCPToolPlugin.spec() computed side_effecting from the MCP server's own untrusted readOnlyHint annotation whenever one was present, for any non-"read" action. A server could therefore talk a tool the operator had explicitly mounted as "write" or "delete" out of needing approval by self-reporting readOnlyHint=true, making ApprovalPolicy's gate a no-op. Reproduced live: a fake wipe_database tool, classified "write", under a deny-by-default approval policy with no approver configured, executed for real. side_effecting for a non-"read" action is now exactly bool(default_side_effecting) -- the operator's own mount-time configuration -- with no influence from any MCP annotation. A missing, false, true, or malformed readOnlyHint all now have the same effect: none. "read" actions are unaffected (already forced side_effecting to False regardless of any hint). Confirmed the adjacent delegated()/pure_read() classification seam in context_runtime/tools/actions.py was never vulnerable to this same class of bug: it only ever reads a wrapper's own source (write_sinks, opaque_callees), never a wrapped MCP client's self-reported metadata. Rewrote the one existing test that asserted the vulnerable behavior as correct (test_read_only_hint_relaxes_approval_but_never_the_class) and added regression coverage: the delete-class equivalent, every missing/false/true/malformed annotation shape, the legitimate approved-write path, and a cross-check that the actions.py seam already refuses this attack shape. --- context_runtime/tools/mcp.py | 24 ++++++---- tests/test_mcp_actions.py | 93 ++++++++++++++++++++++++++++++++---- 2 files changed, 100 insertions(+), 17 deletions(-) diff --git a/context_runtime/tools/mcp.py b/context_runtime/tools/mcp.py index e7ad0bf..499ed95 100644 --- a/context_runtime/tools/mcp.py +++ b/context_runtime/tools/mcp.py @@ -247,8 +247,9 @@ def __init__(self, tool_desc: dict[str, Any], client: MCPClient, *, name: str | default_side_effecting: bool = True, action: str = "write") -> None: """``action`` is the risk class this tool is asked about — set by whoever mounts the server. - The server's ``readOnlyHint`` is an announcement from the code being run; it moves the - approval gate and nothing else. An MCP tool with no declared class is therefore ``write``. + The server's ``readOnlyHint`` is an announcement from the code being run; it has no effect on + either the authorization class or the approval gate. An MCP tool with no declared class is + therefore ``write``. """ if action not in ACTIONS: raise RegistryConfigurationError( @@ -265,8 +266,15 @@ def spec(self) -> ToolSpec: mcp_name = self._desc.get("name") or self._name desc = self._desc.get("description") or "" schema = self._desc.get("inputSchema") or self._desc.get("input_schema") or {"type": "object", "properties": {}} - ann = self._desc.get("annotations") or {} - read_only = bool(ann.get("readOnlyHint")) if "readOnlyHint" in ann else False + # ``readOnlyHint`` (and every other MCP annotation) is an announcement from the code being run, + # not from anyone this repository trusts to grade its own risk. It is read nowhere in this method: + # the operator's own ``action`` classification (passed to ``mount_mcp``'s ``actions``/``default_action``, + # after someone read what the server does) is the only input to both the authorization class and the + # approval gate below. A server cannot talk a ``write``/``delete`` tool out of needing approval by + # calling itself read-only, and a missing, false, true, or malformed hint all have the same effect: + # none. (Fixes M1: a prior version let ``readOnlyHint: true`` set ``side_effecting=False`` for a + # non-``read`` action, which made ``ApprovalPolicy`` skip the approval gate entirely.) + # # ``read`` and ``side_effecting`` cannot both be true: the engine refuses a spec that asks to be # authorized as the weakest class while declaring that it mutates something. When the operator # classified this tool ``read``, that classification is the authoritative statement about it — @@ -274,7 +282,7 @@ def spec(self) -> ToolSpec: if self._action == "read": side = False else: - side = (not read_only) if "readOnlyHint" in ann else bool(self._default_side) + side = bool(self._default_side) return ToolSpec( name=self._name, description=desc, @@ -328,9 +336,9 @@ def mount_mcp( was given, it gets nothing: it is not mounted, and the refusal is reported. There used to be a ``write`` sitting in the signature as the default, which is a risk class a caller could receive without ever choosing one; the class for an unread server is now something the mount has to say. - An announced ``readOnlyHint`` may relax the *approval* gate, never the authorization class, because - the thing asking to be run is not allowed to grade its own risk. ``actions`` values and - ``default_action`` must come from the shared vocabulary ``ACTIONS``. + An announced ``readOnlyHint`` affects neither the authorization class nor the approval gate: the + thing asking to be run is not allowed to grade its own risk, in either direction. ``actions`` values + and ``default_action`` must come from the shared vocabulary ``ACTIONS``. Returns the list of registered tool names — tools refused for want of a class are absent from it. """ if default_action is not None and default_action not in ACTIONS: diff --git a/tests/test_mcp_actions.py b/tests/test_mcp_actions.py index bc792a2..26d5282 100644 --- a/tests/test_mcp_actions.py +++ b/tests/test_mcp_actions.py @@ -1,9 +1,12 @@ """MCP tools are mounted with a class the operator declared, never one the server claimed. An MCP server is code pulled from somewhere else, and ``readOnlyHint`` is its own announcement about itself. -The registry's rule is that the caller declares what it is about to run: the hint may relax the *approval* -gate — an announced read-only tool need not be confirmed — and it may never relax the authorization class, -which is what decides whether the call happens at all. +The registry's rule is that the caller declares what it is about to run: the hint affects neither the +authorization class nor the approval gate. (A prior version let the hint relax the approval gate for a +non-``read`` action — ``side_effecting`` dropped to ``False`` whenever a server claimed ``readOnlyHint: true``, +which made :class:`ApprovalPolicy` skip the approval step entirely for a tool the operator had explicitly +classified ``write``/``delete``. That was Finding M1 of the authorization-stack review: a malicious or +careless server could talk its own consequential tool out of needing approval. Fixed — see below.) The doubles here return a typed :class:`~context_runtime.tools.base.Authorization`, and that is deliberate: under ``authz/v1`` an authorizer that returns ``None`` is a *denial*, so the instinctive ``lambda *a: None`` @@ -83,14 +86,86 @@ def test_a_tool_nobody_classed_is_not_mounted_at_all(): assert seen == [] # nothing was registered, so nothing was ever asked about -def test_read_only_hint_relaxes_approval_but_never_the_class(): - """The hint is an announcement from the code being run: it may stop the call needing confirmation, - and it stops there.""" +def test_read_only_hint_has_no_effect_on_approval_or_class(): + """The hint is an announcement from the code being run, not from anyone this registry trusts to grade + its own risk: it changes neither the authorization class nor whether the approval gate engages. A tool + mounted as ``write`` still needs approval even when the server calls itself read-only — the exploit this + test used to validate as correct behavior (M1): under the default ``deny_side_effects`` policy with no + approver, the call is denied, not silently waved through.""" spy, seen = _spy() - reg = ToolRegistry(authorizer=spy) + reg = ToolRegistry(authorizer=spy) # default policy: deny_side_effects, no approver mount_mcp(reg, FakeMCPClient([_tool("search", readOnlyHint=True)]), default_action="write") - assert reg.run("search", {}).ok - assert seen == [("search", "write", False)] # not confirmed, still authorized as a write + result = reg.run("search", {}) + assert result.ok is False + assert "requires approval" in result.error + assert seen == [("search", "write", True)] # side_effecting is true despite the hint; nothing executed + + +def test_read_only_hint_cannot_downgrade_delete_either(): + """The same bug, one class stricter: a server cannot talk a ``delete`` tool out of needing approval by + claiming ``readOnlyHint: true``.""" + spy, seen = _spy() + reg = ToolRegistry(authorizer=spy) + mount_mcp(reg, FakeMCPClient([_tool("wipe", readOnlyHint=True)]), default_action="delete") + result = reg.run("wipe", {}) + assert result.ok is False + assert "requires approval" in result.error + assert seen == [("wipe", "delete", True)] + + +@pytest.mark.parametrize("annotations", [ + {}, # hint absent entirely + {"readOnlyHint": False}, # hint explicitly false + {"readOnlyHint": True}, # hint explicitly true (the exploit shape) + {"readOnlyHint": "yes"}, # malformed: a truthy non-bool + {"readOnlyHint": None}, # malformed: present but null +], ids=["absent", "false", "true", "truthy-string", "null"]) +def test_no_mcp_metadata_shape_can_downgrade_approval(annotations): + """Every combination of missing, false, true, or malformed ``readOnlyHint`` must leave a ``write`` tool + requiring approval — none of them is a code path that was ever meant to grant a pass.""" + spy, seen = _spy() + reg = ToolRegistry(authorizer=spy) + mount_mcp(reg, FakeMCPClient([_tool("search", **annotations)]), default_action="write") + result = reg.run("search", {}) + assert result.ok is False + assert "requires approval" in result.error + + +def test_an_explicitly_approved_write_still_executes_correctly(): + """The fix must not break the legitimate path: a write tool with a real approver that says yes still + runs, hint or no hint.""" + client = FakeMCPClient([_tool("search", readOnlyHint=True)]) + reg = ToolRegistry(authorizer=_grant, + policy=ApprovalPolicy("deny_side_effects", approver=lambda call: True)) + mount_mcp(reg, client, default_action="write") + result = reg.run("search", {}) + assert result.ok, result.error + assert client.calls == [("search", {})] + + +def test_delegated_classification_already_refuses_a_remote_readonlyhint_as_a_source(): + """A second place this class of bug could have been reintroduced: a ``delegated()``/``pure_read()`` + wrapper around an MCP client claiming its own class from the server's hint instead of from whoever read + the code. This module's own classification seam (``context_runtime.tools.actions.resolve_action``) + already refuses to accept a remote ``readOnlyHint`` as a classification source at all — it checks the + wrapper's own source for write sinks and opaque callees, never anything the wrapped MCP client reports + about itself. Confirmed here so a future change to either module cannot silently reopen this path + without a test noticing.""" + from context_runtime.tools import actions + + def wraps_a_consequential_mcp_call(args: dict): + # the fake client's `readOnlyHint=True` on this tool must have no bearing on this wrapper's own + # classification — its own source (an opaque call to a client object) is what gets checked. + client = FakeMCPClient([_tool("delete_everything", readOnlyHint=True)]) + return client.call_tool("delete_everything", args) + + with pytest.raises(actions.RegistryConfigurationError, match="pure_read"): + actions.resolve_action( + shipped="read", + injected=wraps_a_consequential_mcp_call, + declared=actions.pure_read("this just calls the mcp client, which is a readOnlyHint tool"), + tool="delete_everything", context="test", + ) def test_declared_action_is_the_one_asked_about(): From 69fcf6891e90c64ad40a2f0b62da27142f623a6d Mon Sep 17 00:00:00 2001 From: Phase 5 Integration Date: Sun, 22 Nov 2026 21:25:58 -0500 Subject: [PATCH 15/15] chore(deps): bump agent-harness pin to the M2 fix (1259d1b) PR #35 closed the ToolRegistry.get(name).run(args) authorization bypass. Bumps all four pin sites (pyproject.toml, Dockerfile, and the two deploy Dockerfiles) to that commit so this stack's own build actually includes the fix. Recomputed AGENT_HARNESS_SHA256 against the real tarball. Co-Authored-By: Claude Sonnet 5 --- Dockerfile | 4 ++-- deploy/geo-demo/Dockerfile.aks | 4 ++-- deploy/proxmox-demo/Dockerfile.contextruntime | 4 ++-- pyproject.toml | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Dockerfile b/Dockerfile index 5567af0..fb82373 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,8 +14,8 @@ RUN pip install --no-cache-dir "fastapi>=0.110" "uvicorn>=0.29" "httpx>=0.27" "p # application does not import without it. Pinned to the same commit as pyproject.toml, from the commit's # source archive (no git in this image) and verified against the archive's sha256. # tests/test_container.py checks that this commit equals the one in pyproject.toml. -ARG AGENT_HARNESS_COMMIT=10e5c2ae7419e096630fb031ef8204fede125ec9 -ARG AGENT_HARNESS_SHA256=1d3dc387512a068556fb7bd3e49bf63fbf8e6dc263368b02c00ac4bcb7b7f200 +ARG AGENT_HARNESS_COMMIT=1259d1b338e80414b32b863bcc97a0db93db8cd2 +ARG AGENT_HARNESS_SHA256=5e7ac02ec1fdb6e00aba7d7871db870d08f5b89084c4464173354a4ef036e04c RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}" ENV PYTHONPATH=/app diff --git a/deploy/geo-demo/Dockerfile.aks b/deploy/geo-demo/Dockerfile.aks index 9d750cc..600892e 100644 --- a/deploy/geo-demo/Dockerfile.aks +++ b/deploy/geo-demo/Dockerfile.aks @@ -27,8 +27,8 @@ RUN pip install --no-cache-dir -r /tmp/requirements.txt # context_runtime imports agent-harness (its tool contract) at import time, so the application does not start without it. # Pinned to the same commit as the repository's own Dockerfile and pyproject.toml, from the commit's source archive (no git in # this image) and verified against the archive's sha256. tests/test_geo_image.py keeps these two lines equal to the root Dockerfile. -ARG AGENT_HARNESS_COMMIT=10e5c2ae7419e096630fb031ef8204fede125ec9 -ARG AGENT_HARNESS_SHA256=1d3dc387512a068556fb7bd3e49bf63fbf8e6dc263368b02c00ac4bcb7b7f200 +ARG AGENT_HARNESS_COMMIT=1259d1b338e80414b32b863bcc97a0db93db8cd2 +ARG AGENT_HARNESS_SHA256=5e7ac02ec1fdb6e00aba7d7871db870d08f5b89084c4464173354a4ef036e04c RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}" FROM ${PYTHON_IMAGE} diff --git a/deploy/proxmox-demo/Dockerfile.contextruntime b/deploy/proxmox-demo/Dockerfile.contextruntime index 2271466..ebf976a 100644 --- a/deploy/proxmox-demo/Dockerfile.contextruntime +++ b/deploy/proxmox-demo/Dockerfile.contextruntime @@ -8,8 +8,8 @@ RUN pip install --no-cache-dir \ # agent-harness is a base dependency of context_runtime (the application does not import without it); same # commit and archive hash as the top-level Dockerfile and pyproject.toml. -ARG AGENT_HARNESS_COMMIT=10e5c2ae7419e096630fb031ef8204fede125ec9 -ARG AGENT_HARNESS_SHA256=1d3dc387512a068556fb7bd3e49bf63fbf8e6dc263368b02c00ac4bcb7b7f200 +ARG AGENT_HARNESS_COMMIT=1259d1b338e80414b32b863bcc97a0db93db8cd2 +ARG AGENT_HARNESS_SHA256=5e7ac02ec1fdb6e00aba7d7871db870d08f5b89084c4464173354a4ef036e04c RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}" COPY context_runtime /app/context_runtime diff --git a/pyproject.toml b/pyproject.toml index edf2bbb..f883fe4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,7 +16,7 @@ license = { text = "AGPL-3.0-or-later WITH Commons-Clause" } # because what it depends on now is what the engine does with what it was handed. dependencies = [ "pyyaml>=6.0", - "agent-harness @ git+https://github.com/redevops-io/agent-harness.git@10e5c2ae7419e096630fb031ef8204fede125ec9", + "agent-harness @ git+https://github.com/redevops-io/agent-harness.git@1259d1b338e80414b32b863bcc97a0db93db8cd2", ] [project.optional-dependencies]