zerochat 10.6.0__tar.gz → 10.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.6.0
3
+ Version: 10.7.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "zerochat"
7
- version = "10.6.0"
7
+ version = "10.7.0"
8
8
  description = "Private local web client for AI models, tools and MCP services"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.6.0
3
+ Version: 10.7.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -54,7 +54,7 @@ import zlib
54
54
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
55
55
  from pathlib import Path
56
56
 
57
- SOURCE_BACKEND_VERSION = "10.6.0"
57
+ SOURCE_BACKEND_VERSION = "10.7.0"
58
58
 
59
59
  def _read_source_version(filename: str) -> str | None:
60
60
  """Lee la versión de un archivo del repositorio cuando se ejecuta desde fuentes."""
@@ -335,16 +335,6 @@ def current_session_token() -> str:
335
335
  ACTIVE_PORT = DEFAULT_PORT
336
336
  ACTIVE_HOST = DEFAULT_HOST
337
337
 
338
- # Kept only for this Python process: binds an approved browser tool call to
339
- # the exact JSON-RPC bytes sent to the local host.
340
- TOOL_AUTH_VERSION = "zerochat-tool-auth-v1"
341
- TOOL_AUTH_TTL_MS = 60_000
342
- TOOL_AUTH_MAX_NONCES = 10_000
343
- TOOL_AUTH_KEY = secrets.token_bytes(32)
344
- TOOL_AUTH_SESSION_ID = secrets.token_urlsafe(18)
345
- TOOL_AUTH_NONCES: dict[str, int] = {}
346
- TOOL_AUTH_NONCES_LOCK = threading.Lock()
347
-
348
338
  DETECTED_OS = "windows" if sys.platform.startswith("win") else ("macos" if sys.platform == "darwin" else ("android" if "ANDROID_ROOT" in os.environ else "linux"))
349
339
 
350
340
 
@@ -1885,6 +1875,837 @@ def materialize_managed_services(services_root: Path | None = None) -> None:
1885
1875
  if relative_path.startswith("scripts/"):
1886
1876
  destination.chmod(0o755)
1887
1877
  # ==============================================================================
