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
Give this work a before-and-after number, and find out the hardening already worked (#10996)
Daniel Hanf13208b05e40
diff --git a/.github/workflows/virustotal-installer-delta.yml b/.github/workflows/virustotal-installer-delta.ymlnew file mode 100644index 00000000000..e869e3fb7fd--- /dev/null+++ b/.github/workflows/virustotal-installer-delta.yml@@ -0,0 +1,132 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++# What did the hardening actually buy?+#+# install.ps1 at commit 1ad44677d is the revision reported in #10805, it hashes to ec29980b..., and+# VirusTotal holds its verdict. That is a baseline, and until it was found this work had never had a+# before-and-after number -- six passes of hardening, all argued rather than measured.+#+# This lane reports the delta on three axes, separately, because they move independently:+#+# engine verdicts Which of ~60 engines flagged it, by name. One flags the baseline: Skyhigh+# (Trellix / McAfee Enterprise), BehavesLike.PS.Suspicious.gr. Slowest to move --+# a cloud behavioural verdict is not recomputed because we deleted some code.+# Sigma rules 17 on the baseline (1 high, 11 medium, 5 low). Static and deterministic, and+# what drives the alarming scores third-party analysis sites report. This is the+# axis shape work moves, and it moves immediately.+# YARA rules 2 crowdsourced hits on the baseline. Also static.+#+# Reporting only the engine count makes every shape win look like nothing; reporting only Sigma+# overclaims. Both, or the number is not worth having.+#+# GET only. There is no upload path, deliberately: a freshly uploaded file is a prevalence-zero,+# first-seen sample, which is exactly what CloudBlockLevel HighPlus and ASR rule 01443614 punish, so+# uploading a candidate can CREATE the detection it was meant to measure -- under a hash no user will+# ever have. Released artefacts are uploaded by scripts/virustotal_scan.py at release time; branches+# are not.+#+# The consequence is that an unknown hash is VOID (exit 3), never clean. "0 engines flagged it" for a+# file nothing has ever scanned would be the most misleading thing this could print.+#+# Dispatch only. It spends public-tier quota (4 requests/minute, 500/day) and answers a question that+# is asked deliberately, not on every push.++name: "VirusTotal: installer delta against the reported baseline"++on:+ workflow_dispatch:+ inputs:+ path:+ description: "File to hash and look up"+ required: false+ default: 'install.ps1'+ baseline_sha256:+ description: "Override the baseline hash (default: install.ps1 at 1ad44677d)"+ required: false+ default: ''++permissions:+ contents: read++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: false++jobs:+ delta:+ name: how does this candidate compare+ runs-on: ubuntu-24.04+ timeout-minutes: 20+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ # The baseline is verified against this repository's own history rather than trusted as a+ # constant, and that needs the commit to be present.+ fetch-depth: 0+ persist-credentials: false++ - name: Prove the comparison can still report a regression+ run: |+ set -euo pipefail+ # Before spending any quota. A comparison that silently stopped reporting regressions would+ # produce a reassuring delta forever, and that is a worse outcome than no lane.+ python scripts/virustotal_delta.py --self-test++ # Separate from the self-test because it needs git history, and a shallow clone should skip+ # rather than fail. A baseline hash nobody rechecks is a number that could be pointing at any+ # file at all while the lane looks perfectly healthy.+ - name: Confirm the baseline is the file the reporter ran+ run: |+ set -euo pipefail+ if ! git cat-file -e 1ad44677d^{commit} 2>/dev/null; then+ echo "::warning::1ad44677d is not in this clone, so the baseline could not be reverified"+ exit 0+ fi+ got="$(git show 1ad44677d:install.ps1 | sha256sum | cut -d' ' -f1)"+ want="$(python -c 'import sys; sys.path.insert(0, "scripts"); import virustotal_delta as v; print(v.BASELINE_SHA256)')"+ echo "history $got"+ echo "constant $want"+ if [ "$got" != "$want" ]; then+ echo "::error::the recorded baseline hash is not install.ps1 at 1ad44677d. Every delta reported against it was against the wrong file."+ exit 1+ fi+ echo "baseline reverified against history"++ - name: Compare+ id: compare+ env:+ # VT_API_KEY is the ENV VAR the Python reads (scripts/virustotal_scan.py:37); the+ # repository secret is named VIRUS_TOTAL_API_TOKEN, and release-desktop.yml:2193 maps it+ # the same way. Naming the secret VT_API_KEY here expanded to empty, and the lane then+ # exited 3 / VOID on every run -- loudly, which is the right failure, but it measured+ # nothing.+ VT_API_KEY: ${{ secrets.VIRUS_TOTAL_API_TOKEN }}+ TARGET: ${{ inputs.path }}+ BASELINE: ${{ inputs.baseline_sha256 }}+ run: |+ set -euo pipefail+ args=(--candidate "${TARGET:-install.ps1}" --summary "$RUNNER_TEMP/vt-delta.md")+ if [ -n "$BASELINE" ]; then args+=(--baseline-sha256 "$BASELINE"); fi+ set +e+ python scripts/virustotal_delta.py "${args[@]}"+ code=$?+ set -e+ case "$code" in+ 0) echo "VERDICT: not worse than the baseline." ;;+ 2) echo "::error::VERDICT: worse than the baseline on at least one axis." ;;+ 3) echo "::error::VERDICT: VOID. Nothing was compared." ;;+ *) echo "::error::VERDICT: the tool itself failed (exit $code)." ;;+ esac+ exit "$code"++ - name: Keep the report+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: virustotal-delta+ path: ${{ runner.temp }}/vt-delta.md+ if-no-files-found: warn+ # Long, for the same reason the flagged bundles are kept 90 days: clearance is per hash, and+ # a vendor round trip plus our own reaction routinely outlasts a week.+ retention-days: 90diff --git a/scripts/virustotal_delta.py b/scripts/virustotal_delta.pynew file mode 100644index 00000000000..f7406782a62--- /dev/null+++ b/scripts/virustotal_delta.py@@ -0,0 +1,674 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Compare a candidate installer against a known-flagged baseline on VirusTotal.++Six antivirus-hardening passes shipped without a before-and-after number, because nobody had one.+There is one now: `install.ps1` at commit `1ad44677d` -- the revision reported in+unslothai/unsloth#10805 -- is `ec29980b...`, and VirusTotal holds its verdict. That gives this work a+baseline for the first time, and this tool is the diff against it.++Three numbers, because they move independently and mean different things:++ engine verdicts Which of ~60 engines flagged the file, and with what label. Exactly one flags the+ baseline: Skyhigh (Trellix / McAfee Enterprise) with `BehavesLike.PS.Suspicious.gr`,+ a generic behavioural label. This is the number a user feels and the slowest to+ move, since a cloud behavioural verdict is not recomputed because we deleted some+ code.+ Sigma rules 17 on the baseline (1 high, 11 medium, 5 low). Static, deterministic, and what+ drives the alarming scores third-party analysis sites report. This is the number+ shape work moves, and it should move immediately.+ YARA rules 2 crowdsourced hits on the baseline. Also static.++Reporting only the engine count would make every shape improvement look like it achieved nothing, and+reporting only Sigma would overclaim. Both, separately, or the number is not worth having.++## Hash lookup only. Never upload.++This tool only ever issues `GET /files/{sha256}`. It has no upload path at all, and that is a+deliberate omission rather than an oversight: a freshly uploaded file is a prevalence-zero, first-seen+sample, which is precisely what `CloudBlockLevel HighPlus` and ASR rule `01443614` punish. Uploading a+candidate can therefore *create* the detection it was meant to measure, under a hash no user will ever+have. Released artefacts get uploaded by `virustotal_scan.py` at release time; branches do not.++The consequence is that an unknown hash is a **VOID** outcome, not a clean one. Current `main`'s+`install.ps1` is unknown to VirusTotal today, and "0 engines flagged it" for a file nothing has ever+scanned is the single most misleading sentence this tool could print.+"""++from __future__ import annotations++import argparse+import hashlib+import os+import sys+import time+from dataclasses import dataclass, field+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++from virustotal_scan import ( # noqa: E402+ API_KEY_ENV,+ API_ROOT,+ VirusTotalClient,+ _md_text,+ parse_detections,+ parse_stats,+)+++# The revision reported in #10805, hashed from this repository's own history rather than copied from+# the report: `git show 1ad44677d:install.ps1 | sha256sum` gives exactly this, at exactly the 427,113+# bytes the sample is recorded as. That is what makes it the file that user actually ran, and a test+# recomputes it rather than trusting this constant.+BASELINE_SHA256 = "ec29980bffff30740f876f4955d890e0f1a1c9fd681521be6fbfccd24ffae296"++# What the baseline scored, recorded so a run can say "unchanged" or "moved" without a second network+# call, and so a reader can sanity-check the live answer against what we believed.+BASELINE_NOTE = (+ "install.ps1 at 1ad44677d: 1 malicious / 58 undetected, Skyhigh "+ "BehavesLike.PS.Suspicious.gr; 17 Sigma rules (1 high, 11 medium, 5 low); 2 YARA hits"+)++SEVERITIES = ("critical", "high", "medium", "low")+++@dataclass+class Snapshot:+ """What VirusTotal holds about one file."""++ label: str+ sha256: str = ""+ found: bool = False+ size: int = 0+ first_seen: str = ""+ engines: list[str] = field(default_factory = list)+ # Every engine that returned a verdict of ANY kind. Needed because an engine missing from the+ # candidate's results has not cleared it -- it did not look -- and a set difference against the+ # flagging engines alone cannot tell those two apart.+ responders: set[str] = field(default_factory = set)+ malicious: int = 0+ suspicious: int = 0+ total_engines: int = 0+ sigma: dict[str, int] = field(default_factory = dict)+ yara: list[str] = field(default_factory = list)+ note: str = ""++ @property+ def sigma_total(self) -> int:+ return sum(self.sigma.values())+++def sha256_of(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++# The only categories that mean "this engine looked and did not object". `timeout`,+# `confirmed-timeout`, `failure` and `type-unsupported` are all entries an engine can return without+# having reached a verdict, and treating them as answers is the same mistake as treating absence as+# one: it lets a detection be reported as cleared by an engine that never decided.+CONCLUSIVE_CLEAN = ("undetected", "harmless")+++def responding_engines(raw: object) -> set[str]:+ """Names of every engine that reached a conclusive verdict, flagging or clean."""+ if not isinstance(raw, dict):+ return set()+ conclusive = set(CONCLUSIVE_CLEAN) | {"malicious", "suspicious"}+ return {+ str(engine)+ for engine, result in raw.items()+ if isinstance(result, dict) and result.get("category") in conclusive+ }+++def count_all_verdicts(raw: object, stats) -> int:+ """How many engines answered, counting buckets `ScanStats` has no field for.++ `parse_stats` names `type-unsupported` and `failure` as categories VirusTotal has added, but+ `ScanStats` carries fields only for malicious, suspicious, undetected, harmless and timeout, so+ its `total` undercounts the denominator this report prints, and a response made up entirely of+ the omitted buckets looks like a file nothing has scanned. Summing every numeric bucket in the+ raw dict keeps the shared dataclass untouched, which matters because the release scanner uses+ it too, while still counting what actually came back.+ """+ if not isinstance(raw, dict):+ return stats.total+ total = 0+ for value in raw.values():+ # Booleans are ints in Python and would each add one; VirusTotal sends counts, not flags.+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ continue+ total += int(value)+ return total+++def parse_sigma(raw: object) -> dict[str, int]:+ """Sigma counts by severity.++ VirusTotal has renamed and added buckets over time, so every key is read defensively rather than+ indexed. A KeyError here would turn a measurement into a crash on a day VirusTotal shipped a+ schema change, which is exactly when the measurement matters.+ """+ if not isinstance(raw, dict):+ return {}+ out: dict[str, int] = {}+ # Every bucket VirusTotal reports, not only the four this tool knows how to rank. Iterating a+ # fixed key list is what the docstring above warns about and then did anyway: a candidate that+ # gained rules only in a renamed or newly added bucket produced a dictionary identical to the+ # baseline's, so compare() called Sigma unchanged and the run exited 0 on a regression.+ # Unrankable buckets are kept here and handled separately in compare().+ for key, value in raw.items():+ if not isinstance(key, str):+ continue+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ continue+ if int(value):+ out[key] = int(value)+ return out+++def parse_yara(raw: object) -> list[str]:+ if not isinstance(raw, list):+ return []+ names = []+ for entry in raw:+ if not isinstance(entry, dict):+ continue+ # Ruleset AND rule. Two crowdsourced rulesets can carry the same rule identifier, and+ # keying on the rule alone let a candidate gain a hit from a different ruleset while the+ # parsed list stayed equal to the baseline's, so the comparison reported YARA unchanged and+ # the run exited 0.+ rule = entry.get("rule_name")+ ruleset = entry.get("ruleset_name")+ parts = [p for p in (ruleset, rule) if isinstance(p, str) and p]+ if parts:+ names.append("/".join(parts))+ return sorted(set(names))+++def snapshot_from_payload(label: str, sha256: str, payload: object) -> Snapshot:+ """Build a snapshot from a `GET /files/{sha256}` body."""+ snap = Snapshot(label = label, sha256 = sha256)+ attributes = {}+ if isinstance(payload, dict):+ data = payload.get("data")+ if isinstance(data, dict) and isinstance(data.get("attributes"), dict):+ attributes = data["attributes"]+ if not attributes:+ snap.note = "VirusTotal returned no attributes for this hash"+ return snap++ snap.found = True+ stats = parse_stats(attributes.get("last_analysis_stats"))+ snap.malicious = stats.malicious+ snap.suspicious = stats.suspicious+ snap.total_engines = count_all_verdicts(attributes.get("last_analysis_stats"), stats)+ snap.engines = parse_detections(attributes.get("last_analysis_results"))+ snap.responders = responding_engines(attributes.get("last_analysis_results"))+ snap.sigma = parse_sigma(attributes.get("sigma_analysis_stats"))+ snap.yara = parse_yara(attributes.get("crowdsourced_yara_results"))+ size = attributes.get("size")+ snap.size = int(size) if isinstance(size, int) else 0+ first = attributes.get("first_submission_date")+ snap.first_seen = str(first) if first else ""++ if snap.total_engines == 0:+ # Zero verdicts of any kind means no engine has run, which is not the same as every engine+ # having cleared it. Recorded so the verdict below can refuse to call it clean.+ snap.note = "no engine verdicts at all: the file is known but has not been analysed"+ return snap+++# Below the 20 minutes the workflow gives the whole job. Without a deadline one lookup can spend+# four 300-second socket attempts plus 20, 40 and 80 second backoffs, so the baseline alone can eat+# the budget and the runner kills the step before it fetches the candidate or writes its summary --+# which is a lost run rather than a reported one. `request` checks this BEFORE each attempt, because+# a single attempt can block for the full socket timeout.+LOOKUP_BUDGET_SECONDS = 420.0+++def fetch(+ client: VirusTotalClient,+ sha256: str,+ label: str,+ deadline: float | None = None,+) -> Snapshot:+ try:+ status, payload = client.request(+ "GET",+ f"{API_ROOT}/files/{sha256}",+ allow_status = (404,),+ deadline = deadline,+ )+ except (RuntimeError, TimeoutError) as exc:+ # The retry budget or the deadline is spent. VOID, not clean and not a crash: we did not+ # find out, and the summary has to say so while there is still time to write it.+ # Both are needed: a spent retry budget raises RuntimeError, but a spent deadline raises+ # TimeoutError, which is an OSError and would otherwise walk straight past this handler.+ snap = Snapshot(label = label, sha256 = sha256)+ snap.note = f"the lookup did not complete within its budget: {exc}"+ return snap+ if status == 404:+ snap = Snapshot(label = label, sha256 = sha256)+ snap.note = "not present on VirusTotal"+ return snap+ if status != 200:+ snap = Snapshot(label = label, sha256 = sha256)+ snap.note = f"VirusTotal answered {status}"+ return snap+ return snapshot_from_payload(label, sha256, payload)+++# ---------------------------------------------------------------------------+# The verdict+# ---------------------------------------------------------------------------+++@dataclass+class Delta:+ void: list[str] = field(default_factory = list)+ worse: list[str] = field(default_factory = list)+ better: list[str] = field(default_factory = list)+ same: list[str] = field(default_factory = list)++ def exit_code(self) -> int:+ # 3 = could not measure, 2 = worse than baseline, 0 = same or better. Distinct, because a+ # tool whose "we could not look" is spelled the same as "it got worse" is unreadable, and one+ # whose "we could not look" is spelled the same as "it is fine" is dangerous.+ if self.void:+ return 3+ if self.worse:+ return 2+ return 0+++def compare(baseline: Snapshot, candidate: Snapshot) -> Delta:+ delta = Delta()++ if not candidate.found:+ delta.void.append(+ f"the candidate ({candidate.sha256[:16]}...) is not on VirusTotal: {candidate.note}. "+ f"This is the expected answer for an unreleased build, and it is NOT a clean result -- "+ f"'0 engines flagged it' for a file nothing has scanned is the most misleading thing "+ f"this tool could say. Upload released artefacts only; a fresh upload is a "+ f"prevalence-zero first-seen sample, which is what the strict cloud settings punish."+ )+ if not baseline.found:+ delta.void.append(+ f"the baseline ({baseline.sha256[:16]}...) is not on VirusTotal: {baseline.note}. "+ f"Without it there is nothing to compare against, and an absolute verdict on a 443 KB "+ f"script is noise."+ )+ if candidate.found and candidate.total_engines == 0:+ delta.void.append(f"the candidate has no engine verdicts: {candidate.note}")+ if baseline.found and baseline.total_engines == 0:+ # Same guard, same reason, other side. A baseline VirusTotal knows but has never analysed+ # carries no engines, no Sigma and no YARA, so every finding on the candidate reads as newly+ # introduced and the run exits 2 while having compared against nothing at all.+ delta.void.append(f"the baseline has no engine verdicts: {baseline.note}")+ if delta.void:+ return delta++ # Engines, by name. A count alone hides the case that matters most: the same number of+ # detections, but a different and more widely deployed engine.+ base_engines = {e.split(" (")[0] for e in baseline.engines}+ cand_engines = {e.split(" (")[0] for e in candidate.engines}+ new_engines = sorted(cand_engines - base_engines)+ # An engine that flagged the baseline and is simply ABSENT from the candidate's results has not+ # cleared it: it did not evaluate it. Older or sparser analyses do this routinely, and counting+ # it as an improvement is how a vendor that never looked turns into a vendor that passed us.+ # Only an engine that answered on the candidate, and answered without flagging, has cleared it.+ cleared = base_engines & candidate.responders - cand_engines+ silent = base_engines - candidate.responders+ gone_engines = sorted(cleared)+ if new_engines:+ delta.worse.append(+ f"engines that did not flag the baseline and now flag the candidate: "+ f"{', '.join(new_engines)}"+ )+ if gone_engines:+ delta.better.append(+ f"engines that flagged the baseline and no longer flag the candidate: "+ f"{', '.join(gone_engines)}"+ )+ if silent:+ # Not an improvement and not a regression: an unanswered question. Reported so the summary+ # cannot read as though the vendor that matters most had cleared us.+ delta.same.append(+ f"engines that flagged the baseline and returned no verdict at all on the candidate, "+ f"so they have NOT cleared it: {', '.join(sorted(silent))}"+ )+ if not new_engines and not gone_engines:+ delta.same.append(+ f"engine verdicts unchanged ({len(cand_engines) or 'none'}"+ f"{': ' + ', '.join(sorted(cand_engines)) if cand_engines else ''})"+ )++ # Sigma, per severity and in severity ORDER. Trading one high for three lows is an improvement+ # and a total would call it a regression; the reverse is a regression a total would call an+ # improvement. Reporting each bucket independently does not express that either: a trade moves+ # two buckets in opposite directions, so it lands in `worse` and in `better` at once, and+ # exit_code answers `worse`. SEVERITIES is ordered most severe first, so the most severe bucket+ # that moved is the one that decides; the rest are reported alongside it and do not flip it.+ movements = [+ (severity, baseline.sigma.get(severity, 0), candidate.sigma.get(severity, 0))+ for severity in SEVERITIES+ if baseline.sigma.get(severity, 0) != candidate.sigma.get(severity, 0)+ ]+ if movements:+ detail = ", ".join(f"{sev} {before} -> {after}" for sev, before, after in movements)+ decisive, before, after = movements[0]+ if after > before:+ delta.worse.append(+ f"Sigma {decisive} rose ({before} -> {after}), the most severe bucket that moved: "+ f"{detail}"+ )+ else:+ delta.better.append(+ f"Sigma {decisive} fell ({before} -> {after}), the most severe bucket that moved: "+ f"{detail}"+ )++ # Buckets this tool cannot place in the severity order, which is what a VirusTotal rename or+ # addition looks like on the day it happens. They are deliberately kept out of the ordered+ # trade-off above, because that logic depends on knowing which of two buckets is more severe.+ # A rise in one is reported as worse rather than assumed minor: an unrankable bucket could sit+ # anywhere, including above critical, and calling it an improvement is the one answer that+ # cannot be defended.+ unknown = sorted(+ (key, baseline.sigma.get(key, 0), candidate.sigma.get(key, 0))+ for key in set(baseline.sigma) | set(candidate.sigma)+ if key not in SEVERITIES and baseline.sigma.get(key, 0) != candidate.sigma.get(key, 0)+ )+ for key, before, after in unknown:+ if after > before:+ delta.worse.append(+ f"Sigma {key} rose ({before} -> {after}). This tool does not know where {key!r} "+ f"ranks against {', '.join(SEVERITIES)}, so it is not being called minor."+ )+ else:+ delta.better.append(f"Sigma {key} fell ({before} -> {after}), an unranked bucket")++ if baseline.sigma == candidate.sigma:+ delta.same.append(+ f"Sigma unchanged ({baseline.sigma_total} rules: "+ f"{', '.join(f'{k}={v}' for k, v in sorted(baseline.sigma.items())) or 'none'})"+ )++ base_yara, cand_yara = set(baseline.yara), set(candidate.yara)+ if cand_yara - base_yara:+ delta.worse.append(f"new YARA hits: {', '.join(sorted(cand_yara - base_yara))}")+ if base_yara - cand_yara:+ delta.better.append(f"YARA hits gone: {', '.join(sorted(base_yara - cand_yara))}")+ if base_yara == cand_yara:+ delta.same.append(f"YARA unchanged ({len(cand_yara)} hit(s))")++ return delta+++def render(baseline: Snapshot, candidate: Snapshot, delta: Delta) -> str:+ lines = [+ "### VirusTotal delta against the reported baseline",+ "",+ # Only when the baseline really IS the recorded one. A dispatch can override the hash, and+ # printing the recorded identity beside an override's live numbers produced an artifact that+ # combined someone else's file with install.ps1's historical scores, which is a delta built+ # to be misattributed.+ (+ f"Baseline recorded as: {BASELINE_NOTE}"+ if baseline.sha256.lower() == BASELINE_SHA256.lower()+ else f"Baseline OVERRIDDEN to `{baseline.sha256[:16]}...`, so the recorded "+ f"install.ps1 scores do not apply and no historical comparison is implied."+ ),+ "",+ "| | baseline | candidate |",+ "|---|---|---|",+ f"| sha256 | `{baseline.sha256[:16]}...` | `{candidate.sha256[:16]}...` |",+ f"| on VirusTotal | {'yes' if baseline.found else 'NO'} | {'yes' if candidate.found else 'NO'} |",+ f"| engines flagging | {baseline.malicious + baseline.suspicious} / {baseline.total_engines} "+ f"| {candidate.malicious + candidate.suspicious} / {candidate.total_engines} |",+ f"| which | {_md_text(', '.join(baseline.engines)) or 'none'} "+ f"| {_md_text(', '.join(candidate.engines)) or 'none'} |",+ f"| Sigma | {baseline.sigma_total} ({', '.join(f'{k}={v}' for k, v in sorted(baseline.sigma.items())) or 'none'}) "+ f"| {candidate.sigma_total} ({', '.join(f'{k}={v}' for k, v in sorted(candidate.sigma.items())) or 'none'}) |",+ f"| YARA | {len(baseline.yara)} | {len(candidate.yara)} |",+ "",+ ]+ for heading, rows in (+ ("Worse", delta.worse),+ ("Better", delta.better),+ ("Unchanged", delta.same),+ ("Could not measure", delta.void),+ ):+ if rows:+ lines.append(f"**{heading}**")+ lines.append("")+ # Escaped here rather than at every append site. Engine names, detection labels and+ # YARA rule names all reach these bullets, all are third-party text, and this is+ # appended to $GITHUB_STEP_SUMMARY where a newline ends the bullet, `|` opens a cell and+ # `<` starts HTML that GitHub renders.+ lines.extend(f"- {_md_text(row)}" for row in rows)+ lines.append("")+ if not delta.void and not delta.worse and not delta.better:+ lines.append("Nothing moved. Reported as unchanged rather than dressed up.")+ lines.append("")+ return "\n".join(lines)+++# ---------------------------------------------------------------------------+# Offline self-test+# ---------------------------------------------------------------------------++# Recorded shapes, not live answers, so the comparison logic is testable with no key and no network.+# This is the half that can be wrong in a way nobody notices: a network call that fails is loud, and+# a comparison that silently never reports a regression is not.+_BASELINE_FIXTURE = {+ "data": {+ "attributes": {+ "size": 427113,+ "last_analysis_stats": {"malicious": 1, "undetected": 58},+ "last_analysis_results": {+ "Skyhigh": {"category": "malicious", "result": "BehavesLike.PS.Suspicious.gr"},+ "Microsoft": {"category": "undetected", "result": None},+ },+ "sigma_analysis_stats": {"high": 1, "medium": 11, "low": 5},+ "crowdsourced_yara_results": [+ {"rule_name": "SUSP_PS1_Shape_A"},+ {"rule_name": "SUSP_PS1_Shape_B"},+ ],+ }+ },+}+++def self_test() -> list[str]:+ failures: list[str] = []+ baseline = snapshot_from_payload("baseline", "a" * 64, _BASELINE_FIXTURE)++ if baseline.sigma_total != 17 or baseline.sigma.get("high") != 1:+ failures.append(f"the Sigma parser no longer reads the recorded baseline: {baseline.sigma}")+ if baseline.engines != ["Skyhigh (BehavesLike.PS.Suspicious.gr)"]:+ failures.append(f"the engine parser no longer reads the baseline: {baseline.engines}")+ if len(baseline.yara) != 2:+ failures.append(f"the YARA parser no longer reads the baseline: {baseline.yara}")++ identical = snapshot_from_payload("candidate", "b" * 64, _BASELINE_FIXTURE)+ delta = compare(baseline, identical)+ if delta.worse or delta.better or delta.exit_code() != 0:+ failures.append(f"an identical candidate was not reported as unchanged: {delta}")++ import copy++ improved_payload = copy.deepcopy(_BASELINE_FIXTURE)+ improved_payload["data"]["attributes"]["sigma_analysis_stats"] = {"medium": 4, "low": 5}+ improved_payload["data"]["attributes"]["crowdsourced_yara_results"] = []+ improved = snapshot_from_payload("candidate", "c" * 64, improved_payload)+ delta = compare(baseline, improved)+ if not delta.better or delta.worse:+ failures.append(f"a clear improvement was not reported as better: {delta}")+ if delta.exit_code() != 0:+ failures.append("an improvement exited non-zero")++ worse_payload = copy.deepcopy(_BASELINE_FIXTURE)+ worse_payload["data"]["attributes"]["sigma_analysis_stats"] = {+ "high": 2,+ "medium": 11,+ "low": 5,+ }+ worse = snapshot_from_payload("candidate", "d" * 64, worse_payload)+ delta = compare(baseline, worse)+ if not delta.worse or delta.exit_code() != 2:+ failures.append(f"a new high-severity Sigma rule was not reported as worse: {delta}")++ swapped = copy.deepcopy(_BASELINE_FIXTURE)+ swapped["data"]["attributes"]["last_analysis_results"] = {+ "Microsoft": {"category": "malicious", "result": "Trojan:Script/Wacatac.B!ml"},+ "Skyhigh": {"category": "undetected", "result": None},+ }+ swap = snapshot_from_payload("candidate", "e" * 64, swapped)+ delta = compare(baseline, swap)+ # Same count, different engine, and vastly more consequential. A count-only comparison calls this+ # unchanged, which is the failure mode this check exists for.+ if not delta.worse:+ failures.append(+ "one engine's detection being replaced by another's was not reported as worse. The "+ "count is identical, so a comparison on counts alone would call the most consequential "+ "possible change 'no difference'."+ )++ missing = Snapshot(label = "candidate", sha256 = "f" * 64, note = "not present on VirusTotal")+ delta = compare(baseline, missing)+ if delta.exit_code() != 3 or not delta.void:+ failures.append("an unknown candidate hash was not reported as VOID")+ if delta.worse or delta.same:+ failures.append("an unknown candidate hash produced comparison rows it cannot support")++ unanalysed = snapshot_from_payload(+ "candidate",+ "0" * 64,+ {+ "data": {+ "attributes": {+ "size": 1,+ "last_analysis_stats": {},+ "last_analysis_results": {},+ }+ }+ },+ )+ delta = compare(baseline, unanalysed)+ if delta.exit_code() != 3:+ failures.append(+ "a file that is known to VirusTotal but has never been analysed was not VOID. Zero "+ "verdicts of any kind is not every engine clearing it."+ )++ return failures+++# ---------------------------------------------------------------------------+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument("--candidate", type = Path, help = "a file to hash and look up")+ parser.add_argument(+ "--candidate-sha256", default = "", help = "look up this hash instead of hashing a file"+ )+ parser.add_argument("--baseline-sha256", default = BASELINE_SHA256)+ parser.add_argument(+ "--summary",+ type = Path,+ default = None,+ help = "write the markdown report here as well as to stdout",+ )+ parser.add_argument(+ "--self-test", action = "store_true", help = "check the comparison logic offline and exit"+ )+ parser.add_argument(+ "--request-interval",+ type = float,+ default = 20.0,+ help = "seconds between API calls; the public tier allows 4 per minute",+ )+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)++ if args.self_test:+ failures = self_test()+ for failure in failures:+ print(f"::error::self-test: {failure}")+ if failures:+ print(+ "::error::the delta tool's own checks failed, so no comparison it reports can be "+ "trusted. Refusing to compare."+ )+ return 1+ print("self-test: the comparison reports regressions, improvements and VOID correctly")+ return 0++ if not args.candidate and not args.candidate_sha256:+ print("::error::give --candidate or --candidate-sha256")+ return 1++ # Checked before the key, so a misconfigured run fails on the thing it can see.+ candidate_sha = args.candidate_sha256+ if args.candidate:+ if not args.candidate.is_file():+ print(f"::error::{args.candidate} does not exist")+ return 1+ candidate_sha = sha256_of(args.candidate)+ print(f"{args.candidate} -> {candidate_sha}")++ api_key = os.environ.get(API_KEY_ENV, "").strip()+ if not api_key:+ # VOID, and exit 3. A missing key is the most likely reason this ever produces no comparison,+ # and it must not be spelled the same as "nothing got worse".+ print(f"::warning::{API_KEY_ENV} is not set, so nothing was compared.")+ print("::warning::COULD NOT MEASURE. This is a missing key, not a clean result.")+ return 3++ client = VirusTotalClient(api_key, request_interval = args.request_interval)+ # One budget shared across both lookups, so a slow baseline cannot leave the candidate with the+ # whole remaining job timeout and still overrun it.+ deadline = time.monotonic() + LOOKUP_BUDGET_SECONDS+ baseline = fetch(client, args.baseline_sha256, "baseline", deadline = deadline)+ candidate = fetch(client, candidate_sha, "candidate", deadline = deadline)+ delta = compare(baseline, candidate)++ report = render(baseline, candidate, delta)+ print(report)+ if args.summary:+ args.summary.parent.mkdir(parents = True, exist_ok = True)+ args.summary.write_text(report, encoding = "utf-8")+ summary_path = os.environ.get("GITHUB_STEP_SUMMARY")+ if summary_path:+ with open(summary_path, "a", encoding = "utf-8") as handle:+ handle.write(report + "\n")++ code = delta.exit_code()+ if code == 3:+ print("::error::VOID. Nothing was compared, so nothing was shown to have improved.")+ elif code == 2:+ print("::error::the candidate scores WORSE than the baseline on at least one axis.")+ elif delta.better:+ print(+ "the candidate scores better than the baseline. Sigma and YARA move immediately; a "+ "cloud engine's behavioural verdict may not, and that is reported as unchanged rather "+ "than dressed up."+ )+ return code+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/security/test_virustotal_delta.py b/tests/security/test_virustotal_delta.pynew file mode 100644index 00000000000..e71b7757dcf--- /dev/null+++ b/tests/security/test_virustotal_delta.py@@ -0,0 +1,596 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The VirusTotal delta has to be able to report a regression, and has to refuse to guess.++Six hardening passes shipped with no before-and-after number. This tool produces one, so the way it+fails matters more than the way it succeeds: a comparison that silently never reports a regression is+indistinguishable from one that keeps passing, and a network call that breaks is loud while a+comparison that quietly stops comparing is not.++The other property tested here is that "could not measure" never reads as "clean". A missing API key,+an unknown hash and a file VirusTotal knows but has never analysed are all VOID. That last one is the+subtle case: zero engine verdicts is not sixty engines clearing the file.+"""++from __future__ import annotations++import copy+import hashlib+import os+import subprocess+import sys+from pathlib import Path++import pytest+++REPO = Path(__file__).resolve().parents[2]+SCRIPT = REPO / "scripts" / "virustotal_delta.py"++sys.path.insert(0, str(REPO / "scripts"))+import virustotal_delta as vtd # noqa: E402+++def _snap(+ payload: dict,+ label: str = "candidate",+ sha: str = "b" * 64,+):+ return vtd.snapshot_from_payload(label, sha, payload)+++def _baseline():+ return _snap(vtd._BASELINE_FIXTURE, "baseline", "a" * 64)+++# ---------------------------------------------------------------------------+# The baseline is a real file, not a number someone typed+# ---------------------------------------------------------------------------+++def test_the_baseline_hash_is_the_file_the_reporter_ran() -> None:+ """Recomputed from this repository's history rather than trusted.++ A baseline hash copied from an issue is a number nobody can check. This one is+ `install.ps1` at `1ad44677d`, and if the constant and the history ever disagree, the whole+ comparison is against the wrong file while still looking perfectly healthy.+ """+ # Shape first, and unconditionally. The git half below skips on a shallow clone, which is every+ # CI lane that collects tests/security -- so without this, the single assertion tying the+ # baseline to real history would be green locally and silently absent everywhere that matters.+ assert len(vtd.BASELINE_SHA256) == 64, "the baseline is not a SHA-256"+ assert all(+ c in "0123456789abcdef" for c in vtd.BASELINE_SHA256+ ), "the baseline is not lowercase hex, so it can never match a VirusTotal lookup"++ result = subprocess.run(+ ["git", "show", "1ad44677d:install.ps1"],+ cwd = REPO,+ capture_output = True,+ timeout = 120,+ )+ if result.returncode != 0:+ pytest.skip("that commit is not present in this clone (shallow checkout)")+ blob = result.stdout+ assert hashlib.sha256(blob).hexdigest() == vtd.BASELINE_SHA256, (+ "BASELINE_SHA256 is not the hash of install.ps1 at 1ad44677d. Every delta this tool has "+ "ever reported was against the wrong file."+ )+ assert len(blob) == 427113, (+ f"install.ps1 at 1ad44677d is {len(blob)} bytes, not the 427,113 the reported sample is "+ f"recorded as, so this is not the revision the user in #10805 ran"+ )+++def test_the_recorded_baseline_note_matches_the_fixture() -> None:+ """The prose and the fixture are two statements of the same fact, and they drift apart in+ exactly the situation where someone is reading one and trusting the other."""+ baseline = _baseline()+ assert baseline.sigma_total == 17+ assert baseline.sigma == {"high": 1, "medium": 11, "low": 5}+ assert baseline.engines == ["Skyhigh (BehavesLike.PS.Suspicious.gr)"]+ assert len(baseline.yara) == 2+ for fragment in ("1 high, 11 medium, 5 low", "Skyhigh", "2 YARA"):+ assert (+ fragment in vtd.BASELINE_NOTE+ ), f"the recorded note no longer says {fragment!r}, but the fixture still does"+++# ---------------------------------------------------------------------------+# It must report a regression+# ---------------------------------------------------------------------------+++def test_a_new_high_severity_sigma_rule_is_worse() -> None:+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["sigma_analysis_stats"] = {"high": 2, "medium": 11, "low": 5}+ delta = vtd.compare(_baseline(), _snap(payload))+ assert delta.worse and delta.exit_code() == 2+++def test_a_different_engine_flagging_is_worse_even_at_the_same_count() -> None:+ """The failure mode a count-only comparison has by construction.++ One engine before, one engine after, so the count says nothing changed. But Skyhigh being+ replaced by Microsoft is the most consequential change this file could undergo: Defender is on+ every Windows machine and Skyhigh is enterprise-deployed.+ """+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["last_analysis_results"] = {+ "Microsoft": {"category": "malicious", "result": "Trojan:Script/Wacatac.B!ml"},+ "Skyhigh": {"category": "undetected", "result": None},+ }+ delta = vtd.compare(_baseline(), _snap(payload))+ assert delta.worse, "an engine swap at the same count was reported as no difference"+ assert any("Microsoft" in row for row in delta.worse)+++def test_a_new_yara_hit_is_worse() -> None:+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["crowdsourced_yara_results"] = [+ {"rule_name": "SUSP_PS1_Shape_A"},+ {"rule_name": "SUSP_PS1_Shape_B"},+ {"rule_name": "SOMETHING_NEW"},+ ]+ delta = vtd.compare(_baseline(), _snap(payload))+ assert delta.worse and delta.exit_code() == 2+++def test_severity_is_compared_per_bucket_and_not_in_total() -> None:+ """Trading one high for three lows is an improvement that a total calls a regression, and the+ reverse is a regression a total calls an improvement."""+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ # 17 rules before, 17 after, but one medium became a high.+ payload["data"]["attributes"]["sigma_analysis_stats"] = {"high": 2, "medium": 10, "low": 5}+ delta = vtd.compare(_baseline(), _snap(payload))+ assert delta.exit_code() == 2+ assert any("high" in row for row in delta.worse)+++def test_trading_a_high_for_several_lows_is_the_improvement_the_comment_claims() -> None:+ """The stated intent, finally enforced.++ Reporting each bucket independently cannot express a trade: it moves two buckets in opposite+ directions, so it landed in `worse` and in `better` at once and exit_code answered `worse`.+ A run that swapped the single high rule for three extra low ones was therefore rejected while+ the comment beside it called that exact swap an improvement.+ """+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["sigma_analysis_stats"] = {"high": 0, "medium": 11, "low": 8}+ delta = vtd.compare(_baseline(), _snap(payload))+ assert delta.exit_code() == 0, f"a high rule traded for lows was rejected: {delta.worse}"+ assert any("high" in row for row in delta.better)+ # The lower buckets are still reported; they just do not decide.+ assert any("low" in row for row in delta.better)+++def test_a_low_traded_for_a_high_is_still_a_regression() -> None:+ """The reverse of the trade above, which a total would have called an improvement."""+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["sigma_analysis_stats"] = {"high": 2, "medium": 11, "low": 0}+ delta = vtd.compare(_baseline(), _snap(payload))+ assert delta.exit_code() == 2+ assert any("high" in row for row in delta.worse)+++def test_a_baseline_with_no_engine_verdicts_is_void_like_the_candidate() -> None:+ """The guard existed on one side only.++ A baseline hash VirusTotal knows but has never analysed carries no engines, no Sigma and no+ YARA. Compared against a real candidate, every finding reads as newly introduced, so the run+ exited 2 and named a list of regressions while having compared against nothing at all.+ """+ empty = {+ "data": {"attributes": {"size": 1, "last_analysis_stats": {}, "last_analysis_results": {}}}+ }+ baseline = _snap(empty, "baseline", "a" * 64)+ delta = vtd.compare(baseline, _snap(copy.deepcopy(vtd._BASELINE_FIXTURE)))+ assert delta.exit_code() == 3, "an unanalysed baseline was compared against instead of voiding"+ assert not delta.worse, f"it reported regressions against an empty baseline: {delta.worse}"+++# ---------------------------------------------------------------------------+# It must recognise an improvement without overstating it+# ---------------------------------------------------------------------------+++def test_a_clear_improvement_passes_and_is_named() -> None:+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["sigma_analysis_stats"] = {"medium": 4, "low": 5}+ payload["data"]["attributes"]["crowdsourced_yara_results"] = []+ delta = vtd.compare(_baseline(), _snap(payload))+ assert delta.exit_code() == 0+ assert delta.better and not delta.worse+++def test_an_unmoved_engine_verdict_is_reported_as_unchanged() -> None:+ """A cloud behavioural verdict is not recomputed because we deleted some code. Sigma moving+ while the engine does not is the expected shape of a win here, and reporting it as a clean bill+ of health would be the overclaim this tool exists to avoid."""+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["sigma_analysis_stats"] = {"medium": 4}+ delta = vtd.compare(_baseline(), _snap(payload))+ assert any("unchanged" in row for row in delta.same)+ assert any("Skyhigh" in row for row in delta.same)+++# ---------------------------------------------------------------------------+# VOID is not clean+# ---------------------------------------------------------------------------+++def test_an_unknown_candidate_hash_is_void() -> None:+ missing = vtd.Snapshot(label = "candidate", sha256 = "f" * 64, note = "not present on VirusTotal")+ delta = vtd.compare(_baseline(), missing)+ assert delta.exit_code() == 3+ assert (+ not delta.same and not delta.worse and not delta.better+ ), "an unknown hash produced comparison rows it cannot support"+++def test_a_known_but_never_analysed_file_is_void() -> None:+ """The subtle one. Zero engine verdicts is not sixty engines clearing the file."""+ payload = {+ "data": {"attributes": {"size": 1, "last_analysis_stats": {}, "last_analysis_results": {}}}+ }+ delta = vtd.compare(_baseline(), _snap(payload))+ assert delta.exit_code() == 3+++def test_a_missing_api_key_exits_three_and_never_says_clean() -> None:+ env = {k: v for k, v in os.environ.items() if k != vtd.API_KEY_ENV}+ result = subprocess.run(+ [sys.executable, str(SCRIPT), "--candidate-sha256", "a" * 64],+ capture_output = True,+ text = True,+ timeout = 120,+ env = env,+ )+ assert result.returncode == 3, (+ "a missing key must not exit zero. It is the most likely reason this ever produces no "+ f"comparison, and it must not be spelled the same as 'nothing got worse'.\n{result.stdout}"+ )+ assert "COULD NOT MEASURE" in result.stdout+ assert "clean" not in result.stdout.lower().replace("not a clean result", "")+++def test_the_three_outcomes_have_distinct_exit_codes() -> None:+ void, worse, fine = vtd.Delta(), vtd.Delta(), vtd.Delta()+ void.void.append("x")+ worse.worse.append("y")+ assert (void.exit_code(), worse.exit_code(), fine.exit_code()) == (3, 2, 0)+++# ---------------------------------------------------------------------------+# The tool's own controls, and the parsers+# ---------------------------------------------------------------------------+++def test_the_self_test_passes() -> None:+ result = subprocess.run(+ [sys.executable, str(SCRIPT), "--self-test"], capture_output = True, text = True, timeout = 120+ )+ assert result.returncode == 0, result.stdout + result.stderr+++def test_the_self_test_can_fail() -> None:+ """A control that cannot fail is decoration."""+ original = vtd.compare+ try:+ vtd.compare = lambda base, cand: vtd.Delta() # never reports anything+ failures = vtd.self_test()+ assert failures, "a comparison that reports nothing at all still passed the controls"+ finally:+ vtd.compare = original++[email protected]("raw", [None, [], "high", {"high": "two"}, {"high": True}])+def test_the_sigma_parser_survives_a_schema_change(raw) -> None:+ """VirusTotal has renamed and added buckets over time. A crash here would break the measurement+ on precisely the day the schema moved, which is when it is most worth having."""+ assert vtd.parse_sigma(raw) == {}++[email protected]("raw", [None, {}, "x", [1, 2], [{"no_name": 1}]])+def test_the_yara_parser_survives_a_schema_change(raw) -> None:+ assert vtd.parse_yara(raw) == []+++def test_the_tool_has_no_upload_path_at_all() -> None:+ """Not an oversight. A freshly uploaded file is a prevalence-zero first-seen sample, which is+ what the strict cloud settings punish -- so uploading a candidate can create the detection it+ was meant to measure, under a hash no user will ever have."""+ import ast++ tree = ast.parse(SCRIPT.read_text(encoding = "utf-8"))+ # Parsed, not grepped. The module docstring explains at length why there is no upload path, so a+ # substring search over the file text matches its own explanation -- which is how the first+ # version of this test failed. What matters is what the code does.+ calls = []+ for node in ast.walk(tree):+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ calls.append(node.value)+ methods = {c.upper() for c in calls if c.upper() in {"POST", "PUT", "PATCH", "DELETE"}}+ assert not methods, (+ f"the delta tool now issues {sorted(methods)}. It must only ever GET: a freshly uploaded "+ f"file is a prevalence-zero first-seen sample, so uploading a candidate can create the "+ f"detection it was meant to measure, under a hash no user will ever have."+ )+ imported = {+ alias.name+ for node in ast.walk(tree)+ if isinstance(node, ast.ImportFrom) and node.module+ for alias in node.names+ }+ assert (+ "scan_file" not in imported and "upload_file" not in imported+ ), "the delta tool imported an upload helper from virustotal_scan"+++def test_the_workflow_reads_the_secret_this_repository_actually_has() -> None:+ """`VT_API_KEY` is the env var the Python reads; the repository secret is+ `VIRUS_TOTAL_API_TOKEN`.++ Naming the secret `VT_API_KEY` in the workflow expands to empty, and the lane then exits 3 and+ reports VOID on every run. That fails loudly rather than reporting a false clean, which is the+ right shape -- but a lane that can never measure anything is worth catching here rather than+ after someone dispatches it and waits.+ """+ import yaml as _yaml++ workflow = REPO / ".github" / "workflows" / "virustotal-installer-delta.yml"+ body = workflow.read_text(encoding = "utf-8")+ assert "secrets.VIRUS_TOTAL_API_TOKEN" in body, (+ "the delta lane no longer reads secrets.VIRUS_TOTAL_API_TOKEN, which is the only VirusTotal "+ "secret this repository defines"+ )+ assert "secrets.VT_API_KEY" not in body, (+ "the workflow reads secrets.VT_API_KEY, which does not exist. VT_API_KEY is the ENV VAR "+ "name; the secret is VIRUS_TOTAL_API_TOKEN."+ )+ # And the history check the lane performs needs full depth, or it reverifies nothing.+ data = _yaml.safe_load(body)+ checkout = next(+ s for s in data["jobs"]["delta"]["steps"] if "checkout" in str(s.get("uses", ""))+ )+ assert (+ checkout.get("with", {}).get("fetch-depth") == 0+ ), "the baseline is reverified against 1ad44677d, which a shallow clone does not contain"+++def test_two_rulesets_sharing_a_rule_name_stay_distinct() -> None:+ """A hit gained from another ruleset must not compare equal to the baseline's.++ Crowdsourced rulesets are independent, so the same rule identifier can appear in two of them.+ Keying a hit on the rule name alone collapsed them, and a candidate that picked up a hit from a+ second ruleset still parsed to the baseline's list, so the comparison reported YARA unchanged+ and the run exited 0 on a genuine regression.+ """+ parsed = vtd.parse_yara(+ [+ {"ruleset_name": "set_a", "rule_name": "SUSP_Script"},+ {"ruleset_name": "set_b", "rule_name": "SUSP_Script"},+ ]+ )+ assert len(parsed) == 2, f"the two rulesets collapsed to one hit: {parsed}"++ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["crowdsourced_yara_results"] = [+ {"ruleset_name": "set_a", "rule_name": "SUSP_Script"},+ {"ruleset_name": "set_b", "rule_name": "SUSP_Script"},+ ]+ baseline_payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ baseline_payload["data"]["attributes"]["crowdsourced_yara_results"] = [+ {"ruleset_name": "set_a", "rule_name": "SUSP_Script"},+ ]+ delta = vtd.compare(_snap(baseline_payload, "baseline", "a" * 64), _snap(payload))+ assert delta.exit_code() == 2, "a hit gained from a second ruleset was reported as unchanged"+ assert any("YARA" in row for row in delta.worse), delta.worse+++def test_third_party_text_cannot_break_the_job_summary() -> None:+ """Engine names and rule names are third-party data rendered as Markdown.++ The summary is appended to `$GITHUB_STEP_SUMMARY`, where a newline ends the row or bullet, `|`+ opens a new cell and `<` begins HTML that GitHub renders. `virustotal_scan._md_text` exists for+ exactly this and the report was not using it.+ """+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["last_analysis_results"] = {+ "Evil|Engine": {"category": "malicious", "result": "x | y\n| broken | row |<img src=x>"},+ }+ delta = vtd.compare(_baseline(), _snap(payload))+ report = vtd.render(_baseline(), _snap(payload), delta)+ assert "<img" not in report, "raw HTML from a detection label reached the summary"+ for line in report.splitlines():+ if line.startswith("- ") or (line.startswith("|") and "---" not in line):+ assert "\n" not in line+ assert (+ "Evil\\|Engine" in report or "Evil|Engine" not in report+ ), "the engine name's pipe was not escaped, so it opens a new table cell"+++def test_an_overridden_baseline_is_not_labelled_as_the_recorded_one() -> None:+ """The report identified every baseline as install.ps1 at 1ad44677d, override or not.++ A dispatch can supply `baseline_sha256`, and the lookup and comparison then use that hash while+ the header still claimed the recorded identity and printed that file's historical scores. The+ resulting artifact combines one file's live table with another's name, which is a delta built+ to be misread.+ """+ # The real recorded hash, not the placeholder the other helpers use: the label is chosen by+ # comparing against it, so a stand-in would test nothing.+ real = _snap(copy.deepcopy(vtd._BASELINE_FIXTURE), "baseline", vtd.BASELINE_SHA256)+ recorded = vtd.render(real, _snap(copy.deepcopy(vtd._BASELINE_FIXTURE)), vtd.Delta())+ assert vtd.BASELINE_NOTE in recorded, "the recorded baseline lost its provenance note"++ other = _snap(copy.deepcopy(vtd._BASELINE_FIXTURE), "baseline", "c" * 64)+ overridden = vtd.render(other, _snap(copy.deepcopy(vtd._BASELINE_FIXTURE)), vtd.Delta())+ assert (+ vtd.BASELINE_NOTE not in overridden+ ), "an overridden baseline is still labelled as install.ps1 at the recorded commit"+ assert "OVERRIDDEN" in overridden, overridden.splitlines()[:4]+++def test_a_spent_deadline_becomes_a_void_row_and_not_a_crash() -> None:+ """The deadline this tool added raised past its own handler.++ `VirusTotalClient.request` signals a spent budget with `TimeoutError`, which inherits from+ `OSError` and not from `RuntimeError`, so the `except RuntimeError` in `fetch` let it through.+ The workflow then died with a traceback before `render` wrote anything, which is the lost run+ the deadline was added to prevent.+ """++ class _Expired:+ def request(self, *args, **kwargs):+ raise TimeoutError("deadline reached before GET /files/x")++ snap = vtd.fetch(_Expired(), "d" * 64, "candidate", deadline = 0.0)+ assert snap.total_engines == 0, "a timed-out lookup invented engine verdicts"+ assert "budget" in snap.note, snap.note+++def test_a_renamed_sigma_bucket_is_not_silently_dropped() -> None:+ """The parser warned about renamed buckets in its docstring and then read a fixed key list.++ A candidate that gains rules only in a bucket outside critical/high/medium/low produced a Sigma+ dictionary identical to the baseline's, so the comparison reported Sigma unchanged and the run+ exited 0 on a real regression. The day VirusTotal renames or adds a bucket is exactly the day+ this measurement matters.+ """+ assert vtd.parse_sigma({"informational": 3}) == {+ "informational": 3+ }, "an unrecognised severity bucket is still dropped by the parser"++ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["sigma_analysis_stats"] = {"high": 1, "informational": 4}+ base_payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ base_payload["data"]["attributes"]["sigma_analysis_stats"] = {"high": 1}+ delta = vtd.compare(_snap(base_payload, "baseline", "a" * 64), _snap(payload))+ assert delta.worse, "rules gained in an unranked bucket were reported as no change"+ assert any("informational" in row for row in delta.worse), delta.worse+ assert delta.exit_code() == 2, delta+++def test_an_unranked_bucket_never_overrides_the_ordered_tradeoff() -> None:+ """The ordered comparison depends on knowing which bucket is more severe, so it keeps its own.++ Trading a high for several lows is still the improvement the comment claims, and an unranked+ bucket that did not move must not turn it into a regression.+ """+ base_payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ base_payload["data"]["attributes"]["sigma_analysis_stats"] = {+ "high": 1,+ "low": 5,+ "informational": 2,+ }+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["sigma_analysis_stats"] = {+ "high": 0,+ "low": 8,+ "informational": 2,+ }+ delta = vtd.compare(_snap(base_payload, "baseline", "a" * 64), _snap(payload))+ assert delta.exit_code() == 0, (delta.worse, delta.better)+++def test_engines_that_answered_in_a_newer_bucket_still_count() -> None:+ """`ScanStats.total` sums five buckets, and `parse_stats` documents more than five.++ `type-unsupported` and `failure` are named in that parser's own docstring as categories+ VirusTotal has added, but the dataclass has no field for them, so the engine count this report+ prints was short by however many engines answered that way. Worse, a response made up entirely+ of those buckets summed to zero, which this tool treats as a file nothing has scanned and voids.+ """+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ stats = payload["data"]["attributes"]["last_analysis_stats"]+ before = vtd.snapshot_from_payload("candidate", "b" * 64, payload).total_engines+ stats["type-unsupported"] = 5+ stats["failure"] = 2+ after = vtd.snapshot_from_payload("candidate", "b" * 64, payload).total_engines+ assert (+ after == before + 7+ ), f"engines that answered in a newer bucket were not counted: {before} -> {after}"++ # The bucket-only case, which used to read as unanalysed and void the run.+ only_new = copy.deepcopy(vtd._BASELINE_FIXTURE)+ only_new["data"]["attributes"]["last_analysis_stats"] = {"type-unsupported": 3}+ snap = vtd.snapshot_from_payload("candidate", "b" * 64, only_new)+ assert snap.total_engines == 3, snap.total_engines+ assert "no engine verdicts" not in snap.note, snap.note+++def test_a_non_numeric_bucket_cannot_inflate_the_engine_count() -> None:+ """VirusTotal sends counts; a bool or a string in that position must not add one each."""+ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ clean = vtd.snapshot_from_payload("candidate", "b" * 64, payload).total_engines+ payload["data"]["attributes"]["last_analysis_stats"]["weird"] = True+ payload["data"]["attributes"]["last_analysis_stats"]["odd"] = "12"+ assert vtd.snapshot_from_payload("candidate", "b" * 64, payload).total_engines == clean+++def test_an_engine_that_did_not_answer_has_not_cleared_us() -> None:+ """Absence from the candidate's results is not a clean verdict from that engine.++ Skyhigh is the one engine that actually flags this file, so "Skyhigh no longer flags it" is the+ single most consequential sentence this report can print. Deriving it from a set difference+ made a sparse or older candidate analysis -- one where Skyhigh simply had not run -- say+ exactly that, and exit 0.+ """+ base_payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ base_payload["data"]["attributes"]["last_analysis_results"] = {+ "Skyhigh": {"category": "malicious", "result": "BehavesLike.PS.Suspicious.gr"},+ "Microsoft": {"category": "undetected", "result": None},+ }+ baseline = _snap(base_payload, "baseline", "a" * 64)++ # Skyhigh did not run on the candidate at all.+ silent = copy.deepcopy(vtd._BASELINE_FIXTURE)+ silent["data"]["attributes"]["last_analysis_results"] = {+ "Microsoft": {"category": "undetected", "result": None},+ }+ delta = vtd.compare(baseline, _snap(silent))+ assert not any(+ "no longer flag" in row for row in delta.better+ ), f"an engine that never answered was reported as having cleared the candidate: {delta.better}"+ assert any("NOT cleared" in row for row in delta.same), delta.same++ # And the real improvement still reads as one: Skyhigh answered, and answered undetected.+ cleared = copy.deepcopy(vtd._BASELINE_FIXTURE)+ cleared["data"]["attributes"]["last_analysis_results"] = {+ "Skyhigh": {"category": "undetected", "result": None},+ "Microsoft": {"category": "undetected", "result": None},+ }+ delta = vtd.compare(baseline, _snap(cleared))+ assert any("no longer flag" in row for row in delta.better), delta.better+ assert any("Skyhigh" in row for row in delta.better), delta.better+++ "category", ["timeout", "confirmed-timeout", "failure", "type-unsupported"]+)+def test_an_inconclusive_result_does_not_clear_a_prior_detection(category: str) -> None:+ """An engine that timed out has not cleared us any more than one that never ran.++ The responder set was built on the truthiness of `category`, so these four entries counted as+ answers while `parse_detections` correctly excluded them from the flagging list. The engine then+ appeared in neither set and was reported as having stopped flagging the candidate.+ """+ base_payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ base_payload["data"]["attributes"]["last_analysis_results"] = {+ "Skyhigh": {"category": "malicious", "result": "BehavesLike.PS.Suspicious.gr"},+ "Microsoft": {"category": "undetected", "result": None},+ }+ baseline = _snap(base_payload, "baseline", "a" * 64)++ payload = copy.deepcopy(vtd._BASELINE_FIXTURE)+ payload["data"]["attributes"]["last_analysis_results"] = {+ "Skyhigh": {"category": category, "result": None},+ "Microsoft": {"category": "undetected", "result": None},+ }+ delta = vtd.compare(baseline, _snap(payload))+ assert not any(+ "no longer flag" in row for row in delta.better+ ), f"a {category!r} result was treated as Skyhigh clearing the candidate: {delta.better}"+ assert any("NOT cleared" in row for row in delta.same), delta.same