fix: address 18 CRITICAL+HIGH PR review comments

**Critical Fixes (7 issues):**
- Fix GraphQL schema field names in users tool (role→roles, remove email)
- Fix GraphQL mutation signatures (addUserInput, deleteUser input)
- Fix dict(None) TypeError guards in users tool (use `or {}` pattern)
- Fix FastAPI version constraint (0.116.1→0.115.0)
- Fix WebSocket SSL context handling (support CA bundles, bool, and None)
- Fix critical disk threshold treated as warning (split counters)

**High Priority Fixes (11 issues):**
- Fix Docker update/remove action response field mapping
- Fix path traversal vulnerability in log validation (normalize paths)
- Fix deleteApiKeys validation (check response before success)
- Fix rclone create_remote validation (check response)
- Fix keys input_data type annotation (dict[str, Any])
- Fix VM domain/domains fallback restoration

**Changes by file:**
- unraid_mcp/tools/docker.py: Response field mapping
- unraid_mcp/tools/info.py: Split critical/warning counters
- unraid_mcp/tools/storage.py: Path normalization for traversal protection
- unraid_mcp/tools/users.py: GraphQL schema + null handling
- unraid_mcp/tools/keys.py: Validation + type annotations
- unraid_mcp/tools/rclone.py: Response validation
- unraid_mcp/tools/virtualization.py: Domain fallback
- unraid_mcp/subscriptions/manager.py: SSL context creation
- pyproject.toml: FastAPI version fix
- tests/*: New tests for all fixes

**Review threads resolved:**
PRRT_kwDOO6Hdxs5uu70L, PRRT_kwDOO6Hdxs5uu70O, PRRT_kwDOO6Hdxs5uu70V,
PRRT_kwDOO6Hdxs5uu70e, PRRT_kwDOO6Hdxs5uu70i, PRRT_kwDOO6Hdxs5uu7zn,
PRRT_kwDOO6Hdxs5uu7z_, PRRT_kwDOO6Hdxs5uu7sI, PRRT_kwDOO6Hdxs5uu7sJ,
PRRT_kwDOO6Hdxs5uu7sK, PRRT_kwDOO6Hdxs5uu7Tk, PRRT_kwDOO6Hdxs5uu7Tn,
PRRT_kwDOO6Hdxs5uu7Tr, PRRT_kwDOO6Hdxs5uu7Ts, PRRT_kwDOO6Hdxs5uu7Tu,
PRRT_kwDOO6Hdxs5uu7Tv, PRRT_kwDOO6Hdxs5uu7Tw, PRRT_kwDOO6Hdxs5uu7Tx

All tests passing.

Co-authored-by: docker-fixer <agent@pr-fixes>
Co-authored-by: info-fixer <agent@pr-fixes>
Co-authored-by: storage-fixer <agent@pr-fixes>
Co-authored-by: users-fixer <agent@pr-fixes>
Co-authored-by: config-fixer <agent@pr-fixes>
Co-authored-by: websocket-fixer <agent@pr-fixes>
Co-authored-by: keys-rclone-fixer <agent@pr-fixes>
Co-authored-by: vm-fixer <agent@pr-fixes>
This commit is contained in:
Jacob Magar
2026-02-15 16:42:58 -05:00
parent 2697c269a3
commit 184b8aca1c
35 changed files with 9360 additions and 588 deletions

View File

@@ -8,6 +8,7 @@ error handling, reconnection logic, and authentication.
import asyncio
import json
import os
import ssl
from datetime import datetime
from typing import Any
@@ -153,6 +154,16 @@ class SubscriptionManager:
logger.debug(f"[WEBSOCKET:{subscription_name}] Connecting to: {ws_url}")
logger.debug(f"[WEBSOCKET:{subscription_name}] API Key present: {'Yes' if UNRAID_API_KEY else 'No'}")
# Build SSL context for wss:// connections
ssl_context = None
if ws_url.startswith('wss://'):
if isinstance(UNRAID_VERIFY_SSL, str):
ssl_context = ssl.create_default_context(cafile=UNRAID_VERIFY_SSL)
elif UNRAID_VERIFY_SSL:
ssl_context = ssl.create_default_context()
else:
ssl_context = ssl._create_unverified_context()
# Connection with timeout
connect_timeout = 10
logger.debug(f"[WEBSOCKET:{subscription_name}] Connection timeout: {connect_timeout}s")
@@ -163,7 +174,7 @@ class SubscriptionManager:
ping_interval=20,
ping_timeout=10,
close_timeout=10,
ssl=UNRAID_VERIFY_SSL
ssl=ssl_context
) as websocket:
selected_proto = websocket.subprotocol or "none"

View File

@@ -308,7 +308,13 @@ def register_docker_tool(mcp: FastMCP) -> None:
}
docker_data = data.get("docker", {})
result = docker_data.get(action, docker_data.get("removeContainer"))
# Map action names to GraphQL response field names where they differ
response_field_map = {
"update": "updateContainer",
"remove": "removeContainer",
}
field = response_field_map.get(action, action)
result = docker_data.get(field)
return {
"success": True,
"action": action,

View File

@@ -204,13 +204,18 @@ def _process_system_info(raw_info: dict[str, Any]) -> dict[str, Any]:
def _analyze_disk_health(disks: list[dict[str, Any]]) -> dict[str, int]:
"""Analyze health status of disk arrays."""
counts = {"healthy": 0, "failed": 0, "missing": 0, "new": 0, "warning": 0, "unknown": 0}
counts = {"healthy": 0, "failed": 0, "missing": 0, "new": 0, "warning": 0, "critical": 0, "unknown": 0}
for disk in disks:
status = disk.get("status", "").upper()
warning = disk.get("warning")
critical = disk.get("critical")
if status == "DISK_OK":
counts["warning" if (warning or critical) else "healthy"] += 1
if critical:
counts["critical"] += 1
elif warning:
counts["warning"] += 1
else:
counts["healthy"] += 1
elif status in ("DISK_DSBL", "DISK_INVALID"):
counts["failed"] += 1
elif status == "DISK_NP":
@@ -254,10 +259,11 @@ def _process_array_status(raw: dict[str, Any]) -> dict[str, Any]:
health_summary[label] = _analyze_disk_health(raw[key])
total_failed = sum(h.get("failed", 0) for h in health_summary.values())
total_critical = sum(h.get("critical", 0) for h in health_summary.values())
total_missing = sum(h.get("missing", 0) for h in health_summary.values())
total_warning = sum(h.get("warning", 0) for h in health_summary.values())
if total_failed > 0:
if total_failed > 0 or total_critical > 0:
overall = "CRITICAL"
elif total_missing > 0:
overall = "DEGRADED"

View File

@@ -111,7 +111,7 @@ def register_keys_tool(mcp: FastMCP) -> None:
if action == "update":
if not key_id:
raise ToolError("key_id is required for 'update' action")
input_data = {"id": key_id}
input_data: dict[str, Any] = {"id": key_id}
if name:
input_data["name"] = name
if roles:
@@ -130,6 +130,9 @@ def register_keys_tool(mcp: FastMCP) -> None:
data = await make_graphql_request(
MUTATIONS["delete"], {"input": {"ids": [key_id]}}
)
result = data.get("deleteApiKeys")
if not result:
raise ToolError(f"Failed to delete API key '{key_id}': no confirmation from server")
return {
"success": True,
"message": f"API key '{key_id}' deleted",

View File

@@ -100,7 +100,9 @@ def register_rclone_tool(mcp: FastMCP) -> None:
MUTATIONS["create_remote"],
{"input": {"name": name, "type": provider_type, "config": config_data}},
)
remote = data.get("rclone", {}).get("createRCloneRemote", {})
remote = data.get("rclone", {}).get("createRCloneRemote")
if not remote:
raise ToolError(f"Failed to create remote '{name}': no confirmation from server")
return {
"success": True,
"message": f"Remote '{name}' created successfully",

View File

@@ -4,6 +4,7 @@ Provides the `unraid_storage` tool with 6 actions for shares, physical disks,
unassigned devices, log files, and log content retrieval.
"""
import posixpath
from typing import Any, Literal
from fastmcp import FastMCP
@@ -99,11 +100,14 @@ def register_storage_tool(mcp: FastMCP) -> None:
if not log_path:
raise ToolError("log_path is required for 'logs' action")
_ALLOWED_LOG_PREFIXES = ("/var/log/", "/boot/logs/", "/mnt/")
if not any(log_path.startswith(p) for p in _ALLOWED_LOG_PREFIXES):
# Normalize path to prevent traversal attacks (e.g. /var/log/../../etc/shadow)
normalized = posixpath.normpath(log_path)
if not any(normalized.startswith(p) for p in _ALLOWED_LOG_PREFIXES):
raise ToolError(
f"log_path must start with one of: {', '.join(_ALLOWED_LOG_PREFIXES)}. "
f"Use log_files action to discover valid paths."
)
log_path = normalized
query = QUERIES[action]
variables: dict[str, Any] | None = None

View File

@@ -15,17 +15,17 @@ from ..core.exceptions import ToolError
QUERIES: dict[str, str] = {
"me": """
query GetMe {
me { id name role email }
me { id name description roles }
}
""",
"list": """
query ListUsers {
users { id name role email }
users { id name description roles }
}
""",
"get": """
query GetUser($id: PrefixedID!) {
user(id: $id) { id name role email }
query GetUser($id: ID!) {
user(id: $id) { id name description roles }
}
""",
"cloud": """
@@ -47,13 +47,13 @@ QUERIES: dict[str, str] = {
MUTATIONS: dict[str, str] = {
"add": """
mutation AddUser($input: AddUserInput!) {
addUser(input: $input) { id name role }
mutation AddUser($input: addUserInput!) {
addUser(input: $input) { id name description roles }
}
""",
"delete": """
mutation DeleteUser($id: PrefixedID!) {
deleteUser(id: $id)
mutation DeleteUser($input: deleteUserInput!) {
deleteUser(input: $input) { id name }
}
""",
}
@@ -101,7 +101,7 @@ def register_users_tool(mcp: FastMCP) -> None:
if action == "me":
data = await make_graphql_request(QUERIES["me"])
return dict(data.get("me", {}))
return data.get("me") or {}
if action == "list":
data = await make_graphql_request(QUERIES["list"])
@@ -112,7 +112,7 @@ def register_users_tool(mcp: FastMCP) -> None:
if not user_id:
raise ToolError("user_id is required for 'get' action")
data = await make_graphql_request(QUERIES["get"], {"id": user_id})
return dict(data.get("user", {}))
return data.get("user") or {}
if action == "add":
if not name or not password:
@@ -132,7 +132,7 @@ def register_users_tool(mcp: FastMCP) -> None:
if not user_id:
raise ToolError("user_id is required for 'delete' action")
data = await make_graphql_request(
MUTATIONS["delete"], {"id": user_id}
MUTATIONS["delete"], {"input": {"id": user_id}}
)
return {
"success": True,
@@ -141,11 +141,11 @@ def register_users_tool(mcp: FastMCP) -> None:
if action == "cloud":
data = await make_graphql_request(QUERIES["cloud"])
return dict(data.get("cloud", {}))
return data.get("cloud") or {}
if action == "remote_access":
data = await make_graphql_request(QUERIES["remote_access"])
return dict(data.get("remoteAccess", {}))
return data.get("remoteAccess") or {}
if action == "origins":
data = await make_graphql_request(QUERIES["origins"])

View File

@@ -105,15 +105,16 @@ def register_vm_tool(mcp: FastMCP) -> None:
if action == "list":
data = await make_graphql_request(QUERIES["list"])
if data.get("vms") and data["vms"].get("domains"):
vms = data["vms"]["domains"]
return {"vms": list(vms) if isinstance(vms, list) else []}
if data.get("vms"):
vms = data["vms"].get("domains") or data["vms"].get("domain")
if vms:
return {"vms": list(vms) if isinstance(vms, list) else []}
return {"vms": []}
if action == "details":
data = await make_graphql_request(QUERIES["details"])
if data.get("vms"):
vms = data["vms"].get("domains") or []
vms = data["vms"].get("domains") or data["vms"].get("domain") or []
for vm in vms:
if (
vm.get("uuid") == vm_id