1878
+ # Motor de Control de Acceso y Seguridad de Herramientas (AccessController)
1879
+ # ==============================================================================
1880
+
1881
+ GLOBAL_POLICY_ASK = "ask"
1882
+ GLOBAL_POLICY_ALLOW_ALL = "allow_all"
1883
+ GLOBAL_POLICY_WORKSPACE_TRUST = "workspace_trust"
1884
+ GLOBAL_POLICIES = (GLOBAL_POLICY_ASK, GLOBAL_POLICY_ALLOW_ALL, GLOBAL_POLICY_WORKSPACE_TRUST)
1885
+
1886
+ TOOL_POLICY_ALLOW = "allow"
1887
+ TOOL_POLICY_DENY = "deny"
1888
+ TOOL_POLICY_ASK = "ask"
1889
+
1890
+ SERVER_POLICY_ALLOW = "allow"
1891
+ SERVER_POLICY_DENY = "deny"
1892
+ SERVER_POLICY_ASK = "ask"
1893
+
1894
+ SCOPE_PERMANENT = "permanent"
1895
+ SCOPE_SESSION = "session"
1896
+ SCOPES = (SCOPE_PERMANENT, SCOPE_SESSION)
1897
+
1898
+ DIRECTORY_RULE_PATTERN = re.compile(r"^(R|W|RW):(.+)$")
1899
+ COMMAND_TOOL = "run_command"
1900
+ JOB_CONTROL_TOOL = "check_command"
1901
+
1902
+ SAFE_REDIRECTION_PATTERN = re.compile(r"&>\s*/dev/null|\d?>>?\s*/dev/null|\d?>&\d")
1903
+
1904
+ WORKSPACE_TRUST_PIPE_FILTERS = frozenset([
1905
+ "head", "tail", "grep", "egrep", "fgrep", "rg", "wc", "sort", "uniq", "cut", "tr", "column", "nl", "cat", "jq"
1906
+ ])
1907
+ WORKSPACE_TRUST_GLOBAL_COMMANDS = re.compile(r"(?:^|\s)(?:sudo|su|doas|mkfs|reboot|shutdown|systemctl)\b")
1908
+ WORKSPACE_TRUST_OUTSIDE_REFERENCE = re.compile(r"(?:^|[\s=:'\"])(?:[\\/~]|[A-Za-z]:[\\/])|\$|(?:^|[\s=:'\"\\/])\.\.(?=[\s\\/'\"]|$)")
1909
+
1910
+
1911
+ @dataclasses.dataclass
1912
+ class SecurityContext:
1913
+ """Contexto de seguridad desacoplado para ejecuciones, sesiones o usuarios futuros."""
1914
+ workspace_dir: Path = dataclasses.field(default_factory=lambda: Path.cwd().resolve())
1915
+ user_id: str | None = None
1916
+ session_id: str | None = None
1917
+
1918
+ def resolve_path(self, path_str: str) -> Path | None:
1919
+ """Resuelve una ruta relativa al espacio de trabajo. Rechaza referencias no resueltas."""
1920
+ if not isinstance(path_str, str) or contains_unresolved_reference(path_str):
1921
+ return None
1922
+ norm = normalize_directory_path(path_str)
1923
+ if not norm:
1924
+ return None
1925
+ try:
1926
+ target = Path(norm)
1927
+ if not target.is_absolute():
1928
+ target = (self.workspace_dir / target).resolve()
1929
+ else:
1930
+ target = target.resolve()
1931
+ return target
1932
+ except (ValueError, RuntimeError, OSError):
1933
+ return None
1934
+
1935
+ def is_inside_workspace(self, path_str: str) -> bool:
1936
+ """Determina si la ruta reside estrictamente dentro del espacio de trabajo del contexto."""
1937
+ resolved = self.resolve_path(path_str)
1938
+ if resolved is None:
1939
+ return False
1940
+ try:
1941
+ resolved.relative_to(self.workspace_dir.resolve())
1942
+ return True
1943
+ except ValueError:
1944
+ return False
1945
+
1946
+
1947
+ def contains_unresolved_reference(value: str) -> bool:
1948
+ """Detecta variables de entorno ($VAR, ${VAR}) o expansiones de usuario (~)."""
1949
+ if not isinstance(value, str):
1950
+ return False
1951
+ trimmed = value.strip()
1952
+ if not trimmed:
1953
+ return False
1954
+ if trimmed.startswith("~"):
1955
+ return True
1956
+ return bool(re.search(r"\$(?:\{[^}]+\}|[A-Za-z_][A-Za-z0-9_]*)", trimmed))
1957
+
1958
+
1959
+ def normalize_directory_path(value: str) -> str:
1960
+ """Normaliza rutas posix/windows colapsando . y .. de forma determinista."""
1961
+ if not isinstance(value, str) or not value.strip() or "\0" in value:
1962
+ return ""
1963
+ if contains_unresolved_reference(value):
1964
+ return ""
1965
+ trimmed = value.strip().replace("\\", "/")
1966
+ is_absolute = bool(re.match(r"^(/|[A-Za-z]:/?)", trimmed))
1967
+ parts = []
1968
+ for part in trimmed.split("/"):
1969
+ if not part or part == ".":
1970
+ continue
1971
+ if part == "..":
1972
+ if parts:
1973
+ parts.pop()
1974
+ else:
1975
+ return ""
1976
+ else:
1977
+ parts.append(part)
1978
+ prefix = "/" if trimmed.startswith("/") else ""
1979
+ joined = "/".join(parts)
1980
+ if is_absolute and not joined.startswith("/") and not re.match(r"^[A-Za-z]:", joined):
1981
+ joined = prefix + joined
1982
+ return joined or (prefix or ".")
1983
+
1984
+
1985
+ def parse_directory_rule(raw_rule: str) -> dict | None:
1986
+ """Parsea una regla 'R:path', 'W:path' o 'RW:path' normalizando su ruta."""
1987
+ if not isinstance(raw_rule, str):
1988
+ return None
1989
+ match = DIRECTORY_RULE_PATTERN.match(raw_rule.strip())
1990
+ if not match:
1991
+ return None
1992
+ access = match.group(1)
1993
+ raw_path = match.group(2)
1994
+ path = normalize_directory_path(raw_path)
1995
+ if not path:
1996
+ return None
1997
+ return {"access": access, "path": path, "rule": f"{access}:{path}"}
1998
+
1999
+
2000
+ def matches_directory_pattern(path: str, pattern: str) -> bool:
2001
+ """Comprueba si una ruta cumple un patrón con soporte para /** y prefijos."""
2002
+ if pattern.endswith("/**") and path == pattern[:-3]:
2003
+ return True
2004
+ if "*" not in pattern:
2005
+ if path == pattern:
2006
+ return True
2007
+ prefix = pattern if pattern.endswith("/") else f"{pattern}/"
2008
+ if path.startswith(prefix):
2009
+ return True
2010
+ escaped = re.escape(pattern).replace(r"\*\*\/", ".*").replace(r"\*\*", ".*").replace(r"\*", "[^/]*")
2011
+ return bool(re.fullmatch(escaped, path))
2012
+
2013
+
2014
+ def has_command_chaining(cmd: str) -> bool:
2015
+ """Detecta sintaxis de shell que encadena o bifurca ejecuciones."""
2016
+ if not isinstance(cmd, str):
2017
+ return False
2018
+ return bool(re.search(r"[;\n\r`]|&&|\|\||\$\(|[<>]\(", cmd) or re.search(r"(?<!>|\d)&(?!\d|>)", cmd))
2019
+
2020
+
2021
+ def has_file_redirection(cmd: str) -> bool:
2022
+ """Detecta redirecciones a ficheros no seguras."""
2023
+ if not isinstance(cmd, str):
2024
+ return False
2025
+ sanitized = SAFE_REDIRECTION_PATTERN.sub(" ", cmd)
2026
+ return bool(re.search(r"[<>]", sanitized))
2027
+
2028
+
2029
+ def split_leading_cd(cmd: str) -> dict | None:
2030
+ """Separa un comando inicial 'cd <dir> && <cmd>'."""
2031
+ if not isinstance(cmd, str):
2032
+ return None
2033
+ match = re.match(r"^cd\s+(\"[^\"]*\"|'[^']*'|[^\s;&|<>`$()'\"]+)\s*&&\s*(\S[\s\S]*)$", cmd.strip())
2034
+ if not match:
2035
+ return None
2036
+ raw_dir = match.group(1).strip()
2037
+ if (raw_dir.startswith('"') and raw_dir.endswith('"')) or (raw_dir.startswith("'") and raw_dir.endswith("'")):
2038
+ clean_dir = raw_dir[1:-1]
2039
+ else:
2040
+ clean_dir = raw_dir
2041
+ return {"directory": clean_dir, "command": match.group(2).strip()}
2042
+
2043
+
2044
+ def get_command_base_name(cmd: str) -> str:
2045
+ """Devuelve el nombre del ejecutable principal omitiendo 'cd <dir> &&'."""
2046
+ trimmed = str(cmd or "").strip()
2047
+ cd_part = split_leading_cd(trimmed)
2048
+ command_str = cd_part["command"] if cd_part else trimmed
2049
+ tokens = command_str.split()
2050
+ return tokens[0] if tokens else ""
2051
+
2052
+
2053
+ def get_command_arg(args: dict | None) -> str:
2054
+ """Extrae el argumento de comando con soporte de alias habituales."""
2055
+ if not isinstance(args, dict):
2056
+ return ""
2057
+ val = args.get("command") or args.get("cmd") or args.get("script") or ""
2058
+ return str(val).strip()
2059
+
2060
+
2061
+ def get_path_arg(args: dict | None) -> str:
2062
+ """Extrae la ruta con soporte de alias habituales."""
2063
+ if not isinstance(args, dict):
2064
+ return ""
2065
+ val = args.get("path") or args.get("filepath") or args.get("file") or args.get("directory") or args.get("dir") or ""
2066
+ return str(val).strip() if isinstance(val, str) else ""
2067
+
2068
+
2069
+ def get_integrated_path_access(tool_name: str) -> str:
2070
+ """Clasifica el tipo de acceso al sistema de archivos ('R' o 'W') de herramientas core."""
2071
+ if tool_name in ("read_file", "list_directory", "search_files", "get_diagnostics"):
2072
+ return "R"
2073
+ if tool_name in ("edit_file", "write_file"):
2074
+ return "W"
2075
+ return ""
2076
+
2077
+
2078
+ def is_workspace_local_command(cmd: str) -> bool:
2079
+ """Filtro de seguridad para la política workspace_trust."""
2080
+ if not cmd or has_command_chaining(cmd) or has_file_redirection(cmd):
2081
+ return False
2082
+ piped_stages = cmd.split("|")[1:]
2083
+ for stage in piped_stages:
2084
+ first_token = stage.strip().split()[0] if stage.strip().split() else ""
2085
+ if first_token not in WORKSPACE_TRUST_PIPE_FILTERS:
2086
+ return False
2087
+ return not WORKSPACE_TRUST_GLOBAL_COMMANDS.search(cmd) and not WORKSPACE_TRUST_OUTSIDE_REFERENCE.search(cmd)
2088
+
2089
+
2090
+ def matches_command_prefix(command: str, prefix: str) -> bool:
2091
+ """Verifica si un comando cumple un prefijo autorizado."""
2092
+ clean_prefix = str(prefix).rstrip("*").strip()
2093
+ if not clean_prefix:
2094
+ return False
2095
+ prefixes = [
2096
+ clean_prefix,
2097
+ f"/usr/bin/{clean_prefix}",
2098
+ f"/bin/{clean_prefix}",
2099
+ f"/usr/local/bin/{clean_prefix}"
2100
+ ]
2101
+ for p in prefixes:
2102
+ if command == p:
2103
+ return True
2104
+ if p.endswith("/") and command.startswith(p):
2105
+ return True
2106
+ if command.startswith(f"{p} ") or command.startswith(f"{p}\t"):
2107
+ return True
2108
+ return False
2109
+
2110
+
2111
+ def evaluate_command_constraint(cmd_val: str, command_constraints: dict) -> tuple[bool, bool, str, str]:
2112
+ """Evalúa restricciones granulares de comando (encadenamiento, patrones prohibidos y prefijos)."""
2113
+ if not cmd_val or not isinstance(cmd_val, str) or not isinstance(command_constraints, dict):
2114
+ return True, False, "", ""
2115
+ trimmed = cmd_val.strip()
2116
+ cd_part = split_leading_cd(trimmed)
2117
+ command = cd_part["command"] if cd_part else trimmed
2118
+
2119
+ if command_constraints.get("allowChaining") is not True:
2120
+ has_unauthorized_pipe = (command_constraints.get("allowPipes") is not True) and ("|" in command)
2121
+ if has_command_chaining(command) or has_file_redirection(command) or has_unauthorized_pipe:
2122
+ return False, False, "command_chaining_requires_approval", f"Comando contiene encadenamiento no autorizado: {trimmed}"
2123
+
2124
+ denied_patterns = command_constraints.get("deniedPatterns")
2125
+ if isinstance(denied_patterns, (list, tuple)):
2126
+ for pattern in denied_patterns:
2127
+ if isinstance(pattern, str) and pattern in trimmed:
2128
+ return False, True, "command_matches_denied_pattern", f"The command contains a blocked pattern ({pattern}): {trimmed}"
2129
+
2130
+ allowed_prefixes = command_constraints.get("allowedPrefixes")
2131
+ if isinstance(allowed_prefixes, (list, tuple)) and len(allowed_prefixes) > 0:
2132
+ matched = any(matches_command_prefix(command, p) for p in allowed_prefixes if isinstance(p, str))
2133
+ if not matched:
2134
+ return False, False, "command_outside_allowed_prefixes", f"Comando fuera de los prefijos autorizados: {trimmed}"
2135
+
2136
+ return True, False, "", ""
2137
+
2138
+
2139
+ def get_rule_offer(tool_name: str, args: dict, auth_eval: dict) -> dict | None:
2140
+ """Genera la regla sugerida para confirmaciones permanentes en la interfaz."""
2141
+ command = get_command_arg(args)
2142
+ if command and not auth_eval.get("directoryAccess"):
2143
+ base_name = get_command_base_name(command)
2144
+ if not base_name:
2145
+ return None
2146
+ short_name = base_name.split("/")[-1]
2147
+ return {
2148
+ "type": "command",
2149
+ "command": base_name,
2150
+ "constraints": {
2151
+ "command": {"allowedPrefixes": [short_name], "allowChaining": False, "allowPipes": False}
2152
+ }
2153
+ }
2154
+ path = auth_eval.get("directoryPath") or get_path_arg(args)
2155
+ if not path or not normalize_directory_path(path):
2156
+ return None
2157
+ access = auth_eval.get("directoryAccess") or ("W" if re.search(r"(?:^|_)(?:edit|write)_file$", tool_name) else "R")
2158
+ clean_path = path.replace("\\", "/").rstrip("/")
2159
+ if re.search(r"(?:^|_)list_directory$", tool_name):
2160
+ folder = clean_path
2161
+ else:
2162
+ folder = clean_path[:clean_path.rfind("/")] if "/" in clean_path else "."
2163
+ dir_path = folder or "/"
2164
+ pattern = f"{access}:{dir_path}" if dir_path == "/" else f"{access}:{dir_path}/**"
2165
+ return {"type": "directory", "access": access, "directoryRule": pattern}
2166
+
2167
+
2168
+ @dataclasses.dataclass
2169
+ class AccessDecision:
2170
+ """Resultado formal de la evaluación de una llamada a herramienta."""
2171
+ allowed: bool
2172
+ status: str
2173
+ reason: str
2174
+ requires_approval: bool = False
2175
+ tool_id: str = ""
2176
+ server_name: str = ""
2177
+ server_id: str = ""
2178
+ original_name: str = ""
2179
+ details: str = ""
2180
+ directory_rule: str = ""
2181
+ directory_access: str = ""
2182
+ directory_path: str = ""
2183
+ rule_offer: dict | None = None
2184
+ scope: str = ""
2185
+ constraints: dict | None = None
2186
+
2187
+ def to_dict(self) -> dict:
2188
+ return {
2189
+ "allowed": self.allowed,
2190
+ "status": self.status,
2191
+ "reason": self.reason,
2192
+ "requiresApproval": self.requires_approval,
2193
+ "toolId": self.tool_id,
2194
+ "serverName": self.server_name,
2195
+ "serverId": self.server_id,
2196
+ "originalName": self.original_name,
2197
+ "details": self.details,
2198
+ "directoryRule": self.directory_rule,
2199
+ "directoryAccess": self.directory_access,
2200
+ "directoryPath": self.directory_path,
2201
+ "ruleOffer": self.rule_offer,
2202
+ "scope": self.scope,
2203
+ "constraints": self.constraints
2204
+ }
2205
+
2206
+
2207
+ class AccessController:
2208
+ """Motor de control de acceso y autorización del backend (PDP/PEP)."""
2209
+
2210
+ def __init__(self):
2211
+ self._lock = threading.RLock()
2212
+ self._loaded = False
2213
+ self.global_policy = GLOBAL_POLICY_ASK
2214
+ self.tools: dict[str, dict] = {}
2215
+ self.servers: dict[str, dict] = {}
2216
+ self.directory_rules: list[str] = []
2217
+ self.session_tools: dict[str, dict] = {}
2218
+ self.session_servers: dict[str, dict] = {}
2219
+ self.pending_challenges: dict[str, dict] = {}
2220
+
2221
+ def _ensure_loaded(self, context: SecurityContext | None = None):
2222
+ with self._lock:
2223
+ if not self._loaded:
2224
+ self._loaded = True
2225
+ self.load_from_storage(context=context)
2226
+
2227
+ def load_from_storage(self, policy_id: str = "default", user_id: str | None = None, context: SecurityContext | None = None):
2228
+ """Carga las políticas persistidas en SQLite si existen."""
2229
+ try:
2230
+ get_fn = globals().get("get_security_policy_data")
2231
+ if callable(get_fn):
2232
+ data = get_fn(policy_id, user_id)
2233
+ if data and isinstance(data, dict):
2234
+ self.import_state(data, context=context, persist=False)
2235
+ except (sqlite3.Error, ValueError, KeyError, TypeError) as ex:
2236
+ logger.debug(f"[Security] No se pudo cargar la política desde almacenamiento: {ex}")
2237
+
2238
+ def save_to_storage(self, policy_id: str = "default", user_id: str | None = None, context: SecurityContext | None = None):
2239
+ """Persiste las políticas permanentes actuales en SQLite."""
2240
+ try:
2241
+ save_fn = globals().get("save_security_policy_data")
2242
+ if callable(save_fn):
2243
+ state = self.export_state(context)
2244
+ save_fn(state, policy_id, user_id)
2245
+ except (sqlite3.Error, ValueError, KeyError, TypeError) as ex:
2246
+ logger.debug(f"[Security] No se pudo guardar la política en almacenamiento: {ex}")
2247
+
2248
+ def export_state(self, context: SecurityContext | None = None) -> dict:
2249
+ self._ensure_loaded(context)
2250
+ with self._lock:
2251
+ return {
2252
+ "version": 5,
2253
+ "globalMcpPolicy": self.global_policy,
2254
+ "directoryRules": self.get_directory_rules(context),
2255
+ "tools": dict(self.tools),
2256
+ "servers": dict(self.servers)
2257
+ }
2258
+
2259
+ def import_state(self, state: dict, context: SecurityContext | None = None, persist: bool = True):
2260
+ if not isinstance(state, dict):
2261
+ raise ValueError("El estado de políticas debe ser un diccionario.")
2262
+ with self._lock:
2263
+ if "globalMcpPolicy" in state:
2264
+ pol = state["globalMcpPolicy"]
2265
+ if pol in GLOBAL_POLICIES:
2266
+ self.global_policy = pol
2267
+ else:
2268
+ raise ValueError(f"Política global no válida: '{pol}'. Válidas: {GLOBAL_POLICIES}")
2269
+ if "directoryRules" in state:
2270
+ rules = state["directoryRules"]
2271
+ if isinstance(rules, (list, tuple)):
2272
+ self.set_directory_rules(list(rules), context, persist=False)
2273
+ else:
2274
+ raise ValueError("Las reglas de directorio deben ser una lista.")
2275
+ if "tools" in state:
2276
+ tools_map = state["tools"]
2277
+ if isinstance(tools_map, dict):
2278
+ self.tools = dict(tools_map)
2279
+ else:
2280
+ raise ValueError("tools debe ser un diccionario de herramientas.")
2281
+ if "servers" in state:
2282
+ servers_map = state["servers"]
2283
+ if isinstance(servers_map, dict):
2284
+ self.servers = dict(servers_map)
2285
+ else:
2286
+ raise ValueError("servers debe ser un diccionario de servidores.")
2287
+ if persist:
2288
+ self.save_to_storage(context=context)
2289
+
2290
+ def set_global_policy(self, policy: str, context: SecurityContext | None = None):
2291
+ if policy not in GLOBAL_POLICIES:
2292
+ raise ValueError(f"Política global inválida: {policy}")
2293
+ self._ensure_loaded(context)
2294
+ with self._lock:
2295
+ self.global_policy = policy
2296
+ self.save_to_storage(context=context)
2297
+
2298
+ def get_default_directory_rule(self, context: SecurityContext | None = None) -> str:
2299
+ ctx = context or SecurityContext()
2300
+ base = normalize_directory_path(str(ctx.workspace_dir))
2301
+ return f"RW:{base}" if base == "/" else f"RW:{base}/**"
2302
+
2303
+ def get_directory_rules(self, context: SecurityContext | None = None) -> list[str]:
2304
+ self._ensure_loaded(context)
2305
+ with self._lock:
2306
+ if not self.directory_rules:
2307
+ return [self.get_default_directory_rule(context)]
2308
+ return list(self.directory_rules)
2309
+
2310
+ def set_directory_rules(self, rules: list[str], context: SecurityContext | None = None, persist: bool = True) -> list[str]:
2311
+ if not isinstance(rules, (list, tuple)):
2312
+ raise ValueError("Las reglas de directorio deben ser una lista.")
2313
+ parsed_rules = []
2314
+ for raw in rules:
2315
+ rule_obj = parse_directory_rule(raw)
2316
+ if not rule_obj:
2317
+ raise ValueError(f"Regla de directorio inválida: '{raw}'. Formato esperado: R:path, W:path o RW:path.")
2318
+ parsed_rules.append(rule_obj["rule"])
2319
+ unique_rules = list(dict.fromkeys(parsed_rules))
2320
+ self._ensure_loaded(context)
2321
+ with self._lock:
2322
+ self.directory_rules = unique_rules or [self.get_default_directory_rule(context)]
2323
+ result = list(self.directory_rules)
2324
+ if persist:
2325
+ self.save_to_storage(context=context)
2326
+ return result
2327
+
2328
+ def add_directory_rule(self, rule: str, context: SecurityContext | None = None) -> list[str]:
2329
+ current = self.get_directory_rules(context)
2330
+ return self.set_directory_rules(current + [rule], context)
2331
+
2332
+ def evaluate_directory_rule(self, access: str, path: str, context: SecurityContext | None = None) -> dict:
2333
+ if contains_unresolved_reference(path):
2334
+ return {"allowed": False, "rule": None, "path": ""}
2335
+ normalized = normalize_directory_path(path)
2336
+ if not normalized:
2337
+ return {"allowed": False, "rule": None, "path": ""}
2338
+ ctx = context or SecurityContext()
2339
+ startup_dir = normalize_directory_path(str(ctx.workspace_dir))
2340
+ resolved_absolute = None
2341
+ if not normalized.startswith("/") and not re.match(r"^[A-Za-z]:", normalized) and startup_dir:
2342
+ resolved_absolute = normalize_directory_path(startup_dir if normalized == "." else f"{startup_dir}/{normalized}")
2343
+
2344
+ rules = self.get_directory_rules(ctx)
2345
+ for raw_rule in rules:
2346
+ parsed = parse_directory_rule(raw_rule)
2347
+ if not parsed or (parsed["access"] != access and parsed["access"] != "RW"):
2348
+ continue
2349
+ if matches_directory_pattern(normalized, parsed["path"]):
2350
+ return {"allowed": True, "rule": parsed["rule"], "path": normalized}
2351
+ if resolved_absolute and matches_directory_pattern(resolved_absolute, parsed["path"]):
2352
+ return {"allowed": True, "rule": parsed["rule"], "path": normalized}
2353
+ return {"allowed": False, "rule": None, "path": normalized}
2354
+
2355
+ def evaluate_command_directories(self, args: dict, context: SecurityContext | None = None) -> dict:
2356
+ cmd_arg = get_command_arg(args)
2357
+ cd_part = split_leading_cd(cmd_arg)
2358
+ if not cd_part:
2359
+ return {"allowed": True, "directory": None}
2360
+ target_dir = cd_part["directory"]
2361
+ read_eval = self.evaluate_directory_rule("R", target_dir, context)
2362
+ write_eval = self.evaluate_directory_rule("W", target_dir, context)
2363
+ allowed = read_eval["allowed"] or write_eval["allowed"]
2364
+ return {"allowed": allowed, "directory": target_dir}
2365
+
2366
+ def set_tool_policy(self, tool_id: str, policy: str, scope: str = SCOPE_PERMANENT,
2367
+ constraints: dict | None = None, server_name: str = "", original_name: str = ""):
2368
+ if not tool_id or not isinstance(tool_id, str):
2369
+ return
2370
+ self._ensure_loaded()
2371
+ clean_policy = policy if policy in (TOOL_POLICY_ALLOW, TOOL_POLICY_DENY) else TOOL_POLICY_ASK
2372
+ with self._lock:
2373
+ if clean_policy == TOOL_POLICY_ASK:
2374
+ self.revoke_tool_policy(tool_id)
2375
+ return
2376
+ entry = {
2377
+ "policy": clean_policy,
2378
+ "scope": scope if scope in SCOPES else SCOPE_PERMANENT,
2379
+ "grantedAt": int(time.time() * 1000),
2380
+ "lastUsedAt": int(time.time() * 1000),
2381
+ "serverName": server_name,
2382
+ "originalName": original_name or tool_id,
2383
+ "constraints": constraints
2384
+ }
2385
+ if scope == SCOPE_SESSION:
2386
+ self.session_tools[tool_id] = entry
2387
+ else:
2388
+ self.tools[tool_id] = entry
2389
+ if scope != SCOPE_SESSION:
2390
+ self.save_to_storage()
2391
+
2392
+ def get_tool_policy(self, tool_id: str) -> dict | None:
2393
+ self._ensure_loaded()
2394
+ with self._lock:
2395
+ return self.session_tools.get(tool_id) or self.tools.get(tool_id)
2396
+
2397
+ def revoke_tool_policy(self, tool_id: str) -> bool:
2398
+ self._ensure_loaded()
2399
+ with self._lock:
2400
+ del_session = self.session_tools.pop(tool_id, None) is not None
2401
+ del_perm = self.tools.pop(tool_id, None) is not None
2402
+ if del_perm:
2403
+ self.save_to_storage()
2404
+ return del_session or del_perm
2405
+
2406
+ def set_server_policy(self, server_id: str, policy: str, scope: str = SCOPE_PERMANENT, server_name: str = ""):
2407
+ if not server_id or not isinstance(server_id, str):
2408
+ return
2409
+ clean = server_id.strip()
2410
+ self._ensure_loaded()
2411
+ clean_policy = policy if policy in (SERVER_POLICY_ALLOW, SERVER_POLICY_DENY) else SERVER_POLICY_ASK
2412
+ with self._lock:
2413
+ if clean_policy == SERVER_POLICY_ASK:
2414
+ self.revoke_server_policy(clean)
2415
+ return
2416
+ entry = {
2417
+ "policy": clean_policy,
2418
+ "scope": scope if scope in SCOPES else SCOPE_PERMANENT,
2419
+ "grantedAt": int(time.time() * 1000),
2420
+ "lastUsedAt": int(time.time() * 1000),
2421
+ "serverName": server_name or clean
2422
+ }
2423
+ if scope == SCOPE_SESSION:
2424
+ self.session_servers[clean] = entry
2425
+ else:
2426
+ self.servers[clean] = entry
2427
+ if scope != SCOPE_SESSION:
2428
+ self.save_to_storage()
2429
+
2430
+ def get_server_policy(self, server_id: str) -> dict | None:
2431
+ clean = str(server_id or "").strip()
2432
+ self._ensure_loaded()
2433
+ with self._lock:
2434
+ return self.session_servers.get(clean) or self.servers.get(clean)
2435
+
2436
+ def revoke_server_policy(self, server_id: str) -> bool:
2437
+ clean = str(server_id or "").strip()
2438
+ self._ensure_loaded()
2439
+ with self._lock:
2440
+ del_session = self.session_servers.pop(clean, None) is not None
2441
+ del_perm = self.servers.pop(clean, None) is not None
2442
+ if del_perm:
2443
+ self.save_to_storage()
2444
+ return del_session or del_perm
2445
+
2446
+ def clear_session(self):
2447
+ """Limpia todas las autorizaciones temporales de la sesión activa."""
2448
+ with self._lock:
2449
+ self.session_tools.clear()
2450
+ self.session_servers.clear()
2451
+ self.pending_challenges.clear()
2452
+
2453
+ def create_challenge(self, tool_name: str, args: dict, decision: AccessDecision,
2454
+ server_name: str = "", server_id: str = "") -> dict:
2455
+ """Genera un reto estructurado para solicitar confirmación interactiva al usuario."""
2456
+ challenge_id = f"auth_{secrets.token_urlsafe(16)}"
2457
+ now = int(time.time() * 1000)
2458
+ with self._lock:
2459
+ expired = [cid for cid, c in self.pending_challenges.items() if now - c.get("createdAt", 0) > 600_000]
2460
+ for cid in expired:
2461
+ self.pending_challenges.pop(cid, None)
2462
+
2463
+ challenge_data = {
2464
+ "id": challenge_id,
2465
+ "toolName": tool_name,
2466
+ "arguments": args,
2467
+ "decision": decision.to_dict(),
2468
+ "serverName": server_name,
2469
+ "serverId": server_id,
2470
+ "createdAt": now,
2471
+ "authorized": False,
2472
+ "decisionType": None
2473
+ }
2474
+ self.pending_challenges[challenge_id] = challenge_data
2475
+ return challenge_data
2476
+
2477
+ def authorize_challenge(self, challenge_id: str, decision: str | dict,
2478
+ constraints: dict | None = None, directory_rule: str | None = None,
2479
+ context: SecurityContext | None = None) -> bool:
2480
+ with self._lock:
2481
+ challenge = self.pending_challenges.get(challenge_id)
2482
+ if not challenge:
2483
+ return False
2484
+ dec_type = decision.get("decision") if isinstance(decision, dict) else str(decision)
2485
+ if dec_type not in ("allow_once", "allow_session", "allow_always", "allow_server_always"):
2486
+ return False
2487
+ challenge["authorized"] = True
2488
+ challenge["decisionType"] = dec_type
2489
+ dec_payload = {
2490
+ "decision": dec_type,
2491
+ "constraints": constraints or (decision.get("constraints") if isinstance(decision, dict) else None),
2492
+ "directoryRule": directory_rule or (decision.get("directoryRule") if isinstance(decision, dict) else None)
2493
+ }
2494
+ self.record_decision(dec_payload, challenge["decision"], fallback_tool_name=challenge["toolName"], context=context)
2495
+ return True
2496
+
2497
+ def consume_challenge(self, challenge_id: str) -> dict | None:
2498
+ """Consume y valida un reto previamente autorizado para una ejecución."""
2499
+ with self._lock:
2500
+ challenge = self.pending_challenges.get(challenge_id)
2501
+ if not challenge or not challenge.get("authorized"):
2502
+ return None
2503
+ if challenge.get("decisionType") == "allow_once":
2504
+ return self.pending_challenges.pop(challenge_id)
2505
+ return challenge
2506
+
2507
+ def revoke_challenge(self, challenge_id: str) -> bool:
2508
+ with self._lock:
2509
+ return self.pending_challenges.pop(challenge_id, None) is not None
2510
+
2511
+ def merge_tool_constraints(self, target_tool_id: str, requested: dict | None) -> dict | None:
2512
+ """Combina restricciones granulares existentes con nuevas solicitadas."""
2513
+ existing_entry = self.get_tool_policy(target_tool_id)
2514
+ existing_constraints = existing_entry.get("constraints") if existing_entry else None
2515
+ if not requested or not isinstance(requested, dict):
2516
+ return existing_constraints
2517
+ if not requested.get("command"):
2518
+ return requested
2519
+ req_cmd = requested["command"]
2520
+ ext_cmd = existing_constraints.get("command") if (existing_constraints and isinstance(existing_constraints, dict)) else {}
2521
+
2522
+ raw_prefixes = list(ext_cmd.get("allowedPrefixes") or []) + list(req_cmd.get("allowedPrefixes") or [])
2523
+ seen = set()
2524
+ merged_prefixes = []
2525
+ for p in raw_prefixes:
2526
+ if isinstance(p, str) and p.strip() and p.strip() not in seen:
2527
+ seen.add(p.strip())
2528
+ merged_prefixes.append(p.strip())
2529
+
2530
+ def grants(key: str) -> bool:
2531
+ return req_cmd.get(key) is True and (not ext_cmd or ext_cmd.get(key) is True)
2532
+
2533
+ merged_cmd = {
2534
+ **ext_cmd,
2535
+ **req_cmd,
2536
+ "allowedPrefixes": merged_prefixes if merged_prefixes else None,
2537
+ "allowChaining": grants("allowChaining"),
2538
+ "allowPipes": grants("allowPipes")
2539
+ }
2540
+ return {"command": merged_cmd}
2541
+
2542
+ def record_decision(self, decision: str | dict, auth_eval: dict | AccessDecision,
2543
+ fallback_tool_name: str = "", context: SecurityContext | None = None):
2544
+ """Registra la respuesta de un usuario tras un reto de autorización."""
2545
+ decision_dict = decision if isinstance(decision, dict) else {"decision": str(decision)}
2546
+ decision_type = decision_dict.get("decision", "")
2547
+ eval_dict = auth_eval.to_dict() if isinstance(auth_eval, AccessDecision) else dict(auth_eval)
2548
+ target_tool = eval_dict.get("toolId") or fallback_tool_name
2549
+
2550
+ if decision_type == "allow_session":
2551
+ self.set_tool_policy(target_tool, TOOL_POLICY_ALLOW, scope=SCOPE_SESSION,
2552
+ server_name=eval_dict.get("serverName", ""),
2553
+ original_name=eval_dict.get("originalName", ""))
2554
+ elif decision_type == "allow_server_always":
2555
+ server_target = decision_dict.get("serverId") or eval_dict.get("serverId")
2556
+ if server_target:
2557
+ self.set_server_policy(server_target, SERVER_POLICY_ALLOW, scope=SCOPE_PERMANENT,
2558
+ server_name=eval_dict.get("serverName", ""))
2559
+ elif decision_type == "allow_always":
2560
+ req_constraints = decision_dict.get("constraints")
2561
+ constraints = self.merge_tool_constraints(target_tool, req_constraints)
2562
+ self.set_tool_policy(target_tool, TOOL_POLICY_ALLOW, scope=SCOPE_PERMANENT,
2563
+ constraints=constraints,
2564
+ server_name=eval_dict.get("serverName", ""),
2565
+ original_name=eval_dict.get("originalName", ""))
2566
+ elif decision_type == "allow_once":
2567
+ pass
2568
+
2569
+ if decision_dict.get("directoryRule"):
2570
+ try:
2571
+ self.add_directory_rule(str(decision_dict["directoryRule"]), context)
2572
+ except ValueError:
2573
+ pass
2574
+
2575
+ def evaluate_authorization(self, tool_or_name: str | dict, raw_args: dict | None = None,
2576
+ context: SecurityContext | None = None, server_name: str = "",
2577
+ server_id: str = "", original_name: str = "") -> AccessDecision:
2578
+ """
2579
+ Evalúa si la invocación de una herramienta está permitida, denegada o requiere confirmación.
2580
+ Jerarquía:
2581
+ 1. Lista negra explícita (deny individual o de servidor).
2582
+ 2. Herramientas de control de procesos (check_command).
2583
+ 3. Política global allow_all -> allow incondicional.
2584
+ 4. Política granular de herramienta -> allow (comprobando constraints).
2585
+ 5. Política de servidor completo -> allow incondicional para sus herramientas.
2586
+ 6. Reglas de directorio y Workspace Trust.
2587
+ 7. Por defecto -> ask (solicitar confirmación).
2588
+ """
2589
+ ctx = context or SecurityContext()
2590
+ self._ensure_loaded(ctx)
2591
+ args = dict(raw_args or {})
2592
+ tool_name = tool_or_name.get("name", "") if isinstance(tool_or_name, dict) else str(tool_or_name)
2593
+ tool_id = tool_name
2594
+ orig_name = original_name or (tool_or_name.get("originalName") if isinstance(tool_or_name, dict) else tool_name)
2595
+ srv_name = server_name or (tool_or_name.get("serverName") if isinstance(tool_or_name, dict) else "")
2596
+ srv_id = server_id or (tool_or_name.get("serverId") if isinstance(tool_or_name, dict) else srv_name)
2597
+
2598
+ def make_decision(status: str, reason: str, extra: dict | None = None) -> AccessDecision:
2599
+ payload = extra or {}
2600
+ dec = AccessDecision(
2601
+ allowed=(status == TOOL_POLICY_ALLOW),
2602
+ status=status,
2603
+ reason=reason,
2604
+ requires_approval=(status == TOOL_POLICY_ASK),
2605
+ tool_id=tool_id,
2606
+ server_name=srv_name,
2607
+ server_id=srv_id,
2608
+ original_name=orig_name,
2609
+ details=payload.get("details", ""),
2610
+ directory_rule=payload.get("directoryRule", ""),
2611
+ directory_access=payload.get("directoryAccess", ""),
2612
+ directory_path=payload.get("directoryPath", ""),
2613
+ scope=payload.get("scope", ""),
2614
+ constraints=payload.get("constraints")
2615
+ )
2616
+ if status == TOOL_POLICY_ASK:
2617
+ dec.rule_offer = get_rule_offer(tool_name, args, dec.to_dict())
2618
+ return dec
2619
+
2620
+ default_path_tools = {"list_directory", "search_files", "get_diagnostics"}
2621
+ if (tool_name in default_path_tools or orig_name in default_path_tools) and not get_path_arg(args):
2622
+ args["path"] = "."
2623
+
2624
+ # 1. Denegación explícita (Blacklist)
2625
+ tool_entry = self.get_tool_policy(tool_id)
2626
+ if tool_entry and tool_entry.get("policy") == TOOL_POLICY_DENY:
2627
+ return make_decision(TOOL_POLICY_DENY, "granular_deny_rule")
2628
+
2629
+ if srv_id:
2630
+ server_entry = self.get_server_policy(srv_id)
2631
+ if server_entry and server_entry.get("policy") == SERVER_POLICY_DENY:
2632
+ return make_decision(TOOL_POLICY_DENY, "server_deny_rule")
2633
+
2634
+ # 2. Herramientas auxiliares de control de trabajos
2635
+ if tool_name == JOB_CONTROL_TOOL or orig_name == JOB_CONTROL_TOOL:
2636
+ return make_decision(TOOL_POLICY_ALLOW, "job_control_tool")
2637
+
2638
+ # 3. Política global allow_all
2639
+ if self.global_policy == GLOBAL_POLICY_ALLOW_ALL:
2640
+ return make_decision(TOOL_POLICY_ALLOW, "mcp_global_allow_all")
2641
+
2642
+ # 4. Autorización individual de herramienta
2643
+ if tool_entry and tool_entry.get("policy") == TOOL_POLICY_ALLOW:
2644
+ constraints = tool_entry.get("constraints")
2645
+ if constraints and isinstance(constraints, dict):
2646
+ cmd_arg = get_command_arg(args)
2647
+ if cmd_arg and constraints.get("command"):
2648
+ c_allowed, c_denied, c_reason, c_details = evaluate_command_constraint(cmd_arg, constraints["command"])
2649
+ if c_denied:
2650
+ return make_decision(TOOL_POLICY_DENY, c_reason or "constraint_violation_denied", {"details": c_details})
2651
+ if not c_allowed:
2652
+ return make_decision(TOOL_POLICY_ASK, c_reason or "constraint_outside_scope", {"details": c_details})
2653
+ cmd_dir_eval = self.evaluate_command_directories(args, ctx)
2654
+ if not cmd_dir_eval["allowed"]:
2655
+ return make_decision(TOOL_POLICY_ASK, "command_directory_outside_rules", {
2656
+ "details": f"El comando se ejecuta fuera de las reglas de directorio: {cmd_dir_eval['directory']}"
2657
+ })
2658
+ with self._lock:
2659
+ tool_entry["lastUsedAt"] = int(time.time() * 1000)
2660
+ return make_decision(TOOL_POLICY_ALLOW, "granular_allow_rule", {
2661
+ "scope": tool_entry.get("scope", SCOPE_PERMANENT),
2662
+ "constraints": tool_entry.get("constraints")
2663
+ })
2664
+
2665
+ # 5. Autorización de servidor completo
2666
+ if srv_id:
2667
+ srv_entry = self.get_server_policy(srv_id)
2668
+ if srv_entry and srv_entry.get("policy") == SERVER_POLICY_ALLOW:
2669
+ with self._lock:
2670
+ srv_entry["lastUsedAt"] = int(time.time() * 1000)
2671
+ return make_decision(TOOL_POLICY_ALLOW, "server_allow_rule", {"scope": srv_entry.get("scope", SCOPE_PERMANENT)})
2672
+
2673
+ # 6. Reglas de Directorio y Workspace Trust
2674
+ path_access = get_integrated_path_access(tool_name) or get_integrated_path_access(orig_name)
2675
+ path = get_path_arg(args)
2676
+
2677
+ if path_access and path:
2678
+ dir_eval = self.evaluate_directory_rule(path_access, path, ctx)
2679
+ if dir_eval["allowed"]:
2680
+ return make_decision(TOOL_POLICY_ALLOW, "directory_rule_allow", {"directoryRule": dir_eval["rule"]})
2681
+
2682
+ if self.global_policy == GLOBAL_POLICY_WORKSPACE_TRUST:
2683
+ if ctx.is_inside_workspace(path):
2684
+ return make_decision(TOOL_POLICY_ALLOW, "workspace_trust_allow")
2685
+
2686
+ return make_decision(TOOL_POLICY_ASK, "directory_rule_required", {
2687
+ "details": f"La ruta no coincide con una regla {path_access}: {path}",
2688
+ "directoryAccess": path_access if dir_eval["path"] else "",
2689
+ "directoryPath": dir_eval["path"] or ""
2690
+ })
2691
+
2692
+ if (tool_name == COMMAND_TOOL or orig_name == COMMAND_TOOL) and self.global_policy == GLOBAL_POLICY_WORKSPACE_TRUST:
2693
+ cmd_val = get_command_arg(args)
2694
+ cd_part = split_leading_cd(cmd_val)
2695
+ sub_cmd = cd_part["command"] if cd_part else cmd_val
2696
+ is_local = is_workspace_local_command(sub_cmd) and self.evaluate_command_directories(args, ctx)["allowed"]
2697
+ if is_local:
2698
+ return make_decision(TOOL_POLICY_ALLOW, "workspace_trust_command")
2699
+ return make_decision(TOOL_POLICY_ASK, "workspace_trust_external_or_global_command", {
2700
+ "details": "El comando accede a recursos globales o rutas fuera del espacio de trabajo."
2701
+ })
2702
+
2703
+ # 7. Por defecto: confirmación
2704
+ return make_decision(TOOL_POLICY_ASK, "mcp_default_ask")
2705
+
2706
+
2707
+ ACCESS_CONTROLLER = AccessController()
2708
+ # ==============================================================================
1888
2709
  # Herramientas Locales Core
