Files
MajoorWaldi-ComfyUI-Majoor-…/mjr_am_shared/errors.py
T
Ewald 9c5078d174 fix: harden registry packaging and runtime boundaries
Exclude development-only content from Registry packages while retaining runtime
docs and vendor assets. Centralize environment access and media process execution,
validate filesystem inputs, and restrict nested media protocols.

Route update checks through the backend GitHub boundary and read version metadata
without spawning Git. Preserve annotated-tag priority over lightweight nightly
tags, including packed refs, with regression coverage. Rebuild the frontend bundle.

Validation: Python tests with coverage, JS tests, targeted media/version regression
tests, and the canonical Python quality gate.
2026-09-26 19:21:04 +02:00

70 lines
1.9 KiB
Python

"""
Shared helpers for sanitizing error messages before they reach clients.
"""
from __future__ import annotations
import os
import re
from typing import Any
from mjr_am_shared.runtime_env import get_env
from .log import get_logger
logger = get_logger(__name__)
_DEBUG_MODE = get_env("MJR_DEBUG", "").strip().lower() in ("1", "true", "yes", "on")
_WINDOWS_PATH_RE = re.compile(r"[A-Za-z]:\\[^\s]+")
_UNC_PATH_RE = re.compile(r"\\\\[^\s\\]+\\[^\s]+")
_UNIX_PATH_RE = re.compile(r"(?<![A-Za-z0-9:/?&=#%])/(?!/)[^\s#?]+")
def _mask_paths(value: str) -> str:
"""Mask path-looking substrings to avoid leaking filesystem structure."""
cleaned = _WINDOWS_PATH_RE.sub("[path]", value)
cleaned = _UNC_PATH_RE.sub("[path]", cleaned)
cleaned = _UNIX_PATH_RE.sub("[path]", cleaned)
return cleaned
def sanitize_error_message(exc: Any, fallback: str) -> str:
"""
Build a safe error message for clients.
Args:
exc: Exception or raw value to sanitize.
fallback: Fallback message to show when nothing meaningful remains.
Returns:
A string suitable for inclusion in API responses.
"""
if not fallback:
fallback = "An error occurred"
if exc is None:
return fallback
try:
raw = str(exc)
except Exception:
raw = ""
if not raw:
return fallback
# Never call expandvars — it would expand env-var references like %USERNAME%
# or $HOME embedded in exception messages, leaking real values to clients.
try:
cwd = os.getcwd()
except Exception:
cwd = ""
cleaned = raw.replace(cwd, "[cwd]") if cwd else raw
sanitized = _mask_paths(cleaned)
sanitized = " ".join(sanitized.splitlines()).strip()
if _DEBUG_MODE:
logger.debug("Sanitized error payload: %s", sanitized, exc_info=True)
if sanitized:
return f"{fallback}: {sanitized[:200]}"
return fallback