From 58972998a76e9767dbc5c5d7b426a50e73d733c5 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Mon, 16 Nov 2026 21:35:27 -0800 Subject: [PATCH 01/15] feat(opa): classify structured tool policy and human review --- .github/workflows/ci.yml | 12 +- .../nomos/files/policies/intent_filter.rego | 103 +++++- docs/guides/structured-tool-policy.md | 170 ++++++++++ docs/index.md | 1 + nomos/config/settings.py | 26 +- nomos/nat/functions.py | 93 +++++- nomos/opa/client.py | 25 +- nomos/opa/shell_analysis.py | 90 +++++ policies/intent_filter.rego | 103 +++++- tests/test_opa_tool_policy.py | 313 ++++++++++++++++++ 10 files changed, 920 insertions(+), 16 deletions(-) create mode 100644 docs/guides/structured-tool-policy.md create mode 100644 nomos/opa/shell_analysis.py create mode 100644 tests/test_opa_tool_policy.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6bf132e3..945e1bb1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -175,7 +175,7 @@ jobs: - name: Prepare container run: | apt-get update - apt-get install -y --no-install-recommends git nodejs + apt-get install -y --no-install-recommends git nodejs curl rm -rf /var/lib/apt/lists/* - name: Checkout @@ -202,6 +202,16 @@ jobs: python -m pip install --upgrade "pip @ https://files.pythonhosted.org/packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl#sha256=931c303696af6fa3417112103b1cad26890e5a07eccb5b99783700e33f2b8aad" uv sync --frozen --extra all + - name: Install pinned OPA for structured policy integration tests + run: | + curl --fail --location --silent --show-error \ + https://github.com/open-policy-agent/opa/releases/download/v1.17.0/opa_linux_amd64_static \ + --output "$RUNNER_TEMP/opa" + printf '%s %s\n' e83da46804832578e9d9e1733dffbe4d3b5f8cc9c26eb124da9ceea4abfe189f "$RUNNER_TEMP/opa" | sha256sum --check + chmod +x "$RUNNER_TEMP/opa" + printf 'NOMOS_TEST_OPA_BINARY=%s\n' "$RUNNER_TEMP/opa" >> "$GITHUB_ENV" + "$RUNNER_TEMP/opa" test policies + - name: Run local tests with coverage run: | mkdir -p reports/junit diff --git a/deploy/kubernetes/nomos/files/policies/intent_filter.rego b/deploy/kubernetes/nomos/files/policies/intent_filter.rego index b286afa1..08e04c6d 100644 --- a/deploy/kubernetes/nomos/files/policies/intent_filter.rego +++ b/deploy/kubernetes/nomos/files/policies/intent_filter.rego @@ -7,10 +7,14 @@ import rego.v1 default allow := false -allow if count(deny) == 0 +allow if { + count(deny) == 0 + count(human_review) == 0 +} decision := { "allow": allow, + "policy_decision": policy_decision, "reasons": reasons, "guidance": guidance, "metadata": { @@ -20,7 +24,7 @@ decision := { }, } -reasons := [reason | deny[reason]] +reasons := array.concat([reason | deny[reason]], [reason | human_review[reason]]) guidance := [item | remediation[item]] @@ -49,6 +53,7 @@ valid_policy_ids := { "strict-shell", "git-workflow-local", "read-only-relaxed", + "local-bash", } default_git_workflow_words := { @@ -236,3 +241,97 @@ remediation contains "Use a public interface for keys/secrets or narrow the targ some ref in object.get(input.intent, "normalized_path_refs", []) sensitive_path_match(ref, path) } + +# Hard denial wins over any request for human review. Human approval does not +# override a forbidden operation; policy inspection on replay evaluates again. +policy_decision := "forbidden" if count(deny) > 0 + +else := "requires_human_approval" if count(human_review) > 0 + +else := "allow" + +local_shell_analysis := input.intent.shell_analysis if policy_id == "local-bash" + +deny contains "Recursive forced deletion is forbidden." if { + some command in local_shell_analysis.commands + command.name == "rm" + rm_recursive(command.argv) + rm_force(command.argv) +} + +rm_recursive(argv) if { + some arg in option_arguments(argv) + arg == "--recursive" +} + +rm_recursive(argv) if { + some arg in option_arguments(argv) + regex.match(`^-[^-]*[rR]`, arg) +} + +rm_force(argv) if { + "--force" in option_arguments(argv) +} + +rm_force(argv) if { + some arg in option_arguments(argv) + regex.match(`^-[^-]*f`, arg) +} + +deny contains "Privilege escalation with sudo is forbidden." if { + some command in local_shell_analysis.commands + command.name == "sudo" +} + +deny contains "Login-shell user switching is forbidden." if { + some command in local_shell_analysis.commands + command.name == "su" + some arg in command.argv + login_su_option(arg) +} + +deny contains "World-writable executable permissions are forbidden." if { + some command in local_shell_analysis.commands + command.name == "chmod" + mode := [arg | some i, arg in command.argv; not startswith(arg, "-"); not earlier_positional(command.argv, i)] + count(mode) > 0 + mode[0] in {"777", "0777"} +} + +human_review contains "This command requires human interpretation before host execution." if { + local_shell_analysis.supported == false +} + +human_review contains "Deletion requires human approval." if { + some command in local_shell_analysis.commands + command.name == "rm" +} + +human_review contains "User switching requires human approval." if { + some command in local_shell_analysis.commands + command.name == "su" +} + +# Option parsing stops at --. Preserve option order and do not interpret a +# filename such as -rf after that delimiter as a destructive option. +option_arguments(argv) := [arg | + some i, arg in argv + arg != "--" + not option_terminated(argv, i) +] + +option_terminated(argv, i) if { + some j, value in argv + j < i + value == "--" +} + +earlier_positional(argv, i) if { + some j, value in argv + j < i + not startswith(value, "-") +} + +login_su_option(arg) if arg in {"-", "--login"} + +login_su_option(arg) if regex.match(`^-[^-]*l`, arg) diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md new file mode 100644 index 00000000..c5c43b47 --- /dev/null +++ b/docs/guides/structured-tool-policy.md @@ -0,0 +1,170 @@ + + +# Structured tool policy and human approval + +Nomos can evaluate the actual arguments of an application tool before model +review. This lets an operator distinguish a forbidden action from an action +that needs a person's approval. A human approval never overrides a forbidden +policy decision. + +## What OPA receives + +For a structured `tool_call`, OPA receives the validated, bounded argument +snapshot as `input.intent.tool_arguments`. The existing +`input.intent.operation` still contains the exact tool name, subject and SHA-256 +argument digest. The digest binds the reviewed arguments to the signed writ; +it cannot tell a policy what those arguments mean. + +For example: + +```json +{ + "intent": { + "operation": { + "kind": "tool_call", + "tool_name": "shell.run", + "subject": "user-123", + "arguments_sha256": "" + }, + "tool_arguments": {"command": "rm -rf output"} + } +} +``` + +The actual arguments are available for **all structured calls**, independently +of the selected profile or an operator tool catalog. They remain untrusted +request content: presence is not schema validation against a trusted tool +definition, and arguments cannot supply policy configuration. Shell requests +retain their existing input shape. + +Raw arguments are held only for the current review and are not added to the +durable Intent or signed operation. Sending them to OPA expands the data OPA +can see, however. Protect its transport, access controls and decision logs; +Nomos does not guarantee that an independently configured OPA server will not +log its input. Keep sensitive argument values out of custom policy reasons and +guidance too: those messages can be returned to clients and included in the +existing review audit. + +## Opt in to the local Bash profile + +Existing profiles keep their existing rules. Enable this profile explicitly +and bind each exact tool name to the argument containing its command: + +```yaml +opa: + enabled: true + policy_id: local-bash + shell_tool_arguments: + shell.run: command +``` + +An empty binding map is rejected for this profile. Unbound tools continue +through ordinary policy and Council review; the profile does not infer a tool's +meaning from its name or description. The application must still enforce its +own tool allowlist, user consent, folder grants and filesystem confinement. + +The server derives `input.intent.shell_analysis` from the held command. The +bundled Rego policy consumes these facts, rather than trusting model-provided +command classifications. + +| Recognized command | Policy result | +| --- | --- | +| Recursive forced `rm`, including `-rf`, `-fr`, `-r -f` and long options | Forbidden | +| `sudo` | Forbidden | +| Login `su`, including `-`, `-l`, combined `-lc`, and `--login` | Forbidden | +| `chmod` setting numeric mode `777` or `0777` | Forbidden | +| Other `rm` or `su` | Human approval required | +| Unsupported or opaque shell syntax | Human approval required | +| Other recognized literal commands | Continue to Council review | + +This is a conservative **static grammar**, not a Bash interpreter or a sandbox. +It recognizes one simple command with literal arguments and a bounded set of +standard command names. Expansion, globbing, composition, redirection, +interpreters, unfamiliar executables and malformed input require human review. +Some harmless quoted metacharacters consequently require review too. + +Hard-deny rules take precedence over human-review rules for recognized +commands. A proven literal executable/option prefix is retained for denial +only: `rm -rf *` and `rm -rf "$TARGET"` are forbidden even though their targets +need expansion. This prefix is never sufficient to allow a command. An opaque script can contain operations the static grammar does not +recognize; human approval accepts responsibility for that opaque operation. +The profile does not promise to prove every possible Bash effect safe or to +detect a prohibited operation hidden in an arbitrary program. Runtime isolation +and host environment integrity, including inherited shell functions, remain +separate controls. + +## Three policy decisions + +OPA may return an explicit `policy_decision` alongside its existing boolean +`allow`. Contradictory pairs are rejected: + +| `policy_decision` | `allow` | Meaning | +| --- | --- | --- | +| `allow` | `true` | Continue through normal model review; not permission to execute yet. | +| `forbidden` | `false` | Block; a person cannot override this policy through the approval replay path. | +| `requires_human_approval` | `false` | Stop before execution and let the application obtain approval. | + +Normal authorization keeps the existing `status: denied` for both forbidden +and human-required results and adds the typed `policy_decision` field. Older +clients remain closed. Applications must inspect the field, not parse guidance +or error text to decide whether to show an approval card. Neither an outage nor +an undefined decision means that human approval is required. + +## Recheck policy after approval + +An application with its own approval interface can recheck current policy +without repeating model review. Here `council.authorize` represents an +application-owned client wrapper that calls the `council_authorize` MCP tool; +it is not a new Nomos Python SDK method: + +```python +result = await council.authorize( + api_version="v2", + council_id="operations", + agent_id="example-application", + auth_token=agent_token, + tool_call=exact_tool_call, + policy_only=True, +) +``` + +This is an inspection request, not proof that a person approved anything. It +authenticates and checks permissions as usual, evaluates OPA and stops before +Council review or writ minting. A successful inspection returns +`status: policy_allowed`, `policy_decision: allow`, and no writ. A human-required +inspection returns `status: denied` and `policy_decision: +requires_human_approval`; a forbidden inspection retains `status: denied` and +returns `policy_decision: forbidden` instead. + +An integrating worker may continue only after independently verifying an +application-owned approval bound to the exact final operation, and only when +current policy allows it or requires that human approval. It must still block +forbidden actions, missing or invalid approvals, and unavailable policy. +An inspection response by itself must never authorize a tool effect. + +Policy-only requests require enabled, healthy OPA even when ordinary +authorization is configured to fail open. They never mint a writ and are +recorded as policy inspection in the existing consolidated review ledger, +including installations using the legacy review-audit mode. The opt-in +`local-bash` profile likewise records its pre-review denials and human-review +requirements in both audit modes, with `request_type: authorize` for ordinary +authorization requests. These records contain the privacy-minimized operation, +policy outcome and reason, not fabricated Council votes or authorization. + +## Validation + +Run the Python contracts and the actual Rego engine together: + +```sh +NOMOS_TEST_OPA_BINARY=/path/to/opa python -m pytest \ + tests/test_opa_tool_policy.py tests/test_opa_client.py \ + tests/test_opa_nat_integration.py +opa test policies/intent_filter.rego policies/intent_filter_test.rego +``` + +Without `NOMOS_TEST_OPA_BINARY`, Python tests requiring the external Rego engine +are explicitly skipped. The bundled policy and its Kubernetes chart copy must +remain identical. diff --git a/docs/index.md b/docs/index.md index c62027f7..72741add 100644 --- a/docs/index.md +++ b/docs/index.md @@ -53,6 +53,7 @@ signed receipt. Start with the [README](../README.md) for the one-page overview. |---|---| | [MCP tools and executor API](reference/mcp-api.md) | The council's MCP tools, structured `tool_call` requests, the trusted executor HTTP contract | | [Configuration](reference/configuration.md) | `configs/council.yaml`, executor YAML, executor profiles, risk-based Writ lifetimes | +| [Structured tool policy](guides/structured-tool-policy.md) | Actual tool arguments in OPA, explicit forbidden versus human-required decisions, policy-only inspection | | [Council protocol skill](../skills/council-protocol/SKILL.md) | Loadable instructions for agents that write council requests | | [Development](development.md) | Repository layout, tests, the in-process kernel example | diff --git a/nomos/config/settings.py b/nomos/config/settings.py index 796f13ff..649ad763 100644 --- a/nomos/config/settings.py +++ b/nomos/config/settings.py @@ -618,7 +618,8 @@ class OPAConfig(BaseModel): description=( "Named bundled OPA policy profile. strict-shell requires absolute " "executables; git-workflow-local and read-only-relaxed may permit " - "configured bare command words under configured working directories." + "configured bare command words under configured working directories. " + "local-bash classifies explicitly bound structured shell tools." ), ) relaxed_bare_command_words: list[str] = Field( @@ -636,6 +637,29 @@ class OPAConfig(BaseModel): ), ) + shell_tool_arguments: dict[str, str] = Field( + default_factory=dict, + description=( + "Exact structured tool names mapped to their command argument key. " + "Used only by the opt-in local-bash policy; empty preserves existing behavior." + ), + ) + + @field_validator("shell_tool_arguments") + @classmethod + def validate_shell_tool_arguments(cls, value: dict[str, str]) -> dict[str, str]: + """Reject empty bindings instead of silently leaving a guarded tool unclassified.""" + if any(not key.strip() or not argument.strip() for key, argument in value.items()): + raise ValueError("OPA shell tool names and command argument keys must not be empty") + return value + + @model_validator(mode="after") + def require_local_bash_binding(self) -> "OPAConfig": + """Make activation of the shell profile explicit and nonempty.""" + if self.policy_id == "local-bash" and not self.shell_tool_arguments: + raise ValueError("local-bash requires at least one shell_tool_arguments binding") + return self + @field_validator("enabled", "fail_closed", mode="before") @classmethod def resolve_bool_env_vars(cls, value: Any, info) -> Any: diff --git a/nomos/nat/functions.py b/nomos/nat/functions.py index 230f97a8..410977c6 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -19,7 +19,7 @@ from collections.abc import Awaitable, Callable from dataclasses import dataclass from pathlib import Path -from typing import Any, ClassVar, TypeVar +from typing import Any, ClassVar, Literal, TypeVar from pydantic import ( BaseModel, @@ -512,6 +512,14 @@ class AuthorizeInput(DuplicateSafeJsonModel): "Council to petition. Optional on v1 compatibility tools; required on v2 tools." ), ) + policy_only: bool = Field( + default=False, + strict=True, + description=( + "Evaluate authenticated policy only, without model review or a writ. " + "A policy_allowed result is not execution authorization." + ), + ) command: str = Field(default="", description="Exact shell command to authorize") working_directory: str = Field( default="", description="Directory where a shell command will run" @@ -589,7 +597,14 @@ class AuthorizeOutput(_LoadSheddingOutput): api_version: str = API_VERSION_V1 council_id: str = "" - status: str = Field(default="denied", description="'approved', 'denied', or 'error'") + status: str = Field( + default="denied", + description="'approved', 'denied', 'error', or inspection-only 'policy_allowed'", + ) + policy_decision: Literal["allow", "forbidden", "requires_human_approval"] | None = Field( + default=None, + description="Explicit policy outcome, when available; never inferred from error text.", + ) writ: str | None = Field( default=None, description="Base64-encoded writ blob (only if approved)" ) @@ -1209,13 +1224,13 @@ async def _evaluate_opa_filter( "Retry after OPA is healthy, or disable OPA fail-closed only through " "deployment configuration if that is intentional.", ], - metadata={"fail_closed": True}, + metadata={"fail_closed": True, "evaluation_error": True}, ) logger.warning("OPA evaluation failed; allowing due to fail_open config: %s", exc) return OPAPolicyDecision( allow=True, reasons=[f"OPA unavailable; fail-open allowed by deployment config: {exc}"], - metadata={"fail_closed": False}, + metadata={"fail_closed": False, "evaluation_error": True}, ) @staticmethod @@ -1961,8 +1976,15 @@ def _record_consolidated_review( debate_history: list[DebateRound] | None = None, denial_reason: str = "", timing: dict[str, Any] | None = None, + force_record: bool = False, ) -> None: - """Append the single Tier-1b consolidated review record (no-op in legacy mode). + """Append a consolidated review record; policy inspections are always recorded. + + Ordinary reviews remain no-ops in legacy audit mode. Policy inspection + creates no workflow/intermediate events, so it needs this record in both + audit modes and labels it explicitly rather than implying authorization. + The opt-in local-bash profile also records pre-review policy outcomes + without changing ordinary legacy-profile audit behavior. Called exactly once per accepted intent that reaches a final outcome. The intermediate review entries were suppressed in the council/quorum (gated by @@ -1970,7 +1992,11 @@ def _record_consolidated_review( for the review. Failures propagate like the legacy DECISION_MADE append — this record is the authoritative audit trail, not a best-effort cache. """ - if not self._council.config.consolidated_review_audit: + if ( + not self._council.config.consolidated_review_audit + and request_type != "policy_only" + and not force_record + ): return def _dump(obj: Any) -> dict[str, Any] | None: @@ -1986,6 +2012,10 @@ def _dump(obj: Any) -> dict[str, Any] | None: "reason": "; ".join(getattr(opa_decision, "reasons", []) or []), } + explicit_policy_decision = getattr(opa_decision, "policy_decision", None) + if explicit_policy_decision is not None: + opa_block["policy_decision"] = explicit_policy_decision + policy_evaluation: dict[str, Any] = {} quorum: dict[str, Any] = {} approved_at = denied_at = None @@ -3209,20 +3239,41 @@ async def authorize( stage_start = time.perf_counter() opa_decision = await self._evaluate_opa_filter( intent, - request_type="authorize", + request_type="policy_only" if input_data.policy_only else "authorize", authenticated=agent_identity is not None, agent_permissions=agent_permissions, agent_councils=agent_councils, required_permissions={p.value for p in required_perms}, ) _stage(stages, tool, "opa", stage_start, intent_id=intent.intent_id) + if input_data.policy_only and ( + opa_decision is None + or opa_decision.metadata.get("evaluation_error") + or opa_decision.metadata.get("undefined") + ): + self._record_consolidated_review( + intent, + request_type="policy_only", + final_state="policy_error", + decision="error", + opa_decision=opa_decision, + denial_reason="Policy inspection requires an enabled, healthy OPA decision.", + ) + return AuthorizeOutput( + api_version=input_data.api_version, + council_id=effective_council_id, + status="error", + decision_id=intent.intent_id, + error="Policy inspection requires an enabled, healthy OPA decision.", + ) if opa_decision is not None and not opa_decision.allow: self._record_consolidated_review( intent, - request_type="authorize", + request_type="policy_only" if input_data.policy_only else "authorize", final_state=WorkflowState.DENIED.value, - decision="deny", + decision=opa_decision.policy_decision or "deny", opa_decision=opa_decision, + force_record=self._settings.opa.policy_id == "local-bash", denial_reason=self._opa_denial_error(opa_decision), ) _stage(stages, tool, "total", total_start, intent_id=intent.intent_id) @@ -3240,6 +3291,30 @@ async def authorize( decision_id=intent.intent_id, error=self._opa_denial_error(opa_decision), guidance=self._opa_denial_guidance(opa_decision), + policy_decision=( + None + if opa_decision.metadata.get("evaluation_error") + or opa_decision.metadata.get("undefined") + else opa_decision.policy_decision or "forbidden" + ), + ) + + if input_data.policy_only: + # No writ, model review, or execution authority: the application must + # separately validate its saved human approval and final operation. + self._record_consolidated_review( + intent, + request_type="policy_only", + final_state="policy_evaluated", + decision="policy_allowed", + opa_decision=opa_decision, + ) + return AuthorizeOutput( + api_version=input_data.api_version, + council_id=effective_council_id, + status="policy_allowed", + policy_decision="allow", + decision_id=intent.intent_id, ) stage_start = time.perf_counter() diff --git a/nomos/opa/client.py b/nomos/opa/client.py index fbc7e896..9c93b363 100644 --- a/nomos/opa/client.py +++ b/nomos/opa/client.py @@ -11,12 +11,13 @@ import urllib.request from collections.abc import Iterable, Mapping from dataclasses import dataclass, field -from typing import Any +from typing import Any, Literal from nomos.config.settings import OPAConfig from nomos.level_0.types import Intent from nomos.level_1.policy.paths import normalized_path_references from nomos.level_1.policy.shell import extract_shell_command_words +from nomos.opa.shell_analysis import analyze_shell_command class OPAEvaluationError(RuntimeError): @@ -32,6 +33,7 @@ class OPAPolicyDecision: guidance: list[str] = field(default_factory=list) decision_id: str = "" metadata: dict[str, Any] = field(default_factory=dict) + policy_decision: Literal["allow", "forbidden", "requires_human_approval"] | None = None class OPAHttpClient: @@ -84,6 +86,7 @@ def parse_opa_decision(payload: Mapping[str, Any]) -> OPAPolicyDecision: reasons=["OPA decision was undefined"], guidance=["Check that the configured OPA decision path returns a result object."], decision_id=decision_id, + metadata={"undefined": True}, ) if isinstance(result, bool): @@ -100,6 +103,13 @@ def parse_opa_decision(payload: Mapping[str, Any]) -> OPAPolicyDecision: if not isinstance(allow, bool): raise OPAEvaluationError("OPA result object must include boolean 'allow'") + policy_decision = result.get("policy_decision") + if policy_decision is not None: + if policy_decision not in ("allow", "forbidden", "requires_human_approval"): + raise OPAEvaluationError("OPA policy_decision is invalid") + if allow != (policy_decision == "allow"): + raise OPAEvaluationError("OPA allow contradicts policy_decision") + reasons = _string_list(result.get("reasons")) reason = result.get("reason") if isinstance(reason, str) and reason.strip(): @@ -118,6 +128,7 @@ def parse_opa_decision(payload: Mapping[str, Any]) -> OPAPolicyDecision: guidance=guidance, decision_id=decision_id, metadata=metadata, + policy_decision=policy_decision, ) @@ -134,6 +145,17 @@ def build_intent_filter_input( """Build the structured input document sent to OPA for intent filtering.""" if opa_config is None: opa_config = OPAConfig() + material = getattr(intent, "_tool_review_material", None) + tool_input: dict[str, Any] = {} + if material is not None and intent.operation is not None: + # Use the held, validated request, never a model description or digest lookup. + # Keep this live input out of Intent serialization and the signed operation. + tool_input["tool_arguments"] = json.loads(material.canonical_arguments()) + command_key = opa_config.shell_tool_arguments.get(material.tool_name) + if opa_config.policy_id == "local-bash" and command_key: + tool_input["shell_analysis"] = analyze_shell_command( + tool_input["tool_arguments"].get(command_key) + ) return { "request": { "type": request_type, @@ -154,6 +176,7 @@ def build_intent_filter_input( }, "required_permissions": sorted(set(required_permissions)), "intent": { + **tool_input, "intent_id": intent.intent_id, "agent_id": intent.agent_id, "council_id": intent.council_id, diff --git a/nomos/opa/shell_analysis.py b/nomos/opa/shell_analysis.py new file mode 100644 index 00000000..c6b556ef --- /dev/null +++ b/nomos/opa/shell_analysis.py @@ -0,0 +1,90 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Bounded static shell facts for policy, not a Bash interpreter or sandbox. + +Only one literal simple command is recognized for automated review. Expansion, +redirection, shell composition and opaque interpreters require human review +unless a proven literal prefix already establishes a hard prohibition. Shlex +tokenization alone cannot establish Bash semantics. The application must still +enforce its folder and execution boundary. +""" + +from __future__ import annotations + +import re +import shlex +from typing import Any + +# These executable identities identify policy categories, not safe operations. +# Council still reviews every ordinary command that passes this filter. +_COMMANDS = { + ":", + "true", + "false", + "printf", + "echo", + "pwd", + "ls", + "cat", + "mkdir", + "cp", + "mv", + "touch", + "head", + "tail", + "wc", + "cd", + "rm", + "sudo", + "su", + "chmod", +} +_UNSUPPORTED = re.compile(r"[$`\n\r\x00(){}<>|&;*?\[\]~]") + + +def analyze_shell_command(command: Any) -> dict[str, Any]: + """Return finite JSON facts, routing unrecognized syntax to human review. + + Quotes and backslash-escaped literal words are handled by POSIX shlex. + Metacharacters make the overall command unsupported even inside quotes. This can ask + for review of harmless literals; it cannot silently authorize expansion. + No filesystem lookup, command execution, environment expansion, or PATH + resolution occurs here. Inherited shell functions remain a host concern. + """ + unknown = { + "supported": False, + "commands": [], + "reason": "Command requires human interpretation.", + } + if not isinstance(command, str) or not command.strip() or len(command) > 16_384: + return unknown + try: + words = shlex.split(command, posix=True, comments=False) + except ValueError: + return unknown + if not words or len(words) > 4096: + return unknown + executable = words[0] + name = executable.rsplit("/", 1)[-1] + if name not in _COMMANDS: + return unknown + # Avoid treating assignments, relative scripts, or arbitrary executables + # that happen to have a familiar basename as a standard command. + if "/" in executable and executable not in (f"/bin/{name}", f"/usr/bin/{name}"): + return unknown + # Retain only a proven literal prefix for deny-only rules. For example, + # rm -rf "$TARGET" is opaque overall, but its executable and destructive + # options are already unambiguous. Stop before any expansion/separator; + # an earlier dynamic word might expand to -- and change option parsing. + literal_prefix = [] + for word in words[1:]: + if _UNSUPPORTED.search(word) or "#" in word: + break + literal_prefix.append(word) + supported = not _UNSUPPORTED.search(command) and "#" not in command + return { + "supported": bool(supported), + "commands": [{"name": name, "argv": words[1:] if supported else literal_prefix}], + "reason": "" if supported else unknown["reason"], + } diff --git a/policies/intent_filter.rego b/policies/intent_filter.rego index b286afa1..08e04c6d 100644 --- a/policies/intent_filter.rego +++ b/policies/intent_filter.rego @@ -7,10 +7,14 @@ import rego.v1 default allow := false -allow if count(deny) == 0 +allow if { + count(deny) == 0 + count(human_review) == 0 +} decision := { "allow": allow, + "policy_decision": policy_decision, "reasons": reasons, "guidance": guidance, "metadata": { @@ -20,7 +24,7 @@ decision := { }, } -reasons := [reason | deny[reason]] +reasons := array.concat([reason | deny[reason]], [reason | human_review[reason]]) guidance := [item | remediation[item]] @@ -49,6 +53,7 @@ valid_policy_ids := { "strict-shell", "git-workflow-local", "read-only-relaxed", + "local-bash", } default_git_workflow_words := { @@ -236,3 +241,97 @@ remediation contains "Use a public interface for keys/secrets or narrow the targ some ref in object.get(input.intent, "normalized_path_refs", []) sensitive_path_match(ref, path) } + +# Hard denial wins over any request for human review. Human approval does not +# override a forbidden operation; policy inspection on replay evaluates again. +policy_decision := "forbidden" if count(deny) > 0 + +else := "requires_human_approval" if count(human_review) > 0 + +else := "allow" + +local_shell_analysis := input.intent.shell_analysis if policy_id == "local-bash" + +deny contains "Recursive forced deletion is forbidden." if { + some command in local_shell_analysis.commands + command.name == "rm" + rm_recursive(command.argv) + rm_force(command.argv) +} + +rm_recursive(argv) if { + some arg in option_arguments(argv) + arg == "--recursive" +} + +rm_recursive(argv) if { + some arg in option_arguments(argv) + regex.match(`^-[^-]*[rR]`, arg) +} + +rm_force(argv) if { + "--force" in option_arguments(argv) +} + +rm_force(argv) if { + some arg in option_arguments(argv) + regex.match(`^-[^-]*f`, arg) +} + +deny contains "Privilege escalation with sudo is forbidden." if { + some command in local_shell_analysis.commands + command.name == "sudo" +} + +deny contains "Login-shell user switching is forbidden." if { + some command in local_shell_analysis.commands + command.name == "su" + some arg in command.argv + login_su_option(arg) +} + +deny contains "World-writable executable permissions are forbidden." if { + some command in local_shell_analysis.commands + command.name == "chmod" + mode := [arg | some i, arg in command.argv; not startswith(arg, "-"); not earlier_positional(command.argv, i)] + count(mode) > 0 + mode[0] in {"777", "0777"} +} + +human_review contains "This command requires human interpretation before host execution." if { + local_shell_analysis.supported == false +} + +human_review contains "Deletion requires human approval." if { + some command in local_shell_analysis.commands + command.name == "rm" +} + +human_review contains "User switching requires human approval." if { + some command in local_shell_analysis.commands + command.name == "su" +} + +# Option parsing stops at --. Preserve option order and do not interpret a +# filename such as -rf after that delimiter as a destructive option. +option_arguments(argv) := [arg | + some i, arg in argv + arg != "--" + not option_terminated(argv, i) +] + +option_terminated(argv, i) if { + some j, value in argv + j < i + value == "--" +} + +earlier_positional(argv, i) if { + some j, value in argv + j < i + not startswith(value, "-") +} + +login_su_option(arg) if arg in {"-", "--login"} + +login_su_option(arg) if regex.match(`^-[^-]*l`, arg) diff --git a/tests/test_opa_tool_policy.py b/tests/test_opa_tool_policy.py new file mode 100644 index 00000000..bedbbcd0 --- /dev/null +++ b/tests/test_opa_tool_policy.py @@ -0,0 +1,313 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Structured policy inputs and fail-closed, inspection-only authorization.""" + +import json +import os +import subprocess +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from nomos.config.settings import OPAConfig +from nomos.level_0.types import Intent, ToolCallRequest +from nomos.level_1.ledger.entry import LedgerEntryType +from nomos.nat.functions import AuthorizeInput +from nomos.opa import ( + OPAEvaluationError, + OPAPolicyDecision, + build_intent_filter_input, + parse_opa_decision, +) +from nomos.opa.shell_analysis import analyze_shell_command +from tests.test_opa_nat_integration import RecordingOPAClient, _make_service + + +@pytest.mark.parametrize( + "command", + [ + "echo hello", + "/bin/rm -rf directory", + "sudo id", + "su -lp root", + "chmod 777 file", + "rm -- -rf", + ], +) +def test_literal_command_analysis(command): + assert analyze_shell_command(command)["supported"] is True + + +@pytest.mark.parametrize( + "command", + [ + None, + "", + "echo 'unterminated", + "echo $(id)", + "echo `id`", + "echo hi; sudo id", + "cat file | head", + "rm *", + "bash -lc 'id'", + "python -c 'pass'", + "/tmp/echo hi", + "X=1 echo hi", + "echo hi > out", + "echo hi\nid", + "echo hi &", + "echo hi\x00", + "a" * 16385, + ], +) +def test_opaque_or_unsupported_commands_require_interpretation(command): + assert analyze_shell_command(command)["supported"] is False + + +def test_profile_binding_is_explicit_and_empty_profile_is_rejected(): + assert OPAConfig().shell_tool_arguments == {} + with pytest.raises(ValidationError): + OPAConfig(policy_id="local-bash") + with pytest.raises(ValidationError): + OPAConfig(shell_tool_arguments={"bash": ""}) + + +def test_actual_arguments_are_live_opa_input_and_do_not_change_durable_binding(): + material = ToolCallRequest( + tool_name="shell.run", + arguments={"command": "rm -rf dir", "nested": {"x": 1}}, + subject="user-1", + ) + intent = Intent.create( + agent_id="agent-1", + description="Run a local command", + target_resource="shell.run", + command_type="api", + operation=material.to_operation(), + ) + intent._tool_review_material = material + config = OPAConfig(policy_id="local-bash", shell_tool_arguments={"shell.run": "command"}) + result = build_intent_filter_input( + intent, request_type="authorize", authenticated=True, opa_config=config + ) + assert result["intent"]["tool_arguments"] == material.arguments + assert result["intent"]["shell_analysis"]["commands"] == [ + {"name": "rm", "argv": ["-rf", "dir"]} + ] + result["intent"]["tool_arguments"]["nested"]["x"] = 2 + assert material.arguments["nested"]["x"] == 1 + assert "arguments" not in intent.model_dump(mode="json")["operation"] + assert "tool_arguments" not in intent.model_dump(mode="json") + ordinary = build_intent_filter_input(intent, request_type="authorize", authenticated=True) + assert ordinary["intent"]["tool_arguments"] == material.arguments + assert "shell_analysis" not in ordinary["intent"] + + +@pytest.mark.parametrize( + ("allow", "decision"), + [(True, "forbidden"), (True, "requires_human_approval"), (False, "allow"), (False, "unknown")], +) +def test_contradictory_policy_decisions_fail_closed(allow, decision): + with pytest.raises(OPAEvaluationError): + parse_opa_decision({"result": {"allow": allow, "policy_decision": decision}}) + + +def _request(**kwargs): + return AuthorizeInput( + agent_id="agent-1", command="/bin/echo hello", working_directory="/tmp", **kwargs + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("decision", ["forbidden", "requires_human_approval"]) +@pytest.mark.parametrize("policy_only", [True, False]) +async def test_policy_blocks_before_models_and_never_mints_writ( + tmp_path, monkeypatch, decision, policy_only +): + service = _make_service(tmp_path) + service._opa_client = RecordingOPAClient( + OPAPolicyDecision(allow=False, policy_decision=decision, reasons=["Policy reason"]) + ) + + async def unexpected(*args, **kwargs): + pytest.fail("Model review must not run") + + monkeypatch.setattr(service, "_run_code_review", unexpected) + result = await service.authorize(_request(policy_only=policy_only)) + assert result.status == "denied" + assert result.policy_decision == decision + assert result.writ is None + assert service.council.get_workflow(result.decision_id) is None + + +@pytest.mark.asyncio +async def test_policy_only_allow_is_not_an_execution_authorization(tmp_path, monkeypatch): + service = _make_service(tmp_path) + service._opa_client = RecordingOPAClient(OPAPolicyDecision(allow=True)) + + async def unexpected(*args, **kwargs): + pytest.fail("Model review must not run") + + monkeypatch.setattr(service, "_run_code_review", unexpected) + result = await service.authorize(_request(policy_only=True)) + assert result.status == "policy_allowed" + assert result.policy_decision == "allow" + assert result.writ is None + assert service.council.get_workflow(result.decision_id) is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("condition", ["disabled", "undefined", "failure"]) +@pytest.mark.parametrize("fail_closed", [True, False]) +async def test_policy_only_never_accepts_disabled_undefined_or_unavailable_opa( + tmp_path, condition, fail_closed +): + service = _make_service(tmp_path, fail_closed=fail_closed) + if condition == "disabled": + service._opa_client = None + elif condition == "undefined": + service._opa_client = RecordingOPAClient(parse_opa_decision({})) + else: + service._opa_client = RecordingOPAClient(error=OPAEvaluationError("unavailable")) + result = await service.authorize(_request(policy_only=True)) + assert result.status == "error" + assert result.policy_decision is None + assert result.writ is None + + +def test_policy_only_requires_a_boolean(): + with pytest.raises(ValidationError): + _request(policy_only="false") + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("policy_only", "decision"), + [ + (True, "allow"), + (True, "forbidden"), + (True, "requires_human_approval"), + (False, "forbidden"), + (False, "requires_human_approval"), + ], +) +async def test_policy_outcomes_record_verdict_without_actual_arguments_in_legacy_audit_mode( + tmp_path, policy_only, decision +): + service = _make_service(tmp_path) + service.council.config.consolidated_review_audit = False + service._settings.opa = OPAConfig( + policy_id="local-bash", shell_tool_arguments={"shell.run": "command"} + ) + service._opa_client = RecordingOPAClient( + OPAPolicyDecision(allow=decision == "allow", policy_decision=decision) + ) + request = AuthorizeInput( + agent_id="agent-1", + council_id="opa-test-council", + policy_only=policy_only, + tool_call=ToolCallRequest( + tool_name="shell.run", + subject="user-1", + arguments={"command": "echo private-argument-marker"}, + ), + ) + result = await service.authorize(request) + assert result.writ is None + ledger = service.council.ledger + reviews = [ + entry + for i in range(ledger.length()) + if (entry := ledger.get(i)).entry_type == LedgerEntryType.INTENT_REVIEW_RECORDED + ] + assert len(reviews) == 1 + assert reviews[0].payload["request_type"] == ("policy_only" if policy_only else "authorize") + assert reviews[0].payload["opa"]["policy_decision"] == decision + assert reviews[0].payload["chairman"] == {} + assert reviews[0].payload["quorum"] == {} + assert "private-argument-marker" not in json.dumps(reviews[0].payload) + + +@pytest.mark.asyncio +async def test_normal_fail_closed_error_does_not_claim_a_policy_prohibition(tmp_path): + service = _make_service(tmp_path) + service._opa_client = RecordingOPAClient(error=OPAEvaluationError("unavailable")) + result = await service.authorize(_request()) + assert result.status == "denied" # Preserve the existing fail-closed API. + assert result.policy_decision is None + + +@pytest.mark.parametrize( + ("command", "expected"), + [ + ("echo hello", "allow"), + ("echo 'sudo rm -rf directory'", "allow"), + ("/bin/mkdir demo", "allow"), + ("rm -rf directory", "forbidden"), + ("/bin/rm -fr directory", "forbidden"), + ("rm -r -f directory", "forbidden"), + ("rm -rf *", "forbidden"), + ("rm -rf /tmp/*", "forbidden"), + ('rm -rf "$TARGET"', "forbidden"), + ('rm "$OPTIONS" -rf target', "requires_human_approval"), + ("echo 'rm -rf *'", "requires_human_approval"), + ("rm --recursive --force directory", "forbidden"), + ("rm -R --force directory", "forbidden"), + ("rm -- -rf", "requires_human_approval"), + ("rm file", "requires_human_approval"), + ("sudo id", "forbidden"), + ("/usr/bin/sudo id", "forbidden"), + ("su - root", "forbidden"), + ("su -lc id", "forbidden"), + ("su --login root", "forbidden"), + ("su root", "requires_human_approval"), + ("chmod 777 file", "forbidden"), + ("chmod -R 0777 directory", "forbidden"), + ("chmod 644 777", "allow"), + ("bash -lc 'rm -rf directory'", "requires_human_approval"), + ("rm *", "requires_human_approval"), + ("echo hi; sudo id", "requires_human_approval"), + ("echo $(id)", "requires_human_approval"), + ], +) +def test_real_opa_consumes_actual_command_analysis(command, expected): + binary = os.environ.get("NOMOS_TEST_OPA_BINARY") + if not binary: + pytest.skip("Set NOMOS_TEST_OPA_BINARY to run the actual Rego engine") + material = ToolCallRequest( + tool_name="shell.run", arguments={"command": command}, subject="user-1" + ) + intent = Intent.create( + agent_id="agent-1", + description="Run a local command", + target_resource="shell.run", + command_type="api", + operation=material.to_operation(), + ) + intent._tool_review_material = material + config = OPAConfig(policy_id="local-bash", shell_tool_arguments={"shell.run": "command"}) + document = build_intent_filter_input( + intent, request_type="authorize", authenticated=True, opa_config=config + ) + policy = Path(__file__).resolve().parents[1] / "policies" / "intent_filter.rego" + completed = subprocess.run( + [ + binary, + "eval", + "--format=json", + "--data", + str(policy), + "--stdin-input", + "data.nomos.intent.decision", + ], + input=json.dumps(document), + text=True, + capture_output=True, + check=True, + timeout=10, + ) + response = json.loads(completed.stdout)["result"][0]["expressions"][0]["value"] + assert response["policy_decision"] == expected + assert response["allow"] == (expected == "allow") From 396dc8b49f5e69c4ae6e4867ba591dc47d154fd9 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 09:49:15 -0800 Subject: [PATCH 02/15] docs(opa): distinguish structured and legacy shell input fields --- docs/guides/structured-tool-policy.md | 66 ++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index c5c43b47..178af77b 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -12,8 +12,10 @@ policy decision. ## What OPA receives -For a structured `tool_call`, OPA receives the validated, bounded argument -snapshot as `input.intent.tool_arguments`. The existing +Application-owned tools use structured authorization by default in the Relay +plugin's `local` execution path, including tools that run Bash. OPA receives +their validated, bounded argument snapshot as `input.intent.tool_arguments`. +The existing `input.intent.operation` still contains the exact tool name, subject and SHA-256 argument digest. The digest binds the reviewed arguments to the signed writ; it cannot tell a policy what those arguments mean. @@ -48,6 +50,66 @@ log its input. Keep sensitive argument values out of custom policy reasons and guidance too: those messages can be returned to clients and included in the existing review audit. +## Structured tools versus legacy shell authorization + +There is no separate `legacy = true` switch. In the Relay plugin, each tool's +`executor` selects both its execution route and its Nomos authorization format: + +| Relay tool setting | Authorization request sent to Nomos | Where an approved operation runs | +| --- | --- | --- | +| `executor = "local"` | `tool_call` with the exact tool name, business arguments and subject | The application's callback through the remaining Relay middleware. | +| `executor = "nomos_http"` | Top-level `command` and `working_directory`; no `tool_call` | The trusted Nomos Executor, using the signed shell writ. | + +Both paths begin with JSON tool arguments in Relay. Here, **structured** names +Nomos's `tool_call` authorization envelope; it does not mean the other path +receives unstructured Relay arguments. `local` means application-owned +execution, which may be on a workstation or server. Changing `executor` changes +where execution happens, not merely how the request is serialized. + +Unlisted guarded tools use `default_executor`, whose default is `local`. +There is one shipped explicit exception: omitting the `tools` configuration +retains the built-in `run_shell` entry with `executor = "nomos_http"`. +See the [Relay plugin configuration](../../integrations/nemo-relay/README.md). +Direct Council API clients select the format by supplying either `tool_call` +or the top-level shell fields. Combining a `tool_call` with nonempty shell +execution fields is rejected, rather than silently ignoring conflicting values. + +### OPA fields supplied by each path + +The following paths are inside `input.intent`. **Empty** fields are still +present in the input object; **omitted** fields are absent. OPA can evaluate +whatever a custom Rego policy references, so these are input-shaping and bundled +policy differences, not an OPA-wide list of ignored fields. + +| Field | Structured `local` tool | Legacy `nomos_http` shell request | +| --- | --- | --- | +| `command_type` | `"api"`, even when a tool argument contains Bash. | `"shell"`. | +| `operation` | Tool identity, subject and argument digest. The bundled rules do not use the digest to interpret the command; it binds the signed authorization. | `null`. | +| `tool_arguments` | Actual business arguments, including a nested `command` or `cwd` if the tool defines them. | Omitted. | +| `command` | Empty string. It is not populated from `tool_arguments.command`. | Exact shell command. | +| `working_directory` | Empty string. It is not populated from `tool_arguments.cwd`. | Requested shell working directory. | +| `shell_command_words` | Empty array. The bundled absolute-executable-path check does not inspect nested tool arguments. | Derived from the top-level command and used by the existing shell rules. | +| `shell_analysis` | Present only for an exactly bound tool under `opa.policy_id: local-bash`; derived from its configured command argument. | Omitted. The new `local-bash` command rules do not analyze this legacy path. | +| `normalized_path_refs` | Still derived from the top-level command, working directory and target resource. Paths inside `tool_arguments` are not automatically included. | Derived from the shell command, working directory and target resource for existing sensitive-path checks. | +| `packaged_files` | Empty array; structured authorization rejects packaged-file execution fields. | Contains packaged-file metadata when supplied. | + +Identity, permissions, selected policy, review context, justification and other +shared metadata remain available on both paths. For structured tools, existing +rules that inspect only `intent.command` (such as the remote-fetch-to-interpreter +check) see an empty command; they do not automatically inspect +`intent.tool_arguments.command`. Likewise, sensitive-path rules do not +automatically inspect every path argument of a tool. A policy must explicitly +use `tool_arguments` or the server-derived `shell_analysis` where appropriate. + +For example, a structured tool argument `{"command": "rm -rf output"}` keeps +`intent.command` empty. The new command rules inspect its derived +`intent.shell_analysis`, after the operator binds that exact tool as shown +below. Merely selecting a shell profile does not convert nested arguments into +the legacy shell fields. + +See the [OPA input builder](../../nomos/opa/client.py) and the +[bundled Rego rules](../../policies/intent_filter.rego) for the implementation. + ## Opt in to the local Bash profile Existing profiles keep their existing rules. Enable this profile explicitly From 9f979f7452d868c13d5206f0996af3f85b37e3ca Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 09:55:39 -0800 Subject: [PATCH 03/15] docs(opa): illustrate local and executor inputs with YAML --- docs/guides/structured-tool-policy.md | 153 +++++++++++++++++--------- 1 file changed, 98 insertions(+), 55 deletions(-) diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index 178af77b..e21fe5bb 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -10,61 +10,98 @@ review. This lets an operator distinguish a forbidden action from an action that needs a person's approval. A human approval never overrides a forbidden policy decision. -## What OPA receives - -Application-owned tools use structured authorization by default in the Relay -plugin's `local` execution path, including tools that run Bash. OPA receives -their validated, bounded argument snapshot as `input.intent.tool_arguments`. -The existing -`input.intent.operation` still contains the exact tool name, subject and SHA-256 -argument digest. The digest binds the reviewed arguments to the signed writ; -it cannot tell a policy what those arguments mean. - -For example: - -```json -{ - "intent": { - "operation": { - "kind": "tool_call", - "tool_name": "shell.run", - "subject": "user-123", - "arguments_sha256": "" - }, - "tool_arguments": {"command": "rm -rf output"} - } -} -``` - -The actual arguments are available for **all structured calls**, independently -of the selected profile or an operator tool catalog. They remain untrusted -request content: presence is not schema validation against a trusted tool -definition, and arguments cannot supply policy configuration. Shell requests -retain their existing input shape. + -Raw arguments are held only for the current review and are not added to the -durable Intent or signed operation. Sending them to OPA expands the data OPA -can see, however. Protect its transport, access controls and decision logs; -Nomos does not guarantee that an independently configured OPA server will not -log its input. Keep sensitive argument values out of custom policy reasons and -guidance too: those messages can be returned to clients and included in the -existing review audit. +## Two execution paths -## Structured tools versus legacy shell authorization - -There is no separate `legacy = true` switch. In the Relay plugin, each tool's -`executor` selects both its execution route and its Nomos authorization format: +Each Relay tool's `executor` selects where an approved operation runs and which +authorization format Nomos uses. There is no separate `legacy = true` switch. | Relay tool setting | Authorization request sent to Nomos | Where an approved operation runs | | --- | --- | --- | | `executor = "local"` | `tool_call` with the exact tool name, business arguments and subject | The application's callback through the remaining Relay middleware. | | `executor = "nomos_http"` | Top-level `command` and `working_directory`; no `tool_call` | The trusted Nomos Executor, using the signed shell writ. | -Both paths begin with JSON tool arguments in Relay. Here, **structured** names -Nomos's `tool_call` authorization envelope; it does not mean the other path -receives unstructured Relay arguments. `local` means application-owned -execution, which may be on a workstation or server. Changing `executor` changes -where execution happens, not merely how the request is serialized. +Both paths begin with JSON tool arguments in Relay. Here, **structured** means +Nomos's `tool_call` authorization format. `local` means the application's +callback, which may run on a workstation or server. + +## Example OPA inputs: the same command, two paths + +Both examples propose `/bin/echo hello` with working directory +`/workspace/project`. They show abbreviated OPA HTTP request bodies formatted +as YAML for readability; the wire format is JSON. Other identity, authentication +and review metadata is omitted. The outer `input` is OPA's HTTP wrapper: Rego +accesses the contents as `input.intent`, not `input.input.intent`. + +### `executor = "local"`: arguments stay inside the tool call + +This example uses `opa.policy_id: local-bash` with an explicit +`shell.run: command` binding. Nomos supplies the exact tool arguments and derives +shell facts for that bound command: + +```yaml +input: + council: + opa_policy_id: local-bash + intent: + command_type: api + command: "" + working_directory: "" + shell_command_words: [] + operation: + kind: tool_call + schema_version: 1 + tool_name: shell.run + subject: user-123 + arguments_sha256: "" + canonicalization: nomos-json-v1 + tool_arguments: + command: /bin/echo hello + cwd: /workspace/project + shell_analysis: + supported: true + commands: + - name: echo + argv: [hello] + reason: "" +``` + +The proposed command is in **`tool_arguments.command`**. The legacy +`intent.command` remains empty. The `local-bash` rules use `shell_analysis`; +older rules that inspect only `intent.command` do not inspect the nested command. +The argument digest binds the reviewed arguments to a signed writ; it does not +tell policy what the command means. + +### `executor = "nomos_http"`: command uses the legacy shell fields + +This example uses the existing `strict-shell` policy profile: + +```yaml +input: + council: + opa_policy_id: strict-shell + intent: + command_type: shell + command: /bin/echo hello + working_directory: /workspace/project + shell_command_words: [/bin/echo] + operation: null +``` + +Here, the command is in **`intent.command`**, which the existing shell rules +inspect. `tool_arguments` and `shell_analysis` are absent, not empty objects. +An approved shell writ goes to the trusted Nomos Executor. + +**Policy selection is separate from executor selection.** The examples use +different operator-configured profiles; setting `executor` does not select a +profile automatically. Structured calls always supply their arguments to OPA, +but `shell_analysis` is added only for a bound tool under `local-bash`. Selecting +`local-bash` does not make its new command rules analyze legacy `nomos_http` +requests. + +
+More detail: defaults and field-by-field reference Unlisted guarded tools use `default_executor`, whose default is `local`. There is one shipped explicit exception: omitting the `tools` configuration @@ -74,8 +111,6 @@ Direct Council API clients select the format by supplying either `tool_call` or the top-level shell fields. Combining a `tool_call` with nonempty shell execution fields is rejected, rather than silently ignoring conflicting values. -### OPA fields supplied by each path - The following paths are inside `input.intent`. **Empty** fields are still present in the input object; **omitted** fields are absent. OPA can evaluate whatever a custom Rego policy references, so these are input-shaping and bundled @@ -101,15 +136,23 @@ check) see an empty command; they do not automatically inspect automatically inspect every path argument of a tool. A policy must explicitly use `tool_arguments` or the server-derived `shell_analysis` where appropriate. -For example, a structured tool argument `{"command": "rm -rf output"}` keeps -`intent.command` empty. The new command rules inspect its derived -`intent.shell_analysis`, after the operator binds that exact tool as shown -below. Merely selecting a shell profile does not convert nested arguments into -the legacy shell fields. - See the [OPA input builder](../../nomos/opa/client.py) and the [bundled Rego rules](../../policies/intent_filter.rego) for the implementation. +
+ +### Argument privacy + +Actual tool arguments remain untrusted request content, not trusted tool +definitions or policy configuration. They are available to OPA independently +of any operator tool catalog. Raw arguments are held for the current review +and are not added to the durable Intent or signed operation. + +OPA can now see those arguments, so protect its transport, access and decision +logs. Nomos does not control an independently configured OPA server's logging. +Keep sensitive values out of custom policy reasons and guidance too: those +messages can reach clients and the review audit. + ## Opt in to the local Bash profile Existing profiles keep their existing rules. Enable this profile explicitly From be9e0ccfba26c11575239ae1ba9bbcd580ef06e6 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 09:58:11 -0800 Subject: [PATCH 04/15] docs(opa): show executor settings in Relay plugins.toml --- docs/guides/structured-tool-policy.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index e21fe5bb..ce56c744 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -22,6 +22,24 @@ authorization format Nomos uses. There is no separate `legacy = true` switch. | `executor = "local"` | `tool_call` with the exact tool name, business arguments and subject | The application's callback through the remaining Relay middleware. | | `executor = "nomos_http"` | Top-level `command` and `working_directory`; no `tool_call` | The trusted Nomos Executor, using the signed shell writ. | +Set this in **Relay's `plugins.toml`**, inside the Nomos plugin's existing +`[[plugins.dynamic]]` entry: + +```toml +# Explicit execution route for this exact tool. +[plugins.dynamic.config.tools."shell.run"] +executor = "local" + +# Default for guarded tools without an explicit per-tool entry. +[plugins.dynamic.config] +default_executor = "local" +``` + +`local` is already the default for unlisted guarded tools. Explicit per-tool +entries take precedence, including the shipped `run_shell` entry that uses +`nomos_http` when the `tools` configuration is omitted. These are Relay plugin +settings; the Council's OPA profile is configured separately in YAML below. + Both paths begin with JSON tool arguments in Relay. Here, **structured** means Nomos's `tool_call` authorization format. `local` means the application's callback, which may run on a workstation or server. From 3ceed1158e0b86e34ff30851936e4edfa4db4408 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 10:14:41 -0800 Subject: [PATCH 05/15] docs(opa): explain operation binding and sibling review arguments --- docs/guides/structured-tool-policy.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index ce56c744..f726c481 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -91,6 +91,22 @@ older rules that inspect only `intent.command` do not inspect the nested command The argument digest binds the reviewed arguments to a signed writ; it does not tell policy what the command means. +**Why is `tool_arguments` beside `operation`, rather than inside it?** +[`ToolCallOperation`](../../nomos/level_0/types/tool_call.py) is the compact +operation record persisted in the Intent and bound into the signed writ, +introduced by [PR #112](https://github.com/NVIDIA/Nomos/pull/112). It carries the +argument digest rather than the raw arguments. Adding raw arguments inside +that record would require changing its schema and reviewing the persistence, +privacy and signing implications. The sibling `intent.tool_arguments` field +gives OPA the actual arguments during review while preserving that contract. +Both come from the same validated request; the digest is calculated from those +exact arguments, not supplied independently by the model. + +`operation.kind` identifies the operation type. Its only currently supported +value is `"tool_call"`; legacy shell requests use `operation: null`, not +`kind: shell`. The kind does not identify the tool or its executor: `tool_name` +names the tool, and the Relay configuration selects its execution route. + ### `executor = "nomos_http"`: command uses the legacy shell fields This example uses the existing `strict-shell` policy profile: From 2810762e4fa447b9608616d13cc1a9fea2b79681 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 10:17:32 -0800 Subject: [PATCH 06/15] docs(opa): simplify execution and input comparison tables --- docs/guides/structured-tool-policy.md | 64 ++++++++++++++++----------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index f726c481..bfc14b80 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -17,10 +17,10 @@ policy decision. Each Relay tool's `executor` selects where an approved operation runs and which authorization format Nomos uses. There is no separate `legacy = true` switch. -| Relay tool setting | Authorization request sent to Nomos | Where an approved operation runs | +| Question | `executor = "local"` | `executor = "nomos_http"` | | --- | --- | --- | -| `executor = "local"` | `tool_call` with the exact tool name, business arguments and subject | The application's callback through the remaining Relay middleware. | -| `executor = "nomos_http"` | Top-level `command` and `working_directory`; no `tool_call` | The trusted Nomos Executor, using the signed shell writ. | +| Who executes after approval? | The application, through Relay's callback. | The trusted Nomos Executor service. | +| What does Nomos authorize? | A named tool with its exact JSON arguments (`tool_call`). | A shell command with its working directory. | Set this in **Relay's `plugins.toml`**, inside the Nomos plugin's existing `[[plugins.dynamic]]` entry: @@ -145,30 +145,44 @@ Direct Council API clients select the format by supplying either `tool_call` or the top-level shell fields. Combining a `tool_call` with nonempty shell execution fields is rejected, rather than silently ignoring conflicting values. -The following paths are inside `input.intent`. **Empty** fields are still -present in the input object; **omitted** fields are absent. OPA can evaluate -whatever a custom Rego policy references, so these are input-shaping and bundled -policy differences, not an OPA-wide list of ignored fields. +The table below compares the **two YAML examples above**, both proposing +`/bin/echo hello`. All field paths start inside `input.intent`. +**Not present** means the key is absent; `""`, `[]` and `null` are actual values +sent to OPA. -| Field | Structured `local` tool | Legacy `nomos_http` shell request | +| Field inside `input.intent` | `local` example | `nomos_http` example | | --- | --- | --- | -| `command_type` | `"api"`, even when a tool argument contains Bash. | `"shell"`. | -| `operation` | Tool identity, subject and argument digest. The bundled rules do not use the digest to interpret the command; it binds the signed authorization. | `null`. | -| `tool_arguments` | Actual business arguments, including a nested `command` or `cwd` if the tool defines them. | Omitted. | -| `command` | Empty string. It is not populated from `tool_arguments.command`. | Exact shell command. | -| `working_directory` | Empty string. It is not populated from `tool_arguments.cwd`. | Requested shell working directory. | -| `shell_command_words` | Empty array. The bundled absolute-executable-path check does not inspect nested tool arguments. | Derived from the top-level command and used by the existing shell rules. | -| `shell_analysis` | Present only for an exactly bound tool under `opa.policy_id: local-bash`; derived from its configured command argument. | Omitted. The new `local-bash` command rules do not analyze this legacy path. | -| `normalized_path_refs` | Still derived from the top-level command, working directory and target resource. Paths inside `tool_arguments` are not automatically included. | Derived from the shell command, working directory and target resource for existing sensitive-path checks. | -| `packaged_files` | Empty array; structured authorization rejects packaged-file execution fields. | Contains packaged-file metadata when supplied. | - -Identity, permissions, selected policy, review context, justification and other -shared metadata remain available on both paths. For structured tools, existing -rules that inspect only `intent.command` (such as the remote-fetch-to-interpreter -check) see an empty command; they do not automatically inspect -`intent.tool_arguments.command`. Likewise, sensitive-path rules do not -automatically inspect every path argument of a tool. A policy must explicitly -use `tool_arguments` or the server-derived `shell_analysis` where appropriate. +| `command_type` | `"api"` | `"shell"` | +| `tool_arguments.command` | `"/bin/echo hello"` | Not present | +| `tool_arguments.cwd` | `"/workspace/project"` | Not present | +| `command` | `""` | `"/bin/echo hello"` | +| `working_directory` | `""` | `"/workspace/project"` | +| `operation` | Tool-call binding object shown above | `null` | +| `shell_command_words` | `[]` | `["/bin/echo"]` | +| `shell_analysis` | Derived command facts shown above | Not present | + +The important difference is **where the command and working directory live**. +For `local`, read them from `tool_arguments`; for `nomos_http`, read the +top-level shell fields. The `cwd` argument is specific to this example tool; +other tools can define different arguments. + +**What this means for policy:** OPA does not automatically ignore or translate +fields. Each Rego rule reads the fields it names: + +- Existing shell rules, such as absolute-executable-path and + remote-fetch-to-interpreter checks, use the top-level shell fields. They do + not automatically inspect the command inside `tool_arguments`. +- The new `local-bash` command rules use `shell_analysis`, which is supplied + only for an exactly bound structured tool under that profile. +- Existing sensitive-path checks use `normalized_path_refs`, derived from the + top-level command, working directory and target resource. Paths nested inside + tool arguments are not automatically included. + +Identity, permissions, review context, justification and other shared metadata +remain available on both paths. Both examples have `packaged_files: []` (not +shown in the YAML excerpts); legacy shell requests may also supply packaged-file +metadata, whereas structured authorization rejects packaged-file execution +fields. See the [OPA input builder](../../nomos/opa/client.py) and the [bundled Rego rules](../../policies/intent_filter.rego) for the implementation. From 7b81a6346ae8872df57ca4c13e54d95af492a3fe Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 13:04:05 -0800 Subject: [PATCH 07/15] feat(opa): configure denials without executable allowlists --- .../nomos/files/policies/intent_filter.rego | 28 +++ docs/guides/structured-tool-policy.md | 88 +++++++-- nomos/config/settings.py | 27 +++ nomos/opa/client.py | 3 + nomos/opa/shell_analysis.py | 161 +++++++++++----- policies/intent_filter.rego | 28 +++ tests/test_configured_shell_denials.py | 126 ++++++++++++ tests/test_opa_client.py | 2 + tests/test_opa_nat_integration.py | 1 + tests/test_opa_tool_policy.py | 80 +++++++- tests/test_shell_analysis.py | 180 ++++++++++++++++++ 11 files changed, 650 insertions(+), 74 deletions(-) create mode 100644 tests/test_configured_shell_denials.py create mode 100644 tests/test_shell_analysis.py diff --git a/deploy/kubernetes/nomos/files/policies/intent_filter.rego b/deploy/kubernetes/nomos/files/policies/intent_filter.rego index 08e04c6d..7ea3f3a7 100644 --- a/deploy/kubernetes/nomos/files/policies/intent_filter.rego +++ b/deploy/kubernetes/nomos/files/policies/intent_filter.rego @@ -252,6 +252,13 @@ else := "allow" local_shell_analysis := input.intent.shell_analysis if policy_id == "local-bash" +# Deployment-owned prohibitions are evaluated before automated or human review. +# Matching uses the parsed basename even when the executable has a custom path. +deny contains sprintf("Command %q is forbidden by the configured shell policy.", [command.name]) if { + some command in local_shell_analysis.commands + command.name in object.get(input.council, "opa_denied_shell_commands", []) +} + deny contains "Recursive forced deletion is forbidden." if { some command in local_shell_analysis.commands command.name == "rm" @@ -312,6 +319,27 @@ human_review contains "User switching requires human approval." if { command.name == "su" } +# These selected wrappers can dispatch or evaluate another command. Parsing +# their outer argv does not describe that nested operation. This review list +# is not an exhaustive classifier of arbitrary program effects. +human_review contains "Command dispatch or evaluation requires human approval." if { + some command in local_shell_analysis.commands + command.name in {"exec", "command", "builtin", "env", "nohup", "time", "source", ".", "eval"} +} + +human_review contains "Inline shell code requires human approval." if { + some command in local_shell_analysis.commands + command.name in {"sh", "bash", "dash", "zsh", "ksh", "fish"} + some arg in option_arguments(command.argv) + inline_shell_option(arg) +} + +inline_shell_option(arg) if arg == "--command" + +inline_shell_option(arg) if startswith(arg, "--command=") + +inline_shell_option(arg) if regex.match(`^-[^-]*c`, arg) + # Option parsing stops at --. Preserve option order and do not interpret a # filename such as -rf after that delimiter as a destructive option. option_arguments(argv) := [arg | diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index bfc14b80..e5a96e50 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -80,7 +80,8 @@ input: shell_analysis: supported: true commands: - - name: echo + - executable: /bin/echo + name: echo argv: [hello] reason: "" ``` @@ -91,6 +92,12 @@ older rules that inspect only `intent.command` do not inspect the nested command The argument digest binds the reviewed arguments to a signed writ; it does not tell policy what the command means. +`supported` means the analyzer can describe the command's **syntax**, not that +the executable is trusted or the operation is approved. Each command fact keeps +the exact `executable` spelling, its basename as `name`, and its arguments as +`argv`. For example, `./build/test --list` produces `executable: ./build/test`, +`name: test` and `argv: [--list]`; it does not require a recognized-command list. + **Why is `tool_arguments` beside `operation`, rather than inside it?** [`ToolCallOperation`](../../nomos/level_0/types/tool_call.py) is the compact operation record persisted in the Intent and bound into the signed writ, @@ -212,6 +219,8 @@ opa: policy_id: local-bash shell_tool_arguments: shell.run: command + denied_shell_commands: + - restricted-helper ``` An empty binding map is rejected for this profile. Unbound tools continue @@ -223,29 +232,76 @@ The server derives `input.intent.shell_analysis` from the held command. The bundled Rego policy consumes these facts, rather than trusting model-provided command classifications. -| Recognized command | Policy result | +`opa.denied_shell_commands` is an optional deployment-owned list of executable +basenames to forbid before Council review. It defaults to `[]`; leaving it +empty retains the bundled rules below. Entries are exact, case-sensitive names, +not paths or wildcard patterns. In this synthetic example, `restricted-helper`, +`./build/restricted-helper` and `/workspace/project/build/restricted-helper` +all match the configured name; `restricted-helper-extra` does not. + +The Council sends this configuration to OPA as +`input.council.opa_denied_shell_commands`, separately from tool arguments. +A model-supplied argument cannot replace the configured list. A matching +prohibition is a hard denial, even if another rule requests human review; +human approval cannot override it on replay. + +Operators should supply their own reviewed command baseline through deployment +configuration. The bundled rules and synthetic example are a starting profile, +not a complete organizational security policy. Matching depends on the static +command facts described below; it does not discover commands hidden inside +scripts or establish the identity of an executable's contents. + +| Proposed command or syntax | Policy result | | --- | --- | +| Executable basename listed in `opa.denied_shell_commands` | Forbidden | | Recursive forced `rm`, including `-rf`, `-fr`, `-r -f` and long options | Forbidden | | `sudo` | Forbidden | | Login `su`, including `-`, `-l`, combined `-lc`, and `--login` | Forbidden | | `chmod` setting numeric mode `777` or `0777` | Forbidden | | Other `rm` or `su` | Human approval required | -| Unsupported or opaque shell syntax | Human approval required | -| Other recognized literal commands | Continue to Council review | +| Selected dispatch wrappers such as `env`, `exec`, `command` or `eval`, and shell inline code such as `bash -lc 'id'` | Human approval required | +| Unsupported or dynamic shell syntax | Human approval required | +| Other literal invocations, including `git status`, `python3 script.py` and `./build/test --list` | Continue to Council review | This is a conservative **static grammar**, not a Bash interpreter or a sandbox. -It recognizes one simple command with literal arguments and a bounded set of -standard command names. Expansion, globbing, composition, redirection, -interpreters, unfamiliar executables and malformed input require human review. -Some harmless quoted metacharacters consequently require review too. - -Hard-deny rules take precedence over human-review rules for recognized -commands. A proven literal executable/option prefix is retained for denial -only: `rm -rf *` and `rm -rf "$TARGET"` are forbidden even though their targets -need expansion. This prefix is never sufficient to allow a command. An opaque script can contain operations the static grammar does not -recognize; human approval accepts responsibility for that opaque operation. -The profile does not promise to prove every possible Bash effect safe or to -detect a prohibited operation hidden in an arbitrary program. Runtime isolation +It describes one simple command with a literal executable and arguments. It +does not restrict executable names or directories: bare names (`git`), absolute +paths (`/workspace/project/build/test`) and relative paths (`./build/test`) can +all be analyzed. An absolute path is not required. Relative paths are resolved +by the host against the actual working directory; bare names use the host's +command lookup. The analyzer does not resolve those paths or inspect executable +contents. Unsupported expansion, globbing, composition, redirection or malformed +syntax still requires human review. Some harmless quoted metacharacters may +consequently require review too. + +The supplied Rego rules make the command-policy decisions. They match the +parsed basename, so `/workspace/project/build/rm -rf output` is subject to the +same recursive forced-deletion rule as `/bin/rm -rf output`. This is a +conservative name-based policy, not proof that two executables have identical +behavior. A custom program, wrapper or renamed binary can perform effects its +name does not reveal; a full path alone does not establish executable trust. + +Hard-deny rules take precedence over human-review rules. A proven literal +executable/option prefix is retained for denial only: `rm -rf *` and +`rm -rf "$TARGET"` are forbidden even though their targets need expansion. +Completed words survive a later parse error or analysis limit; unfinished words +are not treated as executable names or options. A retained prefix is never +sufficient to allow a command. + +Selected command wrappers and shell inline-code invocations need human review +under explicit Rego rules: their outer arguments do not describe the operation +they dispatch. These rules are not an exhaustive classifier of program effects. +An opaque script can contain operations the static grammar does not recognize. +A simple interpreter invocation such as `python3 script.py` can +therefore proceed to Council review without its script being statically +analyzed. OPA allowing further review is not permission to execute and does not +prove the program safe. + +Executable spelling is separate from the working directory and filesystem +grants. The host still validates the actual working directory, permitted paths +and runtime confinement. An analyzer accepting a path does not grant access to +it or widen the host's filesystem permissions. The profile does not promise to +detect every prohibited effect inside an arbitrary program; runtime isolation and host environment integrity, including inherited shell functions, remain separate controls. diff --git a/nomos/config/settings.py b/nomos/config/settings.py index 649ad763..c75632c0 100644 --- a/nomos/config/settings.py +++ b/nomos/config/settings.py @@ -10,6 +10,7 @@ import copy import os +import unicodedata from enum import StrEnum from pathlib import Path from typing import Any, cast @@ -645,6 +646,32 @@ class OPAConfig(BaseModel): ), ) + denied_shell_commands: list[str] = Field( + default_factory=list, + description=( + "Exact executable basenames forbidden by the local-bash policy. " + "Operator configuration, not tool arguments; names are case-sensitive " + "and are not paths or patterns. This does not identify binary contents " + "or commands hidden inside arbitrary programs." + ), + ) + + @field_validator("denied_shell_commands") + @classmethod + def validate_denied_shell_commands(cls, value: list[str]) -> list[str]: + """Normalize exact names without accepting paths or silently trimming typos.""" + for name in value: + if not name or any( + char in "/\\*?[]" or char.isspace() or unicodedata.category(char) == "Cc" + for char in name + ): + raise ValueError( + "OPA denied_shell_commands must be nonempty executable basenames " + "without paths, whitespace, control characters or glob patterns; " + "command names are literal" + ) + return sorted(set(value)) + @field_validator("shell_tool_arguments") @classmethod def validate_shell_tool_arguments(cls, value: dict[str, str]) -> dict[str, str]: diff --git a/nomos/opa/client.py b/nomos/opa/client.py index 9c93b363..c414089b 100644 --- a/nomos/opa/client.py +++ b/nomos/opa/client.py @@ -164,6 +164,9 @@ def build_intent_filter_input( "council": { "id": intent.council_id, "opa_policy_id": opa_config.policy_id, + # Only operator configuration supplies prohibitions. A tool's JSON + # arguments cannot replace this separate council-owned namespace. + "opa_denied_shell_commands": sorted(set(opa_config.denied_shell_commands)), "opa_relaxed_bare_command_words": sorted(set(opa_config.relaxed_bare_command_words)), "opa_relaxed_working_dir_prefixes": sorted( set(opa_config.relaxed_working_dir_prefixes) diff --git a/nomos/opa/shell_analysis.py b/nomos/opa/shell_analysis.py index c6b556ef..e3085eb0 100644 --- a/nomos/opa/shell_analysis.py +++ b/nomos/opa/shell_analysis.py @@ -1,77 +1,132 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Bounded static shell facts for policy, not a Bash interpreter or sandbox. +"""Bounded facts about a literal simple command, not executable authorization. -Only one literal simple command is recognized for automated review. Expansion, -redirection, shell composition and opaque interpreters require human review -unless a proven literal prefix already establishes a hard prohibition. Shlex -tokenization alone cannot establish Bash semantics. The application must still -enforce its folder and execution boundary. +Any literal executable name or path can be described. Assignments, reserved +shell syntax, expansion and composition remain unsupported; policy decides +whether the resulting executable/arguments are forbidden or need review. +Neither tokenization nor an absolute path establishes what a program will do. +The application still owns its folder and runtime execution boundary. """ from __future__ import annotations +import io import re import shlex -from typing import Any - -# These executable identities identify policy categories, not safe operations. -# Council still reviews every ordinary command that passes this filter. -_COMMANDS = { - ":", - "true", - "false", - "printf", - "echo", - "pwd", - "ls", - "cat", - "mkdir", - "cp", - "mv", - "touch", - "head", - "tail", - "wc", - "cd", - "rm", - "sudo", - "su", - "chmod", +from typing import TypedDict + +MAX_COMMAND_CHARS = 16_384 +MAX_COMMAND_WORDS = 4096 + +# Grammar prefixes, not an executable allowlist. Quoted/escaped spellings may +# conservatively require review because shlex does not retain quote provenance. +_RESERVED_PREFIXES = { + "!", + "time", + "coproc", + "if", + "then", + "elif", + "else", + "fi", + "for", + "select", + "in", + "do", + "done", + "while", + "until", + "case", + "esac", + "function", } +_ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\+?=") _UNSUPPORTED = re.compile(r"[$`\n\r\x00(){}<>|&;*?\[\]~]") -def analyze_shell_command(command: Any) -> dict[str, Any]: - """Return finite JSON facts, routing unrecognized syntax to human review. +class ShellCommand(TypedDict): + """Proposed executable spelling and arguments; no filesystem identity claim.""" + + executable: str + name: str + argv: list[str] + + +class ShellAnalysis(TypedDict): + """Finite JSON facts consumed by Rego, independently of its policy decision.""" + + supported: bool + commands: list[ShellCommand] + reason: str + + +class _CharacterLimitError(ValueError): + """Stop lexing before a truncated token could be mistaken for a whole word.""" + - Quotes and backslash-escaped literal words are handled by POSIX shlex. - Metacharacters make the overall command unsupported even inside quotes. This can ask - for review of harmless literals; it cannot silently authorize expansion. - No filesystem lookup, command execution, environment expansion, or PATH - resolution occurs here. Inherited shell functions remain a host concern. +class _CommandReader(io.StringIO): + """Bound lexer input while preserving only words completed before the limit. + + A synthetic EOF could make a partial option look complete. Raising instead + lets shlex discard the unfinished word while earlier yielded words survive. + The ordinary EOF of a command within the bound retains normal semantics. """ - unknown = { + + def __init__(self, command: str): + super().__init__(command[:MAX_COMMAND_CHARS]) + self.truncated = len(command) > MAX_COMMAND_CHARS + + def read(self, size: int | None = -1) -> str: + if size == 0: + return "" + if self.truncated and self.tell() >= MAX_COMMAND_CHARS: + raise _CharacterLimitError + return super().read(size) + + +def analyze_shell_command(command: object) -> ShellAnalysis: + """Describe a bounded single command without restricting executable names. + + Bare names, absolute paths and cwd-relative paths are all eligible for + policy/model review. No execution, filesystem or PATH lookup occurs here. + Unsupported syntax, incomplete parsing or a resource limit never produces + ``supported=True``. Proven literal prefixes remain available for deny-only + rules even when parsing later fails; partial words are never retained. + """ + unknown: ShellAnalysis = { "supported": False, "commands": [], "reason": "Command requires human interpretation.", } - if not isinstance(command, str) or not command.strip() or len(command) > 16_384: + if not isinstance(command, str) or not command.strip(): return unknown + stream = _CommandReader(command) + lexer = shlex.shlex(stream, posix=True, punctuation_chars=True) + lexer.whitespace_split = True + lexer.commenters = "" + words: list[str] = [] + complete = not stream.truncated try: - words = shlex.split(command, posix=True, comments=False) + for word in lexer: + if len(words) >= MAX_COMMAND_WORDS: + complete = False + break + words.append(word) except ValueError: - return unknown - if not words or len(words) > 4096: + complete = False + if not words: return unknown executable = words[0] name = executable.rsplit("/", 1)[-1] - if name not in _COMMANDS: - return unknown - # Avoid treating assignments, relative scripts, or arbitrary executables - # that happen to have a familiar basename as a standard command. - if "/" in executable and executable not in (f"/bin/{name}", f"/usr/bin/{name}"): + if ( + not name + or executable in _RESERVED_PREFIXES + or _ASSIGNMENT.match(executable) + or _UNSUPPORTED.search(executable) + or "#" in executable + ): return unknown # Retain only a proven literal prefix for deny-only rules. For example, # rm -rf "$TARGET" is opaque overall, but its executable and destructive @@ -82,9 +137,15 @@ def analyze_shell_command(command: Any) -> dict[str, Any]: if _UNSUPPORTED.search(word) or "#" in word: break literal_prefix.append(word) - supported = not _UNSUPPORTED.search(command) and "#" not in command + supported = complete and not _UNSUPPORTED.search(command) and "#" not in command return { "supported": bool(supported), - "commands": [{"name": name, "argv": words[1:] if supported else literal_prefix}], + "commands": [ + { + "executable": executable, + "name": name, + "argv": words[1:] if supported else literal_prefix, + } + ], "reason": "" if supported else unknown["reason"], } diff --git a/policies/intent_filter.rego b/policies/intent_filter.rego index 08e04c6d..7ea3f3a7 100644 --- a/policies/intent_filter.rego +++ b/policies/intent_filter.rego @@ -252,6 +252,13 @@ else := "allow" local_shell_analysis := input.intent.shell_analysis if policy_id == "local-bash" +# Deployment-owned prohibitions are evaluated before automated or human review. +# Matching uses the parsed basename even when the executable has a custom path. +deny contains sprintf("Command %q is forbidden by the configured shell policy.", [command.name]) if { + some command in local_shell_analysis.commands + command.name in object.get(input.council, "opa_denied_shell_commands", []) +} + deny contains "Recursive forced deletion is forbidden." if { some command in local_shell_analysis.commands command.name == "rm" @@ -312,6 +319,27 @@ human_review contains "User switching requires human approval." if { command.name == "su" } +# These selected wrappers can dispatch or evaluate another command. Parsing +# their outer argv does not describe that nested operation. This review list +# is not an exhaustive classifier of arbitrary program effects. +human_review contains "Command dispatch or evaluation requires human approval." if { + some command in local_shell_analysis.commands + command.name in {"exec", "command", "builtin", "env", "nohup", "time", "source", ".", "eval"} +} + +human_review contains "Inline shell code requires human approval." if { + some command in local_shell_analysis.commands + command.name in {"sh", "bash", "dash", "zsh", "ksh", "fish"} + some arg in option_arguments(command.argv) + inline_shell_option(arg) +} + +inline_shell_option(arg) if arg == "--command" + +inline_shell_option(arg) if startswith(arg, "--command=") + +inline_shell_option(arg) if regex.match(`^-[^-]*c`, arg) + # Option parsing stops at --. Preserve option order and do not interpret a # filename such as -rf after that delimiter as a destructive option. option_arguments(argv) := [arg | diff --git a/tests/test_configured_shell_denials.py b/tests/test_configured_shell_denials.py new file mode 100644 index 00000000..94fa1a06 --- /dev/null +++ b/tests/test_configured_shell_denials.py @@ -0,0 +1,126 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Operator-owned exact executable prohibitions cannot come from tool arguments.""" + +import pytest +from pydantic import ValidationError + +from nomos.config.settings import OPAConfig +from nomos.level_0.types import Intent, ToolCallRequest +from nomos.opa import build_intent_filter_input + + +def test_command_prohibitions_default_to_separate_empty_lists(): + first, second = OPAConfig(), OPAConfig() + assert first.denied_shell_commands == second.denied_shell_commands == [] + first.denied_shell_commands.append("synthetic-blocked") + assert second.denied_shell_commands == [] + + +def test_prohibitions_are_sorted_deduplicated_and_case_sensitive(): + supplied = ["zeta-tool", "demo-tool", "Demo-tool", "demo-tool"] + config = OPAConfig(denied_shell_commands=supplied) + assert config.denied_shell_commands == ["Demo-tool", "demo-tool", "zeta-tool"] + # Normalization must not change the caller's list or retain an alias to it. + assert supplied == ["zeta-tool", "demo-tool", "Demo-tool", "demo-tool"] + supplied.append("another-tool") + assert "another-tool" not in config.denied_shell_commands + + +@pytest.mark.parametrize( + "name", + [ + "", + " ", + " leading", + "trailing ", + "two words", + "/opt/tools/demo", + "./demo", + "build/demo", + r"build\demo", + "tab\tname", + "newline\nname", + "nul\x00name", + "delete\x7fname", + "c1\x80name", + "unicode\u2003space", + "*", + "demo*", + "demo?", + "demo[ab]", + "demo[", + "demo]", + ], +) +def test_prohibitions_reject_paths_patterns_and_ambiguous_names(name): + with pytest.raises(ValidationError): + OPAConfig(denied_shell_commands=[name]) + + +def _intent(*, arguments=None): + if arguments is None: + return Intent.create( + agent_id="test-agent", + description="Inspect an exact shell command", + target_resource="stdout", + command="/bin/echo hello", + working_directory="/workspace/project", + ) + material = ToolCallRequest(tool_name="shell.run", arguments=arguments, subject="test-user") + intent = Intent.create( + agent_id="test-agent", + description="Inspect an exact application command", + target_resource="stdout", + command_type="api", + operation=material.to_operation(), + ) + intent._tool_review_material = material + return intent + + +@pytest.mark.parametrize("structured", [False, True]) +def test_both_input_shapes_copy_operator_prohibitions(structured): + config = OPAConfig(denied_shell_commands=["zeta-tool", "demo-tool"]) + intent = _intent(arguments={"command": "echo hello"} if structured else None) + document = build_intent_filter_input( + intent, request_type="authorize", authenticated=True, opa_config=config + ) + assert document["council"]["opa_denied_shell_commands"] == ["demo-tool", "zeta-tool"] + document["council"]["opa_denied_shell_commands"].clear() + assert config.denied_shell_commands == ["demo-tool", "zeta-tool"] + assert build_intent_filter_input( + intent, request_type="authorize", authenticated=True, opa_config=config + )["council"]["opa_denied_shell_commands"] == ["demo-tool", "zeta-tool"] + + +def test_default_input_contains_no_operator_prohibitions(): + document = build_intent_filter_input(_intent(), request_type="authorize", authenticated=True) + assert document["council"]["opa_denied_shell_commands"] == [] + + +def test_tool_arguments_cannot_replace_council_owned_prohibitions(): + arguments = { + "command": "demo-tool --inspect", + "denied_shell_commands": [], + "opa_denied_shell_commands": [], + "council": {"opa_denied_shell_commands": ["different-tool"]}, + } + intent = _intent(arguments=arguments) + config = OPAConfig( + policy_id="local-bash", + shell_tool_arguments={"shell.run": "command"}, + denied_shell_commands=["demo-tool"], + ) + document = build_intent_filter_input( + intent, request_type="authorize", authenticated=True, opa_config=config + ) + assert document["intent"]["tool_arguments"] == arguments + assert document["council"]["opa_denied_shell_commands"] == ["demo-tool"] + document["intent"]["tool_arguments"]["council"]["opa_denied_shell_commands"].append( + "another-tool" + ) + assert document["council"]["opa_denied_shell_commands"] == ["demo-tool"] + assert config.denied_shell_commands == ["demo-tool"] + assert intent._tool_review_material.arguments == arguments diff --git a/tests/test_opa_client.py b/tests/test_opa_client.py index 6bc97f2e..8e536457 100644 --- a/tests/test_opa_client.py +++ b/tests/test_opa_client.py @@ -61,6 +61,7 @@ def test_build_intent_filter_input_excludes_packaged_file_contents(): assert input_doc["council"] == { "id": intent.council_id, "opa_policy_id": "strict-shell", + "opa_denied_shell_commands": [], "opa_relaxed_bare_command_words": [], "opa_relaxed_working_dir_prefixes": [], } @@ -103,6 +104,7 @@ def test_build_intent_filter_input_includes_council_opa_profile(): assert input_doc["council"] == { "id": intent.council_id, "opa_policy_id": "git-workflow-local", + "opa_denied_shell_commands": [], "opa_relaxed_bare_command_words": ["gh", "git"], "opa_relaxed_working_dir_prefixes": ["/workspace"], } diff --git a/tests/test_opa_nat_integration.py b/tests/test_opa_nat_integration.py index 64a3b919..dc2672a2 100644 --- a/tests/test_opa_nat_integration.py +++ b/tests/test_opa_nat_integration.py @@ -217,6 +217,7 @@ async def test_opa_receives_per_council_profile_settings(tmp_path): assert opa.calls[0]["council"] == { "id": "git-council", "opa_policy_id": "git-workflow-local", + "opa_denied_shell_commands": [], "opa_relaxed_bare_command_words": [], "opa_relaxed_working_dir_prefixes": ["/workspace/projects"], } diff --git a/tests/test_opa_tool_policy.py b/tests/test_opa_tool_policy.py index bedbbcd0..7c8595cc 100644 --- a/tests/test_opa_tool_policy.py +++ b/tests/test_opa_tool_policy.py @@ -34,6 +34,11 @@ "su -lp root", "chmod 777 file", "rm -- -rf", + "git status", + "python3 script.py", + "python -c 'pass'", + "bash -lc 'id'", + "/tmp/echo hi", ], ) def test_literal_command_analysis(command): @@ -51,9 +56,6 @@ def test_literal_command_analysis(command): "echo hi; sudo id", "cat file | head", "rm *", - "bash -lc 'id'", - "python -c 'pass'", - "/tmp/echo hi", "X=1 echo hi", "echo hi > out", "echo hi\nid", @@ -94,7 +96,7 @@ def test_actual_arguments_are_live_opa_input_and_do_not_change_durable_binding() ) assert result["intent"]["tool_arguments"] == material.arguments assert result["intent"]["shell_analysis"]["commands"] == [ - {"name": "rm", "argv": ["-rf", "dir"]} + {"executable": "rm", "name": "rm", "argv": ["-rf", "dir"]} ] result["intent"]["tool_arguments"]["nested"]["x"] = 2 assert material.arguments["nested"]["x"] == 1 @@ -245,8 +247,23 @@ async def test_normal_fail_closed_error_does_not_claim_a_policy_prohibition(tmp_ ("echo hello", "allow"), ("echo 'sudo rm -rf directory'", "allow"), ("/bin/mkdir demo", "allow"), + ("git status", "allow"), + ("python3 script.py", "allow"), + ("npm test", "allow"), + ("/workspace/project/build/test_runner --quick", "allow"), + ("./build/test_runner --quick", "allow"), + ("'/workspace/build tools/test runner' --quick", "allow"), + ("/usr/local/bin/custom-tool hello", "allow"), + ("/opt/tools/echo hello", "allow"), ("rm -rf directory", "forbidden"), ("/bin/rm -fr directory", "forbidden"), + ("/workspace/build/rm -rf output", "forbidden"), + ("./build/rm -rf output", "forbidden"), + ("'./build tools/rm' -rf output", "forbidden"), + ("./build/rm -- -rf", "requires_human_approval"), + ("rm -rf output " + "a " * 5000, "forbidden"), + ("sudo " + "a" * 16400, "forbidden"), + ("sudo id 'unterminated", "forbidden"), ("rm -r -f directory", "forbidden"), ("rm -rf *", "forbidden"), ("rm -rf /tmp/*", "forbidden"), @@ -259,20 +276,65 @@ async def test_normal_fail_closed_error_does_not_claim_a_policy_prohibition(tmp_ ("rm file", "requires_human_approval"), ("sudo id", "forbidden"), ("/usr/bin/sudo id", "forbidden"), + ("/custom/tools/sudo id", "forbidden"), ("su - root", "forbidden"), ("su -lc id", "forbidden"), + ("/workspace/build/su -lc id", "forbidden"), ("su --login root", "forbidden"), ("su root", "requires_human_approval"), ("chmod 777 file", "forbidden"), ("chmod -R 0777 directory", "forbidden"), + ("./build/chmod -R 0777 directory", "forbidden"), ("chmod 644 777", "allow"), ("bash -lc 'rm -rf directory'", "requires_human_approval"), + ("/opt/tools/bash -lc 'id'", "requires_human_approval"), + ("bash --command=id", "requires_human_approval"), + ("bash -- -c", "allow"), + ("echo --command=id", "allow"), + ("exec /bin/rm -rf output", "requires_human_approval"), + ("command /bin/rm -rf output", "requires_human_approval"), + ("env /bin/rm -rf output", "requires_human_approval"), + ("/usr/bin/time /bin/rm -rf output", "requires_human_approval"), + ("VAR=x sudo id", "requires_human_approval"), + ("VAR+=x sudo id", "requires_human_approval"), + ("! sudo id", "requires_human_approval"), + ("time sudo id", "requires_human_approval"), ("rm *", "requires_human_approval"), ("echo hi; sudo id", "requires_human_approval"), ("echo $(id)", "requires_human_approval"), ], ) def test_real_opa_consumes_actual_command_analysis(command, expected): + response = _evaluate_real_shell_policy(command) + assert response["policy_decision"] == expected + assert response["allow"] == (expected == "allow") + + +@pytest.mark.parametrize( + ("command", "denied", "expected"), + [ + ("restricted-helper task", ["restricted-helper"], "forbidden"), + ("/workspace/build/restricted-helper task", ["restricted-helper"], "forbidden"), + ("./build/restricted-helper task", ["restricted-helper"], "forbidden"), + ("restricted-helper task", [], "allow"), + ("Restricted-helper task", ["restricted-helper"], "allow"), + ("echo restricted-helper", ["restricted-helper"], "allow"), + ("su user", ["su"], "forbidden"), + ("nohup task", ["nohup"], "forbidden"), + ("restricted-helper $TARGET", ["restricted-helper"], "forbidden"), + ("restricted-helper 'unterminated", ["restricted-helper"], "forbidden"), + ("git status", ["restricted-helper"], "allow"), + ], +) +def test_real_opa_configured_prohibitions_precede_review(command, denied, expected): + response = _evaluate_real_shell_policy(command, denied) + assert response["policy_decision"] == expected + assert response["allow"] == (expected == "allow") + if expected == "forbidden": + assert any("configured shell policy" in reason for reason in response["reasons"]) + + +def _evaluate_real_shell_policy(command, denied_commands=()): binary = os.environ.get("NOMOS_TEST_OPA_BINARY") if not binary: pytest.skip("Set NOMOS_TEST_OPA_BINARY to run the actual Rego engine") @@ -287,7 +349,11 @@ def test_real_opa_consumes_actual_command_analysis(command, expected): operation=material.to_operation(), ) intent._tool_review_material = material - config = OPAConfig(policy_id="local-bash", shell_tool_arguments={"shell.run": "command"}) + config = OPAConfig( + policy_id="local-bash", + shell_tool_arguments={"shell.run": "command"}, + denied_shell_commands=list(denied_commands), + ) document = build_intent_filter_input( intent, request_type="authorize", authenticated=True, opa_config=config ) @@ -308,6 +374,4 @@ def test_real_opa_consumes_actual_command_analysis(command, expected): check=True, timeout=10, ) - response = json.loads(completed.stdout)["result"][0]["expressions"][0]["value"] - assert response["policy_decision"] == expected - assert response["allow"] == (expected == "allow") + return json.loads(completed.stdout)["result"][0]["expressions"][0]["value"] diff --git a/tests/test_shell_analysis.py b/tests/test_shell_analysis.py new file mode 100644 index 00000000..32d1b2e9 --- /dev/null +++ b/tests/test_shell_analysis.py @@ -0,0 +1,180 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Shell syntax facts must not act as an executable allowlist or run commands.""" + +import pytest + +from nomos.opa.shell_analysis import ( + MAX_COMMAND_CHARS, + MAX_COMMAND_WORDS, + analyze_shell_command, +) + + +@pytest.mark.parametrize( + ("command", "executable", "name", "argv"), + [ + ("git status --short", "git", "git", ["status", "--short"]), + ("python3 script.py", "python3", "python3", ["script.py"]), + ("npm test", "npm", "npm", ["test"]), + ( + "/workspace/project/build/test_runner --quick", + "/workspace/project/build/test_runner", + "test_runner", + ["--quick"], + ), + ("./build/test_runner --quick", "./build/test_runner", "test_runner", ["--quick"]), + ("../build/test_runner --quick", "../build/test_runner", "test_runner", ["--quick"]), + ( + "/usr/local/bin/custom-tool hello", + "/usr/local/bin/custom-tool", + "custom-tool", + ["hello"], + ), + ("/opt/tools/echo hello", "/opt/tools/echo", "echo", ["hello"]), + ("/workspace/build/if hello", "/workspace/build/if", "if", ["hello"]), + ("/workspace/build/time hello", "/workspace/build/time", "time", ["hello"]), + ("/workspace/build/VAR=x hello", "/workspace/build/VAR=x", "VAR=x", ["hello"]), + ( + "/usr/bin/time -p ./build/test_runner", + "/usr/bin/time", + "time", + ["-p", "./build/test_runner"], + ), + ( + "'/workspace/project/build tools/test runner' 'argument with spaces'", + "/workspace/project/build tools/test runner", + "test runner", + ["argument with spaces"], + ), + ( + r"./build\ tools/test\ runner hello", + "./build tools/test runner", + "test runner", + ["hello"], + ), + ("printf '%s' hello", "printf", "printf", ["%s", "hello"]), + ("runner 'a b' c\\ d -- -rf", "runner", "runner", ["a b", "c d", "--", "-rf"]), + ("git -c color.ui=always status", "git", "git", ["-c", "color.ui=always", "status"]), + ("cd build", "cd", "cd", ["build"]), + (":", ":", ":", []), + ], +) +def test_any_literal_executable_is_analysis_input(command, executable, name, argv): + """Eligibility for policy review does not depend on name or install directory.""" + result = analyze_shell_command(command) + assert result["supported"] is True + assert len(result["commands"]) == 1 + parsed = result["commands"][0] + assert parsed["executable"] == executable + assert parsed["name"] == name + assert parsed["argv"] == argv + assert result["reason"] == "" + + +@pytest.mark.parametrize( + "command", + [ + "VAR=x sudo id", + "VAR+=x sudo id", + "VAR+= sudo id", + "PATH=/custom/bin rm -rf output", + "! sudo id", + "time sudo id", + "coproc sudo id", + "if true", + "then sudo id", + "while true", + "for item in output", + "case item in", + "function cleanup", + "echo hello; sudo id", + "echo hello && sudo id", + "cat input | head", + "echo hello > output", + "echo $(id)", + "echo `id`", + "echo hello\nsudo id", + '"${TOOL}" argument', + '"$(choose_tool)" argument', + "`choose_tool` argument", + "/workspace/$TOOL argument", + "'' sudo id", + ], +) +def test_shell_structure_is_not_mistaken_for_an_arbitrary_executable(command): + """Removing executable restrictions must not accidentally admit shell grammar.""" + assert analyze_shell_command(command)["supported"] is False + + +@pytest.mark.parametrize( + ("command", "executable", "name", "argv_prefix"), + [ + ("sudo id " + "a " * 5000, "sudo", "sudo", ["id"]), + ("sudo " + "a" * 16_400, "sudo", "sudo", []), + ("sudo id 'unterminated", "sudo", "sudo", ["id"]), + ("rm -rf output " + "a " * 5000, "rm", "rm", ["-rf", "output"]), + ("rm -rf output " + "a" * 16_400, "rm", "rm", ["-rf", "output"]), + ("rm -rf 'unterminated", "rm", "rm", ["-rf"]), + ("/custom/build/sudo id " + "a " * 5000, "/custom/build/sudo", "sudo", ["id"]), + ('./build/rm -rf "$TARGET"', "./build/rm", "rm", ["-rf"]), + ], +) +def test_incomplete_analysis_keeps_only_proven_command_facts( + command, executable, name, argv_prefix +): + """Padding and malformed tails cannot erase an already known hard-deny prefix.""" + result = analyze_shell_command(command) + assert result["supported"] is False + assert len(result["commands"]) == 1 + parsed = result["commands"][0] + assert parsed["executable"] == executable + assert parsed["name"] == name + assert parsed["argv"][: len(argv_prefix)] == argv_prefix + assert len(parsed["argv"]) <= 4096 + + +def test_character_limit_does_not_turn_partial_word_into_a_destructive_option(): + # The bounded prefix ends at --force, but the real argument continues. + # Treating the cut word as complete would invent a force option. + prefix = "rm -r " + command = prefix + " " * (16_384 - len(prefix) - len("--force")) + "--force-not-an-option" + result = analyze_shell_command(command) + assert result["supported"] is False + assert result["commands"][0]["name"] == "rm" + assert result["commands"][0]["argv"] == ["-r"] + + +def test_analyzing_a_literal_command_does_not_execute_it(tmp_path): + """The proposed executable may be nonexistent; analysis has no process effects.""" + marker = tmp_path / "analysis-must-not-create-this" + result = analyze_shell_command(f"/usr/bin/touch {marker}") + assert result["supported"] is True + assert not marker.exists() + + +def test_exact_character_limit_keeps_complete_final_argument(): + command = "runner " + "a" * (MAX_COMMAND_CHARS - len("runner ")) + result = analyze_shell_command(command) + assert result["supported"] is True + assert result["commands"][0]["argv"] == [command[len("runner ") :]] + + +def test_exact_word_limit_is_supported_but_next_word_is_incomplete_analysis(): + command = "runner " + "a " * (MAX_COMMAND_WORDS - 1) + result = analyze_shell_command(command) + assert result["supported"] is True + assert len(result["commands"][0]["argv"]) == MAX_COMMAND_WORDS - 1 + beyond = analyze_shell_command(command + "a") + assert beyond["supported"] is False + assert beyond["commands"][0]["executable"] == "runner" + + +def test_character_limit_cannot_invent_a_denylisted_executable_from_partial_word(): + # At the character bound this token spells sudo, but its full spelling is + # sudo-not-the-command. No executable word was completed before truncation. + command = " " * (MAX_COMMAND_CHARS - len("sudo")) + "sudo-not-the-command" + result = analyze_shell_command(command) + assert result["supported"] is False + assert result["commands"] == [] From 110decf632ac8d4d4383d65fb010e10441a8793a Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 14:52:18 -0800 Subject: [PATCH 08/15] docs(config): expose optional shell command deny list --- configs/council.yaml | 5 +++++ deploy/kubernetes/nomos/files/council/council.yaml | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/configs/council.yaml b/configs/council.yaml index b7801964..7a0772de 100644 --- a/configs/council.yaml +++ b/configs/council.yaml @@ -256,6 +256,11 @@ opa: url: "${COUNCIL_OPA_URL:-http://opa:8181}" decision_path: "${COUNCIL_OPA_DECISION_PATH:-/v1/data/nomos/intent/decision}" policy_id: "${COUNCIL_OPA_POLICY_ID:-strict-shell}" + # Additional executable basenames forbidden by the local-bash profile. + # Populate with your deployment's reviewed list; exact names, not paths/globs. + # Requires policy_id: local-bash and an explicit shell_tool_arguments binding. + # Empty adds no prohibitions beyond the bundled policy rules. + denied_shell_commands: [] timeout_ms: "${COUNCIL_OPA_TIMEOUT_MS:-500}" fail_closed: "${COUNCIL_OPA_FAIL_CLOSED:-true}" diff --git a/deploy/kubernetes/nomos/files/council/council.yaml b/deploy/kubernetes/nomos/files/council/council.yaml index b7801964..7a0772de 100644 --- a/deploy/kubernetes/nomos/files/council/council.yaml +++ b/deploy/kubernetes/nomos/files/council/council.yaml @@ -256,6 +256,11 @@ opa: url: "${COUNCIL_OPA_URL:-http://opa:8181}" decision_path: "${COUNCIL_OPA_DECISION_PATH:-/v1/data/nomos/intent/decision}" policy_id: "${COUNCIL_OPA_POLICY_ID:-strict-shell}" + # Additional executable basenames forbidden by the local-bash profile. + # Populate with your deployment's reviewed list; exact names, not paths/globs. + # Requires policy_id: local-bash and an explicit shell_tool_arguments binding. + # Empty adds no prohibitions beyond the bundled policy rules. + denied_shell_commands: [] timeout_ms: "${COUNCIL_OPA_TIMEOUT_MS:-500}" fail_closed: "${COUNCIL_OPA_FAIL_CLOSED:-true}" From 83b19ca6b48056038d02a9df2f722dfefbbd2439 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 15:11:36 -0800 Subject: [PATCH 09/15] refactor(opa): clarify parse completeness and agent feedback --- .../nomos/files/policies/intent_filter.rego | 29 ++++++++- docs/guides/structured-tool-policy.md | 39 +++++++++++- nomos/opa/shell_analysis.py | 56 ++++++++++++++--- policies/intent_filter.rego | 29 ++++++++- tests/test_chairman_configuration.py | 6 +- tests/test_opa_tool_policy.py | 57 ++++++++++++++++- tests/test_shell_analysis.py | 62 ++++++++++++++++--- 7 files changed, 250 insertions(+), 28 deletions(-) diff --git a/deploy/kubernetes/nomos/files/policies/intent_filter.rego b/deploy/kubernetes/nomos/files/policies/intent_filter.rego index 7ea3f3a7..da8d89af 100644 --- a/deploy/kubernetes/nomos/files/policies/intent_filter.rego +++ b/deploy/kubernetes/nomos/files/policies/intent_filter.rego @@ -305,8 +305,33 @@ deny contains "World-writable executable permissions are forbidden." if { mode[0] in {"777", "0777"} } -human_review contains "This command requires human interpretation before host execution." if { - local_shell_analysis.supported == false +human_review contains analysis_limitation if { + analysis := local_shell_analysis + not analysis.fully_parsed == true +} + +analysis_limitation := object.get(local_shell_analysis, "reason", "") if { + object.get(local_shell_analysis, "reason", "") != "" +} + +else := "The shell command was not fully parsed." + +# Agent-facing guidance follows the final policy verdict, not parser success. +# A known prohibition must never invite resubmission or a human override. +remediation contains "This operation is forbidden. Do not retry it or seek human approval to override this denial." if { + policy_id == "local-bash" + policy_decision == "forbidden" +} + +remediation contains sprintf("%s Submit the intended literal command and values for a new review, or request human approval. Do not execute before approval.", [analysis_limitation]) if { + policy_decision == "requires_human_approval" + analysis := local_shell_analysis + not analysis.fully_parsed == true +} + +remediation contains "This operation requires human approval. Do not execute before approval." if { + policy_decision == "requires_human_approval" + local_shell_analysis.fully_parsed == true } human_review contains "Deletion requires human approval." if { diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index e5a96e50..0b86534c 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -78,7 +78,7 @@ input: command: /bin/echo hello cwd: /workspace/project shell_analysis: - supported: true + fully_parsed: true commands: - executable: /bin/echo name: echo @@ -92,12 +92,47 @@ older rules that inspect only `intent.command` do not inspect the nested command The argument digest binds the reviewed arguments to a signed writ; it does not tell policy what the command means. -`supported` means the analyzer can describe the command's **syntax**, not that +`fully_parsed` means the analyzer can describe the entire command's **syntax** +within its grammar and resource limits, not that the executable is trusted or the operation is approved. Each command fact keeps the exact `executable` spelling, its basename as `name`, and its arguments as `argv`. For example, `./build/test --list` produces `executable: ./build/test`, `name: test` and `argv: [--list]`; it does not require a recognized-command list. +An incomplete analysis can still retain literal command facts. For example, +`rm -rf "$TARGET"` produces: + +```yaml +fully_parsed: false +commands: + - executable: rm + name: rm + argv: [-rf] +reason: "Variable-expansion syntax ($NAME or ${NAME}) cannot be fully analyzed." +``` + +The reason describes the analysis limitation without repeating argument values. +The final OPA decision supplies agent-facing guidance. For `cat "$TARGET"`, it +explains the variable-expansion limitation and asks for the intended literal +command and values for a new review, or human approval; execution must wait. +For `rm -rf "$TARGET"`, the known prefix is already forbidden, so guidance says +not to retry or seek a human override. A parsing limitation never excuses a +known prohibition. Malformed quotes, size limits, composition and other syntax +limits have distinct explanations. Conservative detection may also flag quoted +literal metacharacters because the analyzer does not retain quote provenance. + +`fully_parsed` replaces the draft field `supported`. Deploy the updated OPA +policy before updating the Nomos producer; roll back the producer first if +needed. If an analysis object lacks the new field, the updated policy requires +human review rather than treating the command as fully parsed. The reverse +pairing is unsupported: an older policy cannot enforce the renamed +incomplete-analysis check, so updating only the producer could bypass that +human-review requirement. +Application adapters must preserve the returned policy guidance when presenting +feedback to the agent; replacing it with a generic approval message hides the +specific analysis limitation. Decisions must still use `policy_decision`, not +matching words in the explanation. + **Why is `tool_arguments` beside `operation`, rather than inside it?** [`ToolCallOperation`](../../nomos/level_0/types/tool_call.py) is the compact operation record persisted in the Intent and bound into the signed writ, diff --git a/nomos/opa/shell_analysis.py b/nomos/opa/shell_analysis.py index e3085eb0..9bbda369 100644 --- a/nomos/opa/shell_analysis.py +++ b/nomos/opa/shell_analysis.py @@ -57,7 +57,7 @@ class ShellCommand(TypedDict): class ShellAnalysis(TypedDict): """Finite JSON facts consumed by Rego, independently of its policy decision.""" - supported: bool + fully_parsed: bool commands: list[ShellCommand] reason: str @@ -86,19 +86,44 @@ def read(self, size: int | None = -1) -> str: return super().read(size) +def _syntax_limitation(command: str) -> str: + """Explain conservative grammar limits without echoing command data or secrets. + + Quote provenance is not retained by shlex. Metacharacters inside quotes may + therefore trigger the same conservative explanation as active shell syntax. + Policy owns the final verdict and any instructions for the agent to retry. + """ + for pattern, reason in ( + (r"\x00", "NUL bytes cannot be analyzed as a shell command."), + (r"[\n\r]", "Multiple lines cannot be fully analyzed."), + (r"\$\(\(", "Arithmetic-expansion syntax cannot be fully analyzed."), + (r"\$\(|`", "Command-substitution syntax cannot be fully analyzed."), + (r"\$", "Variable-expansion syntax ($NAME or ${NAME}) cannot be fully analyzed."), + (r"[;|&]", "Shell composition cannot be fully analyzed as one simple command."), + (r"[<>]", "Shell redirection cannot be fully analyzed."), + (r"[*?\[\]]", "Globbing or pattern syntax cannot be fully analyzed."), + (r"~", "Home-directory expansion cannot be fully analyzed."), + (r"[(){}]", "Shell grouping syntax cannot be fully analyzed."), + (r"#", "Shell comment syntax cannot be fully analyzed."), + ): + if re.search(pattern, command): + return reason + return "" + + def analyze_shell_command(command: object) -> ShellAnalysis: """Describe a bounded single command without restricting executable names. Bare names, absolute paths and cwd-relative paths are all eligible for policy/model review. No execution, filesystem or PATH lookup occurs here. Unsupported syntax, incomplete parsing or a resource limit never produces - ``supported=True``. Proven literal prefixes remain available for deny-only + ``fully_parsed=True``. Proven literal prefixes remain available for deny-only rules even when parsing later fails; partial words are never retained. """ unknown: ShellAnalysis = { - "supported": False, + "fully_parsed": False, "commands": [], - "reason": "Command requires human interpretation.", + "reason": "A nonempty shell command string is required for analysis.", } if not isinstance(command, str) or not command.strip(): return unknown @@ -108,14 +133,24 @@ def analyze_shell_command(command: object) -> ShellAnalysis: lexer.commenters = "" words: list[str] = [] complete = not stream.truncated + limitation = "Command exceeds the analysis character limit." if stream.truncated else "" try: for word in lexer: if len(words) >= MAX_COMMAND_WORDS: complete = False + limitation = limitation or "Command exceeds the analysis word limit." break words.append(word) + except _CharacterLimitError: + complete = False + limitation = "Command exceeds the analysis character limit." except ValueError: complete = False + limitation = ( + limitation or "Unterminated quoting or an incomplete escape prevents full analysis." + ) + limitation = limitation or _syntax_limitation(command[:MAX_COMMAND_CHARS]) + unknown["reason"] = limitation or "No literal executable could be identified." if not words: return unknown executable = words[0] @@ -127,6 +162,11 @@ def analyze_shell_command(command: object) -> ShellAnalysis: or _UNSUPPORTED.search(executable) or "#" in executable ): + if not limitation: + if _ASSIGNMENT.match(executable): + unknown["reason"] = "Shell assignment prefixes cannot be fully analyzed." + elif executable in _RESERVED_PREFIXES: + unknown["reason"] = "Shell reserved-word prefixes cannot be fully analyzed." return unknown # Retain only a proven literal prefix for deny-only rules. For example, # rm -rf "$TARGET" is opaque overall, but its executable and destructive @@ -137,15 +177,15 @@ def analyze_shell_command(command: object) -> ShellAnalysis: if _UNSUPPORTED.search(word) or "#" in word: break literal_prefix.append(word) - supported = complete and not _UNSUPPORTED.search(command) and "#" not in command + fully_parsed = complete and not limitation return { - "supported": bool(supported), + "fully_parsed": bool(fully_parsed), "commands": [ { "executable": executable, "name": name, - "argv": words[1:] if supported else literal_prefix, + "argv": words[1:] if fully_parsed else literal_prefix, } ], - "reason": "" if supported else unknown["reason"], + "reason": "" if fully_parsed else unknown["reason"], } diff --git a/policies/intent_filter.rego b/policies/intent_filter.rego index 7ea3f3a7..da8d89af 100644 --- a/policies/intent_filter.rego +++ b/policies/intent_filter.rego @@ -305,8 +305,33 @@ deny contains "World-writable executable permissions are forbidden." if { mode[0] in {"777", "0777"} } -human_review contains "This command requires human interpretation before host execution." if { - local_shell_analysis.supported == false +human_review contains analysis_limitation if { + analysis := local_shell_analysis + not analysis.fully_parsed == true +} + +analysis_limitation := object.get(local_shell_analysis, "reason", "") if { + object.get(local_shell_analysis, "reason", "") != "" +} + +else := "The shell command was not fully parsed." + +# Agent-facing guidance follows the final policy verdict, not parser success. +# A known prohibition must never invite resubmission or a human override. +remediation contains "This operation is forbidden. Do not retry it or seek human approval to override this denial." if { + policy_id == "local-bash" + policy_decision == "forbidden" +} + +remediation contains sprintf("%s Submit the intended literal command and values for a new review, or request human approval. Do not execute before approval.", [analysis_limitation]) if { + policy_decision == "requires_human_approval" + analysis := local_shell_analysis + not analysis.fully_parsed == true +} + +remediation contains "This operation requires human approval. Do not execute before approval." if { + policy_decision == "requires_human_approval" + local_shell_analysis.fully_parsed == true } human_review contains "Deletion requires human approval." if { diff --git a/tests/test_chairman_configuration.py b/tests/test_chairman_configuration.py index d9291b85..d5843998 100644 --- a/tests/test_chairman_configuration.py +++ b/tests/test_chairman_configuration.py @@ -362,7 +362,8 @@ def test_referenced_profile_uses_final_deep_merged_chairman( ) def test_shipped_yaml_preserves_enabled_unanimous_mode_and_all_parsed_values(relative_path): # Pin the complete shipped profile, including the intentional Nemotron 3.5 - # default migration. Comments/formatting are intentionally ignored; the + # default migration and explicit empty shell-command deny list. + # Comments/formatting are intentionally ignored; the # public-config tests separately assert the model and every role's routing. root = Path(settings_module.__file__).resolve().parents[2] document = yaml.safe_load((root / relative_path).read_text(encoding="utf-8")) @@ -371,10 +372,11 @@ def test_shipped_yaml_preserves_enabled_unanimous_mode_and_all_parsed_values(rel f"given={relative_path!r}: shipped mode must remain " f"enabled=true/allow_quorum=false; got {mode!r}" ) + assert document["opa"]["denied_shell_commands"] == [] canonical = json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=True) digest = hashlib.sha256(canonical.encode()).hexdigest() # Public pinned YAML semantic SHA-256, not a credential; retain the full literal. - expected = "062de80d1a1b58b8adf404763439af9b5e5fe4a65784e0bb1afa9a0562c69e34" # pragma: allowlist secret # noqa: E501 + expected = "3c29da41b0a81d6aad441dec6e76f0215289bba57f5ae987b2455c5049d7e164" # pragma: allowlist secret # noqa: E501 assert digest == expected, ( f"given={relative_path!r}: all parsed release-template values must match pinned base; " f"expected semantic SHA-256 {expected}, got {digest}" diff --git a/tests/test_opa_tool_policy.py b/tests/test_opa_tool_policy.py index 7c8595cc..ce45c6b4 100644 --- a/tests/test_opa_tool_policy.py +++ b/tests/test_opa_tool_policy.py @@ -42,7 +42,7 @@ ], ) def test_literal_command_analysis(command): - assert analyze_shell_command(command)["supported"] is True + assert analyze_shell_command(command)["fully_parsed"] is True @pytest.mark.parametrize( @@ -65,7 +65,7 @@ def test_literal_command_analysis(command): ], ) def test_opaque_or_unsupported_commands_require_interpretation(command): - assert analyze_shell_command(command)["supported"] is False + assert analyze_shell_command(command)["fully_parsed"] is False def test_profile_binding_is_explicit_and_empty_profile_is_rejected(): @@ -334,7 +334,56 @@ def test_real_opa_configured_prohibitions_precede_review(command, denied, expect assert any("configured shell policy" in reason for reason in response["reasons"]) -def _evaluate_real_shell_policy(command, denied_commands=()): +@pytest.mark.parametrize("command", ['cat "$TARGET"', 'rm -rf "$TARGET"']) +@pytest.mark.asyncio +async def test_agent_receives_guidance_for_the_final_policy_decision( + tmp_path, monkeypatch, command +): + response = _evaluate_real_shell_policy(command) + decision = parse_opa_decision({"result": response}) + service = _make_service(tmp_path) + service._opa_client = RecordingOPAClient(decision) + + async def unexpected(*args, **kwargs): + pytest.fail("Incomplete or forbidden commands must not reach Council review") + + monkeypatch.setattr(service, "_run_code_review", unexpected) + result = await service.authorize(_request()) + assert result.status == "denied" + assert result.writ is None + assert result.policy_decision == response["policy_decision"] + # The response also prepends the existing general retry-safety guidance. + assert set(response["guidance"]).issubset(result.guidance) + guidance = " ".join(response["guidance"]) + if command.startswith("rm"): + assert result.policy_decision == "forbidden" + assert "Do not retry" in guidance + assert "Submit the intended literal" not in guidance + assert "or request human approval" not in guidance + else: + assert result.policy_decision == "requires_human_approval" + assert "Variable-expansion" in guidance + assert "Submit the intended literal" in guidance + assert "Do not execute before approval" in guidance + + +@pytest.mark.parametrize("analysis", [{"supported": True}, {"supported": False}, {}]) +def test_missing_renamed_parse_flag_cannot_allow_a_command(analysis): + response = _evaluate_real_shell_policy("echo hello", analysis_override=analysis) + assert response["policy_decision"] == "requires_human_approval" + assert response["allow"] is False + assert any("not fully parsed" in reason for reason in response["reasons"]) + + +def test_fully_parsed_command_can_still_need_human_approval(): + response = _evaluate_real_shell_policy("rm note.txt") + assert response["policy_decision"] == "requires_human_approval" + assert response["guidance"] == [ + "This operation requires human approval. Do not execute before approval." + ] + + +def _evaluate_real_shell_policy(command, denied_commands=(), *, analysis_override=None): binary = os.environ.get("NOMOS_TEST_OPA_BINARY") if not binary: pytest.skip("Set NOMOS_TEST_OPA_BINARY to run the actual Rego engine") @@ -357,6 +406,8 @@ def _evaluate_real_shell_policy(command, denied_commands=()): document = build_intent_filter_input( intent, request_type="authorize", authenticated=True, opa_config=config ) + if analysis_override is not None: + document["intent"]["shell_analysis"] = analysis_override policy = Path(__file__).resolve().parents[1] / "policies" / "intent_filter.rego" completed = subprocess.run( [ diff --git a/tests/test_shell_analysis.py b/tests/test_shell_analysis.py index 32d1b2e9..1c3608be 100644 --- a/tests/test_shell_analysis.py +++ b/tests/test_shell_analysis.py @@ -64,7 +64,7 @@ def test_any_literal_executable_is_analysis_input(command, executable, name, argv): """Eligibility for policy review does not depend on name or install directory.""" result = analyze_shell_command(command) - assert result["supported"] is True + assert result["fully_parsed"] is True assert len(result["commands"]) == 1 parsed = result["commands"][0] assert parsed["executable"] == executable @@ -105,7 +105,7 @@ def test_any_literal_executable_is_analysis_input(command, executable, name, arg ) def test_shell_structure_is_not_mistaken_for_an_arbitrary_executable(command): """Removing executable restrictions must not accidentally admit shell grammar.""" - assert analyze_shell_command(command)["supported"] is False + assert analyze_shell_command(command)["fully_parsed"] is False @pytest.mark.parametrize( @@ -126,7 +126,7 @@ def test_incomplete_analysis_keeps_only_proven_command_facts( ): """Padding and malformed tails cannot erase an already known hard-deny prefix.""" result = analyze_shell_command(command) - assert result["supported"] is False + assert result["fully_parsed"] is False assert len(result["commands"]) == 1 parsed = result["commands"][0] assert parsed["executable"] == executable @@ -141,7 +141,7 @@ def test_character_limit_does_not_turn_partial_word_into_a_destructive_option(): prefix = "rm -r " command = prefix + " " * (16_384 - len(prefix) - len("--force")) + "--force-not-an-option" result = analyze_shell_command(command) - assert result["supported"] is False + assert result["fully_parsed"] is False assert result["commands"][0]["name"] == "rm" assert result["commands"][0]["argv"] == ["-r"] @@ -150,24 +150,24 @@ def test_analyzing_a_literal_command_does_not_execute_it(tmp_path): """The proposed executable may be nonexistent; analysis has no process effects.""" marker = tmp_path / "analysis-must-not-create-this" result = analyze_shell_command(f"/usr/bin/touch {marker}") - assert result["supported"] is True + assert result["fully_parsed"] is True assert not marker.exists() def test_exact_character_limit_keeps_complete_final_argument(): command = "runner " + "a" * (MAX_COMMAND_CHARS - len("runner ")) result = analyze_shell_command(command) - assert result["supported"] is True + assert result["fully_parsed"] is True assert result["commands"][0]["argv"] == [command[len("runner ") :]] def test_exact_word_limit_is_supported_but_next_word_is_incomplete_analysis(): command = "runner " + "a " * (MAX_COMMAND_WORDS - 1) result = analyze_shell_command(command) - assert result["supported"] is True + assert result["fully_parsed"] is True assert len(result["commands"][0]["argv"]) == MAX_COMMAND_WORDS - 1 beyond = analyze_shell_command(command + "a") - assert beyond["supported"] is False + assert beyond["fully_parsed"] is False assert beyond["commands"][0]["executable"] == "runner" @@ -176,5 +176,49 @@ def test_character_limit_cannot_invent_a_denylisted_executable_from_partial_word # sudo-not-the-command. No executable word was completed before truncation. command = " " * (MAX_COMMAND_CHARS - len("sudo")) + "sudo-not-the-command" result = analyze_shell_command(command) - assert result["supported"] is False + assert result["fully_parsed"] is False assert result["commands"] == [] + + +@pytest.mark.parametrize( + ("command", "explanation"), + [ + (None, "nonempty shell command"), + ("", "nonempty shell command"), + ('cat "$TARGET"', "Variable-expansion"), + ('cat "${TARGET}"', "Variable-expansion"), + ("echo $((1 + 2))", "Arithmetic-expansion"), + ("echo $(id)", "Command-substitution"), + ("echo `id`", "Command-substitution"), + ("echo hi; echo there", "composition"), + ("echo hi > out", "redirection"), + ("cat *.txt", "Globbing"), + ("cat ~/file", "Home-directory"), + ("(echo hi)", "grouping"), + ("echo hi # comment", "comment"), + ("echo hi\nid", "Multiple lines"), + ("echo hi\x00", "NUL bytes"), + ("echo 'unterminated", "Unterminated quoting"), + ("echo incomplete\\", "incomplete escape"), + ("VAR=x runner", "assignment prefixes"), + ("time runner", "reserved-word prefixes"), + ("echo " + "a" * MAX_COMMAND_CHARS, "character limit"), + ("echo " + "a " * MAX_COMMAND_WORDS, "word limit"), + ], +) +def test_incomplete_reason_identifies_the_limitation_without_claiming_policy(command, explanation): + result = analyze_shell_command(command) + assert result["fully_parsed"] is False + assert explanation in result["reason"] + assert "approval" not in result["reason"] + assert "forbidden" not in result["reason"] + assert "supported" not in result + + +def test_analysis_reason_does_not_echo_private_command_material(): + marker = "private-argument-marker" + result = analyze_shell_command(f'cat "$TARGET" {marker}') + assert result["fully_parsed"] is False + assert "Variable-expansion" in result["reason"] + assert marker not in result["reason"] + assert "$TARGET" not in result["reason"] From 112f1d2731d5bd0f42e9a74891c052404e270ded Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 15:45:54 -0800 Subject: [PATCH 10/15] refactor(opa): use one authorization status for human review --- .../nomos/files/policies/intent_filter.rego | 10 +- docs/guides/structured-tool-policy.md | 95 ++++++++-- nomos/nat/functions.py | 62 ++++--- nomos/opa/client.py | 45 +++-- policies/intent_filter.rego | 10 +- tests/test_opa_client.py | 2 +- tests/test_opa_tool_policy.py | 164 +++++++++++------- 7 files changed, 263 insertions(+), 125 deletions(-) diff --git a/deploy/kubernetes/nomos/files/policies/intent_filter.rego b/deploy/kubernetes/nomos/files/policies/intent_filter.rego index da8d89af..31b524b9 100644 --- a/deploy/kubernetes/nomos/files/policies/intent_filter.rego +++ b/deploy/kubernetes/nomos/files/policies/intent_filter.rego @@ -14,7 +14,7 @@ allow if { decision := { "allow": allow, - "policy_decision": policy_decision, + "decision": policy_outcome, "reasons": reasons, "guidance": guidance, "metadata": { @@ -244,7 +244,7 @@ remediation contains "Use a public interface for keys/secrets or narrow the targ # Hard denial wins over any request for human review. Human approval does not # override a forbidden operation; policy inspection on replay evaluates again. -policy_decision := "forbidden" if count(deny) > 0 +policy_outcome := "deny" if count(deny) > 0 else := "requires_human_approval" if count(human_review) > 0 @@ -320,17 +320,17 @@ else := "The shell command was not fully parsed." # A known prohibition must never invite resubmission or a human override. remediation contains "This operation is forbidden. Do not retry it or seek human approval to override this denial." if { policy_id == "local-bash" - policy_decision == "forbidden" + policy_outcome == "deny" } remediation contains sprintf("%s Submit the intended literal command and values for a new review, or request human approval. Do not execute before approval.", [analysis_limitation]) if { - policy_decision == "requires_human_approval" + policy_outcome == "requires_human_approval" analysis := local_shell_analysis not analysis.fully_parsed == true } remediation contains "This operation requires human approval. Do not execute before approval." if { - policy_decision == "requires_human_approval" + policy_outcome == "requires_human_approval" local_shell_analysis.fully_parsed == true } diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index 0b86534c..2f9e5cba 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -130,8 +130,8 @@ incomplete-analysis check, so updating only the producer could bypass that human-review requirement. Application adapters must preserve the returned policy guidance when presenting feedback to the agent; replacing it with a generic approval message hides the -specific analysis limitation. Decisions must still use `policy_decision`, not -matching words in the explanation. +specific analysis limitation. Applications must use the authorization response +`status`, not matching words in the explanation, to decide what happens next. **Why is `tool_arguments` beside `operation`, rather than inside it?** [`ToolCallOperation`](../../nomos/level_0/types/tool_call.py) is the compact @@ -340,22 +340,79 @@ detect every prohibited effect inside an arbitrary program; runtime isolation and host environment integrity, including inherited shell functions, remain separate controls. -## Three policy decisions +## Policy decisions and authorization status -OPA may return an explicit `policy_decision` alongside its existing boolean -`allow`. Contradictory pairs are rejected: +OPA returns a `decision` describing policy. The authorization API returns a +`status` describing what the application should do next. These are separate +boundaries: an OPA allow continues normal Council review; it does not authorize +execution by itself. -| `policy_decision` | `allow` | Meaning | +| OPA `decision` | Normal `council_authorize` response | Application action | | --- | --- | --- | -| `allow` | `true` | Continue through normal model review; not permission to execute yet. | -| `forbidden` | `false` | Block; a person cannot override this policy through the approval replay path. | -| `requires_human_approval` | `false` | Stop before execution and let the application obtain approval. | +| `allow` | Continue Council review; `approved` with a writ only if authorized. | Execute only after validating the writ. | +| `deny` | `status: denied`, no writ. | Block; human approval cannot override policy. | +| `requires_human_approval` | `status: requires_human_approval`, no writ. | Obtain application-owned human approval before proceeding. | + +The built-in OPA document also exposes the legacy `allow` boolean (`true` only +for `decision: allow`). Custom policies can return `decision` alone, a boolean, +or a legacy boolean-only `allow`/`allowed` object. If both decision and boolean +are supplied, they must agree. Invalid or contradictory responses are evaluation +errors. The obsolete `policy_decision` field is rejected rather than translated +into a human-approval request. + +At the public authorization boundary, **`status` is the sole outcome field**: +`approved`, `denied`, `requires_human_approval`, `policy_allowed`, or `error`. +Applications must never infer approval requirements from prose, errors or other +fields. Only `requires_human_approval` requests a human. Infrastructure failures +and ordinary Council denials never become approval cards. + +For example, `cat "$TARGET"` needs human interpretation because the analyzer +cannot resolve shell variables. It returns a response like this (selected fields +shown, illustrative IDs): + +```json +{ + "status": "requires_human_approval", + "decision_id": "example-human-review", + "writ": null, + "guidance": [ + "Variable-expansion syntax ($NAME or ${NAME}) cannot be fully analyzed. Submit the intended literal command and values for a new review, or request human approval. Do not execute before approval." + ], + "error": "Human approval required by OPA policy: Variable-expansion syntax ($NAME or ${NAME}) cannot be fully analyzed." +} +``` + +`rm -rf "$TARGET"` is different: the literal `rm -rf` prefix already proves +this profile's prohibition, even though the target variable is unresolved. +Hard denial wins over the incomplete analysis. Its response instead looks like +this (selected fields, illustrative ID and guidance ordering): + +```json +{ + "status": "denied", + "decision_id": "example-policy-denial", + "writ": null, + "guidance": [ + "Safer revisions within the user's authorized goal require fresh authorization. Do not invent permissions or justification, or repeat unchanged policy-denied requests. If no compliant alternative exists, stop and ask for clarification.", + "This operation is forbidden. Do not retry it or seek human approval to override this denial." + ], + "error": "Denied by OPA policy: Recursive forced deletion is forbidden.; Variable-expansion syntax ($NAME or ${NAME}) cannot be fully analyzed." +} +``` + +Denial responses prepend general guidance about fresh authorization for safer +revisions; a human-required response does not prepend that denial advice. +Neither response permits execution. These statuses belong to +`council_authorize`; the separate proposal/workflow API retains its existing +workflow states and does not provide this host approval protocol. -Normal authorization keeps the existing `status: denied` for both forbidden -and human-required results and adds the typed `policy_decision` field. Older -clients remain closed. Applications must inspect the field, not parse guidance -or error text to decide whether to show an approval card. Neither an outage nor -an undefined decision means that human approval is required. +**Migration:** update consumers to recognize the explicit human-required status +before enabling this flow. Older clients must continue to execute only explicit +`approved` responses with valid writs. Do not translate an old service's +`status: denied` plus a former `policy_decision` field into human approval: +`denied` remains denied. Update the OPA document and its parser together; +obsolete discriminator payloads are rejected, while legacy boolean policies +remain supported. ## Recheck policy after approval @@ -378,10 +435,12 @@ result = await council.authorize( This is an inspection request, not proof that a person approved anything. It authenticates and checks permissions as usual, evaluates OPA and stops before Council review or writ minting. A successful inspection returns -`status: policy_allowed`, `policy_decision: allow`, and no writ. A human-required -inspection returns `status: denied` and `policy_decision: -requires_human_approval`; a forbidden inspection retains `status: denied` and -returns `policy_decision: forbidden` instead. +`status: policy_allowed` and no writ. A human-required inspection returns +`status: requires_human_approval`; a forbidden inspection returns +`status: denied`. Disabled, undefined or unhealthy OPA returns `status: error`. +Inspection never returns `approved`. A caller must reject an unexpected +`approved` response, including one from an older service that ignored +`policy_only`, rather than treating it as a successful policy recheck. An integrating worker may continue only after independently verifying an application-owned approval bound to the exact final operation, and only when diff --git a/nomos/nat/functions.py b/nomos/nat/functions.py index 410977c6..783adce2 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -597,21 +597,27 @@ class AuthorizeOutput(_LoadSheddingOutput): api_version: str = API_VERSION_V1 council_id: str = "" - status: str = Field( - default="denied", - description="'approved', 'denied', 'error', or inspection-only 'policy_allowed'", - ) - policy_decision: Literal["allow", "forbidden", "requires_human_approval"] | None = Field( - default=None, - description="Explicit policy outcome, when available; never inferred from error text.", + status: Literal["approved", "denied", "requires_human_approval", "policy_allowed", "error"] = ( + Field( + default="denied", + description=( + "'approved', 'denied', 'requires_human_approval', 'error', " + "or inspection-only 'policy_allowed'" + ), + ) ) writ: str | None = Field( default=None, description="Base64-encoded writ blob (only if approved)" ) writ_id: str = Field(default="", description="Writ ID for status checking") decision_id: str = Field(default="", description="Intent/decision ID") - guidance: list[str] = Field(default_factory=list, description="Guidance from council on denial") - error: str = Field(default="", description="Error message if status is 'error'") + guidance: list[str] = Field( + default_factory=list, + description="Council or policy guidance when authorization does not approve", + ) + error: str = Field( + default="", description="Reason for a denial, human-approval requirement, or error" + ) council_members: list[MemberVote] = Field(default_factory=list, description="Member votes") chairman: ChairmanInfo | None = Field(default=None, description="Chairman decision") code_review: MemberVote | None = Field( @@ -2012,9 +2018,9 @@ def _dump(obj: Any) -> dict[str, Any] | None: "reason": "; ".join(getattr(opa_decision, "reasons", []) or []), } - explicit_policy_decision = getattr(opa_decision, "policy_decision", None) - if explicit_policy_decision is not None: - opa_block["policy_decision"] = explicit_policy_decision + explicit_policy_outcome = getattr(opa_decision, "decision", None) + if explicit_policy_outcome is not None: + opa_block["decision"] = explicit_policy_outcome policy_evaluation: dict[str, Any] = {} quorum: dict[str, Any] = {} @@ -3267,36 +3273,43 @@ async def authorize( error="Policy inspection requires an enabled, healthy OPA decision.", ) if opa_decision is not None and not opa_decision.allow: + # Only an explicit policy request can enter the host approval flow. + # Outages, undefined decisions and ordinary denials never do. + outcome: Literal["requires_human_approval", "denied"] = ( + "requires_human_approval" + if opa_decision.decision == "requires_human_approval" + and not opa_decision.metadata.get("evaluation_error") + and not opa_decision.metadata.get("undefined") + else "denied" + ) + policy_message = self._opa_denial_error(opa_decision) + if outcome == "requires_human_approval": + reasons = "; ".join(opa_decision.reasons) or "policy requires human approval" + policy_message = f"Human approval required by OPA policy: {reasons}" self._record_consolidated_review( intent, request_type="policy_only" if input_data.policy_only else "authorize", - final_state=WorkflowState.DENIED.value, - decision=opa_decision.policy_decision or "deny", + final_state=outcome, + decision=opa_decision.decision or "deny", opa_decision=opa_decision, force_record=self._settings.opa.policy_id == "local-bash", - denial_reason=self._opa_denial_error(opa_decision), + denial_reason=policy_message, ) _stage(stages, tool, "total", total_start, intent_id=intent.intent_id) self._publish_latency( tool=tool, intent_id=intent.intent_id, - outcome="denied", + outcome=outcome, stages=stages, actors=actors, ) return AuthorizeOutput( api_version=input_data.api_version, council_id=effective_council_id, - status="denied", + status=outcome, decision_id=intent.intent_id, - error=self._opa_denial_error(opa_decision), + error=policy_message, guidance=self._opa_denial_guidance(opa_decision), - policy_decision=( - None - if opa_decision.metadata.get("evaluation_error") - or opa_decision.metadata.get("undefined") - else opa_decision.policy_decision or "forbidden" - ), ) if input_data.policy_only: @@ -3313,7 +3326,6 @@ async def authorize( api_version=input_data.api_version, council_id=effective_council_id, status="policy_allowed", - policy_decision="allow", decision_id=intent.intent_id, ) diff --git a/nomos/opa/client.py b/nomos/opa/client.py index c414089b..7c635e93 100644 --- a/nomos/opa/client.py +++ b/nomos/opa/client.py @@ -26,14 +26,18 @@ class OPAEvaluationError(RuntimeError): @dataclass(frozen=True) class OPAPolicyDecision: - """Normalized OPA policy decision.""" + """Normalized OPA policy decision, distinct from authorization API status. + + Only an explicit ``decision="requires_human_approval"`` requests a human. + Legacy boolean-only policies leave ``decision`` unset and cannot request one. + """ allow: bool reasons: list[str] = field(default_factory=list) guidance: list[str] = field(default_factory=list) decision_id: str = "" metadata: dict[str, Any] = field(default_factory=dict) - policy_decision: Literal["allow", "forbidden", "requires_human_approval"] | None = None + decision: Literal["allow", "deny", "requires_human_approval"] | None = None class OPAHttpClient: @@ -99,23 +103,38 @@ def parse_opa_decision(payload: Mapping[str, Any]) -> OPAPolicyDecision: if not isinstance(result, Mapping): raise OPAEvaluationError("OPA result must be a boolean or object") + # The explicit outcome is authoritative. Legacy boolean-only policies remain + # usable, but obsolete or contradictory discriminators must fail closed. + if "policy_decision" in result: + raise OPAEvaluationError("OPA policy_decision is obsolete; use decision") + decision = result.get("decision") + if "decision" in result and decision not in ("allow", "deny", "requires_human_approval"): + raise OPAEvaluationError("OPA decision is invalid") + has_allow = "allow" in result or "allowed" in result + for key in ("allow", "allowed"): + if key in result and not isinstance(result[key], bool): + raise OPAEvaluationError(f"OPA {key} must be boolean") + if "allow" in result and "allowed" in result and result["allow"] != result["allowed"]: + raise OPAEvaluationError("OPA allow contradicts allowed") allow = result.get("allow", result.get("allowed")) - if not isinstance(allow, bool): - raise OPAEvaluationError("OPA result object must include boolean 'allow'") - - policy_decision = result.get("policy_decision") - if policy_decision is not None: - if policy_decision not in ("allow", "forbidden", "requires_human_approval"): - raise OPAEvaluationError("OPA policy_decision is invalid") - if allow != (policy_decision == "allow"): - raise OPAEvaluationError("OPA allow contradicts policy_decision") + if decision is not None: + expected_allow = decision == "allow" + if has_allow and allow != expected_allow: + raise OPAEvaluationError("OPA allow contradicts decision") + allow = expected_allow + elif not has_allow: + raise OPAEvaluationError("OPA result object must include decision or boolean allow") reasons = _string_list(result.get("reasons")) reason = result.get("reason") if isinstance(reason, str) and reason.strip(): reasons.append(reason.strip()) if not allow and not reasons: - reasons.append("OPA policy denied the intent") + reasons.append( + "OPA policy requires human approval" + if decision == "requires_human_approval" + else "OPA policy denied the intent" + ) guidance = _string_list(result.get("guidance")) metadata = result.get("metadata", {}) @@ -128,7 +147,7 @@ def parse_opa_decision(payload: Mapping[str, Any]) -> OPAPolicyDecision: guidance=guidance, decision_id=decision_id, metadata=metadata, - policy_decision=policy_decision, + decision=decision, ) diff --git a/policies/intent_filter.rego b/policies/intent_filter.rego index da8d89af..31b524b9 100644 --- a/policies/intent_filter.rego +++ b/policies/intent_filter.rego @@ -14,7 +14,7 @@ allow if { decision := { "allow": allow, - "policy_decision": policy_decision, + "decision": policy_outcome, "reasons": reasons, "guidance": guidance, "metadata": { @@ -244,7 +244,7 @@ remediation contains "Use a public interface for keys/secrets or narrow the targ # Hard denial wins over any request for human review. Human approval does not # override a forbidden operation; policy inspection on replay evaluates again. -policy_decision := "forbidden" if count(deny) > 0 +policy_outcome := "deny" if count(deny) > 0 else := "requires_human_approval" if count(human_review) > 0 @@ -320,17 +320,17 @@ else := "The shell command was not fully parsed." # A known prohibition must never invite resubmission or a human override. remediation contains "This operation is forbidden. Do not retry it or seek human approval to override this denial." if { policy_id == "local-bash" - policy_decision == "forbidden" + policy_outcome == "deny" } remediation contains sprintf("%s Submit the intended literal command and values for a new review, or request human approval. Do not execute before approval.", [analysis_limitation]) if { - policy_decision == "requires_human_approval" + policy_outcome == "requires_human_approval" analysis := local_shell_analysis not analysis.fully_parsed == true } remediation contains "This operation requires human approval. Do not execute before approval." if { - policy_decision == "requires_human_approval" + policy_outcome == "requires_human_approval" local_shell_analysis.fully_parsed == true } diff --git a/tests/test_opa_client.py b/tests/test_opa_client.py index 8e536457..63712247 100644 --- a/tests/test_opa_client.py +++ b/tests/test_opa_client.py @@ -160,7 +160,7 @@ def test_parse_opa_decision_treats_undefined_as_deny(): def test_parse_opa_decision_rejects_unusable_result(): - with pytest.raises(OPAEvaluationError, match="boolean 'allow'"): + with pytest.raises(OPAEvaluationError, match="decision or boolean allow"): parse_opa_decision({"result": {"reasons": ["missing allow"]}}) diff --git a/tests/test_opa_tool_policy.py b/tests/test_opa_tool_policy.py index ce45c6b4..bfd12093 100644 --- a/tests/test_opa_tool_policy.py +++ b/tests/test_opa_tool_policy.py @@ -109,11 +109,52 @@ def test_actual_arguments_are_live_opa_input_and_do_not_change_durable_binding() @pytest.mark.parametrize( ("allow", "decision"), - [(True, "forbidden"), (True, "requires_human_approval"), (False, "allow"), (False, "unknown")], + [(True, "deny"), (True, "requires_human_approval"), (False, "allow"), (False, "unknown")], ) -def test_contradictory_policy_decisions_fail_closed(allow, decision): +def test_contradictory_decisions_fail_closed(allow, decision): with pytest.raises(OPAEvaluationError): - parse_opa_decision({"result": {"allow": allow, "policy_decision": decision}}) + parse_opa_decision({"result": {"allow": allow, "decision": decision}}) + + +@pytest.mark.parametrize("decision", ["allow", "deny", "requires_human_approval"]) +def test_explicit_opa_decision_needs_no_redundant_boolean(decision): + parsed = parse_opa_decision({"result": {"decision": decision}}) + assert parsed.decision == decision + assert parsed.allow is (decision == "allow") + if decision == "requires_human_approval": + assert parsed.reasons == ["OPA policy requires human approval"] + + +@pytest.mark.parametrize("decision", ["allow", "forbidden", "requires_human_approval"]) +def test_obsolete_opa_discriminator_is_rejected(decision): + with pytest.raises(OPAEvaluationError, match="obsolete"): + parse_opa_decision({"result": {"allow": False, "policy_decision": decision}}) + + +@pytest.mark.parametrize("decision", [None, "forbidden", 1, [], {}]) +def test_invalid_explicit_opa_decision_is_rejected(decision): + with pytest.raises(OPAEvaluationError): + parse_opa_decision({"result": {"allow": False, "decision": decision}}) + + +@pytest.mark.parametrize( + "result", + [ + {"allow": True, "allowed": False}, + {"allow": False, "allowed": True}, + {"allow": True, "allowed": 1}, + {"allow": None, "allowed": False}, + {"decision": "allow", "allow": True, "allowed": False}, + ], +) +def test_invalid_or_contradictory_legacy_boolean_aliases_are_rejected(result): + with pytest.raises(OPAEvaluationError): + parse_opa_decision({"result": result}) + + +@pytest.mark.parametrize("allow", [True, False]) +def test_consistent_legacy_boolean_aliases_are_accepted(allow): + assert parse_opa_decision({"result": {"allow": allow, "allowed": allow}}).allow is allow def _request(**kwargs): @@ -123,14 +164,14 @@ def _request(**kwargs): @pytest.mark.asyncio -@pytest.mark.parametrize("decision", ["forbidden", "requires_human_approval"]) +@pytest.mark.parametrize("decision", ["deny", "requires_human_approval"]) @pytest.mark.parametrize("policy_only", [True, False]) async def test_policy_blocks_before_models_and_never_mints_writ( tmp_path, monkeypatch, decision, policy_only ): service = _make_service(tmp_path) service._opa_client = RecordingOPAClient( - OPAPolicyDecision(allow=False, policy_decision=decision, reasons=["Policy reason"]) + OPAPolicyDecision(allow=False, decision=decision, reasons=["Policy reason"]) ) async def unexpected(*args, **kwargs): @@ -138,9 +179,15 @@ async def unexpected(*args, **kwargs): monkeypatch.setattr(service, "_run_code_review", unexpected) result = await service.authorize(_request(policy_only=policy_only)) - assert result.status == "denied" - assert result.policy_decision == decision + assert result.status == ( + "requires_human_approval" if decision == "requires_human_approval" else "denied" + ) + assert "policy_decision" not in result.model_dump() assert result.writ is None + if decision == "requires_human_approval": + assert result.error.startswith("Human approval required by OPA policy:") + else: + assert result.error.startswith("Denied by OPA policy:") assert service.council.get_workflow(result.decision_id) is None @@ -155,7 +202,7 @@ async def unexpected(*args, **kwargs): monkeypatch.setattr(service, "_run_code_review", unexpected) result = await service.authorize(_request(policy_only=True)) assert result.status == "policy_allowed" - assert result.policy_decision == "allow" + assert "policy_decision" not in result.model_dump() assert result.writ is None assert service.council.get_workflow(result.decision_id) is None @@ -175,7 +222,7 @@ async def test_policy_only_never_accepts_disabled_undefined_or_unavailable_opa( service._opa_client = RecordingOPAClient(error=OPAEvaluationError("unavailable")) result = await service.authorize(_request(policy_only=True)) assert result.status == "error" - assert result.policy_decision is None + assert "policy_decision" not in result.model_dump() assert result.writ is None @@ -189,9 +236,9 @@ def test_policy_only_requires_a_boolean(): ("policy_only", "decision"), [ (True, "allow"), - (True, "forbidden"), + (True, "deny"), (True, "requires_human_approval"), - (False, "forbidden"), + (False, "deny"), (False, "requires_human_approval"), ], ) @@ -204,7 +251,7 @@ async def test_policy_outcomes_record_verdict_without_actual_arguments_in_legacy policy_id="local-bash", shell_tool_arguments={"shell.run": "command"} ) service._opa_client = RecordingOPAClient( - OPAPolicyDecision(allow=decision == "allow", policy_decision=decision) + OPAPolicyDecision(allow=decision == "allow", decision=decision) ) request = AuthorizeInput( agent_id="agent-1", @@ -226,7 +273,7 @@ async def test_policy_outcomes_record_verdict_without_actual_arguments_in_legacy ] assert len(reviews) == 1 assert reviews[0].payload["request_type"] == ("policy_only" if policy_only else "authorize") - assert reviews[0].payload["opa"]["policy_decision"] == decision + assert reviews[0].payload["opa"]["decision"] == decision assert reviews[0].payload["chairman"] == {} assert reviews[0].payload["quorum"] == {} assert "private-argument-marker" not in json.dumps(reviews[0].payload) @@ -238,7 +285,7 @@ async def test_normal_fail_closed_error_does_not_claim_a_policy_prohibition(tmp_ service._opa_client = RecordingOPAClient(error=OPAEvaluationError("unavailable")) result = await service.authorize(_request()) assert result.status == "denied" # Preserve the existing fail-closed API. - assert result.policy_decision is None + assert "policy_decision" not in result.model_dump() @pytest.mark.parametrize( @@ -255,36 +302,36 @@ async def test_normal_fail_closed_error_does_not_claim_a_policy_prohibition(tmp_ ("'/workspace/build tools/test runner' --quick", "allow"), ("/usr/local/bin/custom-tool hello", "allow"), ("/opt/tools/echo hello", "allow"), - ("rm -rf directory", "forbidden"), - ("/bin/rm -fr directory", "forbidden"), - ("/workspace/build/rm -rf output", "forbidden"), - ("./build/rm -rf output", "forbidden"), - ("'./build tools/rm' -rf output", "forbidden"), + ("rm -rf directory", "deny"), + ("/bin/rm -fr directory", "deny"), + ("/workspace/build/rm -rf output", "deny"), + ("./build/rm -rf output", "deny"), + ("'./build tools/rm' -rf output", "deny"), ("./build/rm -- -rf", "requires_human_approval"), - ("rm -rf output " + "a " * 5000, "forbidden"), - ("sudo " + "a" * 16400, "forbidden"), - ("sudo id 'unterminated", "forbidden"), - ("rm -r -f directory", "forbidden"), - ("rm -rf *", "forbidden"), - ("rm -rf /tmp/*", "forbidden"), - ('rm -rf "$TARGET"', "forbidden"), + ("rm -rf output " + "a " * 5000, "deny"), + ("sudo " + "a" * 16400, "deny"), + ("sudo id 'unterminated", "deny"), + ("rm -r -f directory", "deny"), + ("rm -rf *", "deny"), + ("rm -rf /tmp/*", "deny"), + ('rm -rf "$TARGET"', "deny"), ('rm "$OPTIONS" -rf target', "requires_human_approval"), ("echo 'rm -rf *'", "requires_human_approval"), - ("rm --recursive --force directory", "forbidden"), - ("rm -R --force directory", "forbidden"), + ("rm --recursive --force directory", "deny"), + ("rm -R --force directory", "deny"), ("rm -- -rf", "requires_human_approval"), ("rm file", "requires_human_approval"), - ("sudo id", "forbidden"), - ("/usr/bin/sudo id", "forbidden"), - ("/custom/tools/sudo id", "forbidden"), - ("su - root", "forbidden"), - ("su -lc id", "forbidden"), - ("/workspace/build/su -lc id", "forbidden"), - ("su --login root", "forbidden"), + ("sudo id", "deny"), + ("/usr/bin/sudo id", "deny"), + ("/custom/tools/sudo id", "deny"), + ("su - root", "deny"), + ("su -lc id", "deny"), + ("/workspace/build/su -lc id", "deny"), + ("su --login root", "deny"), ("su root", "requires_human_approval"), - ("chmod 777 file", "forbidden"), - ("chmod -R 0777 directory", "forbidden"), - ("./build/chmod -R 0777 directory", "forbidden"), + ("chmod 777 file", "deny"), + ("chmod -R 0777 directory", "deny"), + ("./build/chmod -R 0777 directory", "deny"), ("chmod 644 777", "allow"), ("bash -lc 'rm -rf directory'", "requires_human_approval"), ("/opt/tools/bash -lc 'id'", "requires_human_approval"), @@ -306,39 +353,37 @@ async def test_normal_fail_closed_error_does_not_claim_a_policy_prohibition(tmp_ ) def test_real_opa_consumes_actual_command_analysis(command, expected): response = _evaluate_real_shell_policy(command) - assert response["policy_decision"] == expected + assert response["decision"] == expected assert response["allow"] == (expected == "allow") @pytest.mark.parametrize( ("command", "denied", "expected"), [ - ("restricted-helper task", ["restricted-helper"], "forbidden"), - ("/workspace/build/restricted-helper task", ["restricted-helper"], "forbidden"), - ("./build/restricted-helper task", ["restricted-helper"], "forbidden"), + ("restricted-helper task", ["restricted-helper"], "deny"), + ("/workspace/build/restricted-helper task", ["restricted-helper"], "deny"), + ("./build/restricted-helper task", ["restricted-helper"], "deny"), ("restricted-helper task", [], "allow"), ("Restricted-helper task", ["restricted-helper"], "allow"), ("echo restricted-helper", ["restricted-helper"], "allow"), - ("su user", ["su"], "forbidden"), - ("nohup task", ["nohup"], "forbidden"), - ("restricted-helper $TARGET", ["restricted-helper"], "forbidden"), - ("restricted-helper 'unterminated", ["restricted-helper"], "forbidden"), + ("su user", ["su"], "deny"), + ("nohup task", ["nohup"], "deny"), + ("restricted-helper $TARGET", ["restricted-helper"], "deny"), + ("restricted-helper 'unterminated", ["restricted-helper"], "deny"), ("git status", ["restricted-helper"], "allow"), ], ) def test_real_opa_configured_prohibitions_precede_review(command, denied, expected): response = _evaluate_real_shell_policy(command, denied) - assert response["policy_decision"] == expected + assert response["decision"] == expected assert response["allow"] == (expected == "allow") - if expected == "forbidden": + if expected == "deny": assert any("configured shell policy" in reason for reason in response["reasons"]) @pytest.mark.parametrize("command", ['cat "$TARGET"', 'rm -rf "$TARGET"']) @pytest.mark.asyncio -async def test_agent_receives_guidance_for_the_final_policy_decision( - tmp_path, monkeypatch, command -): +async def test_agent_receives_guidance_for_the_final_decision(tmp_path, monkeypatch, command): response = _evaluate_real_shell_policy(command) decision = parse_opa_decision({"result": response}) service = _make_service(tmp_path) @@ -349,19 +394,22 @@ async def unexpected(*args, **kwargs): monkeypatch.setattr(service, "_run_code_review", unexpected) result = await service.authorize(_request()) - assert result.status == "denied" + assert result.status == ( + "requires_human_approval" if response["decision"] == "requires_human_approval" else "denied" + ) assert result.writ is None - assert result.policy_decision == response["policy_decision"] - # The response also prepends the existing general retry-safety guidance. + assert "policy_decision" not in result.model_dump() + # Denials prepend retry-safety advice; human requests retain approval guidance. assert set(response["guidance"]).issubset(result.guidance) guidance = " ".join(response["guidance"]) if command.startswith("rm"): - assert result.policy_decision == "forbidden" + assert result.status == "denied" assert "Do not retry" in guidance assert "Submit the intended literal" not in guidance assert "or request human approval" not in guidance else: - assert result.policy_decision == "requires_human_approval" + assert result.status == "requires_human_approval" + assert result.guidance == response["guidance"] assert "Variable-expansion" in guidance assert "Submit the intended literal" in guidance assert "Do not execute before approval" in guidance @@ -370,14 +418,14 @@ async def unexpected(*args, **kwargs): @pytest.mark.parametrize("analysis", [{"supported": True}, {"supported": False}, {}]) def test_missing_renamed_parse_flag_cannot_allow_a_command(analysis): response = _evaluate_real_shell_policy("echo hello", analysis_override=analysis) - assert response["policy_decision"] == "requires_human_approval" + assert response["decision"] == "requires_human_approval" assert response["allow"] is False assert any("not fully parsed" in reason for reason in response["reasons"]) def test_fully_parsed_command_can_still_need_human_approval(): response = _evaluate_real_shell_policy("rm note.txt") - assert response["policy_decision"] == "requires_human_approval" + assert response["decision"] == "requires_human_approval" assert response["guidance"] == [ "This operation requires human approval. Do not execute before approval." ] From 4a95ab84b143c171d1b07479cdb23ab06caf2d44 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 16:16:27 -0800 Subject: [PATCH 11/15] docs(opa): link command rules and explain wrapper review --- docs/guides/structured-tool-policy.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index 2f9e5cba..d1b81de9 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -10,6 +10,11 @@ review. This lets an operator distinguish a forbidden action from an action that needs a person's approval. A human approval never overrides a forbidden policy decision. +For the opt-in `local-bash` profile, see the [default command-policy +table](#default-local-bash-command-rules) for commands that are blocked or require +human approval. The shipped Council configuration does not enable this profile +by default. + ## Two execution paths @@ -286,6 +291,12 @@ not a complete organizational security policy. Matching depends on the static command facts described below; it does not discover commands hidden inside scripts or establish the identity of an executable's contents. +### Default local Bash command rules + +These are the bundled `local-bash` rules in +[`policies/intent_filter.rego`](../../policies/intent_filter.rego). They apply +after the profile is explicitly enabled and the tool is bound. + | Proposed command or syntax | Policy result | | --- | --- | | Executable basename listed in `opa.denied_shell_commands` | Forbidden | @@ -325,7 +336,17 @@ sufficient to allow a command. Selected command wrappers and shell inline-code invocations need human review under explicit Rego rules: their outer arguments do not describe the operation -they dispatch. These rules are not an exhaustive classifier of program effects. +they dispatch. For example, `env sudo id` has the outer executable `env`, while +`bash -lc 'rm -rf output'` has the outer executable `bash`. The analyzer does +not recursively analyze the nested command or shell program, so matching only +the outer basename would miss the inner `sudo` or `rm` operation. + +Human review for these selected forms is a conservative choice of this bundled +policy, rather than an inability to tokenize the outer invocation. It does not +mean every use of a wrapper is harmful. The profile chooses human interpretation +instead of relying only on Council review for those forms. These rules do not +recursively enforce the deny list inside arbitrary wrappers or scripts and are +not an exhaustive classifier of program effects. An opaque script can contain operations the static grammar does not recognize. A simple interpreter invocation such as `python3 script.py` can therefore proceed to Council review without its script being statically From 22cbbb0021238cd9d4a8f8f6bf5f96e05adec900 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Tue, 17 Nov 2026 16:35:14 -0800 Subject: [PATCH 12/15] fix(opa): reserve human review for explicit policy rules --- .../nomos/files/policies/intent_filter.rego | 39 -------- docs/guides/structured-tool-policy.md | 98 +++++++++---------- policies/intent_filter.rego | 39 -------- tests/test_opa_tool_policy.py | 56 ++++++----- 4 files changed, 76 insertions(+), 156 deletions(-) diff --git a/deploy/kubernetes/nomos/files/policies/intent_filter.rego b/deploy/kubernetes/nomos/files/policies/intent_filter.rego index 31b524b9..39c70328 100644 --- a/deploy/kubernetes/nomos/files/policies/intent_filter.rego +++ b/deploy/kubernetes/nomos/files/policies/intent_filter.rego @@ -305,17 +305,6 @@ deny contains "World-writable executable permissions are forbidden." if { mode[0] in {"777", "0777"} } -human_review contains analysis_limitation if { - analysis := local_shell_analysis - not analysis.fully_parsed == true -} - -analysis_limitation := object.get(local_shell_analysis, "reason", "") if { - object.get(local_shell_analysis, "reason", "") != "" -} - -else := "The shell command was not fully parsed." - # Agent-facing guidance follows the final policy verdict, not parser success. # A known prohibition must never invite resubmission or a human override. remediation contains "This operation is forbidden. Do not retry it or seek human approval to override this denial." if { @@ -323,15 +312,8 @@ remediation contains "This operation is forbidden. Do not retry it or seek human policy_outcome == "deny" } -remediation contains sprintf("%s Submit the intended literal command and values for a new review, or request human approval. Do not execute before approval.", [analysis_limitation]) if { - policy_outcome == "requires_human_approval" - analysis := local_shell_analysis - not analysis.fully_parsed == true -} - remediation contains "This operation requires human approval. Do not execute before approval." if { policy_outcome == "requires_human_approval" - local_shell_analysis.fully_parsed == true } human_review contains "Deletion requires human approval." if { @@ -344,27 +326,6 @@ human_review contains "User switching requires human approval." if { command.name == "su" } -# These selected wrappers can dispatch or evaluate another command. Parsing -# their outer argv does not describe that nested operation. This review list -# is not an exhaustive classifier of arbitrary program effects. -human_review contains "Command dispatch or evaluation requires human approval." if { - some command in local_shell_analysis.commands - command.name in {"exec", "command", "builtin", "env", "nohup", "time", "source", ".", "eval"} -} - -human_review contains "Inline shell code requires human approval." if { - some command in local_shell_analysis.commands - command.name in {"sh", "bash", "dash", "zsh", "ksh", "fish"} - some arg in option_arguments(command.argv) - inline_shell_option(arg) -} - -inline_shell_option(arg) if arg == "--command" - -inline_shell_option(arg) if startswith(arg, "--command=") - -inline_shell_option(arg) if regex.match(`^-[^-]*c`, arg) - # Option parsing stops at --. Preserve option order and do not interpret a # filename such as -rf after that delimiter as a destructive option. option_arguments(argv) := [arg | diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index d1b81de9..9477cf58 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -117,26 +117,20 @@ reason: "Variable-expansion syntax ($NAME or ${NAME}) cannot be fully analyzed." ``` The reason describes the analysis limitation without repeating argument values. -The final OPA decision supplies agent-facing guidance. For `cat "$TARGET"`, it -explains the variable-expansion limitation and asks for the intended literal -command and values for a new review, or human approval; execution must wait. -For `rm -rf "$TARGET"`, the known prefix is already forbidden, so guidance says -not to retry or seek a human override. A parsing limitation never excuses a -known prohibition. Malformed quotes, size limits, composition and other syntax -limits have distinct explanations. Conservative detection may also flag quoted -literal metacharacters because the analyzer does not retain quote provenance. - -`fully_parsed` replaces the draft field `supported`. Deploy the updated OPA -policy before updating the Nomos producer; roll back the producer first if -needed. If an analysis object lacks the new field, the updated policy requires -human review rather than treating the command as fully parsed. The reverse -pairing is unsupported: an older policy cannot enforce the renamed -incomplete-analysis check, so updating only the producer could bypass that -human-review requirement. -Application adapters must preserve the returned policy guidance when presenting -feedback to the agent; replacing it with a generic approval message hides the -specific analysis limitation. Applications must use the authorization response -`status`, not matching words in the explanation, to decide what happens next. +It does not determine whether a human is required. For `cat "$TARGET"`, OPA +continues to normal Council review of the full proposed command. For +`rm "$TARGET"`, the explicit deletion rule requires human approval regardless +of the variable; replacing it with a literal does not waive that requirement. +For `rm -rf "$TARGET"`, the known prefix is forbidden. A parsing limitation +never excuses a known prohibition. Malformed quotes, size limits, composition +and other syntax limits retain distinct diagnostic explanations. + +`fully_parsed` replaces the draft field `supported` as a diagnostic. Neither +`false` nor a missing completeness flag automatically requests HITL; explicit +policy rules decide between denial, mandatory human review and further Council +review. Conservative analysis may flag quoted literal metacharacters because +it does not retain quote provenance. Applications must use the authorization +response `status`, not explanation text or parse completeness, for routing. **Why is `tool_arguments` beside `operation`, rather than inside it?** [`ToolCallOperation`](../../nomos/level_0/types/tool_call.py) is the compact @@ -305,8 +299,8 @@ after the profile is explicitly enabled and the tool is bound. | Login `su`, including `-`, `-l`, combined `-lc`, and `--login` | Forbidden | | `chmod` setting numeric mode `777` or `0777` | Forbidden | | Other `rm` or `su` | Human approval required | -| Selected dispatch wrappers such as `env`, `exec`, `command` or `eval`, and shell inline code such as `bash -lc 'id'` | Human approval required | -| Unsupported or dynamic shell syntax | Human approval required | +| Dispatch wrappers such as `env`, `exec`, `command` or `eval`, and shell inline code such as `bash -lc 'id'` | Continue to Council review unless an explicit rule matches known facts | +| Unsupported or dynamic shell syntax, including variable expansion and bare `time` | Continue to Council review unless an explicit rule matches known facts | | Other literal invocations, including `git status`, `python3 script.py` and `./build/test --list` | Continue to Council review | This is a conservative **static grammar**, not a Bash interpreter or a sandbox. @@ -316,9 +310,11 @@ paths (`/workspace/project/build/test`) and relative paths (`./build/test`) can all be analyzed. An absolute path is not required. Relative paths are resolved by the host against the actual working directory; bare names use the host's command lookup. The analyzer does not resolve those paths or inspect executable -contents. Unsupported expansion, globbing, composition, redirection or malformed -syntax still requires human review. Some harmless quoted metacharacters may -consequently require review too. +contents. Expansion, globbing, composition, redirection and malformed syntax +can produce `fully_parsed: false`. This describes analysis coverage; it does +not impose human approval. Some harmless quoted metacharacters also produce +incomplete analysis. The full proposed command still goes to Council review +when no explicit denial or human-review rule applies. The supplied Rego rules make the command-policy decisions. They match the parsed basename, so `/workspace/project/build/rm -rf output` is subject to the @@ -328,30 +324,26 @@ behavior. A custom program, wrapper or renamed binary can perform effects its name does not reveal; a full path alone does not establish executable trust. Hard-deny rules take precedence over human-review rules. A proven literal -executable/option prefix is retained for denial only: `rm -rf *` and -`rm -rf "$TARGET"` are forbidden even though their targets need expansion. +executable/option prefix remains evidence for explicit policy rules: +`rm -rf *` and `rm -rf "$TARGET"` are forbidden even though their targets need +expansion, while `rm "$TARGET"` requires human approval. Completed words survive a later parse error or analysis limit; unfinished words are not treated as executable names or options. A retained prefix is never -sufficient to allow a command. - -Selected command wrappers and shell inline-code invocations need human review -under explicit Rego rules: their outer arguments do not describe the operation -they dispatch. For example, `env sudo id` has the outer executable `env`, while -`bash -lc 'rm -rf output'` has the outer executable `bash`. The analyzer does -not recursively analyze the nested command or shell program, so matching only -the outer basename would miss the inner `sudo` or `rm` operation. - -Human review for these selected forms is a conservative choice of this bundled -policy, rather than an inability to tokenize the outer invocation. It does not -mean every use of a wrapper is harmful. The profile chooses human interpretation -instead of relying only on Council review for those forms. These rules do not -recursively enforce the deny list inside arbitrary wrappers or scripts and are -not an exhaustive classifier of program effects. -An opaque script can contain operations the static grammar does not recognize. -A simple interpreter invocation such as `python3 script.py` can -therefore proceed to Council review without its script being statically -analyzed. OPA allowing further review is not permission to execute and does not -prove the program safe. +sufficient to authorize execution. + +Wrappers and shell inline-code invocations do not automatically require HITL. +For example, `env sudo id` has outer executable `env`, while +`bash -lc 'rm -rf output'` has outer executable `bash`. The analyzer does not +recursively analyze the nested operation, so it cannot claim that the inner +command was matched against the deny or human-review rules. Council reviews +the full proposed command. This profile does not establish that arbitrary +scripts or program effects are safe, and allowing further review does not +authorize execution. + +The bundled mandatory-human rules cover identified `rm` and non-login `su` +invocations; hard denials take precedence. There is currently no `git push` +human-review rule in this profile. The table describes the implemented rules, +not complete coverage of every deployment's required ask/deny list. Executable spelling is separate from the working directory and filesystem grants. The host still validates the actual working directory, permitted paths @@ -387,9 +379,9 @@ Applications must never infer approval requirements from prose, errors or other fields. Only `requires_human_approval` requests a human. Infrastructure failures and ordinary Council denials never become approval cards. -For example, `cat "$TARGET"` needs human interpretation because the analyzer -cannot resolve shell variables. It returns a response like this (selected fields -shown, illustrative IDs): +For example, `rm "$TARGET"` requires a human because of the explicit deletion +rule, not because the variable is unresolved. Selected response fields are shown +below with illustrative IDs: ```json { @@ -397,9 +389,9 @@ shown, illustrative IDs): "decision_id": "example-human-review", "writ": null, "guidance": [ - "Variable-expansion syntax ($NAME or ${NAME}) cannot be fully analyzed. Submit the intended literal command and values for a new review, or request human approval. Do not execute before approval." + "This operation requires human approval. Do not execute before approval." ], - "error": "Human approval required by OPA policy: Variable-expansion syntax ($NAME or ${NAME}) cannot be fully analyzed." + "error": "Human approval required by OPA policy: Deletion requires human approval." } ``` @@ -417,7 +409,7 @@ this (selected fields, illustrative ID and guidance ordering): "Safer revisions within the user's authorized goal require fresh authorization. Do not invent permissions or justification, or repeat unchanged policy-denied requests. If no compliant alternative exists, stop and ask for clarification.", "This operation is forbidden. Do not retry it or seek human approval to override this denial." ], - "error": "Denied by OPA policy: Recursive forced deletion is forbidden.; Variable-expansion syntax ($NAME or ${NAME}) cannot be fully analyzed." + "error": "Denied by OPA policy: Recursive forced deletion is forbidden.; Deletion requires human approval." } ``` diff --git a/policies/intent_filter.rego b/policies/intent_filter.rego index 31b524b9..39c70328 100644 --- a/policies/intent_filter.rego +++ b/policies/intent_filter.rego @@ -305,17 +305,6 @@ deny contains "World-writable executable permissions are forbidden." if { mode[0] in {"777", "0777"} } -human_review contains analysis_limitation if { - analysis := local_shell_analysis - not analysis.fully_parsed == true -} - -analysis_limitation := object.get(local_shell_analysis, "reason", "") if { - object.get(local_shell_analysis, "reason", "") != "" -} - -else := "The shell command was not fully parsed." - # Agent-facing guidance follows the final policy verdict, not parser success. # A known prohibition must never invite resubmission or a human override. remediation contains "This operation is forbidden. Do not retry it or seek human approval to override this denial." if { @@ -323,15 +312,8 @@ remediation contains "This operation is forbidden. Do not retry it or seek human policy_outcome == "deny" } -remediation contains sprintf("%s Submit the intended literal command and values for a new review, or request human approval. Do not execute before approval.", [analysis_limitation]) if { - policy_outcome == "requires_human_approval" - analysis := local_shell_analysis - not analysis.fully_parsed == true -} - remediation contains "This operation requires human approval. Do not execute before approval." if { policy_outcome == "requires_human_approval" - local_shell_analysis.fully_parsed == true } human_review contains "Deletion requires human approval." if { @@ -344,27 +326,6 @@ human_review contains "User switching requires human approval." if { command.name == "su" } -# These selected wrappers can dispatch or evaluate another command. Parsing -# their outer argv does not describe that nested operation. This review list -# is not an exhaustive classifier of arbitrary program effects. -human_review contains "Command dispatch or evaluation requires human approval." if { - some command in local_shell_analysis.commands - command.name in {"exec", "command", "builtin", "env", "nohup", "time", "source", ".", "eval"} -} - -human_review contains "Inline shell code requires human approval." if { - some command in local_shell_analysis.commands - command.name in {"sh", "bash", "dash", "zsh", "ksh", "fish"} - some arg in option_arguments(command.argv) - inline_shell_option(arg) -} - -inline_shell_option(arg) if arg == "--command" - -inline_shell_option(arg) if startswith(arg, "--command=") - -inline_shell_option(arg) if regex.match(`^-[^-]*c`, arg) - # Option parsing stops at --. Preserve option order and do not interpret a # filename such as -rf after that delimiter as a destructive option. option_arguments(argv) := [arg | diff --git a/tests/test_opa_tool_policy.py b/tests/test_opa_tool_policy.py index bfd12093..d401c7ca 100644 --- a/tests/test_opa_tool_policy.py +++ b/tests/test_opa_tool_policy.py @@ -64,7 +64,7 @@ def test_literal_command_analysis(command): "a" * 16385, ], ) -def test_opaque_or_unsupported_commands_require_interpretation(command): +def test_opaque_or_unsupported_syntax_is_not_fully_parsed(command): assert analyze_shell_command(command)["fully_parsed"] is False @@ -295,6 +295,10 @@ async def test_normal_fail_closed_error_does_not_claim_a_policy_prohibition(tmp_ ("echo 'sudo rm -rf directory'", "allow"), ("/bin/mkdir demo", "allow"), ("git status", "allow"), + ('cat "$TARGET"', "allow"), + ("time git status", "allow"), + ("/usr/bin/time git status", "allow"), + ("nohup task", "allow"), ("python3 script.py", "allow"), ("npm test", "allow"), ("/workspace/project/build/test_runner --quick", "allow"), @@ -316,7 +320,7 @@ async def test_normal_fail_closed_error_does_not_claim_a_policy_prohibition(tmp_ ("rm -rf /tmp/*", "deny"), ('rm -rf "$TARGET"', "deny"), ('rm "$OPTIONS" -rf target', "requires_human_approval"), - ("echo 'rm -rf *'", "requires_human_approval"), + ("echo 'rm -rf *'", "allow"), ("rm --recursive --force directory", "deny"), ("rm -R --force directory", "deny"), ("rm -- -rf", "requires_human_approval"), @@ -333,22 +337,22 @@ async def test_normal_fail_closed_error_does_not_claim_a_policy_prohibition(tmp_ ("chmod -R 0777 directory", "deny"), ("./build/chmod -R 0777 directory", "deny"), ("chmod 644 777", "allow"), - ("bash -lc 'rm -rf directory'", "requires_human_approval"), - ("/opt/tools/bash -lc 'id'", "requires_human_approval"), - ("bash --command=id", "requires_human_approval"), + ("bash -lc 'rm -rf directory'", "allow"), + ("/opt/tools/bash -lc 'id'", "allow"), + ("bash --command=id", "allow"), ("bash -- -c", "allow"), ("echo --command=id", "allow"), - ("exec /bin/rm -rf output", "requires_human_approval"), - ("command /bin/rm -rf output", "requires_human_approval"), - ("env /bin/rm -rf output", "requires_human_approval"), - ("/usr/bin/time /bin/rm -rf output", "requires_human_approval"), - ("VAR=x sudo id", "requires_human_approval"), - ("VAR+=x sudo id", "requires_human_approval"), - ("! sudo id", "requires_human_approval"), - ("time sudo id", "requires_human_approval"), + ("exec /bin/rm -rf output", "allow"), + ("command /bin/rm -rf output", "allow"), + ("env /bin/rm -rf output", "allow"), + ("/usr/bin/time /bin/rm -rf output", "allow"), + ("VAR=x sudo id", "allow"), + ("VAR+=x sudo id", "allow"), + ("! sudo id", "allow"), + ("time sudo id", "allow"), ("rm *", "requires_human_approval"), - ("echo hi; sudo id", "requires_human_approval"), - ("echo $(id)", "requires_human_approval"), + ("echo hi; sudo id", "allow"), + ("echo $(id)", "allow"), ], ) def test_real_opa_consumes_actual_command_analysis(command, expected): @@ -381,7 +385,7 @@ def test_real_opa_configured_prohibitions_precede_review(command, denied, expect assert any("configured shell policy" in reason for reason in response["reasons"]) -@pytest.mark.parametrize("command", ['cat "$TARGET"', 'rm -rf "$TARGET"']) +@pytest.mark.parametrize("command", ['rm "$TARGET"', 'rm -rf "$TARGET"']) @pytest.mark.asyncio async def test_agent_receives_guidance_for_the_final_decision(tmp_path, monkeypatch, command): response = _evaluate_real_shell_policy(command) @@ -390,7 +394,7 @@ async def test_agent_receives_guidance_for_the_final_decision(tmp_path, monkeypa service._opa_client = RecordingOPAClient(decision) async def unexpected(*args, **kwargs): - pytest.fail("Incomplete or forbidden commands must not reach Council review") + pytest.fail("Explicit human requirements and denials must not reach Council review") monkeypatch.setattr(service, "_run_code_review", unexpected) result = await service.authorize(_request()) @@ -402,7 +406,7 @@ async def unexpected(*args, **kwargs): # Denials prepend retry-safety advice; human requests retain approval guidance. assert set(response["guidance"]).issubset(result.guidance) guidance = " ".join(response["guidance"]) - if command.startswith("rm"): + if command.startswith("rm -rf"): assert result.status == "denied" assert "Do not retry" in guidance assert "Submit the intended literal" not in guidance @@ -410,17 +414,19 @@ async def unexpected(*args, **kwargs): else: assert result.status == "requires_human_approval" assert result.guidance == response["guidance"] - assert "Variable-expansion" in guidance - assert "Submit the intended literal" in guidance + assert "requires human approval" in guidance + assert "Submit the intended literal" not in guidance assert "Do not execute before approval" in guidance -@pytest.mark.parametrize("analysis", [{"supported": True}, {"supported": False}, {}]) -def test_missing_renamed_parse_flag_cannot_allow_a_command(analysis): +@pytest.mark.parametrize( + "analysis", [{"fully_parsed": False}, {"supported": True}, {"supported": False}, {}] +) +def test_parse_completeness_alone_does_not_require_human_approval(analysis): response = _evaluate_real_shell_policy("echo hello", analysis_override=analysis) - assert response["decision"] == "requires_human_approval" - assert response["allow"] is False - assert any("not fully parsed" in reason for reason in response["reasons"]) + assert response["decision"] == "allow" + assert response["allow"] is True + assert response["guidance"] == [] def test_fully_parsed_command_can_still_need_human_approval(): From e5b3ec8b4b9b4947c8feaef81dfa61534c80d599 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Wed, 18 Nov 2026 10:59:57 -0800 Subject: [PATCH 13/15] fix(opa): serialize policy audit records with submissions --- docs/guides/structured-tool-policy.md | 34 ++++++-- nomos/nat/functions.py | 48 ++++++++--- tests/test_one_to_one_ledger.py | 2 +- tests/test_opa_tool_policy.py | 112 +++++++++++++++++++++++++- tests/test_parallel_council_review.py | 8 +- 5 files changed, 178 insertions(+), 26 deletions(-) diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index 9477cf58..3d931437 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -28,22 +28,42 @@ authorization format Nomos uses. There is no separate `legacy = true` switch. | What does Nomos authorize? | A named tool with its exact JSON arguments (`tool_call`). | A shell command with its working directory. | Set this in **Relay's `plugins.toml`**, inside the Nomos plugin's existing -`[[plugins.dynamic]]` entry: +`[[plugins.dynamic]]` entry. Merge these settings into existing tables; do not +append duplicate TOML table headers. Add `shell.run` to the existing +`guard.include` list, preserving the other guarded tools, and ensure no +`guard.exclude` pattern matches it. An executor entry alone does not guard a tool. + +When adding a `tools` map, preserve every existing tool route: an explicit map +replaces the built-in map. For example, keep the shipped `run_shell` route to the +trusted Executor alongside the new application-owned `shell.run` route: ```toml +# Example additions to the existing guard (retain other includes/excludes). +[plugins.dynamic.config.guard] +include = ["run_shell", "shell.run"] + # Explicit execution route for this exact tool. [plugins.dynamic.config.tools."shell.run"] executor = "local" -# Default for guarded tools without an explicit per-tool entry. -[plugins.dynamic.config] +# Preserve the existing trusted-Executor route (including any custom fields). +[plugins.dynamic.config.tools."run_shell"] +executor = "nomos_http" +command_argument = "command" +``` + +`local` is already the default for unlisted guarded tools. If setting it +explicitly, add just this key to the **existing** `[plugins.dynamic.config]` +table, before any of its nested table headers: + +```toml default_executor = "local" ``` -`local` is already the default for unlisted guarded tools. Explicit per-tool -entries take precedence, including the shipped `run_shell` entry that uses -`nomos_http` when the `tools` configuration is omitted. These are Relay plugin -settings; the Council's OPA profile is configured separately in YAML below. +Explicit per-tool entries take precedence. The shipped `run_shell` entry uses +`nomos_http` when the `tools` configuration is omitted; keep that route unless +you intend to change who executes it. These are Relay plugin settings; the +Council's OPA profile is configured separately in YAML below. Both paths begin with JSON tool arguments in Relay. Here, **structured** means Nomos's `tool_call` authorization format. `local` means the application's diff --git a/nomos/nat/functions.py b/nomos/nat/functions.py index 589b6103..2e6d95c9 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -1914,7 +1914,7 @@ async def _commit() -> tuple[Any, list[MemberVote], Any | None, float, float]: # a terminal record: abort_vote writes the legacy # DECISION_MADE, and this writes the consolidated one. try: - self._record_consolidated_review( + self._record_consolidated_review_locked( intent, request_type=request_type, final_state=WorkflowState.FAILED.value, @@ -2031,7 +2031,27 @@ async def _continue_review_outcome( final_workflow.state if final_workflow else None, ) - def _record_consolidated_review( + async def _record_consolidated_review(self, intent: Intent, **review_fields: Any) -> None: + """Serialize final review records with submissions on single-writer ledgers. + + Submission runs in a worker thread while holding ``_submit_lock``. All + other consolidated appends must share that lock so a policy-only check + or a completed review cannot read the same ledger head concurrently. + The parallel-commit abort path already owns the lock and calls the + synchronous locked helper directly; asyncio locks are not reentrant. + Drain a started audit even if its caller is cancelled while waiting for + the writer, then propagate cancellation without issuing authorization. + """ + + async def _record() -> None: + async with self._submit_lock: + self._record_consolidated_review_locked(intent, **review_fields) + + _, cancelled = await self._shield_and_drain(asyncio.create_task(_record())) + if cancelled: + raise asyncio.CancelledError + + def _record_consolidated_review_locked( self, intent: Intent, *, @@ -2048,7 +2068,9 @@ def _record_consolidated_review( timing: dict[str, Any] | None = None, force_record: bool = False, ) -> None: - """Append a consolidated review record; policy inspections are always recorded. + """Append a consolidated review record while the caller holds ``_submit_lock``. + + Policy inspections are always recorded. Ordinary reviews remain no-ops in legacy audit mode. Policy inspection creates no workflow/intermediate events, so it needs this record in both @@ -2518,7 +2540,7 @@ async def propose_intent( ) _stage(stages, tool, "opa", stage_start, intent_id=intent.intent_id) if opa_decision is not None and not opa_decision.allow: - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="propose", final_state=WorkflowState.DENIED.value, @@ -2794,7 +2816,7 @@ async def propose_intent( # A submission error (missing justification, max-pending) is not an # accepted-and-reviewed intent → no audit entry. if result.workflow is not None and result.workflow.state == WorkflowState.DENIED: - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="propose", final_state=result.workflow.state.value, @@ -2875,7 +2897,7 @@ async def propose_intent( state_value = state.value if state else "unknown" if state in (WorkflowState.APPROVED, WorkflowState.DENIED): - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="propose", final_state=state_value, @@ -3403,7 +3425,7 @@ async def authorize( or opa_decision.metadata.get("evaluation_error") or opa_decision.metadata.get("undefined") ): - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="policy_only", final_state="policy_error", @@ -3432,7 +3454,7 @@ async def authorize( if outcome == "requires_human_approval": reasons = "; ".join(opa_decision.reasons) or "policy requires human approval" policy_message = f"Human approval required by OPA policy: {reasons}" - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="policy_only" if input_data.policy_only else "authorize", final_state=outcome, @@ -3461,7 +3483,7 @@ async def authorize( if input_data.policy_only: # No writ, model review, or execution authority: the application must # separately validate its saved human approval and final operation. - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="policy_only", final_state="policy_evaluated", @@ -3843,7 +3865,7 @@ def chairman_authorizes(decision: Any) -> bool: and workflow.evaluation_result is not None and workflow.evaluation_result.decision.decision == DecisionType.DENY ): - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="authorize", final_state=workflow.state.value, @@ -3942,7 +3964,7 @@ def chairman_authorizes(decision: Any) -> bool: guidance_parts = build_denial_guidance(votes) if deferred_cancellation: if state == WorkflowState.DENIED: - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="authorize", final_state=state.value, @@ -3979,7 +4001,7 @@ def chairman_authorizes(decision: Any) -> bool: pass if state == WorkflowState.DENIED: - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="authorize", final_state=state.value, @@ -4016,7 +4038,7 @@ def chairman_authorizes(decision: Any) -> bool: # 8. Approved → record the consolidated review BEFORE minting the writ, so # the audit entry exists even if minting fails (design: append before mint). - self._record_consolidated_review( + await self._record_consolidated_review( intent, request_type="authorize", final_state=WorkflowState.APPROVED.value, diff --git a/tests/test_one_to_one_ledger.py b/tests/test_one_to_one_ledger.py index 6c3efa19..d00dcf2a 100644 --- a/tests/test_one_to_one_ledger.py +++ b/tests/test_one_to_one_ledger.py @@ -352,7 +352,7 @@ async def test_file_mode_appends_twice_on_forced_duplicate(tmp_path, monkeypatch justification="dup", ) for _ in range(2): - service._record_consolidated_review( + await service._record_consolidated_review( intent, request_type="propose", final_state="denied", decision="deny" ) reviews = [ diff --git a/tests/test_opa_tool_policy.py b/tests/test_opa_tool_policy.py index d401c7ca..cbd75ec6 100644 --- a/tests/test_opa_tool_policy.py +++ b/tests/test_opa_tool_policy.py @@ -3,9 +3,11 @@ """Structured policy inputs and fail-closed, inspection-only authorization.""" +import asyncio import json import os import subprocess +import threading from pathlib import Path import pytest @@ -14,7 +16,8 @@ from nomos.config.settings import OPAConfig from nomos.level_0.types import Intent, ToolCallRequest from nomos.level_1.ledger.entry import LedgerEntryType -from nomos.nat.functions import AuthorizeInput +from nomos.level_1.ledger.storage import FileLedgerStorage, InMemoryLedgerStorage +from nomos.nat.functions import AuthorizeInput, ProposeIntentInput from nomos.opa import ( OPAEvaluationError, OPAPolicyDecision, @@ -207,6 +210,113 @@ async def unexpected(*args, **kwargs): assert service.council.get_workflow(result.decision_id) is None +@pytest.mark.asyncio +@pytest.mark.parametrize("storage_kind", ["memory", "file"]) +@pytest.mark.parametrize("cancel_review", [False, True]) +@pytest.mark.parametrize( + ("policy_only", "decision"), + [ + (True, "allow"), + (True, "deny"), + (True, "requires_human_approval"), + (False, "deny"), + (False, "requires_human_approval"), + ], +) +async def test_policy_audit_waits_for_inflight_submission( + tmp_path, monkeypatch, storage_kind, policy_only, decision, cancel_review +): + """Race an actual policy review against a submission holding an old ledger head.""" + service = _make_service(tmp_path) + ledger = service.council.ledger + storage = ( + FileLedgerStorage(tmp_path / "concurrent-ledger.jsonl") + if storage_kind == "file" + else InMemoryLedgerStorage() + ) + # Keep the initialized genesis and bootstrap entries when changing backends. + for entry in ledger._storage.iterate(): + storage.append(entry) + monkeypatch.setattr(ledger, "_storage", storage) + service.council.config.consolidated_review_audit = False + service._settings.opa = OPAConfig( + policy_id="local-bash", shell_tool_arguments={"shell.run": "command"} + ) + submission_paused = asyncio.Event() + review_reached_opa = asyncio.Event() + release_submission = threading.Event() + loop = asyncio.get_running_loop() + event_loop_thread = threading.get_ident() + original_build_next = ledger._build_next + + def pause_after_reading_head(head, *args, **kwargs): + if threading.get_ident() != event_loop_thread and not release_submission.is_set(): + loop.call_soon_threadsafe(submission_paused.set) + if not release_submission.wait(timeout=10): + raise TimeoutError("Test did not release the paused submission") + return original_build_next(head, *args, **kwargs) + + monkeypatch.setattr(ledger, "_build_next", pause_after_reading_head) + + class ConcurrentOPAClient(RecordingOPAClient): + async def evaluate(self, input_doc): + if input_doc["request"]["type"] in {"authorize", "policy_only"}: + review_reached_opa.set() + return OPAPolicyDecision(allow=decision == "allow", decision=decision) + return OPAPolicyDecision(allow=True) + + service._opa_client = ConcurrentOPAClient() + submission = asyncio.create_task( + service.propose_intent( + ProposeIntentInput( + agent_id="agent-1", + description="Concurrent ordinary submission", + command="/bin/echo hello", + working_directory="/tmp", + target_resource="/tmp", + justification="Exercise the real single-writer submission path", + ) + ) + ) + review = None + try: + await asyncio.wait_for(submission_paused.wait(), timeout=5) + review = asyncio.create_task(service.authorize(_request(policy_only=policy_only))) + await asyncio.wait_for(review_reached_opa.wait(), timeout=5) + # OPA has completed; the review must wait for the writer that already + # read the head, rather than append a competing entry with its sequence. + assert not review.done() + if cancel_review: + review.cancel() + finally: + release_submission.set() + tasks = [submission] + ([review] if review is not None else []) + results = await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=5) + + assert results[0].success + result = results[1] + if cancel_review: + assert isinstance(result, asyncio.CancelledError) + else: + expected = { + "allow": "policy_allowed", + "deny": "denied", + "requires_human_approval": "requires_human_approval", + }[decision] + assert result.status == expected + entries = list(storage.iterate()) + assert [entry.sequence for entry in entries] == list(range(len(entries))) + assert ledger.validate() + reviews = [e for e in entries if e.entry_type == LedgerEntryType.INTENT_REVIEW_RECORDED] + assert len(reviews) == 1 + assert reviews[0].payload["opa"]["decision"] == decision + if not cancel_review: + assert reviews[0].payload["intent_id"] == result.decision_id + if storage_kind == "file": + reloaded = FileLedgerStorage(tmp_path / "concurrent-ledger.jsonl") + assert [e.content_hash for e in reloaded.iterate()] == [e.content_hash for e in entries] + + @pytest.mark.asyncio @pytest.mark.parametrize("condition", ["disabled", "undefined", "failure"]) @pytest.mark.parametrize("fail_closed", [True, False]) diff --git a/tests/test_parallel_council_review.py b/tests/test_parallel_council_review.py index 1dcfddff..faa16d13 100644 --- a/tests/test_parallel_council_review.py +++ b/tests/test_parallel_council_review.py @@ -578,13 +578,13 @@ async def member(_intent: Intent) -> IntentEvaluation: decision=DecisionType.DENY, ) ) - original_record = service._record_consolidated_review + original_record = service._record_consolidated_review_locked def delayed_record(*args: Any, **kwargs: Any) -> None: time.sleep(0.05) original_record(*args, **kwargs) - monkeypatch.setattr(service, "_record_consolidated_review", delayed_record) + monkeypatch.setattr(service, "_record_consolidated_review_locked", delayed_record) started = time.perf_counter() result = await service.authorize( AuthorizeInput( @@ -1433,13 +1433,13 @@ async def member(_intent: Intent) -> IntentEvaluation: for member_id in ("m1", "m2", "m3"): _add_member(service, member_id, member) service._chairman = FakeChairman(chairman) # type: ignore[assignment] - original_record = service._record_consolidated_review + original_record = service._record_consolidated_review_locked def delayed_record(*args: Any, **kwargs: Any) -> None: time.sleep(0.05) original_record(*args, **kwargs) - monkeypatch.setattr(service, "_record_consolidated_review", delayed_record) + monkeypatch.setattr(service, "_record_consolidated_review_locked", delayed_record) started = time.perf_counter() result = await service.propose_intent(_proposal("delayed audit telemetry")) wall_ms = (time.perf_counter() - started) * 1000 From 247beb292065afa8094d4d9c812f156e00754f8b Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Thu, 19 Nov 2026 10:01:38 -0800 Subject: [PATCH 14/15] fix(opa): avoid repeated scans of shell option boundaries --- policies/intent_filter.rego | 11 +++-------- policies/intent_filter_test.rego | 9 +++++++++ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/policies/intent_filter.rego b/policies/intent_filter.rego index 39c70328..ccd3511d 100644 --- a/policies/intent_filter.rego +++ b/policies/intent_filter.rego @@ -329,17 +329,12 @@ human_review contains "User switching requires human approval." if { # Option parsing stops at --. Preserve option order and do not interpret a # filename such as -rf after that delimiter as a destructive option. option_arguments(argv) := [arg | + # Find the first delimiter once instead of rescanning argv for every word. + end := min(array.concat([count(argv)], [i | some i, value in argv; value == "--"])) some i, arg in argv - arg != "--" - not option_terminated(argv, i) + i < end ] -option_terminated(argv, i) if { - some j, value in argv - j < i - value == "--" -} - earlier_positional(argv, i) if { some j, value in argv j < i diff --git a/policies/intent_filter_test.rego b/policies/intent_filter_test.rego index d3ac40e3..d0e9ca48 100644 --- a/policies/intent_filter_test.rego +++ b/policies/intent_filter_test.rego @@ -6,6 +6,15 @@ package nomos.intent_test import rego.v1 import data.nomos.intent +# A filename after the first -- must never become an option, even if another +# delimiter follows. Empty and undelimited argument lists retain their order. +test_option_arguments_preserve_first_delimiter_boundary if { + intent.option_arguments([]) == [] + intent.option_arguments(["-r", "-f", "output"]) == ["-r", "-f", "output"] + intent.option_arguments(["--", "-rf"]) == [] + intent.option_arguments(["-r", "--", "-f", "--"]) == ["-r"] +} + base_intent := { "intent_id": "intent-test", "agent_id": "agent-1", From 418341d5a9274bdbe0f8865cb59d8aa928c1a5ef Mon Sep 17 00:00:00 2001 From: Nathan Watson Date: Thu, 19 Nov 2026 11:38:00 -0800 Subject: [PATCH 15/15] feat(opa): expose configured workspace context for structured tools (#163) * feat(opa): expose configured workspace context for structured tools * test(opa): pin shipped workspace mapping defaults --- configs/council.yaml | 3 + .../nomos/files/council/council.yaml | 3 + docs/guides/structured-tool-policy.md | 72 ++++++++ nomos/config/settings.py | 24 +++ nomos/opa/client.py | 27 +++ tests/test_chairman_configuration.py | 5 +- tests/test_opa_workspace_context.py | 170 ++++++++++++++++++ 7 files changed, 302 insertions(+), 2 deletions(-) create mode 100644 tests/test_opa_workspace_context.py diff --git a/configs/council.yaml b/configs/council.yaml index 7a0772de..eb58c686 100644 --- a/configs/council.yaml +++ b/configs/council.yaml @@ -261,6 +261,9 @@ opa: # Requires policy_id: local-bash and an explicit shell_tool_arguments binding. # Empty adds no prohibitions beyond the bundled policy rules. denied_shell_commands: [] + # Optional exact tool -> top-level argument key for a host-declared root. + # Exposes intent.workspace to OPA; does not establish trust or containment. + workspace_arguments: {} timeout_ms: "${COUNCIL_OPA_TIMEOUT_MS:-500}" fail_closed: "${COUNCIL_OPA_FAIL_CLOSED:-true}" diff --git a/deploy/kubernetes/nomos/files/council/council.yaml b/deploy/kubernetes/nomos/files/council/council.yaml index 7a0772de..eb58c686 100644 --- a/deploy/kubernetes/nomos/files/council/council.yaml +++ b/deploy/kubernetes/nomos/files/council/council.yaml @@ -261,6 +261,9 @@ opa: # Requires policy_id: local-bash and an explicit shell_tool_arguments binding. # Empty adds no prohibitions beyond the bundled policy rules. denied_shell_commands: [] + # Optional exact tool -> top-level argument key for a host-declared root. + # Exposes intent.workspace to OPA; does not establish trust or containment. + workspace_arguments: {} timeout_ms: "${COUNCIL_OPA_TIMEOUT_MS:-500}" fail_closed: "${COUNCIL_OPA_FAIL_CLOSED:-true}" diff --git a/docs/guides/structured-tool-policy.md b/docs/guides/structured-tool-policy.md index 3d931437..ed94866f 100644 --- a/docs/guides/structured-tool-policy.md +++ b/docs/guides/structured-tool-policy.md @@ -168,6 +168,78 @@ value is `"tool_call"`; legacy shell requests use `operation: null`, not `kind: shell`. The kind does not identify the tool or its executor: `tool_name` names the tool, and the Relay configuration selects its execution route. +### Optional workspace context for structured tools + +Different hosts use different argument names for their workspace root. A policy +should not need to know each host's spelling. In the Council deployment's +`council.yaml`, map exact tool names to the **top-level JSON argument key** +containing that root: + +```yaml +opa: + workspace_arguments: + shell.run: project_root + file.write: workspace_dir +``` + +Merge this into the existing `opa` section. The default is `{}`, so no tools are +mapped automatically. Keys are literal, not glob patterns or dotted lookups. +For example, `scope.root` selects a top-level property named `scope.root`. +The mapping applies under every policy profile, independently of +`shell_tool_arguments`; it does not select a policy or guard additional tools. + +**Before mapping**, OPA sees the host's original arguments only: + +```yaml +intent: + tool_arguments: + command: chmod 600 notes.txt + cwd: /projects/demo/src + project_root: /projects/demo +``` + +**After mapping**, the same arguments remain intact and a generic field is added: + +```yaml +intent: + workspace: /projects/demo + tool_arguments: + command: chmod 600 notes.txt + cwd: /projects/demo/src + project_root: /projects/demo +``` + +These are abbreviated fragments of the OPA input, not new tool-call schemas. +`workspace` means the host-declared filesystem root for this invocation, not the +working directory. It is copied from the held, validated tool arguments; the +original payload, argument digest, Intent serialization and writ are unchanged. + +| Input case | Generic `intent.workspace` | +| --- | --- | +| Exact tool mapping and valid absolute root | The root string, preserved verbatim | +| Mapping exists, but argument is missing or invalid | `null` (unknown scope) | +| No mapping for the tool | Field omitted | +| Legacy shell / `nomos_http` request | Field omitted; no inference from `working_directory` | + +Accepted roots are nonempty absolute POSIX or Windows paths without surrounding +whitespace or control characters. Validation is syntactic: the Council service +does not inspect the host filesystem, normalize `..`, resolve symlinks or expand +variables. A policy requiring a workspace must handle omitted/null context +explicitly; neither means that the operation is inside an allowed boundary. + +**Trust belongs to the host integration.** The operator chooses which argument +to read, but that does not authenticate its value. The host must derive or +overwrite the argument from its actual authorized workspace before submitting +the tool call. An arbitrary model-supplied path cannot establish an allowed +boundary. The existing argument digest binds the submitted value, not the truth +of that assertion. Do not use the generic field as an automatic allow signal. + +This projection supplies OPA input only. It adds no path-containment rule, +target-path extraction in `shell_analysis.py`, decision-model question, Council +prompt field or HITL routing. Council already receives the original structured +arguments; exposing the same generic context to a decision model is a separate +integration step. Hosts must retain their runtime filesystem controls. + ### `executor = "nomos_http"`: command uses the legacy shell fields This example uses the existing `strict-shell` policy profile: diff --git a/nomos/config/settings.py b/nomos/config/settings.py index bcceeb90..6216d0f3 100644 --- a/nomos/config/settings.py +++ b/nomos/config/settings.py @@ -696,6 +696,15 @@ class OPAConfig(BaseModel): ), ) + workspace_arguments: dict[str, str] = Field( + default_factory=dict, + description=( + "Exact structured tool names mapped to the top-level argument containing " + "the host-declared workspace root. Exposes intent.workspace to OPA under " + "any policy profile; mapping does not authenticate the argument." + ), + ) + denied_shell_commands: list[str] = Field( default_factory=list, description=( @@ -737,6 +746,21 @@ def require_local_bash_binding(self) -> "OPAConfig": raise ValueError("local-bash requires at least one shell_tool_arguments binding") return self + @field_validator("workspace_arguments") + @classmethod + def validate_workspace_arguments(cls, value: dict[str, str]) -> dict[str, str]: + """Reject ambiguous bindings without rewriting exact JSON argument keys.""" + if any( + not item or item != item.strip() or any(unicodedata.category(c) == "Cc" for c in item) + for pair in value.items() + for item in pair + ): + raise ValueError( + "OPA workspace tool names and argument keys must be nonempty, " + "without surrounding whitespace or control characters" + ) + return value + @field_validator("enabled", "fail_closed", mode="before") @classmethod def resolve_bool_env_vars(cls, value: Any, info) -> Any: diff --git a/nomos/opa/client.py b/nomos/opa/client.py index 87f4acfe..ac8a86b8 100644 --- a/nomos/opa/client.py +++ b/nomos/opa/client.py @@ -9,10 +9,12 @@ import http.client import json import os +import unicodedata import urllib.error import urllib.request from collections.abc import Iterable, Mapping from dataclasses import dataclass, field +from pathlib import PurePosixPath, PureWindowsPath from typing import Any, Literal from nomos.config.settings import OPAConfig @@ -178,6 +180,26 @@ def parse_opa_decision(payload: Mapping[str, Any]) -> OPAPolicyDecision: ) +def _workspace_root(value: Any) -> str | None: + """Accept a literal absolute host path without probing or rewriting it. + + The Council service may run on a different machine or operating system. + Accept POSIX and Windows roots, but do not expand variables, resolve symlinks + or claim containment. Null means a configured argument is missing/invalid; + a policy requiring workspace context must handle that explicitly. + """ + if ( + not isinstance(value, str) + or not value + or value != value.strip() + or any(unicodedata.category(char) == "Cc" for char in value) + ): + return None + if PurePosixPath(value).is_absolute() or PureWindowsPath(value).is_absolute(): + return value + return None + + def build_intent_filter_input( intent: Intent, *, @@ -197,6 +219,11 @@ def build_intent_filter_input( # Use the held, validated request, never a model description or digest lookup. # Keep this live input out of Intent serialization and the signed operation. tool_input["tool_arguments"] = json.loads(material.canonical_arguments()) + workspace_key = opa_config.workspace_arguments.get(material.tool_name) + if workspace_key is not None: + tool_input["workspace"] = _workspace_root( + tool_input["tool_arguments"].get(workspace_key) + ) command_key = opa_config.shell_tool_arguments.get(material.tool_name) if opa_config.policy_id == "local-bash" and command_key: tool_input["shell_analysis"] = analyze_shell_command( diff --git a/tests/test_chairman_configuration.py b/tests/test_chairman_configuration.py index d5843998..369ac7d8 100644 --- a/tests/test_chairman_configuration.py +++ b/tests/test_chairman_configuration.py @@ -362,7 +362,7 @@ def test_referenced_profile_uses_final_deep_merged_chairman( ) def test_shipped_yaml_preserves_enabled_unanimous_mode_and_all_parsed_values(relative_path): # Pin the complete shipped profile, including the intentional Nemotron 3.5 - # default migration and explicit empty shell-command deny list. + # default migration, empty shell-command deny list and workspace mapping. # Comments/formatting are intentionally ignored; the # public-config tests separately assert the model and every role's routing. root = Path(settings_module.__file__).resolve().parents[2] @@ -373,10 +373,11 @@ def test_shipped_yaml_preserves_enabled_unanimous_mode_and_all_parsed_values(rel f"enabled=true/allow_quorum=false; got {mode!r}" ) assert document["opa"]["denied_shell_commands"] == [] + assert document["opa"]["workspace_arguments"] == {} canonical = json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=True) digest = hashlib.sha256(canonical.encode()).hexdigest() # Public pinned YAML semantic SHA-256, not a credential; retain the full literal. - expected = "3c29da41b0a81d6aad441dec6e76f0215289bba57f5ae987b2455c5049d7e164" # pragma: allowlist secret # noqa: E501 + expected = "bde1754b45264b8a8a1badaaef594eb6f894fbdfe5154e59e16e207dd49ad005" # pragma: allowlist secret # noqa: E501 assert digest == expected, ( f"given={relative_path!r}: all parsed release-template values must match pinned base; " f"expected semantic SHA-256 {expected}, got {digest}" diff --git a/tests/test_opa_workspace_context.py b/tests/test_opa_workspace_context.py new file mode 100644 index 00000000..85162efa --- /dev/null +++ b/tests/test_opa_workspace_context.py @@ -0,0 +1,170 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Workspace projection is explicit, profile-independent and review-only.""" + +import pytest +from pydantic import ValidationError + +from nomos.config.settings import OPAConfig +from nomos.level_0.types import Intent, ToolCallRequest +from nomos.nat.functions import AuthorizeInput +from nomos.opa import OPAPolicyDecision, build_intent_filter_input +from tests.test_opa_nat_integration import RecordingOPAClient, _make_service + + +def _intent(arguments, tool_name="shell.run"): + material = ToolCallRequest(tool_name=tool_name, arguments=arguments, subject="user-1") + intent = Intent.create( + agent_id="agent-1", + description="Review a workspace operation", + target_resource=tool_name, + command_type="api", + operation=material.to_operation(), + ) + intent._tool_review_material = material + return intent + + +def _input(intent, config): + return build_intent_filter_input( + intent, request_type="authorize", authenticated=True, opa_config=config + ) + + +@pytest.mark.parametrize("profile", ["strict-shell", "read-only-relaxed", "local-bash"]) +@pytest.mark.parametrize( + ("tool", "key"), [("shell.run", "project_root"), ("file.write", "scope.root")] +) +def test_workspace_uses_exact_binding_without_changing_arguments_or_intent(profile, tool, key): + """A model-facing workspace spelling cannot replace the configured argument.""" + intent = _intent( + { + "command": "echo hello", + key: "/projects/demo", + "workspace": "/", + "cwd": "/projects/demo/src", + }, + tool, + ) + before = intent.model_dump(mode="json") + config = OPAConfig( + policy_id=profile, + shell_tool_arguments={tool: "command"} if profile == "local-bash" else {}, + workspace_arguments={tool: key}, + ) + result = _input(intent, config)["intent"] + assert result["workspace"] == "/projects/demo" + assert result["tool_arguments"] == intent._tool_review_material.arguments + assert result["tool_arguments"]["workspace"] == "/" + assert result["tool_arguments"]["cwd"] == "/projects/demo/src" + assert result["working_directory"] == "" + assert intent.model_dump(mode="json") == before + assert "workspace" not in before + assert ("shell_analysis" in result) is (profile == "local-bash") + + +@pytest.mark.parametrize( + "root", + ["/", "/projects/demo", "/projects/demo/../other", r"C:\Projects\demo", r"\\server\share\demo"], +) +def test_absolute_workspace_paths_are_preserved_without_filesystem_resolution(root): + result = _input(_intent({"root": root}), OPAConfig(workspace_arguments={"shell.run": "root"})) + assert result["intent"]["workspace"] == root + + +@pytest.mark.parametrize( + "value", + [ + None, + "", + "relative/root", + "~/project", + "$PROJECT", + " /project", + "/project ", + "/bad\x00root", + "/bad\nroot", + True, + 12, + [], + {}, + ], +) +def test_invalid_workspace_is_explicitly_unknown_not_a_cwd_fallback(value): + result = _input( + _intent({"root": value, "cwd": "/projects/demo", "workspace": "/forged"}), + OPAConfig(workspace_arguments={"shell.run": "root"}), + ) + assert "workspace" in result["intent"] + assert result["intent"]["workspace"] is None + + +def test_missing_mapped_argument_is_explicitly_unknown(): + result = _input(_intent({}), OPAConfig(workspace_arguments={"shell.run": "root"})) + assert result["intent"]["workspace"] is None + + +@pytest.mark.parametrize("bindings", [{}, {"other.tool": "root"}, {"shell.*": "root"}]) +def test_unconfigured_tools_do_not_acquire_workspace_context(bindings): + assert OPAConfig().workspace_arguments == {} + intent = _intent({"root": "/projects/demo", "workspace": "/forged"}) + result = _input(intent, OPAConfig(workspace_arguments=bindings)) + assert result == _input(intent, OPAConfig()) + assert "workspace" not in result["intent"] + + +def test_legacy_shell_input_does_not_infer_a_workspace_from_cwd_or_description(): + intent = Intent.create( + agent_id="agent-1", + command="/bin/echo hello", + working_directory="/projects/demo", + target_resource="/projects/demo", + description="Work inside /projects/demo", + ) + result = _input(intent, OPAConfig(workspace_arguments={"shell.run": "root"})) + assert result == _input(intent, OPAConfig()) + assert "workspace" not in result["intent"] + + +@pytest.mark.parametrize( + "bindings", + [ + {"": "root"}, + {"shell.run": ""}, + {"shell.run ": "root"}, + {"shell.run": " root"}, + {"shell.run": "root\n"}, + ], +) +def test_workspace_configuration_rejects_ambiguous_keys(bindings): + with pytest.raises(ValidationError, match="workspace tool names"): + OPAConfig(workspace_arguments=bindings) + + +@pytest.mark.asyncio +async def test_policy_only_authorization_receives_workspace_without_minting_a_writ(tmp_path): + """Exercise the service handoff, not just the input-builder helper.""" + service = _make_service(tmp_path) + service._settings.opa.workspace_arguments = {"shell.run": "project_root"} + opa = RecordingOPAClient(OPAPolicyDecision(allow=True)) + service._opa_client = opa + result = await service.authorize( + AuthorizeInput( + agent_id="agent-1", + council_id=service.council_id, + description="Review the selected workspace", + justification="Exercise structured policy inspection", + policy_only=True, + tool_call=ToolCallRequest( + tool_name="shell.run", + subject="user-1", + arguments={"command": "echo hello", "project_root": "/projects/demo"}, + ), + ) + ) + assert result.status == "policy_allowed", result.error + assert result.writ is None + assert len(opa.calls) == 1 + assert opa.calls[0]["intent"]["workspace"] == "/projects/demo" + assert opa.calls[0]["request"]["type"] == "policy_only"