diff --git a/docs/system-specs/modules/acp-client.md b/docs/system-specs/modules/acp-client.md index a8843e432ee3..73ac822e2196 100644 --- a/docs/system-specs/modules/acp-client.md +++ b/docs/system-specs/modules/acp-client.md @@ -2169,6 +2169,10 @@ spec the same way kiro-cli v2 does where the wire allows it: kiro-cli 2.35.1: the deny with the target excluded left the call to its permission request, with another name excluded it was refused by the rule, and the allow ran it with no request. +- `toolsSettings.shell.allowedCommands` travels as no rule: a shell allow would + skip the permission request Crew's deny floor runs on. Crew answers a matching + command at that request itself, through the gate's `spec-builtin-grant` row + ([security](security.md) § KAS spec built-in grant). - The spec's `hooks` run from Crew's turn loop (`agent_sdk/spec_hooks.py`); a PostToolUse spec hook's tool matcher is matched on the id the call's permission request stated, or for a call the frame classified as a shell command, KAS's diff --git a/docs/system-specs/modules/governance.md b/docs/system-specs/modules/governance.md index eaec43d29555..313a8ccac129 100644 --- a/docs/system-specs/modules/governance.md +++ b/docs/system-specs/modules/governance.md @@ -1329,7 +1329,9 @@ reads the profile, so any profile at all would withhold every such grant. The ce the one in the gate's own context snapshot, so a ceiling or profile with any opinion on the tool's scopes keeps the call at the prompt; an unresolved profile store or an error withholds. The KAS projection asks `may_grant_builtin_at_gate_now` once when it records -the grant; the gate asks again on every call. +the grant; the gate asks again on every call. A spec's `toolsSettings.shell.allowedCommands` +takes the same row and the same question, asked about `execute_bash`: the patterns are +recorded only when it holds, and the row asks it again for every matching command. What no hook can do is narrow a session **already negotiated**: kiro-cli holds the grants it was given, and nothing reaches into a running one. That limit has the same shape as an diff --git a/docs/system-specs/modules/security.md b/docs/system-specs/modules/security.md index 2d789a25cfd5..a2f78090aa5c 100644 --- a/docs/system-specs/modules/security.md +++ b/docs/system-specs/modules/security.md @@ -2242,6 +2242,24 @@ run. `may_grant_builtin_at_gate` differs from `may_skip_gate` only by omitting t floor clause, which exists because a static grant skips this gate; this grant is made inside it. +The same row answers a spec's `toolsSettings.shell.allowedCommands` (#25320). The +projection records the patterns (`kas_permissions.crew_answered_commands`, at most 64; each entry +read by `platform/allowed_commands.py`, which keeps only literal characters, +escaped punctuation and `.*`, the subset Rust's `regex` and Python read alike, and +matches it in linear time without `re`, so a POSIX class cannot widen a grant and +nested repetition cannot stall the gateway; an entry outside it, an over-long list, +and a list the projection withholds are named in the session-start notice) only when +`may_grant_builtin_at_gate_now("execute_bash")` holds and no restriction the spec's author wrote on the shell withholds it (`withhold_answered_under_authored_rules`, read over every `toolsSettings` shell key except `allowedCommands` itself, `kas_permissions.without_allowed_commands`, so a `deniedCommands` or `denyByDefault` beside it keeps every command prompting), the handle keeps them +(`AcpSessionHandle.kas_crew_answered_commands`) and stamps them on the same own +requests (`AcpEvent.spec_granted_commands`). In place of the built-in name, the row +then needs a shell call (`execute_bash` among its names, `is_shell`) whose +host-recovered command, at most 4,096 characters, holds none of +`; & | < > $ \` ( ) { }`, newline or carriage return, and that one entry +matches whole, as kiro-cli anchors each entry at both ends. Every other +condition above still holds, so a matching command the deny floor, governance or +`confirm_tools` refuses is still refused, and a command that chains, pipes, +redirects, groups or substitutes is never granted whatever the pattern says. + **Read-only auto-approve** — kiro-cli's `autoAllowReadonly` is not used; the tool gate auto-approves read-only tool calls itself, as its `read-only` row — the **last** of `GATE_TIERS`, before `judge`'s fall-through `allow()` — after every diff --git a/src/kiro_crew/acp/harness/kas.py b/src/kiro_crew/acp/harness/kas.py index a82de8a42a05..040534598d60 100644 --- a/src/kiro_crew/acp/harness/kas.py +++ b/src/kiro_crew/acp/harness/kas.py @@ -572,6 +572,9 @@ def record_session_projection(self, handle: Any, custom_agents: Any, active_agen handle.kas_crew_answered = kas_agents_mod.projected_crew_answered( custom_agents, active_agent ) + handle.kas_crew_answered_commands = kas_agents_mod.projected_crew_answered_commands( + custom_agents, active_agent + ) handle.kas_projected_agent = active_agent if custom_agents else "" handle.kas_registered_agents = list(custom_agents) if custom_agents else [] handle.kas_agent_prompt_notice = self.agent_prompt_notice if custom_agents else "" diff --git a/src/kiro_crew/acp/kas_agents.py b/src/kiro_crew/acp/kas_agents.py index d2692d227fbc..287684fef7b4 100644 --- a/src/kiro_crew/acp/kas_agents.py +++ b/src/kiro_crew/acp/kas_agents.py @@ -73,13 +73,16 @@ from kiro_crew.acp.kas_permissions import ( AUTO_APPROVABLE_CAPABILITIES, CREW_ANSWERED_BUILTINS_KEY, + CREW_ANSWERED_COMMANDS_KEY, allowed_tools_to_permissions, auto_approved_capabilities, crew_answered_builtins, + crew_answered_commands, merge_user_permissions, tools_settings_to_permissions, withhold_answered_under_authored_rules, withhold_hook_gated_auto_approval, + without_allowed_commands, ) from kiro_crew.agent_discovery import ( AgentsDirMemo, @@ -235,7 +238,40 @@ def spec_keys_without_carrier( return sorted(lost) _, not_carried = tools_settings_to_permissions(tools_settings) lost.extend(f"toolsSettings.{path}" for path in not_carried) - return sorted(lost) + if ( + isinstance(tools_settings, dict) + and crew_answered_commands(tools_settings) + and _allowed_commands_withheld(spec, None) + ): + # Every entry is usable, but the session answers none of them: name each + # shell key that carries one, so the operator learns why they prompt. + lost.extend( + f"toolsSettings.{key}.allowedCommands" + for key in ("execute_bash", "shell") + if isinstance(tools_settings.get(key), dict) + and tools_settings[key].get("allowedCommands") + ) + return sorted(set(lost)) + + +def _allowed_commands_withheld(spec: dict[str, Any], policy: dict[str, Any] | None) -> bool: + """Whether *spec*'s usable ``shell.allowedCommands`` go unanswered on KAS. + + They do when the governance ceiling withholds the shell grant at the gate, or + when the spec's own author restricted the shell elsewhere (an ``ask``/``deny`` + in *policy* or the raw ``permissions`` block, or another shell setting): the + same reading a shell grant in ``allowedTools`` gets. The ``allowedCommands`` + key itself is the grant, so it is not read as a restriction. One reader for the + projection and the session-start notice, so the two cannot disagree. + """ + if not may_grant_builtin_at_gate_now("execute_bash"): + return True + return not withhold_answered_under_authored_rules( + {"execute_bash"}, + policy, + authored_permissions=spec.get("permissions"), + tools_settings=without_allowed_commands(spec.get("toolsSettings")), + ) class KasAgentTranslationError(ValueError): @@ -1173,6 +1209,14 @@ def to_client_custom_agent( ) if crew_answered: out[CREW_ANSWERED_BUILTINS_KEY] = sorted(crew_answered) + # `toolsSettings.shell.allowedCommands`, answered the same way: the gate + # approves a shell request whose command fullmatches one, after its checks. + # Asked of the ceiling as the shell tool, which is what the call runs, and + # withheld under the same authored restrictions as a shell grant. The + # `allowedCommands` key itself is the grant, so it is not read as one of them. + answered_commands = crew_answered_commands(spec.get("toolsSettings")) + if answered_commands and not _allowed_commands_withheld(spec, permissions): + out[CREW_ANSWERED_COMMANDS_KEY] = answered_commands description = spec.get("description") if isinstance(description, str) and description: @@ -1434,6 +1478,37 @@ def _entry_crew_answered(entry: Any) -> frozenset[str]: return frozenset(n for n in raw if isinstance(n, str) and n) +def _entry_crew_answered_commands(entry: Any) -> tuple[str, ...]: + """The :data:`CREW_ANSWERED_COMMANDS_KEY` patterns of one projected entry, read + like :func:`_entry_crew_answered`: anything malformed answers empty.""" + raw = entry.get(CREW_ANSWERED_COMMANDS_KEY) if isinstance(entry, dict) else None + if not isinstance(raw, list): + return () + return tuple(p for p in raw if isinstance(p, str) and p) + + +def _registered_entry(custom_agents: Any, agent_id: str) -> Any: + entries = [a for a in custom_agents if isinstance(a, dict)] if custom_agents else [] + return next((a for a in entries if a.get("id") == agent_id), None) + + +def _switched_entry(custom_agents: Any, mode_id: str) -> Any: + entries = [a for a in custom_agents if isinstance(a, dict)] if custom_agents else [] + return next((a for a in entries if kas_wire_agent_id(str(a.get("id") or "")) == mode_id), None) + + +def projected_crew_answered_commands(custom_agents: Any, agent_id: str) -> tuple[str, ...]: + """The ``allowedCommands`` patterns Crew answers for *agent_id*'s registered + entry, matched like :func:`projected_crew_answered`.""" + return _entry_crew_answered_commands(_registered_entry(custom_agents, agent_id)) + + +def switched_crew_answered_commands(custom_agents: Any, mode_id: str) -> tuple[str, ...]: + """Those patterns once a KAS mode switch moves the session to *mode_id*, + matched like :func:`switched_crew_answered`.""" + return _entry_crew_answered_commands(_switched_entry(custom_agents, mode_id)) + + def projected_crew_answered(custom_agents: Any, agent_id: str) -> frozenset[str]: """The built-ins Crew answers itself for *agent_id*'s registered entry. diff --git a/src/kiro_crew/acp/kas_permissions.py b/src/kiro_crew/acp/kas_permissions.py index ebde3a5b7872..70e46089c0c4 100644 --- a/src/kiro_crew/acp/kas_permissions.py +++ b/src/kiro_crew/acp/kas_permissions.py @@ -52,6 +52,7 @@ from collections.abc import Callable, Iterable from typing import Any +from kiro_crew.platform import allowed_commands as allowed_commands_mod from kiro_crew.platform.tool_names import KIRO_CLI_NAME_BY_KAS_TOOL, KIRO_TOOL_ALIASES logger = logging.getLogger(__name__) @@ -142,8 +143,83 @@ #: (``_dispatch.attach_kas_custom_agents``). CREW_ANSWERED_BUILTINS_KEY = "_crewAnsweredBuiltins" +#: The key a projected entry carries its :func:`crew_answered_commands` under, for +#: the session's own record, like :data:`CREW_ANSWERED_BUILTINS_KEY`. +CREW_ANSWERED_COMMANDS_KEY = "_crewAnsweredCommands" + #: Keys of a projected ``customAgents`` entry that never reach the engine. -CREW_ONLY_ENTRY_KEYS: frozenset[str] = frozenset({CREW_ANSWERED_BUILTINS_KEY}) +CREW_ONLY_ENTRY_KEYS: frozenset[str] = frozenset( + {CREW_ANSWERED_BUILTINS_KEY, CREW_ANSWERED_COMMANDS_KEY} +) + +#: The ``toolsSettings`` keys kiro-cli reads its shell settings under. +_SHELL_SETTINGS_KEYS = ("execute_bash", "shell") + +#: Bounds on what :func:`crew_answered_commands` keeps, so the record the session +#: carries and the work the gate does per shell call stay small. +_MAX_ALLOWED_COMMANDS = 64 + + +def allowed_command_pattern(raw: Any) -> str | None: + """One kiro-cli ``allowedCommands`` entry as Crew records it, or ``None``. + + Only the subset :mod:`kiro_crew.platform.allowed_commands` reads the same way + kiro-cli does, and matches in linear time, is kept (stripped); any other entry + is ``None`` and its commands keep prompting. Kept verbatim, as kiro-cli reads it. + """ + if allowed_commands_mod.parse(raw) is None: + return None + assert isinstance(raw, str) + return raw + + +def without_allowed_commands(tools_settings: Any) -> Any: + """*tools_settings* with each shell entry's ``allowedCommands`` key left out. + + For :func:`withhold_answered_under_authored_rules`, which reads ANY entry for a + built-in as a restriction: the grant itself is not one. A shell entry that held + only that key goes too; every other key, and any malformed value, is kept, so + it still withholds. + """ + if not isinstance(tools_settings, dict): + return tools_settings + out = dict(tools_settings) + for key in _SHELL_SETTINGS_KEYS: + entry = out.get(key) + if isinstance(entry, dict) and "allowedCommands" in entry: + rest = {k: v for k, v in entry.items() if k != "allowedCommands"} + if rest: + out[key] = rest + else: + del out[key] + return out + + +def _usable_allowed_commands(tools_settings: Any) -> list[str]: + """Every distinct usable ``allowedCommands`` entry of both shell keys, in order.""" + if not isinstance(tools_settings, dict): + return [] + out: list[str] = [] + for key in _SHELL_SETTINGS_KEYS: + settings = tools_settings.get(key) + entries = settings.get("allowedCommands") if isinstance(settings, dict) else None + for raw in entries if isinstance(entries, list) else (): + pattern = allowed_command_pattern(raw) + if pattern is not None: + out.append(pattern) + return list(dict.fromkeys(out)) + + +def crew_answered_commands(tools_settings: Any) -> list[str]: + """The ``shell.allowedCommands`` patterns Crew answers a KAS shell request for. + + A shell allow never reaches the KAS policy (:data:`WITHHELD_CAPABILITIES`), + so each command raises a permission request; the gate's ``spec-builtin-grant`` + tier approves one whose recovered command fullmatches a pattern here, after + every deny tier and governance (``gate_tiers._tier_spec_builtin_grant``). + Pure: the caller asks the governance ceiling about the shell tool. + """ + return _usable_allowed_commands(tools_settings)[:_MAX_ALLOWED_COMMANDS] def crew_answered_builtins(allowed_tools: Any) -> frozenset[str]: @@ -1379,6 +1455,19 @@ def url_glob(raw: str) -> str | None: f"{tool}.deniedCommands", settings.get("deniedCommands"), _regex_to_glob ) rules.extend(_chunked_rules("shell", "deny", denied)) + # No rule: Crew answers the shell requests these match itself, at + # the gate (`crew_answered_commands`). Only an entry it cannot use + # is named. + handled.add("allowedCommands") + allowed = settings.get("allowedCommands") + # Named when an entry is unusable, and when the bound cuts the list: + # those commands keep prompting. + if allowed and ( + not isinstance(allowed, list) + or any(allowed_command_pattern(p) is None for p in allowed) + or len(_usable_allowed_commands(tools_settings)) > _MAX_ALLOWED_COMMANDS + ): + lost.append(f"{tool}.allowedCommands") elif family in ("read", "write"): capability = "fs_read" if family == "read" else "fs_write" handled.add("deniedPaths") diff --git a/src/kiro_crew/acp/session_handle_class.py b/src/kiro_crew/acp/session_handle_class.py index 64ff5488a48d..63866ccda996 100644 --- a/src/kiro_crew/acp/session_handle_class.py +++ b/src/kiro_crew/acp/session_handle_class.py @@ -634,6 +634,9 @@ def __init__( # their permission requests itself, after the deny floor, the # sensitive-path check and the governance ceiling. Empty with no batch. self.kas_crew_answered: frozenset[str] = frozenset() + # The agent's `toolsSettings.shell.allowedCommands` as the gate matches + # them (``kas_permissions.crew_answered_commands``), answered the same way. + self.kas_crew_answered_commands: tuple[str, ...] = () # The agent this session runs: the one the batch was registered for, then # whichever a KAS mode switch moves it to ("" with no batch). A turn that # names no agent runs this one, so its spec hooks are this agent's. diff --git a/src/kiro_crew/acp/session_handle_kas.py b/src/kiro_crew/acp/session_handle_kas.py index 0e3df83cff36..2c09bf2a97a0 100644 --- a/src/kiro_crew/acp/session_handle_kas.py +++ b/src/kiro_crew/acp/session_handle_kas.py @@ -9,7 +9,7 @@ class binds it by name, so it reads and writes the session's own state on the in Instance fields written: ``_compaction_failed_at``, ``_compaction_terminal_seen``, ``_hook_tasks``, ``_kas_prompt_row``, ``_last_kas_mode_id``, ``kas_auto_approved``, -``kas_crew_answered``, ``kas_projected_agent``, ``last_compaction_transient``. +``kas_crew_answered``, ``kas_crew_answered_commands``, ``kas_projected_agent``, ``last_compaction_transient``. Instance fields read: ``_crew_agent``, ``_listed_hooks``, ``_prompt_starts``, ``_runtime``, ``_session_id``, ``_session_key``, ``_turn_done``, @@ -264,11 +264,16 @@ def _handle_kas_update( # -- chosen by wire id, so a built-in of the same name never inherits # the crewmate's approvals. if self.kas_projected_agent: - from kiro_crew.acp.kas_agents import switched_auto_approved, switched_crew_answered + from kiro_crew.acp.kas_agents import ( + switched_auto_approved, + switched_crew_answered, + switched_crew_answered_commands, + ) self.kas_projected_agent = crew_id self.kas_auto_approved = switched_auto_approved(registered, mode_id) self.kas_crew_answered = switched_crew_answered(registered, mode_id) + self.kas_crew_answered_commands = switched_crew_answered_commands(registered, mode_id) return [AcpEvent(kind=EVENT_AGENT_SWITCHED, text=crew_id)] if session_update == UPDATE_SESSION_INFO: return self._handle_kas_session_info(update) diff --git a/src/kiro_crew/acp/session_handle_permissions.py b/src/kiro_crew/acp/session_handle_permissions.py index 6432c2282de5..1133165355b2 100644 --- a/src/kiro_crew/acp/session_handle_permissions.py +++ b/src/kiro_crew/acp/session_handle_permissions.py @@ -15,7 +15,7 @@ class binds it by name, so it reads and writes the session's own state on the in ``_tool_call_cache_overflow``, ``_tool_call_diff_path``, ``_tool_call_harness_tool_name``, ``_tool_call_input_redacted``, ``_tool_call_inputs``, ``_tool_call_is_shell``, ``_tool_call_mcp_server``, ``_tool_call_raw_params``, -``_tool_call_tool_name``, ``kas_crew_answered``, ``mirror_used``, ``spec_denied_tools``. +``_tool_call_tool_name``, ``kas_crew_answered``, ``kas_crew_answered_commands``, ``mirror_used``, ``spec_denied_tools``. """ from __future__ import annotations @@ -655,4 +655,5 @@ def _build_permission_event(self: AcpSessionHandle, msg: JsonRpcMessage) -> AcpE # which shares this session's id and is told apart by the id its # agentSubtaskId frame recorded. event.spec_granted_builtins = frozenset(getattr(self, "kas_crew_answered", ())) + event.spec_granted_commands = tuple(getattr(self, "kas_crew_answered_commands", ())) return event diff --git a/src/kiro_crew/acp/types.py b/src/kiro_crew/acp/types.py index 86c724b05bef..f58369b1d839 100644 --- a/src/kiro_crew/acp/types.py +++ b/src/kiro_crew/acp/types.py @@ -1112,6 +1112,12 @@ class AcpEvent: #: tier and governance, and approves only a host-identified built-in it names. #: Empty everywhere else, which grants nothing. spec_granted_builtins: frozenset[str] = frozenset() + #: spec_granted_commands: on the same requests, the agent's + #: ``toolsSettings.shell.allowedCommands`` as Python regexes + #: (``AcpSessionHandle.kas_crew_answered_commands``), written the same way. The + #: ``spec-builtin-grant`` tier approves a shell call whose recovered command + #: fullmatches one. Empty everywhere else, which grants nothing. + spec_granted_commands: tuple[str, ...] = () # Canonical, NON-model-authored tool identity from adapter-authored # ``_meta.kiro`` or ``_meta.goose`` (see ``_dispatch._kiro_tool_name``). # ``title`` is LLM-authored prose — for shell tools ``select_tool_title`` diff --git a/src/kiro_crew/docs/agent-spec-fields.md b/src/kiro_crew/docs/agent-spec-fields.md index 5c8164c15f9c..46ae2022e4d8 100644 --- a/src/kiro_crew/docs/agent-spec-fields.md +++ b/src/kiro_crew/docs/agent-spec-fields.md @@ -463,7 +463,7 @@ unconfirmed. | `allowedTools` | list | What is AUTO-APPROVED. Entries are globs, not names: `@srv`, `@srv/`, `@srv/*` all match the whole server (`_canonical_grant_pattern`). This is the ONE path that never reaches Crew's PreToolUse gate, so every writer filters it through the governance ceiling (`_apply_allowed_tools_ceiling`) and the KAS projection re-filters on read (`_ceiling_permitted`), because a file can predate the ceiling that now governs it. The file-tool built-ins `grep`, `glob`, `code`, `fs_read`, `fs_write` and `execute_bash` are withheld even on a host with no ceiling, because a grant here would skip the sensitive-path and denied-command checks. Crew's own gate approves the read-only `grep` and `glob` calls, and the tree-sitter lookups of `code`, without a prompt once those checks pass, when every path they name is absolute and holds no credential store. | | `excludedTools` | list | A RESTRICTION, subtracted after `tools`. `spec_grants_tool_search` reads it: a spec that grants `"*"` then excludes `tool_search` grants no loader. Mirrored onto the worker spec alongside the grants, so "superset of what the default grants" cannot quietly become "superset of what it permits". | | `permissions` | object | KAS's own currency: `{"rules": [{"capability", "match", "effect"}]}`. Crew WRITES this derived from `allowedTools` (`derived_agent_permissions`) **only when the program that reads the spec accepts the field** (`auto_approve._spec_permissions_accepted`). On the relay route (`agent.kas_bundle` off) that is the installed kiro-cli: `spec_permissions_supported(installed_kiro_cli_version())`, floor `SPEC_PERMISSIONS_MIN_VERSION` (2.23.0) in `kiro_cli.py`. kiro-cli validates specs with `deny_unknown_fields`, so a release below the floor refuses the WHOLE file and drops every Crew MCP server; an unknown version (no pinned binary, refused or unparseable `--version`) withholds too. With `agent.kas_bundle` on, Crew's own installed engine bundle reads the spec too, so the engine's version must also pass: `installed_bundle().version` against `KAS_SPEC_PERMISSIONS_MIN_ENGINE_VERSION` (0.66.33, the pinned engine) through `kas_pin.engine_spec_permissions_supported`; no engine installed or one below the floor withholds. kiro-cli's gate still applies whenever kiro-cli is installed, since it reads the same files for every other backend; a host with no kiro-cli is not probed and gets the block from the engine alone. The default spec's seed (`_seed_kas_permissions`) preserves an existing block before calling the shared gate (`_write_derived_permissions`), so a block already on disk is never removed by seeding; `kirocrew setup --agent-only --clean` repairs a default spec an older release already refuses. Generated conductor and worker writers use the same gate to replace an inherited value on an accepting release and remove it on an older or unknown one. Fork and publish (`_align_permissions` in `agent_capabilities.py`) route the TARGET block through the same `_write_derived_permissions`, so the published spec carries it only when every reader accepts it (kiro-cli on the relay route; the installed engine, plus kiro-cli when installed, with `agent.kas_bundle` on) and has it removed otherwise; the review of the SOURCE block described below runs whatever the version. `kirocrew doctor` prints the verdict as the KAS block's `auto-approve:` row. A block in the file is not an input to DERIVATION, which reads `allowedTools` and nothing else — but on the wire it is a second input, merged by `merge_user_permissions`: parsed against KAS's own shape and refused whole when it does not fit, `deny`/`ask` relayed unconditionally, `allow` relayed only where the same ceiling permits that capability and that resource, the shell and filesystem families never relayed as an `allow`, and an `allow` the `allowedTools` derivation could have emitted itself not relayed at all when the spec carries such a list — that list is the governed input and is re-derived every projection, so a block that has gone stale against it (including one the seeder wrote and preserved) cannot put a revoked grant back. Every decision, relay and withhold alike, is recorded in the security event log. Without that merge a pure-KAS agent — `permissions` authored, no `allowedTools` — reaches the backend with the field absent, and absent resolves every request to `ask`. On disk the block is left untouched and the backend reads it. One path does read it: fork and publish (`agent_capabilities.py`, `_align_permissions`) compares it against a fresh derivation and refuses with `alternate_permissions_require_review` when the two disagree, so a hand-edited block blocks forking that template. `src/kiro_crew/acp/kas_permissions.py` owns the translation, and refuses the shell and filesystem families outright: a tool-name allowlist carries no resource pattern, so the rule it would produce is unscoped. | -| `toolsSettings` | object | Per-tool settings kiro-cli reads. Crew strips exactly two retired keys on every refresh — `execute_bash`/`shell` `deniedCommands` and `autoAllowReadonly` — because denied commands are enforced only at Crew's PreToolUse gate now, and a stale copy in the spec would keep blocking a built-in the user just re-enabled (`_strip_legacy_denied_commands`). Your other keys are preserved. One key Crew READS: `subagent.availableAgents`, kiro-cli's glob allowlist of what this agent may spawn, is honoured at Crew's own `spawn_run` / `spawn_sub_agents` gate too (those bypass kiro-cli's built-in `subagent` tool) — declared, the target must match a glob; omitted, everything is allowed, as upstream. The gate reads the spec in `~/.kiro/agents` AND, when it knows the parent session's project directory (the live session's cwd and the chat slot's project, or a sub-agent's cwd), in `/.kiro/agents`; a declaration in any scope applies, so a project spec can only narrow what the user-level one allows. When the project directory is unknown and no user-level spec names the parent, a project-scope declaration is not honoured: Crew logs a warning and writes a `parent_spec_unresolved` security event instead of refusing. `subagent.trustedAgents` is a trust grant ("no permission prompts"), not an allowlist, and is not read as one. Details: `docs/system-specs/modules/subagent.md` § Parent agent spec allowlist. No KAS wire slot, so on KAS Crew translates it into `permissions` rules (`kas_permissions.tools_settings_to_permissions`, following KAS's own migration mapping) and merges them like an authored block: `deniedPaths` (read/glob/grep → `fs_read`, write → `fs_write`), `deniedCommands` and `web_fetch.blocked` become `deny` rules. `subagent.availableAgents` becomes a `subagent` `deny` over `"*"` with the listed names in `exclude` (`[]` denies every sub-agent), and `subagent.trustedAgents` a name-scoped `subagent` `allow` that the governance ceiling must permit, both run live on KAS (#25320); a name pattern travels when it is an agent id with `*` as its only wildcard. The other deny-all-but shapes, `shell.denyByDefault` and `write.fallbackAction: "deny"`, would need an `exclude` rule on a command or a path that no live KAS run has confirmed, so they are not carried. A regex becomes a glob only when it is a literal plus `.*` with no character KAS reads as glob syntax, and a pattern over the merge's length bound is dropped rather than refusing the whole block. Allow lists (`allowedCommands`, `allowedPaths`, `web_fetch.trusted`), `autoAllowReadonly`, `allowReadOnly`, `use_aws` and any pattern that does not translate are not carried, so those calls keep prompting; the KAS chat shows one notice at session start naming exactly those entries. goose and opencode never receive the rules, so their notice still names `toolsSettings` whole. | +| `toolsSettings` | object | Per-tool settings kiro-cli reads. Crew strips exactly two retired keys on every refresh — `execute_bash`/`shell` `deniedCommands` and `autoAllowReadonly` — because denied commands are enforced only at Crew's PreToolUse gate now, and a stale copy in the spec would keep blocking a built-in the user just re-enabled (`_strip_legacy_denied_commands`). Your other keys are preserved. One key Crew READS: `subagent.availableAgents`, kiro-cli's glob allowlist of what this agent may spawn, is honoured at Crew's own `spawn_run` / `spawn_sub_agents` gate too (those bypass kiro-cli's built-in `subagent` tool) — declared, the target must match a glob; omitted, everything is allowed, as upstream. The gate reads the spec in `~/.kiro/agents` AND, when it knows the parent session's project directory (the live session's cwd and the chat slot's project, or a sub-agent's cwd), in `/.kiro/agents`; a declaration in any scope applies, so a project spec can only narrow what the user-level one allows. When the project directory is unknown and no user-level spec names the parent, a project-scope declaration is not honoured: Crew logs a warning and writes a `parent_spec_unresolved` security event instead of refusing. `subagent.trustedAgents` is a trust grant ("no permission prompts"), not an allowlist, and is not read as one. Details: `docs/system-specs/modules/subagent.md` § Parent agent spec allowlist. No KAS wire slot, so on KAS Crew translates it into `permissions` rules (`kas_permissions.tools_settings_to_permissions`, following KAS's own migration mapping) and merges them like an authored block: `deniedPaths` (read/glob/grep → `fs_read`, write → `fs_write`), `deniedCommands` and `web_fetch.blocked` become `deny` rules. `subagent.availableAgents` becomes a `subagent` `deny` over `"*"` with the listed names in `exclude` (`[]` denies every sub-agent), and `subagent.trustedAgents` a name-scoped `subagent` `allow` that the governance ceiling must permit, both run live on KAS (#25320); a name pattern travels when it is an agent id with `*` as its only wildcard. The other deny-all-but shapes, `shell.denyByDefault` and `write.fallbackAction: "deny"`, would need an `exclude` rule on a command or a path that no live KAS run has confirmed, so they are not carried. A regex becomes a glob only when it is a literal plus `.*` with no character KAS reads as glob syntax, and a pattern over the merge's length bound is dropped rather than refusing the whole block. `shell.allowedCommands` travels as no rule: Crew answers a matching command's permission request itself, after its deny floor and governance, and never for a command that chains, pipes, redirects or substitutes (`docs/system-specs/modules/security.md` § KAS spec built-in grant). The other allow lists (`allowedPaths`, `web_fetch.trusted`), `autoAllowReadonly`, `allowReadOnly`, `use_aws` and any pattern that does not translate are not carried, so those calls keep prompting; the KAS chat shows one notice at session start naming exactly those entries. goose and opencode never receive the rules, so their notice still names `toolsSettings` whole. | | `hooks` | object | Event-keyed hook lists, stored camelCase (`preToolUse`, `postToolUse`, `userPromptSubmit`, `agentSpawn`, `stop`). Crew merges your `kiro_hooks` config and, when autoimport is on, scripts discovered under `~/.kiro/hooks`, capped per event by `_MAX_USER_HOOKS_PER_EVENT` and in total by `_MAX_TOTAL_USER_HOOKS`. This field is the object form only, which is kiro-cli's own schema. The SOURCE that feeds it, `agent.kiro_hooks` in `~/.kiro/crew/config.json`, additionally accepts a kiro-agent hooks ARRAY — `{name, description?, trigger, matcher?, action, timeout?, enabled?, confirm?}` documents, on the twelve trigger names of kiro-agent's alias table in any of its spellings — and projects it onto this object: only a `command` action on the five triggers kiro-cli names is emitted, so an `agent` action, the other seven triggers and the per-hook `name`/`description`/`timeout` stay in your config without running there, and `enabled: false` or `confirm: true` keeps the hook out of the emission entirely (and out of the autoimport scan). See `steering-and-hooks.md` for that field. No KAS wire slot, so `UNSUPPORTED_SPEC_KEYS` drops the key from the agent Crew injects over the wire. On KAS, Crew's own turn loop fires this field instead (`agent_sdk/spec_hooks.py`, gated on `SessionCapabilities.crew_fires_spec_hooks`), through the same hook-store path as a Hooks-page hook: the `capabilities.script_hooks` gate, the sandboxed spawn, the timeout, and a PreToolUse exit 2 that blocks the tool. A PreToolUse hook runs only on a call that reaches Crew as a permission request, so the KAS projection adds an `ask` rule for every auto-approvable capability that such a hook's matcher covers, this spec's or a Hooks-page one's (`kas_permissions.withhold_hook_gated_auto_approval`). KAS lets `ask` outrank `allow`, so the call comes back as a permission request and the hook sees it. A live session keeps the batch it registered, so when a hook added later covers a capability that batch auto-approves, the next turn resets the session and the claim registers a fresh batch (`spec_hooks.invalidate_stale_kas_session` before the claim, and `spec_hooks.reproject_claimed_session` again under the claimed lease, so a turn that waited behind a busy session is not run on its stale batch). A mode switch mid-turn activates a batch KAS already holds, so when the agent it moves to auto-approves what its PreToolUse hooks cover, the turn is stopped and the next one starts a fresh session projected for that agent (`spec_hooks.refuse_stale_switch`). A switch to one of KAS's own built-in modes, which has no spec on disk, carries no spec hooks: only the Hooks page's hooks are checked, and the refusal runs before the switch is recorded on the chat slot. A process that registers no hook store (the standalone `kirocrew run` task runner) reads the Hooks page's saved hooks from disk for both the projection and the gate (`hooks.persisted_hook_store`), so they still apply there. A `confirm: true` document does not run, since Crew cannot ask for the confirmation, and a new session gets one notice naming how many were skipped. When its own backend is KAS, a subagent or task-runner turn runs its PreToolUse hooks (the Hooks page's and its own agent's spec hooks) on each permission request and refuses the call on a deny, and does not fire them again on the tool-call event (KAS sends that frame first); a subagent passes the spec hooks to PostToolUse too. A tool `matcher` keeps kiro-cli's tool names (`execute_bash`, `fs_write`, and the `shell`/`read`/`write` aliases): on a PreToolUse Crew compares it with the id KAS states for the call and the kiro-cli names that id stands for (`acp/kas_permissions.KAS_TOOL_IDS_BY_KIRO_TOOL`, so `execute_bash` meets KAS's `run_command`), never with the call's title, and the hook's stdin reports that kiro-cli name as `tool_name`. A PreToolUse matcher the table does not know (`use_aws`, `disclose_context`) is kept and warned about: it meets a KAS id it matches as written. A call KAS names no tool for is matched on its title, as a Hooks-page hook is. A PostToolUse matches the same way, on the finished call's id: KAS's tool-call frames name no built-in tool, so it is the id the call's permission request stated, or KAS's shell tool for a call classified as a shell command; a call neither names keeps title matching. A PostToolUse fires once per call, on its terminal result. goose and opencode get the same treatment: their session carries no hooks field either, and every tool call arrives as a permission request, so Crew fires the field there too. A tool matcher meets the tool name the harness states on the call's first `tool_call` frame (goose's `_meta.goose.toolCall.toolName`, opencode's `title`), mapped back to kiro-cli's names (`acp/harness_tool_names.py`, so `execute_bash` meets goose's `shell` and opencode's `bash`). An `mcp__server__tool` matcher meets an MCP call too: goose names the server itself, and opencode's fused `_` title is split against the servers Crew placed on the session and the ones opencode's own config mounts (which Crew reads back when the session starts, so `mcp__docs.server__lookup` meets a `docs.server` tool even though opencode writes it `docs_server_lookup`; a config with more than 256 such rewritten names, or a name over 256 characters, refuses the session rather than leave one out), and also at every `_` for a server neither names; every split is kept. When the fused title is also one of opencode's own tools (`apply_patch`), that tool's names are kept too and its kiro-cli name stays first, so the hook's stdin still reports `fs_write` as `tool_name`. On these backends and KAS a matcher may also be written `@server/tool`, the form Crew builds for an MCP call from the server name the harness states: one literal server name (no glob, so `@*/tool` is refused) and a tool part in the matcher's own characters, `*` included (`@server/*`). Only this conversion accepts it (`spec_hooks._MCP_MATCHER_RE`); the merge that writes kiro-cli's materialized spec keeps its own rule. On those two backends the spec is read from the checkout's `.kiro/agents` first, then the user level, the same order their MCP projection resolves it in, but a project agent's hooks run only when that checkout is trusted to choose its MCP servers (`acp/session_mcp.py`, `_project_mcp_trusted`), and otherwise the user-level spec of that name supplies the hooks; a project spec that cannot be read blocks every tool call. KAS reads the user level alone. As on KAS, this is the chat, subagent and task-runner turn loops: a channel-agent turn (`channel.py`) runs no script hooks on any backend. claude and codex do not run the field yet: each approves some calls inside the harness without asking, and a PreToolUse hook would be skipped on those. kiro-cli runs the field itself, so Crew never fires it there. | | `slashCommand` | any | No KAS wire slot: a KAS session runs without it, and the chat shows one notice at session start saying so. Nothing else in this tree reads it. | | `toolAliases` | object | Maps a Connections-exposed MCP tool to the short name a `@alias` reference in `tools` / `allowedTools` resolves through. On the default spec's rebuild Crew recomputes it from the connector registry, dropping the pairs its own record proves it wrote and keeping the rest, whose authorship is unproven and therefore yours (`agent_materialization/mcp_aliases.py`, `_reconcile_tool_aliases_from_disk`). It reconciles the path it is given, so a spec that rebuild does not touch keeps whatever it holds. A non-dict value there is replaced rather than merged. | diff --git a/src/kiro_crew/hook_runtime/gate_tiers.py b/src/kiro_crew/hook_runtime/gate_tiers.py index fed22b35f8e6..b1403496f729 100644 --- a/src/kiro_crew/hook_runtime/gate_tiers.py +++ b/src/kiro_crew/hook_runtime/gate_tiers.py @@ -1159,6 +1159,30 @@ def _spec_builtin_names(call: ToolCall) -> tuple[str, ...]: return tuple(dict.fromkeys(n for n in names if n)) +def _spec_command_granted(call: ToolCall, names: tuple[str, ...]) -> bool: + """Whether a spec's ``toolsSettings.shell.allowedCommands`` grants this call. + + Only a shell call (kiro-cli's ``execute_bash`` among its names) with its + command recovered by the host, holding none of + :data:`kiro_crew.platform.allowed_commands.UNGRANTABLE_COMMAND_CHARS`, that one of ``spec_granted_commands`` + matches whole, as kiro-cli anchors each entry at both ends. Each entry is read + by :mod:`kiro_crew.platform.allowed_commands`, which accepts only the subset + both engines read alike and matches it in linear time; any other grants nothing. + """ + from kiro_crew.platform import allowed_commands + + if not call.spec_granted_commands or "execute_bash" not in names or not call.is_shell: + return False + command = call.command + if not isinstance(command, str) or not allowed_commands.plain_command(command): + return False + for pattern in call.spec_granted_commands: + segments = allowed_commands.parse(pattern) + if segments is not None and allowed_commands.matches(segments, command): + return True + return False + + def _tier_spec_builtin_grant(facts: GateFacts, tier: GateTier) -> ToolHookResult | None: """A KAS built-in the session's agent spec grants in ``allowedTools``. @@ -1215,12 +1239,14 @@ def grant_spec_builtin( return None call = facts.call granted = call.spec_granted_builtins - if not granted or not call.kas_builtin_ids or not call.identity_trusted: + if not (granted or call.spec_granted_commands): + return None + if not call.kas_builtin_ids or not call.identity_trusted: return None if call.mcp_server or not call.mcp_tool: return None names = _spec_builtin_names(call) - if not any(name in granted for name in names): + if not any(name in granted for name in names) and not _spec_command_granted(call, names): return None from kiro_crew.platform.governance import may_grant_builtin_at_gate diff --git a/src/kiro_crew/hook_runtime/tool_identity.py b/src/kiro_crew/hook_runtime/tool_identity.py index c07605859f34..ce53c6e85032 100644 --- a/src/kiro_crew/hook_runtime/tool_identity.py +++ b/src/kiro_crew/hook_runtime/tool_identity.py @@ -177,6 +177,11 @@ class ToolCall: #: ``spec-builtin-grant`` tier only, after every deny tier and governance. #: Empty (every other harness, a sub-session, a hand-built call) grants nothing. spec_granted_builtins: frozenset[str] = frozenset() + #: ``AcpEvent.spec_granted_commands``: the KAS session's own agent's + #: ``toolsSettings.shell.allowedCommands`` as Python regexes, written the same + #: way. Read by the ``spec-builtin-grant`` tier only, against the recovered + #: ``command``. Empty grants nothing. + spec_granted_commands: tuple[str, ...] = () #: ``AcpEvent.harness_builtin_tool``: the kiro-cli read built-in a claude call #: is for, from the name claude-agent-acp stamped on the tool_call frame. A #: deny target, so a rule on ``web_fetch`` binds claude's WebFetch, and the @@ -236,6 +241,9 @@ def from_event(cls, event: object, **overrides: Any) -> "ToolCall": "identity_unreadable": bool(getattr(event, "mcp_identity_unreadable", False)), "kas_builtin_ids": bool(getattr(event, "kas_builtin_ids", False)), "spec_granted_builtins": _granted_names(getattr(event, "spec_granted_builtins", None)), + "spec_granted_commands": _granted_patterns( + getattr(event, "spec_granted_commands", None) + ), "harness_builtin_tool": getattr(event, "harness_builtin_tool", "") or "", "deepseek_tool_name": getattr(event, "deepseek_tool_name", "") or "", "spawn_target": getattr(event, "spawn_target", "") or "", @@ -262,6 +270,7 @@ def kwargs(self) -> dict[str, Any]: "mcp_identity_unreadable": self.identity_unreadable, "kas_builtin_ids": self.kas_builtin_ids, "spec_granted_builtins": self.spec_granted_builtins, + "spec_granted_commands": self.spec_granted_commands, "harness_builtin_tool": self.harness_builtin_tool, "deepseek_tool_name": self.deepseek_tool_name, "spawn_target": self.spawn_target, @@ -279,6 +288,14 @@ def _granted_names(value: object) -> frozenset[str]: return frozenset(n for n in value if isinstance(n, str) and n) +def _granted_patterns(value: object) -> tuple[str, ...]: + """``AcpEvent.spec_granted_commands`` as the tuple the gate reads, read like + :func:`_granted_names`: anything that is not a sequence of strings grants nothing.""" + if not isinstance(value, (tuple, list)): + return () + return tuple(p for p in value if isinstance(p, str) and p) + + def hook_gate_kwargs(event: object, **overrides: Any) -> dict[str, Any]: """The event-derived keyword arguments for ``HookManager.on_tool_call``. diff --git a/src/kiro_crew/hooks.py b/src/kiro_crew/hooks.py index e2a3c0f9cbd2..c3709fb23975 100644 --- a/src/kiro_crew/hooks.py +++ b/src/kiro_crew/hooks.py @@ -102,6 +102,7 @@ _rule_sensitive_bash, _rule_sensitive_path, _spec_builtin_names, + _spec_command_granted, _tier_app_own_server, _tier_deny_rules, _tier_governance, @@ -196,6 +197,7 @@ _context_matches, _glob_pattern_leaves_root, _granted_names, + _granted_patterns, _has_global_inline_flags, _host_builtin_alias, _is_declared_builtin_mcp_server, @@ -756,6 +758,7 @@ def on_tool_call( mcp_identity_unreadable: bool = False, kas_builtin_ids: bool = False, spec_granted_builtins: frozenset[str] = frozenset(), + spec_granted_commands: tuple[str, ...] = (), harness_builtin_tool: str = "", deepseek_tool_name: str = "", spawn_target: str = "", @@ -792,6 +795,7 @@ def on_tool_call( identity_unreadable=mcp_identity_unreadable, kas_builtin_ids=kas_builtin_ids, spec_granted_builtins=frozenset(spec_granted_builtins), + spec_granted_commands=tuple(spec_granted_commands), harness_builtin_tool=harness_builtin_tool, deepseek_tool_name=deepseek_tool_name, spawn_target=spawn_target, diff --git a/src/kiro_crew/platform/allowed_commands.py b/src/kiro_crew/platform/allowed_commands.py new file mode 100644 index 000000000000..0355ec257513 --- /dev/null +++ b/src/kiro_crew/platform/allowed_commands.py @@ -0,0 +1,131 @@ +"""kiro-cli ``toolsSettings.shell.allowedCommands`` entries, read and matched safely. + +kiro-cli compiles each entry with Rust's ``regex`` crate, anchored at both ends, and +runs a command one matches without a prompt. Crew answers the same grant at its own +gate on KAS, and must neither grant more than kiro-cli would nor let a pattern stall +the gateway. Python's ``re`` does neither safely: it reads some Rust syntax +differently (a POSIX class such as ``[[:alpha:]]``) and backtracks without bound +on nested repetition. + +So only the subset whose meaning is the same in both engines, and which matches in +linear time, is accepted: literal characters, a backslash-escaped punctuation +character as a literal, and ``.*`` as "any run of characters". Optional ``^`` / +``\\A`` at the start and ``$`` / ``\\z`` at the end are read as the anchoring +kiro-cli adds anyway. Every other entry is refused (``None``) and its commands keep +prompting. A literal-plus-``.*`` pattern is the shape kiro-cli's own documentation +shows (``git status``, ``npm run .*``). + +A LEAF on purpose: stdlib only, so both the KAS projection and the gate import it. +""" + +from __future__ import annotations + +#: Characters that make a regex more than a literal; ``.`` is accepted only as ``.*``. +_REGEX_METACHARACTERS = frozenset(".^$*+?()[]{}|\\") + +#: Bound on one entry, so the record a session carries stays small. +MAX_PATTERN_LENGTH = 1024 + +#: Characters that make a command more than one plain command: chaining, pipes, +#: redirection, substitution, grouping and expansion. A command holding any of +#: them is never granted by an entry, however wide, so a ``git status .*`` grant +#: cannot carry ``git status; ``. +UNGRANTABLE_COMMAND_CHARS = frozenset(";&|<>$`(){}\n\r") + +#: Commands longer than this are not matched against an entry at all. +MAX_COMMAND_LENGTH = 4096 + + +def parse(raw: object) -> tuple[str, ...] | None: + """*raw* as its literal segments between ``.*`` wildcards, or ``None``. + + ``("git status",)`` is an exact command; ``("npm run ", "")`` is ``npm run .*``; + ``("", "")`` is ``.*``. ``None`` for anything outside the accepted subset. + """ + if not isinstance(raw, str): + return None + # Read verbatim, as kiro-cli reads it: no stripping, and no character a reader + # could not see (control characters, any whitespace but the plain space). + body = raw + if not body or len(body) > MAX_PATTERN_LENGTH or not _plain_text(body): + return None + for prefix in ("\\A", "^"): + if body.startswith(prefix): + body = body[len(prefix) :] + break + for suffix in ("\\z", "$"): + if body.endswith(suffix) and not body.endswith("\\" + suffix): + body = body[: -len(suffix)] + break + segments: list[str] = [] + current: list[str] = [] + i = 0 + while i < len(body): + ch = body[i] + if body.startswith(".*", i): + segments.append("".join(current)) + current = [] + i += 2 + elif ch == "\\": + nxt = body[i + 1] if i + 1 < len(body) else "" + if not nxt or nxt.isalnum() or nxt.isspace(): + return None + current.append(nxt) + i += 2 + elif ch in _REGEX_METACHARACTERS: + return None + else: + current.append(ch) + i += 1 + segments.append("".join(current)) + if not any(segments) and len(segments) == 1: + return None + return tuple(segments) + + +def _plain_text(text: str) -> bool: + """Every character printable, and the plain space the only whitespace.""" + return all(ch == " " or (ch.isprintable() and not ch.isspace()) for ch in text) + + +def plain_command(command: object) -> bool: + """Whether *command*, exactly as the host recovered it, may be granted at all. + + Not empty, at most :data:`MAX_COMMAND_LENGTH`, none of + :data:`UNGRANTABLE_COMMAND_CHARS`, and no control character or whitespace but + the plain space: a non-breaking space or a tab names a different path to the + shell while looking the same, so a grant for ``rm scratch`` never covers + ``rm scratch`` plus an invisible character. Never stripped or rewritten: the + command matched is the command that runs. + """ + return ( + isinstance(command, str) + and bool(command) + and len(command) <= MAX_COMMAND_LENGTH + and not UNGRANTABLE_COMMAND_CHARS.intersection(command) + and _plain_text(command) + ) + + +def matches(segments: tuple[str, ...], command: str) -> bool: + """Whether *command* is the whole of what *segments* describe. + + Linear in the command's length times the segment count: the first segment is a + prefix, the last a suffix, and each middle one is found left to right after the + previous, which is exactly what a greedy ``.*`` between literals accepts. + """ + if len(segments) == 1: + return command == segments[0] + first, *middle, last = segments + if not command.startswith(first) or len(command) < len(first) + len(last): + return False + if not command.endswith(last): + return False + pos = len(first) + end = len(command) - len(last) + for seg in middle: + found = command.find(seg, pos, end) + if found < 0: + return False + pos = found + len(seg) + return True diff --git a/src/kiro_crew/providers/acp_turns.py b/src/kiro_crew/providers/acp_turns.py index d26d58c67a25..d959b1d06fa9 100644 --- a/src/kiro_crew/providers/acp_turns.py +++ b/src/kiro_crew/providers/acp_turns.py @@ -92,6 +92,8 @@ def _to_llm_event(e: Any) -> LLMEvent: # Dropping this would leave every spec-granted KAS built-in prompting on # this surface: the gate's spec-builtin-grant row reads it. spec_granted_builtins=e.spec_granted_builtins, + # Same row: dropping this would leave every allowedCommands match prompting. + spec_granted_commands=e.spec_granted_commands, # Dropping this would refuse every deepseek read on a side turn. deepseek_tool_name=e.deepseek_tool_name, # Dropping this would let a READ_ONLY turn on an unproved dsh diff --git a/test/test_hooks.py b/test/test_hooks.py index 87616a6b8b36..2d5f76593f85 100644 --- a/test/test_hooks.py +++ b/test/test_hooks.py @@ -576,6 +576,7 @@ class TestHookGateKwargs: "mcp_identity_unreadable": "mcp_identity_unreadable", "kas_builtin_ids": "kas_builtin_ids", "spec_granted_builtins": "spec_granted_builtins", + "spec_granted_commands": "spec_granted_commands", "harness_builtin_tool": "harness_builtin_tool", "deepseek_tool_name": "deepseek_tool_name", "spawn_target": "spawn_target", @@ -602,6 +603,7 @@ def test_maps_every_event_field_verbatim(self): mcp_identity_unreadable=True, kas_builtin_ids=True, spec_granted_builtins=frozenset({"execute_bash"}), + spec_granted_commands=("git status",), harness_builtin_tool="web_fetch", deepseek_tool_name="read", spawn_target="helper", @@ -619,6 +621,7 @@ def test_maps_every_event_field_verbatim(self): "mcp_identity_unreadable": True, "kas_builtin_ids": True, "spec_granted_builtins": frozenset({"execute_bash"}), + "spec_granted_commands": ("git status",), "harness_builtin_tool": "web_fetch", "deepseek_tool_name": "read", "spawn_target": "helper", @@ -649,6 +652,7 @@ def test_missing_and_none_fields_take_the_gate_defaults(self): "mcp_identity_unreadable": False, "kas_builtin_ids": False, "spec_granted_builtins": frozenset(), + "spec_granted_commands": (), "harness_builtin_tool": "", "deepseek_tool_name": "", "spawn_target": "", @@ -746,6 +750,7 @@ def test_the_toolcall_from_an_event_is_the_whole_gate_input(self, monkeypatch): probe.mcp_identity_unreadable = True probe.kas_builtin_ids = True probe.spec_granted_builtins = frozenset({""}) + probe.spec_granted_commands = ("",) call = ToolCall.from_event(probe) blank = ToolCall(title="") unfilled = [ @@ -775,6 +780,8 @@ def test_the_toolcall_from_an_event_is_the_whole_gate_input(self, monkeypatch): assert got[kwarg] is True elif kwarg == "spec_granted_builtins": assert got[kwarg] == frozenset({f"<{attr}>"}) + elif kwarg == "spec_granted_commands": + assert got[kwarg] == (f"<{attr}>",) else: assert got[kwarg] == f"<{attr}>", kwarg diff --git a/test/test_kas_allowed_commands.py b/test/test_kas_allowed_commands.py new file mode 100644 index 000000000000..2e684563defd --- /dev/null +++ b/test/test_kas_allowed_commands.py @@ -0,0 +1,407 @@ +"""A spec's ``toolsSettings.shell.allowedCommands`` on KAS: a matching command runs +without a prompt, and Crew's own checks still run on it. + +On kiro-cli a command one of these patterns matches (anchored at both ends) runs +unprompted. KAS gets no shell allow rule (``kas_permissions.WITHHELD_CAPABILITIES``: +an auto-approved call raises no permission request, so the deny floor would never +see it), so every command reaches Crew's gate as a permission request, and the +``spec-builtin-grant`` tier answers one whose recovered command fullmatches a +pattern -- after every deny tier and governance, and never for a command that +chains, pipes, redirects or substitutes. +""" + +from __future__ import annotations + +import dataclasses +from pathlib import Path +from typing import Any + +import pytest +from test_kas_spec_builtin_grant import _handle, _permission +from test_tool_call_classification_kas import _kas_builtin_flow + +from kiro_crew.acp import kas_agents +from kiro_crew.acp._dispatch import attach_kas_custom_agents +from kiro_crew.acp.kas_permissions import ( + CREW_ANSWERED_COMMANDS_KEY, + allowed_command_pattern, + crew_answered_commands, + tools_settings_to_permissions, +) +from kiro_crew.acp.types import AcpEvent +from kiro_crew.acp_backends import ACP_BACKEND_KAS +from kiro_crew.hooks import ( + TOOL_ALLOW, + TOOL_AUTO_APPROVE, + TOOL_DENY, + HookManager, + HooksConfig, + hook_gate_kwargs, +) +from kiro_crew.platform import context as ctx_mod +from kiro_crew.platform import governance_profiles as gp +from kiro_crew.platform.bootstrap import build_default_context +from kiro_crew.platform.governance import parse_policy + +#: Spelled in two pieces so this file's own text is not one destructive command line. +_DESTRUCTIVE = "rm " + "-rf /" + + +@pytest.fixture(autouse=True) +def _no_profiles(tmp_path: Path, _floor_monkeypatch: pytest.MonkeyPatch): + profiles = tmp_path / "profiles" + profiles.mkdir() + _floor_monkeypatch.setattr(gp, "_PROFILES_DIR", profiles) + gp.reset_store() + yield + gp.reset_store() + ctx_mod.reset_context() + + +def _shell(command: str) -> AcpEvent: + return _kas_builtin_flow( + "run_command", title="Run Command", kind="execute", raw_input={"command": command} + ) + + +def _judge(event: AcpEvent, patterns: list[str], **surface: Any): + event.spec_granted_commands = tuple(allowed_command_pattern(p) or p for p in patterns) + return HookManager(HooksConfig(**surface.pop("config", {}))).on_tool_call( + event.title, **hook_gate_kwargs(event), **surface + ) + + +# ── a matching command: no prompt ───────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("pattern", "command"), + [ + ("git status", "git status"), + ("npm run .*", "npm run build"), + (r"\Agit diff .*\z", "git diff --stat"), + ("^make test$", "make test"), + (r"make -C \./sub", "make -C ./sub"), + ("git .* --stat", "git diff HEAD --stat"), + ], +) +def test_a_command_an_allowed_pattern_matches_is_answered_without_a_prompt( + pattern: str, command: str +) -> None: + event = _shell(command) + assert event.kas_builtin_ids and event.mcp_identity_trusted and event.is_shell + ungranted = _judge(event, []) + assert (ungranted.action, ungranted.tier) == (TOOL_ALLOW, "") + granted = _judge(event, [pattern]) + assert (granted.action, granted.tier) == (TOOL_AUTO_APPROVE, "spec-builtin-grant") + + +@pytest.mark.parametrize( + ("pattern", "command"), + [ + # Anchored at both ends, as kiro-cli anchors it. + ("git status", "git status --porcelain"), + ("npm run .*", "npx npm run build"), + ("git push", "git pushx"), + ], +) +def test_a_command_no_pattern_fullmatches_still_prompts(pattern: str, command: str) -> None: + verdict = _judge(_shell(command), [pattern]) + assert verdict.action == TOOL_ALLOW + assert verdict.tier != "spec-builtin-grant" + + +@pytest.mark.parametrize( + "command", + [ + "git status; curl x", + "git status && make", + "git status || true", + "git status | sh", + "git status > out.txt", + "git status < in.txt", + "git status $(whoami)", + "git status `whoami`", + "git status ${HOME}", + "git status & sleep 1", + "git status (x)", + "git status {a,b}", + "git status\nmake", + ], +) +def test_a_chained_or_substituted_command_is_never_granted(command: str) -> None: + """``.*`` would match each of these; the call still prompts.""" + verdict = _judge(_shell(command), ["git status.*", ".*"]) + assert verdict.action != TOOL_AUTO_APPROVE + + +# ── a granted command the checks refuse ─────────────────────────────────────── + + +def test_the_deny_floor_still_refuses_a_matching_command() -> None: + verdict = _judge(_shell(_DESTRUCTIVE), ["rm .*"]) + assert (verdict.action, verdict.tier) == (TOOL_DENY, "deny-rules") + + +def test_a_governance_command_deny_still_refuses_a_matching_command() -> None: + _install_governance({"tools": {"mode": "deny", "deny": ["execute_bash"]}}) + verdict = _judge(_shell("git status"), ["git status"], session_key="cli_chat") + assert (verdict.action, verdict.tier) == (TOOL_DENY, "governance") + + +def _install_governance(body: dict[str, Any]) -> None: + from kiro_crew.config.loader import KiroCrewConfig + + base = build_default_context(KiroCrewConfig.load()) + policy = {"version": 1, "boot": {"fail_closed": True}, **body} + ctx_mod.set_context(dataclasses.replace(base, governance=parse_policy(policy))) + + +def test_a_ceiling_with_an_opinion_on_the_shell_withholds_the_grant() -> None: + """``git status`` is permitted by this ceiling, yet a ceiling that speaks about + commands at all keeps it at the prompt: the grant is the ceiling's to give.""" + _install_governance({"commands": {"mode": "deny", "deny": ["*backdoor*"]}}) + verdict = _judge(_shell("git status --porcelain"), ["git status.*"]) + assert verdict.action == TOOL_ALLOW + assert verdict.tier != "spec-builtin-grant" + + +def test_confirm_tools_withholds_the_grant() -> None: + verdict = _judge(_shell("git status"), ["git status"], config={"confirm_tools": ["*"]}) + assert verdict.action == TOOL_ALLOW + + +def test_an_unattended_read_only_surface_ignores_the_grant() -> None: + verdict = _judge(_shell("make build"), ["make build"], classifier_only=True) + assert verdict.action != TOOL_AUTO_APPROVE + + +def test_a_pattern_grants_only_the_shell_tool() -> None: + event = _kas_builtin_flow("read_file", raw_input={"path": "/tmp/probe-note.txt"}) + assert _judge(event, [".*"]).tier != "spec-builtin-grant" + + +@pytest.mark.parametrize( + "change", + [{"mcp_identity_trusted": False}, {"kas_builtin_ids": False}], + ids=["untrusted-identity", "not-kas"], +) +def test_only_a_host_identified_shell_call_is_granted(change: dict[str, Any]) -> None: + event = _shell("git status") + for name, value in change.items(): + setattr(event, name, value) + assert _judge(event, ["git status"]).action != TOOL_AUTO_APPROVE + + +def test_a_shell_call_whose_command_was_not_recovered_is_never_granted() -> None: + event = _kas_builtin_flow("run_command", title="Run Command", kind="execute", raw_input={}) + assert _judge(event, [".*"]).action != TOOL_AUTO_APPROVE + + +# ── the patterns and the projection ─────────────────────────────────────────── + + +def test_only_the_subset_both_engines_read_alike_is_kept() -> None: + assert allowed_command_pattern(r"\Agit status\z") == r"\Agit status\z" + # Verbatim: a pattern's own spaces are part of what it grants. + assert allowed_command_pattern("ls -la ") == "ls -la " + for bad in ( + "", + "x" * 1025, + "(unclosed", + 7, + None, + # Rust reads a POSIX class; Python reads a set of the characters `[:alph`. + "rm [[:alpha:]]+", + # Nested repetition, which Python's engine backtracks on without bound. + "echo (a+)+", + "make (all|test)", + r"ls \d+", + "make ?", + "a.b", + "rm scratch\u00a0", + "git\tstatus", + "ls\x00", + ): + assert allowed_command_pattern(bad) is None, bad + + +@pytest.mark.parametrize( + ("pattern", "command"), + [ + ("rm [[:alpha:]]+", "rm a]"), + ("make (a+)+", "make " + "a" * 32 + "!"), + ], +) +def test_a_pattern_outside_the_subset_grants_nothing(pattern: str, command: str) -> None: + """Python would read the first one wider than kiro-cli does, and stall on the second.""" + event = _shell(command) + event.spec_granted_commands = (pattern,) + verdict = HookManager(HooksConfig()).on_tool_call(event.title, **hook_gate_kwargs(event)) + assert verdict.action != TOOL_AUTO_APPROVE + + +@pytest.mark.parametrize( + "command", + [ + "rm scratch\u00a0", + "\u00a0rm scratch", + " rm scratch", + "rm scratch ", + "rm\tscratch", + "rm scratch\x07", + ], +) +def test_a_command_is_matched_verbatim(command: str) -> None: + """Stripping or folding the command would approve a path the grant never named.""" + verdict = _judge(_shell(command), ["rm scratch"]) + assert verdict.action != TOOL_AUTO_APPROVE or verdict.tier != "spec-builtin-grant" + + +@pytest.mark.parametrize("command", ["rm scratch\u00a0", "rm a\tb", "rm a\x07"]) +def test_a_wildcard_never_covers_an_invisible_character(command: str) -> None: + verdict = _judge(_shell(command), ["rm .*"]) + assert verdict.action != TOOL_AUTO_APPROVE or verdict.tier != "spec-builtin-grant" + + +def test_matching_is_greedy_wildcards_between_literals() -> None: + from kiro_crew.platform.allowed_commands import matches, parse + + segs = parse("git .* --stat") + assert segs == ("git ", " --stat") + assert matches(segs, "git diff --stat") + assert not matches(segs, "git --stat") + assert matches(parse("a.*b.*c"), "axbyc") + assert not matches(parse("a.*b.*c"), "acb") + assert matches(parse("npm run .*"), "npm run ") + assert not matches(parse("git status"), "git status ") + + +def test_crew_answered_commands_reads_both_shell_keys() -> None: + settings = { + "shell": {"allowedCommands": ["git status", "(bad", "git status"]}, + "execute_bash": {"allowedCommands": ["make .*"]}, + "read": {"allowedCommands": ["ignored"]}, + } + assert crew_answered_commands(settings) == ["make .*", "git status"] + assert crew_answered_commands(None) == [] + + +def test_allowed_commands_are_named_only_when_a_pattern_cannot_be_used() -> None: + assert tools_settings_to_permissions({"shell": {"allowedCommands": ["git status"]}}) == ( + None, + [], + ) + assert tools_settings_to_permissions({"shell": {"allowedCommands": ["(bad"]}})[1] == [ + "shell.allowedCommands" + ] + + +def test_an_allow_list_over_the_bound_is_named() -> None: + patterns = [f"make target{i}" for i in range(65)] + settings = {"shell": {"allowedCommands": patterns}} + assert len(crew_answered_commands(settings)) == 64 + assert tools_settings_to_permissions(settings)[1] == ["shell.allowedCommands"] + + +@pytest.mark.parametrize( + "extra", + [ + {"permissions": {"rules": [{"capability": "shell", "effect": "ask"}]}}, + {"toolsSettings": {"shell": {"allowedCommands": ["git status"], "deniedCommands": ["x"]}}}, + ], + ids=["authored-ask", "denied-commands"], +) +def test_the_notice_names_allowed_commands_the_session_withholds(extra: dict[str, Any]) -> None: + spec = _spec(**{"toolsSettings": {"shell": {"allowedCommands": ["git status"]}}, **extra}) + lost = kas_agents.spec_keys_without_carrier(spec, translates_tools_settings=True) + assert "toolsSettings.shell.allowedCommands" in lost + + +def test_the_notice_names_allowed_commands_the_ceiling_withholds(monkeypatch) -> None: + spec = _spec(toolsSettings={"shell": {"allowedCommands": ["git status"]}}) + assert kas_agents.spec_keys_without_carrier(spec, translates_tools_settings=True) == [] + monkeypatch.setattr(kas_agents, "may_grant_builtin_at_gate_now", lambda ref: False) + assert kas_agents.spec_keys_without_carrier(spec, translates_tools_settings=True) == [ + "toolsSettings.shell.allowedCommands" + ] + + +def _spec(**extra: Any) -> dict[str, Any]: + return {"name": "a", "prompt": "p", "tools": ["*"], **extra} + + +def test_the_projection_records_the_patterns_and_relays_no_shell_allow() -> None: + spec = _spec(toolsSettings={"shell": {"allowedCommands": ["git status", r"npm run .*\z"]}}) + out = kas_agents.to_client_custom_agent("a", spec, "p") + assert out[CREW_ANSWERED_COMMANDS_KEY] == ["git status", r"npm run .*\z"] + rules = out.get("permissions", {}).get("rules", []) + assert not [r for r in rules if r["capability"] == "shell" and r["effect"] == "allow"] + + +@pytest.mark.parametrize( + "extra", + [ + {"permissions": {"rules": [{"capability": "shell", "effect": "ask"}]}}, + {"toolsSettings": {"shell": {"allowedCommands": ["git status"], "denyByDefault": True}}}, + {"toolsSettings": {"shell": {"allowedCommands": ["git status"], "deniedCommands": ["x"]}}}, + ], + ids=["authored-ask", "other-shell-setting", "denied-commands"], +) +def test_an_authored_shell_restriction_withholds_the_patterns(extra: dict[str, Any]) -> None: + """The spec's own author restricted the shell, so its commands keep prompting, + as a shell grant in `allowedTools` does under the same restriction.""" + spec = _spec(**{"toolsSettings": {"shell": {"allowedCommands": ["git status"]}}, **extra}) + assert CREW_ANSWERED_COMMANDS_KEY not in kas_agents.to_client_custom_agent("a", spec, "p") + + +def test_the_grant_itself_is_not_read_as_a_restriction() -> None: + from kiro_crew.acp.kas_permissions import without_allowed_commands + + assert without_allowed_commands({"shell": {"allowedCommands": ["x"]}, "read": {"a": 1}}) == { + "read": {"a": 1} + } + assert without_allowed_commands( + {"execute_bash": {"allowedCommands": ["x"], "denyByDefault": True}} + ) == {"execute_bash": {"denyByDefault": True}} + assert without_allowed_commands("bad") == "bad" + + +def test_a_ceiling_that_withholds_the_shell_records_no_patterns(monkeypatch) -> None: + monkeypatch.setattr(kas_agents, "may_grant_builtin_at_gate_now", lambda ref: False) + spec = _spec(toolsSettings={"shell": {"allowedCommands": ["git status"]}}) + assert CREW_ANSWERED_COMMANDS_KEY not in kas_agents.to_client_custom_agent("a", spec, "p") + + +def test_the_patterns_never_reach_the_wire() -> None: + spec = _spec(toolsSettings={"shell": {"allowedCommands": ["git status"]}}) + entry = kas_agents.to_client_custom_agent("a", spec, "p") + params: dict[str, Any] = {} + attach_kas_custom_agents(params, [entry]) + (wire,) = params["_meta"]["kiro"]["customAgents"] + assert CREW_ANSWERED_COMMANDS_KEY not in wire + assert CREW_ANSWERED_COMMANDS_KEY in entry + + +def test_the_session_record_follows_the_active_agent_and_a_mode_switch() -> None: + from kiro_crew.agent_files import kas_wire_agent_id + + batch = [ + {"id": "vibe", "prompt": "p", CREW_ANSWERED_COMMANDS_KEY: ["git status", 7]}, + {"id": "other", "prompt": "p"}, + ] + assert kas_agents.projected_crew_answered_commands(batch, "vibe") == ("git status",) + assert kas_agents.projected_crew_answered_commands(batch, "missing") == () + assert kas_agents.switched_crew_answered_commands(batch, kas_wire_agent_id("vibe")) == ( + "git status", + ) + assert kas_agents.switched_crew_answered_commands(batch, "other") == () + + +def test_the_handle_stamps_the_patterns_on_its_own_request_only() -> None: + handle = _handle(ACP_BACKEND_KAS) + handle.kas_crew_answered_commands = ("git status",) + own = handle._build_permission_event(_permission("own-sid")) + child = handle._build_permission_event(_permission("child-sid")) + assert own is not None and own.spec_granted_commands == ("git status",) + assert child is not None and child.spec_granted_commands == () diff --git a/test/test_kas_tools_settings.py b/test/test_kas_tools_settings.py index 67bd47e6e018..8a410728668a 100644 --- a/test/test_kas_tools_settings.py +++ b/test/test_kas_tools_settings.py @@ -114,16 +114,14 @@ def test_shell_and_filesystem_allows_never_become_rules(self): "write": {"allowedPaths": ["./out/**"]}, } assert _rules(settings) == [] - assert _lost(settings) == [ - "read.allowedPaths", - "shell.allowedCommands", - "write.allowedPaths", - ] + # allowedCommands is answered by Crew at the gate, not by a rule + # (`test_kas_allowed_commands.py`), so only the path allows are named. + assert _lost(settings) == ["read.allowedPaths", "write.allowedPaths"] def test_deny_by_default_is_reported_not_translated(self): settings = {"shell": {"allowedCommands": ["git status"], "denyByDefault": True}} assert _rules(settings) == [] - assert _lost(settings) == ["shell.allowedCommands", "shell.denyByDefault"] + assert _lost(settings) == ["shell.denyByDefault"] def test_write_fallback_deny_is_reported_not_translated(self): settings = {"fs_write": {"allowedPaths": ["./out/**"], "fallbackAction": "deny"}}