Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Security: pin the credential-send allowlist entry to the reviewed file (#8104)
Daniel Hand24f0f175ae9
diff --git a/scripts/scan_packages.py b/scripts/scan_packages.pyindex 73f6ff22912..36c81fb20a8 100644--- a/scripts/scan_packages.py+++ b/scripts/scan_packages.py@@ -422,6 +422,8 @@ class Finding:filename: strcheck: strevidence: str = ""+ # Whole-file digest; a baseline entry may pin it (see _load_baseline).+ file_sha256: str = ""# Checkers@@ -1151,6 +1153,9 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:))+ digest = hashlib.sha256(original.encode("utf-8", "replace")).hexdigest()+ for f in findings:+ f.file_sha256 = digestreturn findings@@ -2971,24 +2976,30 @@ def _finding_key(f: Finding) -> tuple[str, str, str, str]:)-def _load_baseline(path: str) -> set[tuple[str, str, str, str]]:- """Load an allowlist JSON into a set of match keys. Missing file -> empty."""+def _load_baseline(path: str) -> "dict[tuple[str, str, str, str], set[str] | None]":+ """Load an allowlist JSON into {match key: pinned file digests}.++ None means unpinned: the key alone suppresses, as before. A set of digests+ covers only those exact file contents, so any other edit to the file reopens+ the finding. For files whose danger sits outside the matched lines, e.g. a+ credential send whose evidence records the urlopen call but not its destination.+ """try:with open(path, "r", encoding = "utf-8") as fh:data = json.load(fh)except FileNotFoundError:- return set()+ return {}except (OSError, json.JSONDecodeError) as exc:print(f" [WARN] could not read baseline {path}: {exc}", file = sys.stderr)- return set()+ return {}if not isinstance(data, dict):print(f" [WARN] baseline {path} is not a JSON object", file = sys.stderr)- return set()+ return {}entries = data.get("entries", [])if not isinstance(entries, list):print(f" [WARN] baseline {path} entries is not a list", file = sys.stderr)- return set()- keys: set[tuple[str, str, str, str]] = set()+ return {}+ keys: dict[tuple[str, str, str, str], "set[str] | None"] = {}legacy = 0for e in entries:if not isinstance(e, dict):@@ -2998,16 +3009,23 @@ def _load_baseline(path: str) -> set[tuple[str, str, str, str]]:evidence_hash = e.get("evidence_hash") or _evidence_hash(e.get("evidence") or "")if not e.get("evidence_hash"):legacy += 1- keys.add(- (- _norm_pkg(e["package"]),- _relpath_in_package(e["file"]),- e["check"],- evidence_hash,- )+ key = (+ _norm_pkg(e["package"]),+ _relpath_in_package(e["file"]),+ e["check"],+ evidence_hash,)except (KeyError, TypeError):continue+ # None = unpinned (key alone suppresses). A set = only those file digests.+ # An unpinned entry wins, since it already suppresses the key on its own.+ pin = e.get("file_sha256")+ if key not in keys:+ keys[key] = {pin} if pin else None+ elif not pin:+ keys[key] = None+ elif keys[key] is not None:+ keys[key].add(pin)if legacy:print(f" [WARN] baseline {path}: {legacy} entries lack evidence_hash and may "@@ -3018,8 +3036,18 @@ def _load_baseline(path: str) -> set[tuple[str, str, str, str]]:return keys-def _write_baseline(path: str, findings: list[Finding]) -> None:- """Persist CRITICAL/HIGH findings as an allowlist for human triage."""+def _write_baseline(+ path: str,+ findings: list[Finding],+ source: "str | None" = None,+) -> None:+ """Persist CRITICAL/HIGH findings as an allowlist for human triage.++ Pins are carried over from `source`, the baseline in effect for this run, so+ regenerating cannot silently widen a reviewed entry. Reading them from `path`+ instead would drop every pin whenever the output goes somewhere new.+ """+ pinned = {k for k, v in _load_baseline(source or path).items() if v is not None}entries = []seen: set[tuple[str, str, str, str]] = set()for f in sorted(findings, key = lambda f: SEVERITY_ORDER.get(f.severity, 99)):@@ -3029,24 +3057,28 @@ def _write_baseline(path: str, findings: list[Finding]) -> None:if key in seen:continueseen.add(key)- entries.append(- {- "package": f.package,- "file": _relpath_in_package(f.filename),- "check": f.check,- "severity": f.severity,- "evidence": f.evidence,- "evidence_hash": _evidence_hash(f.evidence),- }- )+ entry = {+ "package": f.package,+ "file": _relpath_in_package(f.filename),+ "check": f.check,+ "severity": f.severity,+ "evidence": f.evidence,+ "evidence_hash": _evidence_hash(f.evidence),+ }+ if key in pinned and f.file_sha256:+ entry["file_sha256"] = f.file_sha256+ entries.append(entry)doc = {"_comment": ("scan_packages.py allowlist. Each entry is a CRITICAL/HIGH finding ""manually judged benign. Matched on (package, package-relative file, ""check, evidence_hash); evidence_hash is over the matched code with ""L<NN>: markers stripped, so version bumps and line shifts do not "- "reopen an entry but changed code does. severity and evidence are for "- "review only. Regenerate with --write-baseline AFTER reviewing every line."+ "reopen an entry but changed code does. An optional file_sha256 pins an "+ "entry to that exact file, for danger sitting outside the matched lines "+ "(a credential send records the urlopen call, not its destination). "+ "severity and evidence are for review only. Regenerate with "+ "--write-baseline AFTER reviewing every line."),"version": 1,"entries": entries,@@ -3058,14 +3090,20 @@ def _write_baseline(path: str, findings: list[Finding]) -> None:def _partition_baseline(- findings: list[Finding], baseline: set[tuple[str, str, str, str]]+ findings: list[Finding], baseline: "dict[tuple[str, str, str, str], set[str] | None]") -> tuple[list[Finding], list[Finding]]:"""Split findings into (active, suppressed) by allowlist membership."""if not baseline:return list(findings), []active, suppressed = [], []for f in findings:- (suppressed if _finding_key(f) in baseline else active).append(f)+ key = _finding_key(f)+ hit = key in baseline+ if hit:+ pins = baseline[key]+ # A pinned entry only covers the file it was reviewed against.+ hit = pins is None or f.file_sha256 in pins+ (suppressed if hit else active).append(f)return active, suppressed@@ -3229,7 +3267,7 @@ def main() -> int:baseline_path = _DEFAULT_BASELINE_PATHelse:baseline_path = None- baseline = _load_baseline(baseline_path) if baseline_path else set()+ baseline = _load_baseline(baseline_path) if baseline_path else {}active, suppressed = _partition_baseline(all_findings, baseline)@@ -3276,7 +3314,7 @@ def main() -> int:# allowlist (ignoring any loaded baseline), then exit 0. Only reached once# the scan is known complete.if args.write_baseline:- _write_baseline(args.write_baseline, all_findings)+ _write_baseline(args.write_baseline, all_findings, source = baseline_path)return 0# Exit code: 1 only if a NON-baselined CRITICAL or HIGH remains. This is thediff --git a/scripts/scan_packages_baseline.json b/scripts/scan_packages_baseline.jsonindex 8d90795bf3d..1e819390f34 100644--- a/scripts/scan_packages_baseline.json+++ b/scripts/scan_packages_baseline.json@@ -1744,7 +1744,8 @@"check": "Harvests environment variables/secrets AND makes network calls","severity": "CRITICAL","evidence": "Env: L317: token = os.environ.get(\"HF_TOKEN\")\nNetwork: L313: import urllib.request | L316: request = urllib.request.Request(url, headers = {\"User-Agent\": \"unsloth-xet-probe\"}) | L329: with urllib.request.urlopen(request, timeout = PROBE_TIMEOUT_SECONDS) as response: | L342: head = urllib.request.Request(cas, method = \"HEAD\", headers = {\"User-Agent\": \"unsloth-xet-probe\"}) | L344: urllib.request.urlopen(head, timeout = remaining)",- "evidence_hash": "674a558cd1bdfa1470dc2a9a2cd44be98ecc27c0beb37497757c656674e71654"+ "evidence_hash": "674a558cd1bdfa1470dc2a9a2cd44be98ecc27c0beb37497757c656674e71654",+ "file_sha256": "e0b53dbc7749ab7528211ccc87e56a56093b488c5e6efc1445c84c06ff5243db"},{"package": "unsloth-zoo",diff --git a/tests/security/test_scan_packages.py b/tests/security/test_scan_packages.pyindex 2608494b420..f0d7e6432fd 100644--- a/tests/security/test_scan_packages.py+++ b/tests/security/test_scan_packages.py@@ -4,6 +4,7 @@from __future__ import annotationsimport hashlib+import jsonimport osimport reimport subprocess@@ -1240,7 +1241,7 @@ def test_write_baseline_roundtrip_only_crit_high(tmp_path):def test_load_baseline_missing_file_is_empty():- assert sp._load_baseline("/nonexistent/path/bl.json") == set()+ assert sp._load_baseline("/nonexistent/path/bl.json") == {}def test_load_baseline_rejects_non_list_entries(tmp_path, capsys):@@ -1250,7 +1251,7 @@ def test_load_baseline_rejects_non_list_entries(tmp_path, capsys):bl = tmp_path / "bad_entries.json"bl.write_text(json.dumps({"version": 1, "entries": None}), encoding = "utf-8")- assert sp._load_baseline(str(bl)) == set()+ assert sp._load_baseline(str(bl)) == {}assert "entries is not a list" in capsys.readouterr().err@@ -1597,3 +1598,72 @@ def test_run_fix_uses_first_archive_path(monkeypatch):sp._run_fix({"foo"}, entries, max_search = 10) # must not raiseassert seen.get("path") == "/tmp/foo-1.2.3.whl"+++def test_pinned_baseline_entry_only_covers_the_reviewed_file(tmp_path):+ """A file_sha256 pin reopens the finding when anything else in the file changes.++ The evidence for an env-harvest + network finding records the urlopen call but+ not the destination, so a release that repoints the endpoint at an attacker host+ keeps the same evidence hash. Pinning binds the entry to the reviewed bytes.+ """+ bl = tmp_path / "bl.json"+ check = "Harvests environment variables/secrets AND makes network calls"+ reviewed = _mk(sp.CRITICAL, "unsloth-zoo", "z/health.py", check, "Env: L1: token")+ reviewed.file_sha256 = "a" * 64+ sp._write_baseline(str(bl), [reviewed])++ # _write_baseline only pins what was already pinned, so a fresh entry is unpinned.+ doc = json.loads(bl.read_text(encoding = "utf-8"))+ assert "file_sha256" not in doc["entries"][0]+ doc["entries"][0]["file_sha256"] = "a" * 64+ bl.write_text(json.dumps(doc), encoding = "utf-8")+ baseline = sp._load_baseline(str(bl))++ active, suppressed = sp._partition_baseline([reviewed], baseline)+ assert suppressed == [reviewed] and active == []++ # Same package/file/check/evidence, different file bytes -> reopens.+ tampered = _mk(sp.CRITICAL, "unsloth-zoo", "z/health.py", check, "Env: L1: token")+ tampered.file_sha256 = "b" * 64+ active2, suppressed2 = sp._partition_baseline([tampered], baseline)+ assert active2 == [tampered] and suppressed2 == []+++def test_unpinned_baseline_entry_is_content_agnostic(tmp_path):+ """Entries without file_sha256 keep the pre-existing behaviour."""+ bl = tmp_path / "bl.json"+ f = _mk(sp.CRITICAL, "p", "a.py", "c1", "L1: x")+ f.file_sha256 = "a" * 64+ sp._write_baseline(str(bl), [f])+ baseline = sp._load_baseline(str(bl))+ assert baseline[sp._finding_key(f)] is None++ other = _mk(sp.CRITICAL, "p", "a.py", "c1", "L1: x")+ other.file_sha256 = "b" * 64+ active, suppressed = sp._partition_baseline([other], baseline)+ assert suppressed == [other] and active == []+++def test_write_baseline_preserves_an_existing_pin(tmp_path):+ """Regenerating must not silently widen a pinned entry back to any content."""+ bl = tmp_path / "bl.json"+ f = _mk(sp.CRITICAL, "p", "a.py", "c1", "L1: x")+ f.file_sha256 = "a" * 64+ sp._write_baseline(str(bl), [f])+ doc = json.loads(bl.read_text(encoding = "utf-8"))+ doc["entries"][0]["file_sha256"] = "a" * 64+ bl.write_text(json.dumps(doc), encoding = "utf-8")++ sp._write_baseline(str(bl), [f])+ doc2 = json.loads(bl.read_text(encoding = "utf-8"))+ assert doc2["entries"][0]["file_sha256"] == "a" * 64+++def test_check_py_file_stamps_the_file_digest():+ """Findings carry the digest the pin is matched against."""+ src = 'import requests\nimport os\nt = os.environ["HF_TOKEN"]\nrequests.get("http://x", headers={"a": t})\n'+ findings = sp.check_py_file(src, "p/a.py", "p")+ assert findings, "expected at least one finding"+ expected = hashlib.sha256(src.encode("utf-8", "replace")).hexdigest()+ assert all(f.file_sha256 == expected for f in findings)