Files
computer-playbook/cli/contributing/network/diagnose/tools.py
T
kevinveenbirkenbachandClaude Opus 4.8 fc77d9d265 fix(security): resolve all open code-scanning alerts and guard against recurrence
Resolve the 80 open CodeQL/code-scanning alerts on this branch.

Security-sensitive fixes:
- cli/administration/deploy/development: break the unsafe import cycle by
  extracting the env/arg helpers into a leaf module `env.py`, giving the
  load-time DAG compose -> common -> deps -> env.
- web-app-bluesky login-broker server.js: prototype-pollution guard on
  cookie parsing, CR/LF + control-char log sanitisation, HTML-escaped
  exception text, and a ReDoS-bounded handle regex.
- web-app-baserow SSO: harden the open-redirect `next` handling.
- network diagnose probes: require TLS >= 1.2.
- actionlint installer: validate tar members against path traversal.
- decidim/apt-purge lint regexes: rewrite to avoid catastrophic backtracking.
- 6x Playwright URL regexes anchored; crs-k/stale-branches pinned to a commit SHA.

Mechanical cleanups: unused imports/globals/locals, empty-except comments,
import-and-import-from, implicit-string-concat, multiple-definition,
unreachable/useless-assignment.

False positives are intentionally left in place (Django settings patches,
Odoo __manifest__, side-effect imports, cross-module symbols).

Recurrence guards:
- import-linter contract (pyproject + tests/lint) locks the dev-deploy
  package acyclic; a new cycle now fails CI instead of only CodeQL.
- new lint test requires every bandit (S###) `noqa` to carry a justification.
- BLE001 (blind-except) added to ruff as a ratchet (tests/roles exempt,
  current production offenders grandfathered).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 15:42:03 +02:00

65 lines
2.0 KiB
Python

"""Detect the host distro and self-install the binaries the diagnose probes need."""
from __future__ import annotations
import os
import shutil
import sys
from pathlib import Path
from cli.contributing.network.diagnose.config import INSTALL_CMDS, TOOLS
from cli.contributing.network.diagnose.format import cmd_capture
def detect_distro_id(*, os_release_path: str = "/etc/os-release") -> str:
"""Return the distro id from /etc/os-release, lowercased; empty string when unreadable."""
try:
text = Path(os_release_path).read_text() # nocheck: cache-read
for raw in text.splitlines():
if raw.startswith("ID="):
return raw.split("=", 1)[1].strip().strip('"').lower()
except OSError:
pass # best-effort: return empty distro id when /etc/os-release is unreadable
return ""
def missing_tools() -> list[str]:
return [t for t in TOOLS if shutil.which(t) is None]
def ensure_tools() -> None:
"""Install the missing TOOLS via the distro's package manager, when possible."""
missing = missing_tools()
if not missing:
return
distro = detect_distro_id()
cmd = INSTALL_CMDS.get(distro)
if cmd is None:
print(
f" [tool-install] missing {missing} but distro={distro or '?'} unsupported; skipping",
file=sys.stderr,
)
return
if distro in ("debian", "ubuntu"):
rc_upd, _ = cmd_capture(
["apt-get", "update", "-o", "DPkg::Lock::Timeout=120"], timeout=180.0
)
if rc_upd != 0:
print(
f" [tool-install] apt-get update rc={rc_upd}; trying install anyway",
file=sys.stderr,
)
if os.geteuid() != 0 and shutil.which("sudo"):
cmd = ["sudo", *cmd]
print(
f" [tool-install] installing {' '.join(cmd[-2:])} via {distro}",
file=sys.stderr,
)
rc, out = cmd_capture(cmd, timeout=180.0)
if rc != 0:
print(f" [tool-install] FAILED rc={rc}: {out.strip()[:200]}", file=sys.stderr)