From 558ea31090df939ce4b8bdc3eaed6cce5787b4f1 Mon Sep 17 00:00:00 2001 From: Hsin Chen Date: Wed, 18 Nov 2026 13:56:52 -0800 Subject: [PATCH 1/2] Preserve requester deployment context in shell authorization --- docs/reference/mcp-api.md | 12 +++ nomos/llm/council_agent.py | 28 ++++--- nomos/nat/functions.py | 61 +++++++++++++- tests/test_nat_functions.py | 115 ++++++++++++++++++++++++++ tests/test_tool_call_authorization.py | 78 +++++++++++++++++ 5 files changed, 280 insertions(+), 14 deletions(-) diff --git a/docs/reference/mcp-api.md b/docs/reference/mcp-api.md index 6aac46ad..e4882b80 100644 --- a/docs/reference/mcp-api.md +++ b/docs/reference/mcp-api.md @@ -54,6 +54,18 @@ async with streamablehttp_client( | `council_set_council_enabled` | Enable or disable a dynamic council | `management_token`, `council_id`, `enabled` | | `council_validate_catalog` | Validate the catalog and referenced profiles | optional `management_token` | +Shell authorization accepts optional `target_host`, `target_environment`, +`target_cluster`, `target_namespace`, `target_container`, and +`rollback_plan` fields. Target strings can be up to 255 characters and the +validated rollback plan can serialize to at most 8192 UTF-8 JSON bytes. +An automatic rollback plan requires at least one step. + +Council review receives the target fields and the rollback strategy and steps +as requester assertions. OPA receives the target fields and a +`has_rollback_plan` flag. These fields follow normal Intent and audit retention, +so keep secrets out of the values. Executor routing and signed writs retain +their existing contracts. Structured tool calls cannot carry these shell fields. + Application-owned tools use a structured request instead of pretending the tool call is a shell command. Nomos validates and snapshots `arguments`, derives their `nomos-json-v1` SHA-256 digest, and returns a signed v2 writ bound to that diff --git a/nomos/llm/council_agent.py b/nomos/llm/council_agent.py index 227ec208..ffb14b85 100644 --- a/nomos/llm/council_agent.py +++ b/nomos/llm/council_agent.py @@ -371,16 +371,20 @@ def _format_intent_for_review(intent: Intent) -> str: wd = intent.working_directory or "*(not specified)*" parts.append(f"**Working Directory:** {wd}") - if intent.target_host: - parts.append(f"\n**Target Host:** {intent.target_host}") - if intent.target_environment: - parts.append(f"**Target Environment:** {intent.target_environment}") - if intent.target_cluster: - parts.append(f"**Target Cluster:** {intent.target_cluster}") - if intent.target_namespace: - parts.append(f"**Target Namespace:** {intent.target_namespace}") - if intent.target_container: - parts.append(f"**Target Container:** {intent.target_container}") + deployment_target = { + "Target Host": intent.target_host, + "Target Environment": intent.target_environment, + "Target Cluster": intent.target_cluster, + "Target Namespace": intent.target_namespace, + "Target Container": intent.target_container, + } + if any(deployment_target.values()): + parts.append("\n## Deployment Target (requester assertions)") + parts.extend( + f"**{label}:** {json.dumps(_defang_agent_text(value))}" + for label, value in deployment_target.items() + if value + ) if intent.packaged_files: parts.append("\n## Packaged Files") @@ -437,11 +441,11 @@ def _format_intent_for_review(intent: Intent) -> str: parts.append(f" - `{cmd}`") if intent.rollback_plan: - parts.append("\n## Rollback Plan") + parts.append("\n## Rollback Plan (requester assertion)") parts.append(f"**Strategy:** {intent.rollback_plan.strategy}") if intent.rollback_plan.steps: for step in intent.rollback_plan.steps: - parts.append(f" - {step}") + parts.append(f" - {json.dumps(_defang_agent_text(step))}") # Trust comes from which channel the evidence arrived on, never from its text. # certified_evidence_rendered is populated only by the council's verification diff --git a/nomos/nat/functions.py b/nomos/nat/functions.py index 763ef329..1322aa4e 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -27,6 +27,7 @@ ConfigDict, Field, SerializerFunctionWrapHandler, + field_validator, model_serializer, model_validator, ) @@ -51,6 +52,9 @@ INTENT_CONTEXT_MAX_LENGTH, INTENT_DESCRIPTION_MAX_LENGTH, INTENT_JUSTIFICATION_MAX_LENGTH, + RollbackPlan, + RollbackStrategy, + TargetEnvironment, ) from nomos.level_0.types.packaged_file import PackagedFile from nomos.level_0.types.writ import VoteSummary @@ -517,6 +521,12 @@ class AuthorizeInput(DuplicateSafeJsonModel): "working_directory": {"const": ""}, "env": {"maxProperties": 0}, "packaged_files": {"maxItems": 0}, + "target_host": {"const": ""}, + "target_environment": {"type": "null"}, + "target_cluster": {"const": ""}, + "target_namespace": {"const": ""}, + "target_container": {"const": ""}, + "rollback_plan": {"type": "null"}, }, }, ] @@ -550,6 +560,24 @@ class AuthorizeInput(DuplicateSafeJsonModel): ) description: str = Field(default="", description="What the agent wants to do") target_resource: str = Field(default="", description="The resource to act upon") + target_host: str = Field( + default="", max_length=255, description="Requester-declared shell host" + ) + target_environment: TargetEnvironment | None = Field( + default=None, description="Requester-declared shell environment tier" + ) + target_cluster: str = Field( + default="", max_length=255, description="Requester-declared shell cluster" + ) + target_namespace: str = Field( + default="", max_length=255, description="Requester-declared shell namespace" + ) + target_container: str = Field( + default="", max_length=255, description="Requester-declared shell container" + ) + rollback_plan: RollbackPlan | None = Field( + default=None, description="Requester-declared shell rollback plan (up to 8192 JSON bytes)" + ) justification: str = Field(default="", description="Why this action is needed") blast_radius: str = Field(default="", description="Scope of potential impact") context: str = Field(default="", description="What the agent was doing before this request") @@ -573,6 +601,18 @@ class AuthorizeInput(DuplicateSafeJsonModel): description="Files to review and package into the execution writ", ) + @field_validator("rollback_plan") + @classmethod + def validate_rollback_plan(cls, plan: RollbackPlan | None) -> RollbackPlan | None: + if plan is None: + return None + # RollbackPlan's step validator does not run when steps are omitted. + if plan.strategy == RollbackStrategy.AUTOMATIC and not plan.steps: + raise ValueError("Automatic rollback requires at least one step") + if len(plan.model_dump_json().encode("utf-8")) > 8192: + raise ValueError("rollback_plan must serialize to at most 8192 bytes") + return plan + @model_validator(mode="before") @classmethod def infer_structured_api_version(cls, value: object) -> object: @@ -594,10 +634,21 @@ def validate_operation_shape(self) -> "AuthorizeInput": return self if self.api_version != API_VERSION_V2: raise ValueError("structured tool-call authorization uses api_version v2") - if self.command or self.working_directory or self.env or self.packaged_files: + if ( + self.command + or self.working_directory + or self.env + or self.packaged_files + or self.target_host + or self.target_environment is not None + or self.target_cluster + or self.target_namespace + or self.target_container + or self.rollback_plan is not None + ): raise ValueError( "structured tool-call authorization cannot include shell execution " - "or packaged-file fields" + "or packaged-file fields, including deployment context" ) return self @@ -1520,6 +1571,12 @@ def _build_authorize_intent_kwargs(input_data: AuthorizeInput, agent_id: str) -> or input_data.working_directory or "localhost", "command": input_data.command, + "target_host": input_data.target_host, + "target_environment": input_data.target_environment, + "target_cluster": input_data.target_cluster, + "target_namespace": input_data.target_namespace, + "target_container": input_data.target_container, + "rollback_plan": input_data.rollback_plan, "justification": input_data.justification, "blast_radius": input_data.blast_radius, "context": input_data.context, diff --git a/tests/test_nat_functions.py b/tests/test_nat_functions.py index c5ddc9c0..55cd5b93 100644 --- a/tests/test_nat_functions.py +++ b/tests/test_nat_functions.py @@ -9,11 +9,13 @@ import base64 import hashlib import json +from unittest.mock import AsyncMock import pytest from executors.common import certify_execution_result, load_or_create_executor_identity from nomos.auth.authenticator import AgentIdentity +from nomos.auth.writ_factory import _compute_intent_hash from nomos.config.settings import ( CouncilMemberConfig, CouncilSettings, @@ -39,6 +41,7 @@ ProposeIntentInput, WritStatusInput, ) +from nomos.opa import OPAPolicyDecision from trusted_executor_contract import ExecutionResult, WritOfExecution # ── Mock Backend ─────────────────────────────────────────────────────── @@ -146,6 +149,8 @@ def _make_settings_no_backends() -> CouncilSettings: def _make_service_with_mock_agents( decisions: list[str], + *, + council_key_path: str | None = None, ) -> CouncilService: """ Create a CouncilService with mock LLM agents. @@ -155,6 +160,8 @@ def _make_service_with_mock_agents( we build the service with no backends and manually inject agents. """ settings = _make_settings_no_backends() + if council_key_path is not None: + settings = settings.model_copy(update={"council_key_path": council_key_path}) service = CouncilService(settings) for i, decision in enumerate(decisions): @@ -994,6 +1001,114 @@ async def test_check_writ_status_rejects_non_owner(self): class TestCouncilServiceWithAgents: """Tests for CouncilService with mock LLM agents.""" + @pytest.mark.asyncio + @pytest.mark.parametrize( + "target", + [ + {}, + {"target_host": "staging-host", "target_environment": "staging"}, + { + "target_environment": "development", + "target_cluster": "development-cluster", + "target_namespace": "example", + "target_container": "service", + }, + ], + ) + async def test_shell_authorization_preserves_requester_deployment_context( + self, tmp_path, target + ): + service = _make_service_with_mock_agents(["approve"], council_key_path=str(tmp_path)) + reviewer = RecordingLLMBackend() + service._agents[0]._backend = reviewer + service._opa_client = AsyncMock() + service._opa_client.evaluate.return_value = OPAPolicyDecision(allow=True) + rollback = ( + {"strategy": "manual", "steps": ["Reapply the previous configuration"]} + if target + else None + ) + + result = await service.authorize( + AuthorizeInput( + agent_id="agent-1", + command="/bin/echo deploy", + working_directory="/tmp", + justification="Test shell authorization with requester deployment context", + rollback_plan=rollback, + **target, + ) + ) + + assert result.status == "approved", result.error + opa_intent = service._opa_client.evaluate.await_args.args[0]["intent"] + assert opa_intent["command_type"] == "shell" + assert opa_intent["shell_command_words"] == ["/bin/echo"] + assert opa_intent["has_rollback_plan"] is bool(target) + assert "rollback_plan" not in opa_intent + for name in ( + "target_host", + "target_environment", + "target_cluster", + "target_namespace", + "target_container", + ): + assert opa_intent[name] == target.get(name, "") + prompt = reviewer.calls[0][1].content + if target: + assert "Deployment Target (requester assertions)" in prompt + assert "Rollback Plan (requester assertion)" in prompt + for value in target.values(): + assert value in prompt + assert "Reapply the previous configuration" in prompt + else: + assert "Deployment Target" not in prompt + assert "Rollback Plan" not in prompt + + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("target", "error"), + [ + ({"target_host": "host-a", "target_cluster": "cluster-a"}, "both target_host"), + ({"target_namespace": "example"}, "requires target_cluster"), + ({"target_container": "service"}, "requires target_namespace"), + ( + {"target_environment": "production", "justification": ""}, + "Production actions require justification", + ), + ({"target_environment": "production"}, "Production actions require blast_radius"), + ], + ) + async def test_shell_authorization_preserves_existing_intent_target_validation( + self, tmp_path, target, error + ): + service = _make_service_with_mock_agents(["approve"], council_key_path=str(tmp_path)) + service._opa_client = AsyncMock() + result = await service.authorize( + AuthorizeInput( + agent_id="agent-1", + command="/bin/echo deploy", + working_directory="/tmp", + **{"justification": "Test target validation", **target}, + ) + ) + assert result.status == "error" + assert error in result.error + service._opa_client.evaluate.assert_not_awaited() + + def test_old_shell_request_preserves_writ_digest(self): + request = AuthorizeInput( + agent_id="agent-1", + command="/bin/echo deploy", + working_directory="/tmp", + ) + intent = Intent( + intent_id="intent-0123456789abcdef", + **CouncilService._build_authorize_intent_kwargs(request, "agent-1"), + ) + baseline_digest = "4afe1b333e619d0b1e621d935aa6053722b4bfb55dfbc6c3128cc14552b2b66d" # pragma: allowlist secret # noqa: E501 + assert _compute_intent_hash(intent) == baseline_digest + @pytest.mark.asyncio async def test_structured_tool_authorization_reviews_args_and_mints_typed_writ(self): from nomos.auth.writ_factory import WritFactory diff --git a/tests/test_tool_call_authorization.py b/tests/test_tool_call_authorization.py index e9c3cf9e..fdfbcd9a 100644 --- a/tests/test_tool_call_authorization.py +++ b/tests/test_tool_call_authorization.py @@ -14,6 +14,7 @@ from nomos.auth.writ_factory import WritFactory from nomos.level_0.crypto.signing import KeyPair from nomos.level_0.types import Intent, ToolCallWrit +from nomos.level_0.types.intent import RollbackPlan from nomos.level_0.types.tool_call import ToolCallRequest, canonical_tool_arguments from nomos.llm.council_agent import _format_intent_for_review from nomos.nat.functions import AuthorizeInput, CouncilService @@ -197,6 +198,27 @@ async def test_mcp_shell_call_without_api_version_is_v1(): assert request.api_version == "v1" +@needs_nat_mcp +@pytest.mark.asyncio +async def test_mcp_shell_accepts_deployment_context(): + request = await _authorize_through_mcp( + { + "agent_id": "agent", + "command": "/bin/ls", + "working_directory": "/workspace", + "target_environment": "staging", + "rollback_plan": { + "strategy": "manual", + "steps": ["Reapply the previous configuration"], + }, + } + ) + + assert request.api_version == "v1" + assert request.target_environment == "staging" + assert request.rollback_plan.steps == ["Reapply the previous configuration"] + + @needs_nat_mcp @pytest.mark.asyncio async def test_mcp_tool_call_with_explicit_v1_is_rejected(): @@ -359,6 +381,62 @@ def test_authorize_rejects_legacy_or_shell_fields_for_structured_calls(extra): AuthorizeInput(agent_id="app-service", tool_call=_tool_call(), **extra) +@pytest.mark.parametrize( + "target_context", + [ + {"target_host": "host-a"}, + {"target_environment": "staging"}, + {"target_cluster": "cluster-a"}, + {"target_namespace": "example"}, + {"target_container": "service"}, + {"rollback_plan": {"strategy": "manual"}}, + ], +) +def test_structured_calls_reject_shell_deployment_context(target_context): + payload = {"agent_id": "app-service", "tool_call": _tool_call(), **target_context} + with pytest.raises(ValidationError, match="structured tool-call authorization"): + AuthorizeInput.model_validate(payload) + + jsonschema = pytest.importorskip("jsonschema") + with pytest.raises(jsonschema.ValidationError): + jsonschema.validate(payload, AuthorizeInput.model_json_schema()) + + +@pytest.mark.parametrize( + "field", ["target_host", "target_cluster", "target_namespace", "target_container"] +) +def test_shell_authorization_bounds_target_strings(field): + payload = {"agent_id": "app-service", "command": "/bin/ls", "working_directory": "/tmp"} + AuthorizeInput.model_validate({**payload, field: "a" * 255}) + with pytest.raises(ValidationError, match=field): + AuthorizeInput.model_validate({**payload, field: "a" * 256}) + + +def test_shell_authorization_bounds_serialized_rollback_plan(): + payload = {"agent_id": "app-service", "command": "/bin/ls", "working_directory": "/tmp"} + empty_step = RollbackPlan(steps=[""]).model_dump_json().encode("utf-8") + available_bytes = 8192 - len(empty_step) + AuthorizeInput.model_validate({**payload, "rollback_plan": {"steps": ["a" * available_bytes]}}) + with pytest.raises(ValidationError, match="8192 bytes"): + AuthorizeInput.model_validate( + {**payload, "rollback_plan": {"steps": ["é" * (available_bytes // 2 + 1)]}} + ) + + +def test_shell_authorization_requires_steps_for_automatic_rollback(): + payload = {"agent_id": "app-service", "command": "/bin/ls", "working_directory": "/tmp"} + with pytest.raises(ValidationError, match="Automatic rollback requires at least one step"): + AuthorizeInput.model_validate_json( + json.dumps({**payload, "rollback_plan": {"strategy": "automatic"}}) + ) + + steps = ["Restore the saved configuration"] + request = AuthorizeInput.model_validate_json( + json.dumps({**payload, "rollback_plan": {"strategy": "automatic", "steps": steps}}) + ) + assert request.rollback_plan.steps == steps + + def test_public_authorize_schema_describes_exclusive_shapes(): jsonschema = pytest.importorskip("jsonschema") From b0ad3ee7e4ff567211cf6a7f591cdacf866f0fdd Mon Sep 17 00:00:00 2001 From: Hsin Chen Date: Fri, 20 Nov 2026 14:35:33 -0800 Subject: [PATCH 2/2] docs(council): clarify OPA rollback flag semantics --- docs/reference/mcp-api.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/reference/mcp-api.md b/docs/reference/mcp-api.md index e4882b80..690f06da 100644 --- a/docs/reference/mcp-api.md +++ b/docs/reference/mcp-api.md @@ -62,9 +62,11 @@ An automatic rollback plan requires at least one step. Council review receives the target fields and the rollback strategy and steps as requester assertions. OPA receives the target fields and a -`has_rollback_plan` flag. These fields follow normal Intent and audit retention, -so keep secrets out of the values. Executor routing and signed writs retain -their existing contracts. Structured tool calls cannot carry these shell fields. +`has_rollback_plan` flag. The flag is true whenever the requester supplies a +plan object, including one with `strategy: none`. Rollback feasibility remains +unverified. These fields follow normal Intent and audit retention, so keep +secrets out of the values. Executor routing and signed writs retain their +existing contracts. Structured tool calls cannot carry these shell fields. Application-owned tools use a structured request instead of pretending the tool call is a shell command. Nomos validates and snapshots `arguments`, derives