Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions configs/council.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ opa:
# Requires policy_id: local-bash and an explicit shell_tool_arguments binding.
# Empty adds no prohibitions beyond the bundled policy rules.
denied_shell_commands: []
# Optional exact tool -> top-level argument key for a host-declared root.
# Exposes intent.workspace to OPA; does not establish trust or containment.
workspace_arguments: {}
timeout_ms: "${COUNCIL_OPA_TIMEOUT_MS:-500}"
fail_closed: "${COUNCIL_OPA_FAIL_CLOSED:-true}"

Expand Down
3 changes: 3 additions & 0 deletions deploy/kubernetes/nomos/files/council/council.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ opa:
# Requires policy_id: local-bash and an explicit shell_tool_arguments binding.
# Empty adds no prohibitions beyond the bundled policy rules.
denied_shell_commands: []
# Optional exact tool -> top-level argument key for a host-declared root.
# Exposes intent.workspace to OPA; does not establish trust or containment.
workspace_arguments: {}
timeout_ms: "${COUNCIL_OPA_TIMEOUT_MS:-500}"
fail_closed: "${COUNCIL_OPA_FAIL_CLOSED:-true}"

Expand Down
72 changes: 72 additions & 0 deletions docs/guides/structured-tool-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,78 @@ value is `"tool_call"`; legacy shell requests use `operation: null`, not
`kind: shell`. The kind does not identify the tool or its executor: `tool_name`
names the tool, and the Relay configuration selects its execution route.

### Optional workspace context for structured tools

Different hosts use different argument names for their workspace root. A policy
should not need to know each host's spelling. In the Council deployment's
`council.yaml`, map exact tool names to the **top-level JSON argument key**
containing that root:

```yaml
opa:
workspace_arguments:
shell.run: project_root
file.write: workspace_dir
```

Merge this into the existing `opa` section. The default is `{}`, so no tools are
mapped automatically. Keys are literal, not glob patterns or dotted lookups.
For example, `scope.root` selects a top-level property named `scope.root`.
The mapping applies under every policy profile, independently of
`shell_tool_arguments`; it does not select a policy or guard additional tools.

**Before mapping**, OPA sees the host's original arguments only:

```yaml
intent:
tool_arguments:
command: chmod 600 notes.txt
cwd: /projects/demo/src
project_root: /projects/demo
```

**After mapping**, the same arguments remain intact and a generic field is added:

```yaml
intent:
workspace: /projects/demo
tool_arguments:
command: chmod 600 notes.txt
cwd: /projects/demo/src
project_root: /projects/demo
```

These are abbreviated fragments of the OPA input, not new tool-call schemas.
`workspace` means the host-declared filesystem root for this invocation, not the
working directory. It is copied from the held, validated tool arguments; the
original payload, argument digest, Intent serialization and writ are unchanged.

| Input case | Generic `intent.workspace` |
| --- | --- |
| Exact tool mapping and valid absolute root | The root string, preserved verbatim |
| Mapping exists, but argument is missing or invalid | `null` (unknown scope) |
| No mapping for the tool | Field omitted |
| Legacy shell / `nomos_http` request | Field omitted; no inference from `working_directory` |

Accepted roots are nonempty absolute POSIX or Windows paths without surrounding
whitespace or control characters. Validation is syntactic: the Council service
does not inspect the host filesystem, normalize `..`, resolve symlinks or expand
variables. A policy requiring a workspace must handle omitted/null context
explicitly; neither means that the operation is inside an allowed boundary.

**Trust belongs to the host integration.** The operator chooses which argument
to read, but that does not authenticate its value. The host must derive or
overwrite the argument from its actual authorized workspace before submitting
the tool call. An arbitrary model-supplied path cannot establish an allowed
boundary. The existing argument digest binds the submitted value, not the truth
of that assertion. Do not use the generic field as an automatic allow signal.

This projection supplies OPA input only. It adds no path-containment rule,
target-path extraction in `shell_analysis.py`, decision-model question, Council
prompt field or HITL routing. Council already receives the original structured
arguments; exposing the same generic context to a decision model is a separate
integration step. Hosts must retain their runtime filesystem controls.

### `executor = "nomos_http"`: command uses the legacy shell fields

This example uses the existing `strict-shell` policy profile:
Expand Down
24 changes: 24 additions & 0 deletions nomos/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,15 @@ class OPAConfig(BaseModel):
),
)

workspace_arguments: dict[str, str] = Field(
default_factory=dict,
description=(
"Exact structured tool names mapped to the top-level argument containing "
"the host-declared workspace root. Exposes intent.workspace to OPA under "
"any policy profile; mapping does not authenticate the argument."
),
)

