The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface. The fastest local inference engine in the world.
Add governance enforcement for custom nodes (#16167)
guill3d9b2d551788
diff --git a/app/governance.py b/app/governance.pynew file mode 100644index 000000000..247099806--- /dev/null+++ b/app/governance.py@@ -0,0 +1,448 @@+import base64+import binascii+import importlib.machinery+import importlib.util+import json+import logging+import os+from pathlib import Path+import re+import sys+from types import MappingProxyType+from typing import Awaitable, Callable, Mapping+import unicodedata++import yaml+++GOVERNANCE_REQUIRED = False+GOVERNANCE_BUILD_IDENTITY = ""+GOVERNANCE_PUBLIC_KEY = ""+GOVERNANCE_MIN_POLICY_GENERATION = 0+GOVERNANCE_CAPABILITY_VERSION = 1++_DOMAIN_SEPARATOR = b"comfyui-governance-v1\x00"+_MAX_ENVELOPE_BYTES = 1024 * 1024+_MAX_PAYLOAD_BYTES = 512 * 1024+_ENVELOPE_KEYS = {"schema", "payload", "signature"}+_PAYLOAD_KEYS = {+ "schemaVersion",+ "audience",+ "versionId",+ "buildIdentity",+ "sourcesDigest",+ "policyGeneration",+ "activeForms",+ "customNodeMode",+ "packs",+ "deniedPacks",+ "disabledNodes",+ "disabledPartnerNodes",+ "models",+}+_ACTIVE_FORMS = ("customNode", "nodeId", "model", "partnerNode")+# Only add a form here once this build enforces it; anything absent is refused rather than silently allowed.+_ENFORCED_FORMS = frozenset({"customNode", "nodeId", "partnerNode"})+_BASE64URL_PATTERN = re.compile(r"[A-Za-z0-9_-]*")+_PROVIDER_ID_PATTERN = re.compile(r"[a-z0-9._-]+")+# The form pack_digest returns, and the form of a model's sealed digest: "blake3:" and 64 lowercase hex digits.+_BLAKE3_DIGEST_PATTERN = re.compile(r"blake3:[0-9a-f]{64}")+# What the digest measures: Python source (.pyw is source on Windows) and extension modules, native libraries (versioned+# .so.N too), and the .js/.mjs files the frontend serves (server.py lists **/*.js). Any other file a pack's code may open+# or run, such as a shell script, a suffixless executable, .exe, .wasm or .cjs, is not measured.+_PACK_EXTENSIONS = frozenset({".py", ".pyw", ".pyd", ".so", ".dll", ".dylib", ".js", ".mjs"})+# A versioned shared library (libfoo.so.1, libfoo.so.1.2) loads like a .so, though its last suffix is a number.+_VERSIONED_LIBRARY_PATTERN = re.compile(r"\.so(?:\.[0-9]+)+\Z")+_BYTECODE_EXTENSIONS = frozenset({".pyc", ".pyo"})+_LEGACY_MANAGER_PACK = "comfyui-manager"++_COMFYUI_ROOT = Path(__file__).parent.parent+_POLICY_PATH = _COMFYUI_ROOT / "governance" / "policy.signed.json"+_policy: dict | None = None+_disabled_nodes: frozenset[str] = frozenset()+_original_load_custom_node: Callable[[str, set[str], str], Awaitable[bool]] | None = None+_custom_node_mode: str | None = None+_denied_packs: frozenset[str] = frozenset()+_allowed_packs: Mapping[str, str] = MappingProxyType({})+++def load_disabled_nodes(path: str) -> set[str]:+ with open(path, "r", encoding="utf-8") as stream:+ config = yaml.safe_load(stream)++ if not isinstance(config, dict):+ raise ValueError("disabled nodes config must be a mapping")+ if "disabled_nodes" not in config:+ raise ValueError("disabled nodes config must contain disabled_nodes")++ disabled_nodes = config["disabled_nodes"]+ if not isinstance(disabled_nodes, list):+ raise ValueError("disabled_nodes must be a list")+ if not all(isinstance(node_id, str) for node_id in disabled_nodes):+ raise ValueError("disabled_nodes entries must be strings")++ return set(disabled_nodes)+++def set_custom_node_policy(mode: str | None, denied_packs: frozenset[str], allowed_packs: dict[str, str]) -> None:+ if mode is not None and mode not in {"allowlist", "blocklist"}:+ raise ValueError("custom-node policy mode must be allowlist, blocklist, or None")++ global _custom_node_mode, _denied_packs, _allowed_packs+ _custom_node_mode = mode+ _denied_packs = frozenset(denied_packs)+ _allowed_packs = MappingProxyType({name.lower(): digest for name, digest in allowed_packs.items()})+ if mode is not None:+ # Cached bytecode runs without reading the source the digest measures, so a gated install must never write any, child interpreters included.+ sys.dont_write_bytecode = True+ os.environ["PYTHONDONTWRITEBYTECODE"] = "1"+ # A cache prefix (PYTHONPYCACHEPREFIX, -X pycache_prefix) puts bytecode outside the pack, where the digest cannot+ # refuse it; without one, imports look only in the pack's own __pycache__, which the digest does refuse. The+ # environment variable goes too, so Python processes a pack starts do not read the prefix either (a subinterpreter+ # in this process keeps the start-up prefix).+ sys.pycache_prefix = None+ os.environ.pop("PYTHONPYCACHEPREFIX", None)+++class _PackBytecodeError(ValueError):+ def __init__(self, paths: list[Path]):+ super().__init__("pack must not contain compiled Python bytecode")+ self.paths = paths+++class _SourceOnlyLoader(importlib.machinery.SourceFileLoader):+ # Compiles the .py itself on every load. The stock loader would run a cached .pyc instead, and a single-file pack's+ # cache sits in custom_nodes/__pycache__, outside the file its digest measures.+ def get_code(self, fullname):+ path = self.get_filename(fullname)+ return self.source_to_code(self.get_data(path), path)+++def pack_module_spec(name: str, path: str) -> importlib.machinery.ModuleSpec | None:+ """Spec for a pack's entry file, as spec_from_file_location builds it; under a custom-node policy it never reads bytecode."""+ if _custom_node_mode is None:+ return importlib.util.spec_from_file_location(name, path)+ return importlib.util.spec_from_file_location(name, path, loader=_SourceOnlyLoader(name, path))+++def pack_refusal(module_path: str) -> str | None:+ """Return why the custom-node policy refuses this pack, for the log, or None when it may load."""+ if _custom_node_mode is None:+ return None++ basename = Path(module_path).name+ refused = f"Custom node pack '{basename}' is not permitted by your organization's policy."+ # The legacy Manager pack's prestartup script runs scheduled installs before any other pack is checked, so it is+ # refused even when the policy lists it by digest. It is recognised by folder name only: a copy under another folder+ # name is checked like any other pack (a blocklist admits it unless denied; an allowlist admits only a listed digest).+ if basename.casefold() == _LEGACY_MANAGER_PACK:+ return (+ f"Custom node pack '{basename}' is not loaded: ComfyUI-Manager cannot run under a custom-node policy, "+ "because its startup script installs packs before they are checked."+ )+ expected_digest = _allowed_packs.get(basename.lower())+ if _custom_node_mode == "blocklist":+ if basename.lower() in _denied_packs:+ return refused+ if expected_digest is None:+ return None++ try:+ digest = pack_digest(module_path)+ except _PackBytecodeError as error:+ # Usually left by an earlier run without the policy, so the user can fix it without the administrator.+ return (+ f"Custom node pack '{basename}' is not loaded: it carries compiled Python files the policy cannot check "+ f"({', '.join(str(path) for path in error.paths)}). Delete them and restart ComfyUI."+ )+ except (ValueError, OSError) as error:+ logging.warning("Cannot verify custom node pack '%s': %s", basename, error)+ return refused++ if _custom_node_mode == "allowlist":+ allowed = digest in _allowed_packs.values()+ else:+ allowed = digest == expected_digest+ return None if allowed else refused+++def pack_allowed(module_path: str) -> bool:+ return pack_refusal(module_path) is None+++def _is_measured(relative: Path) -> bool:+ return relative.suffix.lower() in _PACK_EXTENSIONS or _VERSIONED_LIBRARY_PATTERN.search("".join(relative.suffixes).lower()) is not None+++def pack_digest(pack_path: str) -> str:+ # Keep local: hashing imports comfy.cli_args, which would freeze CLI defaults before main enables argument parsing.+ from app.assets.services.hashing import compute_blake3_hash+ from blake3 import blake3++ path = Path(pack_path)+ if path.is_symlink():+ raise ValueError("pack path must not be a symlink")++ if path.is_file():+ if path.suffix.lower() != ".py":+ raise ValueError("single-file packs must be Python files")+ root, candidates = path.parent, [path]+ elif path.is_dir():+ root, candidates = path, list(path.rglob("*"))+ else:+ raise ValueError("pack path must be a directory or Python file")++ if any(candidate.is_symlink() for candidate in candidates):+ raise ValueError("pack must not contain symlinks")+ contents = [(candidate.relative_to(root), candidate) for candidate in candidates if candidate.is_file()]+ # An unchecked hash-based .pyc executes without reading the .py this digest measures, so bytecode in the pack is+ # refused outright. Bytecode outside it is not read: pack_module_spec loads entry files from source, and+ # set_custom_node_policy clears sys.pycache_prefix and PYTHONPYCACHEPREFIX so a pack's imports, in this process+ # and in Python processes it starts, find bytecode only in its own __pycache__.+ bytecode = set()+ for relative, _ in contents:+ if "__pycache__" in relative.parts:+ bytecode.add(root.joinpath(*relative.parts[: relative.parts.index("__pycache__") + 1]))+ elif relative.suffix.lower() in _BYTECODE_EXTENSIONS:+ bytecode.add(root / relative)+ if bytecode:+ raise _PackBytecodeError(sorted(bytecode, key=str))+ files = [+ (unicodedata.normalize("NFC", relative.as_posix()), candidate)+ for relative, candidate in contents+ if _is_measured(relative)+ ]+ if len(files) != len({relative_path for relative_path, _ in files}):+ raise ValueError("pack paths must remain unique after NFC normalization")++ hasher = blake3()+ for relative_path, file_path in sorted(files, key=lambda record: record[0].encode("utf-8")):+ file_digest, _ = compute_blake3_hash(str(file_path))+ assert file_digest is not None+ hasher.update(relative_path.encode("utf-8") + b"\x00" + bytes.fromhex(file_digest) + b"\x00")+ return "blake3:" + hasher.hexdigest()+++def apply_disabled_nodes(disabled: set[str]) -> None:+ global _disabled_nodes, _original_load_custom_node++ disabled = disabled.union(_disabled_nodes)+ if not disabled:+ return++ import nodes++ missing = disabled.difference(nodes.NODE_CLASS_MAPPINGS)+ pruned = len(disabled) - len(missing)+ for node_id in disabled:+ nodes.NODE_CLASS_MAPPINGS.pop(node_id, None)+ nodes.NODE_DISPLAY_NAME_MAPPINGS.pop(node_id, None)++ _disabled_nodes = _disabled_nodes.union(disabled)+ if _original_load_custom_node is None:+ _original_load_custom_node = nodes.load_custom_node+ original_load_custom_node = _original_load_custom_node++ async def load_custom_node(module_path: str, ignore: set[str] = set(), module_parent: str = "custom_nodes") -> bool:+ return await original_load_custom_node(module_path, ignore | _disabled_nodes, module_parent)++ nodes.load_custom_node = load_custom_node++ if missing:+ logging.warning("Disabled node IDs were not registered: %s", ", ".join(sorted(missing)))+ logging.info("Pruned %d disabled node%s.", pruned, "" if pruned == 1 else "s")+++def verify_and_load(envelope_bytes: bytes) -> dict:+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey++ if len(envelope_bytes) > _MAX_ENVELOPE_BYTES:+ raise ValueError("governance envelope exceeds maximum size")++ envelope = json.loads(envelope_bytes)+ if not isinstance(envelope, dict) or set(envelope) != _ENVELOPE_KEYS:+ raise ValueError("governance envelope must contain exactly schema, payload, and signature")+ if type(envelope["schema"]) is not int or envelope["schema"] != 1:+ raise ValueError("unsupported governance envelope schema")+ if not isinstance(envelope["payload"], str) or not isinstance(envelope["signature"], str):+ raise ValueError("governance payload and signature must be strings")++ max_encoded_payload_size = (_MAX_PAYLOAD_BYTES * 4 + 2) // 3+ if len(envelope["payload"]) > max_encoded_payload_size:+ raise ValueError("governance payload exceeds maximum size")++ payload_bytes = _decode_base64url(envelope["payload"], "payload")+ if len(payload_bytes) > _MAX_PAYLOAD_BYTES:+ raise ValueError("governance payload exceeds maximum size")+ signature = _decode_base64url(envelope["signature"], "signature")+ if len(signature) != 64:+ raise ValueError("governance signature must be 64 bytes")+ public_key_bytes = _decode_base64url(GOVERNANCE_PUBLIC_KEY, "public key")+ if len(public_key_bytes) != 32:+ raise ValueError("governance public key must be 32 bytes")++ Ed25519PublicKey.from_public_bytes(public_key_bytes).verify(signature, _DOMAIN_SEPARATOR + payload_bytes)++ payload = json.loads(payload_bytes)+ _validate_payload(payload)+ return payload+++def _decode_base64url(encoded: str, field: str) -> bytes:+ if not isinstance(encoded, str) or _BASE64URL_PATTERN.fullmatch(encoded) is None:+ raise ValueError(f"governance {field} must use unpadded base64url")++ try:+ decoded = base64.b64decode(encoded + "=" * (-len(encoded) % 4), altchars=b"-_", validate=True)+ except (binascii.Error, ValueError) as error:+ raise ValueError(f"governance {field} is not valid base64url") from error++ canonical = base64.urlsafe_b64encode(decoded).rstrip(b"=").decode("ascii")+ if canonical != encoded:+ raise ValueError(f"governance {field} is not canonically encoded")+ return decoded+++def _is_pack_basename(name: str) -> bool:+ """Whether a signed pack name is a plain folder or file name under custom_nodes on every OS a release can target,+ so a backslash is refused on Linux and macOS too (the builder never signs one)."""+ return name not in {"", ".", ".."} and "/" not in name and "\\" not in name+++def _validate_payload(payload: dict) -> None:+ if not isinstance(payload, dict) or set(payload) != _PAYLOAD_KEYS:+ raise ValueError("governance payload has an unexpected schema")++ if type(payload["schemaVersion"]) is not int or payload["schemaVersion"] != 1:+ raise ValueError("unsupported governance payload schema")+ for key in ("audience", "versionId", "buildIdentity", "sourcesDigest"):+ if not isinstance(payload[key], str):+ raise ValueError(f"governance payload {key} must be a string")+ if payload["audience"] != "comfyui-core":+ raise ValueError("governance payload has the wrong audience")+ if payload["buildIdentity"] != GOVERNANCE_BUILD_IDENTITY:+ raise ValueError("governance payload has the wrong build identity")+ if type(payload["policyGeneration"]) is not int:+ raise ValueError("governance policy generation must be an integer")+ if payload["policyGeneration"] < GOVERNANCE_MIN_POLICY_GENERATION:+ raise ValueError("governance policy generation is below the required minimum")++ active_forms = payload["activeForms"]+ if not isinstance(active_forms, list) or not all(isinstance(form, str) for form in active_forms):+ raise ValueError("governance activeForms must be a string list")+ if not active_forms:+ raise ValueError("governance activeForms must not be empty")+ if active_forms != [form for form in _ACTIVE_FORMS if form in active_forms]:+ raise ValueError("governance activeForms must be unique and canonically ordered")++ custom_node_mode = payload["customNodeMode"]+ custom_node_active = "customNode" in active_forms+ if custom_node_active and custom_node_mode not in {"allowlist", "blocklist"}:+ raise ValueError("governance customNodeMode is invalid for an active customNode form")+ if not custom_node_active and custom_node_mode is not None:+ raise ValueError("governance customNodeMode must be null when customNode is inactive")++ packs = payload["packs"]+ if not isinstance(packs, list):+ raise ValueError("governance packs must be a list")+ for pack in packs:+ if not isinstance(pack, dict) or set(pack) != {"name", "digest"}:+ raise ValueError("governance pack entries must contain exactly name and digest")+ if not isinstance(pack["name"], str) or not isinstance(pack["digest"], str):+ raise ValueError("governance pack name and digest must be strings")+ # A blocklist looks a pin up by the lowered folder or file name os.listdir returns, so a name that is not a plain+ # name on every target OS is a pin that may silently never apply; an allowlist admits by digest alone. Case is+ # free, since the builder signs folder names as they are and both sides lower them.+ if custom_node_mode == "blocklist" and not _is_pack_basename(pack["name"]):+ raise ValueError("governance blocklist pack names must be basenames")+ # pack_digest always writes this form.+ if _BLAKE3_DIGEST_PATTERN.fullmatch(pack["digest"]) is None:+ raise ValueError("governance pack digests must be canonical BLAKE3 digests")+ pack_names = [pack["name"].lower() for pack in packs]+ if len(pack_names) != len(set(pack_names)):+ raise ValueError("governance pack names must be unique")++ denied_packs = payload["deniedPacks"]+ if not isinstance(denied_packs, list) or not all(isinstance(pack, str) for pack in denied_packs):+ raise ValueError("governance deniedPacks must be a string list")+ if denied_packs != sorted(set(denied_packs)):+ raise ValueError("governance deniedPacks must be sorted and unique")+ if any(pack != pack.lower() or not _is_pack_basename(pack) for pack in denied_packs):+ raise ValueError("governance deniedPacks entries must be lowercase basenames")+ if denied_packs and custom_node_mode != "blocklist":+ raise ValueError("governance deniedPacks requires blocklist mode")++ disabled_nodes = payload["disabledNodes"]+ if not isinstance(disabled_nodes, list) or not all(isinstance(node_id, str) for node_id in disabled_nodes):+ raise ValueError("governance disabledNodes must be a string list")+ if disabled_nodes != sorted(set(disabled_nodes)):+ raise ValueError("governance disabledNodes must be sorted and unique")++ partner_nodes = payload["disabledPartnerNodes"]+ if not isinstance(partner_nodes, list):+ raise ValueError("governance disabledPartnerNodes must be a list")+ partner_node_ids = []+ for partner_node in partner_nodes:+ if not isinstance(partner_node, dict) or set(partner_node) != {"nodeId", "providerId"}:+ raise ValueError("governance partner-node entries must contain exactly nodeId and providerId")+ if not isinstance(partner_node["nodeId"], str) or not isinstance(partner_node["providerId"], str):+ raise ValueError("governance partner-node ids must be strings")+ if _PROVIDER_ID_PATTERN.fullmatch(partner_node["providerId"]) is None:+ raise ValueError("governance providerId is invalid")+ partner_node_ids.append(partner_node["nodeId"])+ if partner_node_ids != sorted(set(partner_node_ids)):+ raise ValueError("governance partner-node entries must be unique and sorted by nodeId")++ models = payload["models"]+ if not isinstance(models, list) or not all(isinstance(model, str) for model in models):+ raise ValueError("governance models must be a string list")+ if models != sorted(set(models)):+ raise ValueError("governance models must be sorted and unique")+ if any(_BLAKE3_DIGEST_PATTERN.fullmatch(model) is None for model in models):+ raise ValueError("governance models must contain canonical BLAKE3 digests")++ if packs and not custom_node_active:+ raise ValueError("governance packs requires an active customNode form")+ if disabled_nodes and "nodeId" not in active_forms:+ raise ValueError("governance disabledNodes requires an active nodeId form")+ if "nodeId" in active_forms and not disabled_nodes:+ raise ValueError("governance nodeId form requires non-empty disabledNodes")+ if partner_nodes and "partnerNode" not in active_forms:+ raise ValueError("governance disabledPartnerNodes requires an active partnerNode form")+ if models and "model" not in active_forms:+ raise ValueError("governance models requires an active model form")+++def _apply_policy(policy: dict) -> None:+ global _policy, _disabled_nodes+ _policy = policy+ active_forms = policy.get("activeForms", ())+ custom_node_mode = policy.get("customNodeMode") if "customNode" in active_forms else None+ allowed_packs = {pack["name"]: pack["digest"] for pack in policy.get("packs", ())}+ set_custom_node_policy(custom_node_mode, frozenset(policy.get("deniedPacks", ())), allowed_packs)+ partner_node_ids = {entry["nodeId"] for entry in policy.get("disabledPartnerNodes", ())}+ _disabled_nodes = frozenset(policy.get("disabledNodes", ())).union(partner_node_ids)+++def initialize() -> None:+ if not GOVERNANCE_REQUIRED:+ return++ try:+ from comfy.cli_args import args++ if args.disabled_nodes_config:+ raise RuntimeError("unsigned disabled-node config is not allowed in a governed build")++ policy = verify_and_load(_POLICY_PATH.read_bytes())+ unenforced = sorted(set(policy.get("activeForms", ())).difference(_ENFORCED_FORMS))+ if unenforced:+ raise RuntimeError("policy requires forms this build cannot enforce: " + ", ".join(unenforced))+ _apply_policy(policy)+ # Manager's prestartup runs scheduled install scripts and pip installs before any pack is checked, so it cannot run under a pack policy.+ if _custom_node_mode is not None and args.enable_manager:+ logging.warning("ComfyUI-Manager is turned off: it cannot run under your organization's custom-node policy.")+ args.enable_manager = False+ except Exception:+ logging.exception("ComfyUI could not apply your organization's policy. Contact your administrator.")+ sys.exit(1)diff --git a/app/node_replace_manager.py b/app/node_replace_manager.pyindex 72e8ac2b1..8d87aa6d4 100644--- a/app/node_replace_manager.py+++ b/app/node_replace_manager.py@@ -22,7 +22,7 @@ def copy_node_struct(node_struct: NodeStruct, empty_inputs: bool = False) -> Nodnew_node_struct["inputs"] = {}else:new_node_struct["inputs"] = node_struct["inputs"].copy()- new_node_struct["_meta"] = node_struct["_meta"].copy()+ new_node_struct["_meta"] = node_struct.get("_meta", {}).copy()return new_node_structdiff --git a/comfy/cli_args.py b/comfy/cli_args.pyindex c4956e807..385084a52 100644--- a/comfy/cli_args.py+++ b/comfy/cli_args.py@@ -214,6 +214,7 @@ parser.add_argument("--windows-standalone-build", action="store_true", help="Winparser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")parser.add_argument("--disable-all-custom-nodes", action="store_true", help="Disable loading all custom nodes.")parser.add_argument("--whitelist-custom-nodes", type=str, nargs='+', default=[], help="Specify custom node folders to load even when --disable-all-custom-nodes is enabled.")+parser.add_argument("--disabled-nodes-config", type=str, default=None, metavar="PATH", help="Path to a YAML file listing node IDs to disable.")parser.add_argument("--disable-partner-nodes", action="store_true", help="Disable loading partner nodes (the paid API nodes). The frontend keeps its internet access.")parser.add_argument("--offline", action="store_true", help="Prevent the frontend from communicating with the internet by setting a restrictive Content-Security-Policy header. Also disables partner nodes.")parser.add_argument("--disable-api-nodes", action="store_true", help="Deprecated alias for --offline. Use --offline, or --disable-partner-nodes to only disable partner nodes.")diff --git a/main.py b/main.pyindex 4365fe120..fb5b512a1 100644--- a/main.py+++ b/main.py@@ -17,6 +17,7 @@ import importlib.metadataimport folder_pathsimport timefrom comfy.cli_args import enables_dynamic_vram+from app import governancefrom app.logger import setup_loggerconsole_log_level = get_console_log_level(args.verbose)file_log_outputs = get_file_log_outputs(args.verbose)@@ -130,16 +131,6 @@ def handle_comfyui_manager_unavailable():args.enable_manager = False-if args.enable_manager:- if importlib.util.find_spec("comfyui_manager"):- import comfyui_manager-- if not comfyui_manager.__file__ or not comfyui_manager.__file__.endswith('__init__.py'):- handle_comfyui_manager_unavailable()- else:- handle_comfyui_manager_unavailable()--def apply_custom_paths():# extra model pathsextra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")@@ -190,7 +181,7 @@ def execute_prestartup_script():def execute_script(script_path):module_name = os.path.splitext(script_path)[0]try:- spec = importlib.util.spec_from_file_location(module_name, script_path)+ spec = governance.pack_module_spec(module_name, script_path)module = importlib.util.module_from_spec(spec)spec.loader.exec_module(module)return True@@ -213,6 +204,11 @@ def execute_prestartup_script():if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":continue+ refusal = governance.pack_refusal(module_path)+ if refusal is not None:+ logging.warning(refusal)+ continue+script_path = os.path.join(module_path, "prestartup_script.py")if os.path.exists(script_path):if args.disable_all_custom_nodes and possible_module not in args.whitelist_custom_nodes:@@ -231,9 +227,19 @@ def execute_prestartup_script():logging.info("{:6.1f} seconds{}: {}".format(n[0], import_message, n[1]))logging.info("")+governance.initialize()apply_custom_paths()init_mime_types()+if args.enable_manager:+ if importlib.util.find_spec("comfyui_manager"):+ import comfyui_manager++ if not comfyui_manager.__file__ or not comfyui_manager.__file__.endswith('__init__.py'):+ handle_comfyui_manager_unavailable()+ else:+ handle_comfyui_manager_unavailable()+if args.enable_manager:comfyui_manager.prestartup()@@ -550,6 +556,8 @@ def start_comfyui(asyncio_loop=None):init_custom_nodes=(not args.disable_all_custom_nodes) or len(args.whitelist_custom_nodes) > 0,init_api_nodes=not args.disable_partner_nodes))+ disabled_nodes = governance.load_disabled_nodes(args.disabled_nodes_config) if args.disabled_nodes_config else set()+ governance.apply_disabled_nodes(disabled_nodes)# Re-apply Comfy's cuDNN benchmark policy after custom-node imports. Benchmark# mode can request near-card-sized autotune workspaces, and some custom nodes set it at import time.diff --git a/nodes.py b/nodes.pyindex 49de5a35b..555aae50a 100644--- a/nodes.py+++ b/nodes.py@@ -39,6 +39,7 @@ from comfy.cli_args import argsimport importlib+from app import governanceimport folder_pathsimport latent_previewimport node_helpers@@ -2262,11 +2263,12 @@ async def load_custom_node(module_path: str, ignore=set(), module_parent="customtry:logging.debug("Trying to load custom node {}".format(module_path))+ spec_from_file_location = governance.pack_module_spec if module_parent == "custom_nodes" else importlib.util.spec_from_file_locationif os.path.isfile(module_path):- module_spec = importlib.util.spec_from_file_location(sys_module_name, module_path)+ module_spec = spec_from_file_location(sys_module_name, module_path)module_dir = os.path.split(module_path)[0]else:- module_spec = importlib.util.spec_from_file_location(sys_module_name, os.path.join(module_path, "__init__.py"))+ module_spec = spec_from_file_location(sys_module_name, os.path.join(module_path, "__init__.py"))module_dir = module_pathmodule = importlib.util.module_from_spec(module_spec)@@ -2385,6 +2387,11 @@ async def init_external_custom_nodes():logging.info(f"Blocked by policy: {module_path}")continue+ refusal = governance.pack_refusal(module_path)+ if refusal is not None:+ logging.warning(refusal)+ continue+time_before = time.perf_counter()success = await load_custom_node(module_path, base_node_names, module_parent="custom_nodes")node_import_times.append((time.perf_counter() - time_before, module_path, success))diff --git a/requirements.txt b/requirements.txtindex 755a335f4..8f2e93b37 100644--- a/requirements.txt+++ b/requirements.txt@@ -26,6 +26,7 @@ comfy-aimdo==0.5.5requestssimpleeval>=1.0.0blake3+cryptography#non essential dependencies:kornia>=0.7.1diff --git a/tests-unit/governance_test/test_apply_disabled_nodes.py b/tests-unit/governance_test/test_apply_disabled_nodes.pynew file mode 100644index 000000000..80e2fdb74--- /dev/null+++ b/tests-unit/governance_test/test_apply_disabled_nodes.py@@ -0,0 +1,247 @@+import copy+import logging+from pathlib import Path++import pytest+import torch++from app import governance+from comfy.cli_args import args+++if not torch.cuda.is_available():+ args.cpu = True++import execution+import nodes+from app.node_replace_manager import NodeReplaceManager+from comfy_api.latest import io+++class TestNode:+ pass++[email protected](autouse=True)+def isolated_governance_state(monkeypatch: pytest.MonkeyPatch):+ class_mappings = dict(nodes.NODE_CLASS_MAPPINGS)+ display_name_mappings = dict(nodes.NODE_DISPLAY_NAME_MAPPINGS)+ load_custom_node = nodes.load_custom_node+ monkeypatch.setattr(governance, "_disabled_nodes", frozenset(), raising=False)+ monkeypatch.setattr(governance, "_original_load_custom_node", None, raising=False)++ try:+ yield+ finally:+ nodes.NODE_CLASS_MAPPINGS.clear()+ nodes.NODE_CLASS_MAPPINGS.update(class_mappings)+ nodes.NODE_DISPLAY_NAME_MAPPINGS.clear()+ nodes.NODE_DISPLAY_NAME_MAPPINGS.update(display_name_mappings)+ nodes.load_custom_node = load_custom_node+++def _prompt(class_type: str, with_meta: bool) -> dict:+ node = {"class_type": class_type, "inputs": {}}+ if with_meta:+ node["_meta"] = {"title": class_type}+ return {"1": node}+++def _replacement(old_node_id: str = "LegacyNode", new_node_id: str = "CurrentNode") -> io.NodeReplace:+ return io.NodeReplace(new_node_id=new_node_id, old_node_id=old_node_id)+++def test_apply_disabled_nodes_removes_class_and_display_name(caplog: pytest.LogCaptureFixture) -> None:+ # Given+ nodes.NODE_CLASS_MAPPINGS["DisabledNode"] = TestNode+ nodes.NODE_DISPLAY_NAME_MAPPINGS["DisabledNode"] = "Disabled Node"++ # When+ with caplog.at_level(logging.INFO):+ governance.apply_disabled_nodes({"DisabledNode"})++ # Then+ assert "DisabledNode" not in nodes.NODE_CLASS_MAPPINGS+ assert "DisabledNode" not in nodes.NODE_DISPLAY_NAME_MAPPINGS+ assert "Pruned 1 disabled node" in caplog.text+++def test_apply_disabled_nodes_prunes_policy_nodes_without_config(monkeypatch: pytest.MonkeyPatch) -> None:+ # Given a signed policy disabled a node and no disabled-node config is given+ nodes.NODE_CLASS_MAPPINGS["PolicyNode"] = TestNode+ nodes.NODE_DISPLAY_NAME_MAPPINGS["PolicyNode"] = "Policy Node"+ monkeypatch.setattr(governance, "_disabled_nodes", frozenset({"PolicyNode"}), raising=False)++ # When+ governance.apply_disabled_nodes(set())++ # Then the policy's node is pruned+ assert "PolicyNode" not in nodes.NODE_CLASS_MAPPINGS+ assert "PolicyNode" not in nodes.NODE_DISPLAY_NAME_MAPPINGS+++def test_apply_disabled_nodes_warns_once_for_all_missing_ids(caplog: pytest.LogCaptureFixture) -> None:+ # Given+ missing = {"MissingNodeA", "MissingNodeB"}++ # When+ with caplog.at_level(logging.WARNING):+ governance.apply_disabled_nodes(missing)++ # Then+ warnings = [record for record in caplog.records if record.levelno == logging.WARNING]+ assert len(warnings) == 1+ assert all(node_id in warnings[0].getMessage() for node_id in missing)++[email protected]("with_meta", [False, True])+def test_disabled_old_id_forwards_to_allowed_target(with_meta: bool) -> None:+ # Given+ nodes.NODE_CLASS_MAPPINGS.update({"LegacyNode": TestNode, "CurrentNode": TestNode})+ manager = NodeReplaceManager()+ manager.register(_replacement())+ prompt = _prompt("LegacyNode", with_meta)++ # When+ governance.apply_disabled_nodes({"LegacyNode"})+ manager.apply_replacements(prompt)++ # Then+ assert manager.has_replacement("LegacyNode") is True+ assert prompt["1"]["class_type"] == "CurrentNode"++[email protected]("with_meta", [False, True])+async def test_disabled_target_is_not_applied_and_prompt_is_refused(with_meta: bool) -> None:+ # Given+ nodes.NODE_CLASS_MAPPINGS["CurrentNode"] = TestNode+ manager = NodeReplaceManager()+ manager.register(_replacement())+ prompt = _prompt("LegacyNode", with_meta)++ # When+ governance.apply_disabled_nodes({"CurrentNode"})+ manager.apply_replacements(prompt)+ valid = await execution.validate_prompt("prompt-id", prompt, None)++ # Then+ assert prompt["1"]["class_type"] == "LegacyNode"+ assert valid[0] is False+ assert valid[1]["type"] == "missing_node_type"+ assert valid[1]["extra_info"]["class_type"] == "LegacyNode"+++async def test_disabling_both_replacement_ends_refuses_prompt() -> None:+ # Given+ nodes.NODE_CLASS_MAPPINGS.update({"LegacyNode": TestNode, "CurrentNode": TestNode})+ manager = NodeReplaceManager()+ manager.register(_replacement())+ prompt = _prompt("LegacyNode", False)++ # When+ governance.apply_disabled_nodes({"LegacyNode", "CurrentNode"})+ manager.apply_replacements(prompt)+ valid = await execution.validate_prompt("prompt-id", prompt, None)++ # Then+ assert prompt["1"]["class_type"] == "LegacyNode"+ assert valid[0] is False+ assert valid[1]["type"] == "missing_node_type"++[email protected]("with_meta", [False, True])+def test_replacement_behavior_is_unchanged_when_neither_end_is_disabled(with_meta: bool) -> None:+ # Given+ nodes.NODE_CLASS_MAPPINGS.update({"LegacyNode": TestNode, "CurrentNode": TestNode})+ manager = NodeReplaceManager()+ manager.register(_replacement())+ prompt = _prompt("LegacyNode", with_meta)+ original_prompt = copy.deepcopy(prompt)++ # When+ governance.apply_disabled_nodes(set())+ manager.apply_replacements(prompt)++ # Then+ assert prompt == original_prompt+++async def test_post_prune_v1_load_cannot_register_disabled_id(tmp_path: Path) -> None:+ # Given+ module_path = tmp_path / "sealed_v1_node.py"+ module_path.write_text(+ "class SealedV1Node:\n"+ " pass\n\n"+ "NODE_CLASS_MAPPINGS = {'DisabledV1': SealedV1Node}\n"+ "NODE_DISPLAY_NAME_MAPPINGS = {'DisabledV1': 'Disabled V1'}\n",+ encoding="utf-8",+ )+ governance.apply_disabled_nodes({"DisabledV1"})++ # When+ loaded = await nodes.load_custom_node(str(module_path), ignore={"OtherNode"})++ # Then+ assert loaded is True+ assert "DisabledV1" not in nodes.NODE_CLASS_MAPPINGS+ assert "DisabledV1" not in nodes.NODE_DISPLAY_NAME_MAPPINGS+++async def test_post_prune_v3_load_cannot_register_disabled_schema_id(tmp_path: Path) -> None:+ # Given+ module_path = tmp_path / "sealed_v3_node.py"+ module_path.write_text(+ "from comfy_api.latest import ComfyExtension\n\n"+ "class SealedV3Node:\n"+ " @classmethod\n"+ " def GET_SCHEMA(cls):\n"+ " class Schema:\n"+ " node_id = 'DisabledV3'\n"+ " display_name = 'Disabled V3'\n\n"+ " return Schema()\n\n\n"+ "class SealedExtension(ComfyExtension):\n"+ " async def get_node_list(self):\n"+ " return [SealedV3Node]\n\n\n"+ "async def comfy_entrypoint():\n"+ " return SealedExtension()\n",+ encoding="utf-8",+ )+ governance.apply_disabled_nodes({"DisabledV3"})++ # When+ loaded = await nodes.load_custom_node(str(module_path))++ # Then+ assert loaded is True+ assert "DisabledV3" not in nodes.NODE_CLASS_MAPPINGS+ assert "DisabledV3" not in nodes.NODE_DISPLAY_NAME_MAPPINGS+++async def test_seal_keeps_replacement_target_absent_after_v1_load(tmp_path: Path) -> None:+ # Given+ module_path = tmp_path / "sealed_target.py"+ module_path.write_text(+ "class SealedTargetNode:\n"+ " pass\n\n"+ "NODE_CLASS_MAPPINGS = {'DisabledTarget': SealedTargetNode}\n",+ encoding="utf-8",+ )+ nodes.NODE_CLASS_MAPPINGS["DisabledTarget"] = TestNode+ manager = NodeReplaceManager()+ manager.register(_replacement(new_node_id="DisabledTarget"))+ governance.apply_disabled_nodes({"DisabledTarget"})+ loaded = await nodes.load_custom_node(str(module_path))+ prompt = _prompt("LegacyNode", False)++ # When+ manager.apply_replacements(prompt)++ # Then+ assert loaded is True+ assert "DisabledTarget" not in nodes.NODE_CLASS_MAPPINGS+ assert prompt["1"]["class_type"] == "LegacyNode"diff --git a/tests-unit/governance_test/test_initialize.py b/tests-unit/governance_test/test_initialize.pynew file mode 100644index 000000000..9748c3fe1--- /dev/null+++ b/tests-unit/governance_test/test_initialize.py@@ -0,0 +1,349 @@+import builtins+import os+from pathlib import Path+import subprocess+import sys+from types import MappingProxyType++import pytest++from app import governance+from comfy.cli_args import args+++COMFYUI_ROOT = Path(__file__).parents[2]+MAIN_PATH = COMFYUI_ROOT / "main.py"+POLICY_MESSAGE = "organization's policy"+++def governed(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:+ policy_path = tmp_path / "policy.signed.json"+ monkeypatch.setattr(governance, "GOVERNANCE_REQUIRED", True, raising=False)+ monkeypatch.setattr(governance, "_POLICY_PATH", policy_path, raising=False)+ monkeypatch.setattr(governance, "_policy", None, raising=False)+ monkeypatch.setattr(governance, "_disabled_nodes", frozenset(), raising=False)+ monkeypatch.setattr(args, "disabled_nodes_config", None)+ monkeypatch.setattr(args, "extra_model_paths_config", None)+ monkeypatch.setattr(args, "enable_manager", False)+ # A custom-node policy switches off bytecode writes for the process; undo that and the pack policy after each test.+ monkeypatch.setattr(sys, "dont_write_bytecode", sys.dont_write_bytecode)+ monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", os.environ.get("PYTHONDONTWRITEBYTECODE", ""))+ monkeypatch.setattr(governance, "_custom_node_mode", None, raising=False)+ monkeypatch.setattr(governance, "_denied_packs", frozenset(), raising=False)+ monkeypatch.setattr(governance, "_allowed_packs", MappingProxyType({}), raising=False)+ return policy_path+++def _assert_policy_exit(exc_info: pytest.ExceptionInfo[SystemExit], log_text: str) -> None:+ assert exc_info.value.code != 0+ assert POLICY_MESSAGE in log_text+++def _run_governed(+ main_path: Path,+ *arguments: str,+ policy_path: Path | None = None,+ import_path: Path | None = None,+) -> subprocess.CompletedProcess[str]:+ setup = [+ "from pathlib import Path",+ "import logging",+ "import runpy",+ "import sys",+ "import types",+ "from app import governance",+ "governance.GOVERNANCE_REQUIRED = True",+ "def stub(name, **values):\n module = types.ModuleType(name)\n module.__dict__.update(values)\n sys.modules[name] = module\n return module",+ "noop = lambda *args, **kwargs: None",+ "folder_paths = stub('folder_paths', __file__='folder_paths.py', base_path='', models_dir='', get_output_directory=lambda: '', add_model_folder_path=noop, set_output_directory=noop, set_input_directory=noop, set_user_directory=noop, get_folder_paths=lambda name: [])",+ "stub('app.logger', setup_logger=noop)",+ "stub('app.assets.lifecycle', cleanup_temp_filesystem=noop)",+ "stub('app.assets.manager', AssetManager=object, default_asset_manager=noop)",+ "import utils",+ "utils.extra_config = stub('utils.extra_config', load_extra_path_config=lambda path: logging.warning('Adding extra search path checkpoints %s', path))",+ "stub('utils.mime_types', init_mime_types=noop)",+ "stub('comfy_execution.progress', get_progress_state=noop)",+ "stub('comfy_execution.utils', get_executing_context=noop)",+ "stub('comfy_api', feature_flags=types.SimpleNamespace())",+ "stub('app.database.db', init_db=noop, dependencies_available=lambda: False, lock_holder_db_path=lambda: None)",+ "control = stub('comfy_aimdo.control', init=noop)",+ "stub('comfy_aimdo', control=control)",+ "stub('cuda_malloc', get_torch_version_noimport=lambda: '')",+ ]+ if policy_path is not None:+ setup.extend(+ (+ f"governance._POLICY_PATH = Path({str(policy_path)!r})",+ "governance.verify_and_load = lambda envelope_bytes: {}",+ )+ )+ if import_path is not None:+ setup.append(f"sys.path.insert(0, {str(import_path)!r})")+ setup.append(f"runpy.run_path({str(main_path)!r}, run_name='__main__')")++ return subprocess.run(+ [sys.executable, "-c", "\n".join(setup), *arguments],+ cwd=COMFYUI_ROOT,+ capture_output=True,+ text=True,+ timeout=120,+ check=False,+ )+++def test_build_constants_have_upstream_safe_defaults() -> None:+ assert governance.GOVERNANCE_REQUIRED is False+ assert governance.GOVERNANCE_BUILD_IDENTITY == ""+ assert governance.GOVERNANCE_PUBLIC_KEY == ""+ assert governance.GOVERNANCE_MIN_POLICY_GENERATION == 0+ assert governance.GOVERNANCE_CAPABILITY_VERSION == 1+++def test_governance_import_does_not_require_policy_dependencies() -> None:+ result = subprocess.run(+ [+ sys.executable,+ "-c",+ """+import builtins++original_import = builtins.__import__++def import_without_policy_dependencies(name, *args, **kwargs):+ if name.split('.', 1)[0] in {'blake3', 'cryptography'}:+ raise ModuleNotFoundError(name)+ return original_import(name, *args, **kwargs)++builtins.__import__ = import_without_policy_dependencies+from app import governance+assert governance.GOVERNANCE_REQUIRED is False+""",+ ],+ cwd=COMFYUI_ROOT,+ capture_output=True,+ text=True,+ timeout=120,+ check=False,+ )++ assert result.returncode == 0, result.stdout + result.stderr+++def test_initialize_is_noop_without_filesystem_access(monkeypatch: pytest.MonkeyPatch) -> None:+ def unexpected_filesystem_access(*_args, **_kwargs):+ pytest.fail("initialize accessed the filesystem")++ monkeypatch.setattr(governance, "GOVERNANCE_REQUIRED", False, raising=False)+ monkeypatch.setattr(builtins, "open", unexpected_filesystem_access)+ monkeypatch.setattr(os.path, "isfile", unexpected_filesystem_access)+ monkeypatch.setattr(Path, "is_file", unexpected_filesystem_access)+ monkeypatch.setattr(Path, "read_bytes", unexpected_filesystem_access)++ governance.initialize()+++def test_initialize_exits_when_manifest_is_missing(governed: Path, caplog: pytest.LogCaptureFixture) -> None:+ with pytest.raises(SystemExit) as exc_info:+ governance.initialize()++ _assert_policy_exit(exc_info, caplog.text)+++def test_initialize_exits_on_internal_exception(+ governed: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ governed.write_bytes(b"signed policy")++ def fail_verification(_envelope_bytes: bytes):+ raise RuntimeError("injected failure")++ monkeypatch.setattr(governance, "verify_and_load", fail_verification, raising=False)++ with pytest.raises(SystemExit) as exc_info:+ governance.initialize()++ _assert_policy_exit(exc_info, caplog.text)+++def test_initialize_rejects_disabled_nodes_config(+ governed: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ # Given a valid policy, so the unsigned config is the only reason to stop+ _use_policy(governed, monkeypatch, {})+ monkeypatch.setattr(args, "disabled_nodes_config", str(governed.parent / "disabled.yaml"))++ with pytest.raises(SystemExit) as exc_info:+ governance.initialize()++ _assert_policy_exit(exc_info, caplog.text)+ assert "unsigned disabled-node config is not allowed" in caplog.text+++def test_initialize_does_not_gate_on_capability_version(+ governed: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ governed.write_bytes(b"signed policy")+ monkeypatch.setattr(governance, "GOVERNANCE_CAPABILITY_VERSION", -1, raising=False)+ monkeypatch.setattr(governance, "verify_and_load", lambda envelope_bytes: {}, raising=False)++ governance.initialize()++[email protected]("active_forms", [["model"], ["customNode", "model"], ["unknownForm"]])+def test_initialize_exits_on_form_this_build_cannot_enforce(+ governed: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ active_forms: list[str],+) -> None:+ governed.write_bytes(b"signed policy")+ monkeypatch.setattr(governance, "verify_and_load", lambda envelope_bytes: {"activeForms": active_forms}, raising=False)++ with pytest.raises(SystemExit) as exc_info:+ governance.initialize()++ _assert_policy_exit(exc_info, caplog.text)+ assert governance._policy is None+++def test_initialize_applies_policy_limited_to_enforced_forms(+ governed: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ governed.write_bytes(b"signed policy")+ policy = {"activeForms": ["nodeId"], "disabledNodes": ["SomeNode"]}+ monkeypatch.setattr(governance, "verify_and_load", lambda envelope_bytes: policy, raising=False)++ governance.initialize()++ assert governance._disabled_nodes == frozenset({"SomeNode"})+++def _use_policy(governed: Path, monkeypatch: pytest.MonkeyPatch, policy: dict) -> None:+ governed.write_bytes(b"signed policy")+ monkeypatch.setattr(governance, "verify_and_load", lambda envelope_bytes: policy, raising=False)+++def test_initialize_prunes_partner_nodes_with_disabled_nodes(governed: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ # Given a policy disabling one node id and one partner node+ _use_policy(+ governed,+ monkeypatch,+ {+ "activeForms": ["nodeId", "partnerNode"],+ "disabledNodes": ["SomeNode"],+ "disabledPartnerNodes": [{"nodeId": "PartnerNode", "providerId": "acme"}],+ },+ )++ # When the policy is applied+ governance.initialize()++ # Then both ids are pruned+ assert governance._disabled_nodes == frozenset({"SomeNode", "PartnerNode"})+++def _custom_node_policy(mode: str) -> dict:+ return {"activeForms": ["customNode"], "customNodeMode": mode, "packs": [], "deniedPacks": []}++[email protected]("mode", ["allowlist", "blocklist"])+def test_initialize_turns_manager_off_under_custom_node_policy(+ governed: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ mode: str,+) -> None:+ # Given Manager is enabled, whose prestartup runs scheduled install scripts before any pack is checked+ _use_policy(governed, monkeypatch, _custom_node_policy(mode))+ monkeypatch.setattr(args, "enable_manager", True)++ # When the policy is applied+ governance.initialize()++ # Then startup continues with Manager off, and the log says why+ assert args.enable_manager is False+ assert "ComfyUI-Manager is turned off" in caplog.text++[email protected]("mode", ["allowlist", "blocklist"])+def test_initialize_applies_custom_node_policy_without_manager(governed: Path, monkeypatch: pytest.MonkeyPatch, mode: str) -> None:+ # Given a custom-node policy with Manager off+ _use_policy(governed, monkeypatch, _custom_node_policy(mode))++ # When the policy is applied+ governance.initialize()++ # Then the pack gate takes the policy's mode+ assert governance._custom_node_mode == mode+++def test_initialize_allows_manager_without_custom_node_policy(governed: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ # Given Manager is enabled and the policy governs node ids only+ _use_policy(governed, monkeypatch, {"activeForms": ["nodeId"], "disabledNodes": ["SomeNode"]})+ monkeypatch.setattr(args, "enable_manager", True)++ # When the policy is applied, then startup continues+ governance.initialize()++ assert governance._custom_node_mode is None+++def test_initialize_accepts_extra_model_paths_that_add_custom_nodes(governed: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ # Given a policy and an extra paths file that adds a custom_nodes folder; packs found there pass the same pack gate at load+ governed.write_bytes(b"signed policy")+ monkeypatch.setattr(governance, "verify_and_load", lambda envelope_bytes: {}, raising=False)+ extra_paths = governed.parent / "extra-paths.yaml"+ extra_paths.write_text("test:\n base_path: .\n checkpoints: models\n custom_nodes: nodes\n", encoding="utf-8")+ monkeypatch.setattr(args, "extra_model_paths_config", [[str(extra_paths)]])++ # When the policy is applied, then startup continues+ governance.initialize()+++def test_manager_import_waits_until_after_governance(tmp_path: Path) -> None:+ sentinel_path = tmp_path / "manager-imported"+ manager_package = tmp_path / "comfyui_manager"+ manager_package.mkdir()+ (manager_package / "__init__.py").write_text(+ f"from pathlib import Path\nPath({str(sentinel_path)!r}).write_text('imported', encoding='utf-8')\n",+ encoding="utf-8",+ )++ result = _run_governed(+ MAIN_PATH,+ "--enable-manager",+ "--quick-test-for-ci",+ import_path=tmp_path,+ )++ assert result.returncode != 0+ assert POLICY_MESSAGE in result.stdout + result.stderr+ assert not sentinel_path.exists()+++def test_governance_failure_precedes_prestartup_scripts(tmp_path: Path) -> None:+ sentinel_path = tmp_path / "prestartup-ran"+ pack_path = tmp_path / "custom_nodes" / "sentinel_pack"+ pack_path.mkdir(parents=True)+ (pack_path / "prestartup_script.py").write_text(+ f"from pathlib import Path\nPath({str(sentinel_path)!r}).write_text('ran', encoding='utf-8')\n",+ encoding="utf-8",+ )++ result = _run_governed(+ MAIN_PATH,+ "--base-directory",+ str(tmp_path),+ "--quick-test-for-ci",+ )++ assert result.returncode != 0+ assert POLICY_MESSAGE in result.stdout + result.stderr+ assert not sentinel_path.exists()diff --git a/tests-unit/governance_test/test_load_disabled_nodes.py b/tests-unit/governance_test/test_load_disabled_nodes.pynew file mode 100644index 000000000..d3aba9380--- /dev/null+++ b/tests-unit/governance_test/test_load_disabled_nodes.py@@ -0,0 +1,47 @@+from pathlib import Path++import pytest+import yaml++from app.governance import load_disabled_nodes+++VALID_CONFIGS = [+ ("disabled_nodes:\n - A\n - B\n", {"A", "B"}),+ ("disabled_nodes: []\n", set()),+ ("disabled_nodes:\n - A\n - A\n", {"A"}),+]++INVALID_CONFIGS = [+ ("disabled_nodes: [\n", yaml.YAMLError),+ ("- A\n", ValueError),+ ("other: []\n", ValueError),+ ('disabled_nodes: "A"\n', ValueError),+ ("disabled_nodes: [1]\n", ValueError),+]++[email protected]("config,expected", VALID_CONFIGS)+def test_load_disabled_nodes_returns_expected_set(tmp_path: Path, config: str, expected: set[str]) -> None:+ config_path = tmp_path / "disabled_nodes.yaml"+ config_path.write_text(config, encoding="utf-8")++ assert load_disabled_nodes(str(config_path)) == expected+++def test_load_disabled_nodes_raises_for_missing_file(tmp_path: Path) -> None:+ with pytest.raises(FileNotFoundError):+ load_disabled_nodes(str(tmp_path / "missing.yaml"))++[email protected]("config,expected_error", INVALID_CONFIGS)+def test_load_disabled_nodes_rejects_invalid_config(+ tmp_path: Path,+ config: str,+ expected_error: type[Exception],+) -> None:+ config_path = tmp_path / "disabled_nodes.yaml"+ config_path.write_text(config, encoding="utf-8")++ with pytest.raises(expected_error):+ load_disabled_nodes(str(config_path))diff --git a/tests-unit/governance_test/test_pack_digest.py b/tests-unit/governance_test/test_pack_digest.pynew file mode 100644index 000000000..788582ef7--- /dev/null+++ b/tests-unit/governance_test/test_pack_digest.py@@ -0,0 +1,242 @@+from pathlib import Path+import sys++import pytest++from app import governance+++GOLDEN_DIGEST = "blake3:ee9d4961b928fa3c0983f95fe2123d44d7cbd44158859d77ff31f7269b68cdba"+SINGLE_FILE_DIGEST = "blake3:5a98145e4f501a639d74720737b5bf4ad075a2ba8befb831d231e32cca56499d"+GOLDEN_FILES = {+ "__init__.py": b"ROOT = 1\n",+ "native/WINDOWS.PYD": b"\x00pyd\xff\n",+ "nested/cafe\u0301.py": b"UNICODE = 'cafe'\n",+ "nested/foo.cpython-311-x86_64-linux-gnu.so": b"\x7fELFfixture-so\n",+ "nested/module.py": b"VALUE = 'nested'\n",+ "README.txt": b"ignored text\n",+ "models/model.safetensors": b"ignored weights\n",+}+++def golden_pack(tmp_path: Path) -> Path:+ pack_path = tmp_path / "pack"+ for relative_path, contents in GOLDEN_FILES.items():+ file_path = pack_path / relative_path+ file_path.parent.mkdir(parents=True, exist_ok=True)+ file_path.write_bytes(contents)+ return pack_path+++def test_pack_digest_matches_cross_language_golden_fixture(golden_pack: Path) -> None:+ # Given the committed tree from golden_pack+ # When its pack digest is computed+ digest = governance.pack_digest(str(golden_pack))++ # Then the byte-exact cross-language vector matches+ assert digest == GOLDEN_DIGEST+++def test_pack_digest_for_single_file_uses_basename_record(golden_pack: Path) -> None:+ # Given a top-level Python file+ single_file = golden_pack / "__init__.py"++ # When it is measured as a pack+ digest = governance.pack_digest(str(single_file))++ # Then exactly one basename record is encoded+ assert digest == SINGLE_FILE_DIGEST+++def test_pack_digest_changes_when_included_file_changes(golden_pack: Path) -> None:+ # Given a golden pack whose nested Python file changes+ module_path = golden_pack / "nested" / "module.py"+ module_path.write_bytes(module_path.read_bytes() + b"# changed\n")++ # When its digest is recomputed+ digest = governance.pack_digest(str(golden_pack))++ # Then the included byte changes the pack identity+ assert digest != GOLDEN_DIGEST+++def test_pack_digest_ignores_changes_to_excluded_file(golden_pack: Path) -> None:+ # Given a golden pack whose text file changes+ text_path = golden_pack / "README.txt"+ text_path.write_bytes(text_path.read_bytes() + b"changed\n")++ # When its digest is recomputed+ digest = governance.pack_digest(str(golden_pack))++ # Then the excluded byte does not change the pack identity+ assert digest == GOLDEN_DIGEST++[email protected]("relative_path", ["__pycache__/root.cpython-311.pyc", "nested/module.pyc", "legacy.pyo"])+def test_pack_digest_rejects_compiled_bytecode(golden_pack: Path, relative_path: str) -> None:+ # Given a pack carrying bytecode that can execute without its source+ bytecode_path = golden_pack / relative_path+ bytecode_path.parent.mkdir(parents=True, exist_ok=True)+ bytecode_path.write_bytes(b"compiled\n")++ # When the pack is measured, then the unmeasurable artifact rejects the whole pack+ with pytest.raises(ValueError):+ governance.pack_digest(str(golden_pack))+++def test_pack_digest_rejects_normalized_relative_path_collision(tmp_path: Path) -> None:+ # Given distinct filesystem entries that normalize to the same NFC path+ pack_path = tmp_path / "pack"+ pack_path.mkdir()+ (pack_path / "cafe\u0301.py").write_bytes(b"decomposed\n")+ (pack_path / "caf\u00e9.py").write_bytes(b"composed\n")+ if len(list(pack_path.iterdir())) < 2:+ pytest.skip("filesystem normalizes Unicode filenames")++ # When the pack is measured, then the ambiguous record name is rejected+ with pytest.raises(ValueError):+ governance.pack_digest(str(pack_path))+++def test_pack_digest_rejects_symlinked_python_file(tmp_path: Path) -> None:+ # Given a pack containing a symlinked Python file+ pack_path = tmp_path / "pack"+ pack_path.mkdir()+ target = tmp_path / "outside.py"+ target.write_bytes(b"outside\n")+ (pack_path / "linked.py").symlink_to(target)++ # When the pack is measured, then the symlink rejects the whole pack+ with pytest.raises(ValueError):+ governance.pack_digest(str(pack_path))+++def test_pack_digest_rejects_symlinked_directory(tmp_path: Path) -> None:+ # Given a pack containing a symlinked directory+ pack_path = tmp_path / "pack"+ pack_path.mkdir()+ target = tmp_path / "outside"+ target.mkdir()+ (pack_path / "linked").symlink_to(target, target_is_directory=True)++ # When the pack is measured, then the symlink rejects the whole pack+ with pytest.raises(ValueError):+ governance.pack_digest(str(pack_path))+++def test_pack_digest_rejects_symlinked_pack_root(tmp_path: Path) -> None:+ # Given a pack root that is itself a symlink+ target = tmp_path / "real-pack"+ target.mkdir()+ pack_path = tmp_path / "linked-pack"+ pack_path.symlink_to(target, target_is_directory=True)++ # When the pack is measured, then the root symlink is rejected+ with pytest.raises(ValueError):+ governance.pack_digest(str(pack_path))+++# Windows drops a trailing dot from a file name, so "lib/libbar.so." is written as "lib/libbar.so", a measured library.+TRAILING_DOT_NAMES_KEPT = pytest.mark.skipif(sys.platform == "win32", reason="Windows strips a trailing dot from file names")+++# Shared with Comfy-Org/cloud services/comfy-builder/packdigest/digest_test.go (sharedFixtureFiles), which asserts the same digest.+SHARED_FIXTURE_DIGEST = "blake3:60627b4c95dad13ffe3dd68e165ac182c605ab1f873a88d11c3b9c0b65d531e1"+SHARED_FIXTURE_FILES = {+ "__init__.py": b"ROOT = 1\n",+ "utils/__init__.pyw": b"WINDOWS_SOURCE = 1\n",+ "web/x.js": b"export const X = 1;\n",+ "web/x.mjs": b"export const Y = 2;\n",+ "lib/libfoo.so.1": b"\x7fELFversioned-so\n",+ "README.md": b"# ignored readme\n",+ "data/config.json": b'{"ignored": true}\n',+}+++# The shared fixture plus names where suffix rules could split: Python's pathlib gives a dotfile ("web/.js") no suffix where+# Go's filepath.Ext would give ".js". Only UPPER.PY and Libs/LibCase.SO.2 are measured. Libs/ is not lib/ so the fixture+# also holds on a case-insensitive filesystem. cloud's digest_test.go (edgeNameFixtureFiles) asserts the same digest.+EDGE_NAME_FIXTURE_DIGEST = "blake3:1f34f2d453c9ad9d2aa5302fc0b3332bc60b88077bfd1841e48d6102aa23968a"+EDGE_NAME_FIXTURE_FILES = {+ **SHARED_FIXTURE_FILES,+ "web/.js": b"DOTFILE_JS = 1\n",+ "pkg/.py": b"DOTFILE_PY = 1\n",+ "lib/.so.1": b"\x7fELFdotfile-so\n",+ "lib/libbar.so.": b"\x7fELFtrailing-dot\n",+ "lib/libt.so.1a": b"\x7fELFnot-a-version\n",+ "web/v.js.map": b'{"version": 3}\n',+ "UPPER.PY": b"UPPER = 1\n",+ "Libs/LibCase.SO.2": b"\x7fELFupper-so\n",+}+++def _write_pack(pack_path: Path, files: dict[str, bytes]) -> Path:+ for relative_path, contents in files.items():+ file_path = pack_path / relative_path+ file_path.parent.mkdir(parents=True, exist_ok=True)+ file_path.write_bytes(contents)+ return pack_path+++def test_pack_digest_matches_shared_fixture_with_windows_source_web_and_versioned_library(tmp_path: Path) -> None:+ # Given the fixture cloud's packdigest also measures+ pack_path = _write_pack(tmp_path / "pack", SHARED_FIXTURE_FILES)++ # When its pack digest is computed+ digest = governance.pack_digest(str(pack_path))++ # Then it is the digest both implementations assert+ assert digest == SHARED_FIXTURE_DIGEST+++@TRAILING_DOT_NAMES_KEPT+def test_pack_digest_matches_shared_fixture_with_edge_names(tmp_path: Path) -> None:+ # Given the shared fixture plus dotfiles, trailing dots, non-numeric versions and upper-case suffixes+ pack_path = _write_pack(tmp_path / "pack", EDGE_NAME_FIXTURE_FILES)++ # When its pack digest is computed+ digest = governance.pack_digest(str(pack_path))++ # Then it is the digest both implementations assert+ assert digest == EDGE_NAME_FIXTURE_DIGEST+++ "relative_path",+ [+ "extra.pyw",+ "web/extra.js",+ "web/extra.mjs",+ "native/EXTRA.JS",+ "lib/libbar.so.1",+ "lib/libbar.so.1.2",+ "lib/LIBBAR.SO.3",+ "native/extra.dll",+ "native/extra.dylib",+ ],+)+def test_pack_digest_measures_source_native_and_web_script_files(golden_pack: Path, relative_path: str) -> None:+ # Given a golden pack gaining Python source, a web script, or a native library+ _write_pack(golden_pack, {relative_path: b"RUNS = 1\n"})++ # When its digest is recomputed+ digest = governance.pack_digest(str(golden_pack))++ # Then the new file changes the pack identity+ assert digest != GOLDEN_DIGEST+++ "relative_path",+ ["README.md", "data/extra.json", "lib/libbar.so.1a", pytest.param("lib/libbar.so.", marks=TRAILING_DOT_NAMES_KEPT), "lib/.so.1", "web/x.js.map"],+)+def test_pack_digest_ignores_files_that_do_not_run(golden_pack: Path, relative_path: str) -> None:+ # Given a golden pack gaining a data file, or a name that only resembles a versioned library+ _write_pack(golden_pack, {relative_path: b"DATA = 1\n"})++ # When its digest is recomputed+ digest = governance.pack_digest(str(golden_pack))++ # Then the pack identity is unchanged+ assert digest == GOLDEN_DIGESTdiff --git a/tests-unit/governance_test/test_pack_gate.py b/tests-unit/governance_test/test_pack_gate.pynew file mode 100644index 000000000..d225e363b--- /dev/null+++ b/tests-unit/governance_test/test_pack_gate.py@@ -0,0 +1,476 @@+from __future__ import annotations++import ast+from collections.abc import Callable+import importlib+import importlib.util+import logging+import os+from pathlib import Path+import py_compile+import subprocess+import sys+import time++import pytest+import torch++from app import governance+from comfy.cli_args import args+++if not torch.cuda.is_available():+ args.cpu = True++import folder_paths+import nodes+++COMFYUI_ROOT = Path(__file__).parents[2]+MAIN_PATH = COMFYUI_ROOT / "main.py"+GENERIC_REFUSAL = "Custom node pack '{name}' is not permitted by your organization's policy."+MANAGER_REFUSAL = (+ "Custom node pack '{name}' is not loaded: ComfyUI-Manager cannot run under a custom-node policy, "+ "because its startup script installs packs before they are checked."+)+BYTECODE_REFUSAL = (+ "Custom node pack '{name}' is not loaded: it carries compiled Python files the policy cannot check ({paths}). "+ "Delete them and restart ComfyUI."+)+++def _load_execute_prestartup_script() -> Callable[[], None]:+ module = ast.parse(MAIN_PATH.read_text(encoding="utf-8"), filename=str(MAIN_PATH))+ function = next(node for node in module.body if isinstance(node, ast.FunctionDef) and node.name == "execute_prestartup_script")+ compiled = compile(ast.Module(body=[function], type_ignores=[]), filename=str(MAIN_PATH), mode="exec")+ namespace = {+ "args": args,+ "folder_paths": folder_paths,+ "governance": governance,+ "importlib": importlib,+ "logging": logging,+ "os": os,+ "time": time,+ }+ exec(compiled, namespace) # noqa: S102 - trusted AST extracted from main.py itself+ return namespace["execute_prestartup_script"]+++def _make_directory_pack(root: Path, name: str = "TestPack") -> tuple[Path, Path, Path]:+ pack_path = root / name+ pack_path.mkdir(parents=True)+ prestartup_sentinel = root.parent / f"{name}-prestartup"+ import_sentinel = root.parent / f"{name}-import"+ (pack_path / "prestartup_script.py").write_text(+ f"from pathlib import Path\nPath({str(prestartup_sentinel)!r}).write_text('ran', encoding='utf-8')\n",+ encoding="utf-8",+ )+ (pack_path / "__init__.py").write_text(+ f"from pathlib import Path\nPath({str(import_sentinel)!r}).write_text('ran', encoding='utf-8')\nNODE_CLASS_MAPPINGS = {{}}\n",+ encoding="utf-8",+ )+ return pack_path, prestartup_sentinel, import_sentinel+++async def _run_both_gates(+ monkeypatch: pytest.MonkeyPatch,+ custom_nodes_path: Path,+ prestartup_sentinel: Path,+ import_sentinel: Path,+) -> tuple[bool, bool]:+ monkeypatch.setattr(folder_paths, "get_folder_paths", lambda name: [str(custom_nodes_path)] if name == "custom_nodes" else [])++ _load_execute_prestartup_script()()+ await nodes.init_external_custom_nodes()++ return prestartup_sentinel.exists(), import_sentinel.exists()++[email protected](autouse=True)+def isolated_pack_policy(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(args, "enable_manager", False)+ monkeypatch.setattr(args, "disable_all_custom_nodes", False)+ monkeypatch.setattr(args, "whitelist_custom_nodes", [])+ governance.set_custom_node_policy(None, frozenset(), {})+ yield+ governance.set_custom_node_policy(None, frozenset(), {})+++ ("mode", "has_entry", "tampered", "denied", "expected_to_run"),+ [+ pytest.param("allowlist", True, False, False, True, id="allowlist-match"),+ pytest.param("allowlist", True, True, False, False, id="allowlist-tamper"),+ pytest.param("allowlist", False, False, False, False, id="allowlist-no-entry"),+ pytest.param("blocklist", True, False, False, True, id="blocklist-match"),+ pytest.param("blocklist", True, True, False, False, id="blocklist-tamper"),+ pytest.param("blocklist", False, False, False, True, id="blocklist-unknown"),+ pytest.param("blocklist", False, False, True, False, id="blocklist-denied"),+ pytest.param("blocklist", True, False, True, False, id="blocklist-shipped-and-denied"),+ ],+)+async def test_posture_matrix_applies_at_both_gates_with_manager_disabled(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ mode: str,+ has_entry: bool,+ tampered: bool,+ denied: bool,+ expected_to_run: bool,+) -> None:+ # Given a pack policy while Manager is absent+ custom_nodes_path = tmp_path / "custom_nodes"+ pack_path, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path)+ digest = governance.pack_digest(str(pack_path))+ entry_name = "manifest-name" if mode == "allowlist" else pack_path.name+ allowed_packs = {entry_name: digest} if has_entry else {}+ denied_packs = frozenset({pack_path.name.lower()}) if denied else frozenset()+ governance.set_custom_node_policy(mode, denied_packs, allowed_packs)+ if tampered:+ with (pack_path / "__init__.py").open("a", encoding="utf-8") as stream:+ stream.write("# tampered\n")++ # When both code-execution gates enumerate the pack+ prestartup_ran, import_ran = await _run_both_gates(+ monkeypatch,+ custom_nodes_path,+ prestartup_sentinel,+ import_sentinel,+ )++ # Then Manager absence never bypasses either gate+ assert args.enable_manager is False+ assert (prestartup_ran, import_ran) == (expected_to_run, expected_to_run)+++async def test_loose_bytecode_beside_source_denies_the_pack(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given an approved pack shipping bytecode outside __pycache__+ custom_nodes_path = tmp_path / "custom_nodes"+ pack_path, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path)+ digest = governance.pack_digest(str(pack_path))+ (pack_path / "shadow.pyc").write_bytes(b"sourceless\n")+ governance.set_custom_node_policy("allowlist", frozenset(), {pack_path.name: digest})++ # When both gates enumerate the pack+ result = await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then neither entry point executes+ assert result == (False, False)+++def _plant_bytecode(source_path: Path, sentinel: Path) -> Path:+ # Compile other code into the cache file Python would read for source_path; an unchecked-hash .pyc runs without the source.+ impostor = source_path.parent.parent / f"impostor-{source_path.stem}.py"+ impostor.write_text(f"from pathlib import Path\nPath({str(sentinel)!r}).write_text('bytecode', encoding='utf-8')\nNODE_CLASS_MAPPINGS = {{}}\n", encoding="utf-8")+ cache_path = Path(importlib.util.cache_from_source(str(source_path)))+ cache_path.parent.mkdir(parents=True, exist_ok=True)+ py_compile.compile(str(impostor), cfile=str(cache_path), invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH, doraise=True)+ impostor.unlink()+ return cache_path+++async def test_allowed_single_file_pack_never_runs_bytecode_beside_it(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given an approved single-file pack, and bytecode for it in custom_nodes/__pycache__, outside what its digest measures+ monkeypatch.setattr(sys, "pycache_prefix", None)+ custom_nodes_path = tmp_path / "custom_nodes"+ custom_nodes_path.mkdir()+ sentinel = tmp_path / "single-file-import"+ module_path = custom_nodes_path / "goodpack.py"+ module_path.write_text(+ f"from pathlib import Path\nPath({str(sentinel)!r}).write_text('source', encoding='utf-8')\nNODE_CLASS_MAPPINGS = {{}}\n",+ encoding="utf-8",+ )+ governance.set_custom_node_policy("allowlist", frozenset(), {module_path.name: governance.pack_digest(str(module_path))})+ _plant_bytecode(module_path, sentinel)+ monkeypatch.setattr(folder_paths, "get_folder_paths", lambda name: [str(custom_nodes_path)] if name == "custom_nodes" else [])++ # When the import loop loads it+ await nodes.init_external_custom_nodes()++ # Then the measured source runs, not the bytecode+ assert sentinel.read_text(encoding="utf-8") == "source"+++async def test_allowed_pack_never_runs_bytecode_from_a_pycache_prefix(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given PYTHONPYCACHEPREFIX in effect, and bytecode in the prefix tree for an approved pack's prestartup script and submodule+ monkeypatch.setattr(sys, "pycache_prefix", str(tmp_path / "pycache-prefix"))+ custom_nodes_path = tmp_path / "custom_nodes"+ pack_path, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path)+ (pack_path / "__init__.py").write_text("from . import helper\nNODE_CLASS_MAPPINGS = {}\n", encoding="utf-8")+ (pack_path / "helper.py").write_text(f"from pathlib import Path\nPath({str(import_sentinel)!r}).write_text('source', encoding='utf-8')\n", encoding="utf-8")+ (pack_path / "prestartup_script.py").write_text(+ f"from pathlib import Path\nPath({str(prestartup_sentinel)!r}).write_text('source', encoding='utf-8')\n", encoding="utf-8"+ )+ _plant_bytecode(pack_path / "helper.py", import_sentinel)+ _plant_bytecode(pack_path / "prestartup_script.py", prestartup_sentinel)+ governance.set_custom_node_policy("allowlist", frozenset(), {pack_path.name: governance.pack_digest(str(pack_path))})++ # When both gates load it+ await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then both run the measured source, not the bytecode+ assert prestartup_sentinel.read_text(encoding="utf-8") == "source"+ assert import_sentinel.read_text(encoding="utf-8") == "source"+++def test_child_interpreter_never_runs_bytecode_from_a_pycache_prefix(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given PYTHONPYCACHEPREFIX in effect, and bytecode in the prefix tree for an approved pack's module+ prefix = tmp_path / "pycache-prefix"+ monkeypatch.setenv("PYTHONPYCACHEPREFIX", str(prefix))+ monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "")+ monkeypatch.setattr(sys, "pycache_prefix", str(prefix))+ pack_path = tmp_path / "pack"+ pack_path.mkdir()+ sentinel = tmp_path / "child-import"+ (pack_path / "helper.py").write_text(f"from pathlib import Path\nPath({str(sentinel)!r}).write_text('source', encoding='utf-8')\n", encoding="utf-8")+ (pack_path / "install.py").write_text("import helper\n", encoding="utf-8")+ _plant_bytecode(pack_path / "helper.py", sentinel)+ governance.set_custom_node_policy("allowlist", frozenset(), {pack_path.name: governance.pack_digest(str(pack_path))})++ # When the pack starts a child interpreter that imports the module+ subprocess.run([sys.executable, str(pack_path / "install.py")], check=True)++ # Then the child runs the measured source, not the bytecode+ assert sentinel.read_text(encoding="utf-8") == "source"+++async def test_pack_carrying_bytecode_logs_the_cause_not_the_policy(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ caplog: pytest.LogCaptureFixture,+) -> None:+ # Given an approved pack that an earlier ungoverned run left __pycache__ folders in+ custom_nodes_path = tmp_path / "custom_nodes"+ pack_path, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path)+ (pack_path / "sub").mkdir()+ (pack_path / "sub" / "__init__.py").write_text("", encoding="utf-8")+ governance.set_custom_node_policy("allowlist", frozenset(), {pack_path.name: governance.pack_digest(str(pack_path))})+ for folder in (pack_path / "__pycache__", pack_path / "sub" / "__pycache__"):+ folder.mkdir()+ (folder / "__init__.cpython-313.pyc").write_bytes(b"compiled\n")+ (folder / "other.cpython-313.pyc").write_bytes(b"compiled\n")++ # When both gates enumerate it+ with caplog.at_level(logging.WARNING):+ result = await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then neither entry point runs, and each gate names the folders to delete instead of blaming the policy+ assert result == (False, False)+ messages = [record.getMessage() for record in caplog.records]+ paths = f"{pack_path / '__pycache__'}, {pack_path / 'sub' / '__pycache__'}"+ assert messages.count(BYTECODE_REFUSAL.format(name=pack_path.name, paths=paths)) == 2+ assert GENERIC_REFUSAL.format(name=pack_path.name) not in messages+++def test_pack_gate_denies_pack_when_digest_cannot_be_read(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given a governed pack that cannot be measured+ pack_path = tmp_path / "pack"+ pack_path.mkdir()+ governance.set_custom_node_policy("allowlist", frozenset(), {pack_path.name: "blake3:" + "0" * 64})+ monkeypatch.setattr(governance, "pack_digest", lambda _path: (_ for _ in ()).throw(OSError("unreadable")))++ # When the pack gate measures it, then the pack is denied closed+ assert governance.pack_allowed(str(pack_path)) is False+++def test_pack_install_in_child_interpreter_keeps_pack_allowed(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given an allowed pack whose install.py imports a pack module+ monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "")+ pack_path = tmp_path / "pack"+ pack_path.mkdir()+ (pack_path / "helper.py").write_text("", encoding="utf-8")+ (pack_path / "install.py").write_text("import helper\n", encoding="utf-8")+ governance.set_custom_node_policy("allowlist", frozenset(), {pack_path.name: governance.pack_digest(str(pack_path))})++ # When the install runs in a child interpreter+ subprocess.run([sys.executable, str(pack_path / "install.py")], check=True)++ # Then it leaves no bytecode behind and the pack is still allowed+ assert governance.pack_allowed(str(pack_path)) is True+++async def test_blocklist_denied_basename_matching_is_case_insensitive(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given a mixed-case pack denied by its lowercase basename+ custom_nodes_path = tmp_path / "custom_nodes"+ _, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path, "MiXeDcAsE")+ governance.set_custom_node_policy("blocklist", frozenset({"mixedcase"}), {})++ # When both gates enumerate it+ result = await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then neither entry point executes+ assert result == (False, False)+++async def test_blocklist_renamed_denied_pack_documents_known_limitation(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given denied shipped bytes moved under an unknown basename+ custom_nodes_path = tmp_path / "custom_nodes"+ pack_path, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path, "renamed-pack")+ governance.set_custom_node_policy(+ "blocklist",+ frozenset({"blocked-pack"}),+ {"blocked-pack": governance.pack_digest(str(pack_path))},+ )++ # When both gates enumerate the renamed pack+ result = await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then blocklist posture treats it as an unknown permitted pack+ assert result == (True, True)+++async def test_absent_policy_preserves_stock_loading(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given policy data with custom-node governance unset+ custom_nodes_path = tmp_path / "custom_nodes"+ _, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path)+ governance.set_custom_node_policy(None, frozenset({"testpack"}), {"TestPack": "blake3:" + "0" * 64})++ # When both stock loading paths run+ result = await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then governance does not alter either path+ assert result == (True, True)+++async def test_existing_disable_all_flag_still_narrows_allowed_pack(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given a governance-allowed pack disabled by the existing CLI flag+ custom_nodes_path = tmp_path / "custom_nodes"+ pack_path, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path)+ governance.set_custom_node_policy("allowlist", frozenset(), {"manifest-name": governance.pack_digest(str(pack_path))})+ monkeypatch.setattr(args, "disable_all_custom_nodes", True)+ monkeypatch.setattr(args, "whitelist_custom_nodes", [])++ # When both loading paths run+ result = await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then governance cannot broaden the existing restriction+ assert result == (False, False)+++async def test_denied_single_file_module_is_never_imported(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given an unknown single-file pack under strict allowlist posture+ custom_nodes_path = tmp_path / "custom_nodes"+ custom_nodes_path.mkdir()+ sentinel = tmp_path / "single-file-import"+ module_path = custom_nodes_path / "unknown.py"+ module_path.write_text(+ f"from pathlib import Path\nPath({str(sentinel)!r}).write_text('ran', encoding='utf-8')\nNODE_CLASS_MAPPINGS = {{}}\n",+ encoding="utf-8",+ )+ governance.set_custom_node_policy("allowlist", frozenset(), {})+ monkeypatch.setattr(folder_paths, "get_folder_paths", lambda name: [str(custom_nodes_path)] if name == "custom_nodes" else [])++ # When the import loop enumerates it+ await nodes.init_external_custom_nodes()++ # Then the module body never executes+ assert not sentinel.exists()+++def test_real_main_rejects_unknown_pack_without_manager(tmp_path: Path) -> None:+ # Given a real startup with Manager absent and an unknown allowlist pack+ custom_nodes_path = tmp_path / "custom_nodes"+ _, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path, "unknown-pack")+ setup = (+ "import runpy, sys\n"+ "from app import governance\n"+ "governance.initialize = lambda: governance.set_custom_node_policy('allowlist', frozenset(), {})\n"+ f"sys.argv = [{str(MAIN_PATH)!r}, '--base-directory', {str(tmp_path)!r}, '--cpu', '--disable-api-nodes', '--quick-test-for-ci']\n"+ f"runpy.run_path({str(MAIN_PATH)!r}, run_name='__main__')\n"+ )++ # When main.py runs through custom-node initialization+ result = subprocess.run(+ [sys.executable, "-c", setup],+ cwd=COMFYUI_ROOT,+ capture_output=True,+ text=True,+ timeout=120,+ check=False,+ )++ # Then startup succeeds without executing either unknown-pack entry point+ assert result.returncode == 0, result.stdout + result.stderr+ assert not prestartup_sentinel.exists()+ assert not import_sentinel.exists()++[email protected]("name", ["ComfyUI-Manager", "comfyui-manager", "COMFYUI-MANAGER"])[email protected]("mode", ["allowlist", "blocklist"])+async def test_legacy_manager_pack_is_refused_under_any_custom_node_policy(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ caplog: pytest.LogCaptureFixture,+ mode: str,+ name: str,+) -> None:+ # Given a legacy Manager pack the policy would otherwise admit: listed by digest, and not denied+ custom_nodes_path = tmp_path / "custom_nodes"+ pack_path, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path, name)+ governance.set_custom_node_policy(mode, frozenset(), {name: governance.pack_digest(str(pack_path))})++ # When both gates enumerate it+ with caplog.at_level(logging.WARNING):+ result = await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then neither its prestartup script (which runs scheduled installs) nor its import runs, and each gate gives the Manager reason, not a list mistake+ assert result == (False, False)+ messages = [record.getMessage() for record in caplog.records]+ assert messages.count(MANAGER_REFUSAL.format(name=name)) == 2+ assert GENERIC_REFUSAL.format(name=name) not in messages+++ ("mode", "denied"),+ [+ pytest.param("allowlist", False, id="allowlist-no-entry"),+ pytest.param("blocklist", True, id="blocklist-denied"),+ ],+)+async def test_other_refused_pack_logs_the_generic_policy_message(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ caplog: pytest.LogCaptureFixture,+ mode: str,+ denied: bool,+) -> None:+ # Given an ordinary pack the policy refuses+ custom_nodes_path = tmp_path / "custom_nodes"+ _, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path, "OtherPack")+ governance.set_custom_node_policy(mode, frozenset({"otherpack"}) if denied else frozenset(), {})++ # When both gates enumerate it+ with caplog.at_level(logging.WARNING):+ result = await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then each gate logs the generic policy message, never the Manager reason+ assert result == (False, False)+ messages = [record.getMessage() for record in caplog.records]+ assert messages.count(GENERIC_REFUSAL.format(name="OtherPack")) == 2+ assert MANAGER_REFUSAL.format(name="OtherPack") not in messages+++async def test_legacy_manager_pack_loads_without_a_custom_node_policy(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # Given a legacy Manager pack and no custom-node policy+ custom_nodes_path = tmp_path / "custom_nodes"+ _, prestartup_sentinel, import_sentinel = _make_directory_pack(custom_nodes_path, "ComfyUI-Manager")+ governance.set_custom_node_policy(None, frozenset(), {})++ # When both stock loading paths run+ result = await _run_both_gates(monkeypatch, custom_nodes_path, prestartup_sentinel, import_sentinel)++ # Then governance leaves it alone+ assert result == (True, True)diff --git a/tests-unit/governance_test/test_verify.py b/tests-unit/governance_test/test_verify.pynew file mode 100644index 000000000..d9de32c04--- /dev/null+++ b/tests-unit/governance_test/test_verify.py@@ -0,0 +1,615 @@+import base64+import json+from pathlib import Path+import sys++from cryptography.exceptions import InvalidSignature+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey+import pytest++from app import governance+++DOMAIN_SEPARATOR = b"comfyui-governance-v1\x00"+BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"+PAYLOAD_KEYS = {+ "schemaVersion",+ "audience",+ "versionId",+ "buildIdentity",+ "sourcesDigest",+ "policyGeneration",+ "activeForms",+ "customNodeMode",+ "packs",+ "deniedPacks",+ "disabledNodes",+ "disabledPartnerNodes",+ "models",+}+++def _b64url(raw: bytes) -> str:+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")+++def _payload() -> dict:+ return {+ "schemaVersion": 1,+ "audience": "comfyui-core",+ "versionId": "version-1",+ "buildIdentity": "test-build",+ "sourcesDigest": "sources-digest",+ "policyGeneration": 7,+ "activeForms": ["customNode"],+ "customNodeMode": "allowlist",+ "packs": [],+ "deniedPacks": [],+ "disabledNodes": [],+ "disabledPartnerNodes": [],+ "models": [],+ }+++def _envelope(+ private_key: Ed25519PrivateKey,+ payload: dict | None = None,+ *,+ payload_bytes: bytes | None = None,+ domain_separated: bool = True,+) -> bytes:+ if payload_bytes is None:+ payload_bytes = json.dumps(payload if payload is not None else _payload(), separators=(",", ":")).encode()+ message = DOMAIN_SEPARATOR + payload_bytes if domain_separated else payload_bytes+ outer = {"schema": 1, "payload": _b64url(payload_bytes), "signature": _b64url(private_key.sign(message))}+ return json.dumps(outer, separators=(",", ":")).encode()+++def _outer(envelope: bytes) -> dict:+ return json.loads(envelope)+++def _encoded_outer(outer: dict) -> bytes:+ return json.dumps(outer, separators=(",", ":")).encode()+++def _noncanonical_trailing_bits(encoded: str) -> str:+ # The last character of an unpadded encoding carries 4 unused bits when length % 4 == 2 and 2 when it is 3. Flipping+ # only those keeps the decoded bytes and leaves them set, which a canonical encoding never has.+ assert len(encoded) % 4 in {2, 3}+ unused_bits = 0b1111 if len(encoded) % 4 == 2 else 0b11+ index = BASE64URL_ALPHABET.index(encoded[-1])+ assert index & unused_bits == 0+ return encoded[:-1] + BASE64URL_ALPHABET[index ^ unused_bits]+++def private_key(monkeypatch: pytest.MonkeyPatch) -> Ed25519PrivateKey:+ key = Ed25519PrivateKey.generate()+ public_bytes = key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)+ monkeypatch.setattr(governance, "GOVERNANCE_BUILD_IDENTITY", "test-build")+ monkeypatch.setattr(governance, "GOVERNANCE_PUBLIC_KEY", _b64url(public_bytes))+ monkeypatch.setattr(governance, "GOVERNANCE_MIN_POLICY_GENERATION", 7)+ return key+++def test_valid_envelope_returns_parsed_payload(private_key: Ed25519PrivateKey) -> None:+ payload = _payload()++ assert governance.verify_and_load(_envelope(private_key, payload)) == payload+++ ("active_forms", "custom_node_mode"),+ [(["customNode"], "allowlist"), (["model"], None)],+)+def test_active_allowlist_form_can_have_empty_resolved_data(+ private_key: Ed25519PrivateKey,+ active_forms: list[str],+ custom_node_mode: str | None,+) -> None:+ payload = _payload()+ payload.update(activeForms=active_forms, customNodeMode=custom_node_mode)++ loaded = governance.verify_and_load(_envelope(private_key, payload))++ assert loaded["activeForms"] == active_forms+++def test_payload_tampering_fails_signature_verification(private_key: Ed25519PrivateKey) -> None:+ outer = _outer(_envelope(private_key))+ payload_bytes = base64.urlsafe_b64decode(outer["payload"] + "==")+ outer["payload"] = _b64url(payload_bytes.replace(b"comfyui-core", b"comfyui-corf"))++ with pytest.raises(InvalidSignature):+ governance.verify_and_load(_encoded_outer(outer))+++def test_signature_tampering_fails_verification(private_key: Ed25519PrivateKey) -> None:+ outer = _outer(_envelope(private_key))+ signature = bytearray(base64.urlsafe_b64decode(outer["signature"] + "=="))+ signature[0] ^= 1+ outer["signature"] = _b64url(bytes(signature))++ with pytest.raises(InvalidSignature):+ governance.verify_and_load(_encoded_outer(outer))+++def test_signature_from_wrong_key_is_rejected(private_key: Ed25519PrivateKey) -> None:+ with pytest.raises(InvalidSignature):+ governance.verify_and_load(_envelope(Ed25519PrivateKey.generate()))+++ ("key", "value"),+ [+ ("audience", "desktop"),+ ("buildIdentity", "foreign-build"),+ ("schemaVersion", 2),+ ],+)+def test_signed_payload_identity_mismatches_are_rejected(+ private_key: Ed25519PrivateKey,+ key: str,+ value: str | int,+) -> None:+ payload = _payload()+ payload[key] = value++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++def test_signature_without_domain_separator_is_rejected(private_key: Ed25519PrivateKey) -> None:+ with pytest.raises(InvalidSignature):+ governance.verify_and_load(_envelope(private_key, domain_separated=False))+++def test_policy_generation_below_floor_is_rejected(private_key: Ed25519PrivateKey) -> None:+ payload = _payload()+ payload["policyGeneration"] = 6++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++def test_policy_generation_equal_to_floor_is_accepted(private_key: Ed25519PrivateKey) -> None:+ assert governance.verify_and_load(_envelope(private_key))["policyGeneration"] == 7++[email protected]("schema", [2, "1", True, None])+def test_envelope_schema_must_be_integer_one(private_key: Ed25519PrivateKey, schema) -> None:+ outer = _outer(_envelope(private_key))+ outer["schema"] = schema++ with pytest.raises(ValueError):+ governance.verify_and_load(_encoded_outer(outer))++[email protected]("missing_key", ["schema", "payload", "signature"])+def test_envelope_rejects_each_missing_key(private_key: Ed25519PrivateKey, missing_key: str) -> None:+ outer = _outer(_envelope(private_key))+ del outer[missing_key]++ with pytest.raises(ValueError):+ governance.verify_and_load(_encoded_outer(outer))+++def test_envelope_rejects_extra_key(private_key: Ed25519PrivateKey) -> None:+ outer = _outer(_envelope(private_key))+ outer["kid"] = "unexpected"++ with pytest.raises(ValueError):+ governance.verify_and_load(_encoded_outer(outer))++[email protected](("key", "value"), [("payload", 1), ("signature", None)])+def test_envelope_rejects_wrong_codec_field_types(+ private_key: Ed25519PrivateKey,+ key: str,+ value,+) -> None:+ outer = _outer(_envelope(private_key))+ outer[key] = value++ with pytest.raises(ValueError):+ governance.verify_and_load(_encoded_outer(outer))++[email protected]("invalid_envelope", [b"not json", b"[]", b"{}", json.dumps(_payload()).encode()])+def test_unsigned_or_non_object_envelopes_are_rejected(invalid_envelope: bytes) -> None:+ with pytest.raises(ValueError):+ governance.verify_and_load(invalid_envelope)+++def test_signed_payload_must_be_an_object(private_key: Ed25519PrivateKey) -> None:+ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload_bytes=b"[]"))++[email protected]("missing_key", sorted(PAYLOAD_KEYS))+def test_payload_rejects_each_missing_key(private_key: Ed25519PrivateKey, missing_key: str) -> None:+ payload = _payload()+ del payload[missing_key]++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++def test_payload_rejects_extra_key(private_key: Ed25519PrivateKey) -> None:+ payload = _payload()+ payload["modelPolicy"] = {}++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++ ("key", "value"),+ [+ ("schemaVersion", "1"),+ ("schemaVersion", True),+ ("audience", 1),+ ("versionId", 1),+ ("buildIdentity", 1),+ ("sourcesDigest", 1),+ ("policyGeneration", "7"),+ ("policyGeneration", True),+ ("activeForms", "customNode"),+ ("customNodeMode", 1),+ ("packs", {}),+ ("deniedPacks", {}),+ ("disabledNodes", {}),+ ("disabledPartnerNodes", {}),+ ("models", {}),+ ],+)+def test_payload_rejects_wrong_top_level_types(+ private_key: Ed25519PrivateKey,+ key: str,+ value,+) -> None:+ payload = _payload()+ payload[key] = value++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++ ("active_forms", "custom_node_mode"),+ [+ (["unknown"], None),+ (["model", "customNode"], "allowlist"),+ (["customNode", "customNode"], "allowlist"),+ ([], None),+ (["model"], "allowlist"),+ (["customNode"], None),+ (["customNode"], "audit"),+ ([1], None),+ ],+)+def test_payload_rejects_invalid_active_form_and_mode_combinations(+ private_key: Ed25519PrivateKey,+ active_forms: list,+ custom_node_mode,+) -> None:+ payload = _payload()+ payload.update(activeForms=active_forms, customNodeMode=custom_node_mode)++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++ "denied_packs",+ [["pack"], ["Pack"], ["path/pack"], ["path\\pack"], [""], ["."], [".."], ["b", "a"], ["pack", "pack"], [1]],+)+def test_payload_rejects_invalid_denied_packs(+ private_key: Ed25519PrivateKey,+ denied_packs: list,+) -> None:+ payload = _payload()+ payload["deniedPacks"] = denied_packs+ if denied_packs == ["pack"]:+ payload["customNodeMode"] = "allowlist"+ else:+ payload["customNodeMode"] = "blocklist"++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++ ("active_forms", "custom_node_mode", "key", "value"),+ [+ (["model"], None, "packs", [{"name": "pack", "digest": "blake3:" + "a" * 64}]),+ (["customNode"], "allowlist", "disabledNodes", ["Node"]),+ (["customNode"], "allowlist", "disabledPartnerNodes", [{"nodeId": "Node", "providerId": "provider"}]),+ (["customNode"], "allowlist", "models", ["blake3:" + "a" * 64]),+ ],+)+def test_payload_rejects_nonempty_data_for_inactive_form(+ private_key: Ed25519PrivateKey,+ active_forms: list[str],+ custom_node_mode: str | None,+ key: str,+ value: list,+) -> None:+ payload = _payload()+ payload.update(activeForms=active_forms, customNodeMode=custom_node_mode)+ payload[key] = value++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++def test_node_id_form_rejects_empty_disabled_nodes(private_key: Ed25519PrivateKey) -> None:+ payload = _payload()+ payload.update(activeForms=["nodeId"], customNodeMode=None)++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))++[email protected]("disabled_nodes", [["B", "A"], ["A", "A"], [1]])+def test_disabled_nodes_must_be_a_sorted_unique_string_list(+ private_key: Ed25519PrivateKey,+ disabled_nodes: list,+) -> None:+ payload = _payload()+ payload.update(activeForms=["nodeId"], customNodeMode=None, disabledNodes=disabled_nodes)++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++ "packs",+ [+ ["pack"],+ [{"name": "pack"}],+ [{"name": "pack", "digest": "digest", "extra": "value"}],+ [{"name": 1, "digest": "digest"}],+ [{"name": "pack", "digest": 1}],+ ],+)+def test_packs_require_exact_string_entry_schema(private_key: Ed25519PrivateKey, packs: list) -> None:+ payload = _payload()+ payload["packs"] = packs++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++ "pack",+ [+ {"name": "pack", "digest": "digest"},+ {"name": "pack", "digest": "a" * 64},+ {"name": "pack", "digest": "blake3:" + "A" * 64},+ {"name": "pack", "digest": "blake3:" + "a" * 63},+ {"name": "pack", "digest": "blake3:" + "a" * 65},+ {"name": "pack", "digest": "blake3:" + "g" * 64},+ {"name": "pack", "digest": "sha256:" + "a" * 64},+ {"name": "pack", "digest": "blake3:" + "a" * 64 + "\n"},+ ],+)+def test_packs_reject_digests_not_in_pack_digest_form(private_key: Ed25519PrivateKey, pack: dict) -> None:+ payload = _payload()+ payload["packs"] = [pack]++ with pytest.raises(ValueError, match="canonical BLAKE3"):+ governance.verify_and_load(_envelope(private_key, payload))++[email protected]("name", ["nested/pack", "org\\pack", "..", ".", ""])+def test_blocklist_rejects_pack_names_that_are_not_basenames(private_key: Ed25519PrivateKey, name: str) -> None:+ payload = _payload()+ payload["customNodeMode"] = "blocklist"+ payload["packs"] = [{"name": name, "digest": "blake3:" + "a" * 64}]++ with pytest.raises(ValueError, match="blocklist pack names must be basenames"):+ governance.verify_and_load(_envelope(private_key, payload))+++def test_allowlist_accepts_pack_names_with_separators(private_key: Ed25519PrivateKey) -> None:+ # An allowlist admits a pack by digest alone, so the name is never looked up.+ payload = _payload()+ payload["packs"] = [{"name": "nested/pack", "digest": "blake3:" + "a" * 64}]++ assert governance.verify_and_load(_envelope(private_key, payload))["packs"] == payload["packs"]+++def test_blocklist_mixed_case_pin_refuses_a_folder_with_another_digest(+ private_key: Ed25519PrivateKey,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ # _apply_policy sets module and interpreter state; monkeypatch puts all of it back after the test.+ for name in ("_policy", "_disabled_nodes", "_custom_node_mode", "_denied_packs", "_allowed_packs"):+ monkeypatch.setattr(governance, name, getattr(governance, name))+ monkeypatch.setattr(sys, "dont_write_bytecode", sys.dont_write_bytecode)+ monkeypatch.setattr(sys, "pycache_prefix", sys.pycache_prefix)+ monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1")+ monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False)+ pack_path = tmp_path / "ComfyUI-Example-Pack"+ pack_path.mkdir()+ (pack_path / "__init__.py").write_bytes(b"NODE_CLASS_MAPPINGS = {}\n")+ payload = _payload()+ payload["customNodeMode"] = "blocklist"+ payload["packs"] = [{"name": "ComfyUI-Example-Pack", "digest": "blake3:" + "0" * 64}]++ governance._apply_policy(governance.verify_and_load(_envelope(private_key, payload)))++ assert governance.pack_refusal(str(pack_path)) == (+ "Custom node pack 'ComfyUI-Example-Pack' is not permitted by your organization's policy."+ )+++def test_packs_accept_pack_digest_output_under_mixed_case_names(private_key: Ed25519PrivateKey, tmp_path: Path) -> None:+ pack_path = tmp_path / "ComfyUI-Example-Pack"+ pack_path.mkdir()+ (pack_path / "__init__.py").write_bytes(b"NODE_CLASS_MAPPINGS = {}\n")+ payload = _payload()+ payload["packs"] = [+ {"name": "ComfyUI-Example-Pack", "digest": governance.pack_digest(str(pack_path))},+ # The digest cloud's packdigest and test_pack_digest.py both assert for their shared fixture.+ {"name": "shared-fixture", "digest": "blake3:60627b4c95dad13ffe3dd68e165ac182c605ab1f873a88d11c3b9c0b65d531e1"},+ ]++ assert governance.verify_and_load(_envelope(private_key, payload))["packs"] == payload["packs"]+++ "entries",+ [+ ["Node"],+ [{"nodeId": "Node"}],+ [{"nodeId": "Node", "providerId": "provider", "extra": "value"}],+ [{"nodeId": 1, "providerId": "provider"}],+ [{"nodeId": "Node", "providerId": 1}],+ [{"nodeId": "A", "providerId": "Provider"}],+ [{"nodeId": "A", "providerId": "provider/id"}],+ [{"nodeId": "A", "providerId": ""}],+ [{"nodeId": "B", "providerId": "b"}, {"nodeId": "A", "providerId": "a"}],+ [{"nodeId": "A", "providerId": "a"}, {"nodeId": "A", "providerId": "b"}],+ ],+)+def test_partner_nodes_require_exact_canonical_entries(private_key: Ed25519PrivateKey, entries: list) -> None:+ payload = _payload()+ payload.update(activeForms=["partnerNode"], customNodeMode=None, disabledPartnerNodes=entries)++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))+++ "models",+ [+ ["a" * 64],+ ["blake3:" + "A" * 64],+ ["blake3:" + "a" * 63],+ ["blake3:" + "g" * 64],+ ["blake3:" + "b" * 64, "blake3:" + "a" * 64],+ ["blake3:" + "a" * 64, "blake3:" + "a" * 64],+ [1],+ ],+)+def test_models_require_sorted_unique_canonical_blake3_digests(+ private_key: Ed25519PrivateKey,+ models: list,+) -> None:+ payload = _payload()+ payload.update(activeForms=["model"], customNodeMode=None, models=models)++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key, payload))++[email protected]("field", ["payload", "signature", "public_key"])+def test_padded_base64_is_rejected(private_key: Ed25519PrivateKey, monkeypatch: pytest.MonkeyPatch, field: str) -> None:+ outer = _outer(_envelope(private_key))+ if field == "public_key":+ monkeypatch.setattr(governance, "GOVERNANCE_PUBLIC_KEY", governance.GOVERNANCE_PUBLIC_KEY + "=")+ else:+ outer[field] += "="++ with pytest.raises(ValueError):+ governance.verify_and_load(_encoded_outer(outer))++[email protected]("field", ["payload", "signature", "public_key"])[email protected]("character", ["+", "/"])+def test_non_url_safe_base64_alphabet_is_rejected(+ private_key: Ed25519PrivateKey,+ monkeypatch: pytest.MonkeyPatch,+ field: str,+ character: str,+) -> None:+ outer = _outer(_envelope(private_key))+ if field == "public_key":+ monkeypatch.setattr(governance, "GOVERNANCE_PUBLIC_KEY", character + governance.GOVERNANCE_PUBLIC_KEY[1:])+ else:+ outer[field] = character + outer[field][1:]++ with pytest.raises(ValueError):+ governance.verify_and_load(_encoded_outer(outer))++[email protected]("field", ["payload", "signature", "public_key"])+def test_noncanonical_trailing_bits_are_rejected(+ private_key: Ed25519PrivateKey,+ monkeypatch: pytest.MonkeyPatch,+ field: str,+) -> None:+ payload_bytes = json.dumps(_payload(), separators=(",", ":")).encode()+ while len(payload_bytes) % 3 == 0:+ payload_bytes += b" "+ outer = _outer(_envelope(private_key, payload_bytes=payload_bytes))+ if field == "public_key":+ monkeypatch.setattr(governance, "GOVERNANCE_PUBLIC_KEY", _noncanonical_trailing_bits(governance.GOVERNANCE_PUBLIC_KEY))+ else:+ outer[field] = _noncanonical_trailing_bits(outer[field])++ with pytest.raises(ValueError):+ governance.verify_and_load(_encoded_outer(outer))++[email protected]("signature_size", [63, 65])+def test_signature_must_decode_to_64_bytes(private_key: Ed25519PrivateKey, signature_size: int) -> None:+ outer = _outer(_envelope(private_key))+ outer["signature"] = _b64url(b"s" * signature_size)++ with pytest.raises(ValueError):+ governance.verify_and_load(_encoded_outer(outer))++[email protected]("public_key_size", [31, 33])+def test_public_key_must_decode_to_32_bytes(+ private_key: Ed25519PrivateKey,+ monkeypatch: pytest.MonkeyPatch,+ public_key_size: int,+) -> None:+ monkeypatch.setattr(governance, "GOVERNANCE_PUBLIC_KEY", _b64url(b"k" * public_key_size))++ with pytest.raises(ValueError):+ governance.verify_and_load(_envelope(private_key))+++def test_oversized_envelope_is_rejected_before_parsing(+ private_key: Ed25519PrivateKey,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ envelope = _envelope(private_key)+ monkeypatch.setattr(governance, "_MAX_ENVELOPE_BYTES", len(envelope) - 1, raising=False)+ monkeypatch.setattr(governance.json, "loads", lambda *_args, **_kwargs: pytest.fail("parsed oversized envelope"))++ with pytest.raises(ValueError):+ governance.verify_and_load(envelope)+++def test_oversized_payload_is_rejected_before_decoding(+ private_key: Ed25519PrivateKey,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ outer = _outer(_envelope(private_key))+ monkeypatch.setattr(governance, "_MAX_PAYLOAD_BYTES", 1, raising=False)+ monkeypatch.setattr(governance.base64, "b64decode", lambda *_args, **_kwargs: pytest.fail("decoded oversized payload"))++ with pytest.raises(ValueError):+ governance.verify_and_load(_encoded_outer(outer))+++def test_valid_signature_is_checked_before_invalid_json_is_parsed(private_key: Ed25519PrivateKey) -> None:+ with pytest.raises(json.JSONDecodeError):+ governance.verify_and_load(_envelope(private_key, payload_bytes=b"not json"))+++def test_invalid_signature_precedes_parsing_valid_json(private_key: Ed25519PrivateKey) -> None:+ outer = _outer(_envelope(private_key))+ outer["signature"] = _b64url(b"s" * 64)++ with pytest.raises(InvalidSignature):+ governance.verify_and_load(_encoded_outer(outer))diff --git a/tests-unit/main_prestartup_test.py b/tests-unit/main_prestartup_test.pyindex a9c86aa2f..3ffb24f2c 100644--- a/tests-unit/main_prestartup_test.py+++ b/tests-unit/main_prestartup_test.py@@ -9,6 +9,7 @@ from types import SimpleNamespaceimport timeimport folder_paths+from app import governancedef _load_execute_prestartup_script():@@ -19,6 +20,7 @@ def _load_execute_prestartup_script():namespace = {"args": SimpleNamespace(disable_all_custom_nodes=False, whitelist_custom_nodes=[], enable_manager=False),"folder_paths": folder_paths,+ "governance": governance,"importlib": importlib,"logging": logging,"os": os,diff --git a/tests/execution/test_disabled_nodes.py b/tests/execution/test_disabled_nodes.pynew file mode 100644index 000000000..8bfe53220--- /dev/null+++ b/tests/execution/test_disabled_nodes.py@@ -0,0 +1,171 @@+from contextlib import contextmanager+import json+from pathlib import Path+import socket+import subprocess+import sys+import time+from typing import Iterator+import urllib.error+import urllib.request++import pytest+++COMFYUI_ROOT = Path(__file__).parents[2]+++def _unused_port() -> int:+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return sock.getsockname()[1]+++def _get_json(url: str) -> dict:+ with urllib.request.urlopen(url, timeout=5) as response:+ return json.load(response)+++def _post_prompt(base_url: str, prompt: dict) -> tuple[int, dict]:+ request = urllib.request.Request(+ f"{base_url}/prompt",+ data=json.dumps({"prompt": prompt}).encode(),+ headers={"Content-Type": "application/json"},+ )+ try:+ with urllib.request.urlopen(request, timeout=15) as response:+ return response.status, json.load(response)+ except urllib.error.HTTPError as error:+ return error.code, json.load(error)+++def _wait_for_server(process: subprocess.Popen, base_url: str, log_path: Path) -> None:+ deadline = time.monotonic() + 120+ while time.monotonic() < deadline:+ if process.poll() is not None:+ pytest.fail(f"server exited during startup:\n{log_path.read_text(encoding='utf-8')}")+ try:+ _get_json(f"{base_url}/system_stats")+ return+ except urllib.error.URLError:+ time.sleep(0.25)+ pytest.fail(f"server readiness timed out:\n{log_path.read_text(encoding='utf-8')}")+++def _wait_for_history(base_url: str, prompt_id: str) -> dict:+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline:+ history = _get_json(f"{base_url}/history/{prompt_id}")+ if prompt_id in history:+ return history[prompt_id]+ time.sleep(0.1)+ raise AssertionError(f"prompt {prompt_id} did not finish")+++@contextmanager+def _running_server(tmp_path: Path, disabled_node: str, testing_nodes: bool = False) -> Iterator[str]:+ config_path = tmp_path / "disabled_nodes.yaml"+ config_path.write_text(f"disabled_nodes:\n - {disabled_node}\n", encoding="utf-8")+ log_path = tmp_path / "server.log"+ port = _unused_port()+ base_url = f"http://127.0.0.1:{port}"+ command = [+ sys.executable,+ "main.py",+ "--listen",+ "127.0.0.1",+ "--port",+ str(port),+ "--cpu",+ "--cache-none",+ "--disable-api-nodes",+ "--output-directory",+ str(tmp_path / "output"),+ "--temp-directory",+ str(tmp_path),+ "--disabled-nodes-config",+ str(config_path),+ ]+ if testing_nodes:+ command += ["--extra-model-paths-config", str(Path(__file__).parent / "extra_model_paths.yaml")]+ else:+ command.append("--disable-all-custom-nodes")+ with log_path.open("w", encoding="utf-8") as log:+ process = subprocess.Popen(command, cwd=COMFYUI_ROOT, stdout=log, stderr=subprocess.STDOUT, text=True)+ try:+ _wait_for_server(process, base_url, log_path)+ yield base_url+ finally:+ process.terminate()+ try:+ process.wait(timeout=10)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=10)+++def test_disabled_old_id_forwards_and_executes_allowed_target(tmp_path: Path) -> None:+ # Given+ prompt = {+ "source-a": {+ "class_type": "EmptyImage",+ "inputs": {"width": 16, "height": 16, "batch_size": 1, "color": 0},+ },+ "source-b": {+ "class_type": "EmptyImage",+ "inputs": {"width": 16, "height": 16, "batch_size": 1, "color": 0},+ },+ "legacy": {+ "class_type": "ImageBatch",+ "inputs": {"image1": ["source-a", 0], "image2": ["source-b", 0]},+ },+ "output": {"class_type": "PreviewImage", "inputs": {"images": ["legacy", 0]}},+ }++ # When+ with _running_server(tmp_path, "ImageBatch") as base_url:+ object_info = _get_json(f"{base_url}/object_info")+ status, response = _post_prompt(base_url, prompt)+ history = _wait_for_history(base_url, response["prompt_id"])++ # Then+ assert "ImageBatch" not in object_info+ assert status == 200+ assert history["status"]["status_str"] == "success"+ assert history["prompt"][2]["legacy"]["class_type"] == "BatchImagesNode"+++def test_replacement_pointing_to_disabled_target_is_refused(tmp_path: Path) -> None:+ # Given+ prompt = {"1": {"class_type": "ConditioningAverage ", "inputs": {}}}++ # When+ with _running_server(tmp_path, "ConditioningAverage") as base_url:+ object_info = _get_json(f"{base_url}/object_info")+ status, response = _post_prompt(base_url, prompt)++ # Then+ assert "ConditioningAverage" not in object_info+ assert status == 400+ assert response["error"]["type"] == "missing_node_type"+ assert response["error"]["extra_info"]["class_type"] == "ConditioningAverage "+++def test_disabled_node_cannot_be_reached_through_expansion(tmp_path: Path) -> None:+ # Given+ prompt = {"1": {"class_type": "TestExpandsToDisabledNode", "inputs": {}}}++ # When+ with _running_server(tmp_path, "TestDisabledNode", testing_nodes=True) as base_url:+ object_info = _get_json(f"{base_url}/object_info")+ status, response = _post_prompt(base_url, prompt)+ history = _wait_for_history(base_url, response["prompt_id"])++ # Then+ assert "TestExpandsToDisabledNode" in object_info+ assert "TestDisabledNode" not in object_info+ assert status == 200+ assert history["status"]["status_str"] == "error"diff --git a/tests/execution/testing_nodes/testing-pack/specific_tests.py b/tests/execution/testing_nodes/testing-pack/specific_tests.pyindex 156f9b314..c91fd1f9b 100644--- a/tests/execution/testing_nodes/testing-pack/specific_tests.py+++ b/tests/execution/testing_nodes/testing-pack/specific_tests.py@@ -305,6 +305,37 @@ class TestDynamicDependencyCycle:"expand": g.finalize(),}+class TestDisabledNode:+ @classmethod+ def INPUT_TYPES(cls):+ return {"required": {}}++ RETURN_TYPES = ()+ FUNCTION = "execute"+ CATEGORY = "Testing/Nodes"+ OUTPUT_NODE = True++ def execute(self):+ return ()++class TestExpandsToDisabledNode:+ @classmethod+ def INPUT_TYPES(cls):+ return {"required": {}}++ RETURN_TYPES = ()+ FUNCTION = "expand"+ CATEGORY = "Testing/Nodes"+ OUTPUT_NODE = True++ def expand(self):+ g = GraphBuilder()+ g.node("TestDisabledNode")+ return {+ "result": (),+ "expand": g.finalize(),+ }+class TestMixedExpansionReturns:@classmethoddef INPUT_TYPES(cls):@@ -554,6 +585,8 @@ TEST_NODE_CLASS_MAPPINGS = {"TestCustomValidation4": TestCustomValidation4,"TestCustomValidation5": TestCustomValidation5,"TestDynamicDependencyCycle": TestDynamicDependencyCycle,+ "TestDisabledNode": TestDisabledNode,+ "TestExpandsToDisabledNode": TestExpandsToDisabledNode,"TestMixedExpansionReturns": TestMixedExpansionReturns,"TestSamplingInExpansion": TestSamplingInExpansion,"TestSleep": TestSleep,@@ -575,6 +608,8 @@ TEST_NODE_DISPLAY_NAME_MAPPINGS = {"TestCustomValidation4": "Custom Validation 4","TestCustomValidation5": "Custom Validation 5","TestDynamicDependencyCycle": "Dynamic Dependency Cycle",+ "TestDisabledNode": "Disabled Node",+ "TestExpandsToDisabledNode": "Expands To Disabled Node","TestMixedExpansionReturns": "Mixed Expansion Returns","TestSamplingInExpansion": "Sampling In Expansion","TestSleep": "Test Sleep",