Skip to content

Studio: avoid hidden PowerShell arguments in CLI setup and updates - #10560

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
oobabooga:fix/windows-cli-powershell-launch
Sep 9, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
oobabooga:fix/windows-cli-powershell-launch

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Problem

Studio's Windows installer and Desktop Rust launcher already avoid pairing -WindowStyle Hidden with -ExecutionPolicy Bypass, documenting the combination as a Microsoft detection signature. The CLI still assembled that pair. The existing installer AV-shape guard scans shell scripts, so it did not cover Python-generated arguments.

This path runs during Desktop updates: spawn_update in studio/src-tauri/src/update.rs pipes the CLI's stdout, making sys.stdout.isatty() false and selecting the hidden-launch branch for setup.ps1. The same subprocess already receives CREATE_NO_WINDOW, so removing the PowerShell window-style argument preserves console suppression.

The CLI has two argument builders and three affected handoffs: setup.ps1, a local install.ps1 --shortcuts-only, and a downloaded installer used when no local copy is available. Shortcut refresh applies to standalone updates; Tauri-initiated updates skip that refresh.

Change

Remove -WindowStyle Hidden from both CLI argument builders. Redirected launches keep CREATE_NO_WINDOW, -NoLogo and -NonInteractive. Interactive launches keep their existing behavior.

The setup and local-refresh paths retain their -Command quoting and *>&1 output handling. Downloaded refresh retains -File, UTF-8 BOM encoding and temporary-script cleanup. Execution policy is unchanged. Switching these paths to RemoteSigned needs separate path-origin compatibility work.

Both call sites now explain the launch policy. The behavioral regression test and the shell-script guard cross-reference each other so their complementary coverage is visible.

Verification

  • Six behavioral cases exercise the actual setup, local-refresh and fetched-refresh handoffs with console and redirected output, capturing subprocess arguments and creation flags.
  • Against the previous implementation, all three redirected cases fail because -WindowStyle is present; the three console cases pass.
  • Focused PowerShell launch, shortcut refresh, uv-cache handoff, Windows update-launcher and installer AV-shape suites: 197 passed, 6 skipped on Linux. Windows-only execution checks were skipped.
  • Repository lint and formatting hooks passed.
  • git diff --check passed.

Scope

This brings the CLI setup and refresh launches into line with the existing Hidden/Bypass rule. It does not remove the installer native helper's runtime C# compilation, change path resolution or process detection, or repair denied caches and missing Python packages. Compiler removal is being addressed separately in #10540.

The packaged Windows application and Bitdefender were not tested. This is not a claim that the reported antivirus block is resolved.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-09T10:23:47.338722Z efa5ff1 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member

Checked this one by measurement rather than by reading the diff, since the claim it rests on is that removing the flag cannot change which launches are hidden. It holds, and the mechanism is stronger than the description says.

What I verified

_windows_hidden_subprocess_kwargs() and the removed -WindowStyle Hidden are gated on the same predicate, _should_hide_windows_subprocesses(). So the substitution is exact by construction: every launch that used to get the flag now gets the kwargs, and every launch that did not still does not. There is no window where one applies and the other does not.

Those kwargs are also not just CREATE_NO_WINDOW. They set STARTUPINFO with STARTF_USESHOWWINDOW and SW_HIDE as well, so console suppression is covered twice at the process level.

And the flag was inert rather than merely compensated for. -WindowStyle sets the initial show state of a window PowerShell would own; with CREATE_NO_WINDOW the child gets no console at all, so there was no window to style. Removing it cannot change what the user sees.

All three handoffs pass those kwargs: _run_setup_script (Popen), _run_installer_ps1 (run), _run_fetched_installer_ps1 (run).

The new test is not vacuous. Against origin/main's studio.py it fails on exactly the three redirected cases and passes the three console ones, which is what the description claims:

FAILED ...test_windows_launch_uses_process_flags_without_windowstyle[setup-redirected]
FAILED ...test_windows_launch_uses_process_flags_without_windowstyle[local-refresh-redirected]
FAILED ...test_windows_launch_uses_process_flags_without_windowstyle[fetched-refresh-redirected]
3 failed, 3 passed

No -WindowStyle is left in any non-test Python after this. The one remaining use, the shortcut launcher in tests/studio/install/test_launch_studio_launcher.py, pairs Hidden with RemoteSigned rather than Bypass, which is the allowed combination and is asserted as such.