1889
2710
  # ==============================================================================
1890
2711
 
@@ -3997,6 +4818,15 @@ STORAGE_MIGRATIONS = [
3997
4818
  """),
3998
4819
  (4, "004_add_extra_json_to_conversations", """
3999
4820
  ALTER TABLE conversations ADD COLUMN extra_json TEXT DEFAULT '{}';
4821
+ """),
4822
+ (5, "005_create_security_policies_table", """
4823
+ CREATE TABLE IF NOT EXISTS security_policies (
4824
+ id TEXT PRIMARY KEY,
4825
+ user_id TEXT,
4826
+ data_json TEXT NOT NULL,
4827
+ updated_at INTEGER NOT NULL
4828
+ );
4829
+ CREATE INDEX IF NOT EXISTS idx_security_policies_user ON security_policies(user_id);
4000
4830
  """)
4001
4831
  ]
4002
4832
 
@@ -4480,6 +5310,40 @@ def has_blobs(blob_ids: list[str]) -> dict:
4480
5310
  "missing": [bid for bid in unique_ids if bid not in existing_set],
4481
5311
  }
4482
5312
 
5313
+
5314
+ def get_security_policy_data(policy_id: str = "default", user_id: str | None = None) -> dict | None:
5315
+ """Recupera los datos de políticas de seguridad guardados en SQLite."""
5316
+ clean_id = (policy_id or "default").strip()
5317
+ with open_storage() as conn:
5318
+ row = conn.execute("SELECT data_json FROM security_policies WHERE id = ?;", (clean_id,)).fetchone()
5319
+ if not row:
5320
+ return None
5321
+ try:
5322
+ return json.loads(row["data_json"])
5323
+ except (ValueError, TypeError):
5324
+ return None
5325
+
5326
+
5327
+ def save_security_policy_data(data: dict, policy_id: str = "default", user_id: str | None = None) -> dict:
5328
+ """Guarda los datos de políticas de seguridad en SQLite."""
5329
+ if not isinstance(data, dict):
5330
+ raise ValueError("Los datos de política de seguridad deben ser un objeto JSON")
5331
+ clean_id = (policy_id or "default").strip()
5332
+ data_str = json.dumps(data, ensure_ascii=False)
5333
+ now = int(time.time() * 1000)
5334
+ with open_storage() as conn:
5335
+ conn.execute("""
5336
+ INSERT INTO security_policies (id, user_id, data_json, updated_at)
5337
+ VALUES (?, ?, ?, ?)
5338
+ ON CONFLICT(id) DO UPDATE SET
5339
+ user_id = excluded.user_id,
5340
+ data_json = excluded.data_json,
5341
+ updated_at = excluded.updated_at;
5342
+ """, (clean_id, user_id, data_str, now))
5343
+ conn.commit()
5344
+ return {"id": clean_id, "updated_at": now}
5345
+
5346
+
4483
5347
  DEFAULT_HEARTBEAT_TIMEOUT = float(os.environ.get("ZEROCHAT_HEARTBEAT_TIMEOUT", "60.0"))
4484
5348
  DEFAULT_HEARTBEAT_GRACE = float(os.environ.get("ZEROCHAT_HEARTBEAT_GRACE", "45.0"))
4485
5349
  DEFAULT_HEARTBEAT_POLL = float(os.environ.get("ZEROCHAT_HEARTBEAT_POLL", "5.0"))
@@ -4903,42 +5767,6 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
4903
5767
  token_candidate = auth_header[7:].strip()
4904
5768
  return bool(token_candidate) and hmac.compare_digest(token_candidate.encode(), current_session_token().encode())
4905
5769
 
4906
- def verify_tool_authorization(self, body: bytes, request_path: str) -> str | None:
4907
- """Validate and atomically consume an authorization for one tool call."""
4908
- session_id = self.headers.get("X-ZeroChat-Tool-Session", "")
4909
- expires_raw = self.headers.get("X-ZeroChat-Tool-Expires", "")
4910
- nonce = self.headers.get("X-ZeroChat-Tool-Nonce", "")
4911
- signature = self.headers.get("X-ZeroChat-Tool-Signature", "")
4912
- if (not isinstance(session_id, str) or len(session_id) > 128 or
4913
- not isinstance(nonce, str) or not re.fullmatch(r"[A-Za-z0-9_-]{22,128}", nonce) or
4914
- not isinstance(signature, str) or not re.fullmatch(r"[A-Za-z0-9_-]{43,128}", signature)):
4915
- return "Missing or invalid tool authorization"
4916
- try:
4917
- expires_at = int(expires_raw)
4918
- except (TypeError, ValueError):
4919
- return "Missing or invalid tool authorization"
4920
- now_ms = int(time.time() * 1000)
4921
- if session_id != TOOL_AUTH_SESSION_ID or expires_at < now_ms or expires_at > now_ms + TOOL_AUTH_TTL_MS:
4922
- return "Expired or invalid tool authorization"
4923
- body_hash = hashlib.sha256(body).hexdigest()
4924
- signature_base = json.dumps(
4925
- [TOOL_AUTH_VERSION, session_id, "POST", request_path or "/", expires_at, nonce, body_hash],
4926
- separators=(",", ":"), ensure_ascii=True
4927
- ).encode("utf-8")
4928
- expected = base64.urlsafe_b64encode(hmac.new(TOOL_AUTH_KEY, signature_base, hashlib.sha256).digest()).rstrip(b"=").decode("ascii")
4929
- if not hmac.compare_digest(signature, expected):
4930
- return "Invalid tool authorization signature"
4931
- with TOOL_AUTH_NONCES_LOCK:
4932
- for value, expiry in list(TOOL_AUTH_NONCES.items()):
4933
- if expiry < now_ms:
4934
- del TOOL_AUTH_NONCES[value]
4935
- if nonce in TOOL_AUTH_NONCES:
4936
- return "Tool authorization was already used"
4937
- if len(TOOL_AUTH_NONCES) >= TOOL_AUTH_MAX_NONCES:
4938
- return "Tool authorization cache is full"
4939
- TOOL_AUTH_NONCES[nonce] = expires_at
4940
- return None
4941
-
4942
5770
  def do_OPTIONS(self):
4943
5771
  t0 = time.monotonic()
4944
5772
  safe_path = sanitize_log_path(self.path)
@@ -5087,12 +5915,6 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
5087
5915
  "serverInfo": server_info,
5088
5916
  "capabilities": {
5089
5917
  "tools": {"listChanged": True}
5090
- },
5091
- "toolAuthorization": {
5092
- "version": TOOL_AUTH_VERSION,
5093
- "sessionId": TOOL_AUTH_SESSION_ID,
5094
- "key": base64.urlsafe_b64encode(TOOL_AUTH_KEY).rstrip(b"=").decode("ascii"),
5095
- "ttlMs": TOOL_AUTH_TTL_MS
5096
5918
  }
5097
5919
  }
5098
5920
 
@@ -5107,8 +5929,35 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
5107
5929
  if method == "tools/list":
5108
5930
  return {"tools": GLOBAL_MCP_MANAGER.tools()}, None, ""
5109
5931
  if method == "tools/call":
5932
+ tool_name = params.get("name", "")
5933
+ raw_args = params.get("arguments", {})
5934
+ args = raw_args if isinstance(raw_args, dict) else {}
5935
+ meta = params.get("_meta")
5936
+ challenge_id = params.get("challengeId") or (meta.get("challengeId") if isinstance(meta, dict) else None)
5937
+ ctx = SecurityContext(workspace_dir=Path.cwd().resolve())
5938
+
5939
+ authorized_challenge = ACCESS_CONTROLLER.consume_challenge(challenge_id) if challenge_id else None
5940
+ if not authorized_challenge:
5941
+ decision = ACCESS_CONTROLLER.evaluate_authorization(tool_name, args, context=ctx, server_name="external")
5942
+ if decision.status == TOOL_POLICY_DENY:
5943
+ err_msg = f"Bloqueado por política de seguridad: {decision.reason}"
5944
+ return {"content": [{"type": "text", "text": f"Error: {err_msg}"}], "isError": True, "securityStatus": "deny", "reason": decision.reason}, None, err_msg
5945
+ if decision.status == TOOL_POLICY_ASK:
5946
+ ch = ACCESS_CONTROLLER.create_challenge(tool_name, args, decision, server_name="external")
5947
+ return {
5948
+ "requiresAuthorization": True,
5949
+ "challengeId": ch["id"],
5950
+ "toolName": tool_name,
5951
+ "serverName": "external",
5952
+ "arguments": args,
5953
+ "ruleOffer": decision.rule_offer,
5954
+ "details": decision.details,
5955
+ "content": [{"type": "text", "text": "Esta herramienta requiere autorización del usuario."}],
5956
+ "isError": False
5957
+ }, None, ""
5958
+
5110
5959
  try:
5111
- result = GLOBAL_MCP_MANAGER.call(params["name"], params.get("arguments", {}))
5960
+ result = GLOBAL_MCP_MANAGER.call(tool_name, args)
5112
5961
  except Exception as ex:
5113
5962
  return self._tool_exception_result(ex), None, str(ex)
5114
5963
  tool_error_info = ""
@@ -5139,15 +5988,39 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
5139
5988
  if method == "tools/list":
5140
5989
  return {"tools": [dict(definition) for definition in LOCAL_TOOLS_DEFINITIONS]}, None, ""
5141
5990
  if method == "tools/call":
5142
- tool_name = params["name"]
5991
+ tool_name = params.get("name", "")
5143
5992
  handler = LOCAL_TOOL_HANDLERS.get(tool_name)
5144
5993
  if not handler:
5145
5994
  return None, {"code": -32601, "message": f"Herramienta local '{tool_name}' no encontrada."}, ""
5146
- arguments = dict(params.get("arguments", {}))
5147
- if tool_name == "run_command":
5148
- # La clave la pone el cliente, no el modelo: permite detener el comando antes de conocer su job_id.
5149
- meta = params.get("_meta")
5150
- arguments["job_key"] = meta.get("zerochatJobKey") if isinstance(meta, dict) else None
5995
+ raw_args = params.get("arguments", {})
5996
+ args = dict(raw_args) if isinstance(raw_args, dict) else {}
5997
+ meta = params.get("_meta")
5998
+ if tool_name == "run_command" and isinstance(meta, dict) and "zerochatJobKey" in meta:
5999
+ args["job_key"] = meta.get("zerochatJobKey")
6000
+ challenge_id = params.get("challengeId") or (meta.get("challengeId") if isinstance(meta, dict) else None)
6001
+ ctx = SecurityContext(workspace_dir=Path.cwd().resolve())
6002
+
6003
+ authorized_challenge = ACCESS_CONTROLLER.consume_challenge(challenge_id) if challenge_id else None
6004
+ if not authorized_challenge:
6005
+ decision = ACCESS_CONTROLLER.evaluate_authorization(tool_name, args, context=ctx, server_name="mcp-proxy")
6006
+ if decision.status == TOOL_POLICY_DENY:
6007
+ err_msg = f"Bloqueado por política de seguridad: {decision.reason}"
6008
+ return {"content": [{"type": "text", "text": f"Error: {err_msg}"}], "isError": True, "securityStatus": "deny", "reason": decision.reason}, None, err_msg
6009
+ if decision.status == TOOL_POLICY_ASK:
6010
+ ch = ACCESS_CONTROLLER.create_challenge(tool_name, args, decision, server_name="mcp-proxy")
6011
+ return {
6012
+ "requiresAuthorization": True,
6013
+ "challengeId": ch["id"],
6014
+ "toolName": tool_name,
6015
+ "serverName": "mcp-proxy",
6016
+ "arguments": args,
6017
+ "ruleOffer": decision.rule_offer,
6018
+ "details": decision.details,
6019
+ "content": [{"type": "text", "text": "Esta herramienta requiere autorización del usuario."}],
6020
+ "isError": False
6021
+ }, None, ""
6022
+
6023
+ arguments = dict(args)
5151
6024
  try:
5152
6025
  tool_output_json = handler(**arguments)
5153
6026
  except Exception as ex:
@@ -5201,6 +6074,63 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
5201
6074
  return self._dispatch_conversations(method, params)
5202
6075
  if method.startswith("zerochat/blobs/"):
5203
6076
  return self._dispatch_blobs(method, params)
6077
+ if method.startswith("zerochat/security/"):
6078
+ return self._dispatch_security(method, params)
6079
+ return None, {"code": -32601, "message": f"Método '{method}' no soportado."}, ""
6080
+
6081
+ @staticmethod
6082
+ def _dispatch_security(method: str, params: dict) -> tuple[dict | None, dict | None, str]:
6083
+ """Gestión de políticas y reglas de seguridad almacenadas en el backend local."""
6084
+ params = params if isinstance(params, dict) else {}
6085
+ user_id = params.get("user_id")
6086
+ session_id = params.get("session_id")
6087
+ ctx = SecurityContext(workspace_dir=Path.cwd().resolve(), user_id=user_id, session_id=session_id)
6088
+ try:
6089
+ if method == "zerochat/security/get":
6090
+ return {"policies": ACCESS_CONTROLLER.export_state(ctx)}, None, ""
6091
+ if method == "zerochat/security/update":
6092
+ ACCESS_CONTROLLER.import_state(params, context=ctx, persist=True)
6093
+ return {"policies": ACCESS_CONTROLLER.export_state(ctx)}, None, ""
6094
+ if method == "zerochat/security/authorize":
6095
+ challenge_id = params.get("challengeId")
6096
+ if not challenge_id or not isinstance(challenge_id, str):
6097
+ return None, {"code": -32602, "message": "challengeId es obligatorio"}, ""
6098
+ decision = params.get("decision", "deny")
6099
+ if decision == "deny":
6100
+ ACCESS_CONTROLLER.revoke_challenge(challenge_id)
6101
+ return {"authorized": False, "status": "deny"}, None, ""
6102
+
6103
+ constraints = params.get("constraints")
6104
+ dir_rule = params.get("directoryRule")
6105
+ success = ACCESS_CONTROLLER.authorize_challenge(challenge_id, decision, constraints, dir_rule, context=ctx)
6106
+ if not success:
6107
+ return None, {"code": -32002, "message": "Reto no encontrado o no válido"}, ""
6108
+
6109
+ if params.get("execute"):
6110
+ ch = ACCESS_CONTROLLER.consume_challenge(challenge_id)
6111
+ if not ch:
6112
+ return None, {"code": -32002, "message": "Error al consumir el reto para ejecución"}, ""
6113
+ t_name = ch["toolName"]
6114
+ t_args = ch["arguments"]
6115
+ handler = LOCAL_TOOL_HANDLERS.get(t_name)
6116
+ if handler:
6117
+ out_json = handler(**t_args)
6118
+ tool_err = ""
6119
+ try:
6120
+ po = json.loads(out_json)
6121
+ if isinstance(po, dict) and po.get("success") is False:
6122
+ tool_err = str(po.get("error", "Error en herramienta"))
6123
+ except (json.JSONDecodeError, TypeError, ValueError):
6124
+ pass
6125
+ return {"authorized": True, "result": {"content": [{"type": "text", "text": out_json}], "isError": bool(tool_err)}}, None, tool_err
6126
+ else:
6127
+ ext_res = GLOBAL_MCP_MANAGER.call(t_name, t_args)
6128
+ return {"authorized": True, "result": ext_res}, None, ""
6129
+ return {"authorized": True, "challengeId": challenge_id}, None, ""
6130
+ except ValueError as exc:
6131
+ return None, {"code": -32602, "message": str(exc)}, ""
6132
+ except Exception as exc:
6133
+ return None, {"code": -32603, "message": f"Error de seguridad: {exc}"}, str(exc)
5204
6134
  return None, {"code": -32601, "message": f"Método '{method}' no soportado."}, ""
5205
6135
 
5206
6136
  @staticmethod
@@ -5461,13 +6391,6 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
5461
6391
  method = req["method"]
5462
6392
  params = req.get("params", {})
5463
6393
 
5464
- if method == "tools/call":
5465
- auth_error = self.verify_tool_authorization(post_data, req_path or "/")
5466
- if auth_error:
5467
- self._log_req("POST", safe_path)
5468
- self._reject(403, {"error": auth_error}, safe_path, t0, auth_error)
5469
- return
5470
-
5471
6394
  # Etiqueta de seguimiento para la petición y respuesta (sin datos sensibles)
5472
6395
  action_tag = f"[tools/call: {params['name']}]" if method == "tools/call" else f"[rpc: {method}]"
5473
6396
  log_detail = f"{safe_path} {action_tag}"
@@ -6465,14 +7388,15 @@ def prepare_environment(args, is_dev: bool):
6465
7388
 
6466
7389
 
6467
7390
  def reset_session_credentials():
6468
- """Carga el token diario y renueva la clave de firma de herramientas."""
6469
- global TOOL_AUTH_KEY, TOOL_AUTH_SESSION_ID, TOOL_AUTH_NONCES
7391
+ """Carga el token diario y reinicia las autorizaciones de sesión en memoria."""
6470
7392
  current_session_token()
6471
- # A restart deliberately invalidates every browser-side signing credential.
6472
- TOOL_AUTH_KEY = secrets.token_bytes(32)
6473
- TOOL_AUTH_SESSION_ID = secrets.token_urlsafe(18)
6474
- with TOOL_AUTH_NONCES_LOCK:
6475
- TOOL_AUTH_NONCES = {}
7393
+ ACCESS_CONTROLLER.clear_session()
7394
+ if RUN_SESSION is not None:
7395
+ if RUN_SESSION.tool_security:
7396
+ ACCESS_CONTROLLER.import_state(RUN_SESSION.tool_security, persist=False)
7397
+ if RUN_SESSION.allow_dangerous_tools:
7398
+ for tool_name in ("write_file", "edit_file", "run_command"):
7399
+ ACCESS_CONTROLLER.set_tool_policy(tool_name, TOOL_POLICY_ALLOW, scope=SCOPE_SESSION)
6476
7400
 
6477
7401
 
6478
7402
  def open_server(args, local_ui: bool) -> ThreadingHTTPServer:
File without changes
File without changes
File without changes