diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index afee6cf9..32a804df 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/configs/council.yaml b/configs/council.yaml index d598b04a..f9e896cd 100644 --- a/configs/council.yaml +++ b/configs/council.yaml @@ -262,6 +262,14 @@ 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: [] + # 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 d598b04a..f9e896cd 100644 --- a/deploy/kubernetes/nomos/files/council/council.yaml +++ b/deploy/kubernetes/nomos/files/council/council.yaml @@ -262,6 +262,14 @@ 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: [] + # 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/policies/intent_filter.rego b/deploy/kubernetes/nomos/files/policies/intent_filter.rego index b286afa1..39c70328 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, + "decision": policy_outcome, "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,111 @@ 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_outcome := "deny" 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" + +# 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" + 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"} +} + +# 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_outcome == "deny" +} + +remediation contains "This operation requires human approval. Do not execute before approval." if { + policy_outcome == "requires_human_approval" +} + +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..ed94866f --- /dev/null +++ b/docs/guides/structured-tool-policy.md @@ -0,0 +1,578 @@ + + +# 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. + +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 + +Each Relay tool's `executor` selects where an approved operation runs and which +authorization format Nomos uses. There is no separate `legacy = true` switch. + +| Question | `executor = "local"` | `executor = "nomos_http"` | +| --- | --- | --- | +| 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. 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" + +# 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" +``` + +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 +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: + fully_parsed: true + commands: + - executable: /bin/echo + 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. + +`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. +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 +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. + +### 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: + +```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 +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. + +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 inside `input.intent` | `local` example | `nomos_http` example | +| --- | --- | --- | +| `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. + +
+ +### 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 +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 + denied_shell_commands: + - restricted-helper +``` + +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. + +`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. + +### 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 | +| 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 | +| 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. +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. 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 +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 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 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 +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. + +## Policy decisions and authorization status + +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. + +| OPA `decision` | Normal `council_authorize` response | Application action | +| --- | --- | --- | +| `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, `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 +{ + "status": "requires_human_approval", + "decision_id": "example-human-review", + "writ": null, + "guidance": [ + "This operation requires human approval. Do not execute before approval." + ], + "error": "Human approval required by OPA policy: Deletion requires human approval." +} +``` + +`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.; Deletion requires human approval." +} +``` + +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. + +**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 + +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` 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 +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 18ef1e5e..64fd5f79 100644 --- a/docs/index.md +++ b/docs/index.md @@ -56,6 +56,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 2d6a67ee..81e133c9 100644 --- a/nomos/config/settings.py +++ b/nomos/config/settings.py @@ -12,6 +12,7 @@ import logging import math import os +import unicodedata from enum import StrEnum from itertools import pairwise from pathlib import Path @@ -751,7 +752,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( @@ -769,6 +771,79 @@ 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." + ), + ) + + 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=( + "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]: + """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("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/nat/functions.py b/nomos/nat/functions.py index c5187dc9..a9ac00fd 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -21,7 +21,7 @@ from contextvars import ContextVar from dataclasses import dataclass from pathlib import Path -from typing import Any, ClassVar, TypeVar, cast +from typing import Any, ClassVar, Literal, TypeVar, cast import anyio import httpx @@ -681,6 +681,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" @@ -758,14 +766,27 @@ class AuthorizeOutput(_LoadSheddingOutput): api_version: str = API_VERSION_V1 council_id: str = "" - status: str = Field(default="denied", description="'approved', 'denied', or 'error'") + 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( @@ -1543,13 +1564,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 @@ -2770,9 +2791,18 @@ async def _record_consolidated_review( debate_history: list[DebateRound] | None = None, denial_reason: str = "", timing: dict[str, Any] | None = None, + force_record: bool = False, stages: dict[str, float] | None = None, ) -> None: - """Append the single Tier-1b consolidated review record (no-op in legacy mode). + """Append a final review record through the dedicated ledger thread. + + 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 @@ -2787,7 +2817,11 @@ async def _record_consolidated_review( before they go on to mint. A caller cancelled mid-append waits for the append to finish and is then cancelled, so no review ends half-recorded. """ - 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 payload = self._consolidated_review_payload( intent, @@ -2891,6 +2925,10 @@ def _dump(obj: Any) -> dict[str, Any] | None: "reason": "; ".join(getattr(opa_decision, "reasons", []) or []), } + 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] = {} approved_at = denied_at = None @@ -4347,40 +4385,93 @@ 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") + ): + await self._record_consolidated_review( + intent, + stages=stages, + 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: + # 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}" await self._record_consolidated_review( intent, stages=stages, - request_type="authorize", - final_state=WorkflowState.DENIED.value, - decision="deny", + request_type="policy_only" if input_data.policy_only else "authorize", + final_state=outcome, + decision=opa_decision.decision or "deny", opa_decision=opa_decision, - denial_reason=self._opa_denial_error(opa_decision), + force_record=self._settings.opa.policy_id == "local-bash", + 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), ) + if input_data.policy_only: + # No writ, model review, or execution authority: the application must + # separately validate its saved human approval and final operation. + await self._record_consolidated_review( + intent, + stages=stages, + 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", + decision_id=intent.intent_id, + ) + # System one (member zero): after OPA, before council. Its vector feeds the # chairman and the council prompt, and may fast-path a read-only intent. stage_start = time.perf_counter() diff --git a/nomos/opa/client.py b/nomos/opa/client.py index dae7315c..264fafcb 100644 --- a/nomos/opa/client.py +++ b/nomos/opa/client.py @@ -12,9 +12,11 @@ import re import ssl import time +import unicodedata from collections.abc import Iterable, Mapping from dataclasses import dataclass, field -from typing import Any +from pathlib import PurePosixPath, PureWindowsPath +from typing import Any, Literal from urllib.parse import urlparse import anyio @@ -24,6 +26,7 @@ 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 from nomos_runtime import ( ClientTLSConfig, TLSConfigurationError, @@ -40,13 +43,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) + decision: Literal["allow", "deny", "requires_human_approval"] | None = None class OPAHttpClient: @@ -309,6 +317,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): @@ -321,16 +330,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'") + 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", {}) @@ -343,9 +374,30 @@ def parse_opa_decision(payload: Mapping[str, Any]) -> OPAPolicyDecision: guidance=guidance, decision_id=decision_id, metadata=metadata, + decision=decision, ) +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, *, @@ -359,6 +411,22 @@ 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()) + 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( + tool_input["tool_arguments"].get(command_key) + ) return { "request": { "type": request_type, @@ -367,6 +435,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) @@ -379,6 +450,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..9bbda369 --- /dev/null +++ b/nomos/opa/shell_analysis.py @@ -0,0 +1,191 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Bounded facts about a literal simple command, not executable authorization. + +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 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(){}<>|&;*?\[\]~]") + + +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.""" + + fully_parsed: bool + commands: list[ShellCommand] + reason: str + + +class _CharacterLimitError(ValueError): + """Stop lexing before a truncated token could be mistaken for a whole word.""" + + +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. + """ + + 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 _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 + ``fully_parsed=True``. Proven literal prefixes remain available for deny-only + rules even when parsing later fails; partial words are never retained. + """ + unknown: ShellAnalysis = { + "fully_parsed": False, + "commands": [], + "reason": "A nonempty shell command string is required for analysis.", + } + 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 + 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] + name = executable.rsplit("/", 1)[-1] + if ( + not name + or executable in _RESERVED_PREFIXES + or _ASSIGNMENT.match(executable) + 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 + # 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) + fully_parsed = complete and not limitation + return { + "fully_parsed": bool(fully_parsed), + "commands": [ + { + "executable": executable, + "name": name, + "argv": words[1:] if fully_parsed else literal_prefix, + } + ], + "reason": "" if fully_parsed else unknown["reason"], + } diff --git a/policies/intent_filter.rego b/policies/intent_filter.rego index b286afa1..ccd3511d 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, + "decision": policy_outcome, "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,106 @@ 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_outcome := "deny" 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" + +# 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" + 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"} +} + +# 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_outcome == "deny" +} + +remediation contains "This operation requires human approval. Do not execute before approval." if { + policy_outcome == "requires_human_approval" +} + +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 | + # 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 + i < end +] + +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/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", diff --git a/tests/test_chairman_configuration.py b/tests/test_chairman_configuration.py index adb65df8..f00edfe2 100644 --- a/tests/test_chairman_configuration.py +++ b/tests/test_chairman_configuration.py @@ -370,7 +370,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, 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] document = yaml.safe_load((root / relative_path).read_text(encoding="utf-8")) @@ -379,11 +380,13 @@ 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"] == [] + 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. - # Re-pinned for the system_one block (member zero), which ships with every level off. - expected = "a950b1e9ff84897374bf6094f89549648de069651425ed51bfaf3e9ca2198793" # pragma: allowlist secret # noqa: E501 + # Re-pinned for system_one and the explicit empty workspace mapping. + expected = "4063c14f7662b3cf4bf36dc0d896329c1f566b55ab8ee73af64c97a4d26aa619" # 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_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 160e0716..689104f6 100644 --- a/tests/test_opa_client.py +++ b/tests/test_opa_client.py @@ -66,6 +66,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": [], } @@ -108,6 +109,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"], } @@ -163,7 +165,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_nat_integration.py b/tests/test_opa_nat_integration.py index 5e719d7d..4c6b1618 100644 --- a/tests/test_opa_nat_integration.py +++ b/tests/test_opa_nat_integration.py @@ -220,6 +220,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 new file mode 100644 index 00000000..f90ad972 --- /dev/null +++ b/tests/test_opa_tool_policy.py @@ -0,0 +1,593 @@ +# 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 asyncio +import json +import os +import subprocess +import threading +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.level_1.ledger.storage import FileLedgerStorage, InMemoryLedgerStorage +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", + "git status", + "python3 script.py", + "python -c 'pass'", + "bash -lc 'id'", + "/tmp/echo hi", + ], +) +def test_literal_command_analysis(command): + assert analyze_shell_command(command)["fully_parsed"] is True + + +@pytest.mark.parametrize( + "command", + [ + None, + "", + "echo 'unterminated", + "echo $(id)", + "echo `id`", + "echo hi; sudo id", + "cat file | head", + "rm *", + "X=1 echo hi", + "echo hi > out", + "echo hi\nid", + "echo hi &", + "echo hi\x00", + "a" * 16385, + ], +) +def test_opaque_or_unsupported_syntax_is_not_fully_parsed(command): + assert analyze_shell_command(command)["fully_parsed"] 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"] == [ + {"executable": "rm", "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, "deny"), (True, "requires_human_approval"), (False, "allow"), (False, "unknown")], +) +def test_contradictory_decisions_fail_closed(allow, decision): + with pytest.raises(OPAEvaluationError): + 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): + return AuthorizeInput( + agent_id="agent-1", command="/bin/echo hello", working_directory="/tmp", **kwargs + ) + + +@pytest.mark.asyncio +@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, decision=decision, reasons=["Policy reason"]) + ) + + async def unexpected(*args, **kwargs): + pytest.fail("Model review must not run") + + monkeypatch.setattr(service, "_run_code_review", unexpected) + monkeypatch.setattr(service, "_run_pre_council_filter", unexpected) + result = await service.authorize(_request(policy_only=policy_only)) + 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 + + +@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) + monkeypatch.setattr(service, "_run_pre_council_filter", unexpected) + result = await service.authorize(_request(policy_only=True)) + assert result.status == "policy_allowed" + assert "policy_decision" not in result.model_dump() + assert result.writ is None + 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_review( + tmp_path, monkeypatch, storage_kind, policy_only, decision, cancel_review +): + """Queue policy outcomes behind an in-flight audit on the ledger thread. + + Current services keep workflow mutation on the event loop and serialize final + appends on a dedicated thread. File-backed services require consolidated + auditing; in-memory legacy mode still records explicit policy inspections. + """ + 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 = storage_kind == "file" + service._settings.opa = OPAConfig( + policy_id="local-bash", shell_tool_arguments={"shell.run": "command"} + ) + append_paused = asyncio.Event() + review_reached_opa = asyncio.Event() + release_append = 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_append.is_set(): + loop.call_soon_threadsafe(append_paused.set) + if not release_append.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): + evaluations = 0 + + async def evaluate(self, input_doc): + self.evaluations += 1 + if self.evaluations == 1: + return OPAPolicyDecision(allow=True, decision="allow") + review_reached_opa.set() + return OPAPolicyDecision(allow=decision == "allow", decision=decision) + + service._opa_client = ConcurrentOPAClient() + first_review = asyncio.create_task(service.authorize(_request(policy_only=True))) + review = None + try: + await asyncio.wait_for(append_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_append.set() + tasks = [first_review] + ([review] if review is not None else []) + results = await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=5) + + assert results[0].status == "policy_allowed" + 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) == 2 + assert reviews[0].payload["opa"]["decision"] == "allow" + assert reviews[1].payload["opa"]["decision"] == decision + if not cancel_review: + assert reviews[1].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]) +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 "policy_decision" not in result.model_dump() + 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, "deny"), + (True, "requires_human_approval"), + (False, "deny"), + (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", 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"]["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 "policy_decision" not in result.model_dump() + + +@pytest.mark.parametrize( + ("command", "expected"), + [ + ("echo hello", "allow"), + ("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"), + ("./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", "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, "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 *'", "allow"), + ("rm --recursive --force directory", "deny"), + ("rm -R --force directory", "deny"), + ("rm -- -rf", "requires_human_approval"), + ("rm file", "requires_human_approval"), + ("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", "deny"), + ("chmod -R 0777 directory", "deny"), + ("./build/chmod -R 0777 directory", "deny"), + ("chmod 644 777", "allow"), + ("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", "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", "allow"), + ("echo $(id)", "allow"), + ], +) +def test_real_opa_consumes_actual_command_analysis(command, expected): + response = _evaluate_real_shell_policy(command) + assert response["decision"] == expected + assert response["allow"] == (expected == "allow") + + +@pytest.mark.parametrize( + ("command", "denied", "expected"), + [ + ("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"], "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["decision"] == expected + assert response["allow"] == (expected == "allow") + if expected == "deny": + assert any("configured shell policy" in reason for reason in response["reasons"]) + + +@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) + decision = parse_opa_decision({"result": response}) + service = _make_service(tmp_path) + service._opa_client = RecordingOPAClient(decision) + + async def unexpected(*args, **kwargs): + pytest.fail("Explicit human requirements and denials must not reach Council review") + + monkeypatch.setattr(service, "_run_code_review", unexpected) + monkeypatch.setattr(service, "_run_pre_council_filter", unexpected) + result = await service.authorize(_request()) + assert result.status == ( + "requires_human_approval" if response["decision"] == "requires_human_approval" else "denied" + ) + assert result.writ is None + 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 -rf"): + 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.status == "requires_human_approval" + assert result.guidance == response["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", [{"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"] == "allow" + assert response["allow"] is True + assert response["guidance"] == [] + + +def test_fully_parsed_command_can_still_need_human_approval(): + response = _evaluate_real_shell_policy("rm note.txt") + assert response["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") + 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"}, + denied_shell_commands=list(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( + [ + 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, + ) + return json.loads(completed.stdout)["result"][0]["expressions"][0]["value"] 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" diff --git a/tests/test_shell_analysis.py b/tests/test_shell_analysis.py new file mode 100644 index 00000000..1c3608be --- /dev/null +++ b/tests/test_shell_analysis.py @@ -0,0 +1,224 @@ +# 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["fully_parsed"] 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)["fully_parsed"] 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["fully_parsed"] 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["fully_parsed"] 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["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["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["fully_parsed"] is True + assert len(result["commands"][0]["argv"]) == MAX_COMMAND_WORDS - 1 + beyond = analyze_shell_command(command + "a") + assert beyond["fully_parsed"] 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["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"]