Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(explorer): legacy server origins, CLI origin edge cases, test isolation and lint (#1970)

Roshan Banisetti67dcecb86643
diff --git a/docs/cli-setup.md b/docs/cli-setup.md
index c401eeec..44d6617c 100644
--- a/docs/cli-setup.md
+++ b/docs/cli-setup.md
@@ -150,7 +150,7 @@ python -c "import semantica; print(semantica.__version__)"
| Variable | Default | Description |
| :-------- | :------- | :----------- |
-| `SEMANTICA_CORS_ORIGINS` | `http://localhost:5173,http://127.0.0.1:5173` | Comma-separated list of allowed CORS origins |
+| `SEMANTICA_CORS_ORIGINS` | `http://localhost:5173,http://127.0.0.1:5173,http://localhost:8000,http://127.0.0.1:8000` | Comma-separated list of allowed CORS and WebSocket origins. The default covers the Vite dev server and the server's own port, so a browser opened on `127.0.0.1:8000` can open the WebSocket; setting it replaces the default |
No other environment variables are read by these commands.
diff --git a/docs/explorer-setup.md b/docs/explorer-setup.md
index 08d40532..c2a27536 100644
--- a/docs/explorer-setup.md
+++ b/docs/explorer-setup.md
@@ -166,7 +166,7 @@ semantica-explorer --graph my_graph.json --no-browser
</Warning>
<Tip>
- **CORS and WebSocket Origins:** `semantica-explorer` automatically allows browser connections from `localhost` and `127.0.0.1` on the configured `--port` (and Vite dev port `5173`). To allow external browser origins or custom domains for both HTTP CORS and `/ws/graph-updates` WebSocket connections, set the `ALLOWED_ORIGINS` environment variable (e.g. `ALLOWED_ORIGINS="https://explorer.example.com"`). An origin not in the allowlist causes the WebSocket handshake to fail with HTTP 403; add the origin to `ALLOWED_ORIGINS` to resolve this for custom or external clients. `EXPLORER_CORS_ORIGINS` is also supported as a legacy alias.
+ **CORS and WebSocket Origins:** `semantica-explorer` automatically allows browser connections from `localhost` and `127.0.0.1` on the configured `--port` (and Vite dev port `5173`). When `--host` is not a loopback address, `http://<host>:<port>` is allowed too, so a browser opened on the address the Explorer is served at can connect; an IPv6 host is written in brackets, as a browser sends it (`--host fe80::1` allows `http://[fe80::1]:<port>`). With `--port 0` the operating system picks the port after start-up, so no port origin is added: set `ALLOWED_ORIGINS` to include it. To allow external browser origins or custom domains for both HTTP CORS and `/ws/graph-updates` WebSocket connections, set the `ALLOWED_ORIGINS` environment variable (e.g. `ALLOWED_ORIGINS="https://explorer.example.com"`). An origin not in the allowlist causes the WebSocket handshake to fail with HTTP 403; add the origin to `ALLOWED_ORIGINS` to resolve this for custom or external clients. `EXPLORER_CORS_ORIGINS` is also supported as a legacy alias.
</Tip>
diff --git a/docs/reference/explorer.md b/docs/reference/explorer.md
index b00a577b..e1197e29 100644
--- a/docs/reference/explorer.md
+++ b/docs/reference/explorer.md
@@ -102,7 +102,9 @@ The `semantica-explorer` command accepts exactly four flags:
<Note>
There are no flags for authentication, CORS, or log level in the CLI. Allowed origins for HTTP CORS and WebSocket handshakes (`/ws/graph-updates`) are configured via the `ALLOWED_ORIGINS` environment variable (comma-separated). `EXPLORER_CORS_ORIGINS` is also supported as a legacy alias.
- When launching via `semantica-explorer` without explicit environment variables, the server automatically allows connections from `localhost` and `127.0.0.1` on the configured `--port` (default: `8000`), in addition to local frontend development origins (`http://localhost:5173,http://127.0.0.1:5173`).
+ When launching via `semantica-explorer` without explicit environment variables, the server automatically allows connections from `localhost` and `127.0.0.1` on the configured `--port` (default: `8000`), in addition to local frontend development origins (`http://localhost:5173,http://127.0.0.1:5173`). When `--host` is not a loopback address, `http://<host>:<port>` is allowed as well, with an IPv6 host in brackets (`http://[fe80::1]:<port>`). With `--port 0` the operating system picks the port after start-up, so no port origin is added; set `ALLOWED_ORIGINS` to include it.
+
+ Without the CLI, `create_app()` uses the same default for every caller, including the module-level `app`, the Docker image and programmatic use: `localhost` and `127.0.0.1` on ports `5173` and `8000`, whatever port the app is actually served on. Those origins are local only, and the API key still protects the endpoints. Set `ALLOWED_ORIGINS` to replace the default.
</Note>
<Tip>
diff --git a/semantica/explorer/__init__.py b/semantica/explorer/__init__.py
index e1d58564..7ed90c15 100644
--- a/semantica/explorer/__init__.py
+++ b/semantica/explorer/__init__.py
@@ -21,6 +21,17 @@ _out = Console()
_err = Console(stderr=True)
+def _browser_origin(host, port):
+ """The Origin a browser sends for a page served from ``host``:``port``.
+
+ An IPv6 literal is written in brackets, as it is in a URL, so
+ ``--host fe80::1`` gives ``http://[fe80::1]:<port>``.
+ """
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ return f"http://{host}:{port}"
+
+
def main(argv=None):
"""CLI entry point for the Knowledge Explorer server."""
parser = argparse.ArgumentParser(
@@ -79,19 +90,25 @@ 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",
- f"http://localhost:{args.port}",
- f"http://127.0.0.1:{args.port}",
- ]
- if args.host not in ("127.0.0.1", "localhost", "0.0.0.0", "::1", "::"):
- default_origins.append(f"http://{args.host}:{args.port}")
+ 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))
allowed_origins = list(dict.fromkeys(default_origins))
app = create_app(session=session, allowed_origins=allowed_origins)
- url = f"http://{args.host}:{args.port}"
+ # The page is served at its origin, so the URL the browser opens and the
+ # banner shows is written the same way (an IPv6 host in brackets).
+ url = _browser_origin(args.host, args.port)
_LOOPBACK_HOSTS = {"127.0.0.1", "::1", "localhost"}
if args.host not in _LOOPBACK_HOSTS:
diff --git a/semantica/server.py b/semantica/server.py
index dda76656..8e3d5ade 100644
--- a/semantica/server.py
+++ b/semantica/server.py
@@ -92,11 +92,16 @@ app = FastAPI(
)
# --- CORS -----------------------------------------------------------
-# Allow origins from environment (comma-separated); defaults to
-# localhost only so production deployments must configure this.
-_cors_origins_env = os.environ.get(
- "SEMANTICA_CORS_ORIGINS", "http://localhost:5173,http://127.0.0.1:5173"
+# Allow origins from environment (comma-separated). The default matches
+# semantica/explorer/app.py: the Vite dev server (5173) and this server's
+# own port (8000), on localhost and 127.0.0.1 only, so a browser opened on
+# the server can open its WebSocket. Production deployments must set
+# SEMANTICA_CORS_ORIGINS, which replaces the default entirely.
+_DEFAULT_CORS_ORIGINS = (
+ "http://localhost:5173,http://127.0.0.1:5173,"
+ "http://localhost:8000,http://127.0.0.1:8000"
)
+_cors_origins_env = os.environ.get("SEMANTICA_CORS_ORIGINS", _DEFAULT_CORS_ORIGINS)
_cors_origins = [o.strip() for o in _cors_origins_env.split(",") if o.strip()]
app.add_middleware(
CORSMiddleware,
diff --git a/tests/explorer/test_explorer_auth.py b/tests/explorer/test_explorer_auth.py
index 2a956e76..d483ce61 100644
--- a/tests/explorer/test_explorer_auth.py
+++ b/tests/explorer/test_explorer_auth.py
@@ -32,7 +32,12 @@ def _build_sample_graph() -> ContextGraph:
@pytest.fixture
-def client():
+def client(monkeypatch):
+ # create_app() reads the allowed origins from the environment, so an
+ # ALLOWED_ORIGINS or EXPLORER_CORS_ORIGINS exported in the developer's
+ # shell would replace the defaults these tests rely on.
+ monkeypatch.delenv("ALLOWED_ORIGINS", raising=False)
+ monkeypatch.delenv("EXPLORER_CORS_ORIGINS", raising=False)
session = GraphSession(_build_sample_graph())
app = create_app(session=session)
with TestClient(app) as test_client:
diff --git a/tests/explorer/test_explorer_entrypoints.py b/tests/explorer/test_explorer_entrypoints.py
index 8c971691..1acc53cb 100644
--- a/tests/explorer/test_explorer_entrypoints.py
+++ b/tests/explorer/test_explorer_entrypoints.py
@@ -3,7 +3,7 @@ import pytest
pytest.importorskip("fastapi")
from fastapi import FastAPI # noqa: E402
-from starlette.testclient import TestClient
+from starlette.testclient import TestClient # noqa: E402
from starlette.websockets import WebSocketDisconnect # noqa: E402
from semantica.context.context_graph import ContextGraph # noqa: E402
@@ -147,8 +147,73 @@ def test_legacy_server_mounts_editable_markdown_routes(monkeypatch):
assert saved.json()["body"] == "Updated server content"
+def reload_legacy_server(monkeypatch):
+ """Re-import ``semantica.server`` under the test's environment.
+
+ The legacy server reads ``SEMANTICA_CORS_ORIGINS`` once, at import, so a
+ test that changes it has to re-import the module. The fixture re-imports
+ it again after the environment is restored, so later tests see the
+ module as it is by default.
+ """
+ import importlib
+
+ from semantica import server
+
+ yield lambda: importlib.reload(server)
+ monkeypatch.undo()
+ importlib.reload(server)
+
+
+def _websocket_ack(client, origin):
+ with client.websocket_connect(
+ "/ws/graph-updates", headers={"Origin": origin}
+ ) as websocket:
+ return websocket.receive_json()["event"]
+
+
+def _websocket_close_code(client, origin):
+ with pytest.raises(WebSocketDisconnect) as excinfo:
+ with client.websocket_connect("/ws/graph-updates", headers={"Origin": origin}):
+ pass
+ return excinfo.value.code
+
+
+def test_legacy_server_accepts_websocket_from_its_own_port(
+ reload_legacy_server, monkeypatch
+):
+ """The legacy server listens on 8000, so a browser opened there must be able
+ to open the WebSocket, while other origins are still refused."""
+ monkeypatch.setenv("SEMANTICA_ALLOW_ANONYMOUS", "true")
+ monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)
+ monkeypatch.delenv("SEMANTICA_CORS_ORIGINS", raising=False)
+ server = reload_legacy_server()
+
+ with TestClient(server.app) as client:
+ for origin in ("http://localhost:8000", "http://127.0.0.1:8000"):
+ assert _websocket_ack(client, origin) == "connection_ack"
+ for origin in ("https://evil.example", "http://localhost:8001"):
+ assert _websocket_close_code(client, origin) == 4403
+
+
+def test_legacy_server_explicit_cors_origins_replace_the_default(
+ reload_legacy_server, monkeypatch
+):
+ """An explicit SEMANTICA_CORS_ORIGINS is the whole allowlist: the default
+ localhost:8000 origin is not added to it."""
+ monkeypatch.setenv("SEMANTICA_ALLOW_ANONYMOUS", "true")
+ monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)
+ monkeypatch.setenv("SEMANTICA_CORS_ORIGINS", "https://custom.example.com")
+ server = reload_legacy_server()
+
+ with TestClient(server.app) as client:
+ assert _websocket_ack(client, "https://custom.example.com") == "connection_ack"
+ assert _websocket_close_code(client, "http://localhost:8000") == 4403
+
+
def test_cli_main_configures_allowed_origins_for_custom_port(tmp_path, monkeypatch):
- """Regression test for #1257: semantica-explorer --port 8020 includes port in allowed_origins."""
+ """Regression test for #1257: semantica-explorer --port 8020 includes the port in
+ allowed_origins."""
monkeypatch.setenv("SEMANTICA_ALLOW_ANONYMOUS", "true")
monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)
monkeypatch.delenv("ALLOWED_ORIGINS", raising=False)
@@ -157,9 +222,10 @@ def test_cli_main_configures_allowed_origins_for_custom_port(tmp_path, monkeypat
graph_file = tmp_path / "test_graph.json"
graph_file.write_text('{"nodes": [], "edges": []}', encoding="utf-8")
- from semantica.explorer import main
import uvicorn
+ from semantica.explorer import main
+
captured_app = None
captured_kwargs = {}
@@ -173,8 +239,14 @@ def test_cli_main_configures_allowed_origins_for_custom_port(tmp_path, monkeypat
main(["--graph", str(graph_file), "--port", "8020", "--no-browser"])
assert captured_kwargs["port"] == 8020
- assert "http://127.0.0.1:8020" in captured_app.state.explorer_settings["allowed_origins"]
- assert "http://localhost:8020" in captured_app.state.explorer_settings["allowed_origins"]
+ assert (
+ "http://127.0.0.1:8020"
+ in captured_app.state.explorer_settings["allowed_origins"]
+ )
+ assert (
+ "http://localhost:8020"
+ in captured_app.state.explorer_settings["allowed_origins"]
+ )
with TestClient(captured_app) as client:
with client.websocket_connect(
@@ -202,9 +274,10 @@ def test_cli_main_preserves_explicit_allowed_origins(tmp_path, monkeypatch):
graph_file = tmp_path / "test_graph.json"
graph_file.write_text('{"nodes": [], "edges": []}', encoding="utf-8")
- from semantica.explorer import main
import uvicorn
+ from semantica.explorer import main
+
captured_app = None
def mock_run(app, **kwargs):
@@ -218,3 +291,70 @@ def test_cli_main_preserves_explicit_allowed_origins(tmp_path, monkeypatch):
assert captured_app.state.explorer_settings["allowed_origins"] == [
"https://custom.example.com"
]
+
+
+def _cli_allowed_origins(tmp_path, monkeypatch, *args, browser=False):
+ """Run ``semantica-explorer`` with ``args`` and return the app's origins.
+
+ ``browser=True`` leaves the browser auto-open on, for a test that patches it.
+ """
+ monkeypatch.setenv("SEMANTICA_ALLOW_ANONYMOUS", "true")
+ monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)
+ monkeypatch.delenv("ALLOWED_ORIGINS", raising=False)
+ monkeypatch.delenv("EXPLORER_CORS_ORIGINS", raising=False)
+ graph_file = tmp_path / "test_graph.json"
+ graph_file.write_text('{"nodes": [], "edges": []}', encoding="utf-8")
+
+ import uvicorn
+
+ from semantica.explorer import main
+
+ captured = {}
+ monkeypatch.setattr(uvicorn, "run", lambda app, **kwargs: captured.update(app=app))
+ flags = [] if browser else ["--no-browser"]
+ main(["--graph", str(graph_file), *flags, *args])
+ return captured["app"].state.explorer_settings["allowed_origins"]
+
+
+def test_cli_main_brackets_an_ipv6_host_origin(tmp_path, monkeypatch):
+ """A browser sends an IPv6 origin in brackets, so --host fe80::1 must give
+ http://[fe80::1]:<port>, not an origin that can never match."""
+ origins = _cli_allowed_origins(
+ tmp_path, monkeypatch, "--host", "fe80::1", "--port", "8020"
+ )
+
+ assert "http://[fe80::1]:8020" in origins
+ 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."""
+ import threading
+ import webbrowser
+
+ class _RunNow:
+ def __init__(self, _delay, function):
+ self.function = function
+
+ def start(self):
+ self.function()
+
+ opened = []
+ monkeypatch.setattr(threading, "Timer", _RunNow)
+ monkeypatch.setattr(webbrowser, "open", opened.append)
+
+ origins = _cli_allowed_origins(
+ tmp_path, monkeypatch, "--host", "fe80::1", "--port", "8020", browser=True
+ )
+
+ assert opened == ["http://[fe80::1]:8020"]
+ assert opened[0] in origins