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 74b9b4b..9cf329d 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,9 @@ def extract_text(path: Path) -> str: return _extract_docx(path) if suffix == ".pptx": return _extract_pptx(path) - except Exception: + except Exception: # noqa: BLE001 -- broad on purpose: the parsers raise many types; a bad file means "" + # 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/src/secfoo/runner.py b/src/secfoo/runner.py index 6fe8f04..8b09b09 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: # 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 @@ -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: # 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) 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: # noqa: BLE001 -- 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..76ea080 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: # noqa: BLE001 -- 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..d5a8275 --- /dev/null +++ b/tests/test_runner_best_effort.py @@ -0,0 +1,45 @@ +"""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) + + +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"