517 lines
22 KiB
Python
517 lines
22 KiB
Python
"""kuri-tool-guard — guard functions for tool-call policies."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import ast
|
||
import logging
|
||
import os
|
||
import time
|
||
import urllib.parse
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from . import _parser, _predicates, _state
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 1 — Home root search (Hermes search tools)
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
|
||
def _guard_home_root(args: dict[str, Any]) -> dict[str, str] | None:
|
||
"""Block search_files/search when path targets home root."""
|
||
path = args.get("path", "")
|
||
if not isinstance(path, str) or not path:
|
||
return None
|
||
if _state._path_is_protected_home_root(path):
|
||
logger.warning("kuri-tool-guard: home-root blocked search_files(path=%r)", path)
|
||
return {"action": "block", "message": _state._HOME_ROOT_SEARCH_MSG}
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 2 — Terminal file writes
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
|
||
def _guard_terminal(args: dict[str, Any]) -> dict[str, str] | None:
|
||
"""Block terminal when command violates file policies."""
|
||
command = args.get("command", "")
|
||
if not isinstance(command, str) or not command:
|
||
return None
|
||
reason = _predicates._match_terminal_predicate(command)
|
||
if reason is None:
|
||
return None
|
||
logger.warning("kuri-tool-guard: terminal blocked (%s): %r", reason, command[:120])
|
||
if reason == "cat_terminal":
|
||
return {"action": "block", "message": _predicates._CAT_TERMINAL_MSG}
|
||
if reason == _predicates._BOUNDED_OUTPUT_MSG:
|
||
return {"action": "block", "message": reason}
|
||
return {"action": "block", "message": _predicates._SHELL_WRITE_MSG}
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 3 — write_file on existing file
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_WRITE_FILE_MSG = (
|
||
"write_file 僅用於建立新檔案;目標檔案已存在。" # noqa: RUF001
|
||
"直接覆寫會略過 plugin 安全檢查且原有內容不可回復。"
|
||
"請先用 read_file 確認目前內容,再用 patch 修改需要變更的區段。" # noqa: RUF001
|
||
"不要改用其他工具或操作順序繞過這個限制。"
|
||
)
|
||
|
||
|
||
def _guard_write_file(args: dict[str, Any]) -> dict[str, str] | None:
|
||
"""Block write_file when the target path already exists."""
|
||
path = args.get("path", "")
|
||
if not isinstance(path, str) or not path:
|
||
return None
|
||
if os.path.exists(os.path.expanduser(path)):
|
||
logger.warning("kuri-tool-guard: write_file blocked existing file: %r", path)
|
||
return {"action": "block", "message": _WRITE_FILE_MSG}
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 4 — patch on memory files
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_MEMORY_PATHS: frozenset[tuple[str, ...]] = frozenset(
|
||
{
|
||
("memories", "MEMORY.md"),
|
||
("memories", "USER.md"),
|
||
}
|
||
)
|
||
|
||
_PATCH_MEMORY_MSG = (
|
||
"不允許直接 patch memories/MEMORY.md 或 memories/USER.md。"
|
||
"這些 canonical 記憶檔案由 memory 工具管理。"
|
||
"請先用 read_file 唯讀檢查。需要變更時使用 memory 工具。"
|
||
)
|
||
|
||
|
||
def _guard_patch_memory(args: dict[str, Any]) -> dict[str, str] | None:
|
||
"""Block patch when path ends with memories/MEMORY.md or memories/USER.md."""
|
||
path = args.get("path", "")
|
||
if not isinstance(path, str) or not path:
|
||
return None
|
||
expanded = os.path.expandvars(os.path.expanduser(path))
|
||
normalized = os.path.normpath(expanded)
|
||
parts = Path(normalized).parts
|
||
if len(parts) >= 2 and parts[-2:] in _MEMORY_PATHS:
|
||
logger.warning("kuri-tool-guard: patch blocked on memory path: %r", path)
|
||
return {"action": "block", "message": _PATCH_MEMORY_MSG}
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 11 — Skill directory lockdown (patch / write_file)
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_SKILL_DIR_MSG = (
|
||
"不允許用 patch/write_file 直接修改 Hermes skill 目錄下的檔案。" # noqa: RUF001
|
||
"skill 檔案一律用 skill_manage 編輯,依其 action(patch/edit/write_file/remove_file)" # noqa: RUF001
|
||
"與 file_path 操作。請改用 skill_manage,不要繞過。" # noqa: RUF001
|
||
)
|
||
|
||
_SKILL_DIR_UNRESOLVED_MSG = (
|
||
"路徑含無法解析的變數或使用者 token($VAR/~user/%VAR%),無法確認是否落在 " # noqa: RUF001
|
||
"Hermes skill 目錄;patch/write_file 不是修改 skill 的正規入口,保守阻擋。 " # noqa: RUF001
|
||
"請改用已解析的絕對路徑,或直接用 skill_manage(action/file_path)。" # noqa: RUF001
|
||
)
|
||
|
||
_SKILL_DIR_NO_HOME_MSG = (
|
||
"無法解析 Hermes home(HERMES_HOME 未設定且 Path.home() 不可用),無法判定 " # noqa: RUF001
|
||
"路徑是否落在 skill 目錄;patch/write_file 不是修改 skill 的正規入口,保守阻擋。 " # noqa: RUF001
|
||
"請直接用 skill_manage(action/file_path)。" # noqa: RUF001
|
||
)
|
||
|
||
|
||
def _guard_skill_dir(tool_name: str, args: dict[str, Any]) -> dict[str, str] | None:
|
||
"""Block patch/write_file targeting any Hermes skill root."""
|
||
path = args.get("path", "")
|
||
if not isinstance(path, str) or not path:
|
||
return None
|
||
if _state._path_has_unresolved_token(path):
|
||
logger.warning(
|
||
"kuri-tool-guard: %s blocked on unresolvable path token: %r",
|
||
tool_name,
|
||
path,
|
||
)
|
||
return {"action": "block", "message": _SKILL_DIR_UNRESOLVED_MSG}
|
||
if _state._get_hermes_home() is None:
|
||
logger.warning("kuri-tool-guard: %s blocked: Hermes home unresolvable", tool_name)
|
||
return {"action": "block", "message": _SKILL_DIR_NO_HOME_MSG}
|
||
if _state._path_is_under_skill_root(path):
|
||
logger.warning("kuri-tool-guard: %s blocked on skill path: %r", tool_name, path)
|
||
return {"action": "block", "message": _SKILL_DIR_MSG}
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 5 — GitHub.com web access block
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_GITHUB_WEB_TOOLS = frozenset({"web_extract", "browser_navigate"})
|
||
|
||
_GITHUB_WEB_MSG = (
|
||
"不允許用 web_extract 或 browser 工具存取 github.com。"
|
||
"請改用 gh CLI,它提供可驗證的 GitHub 操作與授權流程。" # noqa: RUF001
|
||
)
|
||
_RAW_GITHUB_WEB_MSG = (
|
||
"不允許用 web_extract 或 browser 工具存取 raw.githubusercontent.com。"
|
||
"請改用 curl 透過 terminal 下載。"
|
||
)
|
||
|
||
_GITHUB_DOMAIN = "github.com"
|
||
_RAW_GITHUB_DOMAIN = "raw.githubusercontent.com"
|
||
|
||
|
||
def _get_block_message(hostname: str) -> str | None:
|
||
"""Return block message for a parsed hostname, or None."""
|
||
if hostname == _GITHUB_DOMAIN or hostname.endswith("." + _GITHUB_DOMAIN):
|
||
return _GITHUB_WEB_MSG
|
||
if hostname == _RAW_GITHUB_DOMAIN:
|
||
return _RAW_GITHUB_WEB_MSG
|
||
return None
|
||
|
||
|
||
def _is_github_url(candidate: str) -> str | None:
|
||
"""Return error message if *candidate* contains a blocked GitHub domain, else None."""
|
||
lower = candidate.lower().strip()
|
||
|
||
# Bare domain (no scheme, no path) — exact match
|
||
msg = _get_block_message(lower)
|
||
if msg:
|
||
return msg
|
||
|
||
# Full URL with scheme — parse hostname
|
||
if "://" in lower:
|
||
parsed = urllib.parse.urlsplit(lower)
|
||
if parsed.hostname:
|
||
return _get_block_message(parsed.hostname)
|
||
|
||
return None
|
||
|
||
|
||
def _guard_github_web(args: dict[str, Any]) -> dict[str, str] | None:
|
||
"""Block web_extract / browser_navigate for github.com and raw.githubusercontent.com."""
|
||
|
||
def _check(url: str) -> dict[str, str] | None:
|
||
msg = _is_github_url(url)
|
||
if msg is not None:
|
||
logger.warning("kuri-tool-guard: github web blocked url=%r", url)
|
||
return {"action": "block", "message": msg}
|
||
return None
|
||
|
||
# web_extract(urls=[...])
|
||
if "urls" in args and isinstance(args["urls"], list):
|
||
for u in args["urls"]:
|
||
if isinstance(u, str):
|
||
result = _check(u)
|
||
if result:
|
||
return result
|
||
# browser_navigate(url=...)
|
||
if "url" in args and isinstance(args["url"], str):
|
||
return _check(args["url"])
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 6 — Consecutive process(action='poll') block
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_PROCESS_POLL_MSG = (
|
||
"不允許在沒有其他工具呼叫的情況下連續第三次 process(action='poll')。"
|
||
"短時間重複查看通常不會產生新結果,且會佔用工具額度。" # noqa: RUF001
|
||
"下次記得在啟動工作時設定 notify_on_complete=true 並等待通知。"
|
||
"若未設定,請先等待一段合理的時間再查看。" # noqa: RUF001
|
||
)
|
||
|
||
|
||
def _guard_process_poll(
|
||
tool_name: str,
|
||
args: dict[str, Any],
|
||
session_id: str,
|
||
) -> dict[str, str] | None:
|
||
"""Track consecutive polls; block on the 3rd in a row.
|
||
|
||
Any non-poll tool (or process with non-poll action) resets the counter.
|
||
"""
|
||
now = time.time()
|
||
with _state._LOCK:
|
||
_state._cleanup_poll_state(now)
|
||
if tool_name == "process" and args.get("action") == "poll":
|
||
prior_count = _state._POLL_STATE.get(session_id, (0, now))[0]
|
||
if (
|
||
session_id not in _state._POLL_STATE
|
||
and len(_state._POLL_STATE) >= _state._POLL_STATE_MAX_SESSIONS
|
||
):
|
||
_state._evict_oldest_poll_session()
|
||
count = prior_count + 1
|
||
_state._POLL_STATE[session_id] = (count, now)
|
||
else:
|
||
_state._POLL_STATE.pop(session_id, None)
|
||
return None
|
||
|
||
if tool_name == "process" and args.get("action") == "poll":
|
||
if count >= 3:
|
||
logger.warning(
|
||
"kuri-tool-guard: consecutive poll blocked (session=%s, count=%d)",
|
||
session_id,
|
||
count,
|
||
)
|
||
return {"action": "block", "message": _PROCESS_POLL_MSG}
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 7 — cron/jobs.json file block
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_CRON_JOBS_JSON_TOOLS = frozenset({"write_file", "patch"})
|
||
_CRON_JOBS_JSON_MARKER = "cron/jobs.json"
|
||
|
||
_CRON_JOBS_JSON_MSG = (
|
||
"不允許直接寫入或修改 cron/jobs.json。新增任務請用 cronjob create。修改請用 cronjob update。"
|
||
)
|
||
|
||
|
||
def _guard_cron_jobs_json(
|
||
tool_name: str,
|
||
args: dict[str, Any],
|
||
) -> dict[str, str] | None:
|
||
"""Block any file operation targeting cron/jobs.json."""
|
||
if tool_name not in _CRON_JOBS_JSON_TOOLS or not isinstance(args, dict):
|
||
return None
|
||
|
||
if tool_name == "terminal":
|
||
command = args.get("command", "")
|
||
if isinstance(command, str) and _CRON_JOBS_JSON_MARKER in command:
|
||
logger.warning(
|
||
"kuri-tool-guard: blocked terminal on cron/jobs.json: %r",
|
||
command[:120],
|
||
)
|
||
return {"action": "block", "message": _CRON_JOBS_JSON_MSG}
|
||
else:
|
||
path = args.get("path", "")
|
||
if isinstance(path, str) and path.replace("\\", "/").endswith(_CRON_JOBS_JSON_MARKER):
|
||
logger.warning(
|
||
"kuri-tool-guard: blocked %s on cron/jobs.json (path=%r)",
|
||
tool_name,
|
||
path,
|
||
)
|
||
return {"action": "block", "message": _CRON_JOBS_JSON_MSG}
|
||
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 8 — Terminal home-root operand guard + locate block
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
|
||
def _is_locate_command(tokens: list[str]) -> bool:
|
||
"""True if the effective command (after wrapper skips) is locate/plocate/mlocate."""
|
||
idx = _parser._first_command_token_index(tokens)
|
||
return idx < len(tokens) and os.path.basename(tokens[idx]) in _state._LOCATE_COMMANDS
|
||
|
||
|
||
def _guard_terminal_home_root(args: dict[str, Any]) -> dict[str, str] | None:
|
||
"""Block terminal when any command segment uses a protected home root as operand.
|
||
|
||
Also blocks locate/plocate/mlocate unconditionally (system-wide index).
|
||
"""
|
||
command = args.get("command", "")
|
||
if not isinstance(command, str) or not command:
|
||
return None
|
||
|
||
all_tokens = _parser._get_command_tokens(command)
|
||
if not all_tokens:
|
||
return None
|
||
|
||
# Check locate before operand check (locate has no path operand)
|
||
for tokens in all_tokens:
|
||
if _is_locate_command(tokens):
|
||
logger.warning("kuri-tool-guard: terminal blocked (locate): %r", command[:120])
|
||
return {"action": "block", "message": _state._LOCATE_MSG}
|
||
|
||
# Check each token against protected home roots
|
||
for tokens in all_tokens:
|
||
for token in tokens: # includes command name and all args
|
||
if _state._token_is_home_root_operand(token):
|
||
logger.warning(
|
||
"kuri-tool-guard: terminal blocked (home-root operand %r): %r",
|
||
token,
|
||
command[:120],
|
||
)
|
||
return {"action": "block", "message": _state._HOME_ROOT_TERMINAL_MSG}
|
||
|
||
return None
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
# Guard 9 — execute_code per-call home-root protection
|
||
# ═══════════════════════════════════════════════════════════════════
|
||
|
||
_HOME_ROOT_EXECUTE_CODE_MSG = (
|
||
"不允許把目前有效 Unix 帳號的整個 home root 當作 traversal operand。"
|
||
"請指定更窄的子路徑。"
|
||
"使用 Hermes profile 內的路徑時。請透過環境變數或明確的相對路徑。"
|
||
)
|
||
|
||
|
||
def _call_arg_is_protected_root(node: ast.Call, arg_idx: int) -> bool:
|
||
if arg_idx >= len(node.args):
|
||
return False
|
||
arg = node.args[arg_idx]
|
||
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
|
||
expanded = os.path.expandvars(arg.value)
|
||
return _state._path_is_protected_home_root(expanded)
|
||
return False
|
||
|
||
|
||
def _glob_pattern_starts_with_root(pattern: str) -> bool:
|
||
"""Check if a glob pattern's fixed base equals a protected home root.
|
||
|
||
Resolves ``~`` via passwd home (not ``$HOME``) first, then extracts
|
||
the fixed path before the first glob metacharacter.
|
||
"""
|
||
protected = _state._get_protected_home_roots()
|
||
if not protected:
|
||
return False
|
||
expanded = os.path.expandvars(pattern)
|
||
# Resolve leading ~ via passwd home (not $HOME)
|
||
passwd_home = _state._get_passwd_home()
|
||
if passwd_home and (expanded == "~" or expanded.startswith("~/")):
|
||
expanded = _state._resolve_tilde(expanded, passwd_home)
|
||
elif expanded.startswith("~"):
|
||
expanded = os.path.expanduser(expanded)
|
||
# Find the first glob metacharacter
|
||
base = expanded
|
||
for i, c in enumerate(expanded):
|
||
if c in ("*", "?", "["):
|
||
base = expanded[:i].rstrip("/")
|
||
break
|
||
return os.path.normpath(base) in protected
|
||
|
||
|
||
def _os_system_hits_home_root(cmd: str) -> bool:
|
||
all_tokens = _parser._get_command_tokens(cmd)
|
||
if not all_tokens:
|
||
return False
|
||
for tokens in all_tokens:
|
||
for token in tokens:
|
||
if _state._token_is_home_root_operand(token):
|
||
return True
|
||
return False
|
||
|
||
|
||
def _is_path_method_call(node: ast.Call) -> bool:
|
||
return (
|
||
isinstance(node.func, ast.Attribute)
|
||
and isinstance(node.func.value, ast.Call)
|
||
and isinstance(node.func.value.func, ast.Name)
|
||
and node.func.value.func.id == "Path"
|
||
)
|
||
|
||
|
||
# Static-analysis limitations:
|
||
# - Dynamic string construction: ``f"/home/{user}"`` where user is runtime
|
||
# - eval/exec: string content opaque to AST
|
||
# - Custom recursive wrapper functions
|
||
# - os.listdir with manual recursive loops (semantically equal to os.walk)
|
||
# - Encoded/obfuscated path strings
|
||
# - Import aliases (e.g. ``import os.path as op``)
|
||
|
||
|
||
def _check_ast_walk(node: ast.Call) -> bool:
|
||
"""Check if ``os.walk(path)`` has a protected-root first arg."""
|
||
return _call_arg_is_protected_root(node, 0)
|
||
|
||
|
||
def _check_ast_path_method(node: ast.Call) -> bool:
|
||
"""Check if ``Path(...).rglob(pattern)`` has a protected Path arg."""
|
||
return (
|
||
_is_path_method_call(node) and _call_arg_is_protected_root(node.func.value, 0) # type: ignore
|
||
)
|
||
|
||
|
||
def _check_ast_recursive_glob(node: ast.Call) -> bool:
|
||
"""Check if ``glob.glob(pattern, recursive=True)`` starts at a protected root."""
|
||
if not isinstance(node.func.value, ast.Name) or node.func.value.id != "glob": # type: ignore
|
||
return False
|
||
has_recursive = any(
|
||
kw.arg == "recursive" and isinstance(kw.value, ast.Constant) and kw.value.value
|
||
for kw in node.keywords
|
||
)
|
||
return bool(
|
||
has_recursive
|
||
and node.args
|
||
and isinstance(node.args[0], ast.Constant)
|
||
and isinstance(node.args[0].value, str)
|
||
and _glob_pattern_starts_with_root(node.args[0].value)
|
||
)
|
||
|
||
|
||
def _check_ast_subprocess(node: ast.Call) -> bool:
|
||
"""Check if ``subprocess.run/popen/call([tool, path, ...])`` contains a root arg."""
|
||
if not node.args:
|
||
return False
|
||
args_list = node.args[0]
|
||
if not isinstance(args_list, (ast.List, ast.Tuple)):
|
||
return False
|
||
for elt in args_list.elts:
|
||
if (
|
||
isinstance(elt, ast.Constant)
|
||
and isinstance(elt.value, str)
|
||
and _state._path_is_protected_home_root(elt.value)
|
||
):
|
||
return True
|
||
return False
|
||
|
||
|
||
def _check_ast_system(node: ast.Call) -> bool:
|
||
"""Check if ``os.system(cmd)`` references a home root operand."""
|
||
if not node.args:
|
||
return False
|
||
cmd_arg = node.args[0]
|
||
return (
|
||
isinstance(cmd_arg, ast.Constant)
|
||
and isinstance(cmd_arg.value, str)
|
||
and _os_system_hits_home_root(cmd_arg.value)
|
||
)
|
||
|
||
|
||
def _guard_execute_code(args: dict[str, Any]) -> dict[str, str] | None:
|
||
"""Block execute_code when a traversal call targets a protected home root.
|
||
|
||
Each traversal call is analysed independently via typed helpers.
|
||
"""
|
||
code = args.get("code", "")
|
||
if not isinstance(code, str) or not code:
|
||
return None
|
||
try:
|
||
tree = ast.parse(code)
|
||
except SyntaxError:
|
||
return None
|
||
|
||
for node in ast.walk(tree):
|
||
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
|
||
continue
|
||
callee = node.func.attr
|
||
|
||
if (
|
||
(callee == "walk" and _check_ast_walk(node))
|
||
or (callee == "rglob" and _check_ast_path_method(node))
|
||
or (callee == "glob" and _check_ast_recursive_glob(node))
|
||
or (callee in ("run", "Popen", "call") and _check_ast_subprocess(node))
|
||
or (callee == "system" and _check_ast_system(node))
|
||
):
|
||
logger.warning("kuri-tool-guard: execute_code blocked (%s)", callee)
|
||
return {"action": "block", "message": _HOME_ROOT_EXECUTE_CODE_MSG}
|
||
|
||
return None
|