Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(explorer): allow WebSocket origin on configured port (#1919)
Sameer Kadam5115dc322d59
diff --git a/docs/explorer-setup.md b/docs/explorer-setup.mdindex b21e2a3f..08d40532 100644--- a/docs/explorer-setup.md+++ b/docs/explorer-setup.md@@ -165,6 +165,10 @@ semantica-explorer --graph my_graph.json --no-browser`--host 0.0.0.0` makes Explorer reachable on every network interface. Since v0.6.5 the Explorer API requires `SEMANTICA_API_KEY` (sent as the `X-API-Key` header) and fails closed with `503` when unconfigured; unauthenticated access is only possible when `SEMANTICA_ALLOW_ANONYMOUS=true` is set explicitly. Only use this on a trusted private network.</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.+</Tip>+## Browser Accessdiff --git a/docs/reference/explorer.md b/docs/reference/explorer.mdindex eb56c545..b00a577b 100644--- a/docs/reference/explorer.md+++ b/docs/reference/explorer.md@@ -100,16 +100,18 @@ The `semantica-explorer` command accepts exactly four flags:| `--no-browser` |: | off | Skip auto-opening the browser tab |<Note>- There are no flags for authentication, CORS, or log level in the CLI. CORS allowed origins are configured via the `EXPLORER_CORS_ORIGINS` environment variable (comma-separated, default: `http://localhost:5173,http://127.0.0.1:5173`).+ 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`).</Note><Tip>- **CORS origins are configured via environment variable.** Set `EXPLORER_CORS_ORIGINS` to a comma-separated list of allowed origins before launching (e.g. `EXPLORER_CORS_ORIGINS="http://myapp.example.com"`).+ **Origins are configured via environment variable.** To allow external or custom browser origins for both REST API CORS and real-time graph updates over WebSocket (`/ws/graph-updates`), set `ALLOWED_ORIGINS` (or `EXPLORER_CORS_ORIGINS`) to a comma-separated list of allowed origins before launching (e.g. `ALLOWED_ORIGINS="http://myapp.example.com"`). When explicitly set, only the specified origins are allowed.</Tip>```bash# Full example-EXPLORER_CORS_ORIGINS="http://myapp.example.com" \+ALLOWED_ORIGINS="http://myapp.example.com" \semantica-explorer --graph my_graph.json --host 0.0.0.0 --port 8080 --no-browser```diff --git a/explorer/README.md b/explorer/README.mdindex 7e579814..f5e68ecf 100644--- a/explorer/README.md+++ b/explorer/README.md@@ -148,7 +148,8 @@ This writes the compiled assets to `../semantica/static/`. The Python server the| Variable | Default | Description || --- | --- | --- |-| `EXPLORER_CORS_ORIGINS` | `http://localhost:5173,http://127.0.0.1:5173` | Comma-separated list of allowed CORS origins |+| `ALLOWED_ORIGINS` | `http://localhost:5173,http://127.0.0.1:5173,http://localhost:8000,http://127.0.0.1:8000` | Comma-separated list of allowed origins for HTTP CORS and `/ws/graph-updates` WebSocket handshakes. When launched via `semantica-explorer`, the bound `--port` is automatically included unless an explicit allowlist is configured. |+| `EXPLORER_CORS_ORIGINS` | *(falls back to `ALLOWED_ORIGINS`)* | Legacy alias for `ALLOWED_ORIGINS` (supported for backward compatibility). || `EXPLORER_CORS_CREDENTIALS` | `false` | Set to `true` to allow credentialed cross-origin requests (only needed behind an authenticating reverse proxy) || `SEMANTICA_API_KEY` | *(unset)* | API key required on protected routes since v0.6.5; send it as the `X-API-Key` header. When unset, protected routes fail closed with `503`. || `SEMANTICA_ALLOW_ANONYMOUS` | `false` | Set to `true` to opt into unauthenticated access (local development only). |diff --git a/semantica/explorer/__init__.py b/semantica/explorer/__init__.pyindex f9a780fe..e1d58564 100644--- a/semantica/explorer/__init__.py+++ b/semantica/explorer/__init__.py@@ -77,7 +77,19 @@ def main(argv=None):f"[cyan]{stats.get('edge_count', 0)}[/cyan] edges")- app = create_app(session=session)+ 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}")+ allowed_origins = list(dict.fromkeys(default_origins))++ app = create_app(session=session, allowed_origins=allowed_origins)url = f"http://{args.host}:{args.port}"diff --git a/semantica/explorer/app.py b/semantica/explorer/app.pyindex 52d4548f..db34a800 100644--- a/semantica/explorer/app.py+++ b/semantica/explorer/app.py@@ -6,7 +6,7 @@ import asyncioimport osfrom contextlib import asynccontextmanagerfrom pathlib import Path-from typing import Optional+from typing import Optional, Sequencefrom fastapi import Depends, FastAPI, HTTPException, Requestfrom fastapi.middleware.cors import CORSMiddleware@@ -39,7 +39,10 @@ def _read_explorer_settings() -> dict:elif "EXPLORER_CORS_ORIGINS" in os.environ:raw_origins = os.environ["EXPLORER_CORS_ORIGINS"]else:- raw_origins = "http://localhost:5173,http://127.0.0.1:5173"+ raw_origins = (+ "http://localhost:5173,http://127.0.0.1:5173,"+ "http://localhost:8000,http://127.0.0.1:8000"+ )return {"allowed_origins": [origin.strip() for origin in raw_origins.split(",") if origin.strip()@@ -60,6 +63,7 @@ def create_app(session: Optional[GraphSession] = None,provenance_storage_path: Optional[str] = None,agent_memory: Optional[AgentMemory] = None,+ allowed_origins: Optional[Sequence[str]] = None,) -> FastAPI:"""Create an Explorer application over live graph and memory objects.@@ -69,11 +73,18 @@ def create_app(provenance_storage_path: Optional per-app provenance database path.agent_memory: Existing AgentMemory instance to expose in the Memoriesworkspace. The workspace is unavailable when omitted.+ allowed_origins: Optional custom sequence of allowed CORS/WebSocket+ origins. When omitted, origins are read from ALLOWED_ORIGINS (or+ EXPLORER_CORS_ORIGINS) or default to standard localhost origins.Returns:Configured FastAPI application."""settings = _read_explorer_settings()+ if allowed_origins is not None:+ settings["allowed_origins"] = [+ origin.strip() for origin in allowed_origins if origin.strip()+ ]prov_path = provenance_storage_path or settings.get("provenance_storage_path")if session is None:active_session = GraphSession(diff --git a/tests/explorer/test_explorer_api.py b/tests/explorer/test_explorer_api.pyindex dc8029f2..b69a7e51 100644--- a/tests/explorer/test_explorer_api.py+++ b/tests/explorer/test_explorer_api.py@@ -185,6 +185,29 @@ class TestHealthInfo:assert app.state.explorer_settings["allowed_origins"] == ["https://legacy.example.com"]+ def test_env_settings_default_allowed_origins(self, monkeypatch):+ monkeypatch.delenv("ALLOWED_ORIGINS", raising=False)+ monkeypatch.delenv("EXPLORER_CORS_ORIGINS", raising=False)++ app = create_app()++ assert app.state.explorer_settings["allowed_origins"] == [+ "http://localhost:5173",+ "http://127.0.0.1:5173",+ "http://localhost:8000",+ "http://127.0.0.1:8000",+ ]++ def test_create_app_explicit_allowed_origins_argument(self, monkeypatch):+ monkeypatch.delenv("ALLOWED_ORIGINS", raising=False)+ monkeypatch.delenv("EXPLORER_CORS_ORIGINS", raising=False)++ app = create_app(allowed_origins=["http://127.0.0.1:8020", "http://localhost:8020"])+ assert app.state.explorer_settings["allowed_origins"] == [+ "http://127.0.0.1:8020",+ "http://localhost:8020",+ ]+def test_default_app_initializes_empty_graph_session(self):with TestClient(create_app()) as test_client:response = test_client.get("/api/graph/nodes")diff --git a/tests/explorer/test_explorer_auth.py b/tests/explorer/test_explorer_auth.pyindex 3261d176..2a956e76 100644--- a/tests/explorer/test_explorer_auth.py+++ b/tests/explorer/test_explorer_auth.py@@ -22,6 +22,7 @@ from semantica.explorer.app import create_app # noqa: E402from semantica.explorer.session import GraphSession # noqa: E402from starlette.testclient import TestClient # noqa: E402+from starlette.websockets import WebSocketDisconnect # noqa: E402def _build_sample_graph() -> ContextGraph:@@ -224,3 +225,65 @@ def test_websocket_accepts_missing_origin_under_anonymous_mode(client, monkeypatwith client.websocket_connect("/ws/graph-updates") as websocket:ack = websocket.receive_json()assert ack["event"] == "connection_ack"+++def test_websocket_accepts_default_port_8000_origin_under_anonymous_mode(client, monkeypatch):+ """Regression test for #1257: default CLI port 8000 origin must be accepted."""+ monkeypatch.setenv("SEMANTICA_ALLOW_ANONYMOUS", "true")+ monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)++ for origin in ("http://127.0.0.1:8000", "http://localhost:8000"):+ with client.websocket_connect(+ "/ws/graph-updates", headers={"Origin": origin}+ ) as websocket:+ ack = websocket.receive_json()+ assert ack["event"] == "connection_ack"+++def test_websocket_accepts_non_default_port_origin_when_configured(monkeypatch):+ """Regression test for #1257: custom port origin (e.g. 8020) must be accepted when configured."""+ monkeypatch.setenv("SEMANTICA_ALLOW_ANONYMOUS", "true")+ monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)++ app = create_app(+ session=GraphSession(_build_sample_graph()),+ allowed_origins=["http://localhost:5173", "http://127.0.0.1:8020", "http://localhost:8020"],+ )+ with TestClient(app) as test_client:+ with test_client.websocket_connect(+ "/ws/graph-updates", headers={"Origin": "http://127.0.0.1:8020"}+ ) as websocket:+ ack = websocket.receive_json()+ assert ack["event"] == "connection_ack"++ # Hostile origins must still be rejected+ with pytest.raises(WebSocketDisconnect) as excinfo:+ with test_client.websocket_connect(+ "/ws/graph-updates", headers={"Origin": "https://evil.example"}+ ):+ pass+ assert excinfo.value.code == 4403+++def test_websocket_explicit_allowed_origins_preserves_user_allowlist(monkeypatch):+ """Preserve explicit ALLOWED_ORIGINS: do not silently allow unlisted origins."""+ monkeypatch.setenv("SEMANTICA_ALLOW_ANONYMOUS", "true")+ monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)+ monkeypatch.setenv("ALLOWED_ORIGINS", "https://custom.example.com")++ app = create_app(session=GraphSession(_build_sample_graph()))+ with TestClient(app) as test_client:+ # Specified origin is accepted+ with test_client.websocket_connect(+ "/ws/graph-updates", headers={"Origin": "https://custom.example.com"}+ ) as websocket:+ ack = websocket.receive_json()+ assert ack["event"] == "connection_ack"++ # Unlisted origins are rejected+ with pytest.raises(WebSocketDisconnect) as excinfo:+ with test_client.websocket_connect(+ "/ws/graph-updates", headers={"Origin": "http://127.0.0.1:8020"}+ ):+ pass+ assert excinfo.value.code == 4403diff --git a/tests/explorer/test_explorer_entrypoints.py b/tests/explorer/test_explorer_entrypoints.pyindex fdfa0e91..8c971691 100644--- a/tests/explorer/test_explorer_entrypoints.py+++ b/tests/explorer/test_explorer_entrypoints.py@@ -3,7 +3,8 @@ import pytestpytest.importorskip("fastapi")from fastapi import FastAPI # noqa: E402-from starlette.testclient import TestClient # noqa: E402+from starlette.testclient import TestClient+from starlette.websockets import WebSocketDisconnect # noqa: E402from semantica.context.context_graph import ContextGraph # noqa: E402from semantica.explorer.runtime import install_mutation_bridge # noqa: E402@@ -144,3 +145,76 @@ def test_legacy_server_mounts_editable_markdown_routes(monkeypatch):)assert saved.status_code == 200assert saved.json()["body"] == "Updated server content"+++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."""+ 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")++ from semantica.explorer import main+ import uvicorn++ captured_app = None+ captured_kwargs = {}++ def mock_run(app, **kwargs):+ nonlocal captured_app, captured_kwargs+ captured_app = app+ captured_kwargs = kwargs++ monkeypatch.setattr(uvicorn, "run", mock_run)++ 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"]++ with TestClient(captured_app) as client:+ with client.websocket_connect(+ "/ws/graph-updates", headers={"Origin": "http://127.0.0.1:8020"}+ ) as ws:+ ack = ws.receive_json()+ assert ack["event"] == "connection_ack"++ # Hostile origin still rejected+ with pytest.raises(WebSocketDisconnect) as excinfo:+ with client.websocket_connect(+ "/ws/graph-updates", headers={"Origin": "https://evil.example"}+ ):+ pass+ assert excinfo.value.code == 4403+++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")+ monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)+ monkeypatch.setenv("ALLOWED_ORIGINS", "https://custom.example.com")+ monkeypatch.delenv("EXPLORER_CORS_ORIGINS", raising=False)++ graph_file = tmp_path / "test_graph.json"+ graph_file.write_text('{"nodes": [], "edges": []}', encoding="utf-8")++ from semantica.explorer import main+ import uvicorn++ captured_app = None++ def mock_run(app, **kwargs):+ nonlocal captured_app+ captured_app = app++ monkeypatch.setattr(uvicorn, "run", mock_run)++ main(["--graph", str(graph_file), "--port", "8020", "--no-browser"])++ assert captured_app.state.explorer_settings["allowed_origins"] == [+ "https://custom.example.com"+ ]