From 50a91cfeabf9f26619c1e14ae8f087d686e07887 Mon Sep 17 00:00:00 2001 From: Ayham Joumran <140757050+AyhamJo7@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:08:24 +0100 Subject: [PATCH 1/3] fix(lint): resolve the error-handling ruff findings in src Best-effort catches that swallowed failures silently now log them at debug level and say in one line why they stay broad. subprocess.run in _git_head_commit passes check=False like its sibling, RunRepository.__enter__ returns Self, and the percentile index drops a redundant int(). Behaviour is unchanged; a new test pins the git fallbacks and the logged cloud-sync failure. Closes #168 --- src/secfoo/docext.py | 6 +++++- src/secfoo/runner.py | 13 +++++++------ src/secfoo/storage/repository.py | 6 +++++- src/secfoo/web/dashboard_common.py | 2 +- src/secfoo/web/templating.py | 6 +++++- tests/test_runner_best_effort.py | 30 ++++++++++++++++++++++++++++++ 6 files changed, 53 insertions(+), 10 deletions(-) create mode 100644 tests/test_runner_best_effort.py diff --git a/src/secfoo/docext.py b/src/secfoo/docext.py index 74b9b4b..54f82a8 100644 --- a/src/secfoo/docext.py +++ b/src/secfoo/docext.py @@ -28,9 +28,12 @@ from __future__ import annotations +import logging import zipfile from pathlib import Path +logger = logging.getLogger(__name__) + SUPPORTED_EXTENSIONS = {".pdf", ".docx", ".pptx"} # Generous for a real vendor security document (SOC 2 reports, ISO @@ -107,7 +110,8 @@ def extract_text(path: Path) -> str: return _extract_docx(path) if suffix == ".pptx": return _extract_pptx(path) - except Exception: + except Exception: # Broad on purpose: the parsers raise many types; a bad file means "" + logger.debug("text extraction failed for a %s file", suffix, exc_info=True) return "" return "" diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 6fe8f04..b46eb3b 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -57,10 +57,11 @@ def _git_head_commit(path: Path) -> str | None: try: result = subprocess.run( ["git", "-C", str(path), "rev-parse", "HEAD"], - capture_output=True, text=True, timeout=10, + capture_output=True, text=True, timeout=10, check=False, ) return result.stdout.strip() if result.returncode == 0 else None - except Exception: + except Exception: # Broad on purpose: the commit is optional metadata; any failure is "unknown" + logger.debug("git HEAD lookup failed", exc_info=True) return None @@ -156,8 +157,8 @@ def _try_cloud_sync(repo: RunRepository, run_uuid: str) -> None: if config is None: return cloud.sync_run(repo, run_uuid, config) - except Exception: - pass + except Exception: # Broad on purpose: any sync failure must not fail the local run + logger.debug("cloud sync skipped for run %s", run_uuid, exc_info=True) def _try_osv_enrich(repo: RunRepository, report_text: str) -> None: @@ -173,8 +174,8 @@ def _try_osv_enrich(repo: RunRepository, report_text: str) -> None: keys = osv_keys_for_report(report_text) if keys: osv.enrich_lookups(repo, list(keys)) - except Exception: - pass + except Exception: # Broad on purpose: any enrichment failure must not fail the local run + logger.debug("OSV enrichment skipped", exc_info=True) def _stack_fields(stack: Stack | None, language: str | None) -> dict[str, str | None]: diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index 4059263..f183ce0 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -9,10 +9,14 @@ from contextvars import ContextVar from datetime import datetime, timedelta, timezone from pathlib import Path +from typing import TYPE_CHECKING from secfoo.config import DB_PATH, ensure_store_dirs from secfoo.report.markdown import read_stored_report +if TYPE_CHECKING: + from typing_extensions import Self + # Lets a host process that serves multiple SQLite files (the multi-tenant # portal, one file per tenant) select which file `RunRepository()` opens # without a caller having to pass db_path explicitly -- every route in @@ -344,7 +348,7 @@ def _migrate_attachment_kind_check(self) -> None: def close(self) -> None: self._conn.close() - def __enter__(self) -> "RunRepository": + def __enter__(self) -> Self: return self def __exit__(self, *exc: object) -> None: diff --git a/src/secfoo/web/dashboard_common.py b/src/secfoo/web/dashboard_common.py index 604fc60..6d19ecf 100644 --- a/src/secfoo/web/dashboard_common.py +++ b/src/secfoo/web/dashboard_common.py @@ -15,7 +15,7 @@ def percentile(values: list[float], pct: float) -> float | None: if not values: return None ordered = sorted(values) - index = min(len(ordered) - 1, int(round(pct / 100 * (len(ordered) - 1)))) + index = min(len(ordered) - 1, round(pct / 100 * (len(ordered) - 1))) return ordered[index] diff --git a/src/secfoo/web/templating.py b/src/secfoo/web/templating.py index 4718f9c..ec0df48 100644 --- a/src/secfoo/web/templating.py +++ b/src/secfoo/web/templating.py @@ -1,5 +1,6 @@ from __future__ import annotations +import logging import re from pathlib import Path @@ -12,6 +13,8 @@ from secfoo.report.architecture import classify_design_verdict from secfoo.skills.loader import load_all_skills +logger = logging.getLogger(__name__) + TEMPLATES_DIR = Path(__file__).parent / "templates" templates = Jinja2Templates(directory=str(TEMPLATES_DIR)) @@ -299,7 +302,8 @@ def active_run_count() -> int: try: with RunRepository() as repo: return len(repo.list_runs(status="running", limit=100)) - except Exception: + except Exception: # Broad on purpose: a storage problem must not break page rendering + logger.debug("active run count unavailable", exc_info=True) return 0 diff --git a/tests/test_runner_best_effort.py b/tests/test_runner_best_effort.py new file mode 100644 index 0000000..1aa2a1f --- /dev/null +++ b/tests/test_runner_best_effort.py @@ -0,0 +1,30 @@ +"""The runner's best-effort helpers degrade quietly but leave a debug trace.""" + +import logging +import subprocess + +from secfoo import runner + + +def test_git_head_commit_is_none_without_a_git_binary(tmp_path, monkeypatch): + monkeypatch.setenv("PATH", str(tmp_path)) + assert runner._git_head_commit(tmp_path) is None + + +def test_git_head_commit_is_none_when_git_times_out(tmp_path, monkeypatch): + def timeout(*args, **kwargs): + raise subprocess.TimeoutExpired(cmd="git", timeout=10) + + monkeypatch.setattr(subprocess, "run", timeout) + assert runner._git_head_commit(tmp_path) is None + + +def test_a_failed_cloud_sync_is_logged_and_does_not_raise(monkeypatch, caplog): + def broken_config(): + raise RuntimeError("portal unreachable") + + monkeypatch.setattr(runner.cloud, "load_cloud_config", broken_config) + with caplog.at_level(logging.DEBUG, logger="secfoo.runner"): + runner._try_cloud_sync(repo=None, run_uuid="run-1") + + assert any("cloud sync skipped for run run-1" in r.getMessage() for r in caplog.records) From e9331a8b3073e1cfd79181c9891a8e8ba5e18efb Mon Sep 17 00:00:00 2001 From: aitechnology <40792067+vsn411@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:44:25 +0000 Subject: [PATCH 2/3] fix(lint): mark the kept broad excepts noqa BLE001; make sync_design_system.py executable Logging at debug level does not satisfy BLE001, so each broad catch that stays keeps its reason and an explicit noqa. EXE001: the script has a shebang, so give it the executable bit like check_pypi_version.py. Co-Authored-By: Claude Opus 5.5 --- scripts/sync_design_system.py | 0 src/secfoo/docext.py | 2 +- src/secfoo/runner.py | 6 +++--- src/secfoo/web/templating.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) mode change 100644 => 100755 scripts/sync_design_system.py diff --git a/scripts/sync_design_system.py b/scripts/sync_design_system.py old mode 100644 new mode 100755 diff --git a/src/secfoo/docext.py b/src/secfoo/docext.py index 54f82a8..eb45d79 100644 --- a/src/secfoo/docext.py +++ b/src/secfoo/docext.py @@ -110,7 +110,7 @@ def extract_text(path: Path) -> str: return _extract_docx(path) if suffix == ".pptx": return _extract_pptx(path) - except Exception: # Broad on purpose: the parsers raise many types; a bad file means "" + except Exception: # noqa: BLE001 -- broad on purpose: the parsers raise many types; a bad file means "" logger.debug("text extraction failed for a %s file", suffix, exc_info=True) return "" return "" diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index b46eb3b..8b09b09 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -60,7 +60,7 @@ def _git_head_commit(path: Path) -> str | None: capture_output=True, text=True, timeout=10, check=False, ) return result.stdout.strip() if result.returncode == 0 else None - except Exception: # Broad on purpose: the commit is optional metadata; any failure is "unknown" + except Exception: # noqa: BLE001 -- broad on purpose: the commit is optional metadata; any failure is "unknown" logger.debug("git HEAD lookup failed", exc_info=True) return None @@ -157,7 +157,7 @@ def _try_cloud_sync(repo: RunRepository, run_uuid: str) -> None: if config is None: return cloud.sync_run(repo, run_uuid, config) - except Exception: # Broad on purpose: any sync failure must not fail the local run + except Exception: # noqa: BLE001 -- broad on purpose: any sync failure must not fail the local run logger.debug("cloud sync skipped for run %s", run_uuid, exc_info=True) @@ -174,7 +174,7 @@ def _try_osv_enrich(repo: RunRepository, report_text: str) -> None: keys = osv_keys_for_report(report_text) if keys: osv.enrich_lookups(repo, list(keys)) - except Exception: # Broad on purpose: any enrichment failure must not fail the local run + except Exception: # noqa: BLE001 -- broad on purpose: any enrichment failure must not fail the local run logger.debug("OSV enrichment skipped", exc_info=True) diff --git a/src/secfoo/web/templating.py b/src/secfoo/web/templating.py index ec0df48..76ea080 100644 --- a/src/secfoo/web/templating.py +++ b/src/secfoo/web/templating.py @@ -302,7 +302,7 @@ def active_run_count() -> int: try: with RunRepository() as repo: return len(repo.list_runs(status="running", limit=100)) - except Exception: # Broad on purpose: a storage problem must not break page rendering + except Exception: # noqa: BLE001 -- broad on purpose: a storage problem must not break page rendering logger.debug("active run count unavailable", exc_info=True) return 0 From 05e6c6dc8391543ba714d5c456edf4b13c8a0c08 Mon Sep 17 00:00:00 2001 From: Ayham Joumran <140757050+AyhamJo7@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:20:20 +0100 Subject: [PATCH 3/3] fix(docext): keep file-derived values out of the extraction debug log CodeQL flagged the new debug line as log injection because it formatted the upload's suffix. Only .pdf/.docx/.pptx can reach it, but the traceback already names the parser, so the message drops the value. --- src/secfoo/docext.py | 3 ++- tests/test_runner_best_effort.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/secfoo/docext.py b/src/secfoo/docext.py index eb45d79..9cf329d 100644 --- a/src/secfoo/docext.py +++ b/src/secfoo/docext.py @@ -111,7 +111,8 @@ def extract_text(path: Path) -> str: if suffix == ".pptx": return _extract_pptx(path) except Exception: # noqa: BLE001 -- broad on purpose: the parsers raise many types; a bad file means "" - logger.debug("text extraction failed for a %s file", suffix, exc_info=True) + # No file-derived value in the message: the traceback names the parser. + logger.debug("text extraction failed", exc_info=True) return "" return "" diff --git a/tests/test_runner_best_effort.py b/tests/test_runner_best_effort.py index 1aa2a1f..d5a8275 100644 --- a/tests/test_runner_best_effort.py +++ b/tests/test_runner_best_effort.py @@ -28,3 +28,18 @@ def broken_config(): runner._try_cloud_sync(repo=None, run_uuid="run-1") assert any("cloud sync skipped for run run-1" in r.getMessage() for r in caplog.records) + + +def test_a_failed_extraction_logs_nothing_from_the_file_name(tmp_path, monkeypatch, caplog): + from secfoo import docext + + def broken(path): + raise ValueError("bad pdf") + + monkeypatch.setattr(docext, "_extract_pdf", broken) + with caplog.at_level(logging.DEBUG, logger="secfoo.docext"): + assert docext.extract_text(tmp_path / "upload.pdf") == "" + + (record,) = [r for r in caplog.records if r.name == "secfoo.docext"] + assert record.args == () + assert record.getMessage() == "text extraction failed"