kuri-tool-guard/_state.py

258 lines
9.3 KiB
Python

"""kuri-tool-guard — shared state, home-root helpers, mutable poll state."""
from __future__ import annotations
import logging
import os
import pwd
import threading
from collections.abc import Callable
from pathlib import Path
logger = logging.getLogger(__name__)
# ═══════════════════════════════════════════════════════════════════
# Protected home-root helpers
# ═══════════════════════════════════════════════════════════════════
def _build_protected_home_roots(
username: str,
passwd_home: str,
realpath_fn: Callable[[str], str] = os.path.realpath,
) -> frozenset[str]:
raw: set[str] = {passwd_home, f"/home/{username}", f"/var/home/{username}"}
roots: set[str] = set()
for r in raw:
roots.add(os.path.normpath(r))
roots.add(realpath_fn(r))
roots.discard(os.path.normpath("/"))
roots.discard(realpath_fn("/"))
return frozenset(roots)
def _get_protected_home_roots() -> frozenset[str]:
try:
pw = pwd.getpwuid(os.geteuid())
return _build_protected_home_roots(
username=pw.pw_name,
passwd_home=pw.pw_dir,
)
except (KeyError, OSError):
return frozenset()
def _resolve_tilde(path: str, passwd_home: str) -> str:
if path in ("~", "~/", "~/."):
return passwd_home
if path.startswith("~/"):
return passwd_home + path[1:]
if path.startswith("~"):
return os.path.expanduser(path)
return path
def _get_passwd_home() -> str | None:
try:
return pwd.getpwuid(os.geteuid()).pw_dir
except (KeyError, OSError):
return None
try:
from hermes_constants import get_hermes_home as _canonical_hermes_home # type: ignore
except ImportError:
_canonical_hermes_home = None
def _get_hermes_home() -> str | None:
"""Resolve the Hermes home (canonical first, standalone fallback).
Canonical ``get_hermes_home()`` covers context-local override →
``HERMES_HOME`` → platform default. The fallback below only runs when
the Hermes API is not importable (e.g. standalone test env).
"""
if _canonical_hermes_home is not None:
try:
return str(_canonical_hermes_home())
except RuntimeError:
return None
env = os.environ.get("HERMES_HOME")
if env:
env = env.strip()
if env:
return os.path.normpath(os.path.expanduser(env))
try:
return str(Path.home() / ".hermes")
except RuntimeError:
return None
def _get_skill_roots() -> frozenset[str]:
"""Return protected Hermes skill root variants (normcase + realpath).
Profile skill roots are covered by a lexical pattern in
``_path_is_under_skill_root`` (``<home>/profiles/*/skills``), so they
are protected even before the profile directory exists.
"""
base = _get_hermes_home()
if base is None:
return frozenset()
root = os.path.normpath(os.path.join(base, "skills"))
resolved = {
os.path.normcase(root),
os.path.normcase(os.path.realpath(root)),
}
return frozenset(resolved)
def _path_has_unresolved_token(path: str) -> bool:
"""True when the path still contains an unresolvable token.
``expandvars`` leaves unknown ``$VAR`` / ``%VAR%`` and ``expanduser``
leaves unknown ``~user`` as-is; the caller must treat these as
undeterminable and block conservatively. Known tradeoff: literal ``$``,
``~`` or ``%`` in legitimate filenames are also blocked.
"""
expanded = os.path.expandvars(os.path.expanduser(path))
return any(c in expanded for c in ("$", "~", "%"))
def _path_is_under_skill_root(path: str) -> bool:
"""True when *path* is inside a protected Hermes skill root."""
expanded = os.path.expandvars(os.path.expanduser(path))
normalized = os.path.normcase(os.path.normpath(expanded))
normalized_real = os.path.normcase(os.path.realpath(normalized))
for root in _get_skill_roots():
if normalized == root or normalized.startswith(root + os.sep):
return True
if normalized_real == root or normalized_real.startswith(root + os.sep):
return True
# Lexical profile pattern: <home>/profiles/<any>/skills/** — protects
# profiles that do not exist yet (write_file creates parent dirs).
# Both the normalized and realpath home variants are covered so an
# equivalent path (symlink target, `..`, ~) cannot bypass the pattern.
base = _get_hermes_home()
if base is not None:
base_norm = os.path.normcase(os.path.normpath(os.path.expandvars(os.path.expanduser(base))))
base_real = os.path.normcase(os.path.realpath(base))
for prefix_base in {base_norm, base_real}:
profiles_prefix = os.path.join(prefix_base, "profiles")
for candidate in (normalized, normalized_real):
if candidate.startswith(profiles_prefix + os.sep):
rel = candidate[len(profiles_prefix) + 1 :]
parts = rel.split(os.sep)
if len(parts) >= 2 and parts[1] == "skills":
return True
return False
def _path_is_protected_home_root(path: str) -> bool:
if not path or not isinstance(path, str):
return False
protected = _get_protected_home_roots()
if not protected:
return False
stripped = path.strip()
expanded = os.path.expandvars(stripped)
passwd_home = _get_passwd_home()
if passwd_home:
expanded = _resolve_tilde(expanded, passwd_home)
if os.path.normpath(expanded) in protected:
return True
return os.path.realpath(expanded) in protected
# ── Shared token helpers for terminal operand check ────────────────
def _token_is_home_root_operand(token: str) -> bool:
if not token or token.startswith("-"):
return False
expanded = os.path.expandvars(token)
passwd_home = _get_passwd_home()
if passwd_home and (expanded == "~" or expanded.startswith("~/")):
expanded = _resolve_tilde(expanded, passwd_home)
elif not passwd_home or not expanded.startswith("~"):
expanded = os.path.expanduser(expanded)
if os.path.normpath(expanded) in _get_protected_home_roots():
return True
if os.path.realpath(expanded) in _get_protected_home_roots():
return True
if any(c in expanded for c in ("*", "?", "[")):
glob_idx = -1
for i, c in enumerate(expanded):
if c in ("*", "?", "["):
glob_idx = i
break
if glob_idx > 0:
dir_part = expanded[:glob_idx]
dir_norm = os.path.normpath(dir_part.rstrip("/"))
if dir_norm in _get_protected_home_roots():
return True
return False
# ═══════════════════════════════════════════════════════════════════
# Shared constants
# ═══════════════════════════════════════════════════════════════════
_SEARCH_TOOLS = frozenset({"search_files", "search"})
_HOME_ROOT_SEARCH_MSG = (
"不允許把目前有效 Unix 帳號的整個 home root 當成搜尋範圍。"
"請指定更窄的子路徑。"
"Hermes plugin 名稱已知時。請先檢查 "
"${HERMES_HOME:-$HOME/.hermes}/plugins/<name>。"
)
_GUARDED_TOOLS = frozenset(
{
"search_files",
"search",
"terminal",
"write_file",
"patch",
"web_extract",
"browser_navigate",
"process",
"execute_code",
}
)
_LOCATE_COMMANDS = frozenset({"locate", "plocate", "mlocate"})
_HOME_ROOT_TERMINAL_MSG = (
"不允許把目前有效 Unix 帳號的整個 home root 當作 operand。"
"請指定更窄的子路徑。"
"Hermes plugin 名稱已知時。請先檢查 "
"${HERMES_HOME:-$HOME/.hermes}/plugins/<name>。"
)
_LOCATE_MSG = (
"locate 類工具搜尋整個系統索引。無法保證只查看授權範圍。請改用明確子路徑下的 fd、rg 或 find。"
)
# ═══════════════════════════════════════════════════════════════════
# Mutable poll state (thread-safe)
# ═══════════════════════════════════════════════════════════════════
_POLL_STATE_TTL_SECONDS = 24 * 60 * 60
_POLL_STATE_MAX_SESSIONS = 1024
_POLL_STATE: dict[str, tuple[int, float]] = {}
_LOCK = threading.Lock()
def _cleanup_poll_state(now: float) -> None:
expires_before = now - _POLL_STATE_TTL_SECONDS
for session_id, (_, last_seen) in tuple(_POLL_STATE.items()):
if last_seen <= expires_before:
del _POLL_STATE[session_id]
def _evict_oldest_poll_session() -> None:
oldest_session_id = min(
_POLL_STATE,
key=lambda candidate: (_POLL_STATE[candidate][1], candidate),
)
del _POLL_STATE[oldest_session_id]