denied_shell_commands: list[str] = Field(
default_factory=list,
description=(
Expand Down Expand Up @@ -737,6 +746,21 @@ def require_local_bash_binding(self) -> "OPAConfig":
raise ValueError("local-bash requires at least one shell_tool_arguments binding")
return self

@field_validator("workspace_arguments")
@classmethod
def validate_workspace_arguments(cls, value: dict[str, str]) -> dict[str, str]:
"""Reject ambiguous bindings without rewriting exact JSON argument keys."""
if any(
not item or item != item.strip() or any(unicodedata.category(c) == "Cc" for c in item)
for pair in value.items()
for item in pair
):
raise ValueError(
"OPA workspace tool names and argument keys must be nonempty, "
"without surrounding whitespace or control characters"
)
return value

@field_validator("enabled", "fail_closed", mode="before")
@classmethod
def resolve_bool_env_vars(cls, value: Any, info) -> Any:
Expand Down
27 changes: 27 additions & 0 deletions nomos/opa/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
import http.client
import json
import os
import unicodedata
import urllib.error
import urllib.request
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from pathlib import PurePosixPath, PureWindowsPath
from typing import Any, Literal

from nomos.config.settings import OPAConfig
Expand Down Expand Up @@ -178,6 +180,26 @@ def parse_opa_decision(payload: Mapping[str, Any]) -> OPAPolicyDecision:
)


def _workspace_root(value: Any) -> str | None:
"""Accept a literal absolute host path without probing or rewriting it.

The Council service may run on a different machine or operating system.
Accept POSIX and Windows roots, but do not expand variables, resolve symlinks
or claim containment. Null means a configured argument is missing/invalid;
a policy requiring workspace context must handle that explicitly.
"""
if (
not isinstance(value, str)
or not value
or value != value.strip()
or any(unicodedata.category(char) == "Cc" for char in value)
):
return None
if PurePosixPath(value).is_absolute() or PureWindowsPath(value).is_absolute():
return value
return None


def build_intent_filter_input(
intent: Intent,
*,
Expand All @@ -197,6 +219,11 @@ def build_intent_filter_input(
# Use the held, validated request, never a model description or digest lookup.
# Keep this live input out of Intent serialization and the signed operation.
tool_input["tool_arguments"] = json.loads(material.canonical_arguments())
workspace_key = opa_config.workspace_arguments.get(material.tool_name)
if workspace_key is not None:
tool_input["workspace"] = _workspace_root(
tool_input["tool_arguments"].get(workspace_key)
)
command_key = opa_config.shell_tool_arguments.get(material.tool_name)
if opa_config.policy_id == "local-bash" and command_key:
tool_input["shell_analysis"] = analyze_shell_command(
Expand Down
5 changes: 3 additions & 2 deletions tests/test_chairman_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ def test_referenced_profile_uses_final_deep_merged_chairman(
)
def test_shipped_yaml_preserves_enabled_unanimous_mode_and_all_parsed_values(relative_path):
# Pin the complete shipped profile, including the intentional Nemotron 3.5
# default migration and explicit empty shell-command deny list.
# default migration, empty shell-command deny list and workspace mapping.
# Comments/formatting are intentionally ignored; the
# public-config tests separately assert the model and every role's routing.
root = Path(settings_module.__file__).resolve().parents[2]
Expand All @@ -373,10 +373,11 @@ def test_shipped_yaml_preserves_enabled_unanimous_mode_and_all_parsed_values(rel
f"enabled=true/allow_quorum=false; got {mode!r}"
)
assert document["opa"]["denied_shell_commands"] == []
assert document["opa"]["workspace_arguments"] == {}
canonical = json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
digest = hashlib.sha256(canonical.encode()).hexdigest()
# Public pinned YAML semantic SHA-256, not a credential; retain the full literal.
expected = "3c29da41b0a81d6aad441dec6e76f0215289bba57f5ae987b2455c5049d7e164" # pragma: allowlist secret # noqa: E501
expected = "bde1754b45264b8a8a1badaaef594eb6f894fbdfe5154e59e16e207dd49ad005" # pragma: allowlist secret # noqa: E501
assert digest == expected, (
f"given={relative_path!r}: all parsed release-template values must match pinned base; "
f"expected semantic SHA-256 {expected}, got {digest}"
Expand Down
170 changes: 170 additions & 0 deletions tests/test_opa_workspace_context.py
Original file line number Diff line number Diff line change
@@ -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"
Loading