Against #10540, which touches tests/studio/test_installer_av_shapes.py heavily: no conflict in either merge order, and with both applied test_installer_av_shapes.py, test_studio_runtime_gate_powershell.py, test_windows_installer_native_type_fallback.py and test_launch_studio_launcher.py give 112 passed, 2 skipped.

One thing worth adding

The guard still cannot see Python, and the cross-reference comment documents that rather than closing it. A fourth handoff added later would be uncovered, because the three behavioural cases name the three that exist today.

Extending test_a_hidden_window_never_pairs_with_a_bypassed_policy to unsloth_cli/**/*.py as-is would not work, and would be worse than not extending it, because it would look like coverage. The regex is -WindowStyle\s+Hidden, and the Python form is two separate tokens:

powershell_args.extend(["-NoLogo", "-NonInteractive", "-WindowStyle", "Hidden"])

which that pattern does not match. A Python-aware assertion needs to look for the tokens adjacent in an argv list, or read the argv builders through the AST. Worth doing in this PR while the context is fresh, but I would not block on it.

Scope

Agreed on leaving Bypass alone here. Moving these paths to RemoteSigned is a path-origin compatibility question and does not belong in the same change, and the PR is right that this is not a claim the reported Bitdefender block is resolved. The block is on the compiler chain, which is #10540's job; this removes an independently scored launch shape, which is worth doing on its own merits.

Static and LLM malicious scan of the diff: clean.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

2 similar comments
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: efa5ff1bd1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Reviewed this properly rather than by eye, and it holds up. Merging it.

The mechanism, confirmed against primary sources rather than assumed. CREATE_NO_WINDOW stops the console window from existing at all ("the console handle for the application is not set"). STARTUPINFO.wShowWindow with SW_HIDE starts a window hidden if one is created. -WindowStyle Hidden is applied by PowerShell inside the already-running process: ConsoleHost.ParseCommandLine reaches ConsoleControl.SetConsoleMode, which calls GetConsoleWindow() then ShowWindow(hwnd, SW_HIDE), and asserts the console handle is never zero. It is show-then-hide, on a window that under CREATE_NO_WINDOW was never drawn. So at these three sites the flag was doing nothing.

The two gates are the same predicate, which is the part worth checking, since a flag removed from argv would matter if the process flags were conditional on something else. _should_hide_windows_subprocesses() decides both the argv branch and _windows_hidden_subprocess_kwargs(), and the latter early-returns {} under the same condition, then sets creationflags and startupinfo together. There is no state where the argv change applies and the process flags do not. All three handoffs pass the kwargs: _run_setup_script, _run_installer_ps1, _run_fetched_installer_ps1.

Three cases I specifically went looking for, all clear. Interactive stdout: _should_hide_windows_subprocesses() is false, so the extend never ran before this PR either, and both argv are identical. Windows PowerShell 5.1 versus pwsh 7: both share the same SetConsoleMode implementation, and the only documented divergence is pwsh erroring on non-Windows, unreachable here. A nested PowerShell spawned by install.ps1: -WindowStyle acts on the process's own console window and is not inherited, so a grandchild's visibility is governed by the parent's CREATE_NO_WINDOW either way.

Scoping is right, and I checked the thing that would have made it wrong. install.ps1:2816 keeps -WindowStyle Hidden on the shortcut, where there is no CREATE_NO_WINDOW to lean on and the flag does real work, paired with -ExecutionPolicy RemoteSigned for exactly the reason the comment above it gives. studio/src-tauri/src/install.rs already refuses the Hidden/Bypass pair and asserts it. So this brings the CLI into line with the Rust launcher rather than introducing a new position.

The new test is not vacuous. Against an otherwise identical tree with only studio.py reverted, it fails on the three redirected cases and passes the three console ones, which is exactly the claim. It also covers a gap the shell-script scanner structurally cannot see, since that scanner reads the .ps1 and .sh files and this argv is assembled in Python.

Red checks, each traced rather than waved off:

check cause
linux ubuntu2404-arm-root built from source: nvidia-npp-cu13 -- character-identical on main. Upstream arm64 wheel availability.
Repo tests (CPU) byte-identical failure set on main, including the same literal offsets in test_windows_amd_gpu_scan_fallback.
(Python 3.13) test_event_batch_flushes_while_upstream_is_idle, a timing race; reproduces on a tree with this PR's only change reverted, and this check is red on several recent main commits.
Chat UI, API, Update and GGUF inference macOS runner; its own log records the backend stalling 25s and an artifact upload ENOTFOUND. Green on main.

None of the four touch anything in the diff, and the diff is three files that do not include studio/backend.

