~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: add coverage for security_headers, server_config, web exceptions (#3051)
LearningCircuitb62a65cf7f9b
diff --git a/tests/security/test_security_headers_gaps.py b/tests/security/test_security_headers_gaps.pynew file mode 100644index 0000000000..98cddfe9ac--- /dev/null+++ b/tests/security/test_security_headers_gaps.py@@ -0,0 +1,261 @@+"""Tests for uncovered branches in security_headers.py."""++import flask+import pytest++from local_deep_research.security.security_headers import SecurityHeaders+++def _make_app(**config_overrides):+ """Create a minimal Flask app with SecurityHeaders."""+ app = flask.Flask(__name__)+ app.config["TESTING"] = True+ for k, v in config_overrides.items():+ app.config[k] = v+ SecurityHeaders(app)+ return app+++class TestIsApiRoute:+ def test_api_prefix(self):+ assert SecurityHeaders._is_api_route("/api/research") is True++ def test_research_api_prefix(self):+ assert SecurityHeaders._is_api_route("/research/api/test") is True++ def test_history_api_prefix(self):+ assert SecurityHeaders._is_api_route("/history/api") is True++ def test_static_not_api(self):+ assert SecurityHeaders._is_api_route("/static/file.js") is False++ def test_root_not_api(self):+ assert SecurityHeaders._is_api_route("/") is False++ def test_settings_not_api(self):+ assert SecurityHeaders._is_api_route("/settings/") is False+++class TestValidateCorsConfig:+ def test_credentials_with_wildcard_raises(self):+ with pytest.raises(+ ValueError, match="Cannot use credentials with wildcard"+ ):+ _make_app(+ SECURITY_CORS_ALLOWED_ORIGINS="*",+ SECURITY_CORS_ALLOW_CREDENTIALS=True,+ )++ def test_credentials_with_specific_origin_ok(self):+ app = _make_app(+ SECURITY_CORS_ALLOWED_ORIGINS="https://example.com",+ SECURITY_CORS_ALLOW_CREDENTIALS=True,+ )+ assert app is not None++ def test_cors_disabled_skips_validation(self):+ # Should not raise even with bad config when CORS is disabled+ app = _make_app(+ SECURITY_CORS_ENABLED=False,+ SECURITY_CORS_ALLOWED_ORIGINS="*",+ SECURITY_CORS_ALLOW_CREDENTIALS=True,+ )+ assert app is not None++ def test_multi_origin_with_credentials_logs_info(self):+ app = _make_app(+ SECURITY_CORS_ALLOWED_ORIGINS="https://a.com,https://b.com",+ SECURITY_CORS_ALLOW_CREDENTIALS=True,+ )+ assert app is not None+++class TestAddSecurityHeaders:+ def test_basic_headers_present(self):+ app = _make_app()+ with app.test_client() as client:++ @app.route("/test")+ def test_route():+ return "ok"++ resp = client.get("/test")+ assert "Content-Security-Policy" in resp.headers+ assert "X-Frame-Options" in resp.headers+ assert "X-Content-Type-Options" in resp.headers+ assert "Permissions-Policy" in resp.headers+ assert "Referrer-Policy" in resp.headers++ def test_hsts_not_set_on_http(self):+ app = _make_app()+ with app.test_client() as client:++ @app.route("/test")+ def test_route():+ return "ok"++ resp = client.get("/test")+ assert "Strict-Transport-Security" not in resp.headers++ def test_static_path_no_cache_control(self):+ """Static paths should NOT get no-cache headers."""+ app = _make_app()++ @app.route("/static/test.js")+ def static_test():+ return "js"++ with app.test_client() as client:+ resp = client.get("/static/test.js")+ cache = resp.headers.get("Cache-Control", "")+ assert "no-store" not in cache++ def test_non_static_path_gets_no_cache(self):+ app = _make_app()++ @app.route("/page")+ def page():+ return "html"++ with app.test_client() as client:+ resp = client.get("/page")+ assert "no-store" in resp.headers.get("Cache-Control", "")++ def test_coep_policy_from_config(self):+ app = _make_app(SECURITY_COEP_POLICY="require-corp")++ @app.route("/test")+ def test_route():+ return "ok"++ with app.test_client() as client:+ resp = client.get("/test")+ assert (+ resp.headers["Cross-Origin-Embedder-Policy"] == "require-corp"+ )+++class TestCorsHeaders:+ def test_wildcard_origin(self):+ app = _make_app(SECURITY_CORS_ALLOWED_ORIGINS="*")++ @app.route("/api/test")+ def api_test():+ return "ok"++ with app.test_client() as client:+ resp = client.get("/api/test")+ assert resp.headers["Access-Control-Allow-Origin"] == "*"+ assert "Access-Control-Allow-Credentials" not in resp.headers++ def test_single_origin(self):+ app = _make_app(+ SECURITY_CORS_ALLOWED_ORIGINS="https://example.com",+ SECURITY_CORS_ALLOW_CREDENTIALS=True,+ )++ @app.route("/api/test")+ def api_test():+ return "ok"++ with app.test_client() as client:+ resp = client.get("/api/test")+ assert (+ resp.headers["Access-Control-Allow-Origin"]+ == "https://example.com"+ )+ assert resp.headers["Access-Control-Allow-Credentials"] == "true"++ def test_multi_origin_reflects_matching(self):+ app = _make_app(+ SECURITY_CORS_ALLOWED_ORIGINS="https://a.com,https://b.com",+ SECURITY_CORS_ALLOW_CREDENTIALS=True,+ )++ @app.route("/api/test")+ def api_test():+ return "ok"++ with app.test_client() as client:+ resp = client.get("/api/test", headers={"Origin": "https://b.com"})+ assert (+ resp.headers["Access-Control-Allow-Origin"] == "https://b.com"+ )+ assert resp.headers["Access-Control-Allow-Credentials"] == "true"++ def test_multi_origin_non_matching_uses_first(self):+ app = _make_app(+ SECURITY_CORS_ALLOWED_ORIGINS="https://a.com,https://b.com",+ )++ @app.route("/api/test")+ def api_test():+ return "ok"++ with app.test_client() as client:+ resp = client.get(+ "/api/test", headers={"Origin": "https://evil.com"}+ )+ origin = resp.headers["Access-Control-Allow-Origin"]+ assert origin in ("https://a.com", "https://b.com")++ def test_non_api_route_no_cors(self):+ app = _make_app(SECURITY_CORS_ALLOWED_ORIGINS="*")++ @app.route("/page")+ def page():+ return "ok"++ with app.test_client() as client:+ resp = client.get("/page")+ assert "Access-Control-Allow-Origin" not in resp.headers++ def test_max_age_header(self):+ app = _make_app(SECURITY_CORS_ALLOWED_ORIGINS="*")++ @app.route("/api/test")+ def api_test():+ return "ok"++ with app.test_client() as client:+ resp = client.get("/api/test")+ assert resp.headers["Access-Control-Max-Age"] == "3600"+++class TestGetCspPolicy:+ def test_default_connect_src(self):+ app = _make_app()+ sh = SecurityHeaders()+ sh.app = app+ csp = sh.get_csp_policy()+ assert "connect-src 'self'" in csp++ def test_custom_connect_src(self):+ app = _make_app(+ SECURITY_CSP_CONNECT_SRC="'self' https://api.example.com"+ )+ sh = SecurityHeaders()+ sh.app = app+ csp = sh.get_csp_policy()+ assert "connect-src 'self' https://api.example.com" in csp++ def test_csp_contains_required_directives(self):+ app = _make_app()+ sh = SecurityHeaders()+ sh.app = app+ csp = sh.get_csp_policy()+ for directive in [+ "default-src",+ "script-src",+ "style-src",+ "img-src",+ "object-src 'none'",+ ]:+ assert directive in csp+++class TestGetPermissionsPolicy:+ def test_disables_dangerous_features(self):+ policy = SecurityHeaders.get_permissions_policy()+ for feature in ["geolocation", "camera", "microphone", "payment"]:+ assert f"{feature}=()" in policydiff --git a/tests/web/test_exceptions_gaps.py b/tests/web/test_exceptions_gaps.pynew file mode 100644index 0000000000..13c1810055--- /dev/null+++ b/tests/web/test_exceptions_gaps.py@@ -0,0 +1,73 @@+"""Tests for web/exceptions.py coverage."""++from local_deep_research.web.exceptions import (+ AuthenticationRequiredError,+ WebAPIException,+)+++class TestWebAPIException:+ def test_default_fields(self):+ exc = WebAPIException("something broke")+ assert exc.message == "something broke"+ assert exc.status_code == 500+ assert exc.error_code == "WebAPIException"+ assert exc.details == {}++ def test_custom_fields(self):+ exc = WebAPIException(+ "bad request",+ status_code=400,+ error_code="BAD_REQUEST",+ details={"field": "name"},+ )+ assert exc.status_code == 400+ assert exc.error_code == "BAD_REQUEST"+ assert exc.details == {"field": "name"}++ def test_to_dict_basic(self):+ exc = WebAPIException("error")+ d = exc.to_dict()+ assert d["status"] == "error"+ assert d["message"] == "error"+ assert d["error_code"] == "WebAPIException"+ assert "details" not in d # empty details not included++ def test_to_dict_with_details(self):+ exc = WebAPIException("error", details={"key": "val"})+ d = exc.to_dict()+ assert d["details"] == {"key": "val"}++ def test_is_exception(self):+ exc = WebAPIException("test")+ assert isinstance(exc, Exception)+ assert str(exc) == "test"+++class TestAuthenticationRequiredError:+ def test_default_message(self):+ exc = AuthenticationRequiredError()+ assert "Authentication required" in exc.message+ assert exc.status_code == 401+ assert exc.error_code == "AUTHENTICATION_REQUIRED"+ assert exc.details == {}++ def test_custom_message(self):+ exc = AuthenticationRequiredError(message="Please log in")+ assert exc.message == "Please log in"++ def test_with_username(self):+ exc = AuthenticationRequiredError(username="alice")+ assert exc.details == {"username": "alice"}+ assert exc.status_code == 401++ def test_to_dict(self):+ exc = AuthenticationRequiredError(username="bob")+ d = exc.to_dict()+ assert d["status"] == "error"+ assert d["error_code"] == "AUTHENTICATION_REQUIRED"+ assert d["details"]["username"] == "bob"++ def test_inherits_from_web_api_exception(self):+ exc = AuthenticationRequiredError()+ assert isinstance(exc, WebAPIException)diff --git a/tests/web/test_server_config_gaps.py b/tests/web/test_server_config_gaps.pynew file mode 100644index 0000000000..2ee23fbb59--- /dev/null+++ b/tests/web/test_server_config_gaps.py@@ -0,0 +1,181 @@+"""Tests for server_config.py uncovered branches."""++import json+from unittest.mock import patch++from local_deep_research.web.server_config import (+ _DEFAULTS,+ _load_legacy_config,+ has_legacy_customizations,+ load_server_config,+)+++class TestHasLegacyCustomizations:+ def test_no_file_returns_false(self, tmp_path):+ assert has_legacy_customizations(tmp_path / "missing.json") is False++ def test_invalid_json_returns_false(self, tmp_path):+ p = tmp_path / "bad.json"+ p.write_text("not json{{{", encoding="utf-8")+ assert has_legacy_customizations(p) is False++ def test_non_dict_json_returns_false(self, tmp_path):+ p = tmp_path / "list.json"+ p.write_text("[1,2,3]", encoding="utf-8")+ assert has_legacy_customizations(p) is False++ def test_all_defaults_returns_false(self, tmp_path):+ p = tmp_path / "config.json"+ p.write_text(json.dumps(_DEFAULTS), encoding="utf-8")+ assert has_legacy_customizations(p) is False++ def test_non_default_value_returns_true(self, tmp_path):+ p = tmp_path / "config.json"+ data = {"port": 9999}+ p.write_text(json.dumps(data), encoding="utf-8")+ assert has_legacy_customizations(p) is True++ def test_unrecognized_key_returns_true(self, tmp_path):+ p = tmp_path / "config.json"+ data = {"unknown_key": "value"}+ p.write_text(json.dumps(data), encoding="utf-8")+ assert has_legacy_customizations(p) is True++ def test_empty_dict_returns_false(self, tmp_path):+ p = tmp_path / "config.json"+ p.write_text("{}", encoding="utf-8")+ assert has_legacy_customizations(p) is False+++class TestLoadLegacyConfig:+ def test_no_file_returns_empty(self, tmp_path):+ with patch(+ "local_deep_research.web.server_config.get_server_config_path",+ return_value=tmp_path / "missing.json",+ ):+ assert _load_legacy_config() == {}++ def test_invalid_json_returns_empty(self, tmp_path):+ p = tmp_path / "bad.json"+ p.write_text("{broken", encoding="utf-8")+ with patch(+ "local_deep_research.web.server_config.get_server_config_path",+ return_value=p,+ ):+ assert _load_legacy_config() == {}++ def test_non_dict_returns_empty(self, tmp_path):+ p = tmp_path / "list.json"+ p.write_text('"just a string"', encoding="utf-8")+ with patch(+ "local_deep_research.web.server_config.get_server_config_path",+ return_value=p,+ ):+ assert _load_legacy_config() == {}++ def test_recognized_keys_extracted(self, tmp_path):+ p = tmp_path / "config.json"+ p.write_text(+ json.dumps({"host": "localhost", "port": 8080}), encoding="utf-8"+ )+ with patch(+ "local_deep_research.web.server_config.get_server_config_path",+ return_value=p,+ ):+ result = _load_legacy_config()+ assert result["host"] == "localhost"+ assert result["port"] == 8080++ def test_unrecognized_keys_ignored(self, tmp_path):+ p = tmp_path / "config.json"+ p.write_text(+ json.dumps({"host": "localhost", "bogus_key": "val"}),+ encoding="utf-8",+ )+ with patch(+ "local_deep_research.web.server_config.get_server_config_path",+ return_value=p,+ ):+ result = _load_legacy_config()+ assert "host" in result+ assert "bogus_key" not in result+++class TestLoadServerConfig:+ def test_returns_all_expected_keys(self):+ with patch(+ "local_deep_research.web.server_config._load_legacy_config",+ return_value={},+ ):+ config = load_server_config()+ for key in _DEFAULTS:+ assert key in config++ def test_defaults_when_no_legacy_no_env(self):+ with (+ patch(+ "local_deep_research.web.server_config._load_legacy_config",+ return_value={},+ ),+ patch.dict("os.environ", {}, clear=False),+ ):+ # Remove any LDR_ env vars+ import os++ env_clean = {+ k: v for k, v in os.environ.items() if not k.startswith("LDR_")+ }+ with patch.dict("os.environ", env_clean, clear=True):+ config = load_server_config()+ assert config["port"] in (5000, _DEFAULTS["port"])++ def test_unrecognized_allow_registrations_env_defaults_false(self):+ with (+ patch(+ "local_deep_research.web.server_config._load_legacy_config",+ return_value={},+ ),+ patch.dict(+ "os.environ",+ {"LDR_APP_ALLOW_REGISTRATIONS": "nein"},+ clear=False,+ ),+ ):+ config = load_server_config()+ assert config["allow_registrations"] is False++ def test_recognized_allow_registrations_env_passes(self):+ with (+ patch(+ "local_deep_research.web.server_config._load_legacy_config",+ return_value={},+ ),+ patch.dict(+ "os.environ",+ {"LDR_APP_ALLOW_REGISTRATIONS": "true"},+ clear=False,+ ),+ ):+ config = load_server_config()+ # Should be True (recognized value)+ assert config["allow_registrations"] is True++ def test_legacy_unrecognized_allow_registrations_string(self):+ with (+ patch(+ "local_deep_research.web.server_config._load_legacy_config",+ return_value={"allow_registrations": "disabled"},+ ),+ patch.dict("os.environ", {}, clear=False),+ ):+ import os++ env_clean = {+ k: v+ for k, v in os.environ.items()+ if k != "LDR_APP_ALLOW_REGISTRATIONS"+ }+ with patch.dict("os.environ", env_clean, clear=True):+ config = load_server_config()+ assert config["allow_registrations"] is False