Personal AI, On Personal Devices
Python
security(server): configurable CORS origins and refuse credentialed wildcard (#1005)
clawdovil-agent-bv308512e5f400
diff --git a/src/openjarvis/cli/serve.py b/src/openjarvis/cli/serve.pyindex f73bd101..ded1d5c5 100644--- a/src/openjarvis/cli/serve.py+++ b/src/openjarvis/cli/serve.py@@ -3,6 +3,7 @@from __future__ import annotationsimport logging+import osimport sysimport click@@ -28,6 +29,16 @@ logger = logging.getLogger(__name__)_DEFAULT_TOOLS = frozenset({"think", "calculator", "web_search"})+def _resolve_server_cors_origins(configured: object) -> list[str]:+ """Resolve server CORS origins with environment taking precedence."""+ raw = os.environ.get("OPENJARVIS_CORS_ORIGINS", "").strip()+ if raw:+ return [origin.strip() for origin in raw.split(",") if origin.strip()]+ if isinstance(configured, list):+ return [origin for origin in configured if isinstance(origin, str)]+ return []++def _resolve_allowed_tools(config: object) -> tuple[set[str], bool]:"""Return configured tool names and whether the selection was explicit.@@ -202,8 +213,6 @@ def serve(# If cloud API keys are set, prepare a cloud engine. We build the# MultiEngine after local discovery so healthy local fallbacks such as# Ollama stay visible even when the configured preferred engine is MLX.- import os-cloud_engine = None_has_cloud = (os.environ.get("OPENAI_API_KEY")@@ -732,6 +741,7 @@ def serve(except Exception as exc:logger.debug("ChannelBridge init skipped: %s", exc)+ cors_origins = _resolve_server_cors_origins(config.server.cors_origins)app = create_app(engine,model_name,@@ -754,7 +764,7 @@ def serve(audit_logger=sec.audit_logger,api_key=api_key,webhook_config=webhook_config,- cors_origins=config.server.cors_origins,+ cors_origins=cors_origins,)console.print(@@ -773,7 +783,7 @@ def serve(except ValueError:_is_loop = bind_host in ("localhost", "")- if not _is_loop and "*" in config.server.cors_origins:+ if not _is_loop and "*" in cors_origins:console.print("[yellow bold]WARNING:[/yellow bold] Wildcard CORS with credentials ""enabled on non-loopback interface. This allows any website to make "diff --git a/src/openjarvis/server/app.py b/src/openjarvis/server/app.pyindex ae14104e..dba9d53c 100644--- a/src/openjarvis/server/app.py+++ b/src/openjarvis/server/app.py@@ -3,6 +3,7 @@from __future__ import annotationsimport logging+import osimport pathlibimport threadingimport time@@ -247,10 +248,18 @@ def create_app(from fastapi.middleware.cors import CORSMiddleware- _origins = (- cors_origins- if cors_origins is not None- else [+ # Allow deployments to pin the exact browser origins via+ # OPENJARVIS_CORS_ORIGINS (comma-separated). On an exposed server this+ # should be set to your real frontend origin(s) only — never "*", which+ # combined with allow_credentials=True would let any website call the API+ # in the user's authenticated context.+ _env_origins = os.environ.get("OPENJARVIS_CORS_ORIGINS", "").strip()+ if cors_origins is not None:+ _origins = cors_origins+ elif _env_origins:+ _origins = [o.strip() for o in _env_origins.split(",") if o.strip()]+ else:+ _origins = ["http://localhost:5173","http://127.0.0.1:5173","http://localhost:5174",@@ -264,7 +273,8 @@ def create_app("http://tauri.localhost","https://tauri.localhost",]- )+ # Defense in depth: a literal "*" with credentials is unsafe. Refuse it.+ _origins = [o for o in _origins if o != "*"]# Store dependencies in app stateapp.state.engine = engineapp.state.model = modeldiff --git a/tests/cli/test_serve_single_build.py b/tests/cli/test_serve_single_build.pyindex 087108e6..38c40a0c 100644--- a/tests/cli/test_serve_single_build.py+++ b/tests/cli/test_serve_single_build.py@@ -204,6 +204,29 @@ def test_serve_does_not_call_systembuilder_build(tmp_path, monkeypatch):inject_spy.assert_called_once_with()+def test_serve_passes_environment_cors_origins(tmp_path, monkeypatch):+ """The normal CLI path must not mask the environment override."""+ monkeypatch.setenv(+ "OPENJARVIS_CORS_ORIGINS",+ "https://frontend.example,https://admin.example",+ )+ create_app = MagicMock(return_value=MagicMock())++ with patch("openjarvis.server.app.create_app", create_app):+ result = _run_serve(+ tmp_path,+ monkeypatch,+ build_spy=MagicMock(),+ set_system_spy=MagicMock(),+ )++ assert result.exit_code == 0, result.output+ assert create_app.call_args.kwargs["cors_origins"] == [+ "https://frontend.example",+ "https://admin.example",+ ]++def test_executor_receives_required_system_attrs(tmp_path, monkeypatch):"""The executor still gets a system exposing the attributes it reads.diff --git a/tests/cli/test_serve_tools.py b/tests/cli/test_serve_tools.pyindex 1aedef8d..159e1bdd 100644--- a/tests/cli/test_serve_tools.py+++ b/tests/cli/test_serve_tools.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport pytest-from openjarvis.cli.serve import _resolve_allowed_tools+from openjarvis.cli.serve import _resolve_allowed_tools, _resolve_server_cors_originsfrom openjarvis.core.config import JarvisConfig@@ -51,3 +51,22 @@ def test_serve_defaults_tools_when_no_selection_is_configured():assert allowed == {"think", "calculator", "web_search"}assert explicit is False+++def test_cors_environment_overrides_configured_defaults(monkeypatch):+ monkeypatch.setenv(+ "OPENJARVIS_CORS_ORIGINS",+ " https://frontend.example, https://admin.example ",+ )++ origins = _resolve_server_cors_origins(["http://localhost:5173"])++ assert origins == ["https://frontend.example", "https://admin.example"]+++def test_cors_config_is_used_without_environment(monkeypatch):+ monkeypatch.delenv("OPENJARVIS_CORS_ORIGINS", raising=False)++ origins = _resolve_server_cors_origins(["http://localhost:5173"])++ assert origins == ["http://localhost:5173"]diff --git a/tests/server/test_cors_auth_interaction.py b/tests/server/test_cors_auth_interaction.pyindex 2e675103..1cf4ccef 100644--- a/tests/server/test_cors_auth_interaction.py+++ b/tests/server/test_cors_auth_interaction.py@@ -35,6 +35,81 @@ def _test_config():class TestCorsPreflightWithApiKey:+ def test_environment_origins_used_when_factory_argument_is_omitted(+ self, monkeypatch+ ):+ monkeypatch.setenv("OPENJARVIS_CORS_ORIGINS", "https://frontend.example")+ app = create_app(+ _make_engine(),+ "test-model",+ config=_test_config(),+ api_key="oj_sk_test123",+ )+ client = TestClient(app)++ resp = client.options(+ "/v1/models",+ headers={+ "Origin": "https://frontend.example",+ "Access-Control-Request-Method": "GET",+ },+ )++ assert resp.status_code == 200+ assert resp.headers.get("access-control-allow-origin") == (+ "https://frontend.example"+ )++ def test_explicit_factory_origins_override_environment(self, monkeypatch):+ monkeypatch.setenv("OPENJARVIS_CORS_ORIGINS", "https://env.example")+ app = create_app(+ _make_engine(),+ "test-model",+ config=_test_config(),+ api_key="oj_sk_test123",+ cors_origins=["https://explicit.example"],+ )+ client = TestClient(app)++ explicit = client.options(+ "/v1/models",+ headers={+ "Origin": "https://explicit.example",+ "Access-Control-Request-Method": "GET",+ },+ )+ env = client.options(+ "/v1/models",+ headers={+ "Origin": "https://env.example",+ "Access-Control-Request-Method": "GET",+ },+ )++ assert explicit.status_code == 200+ assert env.status_code == 400++ def test_wildcard_origin_is_removed(self, monkeypatch):+ monkeypatch.setenv("OPENJARVIS_CORS_ORIGINS", "*")+ app = create_app(+ _make_engine(),+ "test-model",+ config=_test_config(),+ api_key="oj_sk_test123",+ )+ client = TestClient(app)++ resp = client.options(+ "/v1/models",+ headers={+ "Origin": "https://untrusted.example",+ "Access-Control-Request-Method": "GET",+ },+ )++ assert resp.status_code == 400+ assert "access-control-allow-origin" not in resp.headers+def test_preflight_gets_cors_headers_not_401(self):app = create_app(_make_engine(),