One thing this PR correctly does not claim: it is not a fix for any reported antivirus block, and it is not tested against a packaged build or a real scanner. It removes an argument that was inert here and is a well-catalogued adversary pattern, which is worth doing on its own terms.

@danielhanchen
danielhanchen merged commit 247e3e8 into unslothai:main Sep 9, 2026
79 of 85 checks passed
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…stead of arguing that it does not

Six antivirus-hardening passes have shipped (#7822, #8586, #6326, #10540, #10560, #10504). Each was
argued safe in prose, because there was no way to show it. The worry that hardening breaks
functionality is the right worry, and the answer to it is a measurement, not a more careful argument.

This lane installs from the merge base and from the candidate on two identical Windows runners and
compares four things. Zero differences is the pass condition.

- **The transcript.** Every line the installer printed, normalised. `step` pads its label to exactly
  15 columns and the output lock pins the indent, so leading whitespace is compared and only
  trailing whitespace is stripped.
- **The `.lnk` launch contract**, read back through the shell rather than taken from the installer's
  own log: target, arguments, working directory, window style, icon. `arguments` carries
  `-WindowStyle` and `-ExecutionPolicy`, which is the pair this whole effort is about, and a change
  there is completely invisible in the transcript -- which is what a prose review looks at.
- **The generated files** whose text is a contract: `launch-studio.ps1`, `unsloth.cmd`,
  `share/studio.conf`, plus the shape of the install tree.
- **Idempotency**, by installing twice. Several of the changes this lane judges touch
  content-comparison paths -- the code deciding whether a launcher needs rewriting at all -- so "a
  reinstall writes nothing" is a contract that can break silently.

## VOID is not a pass

Same commit on both sides, missing evidence, an installer that did not finish, a checkout that
resolved to the wrong tree: each is reported as "nothing was measured" and exits **3**, distinct from
**2** for "it changed", because those need different reactions from whoever reads the run.

Two of those guards exist because the failure actually happened while building this:

- A collection error on both sides compared equal to itself. Two runs that both failed to read any
  shortcut reported "1 compared, every field equal" and exited zero. Failures are symmetric far more
  often than behaviour changes are, since they come from the host and both sides share it, so the
  symmetry is no comfort at all. Any entry carrying an `error` is now VOID.
- `ConvertTo-Json` unwraps a one-element collection into a bare object, and `-AsArray` does not exist
  on Windows PowerShell 5.1. With exactly one shortcut found, `shortcuts.json` was an object;
  iterating that yields dictionary *keys*, so two different launch contracts would have compared as
  agreement. Forced to an array on the producing side and tolerated on the consuming side.

The `measure` job also asserts that `git rev-parse HEAD` equals the SHA it asked for. A checkout that
silently resolved to the default branch would make both sides the same tree, the comparison trivially
pass, and the lane report that a change broke nothing while never having seen the change.

Both sides are measured with the tools from the candidate, never each side's own copy: a base commit
that predates them has neither, and measuring two sides with two different rulers is not a
measurement.

## The comparer can fail, and that is tested

A differ reporting no differences looks identical whether it is working or broken, so the comparer
carries positive controls and refuses to produce a verdict if they fail. They run twice: once before
either install starts, so a drifted normaliser costs seconds rather than ninety minutes of runner
time ending in a meaningless green check, and once immediately before the verdict.

20 unit tests in `tests/python/test_installer_differential_comparer.py`, weighted toward the failure
direction. A changed output line, a lost indent, `RemoteSigned` becoming `Bypass` in a shortcut, a
shortcut that stopped being created, a changed generated launcher, a second run that rewrote
something -- each must be reported. One of them widens the normaliser until it erases every line and
requires the self-test to notice, because a control that cannot fail is decoration.

The other direction is tested too, since a lane that fails on every run gets disabled, which costs
the same coverage by a slower route: a `uv` patch release and a 30-second timing difference must not
fail it. Version drift is normalised away **and printed anyway** -- silently normalising something
and never mentioning it is how a lane stops being able to tell you anything. Every normalisation rule
carries a written cause, enforced by a test, because that list is exactly where a future "just make
it green" change would land.

## Cost

Two full clean-machine installs, so it opts in: the `installer-differential` label, a dispatch, or
the weekly schedule. `synchronize` is in the trigger list so a labelled PR keeps being re-measured as
it is pushed to, rather than the verdict being about whichever commit was there when the label went
on. Not a required check.

## What it cannot answer

Nothing about a third-party antivirus: hosted runners have none, and installing an endpoint agent per
run is neither fast nor faithful. Nothing about Windows PowerShell 5.1 at a real console either --
that is `windows-vt-preflight.yml`.

## Verification

- 887 passed, 9 skipped across `tests/security/`, the new comparer tests, the workflow-trigger lint
  and the installer shape suite.
- The collector was run end to end under `pwsh` on Linux, feeding the real comparer. That is what
  exposed both JSON defects above and a third: `Join-Path` throws on a null path, and composing
  `%APPDATA%` unconditionally made a parse-clean script print a binding error before doing any work.
- `Parser::ParseFile` clean on the collector; the workflow parses as YAML with the three expected
  jobs.
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…already worked

Six hardening passes shipped with no measurement (#7822, #8586, #6326, #10540, #10560, #10504). There
was no baseline to measure against. There is one now: install.ps1 at commit 1ad4467 is the revision
reported in #10805, it hashes to ec29980b..., and VirusTotal holds its verdict.

## The result, run live against the real key

    | | baseline (1ad4467) | main (2c70592a) |
    | engines flagging | 1 / 60                | 1 / 61          |
    | which            | Skyhigh BehavesLike.PS.Suspicious.gr | the same |
    | Sigma            | 17 (high 1, medium 11, low 5) | 14 (medium 10, low 4) |
    | YARA             | 2                     | 0               |

The **high**-severity Sigma rule is gone. So are both crowdsourced YARA hits,
`INDICATOR_SUSPICIOUS_PWSH_B64Encoded_Concatenated_FileEXEC` and `Windows_API_Function`. Three fewer
Sigma rules overall. The Skyhigh verdict has not moved, and that is reported as unchanged rather than
dressed up: a cloud behavioural verdict is not recomputed because we deleted some code.

So the static indicators, which are what drives the alarming scores third-party analysis sites report,
already improved measurably. That was not knowable before.

Two corrections to what I wrote in the plan, both from running this rather than reasoning about it:

- I recorded current main's install.ps1 as **not on VirusTotal**. It is. It has been scanned since,
  so the delta above is real and not a projection.
- I treated the prior passes as unverifiable. They are verifiable, retroactively, and they worked on
  the axis they could affect.

## Three axes, separately

Reporting only the engine count makes every shape win look like it achieved nothing. Reporting only
Sigma overclaims. Both, or the number is not worth having.

Engines are compared **by name**, not by count. A count-only comparison calls the single most
consequential possible change -- Skyhigh's detection being replaced by Microsoft's, one engine before
and one after -- "no difference". Defender is on every Windows machine; Skyhigh is enterprise-deployed.
There is a test for exactly that case.

Sigma is compared **per severity**, not in total. Trading one high for three lows is an improvement a
total calls a regression, and the reverse is a regression a total calls an improvement.

## GET only, and VOID is not clean

There is no upload path, and that is a deliberate omission rather than an oversight. 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
`virustotal_scan.py` at release time; branches are not. A test parses the module and asserts no
non-GET method appears, having first been written as a grep and caught matching the module's own
explanation of why there is no upload.

So an unknown hash is VOID, exit 3, never clean. Also VOID: a missing `VT_API_KEY`, and a file
VirusTotal knows but has never analysed -- that last one being the subtle case, because zero engine
verdicts is not sixty engines clearing the file. Exit codes are distinct: 3 could-not-measure, 2
worse, 0 not worse.

## The baseline is checked, not trusted

A baseline hash copied out of an issue is a number nobody can verify, and if it ever pointed at the
wrong file every delta reported against it would be wrong while the lane looked perfectly healthy. So
both a test and a workflow step recompute it from this repository's history -- `git show
1ad4467:install.ps1` -- and assert the 427,113 bytes the sample is recorded as. A shallow clone
skips rather than fails.

## Verification

- 613 passed, 6 skipped across `tests/security/`, including 25 new tests.
- Run live against the real key; the table above is its actual output.
- Weighted toward the failure direction: a new high-severity rule, a new YARA hit, an engine swap at
  an unchanged count, and a medium promoted to high must each be reported as worse. One test replaces
  the comparison with one that reports nothing and requires the self-test to notice, because a
  control that cannot fail is decoration.
- Both parsers are fuzzed against schema drift. VirusTotal has renamed and added buckets over time,
  and a crash would break the measurement on precisely the day the schema moved.
danielhanchen added a commit that referenced this pull request Sep 15, 2026
…already worked (#10996)

* Give this work a before-and-after number, and find out the hardening already worked

Six hardening passes shipped with no measurement (#7822, #8586, #6326, #10540, #10560, #10504). There
was no baseline to measure against. There is one now: install.ps1 at commit 1ad4467 is the revision
reported in #10805, it hashes to ec29980b..., and VirusTotal holds its verdict.

## The result, run live against the real key

    | | baseline (1ad4467) | main (2c70592a) |
    | engines flagging | 1 / 60                | 1 / 61          |
    | which            | Skyhigh BehavesLike.PS.Suspicious.gr | the same |
    | Sigma            | 17 (high 1, medium 11, low 5) | 14 (medium 10, low 4) |
    | YARA             | 2                     | 0               |

The **high**-severity Sigma rule is gone. So are both crowdsourced YARA hits,
`INDICATOR_SUSPICIOUS_PWSH_B64Encoded_Concatenated_FileEXEC` and `Windows_API_Function`. Three fewer
Sigma rules overall. The Skyhigh verdict has not moved, and that is reported as unchanged rather than
dressed up: a cloud behavioural verdict is not recomputed because we deleted some code.

So the static indicators, which are what drives the alarming scores third-party analysis sites report,
already improved measurably. That was not knowable before.

Two corrections to what I wrote in the plan, both from running this rather than reasoning about it:

- I recorded current main's install.ps1 as **not on VirusTotal**. It is. It has been scanned since,
  so the delta above is real and not a projection.
- I treated the prior passes as unverifiable. They are verifiable, retroactively, and they worked on
  the axis they could affect.

## Three axes, separately

Reporting only the engine count makes every shape win look like it achieved nothing. Reporting only
Sigma overclaims. Both, or the number is not worth having.

Engines are compared **by name**, not by count. A count-only comparison calls the single most
consequential possible change -- Skyhigh's detection being replaced by Microsoft's, one engine before
and one after -- "no difference". Defender is on every Windows machine; Skyhigh is enterprise-deployed.
There is a test for exactly that case.

Sigma is compared **per severity**, not in total. Trading one high for three lows is an improvement a
total calls a regression, and the reverse is a regression a total calls an improvement.

## GET only, and VOID is not clean

There is no upload path, and that is a deliberate omission rather than an oversight. 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
`virustotal_scan.py` at release time; branches are not. A test parses the module and asserts no
non-GET method appears, having first been written as a grep and caught matching the module's own
explanation of why there is no upload.

So an unknown hash is VOID, exit 3, never clean. Also VOID: a missing `VT_API_KEY`, and a file
VirusTotal knows but has never analysed -- that last one being the subtle case, because zero engine
verdicts is not sixty engines clearing the file. Exit codes are distinct: 3 could-not-measure, 2
worse, 0 not worse.

## The baseline is checked, not trusted

A baseline hash copied out of an issue is a number nobody can verify, and if it ever pointed at the
wrong file every delta reported against it would be wrong while the lane looked perfectly healthy. So
both a test and a workflow step recompute it from this repository's history -- `git show
1ad4467:install.ps1` -- and assert the 427,113 bytes the sample is recorded as. A shallow clone
skips rather than fails.

## Verification

- 613 passed, 6 skipped across `tests/security/`, including 25 new tests.
- Run live against the real key; the table above is its actual output.
- Weighted toward the failure direction: a new high-severity rule, a new YARA hit, an engine swap at
  an unchanged count, and a medium promoted to high must each be reported as worse. One test replaces
  the comparison with one that reports nothing and requires the self-test to notice, because a
  control that cannot fail is decoration.
- Both parsers are fuzzed against schema drift. VirusTotal has renamed and added buckets over time,
  and a crash would break the measurement on precisely the day the schema moved.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the VirusTotal secret this repository actually has, so the lane can measure something

`secrets.VT_API_KEY` does not exist. `VT_API_KEY` is the ENV VAR name the Python reads
(`scripts/virustotal_scan.py:37`); the repository secret is `VIRUS_TOTAL_API_TOKEN`, which is the only
VirusTotal secret in all 51 workflows, and `release-desktop.yml:2193` maps it the same way.

As written the expression expanded to empty and the lane exited 3 / VOID on every dispatch. That is
the right failure shape -- it refuses to report a clean it did not measure -- but a lane that can
never measure anything is not worth having, and the failure only surfaces after someone dispatches
it and waits.

Two guards added, because both halves of this were invisible:

- `test_the_workflow_reads_the_secret_this_repository_actually_has` pins the secret name in both
  directions and also asserts the checkout keeps `fetch-depth: 0`, since the step that reverifies
  the baseline against commit 1ad4467 reverifies nothing on a shallow clone.
- `test_the_baseline_hash_is_the_file_the_reporter_ran` now checks the constant's shape
  unconditionally before the git half. That git half skips on a shallow clone, which is every CI lane
  that collects `tests/security` -- so the one assertion tying the baseline to real history was green
  locally and silently absent everywhere it mattered.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Compare Sigma severities in order, and void an unanalysed baseline too

The per-severity comparison reported each bucket independently, which cannot express a trade:
swapping the single high rule for three extra low ones moves two buckets in opposite
directions, so it landed in worse and in better at once and exit_code answered worse. The
comment beside that loop calls exactly that swap an improvement. SEVERITIES is ordered most
severe first, so the most severe bucket that moved now decides and the rest are reported
alongside it without flipping the verdict.

The zero-engine guard was on the candidate only. A baseline hash VirusTotal knows but has never
analysed carries no engines, no Sigma and no YARA, so every finding on the candidate read as
newly introduced and the run exited 2 having compared against nothing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Bound the lookups, keep ruleset identity, and escape third-party text

Neither lookup carried a deadline, and request can spend four 300-second socket attempts plus 20,
40 and 80 seconds of backoff. The workflow gives the whole job 20 minutes, so the baseline lookup
alone could exhaust it and the runner would kill the step before it fetched the candidate or wrote
its summary, which is a lost run rather than a reported one. Both lookups now share a 420 second
budget and an expired budget is reported as VOID, since we did not find out.

YARA hits were keyed on the rule name alone, so the same rule identifier appearing in two
crowdsourced rulesets collapsed to one entry: a candidate could gain a hit from a second ruleset,
parse to the same list as the baseline, and exit 0 on a real regression. Keyed on ruleset and rule
now.

Engine names and detection labels are third-party text and the report is appended to
GITHUB_STEP_SUMMARY, where a newline ends the row, a pipe opens a cell and an angle bracket starts
HTML that GitHub renders. virustotal_scan._md_text exists for exactly this and the report was
bypassing it; reused rather than duplicated.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Stop labelling an overridden baseline as the recorded install.ps1

A dispatch can supply baseline_sha256, and the lookup and the comparison then use that hash while
the header still announced the recorded identity and printed install.ps1's historical scores
beside the override's live table. That is an artifact built to be misattributed: the numbers
belong to one file and the name to another.

The note is now printed only when the baseline hash really is the recorded one, and an override
says so and disclaims the historical comparison.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Catch a spent deadline in the VirusTotal delta lookup

VirusTotalClient.request signals an expired deadline with TimeoutError,
which inherits from OSError rather than RuntimeError, so the handler in
fetch never ran and the workflow died with a traceback before render
wrote its summary. That is the lost run the deadline was meant to
prevent. Catch both and keep returning a VOID row.

* Keep Sigma buckets this tool cannot rank

The parser warned in its own docstring that VirusTotal renames and adds
severity buckets, then read a fixed key list, so a candidate that gained
rules only in a new bucket produced a dictionary identical to the
baseline's and the run exited 0 on a regression. Keep every reported
bucket. Unrankable ones stay out of the ordered trade-off, which depends
on knowing which of two buckets is more severe, and a rise in one is
reported as worse rather than assumed minor.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Count every engine verdict bucket, not the five the dataclass carries

parse_stats names type-unsupported and failure as categories VirusTotal
has added, but ScanStats has fields only for five buckets, so the engine
count this report prints was short by however many engines answered that
way, and a response made up entirely of those buckets summed to zero and
voided the run as unanalysed. Sum every numeric bucket from the raw
stats, which leaves the shared dataclass alone for the release scanner.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require an explicit verdict before calling an engine cleared

An engine that flagged the baseline and is absent from the candidate's
results has not cleared it, it did not evaluate it, and a set difference
cannot tell those apart. Since Skyhigh is the one engine that actually
flags this file, a sparse candidate analysis could print the single most
consequential sentence in the report and exit 0. Track which engines
returned a verdict of any kind, call only an answering non-flagging
engine cleared, and report the silent ones as an unanswered question.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Only a conclusive verdict clears a prior detection

The responder set was built on the truthiness of the category, so
timeout, confirmed-timeout, failure and type-unsupported counted as
answers while parse_detections correctly left them out of the flagging
list. An engine returning one of those appeared in neither set and was
reported as having stopped flagging the candidate, which is the same
mistake as treating absence as a clean verdict.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…already worked (unslothai#10996)

* Give this work a before-and-after number, and find out the hardening already worked

Six hardening passes shipped with no measurement (unslothai#7822, unslothai#8586, unslothai#6326, unslothai#10540, unslothai#10560, unslothai#10504). There
was no baseline to measure against. There is one now: install.ps1 at commit 1ad4467 is the revision
reported in unslothai#10805, it hashes to ec29980b..., and VirusTotal holds its verdict.

## The result, run live against the real key

    | | baseline (1ad4467) | main (2c70592a) |
    | engines flagging | 1 / 60                | 1 / 61          |
    | which            | Skyhigh BehavesLike.PS.Suspicious.gr | the same |
    | Sigma            | 17 (high 1, medium 11, low 5) | 14 (medium 10, low 4) |
    | YARA             | 2                     | 0               |

The **high**-severity Sigma rule is gone. So are both crowdsourced YARA hits,
`INDICATOR_SUSPICIOUS_PWSH_B64Encoded_Concatenated_FileEXEC` and `Windows_API_Function`. Three fewer
Sigma rules overall. The Skyhigh verdict has not moved, and that is reported as unchanged rather than
dressed up: a cloud behavioural verdict is not recomputed because we deleted some code.

So the static indicators, which are what drives the alarming scores third-party analysis sites report,
already improved measurably. That was not knowable before.

Two corrections to what I wrote in the plan, both from running this rather than reasoning about it:

- I recorded current main's install.ps1 as **not on VirusTotal**. It is. It has been scanned since,
  so the delta above is real and not a projection.
- I treated the prior passes as unverifiable. They are verifiable, retroactively, and they worked on
  the axis they could affect.

## Three axes, separately

Reporting only the engine count makes every shape win look like it achieved nothing. Reporting only
Sigma overclaims. Both, or the number is not worth having.

Engines are compared **by name**, not by count. A count-only comparison calls the single most
consequential possible change -- Skyhigh's detection being replaced by Microsoft's, one engine before
and one after -- "no difference". Defender is on every Windows machine; Skyhigh is enterprise-deployed.
There is a test for exactly that case.

Sigma is compared **per severity**, not in total. Trading one high for three lows is an improvement a
total calls a regression, and the reverse is a regression a total calls an improvement.

## GET only, and VOID is not clean

There is no upload path, and that is a deliberate omission rather than an oversight. 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
`virustotal_scan.py` at release time; branches are not. A test parses the module and asserts no
non-GET method appears, having first been written as a grep and caught matching the module's own
explanation of why there is no upload.

So an unknown hash is VOID, exit 3, never clean. Also VOID: a missing `VT_API_KEY`, and a file
VirusTotal knows but has never analysed -- that last one being the subtle case, because zero engine
verdicts is not sixty engines clearing the file. Exit codes are distinct: 3 could-not-measure, 2
worse, 0 not worse.

## The baseline is checked, not trusted

A baseline hash copied out of an issue is a number nobody can verify, and if it ever pointed at the
wrong file every delta reported against it would be wrong while the lane looked perfectly healthy. So
both a test and a workflow step recompute it from this repository's history -- `git show
1ad4467:install.ps1` -- and assert the 427,113 bytes the sample is recorded as. A shallow clone
skips rather than fails.

## Verification

- 613 passed, 6 skipped across `tests/security/`, including 25 new tests.
- Run live against the real key; the table above is its actual output.
- Weighted toward the failure direction: a new high-severity rule, a new YARA hit, an engine swap at
  an unchanged count, and a medium promoted to high must each be reported as worse. One test replaces
  the comparison with one that reports nothing and requires the self-test to notice, because a
  control that cannot fail is decoration.
- Both parsers are fuzzed against schema drift. VirusTotal has renamed and added buckets over time,
  and a crash would break the measurement on precisely the day the schema moved.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the VirusTotal secret this repository actually has, so the lane can measure something

`secrets.VT_API_KEY` does not exist. `VT_API_KEY` is the ENV VAR name the Python reads
(`scripts/virustotal_scan.py:37`); the repository secret is `VIRUS_TOTAL_API_TOKEN`, which is the only
VirusTotal secret in all 51 workflows, and `release-desktop.yml:2193` maps it the same way.

As written the expression expanded to empty and the lane exited 3 / VOID on every dispatch. That is
the right failure shape -- it refuses to report a clean it did not measure -- but a lane that can
never measure anything is not worth having, and the failure only surfaces after someone dispatches
it and waits.

Two guards added, because both halves of this were invisible:

- `test_the_workflow_reads_the_secret_this_repository_actually_has` pins the secret name in both
  directions and also asserts the checkout keeps `fetch-depth: 0`, since the step that reverifies
  the baseline against commit 1ad4467 reverifies nothing on a shallow clone.
- `test_the_baseline_hash_is_the_file_the_reporter_ran` now checks the constant's shape
  unconditionally before the git half. That git half skips on a shallow clone, which is every CI lane
  that collects `tests/security` -- so the one assertion tying the baseline to real history was green
  locally and silently absent everywhere it mattered.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Compare Sigma severities in order, and void an unanalysed baseline too

The per-severity comparison reported each bucket independently, which cannot express a trade:
swapping the single high rule for three extra low ones moves two buckets in opposite
directions, so it landed in worse and in better at once and exit_code answered worse. The
comment beside that loop calls exactly that swap an improvement. SEVERITIES is ordered most
severe first, so the most severe bucket that moved now decides and the rest are reported
alongside it without flipping the verdict.

The zero-engine guard was on the candidate only. A baseline hash VirusTotal knows but has never
analysed carries no engines, no Sigma and no YARA, so every finding on the candidate read as
newly introduced and the run exited 2 having compared against nothing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Bound the lookups, keep ruleset identity, and escape third-party text

Neither lookup carried a deadline, and request can spend four 300-second socket attempts plus 20,
40 and 80 seconds of backoff. The workflow gives the whole job 20 minutes, so the baseline lookup
alone could exhaust it and the runner would kill the step before it fetched the candidate or wrote
its summary, which is a lost run rather than a reported one. Both lookups now share a 420 second
budget and an expired budget is reported as VOID, since we did not find out.

YARA hits were keyed on the rule name alone, so the same rule identifier appearing in two
crowdsourced rulesets collapsed to one entry: a candidate could gain a hit from a second ruleset,
parse to the same list as the baseline, and exit 0 on a real regression. Keyed on ruleset and rule
now.

Engine names and detection labels are third-party text and the report is appended to
GITHUB_STEP_SUMMARY, where a newline ends the row, a pipe opens a cell and an angle bracket starts
HTML that GitHub renders. virustotal_scan._md_text exists for exactly this and the report was
bypassing it; reused rather than duplicated.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Stop labelling an overridden baseline as the recorded install.ps1

A dispatch can supply baseline_sha256, and the lookup and the comparison then use that hash while
the header still announced the recorded identity and printed install.ps1's historical scores
beside the override's live table. That is an artifact built to be misattributed: the numbers
belong to one file and the name to another.

The note is now printed only when the baseline hash really is the recorded one, and an override
says so and disclaims the historical comparison.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Catch a spent deadline in the VirusTotal delta lookup

VirusTotalClient.request signals an expired deadline with TimeoutError,
which inherits from OSError rather than RuntimeError, so the handler in
fetch never ran and the workflow died with a traceback before render
wrote its summary. That is the lost run the deadline was meant to
prevent. Catch both and keep returning a VOID row.

* Keep Sigma buckets this tool cannot rank

The parser warned in its own docstring that VirusTotal renames and adds
severity buckets, then read a fixed key list, so a candidate that gained
rules only in a new bucket produced a dictionary identical to the
baseline's and the run exited 0 on a regression. Keep every reported
bucket. Unrankable ones stay out of the ordered trade-off, which depends
on knowing which of two buckets is more severe, and a rise in one is
reported as worse rather than assumed minor.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Count every engine verdict bucket, not the five the dataclass carries

parse_stats names type-unsupported and failure as categories VirusTotal
has added, but ScanStats has fields only for five buckets, so the engine
count this report prints was short by however many engines answered that
way, and a response made up entirely of those buckets summed to zero and
voided the run as unanalysed. Sum every numeric bucket from the raw
stats, which leaves the shared dataclass alone for the release scanner.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Require an explicit verdict before calling an engine cleared

An engine that flagged the baseline and is absent from the candidate's
results has not cleared it, it did not evaluate it, and a set difference
cannot tell those apart. Since Skyhigh is the one engine that actually
flags this file, a sparse candidate analysis could print the single most
consequential sentence in the report and exit 0. Track which engines
returned a verdict of any kind, call only an answering non-flagging
engine cleared, and report the silent ones as an unanswered question.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Only a conclusive verdict clears a prior detection

The responder set was built on the truthiness of the category, so
timeout, confirmed-timeout, failure and type-unsupported counted as
answers while parse_detections correctly left them out of the flagging
list. An engine returning one of those appeared in neither set and was
reported as having stopped flagging the candidate, which is the same
mistake as treating absence as a clean verdict.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants