diff --git a/executors/docker/enforcer.py b/executors/docker/enforcer.py index 416d3686..8bcd1426 100644 --- a/executors/docker/enforcer.py +++ b/executors/docker/enforcer.py @@ -28,6 +28,8 @@ import subprocess import time +from nomos_runtime.shell_line import control_tokens, shell_line_problem + from .config import ExecutorConfig from .models import ExecutionContext, ExecutionResult, WritOfExecution from .nonce_store import NonceStore @@ -199,6 +201,12 @@ async def execute_writ( ) # 6. Blocked pattern check + problem = shell_line_problem(writ.command) + if problem: + return ExecutionResult( + writ_id=writ.writ_id, error=problem, verification_stage="blocked_pattern" + ) + blocked = self._check_blocked_patterns(writ.command) if blocked: return ExecutionResult( @@ -302,12 +310,7 @@ def _is_env_assignment(token: str) -> bool: @staticmethod def _shell_tokens(command: str) -> list[str]: """Tokenize a shell command while preserving command separators.""" - try: - lexer = shlex.shlex(command, posix=True, punctuation_chars="|&;()<>") - lexer.whitespace_split = True - return list(lexer) - except ValueError: - return command.strip().split() + return control_tokens(command, "|&;()<>") def _extract_tool_names(self, command: str) -> list[str]: """ diff --git a/nomos/auth/writ_factory.py b/nomos/auth/writ_factory.py index b69510f8..49b86f0b 100644 --- a/nomos/auth/writ_factory.py +++ b/nomos/auth/writ_factory.py @@ -35,6 +35,7 @@ WritOfExecution, ) from nomos.store.base import DurableStore +from nomos_runtime.shell_line import shell_line_problem logger = logging.getLogger(__name__) @@ -182,10 +183,15 @@ async def mint_writ( writ: AuthorizationWrit if operation is None: + # Command Writs carry shell text regardless of the intent's review type. + command = intent.command or "" + problem = shell_line_problem(command) + if problem: + raise ValueError(problem) writ = WritOfExecution( writ_id=_generate_writ_id(), intent_hash=_compute_intent_hash(intent), - command=intent.command or "", + command=command, working_directory=working_directory or intent.working_directory or "", target_agent_id=target_agent_id, packaged_files=intent.packaged_files, diff --git a/nomos/level_0/types/intent.py b/nomos/level_0/types/intent.py index 4f29715d..a1212157 100644 --- a/nomos/level_0/types/intent.py +++ b/nomos/level_0/types/intent.py @@ -14,7 +14,9 @@ from enum import StrEnum from typing import Any -from pydantic import BaseModel, Field, PrivateAttr, field_validator, model_validator +from pydantic import BaseModel, Field, PrivateAttr, ValidationInfo, field_validator, model_validator + +from nomos_runtime.shell_line import shell_line_problem from .attestation import AttestationVector from .packaged_file import PackagedFile @@ -287,6 +289,20 @@ def validate_command(cls, v: str) -> str: raise ValueError(f"Command contains dangerous pattern: {pattern}") return v + def shell_command_problem(self) -> str: + """Return a shell syntax error for shell intents only.""" + if self.command_type != CommandType.SHELL: + return "" + return shell_line_problem(self.command) + + @model_validator(mode="after") + def validate_shell_command(self, info: ValidationInfo) -> "Intent": + if not (info.context or {}).get("restore_durable_workflow"): + problem = self.shell_command_problem() + if problem: + raise ValueError(problem) + return self + @field_validator("target_namespace") @classmethod def validate_namespace(cls, v: str) -> str: diff --git a/nomos/level_1/policy/shell.py b/nomos/level_1/policy/shell.py index 900d7d16..296ac546 100644 --- a/nomos/level_1/policy/shell.py +++ b/nomos/level_1/policy/shell.py @@ -4,9 +4,10 @@ """Shell command policy helpers.""" import re -import shlex -_COMMAND_SEPARATORS = {"|", "||", "&", "&&", ";"} +from nomos_runtime.shell_line import control_tokens + +_COMMAND_SEPARATORS = {"|", "||", "&", "&&", ";", "\n"} _COMMAND_GROUP_TOKENS = {"(", ")"} _REDIRECT_TOKENS = {">", ">>", "<", "<<", "<<<", ">|", "<>", "&>", "&>>", "2>", "2>>"} _SHELL_BUILTINS = {"cd"} @@ -21,22 +22,12 @@ def _is_env_assignment(word: str) -> bool: def _shell_tokens(command: str) -> list[str]: """Tokenize a shell command while preserving command separators.""" - try: - lexer = shlex.shlex(command, posix=True, punctuation_chars="|&;()<>") - lexer.whitespace_split = True - return list(lexer) - except ValueError: - return command.strip().split() + return control_tokens(command, "|&;()<>") def _shell_tokens_preserving_redirection_words(command: str) -> list[str]: """Tokenize shell words while preserving compact redirections like ``2>/dev/null``.""" - try: - lexer = shlex.shlex(command, posix=True, punctuation_chars="|&;()") - lexer.whitespace_split = True - return list(lexer) - except ValueError: - return command.strip().split() + return control_tokens(command, "|&;()") def _is_non_persistent_redirect_target(target: str) -> bool: diff --git a/nomos/level_4/council/council.py b/nomos/level_4/council/council.py index 6a766c3e..1e8bc21b 100644 --- a/nomos/level_4/council/council.py +++ b/nomos/level_4/council/council.py @@ -405,6 +405,17 @@ def _local_workflow(self, intent_id: str) -> IntentWorkflow | None: self.expire_workflow(workflow) return workflow + def _workflow_for_action(self, intent_id: str) -> tuple[IntentWorkflow | None, str]: + """Read the target command before maintenance can change its recorded state.""" + workflow = self._workflows.get(intent_id) + if workflow is not None: + problem = workflow.intent.shell_command_problem() + if problem: + return workflow, problem + + self._prune_terminal_workflows() + return self._local_workflow(intent_id), "" + def _expire_elapsed_workflows(self) -> None: """Apply every local decision deadline, for listings of current state.""" if self._config.loop_owned_workflows: @@ -542,6 +553,10 @@ def preflight_intent( agent_role: AgentRole | None = None, ) -> PreflightResult: """Evaluate policy and reserve capacity without mutating workflow or ledger state.""" + problem = intent.shell_command_problem() + if problem: + return PreflightResult(success=False, error=problem) + self._prune_terminal_workflows() self._reap_expired_preflights() @@ -601,6 +616,10 @@ def submit_intent( Returns immediately with the initial evaluation result. For intents requiring approval, the workflow enters AWAITING_APPROVAL. """ + problem = intent.shell_command_problem() + if problem: + return SubmitResult(success=False, error=problem) + # Drop bookkeeping for long-finished workflows so the in-memory map # stays bounded for a long-lived council; their outcome remains in the # ledger and persistent store. @@ -748,18 +767,6 @@ def approve_intent( reason: str = "", ) -> SubmitResult: """Cast an approval vote for an intent.""" - self._prune_terminal_workflows() - workflow = self._local_workflow(intent_id) - if workflow is None: - return SubmitResult(success=False, error="Intent not found") - - if workflow.state != WorkflowState.AWAITING_APPROVAL: - return SubmitResult( - success=False, - workflow=workflow, - error=f"Intent is not awaiting approval (state: {workflow.state.value})", - ) - return self.cast_member_vote(intent_id, approver_id, VoteType.APPROVE, reason=reason) def deny_intent( @@ -769,18 +776,6 @@ def deny_intent( reason: str = "", ) -> SubmitResult: """Cast a denial vote for an intent.""" - self._prune_terminal_workflows() - workflow = self._local_workflow(intent_id) - if workflow is None: - return SubmitResult(success=False, error="Intent not found") - - if workflow.state != WorkflowState.AWAITING_APPROVAL: - return SubmitResult( - success=False, - workflow=workflow, - error=f"Intent is not awaiting approval (state: {workflow.state.value})", - ) - return self.cast_member_vote(intent_id, denier_id, VoteType.DENY, reason=reason) def cast_member_vote( @@ -793,11 +788,13 @@ def cast_member_vote( finalize: bool = True, ) -> SubmitResult: """Record a council member vote and optionally finalize the review.""" - self._prune_terminal_workflows() - workflow = self._local_workflow(intent_id) + workflow, problem = self._workflow_for_action(intent_id) if workflow is None: return SubmitResult(success=False, error="Intent not found") + if problem: + return SubmitResult(success=False, workflow=workflow, error=problem) + if workflow.state != WorkflowState.AWAITING_APPROVAL: return SubmitResult( success=False, @@ -836,11 +833,13 @@ def revise_vote( who already voted to change their position and records the change as a ``DEBATE_VOTE`` ledger entry. """ - self._prune_terminal_workflows() - workflow = self._local_workflow(intent_id) + workflow, problem = self._workflow_for_action(intent_id) if workflow is None: return SubmitResult(success=False, error="Intent not found") + if problem: + return SubmitResult(success=False, workflow=workflow, error=problem) + if workflow.state != WorkflowState.AWAITING_APPROVAL: return SubmitResult( success=False, @@ -875,11 +874,13 @@ def finalize_intent_review( partial_voters: set[str] | None = None, ) -> SubmitResult: """Finalize a batched council review round and sync workflow state.""" - self._prune_terminal_workflows() - workflow = self._local_workflow(intent_id) + workflow, problem = self._workflow_for_action(intent_id) if workflow is None: return SubmitResult(success=False, error="Intent not found") + if problem: + return SubmitResult(success=False, workflow=workflow, error=problem) + if workflow.state != WorkflowState.AWAITING_APPROVAL: return SubmitResult(success=True, workflow=workflow) @@ -937,9 +938,8 @@ def mint_token( The token authorizes execution of the action described in the intent. """ - self._prune_terminal_workflows() - workflow = self._local_workflow(intent_id) - if workflow is None: + workflow, problem = self._workflow_for_action(intent_id) + if workflow is None or problem: return None if workflow.state != WorkflowState.APPROVED: @@ -978,11 +978,13 @@ def execute_intent(self, intent_id: str) -> ExecuteResult: This is the complete flow: execute -> verify -> complete/rollback. """ - self._prune_terminal_workflows() - workflow = self._local_workflow(intent_id) + workflow, problem = self._workflow_for_action(intent_id) if workflow is None: return ExecuteResult(success=False, error="Intent not found") + if problem: + return ExecuteResult(success=False, workflow=workflow, error=problem) + if workflow.state == WorkflowState.APPROVED: token = self.mint_token(intent_id) if token is None: diff --git a/nomos/level_4/council/workflow.py b/nomos/level_4/council/workflow.py index 9c64bc9d..a2b0664d 100644 --- a/nomos/level_4/council/workflow.py +++ b/nomos/level_4/council/workflow.py @@ -239,7 +239,9 @@ def _dt(key: str) -> datetime | None: token = data.get("capability_token") return cls( - intent=Intent.from_dict(data["intent"]), + intent=Intent.model_validate( + data["intent"], context={"restore_durable_workflow": True} + ), state=WorkflowState(data["state"]), logical_version=int(data.get("logical_version", 0)), retire_after=_dt("retire_after"), diff --git a/nomos_runtime/shell_line.py b/nomos_runtime/shell_line.py new file mode 100644 index 00000000..5ad50b58 --- /dev/null +++ b/nomos_runtime/shell_line.py @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Line-oriented command syntax shared by the council and executor.""" + +import shlex + + +def shell_line_problem(command: str) -> str: + """Describe unsupported syntax without including any of the command.""" + if "\x00" in command: + return "Shell command contains a null byte" + if "\n" in command or "\r" in command: + return "Shell command must be a single line" + if "`" in command: + return "Shell command contains unsupported backticks" + return "" + + +def control_tokens(command: str, punctuation: str) -> list[str]: + """Keep line breaks as separators when inspecting previously stored commands.""" + tokens: list[str] = [] + lines = command.replace("\r\n", "\n").replace("\r", "\n").split("\n") + for index, line in enumerate(lines): + if index: + tokens.append("\n") + try: + lexer = shlex.shlex(line, posix=True, punctuation_chars=punctuation) + lexer.whitespace_split = True + tokens.extend(list(lexer)) + except ValueError: + # A line that does not lex cleanly still has a distinct boundary. + tokens.extend(line.split()) + return tokens diff --git a/tests/level_0/test_types.py b/tests/level_0/test_types.py index 268b626b..82901046 100644 --- a/tests/level_0/test_types.py +++ b/tests/level_0/test_types.py @@ -565,3 +565,34 @@ def test_serialization_roundtrip(self): assert restored.strategy == RollbackStrategy.SNAPSHOT assert restored.estimated_duration_seconds == 120 assert restored.artifacts["snapshot_id"] == "snap-123" + + +@pytest.mark.parametrize("delimiter", ["\n", "\r", "\x00", "`"]) +def test_new_shell_intents_reject_unsupported_line_syntax(delimiter): + with pytest.raises(ValueError, match="Shell command"): + Intent.create( + agent_id="agent-1", + description="Print a label", + target_resource="/workspace", + command=f"/bin/echo left{delimiter}right", + ) + + +@pytest.mark.parametrize( + ("command_type", "command"), + [ + (CommandType.SQL, "SELECT `name`\nFROM users"), + (CommandType.PYTHON, "def value():\n return 1"), + ], +) +def test_non_shell_intents_accept_their_language_syntax(command_type, command): + intent = Intent.create( + agent_id="agent-1", + description="Read a value from a program", + target_resource="/workspace", + command=command, + command_type=command_type, + ) + + assert intent.command == command + assert intent.command_type == command_type diff --git a/tests/level_4/test_council_workflow_store.py b/tests/level_4/test_council_workflow_store.py index e87d964b..ad5f947a 100644 --- a/tests/level_4/test_council_workflow_store.py +++ b/tests/level_4/test_council_workflow_store.py @@ -21,7 +21,10 @@ from datetime import UTC, datetime, timedelta from typing import Any +import pytest + from nomos.level_0.types import AgentRole, CouncilMember, Intent +from nomos.level_0.types.intent import CommandType from nomos.level_3.executor import NoOpHandler from nomos.level_4.council import CouncilConfig, SecurityCouncil, WorkflowState from nomos.level_4.council.workflow import IntentWorkflow @@ -215,3 +218,58 @@ def test_reap_only_removes_expired_terminal_rows(): removed = store.reap_terminal_before(now) assert removed == 1 assert set(store.rows) == {"fresh", "pending"} + + +@pytest.mark.parametrize("operation", ["vote", "revise", "finalize", "preflight", "submit"]) +def test_a_durable_command_remains_readable_but_cannot_enter_a_review(operation): + store = FakeWorkflowStore() + owner = _council(store) + intent = _noop_intent() + result = owner.submit_intent(intent) + assert result.success and result.requires_approval + stored = result.workflow.to_durable_dict() + stored["intent"]["command"] = "/bin/echo line one\n/bin/echo line two" + store.upsert_workflow( + intent.intent_id, + stored, + state=WorkflowState.AWAITING_APPROVAL.value, + is_terminal=False, + expires_at=None, + ) + prior_writes = store.upserts + council = _council(store) + restored = council.get_workflow(intent.intent_id) + assert restored is not None and restored.intent.command == stored["intent"]["command"] + + if operation == "vote": + refusal = council.approve_intent(intent.intent_id, "alice") + elif operation == "revise": + refusal = council.revise_vote(intent.intent_id, "alice", "approve") + elif operation == "finalize": + refusal = council.finalize_intent_review(intent.intent_id) + elif operation == "preflight": + refusal = council.preflight_intent(restored.intent) + else: + refusal = _council().submit_intent(restored.intent) + + assert not refusal.success + assert "single line" in refusal.error + assert store.upserts == prior_writes + assert restored.state == WorkflowState.AWAITING_APPROVAL + assert council.mint_token(intent.intent_id) is None + + +def test_non_shell_intent_passes_council_review_and_execution(): + council = _council() + intent = Intent.create( + agent_id="agent-1", + action_type="system.noop", + description="Review a multiline Python command", + target_resource="/workspace", + justification="workflow store test", + command="def value():\n return 1", + command_type=CommandType.PYTHON, + ) + + assert council.preflight_intent(intent).success + assert _drive_to_completed(council, intent).state == WorkflowState.COMPLETED diff --git a/tests/test_decision_deadlines.py b/tests/test_decision_deadlines.py index e0016d26..2eb4a4a8 100644 --- a/tests/test_decision_deadlines.py +++ b/tests/test_decision_deadlines.py @@ -153,6 +153,50 @@ async def test_no_vote_on_an_elapsed_review_outside_the_cleanup_batch(): await service.aclose_workflows() +@pytest.mark.parametrize( + ("operation", "args", "approved"), + [ + ("approve_intent", ("manual",), False), + ("deny_intent", ("manual",), False), + ("cast_member_vote", ("manual", VoteType.APPROVE), False), + ("revise_vote", ("manual", "approve"), False), + ("finalize_intent_review", (), False), + ("mint_token", (), True), + ("execute_intent", (), True), + ], +) +@pytest.mark.asyncio +async def test_refused_command_does_not_expire_the_workflow(operation, args, approved): + service = _service() + clock = _one_entry_sweeps(service) + council = service.council + try: + (intent_id,) = await (_approved(service, 1) if approved else _awaiting(service, 1)) + saved = council._workflows[intent_id].to_durable_dict() + saved["intent"]["command"] = "/bin/echo first\n/bin/echo second" + workflow = IntentWorkflow.from_durable_dict(saved) + council._workflows[intent_id] = workflow + pending_votes = council._quorum_manager.get_pending_votes() + snapshots = [] + council._snapshot_sink = snapshots.append + clock.advance(seconds=_PAST_FALLBACK_DEADLINE) + + result = getattr(council, operation)(intent_id, *args) + + assert workflow.to_durable_dict() == saved + assert council._quorum_manager.get_pending_votes() == pending_votes + assert snapshots == [] + if operation == "mint_token": + assert result is None + else: + assert not result.success + assert "single line" in result.error + assert council.get_workflow(intent_id).state == WorkflowState.EXPIRED + assert len(snapshots) == 1 + finally: + await service.aclose_workflows() + + @pytest.mark.asyncio async def test_listings_hold_no_elapsed_entry_whatever_the_cleanup_batch(): service = _service() diff --git a/tests/test_enforcer.py b/tests/test_enforcer.py index ec026da8..97ef2da5 100644 --- a/tests/test_enforcer.py +++ b/tests/test_enforcer.py @@ -1017,3 +1017,27 @@ def test_resolved_path_catches_relative_bypass(self, kp, mock_nonce_store): err = enforcer._check_denied_paths("cat /etc/shadow") assert err is not None assert "shadow" in err + + +@pytest.mark.asyncio +@pytest.mark.parametrize("delimiter", ["\n", "\r", "\x00", "`"]) +async def test_a_signed_command_with_unsupported_line_syntax_stops_before_attachments( + delimiter, kp, mock_nonce_store, tmp_path, monkeypatch +): + enforcer = WritEnforcer( + public_key=kp.public_key, + nonce_store=mock_nonce_store, + config=ExecutorConfig(allowed_working_directories=[str(tmp_path)]), + ) + writ = _make_signed_writ( + kp, command=f"/bin/echo left{delimiter}right", working_directory=str(tmp_path) + ) + + def unpack(_writ): + pytest.fail("The executor must refuse this command before unpacking attachments") + + monkeypatch.setattr(enforcer, "_unpack_packaged_files", unpack) + result = await enforcer.execute_writ(_serialize(writ)) + + assert not result.success + assert result.verification_stage == "blocked_pattern" diff --git a/tests/test_policy_shell_lines.py b/tests/test_policy_shell_lines.py new file mode 100644 index 00000000..6b47f2bd --- /dev/null +++ b/tests/test_policy_shell_lines.py @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import pytest + +from nomos.level_1.policy.shell import extract_shell_command_words + + +@pytest.mark.parametrize("separator", ["\n", "\r", "\r\n", ";\n"]) +def test_parser_preserves_each_line_boundary(separator): + command = f"/bin/echo first{separator}/bin/printf second" + assert extract_shell_command_words(command) == ["/bin/echo", "/bin/printf"] diff --git a/tests/test_writ_factory.py b/tests/test_writ_factory.py index 0b2b554c..503085de 100644 --- a/tests/test_writ_factory.py +++ b/tests/test_writ_factory.py @@ -8,12 +8,14 @@ """ import base64 +from unittest.mock import AsyncMock import pytest from nomos.auth.writ_factory import WritFactory, _compute_intent_hash from nomos.level_0.crypto.signing import KeyPair from nomos.level_0.types import Intent, PackagedFile +from nomos.level_0.types.intent import CommandType from nomos.level_0.types.writ import VoteSummary @@ -78,6 +80,32 @@ async def test_writ_has_correct_command(self): assert writ.command == "ls -la /tmp" + @pytest.mark.parametrize( + ("command_type", "command", "error"), + [ + (CommandType.SQL, "SELECT `name` FROM users", "backticks"), + (CommandType.PYTHON, "def value():\n return 1", "single line"), + ], + ) + @pytest.mark.asyncio + async def test_refuses_unsupported_shell_writ_before_signing( + self, command_type, command, error + ): + intent = Intent.create( + agent_id="agent-dev", + description="Review a typed command", + target_resource="workspace", + command_type=command_type, + command=command, + ) + sign = AsyncMock(side_effect=AssertionError("Unsupported shell Writ reached signing")) + factory = WritFactory(council_key_pair=KeyPair.generate(), sign_async=sign) + + with pytest.raises(ValueError, match=error): + await factory.mint_writ(intent, "agent-dev", "quorum", [], "low") + + sign.assert_not_awaited() + @pytest.mark.asyncio async def test_writ_id_unique(self): factory, _ = _make_factory()