~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
fix(ci): scan authenticated API operations with ZAP coverage checks (#6649)
LearningCircuitd594b28933e4
diff --git a/.github/workflows/owasp-zap-scan.yml b/.github/workflows/owasp-zap-scan.ymlindex acfabf414a..779af7e24a 100644--- a/.github/workflows/owasp-zap-scan.yml+++ b/.github/workflows/owasp-zap-scan.yml@@ -3,6 +3,11 @@ name: OWASP ZAP Security Scan# Baseline and API scans - called by release-gate.ymlon:+ pull_request:+ paths:+ - ".github/workflows/owasp-zap-scan.yml"+ - "scripts/ci/zap_api_*.py"+ - "tests/ci/standalone/test_zap*.py"workflow_call: # Called by release-gate.ymlworkflow_dispatch:@@ -111,6 +116,10 @@ jobs:name: ZAP API Scanruns-on: ubuntu-latesttimeout-minutes: 45+ env:+ # Active scanning exercises handlers instead of exhausting a rate quota.+ # Authentication, CSRF and encrypted databases remain enabled.+ LDR_DISABLE_RATE_LIMITING: 'true'permissions:contents: readsecurity-events: write@@ -145,15 +154,19 @@ jobs:run: |pdm sync -d- - name: Start LDR server for testing+ - name: Test schema and coverage policy+ run: python -m unittest discover -s tests/ci/standalone -p 'test_zap*.py' -v++ - name: Start seeded API fixture serverrun: |export CI=true+ export LDR_DATA_DIR="$RUNNER_TEMP/zap-api-data"export LDR_DB_CONFIG_KDF_ITERATIONS=1000# Without LDR_TEST_MODE the 1000 is clamped to the production# minimum (256000), making SQLCipher ~256x slower — see #4430.export LDR_TEST_MODE=1export PYTHONPATH=$PWD/src:$PYTHONPATH- pdm run python -m local_deep_research.web.app > server.log 2>&1 &+ pdm run python scripts/ci/zap_api_target.py > server.log 2>&1 &SERVER_PID=$!echo "$SERVER_PID" > server.pid@@ -161,7 +174,7 @@ jobs:# --connect-timeout/--max-time bound TCP and total request time so a# hung connection fails fast instead of eating the job timeout.for _ in {1..90}; do- if curl -fsS --connect-timeout 2 --max-time 5 http://localhost:5000/api/v1/health > /dev/null; then+ if curl -fsS --connect-timeout 2 --max-time 5 http://127.0.0.1:5000/api/v1/health > /dev/null; thenecho "Server started successfully"breakfi@@ -169,29 +182,38 @@ jobs:done# Verify server is running- if ! curl -fsS --connect-timeout 2 --max-time 5 http://localhost:5000/api/v1/health > /dev/null; then+ if ! curl -fsS --connect-timeout 2 --max-time 5 http://127.0.0.1:5000/api/v1/health > /dev/null; thenecho "Server failed to start"cat server.logexit 1fi- - name: Generate OpenAPI specification+ - name: Require generated OpenAPI specificationrun: |- # If you have an OpenAPI spec, use it. Otherwise, ZAP will discover endpoints- # For now, we'll let ZAP discover API endpoints automatically- echo "Using automatic API endpoint discovery"+ python - <<'PYCODE'+ import json+ from pathlib import Path+ spec = json.loads(Path("zap-openapi.json").read_text())+ assert spec["openapi"].startswith("3.") and spec["paths"], "empty API specification"+ PYCODE- name: Run ZAP API Scanuses: zaproxy/action-api-scan@5158fe4d9d8fcc75ea204db81317cce7f9e5453d # v0.10.0with:- target: 'http://localhost:5000/api/v1'+ target: '/zap/wrk/zap-openapi.json'format: 'openapi'rules_file_name: '.zap/rules.tsv'- cmd_options: '-a -I' # -I: only fail on FAIL-level alerts per rules.tsv (ignore WARN/INFO)+ # Keep the existing alert policy; authentication and coverage failures+ # are independent blockers. The hook logs in with real session/CSRF.+ cmd_options: '-a -I --hook=/zap/wrk/scripts/ci/zap_api_hooks.py -z "-config scanner.threadPerHost=2"'allow_issue_writing: falsefail_action: trueartifact_name: zapapi+ - name: Require authenticated active-scan coverage+ if: always()+ run: python scripts/ci/zap_api_hooks.py zap-api-coverage.json+- name: Upload ZAP API scan resultsuses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1if: always()@@ -201,7 +223,9 @@ jobs:report_html.htmlreport_json.jsonreport_md.md- retention-days: 30+ zap-api-coverage.json+ zap-openapi.json+ retention-days: 7- name: Stop serverif: always()diff --git a/scripts/ci/zap_api_hooks.py b/scripts/ci/zap_api_hooks.pynew file mode 100644index 0000000000..d5ece06af8--- /dev/null+++ b/scripts/ci/zap_api_hooks.py@@ -0,0 +1,244 @@+"""Authenticated ZAP API scan and evidence checks for the disposable CI target."""++import copy+import http.cookiejar+import json+import sys+import urllib.error+import urllib.parse+import urllib.request+from pathlib import Path++BASE = "http://127.0.0.1:5000"+OPERATIONS = {+ "/api/v1/": "GET",+ "/api/v1/quick_summary": "POST",+ "/api/v1/generate_report": "POST",+ "/api/v1/analyze_documents": "POST",+ "/history/api": "GET",+}+AUTHENTICATED = False+++def build_spec(source):+ """Use real route definitions, adding bodies for manually parsed JSON."""+ spec = copy.deepcopy(source)+ if not spec.get("openapi", "").startswith("3."):+ raise ValueError("Expected the application's OpenAPI 3 schema")+ spec["servers"] = [{"url": BASE}]+ spec["paths"] = {}+ for path, method in OPERATIONS.items():+ operation = copy.deepcopy(source["paths"][path][method.lower()])+ if method == "POST":+ properties = {+ "query": {"type": "string", "default": "CI research fixture"}+ }+ required = ["query"]+ if path.endswith("analyze_documents"):+ properties["collection_name"] = {+ "type": "string",+ "default": "ci-fixture",+ }+ required.append("collection_name")+ operation["requestBody"] = {+ "required": True,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "required": required,+ "properties": properties,+ }+ }+ },+ }+ elif path == "/history/api":+ operation["parameters"] = [+ {+ "name": name,+ "in": "query",+ "schema": {"type": "integer", "default": default},+ }+ for name, default in (("limit", 20), ("offset", 0))+ ]+ spec["paths"][path] = {method.lower(): operation}+ return spec+++def request(opener, path, data=None, token=None, form=False):+ headers = {"Accept": "application/json"}+ if token:+ headers["X-CSRFToken"] = token+ if data is not None:+ headers["Content-Type"] = (+ "application/x-www-form-urlencoded" if form else "application/json"+ )+ data = (+ urllib.parse.urlencode(data) if form else json.dumps(data)+ ).encode()+ # Scheme and host are fixed to this job's disposable loopback server.+ req = urllib.request.Request(BASE + path, data=data, headers=headers) # noqa: S310+ try:+ response = opener.open(req, timeout=30)+ except urllib.error.HTTPError as exc:+ response = exc+ with response:+ body = response.read()+ if "application/json" in response.headers.get("Content-Type", ""):+ body = json.loads(body)+ return response.status, body+++class NoRedirect(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ # The preflight only needs the local login response; never forward+ # authentication headers to a redirect destination.+ return None+++def authenticate():+ anonymous = urllib.request.build_opener(+ urllib.request.ProxyHandler({}), NoRedirect()+ )+ if request(anonymous, "/api/v1/")[0] != 401:+ raise ValueError("Anonymous API access did not fail with 401")+ jar = http.cookiejar.CookieJar()+ client = urllib.request.build_opener(+ urllib.request.ProxyHandler({}),+ urllib.request.HTTPCookieProcessor(jar),+ NoRedirect(),+ )+ status, response = request(client, "/auth/csrf-token")+ if status != 200:+ raise ValueError("Could not obtain login CSRF token")+ login_status, _ = request(+ client,+ "/auth/login",+ {"username": "test_admin", "password": "testpass123"},+ response["csrf_token"],+ form=True,+ ) # pragma: allowlist secret+ if login_status != 302:+ raise ValueError("Fixture login did not succeed")+ status, response = request(client, "/auth/csrf-token")+ if status != 200:+ raise ValueError("Could not obtain authenticated CSRF token")+ token = response["csrf_token"]+ # Authentication and CSRF protection stay enabled on this fixture server.+ if (+ request(client, "/api/v1/quick_summary", {"query": "CI fixture"})[0]+ != 403+ ):+ raise ValueError(+ "Authenticated API request without CSRF was not rejected"+ )+ for path, method in OPERATIONS.items():+ body = {"query": "CI fixture"} if method == "POST" else None+ if path.endswith("analyze_documents"):+ body["collection_name"] = "ci-fixture"+ status, response = request(client, path, body, token)+ if status != 200 or not isinstance(response, dict):+ raise ValueError(+ f"Authenticated API preflight failed for {method} {path}"+ )+ if path == "/history/api" and not response.get("items"):+ raise ValueError("Authenticated history fixture is empty")+ # Capture the final cookie, after login/session bootstrap has completed.+ probe = urllib.request.Request("http://127.0.0.1:5000/api/v1/")+ jar.add_cookie_header(probe)+ cookie = probe.get_header("Cookie")+ if not cookie:+ raise ValueError("Login produced no usable session cookie")+ return cookie, token+++def zap_started(zap, target):+ global AUTHENTICATED+ cookie, token = authenticate()+ for name, value in (("Cookie", cookie), ("X-CSRFToken", token)):+ result = zap.replacer.add_rule(+ description=f"CI authenticated {name}",+ enabled="true",+ matchtype="REQ_HEADER",+ matchregex="false",+ matchstring=name,+ replacement=value,+ url=r"^http://127\.0\.0\.1:5000/.*$",+ )+ if result != "OK":+ raise ValueError(+ "ZAP could not configure authenticated request headers"+ )+ AUTHENTICATED = True+++def coverage(messages, active_scans):+ rows = {+ f"{method} {path}": {"requests": 0, "successful_json_responses": 0}+ for path, method in OPERATIONS.items()+ }+ for message in messages:+ method, url, _ = message["requestHeader"].splitlines()[0].split(" ", 2)+ parsed = urllib.parse.urlsplit(url)+ if parsed.scheme and (+ parsed.scheme != "http" or parsed.netloc != "127.0.0.1:5000"+ ):+ continue+ key = f"{method} {parsed.path}"+ if key not in rows:+ continue+ status = int(message["responseHeader"].splitlines()[0].split()[1])+ headers = message["responseHeader"].lower()+ rows[key]["requests"] += 1+ if 200 <= status < 300 and "content-type: application/json" in headers:+ rows[key]["successful_json_responses"] += 1+ return {"active_scans": active_scans, "operations": rows}+++def validate_coverage(report):+ if (+ type(report.get("active_scans")) is not int+ or report["active_scans"] < 1+ ):+ raise ValueError("No completed active scan")+ for path, method in OPERATIONS.items():+ row = report["operations"][f"{method} {path}"]+ if row["requests"] < 1 or row["successful_json_responses"] < 1:+ raise ValueError(+ f"No authenticated active-scan coverage for {method} {path}"+ )+++def zap_pre_shutdown(zap):+ if not AUTHENTICATED:+ raise ValueError("Authenticated scan setup never completed")+ scans = zap.ascan.scans+ if not scans or any(int(scan["progress"]) != 100 for scan in scans):+ raise ValueError("Active scan did not complete")+ ids = sorted(+ {+ str(message_id)+ for scan in scans+ for message_id in zap.ascan.messages_ids(scan["id"])+ }+ )++ def scan_messages():+ for start in range(0, len(ids), 100):+ yield from zap.core.messages_by_id(+ ",".join(ids[start : start + 100])+ )++ report = coverage(scan_messages(), len(scans))+ # Store counts only: never persist session cookies or request/response bodies.+ Path("/zap/wrk/zap-api-coverage.json").write_text(+ json.dumps(report, indent=2) + "\n", encoding="utf-8"+ )+ validate_coverage(report)+ print(+ f"Verified authenticated active-scan coverage for {len(OPERATIONS)} operations"+ )+++if __name__ == "__main__":+ validate_coverage(json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")))diff --git a/scripts/ci/zap_api_target.py b/scripts/ci/zap_api_target.pynew file mode 100644index 0000000000..c812f3a21a--- /dev/null+++ b/scripts/ci/zap_api_target.py@@ -0,0 +1,53 @@+"""Start the disposable authenticated API target used only by ZAP CI."""++import json+import os+from pathlib import Path+++def fixture_summary(query, **kwargs):+ return {"summary": "CI research fixture", "findings": []}+++def fixture_report(query, **kwargs):+ return {"content": "CI research report", "metadata": {}}+++def fixture_documents(query, collection_name, **kwargs):+ return {"summary": "CI document fixture", "documents": []}+++def main():+ if (+ os.environ.get("GITHUB_ACTIONS") != "true"+ or os.environ.get("LDR_TEST_MODE") != "1"+ ):+ raise SystemExit(+ "This fixture target may only run in test-mode GitHub Actions"+ )+ from init_test_database import main as init_database+ from seed_history_delete import main as seed_history+ from zap_api_hooks import build_spec++ init_database()+ seed_history()++ import uvicorn+ from local_deep_research.api import research_functions+ from local_deep_research.web.fastapi_app import app+ from local_deep_research.web.routers import api_v1++ # Keep the real routing, authentication, CSRF, validation, settings and+ # encrypted DB paths. Replace only research-provider work so active scan+ # payloads cannot invoke paid LLMs or external search services.+ research_functions.quick_summary = fixture_summary+ research_functions.generate_report = fixture_report+ api_v1.analyze_documents = fixture_documents+ Path("zap-openapi.json").write_text(+ json.dumps(build_spec(app.openapi()), indent=2) + "\n", encoding="utf-8"+ )+ uvicorn.run(app, host="127.0.0.1", port=5000)+++if __name__ == "__main__":+ main()diff --git a/tests/ci/standalone/test_zap_api_contract.py b/tests/ci/standalone/test_zap_api_contract.pynew file mode 100644index 0000000000..f380e8eaef--- /dev/null+++ b/tests/ci/standalone/test_zap_api_contract.py@@ -0,0 +1,167 @@+"""Check ZAP's schema and coverage contracts without starting the application."""++# allow: no-sut-import — imports the standalone CI hook directly.++import importlib.util+import json+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock, patch++ROOT = Path(__file__).resolve().parents[3]+SPEC = importlib.util.spec_from_file_location(+ "zap_api_hooks", ROOT / "scripts/ci/zap_api_hooks.py"+)+HOOK = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(HOOK)+++def messages(status=200, content_type="application/json"):+ return [+ {+ "requestHeader": f"{method} {HOOK.BASE}{path} HTTP/1.1\r\nHost: 127.0.0.1:5000\r\nCookie: private-fixture\r\n",+ "responseHeader": f"HTTP/1.1 {status} Response\r\nContent-Type: {content_type}\r\n",+ "responseBody": "private-fixture-body",+ }+ for path, method in HOOK.OPERATIONS.items()+ ]+++class ContractTests(unittest.TestCase):+ def test_schema_uses_real_routes_and_has_research_request_bodies(self):+ source = {+ "openapi": "3.1.0",+ "paths": {+ path: {+ method.lower(): {+ "operationId": str(i),+ "responses": {"200": {"description": "OK"}},+ }+ }+ for i, (path, method) in enumerate(HOOK.OPERATIONS.items())+ },+ }+ source["paths"]["/unrelated"] = {"get": {}}+ result = HOOK.build_spec(source)+ self.assertEqual(result["servers"], [{"url": HOOK.BASE}])+ self.assertEqual(set(result["paths"]), set(HOOK.OPERATIONS))+ for path, method in HOOK.OPERATIONS.items():+ if method == "POST":+ body = result["paths"][path]["post"]["requestBody"]["content"][+ "application/json"+ ]["schema"]+ self.assertIn("query", body["required"])+ if path.endswith("analyze_documents"):+ self.assertIn("collection_name", body["required"])+ self.assertNotIn(+ "requestBody", source["paths"]["/api/v1/quick_summary"]["post"]+ )+ del source["paths"]["/api/v1/quick_summary"]+ with self.assertRaises(KeyError):+ HOOK.build_spec(source)++ def test_each_operation_needs_successful_active_scan_requests(self):+ report = HOOK.coverage(messages(), 1)+ HOOK.validate_coverage(report)+ for index in range(len(HOOK.OPERATIONS)):+ data = messages()+ del data[index]+ with self.subTest(index=index), self.assertRaises(ValueError):+ HOOK.validate_coverage(HOOK.coverage(data, 1))++ def test_login_errors_redirects_html_and_inactive_scans_cannot_pass(self):+ for status in (302, 401, 403, 429, 500):+ with self.subTest(status=status), self.assertRaises(ValueError):+ HOOK.validate_coverage(HOOK.coverage(messages(status), 1))+ with self.assertRaises(ValueError):+ HOOK.validate_coverage(+ HOOK.coverage(messages(content_type="text/html"), 1)+ )+ with self.assertRaises(ValueError):+ HOOK.validate_coverage(HOOK.coverage(messages(), 0))++ def test_an_unrelated_host_cannot_supply_coverage(self):+ data = messages()+ for message in data:+ message["requestHeader"] = message["requestHeader"].replace(+ "http://127.0.0.1:5000", "https://example.invalid"+ )+ with self.assertRaises(ValueError):+ HOOK.validate_coverage(HOOK.coverage(data, 1))++ def test_login_preflight_does_not_follow_redirects(self):+ replies = [+ (401, {}),+ (200, {"csrf_token": "before-login"}),+ (302, b""),+ (200, {"csrf_token": "after-login"}),+ (403, {}),+ *((200, {"items": ["seed"]}) for _ in HOOK.OPERATIONS),+ ]++ def add_cookie(jar, request):+ request.add_header("Cookie", "fixture-session")++ with (+ patch.object(HOOK, "request", side_effect=replies) as request,+ patch.object(+ HOOK.http.cookiejar.CookieJar, "add_cookie_header", add_cookie+ ),+ ):+ self.assertEqual(+ HOOK.authenticate(), ("fixture-session", "after-login")+ )+ for call in request.call_args_list:+ self.assertTrue(+ any(+ isinstance(handler, HOOK.NoRedirect)+ for handler in call.args[0].handlers+ )+ )+ self.assertEqual(request.call_args_list[2].args[3], "before-login")+ self.assertEqual(request.call_args_list[-1].args[3], "after-login")++ def test_authenticated_headers_are_bound_to_loopback_target(self):+ zap = SimpleNamespace(+ replacer=SimpleNamespace(add_rule=Mock(return_value="OK"))+ )+ with (+ patch.object(+ HOOK,+ "authenticate",+ return_value=("fixture-cookie", "fixture-csrf"),+ ),+ patch.object(HOOK, "AUTHENTICATED", False),+ ):+ HOOK.zap_started(zap, "/zap/wrk/zap-openapi.json")+ self.assertTrue(HOOK.AUTHENTICATED)+ self.assertEqual(zap.replacer.add_rule.call_count, 2)+ for call in zap.replacer.add_rule.call_args_list:+ self.assertEqual(+ call.kwargs["url"], r"^http://127\.0\.0\.1:5000/.*$"+ )+ self.assertEqual(call.kwargs["matchtype"], "REQ_HEADER")++ def test_evidence_comes_from_active_scan_message_ids_and_is_redacted(self):+ zap = SimpleNamespace(+ ascan=SimpleNamespace(+ scans=[{"id": "0", "progress": "100"}],+ messages_ids=Mock(return_value=["1", "2"]),+ ),+ core=SimpleNamespace(messages_by_id=Mock(return_value=messages())),+ )+ with (+ patch.object(HOOK, "AUTHENTICATED", True),+ patch.object(HOOK.Path, "write_text") as write,+ ):+ HOOK.zap_pre_shutdown(zap)+ stored = write.call_args.args[0]+ HOOK.validate_coverage(json.loads(stored))+ self.assertNotIn("private-fixture", stored)+ zap.ascan.messages_ids.assert_called_once_with("0")+ zap.core.messages_by_id.assert_called_once_with("1,2")+++if __name__ == "__main__":+ unittest.main()