From 0cea888dd1baeb57674fd771d72c0bcb9c411951 Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Wed, 16 Sep 2026 04:46:34 +0000 Subject: [PATCH 1/5] feat(models): add --host/--port to search/list-folders/list-folder/show `comfy models search`, `list-folders`, `list-folder`, and `show` routed via `resolve_target(where=...)` but never exposed `--host`/`--port`, so the only way to point them at a specific local ComfyUI was the process-wide `COMFY_LOCAL_URL` env var. `resolve_target()` already accepts `host`/`port`; this threads them through the shared `_resolve_and_stamp` helper, mirroring the `comfy upload` flags (BE-5662): validate the host (URL-injection / control chars) and port range, reject the flags against an effective cloud target with a structured `host_flag_cloud` error that names how the cloud decision was reached, and otherwise apply the local precedence explicit flag > COMFY_LOCAL_URL > 127.0.0.1:8188. No flags => behavior is unchanged. Co-Authored-By: Claude Opus 4.8 --- comfy_cli/command/models/search.py | 121 ++++++++++++- tests/comfy_cli/command/models/test_search.py | 169 ++++++++++++++++++ 2 files changed, 283 insertions(+), 7 deletions(-) diff --git a/comfy_cli/command/models/search.py b/comfy_cli/command/models/search.py index d39141639..e2996ad3f 100644 --- a/comfy_cli/command/models/search.py +++ b/comfy_cli/command/models/search.py @@ -1,6 +1,8 @@ """``comfy models`` — live model discovery against local or cloud. -Four subcommands, all routed by ``--where`` (cloud auto-detect by default): +Four subcommands, all routed by ``--where`` (cloud auto-detect by default); +each also accepts ``--host``/``--port`` to aim a *local* query at a specific +ComfyUI (rejected against a cloud target), mirroring ``comfy upload``: comfy models list-folders # GET /api/experiment/models | /models comfy models list-folder # GET /api/experiment/models/ | /models/ @@ -178,7 +180,20 @@ def _emit_http_error(e: urllib.error.HTTPError, *, renderer, target, message: st raise typer.Exit(code=1) from e -def _resolve_and_stamp(renderer, where: str | None): +# How a `cloud` routing decision was reached, in words, for the --host/--port +# rejection message. Keys are `where.WhereResolution.source` values. Mirrors the +# copy `cmdline.upload` uses (BE-5662) — kept local rather than imported so this +# module stays free of a `cmdline` import cycle. +_WHERE_SOURCE_PHRASES = { + "flag": "targeting cloud via --where cloud", + "env": "targeting cloud via the COMFY_WHERE environment variable", + "project": "targeting cloud via this project's configured default", + "config": "targeting cloud via your saved `where_default` setting", + "auto": "targeting cloud because you're signed in (no explicit --where)", +} + + +def _resolve_and_stamp(renderer, where: str | None, *, host: str | None = None, port: int | None = None): """Resolve the routing Target for a ``models`` verb and stamp it on the renderer. Every verb here calls this at the point it decides local-vs-cloud, so the @@ -186,10 +201,70 @@ def _resolve_and_stamp(renderer, where: str | None): Errors raised *before* this (an unsafe path segment) keep ``where: null``, which is correct — nothing had routed yet. Explicit ``emit(..., where=...)`` arguments still take precedence over the stamp. + + ``host``/``port`` route a **local** ``models`` query at a specific ComfyUI + (the ``--host``/``--port`` flags), mirroring ``comfy upload`` (BE-5662): + they are validated the same way, rejected against an effective ``cloud`` + target, and otherwise handed to ``resolve_target``, which applies the local + precedence explicit flag > ``COMFY_LOCAL_URL`` > ``127.0.0.1:8188``. With + both ``None`` (no flags), resolution is exactly what it was before the flags + existed. The cloud target's address comes from the signed-in account and + ignores host/port entirely, so pairing them with a cloud target is a usage + error rather than a silently-ignored flag — the root cause of the comfy-mcp + bug where ``search_models`` answered from the local machine regardless of + the configured remote target. """ + from comfy_cli import where as where_module + from comfy_cli.config_manager import ConfigManager + from comfy_cli.host_port import report_usage_error, validate_host from comfy_cli.target import resolve_target - target = resolve_target(where=where) + # Validate the flags before resolving anything: the host lands verbatim in + # ``http://{host}:{port}/...``, so a URL-special or control character is a + # usage error (BadParameter, exit 2) regardless of target. Port range is + # checked the same way ``comfy upload`` does. ``report_usage_error`` emits + # the terminating envelope for that rejection in JSON/NDJSON mode; the + # exception still escapes, so click's exit-2 usage contract is unchanged. + with report_usage_error(renderer): + if host is not None: + host = validate_host(host) + if port is not None and not (1 <= port <= 65535): + raise typer.BadParameter(f"invalid port: {port} is out of range (1-65535)") + + try: + decision = where_module.resolve( + flag=where, config_value=ConfigManager().get(where_module.CONFIG_KEY_WHERE_DEFAULT) + ) + except ValueError as e: + renderer.error(code="where_invalid", message=str(e), hint="use --where local or --where cloud") + raise typer.Exit(code=1) from e + + effective_where = "cloud" if decision.target is where_module.WhereTarget.CLOUD else "local" + # Routing is decided, so every error envelope from here down can name the + # target — including the `host_flag_cloud` rejection immediately below. + renderer.where = effective_where + # --host/--port address a local ComfyUI; the cloud target's address comes + # from the signed-in account and ignores them (``Target.host``/``port`` are + # documented local-only). Reject the combination rather than silently + # answering from a machine the caller didn't name. + if effective_where == "cloud" and (host is not None or port is not None): + # The cloud target can come from an explicit --where, but equally from + # COMFY_WHERE, a project/config default, or credential auto-detection — + # so name the source rather than accusing the user of a flag they may + # never have typed. + source = _WHERE_SOURCE_PHRASES.get(decision.source, f"resolved to cloud by {decision.source}") + renderer.error( + code="host_flag_cloud", + message=f"--host/--port target a local ComfyUI server, but this run is {source}", + hint=( + "pass --where local to aim at a local server; to reach a different cloud address " + "set COMFY_CLOUD_BASE_URL or run `comfy cloud set-base-url`" + ), + details={"host": host, "port": port, "where": effective_where, "where_source": decision.source}, + ) + raise typer.Exit(code=1) + + target = resolve_target(where=effective_where, host=host, port=port) renderer.where = target.kind return target @@ -211,9 +286,17 @@ def list_folders_cmd( str | None, typer.Option("--where", show_default=False, help="Override the resolved routing mode."), ] = None, + host: Annotated[ + str | None, + typer.Option(help="Server host (defaults to COMFY_LOCAL_URL or 127.0.0.1). Local targets only."), + ] = None, + port: Annotated[ + int | None, + typer.Option(help="Server port (defaults to COMFY_LOCAL_URL or 8188). Local targets only."), + ] = None, ): renderer = get_renderer() - target = _resolve_and_stamp(renderer, where) + target = _resolve_and_stamp(renderer, where, host=host, port=port) url = target.url(*_models_path_parts(target)) try: @@ -286,10 +369,18 @@ def list_folder_cmd( int | None, typer.Option("--limit", show_default=False, help="Cap output to N rows."), ] = None, + host: Annotated[ + str | None, + typer.Option(help="Server host (defaults to COMFY_LOCAL_URL or 127.0.0.1). Local targets only."), + ] = None, + port: Annotated[ + int | None, + typer.Option(help="Server port (defaults to COMFY_LOCAL_URL or 8188). Local targets only."), + ] = None, ): renderer = get_renderer() _reject_unsafe_path_segment(folder, kind="folder", renderer=renderer) - target = _resolve_and_stamp(renderer, where) + target = _resolve_and_stamp(renderer, where, host=host, port=port) # Percent-encoded for the same reason `_local_folder_matches` does it: the # relaxed validation above admits spaces, `?`/`#`, and non-ASCII, none of # which may be allowed to alter the request. Error payloads below carry the @@ -740,11 +831,19 @@ def search_cmd( str | None, typer.Option("--where", show_default=False, help="Override the resolved routing mode."), ] = None, + host: Annotated[ + str | None, + typer.Option(help="Server host (defaults to COMFY_LOCAL_URL or 127.0.0.1). Local targets only."), + ] = None, + port: Annotated[ + int | None, + typer.Option(help="Server port (defaults to COMFY_LOCAL_URL or 8188). Local targets only."), + ] = None, ): renderer = get_renderer() if type_ is not None: _reject_unsafe_path_segment(type_, kind="type", renderer=renderer) - target = _resolve_and_stamp(renderer, where) + target = _resolve_and_stamp(renderer, where, host=host, port=port) try: if target.is_cloud: @@ -826,9 +925,17 @@ def show_cmd( str | None, typer.Option("--where", show_default=False, help="Override the resolved routing mode."), ] = None, + host: Annotated[ + str | None, + typer.Option(help="Server host (defaults to COMFY_LOCAL_URL or 127.0.0.1). Local targets only."), + ] = None, + port: Annotated[ + int | None, + typer.Option(help="Server port (defaults to COMFY_LOCAL_URL or 8188). Local targets only."), + ] = None, ): renderer = get_renderer() - target = _resolve_and_stamp(renderer, where) + target = _resolve_and_stamp(renderer, where, host=host, port=port) if not target.is_cloud: # On local there's no asset catalog. We can confirm the file exists by diff --git a/tests/comfy_cli/command/models/test_search.py b/tests/comfy_cli/command/models/test_search.py index fb342387b..97c587243 100644 --- a/tests/comfy_cli/command/models/test_search.py +++ b/tests/comfy_cli/command/models/test_search.py @@ -1044,3 +1044,172 @@ def test_local_is_explicitly_unsupported(self, local_target, monkeypatch, capsys env = _run(["show", "anything.safetensors", "--where", "local"], capsys) assert env["ok"] is False assert env["error"]["code"] == "models_show_local_unsupported" + + +# --------------------------------------------------------------------------- +# --host/--port routing (BE-5788) — mirrors `comfy upload` (BE-5662) +# --------------------------------------------------------------------------- + + +class TestHostPortRouting: + """``comfy models --host/--port`` aims a LOCAL query at a specific + ComfyUI, closing the gap where these four verbs could only reach the + process-wide ``COMFY_LOCAL_URL`` (or the 127.0.0.1:8188 default). The URL + the request actually hits is asserted end-to-end through the *real* + ``resolve_target`` — no fixture pins it — so the precedence (explicit flag > + ``COMFY_LOCAL_URL`` > default), resolved independently for host and port, is + exercised, not mocked. + """ + + def test_host_and_port_reach_the_resolved_url(self, monkeypatch, capsys): + monkeypatch.delenv("COMFY_LOCAL_URL", raising=False) + _patch_urlopen(monkeypatch, {"10.0.0.5:9999/models": _LOCAL_FOLDERS}) + env = _run(["list-folders", "--where", "local", "--host", "10.0.0.5", "--port", "9999"], capsys) + assert env["ok"] is True, env + assert env["data"]["url"] == "http://10.0.0.5:9999/models" + + def test_no_flags_keeps_the_loopback_default(self, monkeypatch, capsys): + # Acceptance: no flags -> behavior identical to today. + monkeypatch.delenv("COMFY_LOCAL_URL", raising=False) + _patch_urlopen(monkeypatch, {"127.0.0.1:8188/models": _LOCAL_FOLDERS}) + env = _run(["list-folders", "--where", "local"], capsys) + assert env["ok"] is True, env + assert env["data"]["url"] == "http://127.0.0.1:8188/models" + + def test_no_flags_still_honors_comfy_local_url(self, monkeypatch, capsys): + monkeypatch.setenv("COMFY_LOCAL_URL", "http://192.168.1.50:7777") + _patch_urlopen(monkeypatch, {"192.168.1.50:7777/models": _LOCAL_FOLDERS}) + env = _run(["list-folders", "--where", "local"], capsys) + assert env["ok"] is True, env + assert env["data"]["url"] == "http://192.168.1.50:7777/models" + + def test_flags_beat_comfy_local_url(self, monkeypatch, capsys): + monkeypatch.setenv("COMFY_LOCAL_URL", "http://192.168.1.50:7777") + _patch_urlopen(monkeypatch, {"10.0.0.5:9999/models": _LOCAL_FOLDERS}) + env = _run(["list-folders", "--where", "local", "--host", "10.0.0.5", "--port", "9999"], capsys) + assert env["ok"] is True, env + assert env["data"]["url"] == "http://10.0.0.5:9999/models" + + def test_host_only_flag_keeps_the_env_port(self, monkeypatch, capsys): + # host and port resolve independently, so --host alone must not drop the + # env var's port back to the 8188 default. + monkeypatch.setenv("COMFY_LOCAL_URL", "http://192.168.1.50:7777") + _patch_urlopen(monkeypatch, {"10.0.0.5:7777/models": _LOCAL_FOLDERS}) + env = _run(["list-folders", "--where", "local", "--host", "10.0.0.5"], capsys) + assert env["ok"] is True, env + assert env["data"]["url"] == "http://10.0.0.5:7777/models" + + def test_ipv6_host_is_bracketed_in_the_url(self, monkeypatch, capsys): + monkeypatch.delenv("COMFY_LOCAL_URL", raising=False) + _patch_urlopen(monkeypatch, {"[::1]:8189/models": _LOCAL_FOLDERS}) + env = _run(["list-folders", "--where", "local", "--host", "::1", "--port", "8189"], capsys) + assert env["ok"] is True, env + assert env["data"]["url"] == "http://[::1]:8189/models" + + def test_search_threads_host_port_to_resolve_target(self, monkeypatch, capsys): + # The other verbs route through the same helper; assert `search` in + # particular hands the pair to `resolve_target`. + from comfy_cli.target import Target + + seen: dict[str, Any] = {} + + def fake_resolve_target(**kwargs): + seen.update(kwargs) + return Target( + kind="local", + base_url="http://10.0.0.5:9999", + path_prefix="", + history_path="history", + host="10.0.0.5", + port=9999, + ) + + monkeypatch.setattr("comfy_cli.target.resolve_target", fake_resolve_target) + _patch_urlopen(monkeypatch, {"10.0.0.5:9999/models/loras": _LOCAL_FILES_BY_FOLDER["loras"]}) + env = _run( + ["search", "--text", "ltx", "--type", "lora", "--where", "local", "--host", "10.0.0.5", "--port", "9999"], + capsys, + ) + assert env["ok"] is True, env + assert seen["host"] == "10.0.0.5" + assert seen["port"] == 9999 + assert seen["where"] == "local" + + +class TestHostPortCloudRejection: + """``--host``/``--port`` name a LOCAL server, so pairing them with an + effective cloud target is a structured usage error rather than a silently + ignored flag — the comfy-mcp root cause this ticket fixes.""" + + @pytest.mark.parametrize( + "args", + [ + ["list-folders", "--where", "cloud", "--host", "10.0.0.5"], + ["list-folders", "--where", "cloud", "--port", "9999"], + ["list-folder", "loras", "--where", "cloud", "--host", "10.0.0.5"], + ["search", "--where", "cloud", "--host", "10.0.0.5", "--port", "9999"], + ["show", "flux1-dev.safetensors", "--where", "cloud", "--port", "9999"], + ], + ) + def test_host_or_port_with_cloud_where_flag_is_rejected(self, args, monkeypatch, capsys): + # urlopen must never be reached: the rejection fires before routing. + _patch_urlopen(monkeypatch, {}) + env = _run(args, capsys) + assert env["ok"] is False, env + assert env["error"]["code"] == "host_flag_cloud" + + def test_cloud_where_env_is_rejected_and_names_the_source(self, monkeypatch, capsys): + # COMFY_WHERE is how a top-level `comfy --where cloud` arrives, so the + # guard keys off the RESOLVED target, not the flag. + monkeypatch.setenv("COMFY_WHERE", "cloud") + _patch_urlopen(monkeypatch, {}) + env = _run(["search", "--host", "10.0.0.5"], capsys) + assert env["ok"] is False, env + assert env["error"]["code"] == "host_flag_cloud" + assert "COMFY_WHERE" in env["error"]["message"] + assert env["error"]["details"]["where_source"] == "env" + + +class TestHostPortUsageErrors: + """A bad ``--host``/``--port`` is a usage error (exit 2), validated the same + way ``comfy upload`` validates its flags, before any request is made.""" + + @pytest.fixture + def runner(self): + return CliRunner() + + @pytest.mark.parametrize( + "bad", + [ + "evil/host", + "user@evil", + "host?x", + "host#x", + "host\rname", + "host\nname", + "", + " ", + "a%0d%0aX-Injected:%201", + "host%2fpath", + "127.0.0.1:8188", + "localhost:8188", + ], + ) + def test_invalid_host_is_a_usage_error(self, runner, bad): + # typer.BadParameter -> click UsageError -> exit code 2. + result = runner.invoke(search_cmd.app, ["list-folders", "--where", "local", "--host", bad]) + assert result.exit_code == 2, result.output + + @pytest.mark.parametrize("bad", ["0", "65536", "-1"]) + def test_out_of_range_port_is_a_usage_error(self, runner, bad): + result = runner.invoke(search_cmd.app, ["list-folders", "--where", "local", "--port", bad]) + assert result.exit_code == 2, result.output + + @pytest.mark.parametrize("good", ["::1", "[::1]", "fe80::1"]) + def test_ipv6_literal_host_is_accepted(self, good, monkeypatch, capsys): + monkeypatch.delenv("COMFY_LOCAL_URL", raising=False) + bracketed = good if good.startswith("[") else f"[{good}]" + _patch_urlopen(monkeypatch, {f"{bracketed}:8188/models": _LOCAL_FOLDERS}) + env = _run(["list-folders", "--where", "local", "--host", good], capsys) + assert env["ok"] is True, env + assert env["data"]["url"] == f"http://{bracketed}:8188/models" From 4806d89b6071510444ac095b9d1dbfbc8dda0a11 Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Thu, 8 Oct 2026 01:54:18 +0000 Subject: [PATCH 2/5] fix(models): keep defensive where config read; harden --host validation - _resolve_and_stamp now resolves routing via where.resolve_default_or_exit, restoring the broken-config fallback resolve_target had and giving where_invalid a hint that names every routing source. - Stamp the subcommand on the renderer so host_port_invalid, where_invalid and host_flag_cloud envelopes carry the same `command` as success. - validate_host rejects stray brackets ('[localhost]', 'a]b') and hosts the IDNA codec cannot encode, which previously escaped as raw tracebacks. - Clarify --host/--port help on `models show` (cloud-only verb). - Drop internal ticket IDs from comments (public-repo hygiene). Co-Authored-By: Claude Opus 5.5 --- comfy_cli/command/models/search.py | 44 +++++++++++------- comfy_cli/host_port.py | 27 +++++++++++ tests/comfy_cli/command/models/test_search.py | 46 ++++++++++++++++++- tests/comfy_cli/test_host_port.py | 12 +++++ 4 files changed, 111 insertions(+), 18 deletions(-) diff --git a/comfy_cli/command/models/search.py b/comfy_cli/command/models/search.py index e2996ad3f..c6a39f4b2 100644 --- a/comfy_cli/command/models/search.py +++ b/comfy_cli/command/models/search.py @@ -182,7 +182,7 @@ def _emit_http_error(e: urllib.error.HTTPError, *, renderer, target, message: st # How a `cloud` routing decision was reached, in words, for the --host/--port # rejection message. Keys are `where.WhereResolution.source` values. Mirrors the -# copy `cmdline.upload` uses (BE-5662) — kept local rather than imported so this +# copy `cmdline.upload` uses — kept local rather than imported so this # module stays free of a `cmdline` import cycle. _WHERE_SOURCE_PHRASES = { "flag": "targeting cloud via --where cloud", @@ -193,7 +193,7 @@ def _emit_http_error(e: urllib.error.HTTPError, *, renderer, target, message: st } -def _resolve_and_stamp(renderer, where: str | None, *, host: str | None = None, port: int | None = None): +def _resolve_and_stamp(renderer, where: str | None, *, command: str, host: str | None = None, port: int | None = None): """Resolve the routing Target for a ``models`` verb and stamp it on the renderer. Every verb here calls this at the point it decides local-vs-cloud, so the @@ -203,7 +203,7 @@ def _resolve_and_stamp(renderer, where: str | None, *, host: str | None = None, ``emit(..., where=...)`` arguments still take precedence over the stamp. ``host``/``port`` route a **local** ``models`` query at a specific ComfyUI - (the ``--host``/``--port`` flags), mirroring ``comfy upload`` (BE-5662): + (the ``--host``/``--port`` flags), mirroring ``comfy upload``: they are validated the same way, rejected against an effective ``cloud`` target, and otherwise handed to ``resolve_target``, which applies the local precedence explicit flag > ``COMFY_LOCAL_URL`` > ``127.0.0.1:8188``. With @@ -215,10 +215,15 @@ def _resolve_and_stamp(renderer, where: str | None, *, host: str | None = None, the configured remote target. """ from comfy_cli import where as where_module - from comfy_cli.config_manager import ConfigManager from comfy_cli.host_port import report_usage_error, validate_host from comfy_cli.target import resolve_target + # Stamp the subcommand too, so every failure envelope from here down — + # the usage-error, ``where_invalid`` and ``host_flag_cloud`` rejections + # and the verb's own downstream errors — names the same ``command`` as + # the verb's success envelope rather than the renderer's group default. + renderer.command = command + # Validate the flags before resolving anything: the host lands verbatim in # ``http://{host}:{port}/...``, so a URL-special or control character is a # usage error (BadParameter, exit 2) regardless of target. Port range is @@ -231,13 +236,12 @@ def _resolve_and_stamp(renderer, where: str | None, *, host: str | None = None, if port is not None and not (1 <= port <= 65535): raise typer.BadParameter(f"invalid port: {port} is out of range (1-65535)") - try: - decision = where_module.resolve( - flag=where, config_value=ConfigManager().get(where_module.CONFIG_KEY_WHERE_DEFAULT) - ) - except ValueError as e: - renderer.error(code="where_invalid", message=str(e), hint="use --where local or --where cloud") - raise typer.Exit(code=1) from e + # ``resolve_default_or_exit`` reads the persisted ``where_default`` + # defensively (a broken config drops to the next precedence source, as + # ``resolve_target`` did before these flags existed) and turns a bad + # --where / COMFY_WHERE / project / config value into a ``where_invalid`` + # envelope whose hint names all of those sources. + decision = where_module.resolve_default_or_exit(flag=where) effective_where = "cloud" if decision.target is where_module.WhereTarget.CLOUD else "local" # Routing is decided, so every error envelope from here down can name the @@ -296,7 +300,7 @@ def list_folders_cmd( ] = None, ): renderer = get_renderer() - target = _resolve_and_stamp(renderer, where, host=host, port=port) + target = _resolve_and_stamp(renderer, where, command="models list-folders", host=host, port=port) url = target.url(*_models_path_parts(target)) try: @@ -380,7 +384,7 @@ def list_folder_cmd( ): renderer = get_renderer() _reject_unsafe_path_segment(folder, kind="folder", renderer=renderer) - target = _resolve_and_stamp(renderer, where, host=host, port=port) + target = _resolve_and_stamp(renderer, where, command="models list-folder", host=host, port=port) # Percent-encoded for the same reason `_local_folder_matches` does it: the # relaxed validation above admits spaces, `?`/`#`, and non-ASCII, none of # which may be allowed to alter the request. Error payloads below carry the @@ -843,7 +847,7 @@ def search_cmd( renderer = get_renderer() if type_ is not None: _reject_unsafe_path_segment(type_, kind="type", renderer=renderer) - target = _resolve_and_stamp(renderer, where, host=host, port=port) + target = _resolve_and_stamp(renderer, where, command="models search", host=host, port=port) try: if target.is_cloud: @@ -927,15 +931,21 @@ def show_cmd( ] = None, host: Annotated[ str | None, - typer.Option(help="Server host (defaults to COMFY_LOCAL_URL or 127.0.0.1). Local targets only."), + typer.Option( + help="Server host, for parity with the other `models` verbs. `show` needs the cloud asset " + "catalog, so a local target (including one named here) is reported as unsupported." + ), ] = None, port: Annotated[ int | None, - typer.Option(help="Server port (defaults to COMFY_LOCAL_URL or 8188). Local targets only."), + typer.Option( + help="Server port, for parity with the other `models` verbs. `show` needs the cloud asset " + "catalog, so a local target (including one named here) is reported as unsupported." + ), ] = None, ): renderer = get_renderer() - target = _resolve_and_stamp(renderer, where, host=host, port=port) + target = _resolve_and_stamp(renderer, where, command="models show", host=host, port=port) if not target.is_cloud: # On local there's no asset catalog. We can confirm the file exists by diff --git a/comfy_cli/host_port.py b/comfy_cli/host_port.py index d375702bc..257dba94b 100644 --- a/comfy_cli/host_port.py +++ b/comfy_cli/host_port.py @@ -117,9 +117,36 @@ def validate_host(host: str) -> str: if any(c.isspace() or ord(c) < 0x20 or ord(c) == 0x7F for c in candidate): raise typer.BadParameter(f"invalid host: {host!r} (contains whitespace or control characters)") _reject_embedded_port(host) + _reject_stray_brackets(host) + # The URL layer IDNA-encodes the host before connecting; a value it can't + # encode (an empty or over-long label, say) would otherwise escape as a + # raw ``UnicodeError`` traceback rather than a usage error. + try: + host.encode("idna") + except UnicodeError: + raise typer.BadParameter(f"invalid host: {host!r} (not a valid hostname)") from None return host +def _reject_stray_brackets(host: str) -> None: + """Reject ``[``/``]`` anywhere but around a genuine IPv6 literal. + + ``_reject_embedded_port`` only inspects colon-bearing hosts, so a + colon-free ``'[localhost]'`` or ``'a]b'`` slipped through and then made + ``urllib.parse.urlsplit`` raise ``ValueError("Invalid IPv6 URL")`` — an + uncaught traceback instead of a usage error. + """ + if "[" not in host and "]" not in host: + return + if host.startswith("[") and host.endswith("]"): + try: + ipaddress.IPv6Address(host[1:-1]) + return + except ValueError: + pass + raise typer.BadParameter(f"invalid host: {host!r} (brackets are only valid around an IPv6 literal)") + + def _reject_embedded_port(host: str) -> None: """Reject a colon in a host unless it's a genuine IPv6 literal. diff --git a/tests/comfy_cli/command/models/test_search.py b/tests/comfy_cli/command/models/test_search.py index 97c587243..b955d680e 100644 --- a/tests/comfy_cli/command/models/test_search.py +++ b/tests/comfy_cli/command/models/test_search.py @@ -1047,7 +1047,7 @@ def test_local_is_explicitly_unsupported(self, local_target, monkeypatch, capsys # --------------------------------------------------------------------------- -# --host/--port routing (BE-5788) — mirrors `comfy upload` (BE-5662) +# --host/--port routing — mirrors `comfy upload` # --------------------------------------------------------------------------- @@ -1169,6 +1169,43 @@ def test_cloud_where_env_is_rejected_and_names_the_source(self, monkeypatch, cap assert "COMFY_WHERE" in env["error"]["message"] assert env["error"]["details"]["where_source"] == "env" + def test_rejection_envelope_names_the_subcommand(self, monkeypatch, capsys): + # The shared helper stamps the verb, so the failure line carries the + # same ``command`` a consumer sees on that verb's success envelope. + _patch_urlopen(monkeypatch, {}) + env = _run(["list-folder", "loras", "--where", "cloud", "--host", "10.0.0.5"], capsys) + assert env["error"]["code"] == "host_flag_cloud" + assert env["command"] == "models list-folder" + + +class TestRoutingResolutionFallbacks: + """Routing resolution in ``_resolve_and_stamp`` keeps the defensive config + read ``resolve_target`` had before the --host/--port flags existed.""" + + def test_unreadable_config_falls_through_to_next_source(self, monkeypatch, capsys): + import configparser + + def broken_config(*_a, **_kw): + raise configparser.MissingSectionHeaderError("config.ini", 1, "garbage") + + monkeypatch.delenv("COMFY_LOCAL_URL", raising=False) + monkeypatch.delenv("COMFY_WHERE", raising=False) + monkeypatch.setattr("comfy_cli.config_manager.ConfigManager", broken_config) + _patch_urlopen(monkeypatch, {"127.0.0.1:8188/models": _LOCAL_FOLDERS}) + env = _run(["list-folders", "--where", "local"], capsys) + assert env["ok"] is True, env + assert env["data"]["url"] == "http://127.0.0.1:8188/models" + + def test_invalid_where_env_is_a_where_invalid_envelope(self, monkeypatch, capsys): + monkeypatch.setenv("COMFY_WHERE", "moon") + _patch_urlopen(monkeypatch, {}) + env = _run(["search", "--text", "x"], capsys) + assert env["ok"] is False, env + assert env["error"]["code"] == "where_invalid" + # The hint names every source a bad value can come from, not just --where. + assert "COMFY_WHERE" in env["error"]["hint"] + assert env["command"] == "models search" + class TestHostPortUsageErrors: """A bad ``--host``/``--port`` is a usage error (exit 2), validated the same @@ -1193,6 +1230,13 @@ def runner(self): "host%2fpath", "127.0.0.1:8188", "localhost:8188", + # Colon-free brackets used to slip past validation and crash + # urlsplit with "Invalid IPv6 URL"; an un-IDNA-encodable host used + # to escape as a raw UnicodeError. + "[localhost]", + "a]b", + "a" * 64 + ".example", + "a..b", ], ) def test_invalid_host_is_a_usage_error(self, runner, bad): diff --git a/tests/comfy_cli/test_host_port.py b/tests/comfy_cli/test_host_port.py index 1c610c46a..4e261f3c3 100644 --- a/tests/comfy_cli/test_host_port.py +++ b/tests/comfy_cli/test_host_port.py @@ -527,3 +527,15 @@ def test_report_usage_error_command_overrides_the_renderer_default(): with report_usage_error(r, command="jobs status"): raise typer.BadParameter("nope") assert json.loads(buf.getvalue().strip().splitlines()[-1])["command"] == "jobs status" + + +@pytest.mark.parametrize("host", ["[localhost]", "a]b", "[x", "[not-ipv6]"]) +def test_validate_host_rejects_stray_brackets(host): + with pytest.raises(typer.BadParameter, match="brackets"): + validate_host(host) + + +@pytest.mark.parametrize("host", ["a" * 64 + ".example", "a..b"]) +def test_validate_host_rejects_unencodable_hostnames(host): + with pytest.raises(typer.BadParameter, match="not a valid hostname"): + validate_host(host) From aafc4b7739cc9523f2e5d42c9f8a78dcc6038626 Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Thu, 8 Oct 2026 06:31:02 +0000 Subject: [PATCH 3/5] fix(host): reject hosts urlsplit rejects after NFKC normalization IDNA encoding accepts a fullwidth slash (it folds to '/'), but urlsplit raises ValueError on it, which escaped the models commands as a traceback. Validate the URL callers build and surface a usage error instead. Co-Authored-By: Claude Opus 5.5 --- comfy_cli/host_port.py | 9 +++++++++ tests/comfy_cli/test_host_port.py | 7 ++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/comfy_cli/host_port.py b/comfy_cli/host_port.py index 257dba94b..5e7a7f0fd 100644 --- a/comfy_cli/host_port.py +++ b/comfy_cli/host_port.py @@ -125,6 +125,15 @@ def validate_host(host: str) -> str: host.encode("idna") except UnicodeError: raise typer.BadParameter(f"invalid host: {host!r} (not a valid hostname)") from None + # IDNA encoding is not a URL-parser pass: ``urlsplit`` NFKC-normalizes the + # netloc and rejects a fullwidth ``/`` (it folds to ``/``) that IDNA lets + # through, so check the URL the callers will build as well. + from comfy_cli.env_checker import _bracket_host + + try: + urllib.parse.urlsplit(f"http://{_bracket_host(host)}:{DEFAULT_PORT}/") + except ValueError: + raise typer.BadParameter(f"invalid host: {host!r} (not a valid hostname)") from None return host diff --git a/tests/comfy_cli/test_host_port.py b/tests/comfy_cli/test_host_port.py index 4e261f3c3..caee0c4f7 100644 --- a/tests/comfy_cli/test_host_port.py +++ b/tests/comfy_cli/test_host_port.py @@ -535,7 +535,12 @@ def test_validate_host_rejects_stray_brackets(host): validate_host(host) -@pytest.mark.parametrize("host", ["a" * 64 + ".example", "a..b"]) +@pytest.mark.parametrize("host", ["a" * 64 + ".example", "a..b", "example\uff0ftest", "example\uff1ftest"]) def test_validate_host_rejects_unencodable_hostnames(host): with pytest.raises(typer.BadParameter, match="not a valid hostname"): validate_host(host) + + +@pytest.mark.parametrize("host", ["::1", "[::1]", "localhost", "127.0.0.1", "b\u00fccher.example"]) +def test_validate_host_accepts_url_parseable_hosts(host): + assert validate_host(host) == host From ada92ddbbfc1284ba487963ca4e23e3333a744ad Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Tue, 17 Nov 2026 00:06:55 +0000 Subject: [PATCH 4/5] fix(models): forward --host as its ASCII IDNA form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit validate_host only checks that a host can be IDNA-encoded and returns the Unicode form; urllib copies the authority into the Host header, which http.client encodes as Latin-1, so `--host 例え.test` raised an uncaught UnicodeEncodeError before connecting. Convert non-ASCII hosts to punycode in _resolve_and_stamp and add a regression test at the opener boundary. Co-Authored-By: Claude Opus 5.5 --- comfy_cli/command/models/search.py | 8 ++++++++ tests/comfy_cli/command/models/test_search.py | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/comfy_cli/command/models/search.py b/comfy_cli/command/models/search.py index c6a39f4b2..3c38e32d4 100644 --- a/comfy_cli/command/models/search.py +++ b/comfy_cli/command/models/search.py @@ -233,6 +233,14 @@ def _resolve_and_stamp(renderer, where: str | None, *, command: str, host: str | with report_usage_error(renderer): if host is not None: host = validate_host(host) + # ``validate_host`` only proves the host *can* be IDNA-encoded; it + # hands back the Unicode form. ``urllib`` copies the URL authority + # into the ``Host`` header, which ``http.client`` encodes as + # Latin-1, so ``--host 例え.test`` would raise an uncaught + # ``UnicodeEncodeError`` before connecting. Forward the ASCII + # (punycode) form instead; IP literals are already ASCII. + if not host.isascii(): + host = host.encode("idna").decode("ascii") if port is not None and not (1 <= port <= 65535): raise typer.BadParameter(f"invalid port: {port} is out of range (1-65535)") diff --git a/tests/comfy_cli/command/models/test_search.py b/tests/comfy_cli/command/models/test_search.py index b955d680e..19f2427d1 100644 --- a/tests/comfy_cli/command/models/test_search.py +++ b/tests/comfy_cli/command/models/test_search.py @@ -1106,6 +1106,22 @@ def test_ipv6_host_is_bracketed_in_the_url(self, monkeypatch, capsys): assert env["ok"] is True, env assert env["data"]["url"] == "http://[::1]:8189/models" + def test_unicode_host_is_forwarded_as_idna_ascii(self, monkeypatch, capsys): + # urllib copies the authority into the Host header, which http.client + # encodes as Latin-1 — a raw Unicode host would raise UnicodeEncodeError + # before connecting. The request reaching the opener must carry the + # punycode form, and its Host header must encode the way http.client does. + import urllib.request + + monkeypatch.delenv("COMFY_LOCAL_URL", raising=False) + ascii_host = "例え.test".encode("idna").decode("ascii") + calls = _patch_urlopen(monkeypatch, {f"{ascii_host}:8188/models/loras": _LOCAL_FILES_BY_FOLDER["loras"]}) + env = _run(["search", "--where", "local", "--host", "例え.test", "--type", "lora"], capsys) + assert env["ok"] is True, env + url = calls[0]["url"] + assert url == f"http://{ascii_host}:8188/models/loras" + urllib.request.Request(url).host.encode("latin-1") + def test_search_threads_host_port_to_resolve_target(self, monkeypatch, capsys): # The other verbs route through the same helper; assert `search` in # particular hands the pair to `resolve_target`. From a9d7e7f18b823899c34b4562ed6ff20f55cf16ac Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Tue, 17 Nov 2026 00:27:07 +0000 Subject: [PATCH 5/5] fix(models): validate the IDNA-converted --host too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit IDNA's NFKC step can fold characters into ones validate_host rejects: fullwidth % becomes %, so localhost%0d%0a turned into a percent-encoded CRLF that escaped as a request-layer traceback instead of the host_port_invalid usage envelope. Re-validate the ASCII form. Co-Authored-By: Claude Opus 5.5 --- comfy_cli/command/models/search.py | 7 +++++-- tests/comfy_cli/command/models/test_search.py | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/comfy_cli/command/models/search.py b/comfy_cli/command/models/search.py index 3c38e32d4..20bc8dda4 100644 --- a/comfy_cli/command/models/search.py +++ b/comfy_cli/command/models/search.py @@ -238,9 +238,12 @@ def _resolve_and_stamp(renderer, where: str | None, *, command: str, host: str | # into the ``Host`` header, which ``http.client`` encodes as # Latin-1, so ``--host 例え.test`` would raise an uncaught # ``UnicodeEncodeError`` before connecting. Forward the ASCII - # (punycode) form instead; IP literals are already ASCII. + # (punycode) form instead; IP literals are already ASCII. IDNA's + # NFKC step can fold characters into ones ``validate_host`` rejects + # (fullwidth ``%`` becomes ``%``, so ``localhost%0d%0a`` turns into + # a percent-encoded CRLF), so validate the converted form too. if not host.isascii(): - host = host.encode("idna").decode("ascii") + host = validate_host(host.encode("idna").decode("ascii")) if port is not None and not (1 <= port <= 65535): raise typer.BadParameter(f"invalid port: {port} is out of range (1-65535)") diff --git a/tests/comfy_cli/command/models/test_search.py b/tests/comfy_cli/command/models/test_search.py index 19f2427d1..e2a71a762 100644 --- a/tests/comfy_cli/command/models/test_search.py +++ b/tests/comfy_cli/command/models/test_search.py @@ -1122,6 +1122,24 @@ def test_unicode_host_is_forwarded_as_idna_ascii(self, monkeypatch, capsys): assert url == f"http://{ascii_host}:8188/models/loras" urllib.request.Request(url).host.encode("latin-1") + def test_host_whose_idna_form_is_unsafe_is_a_usage_error(self, monkeypatch, capsys): + # Fullwidth ``%`` NFKC-folds to ``%`` during IDNA conversion, so the + # ASCII form carries a percent-encoded CRLF the Unicode input did not. + # It must surface as the host_port_invalid usage envelope, not escape + # from the request layer as a traceback. + monkeypatch.delenv("COMFY_LOCAL_URL", raising=False) + calls = _patch_urlopen(monkeypatch, {}) + _force_json_renderer() + result = CliRunner().invoke( + search_cmd.app, ["search", "--where", "local", "--host", "localhost%0d%0a", "--type", "lora"] + ) + assert result.exit_code == 2, result.output + out = capsys.readouterr().out or result.stdout + env = json.loads(out.strip().splitlines()[-1]) + assert env["ok"] is False + assert env["error"]["code"] == "host_port_invalid" + assert calls == [] + def test_search_threads_host_port_to_resolve_target(self, monkeypatch, capsys): # The other verbs route through the same helper; assert `search` in # particular hands the pair to `resolve_target`.