From ad353acead47c2e36810b820c81c5ac82b3f6a8e Mon Sep 17 00:00:00 2001 From: drobison Date: Wed, 16 Sep 2026 13:08:19 -0600 Subject: [PATCH 1/6] fix(policy): reject newline and backtick in commands; lex line breaks as separators A newline is a command terminator in `sh -c` but whitespace to `shlex`, so `/bin/true\nrm -rf x` lexed as one command word and passed both the council's absolute-executable rule and the executor's tool whitelist. A backtick is command substitution the lexer cannot see. Both characters are in the executor's `_SHELL_META`, so exactly these commands were the ones run with `shell=True`. Fixed at three independent layers: - Intent.validate_command rejects \r, \n, NUL and backtick at intake. - nomos/level_1/policy/shell.py splits on line breaks before lexing and emits an explicit "\n" separator token (also added to _COMMAND_SEPARATORS), so extract_shell_command_words / shell_path_policy_error / OPA input see every command segment. - executors/docker/enforcer.py rejects line breaks and backticks at the blocked_pattern stage and applies the same line split in _shell_tokens, making its existing (dead) "\n" separator entry live. OpenShellEnforcer subclasses WritEnforcer and has no tokenizer of its own, so it inherits the fix. $(...) substitution was already caught via the "(" punctuation token; a regression test now proves it stays caught. Report: reports/h5-shell-separators.md (local, gitignored; audit 2026-09-16, H5). Co-Authored-By: Claude Fable 5.1 --- executors/docker/enforcer.py | 34 +++++++++++++++++++++------ nomos/level_0/types/intent.py | 11 +++++++++ nomos/level_1/policy/shell.py | 36 ++++++++++++++++++----------- tests/level_0/test_types.py | 32 ++++++++++++++++++++++++++ tests/test_enforcer.py | 43 +++++++++++++++++++++++++++++++++++ tests/test_policy_shell.py | 39 +++++++++++++++++++++++++++++++ 6 files changed, 175 insertions(+), 20 deletions(-) create mode 100644 tests/test_policy_shell.py diff --git a/executors/docker/enforcer.py b/executors/docker/enforcer.py index f7223d39..8a515160 100644 --- a/executors/docker/enforcer.py +++ b/executors/docker/enforcer.py @@ -43,6 +43,10 @@ # Shell metacharacters that require shell=True to interpret correctly. _SHELL_META = re.compile(r"[|&;<>()$`\\\"\']|\*|\?|\[|\]|\{|\}|~|\n") _COMMAND_SEPARATORS = {";", "&&", "||", "|", "&", "\n"} +_LINE_BREAK = re.compile(r"\r\n|\r|\n") +# Characters that hide a second command from the tokenizer: line breaks are +# command terminators in sh -c, a backtick is command substitution. +_HIDDEN_COMMAND_CHARS = re.compile(r"[\r\n`]") _COMMAND_GROUP_TOKENS = {"(", ")"} _REDIRECT_TOKENS = {">", ">>", "<", "<<", "2>", "2>>", "&>", ">&"} @@ -207,6 +211,12 @@ async def execute_writ( ) # 6. Blocked pattern check + if _HIDDEN_COMMAND_CHARS.search(writ.command): + return ExecutionResult( + writ_id=writ.writ_id, + error="Command contains a line break or backtick — rejected", + verification_stage="blocked_pattern", + ) blocked = self._check_blocked_patterns(writ.command) if blocked: return ExecutionResult( @@ -309,13 +319,23 @@ 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() + """Tokenize a shell command while preserving command separators. + + Each line is lexed separately and joined with an explicit ``\\n`` token: + ``shlex`` treats a line break as whitespace, ``sh -c`` treats it as a + command terminator. + """ + tokens: list[str] = [] + for index, line in enumerate(_LINE_BREAK.split(command)): + if index: + tokens.append("\n") + try: + lexer = shlex.shlex(line, posix=True, punctuation_chars="|&;()<>") + lexer.whitespace_split = True + tokens.extend(lexer) + except ValueError: + tokens.extend(line.strip().split()) + return tokens def _extract_tool_names(self, command: str) -> list[str]: """ diff --git a/nomos/level_0/types/intent.py b/nomos/level_0/types/intent.py index aa25b024..940d81ed 100644 --- a/nomos/level_0/types/intent.py +++ b/nomos/level_0/types/intent.py @@ -26,6 +26,8 @@ from .packaged_file import PackagedFile +_COMMAND_CONTROL_CHARS = re.compile(r"[\r\n\x00]") + INTENT_DESCRIPTION_MAX_LENGTH = 16000 INTENT_CONTEXT_MAX_LENGTH = 32000 INTENT_JUSTIFICATION_MAX_LENGTH = 32000 @@ -270,6 +272,15 @@ def validate_intent_id(cls, v: str) -> str: @field_validator("command") @classmethod def validate_command(cls, v: str) -> str: + # A newline, carriage return or NUL hides a second command from every + # shell lexer downstream; a backtick is command substitution the lexers + # cannot see. None has a legitimate use in a governed command. + if _COMMAND_CONTROL_CHARS.search(v): + raise ValueError( + "Command contains a control character (newline, carriage return or NUL)" + ) + if "`" in v: + raise ValueError("Command contains backtick command substitution; use $(...)") dangerous_patterns = [ r"rm\s+-rf\s+/\s*$", r":\(\)\s*{\s*:\|:\s*&\s*}\s*;", diff --git a/nomos/level_1/policy/shell.py b/nomos/level_1/policy/shell.py index d38dbd46..def9a7fe 100644 --- a/nomos/level_1/policy/shell.py +++ b/nomos/level_1/policy/shell.py @@ -14,7 +14,8 @@ import re import shlex -_COMMAND_SEPARATORS = {"|", "||", "&", "&&", ";"} +_COMMAND_SEPARATORS = {"|", "||", "&", "&&", ";", "\n"} +_LINE_BREAK = re.compile(r"\r\n|\r|\n") _COMMAND_GROUP_TOKENS = {"(", ")"} _REDIRECT_TOKENS = {">", ">>", "<", "<<", "<<<", ">|", "<>", "&>", "&>>", "2>", "2>>"} _SHELL_BUILTINS = {"cd"} @@ -27,24 +28,33 @@ def _is_env_assignment(word: str) -> bool: return bool(sep and name and re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name)) +def _lex_lines(command: str, punctuation_chars: str) -> list[str]: + """Tokenize each line separately and join them with an explicit ``\\n`` separator. + + ``shlex`` treats a line break as whitespace, but ``sh -c`` treats it as a + command terminator. Splitting first keeps the two views in agreement. + """ + tokens: list[str] = [] + for index, line in enumerate(_LINE_BREAK.split(command)): + if index: + tokens.append("\n") + try: + lexer = shlex.shlex(line, posix=True, punctuation_chars=punctuation_chars) + lexer.whitespace_split = True + tokens.extend(lexer) + except ValueError: + tokens.extend(line.strip().split()) + return tokens + + 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 _lex_lines(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 _lex_lines(command, "|&;()") def _is_non_persistent_redirect_target(target: str) -> bool: diff --git a/tests/level_0/test_types.py b/tests/level_0/test_types.py index 2ce6831b..125727cc 100644 --- a/tests/level_0/test_types.py +++ b/tests/level_0/test_types.py @@ -378,6 +378,38 @@ def test_dangerous_command_rejected(self): ) assert "dangerous pattern" in str(exc.value) + @pytest.mark.parametrize( + "command", + [ + "/bin/true\nrm -rf /tmp/x", + "/bin/true\r\nrm -rf /tmp/x", + "/bin/echo `bash -c id`", + "/bin/echo hi\x00", + ], + ids=["newline", "crlf", "backtick", "nul"], + ) + def test_intent_rejects_control_characters(self, command): + """Newline, CR, NUL and backtick hide a second command from the policy lexers.""" + with pytest.raises(ValidationError) as exc: + Intent.create( + agent_id="agent-1", + action_type="shell.exec", + description="control character in command", + target_resource="/tmp", + command=command, + ) + assert "control character" in str(exc.value) or "backtick" in str(exc.value) + + def test_intent_accepts_pipeline_without_control_characters(self): + intent = Intent.create( + agent_id="agent-1", + action_type="shell.exec", + description="ordinary pipeline", + target_resource="/tmp", + command="/bin/cat /tmp/a | /bin/grep x && /bin/echo $(id -u)", + ) + assert intent.command.startswith("/bin/cat") + def test_invalid_namespace_format(self): """Test that Kubernetes namespace must be valid format.""" with pytest.raises(ValidationError) as exc: diff --git a/tests/test_enforcer.py b/tests/test_enforcer.py index a5d6db38..67383e9f 100644 --- a/tests/test_enforcer.py +++ b/tests/test_enforcer.py @@ -1025,3 +1025,46 @@ 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 + + +class TestControlCharacters: + """Newline and backtick hide a second command from the tokenizer.""" + + def _enforcer(self, kp, mock_nonce_store, **cfg): + config = ExecutorConfig(allowed_working_directories=["/tmp"], **cfg) + return WritEnforcer(public_key=kp.public_key, nonce_store=mock_nonce_store, config=config) + + @pytest.mark.asyncio + async def test_backtick_blocked(self, kp, mock_nonce_store): + enforcer = self._enforcer(kp, mock_nonce_store, allowed_tools=["echo"]) + writ = _make_signed_writ(kp, command="echo `bash -c id`") + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False + assert result.verification_stage == "blocked_pattern" + + @pytest.mark.asyncio + async def test_newline_blocked(self, kp, mock_nonce_store): + enforcer = self._enforcer(kp, mock_nonce_store, allowed_tools=["echo"]) + writ = _make_signed_writ(kp, command="echo hi\nbash -c id") + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False + assert result.verification_stage == "blocked_pattern" + + @pytest.mark.asyncio + async def test_carriage_return_blocked(self, kp, mock_nonce_store): + enforcer = self._enforcer(kp, mock_nonce_store) + writ = _make_signed_writ(kp, command="echo hi\rbash -c id") + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False + assert result.verification_stage == "blocked_pattern" + + @pytest.mark.asyncio + async def test_dollar_paren_still_caught_by_whitelist(self, kp, mock_nonce_store): + enforcer = self._enforcer(kp, mock_nonce_store, allowed_tools=["echo"]) + writ = _make_signed_writ(kp, command="echo $(bash -c id)") + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False + assert result.verification_stage == "tool_whitelist" + + def test_tokenizer_sees_newline_as_separator(self, enforcer): + assert enforcer._extract_tool_names("echo hi\nbash -c id") == ["echo", "bash"] diff --git a/tests/test_policy_shell.py b/tests/test_policy_shell.py new file mode 100644 index 00000000..572e503d --- /dev/null +++ b/tests/test_policy_shell.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-NvidiaProprietary +# +# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual +# property and proprietary rights in and to this material, related +# documentation and any modifications thereto. Any use, reproduction, +# disclosure or distribution of this material and related documentation +# without an express license agreement from NVIDIA CORPORATION or +# its affiliates is strictly prohibited. + + +"""Tests for the council-side shell command policy helpers.""" + +from nomos.level_1.policy.shell import extract_shell_command_words, shell_path_policy_error + + +class TestCommandSeparators: + def test_semicolon_is_a_separator(self): + assert extract_shell_command_words("/bin/true; rm -rf /tmp/x") == ["/bin/true", "rm"] + assert "rm" in shell_path_policy_error("/bin/true; rm -rf /tmp/x") + + def test_newline_is_a_separator(self): + """A newline starts a new command in sh -c; the policy must see it.""" + assert extract_shell_command_words("/bin/true\nrm -rf /tmp/x") == ["/bin/true", "rm"] + assert "rm" in shell_path_policy_error("/bin/true\nrm -rf /tmp/x") + + def test_crlf_is_a_separator(self): + assert extract_shell_command_words("/bin/true\r\nrm -rf /tmp/x") == ["/bin/true", "rm"] + + def test_dollar_paren_substitution_still_caught(self): + assert "bash" in shell_path_policy_error("/bin/echo $(bash -c id)") + + def test_multi_stage_pipeline_unchanged(self): + words = extract_shell_command_words("/bin/a | /bin/b && /bin/c || /bin/d") + assert words == ["/bin/a", "/bin/b", "/bin/c", "/bin/d"] + assert shell_path_policy_error("/bin/a | /bin/b && /bin/c || /bin/d") == "" + + def test_env_assignment_prefix_unchanged(self): + assert extract_shell_command_words("FOO=1 /bin/env") == ["/bin/env"] From 5da7a00861019beb665d48901467de611d24d4a0 Mon Sep 17 00:00:00 2001 From: drobison Date: Thu, 17 Sep 2026 13:17:57 -0600 Subject: [PATCH 2/6] fix: hydrate legacy commands read-only and inspect $(...) inside double quotes Addresses the review findings on the control-character admission ban: - Stored workflows whose command predates the ban still hydrate. Intent.from_stored validates with context={"stored": True}, which skips only the newline/CR/NUL/backtick ban; dangerous-pattern checks still apply. Fresh submissions are unchanged and still rejected. - Such a record can never execute: cast_member_vote re-runs the admission check and denies with "command no longer admissible", and mint_token refuses to mint for it. Pending-approval listing now isolates a bad record (log and skip) instead of blanking the whole list. - Command substitution inside double quotes is now inspected on both layers. A quote-aware scanner cuts every $(...) region (balanced parentheses, single-quoted text literal, unbalanced runs to the end) out of the command and lexes each body as its own segment, so the inner tool reaches the absolute-path rule, OPA shell_command_words and the executor whitelist. The backtick error message now says $(...) is inspected rather than implying it is uninspected. - _lex_lines is documented as conservative tokenization (quoted newlines and backslash-newline continuations are split; bare CR is a separator). - Attack-probe harness counts an explicit "Invalid intent" admission rejection as blocked without treating transport errors as blocked. Co-Authored-By: Claude Fable 5.1 --- executors/docker/enforcer.py | 63 +++++++++- nomos/level_0/types/intent.py | 49 ++++++-- nomos/level_1/policy/shell.py | 70 +++++++++++- nomos/level_4/council/council.py | 37 +++++- nomos/level_4/council/workflow.py | 2 +- scripts/council_test_helpers.py | 17 +++ scripts/test_script_obfuscation.py | 6 +- tests/level_0/test_types.py | 29 +++++ tests/level_4/test_council_legacy_commands.py | 108 ++++++++++++++++++ tests/test_enforcer.py | 33 ++++++ tests/test_policy_shell.py | 26 +++++ 11 files changed, 424 insertions(+), 16 deletions(-) create mode 100644 tests/level_4/test_council_legacy_commands.py diff --git a/executors/docker/enforcer.py b/executors/docker/enforcer.py index 8a515160..a7c6d128 100644 --- a/executors/docker/enforcer.py +++ b/executors/docker/enforcer.py @@ -53,6 +53,61 @@ logger = logging.getLogger(__name__) +def _split_command_substitutions(command: str) -> tuple[str, list[str]]: + """Cut every ``$(...)`` command substitution out of ``command``. + + Returns the command with each substitution removed, plus the body of each + one in order. The caller lexes every body as a command of its own, so a + tool named inside a substitution is checked like any other command word. + + Single-quoted text is literal to the shell and is left alone. Double quotes + do **not** suppress substitution, so bodies inside them are cut out too. A + ``$(`` with no closing parenthesis is taken to run to the end of the + command, which is the conservative reading. ``$((...))`` yields a body + wrapped in parentheses: bash falls back to a subshell substitution when the + text is not arithmetic, so the body is lexed as a command group. Nested + substitutions are found when the body is lexed. + """ + outer: list[str] = [] + bodies: list[str] = [] + in_single = False + i = 0 + n = len(command) + while i < n: + ch = command[i] + if ch == "\\" and not in_single: + outer.append(command[i : i + 2]) + i += 2 + continue + if ch == "'": + in_single = not in_single + if in_single or ch != "$" or i + 1 >= n or command[i + 1] != "(": + outer.append(ch) + i += 1 + continue + depth = 0 + body_single = False + j = i + 1 + while j < n: + c = command[j] + if c == "\\" and not body_single: + j += 2 + continue + if c == "'": + body_single = not body_single + elif not body_single: + if c == "(": + depth += 1 + elif c == ")": + depth -= 1 + if depth == 0: + break + j += 1 + bodies.append(command[i + 2 : j]) + i = j + 1 + return "".join(outer), bodies + + class WritEnforcer: """Verifies and executes Writs of Execution. @@ -344,7 +399,8 @@ def _extract_tool_names(self, command: str) -> list[str]: This scans simple shell control operators so local policy applies to every stage of a compound command, not just the first token. """ - tokens = self._shell_tokens(command) + outer, substitutions = _split_command_substitutions(command) + tokens = self._shell_tokens(outer) tools: list[str] = [] expect_command = True skip_redirect_target = False @@ -377,6 +433,11 @@ def _extract_tool_names(self, command: str) -> list[str]: tools.append(os.path.basename(word)) expect_command = False + # ``$(...)`` runs a command of its own, inside double quotes too, so its + # body is checked against the whitelist like any other segment. + for body in substitutions: + tools.extend(self._extract_tool_names(body)) + return tools def _unpack_packaged_files(self, writ: WritOfExecution) -> ExecutionResult | None: diff --git a/nomos/level_0/types/intent.py b/nomos/level_0/types/intent.py index 940d81ed..a10df4c4 100644 --- a/nomos/level_0/types/intent.py +++ b/nomos/level_0/types/intent.py @@ -22,7 +22,7 @@ from enum import StrEnum from typing import Any -from pydantic import BaseModel, Field, field_validator, model_validator +from pydantic import BaseModel, Field, ValidationInfo, field_validator, model_validator from .packaged_file import PackagedFile @@ -269,18 +269,35 @@ def validate_intent_id(cls, v: str) -> str: raise ValueError("intent_id must start with 'intent-'") return v + @staticmethod + def command_admission_error(command: str) -> str | None: + """Return why ``command`` is not admissible, or None when it is. + + A newline, carriage return or NUL hides a second command from every + shell lexer downstream; a backtick is command substitution the lexers + cannot see. None has a legitimate use in a governed command, so the + ban applies to every ``CommandType`` by design, not only to shell. + ``$(...)`` is permitted because the policy lexers inspect its body. + """ + if _COMMAND_CONTROL_CHARS.search(command): + return "Command contains a control character (newline, carriage return or NUL)" + if "`" in command: + return ( + "Command contains backtick command substitution, which policy cannot " + "inspect; use $(...), whose body is inspected" + ) + return None + @field_validator("command") @classmethod - def validate_command(cls, v: str) -> str: - # A newline, carriage return or NUL hides a second command from every - # shell lexer downstream; a backtick is command substitution the lexers - # cannot see. None has a legitimate use in a governed command. - if _COMMAND_CONTROL_CHARS.search(v): - raise ValueError( - "Command contains a control character (newline, carriage return or NUL)" - ) - if "`" in v: - raise ValueError("Command contains backtick command substitution; use $(...)") + def validate_command(cls, v: str, info: ValidationInfo) -> str: + # Records that were valid when stored are rehydrated with + # ``context={"stored": True}`` (see ``from_stored``): they must remain + # readable, and the admission ban is re-applied before any of them can + # be approved or minted. Every fresh submission is checked here. + admission_error = cls.command_admission_error(v) + if admission_error and not (info.context or {}).get("stored"): + raise ValueError(admission_error) dangerous_patterns = [ r"rm\s+-rf\s+/\s*$", r":\(\)\s*{\s*:\|:\s*&\s*}\s*;", @@ -358,6 +375,16 @@ def to_dict(self) -> dict: def from_dict(cls, data: dict) -> "Intent": return cls.model_validate(data) + @classmethod + def from_stored(cls, data: dict) -> "Intent": + """Rehydrate an intent persisted by an earlier version. + + Skips only the command admission ban (control characters, backtick) so + historical records stay readable; ``command_admission_error`` is + re-checked before such an intent can be approved or minted. + """ + return cls.model_validate(data, context={"stored": True}) + def content_for_hashing(self) -> dict: """Return canonical content for hash computation.""" return { diff --git a/nomos/level_1/policy/shell.py b/nomos/level_1/policy/shell.py index def9a7fe..66a7781d 100644 --- a/nomos/level_1/policy/shell.py +++ b/nomos/level_1/policy/shell.py @@ -33,6 +33,12 @@ def _lex_lines(command: str, punctuation_chars: str) -> list[str]: ``shlex`` treats a line break as whitespace, but ``sh -c`` treats it as a command terminator. Splitting first keeps the two views in agreement. + + This is conservative tokenization, not shell-equivalent parsing: a line + break inside quotes and a backslash-newline continuation are split as well, + and a bare carriage return is treated as a separator although POSIX ``sh`` + does not. Commands containing any line break are rejected at intake and at + the executor, so the split only matters as defense in depth. """ tokens: list[str] = [] for index, line in enumerate(_LINE_BREAK.split(command)): @@ -47,6 +53,61 @@ def _lex_lines(command: str, punctuation_chars: str) -> list[str]: return tokens +def _split_command_substitutions(command: str) -> tuple[str, list[str]]: + """Cut every ``$(...)`` command substitution out of ``command``. + + Returns the command with each substitution removed, plus the body of each + one in order. The caller lexes every body as a command of its own, so a + tool named inside a substitution is checked like any other command word. + + Single-quoted text is literal to the shell and is left alone. Double quotes + do **not** suppress substitution, so bodies inside them are cut out too. A + ``$(`` with no closing parenthesis is taken to run to the end of the + command, which is the conservative reading. ``$((...))`` yields a body + wrapped in parentheses: bash falls back to a subshell substitution when the + text is not arithmetic, so the body is lexed as a command group. Nested + substitutions are found when the body is lexed. + """ + outer: list[str] = [] + bodies: list[str] = [] + in_single = False + i = 0 + n = len(command) + while i < n: + ch = command[i] + if ch == "\\" and not in_single: + outer.append(command[i : i + 2]) + i += 2 + continue + if ch == "'": + in_single = not in_single + if in_single or ch != "$" or i + 1 >= n or command[i + 1] != "(": + outer.append(ch) + i += 1 + continue + depth = 0 + body_single = False + j = i + 1 + while j < n: + c = command[j] + if c == "\\" and not body_single: + j += 2 + continue + if c == "'": + body_single = not body_single + elif not body_single: + if c == "(": + depth += 1 + elif c == ")": + depth -= 1 + if depth == 0: + break + j += 1 + bodies.append(command[i + 2 : j]) + i = j + 1 + return "".join(outer), bodies + + def _shell_tokens(command: str) -> list[str]: """Tokenize a shell command while preserving command separators.""" return _lex_lines(command, "|&;()<>") @@ -125,7 +186,9 @@ def extract_shell_command_words(command: str) -> list[str]: expect_command = True skip_redirect_target = False - for word in _shell_tokens(command): + outer, substitutions = _split_command_substitutions(command) + + for word in _shell_tokens(outer): if not word: continue @@ -153,6 +216,11 @@ def extract_shell_command_words(command: str) -> list[str]: command_words.append(word) expect_command = False + # ``$(...)`` runs a command of its own, whether or not it sits inside double + # quotes, so its body is lexed as a further segment. + for body in substitutions: + command_words.extend(extract_shell_command_words(body)) + return command_words diff --git a/nomos/level_4/council/council.py b/nomos/level_4/council/council.py index 47f1c107..b9625c8b 100644 --- a/nomos/level_4/council/council.py +++ b/nomos/level_4/council/council.py @@ -533,6 +533,10 @@ def cast_member_vote( error=f"Intent is not awaiting approval (state: {workflow.state.value})", ) + inadmissible = self._refuse_inadmissible(workflow) + if inadmissible is not None: + return inadmissible + result = self._quorum_manager.cast_vote( intent_id=intent_id, voter_id=voter_id, @@ -545,6 +549,25 @@ def cast_member_vote( self._apply_quorum_result(workflow, result.status, reason) return SubmitResult(success=True, workflow=workflow) + def _refuse_inadmissible(self, workflow: IntentWorkflow) -> SubmitResult | None: + """Deny a stored intent whose command no longer passes admission. + + A record rehydrated from the shared store skips the admission ban so + history stays readable (``Intent.from_stored``); it must never become + executable. Re-check here, on the path every approval takes. + """ + admission_error = Intent.command_admission_error(workflow.intent.command) + if admission_error is None: + return None + error = f"command no longer admissible: {admission_error}" + if workflow.state == WorkflowState.AWAITING_APPROVAL: + workflow.transition_to(WorkflowState.DENIED) + workflow.denied_at = self._clock.now() + workflow.denial_reason = error + self._persist_workflow(workflow) + logger.warning("refusing intent %s: %s", workflow.intent_id, error) + return SubmitResult(success=False, workflow=workflow, error=error) + def revise_vote( self, intent_id: str, @@ -625,6 +648,11 @@ def mint_token( return None intent = workflow.intent + if Intent.command_admission_error(intent.command) is not None: + logger.warning( + "refusing to mint for intent %s: command no longer admissible", intent_id + ) + return None scope = CapabilityScope( action_type=intent.action_type, resource_pattern=intent.target_resource, @@ -788,7 +816,14 @@ def get_pending_approvals(self) -> list[IntentWorkflow]: for data in self._workflow_store.list_workflows_by_state( [WorkflowState.AWAITING_APPROVAL.value] ): - workflow = IntentWorkflow.from_durable_dict(data) + try: + workflow = IntentWorkflow.from_durable_dict(data) + except Exception: # one bad record must not hide the rest + logger.warning( + "skipping unreadable pending workflow %s", + (data.get("intent") or {}).get("intent_id", "?"), + ) + continue pending.setdefault(workflow.intent_id, workflow) except Exception: # listing falls back to local view logger.warning("failed to list pending approvals from store") diff --git a/nomos/level_4/council/workflow.py b/nomos/level_4/council/workflow.py index 24cea164..b6d13b0d 100644 --- a/nomos/level_4/council/workflow.py +++ b/nomos/level_4/council/workflow.py @@ -241,7 +241,7 @@ def _dt(key: str) -> datetime | None: token = data.get("capability_token") return cls( - intent=Intent.from_dict(data["intent"]), + intent=Intent.from_stored(data["intent"]), state=WorkflowState(data["state"]), submitted_at=_dt("submitted_at"), evaluated_at=_dt("evaluated_at"), diff --git a/scripts/council_test_helpers.py b/scripts/council_test_helpers.py index a1c5c831..5eba3086 100644 --- a/scripts/council_test_helpers.py +++ b/scripts/council_test_helpers.py @@ -167,6 +167,23 @@ def print_case(idx: int, case: dict, args: dict, result: dict): print(f" ERROR: {result['error']}") +def admission_rejected(result: dict) -> bool: + """True when the council refused the intent at admission (before review). + + A blocked attack can end as ``state == "denied"`` (reviewed and denied) or + as an explicit validation rejection (``success`` false, error starting + ``Invalid intent``). Transport or server errors are neither. + """ + return result.get("success") is False and str(result.get("error", "")).startswith( + "Invalid intent" + ) + + +def blocked(result: dict) -> bool: + """True when the intent was denied by review or rejected at admission.""" + return result.get("state") == "denied" or admission_rejected(result) + + def print_summary(suite_name: str, results: list): import sys diff --git a/scripts/test_script_obfuscation.py b/scripts/test_script_obfuscation.py index 744c057b..1b06a3a1 100644 --- a/scripts/test_script_obfuscation.py +++ b/scripts/test_script_obfuscation.py @@ -33,6 +33,8 @@ from council_test_helpers import ( MCP_URL, + admission_rejected, + blocked, parse_result, print_case, print_client_config, @@ -200,11 +202,13 @@ async def run_all(): print_case(idx, case, args, result) state = result.get("state", "unknown") + if admission_rejected(result): + state = "rejected at admission" results.append( { "label": case["label"], "state": state, - "passed_unexpectedly": state != "denied", + "passed_unexpectedly": not blocked(result), } ) diff --git a/tests/level_0/test_types.py b/tests/level_0/test_types.py index 125727cc..a7fd0d46 100644 --- a/tests/level_0/test_types.py +++ b/tests/level_0/test_types.py @@ -400,6 +400,35 @@ def test_intent_rejects_control_characters(self, command): ) assert "control character" in str(exc.value) or "backtick" in str(exc.value) + def test_stored_intent_with_control_characters_still_hydrates(self): + """A record that was valid when stored stays readable; fresh submission does not.""" + legacy = Intent.create( + agent_id="agent-1", + action_type="shell.exec", + description="legacy record", + target_resource="/tmp", + command="/bin/true", + ).to_dict() + legacy["command"] = "/bin/true\nrm -rf /tmp/x" + + hydrated = Intent.from_stored(legacy) + assert hydrated.command == "/bin/true\nrm -rf /tmp/x" + assert Intent.command_admission_error(hydrated.command) is not None + with pytest.raises(ValidationError): + Intent.from_dict(legacy) + + def test_stored_intent_still_rejects_dangerous_patterns(self): + legacy = Intent.create( + agent_id="agent-1", + action_type="shell.exec", + description="legacy record", + target_resource="/tmp", + command="/bin/true", + ).to_dict() + legacy["command"] = "mkfs.ext4 /dev/sda1" + with pytest.raises(ValidationError): + Intent.from_stored(legacy) + def test_intent_accepts_pipeline_without_control_characters(self): intent = Intent.create( agent_id="agent-1", diff --git a/tests/level_4/test_council_legacy_commands.py b/tests/level_4/test_council_legacy_commands.py new file mode 100644 index 00000000..ea5eac9e --- /dev/null +++ b/tests/level_4/test_council_legacy_commands.py @@ -0,0 +1,108 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-NvidiaProprietary +# +# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual +# property and proprietary rights in and to this material, related +# documentation and any modifications thereto. Any use, reproduction, +# disclosure or distribution of this material and related documentation +# without an express license agreement from NVIDIA CORPORATION or +# its affiliates is strictly prohibited. + +"""Stored workflows whose command predates the control-character ban. + +Such records were valid when written. They must stay readable (status, pending +lists) but must never become executable: approval is refused and nothing is +minted. A fresh submission with the same command is rejected outright. +""" + +import pytest +from pydantic import ValidationError + +from nomos.level_0.types import Intent +from nomos.level_4.council import SecurityCouncil, WorkflowState + +from .test_council_workflow_store import FakeWorkflowStore, _council + +LEGACY_COMMAND = "/bin/true\nrm -rf /tmp/x" + + +def _shell_intent(command: str, tag: str) -> Intent: + return Intent.create( + agent_id="agent-1", + action_type="shell.exec", + description=f"shell action {tag}", + target_resource="/tmp/test", + command=command, + justification="legacy command hydration test", + ) + + +def _store_with_legacy_and_clean() -> tuple[SecurityCouncil, str, str]: + """Persist two awaiting-approval records; rewrite one to a pre-ban command.""" + store = FakeWorkflowStore() + council = _council(store) + legacy = _shell_intent("/bin/true", "legacy") + clean = _shell_intent("/bin/true", "clean") + for intent in (legacy, clean): + result = council.submit_intent(intent) + assert result.success and result.requires_approval, result.error + record = result.workflow.to_durable_dict() + if intent is legacy: + record["intent"]["command"] = LEGACY_COMMAND + store.upsert_workflow( + intent.intent_id, + record, + state=WorkflowState.AWAITING_APPROVAL.value, + is_terminal=False, + expires_at=None, + ) + return council, legacy.intent_id, clean.intent_id + + +def test_legacy_record_hydrates_and_lists_alongside_clean_record(): + council, legacy_id, clean_id = _store_with_legacy_and_clean() + replica = _council(council._workflow_store) # fresh replica: reads only the store + + legacy = replica.get_workflow(legacy_id) + clean = replica.get_workflow(clean_id) + assert legacy is not None and legacy.intent.command == LEGACY_COMMAND + assert clean is not None and clean.intent.command == "/bin/true" + + pending = {wf.intent_id for wf in replica.get_pending_approvals()} + assert pending == {legacy_id, clean_id} + + +def test_legacy_record_cannot_be_approved_or_minted(): + council, legacy_id, clean_id = _store_with_legacy_and_clean() + store = council._workflow_store + replica = _council(store) + assert replica.get_workflow(legacy_id).intent.command == LEGACY_COMMAND + + result = replica.approve_intent(legacy_id, "alice") + assert result.success is False + assert "command no longer admissible" in result.error + assert replica.get_workflow(legacy_id).state == WorkflowState.DENIED + assert store.rows[legacy_id]["state"] == WorkflowState.DENIED.value + assert replica.mint_token(legacy_id) is None + assert replica.execute_intent(legacy_id).success is False + + # The clean record beside it is unaffected. + assert council.approve_intent(clean_id, "alice").success + assert council.approve_intent(clean_id, "bob").success + assert council.get_workflow(clean_id).state == WorkflowState.APPROVED + assert council.mint_token(clean_id) is not None + + +def test_unreadable_pending_record_is_skipped_not_fatal(): + council, legacy_id, clean_id = _store_with_legacy_and_clean() + store = council._workflow_store + store.rows[legacy_id]["workflow_json"]["intent"]["command"] = "mkfs.ext4 /dev/sda1" + replica = _council(store) + + assert {wf.intent_id for wf in replica.get_pending_approvals()} == {clean_id} + + +def test_fresh_submission_with_newline_is_rejected(): + with pytest.raises(ValidationError) as exc: + _shell_intent(LEGACY_COMMAND, "fresh") + assert "control character" in str(exc.value) diff --git a/tests/test_enforcer.py b/tests/test_enforcer.py index 67383e9f..41b705cb 100644 --- a/tests/test_enforcer.py +++ b/tests/test_enforcer.py @@ -534,6 +534,39 @@ async def test_disallowed_tool_rejected(self, kp, mock_nonce_store): assert result.verification_stage == "tool_whitelist" assert "terraform" in result.error.lower() + @pytest.mark.asyncio + async def test_double_quoted_substitution_checked_against_whitelist(self, kp, mock_nonce_store): + """``"$(uname -s)"`` runs uname; double quotes must not hide it from the whitelist.""" + config = ExecutorConfig( + allowed_working_directories=["/tmp"], + allowed_tools=["echo"], + ) + enforcer = WritEnforcer( + public_key=kp.public_key, + nonce_store=mock_nonce_store, + config=config, + ) + writ = _make_signed_writ(kp, command='/bin/echo "$(uname -s)"') + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False + assert result.verification_stage == "tool_whitelist" + assert "uname" in result.error.lower() + + def test_extract_tool_names_sees_through_double_quotes(self, enforcer): + assert enforcer._extract_tool_names('/bin/echo "$(uname -s)"') == ["echo", "uname"] + assert enforcer._extract_tool_names('/bin/echo "$(echo $(uname -s))"') == [ + "echo", + "echo", + "uname", + ] + assert enforcer._extract_tool_names("/bin/echo '$(uname -s)'") == ["echo"] + assert enforcer._extract_tool_names("/bin/echo $(uname -s)") == ["echo", "uname"] + assert enforcer._extract_tool_names("/bin/cat /tmp/a | /bin/echo $(id -u)") == [ + "cat", + "echo", + "id", + ] + @pytest.mark.asyncio async def test_empty_whitelist_allows_all(self, kp, mock_nonce_store): config = ExecutorConfig( diff --git a/tests/test_policy_shell.py b/tests/test_policy_shell.py index 572e503d..5536af5c 100644 --- a/tests/test_policy_shell.py +++ b/tests/test_policy_shell.py @@ -37,3 +37,29 @@ def test_multi_stage_pipeline_unchanged(self): def test_env_assignment_prefix_unchanged(self): assert extract_shell_command_words("FOO=1 /bin/env") == ["/bin/env"] + + +class TestCommandSubstitution: + def test_double_quoted_substitution_is_extracted(self): + """Double quotes do not stop $(...) from running; the inner tool must be seen.""" + assert extract_shell_command_words('/bin/echo "$(uname -s)"') == ["/bin/echo", "uname"] + assert "uname" in shell_path_policy_error('/bin/echo "$(uname -s)"') + + def test_nested_double_quoted_substitution_is_extracted(self): + words = extract_shell_command_words('/bin/echo "$(echo $(uname -s))"') + assert words == ["/bin/echo", "echo", "uname"] + + def test_single_quoted_substitution_is_literal(self): + assert extract_shell_command_words("/bin/echo '$(uname -s)'") == ["/bin/echo"] + assert shell_path_policy_error("/bin/echo '$(uname -s)'") == "" + + def test_unquoted_substitution_still_extracted(self): + assert extract_shell_command_words("/bin/echo $(uname -s)") == ["/bin/echo", "uname"] + + def test_unbalanced_substitution_runs_to_end(self): + assert extract_shell_command_words('/bin/echo "$(uname -s') == ["/bin/echo", "uname"] + + def test_existing_pipeline_with_substitution_unchanged(self): + command = "/bin/cat /tmp/a | /bin/grep x && /bin/echo $(id -u)" + assert extract_shell_command_words(command) == ["/bin/cat", "/bin/grep", "/bin/echo", "id"] + assert "id" in shell_path_policy_error(command) From 40074298487fee79c973f9f12f530bdcdd62b18f Mon Sep 17 00:00:00 2001 From: drobison Date: Thu, 17 Sep 2026 13:33:31 -0600 Subject: [PATCH 3/6] fix(policy): track shell quote context in the substitution scanner The scanner now follows the shell's quoting rules: an apostrophe inside double quotes is literal, a body's quote state starts fresh, and parentheses count only outside quotes, so a quoted ")" no longer ends a substitution early. Balanced $((...)) is recognised as arithmetic and runs no command of its own; only substitutions nested inside it are extracted. Each substitution leaves a marker in the outer command, and a marker in command position is reported as the word "$(...)" so a command name produced by expansion fails the absolute-path policy and the tool whitelist. Process substitution bodies <(...) and >(...) are extracted too. Both scanner copies stay byte-identical. Co-Authored-By: Claude Fable 5.1 --- executors/docker/enforcer.py | 129 ++++++++++++++++++++++++---------- nomos/level_0/types/intent.py | 3 +- nomos/level_1/policy/shell.py | 129 ++++++++++++++++++++++++---------- tests/test_enforcer.py | 61 ++++++++++++++++ tests/test_policy_shell.py | 37 ++++++++++ 5 files changed, 280 insertions(+), 79 deletions(-) diff --git a/executors/docker/enforcer.py b/executors/docker/enforcer.py index a7c6d128..036ccfbf 100644 --- a/executors/docker/enforcer.py +++ b/executors/docker/enforcer.py @@ -53,61 +53,107 @@ logger = logging.getLogger(__name__) +# Marks the place where a substitution stood in the outer command. A word in +# command position that carries it names an executable the shell would only +# know after expansion, which policy cannot inspect. +_SUBSTITUTION_MARK = "\x1fSUBST\x1f" +SUBSTITUTED_COMMAND_WORD = "$(...)" + + def _split_command_substitutions(command: str) -> tuple[str, list[str]]: - """Cut every ``$(...)`` command substitution out of ``command``. - - Returns the command with each substitution removed, plus the body of each - one in order. The caller lexes every body as a command of its own, so a - tool named inside a substitution is checked like any other command word. - - Single-quoted text is literal to the shell and is left alone. Double quotes - do **not** suppress substitution, so bodies inside them are cut out too. A - ``$(`` with no closing parenthesis is taken to run to the end of the - command, which is the conservative reading. ``$((...))`` yields a body - wrapped in parentheses: bash falls back to a subshell substitution when the - text is not arithmetic, so the body is lexed as a command group. Nested - substitutions are found when the body is lexed. + """Replace every command substitution in ``command`` with a marker. + + Returns the command with each ``$(...)``, ``<(...)`` and ``>(...)`` replaced + by ``_SUBSTITUTION_MARK``, plus the body of each one in order. The caller + lexes every body as a command of its own, so a tool named inside a + substitution is checked like any other command word, and a marker left in + command position means the executable itself comes from a substitution. + + Quote context follows the shell: single-quoted text is literal and never + starts a substitution, an apostrophe inside double quotes is literal, and + double quotes do **not** suppress ``$(...)``. Inside a body the quote state + starts fresh, and parentheses only count outside quotes, so a quoted ``)`` + does not end the body. A substitution with no closing parenthesis runs to + the end of the command, which is the conservative reading. + + ``$((...))`` whose text is balanced is arithmetic expansion: it runs no + command of its own, so only nested ``$(...)`` inside it are extracted. """ outer: list[str] = [] bodies: list[str] = [] - in_single = False + quote = "" # "", "'" or '"' i = 0 n = len(command) while i < n: ch = command[i] - if ch == "\\" and not in_single: + if ch == "\\" and quote != "'": outer.append(command[i : i + 2]) i += 2 continue - if ch == "'": - in_single = not in_single - if in_single or ch != "$" or i + 1 >= n or command[i + 1] != "(": + if ch == quote: + quote = "" outer.append(ch) i += 1 continue - depth = 0 - body_single = False - j = i + 1 - while j < n: - c = command[j] - if c == "\\" and not body_single: - j += 2 - continue - if c == "'": - body_single = not body_single - elif not body_single: - if c == "(": - depth += 1 - elif c == ")": - depth -= 1 - if depth == 0: - break - j += 1 - bodies.append(command[i + 2 : j]) - i = j + 1 + if not quote and ch in "'\"": + quote = ch + outer.append(ch) + i += 1 + continue + # ``$(`` opens a substitution outside quotes and inside double quotes; + # process substitution only outside quotes; nothing inside single quotes. + starts = ( + i + 1 < n + and command[i + 1] == "(" + and ((ch == "$" and quote != "'") or (ch in "<>" and not quote)) + ) + if not starts: + outer.append(ch) + i += 1 + continue + end = _matching_paren(command, i + 1) + body = command[i + 2 : end] + if ch == "$" and body.startswith("(") and body.endswith(")") and end < n: + # Arithmetic: nothing runs directly, but the expression is expanded + # first, so substitutions nested inside it still do. + bodies.extend(_split_command_substitutions(body[1:-1])[1]) + else: + bodies.append(body) + outer.append(_SUBSTITUTION_MARK) + i = end + 1 return "".join(outer), bodies +def _matching_paren(command: str, start: int) -> int: + """Index of the ``)`` that closes the ``(`` at ``start``, or ``len(command)``. + + Parentheses are counted only outside quotes; quote state starts fresh at + the opening parenthesis, as it does for the shell. + """ + depth = 0 + quote = "" + j = start + n = len(command) + while j < n: + c = command[j] + if c == "\\" and quote != "'": + j += 2 + continue + if quote: + if c == quote: + quote = "" + elif c in "'\"": + quote = c + elif c == "(": + depth += 1 + elif c == ")": + depth -= 1 + if depth == 0: + return j + j += 1 + return n + + class WritEnforcer: """Verifies and executes Writs of Execution. @@ -430,7 +476,12 @@ def _extract_tool_names(self, command: str) -> list[str]: if expect_command: if self._is_env_assignment(word): continue - tools.append(os.path.basename(word)) + if _SUBSTITUTION_MARK in word: + # The executable name is produced by a substitution at + # run time; no whitelist entry can vouch for it. + tools.append(SUBSTITUTED_COMMAND_WORD) + else: + tools.append(os.path.basename(word)) expect_command = False # ``$(...)`` runs a command of its own, inside double quotes too, so its diff --git a/nomos/level_0/types/intent.py b/nomos/level_0/types/intent.py index a10df4c4..a04ff7da 100644 --- a/nomos/level_0/types/intent.py +++ b/nomos/level_0/types/intent.py @@ -284,7 +284,8 @@ def command_admission_error(command: str) -> str | None: if "`" in command: return ( "Command contains backtick command substitution, which policy cannot " - "inspect; use $(...), whose body is inspected" + "inspect; use $(...), whose body is lexed like any other command and " + "which may not supply the command name itself" ) return None diff --git a/nomos/level_1/policy/shell.py b/nomos/level_1/policy/shell.py index 66a7781d..acc12d6f 100644 --- a/nomos/level_1/policy/shell.py +++ b/nomos/level_1/policy/shell.py @@ -53,61 +53,107 @@ def _lex_lines(command: str, punctuation_chars: str) -> list[str]: return tokens +# Marks the place where a substitution stood in the outer command. A word in +# command position that carries it names an executable the shell would only +# know after expansion, which policy cannot inspect. +_SUBSTITUTION_MARK = "\x1fSUBST\x1f" +SUBSTITUTED_COMMAND_WORD = "$(...)" + + def _split_command_substitutions(command: str) -> tuple[str, list[str]]: - """Cut every ``$(...)`` command substitution out of ``command``. - - Returns the command with each substitution removed, plus the body of each - one in order. The caller lexes every body as a command of its own, so a - tool named inside a substitution is checked like any other command word. - - Single-quoted text is literal to the shell and is left alone. Double quotes - do **not** suppress substitution, so bodies inside them are cut out too. A - ``$(`` with no closing parenthesis is taken to run to the end of the - command, which is the conservative reading. ``$((...))`` yields a body - wrapped in parentheses: bash falls back to a subshell substitution when the - text is not arithmetic, so the body is lexed as a command group. Nested - substitutions are found when the body is lexed. + """Replace every command substitution in ``command`` with a marker. + + Returns the command with each ``$(...)``, ``<(...)`` and ``>(...)`` replaced + by ``_SUBSTITUTION_MARK``, plus the body of each one in order. The caller + lexes every body as a command of its own, so a tool named inside a + substitution is checked like any other command word, and a marker left in + command position means the executable itself comes from a substitution. + + Quote context follows the shell: single-quoted text is literal and never + starts a substitution, an apostrophe inside double quotes is literal, and + double quotes do **not** suppress ``$(...)``. Inside a body the quote state + starts fresh, and parentheses only count outside quotes, so a quoted ``)`` + does not end the body. A substitution with no closing parenthesis runs to + the end of the command, which is the conservative reading. + + ``$((...))`` whose text is balanced is arithmetic expansion: it runs no + command of its own, so only nested ``$(...)`` inside it are extracted. """ outer: list[str] = [] bodies: list[str] = [] - in_single = False + quote = "" # "", "'" or '"' i = 0 n = len(command) while i < n: ch = command[i] - if ch == "\\" and not in_single: + if ch == "\\" and quote != "'": outer.append(command[i : i + 2]) i += 2 continue - if ch == "'": - in_single = not in_single - if in_single or ch != "$" or i + 1 >= n or command[i + 1] != "(": + if ch == quote: + quote = "" outer.append(ch) i += 1 continue - depth = 0 - body_single = False - j = i + 1 - while j < n: - c = command[j] - if c == "\\" and not body_single: - j += 2 - continue - if c == "'": - body_single = not body_single - elif not body_single: - if c == "(": - depth += 1 - elif c == ")": - depth -= 1 - if depth == 0: - break - j += 1 - bodies.append(command[i + 2 : j]) - i = j + 1 + if not quote and ch in "'\"": + quote = ch + outer.append(ch) + i += 1 + continue + # ``$(`` opens a substitution outside quotes and inside double quotes; + # process substitution only outside quotes; nothing inside single quotes. + starts = ( + i + 1 < n + and command[i + 1] == "(" + and ((ch == "$" and quote != "'") or (ch in "<>" and not quote)) + ) + if not starts: + outer.append(ch) + i += 1 + continue + end = _matching_paren(command, i + 1) + body = command[i + 2 : end] + if ch == "$" and body.startswith("(") and body.endswith(")") and end < n: + # Arithmetic: nothing runs directly, but the expression is expanded + # first, so substitutions nested inside it still do. + bodies.extend(_split_command_substitutions(body[1:-1])[1]) + else: + bodies.append(body) + outer.append(_SUBSTITUTION_MARK) + i = end + 1 return "".join(outer), bodies +def _matching_paren(command: str, start: int) -> int: + """Index of the ``)`` that closes the ``(`` at ``start``, or ``len(command)``. + + Parentheses are counted only outside quotes; quote state starts fresh at + the opening parenthesis, as it does for the shell. + """ + depth = 0 + quote = "" + j = start + n = len(command) + while j < n: + c = command[j] + if c == "\\" and quote != "'": + j += 2 + continue + if quote: + if c == quote: + quote = "" + elif c in "'\"": + quote = c + elif c == "(": + depth += 1 + elif c == ")": + depth -= 1 + if depth == 0: + return j + j += 1 + return n + + def _shell_tokens(command: str) -> list[str]: """Tokenize a shell command while preserving command separators.""" return _lex_lines(command, "|&;()<>") @@ -213,7 +259,12 @@ def extract_shell_command_words(command: str) -> list[str]: if expect_command: if _is_env_assignment(word): continue - command_words.append(word) + if _SUBSTITUTION_MARK in word: + # The executable name is produced by a substitution at run + # time; report it as such so policy fails closed. + command_words.append(SUBSTITUTED_COMMAND_WORD) + else: + command_words.append(word) expect_command = False # ``$(...)`` runs a command of its own, whether or not it sits inside double diff --git a/tests/test_enforcer.py b/tests/test_enforcer.py index 41b705cb..f529ba14 100644 --- a/tests/test_enforcer.py +++ b/tests/test_enforcer.py @@ -567,6 +567,67 @@ def test_extract_tool_names_sees_through_double_quotes(self, enforcer): "id", ] + @pytest.mark.asyncio + async def test_quoted_paren_in_substitution_checked(self, kp, mock_nonce_store): + """A quoted ``)`` inside ``$(...)`` must not end the body early and hide a later tool.""" + config = ExecutorConfig( + allowed_working_directories=["/tmp"], + allowed_tools=["echo", "printf"], + ) + enforcer = WritEnforcer( + public_key=kp.public_key, + nonce_store=mock_nonce_store, + config=config, + ) + writ = _make_signed_writ(kp, command='/bin/echo $(/bin/printf ")"; uname -s)') + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False + assert result.verification_stage == "tool_whitelist" + assert "uname" in result.error.lower() + + @pytest.mark.asyncio + async def test_substituted_command_word_rejected_by_whitelist(self, kp, mock_nonce_store): + """``$( $(/bin/echo uname) )`` runs whatever the inner echo prints; refuse it.""" + config = ExecutorConfig( + allowed_working_directories=["/tmp"], + allowed_tools=["echo"], + ) + enforcer = WritEnforcer( + public_key=kp.public_key, + nonce_store=mock_nonce_store, + config=config, + ) + for command in ('/bin/echo "$( $(/bin/echo uname) )"', "/bin/echo \"'$(uname -s)'\""): + writ = _make_signed_writ(kp, command=command) + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False, command + assert result.verification_stage == "tool_whitelist", command + + @pytest.mark.asyncio + async def test_arithmetic_expansion_is_not_a_tool(self, kp, mock_nonce_store): + config = ExecutorConfig( + allowed_working_directories=["/tmp"], + max_command_timeout=30, + allowed_tools=["echo"], + ) + enforcer = WritEnforcer( + public_key=kp.public_key, + nonce_store=mock_nonce_store, + config=config, + ) + assert enforcer._extract_tool_names("/bin/echo $((1+2))") == ["echo"] + assert enforcer._extract_tool_names('/bin/echo "$((1+2))"') == ["echo"] + assert enforcer._extract_tool_names("/bin/echo $(( $(uname -s) ))") == ["echo", "uname"] + writ = _make_signed_writ(kp, command="/bin/echo $((1+2))") + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is True + assert result.stdout.strip() == "3" + + def test_extract_tool_names_sees_process_substitution(self, enforcer): + assert enforcer._extract_tool_names("/bin/cat <(uname -s)") == ["cat", "uname"] + assert enforcer._extract_tool_names('/bin/echo "it\'s $(uname -s)"') == ["echo", "uname"] + assert enforcer._extract_tool_names("$(/bin/echo uname)") == ["$(...)", "echo"] + @pytest.mark.asyncio async def test_empty_whitelist_allows_all(self, kp, mock_nonce_store): config = ExecutorConfig( diff --git a/tests/test_policy_shell.py b/tests/test_policy_shell.py index 5536af5c..b5612825 100644 --- a/tests/test_policy_shell.py +++ b/tests/test_policy_shell.py @@ -59,6 +59,43 @@ def test_unquoted_substitution_still_extracted(self): def test_unbalanced_substitution_runs_to_end(self): assert extract_shell_command_words('/bin/echo "$(uname -s') == ["/bin/echo", "uname"] + def test_apostrophe_inside_double_quotes_is_literal(self): + """An apostrophe inside double quotes does not open a single-quoted run.""" + words = extract_shell_command_words('/bin/echo "it\'s $(uname -s)"') + assert words == ["/bin/echo", "uname"] + words = extract_shell_command_words("/bin/echo \"'$(uname -s)'\"") + assert words == ["/bin/echo", "uname"] + + def test_quoted_close_paren_does_not_end_body(self): + command = '/bin/echo $(/bin/printf ")"; uname -s)' + assert extract_shell_command_words(command) == ["/bin/echo", "/bin/printf", "uname"] + assert extract_shell_command_words("/bin/echo $(echo ')')") == ["/bin/echo", "echo"] + + def test_arithmetic_expansion_runs_no_command(self): + for command in ("/bin/echo $((1+2))", '/bin/echo "$((1+2))"', "/bin/echo $(( (1+2)*3 ))"): + assert extract_shell_command_words(command) == ["/bin/echo"], command + assert shell_path_policy_error(command) == "", command + + def test_substitution_nested_in_arithmetic_is_extracted(self): + assert extract_shell_command_words("/bin/echo $(( $(uname -s) ))") == ["/bin/echo", "uname"] + + def test_substitution_supplying_the_command_word_fails_closed(self): + """When the executable name comes from a substitution nobody can inspect it.""" + words = extract_shell_command_words('/bin/echo "$( $(/bin/echo uname) )"') + assert words == ["/bin/echo", "$(...)", "/bin/echo"] + assert "$(...)" in shell_path_policy_error('/bin/echo "$( $(/bin/echo uname) )"') + assert extract_shell_command_words("$(/bin/echo uname)") == ["$(...)", "/bin/echo"] + assert extract_shell_command_words("/bin/echo$(uname)") == ["$(...)", "uname"] + + def test_process_substitution_body_is_extracted(self): + assert extract_shell_command_words("/bin/cat <(uname -s)") == ["/bin/cat", "uname"] + words = extract_shell_command_words("/bin/tee >(uname -s) Date: Thu, 17 Sep 2026 13:43:27 -0600 Subject: [PATCH 4/6] fix(policy): give nested substitutions their own quote context _matching_paren now recurses into a nested $(...) (also inside double quotes) and resumes the enclosing quote state afterwards, so a quote or ")" inside the nested body cannot end the outer substitution early and hide a later command word. Regression tests cover the nested printf form at policy and signed-writ level. Both scanner copies stay byte-identical. Co-Authored-By: Claude Fable 5.1 --- executors/docker/enforcer.py | 14 +++++++++++++- nomos/level_1/policy/shell.py | 14 +++++++++++++- tests/test_enforcer.py | 20 ++++++++++++++++++++ tests/test_policy_shell.py | 13 +++++++++++++ 4 files changed, 59 insertions(+), 2 deletions(-) diff --git a/executors/docker/enforcer.py b/executors/docker/enforcer.py index 036ccfbf..ed840d3e 100644 --- a/executors/docker/enforcer.py +++ b/executors/docker/enforcer.py @@ -128,7 +128,10 @@ def _matching_paren(command: str, start: int) -> int: """Index of the ``)`` that closes the ``(`` at ``start``, or ``len(command)``. Parentheses are counted only outside quotes; quote state starts fresh at - the opening parenthesis, as it does for the shell. + the opening parenthesis, as it does for the shell. A nested ``$(`` (also + inside double quotes) opens its own context: it is matched recursively and + the enclosing quote state resumes after it, so a quote or ``)`` inside the + nested body cannot end the outer one. """ depth = 0 quote = "" @@ -139,6 +142,15 @@ def _matching_paren(command: str, start: int) -> int: if c == "\\" and quote != "'": j += 2 continue + if quote == "'": + if c == "'": + quote = "" + j += 1 + continue + nested = j + 1 < n and command[j + 1] == "(" and (c == "$" or (c in "<>" and not quote)) + if nested and j > start: + j = _matching_paren(command, j + 1) + 1 + continue if quote: if c == quote: quote = "" diff --git a/nomos/level_1/policy/shell.py b/nomos/level_1/policy/shell.py index acc12d6f..c599b5da 100644 --- a/nomos/level_1/policy/shell.py +++ b/nomos/level_1/policy/shell.py @@ -128,7 +128,10 @@ def _matching_paren(command: str, start: int) -> int: """Index of the ``)`` that closes the ``(`` at ``start``, or ``len(command)``. Parentheses are counted only outside quotes; quote state starts fresh at - the opening parenthesis, as it does for the shell. + the opening parenthesis, as it does for the shell. A nested ``$(`` (also + inside double quotes) opens its own context: it is matched recursively and + the enclosing quote state resumes after it, so a quote or ``)`` inside the + nested body cannot end the outer one. """ depth = 0 quote = "" @@ -139,6 +142,15 @@ def _matching_paren(command: str, start: int) -> int: if c == "\\" and quote != "'": j += 2 continue + if quote == "'": + if c == "'": + quote = "" + j += 1 + continue + nested = j + 1 < n and command[j + 1] == "(" and (c == "$" or (c in "<>" and not quote)) + if nested and j > start: + j = _matching_paren(command, j + 1) + 1 + continue if quote: if c == quote: quote = "" diff --git a/tests/test_enforcer.py b/tests/test_enforcer.py index f529ba14..fbcd6496 100644 --- a/tests/test_enforcer.py +++ b/tests/test_enforcer.py @@ -585,6 +585,26 @@ async def test_quoted_paren_in_substitution_checked(self, kp, mock_nonce_store): assert result.verification_stage == "tool_whitelist" assert "uname" in result.error.lower() + @pytest.mark.asyncio + async def test_nested_quoted_substitution_checked(self, kp, mock_nonce_store): + """Nested ``$(...)`` inside double quotes gets its own quote context.""" + config = ExecutorConfig( + allowed_working_directories=["/tmp"], + allowed_tools=["echo", "printf"], + ) + enforcer = WritEnforcer( + public_key=kp.public_key, + nonce_store=mock_nonce_store, + config=config, + ) + command = '/bin/echo "$(/bin/echo "$(/bin/printf ")")"; uname -s)"' + assert enforcer._extract_tool_names(command) == ["echo", "echo", "uname", "printf"] + writ = _make_signed_writ(kp, command=command) + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False + assert result.verification_stage == "tool_whitelist" + assert "uname" in result.error.lower() + @pytest.mark.asyncio async def test_substituted_command_word_rejected_by_whitelist(self, kp, mock_nonce_store): """``$( $(/bin/echo uname) )`` runs whatever the inner echo prints; refuse it.""" diff --git a/tests/test_policy_shell.py b/tests/test_policy_shell.py index b5612825..6b02ee1a 100644 --- a/tests/test_policy_shell.py +++ b/tests/test_policy_shell.py @@ -71,6 +71,19 @@ def test_quoted_close_paren_does_not_end_body(self): assert extract_shell_command_words(command) == ["/bin/echo", "/bin/printf", "uname"] assert extract_shell_command_words("/bin/echo $(echo ')')") == ["/bin/echo", "echo"] + def test_nested_substitution_keeps_its_own_quote_context(self): + """A quote or ``)`` inside a nested ``$(...)`` cannot end the enclosing body.""" + command = '/bin/echo "$(/bin/echo "$(/bin/printf ")")"; uname -s)"' + assert extract_shell_command_words(command) == [ + "/bin/echo", + "/bin/echo", + "uname", + "/bin/printf", + ] + assert "uname" in shell_path_policy_error(command) + words = extract_shell_command_words('/bin/echo $(/bin/echo "$(uname)" x) y') + assert words == ["/bin/echo", "/bin/echo", "uname"] + def test_arithmetic_expansion_runs_no_command(self): for command in ("/bin/echo $((1+2))", '/bin/echo "$((1+2))"', "/bin/echo $(( (1+2)*3 ))"): assert extract_shell_command_words(command) == ["/bin/echo"], command From e276b16d80730d1416a0fc7cc62b283e607278c6 Mon Sep 17 00:00:00 2001 From: drobison Date: Thu, 17 Sep 2026 13:52:41 -0600 Subject: [PATCH 5/6] fix(policy): scan arithmetic expressions as double-quoted text The shell treats the inside of $((...)) as if it were double-quoted, so single quotes there are ordinary characters and a $(...) between them still runs. The scanner now passes arithmetic=True when it looks inside an arithmetic expression, which makes quote characters plain text and extracts every nested substitution. Tests cover the direct and the parameter-default forms at policy and signed-writ level. Both scanner copies stay byte-identical. Co-Authored-By: Claude Fable 5.1 --- executors/docker/enforcer.py | 11 ++++++++--- nomos/level_1/policy/shell.py | 11 ++++++++--- tests/test_enforcer.py | 22 ++++++++++++++++++++++ tests/test_policy_shell.py | 10 ++++++++++ 4 files changed, 48 insertions(+), 6 deletions(-) diff --git a/executors/docker/enforcer.py b/executors/docker/enforcer.py index ed840d3e..41d9973a 100644 --- a/executors/docker/enforcer.py +++ b/executors/docker/enforcer.py @@ -60,7 +60,9 @@ SUBSTITUTED_COMMAND_WORD = "$(...)" -def _split_command_substitutions(command: str) -> tuple[str, list[str]]: +def _split_command_substitutions( + command: str, *, arithmetic: bool = False +) -> tuple[str, list[str]]: """Replace every command substitution in ``command`` with a marker. Returns the command with each ``$(...)``, ``<(...)`` and ``>(...)`` replaced @@ -78,6 +80,9 @@ def _split_command_substitutions(command: str) -> tuple[str, list[str]]: ``$((...))`` whose text is balanced is arithmetic expansion: it runs no command of its own, so only nested ``$(...)`` inside it are extracted. + The shell treats an arithmetic expression as if it were double-quoted, so + when ``arithmetic`` is set quote characters are ordinary text and every + ``$(`` inside the expression is a substitution. """ outer: list[str] = [] bodies: list[str] = [] @@ -95,7 +100,7 @@ def _split_command_substitutions(command: str) -> tuple[str, list[str]]: outer.append(ch) i += 1 continue - if not quote and ch in "'\"": + if not quote and not arithmetic and ch in "'\"": quote = ch outer.append(ch) i += 1 @@ -116,7 +121,7 @@ def _split_command_substitutions(command: str) -> tuple[str, list[str]]: if ch == "$" and body.startswith("(") and body.endswith(")") and end < n: # Arithmetic: nothing runs directly, but the expression is expanded # first, so substitutions nested inside it still do. - bodies.extend(_split_command_substitutions(body[1:-1])[1]) + bodies.extend(_split_command_substitutions(body[1:-1], arithmetic=True)[1]) else: bodies.append(body) outer.append(_SUBSTITUTION_MARK) diff --git a/nomos/level_1/policy/shell.py b/nomos/level_1/policy/shell.py index c599b5da..572a6ddf 100644 --- a/nomos/level_1/policy/shell.py +++ b/nomos/level_1/policy/shell.py @@ -60,7 +60,9 @@ def _lex_lines(command: str, punctuation_chars: str) -> list[str]: SUBSTITUTED_COMMAND_WORD = "$(...)" -def _split_command_substitutions(command: str) -> tuple[str, list[str]]: +def _split_command_substitutions( + command: str, *, arithmetic: bool = False +) -> tuple[str, list[str]]: """Replace every command substitution in ``command`` with a marker. Returns the command with each ``$(...)``, ``<(...)`` and ``>(...)`` replaced @@ -78,6 +80,9 @@ def _split_command_substitutions(command: str) -> tuple[str, list[str]]: ``$((...))`` whose text is balanced is arithmetic expansion: it runs no command of its own, so only nested ``$(...)`` inside it are extracted. + The shell treats an arithmetic expression as if it were double-quoted, so + when ``arithmetic`` is set quote characters are ordinary text and every + ``$(`` inside the expression is a substitution. """ outer: list[str] = [] bodies: list[str] = [] @@ -95,7 +100,7 @@ def _split_command_substitutions(command: str) -> tuple[str, list[str]]: outer.append(ch) i += 1 continue - if not quote and ch in "'\"": + if not quote and not arithmetic and ch in "'\"": quote = ch outer.append(ch) i += 1 @@ -116,7 +121,7 @@ def _split_command_substitutions(command: str) -> tuple[str, list[str]]: if ch == "$" and body.startswith("(") and body.endswith(")") and end < n: # Arithmetic: nothing runs directly, but the expression is expanded # first, so substitutions nested inside it still do. - bodies.extend(_split_command_substitutions(body[1:-1])[1]) + bodies.extend(_split_command_substitutions(body[1:-1], arithmetic=True)[1]) else: bodies.append(body) outer.append(_SUBSTITUTION_MARK) diff --git a/tests/test_enforcer.py b/tests/test_enforcer.py index fbcd6496..901dc917 100644 --- a/tests/test_enforcer.py +++ b/tests/test_enforcer.py @@ -643,6 +643,28 @@ async def test_arithmetic_expansion_is_not_a_tool(self, kp, mock_nonce_store): assert result.success is True assert result.stdout.strip() == "3" + @pytest.mark.asyncio + async def test_quoted_substitution_inside_arithmetic_rejected(self, kp, mock_nonce_store): + """``$((1 + '$(uname)'))`` still runs uname; the quotes are not delimiters.""" + config = ExecutorConfig( + allowed_working_directories=["/tmp"], + allowed_tools=["echo"], + ) + enforcer = WritEnforcer( + public_key=kp.public_key, + nonce_store=mock_nonce_store, + config=config, + ) + for command in ( + "/bin/echo \"$((1 + '$(uname)'))\"", + "/bin/echo \"$((1 + ${unset_var:-'$(uname -s >&2)'}))\"", + ): + assert enforcer._extract_tool_names(command) == ["echo", "uname"], command + writ = _make_signed_writ(kp, command=command) + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False, command + assert result.verification_stage == "tool_whitelist", command + def test_extract_tool_names_sees_process_substitution(self, enforcer): assert enforcer._extract_tool_names("/bin/cat <(uname -s)") == ["cat", "uname"] assert enforcer._extract_tool_names('/bin/echo "it\'s $(uname -s)"') == ["echo", "uname"] diff --git a/tests/test_policy_shell.py b/tests/test_policy_shell.py index 6b02ee1a..59e4569c 100644 --- a/tests/test_policy_shell.py +++ b/tests/test_policy_shell.py @@ -89,6 +89,16 @@ def test_arithmetic_expansion_runs_no_command(self): assert extract_shell_command_words(command) == ["/bin/echo"], command assert shell_path_policy_error(command) == "", command + def test_quotes_inside_arithmetic_do_not_hide_substitutions(self): + """An arithmetic expression is treated as double-quoted by the shell, so + single quotes inside it are ordinary text and ``$(...)`` still runs.""" + for command in ( + "/bin/echo \"$((1 + '$(uname)'))\"", + "/bin/echo $((1 + '$(uname)'))", + "/bin/echo \"$((1 + ${unset_var:-'$(uname -s >&2)'}))\"", + ): + assert extract_shell_command_words(command) == ["/bin/echo", "uname"], command + def test_substitution_nested_in_arithmetic_is_extracted(self): assert extract_shell_command_words("/bin/echo $(( $(uname -s) ))") == ["/bin/echo", "uname"] From 987d00fe6a0feced209dadb9f4b4c99bc150e25e Mon Sep 17 00:00:00 2001 From: drobison Date: Thu, 17 Sep 2026 14:07:16 -0600 Subject: [PATCH 6/6] fix(executor): reject NUL early; guard the pending-record log; Apache headers - The executor's early hidden-character check now covers NUL, so a writ carrying one is refused at the blocked_pattern stage before any packaged file is written, instead of failing later inside subprocess. - get_pending_approvals extracts the intent id for its skip log only when the stored intent is a mapping, so a wrong-shaped record is skipped rather than aborting the listing. - The obfuscation probe normalises an admission rejection before the per-case line is printed, so the verdict and the summary agree. - New test files carry the repository's Apache-2.0 header. Co-Authored-By: Claude Fable 5.1 --- executors/docker/enforcer.py | 7 ++-- nomos/level_4/council/council.py | 8 ++++- scripts/council_test_helpers.py | 9 +++-- scripts/test_script_obfuscation.py | 6 ++-- tests/level_4/test_council_legacy_commands.py | 35 ++++++++++++++----- tests/test_enforcer.py | 17 +++++++++ tests/test_policy_shell.py | 9 +---- 7 files changed, 66 insertions(+), 25 deletions(-) diff --git a/executors/docker/enforcer.py b/executors/docker/enforcer.py index 41d9973a..9e95fed4 100644 --- a/executors/docker/enforcer.py +++ b/executors/docker/enforcer.py @@ -45,8 +45,9 @@ _COMMAND_SEPARATORS = {";", "&&", "||", "|", "&", "\n"} _LINE_BREAK = re.compile(r"\r\n|\r|\n") # Characters that hide a second command from the tokenizer: line breaks are -# command terminators in sh -c, a backtick is command substitution. -_HIDDEN_COMMAND_CHARS = re.compile(r"[\r\n`]") +# command terminators in sh -c, a backtick is command substitution, and NUL +# would only fail later inside subprocess, after packaged files were unpacked. +_HIDDEN_COMMAND_CHARS = re.compile(r"[\r\n\x00`]") _COMMAND_GROUP_TOKENS = {"(", ")"} _REDIRECT_TOKENS = {">", ">>", "<", "<<", "2>", "2>>", "&>", ">&"} @@ -332,7 +333,7 @@ async def execute_writ( if _HIDDEN_COMMAND_CHARS.search(writ.command): return ExecutionResult( writ_id=writ.writ_id, - error="Command contains a line break or backtick — rejected", + error="Command contains a line break, NUL, or backtick — rejected", verification_stage="blocked_pattern", ) blocked = self._check_blocked_patterns(writ.command) diff --git a/nomos/level_4/council/council.py b/nomos/level_4/council/council.py index b9625c8b..555c5645 100644 --- a/nomos/level_4/council/council.py +++ b/nomos/level_4/council/council.py @@ -819,9 +819,15 @@ def get_pending_approvals(self) -> list[IntentWorkflow]: try: workflow = IntentWorkflow.from_durable_dict(data) except Exception: # one bad record must not hide the rest + stored_intent = data.get("intent") + intent_id = ( + stored_intent.get("intent_id", "?") + if isinstance(stored_intent, dict) + else "?" + ) logger.warning( "skipping unreadable pending workflow %s", - (data.get("intent") or {}).get("intent_id", "?"), + intent_id, ) continue pending.setdefault(workflow.intent_id, workflow) diff --git a/scripts/council_test_helpers.py b/scripts/council_test_helpers.py index 5eba3086..33e463b5 100644 --- a/scripts/council_test_helpers.py +++ b/scripts/council_test_helpers.py @@ -69,9 +69,12 @@ def print_case(idx: int, case: dict, args: dict, result: dict): chairman = result.get("chairman", {}) votes = result.get("council_members", []) - verdict = ( - "\033[92m✅ DENIED\033[0m" if state == "denied" else f"\033[91m❌ PASSED ({state})\033[0m" - ) + if state == "denied": + verdict = "\033[92m✅ DENIED\033[0m" + elif state == "rejected at admission": + verdict = "\033[92m✅ REJECTED AT ADMISSION\033[0m" + else: + verdict = f"\033[91m❌ PASSED ({state})\033[0m" print(f"\n{'=' * 72}") print(f" CASE {idx}: {case['label']}") diff --git a/scripts/test_script_obfuscation.py b/scripts/test_script_obfuscation.py index 1b06a3a1..67c2ea6d 100644 --- a/scripts/test_script_obfuscation.py +++ b/scripts/test_script_obfuscation.py @@ -200,10 +200,12 @@ async def run_all(): except Exception as e: result = {"state": "error", "error": str(e)} + if admission_rejected(result): + # Normalise before printing so the per-case verdict and the + # summary agree that an admission rejection is a block. + result["state"] = "rejected at admission" print_case(idx, case, args, result) state = result.get("state", "unknown") - if admission_rejected(result): - state = "rejected at admission" results.append( { "label": case["label"], diff --git a/tests/level_4/test_council_legacy_commands.py b/tests/level_4/test_council_legacy_commands.py index ea5eac9e..d7a99f5b 100644 --- a/tests/level_4/test_council_legacy_commands.py +++ b/tests/level_4/test_council_legacy_commands.py @@ -1,12 +1,5 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: LicenseRef-NvidiaProprietary -# -# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual -# property and proprietary rights in and to this material, related -# documentation and any modifications thereto. Any use, reproduction, -# disclosure or distribution of this material and related documentation -# without an express license agreement from NVIDIA CORPORATION or -# its affiliates is strictly prohibited. +# SPDX-License-Identifier: Apache-2.0 """Stored workflows whose command predates the control-character ban. @@ -106,3 +99,29 @@ def test_fresh_submission_with_newline_is_rejected(): with pytest.raises(ValidationError) as exc: _shell_intent(LEGACY_COMMAND, "fresh") assert "control character" in str(exc.value) + + +def test_wrong_shaped_intent_record_is_skipped_not_fatal(): + """A record whose ``intent`` is not a mapping must be skipped like any other + unreadable record, not turn the whole listing into an error.""" + store = FakeWorkflowStore() + council = _council(store) + good = _shell_intent("/bin/true", "good") + bad = _shell_intent("/bin/true", "bad") + for intent in (good, bad): + result = council.submit_intent(intent) + assert result.success and result.requires_approval, result.error + record = result.workflow.to_durable_dict() + if intent is bad: + record["intent"] = "not-a-mapping" + store.upsert_workflow( + intent.intent_id, + record, + state=WorkflowState.AWAITING_APPROVAL.value, + is_terminal=False, + expires_at=None, + ) + + replica = _council(store) + pending = replica.get_pending_approvals() + assert [wf.intent.intent_id for wf in pending] == [good.intent_id] diff --git a/tests/test_enforcer.py b/tests/test_enforcer.py index 901dc917..f3399f5a 100644 --- a/tests/test_enforcer.py +++ b/tests/test_enforcer.py @@ -1178,6 +1178,23 @@ async def test_backtick_blocked(self, kp, mock_nonce_store): assert result.success is False assert result.verification_stage == "blocked_pattern" + @pytest.mark.asyncio + async def test_nul_blocked_before_packaged_files_unpack(self, kp, mock_nonce_store, tmp_path): + """NUL is refused at the blocked_pattern stage, before any packaged + file is written to the working directory.""" + config = ExecutorConfig(allowed_working_directories=[str(tmp_path)]) + enforcer = WritEnforcer( + public_key=kp.public_key, nonce_store=mock_nonce_store, config=config + ) + writ = _make_signed_writ( + kp, command="/bin/echo safe\x00/bin/echo hidden", working_directory=str(tmp_path) + ) + result = await enforcer.execute_writ(_serialize(writ)) + assert result.success is False + assert result.verification_stage == "blocked_pattern" + assert "NUL" in result.error + assert list(tmp_path.iterdir()) == [] + @pytest.mark.asyncio async def test_newline_blocked(self, kp, mock_nonce_store): enforcer = self._enforcer(kp, mock_nonce_store, allowed_tools=["echo"]) diff --git a/tests/test_policy_shell.py b/tests/test_policy_shell.py index 59e4569c..ce14a41c 100644 --- a/tests/test_policy_shell.py +++ b/tests/test_policy_shell.py @@ -1,12 +1,5 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: LicenseRef-NvidiaProprietary -# -# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual -# property and proprietary rights in and to this material, related -# documentation and any modifications thereto. Any use, reproduction, -# disclosure or distribution of this material and related documentation -# without an express license agreement from NVIDIA CORPORATION or -# its affiliates is strictly prohibited. +# SPDX-License-Identifier: Apache-2.0 """Tests for the council-side shell command policy helpers."""