~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(security): resolve SQLCipher Bearer alerts and validate scan uploads (#7377)
LearningCircuitb47d59b3ebe4
diff --git a/.github/scripts/prepare_bearer_sarif.py b/.github/scripts/prepare_bearer_sarif.pynew file mode 100644index 0000000000..998deb3d9b--- /dev/null+++ b/.github/scripts/prepare_bearer_sarif.py@@ -0,0 +1,96 @@+"""Prepare successful Bearer scans for GitHub without discarding findings.++Bearer 2.1.2 emits results:null for a clean scan, but SARIF requires an array.+Only normalize that representation. The workflow must first require scanner+success: a report alone cannot prove that the scan completed.+"""++import argparse+import json+from pathlib import Path+++def _reject_constant(name: str) -> None:+ raise ValueError(f"non-standard JSON constant {name} in report")+++def _load(path: Path) -> object:+ # json accepts NaN/Infinity, which RFC 8259 parsers downstream reject.+ return json.loads(+ path.read_text(encoding="utf-8"), parse_constant=_reject_constant+ )+++def prepare(source: Path, destination: Path) -> None:+ if source.resolve() == destination.resolve():+ raise ValueError("preserve the original Bearer report")+ report = _load(source)+ if not isinstance(report, dict) or report.get("version") != "2.1.0":+ raise ValueError("expected a SARIF 2.1.0 report")+ runs = report.get("runs")+ if not isinstance(runs, list) or len(runs) != 1:+ raise ValueError("expected one Bearer scan run")+ run = runs[0]+ if not isinstance(run, dict):+ raise ValueError("invalid Bearer run")+ tool = run.get("tool")+ driver = tool.get("driver") if isinstance(tool, dict) else None+ if not isinstance(driver, dict) or driver.get("name") != "Bearer":+ raise ValueError("expected a Bearer report")+ if "results" not in run:+ raise ValueError("missing scan results are not a clean scan")+ invocations = run.get("invocations", [])+ if not isinstance(invocations, list) or any(+ not isinstance(invocation, dict)+ or invocation.get("executionSuccessful") is not True+ for invocation in invocations+ ):+ raise ValueError("report contains an unsuccessful invocation")+ results = run["results"]+ if results is None:+ run["results"] = []+ elif not isinstance(results, list) or any(+ not isinstance(result, dict) for result in results+ ):+ raise ValueError("invalid scan results")+ destination.write_text(+ json.dumps(report, indent=2) + "\n", encoding="utf-8"+ )+++def level_counts(path: Path) -> tuple[int, int, int, int]:+ """Count a prepared report's findings as errors, warnings, notes, total.++ Bearer leaves ``level`` off its results and sets it on the rule's+ ``defaultConfiguration`` instead; SARIF falls back to "warning" when+ neither is present.+ """+ run = _load(path)["runs"][0]+ rules = run["tool"]["driver"].get("rules") or []+ defaults = {+ rule.get("id"): (rule.get("defaultConfiguration") or {}).get("level")+ for rule in rules+ if isinstance(rule, dict)+ }+ levels = [+ result.get("level") or defaults.get(result.get("ruleId")) or "warning"+ for result in run["results"]+ ]+ return (+ levels.count("error"),+ levels.count("warning"),+ levels.count("note"),+ len(levels),+ )+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("source", type=Path)+ parser.add_argument("destination", type=Path)+ args = parser.parse_args()+ prepare(args.source, args.destination)+++if __name__ == "__main__":+ main()diff --git a/.github/workflows/bearer.yml b/.github/workflows/bearer.ymlindex 3deff76d3b..ec6c65e44b 100644--- a/.github/workflows/bearer.yml+++ b/.github/workflows/bearer.yml@@ -1,6 +1,13 @@name: Bearer Security Scanon:+ pull_request:+ paths:+ - "src/local_deep_research/database/sqlcipher_compat.py"+ - "bearer.yml"+ - ".github/workflows/bearer.yml"+ - ".github/scripts/prepare_bearer_sarif.py"+ - "tests/ci/standalone/test_bearer_sarif.py"workflow_dispatch:workflow_call: # Called by release-gate.ymlschedule:@@ -29,6 +36,9 @@ jobs:with:persist-credentials: false+ - name: Test Bearer report preparation+ run: python3 -m unittest discover -s tests/ci/standalone -p 'test_bearer_sarif.py' -v+- name: Run Bearer SAST Scanneruses: bearer/bearer-action@828eeb928ce2f4a7ca5ed57fb8b59508cb8c79bc # v2with:@@ -41,36 +51,32 @@ jobs:# Failing here would break CI without adding security value.exit-code: 0- # Fail loudly if Bearer produced no SARIF — never fabricate an empty one.- # An empty-results SARIF uploaded under the bearer-security category would- # make GitHub mark every previously-open Bearer alert as fixed, silently- # clearing real findings. Mirror the Grype/Trivy jobs: error + exit 1, skip- # upload. bearer-action writes a SARIF even with zero findings, so a missing- # file means a real scan failure, not a clean run.- - name: Ensure SARIF file exists+ # Run only after scanner success. Bearer 2.1.2 represents a clean scan+ # as results:null, which GitHub rejects. Preserve the raw report and+ # normalize only that value; missing/malformed reports still fail.+ # Never upload a partial report left behind by a failed scanner.+ - name: Prepare successful Bearer SARIF for GitHubid: check-sarif- if: always()run: |- if [ -f bearer-results.sarif ]; then- echo "exists=true" >> "$GITHUB_OUTPUT"- else- echo "::error::Bearer did not produce a SARIF file — scan needs to be rerun"- exit 1- fi+ python3 .github/scripts/prepare_bearer_sarif.py bearer-results.sarif bearer-results.github.sarif+ echo "exists=true" >> "$GITHUB_OUTPUT"- name: Upload Bearer results to GitHub Security tabuses: github/codeql-action/upload-sarif@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0- if: always() && steps.check-sarif.outputs.exists == 'true'+ if: success() && steps.check-sarif.outputs.exists == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)with:- sarif_file: bearer-results.sarif+ sarif_file: bearer-results.github.sarifcategory: bearer-security+ wait-for-processing: true- name: Upload Bearer results as artifactuses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2- if: always() && steps.check-sarif.outputs.exists == 'true'+ if: always()with:name: bearer-scan-results- path: bearer-results.sarif+ path: |+ bearer-results.sarif+ bearer-results.github.sarifretention-days: 7- name: Display Bearer summary@@ -81,12 +87,10 @@ jobs:echo ""} >> "$GITHUB_STEP_SUMMARY"- if [ -f bearer-results.sarif ]; then- # Count findings by level- ERRORS=$(python3 -c "import json; data=json.load(open('bearer-results.sarif')); results=data.get('runs',[{}])[0].get('results',[]); print(len([r for r in results if r.get('level')=='error']))" 2>/dev/null || echo "0")- WARNINGS=$(python3 -c "import json; data=json.load(open('bearer-results.sarif')); results=data.get('runs',[{}])[0].get('results',[]); print(len([r for r in results if r.get('level')=='warning']))" 2>/dev/null || echo "0")- NOTES=$(python3 -c "import json; data=json.load(open('bearer-results.sarif')); results=data.get('runs',[{}])[0].get('results',[]); print(len([r for r in results if r.get('level')=='note']))" 2>/dev/null || echo "0")- TOTAL=$(python3 -c "import json; data=json.load(open('bearer-results.sarif')); print(len(data.get('runs',[{}])[0].get('results',[])))" 2>/dev/null || echo "0")+ if [ -f bearer-results.github.sarif ]; then+ # Count findings by effective level (Bearer sets it on the rule)+ COUNTS=$(python3 -c "import sys; sys.path.insert(0, '.github/scripts'); from pathlib import Path; from prepare_bearer_sarif import level_counts; print(*level_counts(Path('bearer-results.github.sarif')))")+ read -r ERRORS WARNINGS NOTES TOTAL <<< "$COUNTS"{echo "📊 **Scan Results:**"diff --git a/changelog.d/+bearer-clean-scan.security.md b/changelog.d/+bearer-clean-scan.security.mdnew file mode 100644index 0000000000..4b6143e914--- /dev/null+++ b/changelog.d/+bearer-clean-scan.security.md@@ -0,0 +1 @@+Resolve the two fixed-name SQLCipher wrapper false positives and make clean Bearer reports valid for GitHub. Preserve original scan artifacts and prevent failed scans from uploading results that could clear existing alerts.diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.mdindex 594047d2ce..33ccf6fb3c 100644--- a/docs/ci/workflow-status.md+++ b/docs/ci/workflow-status.md@@ -57,7 +57,7 @@| Workflow | Last activity | Trigger | Live badge ||---|---|---|---|| `backwards-compatibility.yml` | last 30 days | workflow_call, PR, push:main, release, schedule(0 2 * * 0), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/backwards-compatibility.yml) |-| `bearer.yml` | last 30 days | manual, workflow_call, schedule(0 4 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/bearer.yml) |+| `bearer.yml` | last 30 days | PR, manual, workflow_call, schedule(0 4 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/bearer.yml) || `checkov.yml` | last 30 days | manual, workflow_call | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/checkov.yml) || `codeql.yml` | last 30 days | push:main, PR, schedule(45 5 * * 0), workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/codeql.yml) || `container-security.yml` | last 30 days | workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/container-security.yml) |diff --git a/src/local_deep_research/database/sqlcipher_compat.py b/src/local_deep_research/database/sqlcipher_compat.pyindex 01a9636ff4..a91efa08a5 100644--- a/src/local_deep_research/database/sqlcipher_compat.py+++ b/src/local_deep_research/database/sqlcipher_compat.py@@ -137,6 +137,9 @@ def _guarded_connection_type(connection_type, cursor_type, check_same_thread):for name in _CURSOR_THREAD_CHECKED:if hasattr(cursor_type, name):+ # bearer:disable python_lang_code_injection+ # ``name`` only ever comes from the hardcoded+ # _CURSOR_THREAD_CHECKED tuple above, never from input.setattr(ThreadCheckedCursor,name,@@ -146,6 +149,9 @@ def _guarded_connection_type(connection_type, cursor_type, check_same_thread):)for name in _CONNECTION_THREAD_CHECKED:if hasattr(connection_type, name):+ # bearer:disable python_lang_code_injection+ # ``name`` only ever comes from the hardcoded+ # _CONNECTION_THREAD_CHECKED tuple above, never from input.setattr(LifecycleConnection,name,diff --git a/tests/ci/standalone/test_bearer_sarif.py b/tests/ci/standalone/test_bearer_sarif.pynew file mode 100644index 0000000000..cfdd435665--- /dev/null+++ b/tests/ci/standalone/test_bearer_sarif.py@@ -0,0 +1,131 @@+"""Keep clean Bearer uploads valid without hiding failed scans or findings."""++import copy+import importlib.util+import json+import tempfile+import unittest+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[3]+SPEC = importlib.util.spec_from_file_location(+ "prepare_bearer", ROOT / ".github/scripts/prepare_bearer_sarif.py"+)+PREPARE = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(PREPARE)+++class BearerSarifTests(unittest.TestCase):+ def setUp(self):+ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.source = Path(directory.name) / "raw.sarif"+ self.destination = Path(directory.name) / "upload.sarif"+ self.report = {+ "version": "2.1.0",+ "runs": [{"tool": {"driver": {"name": "Bearer"}}, "results": None}],+ }++ def prepare(self):+ raw = json.dumps(self.report)+ self.source.write_text(raw)+ PREPARE.prepare(self.source, self.destination)+ self.assertEqual(self.source.read_text(), raw)+ return json.loads(self.destination.read_text())++ def test_native_null_becomes_empty_array_only(self):+ expected = copy.deepcopy(self.report)+ expected["runs"][0]["results"] = []+ self.assertEqual(self.prepare(), expected)++ def test_existing_findings_and_metadata_are_preserved(self):+ run = self.report["runs"][0]+ run["results"] = [+ {"ruleId": "python_lang_code_injection", "level": "error"}+ ]+ run["tool"]["driver"]["rules"] = [{"id": "python_lang_code_injection"}]+ run["properties"] = {"scan": "canary"}+ run["invocations"] = [{"executionSuccessful": True}]+ self.assertEqual(self.prepare(), self.report)++ def test_valid_empty_scan_is_preserved(self):+ self.report["runs"][0]["results"] = []+ self.assertEqual(self.prepare(), self.report)++ def test_incomplete_wrong_tool_and_failed_scans_do_not_create_upload(self):+ mutations = (+ lambda r: r.update(version="1.0.0"),+ lambda r: r.update(runs=[]),+ lambda r: r["runs"].append(copy.deepcopy(r["runs"][0])),+ lambda r: r["runs"][0].pop("results"),+ lambda r: r["runs"][0].update(results={}),+ lambda r: r["runs"][0].update(results=[None]),+ lambda r: r["runs"][0].update(tool=None),+ lambda r: r["runs"][0]["tool"]["driver"].update(name="other"),+ lambda r: r["runs"][0].update(+ invocations=[{"executionSuccessful": False}]+ ),+ lambda r: r["runs"][0].update(invocations=[{}]),+ lambda r: r["runs"][0].update(+ invocations=[{"executionSuccessful": 1}]+ ),+ )+ original = copy.deepcopy(self.report)+ for mutate in mutations:+ with self.subTest(mutation=mutate):+ self.report = copy.deepcopy(original)+ mutate(self.report)+ with self.assertRaises(ValueError):+ self.prepare()+ self.assertFalse(self.destination.exists())++ def test_missing_or_invalid_input_does_not_create_upload(self):+ with self.assertRaises(FileNotFoundError):+ PREPARE.prepare(self.source, self.destination)+ self.source.write_text("{truncated")+ with self.assertRaises(ValueError):+ PREPARE.prepare(self.source, self.destination)+ self.assertFalse(self.destination.exists())++ def test_non_standard_json_constants_do_not_create_upload(self):+ for constant in ("NaN", "Infinity", "-Infinity"):+ with self.subTest(constant=constant):+ self.source.write_text(+ json.dumps(self.report).replace(+ '"results": null',+ '"results": [], "properties": {"score": %s}' % constant,+ )+ )+ with self.assertRaises(ValueError):+ PREPARE.prepare(self.source, self.destination)+ self.assertFalse(self.destination.exists())++ def test_level_counts_fall_back_to_rule_default_then_warning(self):+ run = self.report["runs"][0]+ run["tool"]["driver"]["rules"] = [+ {"id": "ruled", "defaultConfiguration": {"level": "error"}},+ {"id": "unruled"},+ ]+ run["results"] = [+ {"ruleId": "ruled"},+ {"ruleId": "ruled", "level": "note"},+ {"ruleId": "unruled"},+ {"ruleId": "unknown", "level": "warning"},+ ]+ self.prepare()+ self.assertEqual(PREPARE.level_counts(self.destination), (1, 2, 1, 4))++ def test_level_counts_of_a_clean_scan(self):+ self.prepare()+ self.assertEqual(PREPARE.level_counts(self.destination), (0, 0, 0, 0))++ def test_cannot_overwrite_raw_report(self):+ self.source.write_text(json.dumps(self.report))+ with self.assertRaises(ValueError):+ PREPARE.prepare(self.source, self.source)+ self.assertEqual(json.loads(self.source.read_text()), self.report)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/ci/test_bearer_workflow.py b/tests/ci/test_bearer_workflow.pynew file mode 100644index 0000000000..4922a34678--- /dev/null+++ b/tests/ci/test_bearer_workflow.py@@ -0,0 +1,72 @@+"""Contracts for when the Bearer workflow may upload to code scanning."""++# allow: no-sut-import — this test parses .github/workflows/bearer.yml+# directly; the "system under test" is CI configuration, not application+# code, so there is nothing under local_deep_research to import.++from pathlib import Path++import yaml+++REPO_ROOT = Path(__file__).resolve().parents[2]+WORKFLOW = REPO_ROOT / ".github" / "workflows" / "bearer.yml"+++def _steps() -> list[dict]:+ workflow = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))+ return workflow["jobs"]["bearer-scan"]["steps"]+++def _step(prefix: str) -> dict:+ return next(+ step+ for step in _steps()+ if str(step.get("uses", "")).startswith(prefix)+ )+++def test_code_scanning_upload_needs_a_successful_scan():+ """A failed Bearer run can leave a partial SARIF behind.++ Uploading it under the same category would mark the missing findings as+ fixed, so the upload must run only after every earlier step succeeded+ and must read the prepared report, never the raw scanner output.+ """+ upload = _step("github/codeql-action/upload-sarif@")+ condition = upload["if"]+ assert condition.startswith("success() && ")+ assert "always()" not in condition+ assert "steps.check-sarif.outputs.exists == 'true'" in condition+ assert upload["with"]["sarif_file"] == "bearer-results.github.sarif"+ assert upload["with"]["category"] == "bearer-security"+ assert "continue-on-error" not in upload+++def test_report_is_prepared_before_upload_and_scan_failures_are_not_masked():+ steps = _steps()+ names = [step.get("name", "") for step in steps]+ prepare = names.index("Prepare successful Bearer SARIF for GitHub")+ upload = next(+ index+ for index, step in enumerate(steps)+ if str(step.get("uses", "")).startswith(+ "github/codeql-action/upload-sarif@"+ )+ )+ assert prepare < upload+ assert "if" not in steps[prepare], "prepare must not run after a failure"+ assert (+ "prepare_bearer_sarif.py bearer-results.sarif" in steps[prepare]["run"]+ )+ scanner = _step("bearer/bearer-action@")+ assert "continue-on-error" not in scanner+ assert "if" not in scanner+++def test_fork_pull_requests_scan_without_uploading():+ condition = _step("github/codeql-action/upload-sarif@")["if"]+ assert (+ "github.event_name != 'pull_request' || "+ "github.event.pull_request.head.repo.full_name == github.repository"+ ) in condition