Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(explorer): reject unsupported port zero before startup (#1990)

Alvaro Balbin84e67484e92f
diff --git a/semantica/cli.py b/semantica/cli.py
index 3937c689..62a97d75 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -5877,7 +5877,7 @@ def explorer(ctx: click.Context) -> None:
@explorer.command("start")
[email protected]("--port", default=5173, type=int, show_default=True)
[email protected]("--port", default=5173, type=click.IntRange(1, 65535), show_default=True)
@click.option("--api-url", default="http://localhost:8000", show_default=True)
@click.option("--graph", default=None, type=click.Path(exists=True),
help="Optional graph JSON file to preload.")
@@ -5931,7 +5931,7 @@ def explorer_status(cli_ctx: CLIContext, local_json: bool) -> None:
@explorer.command("open")
[email protected]("--port", default=5173, type=int, show_default=True)
[email protected]("--port", default=5173, type=click.IntRange(1, 65535), show_default=True)
@click.pass_obj
def explorer_open(cli_ctx: CLIContext, port: int) -> None:
"""Open the Explorer in the default browser."""
diff --git a/semantica/explorer/__init__.py b/semantica/explorer/__init__.py
index 7ed90c15..44c2538a 100644
--- a/semantica/explorer/__init__.py
+++ b/semantica/explorer/__init__.py
@@ -32,6 +32,22 @@ def _browser_origin(host, port):
return f"http://{host}:{port}"
+def _port(value):
+ """Validate ``--port`` as an integer in the 1-65535 range.
+
+ ``--port 0`` is rejected here: with port 0 the OS picks the port only
+ after the allowlist and the browser URL have been built, so neither can
+ ever use it. Out-of-range values (negatives, more than 65535) are
+ rejected too, instead of reaching uvicorn and failing there.
+ """
+ port = int(value)
+ if not 1 <= port <= 65535:
+ raise argparse.ArgumentTypeError(
+ "port must be an integer from 1 to 65535"
+ )
+ return port
+
+
def main(argv=None):
"""CLI entry point for the Knowledge Explorer server."""
parser = argparse.ArgumentParser(
@@ -45,9 +61,9 @@ def main(argv=None):
)
parser.add_argument(
"--port", "-p",
- type=int,
+ type=_port,
default=8000,
- help="Port to bind the server to (default: 8000).",
+ help="Port to bind the server to, 1-65535 (default: 8000).",
)
parser.add_argument(
"--host",
@@ -61,7 +77,6 @@ def main(argv=None):
)
args = parser.parse_args(argv)
-
import os
if not os.path.isfile(args.graph):
_err.print(f"[bold red]Error:[/bold red] graph file not found: {args.graph}")
@@ -91,17 +106,14 @@ def main(argv=None):
allowed_origins = None
if "ALLOWED_ORIGINS" not in os.environ and "EXPLORER_CORS_ORIGINS" not in os.environ:
default_origins = ["http://localhost:5173", "http://127.0.0.1:5173"]
- # With --port 0 the OS picks the port after this list is built, so
- # there is no port to allow here.
- if args.port != 0:
- default_origins += [
- _browser_origin("localhost", args.port),
- _browser_origin("127.0.0.1", args.port),
- ]
- # A non-loopback --host is also allowed as an origin, so a browser
- # opened on the address the Explorer is reached at can connect.
- if args.host not in ("127.0.0.1", "localhost", "0.0.0.0", "::1", "::"):
- default_origins.append(_browser_origin(args.host, args.port))
+ default_origins += [
+ _browser_origin("localhost", args.port),
+ _browser_origin("127.0.0.1", args.port),
+ ]
+ # A non-loopback --host is also allowed as an origin, so a browser
+ # opened on the address the Explorer is reached at can connect.
+ if args.host not in ("127.0.0.1", "localhost", "0.0.0.0", "::1", "::"):
+ default_origins.append(_browser_origin(args.host, args.port))
allowed_origins = list(dict.fromkeys(default_origins))
app = create_app(session=session, allowed_origins=allowed_origins)
diff --git a/tests/explorer/test_explorer_entrypoints.py b/tests/explorer/test_explorer_entrypoints.py
index 1acc53cb..f355ac8e 100644
--- a/tests/explorer/test_explorer_entrypoints.py
+++ b/tests/explorer/test_explorer_entrypoints.py
@@ -264,6 +264,23 @@ def test_cli_main_configures_allowed_origins_for_custom_port(tmp_path, monkeypat
assert excinfo.value.code == 4403
[email protected]("port", ["0", "-1", "65536", "70000"])
+def test_cli_main_rejects_out_of_range_ports(tmp_path, monkeypatch, capsys, port):
+ graph_file = tmp_path / "test_graph.json"
+ graph_file.write_text('{"nodes": [], "edges": []}', encoding="utf-8")
+
+ from semantica.explorer import main
+ import uvicorn
+
+ monkeypatch.setattr(uvicorn, "run", lambda *args, **kwargs: None)
+
+ with pytest.raises(SystemExit) as excinfo:
+ main(["--graph", str(graph_file), "--port", port, "--no-browser"])
+
+ assert excinfo.value.code == 2
+ assert "port must be an integer from 1 to 65535" in capsys.readouterr().err
+
+
def test_cli_main_preserves_explicit_allowed_origins(tmp_path, monkeypatch):
"""Ensure explicit ALLOWED_ORIGINS is not overridden when --port is specified."""
monkeypatch.setenv("SEMANTICA_ALLOW_ANONYMOUS", "true")
@@ -327,14 +344,6 @@ def test_cli_main_brackets_an_ipv6_host_origin(tmp_path, monkeypatch):
assert "http://fe80::1:8020" not in origins
-def test_cli_main_skips_the_port_origins_for_port_zero(tmp_path, monkeypatch):
- """With --port 0 the OS picks the port later, so no :0 origin is added and
- the Vite defaults are kept."""
- origins = _cli_allowed_origins(tmp_path, monkeypatch, "--port", "0")
-
- assert origins == ["http://localhost:5173", "http://127.0.0.1:5173"]
-
-
def test_cli_main_opens_the_bracketed_url_for_an_ipv6_host(tmp_path, monkeypatch):
"""The browser is opened at the URL whose origin the CLI allows, so an IPv6
host is bracketed there too."""